blob: cdb8368494da2de18326aa485d3ae0178f5d4209 [file] [log] [blame]
Linus Nilssoncab39d82020-05-14 16:32:21 -07001/*
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 "MediaTranscoder"
19
20#include <android-base/logging.h>
Chong Zhangb55c5452020-06-26 14:32:12 -070021#include <binder/Parcel.h>
Linus Nilssoncab39d82020-05-14 16:32:21 -070022#include <fcntl.h>
23#include <media/MediaSampleReaderNDK.h>
Chong Zhang308e91f2020-06-10 15:27:56 -070024#include <media/MediaSampleWriter.h>
Linus Nilssoncab39d82020-05-14 16:32:21 -070025#include <media/MediaTranscoder.h>
Linus Nilsson16d772b2020-09-29 19:21:11 -070026#include <media/NdkCommon.h>
Linus Nilssoncab39d82020-05-14 16:32:21 -070027#include <media/PassthroughTrackTranscoder.h>
28#include <media/VideoTrackTranscoder.h>
29#include <unistd.h>
30
31namespace android {
32
Linus Nilssoncab39d82020-05-14 16:32:21 -070033static AMediaFormat* mergeMediaFormats(AMediaFormat* base, AMediaFormat* overlay) {
34 if (base == nullptr || overlay == nullptr) {
35 LOG(ERROR) << "Cannot merge null formats";
36 return nullptr;
37 }
38
39 AMediaFormat* format = AMediaFormat_new();
40 if (AMediaFormat_copy(format, base) != AMEDIA_OK) {
41 AMediaFormat_delete(format);
42 return nullptr;
43 }
44
45 // Note: AMediaFormat does not expose a function for appending values from another format or for
46 // iterating over all values and keys in a format. Instead we define a static list of known keys
47 // along with their value types and copy the ones that are present. A better solution would be
48 // to either implement required functions in NDK or to parse the overlay format's string
49 // representation and copy all existing keys.
Linus Nilsson16d772b2020-09-29 19:21:11 -070050 static const AMediaFormatUtils::EntryCopier kSupportedFormatEntries[] = {
51 ENTRY_COPIER(AMEDIAFORMAT_KEY_MIME, String),
52 ENTRY_COPIER(AMEDIAFORMAT_KEY_DURATION, Int64),
53 ENTRY_COPIER(AMEDIAFORMAT_KEY_WIDTH, Int32),
54 ENTRY_COPIER(AMEDIAFORMAT_KEY_HEIGHT, Int32),
55 ENTRY_COPIER(AMEDIAFORMAT_KEY_BIT_RATE, Int32),
56 ENTRY_COPIER(AMEDIAFORMAT_KEY_PROFILE, Int32),
57 ENTRY_COPIER(AMEDIAFORMAT_KEY_LEVEL, Int32),
58 ENTRY_COPIER(AMEDIAFORMAT_KEY_COLOR_FORMAT, Int32),
59 ENTRY_COPIER(AMEDIAFORMAT_KEY_COLOR_RANGE, Int32),
60 ENTRY_COPIER(AMEDIAFORMAT_KEY_COLOR_STANDARD, Int32),
61 ENTRY_COPIER(AMEDIAFORMAT_KEY_COLOR_TRANSFER, Int32),
62 ENTRY_COPIER(AMEDIAFORMAT_KEY_FRAME_RATE, Int32),
63 ENTRY_COPIER(AMEDIAFORMAT_KEY_I_FRAME_INTERVAL, Int32),
64 ENTRY_COPIER(AMEDIAFORMAT_KEY_PRIORITY, Int32),
65 ENTRY_COPIER2(AMEDIAFORMAT_KEY_OPERATING_RATE, Float, Int32),
Linus Nilssoncab39d82020-05-14 16:32:21 -070066 };
Linus Nilsson16d772b2020-09-29 19:21:11 -070067 const size_t entryCount = sizeof(kSupportedFormatEntries) / sizeof(kSupportedFormatEntries[0]);
Linus Nilssoncab39d82020-05-14 16:32:21 -070068
Linus Nilsson16d772b2020-09-29 19:21:11 -070069 AMediaFormatUtils::CopyFormatEntries(overlay, format, kSupportedFormatEntries, entryCount);
Linus Nilssoncab39d82020-05-14 16:32:21 -070070 return format;
71}
72
73void MediaTranscoder::sendCallback(media_status_t status) {
Chong Zhangb55c5452020-06-26 14:32:12 -070074 // If the transcoder is already cancelled explicitly, don't send any error callbacks.
75 // Tracks and sample writer will report errors for abort. However, currently we can't
76 // tell it apart from real errors. Ideally we still want to report real errors back
77 // to client, as there is a small chance that explicit abort and the real error come
78 // at around the same time, we should report that if abort has a specific error code.
79 // On the other hand, if the transcoder actually finished (status is AMEDIA_OK) at around
80 // the same time of the abort, we should still report the finish back to the client.
81 if (mCancelled && status != AMEDIA_OK) {
82 return;
83 }
84
Linus Nilssoncab39d82020-05-14 16:32:21 -070085 bool expected = false;
86 if (mCallbackSent.compare_exchange_strong(expected, true)) {
87 if (status == AMEDIA_OK) {
88 mCallbacks->onFinished(this);
89 } else {
90 mCallbacks->onError(this, status);
91 }
92
93 // Transcoding is done and the callback to the client has been sent, so tear down the
Chong Zhang308e91f2020-06-10 15:27:56 -070094 // pipeline but do it asynchronously to avoid deadlocks. If an error occurred, client
95 // should clean up the file.
Chong Zhanga2cc86b2020-06-17 16:56:49 -070096 std::thread asyncCancelThread{[self = shared_from_this()] { self->cancel(); }};
Linus Nilssoncab39d82020-05-14 16:32:21 -070097 asyncCancelThread.detach();
98 }
99}
100
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700101void MediaTranscoder::onTrackFormatAvailable(const MediaTrackTranscoder* transcoder) {
102 LOG(INFO) << "TrackTranscoder " << transcoder << " format available.";
103
104 std::scoped_lock lock{mTracksAddedMutex};
105
106 // Ignore duplicate format change.
107 if (mTracksAdded.count(transcoder) > 0) {
108 return;
109 }
110
111 // Add track to the writer.
Linus Nilssonc31d2492020-09-23 12:30:00 -0700112 auto consumer = mSampleWriter->addTrack(transcoder->getOutputFormat());
113 if (consumer == nullptr) {
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700114 LOG(ERROR) << "Unable to add track to sample writer.";
115 sendCallback(AMEDIA_ERROR_UNKNOWN);
116 return;
117 }
118
Linus Nilssonc31d2492020-09-23 12:30:00 -0700119 MediaTrackTranscoder* mutableTranscoder = const_cast<MediaTrackTranscoder*>(transcoder);
120 mutableTranscoder->setSampleConsumer(consumer);
121
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700122 mTracksAdded.insert(transcoder);
123 if (mTracksAdded.size() == mTrackTranscoders.size()) {
Linus Nilsson6233fed2020-08-13 15:15:14 -0700124 // Enable sequential access mode on the sample reader to achieve optimal read performance.
125 // This has to wait until all tracks have delivered their output formats and the sample
126 // writer is started. Otherwise the tracks will not get their output sample queues drained
127 // and the transcoder could hang due to one track running out of buffers and blocking the
128 // other tracks from reading source samples before they could output their formats.
129 mSampleReader->setEnforceSequentialAccess(true);
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700130 LOG(INFO) << "Starting sample writer.";
131 bool started = mSampleWriter->start();
132 if (!started) {
133 LOG(ERROR) << "Unable to start sample writer.";
134 sendCallback(AMEDIA_ERROR_UNKNOWN);
135 }
136 }
137}
138
Linus Nilssoncab39d82020-05-14 16:32:21 -0700139void MediaTranscoder::onTrackFinished(const MediaTrackTranscoder* transcoder) {
140 LOG(DEBUG) << "TrackTranscoder " << transcoder << " finished";
141}
142
143void MediaTranscoder::onTrackError(const MediaTrackTranscoder* transcoder, media_status_t status) {
Linus Nilsson93cf9132020-09-24 12:12:48 -0700144 LOG(ERROR) << "TrackTranscoder " << transcoder << " returned error " << status;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700145 sendCallback(status);
146}
147
Linus Nilssone2cdd1f2020-07-07 17:29:26 -0700148void MediaTranscoder::onFinished(const MediaSampleWriter* writer __unused, media_status_t status) {
Linus Nilssoncab39d82020-05-14 16:32:21 -0700149 LOG((status != AMEDIA_OK) ? ERROR : DEBUG) << "Sample writer finished with status " << status;
150 sendCallback(status);
151}
152
Linus Nilssone2cdd1f2020-07-07 17:29:26 -0700153void MediaTranscoder::onProgressUpdate(const MediaSampleWriter* writer __unused, int32_t progress) {
154 // Dispatch progress updated to the client.
155 mCallbacks->onProgressUpdate(this, progress);
156}
157
Chong Zhang308e91f2020-06-10 15:27:56 -0700158MediaTranscoder::MediaTranscoder(const std::shared_ptr<CallbackInterface>& callbacks)
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700159 : mCallbacks(callbacks) {}
Chong Zhang308e91f2020-06-10 15:27:56 -0700160
Linus Nilssoncab39d82020-05-14 16:32:21 -0700161std::shared_ptr<MediaTranscoder> MediaTranscoder::create(
162 const std::shared_ptr<CallbackInterface>& callbacks,
Chong Zhangb55c5452020-06-26 14:32:12 -0700163 const std::shared_ptr<const Parcel>& pausedState) {
Linus Nilssoncab39d82020-05-14 16:32:21 -0700164 if (pausedState != nullptr) {
Chong Zhangb55c5452020-06-26 14:32:12 -0700165 LOG(INFO) << "Initializing from paused state.";
166 }
167 if (callbacks == nullptr) {
Linus Nilssoncab39d82020-05-14 16:32:21 -0700168 LOG(ERROR) << "Callbacks cannot be null";
169 return nullptr;
170 }
171
172 return std::shared_ptr<MediaTranscoder>(new MediaTranscoder(callbacks));
173}
174
Chong Zhang308e91f2020-06-10 15:27:56 -0700175media_status_t MediaTranscoder::configureSource(int fd) {
176 if (fd < 0) {
177 LOG(ERROR) << "Invalid source fd: " << fd;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700178 return AMEDIA_ERROR_INVALID_PARAMETER;
179 }
180
181 const size_t fileSize = lseek(fd, 0, SEEK_END);
182 lseek(fd, 0, SEEK_SET);
183
184 mSampleReader = MediaSampleReaderNDK::createFromFd(fd, 0 /* offset */, fileSize);
Linus Nilssoncab39d82020-05-14 16:32:21 -0700185
186 if (mSampleReader == nullptr) {
Chong Zhang308e91f2020-06-10 15:27:56 -0700187 LOG(ERROR) << "Unable to parse source fd: " << fd;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700188 return AMEDIA_ERROR_UNSUPPORTED;
189 }
190
191 const size_t trackCount = mSampleReader->getTrackCount();
192 for (size_t trackIndex = 0; trackIndex < trackCount; ++trackIndex) {
193 AMediaFormat* trackFormat = mSampleReader->getTrackFormat(static_cast<int>(trackIndex));
194 if (trackFormat == nullptr) {
195 LOG(ERROR) << "Track #" << trackIndex << " has no format";
196 return AMEDIA_ERROR_MALFORMED;
197 }
198
199 mSourceTrackFormats.emplace_back(trackFormat, &AMediaFormat_delete);
200 }
201
202 return AMEDIA_OK;
203}
204
205std::vector<std::shared_ptr<AMediaFormat>> MediaTranscoder::getTrackFormats() const {
206 // Return a deep copy of the formats to avoid the caller modifying our internal formats.
207 std::vector<std::shared_ptr<AMediaFormat>> trackFormats;
208 for (const std::shared_ptr<AMediaFormat>& sourceFormat : mSourceTrackFormats) {
209 AMediaFormat* copy = AMediaFormat_new();
210 AMediaFormat_copy(copy, sourceFormat.get());
211 trackFormats.emplace_back(copy, &AMediaFormat_delete);
212 }
213 return trackFormats;
214}
215
216media_status_t MediaTranscoder::configureTrackFormat(size_t trackIndex, AMediaFormat* trackFormat) {
217 if (mSampleReader == nullptr) {
218 LOG(ERROR) << "Source must be configured before tracks";
219 return AMEDIA_ERROR_INVALID_OPERATION;
220 } else if (trackIndex >= mSourceTrackFormats.size()) {
221 LOG(ERROR) << "Track index " << trackIndex
222 << " is out of bounds. Track count: " << mSourceTrackFormats.size();
223 return AMEDIA_ERROR_INVALID_PARAMETER;
224 }
225
Linus Nilsson6233fed2020-08-13 15:15:14 -0700226 media_status_t status = mSampleReader->selectTrack(trackIndex);
227 if (status != AMEDIA_OK) {
228 LOG(ERROR) << "Unable to select track " << trackIndex;
229 return status;
230 }
231
Linus Nilssone4716f22020-07-10 16:07:57 -0700232 std::shared_ptr<MediaTrackTranscoder> transcoder;
233 std::shared_ptr<AMediaFormat> format;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700234
235 if (trackFormat == nullptr) {
Linus Nilssone4716f22020-07-10 16:07:57 -0700236 transcoder = std::make_shared<PassthroughTrackTranscoder>(shared_from_this());
Linus Nilssoncab39d82020-05-14 16:32:21 -0700237 } else {
238 const char* srcMime = nullptr;
239 if (!AMediaFormat_getString(mSourceTrackFormats[trackIndex].get(), AMEDIAFORMAT_KEY_MIME,
240 &srcMime)) {
241 LOG(ERROR) << "Source track #" << trackIndex << " has no mime type";
242 return AMEDIA_ERROR_MALFORMED;
243 }
244
245 if (strncmp(srcMime, "video/", 6) != 0) {
246 LOG(ERROR) << "Only video tracks are supported for transcoding. Unable to configure "
247 "track #"
248 << trackIndex << " with mime " << srcMime;
249 return AMEDIA_ERROR_UNSUPPORTED;
250 }
251
252 const char* dstMime = nullptr;
253 if (AMediaFormat_getString(trackFormat, AMEDIAFORMAT_KEY_MIME, &dstMime)) {
254 if (strncmp(dstMime, "video/", 6) != 0) {
255 LOG(ERROR) << "Unable to convert media types for track #" << trackIndex << ", from "
256 << srcMime << " to " << dstMime;
257 return AMEDIA_ERROR_UNSUPPORTED;
258 }
259 }
260
Linus Nilssone4716f22020-07-10 16:07:57 -0700261 transcoder = VideoTrackTranscoder::create(shared_from_this());
Linus Nilssoncab39d82020-05-14 16:32:21 -0700262
263 AMediaFormat* mergedFormat =
264 mergeMediaFormats(mSourceTrackFormats[trackIndex].get(), trackFormat);
265 if (mergedFormat == nullptr) {
266 LOG(ERROR) << "Unable to merge source and destination formats";
267 return AMEDIA_ERROR_UNKNOWN;
268 }
269
270 format = std::shared_ptr<AMediaFormat>(mergedFormat, &AMediaFormat_delete);
271 }
272
Chong Zhangc8c88cc2020-09-17 12:50:49 -0700273 status = transcoder->configure(mSampleReader, trackIndex, format);
Linus Nilssoncab39d82020-05-14 16:32:21 -0700274 if (status != AMEDIA_OK) {
275 LOG(ERROR) << "Configure track transcoder for track #" << trackIndex << " returned error "
276 << status;
277 return status;
278 }
279
280 mTrackTranscoders.emplace_back(std::move(transcoder));
281 return AMEDIA_OK;
282}
283
Chong Zhang308e91f2020-06-10 15:27:56 -0700284media_status_t MediaTranscoder::configureDestination(int fd) {
285 if (fd < 0) {
286 LOG(ERROR) << "Invalid destination fd: " << fd;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700287 return AMEDIA_ERROR_INVALID_PARAMETER;
Chong Zhang308e91f2020-06-10 15:27:56 -0700288 }
289
290 if (mSampleWriter != nullptr) {
Linus Nilssoncab39d82020-05-14 16:32:21 -0700291 LOG(ERROR) << "Destination is already configured.";
292 return AMEDIA_ERROR_INVALID_OPERATION;
293 }
294
Linus Nilssonc31d2492020-09-23 12:30:00 -0700295 mSampleWriter = MediaSampleWriter::Create();
Linus Nilssone2cdd1f2020-07-07 17:29:26 -0700296 const bool initOk = mSampleWriter->init(fd, shared_from_this());
Linus Nilssoncab39d82020-05-14 16:32:21 -0700297
298 if (!initOk) {
Chong Zhang308e91f2020-06-10 15:27:56 -0700299 LOG(ERROR) << "Unable to initialize sample writer with destination fd: " << fd;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700300 mSampleWriter.reset();
301 return AMEDIA_ERROR_UNKNOWN;
302 }
303
304 return AMEDIA_OK;
305}
306
307media_status_t MediaTranscoder::start() {
308 if (mTrackTranscoders.size() < 1) {
309 LOG(ERROR) << "Unable to start, no tracks are configured.";
310 return AMEDIA_ERROR_INVALID_OPERATION;
311 } else if (mSampleWriter == nullptr) {
312 LOG(ERROR) << "Unable to start, destination is not configured";
313 return AMEDIA_ERROR_INVALID_OPERATION;
314 }
315
Linus Nilssoncab39d82020-05-14 16:32:21 -0700316 // Start transcoders
317 for (auto& transcoder : mTrackTranscoders) {
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700318 bool started = transcoder->start();
Linus Nilssoncab39d82020-05-14 16:32:21 -0700319 if (!started) {
320 LOG(ERROR) << "Unable to start track transcoder.";
Chong Zhang308e91f2020-06-10 15:27:56 -0700321 cancel();
Linus Nilssoncab39d82020-05-14 16:32:21 -0700322 return AMEDIA_ERROR_UNKNOWN;
323 }
324 }
325 return AMEDIA_OK;
326}
327
Chong Zhangb55c5452020-06-26 14:32:12 -0700328media_status_t MediaTranscoder::pause(std::shared_ptr<const Parcel>* pausedState) {
329 // TODO: write internal states to parcel.
330 *pausedState = std::make_shared<Parcel>();
331 return cancel();
Linus Nilssoncab39d82020-05-14 16:32:21 -0700332}
333
334media_status_t MediaTranscoder::resume() {
Chong Zhangb55c5452020-06-26 14:32:12 -0700335 // TODO: restore internal states from parcel.
336 return start();
Linus Nilssoncab39d82020-05-14 16:32:21 -0700337}
338
Chong Zhang308e91f2020-06-10 15:27:56 -0700339media_status_t MediaTranscoder::cancel() {
Linus Nilssoncab39d82020-05-14 16:32:21 -0700340 bool expected = false;
341 if (!mCancelled.compare_exchange_strong(expected, true)) {
342 // Already cancelled.
343 return AMEDIA_OK;
344 }
345
346 mSampleWriter->stop();
Linus Nilsson6233fed2020-08-13 15:15:14 -0700347 mSampleReader->setEnforceSequentialAccess(false);
Linus Nilssoncab39d82020-05-14 16:32:21 -0700348 for (auto& transcoder : mTrackTranscoders) {
349 transcoder->stop();
350 }
351
Linus Nilssoncab39d82020-05-14 16:32:21 -0700352 return AMEDIA_OK;
353}
354
355} // namespace android