1 /* 2 * Copyright (C) 2019 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef __ENCODER_H__ 18 #define __ENCODER_H__ 19 20 #include <chrono> 21 #include <condition_variable> 22 #include <mutex> 23 #include <queue> 24 #include <thread> 25 26 #include "BenchmarkCommon.h" 27 #include "Stats.h" 28 29 // constant not defined in NDK api 30 constexpr int32_t COLOR_FormatYUV420Flexible = 0x7F420888; 31 32 struct encParameter { 33 int32_t bitrate = -1; 34 int32_t numFrames = -1; 35 int32_t frameSize = -1; 36 int32_t sampleRate = 0; 37 int32_t numChannels = 0; 38 int32_t maxFrameSize = -1; 39 int32_t width = 0; 40 int32_t height = 0; 41 int32_t frameRate = -1; 42 int32_t iFrameInterval = 0; 43 int32_t profile = -1; 44 int32_t level = -1; 45 int32_t colorFormat = COLOR_FormatYUV420Flexible; 46 }; 47 48 class Encoder : public CallBackHandle { 49 public: Encoder()50 Encoder() 51 : mCodec(nullptr), 52 mFormat(nullptr), 53 mNumInputFrame(0), 54 mNumOutputFrame(0), 55 mSawInputEOS(false), 56 mSawOutputEOS(false), 57 mSignalledError(false), 58 mErrorCode(AMEDIA_OK) {} 59 ~Encoder()60 virtual ~Encoder() {} 61 62 // Encoder related utilities 63 void setupEncoder(); 64 65 void deInitCodec(); 66 67 void resetEncoder(); 68 69 // Async callback APIs 70 void onInputAvailable(AMediaCodec *codec, int32_t index) override; 71 72 void onFormatChanged(AMediaCodec *codec, AMediaFormat *format) override; 73 74 void onError(AMediaCodec *mediaCodec, media_status_t err) override; 75 76 void onOutputAvailable(AMediaCodec *codec, int32_t index, 77 AMediaCodecBufferInfo *bufferInfo) override; 78 79 // Process the frames and give encoded output 80 int32_t encode(std::string &codecName, std::ifstream &eleStream, size_t eleSize, bool asyncMode, 81 encParameter encParams, char *mime); 82 83 void dumpStatistics(string inputReference, int64_t durationUs, string codecName = "", 84 string mode = "", string statsFile = ""); 85 86 private: 87 AMediaCodec *mCodec; 88 AMediaFormat *mFormat; 89 90 int32_t mNumInputFrame; 91 int32_t mNumOutputFrame; 92 bool mSawInputEOS; 93 bool mSawOutputEOS; 94 bool mSignalledError; 95 media_status_t mErrorCode; 96 97 char *mMime; 98 int32_t mOffset; 99 std::ifstream *mEleStream; 100 size_t mInputBufferSize; 101 encParameter mParams; 102 103 // Asynchronous locks 104 std::mutex mMutex; 105 std::condition_variable mEncoderDoneCondition; 106 }; 107 #endif // __ENCODER_H__ 108