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