blob: 3db74557274a42c6e3743dc693c94e4d18ea0987 [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.
Linus Nilssoncab39d82020-05-14 16:32:21 -070098 std::thread asyncCancelThread{
Chong Zhang308e91f2020-06-10 15:27:56 -070099 [self = shared_from_this()] { self->cancel(); }};
Linus Nilssoncab39d82020-05-14 16:32:21 -0700100 asyncCancelThread.detach();
101 }
102}
103
104void MediaTranscoder::onTrackFinished(const MediaTrackTranscoder* transcoder) {
105 LOG(DEBUG) << "TrackTranscoder " << transcoder << " finished";
106}
107
108void MediaTranscoder::onTrackError(const MediaTrackTranscoder* transcoder, media_status_t status) {
109 LOG(DEBUG) << "TrackTranscoder " << transcoder << " returned error " << status;
110 sendCallback(status);
111}
112
113void MediaTranscoder::onSampleWriterFinished(media_status_t status) {
114 LOG((status != AMEDIA_OK) ? ERROR : DEBUG) << "Sample writer finished with status " << status;
115 sendCallback(status);
116}
117
Chong Zhang308e91f2020-06-10 15:27:56 -0700118MediaTranscoder::MediaTranscoder(const std::shared_ptr<CallbackInterface>& callbacks)
119 : mCallbacks(callbacks) {}
120
Linus Nilssoncab39d82020-05-14 16:32:21 -0700121std::shared_ptr<MediaTranscoder> MediaTranscoder::create(
122 const std::shared_ptr<CallbackInterface>& callbacks,
123 const std::shared_ptr<Parcel>& pausedState) {
124 if (pausedState != nullptr) {
125 LOG(ERROR) << "Initializing from paused state is currently not supported.";
126 return nullptr;
127 } else if (callbacks == nullptr) {
128 LOG(ERROR) << "Callbacks cannot be null";
129 return nullptr;
130 }
131
132 return std::shared_ptr<MediaTranscoder>(new MediaTranscoder(callbacks));
133}
134
Chong Zhang308e91f2020-06-10 15:27:56 -0700135media_status_t MediaTranscoder::configureSource(int fd) {
136 if (fd < 0) {
137 LOG(ERROR) << "Invalid source fd: " << fd;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700138 return AMEDIA_ERROR_INVALID_PARAMETER;
139 }
140
141 const size_t fileSize = lseek(fd, 0, SEEK_END);
142 lseek(fd, 0, SEEK_SET);
143
144 mSampleReader = MediaSampleReaderNDK::createFromFd(fd, 0 /* offset */, fileSize);
Linus Nilssoncab39d82020-05-14 16:32:21 -0700145
146 if (mSampleReader == nullptr) {
Chong Zhang308e91f2020-06-10 15:27:56 -0700147 LOG(ERROR) << "Unable to parse source fd: " << fd;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700148 return AMEDIA_ERROR_UNSUPPORTED;
149 }
150
151 const size_t trackCount = mSampleReader->getTrackCount();
152 for (size_t trackIndex = 0; trackIndex < trackCount; ++trackIndex) {
153 AMediaFormat* trackFormat = mSampleReader->getTrackFormat(static_cast<int>(trackIndex));
154 if (trackFormat == nullptr) {
155 LOG(ERROR) << "Track #" << trackIndex << " has no format";
156 return AMEDIA_ERROR_MALFORMED;
157 }
158
159 mSourceTrackFormats.emplace_back(trackFormat, &AMediaFormat_delete);
160 }
161
162 return AMEDIA_OK;
163}
164
165std::vector<std::shared_ptr<AMediaFormat>> MediaTranscoder::getTrackFormats() const {
166 // Return a deep copy of the formats to avoid the caller modifying our internal formats.
167 std::vector<std::shared_ptr<AMediaFormat>> trackFormats;
168 for (const std::shared_ptr<AMediaFormat>& sourceFormat : mSourceTrackFormats) {
169 AMediaFormat* copy = AMediaFormat_new();
170 AMediaFormat_copy(copy, sourceFormat.get());
171 trackFormats.emplace_back(copy, &AMediaFormat_delete);
172 }
173 return trackFormats;
174}
175
176media_status_t MediaTranscoder::configureTrackFormat(size_t trackIndex, AMediaFormat* trackFormat) {
177 if (mSampleReader == nullptr) {
178 LOG(ERROR) << "Source must be configured before tracks";
179 return AMEDIA_ERROR_INVALID_OPERATION;
180 } else if (trackIndex >= mSourceTrackFormats.size()) {
181 LOG(ERROR) << "Track index " << trackIndex
182 << " is out of bounds. Track count: " << mSourceTrackFormats.size();
183 return AMEDIA_ERROR_INVALID_PARAMETER;
184 }
185
186 std::unique_ptr<MediaTrackTranscoder> transcoder = nullptr;
187 std::shared_ptr<AMediaFormat> format = nullptr;
188
189 if (trackFormat == nullptr) {
190 transcoder = std::make_unique<PassthroughTrackTranscoder>(shared_from_this());
191 } else {
192 const char* srcMime = nullptr;
193 if (!AMediaFormat_getString(mSourceTrackFormats[trackIndex].get(), AMEDIAFORMAT_KEY_MIME,
194 &srcMime)) {
195 LOG(ERROR) << "Source track #" << trackIndex << " has no mime type";
196 return AMEDIA_ERROR_MALFORMED;
197 }
198
199 if (strncmp(srcMime, "video/", 6) != 0) {
200 LOG(ERROR) << "Only video tracks are supported for transcoding. Unable to configure "
201 "track #"
202 << trackIndex << " with mime " << srcMime;
203 return AMEDIA_ERROR_UNSUPPORTED;
204 }
205
206 const char* dstMime = nullptr;
207 if (AMediaFormat_getString(trackFormat, AMEDIAFORMAT_KEY_MIME, &dstMime)) {
208 if (strncmp(dstMime, "video/", 6) != 0) {
209 LOG(ERROR) << "Unable to convert media types for track #" << trackIndex << ", from "
210 << srcMime << " to " << dstMime;
211 return AMEDIA_ERROR_UNSUPPORTED;
212 }
213 }
214
215 transcoder = std::make_unique<VideoTrackTranscoder>(shared_from_this());
216
217 AMediaFormat* mergedFormat =
218 mergeMediaFormats(mSourceTrackFormats[trackIndex].get(), trackFormat);
219 if (mergedFormat == nullptr) {
220 LOG(ERROR) << "Unable to merge source and destination formats";
221 return AMEDIA_ERROR_UNKNOWN;
222 }
223
224 format = std::shared_ptr<AMediaFormat>(mergedFormat, &AMediaFormat_delete);
225 }
226
227 media_status_t status = transcoder->configure(mSampleReader, trackIndex, format);
228 if (status != AMEDIA_OK) {
229 LOG(ERROR) << "Configure track transcoder for track #" << trackIndex << " returned error "
230 << status;
231 return status;
232 }
233
234 mTrackTranscoders.emplace_back(std::move(transcoder));
235 return AMEDIA_OK;
236}
237
Chong Zhang308e91f2020-06-10 15:27:56 -0700238media_status_t MediaTranscoder::configureDestination(int fd) {
239 if (fd < 0) {
240 LOG(ERROR) << "Invalid destination fd: " << fd;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700241 return AMEDIA_ERROR_INVALID_PARAMETER;
Chong Zhang308e91f2020-06-10 15:27:56 -0700242 }
243
244 if (mSampleWriter != nullptr) {
Linus Nilssoncab39d82020-05-14 16:32:21 -0700245 LOG(ERROR) << "Destination is already configured.";
246 return AMEDIA_ERROR_INVALID_OPERATION;
247 }
248
Linus Nilssoncab39d82020-05-14 16:32:21 -0700249 mSampleWriter = std::make_unique<MediaSampleWriter>();
250 const bool initOk = mSampleWriter->init(
251 fd, std::bind(&MediaTranscoder::onSampleWriterFinished, this, std::placeholders::_1));
Linus Nilssoncab39d82020-05-14 16:32:21 -0700252
253 if (!initOk) {
Chong Zhang308e91f2020-06-10 15:27:56 -0700254 LOG(ERROR) << "Unable to initialize sample writer with destination fd: " << fd;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700255 mSampleWriter.reset();
256 return AMEDIA_ERROR_UNKNOWN;
257 }
258
259 return AMEDIA_OK;
260}
261
262media_status_t MediaTranscoder::start() {
263 if (mTrackTranscoders.size() < 1) {
264 LOG(ERROR) << "Unable to start, no tracks are configured.";
265 return AMEDIA_ERROR_INVALID_OPERATION;
266 } else if (mSampleWriter == nullptr) {
267 LOG(ERROR) << "Unable to start, destination is not configured";
268 return AMEDIA_ERROR_INVALID_OPERATION;
269 }
270
271 // Add tracks to the writer.
272 for (auto& transcoder : mTrackTranscoders) {
273 const bool ok = mSampleWriter->addTrack(transcoder->getOutputQueue(),
274 transcoder->getOutputFormat());
275 if (!ok) {
276 LOG(ERROR) << "Unable to add track to sample writer.";
277 return AMEDIA_ERROR_UNKNOWN;
278 }
279 }
280
281 bool started = mSampleWriter->start();
282 if (!started) {
283 LOG(ERROR) << "Unable to start sample writer.";
284 return AMEDIA_ERROR_UNKNOWN;
285 }
286
287 // Start transcoders
288 for (auto& transcoder : mTrackTranscoders) {
289 started = transcoder->start();
290 if (!started) {
291 LOG(ERROR) << "Unable to start track transcoder.";
Chong Zhang308e91f2020-06-10 15:27:56 -0700292 cancel();
Linus Nilssoncab39d82020-05-14 16:32:21 -0700293 return AMEDIA_ERROR_UNKNOWN;
294 }
295 }
296 return AMEDIA_OK;
297}
298
299media_status_t MediaTranscoder::pause(std::shared_ptr<const Parcelable>* pausedState) {
300 (void)pausedState;
301 LOG(ERROR) << "Pause is not currently supported";
302 return AMEDIA_ERROR_UNSUPPORTED;
303}
304
305media_status_t MediaTranscoder::resume() {
306 LOG(ERROR) << "Resume is not currently supported";
307 return AMEDIA_ERROR_UNSUPPORTED;
308}
309
Chong Zhang308e91f2020-06-10 15:27:56 -0700310media_status_t MediaTranscoder::cancel() {
Linus Nilssoncab39d82020-05-14 16:32:21 -0700311 bool expected = false;
312 if (!mCancelled.compare_exchange_strong(expected, true)) {
313 // Already cancelled.
314 return AMEDIA_OK;
315 }
316
317 mSampleWriter->stop();
318 for (auto& transcoder : mTrackTranscoders) {
319 transcoder->stop();
320 }
321
Linus Nilssoncab39d82020-05-14 16:32:21 -0700322 return AMEDIA_OK;
323}
324
325} // namespace android