Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2020 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 | // #define LOG_NDEBUG 0 |
| 18 | #define LOG_TAG "VideoTrackTranscoder" |
| 19 | |
| 20 | #include <android-base/logging.h> |
Hangyu Kuang | 0d93f0b | 2020-12-11 18:51:16 +0000 | [diff] [blame] | 21 | #include <android-base/properties.h> |
Linus Nilsson | 9359189 | 2020-08-03 18:56:55 -0700 | [diff] [blame] | 22 | #include <media/NdkCommon.h> |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 23 | #include <media/VideoTrackTranscoder.h> |
Linus Nilsson | b09aac2 | 2020-07-29 11:56:53 -0700 | [diff] [blame] | 24 | #include <utils/AndroidThreads.h> |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 25 | |
Linus Nilsson | 7a127b2 | 2020-10-15 16:23:54 -0700 | [diff] [blame] | 26 | using namespace AMediaFormatUtils; |
| 27 | |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 28 | namespace android { |
| 29 | |
| 30 | // Check that the codec sample flags have the expected NDK meaning. |
| 31 | static_assert(SAMPLE_FLAG_CODEC_CONFIG == AMEDIACODEC_BUFFER_FLAG_CODEC_CONFIG, |
| 32 | "Sample flag mismatch: CODEC_CONFIG"); |
| 33 | static_assert(SAMPLE_FLAG_END_OF_STREAM == AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM, |
| 34 | "Sample flag mismatch: END_OF_STREAM"); |
| 35 | static_assert(SAMPLE_FLAG_PARTIAL_FRAME == AMEDIACODEC_BUFFER_FLAG_PARTIAL_FRAME, |
| 36 | "Sample flag mismatch: PARTIAL_FRAME"); |
| 37 | |
Linus Nilsson | cab39d8 | 2020-05-14 16:32:21 -0700 | [diff] [blame] | 38 | // Color format defined by surface. (See MediaCodecInfo.CodecCapabilities#COLOR_FormatSurface.) |
| 39 | static constexpr int32_t kColorFormatSurface = 0x7f000789; |
| 40 | // Default key frame interval in seconds. |
| 41 | static constexpr float kDefaultKeyFrameIntervalSeconds = 1.0f; |
Linus Nilsson | 7a127b2 | 2020-10-15 16:23:54 -0700 | [diff] [blame] | 42 | // Default codec operating rate. |
Linus Nilsson | 504394a | 2020-12-16 11:10:10 -0800 | [diff] [blame] | 43 | static int32_t kDefaultCodecOperatingRate720P = base::GetIntProperty( |
hkuang | bcb9ec1 | 2020-12-14 22:16:09 -0800 | [diff] [blame] | 44 | "debug.media.transcoding.codec_max_operating_rate_720P", /*default*/ 480); |
| 45 | static int32_t kDefaultCodecOperatingRate1080P = base::GetIntProperty( |
| 46 | "debug.media.transcoding.codec_max_operating_rate_1080P", /*default*/ 240); |
Linus Nilsson | 7a127b2 | 2020-10-15 16:23:54 -0700 | [diff] [blame] | 47 | // Default codec priority. |
| 48 | static constexpr int32_t kDefaultCodecPriority = 1; |
| 49 | // Default bitrate, in case source estimation fails. |
| 50 | static constexpr int32_t kDefaultBitrateMbps = 10 * 1000 * 1000; |
Linus Nilsson | af4a321 | 2020-12-15 08:18:25 -0800 | [diff] [blame] | 51 | // Default frame rate. |
| 52 | static constexpr int32_t kDefaultFrameRate = 30; |
Linus Nilsson | cab39d8 | 2020-05-14 16:32:21 -0700 | [diff] [blame] | 53 | |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 54 | template <typename T> |
| 55 | void VideoTrackTranscoder::BlockingQueue<T>::push(T const& value, bool front) { |
| 56 | { |
Linus Nilsson | 93cf913 | 2020-09-24 12:12:48 -0700 | [diff] [blame] | 57 | std::scoped_lock lock(mMutex); |
| 58 | if (mAborted) { |
| 59 | return; |
| 60 | } |
| 61 | |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 62 | if (front) { |
| 63 | mQueue.push_front(value); |
| 64 | } else { |
| 65 | mQueue.push_back(value); |
| 66 | } |
| 67 | } |
| 68 | mCondition.notify_one(); |
| 69 | } |
| 70 | |
| 71 | template <typename T> |
| 72 | T VideoTrackTranscoder::BlockingQueue<T>::pop() { |
Linus Nilsson | 93cf913 | 2020-09-24 12:12:48 -0700 | [diff] [blame] | 73 | std::unique_lock lock(mMutex); |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 74 | while (mQueue.empty()) { |
| 75 | mCondition.wait(lock); |
| 76 | } |
| 77 | T value = mQueue.front(); |
| 78 | mQueue.pop_front(); |
| 79 | return value; |
| 80 | } |
| 81 | |
Linus Nilsson | 93cf913 | 2020-09-24 12:12:48 -0700 | [diff] [blame] | 82 | // Note: Do not call if another thread might waiting in pop. |
| 83 | template <typename T> |
| 84 | void VideoTrackTranscoder::BlockingQueue<T>::abort() { |
| 85 | std::scoped_lock lock(mMutex); |
| 86 | mAborted = true; |
| 87 | mQueue.clear(); |
| 88 | } |
| 89 | |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 90 | // The CodecWrapper class is used to let AMediaCodec instances outlive the transcoder object itself |
| 91 | // by giving the codec a weak pointer to the transcoder. Codecs wrapped in this object are kept |
| 92 | // alive by the transcoder and the codec's outstanding buffers. Once the transcoder stops and all |
| 93 | // output buffers have been released by downstream components the codec will also be released. |
| 94 | class VideoTrackTranscoder::CodecWrapper { |
| 95 | public: |
| 96 | CodecWrapper(AMediaCodec* codec, const std::weak_ptr<VideoTrackTranscoder>& transcoder) |
| 97 | : mCodec(codec), mTranscoder(transcoder), mCodecStarted(false) {} |
| 98 | ~CodecWrapper() { |
| 99 | if (mCodecStarted) { |
| 100 | AMediaCodec_stop(mCodec); |
| 101 | } |
| 102 | AMediaCodec_delete(mCodec); |
| 103 | } |
| 104 | |
| 105 | AMediaCodec* getCodec() { return mCodec; } |
| 106 | std::shared_ptr<VideoTrackTranscoder> getTranscoder() const { return mTranscoder.lock(); }; |
| 107 | void setStarted() { mCodecStarted = true; } |
| 108 | |
| 109 | private: |
| 110 | AMediaCodec* mCodec; |
| 111 | std::weak_ptr<VideoTrackTranscoder> mTranscoder; |
| 112 | bool mCodecStarted; |
| 113 | }; |
| 114 | |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 115 | // Dispatch responses to codec callbacks onto the message queue. |
| 116 | struct AsyncCodecCallbackDispatch { |
| 117 | static void onAsyncInputAvailable(AMediaCodec* codec, void* userdata, int32_t index) { |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 118 | VideoTrackTranscoder::CodecWrapper* wrapper = |
| 119 | static_cast<VideoTrackTranscoder::CodecWrapper*>(userdata); |
| 120 | if (auto transcoder = wrapper->getTranscoder()) { |
| 121 | if (codec == transcoder->mDecoder) { |
| 122 | transcoder->mCodecMessageQueue.push( |
| 123 | [transcoder, index] { transcoder->enqueueInputSample(index); }); |
| 124 | } |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 125 | } |
| 126 | } |
| 127 | |
| 128 | static void onAsyncOutputAvailable(AMediaCodec* codec, void* userdata, int32_t index, |
| 129 | AMediaCodecBufferInfo* bufferInfoPtr) { |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 130 | VideoTrackTranscoder::CodecWrapper* wrapper = |
| 131 | static_cast<VideoTrackTranscoder::CodecWrapper*>(userdata); |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 132 | AMediaCodecBufferInfo bufferInfo = *bufferInfoPtr; |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 133 | if (auto transcoder = wrapper->getTranscoder()) { |
| 134 | transcoder->mCodecMessageQueue.push([transcoder, index, codec, bufferInfo] { |
| 135 | if (codec == transcoder->mDecoder) { |
| 136 | transcoder->transferBuffer(index, bufferInfo); |
| 137 | } else if (codec == transcoder->mEncoder->getCodec()) { |
| 138 | transcoder->dequeueOutputSample(index, bufferInfo); |
| 139 | } |
| 140 | }); |
| 141 | } |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 142 | } |
| 143 | |
| 144 | static void onAsyncFormatChanged(AMediaCodec* codec, void* userdata, AMediaFormat* format) { |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 145 | VideoTrackTranscoder::CodecWrapper* wrapper = |
| 146 | static_cast<VideoTrackTranscoder::CodecWrapper*>(userdata); |
| 147 | if (auto transcoder = wrapper->getTranscoder()) { |
| 148 | const char* kCodecName = (codec == transcoder->mDecoder ? "Decoder" : "Encoder"); |
| 149 | LOG(DEBUG) << kCodecName << " format changed: " << AMediaFormat_toString(format); |
| 150 | if (codec == transcoder->mEncoder->getCodec()) { |
| 151 | transcoder->mCodecMessageQueue.push( |
| 152 | [transcoder, format] { transcoder->updateTrackFormat(format); }); |
| 153 | } |
Chong Zhang | a2cc86b | 2020-06-17 16:56:49 -0700 | [diff] [blame] | 154 | } |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 155 | } |
| 156 | |
| 157 | static void onAsyncError(AMediaCodec* codec, void* userdata, media_status_t error, |
| 158 | int32_t actionCode, const char* detail) { |
| 159 | LOG(ERROR) << "Error from codec " << codec << ", userdata " << userdata << ", error " |
| 160 | << error << ", action " << actionCode << ", detail " << detail; |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 161 | VideoTrackTranscoder::CodecWrapper* wrapper = |
| 162 | static_cast<VideoTrackTranscoder::CodecWrapper*>(userdata); |
| 163 | if (auto transcoder = wrapper->getTranscoder()) { |
| 164 | transcoder->mCodecMessageQueue.push( |
Linus Nilsson | fdb3e33 | 2020-09-18 17:11:41 -0700 | [diff] [blame] | 165 | [transcoder, error] { transcoder->mStatus = error; }, true); |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 166 | } |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 167 | } |
| 168 | }; |
| 169 | |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 170 | // static |
| 171 | std::shared_ptr<VideoTrackTranscoder> VideoTrackTranscoder::create( |
Chong Zhang | bbb4eac | 2020-11-18 11:12:06 -0800 | [diff] [blame] | 172 | const std::weak_ptr<MediaTrackTranscoderCallback>& transcoderCallback, pid_t pid, |
| 173 | uid_t uid) { |
| 174 | return std::shared_ptr<VideoTrackTranscoder>( |
| 175 | new VideoTrackTranscoder(transcoderCallback, pid, uid)); |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 176 | } |
| 177 | |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 178 | VideoTrackTranscoder::~VideoTrackTranscoder() { |
| 179 | if (mDecoder != nullptr) { |
| 180 | AMediaCodec_delete(mDecoder); |
| 181 | } |
| 182 | |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 183 | if (mSurface != nullptr) { |
| 184 | ANativeWindow_release(mSurface); |
| 185 | } |
| 186 | } |
| 187 | |
hkuang | bcb9ec1 | 2020-12-14 22:16:09 -0800 | [diff] [blame] | 188 | // Search the default operating rate based on resolution. |
| 189 | static int32_t getDefaultOperatingRate(AMediaFormat* encoderFormat) { |
| 190 | int32_t width, height; |
| 191 | if (AMediaFormat_getInt32(encoderFormat, AMEDIAFORMAT_KEY_WIDTH, &width) && (width > 0) && |
| 192 | AMediaFormat_getInt32(encoderFormat, AMEDIAFORMAT_KEY_HEIGHT, &height) && (height > 0)) { |
| 193 | if ((width == 1280 && height == 720) || (width == 720 && height == 1280)) { |
Linus Nilsson | 504394a | 2020-12-16 11:10:10 -0800 | [diff] [blame] | 194 | return kDefaultCodecOperatingRate720P; |
hkuang | bcb9ec1 | 2020-12-14 22:16:09 -0800 | [diff] [blame] | 195 | } else if ((width == 1920 && height == 1080) || (width == 1080 && height == 1920)) { |
| 196 | return kDefaultCodecOperatingRate1080P; |
hkuang | bcb9ec1 | 2020-12-14 22:16:09 -0800 | [diff] [blame] | 197 | } else { |
| 198 | LOG(WARNING) << "Could not find default operating rate: " << width << " " << height; |
Linus Nilsson | 504394a | 2020-12-16 11:10:10 -0800 | [diff] [blame] | 199 | // Don't set operating rate if the correct dimensions are not found. |
hkuang | bcb9ec1 | 2020-12-14 22:16:09 -0800 | [diff] [blame] | 200 | } |
| 201 | } else { |
| 202 | LOG(ERROR) << "Failed to get default operating rate due to missing resolution"; |
| 203 | } |
| 204 | return -1; |
| 205 | } |
| 206 | |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 207 | // Creates and configures the codecs. |
| 208 | media_status_t VideoTrackTranscoder::configureDestinationFormat( |
| 209 | const std::shared_ptr<AMediaFormat>& destinationFormat) { |
| 210 | media_status_t status = AMEDIA_OK; |
| 211 | |
| 212 | if (destinationFormat == nullptr) { |
Linus Nilsson | cab39d8 | 2020-05-14 16:32:21 -0700 | [diff] [blame] | 213 | LOG(ERROR) << "Destination format is null, use passthrough transcoder"; |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 214 | return AMEDIA_ERROR_INVALID_PARAMETER; |
| 215 | } |
| 216 | |
Linus Nilsson | cab39d8 | 2020-05-14 16:32:21 -0700 | [diff] [blame] | 217 | AMediaFormat* encoderFormat = AMediaFormat_new(); |
| 218 | if (!encoderFormat || AMediaFormat_copy(encoderFormat, destinationFormat.get()) != AMEDIA_OK) { |
| 219 | LOG(ERROR) << "Unable to copy destination format"; |
| 220 | return AMEDIA_ERROR_INVALID_PARAMETER; |
| 221 | } |
| 222 | |
Linus Nilsson | 800793f | 2020-07-31 16:16:38 -0700 | [diff] [blame] | 223 | int32_t bitrate; |
| 224 | if (!AMediaFormat_getInt32(encoderFormat, AMEDIAFORMAT_KEY_BIT_RATE, &bitrate)) { |
| 225 | status = mMediaSampleReader->getEstimatedBitrateForTrack(mTrackIndex, &bitrate); |
| 226 | if (status != AMEDIA_OK) { |
| 227 | LOG(ERROR) << "Unable to estimate bitrate. Using default " << kDefaultBitrateMbps; |
| 228 | bitrate = kDefaultBitrateMbps; |
| 229 | } |
| 230 | |
| 231 | LOG(INFO) << "Configuring bitrate " << bitrate; |
| 232 | AMediaFormat_setInt32(encoderFormat, AMEDIAFORMAT_KEY_BIT_RATE, bitrate); |
| 233 | } |
| 234 | |
Linus Nilsson | 7a127b2 | 2020-10-15 16:23:54 -0700 | [diff] [blame] | 235 | SetDefaultFormatValueFloat(AMEDIAFORMAT_KEY_I_FRAME_INTERVAL, encoderFormat, |
| 236 | kDefaultKeyFrameIntervalSeconds); |
hkuang | bcb9ec1 | 2020-12-14 22:16:09 -0800 | [diff] [blame] | 237 | |
| 238 | int32_t operatingRate = getDefaultOperatingRate(encoderFormat); |
| 239 | |
| 240 | if (operatingRate != -1) { |
| 241 | SetDefaultFormatValueInt32(AMEDIAFORMAT_KEY_OPERATING_RATE, encoderFormat, operatingRate); |
| 242 | } |
| 243 | |
Linus Nilsson | 7a127b2 | 2020-10-15 16:23:54 -0700 | [diff] [blame] | 244 | SetDefaultFormatValueInt32(AMEDIAFORMAT_KEY_PRIORITY, encoderFormat, kDefaultCodecPriority); |
Linus Nilsson | af4a321 | 2020-12-15 08:18:25 -0800 | [diff] [blame] | 245 | SetDefaultFormatValueInt32(AMEDIAFORMAT_KEY_FRAME_RATE, encoderFormat, kDefaultFrameRate); |
Linus Nilsson | cab39d8 | 2020-05-14 16:32:21 -0700 | [diff] [blame] | 246 | AMediaFormat_setInt32(encoderFormat, AMEDIAFORMAT_KEY_COLOR_FORMAT, kColorFormatSurface); |
| 247 | |
Chong Zhang | d6e4aec | 2020-06-22 14:13:07 -0700 | [diff] [blame] | 248 | // Always encode without rotation. The rotation degree will be transferred directly to |
| 249 | // MediaSampleWriter track format, and MediaSampleWriter will call AMediaMuxer_setOrientationHint. |
| 250 | AMediaFormat_setInt32(encoderFormat, AMEDIAFORMAT_KEY_ROTATION, 0); |
| 251 | |
Linus Nilsson | cab39d8 | 2020-05-14 16:32:21 -0700 | [diff] [blame] | 252 | mDestinationFormat = std::shared_ptr<AMediaFormat>(encoderFormat, &AMediaFormat_delete); |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 253 | |
| 254 | // Create and configure the encoder. |
| 255 | const char* destinationMime = nullptr; |
| 256 | bool ok = AMediaFormat_getString(mDestinationFormat.get(), AMEDIAFORMAT_KEY_MIME, |
| 257 | &destinationMime); |
| 258 | if (!ok) { |
| 259 | LOG(ERROR) << "Destination MIME type is required for transcoding."; |
| 260 | return AMEDIA_ERROR_INVALID_PARAMETER; |
| 261 | } |
| 262 | |
Chong Zhang | bbb4eac | 2020-11-18 11:12:06 -0800 | [diff] [blame] | 263 | AMediaCodec* encoder = AMediaCodec_createEncoderByTypeForClient(destinationMime, mPid, mUid); |
Linus Nilsson | c6221db | 2020-03-18 14:46:22 -0700 | [diff] [blame] | 264 | if (encoder == nullptr) { |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 265 | LOG(ERROR) << "Unable to create encoder for type " << destinationMime; |
| 266 | return AMEDIA_ERROR_UNSUPPORTED; |
| 267 | } |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 268 | mEncoder = std::make_shared<CodecWrapper>(encoder, shared_from_this()); |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 269 | |
Linus Nilsson | af4a321 | 2020-12-15 08:18:25 -0800 | [diff] [blame] | 270 | LOG(DEBUG) << "Configuring encoder with: " << AMediaFormat_toString(mDestinationFormat.get()); |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 271 | status = AMediaCodec_configure(mEncoder->getCodec(), mDestinationFormat.get(), |
| 272 | NULL /* surface */, NULL /* crypto */, |
| 273 | AMEDIACODEC_CONFIGURE_FLAG_ENCODE); |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 274 | if (status != AMEDIA_OK) { |
| 275 | LOG(ERROR) << "Unable to configure video encoder: " << status; |
| 276 | return status; |
| 277 | } |
| 278 | |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 279 | status = AMediaCodec_createInputSurface(mEncoder->getCodec(), &mSurface); |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 280 | if (status != AMEDIA_OK) { |
| 281 | LOG(ERROR) << "Unable to create an encoder input surface: %d" << status; |
| 282 | return status; |
| 283 | } |
| 284 | |
| 285 | // Create and configure the decoder. |
| 286 | const char* sourceMime = nullptr; |
| 287 | ok = AMediaFormat_getString(mSourceFormat.get(), AMEDIAFORMAT_KEY_MIME, &sourceMime); |
| 288 | if (!ok) { |
| 289 | LOG(ERROR) << "Source MIME type is required for transcoding."; |
| 290 | return AMEDIA_ERROR_INVALID_PARAMETER; |
| 291 | } |
| 292 | |
Chong Zhang | bbb4eac | 2020-11-18 11:12:06 -0800 | [diff] [blame] | 293 | mDecoder = AMediaCodec_createDecoderByTypeForClient(sourceMime, mPid, mUid); |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 294 | if (mDecoder == nullptr) { |
| 295 | LOG(ERROR) << "Unable to create decoder for type " << sourceMime; |
| 296 | return AMEDIA_ERROR_UNSUPPORTED; |
| 297 | } |
| 298 | |
Linus Nilsson | 9359189 | 2020-08-03 18:56:55 -0700 | [diff] [blame] | 299 | auto decoderFormat = std::shared_ptr<AMediaFormat>(AMediaFormat_new(), &AMediaFormat_delete); |
| 300 | if (!decoderFormat || |
| 301 | AMediaFormat_copy(decoderFormat.get(), mSourceFormat.get()) != AMEDIA_OK) { |
| 302 | LOG(ERROR) << "Unable to copy source format"; |
| 303 | return AMEDIA_ERROR_INVALID_PARAMETER; |
| 304 | } |
| 305 | |
| 306 | // Prevent decoder from overwriting frames that the encoder has not yet consumed. |
| 307 | AMediaFormat_setInt32(decoderFormat.get(), TBD_AMEDIACODEC_PARAMETER_KEY_ALLOW_FRAME_DROP, 0); |
| 308 | |
Linus Nilsson | 16d772b | 2020-09-29 19:21:11 -0700 | [diff] [blame] | 309 | // Copy over configurations that apply to both encoder and decoder. |
Linus Nilsson | 7a127b2 | 2020-10-15 16:23:54 -0700 | [diff] [blame] | 310 | static const EntryCopier kEncoderEntriesToCopy[] = { |
Linus Nilsson | 16d772b | 2020-09-29 19:21:11 -0700 | [diff] [blame] | 311 | ENTRY_COPIER2(AMEDIAFORMAT_KEY_OPERATING_RATE, Float, Int32), |
| 312 | ENTRY_COPIER(AMEDIAFORMAT_KEY_PRIORITY, Int32), |
| 313 | }; |
| 314 | const size_t entryCount = sizeof(kEncoderEntriesToCopy) / sizeof(kEncoderEntriesToCopy[0]); |
Linus Nilsson | 7a127b2 | 2020-10-15 16:23:54 -0700 | [diff] [blame] | 315 | CopyFormatEntries(mDestinationFormat.get(), decoderFormat.get(), kEncoderEntriesToCopy, |
| 316 | entryCount); |
Linus Nilsson | 16d772b | 2020-09-29 19:21:11 -0700 | [diff] [blame] | 317 | |
Linus Nilsson | af4a321 | 2020-12-15 08:18:25 -0800 | [diff] [blame] | 318 | LOG(DEBUG) << "Configuring decoder with: " << AMediaFormat_toString(decoderFormat.get()); |
Linus Nilsson | 9359189 | 2020-08-03 18:56:55 -0700 | [diff] [blame] | 319 | status = AMediaCodec_configure(mDecoder, decoderFormat.get(), mSurface, NULL /* crypto */, |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 320 | 0 /* flags */); |
| 321 | if (status != AMEDIA_OK) { |
| 322 | LOG(ERROR) << "Unable to configure video decoder: " << status; |
| 323 | return status; |
| 324 | } |
| 325 | |
| 326 | // Configure codecs to run in async mode. |
| 327 | AMediaCodecOnAsyncNotifyCallback asyncCodecCallbacks = { |
| 328 | .onAsyncInputAvailable = AsyncCodecCallbackDispatch::onAsyncInputAvailable, |
| 329 | .onAsyncOutputAvailable = AsyncCodecCallbackDispatch::onAsyncOutputAvailable, |
| 330 | .onAsyncFormatChanged = AsyncCodecCallbackDispatch::onAsyncFormatChanged, |
| 331 | .onAsyncError = AsyncCodecCallbackDispatch::onAsyncError}; |
| 332 | |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 333 | // Note: The decoder does not need its own wrapper because its lifetime is tied to the |
| 334 | // transcoder. But the same callbacks are reused for decoder and encoder so we pass the encoder |
| 335 | // wrapper as userdata here but never read the codec from it in the callback. |
| 336 | status = AMediaCodec_setAsyncNotifyCallback(mDecoder, asyncCodecCallbacks, mEncoder.get()); |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 337 | if (status != AMEDIA_OK) { |
| 338 | LOG(ERROR) << "Unable to set decoder to async mode: " << status; |
| 339 | return status; |
| 340 | } |
| 341 | |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 342 | status = AMediaCodec_setAsyncNotifyCallback(mEncoder->getCodec(), asyncCodecCallbacks, |
| 343 | mEncoder.get()); |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 344 | if (status != AMEDIA_OK) { |
| 345 | LOG(ERROR) << "Unable to set encoder to async mode: " << status; |
| 346 | return status; |
| 347 | } |
| 348 | |
| 349 | return AMEDIA_OK; |
| 350 | } |
| 351 | |
| 352 | void VideoTrackTranscoder::enqueueInputSample(int32_t bufferIndex) { |
| 353 | media_status_t status = AMEDIA_OK; |
| 354 | |
Linus Nilsson | c6221db | 2020-03-18 14:46:22 -0700 | [diff] [blame] | 355 | if (mEosFromSource) { |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 356 | return; |
| 357 | } |
| 358 | |
| 359 | status = mMediaSampleReader->getSampleInfoForTrack(mTrackIndex, &mSampleInfo); |
| 360 | if (status != AMEDIA_OK && status != AMEDIA_ERROR_END_OF_STREAM) { |
| 361 | LOG(ERROR) << "Error getting next sample info: " << status; |
| 362 | mStatus = status; |
| 363 | return; |
| 364 | } |
| 365 | const bool endOfStream = (status == AMEDIA_ERROR_END_OF_STREAM); |
| 366 | |
| 367 | if (!endOfStream) { |
| 368 | size_t bufferSize = 0; |
| 369 | uint8_t* sourceBuffer = AMediaCodec_getInputBuffer(mDecoder, bufferIndex, &bufferSize); |
| 370 | if (sourceBuffer == nullptr) { |
| 371 | LOG(ERROR) << "Decoder returned a NULL input buffer."; |
| 372 | mStatus = AMEDIA_ERROR_UNKNOWN; |
| 373 | return; |
| 374 | } else if (bufferSize < mSampleInfo.size) { |
| 375 | LOG(ERROR) << "Decoder returned an input buffer that is smaller than the sample."; |
| 376 | mStatus = AMEDIA_ERROR_UNKNOWN; |
| 377 | return; |
| 378 | } |
| 379 | |
| 380 | status = mMediaSampleReader->readSampleDataForTrack(mTrackIndex, sourceBuffer, |
| 381 | mSampleInfo.size); |
| 382 | if (status != AMEDIA_OK) { |
| 383 | LOG(ERROR) << "Unable to read next sample data. Aborting transcode."; |
| 384 | mStatus = status; |
| 385 | return; |
| 386 | } |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 387 | } else { |
| 388 | LOG(DEBUG) << "EOS from source."; |
Linus Nilsson | c6221db | 2020-03-18 14:46:22 -0700 | [diff] [blame] | 389 | mEosFromSource = true; |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 390 | } |
| 391 | |
| 392 | status = AMediaCodec_queueInputBuffer(mDecoder, bufferIndex, 0, mSampleInfo.size, |
| 393 | mSampleInfo.presentationTimeUs, mSampleInfo.flags); |
| 394 | if (status != AMEDIA_OK) { |
| 395 | LOG(ERROR) << "Unable to queue input buffer for decode: " << status; |
| 396 | mStatus = status; |
| 397 | return; |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | void VideoTrackTranscoder::transferBuffer(int32_t bufferIndex, AMediaCodecBufferInfo bufferInfo) { |
| 402 | if (bufferIndex >= 0) { |
| 403 | bool needsRender = bufferInfo.size > 0; |
| 404 | AMediaCodec_releaseOutputBuffer(mDecoder, bufferIndex, needsRender); |
| 405 | } |
| 406 | |
| 407 | if (bufferInfo.flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM) { |
| 408 | LOG(DEBUG) << "EOS from decoder."; |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 409 | media_status_t status = AMediaCodec_signalEndOfInputStream(mEncoder->getCodec()); |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 410 | if (status != AMEDIA_OK) { |
| 411 | LOG(ERROR) << "SignalEOS on encoder returned error: " << status; |
| 412 | mStatus = status; |
| 413 | } |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | void VideoTrackTranscoder::dequeueOutputSample(int32_t bufferIndex, |
| 418 | AMediaCodecBufferInfo bufferInfo) { |
| 419 | if (bufferIndex >= 0) { |
| 420 | size_t sampleSize = 0; |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 421 | uint8_t* buffer = |
| 422 | AMediaCodec_getOutputBuffer(mEncoder->getCodec(), bufferIndex, &sampleSize); |
Linus Nilsson | c6221db | 2020-03-18 14:46:22 -0700 | [diff] [blame] | 423 | |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 424 | MediaSample::OnSampleReleasedCallback bufferReleaseCallback = |
| 425 | [encoder = mEncoder](MediaSample* sample) { |
| 426 | AMediaCodec_releaseOutputBuffer(encoder->getCodec(), sample->bufferId, |
| 427 | false /* render */); |
| 428 | }; |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 429 | |
| 430 | std::shared_ptr<MediaSample> sample = MediaSample::createWithReleaseCallback( |
Linus Nilsson | c6221db | 2020-03-18 14:46:22 -0700 | [diff] [blame] | 431 | buffer, bufferInfo.offset, bufferIndex, bufferReleaseCallback); |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 432 | sample->info.size = bufferInfo.size; |
| 433 | sample->info.flags = bufferInfo.flags; |
| 434 | sample->info.presentationTimeUs = bufferInfo.presentationTimeUs; |
| 435 | |
Linus Nilsson | c31d249 | 2020-09-23 12:30:00 -0700 | [diff] [blame] | 436 | onOutputSampleAvailable(sample); |
Linus Nilsson | fdb3e33 | 2020-09-18 17:11:41 -0700 | [diff] [blame] | 437 | |
| 438 | mLastSampleWasSync = sample->info.flags & SAMPLE_FLAG_SYNC_SAMPLE; |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 439 | } else if (bufferIndex == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) { |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 440 | AMediaFormat* newFormat = AMediaCodec_getOutputFormat(mEncoder->getCodec()); |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 441 | LOG(DEBUG) << "Encoder output format changed: " << AMediaFormat_toString(newFormat); |
| 442 | } |
| 443 | |
| 444 | if (bufferInfo.flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM) { |
| 445 | LOG(DEBUG) << "EOS from encoder."; |
Linus Nilsson | c6221db | 2020-03-18 14:46:22 -0700 | [diff] [blame] | 446 | mEosFromEncoder = true; |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 447 | } |
| 448 | } |
| 449 | |
Chong Zhang | a2cc86b | 2020-06-17 16:56:49 -0700 | [diff] [blame] | 450 | void VideoTrackTranscoder::updateTrackFormat(AMediaFormat* outputFormat) { |
| 451 | if (mActualOutputFormat != nullptr) { |
| 452 | LOG(WARNING) << "Ignoring duplicate format change."; |
| 453 | return; |
| 454 | } |
| 455 | |
| 456 | AMediaFormat* formatCopy = AMediaFormat_new(); |
| 457 | if (!formatCopy || AMediaFormat_copy(formatCopy, outputFormat) != AMEDIA_OK) { |
| 458 | LOG(ERROR) << "Unable to copy outputFormat"; |
| 459 | AMediaFormat_delete(formatCopy); |
| 460 | mStatus = AMEDIA_ERROR_INVALID_PARAMETER; |
| 461 | return; |
| 462 | } |
| 463 | |
| 464 | // Generate the actual track format for muxer based on the encoder output format, |
| 465 | // since many vital information comes in the encoder format (eg. CSD). |
| 466 | // Transfer necessary fields from the user-configured track format (derived from |
| 467 | // source track format and user transcoding request) where needed. |
| 468 | |
| 469 | // Transfer SAR settings: |
| 470 | // If mDestinationFormat has SAR set, it means the original source has SAR specified |
| 471 | // at container level. This is supposed to override any SAR settings in the bitstream, |
| 472 | // thus should always be transferred to the container of the transcoded file. |
| 473 | int32_t sarWidth, sarHeight; |
Chong Zhang | d6e4aec | 2020-06-22 14:13:07 -0700 | [diff] [blame] | 474 | if (AMediaFormat_getInt32(mSourceFormat.get(), AMEDIAFORMAT_KEY_SAR_WIDTH, &sarWidth) && |
Chong Zhang | a2cc86b | 2020-06-17 16:56:49 -0700 | [diff] [blame] | 475 | (sarWidth > 0) && |
Chong Zhang | d6e4aec | 2020-06-22 14:13:07 -0700 | [diff] [blame] | 476 | AMediaFormat_getInt32(mSourceFormat.get(), AMEDIAFORMAT_KEY_SAR_HEIGHT, &sarHeight) && |
Chong Zhang | a2cc86b | 2020-06-17 16:56:49 -0700 | [diff] [blame] | 477 | (sarHeight > 0)) { |
| 478 | AMediaFormat_setInt32(formatCopy, AMEDIAFORMAT_KEY_SAR_WIDTH, sarWidth); |
| 479 | AMediaFormat_setInt32(formatCopy, AMEDIAFORMAT_KEY_SAR_HEIGHT, sarHeight); |
| 480 | } |
| 481 | // Transfer DAR settings. |
| 482 | int32_t displayWidth, displayHeight; |
Chong Zhang | d6e4aec | 2020-06-22 14:13:07 -0700 | [diff] [blame] | 483 | if (AMediaFormat_getInt32(mSourceFormat.get(), AMEDIAFORMAT_KEY_DISPLAY_WIDTH, &displayWidth) && |
Chong Zhang | a2cc86b | 2020-06-17 16:56:49 -0700 | [diff] [blame] | 484 | (displayWidth > 0) && |
Chong Zhang | d6e4aec | 2020-06-22 14:13:07 -0700 | [diff] [blame] | 485 | AMediaFormat_getInt32(mSourceFormat.get(), AMEDIAFORMAT_KEY_DISPLAY_HEIGHT, |
Chong Zhang | a2cc86b | 2020-06-17 16:56:49 -0700 | [diff] [blame] | 486 | &displayHeight) && |
| 487 | (displayHeight > 0)) { |
| 488 | AMediaFormat_setInt32(formatCopy, AMEDIAFORMAT_KEY_DISPLAY_WIDTH, displayWidth); |
| 489 | AMediaFormat_setInt32(formatCopy, AMEDIAFORMAT_KEY_DISPLAY_HEIGHT, displayHeight); |
| 490 | } |
| 491 | |
Chong Zhang | d6e4aec | 2020-06-22 14:13:07 -0700 | [diff] [blame] | 492 | // Transfer rotation settings. |
| 493 | // Note that muxer itself doesn't take rotation from the track format. It requires |
| 494 | // AMediaMuxer_setOrientationHint to set the rotation. Here we pass the rotation to |
| 495 | // MediaSampleWriter using the track format. MediaSampleWriter will then call |
| 496 | // AMediaMuxer_setOrientationHint as needed. |
| 497 | int32_t rotation; |
| 498 | if (AMediaFormat_getInt32(mSourceFormat.get(), AMEDIAFORMAT_KEY_ROTATION, &rotation) && |
| 499 | (rotation != 0)) { |
| 500 | AMediaFormat_setInt32(formatCopy, AMEDIAFORMAT_KEY_ROTATION, rotation); |
| 501 | } |
| 502 | |
Linus Nilsson | 42a971b | 2020-07-01 16:41:11 -0700 | [diff] [blame] | 503 | // Transfer track duration. |
| 504 | // Preserve the source track duration by sending it to MediaSampleWriter. |
| 505 | int64_t durationUs; |
| 506 | if (AMediaFormat_getInt64(mSourceFormat.get(), AMEDIAFORMAT_KEY_DURATION, &durationUs) && |
| 507 | durationUs > 0) { |
| 508 | AMediaFormat_setInt64(formatCopy, AMEDIAFORMAT_KEY_DURATION, durationUs); |
| 509 | } |
| 510 | |
Chong Zhang | a2cc86b | 2020-06-17 16:56:49 -0700 | [diff] [blame] | 511 | // TODO: transfer other fields as required. |
| 512 | |
| 513 | mActualOutputFormat = std::shared_ptr<AMediaFormat>(formatCopy, &AMediaFormat_delete); |
| 514 | |
| 515 | notifyTrackFormatAvailable(); |
| 516 | } |
| 517 | |
Linus Nilsson | fdb3e33 | 2020-09-18 17:11:41 -0700 | [diff] [blame] | 518 | media_status_t VideoTrackTranscoder::runTranscodeLoop(bool* stopped) { |
Linus Nilsson | b09aac2 | 2020-07-29 11:56:53 -0700 | [diff] [blame] | 519 | androidSetThreadPriority(0 /* tid (0 = current) */, ANDROID_PRIORITY_VIDEO); |
| 520 | |
Chong Zhang | b55c545 | 2020-06-26 14:32:12 -0700 | [diff] [blame] | 521 | // Push start decoder and encoder as two messages, so that these are subject to the |
Chong Zhang | bc06248 | 2020-10-14 16:43:53 -0700 | [diff] [blame] | 522 | // stop request as well. If the session is cancelled (or paused) immediately after start, |
Chong Zhang | b55c545 | 2020-06-26 14:32:12 -0700 | [diff] [blame] | 523 | // we don't need to waste time start then stop the codecs. |
| 524 | mCodecMessageQueue.push([this] { |
| 525 | media_status_t status = AMediaCodec_start(mDecoder); |
| 526 | if (status != AMEDIA_OK) { |
| 527 | LOG(ERROR) << "Unable to start video decoder: " << status; |
| 528 | mStatus = status; |
| 529 | } |
| 530 | }); |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 531 | |
Chong Zhang | b55c545 | 2020-06-26 14:32:12 -0700 | [diff] [blame] | 532 | mCodecMessageQueue.push([this] { |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 533 | media_status_t status = AMediaCodec_start(mEncoder->getCodec()); |
Chong Zhang | b55c545 | 2020-06-26 14:32:12 -0700 | [diff] [blame] | 534 | if (status != AMEDIA_OK) { |
| 535 | LOG(ERROR) << "Unable to start video encoder: " << status; |
| 536 | mStatus = status; |
| 537 | } |
Linus Nilsson | e4716f2 | 2020-07-10 16:07:57 -0700 | [diff] [blame] | 538 | mEncoder->setStarted(); |
Chong Zhang | b55c545 | 2020-06-26 14:32:12 -0700 | [diff] [blame] | 539 | }); |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 540 | |
| 541 | // Process codec events until EOS is reached, transcoding is stopped or an error occurs. |
Linus Nilsson | fdb3e33 | 2020-09-18 17:11:41 -0700 | [diff] [blame] | 542 | while (mStopRequest != STOP_NOW && !mEosFromEncoder && mStatus == AMEDIA_OK) { |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 543 | std::function<void()> message = mCodecMessageQueue.pop(); |
| 544 | message(); |
Linus Nilsson | fdb3e33 | 2020-09-18 17:11:41 -0700 | [diff] [blame] | 545 | |
| 546 | if (mStopRequest == STOP_ON_SYNC && mLastSampleWasSync) { |
| 547 | break; |
| 548 | } |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 549 | } |
| 550 | |
Linus Nilsson | 93cf913 | 2020-09-24 12:12:48 -0700 | [diff] [blame] | 551 | mCodecMessageQueue.abort(); |
| 552 | AMediaCodec_stop(mDecoder); |
| 553 | |
Linus Nilsson | fdb3e33 | 2020-09-18 17:11:41 -0700 | [diff] [blame] | 554 | // Signal if transcoding was stopped before it finished. |
| 555 | if (mStopRequest != NONE && !mEosFromEncoder && mStatus == AMEDIA_OK) { |
| 556 | *stopped = true; |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 557 | } |
| 558 | |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 559 | return mStatus; |
| 560 | } |
| 561 | |
| 562 | void VideoTrackTranscoder::abortTranscodeLoop() { |
Linus Nilsson | fdb3e33 | 2020-09-18 17:11:41 -0700 | [diff] [blame] | 563 | if (mStopRequest == STOP_NOW) { |
| 564 | // Wake up transcoder thread. |
| 565 | mCodecMessageQueue.push([] {}, true /* front */); |
| 566 | } |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 567 | } |
| 568 | |
Linus Nilsson | cab39d8 | 2020-05-14 16:32:21 -0700 | [diff] [blame] | 569 | std::shared_ptr<AMediaFormat> VideoTrackTranscoder::getOutputFormat() const { |
Chong Zhang | a2cc86b | 2020-06-17 16:56:49 -0700 | [diff] [blame] | 570 | return mActualOutputFormat; |
Linus Nilsson | cab39d8 | 2020-05-14 16:32:21 -0700 | [diff] [blame] | 571 | } |
| 572 | |
Linus Nilsson | 0da327a | 2020-01-31 16:22:18 -0800 | [diff] [blame] | 573 | } // namespace android |