blob: cee37026236ab788894a585baf82a97560a9e1b8 [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>
21#include <fcntl.h>
22#include <media/MediaSampleReaderNDK.h>
Chong Zhang308e91f2020-06-10 15:27:56 -070023#include <media/MediaSampleWriter.h>
Linus Nilssoncab39d82020-05-14 16:32:21 -070024#include <media/MediaTranscoder.h>
25#include <media/PassthroughTrackTranscoder.h>
26#include <media/VideoTrackTranscoder.h>
27#include <unistd.h>
28
29namespace android {
30
31#define DEFINE_FORMAT_VALUE_COPY_FUNC(_type, _typeName) \
32 static void copy##_typeName(const char* key, AMediaFormat* to, AMediaFormat* from) { \
33 _type value; \
34 if (AMediaFormat_get##_typeName(from, key, &value)) { \
35 AMediaFormat_set##_typeName(to, key, value); \
36 } \
37 }
38
39DEFINE_FORMAT_VALUE_COPY_FUNC(const char*, String);
40DEFINE_FORMAT_VALUE_COPY_FUNC(int64_t, Int64);
41DEFINE_FORMAT_VALUE_COPY_FUNC(int32_t, Int32);
42
43static AMediaFormat* mergeMediaFormats(AMediaFormat* base, AMediaFormat* overlay) {
44 if (base == nullptr || overlay == nullptr) {
45 LOG(ERROR) << "Cannot merge null formats";
46 return nullptr;
47 }
48
49 AMediaFormat* format = AMediaFormat_new();
50 if (AMediaFormat_copy(format, base) != AMEDIA_OK) {
51 AMediaFormat_delete(format);
52 return nullptr;
53 }
54
55 // Note: AMediaFormat does not expose a function for appending values from another format or for
56 // iterating over all values and keys in a format. Instead we define a static list of known keys
57 // along with their value types and copy the ones that are present. A better solution would be
58 // to either implement required functions in NDK or to parse the overlay format's string
59 // representation and copy all existing keys.
60 static const struct {
61 const char* key;
62 void (*copyValue)(const char* key, AMediaFormat* to, AMediaFormat* from);
63 } kSupportedConfigs[] = {
64 {AMEDIAFORMAT_KEY_MIME, copyString},
65 {AMEDIAFORMAT_KEY_DURATION, copyInt64},
66 {AMEDIAFORMAT_KEY_WIDTH, copyInt32},
67 {AMEDIAFORMAT_KEY_HEIGHT, copyInt32},
68 {AMEDIAFORMAT_KEY_BIT_RATE, copyInt32},
69 {AMEDIAFORMAT_KEY_PROFILE, copyInt32},
70 {AMEDIAFORMAT_KEY_LEVEL, copyInt32},
71 {AMEDIAFORMAT_KEY_COLOR_FORMAT, copyInt32},
72 {AMEDIAFORMAT_KEY_COLOR_RANGE, copyInt32},
73 {AMEDIAFORMAT_KEY_COLOR_STANDARD, copyInt32},
74 {AMEDIAFORMAT_KEY_COLOR_TRANSFER, copyInt32},
75 {AMEDIAFORMAT_KEY_FRAME_RATE, copyInt32},
76 {AMEDIAFORMAT_KEY_I_FRAME_INTERVAL, copyInt32},
77 };
78
79 for (int i = 0; i < (sizeof(kSupportedConfigs) / sizeof(kSupportedConfigs[0])); ++i) {
80 kSupportedConfigs[i].copyValue(kSupportedConfigs[i].key, format, overlay);
81 }
82
83 return format;
84}
85
86void MediaTranscoder::sendCallback(media_status_t status) {
87 bool expected = false;
88 if (mCallbackSent.compare_exchange_strong(expected, true)) {
89 if (status == AMEDIA_OK) {
90 mCallbacks->onFinished(this);
91 } else {
92 mCallbacks->onError(this, status);
93 }
94
95 // Transcoding is done and the callback to the client has been sent, so tear down the
Chong Zhang308e91f2020-06-10 15:27:56 -070096 // pipeline but do it asynchronously to avoid deadlocks. If an error occurred, client
97 // should clean up the file.
Chong Zhang66469272020-06-04 16:51:55 -070098 std::thread asyncCancelThread{[self = shared_from_this()] { self->cancel(); }};
Linus Nilssoncab39d82020-05-14 16:32:21 -070099 asyncCancelThread.detach();
100 }
101}
102
103void MediaTranscoder::onTrackFinished(const MediaTrackTranscoder* transcoder) {
104 LOG(DEBUG) << "TrackTranscoder " << transcoder << " finished";
105}
106
107void MediaTranscoder::onTrackError(const MediaTrackTranscoder* transcoder, media_status_t status) {
108 LOG(DEBUG) << "TrackTranscoder " << transcoder << " returned error " << status;
109 sendCallback(status);
110}
111
112void MediaTranscoder::onSampleWriterFinished(media_status_t status) {
113 LOG((status != AMEDIA_OK) ? ERROR : DEBUG) << "Sample writer finished with status " << status;
114 sendCallback(status);
115}
116
Chong Zhang308e91f2020-06-10 15:27:56 -0700117MediaTranscoder::MediaTranscoder(const std::shared_ptr<CallbackInterface>& callbacks)
Chong Zhang66469272020-06-04 16:51:55 -0700118 : mCallbacks(callbacks) {}
Chong Zhang308e91f2020-06-10 15:27:56 -0700119
Linus Nilssoncab39d82020-05-14 16:32:21 -0700120std::shared_ptr<MediaTranscoder> MediaTranscoder::create(
121 const std::shared_ptr<CallbackInterface>& callbacks,
122 const std::shared_ptr<Parcel>& pausedState) {
123 if (pausedState != nullptr) {
124 LOG(ERROR) << "Initializing from paused state is currently not supported.";
125 return nullptr;
126 } else if (callbacks == nullptr) {
127 LOG(ERROR) << "Callbacks cannot be null";
128 return nullptr;
129 }
130
131 return std::shared_ptr<MediaTranscoder>(new MediaTranscoder(callbacks));
132}
133
Chong Zhang308e91f2020-06-10 15:27:56 -0700134media_status_t MediaTranscoder::configureSource(int fd) {
135 if (fd < 0) {
136 LOG(ERROR) << "Invalid source fd: " << fd;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700137 return AMEDIA_ERROR_INVALID_PARAMETER;
138 }
139
140 const size_t fileSize = lseek(fd, 0, SEEK_END);
141 lseek(fd, 0, SEEK_SET);
142
143 mSampleReader = MediaSampleReaderNDK::createFromFd(fd, 0 /* offset */, fileSize);
Linus Nilssoncab39d82020-05-14 16:32:21 -0700144
145 if (mSampleReader == nullptr) {
Chong Zhang308e91f2020-06-10 15:27:56 -0700146 LOG(ERROR) << "Unable to parse source fd: " << fd;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700147 return AMEDIA_ERROR_UNSUPPORTED;
148 }
149
150 const size_t trackCount = mSampleReader->getTrackCount();
151 for (size_t trackIndex = 0; trackIndex < trackCount; ++trackIndex) {
152 AMediaFormat* trackFormat = mSampleReader->getTrackFormat(static_cast<int>(trackIndex));
153 if (trackFormat == nullptr) {
154 LOG(ERROR) << "Track #" << trackIndex << " has no format";
155 return AMEDIA_ERROR_MALFORMED;
156 }
157
158 mSourceTrackFormats.emplace_back(trackFormat, &AMediaFormat_delete);
159 }
160
161 return AMEDIA_OK;
162}
163
164std::vector<std::shared_ptr<AMediaFormat>> MediaTranscoder::getTrackFormats() const {
165 // Return a deep copy of the formats to avoid the caller modifying our internal formats.
166 std::vector<std::shared_ptr<AMediaFormat>> trackFormats;
167 for (const std::shared_ptr<AMediaFormat>& sourceFormat : mSourceTrackFormats) {
168 AMediaFormat* copy = AMediaFormat_new();
169 AMediaFormat_copy(copy, sourceFormat.get());
170 trackFormats.emplace_back(copy, &AMediaFormat_delete);
171 }
172 return trackFormats;
173}
174
175media_status_t MediaTranscoder::configureTrackFormat(size_t trackIndex, AMediaFormat* trackFormat) {
176 if (mSampleReader == nullptr) {
177 LOG(ERROR) << "Source must be configured before tracks";
178 return AMEDIA_ERROR_INVALID_OPERATION;
179 } else if (trackIndex >= mSourceTrackFormats.size()) {
180 LOG(ERROR) << "Track index " << trackIndex
181 << " is out of bounds. Track count: " << mSourceTrackFormats.size();
182 return AMEDIA_ERROR_INVALID_PARAMETER;
183 }
184
185 std::unique_ptr<MediaTrackTranscoder> transcoder = nullptr;
186 std::shared_ptr<AMediaFormat> format = nullptr;
187
188 if (trackFormat == nullptr) {
189 transcoder = std::make_unique<PassthroughTrackTranscoder>(shared_from_this());
190 } else {
191 const char* srcMime = nullptr;
192 if (!AMediaFormat_getString(mSourceTrackFormats[trackIndex].get(), AMEDIAFORMAT_KEY_MIME,
193 &srcMime)) {
194 LOG(ERROR) << "Source track #" << trackIndex << " has no mime type";
195 return AMEDIA_ERROR_MALFORMED;
196 }
197
198 if (strncmp(srcMime, "video/", 6) != 0) {
199 LOG(ERROR) << "Only video tracks are supported for transcoding. Unable to configure "
200 "track #"
201 << trackIndex << " with mime " << srcMime;
202 return AMEDIA_ERROR_UNSUPPORTED;
203 }
204
205 const char* dstMime = nullptr;
206 if (AMediaFormat_getString(trackFormat, AMEDIAFORMAT_KEY_MIME, &dstMime)) {
207 if (strncmp(dstMime, "video/", 6) != 0) {
208 LOG(ERROR) << "Unable to convert media types for track #" << trackIndex << ", from "
209 << srcMime << " to " << dstMime;
210 return AMEDIA_ERROR_UNSUPPORTED;
211 }
212 }
213
214 transcoder = std::make_unique<VideoTrackTranscoder>(shared_from_this());
215
216 AMediaFormat* mergedFormat =
217 mergeMediaFormats(mSourceTrackFormats[trackIndex].get(), trackFormat);
218 if (mergedFormat == nullptr) {
219 LOG(ERROR) << "Unable to merge source and destination formats";
220 return AMEDIA_ERROR_UNKNOWN;
221 }
222
223 format = std::shared_ptr<AMediaFormat>(mergedFormat, &AMediaFormat_delete);
224 }
225
226 media_status_t status = transcoder->configure(mSampleReader, trackIndex, format);
227 if (status != AMEDIA_OK) {
228 LOG(ERROR) << "Configure track transcoder for track #" << trackIndex << " returned error "
229 << status;
230 return status;
231 }
232
233 mTrackTranscoders.emplace_back(std::move(transcoder));
234 return AMEDIA_OK;
235}
236
Chong Zhang308e91f2020-06-10 15:27:56 -0700237media_status_t MediaTranscoder::configureDestination(int fd) {
238 if (fd < 0) {
239 LOG(ERROR) << "Invalid destination fd: " << fd;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700240 return AMEDIA_ERROR_INVALID_PARAMETER;
Chong Zhang308e91f2020-06-10 15:27:56 -0700241 }
242
243 if (mSampleWriter != nullptr) {
Linus Nilssoncab39d82020-05-14 16:32:21 -0700244 LOG(ERROR) << "Destination is already configured.";
245 return AMEDIA_ERROR_INVALID_OPERATION;
246 }
247
Linus Nilssoncab39d82020-05-14 16:32:21 -0700248 mSampleWriter = std::make_unique<MediaSampleWriter>();
249 const bool initOk = mSampleWriter->init(
250 fd, std::bind(&MediaTranscoder::onSampleWriterFinished, this, std::placeholders::_1));
Linus Nilssoncab39d82020-05-14 16:32:21 -0700251
252 if (!initOk) {
Chong Zhang308e91f2020-06-10 15:27:56 -0700253 LOG(ERROR) << "Unable to initialize sample writer with destination fd: " << fd;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700254 mSampleWriter.reset();
255 return AMEDIA_ERROR_UNKNOWN;
256 }
257
258 return AMEDIA_OK;
259}
260
261media_status_t MediaTranscoder::start() {
262 if (mTrackTranscoders.size() < 1) {
263 LOG(ERROR) << "Unable to start, no tracks are configured.";
264 return AMEDIA_ERROR_INVALID_OPERATION;
265 } else if (mSampleWriter == nullptr) {
266 LOG(ERROR) << "Unable to start, destination is not configured";
267 return AMEDIA_ERROR_INVALID_OPERATION;
268 }
269
270 // Add tracks to the writer.
271 for (auto& transcoder : mTrackTranscoders) {
272 const bool ok = mSampleWriter->addTrack(transcoder->getOutputQueue(),
273 transcoder->getOutputFormat());
274 if (!ok) {
275 LOG(ERROR) << "Unable to add track to sample writer.";
276 return AMEDIA_ERROR_UNKNOWN;
277 }
278 }
279
280 bool started = mSampleWriter->start();
281 if (!started) {
282 LOG(ERROR) << "Unable to start sample writer.";
283 return AMEDIA_ERROR_UNKNOWN;
284 }
285
286 // Start transcoders
287 for (auto& transcoder : mTrackTranscoders) {
288 started = transcoder->start();
289 if (!started) {
290 LOG(ERROR) << "Unable to start track transcoder.";
Chong Zhang308e91f2020-06-10 15:27:56 -0700291 cancel();
Linus Nilssoncab39d82020-05-14 16:32:21 -0700292 return AMEDIA_ERROR_UNKNOWN;
293 }
294 }
295 return AMEDIA_OK;
296}
297
298media_status_t MediaTranscoder::pause(std::shared_ptr<const Parcelable>* pausedState) {
299 (void)pausedState;
300 LOG(ERROR) << "Pause is not currently supported";
301 return AMEDIA_ERROR_UNSUPPORTED;
302}
303
304media_status_t MediaTranscoder::resume() {
305 LOG(ERROR) << "Resume is not currently supported";
306 return AMEDIA_ERROR_UNSUPPORTED;
307}
308
Chong Zhang308e91f2020-06-10 15:27:56 -0700309media_status_t MediaTranscoder::cancel() {
Linus Nilssoncab39d82020-05-14 16:32:21 -0700310 bool expected = false;
311 if (!mCancelled.compare_exchange_strong(expected, true)) {
312 // Already cancelled.
313 return AMEDIA_OK;
314 }
315
316 mSampleWriter->stop();
317 for (auto& transcoder : mTrackTranscoders) {
318 transcoder->stop();
319 }
320
Linus Nilssoncab39d82020-05-14 16:32:21 -0700321 return AMEDIA_OK;
322}
323
324} // namespace android