blob: 413f0494c0c6a0aec94d9e381fea8cf5e4e82637 [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>
Linus Nilsson16d772b2020-09-29 19:21:11 -070025#include <media/NdkCommon.h>
Linus Nilssoncab39d82020-05-14 16:32:21 -070026#include <media/PassthroughTrackTranscoder.h>
27#include <media/VideoTrackTranscoder.h>
28#include <unistd.h>
29
30namespace android {
31
Linus Nilssona676a9a2021-03-15 18:22:43 -070032static std::shared_ptr<AMediaFormat> createVideoTrackFormat(AMediaFormat* srcFormat,
33 AMediaFormat* options) {
34 if (srcFormat == nullptr || options == nullptr) {
Linus Nilssoncab39d82020-05-14 16:32:21 -070035 LOG(ERROR) << "Cannot merge null formats";
36 return nullptr;
37 }
38
Linus Nilssona676a9a2021-03-15 18:22:43 -070039 // ------- Define parameters to copy from the source track format -------
40 std::vector<AMediaFormatUtils::EntryCopier> srcParamsToCopy{
41 ENTRY_COPIER(AMEDIAFORMAT_KEY_MIME, String),
42 ENTRY_COPIER(AMEDIAFORMAT_KEY_DURATION, Int64),
43 ENTRY_COPIER(AMEDIAFORMAT_KEY_WIDTH, Int32),
44 ENTRY_COPIER(AMEDIAFORMAT_KEY_HEIGHT, Int32),
45 ENTRY_COPIER(AMEDIAFORMAT_KEY_FRAME_RATE, Int32),
46 ENTRY_COPIER(AMEDIAFORMAT_KEY_COLOR_RANGE, Int32),
47 ENTRY_COPIER(AMEDIAFORMAT_KEY_COLOR_STANDARD, Int32),
48 ENTRY_COPIER(AMEDIAFORMAT_KEY_COLOR_TRANSFER, Int32),
49 };
50
51 // If the destination codec is the same as the source codec, we can preserve profile and level
52 // from the source track as default values. Otherwise leave them unspecified.
53 const char *srcMime, *dstMime;
54 AMediaFormat_getString(srcFormat, AMEDIAFORMAT_KEY_MIME, &srcMime);
55 if (!AMediaFormat_getString(options, AMEDIAFORMAT_KEY_MIME, &dstMime) ||
56 strcmp(srcMime, dstMime) == 0) {
57 srcParamsToCopy.push_back(ENTRY_COPIER(AMEDIAFORMAT_KEY_PROFILE, String));
58 srcParamsToCopy.push_back(ENTRY_COPIER(AMEDIAFORMAT_KEY_LEVEL, String));
Linus Nilssoncab39d82020-05-14 16:32:21 -070059 }
60
Linus Nilssona676a9a2021-03-15 18:22:43 -070061 // ------- Define parameters to copy from the caller's options -------
62 static const std::vector<AMediaFormatUtils::EntryCopier> kSupportedOptions{
Linus Nilsson16d772b2020-09-29 19:21:11 -070063 ENTRY_COPIER(AMEDIAFORMAT_KEY_MIME, String),
64 ENTRY_COPIER(AMEDIAFORMAT_KEY_DURATION, Int64),
65 ENTRY_COPIER(AMEDIAFORMAT_KEY_WIDTH, Int32),
66 ENTRY_COPIER(AMEDIAFORMAT_KEY_HEIGHT, Int32),
67 ENTRY_COPIER(AMEDIAFORMAT_KEY_BIT_RATE, Int32),
68 ENTRY_COPIER(AMEDIAFORMAT_KEY_PROFILE, Int32),
69 ENTRY_COPIER(AMEDIAFORMAT_KEY_LEVEL, Int32),
Linus Nilsson16d772b2020-09-29 19:21:11 -070070 ENTRY_COPIER(AMEDIAFORMAT_KEY_COLOR_RANGE, Int32),
71 ENTRY_COPIER(AMEDIAFORMAT_KEY_COLOR_STANDARD, Int32),
72 ENTRY_COPIER(AMEDIAFORMAT_KEY_COLOR_TRANSFER, Int32),
73 ENTRY_COPIER(AMEDIAFORMAT_KEY_FRAME_RATE, Int32),
74 ENTRY_COPIER(AMEDIAFORMAT_KEY_I_FRAME_INTERVAL, Int32),
75 ENTRY_COPIER(AMEDIAFORMAT_KEY_PRIORITY, Int32),
76 ENTRY_COPIER2(AMEDIAFORMAT_KEY_OPERATING_RATE, Float, Int32),
Linus Nilssoncab39d82020-05-14 16:32:21 -070077 };
78
Linus Nilssona676a9a2021-03-15 18:22:43 -070079 // ------- Copy parameters from source and options to the destination -------
80 auto trackFormat = std::shared_ptr<AMediaFormat>(AMediaFormat_new(), &AMediaFormat_delete);
81 AMediaFormatUtils::CopyFormatEntries(srcFormat, trackFormat.get(), srcParamsToCopy);
82 AMediaFormatUtils::CopyFormatEntries(options, trackFormat.get(), kSupportedOptions);
83 return trackFormat;
Linus Nilssoncab39d82020-05-14 16:32:21 -070084}
85
Linus Nilssonfdb3e332020-09-18 17:11:41 -070086void MediaTranscoder::onThreadFinished(const void* thread, media_status_t threadStatus,
87 bool threadStopped) {
88 LOG(DEBUG) << "Thread " << thread << " finished with status " << threadStatus << " stopped "
89 << threadStopped;
90
91 // Stop all threads if one reports an error.
92 if (threadStatus != AMEDIA_OK) {
93 requestStop(false /* stopOnSync */);
94 }
95
96 std::scoped_lock lock{mThreadStateMutex};
97
98 // Record the change.
99 mThreadStates[thread] = DONE;
100 if (threadStatus != AMEDIA_OK && mTranscoderStatus == AMEDIA_OK) {
101 mTranscoderStatus = threadStatus;
102 }
103
104 mTranscoderStopped |= threadStopped;
105
106 // Check if all threads are done. Note that if all transcoders have stopped but the sample
107 // writer has not yet started, it never will.
108 bool transcodersDone = true;
109 ThreadState sampleWriterState = PENDING;
110 for (const auto& it : mThreadStates) {
111 LOG(DEBUG) << " Thread " << it.first << " state" << it.second;
112 if (it.first == static_cast<const void*>(mSampleWriter.get())) {
113 sampleWriterState = it.second;
114 } else {
115 transcodersDone &= (it.second == DONE);
116 }
117 }
118 if (!transcodersDone || sampleWriterState == RUNNING) {
Chong Zhangb55c5452020-06-26 14:32:12 -0700119 return;
120 }
121
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700122 // All done. Send callback asynchronously and wake up threads waiting in cancel/pause.
123 mThreadsDone = true;
124 if (!mCallbackSent) {
125 std::thread asyncNotificationThread{[this, self = shared_from_this(),
126 status = mTranscoderStatus,
127 stopped = mTranscoderStopped] {
128 // If the transcoder was stopped that means a caller is waiting in stop or pause
129 // in which case we don't send a callback.
130 if (status != AMEDIA_OK) {
131 mCallbacks->onError(this, status);
132 } else if (!stopped) {
133 mCallbacks->onFinished(this);
134 }
135 mThreadsDoneSignal.notify_all();
136 }};
137 asyncNotificationThread.detach();
138 mCallbackSent = true;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700139 }
140}
141
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700142void MediaTranscoder::onTrackFormatAvailable(const MediaTrackTranscoder* transcoder) {
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700143 LOG(DEBUG) << "TrackTranscoder " << transcoder << " format available.";
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700144
145 std::scoped_lock lock{mTracksAddedMutex};
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700146 const void* sampleWriterPtr = static_cast<const void*>(mSampleWriter.get());
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700147
148 // Ignore duplicate format change.
149 if (mTracksAdded.count(transcoder) > 0) {
150 return;
151 }
152
153 // Add track to the writer.
Linus Nilssonc31d2492020-09-23 12:30:00 -0700154 auto consumer = mSampleWriter->addTrack(transcoder->getOutputFormat());
155 if (consumer == nullptr) {
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700156 LOG(ERROR) << "Unable to add track to sample writer.";
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700157 onThreadFinished(sampleWriterPtr, AMEDIA_ERROR_UNKNOWN, false /* stopped */);
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700158 return;
159 }
160
Linus Nilssonc31d2492020-09-23 12:30:00 -0700161 MediaTrackTranscoder* mutableTranscoder = const_cast<MediaTrackTranscoder*>(transcoder);
162 mutableTranscoder->setSampleConsumer(consumer);
163
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700164 mTracksAdded.insert(transcoder);
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700165 bool errorStarting = false;
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700166 if (mTracksAdded.size() == mTrackTranscoders.size()) {
Linus Nilsson6233fed2020-08-13 15:15:14 -0700167 // Enable sequential access mode on the sample reader to achieve optimal read performance.
168 // This has to wait until all tracks have delivered their output formats and the sample
169 // writer is started. Otherwise the tracks will not get their output sample queues drained
170 // and the transcoder could hang due to one track running out of buffers and blocking the
171 // other tracks from reading source samples before they could output their formats.
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700172
173 std::scoped_lock lock{mThreadStateMutex};
174 // Don't start the sample writer if a stop already has been requested.
175 if (!mSampleWriterStopped) {
176 if (!mCancelled) {
177 mSampleReader->setEnforceSequentialAccess(true);
178 }
179 LOG(DEBUG) << "Starting sample writer.";
180 errorStarting = !mSampleWriter->start();
181 if (!errorStarting) {
182 mThreadStates[sampleWriterPtr] = RUNNING;
183 }
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700184 }
185 }
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700186
187 if (errorStarting) {
188 LOG(ERROR) << "Unable to start sample writer.";
189 onThreadFinished(sampleWriterPtr, AMEDIA_ERROR_UNKNOWN, false /* stopped */);
190 }
Chong Zhanga2cc86b2020-06-17 16:56:49 -0700191}
192
Linus Nilssoncab39d82020-05-14 16:32:21 -0700193void MediaTranscoder::onTrackFinished(const MediaTrackTranscoder* transcoder) {
194 LOG(DEBUG) << "TrackTranscoder " << transcoder << " finished";
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700195 onThreadFinished(static_cast<const void*>(transcoder), AMEDIA_OK, false /* stopped */);
196}
197
198void MediaTranscoder::onTrackStopped(const MediaTrackTranscoder* transcoder) {
199 LOG(DEBUG) << "TrackTranscoder " << transcoder << " stopped";
200 onThreadFinished(static_cast<const void*>(transcoder), AMEDIA_OK, true /* stopped */);
Linus Nilssoncab39d82020-05-14 16:32:21 -0700201}
202
203void MediaTranscoder::onTrackError(const MediaTrackTranscoder* transcoder, media_status_t status) {
Linus Nilsson93cf9132020-09-24 12:12:48 -0700204 LOG(ERROR) << "TrackTranscoder " << transcoder << " returned error " << status;
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700205 onThreadFinished(static_cast<const void*>(transcoder), status, false /* stopped */);
Linus Nilssoncab39d82020-05-14 16:32:21 -0700206}
207
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700208void MediaTranscoder::onFinished(const MediaSampleWriter* writer, media_status_t status) {
209 LOG(status == AMEDIA_OK ? DEBUG : ERROR) << "Sample writer finished with status " << status;
210 onThreadFinished(static_cast<const void*>(writer), status, false /* stopped */);
211}
212
213void MediaTranscoder::onStopped(const MediaSampleWriter* writer) {
214 LOG(DEBUG) << "Sample writer " << writer << " stopped";
215 onThreadFinished(static_cast<const void*>(writer), AMEDIA_OK, true /* stopped */);
Linus Nilssoncab39d82020-05-14 16:32:21 -0700216}
217
Linus Nilssone2cdd1f2020-07-07 17:29:26 -0700218void MediaTranscoder::onProgressUpdate(const MediaSampleWriter* writer __unused, int32_t progress) {
219 // Dispatch progress updated to the client.
220 mCallbacks->onProgressUpdate(this, progress);
221}
222
Chong Zhang457c6892021-02-01 15:34:20 -0800223void MediaTranscoder::onHeartBeat(const MediaSampleWriter* writer __unused) {
224 // Signal heart-beat to the client.
225 mCallbacks->onHeartBeat(this);
226}
227
228MediaTranscoder::MediaTranscoder(const std::shared_ptr<CallbackInterface>& callbacks,
229 int64_t heartBeatIntervalUs, pid_t pid, uid_t uid)
230 : mCallbacks(callbacks), mHeartBeatIntervalUs(heartBeatIntervalUs), mPid(pid), mUid(uid) {}
Chong Zhang308e91f2020-06-10 15:27:56 -0700231
Linus Nilssoncab39d82020-05-14 16:32:21 -0700232std::shared_ptr<MediaTranscoder> MediaTranscoder::create(
Chong Zhang457c6892021-02-01 15:34:20 -0800233 const std::shared_ptr<CallbackInterface>& callbacks, int64_t heartBeatIntervalUs, pid_t pid,
234 uid_t uid, const std::shared_ptr<ndk::ScopedAParcel>& pausedState) {
Linus Nilssoncab39d82020-05-14 16:32:21 -0700235 if (pausedState != nullptr) {
Chong Zhangb55c5452020-06-26 14:32:12 -0700236 LOG(INFO) << "Initializing from paused state.";
237 }
238 if (callbacks == nullptr) {
Linus Nilssoncab39d82020-05-14 16:32:21 -0700239 LOG(ERROR) << "Callbacks cannot be null";
240 return nullptr;
241 }
242
Chong Zhang457c6892021-02-01 15:34:20 -0800243 return std::shared_ptr<MediaTranscoder>(
244 new MediaTranscoder(callbacks, heartBeatIntervalUs, pid, uid));
Linus Nilssoncab39d82020-05-14 16:32:21 -0700245}
246
Chong Zhang308e91f2020-06-10 15:27:56 -0700247media_status_t MediaTranscoder::configureSource(int fd) {
248 if (fd < 0) {
249 LOG(ERROR) << "Invalid source fd: " << fd;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700250 return AMEDIA_ERROR_INVALID_PARAMETER;
251 }
252
253 const size_t fileSize = lseek(fd, 0, SEEK_END);
254 lseek(fd, 0, SEEK_SET);
255
256 mSampleReader = MediaSampleReaderNDK::createFromFd(fd, 0 /* offset */, fileSize);
Linus Nilssoncab39d82020-05-14 16:32:21 -0700257 if (mSampleReader == nullptr) {
Chong Zhang308e91f2020-06-10 15:27:56 -0700258 LOG(ERROR) << "Unable to parse source fd: " << fd;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700259 return AMEDIA_ERROR_UNSUPPORTED;
260 }
261
262 const size_t trackCount = mSampleReader->getTrackCount();
263 for (size_t trackIndex = 0; trackIndex < trackCount; ++trackIndex) {
264 AMediaFormat* trackFormat = mSampleReader->getTrackFormat(static_cast<int>(trackIndex));
265 if (trackFormat == nullptr) {
266 LOG(ERROR) << "Track #" << trackIndex << " has no format";
267 return AMEDIA_ERROR_MALFORMED;
268 }
269
270 mSourceTrackFormats.emplace_back(trackFormat, &AMediaFormat_delete);
271 }
272
273 return AMEDIA_OK;
274}
275
276std::vector<std::shared_ptr<AMediaFormat>> MediaTranscoder::getTrackFormats() const {
277 // Return a deep copy of the formats to avoid the caller modifying our internal formats.
278 std::vector<std::shared_ptr<AMediaFormat>> trackFormats;
279 for (const std::shared_ptr<AMediaFormat>& sourceFormat : mSourceTrackFormats) {
280 AMediaFormat* copy = AMediaFormat_new();
281 AMediaFormat_copy(copy, sourceFormat.get());
282 trackFormats.emplace_back(copy, &AMediaFormat_delete);
283 }
284 return trackFormats;
285}
286
Linus Nilssona676a9a2021-03-15 18:22:43 -0700287media_status_t MediaTranscoder::configureTrackFormat(size_t trackIndex,
288 AMediaFormat* destinationOptions) {
Linus Nilssoncab39d82020-05-14 16:32:21 -0700289 if (mSampleReader == nullptr) {
290 LOG(ERROR) << "Source must be configured before tracks";
291 return AMEDIA_ERROR_INVALID_OPERATION;
292 } else if (trackIndex >= mSourceTrackFormats.size()) {
293 LOG(ERROR) << "Track index " << trackIndex
294 << " is out of bounds. Track count: " << mSourceTrackFormats.size();
295 return AMEDIA_ERROR_INVALID_PARAMETER;
296 }
297
Linus Nilssone4716f22020-07-10 16:07:57 -0700298 std::shared_ptr<MediaTrackTranscoder> transcoder;
Linus Nilssona676a9a2021-03-15 18:22:43 -0700299 std::shared_ptr<AMediaFormat> trackFormat;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700300
Linus Nilssona676a9a2021-03-15 18:22:43 -0700301 if (destinationOptions == nullptr) {
Linus Nilssone4716f22020-07-10 16:07:57 -0700302 transcoder = std::make_shared<PassthroughTrackTranscoder>(shared_from_this());
Linus Nilssoncab39d82020-05-14 16:32:21 -0700303 } else {
Linus Nilssona676a9a2021-03-15 18:22:43 -0700304 AMediaFormat* srcTrackFormat = mSourceTrackFormats[trackIndex].get();
305
Linus Nilssoncab39d82020-05-14 16:32:21 -0700306 const char* srcMime = nullptr;
Linus Nilssona676a9a2021-03-15 18:22:43 -0700307 if (!AMediaFormat_getString(srcTrackFormat, AMEDIAFORMAT_KEY_MIME, &srcMime)) {
Linus Nilssoncab39d82020-05-14 16:32:21 -0700308 LOG(ERROR) << "Source track #" << trackIndex << " has no mime type";
309 return AMEDIA_ERROR_MALFORMED;
310 }
311
312 if (strncmp(srcMime, "video/", 6) != 0) {
313 LOG(ERROR) << "Only video tracks are supported for transcoding. Unable to configure "
314 "track #"
315 << trackIndex << " with mime " << srcMime;
316 return AMEDIA_ERROR_UNSUPPORTED;
317 }
318
319 const char* dstMime = nullptr;
Linus Nilssona676a9a2021-03-15 18:22:43 -0700320 if (AMediaFormat_getString(destinationOptions, AMEDIAFORMAT_KEY_MIME, &dstMime)) {
Linus Nilssoncab39d82020-05-14 16:32:21 -0700321 if (strncmp(dstMime, "video/", 6) != 0) {
322 LOG(ERROR) << "Unable to convert media types for track #" << trackIndex << ", from "
323 << srcMime << " to " << dstMime;
324 return AMEDIA_ERROR_UNSUPPORTED;
325 }
326 }
327
Chong Zhangbbb4eac2020-11-18 11:12:06 -0800328 transcoder = VideoTrackTranscoder::create(shared_from_this(), mPid, mUid);
Linus Nilssoncab39d82020-05-14 16:32:21 -0700329
Linus Nilssona676a9a2021-03-15 18:22:43 -0700330 trackFormat = createVideoTrackFormat(srcTrackFormat, destinationOptions);
331 if (trackFormat == nullptr) {
332 LOG(ERROR) << "Unable to create video track format";
Linus Nilssoncab39d82020-05-14 16:32:21 -0700333 return AMEDIA_ERROR_UNKNOWN;
334 }
Linus Nilssoncab39d82020-05-14 16:32:21 -0700335 }
336
Linus Nilssonaf4a3212020-12-15 08:18:25 -0800337 media_status_t status = mSampleReader->selectTrack(trackIndex);
338 if (status != AMEDIA_OK) {
339 LOG(ERROR) << "Unable to select track " << trackIndex;
340 return status;
341 }
342
Linus Nilssona676a9a2021-03-15 18:22:43 -0700343 status = transcoder->configure(mSampleReader, trackIndex, trackFormat);
Linus Nilssoncab39d82020-05-14 16:32:21 -0700344 if (status != AMEDIA_OK) {
345 LOG(ERROR) << "Configure track transcoder for track #" << trackIndex << " returned error "
346 << status;
Linus Nilssonaf4a3212020-12-15 08:18:25 -0800347 mSampleReader->unselectTrack(trackIndex);
Linus Nilssoncab39d82020-05-14 16:32:21 -0700348 return status;
349 }
350
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700351 std::scoped_lock lock{mThreadStateMutex};
352 mThreadStates[static_cast<const void*>(transcoder.get())] = PENDING;
353
Linus Nilssoncab39d82020-05-14 16:32:21 -0700354 mTrackTranscoders.emplace_back(std::move(transcoder));
355 return AMEDIA_OK;
356}
357
Chong Zhang308e91f2020-06-10 15:27:56 -0700358media_status_t MediaTranscoder::configureDestination(int fd) {
359 if (fd < 0) {
360 LOG(ERROR) << "Invalid destination fd: " << fd;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700361 return AMEDIA_ERROR_INVALID_PARAMETER;
Chong Zhang308e91f2020-06-10 15:27:56 -0700362 }
363
364 if (mSampleWriter != nullptr) {
Linus Nilssoncab39d82020-05-14 16:32:21 -0700365 LOG(ERROR) << "Destination is already configured.";
366 return AMEDIA_ERROR_INVALID_OPERATION;
367 }
368
Linus Nilssonc31d2492020-09-23 12:30:00 -0700369 mSampleWriter = MediaSampleWriter::Create();
Chong Zhang457c6892021-02-01 15:34:20 -0800370 const bool initOk = mSampleWriter->init(fd, shared_from_this(), mHeartBeatIntervalUs);
Linus Nilssoncab39d82020-05-14 16:32:21 -0700371
372 if (!initOk) {
Chong Zhang308e91f2020-06-10 15:27:56 -0700373 LOG(ERROR) << "Unable to initialize sample writer with destination fd: " << fd;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700374 mSampleWriter.reset();
375 return AMEDIA_ERROR_UNKNOWN;
376 }
377
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700378 std::scoped_lock lock{mThreadStateMutex};
379 mThreadStates[static_cast<const void*>(mSampleWriter.get())] = PENDING;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700380 return AMEDIA_OK;
381}
382
383media_status_t MediaTranscoder::start() {
384 if (mTrackTranscoders.size() < 1) {
385 LOG(ERROR) << "Unable to start, no tracks are configured.";
386 return AMEDIA_ERROR_INVALID_OPERATION;
387 } else if (mSampleWriter == nullptr) {
388 LOG(ERROR) << "Unable to start, destination is not configured";
389 return AMEDIA_ERROR_INVALID_OPERATION;
390 }
391
Linus Nilssoncab39d82020-05-14 16:32:21 -0700392 // Start transcoders
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700393 bool started = true;
394 {
395 std::scoped_lock lock{mThreadStateMutex};
396 for (auto& transcoder : mTrackTranscoders) {
397 if (!(started = transcoder->start())) {
398 break;
399 }
400 mThreadStates[static_cast<const void*>(transcoder.get())] = RUNNING;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700401 }
402 }
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700403 if (!started) {
404 LOG(ERROR) << "Unable to start track transcoder.";
405 cancel();
406 return AMEDIA_ERROR_UNKNOWN;
407 }
Linus Nilssoncab39d82020-05-14 16:32:21 -0700408 return AMEDIA_OK;
409}
410
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700411media_status_t MediaTranscoder::requestStop(bool stopOnSync) {
412 std::scoped_lock lock{mThreadStateMutex};
413 if (mCancelled) {
414 LOG(DEBUG) << "MediaTranscoder already cancelled";
415 return AMEDIA_ERROR_UNSUPPORTED;
416 }
417
418 if (!stopOnSync) {
419 mSampleWriterStopped = true;
420 mSampleWriter->stop();
421 }
422
423 mSampleReader->setEnforceSequentialAccess(false);
424 for (auto& transcoder : mTrackTranscoders) {
425 transcoder->stop(stopOnSync);
426 }
427
428 mCancelled = true;
429 return AMEDIA_OK;
430}
431
432void MediaTranscoder::waitForThreads() NO_THREAD_SAFETY_ANALYSIS {
433 std::unique_lock lock{mThreadStateMutex};
434 while (!mThreadsDone) {
435 mThreadsDoneSignal.wait(lock);
436 }
437}
438
Chong Zhange4e088f2020-10-21 19:10:42 -0700439media_status_t MediaTranscoder::pause(std::shared_ptr<ndk::ScopedAParcel>* pausedState) {
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700440 media_status_t status = requestStop(true /* stopOnSync */);
441 if (status != AMEDIA_OK) {
442 return status;
443 }
444
445 waitForThreads();
446
Chong Zhangb55c5452020-06-26 14:32:12 -0700447 // TODO: write internal states to parcel.
Chong Zhange4e088f2020-10-21 19:10:42 -0700448 *pausedState = std::shared_ptr<::ndk::ScopedAParcel>(new ::ndk::ScopedAParcel());
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700449 return AMEDIA_OK;
450}
451
452media_status_t MediaTranscoder::cancel() {
453 media_status_t status = requestStop(false /* stopOnSync */);
454 if (status != AMEDIA_OK) {
455 return status;
456 }
457
458 waitForThreads();
459
460 // TODO: Release transcoders?
461 return AMEDIA_OK;
Linus Nilssoncab39d82020-05-14 16:32:21 -0700462}
463
464media_status_t MediaTranscoder::resume() {
Chong Zhangb55c5452020-06-26 14:32:12 -0700465 // TODO: restore internal states from parcel.
466 return start();
Linus Nilssoncab39d82020-05-14 16:32:21 -0700467}
468
Linus Nilssoncab39d82020-05-14 16:32:21 -0700469} // namespace android