blob: c1456fda98cbc5de3ebfadd542c424f89e1b167b [file] [log] [blame]
Linus Nilsson0da327a2020-01-31 16:22:18 -08001/*
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 Nilsson93591892020-08-03 18:56:55 -070021#include <media/NdkCommon.h>
Linus Nilsson0da327a2020-01-31 16:22:18 -080022#include <media/VideoTrackTranscoder.h>
Linus Nilssonb09aac22020-07-29 11:56:53 -070023#include <utils/AndroidThreads.h>
Linus Nilsson0da327a2020-01-31 16:22:18 -080024
Linus Nilsson7a127b22020-10-15 16:23:54 -070025using namespace AMediaFormatUtils;
26
Linus Nilsson0da327a2020-01-31 16:22:18 -080027namespace android {
28
29// Check that the codec sample flags have the expected NDK meaning.
30static_assert(SAMPLE_FLAG_CODEC_CONFIG == AMEDIACODEC_BUFFER_FLAG_CODEC_CONFIG,
31 "Sample flag mismatch: CODEC_CONFIG");
32static_assert(SAMPLE_FLAG_END_OF_STREAM == AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM,
33 "Sample flag mismatch: END_OF_STREAM");
34static_assert(SAMPLE_FLAG_PARTIAL_FRAME == AMEDIACODEC_BUFFER_FLAG_PARTIAL_FRAME,
35 "Sample flag mismatch: PARTIAL_FRAME");
36
Linus Nilssoncab39d82020-05-14 16:32:21 -070037// Color format defined by surface. (See MediaCodecInfo.CodecCapabilities#COLOR_FormatSurface.)
38static constexpr int32_t kColorFormatSurface = 0x7f000789;
39// Default key frame interval in seconds.
40static constexpr float kDefaultKeyFrameIntervalSeconds = 1.0f;
Linus Nilsson7a127b22020-10-15 16:23:54 -070041// Default codec operating rate.
42static constexpr int32_t kDefaultCodecOperatingRate = 240;
43// Default codec priority.
44static constexpr int32_t kDefaultCodecPriority = 1;
45// Default bitrate, in case source estimation fails.
46static constexpr int32_t kDefaultBitrateMbps = 10 * 1000 * 1000;
Linus Nilssoncab39d82020-05-14 16:32:21 -070047
Linus Nilsson0da327a2020-01-31 16:22:18 -080048template <typename T>
49void VideoTrackTranscoder::BlockingQueue<T>::push(T const& value, bool front) {
50 {
Linus Nilsson93cf9132020-09-24 12:12:48 -070051 std::scoped_lock lock(mMutex);
52 if (mAborted) {
53 return;
54 }
55
Linus Nilsson0da327a2020-01-31 16:22:18 -080056 if (front) {
57 mQueue.push_front(value);
58 } else {
59 mQueue.push_back(value);
60 }
61 }
62 mCondition.notify_one();
63}
64
65template <typename T>
66T VideoTrackTranscoder::BlockingQueue<T>::pop() {
Linus Nilsson93cf9132020-09-24 12:12:48 -070067 std::unique_lock lock(mMutex);
Linus Nilsson0da327a2020-01-31 16:22:18 -080068 while (mQueue.empty()) {
69 mCondition.wait(lock);
70 }
71 T value = mQueue.front();
72 mQueue.pop_front();
73 return value;
74}
75
Linus Nilsson93cf9132020-09-24 12:12:48 -070076// Note: Do not call if another thread might waiting in pop.
77template <typename T>
78void VideoTrackTranscoder::BlockingQueue<T>::abort() {
79 std::scoped_lock lock(mMutex);
80 mAborted = true;
81 mQueue.clear();
82}
83
Linus Nilssone4716f22020-07-10 16:07:57 -070084// 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.
88class VideoTrackTranscoder::CodecWrapper {
89public:
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
103private:
104 AMediaCodec* mCodec;
105 std::weak_ptr<VideoTrackTranscoder> mTranscoder;
106 bool mCodecStarted;
107};
108
Linus Nilsson0da327a2020-01-31 16:22:18 -0800109// Dispatch responses to codec callbacks onto the message queue.
110struct AsyncCodecCallbackDispatch {
111 static void onAsyncInputAvailable(AMediaCodec* codec, void* userdata, int32_t index) {
Linus Nilssone4716f22020-07-10 16:07:57 -0700112 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 Nilsson0da327a2020-01-31 16:22:18 -0800119 }
120 }
121
122 static void onAsyncOutputAvailable(AMediaCodec* codec, void* userdata, int32_t index,
123 AMediaCodecBufferInfo* bufferInfoPtr) {
Linus Nilssone4716f22020-07-10 16:07:57 -0700124 VideoTrackTranscoder::CodecWrapper* wrapper =
125 static_cast<VideoTrackTranscoder::CodecWrapper*>(userdata);
Linus Nilsson0da327a2020-01-31 16:22:18 -0800126 AMediaCodecBufferInfo bufferInfo = *bufferInfoPtr;
Linus Nilssone4716f22020-07-10 16:07:57 -0700127 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 Nilsson0da327a2020-01-31 16:22:18 -0800136 }
137
138 static void onAsyncFormatChanged(AMediaCodec* codec, void* userdata, AMediaFormat* format) {
Linus Nilssone4716f22020-07-10 16:07:57 -0700139 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 Zhanga2cc86b2020-06-17 16:56:49 -0700148 }
Linus Nilsson0da327a2020-01-31 16:22:18 -0800149 }
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 Nilssone4716f22020-07-10 16:07:57 -0700155 VideoTrackTranscoder::CodecWrapper* wrapper =
156 static_cast<VideoTrackTranscoder::CodecWrapper*>(userdata);
157 if (auto transcoder = wrapper->getTranscoder()) {
158 transcoder->mCodecMessageQueue.push(
159 [transcoder, error] {
160 transcoder->mStatus = error;
161 transcoder->mStopRequested = true;
162 },
163 true);
164 }
Linus Nilsson0da327a2020-01-31 16:22:18 -0800165 }
166};
167
Linus Nilssone4716f22020-07-10 16:07:57 -0700168// static
169std::shared_ptr<VideoTrackTranscoder> VideoTrackTranscoder::create(
Chong Zhangbbb4eac2020-11-18 11:12:06 -0800170 const std::weak_ptr<MediaTrackTranscoderCallback>& transcoderCallback, pid_t pid,
171 uid_t uid) {
172 return std::shared_ptr<VideoTrackTranscoder>(
173 new VideoTrackTranscoder(transcoderCallback, pid, uid));
Linus Nilssone4716f22020-07-10 16:07:57 -0700174}
175
Linus Nilsson0da327a2020-01-31 16:22:18 -0800176VideoTrackTranscoder::~VideoTrackTranscoder() {
177 if (mDecoder != nullptr) {
178 AMediaCodec_delete(mDecoder);
179 }
180
Linus Nilsson0da327a2020-01-31 16:22:18 -0800181 if (mSurface != nullptr) {
182 ANativeWindow_release(mSurface);
183 }
184}
185
186// Creates and configures the codecs.
187media_status_t VideoTrackTranscoder::configureDestinationFormat(
188 const std::shared_ptr<AMediaFormat>& destinationFormat) {
189 media_status_t status = AMEDIA_OK;
190
191 if (destinationFormat == nullptr) {
Linus Nilssoncab39d82020-05-14 16:32:21 -0700192 LOG(ERROR) << "Destination format is null, use passthrough transcoder";
Linus Nilsson0da327a2020-01-31 16:22:18 -0800193 return AMEDIA_ERROR_INVALID_PARAMETER;
194 }
195
Linus Nilssoncab39d82020-05-14 16:32:21 -0700196 AMediaFormat* encoderFormat = AMediaFormat_new();
197 if (!encoderFormat || AMediaFormat_copy(encoderFormat, destinationFormat.get()) != AMEDIA_OK) {
198 LOG(ERROR) << "Unable to copy destination format";
199 return AMEDIA_ERROR_INVALID_PARAMETER;
200 }
201
Linus Nilsson800793f2020-07-31 16:16:38 -0700202 int32_t bitrate;
203 if (!AMediaFormat_getInt32(encoderFormat, AMEDIAFORMAT_KEY_BIT_RATE, &bitrate)) {
204 status = mMediaSampleReader->getEstimatedBitrateForTrack(mTrackIndex, &bitrate);
205 if (status != AMEDIA_OK) {
206 LOG(ERROR) << "Unable to estimate bitrate. Using default " << kDefaultBitrateMbps;
207 bitrate = kDefaultBitrateMbps;
208 }
209
210 LOG(INFO) << "Configuring bitrate " << bitrate;
211 AMediaFormat_setInt32(encoderFormat, AMEDIAFORMAT_KEY_BIT_RATE, bitrate);
212 }
213
Linus Nilsson7a127b22020-10-15 16:23:54 -0700214 SetDefaultFormatValueFloat(AMEDIAFORMAT_KEY_I_FRAME_INTERVAL, encoderFormat,
215 kDefaultKeyFrameIntervalSeconds);
216 SetDefaultFormatValueInt32(AMEDIAFORMAT_KEY_OPERATING_RATE, encoderFormat,
217 kDefaultCodecOperatingRate);
218 SetDefaultFormatValueInt32(AMEDIAFORMAT_KEY_PRIORITY, encoderFormat, kDefaultCodecPriority);
219
Linus Nilssoncab39d82020-05-14 16:32:21 -0700220 AMediaFormat_setInt32(encoderFormat, AMEDIAFORMAT_KEY_COLOR_FORMAT, kColorFormatSurface);
221
Chong Zhangd6e4aec2020-06-22 14:13:07 -0700222 // Always encode without rotation. The rotation degree will be transferred directly to
223 // MediaSampleWriter track format, and MediaSampleWriter will call AMediaMuxer_setOrientationHint.
224 AMediaFormat_setInt32(encoderFormat, AMEDIAFORMAT_KEY_ROTATION, 0);
225
Linus Nilssoncab39d82020-05-14 16:32:21 -0700226 mDestinationFormat = std::shared_ptr<AMediaFormat>(encoderFormat, &AMediaFormat_delete);
Linus Nilsson0da327a2020-01-31 16:22:18 -0800227
228 // Create and configure the encoder.
229 const char* destinationMime = nullptr;
230 bool ok = AMediaFormat_getString(mDestinationFormat.get(), AMEDIAFORMAT_KEY_MIME,
231 &destinationMime);
232 if (!ok) {
233 LOG(ERROR) << "Destination MIME type is required for transcoding.";
234 return AMEDIA_ERROR_INVALID_PARAMETER;
235 }
236
Chong Zhangbbb4eac2020-11-18 11:12:06 -0800237 AMediaCodec* encoder = AMediaCodec_createEncoderByTypeForClient(destinationMime, mPid, mUid);
Linus Nilssonc6221db2020-03-18 14:46:22 -0700238 if (encoder == nullptr) {
Linus Nilsson0da327a2020-01-31 16:22:18 -0800239 LOG(ERROR) << "Unable to create encoder for type " << destinationMime;
240 return AMEDIA_ERROR_UNSUPPORTED;
241 }
Linus Nilssone4716f22020-07-10 16:07:57 -0700242 mEncoder = std::make_shared<CodecWrapper>(encoder, shared_from_this());
Linus Nilsson0da327a2020-01-31 16:22:18 -0800243
Linus Nilssone4716f22020-07-10 16:07:57 -0700244 status = AMediaCodec_configure(mEncoder->getCodec(), mDestinationFormat.get(),
245 NULL /* surface */, NULL /* crypto */,
246 AMEDIACODEC_CONFIGURE_FLAG_ENCODE);
Linus Nilsson0da327a2020-01-31 16:22:18 -0800247 if (status != AMEDIA_OK) {
248 LOG(ERROR) << "Unable to configure video encoder: " << status;
249 return status;
250 }
251
Linus Nilssone4716f22020-07-10 16:07:57 -0700252 status = AMediaCodec_createInputSurface(mEncoder->getCodec(), &mSurface);
Linus Nilsson0da327a2020-01-31 16:22:18 -0800253 if (status != AMEDIA_OK) {
254 LOG(ERROR) << "Unable to create an encoder input surface: %d" << status;
255 return status;
256 }
257
258 // Create and configure the decoder.
259 const char* sourceMime = nullptr;
260 ok = AMediaFormat_getString(mSourceFormat.get(), AMEDIAFORMAT_KEY_MIME, &sourceMime);
261 if (!ok) {
262 LOG(ERROR) << "Source MIME type is required for transcoding.";
263 return AMEDIA_ERROR_INVALID_PARAMETER;
264 }
265
Chong Zhangbbb4eac2020-11-18 11:12:06 -0800266 mDecoder = AMediaCodec_createDecoderByTypeForClient(sourceMime, mPid, mUid);
Linus Nilsson0da327a2020-01-31 16:22:18 -0800267 if (mDecoder == nullptr) {
268 LOG(ERROR) << "Unable to create decoder for type " << sourceMime;
269 return AMEDIA_ERROR_UNSUPPORTED;
270 }
271
Linus Nilsson93591892020-08-03 18:56:55 -0700272 auto decoderFormat = std::shared_ptr<AMediaFormat>(AMediaFormat_new(), &AMediaFormat_delete);
273 if (!decoderFormat ||
274 AMediaFormat_copy(decoderFormat.get(), mSourceFormat.get()) != AMEDIA_OK) {
275 LOG(ERROR) << "Unable to copy source format";
276 return AMEDIA_ERROR_INVALID_PARAMETER;
277 }
278
279 // Prevent decoder from overwriting frames that the encoder has not yet consumed.
280 AMediaFormat_setInt32(decoderFormat.get(), TBD_AMEDIACODEC_PARAMETER_KEY_ALLOW_FRAME_DROP, 0);
281
Linus Nilsson16d772b2020-09-29 19:21:11 -0700282 // Copy over configurations that apply to both encoder and decoder.
Linus Nilsson7a127b22020-10-15 16:23:54 -0700283 static const EntryCopier kEncoderEntriesToCopy[] = {
Linus Nilsson16d772b2020-09-29 19:21:11 -0700284 ENTRY_COPIER2(AMEDIAFORMAT_KEY_OPERATING_RATE, Float, Int32),
285 ENTRY_COPIER(AMEDIAFORMAT_KEY_PRIORITY, Int32),
286 };
287 const size_t entryCount = sizeof(kEncoderEntriesToCopy) / sizeof(kEncoderEntriesToCopy[0]);
Linus Nilsson7a127b22020-10-15 16:23:54 -0700288 CopyFormatEntries(mDestinationFormat.get(), decoderFormat.get(), kEncoderEntriesToCopy,
289 entryCount);
Linus Nilsson16d772b2020-09-29 19:21:11 -0700290
Linus Nilsson93591892020-08-03 18:56:55 -0700291 status = AMediaCodec_configure(mDecoder, decoderFormat.get(), mSurface, NULL /* crypto */,
Linus Nilsson0da327a2020-01-31 16:22:18 -0800292 0 /* flags */);
293 if (status != AMEDIA_OK) {
294 LOG(ERROR) << "Unable to configure video decoder: " << status;
295 return status;
296 }
297
298 // Configure codecs to run in async mode.
299 AMediaCodecOnAsyncNotifyCallback asyncCodecCallbacks = {
300 .onAsyncInputAvailable = AsyncCodecCallbackDispatch::onAsyncInputAvailable,
301 .onAsyncOutputAvailable = AsyncCodecCallbackDispatch::onAsyncOutputAvailable,
302 .onAsyncFormatChanged = AsyncCodecCallbackDispatch::onAsyncFormatChanged,
303 .onAsyncError = AsyncCodecCallbackDispatch::onAsyncError};
304
Linus Nilssone4716f22020-07-10 16:07:57 -0700305 // Note: The decoder does not need its own wrapper because its lifetime is tied to the
306 // transcoder. But the same callbacks are reused for decoder and encoder so we pass the encoder
307 // wrapper as userdata here but never read the codec from it in the callback.
308 status = AMediaCodec_setAsyncNotifyCallback(mDecoder, asyncCodecCallbacks, mEncoder.get());
Linus Nilsson0da327a2020-01-31 16:22:18 -0800309 if (status != AMEDIA_OK) {
310 LOG(ERROR) << "Unable to set decoder to async mode: " << status;
311 return status;
312 }
313
Linus Nilssone4716f22020-07-10 16:07:57 -0700314 status = AMediaCodec_setAsyncNotifyCallback(mEncoder->getCodec(), asyncCodecCallbacks,
315 mEncoder.get());
Linus Nilsson0da327a2020-01-31 16:22:18 -0800316 if (status != AMEDIA_OK) {
317 LOG(ERROR) << "Unable to set encoder to async mode: " << status;
318 return status;
319 }
320
321 return AMEDIA_OK;
322}
323
324void VideoTrackTranscoder::enqueueInputSample(int32_t bufferIndex) {
325 media_status_t status = AMEDIA_OK;
326
Linus Nilssonc6221db2020-03-18 14:46:22 -0700327 if (mEosFromSource) {
Linus Nilsson0da327a2020-01-31 16:22:18 -0800328 return;
329 }
330
331 status = mMediaSampleReader->getSampleInfoForTrack(mTrackIndex, &mSampleInfo);
332 if (status != AMEDIA_OK && status != AMEDIA_ERROR_END_OF_STREAM) {
333 LOG(ERROR) << "Error getting next sample info: " << status;
334 mStatus = status;
335 return;
336 }
337 const bool endOfStream = (status == AMEDIA_ERROR_END_OF_STREAM);
338
339 if (!endOfStream) {
340 size_t bufferSize = 0;
341 uint8_t* sourceBuffer = AMediaCodec_getInputBuffer(mDecoder, bufferIndex, &bufferSize);
342 if (sourceBuffer == nullptr) {
343 LOG(ERROR) << "Decoder returned a NULL input buffer.";
344 mStatus = AMEDIA_ERROR_UNKNOWN;
345 return;
346 } else if (bufferSize < mSampleInfo.size) {
347 LOG(ERROR) << "Decoder returned an input buffer that is smaller than the sample.";
348 mStatus = AMEDIA_ERROR_UNKNOWN;
349 return;
350 }
351
352 status = mMediaSampleReader->readSampleDataForTrack(mTrackIndex, sourceBuffer,
353 mSampleInfo.size);
354 if (status != AMEDIA_OK) {
355 LOG(ERROR) << "Unable to read next sample data. Aborting transcode.";
356 mStatus = status;
357 return;
358 }
Linus Nilsson0da327a2020-01-31 16:22:18 -0800359 } else {
360 LOG(DEBUG) << "EOS from source.";
Linus Nilssonc6221db2020-03-18 14:46:22 -0700361 mEosFromSource = true;
Linus Nilsson0da327a2020-01-31 16:22:18 -0800362 }
363
364 status = AMediaCodec_queueInputBuffer(mDecoder, bufferIndex, 0, mSampleInfo.size,
365 mSampleInfo.presentationTimeUs, mSampleInfo.flags);
366 if (status != AMEDIA_OK) {
367 LOG(ERROR) << "Unable to queue input buffer for decode: " << status;
368 mStatus = status;
369 return;
370 }
371}
372
373void VideoTrackTranscoder::transferBuffer(int32_t bufferIndex, AMediaCodecBufferInfo bufferInfo) {
374 if (bufferIndex >= 0) {
375 bool needsRender = bufferInfo.size > 0;
376 AMediaCodec_releaseOutputBuffer(mDecoder, bufferIndex, needsRender);
377 }
378
379 if (bufferInfo.flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM) {
380 LOG(DEBUG) << "EOS from decoder.";
Linus Nilssone4716f22020-07-10 16:07:57 -0700381 media_status_t status = AMediaCodec_signalEndOfInputStream(mEncoder->getCodec());
Linus Nilsson0da327a2020-01-31 16:22:18 -0800382 if (status != AMEDIA_OK) {
383 LOG(ERROR) << "SignalEOS on encoder returned error: " << status;
384 mStatus = status;
385 }
386 }
387}
388
389void VideoTrackTranscoder::dequeueOutputSample(int32_t bufferIndex,
390 AMediaCodecBufferInfo bufferInfo) {
391 if (bufferIndex >= 0) {
392 size_t sampleSize = 0;
Linus Nilssone4716f22020-07-10 16:07:57 -0700393 uint8_t* buffer =
394 AMediaCodec_getOutputBuffer(mEncoder->getCodec(), bufferIndex, &sampleSize);
Linus Nilssonc6221db2020-03-18 14:46:22 -0700395
Linus Nilssone4716f22020-07-10 16:07:57 -0700396 MediaSample::OnSampleReleasedCallback bufferReleaseCallback =
397 [encoder = mEncoder](MediaSample* sample) {
398 AMediaCodec_releaseOutputBuffer(encoder->getCodec(), sample->bufferId,
399 false /* render */);
400 };
Linus Nilsson0da327a2020-01-31 16:22:18 -0800401
402 std::shared_ptr<MediaSample> sample = MediaSample::createWithReleaseCallback(
Linus Nilssonc6221db2020-03-18 14:46:22 -0700403 buffer, bufferInfo.offset, bufferIndex, bufferReleaseCallback);
Linus Nilsson0da327a2020-01-31 16:22:18 -0800404 sample->info.size = bufferInfo.size;
405 sample->info.flags = bufferInfo.flags;
406 sample->info.presentationTimeUs = bufferInfo.presentationTimeUs;
407
Linus Nilssonc31d2492020-09-23 12:30:00 -0700408 onOutputSampleAvailable(sample);
Linus Nilsson0da327a2020-01-31 16:22:18 -0800409 } else if (bufferIndex == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
Linus Nilssone4716f22020-07-10 16:07:57 -0700410 AMediaFormat* newFormat = AMediaCodec_getOutputFormat(mEncoder->getCodec());
Linus Nilsson0da327a2020-01-31 16:22:18 -0800411 LOG(DEBUG) << "Encoder output format changed: " << AMediaFormat_toString(newFormat);
412 }
413
414 if (bufferInfo.flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM) {
415 LOG(DEBUG) << "EOS from encoder.";
Linus Nilssonc6221db2020-03-18 14:46:22 -0700416 mEosFromEncoder = true;
Linus Nilsson0da327a2020-01-31 16:22:18 -0800417 }
418}
419
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700420void VideoTrackTranscoder::updateTrackFormat(AMediaFormat* outputFormat) {
421 if (mActualOutputFormat != nullptr) {
422 LOG(WARNING) << "Ignoring duplicate format change.";
423 return;
424 }
425
426 AMediaFormat* formatCopy = AMediaFormat_new();
427 if (!formatCopy || AMediaFormat_copy(formatCopy, outputFormat) != AMEDIA_OK) {
428 LOG(ERROR) << "Unable to copy outputFormat";
429 AMediaFormat_delete(formatCopy);
430 mStatus = AMEDIA_ERROR_INVALID_PARAMETER;
431 return;
432 }
433
434 // Generate the actual track format for muxer based on the encoder output format,
435 // since many vital information comes in the encoder format (eg. CSD).
436 // Transfer necessary fields from the user-configured track format (derived from
437 // source track format and user transcoding request) where needed.
438
439 // Transfer SAR settings:
440 // If mDestinationFormat has SAR set, it means the original source has SAR specified
441 // at container level. This is supposed to override any SAR settings in the bitstream,
442 // thus should always be transferred to the container of the transcoded file.
443 int32_t sarWidth, sarHeight;
Chong Zhangd6e4aec2020-06-22 14:13:07 -0700444 if (AMediaFormat_getInt32(mSourceFormat.get(), AMEDIAFORMAT_KEY_SAR_WIDTH, &sarWidth) &&
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700445 (sarWidth > 0) &&
Chong Zhangd6e4aec2020-06-22 14:13:07 -0700446 AMediaFormat_getInt32(mSourceFormat.get(), AMEDIAFORMAT_KEY_SAR_HEIGHT, &sarHeight) &&
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700447 (sarHeight > 0)) {
448 AMediaFormat_setInt32(formatCopy, AMEDIAFORMAT_KEY_SAR_WIDTH, sarWidth);
449 AMediaFormat_setInt32(formatCopy, AMEDIAFORMAT_KEY_SAR_HEIGHT, sarHeight);
450 }
451 // Transfer DAR settings.
452 int32_t displayWidth, displayHeight;
Chong Zhangd6e4aec2020-06-22 14:13:07 -0700453 if (AMediaFormat_getInt32(mSourceFormat.get(), AMEDIAFORMAT_KEY_DISPLAY_WIDTH, &displayWidth) &&
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700454 (displayWidth > 0) &&
Chong Zhangd6e4aec2020-06-22 14:13:07 -0700455 AMediaFormat_getInt32(mSourceFormat.get(), AMEDIAFORMAT_KEY_DISPLAY_HEIGHT,
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700456 &displayHeight) &&
457 (displayHeight > 0)) {
458 AMediaFormat_setInt32(formatCopy, AMEDIAFORMAT_KEY_DISPLAY_WIDTH, displayWidth);
459 AMediaFormat_setInt32(formatCopy, AMEDIAFORMAT_KEY_DISPLAY_HEIGHT, displayHeight);
460 }
461
Chong Zhangd6e4aec2020-06-22 14:13:07 -0700462 // Transfer rotation settings.
463 // Note that muxer itself doesn't take rotation from the track format. It requires
464 // AMediaMuxer_setOrientationHint to set the rotation. Here we pass the rotation to
465 // MediaSampleWriter using the track format. MediaSampleWriter will then call
466 // AMediaMuxer_setOrientationHint as needed.
467 int32_t rotation;
468 if (AMediaFormat_getInt32(mSourceFormat.get(), AMEDIAFORMAT_KEY_ROTATION, &rotation) &&
469 (rotation != 0)) {
470 AMediaFormat_setInt32(formatCopy, AMEDIAFORMAT_KEY_ROTATION, rotation);
471 }
472
Linus Nilsson42a971b2020-07-01 16:41:11 -0700473 // Transfer track duration.
474 // Preserve the source track duration by sending it to MediaSampleWriter.
475 int64_t durationUs;
476 if (AMediaFormat_getInt64(mSourceFormat.get(), AMEDIAFORMAT_KEY_DURATION, &durationUs) &&
477 durationUs > 0) {
478 AMediaFormat_setInt64(formatCopy, AMEDIAFORMAT_KEY_DURATION, durationUs);
479 }
480
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700481 // TODO: transfer other fields as required.
482
483 mActualOutputFormat = std::shared_ptr<AMediaFormat>(formatCopy, &AMediaFormat_delete);
484
485 notifyTrackFormatAvailable();
486}
487
Linus Nilsson0da327a2020-01-31 16:22:18 -0800488media_status_t VideoTrackTranscoder::runTranscodeLoop() {
Linus Nilssonb09aac22020-07-29 11:56:53 -0700489 androidSetThreadPriority(0 /* tid (0 = current) */, ANDROID_PRIORITY_VIDEO);
490
Chong Zhangb55c5452020-06-26 14:32:12 -0700491 // Push start decoder and encoder as two messages, so that these are subject to the
Chong Zhangbc062482020-10-14 16:43:53 -0700492 // stop request as well. If the session is cancelled (or paused) immediately after start,
Chong Zhangb55c5452020-06-26 14:32:12 -0700493 // we don't need to waste time start then stop the codecs.
494 mCodecMessageQueue.push([this] {
495 media_status_t status = AMediaCodec_start(mDecoder);
496 if (status != AMEDIA_OK) {
497 LOG(ERROR) << "Unable to start video decoder: " << status;
498 mStatus = status;
499 }
500 });
Linus Nilsson0da327a2020-01-31 16:22:18 -0800501
Chong Zhangb55c5452020-06-26 14:32:12 -0700502 mCodecMessageQueue.push([this] {
Linus Nilssone4716f22020-07-10 16:07:57 -0700503 media_status_t status = AMediaCodec_start(mEncoder->getCodec());
Chong Zhangb55c5452020-06-26 14:32:12 -0700504 if (status != AMEDIA_OK) {
505 LOG(ERROR) << "Unable to start video encoder: " << status;
506 mStatus = status;
507 }
Linus Nilssone4716f22020-07-10 16:07:57 -0700508 mEncoder->setStarted();
Chong Zhangb55c5452020-06-26 14:32:12 -0700509 });
Linus Nilsson0da327a2020-01-31 16:22:18 -0800510
511 // Process codec events until EOS is reached, transcoding is stopped or an error occurs.
Linus Nilssonc6221db2020-03-18 14:46:22 -0700512 while (!mStopRequested && !mEosFromEncoder && mStatus == AMEDIA_OK) {
Linus Nilsson0da327a2020-01-31 16:22:18 -0800513 std::function<void()> message = mCodecMessageQueue.pop();
514 message();
515 }
516
Linus Nilsson93cf9132020-09-24 12:12:48 -0700517 mCodecMessageQueue.abort();
518 AMediaCodec_stop(mDecoder);
519
Linus Nilsson0da327a2020-01-31 16:22:18 -0800520 // Return error if transcoding was stopped before it finished.
Linus Nilssonc6221db2020-03-18 14:46:22 -0700521 if (mStopRequested && !mEosFromEncoder && mStatus == AMEDIA_OK) {
Linus Nilsson0da327a2020-01-31 16:22:18 -0800522 mStatus = AMEDIA_ERROR_UNKNOWN; // TODO: Define custom error codes?
523 }
524
Linus Nilsson0da327a2020-01-31 16:22:18 -0800525 return mStatus;
526}
527
528void VideoTrackTranscoder::abortTranscodeLoop() {
529 // Push abort message to the front of the codec event queue.
530 mCodecMessageQueue.push([this] { mStopRequested = true; }, true /* front */);
531}
532
Linus Nilssoncab39d82020-05-14 16:32:21 -0700533std::shared_ptr<AMediaFormat> VideoTrackTranscoder::getOutputFormat() const {
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700534 return mActualOutputFormat;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700535}
536
Linus Nilsson0da327a2020-01-31 16:22:18 -0800537} // namespace android