blob: 4cf54f168b9e80ffcc93f15f89fd1b7fefa45931 [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(
170 const std::weak_ptr<MediaTrackTranscoderCallback>& transcoderCallback) {
171 return std::shared_ptr<VideoTrackTranscoder>(new VideoTrackTranscoder(transcoderCallback));
172}
173
Linus Nilsson0da327a2020-01-31 16:22:18 -0800174VideoTrackTranscoder::~VideoTrackTranscoder() {
175 if (mDecoder != nullptr) {
176 AMediaCodec_delete(mDecoder);
177 }
178
Linus Nilsson0da327a2020-01-31 16:22:18 -0800179 if (mSurface != nullptr) {
180 ANativeWindow_release(mSurface);
181 }
182}
183
184// Creates and configures the codecs.
185media_status_t VideoTrackTranscoder::configureDestinationFormat(
186 const std::shared_ptr<AMediaFormat>& destinationFormat) {
187 media_status_t status = AMEDIA_OK;
188
189 if (destinationFormat == nullptr) {
Linus Nilssoncab39d82020-05-14 16:32:21 -0700190 LOG(ERROR) << "Destination format is null, use passthrough transcoder";
Linus Nilsson0da327a2020-01-31 16:22:18 -0800191 return AMEDIA_ERROR_INVALID_PARAMETER;
192 }
193
Linus Nilssoncab39d82020-05-14 16:32:21 -0700194 AMediaFormat* encoderFormat = AMediaFormat_new();
195 if (!encoderFormat || AMediaFormat_copy(encoderFormat, destinationFormat.get()) != AMEDIA_OK) {
196 LOG(ERROR) << "Unable to copy destination format";
197 return AMEDIA_ERROR_INVALID_PARAMETER;
198 }
199
Linus Nilsson800793f2020-07-31 16:16:38 -0700200 int32_t bitrate;
201 if (!AMediaFormat_getInt32(encoderFormat, AMEDIAFORMAT_KEY_BIT_RATE, &bitrate)) {
202 status = mMediaSampleReader->getEstimatedBitrateForTrack(mTrackIndex, &bitrate);
203 if (status != AMEDIA_OK) {
204 LOG(ERROR) << "Unable to estimate bitrate. Using default " << kDefaultBitrateMbps;
205 bitrate = kDefaultBitrateMbps;
206 }
207
208 LOG(INFO) << "Configuring bitrate " << bitrate;
209 AMediaFormat_setInt32(encoderFormat, AMEDIAFORMAT_KEY_BIT_RATE, bitrate);
210 }
211
Linus Nilsson7a127b22020-10-15 16:23:54 -0700212 SetDefaultFormatValueFloat(AMEDIAFORMAT_KEY_I_FRAME_INTERVAL, encoderFormat,
213 kDefaultKeyFrameIntervalSeconds);
214 SetDefaultFormatValueInt32(AMEDIAFORMAT_KEY_OPERATING_RATE, encoderFormat,
215 kDefaultCodecOperatingRate);
216 SetDefaultFormatValueInt32(AMEDIAFORMAT_KEY_PRIORITY, encoderFormat, kDefaultCodecPriority);
217
Linus Nilssoncab39d82020-05-14 16:32:21 -0700218 AMediaFormat_setInt32(encoderFormat, AMEDIAFORMAT_KEY_COLOR_FORMAT, kColorFormatSurface);
219
Chong Zhangd6e4aec2020-06-22 14:13:07 -0700220 // Always encode without rotation. The rotation degree will be transferred directly to
221 // MediaSampleWriter track format, and MediaSampleWriter will call AMediaMuxer_setOrientationHint.
222 AMediaFormat_setInt32(encoderFormat, AMEDIAFORMAT_KEY_ROTATION, 0);
223
Linus Nilssoncab39d82020-05-14 16:32:21 -0700224 mDestinationFormat = std::shared_ptr<AMediaFormat>(encoderFormat, &AMediaFormat_delete);
Linus Nilsson0da327a2020-01-31 16:22:18 -0800225
226 // Create and configure the encoder.
227 const char* destinationMime = nullptr;
228 bool ok = AMediaFormat_getString(mDestinationFormat.get(), AMEDIAFORMAT_KEY_MIME,
229 &destinationMime);
230 if (!ok) {
231 LOG(ERROR) << "Destination MIME type is required for transcoding.";
232 return AMEDIA_ERROR_INVALID_PARAMETER;
233 }
234
Linus Nilssonc6221db2020-03-18 14:46:22 -0700235 AMediaCodec* encoder = AMediaCodec_createEncoderByType(destinationMime);
236 if (encoder == nullptr) {
Linus Nilsson0da327a2020-01-31 16:22:18 -0800237 LOG(ERROR) << "Unable to create encoder for type " << destinationMime;
238 return AMEDIA_ERROR_UNSUPPORTED;
239 }
Linus Nilssone4716f22020-07-10 16:07:57 -0700240 mEncoder = std::make_shared<CodecWrapper>(encoder, shared_from_this());
Linus Nilsson0da327a2020-01-31 16:22:18 -0800241
Linus Nilssone4716f22020-07-10 16:07:57 -0700242 status = AMediaCodec_configure(mEncoder->getCodec(), mDestinationFormat.get(),
243 NULL /* surface */, NULL /* crypto */,
244 AMEDIACODEC_CONFIGURE_FLAG_ENCODE);
Linus Nilsson0da327a2020-01-31 16:22:18 -0800245 if (status != AMEDIA_OK) {
246 LOG(ERROR) << "Unable to configure video encoder: " << status;
247 return status;
248 }
249
Linus Nilssone4716f22020-07-10 16:07:57 -0700250 status = AMediaCodec_createInputSurface(mEncoder->getCodec(), &mSurface);
Linus Nilsson0da327a2020-01-31 16:22:18 -0800251 if (status != AMEDIA_OK) {
252 LOG(ERROR) << "Unable to create an encoder input surface: %d" << status;
253 return status;
254 }
255
256 // Create and configure the decoder.
257 const char* sourceMime = nullptr;
258 ok = AMediaFormat_getString(mSourceFormat.get(), AMEDIAFORMAT_KEY_MIME, &sourceMime);
259 if (!ok) {
260 LOG(ERROR) << "Source MIME type is required for transcoding.";
261 return AMEDIA_ERROR_INVALID_PARAMETER;
262 }
263
264 mDecoder = AMediaCodec_createDecoderByType(sourceMime);
265 if (mDecoder == nullptr) {
266 LOG(ERROR) << "Unable to create decoder for type " << sourceMime;
267 return AMEDIA_ERROR_UNSUPPORTED;
268 }
269
Linus Nilsson93591892020-08-03 18:56:55 -0700270 auto decoderFormat = std::shared_ptr<AMediaFormat>(AMediaFormat_new(), &AMediaFormat_delete);
271 if (!decoderFormat ||
272 AMediaFormat_copy(decoderFormat.get(), mSourceFormat.get()) != AMEDIA_OK) {
273 LOG(ERROR) << "Unable to copy source format";
274 return AMEDIA_ERROR_INVALID_PARAMETER;
275 }
276
277 // Prevent decoder from overwriting frames that the encoder has not yet consumed.
278 AMediaFormat_setInt32(decoderFormat.get(), TBD_AMEDIACODEC_PARAMETER_KEY_ALLOW_FRAME_DROP, 0);
279
Linus Nilsson16d772b2020-09-29 19:21:11 -0700280 // Copy over configurations that apply to both encoder and decoder.
Linus Nilsson7a127b22020-10-15 16:23:54 -0700281 static const EntryCopier kEncoderEntriesToCopy[] = {
Linus Nilsson16d772b2020-09-29 19:21:11 -0700282 ENTRY_COPIER2(AMEDIAFORMAT_KEY_OPERATING_RATE, Float, Int32),
283 ENTRY_COPIER(AMEDIAFORMAT_KEY_PRIORITY, Int32),
284 };
285 const size_t entryCount = sizeof(kEncoderEntriesToCopy) / sizeof(kEncoderEntriesToCopy[0]);
Linus Nilsson7a127b22020-10-15 16:23:54 -0700286 CopyFormatEntries(mDestinationFormat.get(), decoderFormat.get(), kEncoderEntriesToCopy,
287 entryCount);
Linus Nilsson16d772b2020-09-29 19:21:11 -0700288
Linus Nilsson93591892020-08-03 18:56:55 -0700289 status = AMediaCodec_configure(mDecoder, decoderFormat.get(), mSurface, NULL /* crypto */,
Linus Nilsson0da327a2020-01-31 16:22:18 -0800290 0 /* flags */);
291 if (status != AMEDIA_OK) {
292 LOG(ERROR) << "Unable to configure video decoder: " << status;
293 return status;
294 }
295
296 // Configure codecs to run in async mode.
297 AMediaCodecOnAsyncNotifyCallback asyncCodecCallbacks = {
298 .onAsyncInputAvailable = AsyncCodecCallbackDispatch::onAsyncInputAvailable,
299 .onAsyncOutputAvailable = AsyncCodecCallbackDispatch::onAsyncOutputAvailable,
300 .onAsyncFormatChanged = AsyncCodecCallbackDispatch::onAsyncFormatChanged,
301 .onAsyncError = AsyncCodecCallbackDispatch::onAsyncError};
302
Linus Nilssone4716f22020-07-10 16:07:57 -0700303 // Note: The decoder does not need its own wrapper because its lifetime is tied to the
304 // transcoder. But the same callbacks are reused for decoder and encoder so we pass the encoder
305 // wrapper as userdata here but never read the codec from it in the callback.
306 status = AMediaCodec_setAsyncNotifyCallback(mDecoder, asyncCodecCallbacks, mEncoder.get());
Linus Nilsson0da327a2020-01-31 16:22:18 -0800307 if (status != AMEDIA_OK) {
308 LOG(ERROR) << "Unable to set decoder to async mode: " << status;
309 return status;
310 }
311
Linus Nilssone4716f22020-07-10 16:07:57 -0700312 status = AMediaCodec_setAsyncNotifyCallback(mEncoder->getCodec(), asyncCodecCallbacks,
313 mEncoder.get());
Linus Nilsson0da327a2020-01-31 16:22:18 -0800314 if (status != AMEDIA_OK) {
315 LOG(ERROR) << "Unable to set encoder to async mode: " << status;
316 return status;
317 }
318
319 return AMEDIA_OK;
320}
321
322void VideoTrackTranscoder::enqueueInputSample(int32_t bufferIndex) {
323 media_status_t status = AMEDIA_OK;
324
Linus Nilssonc6221db2020-03-18 14:46:22 -0700325 if (mEosFromSource) {
Linus Nilsson0da327a2020-01-31 16:22:18 -0800326 return;
327 }
328
329 status = mMediaSampleReader->getSampleInfoForTrack(mTrackIndex, &mSampleInfo);
330 if (status != AMEDIA_OK && status != AMEDIA_ERROR_END_OF_STREAM) {
331 LOG(ERROR) << "Error getting next sample info: " << status;
332 mStatus = status;
333 return;
334 }
335 const bool endOfStream = (status == AMEDIA_ERROR_END_OF_STREAM);
336
337 if (!endOfStream) {
338 size_t bufferSize = 0;
339 uint8_t* sourceBuffer = AMediaCodec_getInputBuffer(mDecoder, bufferIndex, &bufferSize);
340 if (sourceBuffer == nullptr) {
341 LOG(ERROR) << "Decoder returned a NULL input buffer.";
342 mStatus = AMEDIA_ERROR_UNKNOWN;
343 return;
344 } else if (bufferSize < mSampleInfo.size) {
345 LOG(ERROR) << "Decoder returned an input buffer that is smaller than the sample.";
346 mStatus = AMEDIA_ERROR_UNKNOWN;
347 return;
348 }
349
350 status = mMediaSampleReader->readSampleDataForTrack(mTrackIndex, sourceBuffer,
351 mSampleInfo.size);
352 if (status != AMEDIA_OK) {
353 LOG(ERROR) << "Unable to read next sample data. Aborting transcode.";
354 mStatus = status;
355 return;
356 }
Linus Nilsson0da327a2020-01-31 16:22:18 -0800357 } else {
358 LOG(DEBUG) << "EOS from source.";
Linus Nilssonc6221db2020-03-18 14:46:22 -0700359 mEosFromSource = true;
Linus Nilsson0da327a2020-01-31 16:22:18 -0800360 }
361
362 status = AMediaCodec_queueInputBuffer(mDecoder, bufferIndex, 0, mSampleInfo.size,
363 mSampleInfo.presentationTimeUs, mSampleInfo.flags);
364 if (status != AMEDIA_OK) {
365 LOG(ERROR) << "Unable to queue input buffer for decode: " << status;
366 mStatus = status;
367 return;
368 }
369}
370
371void VideoTrackTranscoder::transferBuffer(int32_t bufferIndex, AMediaCodecBufferInfo bufferInfo) {
372 if (bufferIndex >= 0) {
373 bool needsRender = bufferInfo.size > 0;
374 AMediaCodec_releaseOutputBuffer(mDecoder, bufferIndex, needsRender);
375 }
376
377 if (bufferInfo.flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM) {
378 LOG(DEBUG) << "EOS from decoder.";
Linus Nilssone4716f22020-07-10 16:07:57 -0700379 media_status_t status = AMediaCodec_signalEndOfInputStream(mEncoder->getCodec());
Linus Nilsson0da327a2020-01-31 16:22:18 -0800380 if (status != AMEDIA_OK) {
381 LOG(ERROR) << "SignalEOS on encoder returned error: " << status;
382 mStatus = status;
383 }
384 }
385}
386
387void VideoTrackTranscoder::dequeueOutputSample(int32_t bufferIndex,
388 AMediaCodecBufferInfo bufferInfo) {
389 if (bufferIndex >= 0) {
390 size_t sampleSize = 0;
Linus Nilssone4716f22020-07-10 16:07:57 -0700391 uint8_t* buffer =
392 AMediaCodec_getOutputBuffer(mEncoder->getCodec(), bufferIndex, &sampleSize);
Linus Nilssonc6221db2020-03-18 14:46:22 -0700393
Linus Nilssone4716f22020-07-10 16:07:57 -0700394 MediaSample::OnSampleReleasedCallback bufferReleaseCallback =
395 [encoder = mEncoder](MediaSample* sample) {
396 AMediaCodec_releaseOutputBuffer(encoder->getCodec(), sample->bufferId,
397 false /* render */);
398 };
Linus Nilsson0da327a2020-01-31 16:22:18 -0800399
400 std::shared_ptr<MediaSample> sample = MediaSample::createWithReleaseCallback(
Linus Nilssonc6221db2020-03-18 14:46:22 -0700401 buffer, bufferInfo.offset, bufferIndex, bufferReleaseCallback);
Linus Nilsson0da327a2020-01-31 16:22:18 -0800402 sample->info.size = bufferInfo.size;
403 sample->info.flags = bufferInfo.flags;
404 sample->info.presentationTimeUs = bufferInfo.presentationTimeUs;
405
Linus Nilssonc31d2492020-09-23 12:30:00 -0700406 onOutputSampleAvailable(sample);
Linus Nilsson0da327a2020-01-31 16:22:18 -0800407 } else if (bufferIndex == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
Linus Nilssone4716f22020-07-10 16:07:57 -0700408 AMediaFormat* newFormat = AMediaCodec_getOutputFormat(mEncoder->getCodec());
Linus Nilsson0da327a2020-01-31 16:22:18 -0800409 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 Nilssonc6221db2020-03-18 14:46:22 -0700414 mEosFromEncoder = true;
Linus Nilsson0da327a2020-01-31 16:22:18 -0800415 }
416}
417
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700418void 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 Zhangd6e4aec2020-06-22 14:13:07 -0700442 if (AMediaFormat_getInt32(mSourceFormat.get(), AMEDIAFORMAT_KEY_SAR_WIDTH, &sarWidth) &&
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700443 (sarWidth > 0) &&
Chong Zhangd6e4aec2020-06-22 14:13:07 -0700444 AMediaFormat_getInt32(mSourceFormat.get(), AMEDIAFORMAT_KEY_SAR_HEIGHT, &sarHeight) &&
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700445 (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 Zhangd6e4aec2020-06-22 14:13:07 -0700451 if (AMediaFormat_getInt32(mSourceFormat.get(), AMEDIAFORMAT_KEY_DISPLAY_WIDTH, &displayWidth) &&
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700452 (displayWidth > 0) &&
Chong Zhangd6e4aec2020-06-22 14:13:07 -0700453 AMediaFormat_getInt32(mSourceFormat.get(), AMEDIAFORMAT_KEY_DISPLAY_HEIGHT,
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700454 &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 Zhangd6e4aec2020-06-22 14:13:07 -0700460 // 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 Nilsson42a971b2020-07-01 16:41:11 -0700471 // 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 Zhanga2cc86b2020-06-17 16:56:49 -0700479 // TODO: transfer other fields as required.
480
481 mActualOutputFormat = std::shared_ptr<AMediaFormat>(formatCopy, &AMediaFormat_delete);
482
483 notifyTrackFormatAvailable();
484}
485
Linus Nilsson0da327a2020-01-31 16:22:18 -0800486media_status_t VideoTrackTranscoder::runTranscodeLoop() {
Linus Nilssonb09aac22020-07-29 11:56:53 -0700487 androidSetThreadPriority(0 /* tid (0 = current) */, ANDROID_PRIORITY_VIDEO);
488
Chong Zhangb55c5452020-06-26 14:32:12 -0700489 // Push start decoder and encoder as two messages, so that these are subject to the
Chong Zhangbc062482020-10-14 16:43:53 -0700490 // stop request as well. If the session is cancelled (or paused) immediately after start,
Chong Zhangb55c5452020-06-26 14:32:12 -0700491 // 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 Nilsson0da327a2020-01-31 16:22:18 -0800499
Chong Zhangb55c5452020-06-26 14:32:12 -0700500 mCodecMessageQueue.push([this] {
Linus Nilssone4716f22020-07-10 16:07:57 -0700501 media_status_t status = AMediaCodec_start(mEncoder->getCodec());
Chong Zhangb55c5452020-06-26 14:32:12 -0700502 if (status != AMEDIA_OK) {
503 LOG(ERROR) << "Unable to start video encoder: " << status;
504 mStatus = status;
505 }
Linus Nilssone4716f22020-07-10 16:07:57 -0700506 mEncoder->setStarted();
Chong Zhangb55c5452020-06-26 14:32:12 -0700507 });
Linus Nilsson0da327a2020-01-31 16:22:18 -0800508
509 // Process codec events until EOS is reached, transcoding is stopped or an error occurs.
Linus Nilssonc6221db2020-03-18 14:46:22 -0700510 while (!mStopRequested && !mEosFromEncoder && mStatus == AMEDIA_OK) {
Linus Nilsson0da327a2020-01-31 16:22:18 -0800511 std::function<void()> message = mCodecMessageQueue.pop();
512 message();
513 }
514
Linus Nilsson93cf9132020-09-24 12:12:48 -0700515 mCodecMessageQueue.abort();
516 AMediaCodec_stop(mDecoder);
517
Linus Nilsson0da327a2020-01-31 16:22:18 -0800518 // Return error if transcoding was stopped before it finished.
Linus Nilssonc6221db2020-03-18 14:46:22 -0700519 if (mStopRequested && !mEosFromEncoder && mStatus == AMEDIA_OK) {
Linus Nilsson0da327a2020-01-31 16:22:18 -0800520 mStatus = AMEDIA_ERROR_UNKNOWN; // TODO: Define custom error codes?
521 }
522
Linus Nilsson0da327a2020-01-31 16:22:18 -0800523 return mStatus;
524}
525
526void VideoTrackTranscoder::abortTranscodeLoop() {
527 // Push abort message to the front of the codec event queue.
528 mCodecMessageQueue.push([this] { mStopRequested = true; }, true /* front */);
529}
530
Linus Nilssoncab39d82020-05-14 16:32:21 -0700531std::shared_ptr<AMediaFormat> VideoTrackTranscoder::getOutputFormat() const {
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700532 return mActualOutputFormat;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700533}
534
Linus Nilsson0da327a2020-01-31 16:22:18 -0800535} // namespace android