blob: bb0da882712962b6720b74a868111ddd8ac94979 [file] [log] [blame]
Linus Nilssona85df7f2020-02-20 16:32:04 -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 "MediaSampleWriter"
19
20#include <android-base/logging.h>
21#include <media/MediaSampleWriter.h>
22#include <media/NdkMediaMuxer.h>
23
24namespace android {
25
26class DefaultMuxer : public MediaSampleWriterMuxerInterface {
27public:
28 // MediaSampleWriterMuxerInterface
Chong Zhangd6e4aec2020-06-22 14:13:07 -070029 ssize_t addTrack(AMediaFormat* trackFormat) override {
30 // If the track format has rotation, need to call AMediaMuxer_setOrientationHint
31 // to set the rotation. Muxer doesn't take rotation specified on the track.
32 const char* mime;
33 if (AMediaFormat_getString(trackFormat, AMEDIAFORMAT_KEY_MIME, &mime) &&
34 strncmp(mime, "video/", 6) == 0) {
35 int32_t rotation;
36 if (AMediaFormat_getInt32(trackFormat, AMEDIAFORMAT_KEY_ROTATION, &rotation) &&
37 (rotation != 0)) {
38 AMediaMuxer_setOrientationHint(mMuxer, rotation);
39 }
40 }
41
Linus Nilssona85df7f2020-02-20 16:32:04 -080042 return AMediaMuxer_addTrack(mMuxer, trackFormat);
43 }
44 media_status_t start() override { return AMediaMuxer_start(mMuxer); }
45 media_status_t writeSampleData(size_t trackIndex, const uint8_t* data,
46 const AMediaCodecBufferInfo* info) override {
47 return AMediaMuxer_writeSampleData(mMuxer, trackIndex, data, info);
48 }
49 media_status_t stop() override { return AMediaMuxer_stop(mMuxer); }
50 // ~MediaSampleWriterMuxerInterface
51
52 static std::shared_ptr<DefaultMuxer> create(int fd) {
53 AMediaMuxer* ndkMuxer = AMediaMuxer_new(fd, AMEDIAMUXER_OUTPUT_FORMAT_MPEG_4);
54 if (ndkMuxer == nullptr) {
55 LOG(ERROR) << "Unable to create AMediaMuxer";
56 return nullptr;
57 }
58
59 return std::make_shared<DefaultMuxer>(ndkMuxer);
60 }
61
62 ~DefaultMuxer() {
63 if (mMuxer != nullptr) {
64 AMediaMuxer_delete(mMuxer);
65 }
66 }
67
68 DefaultMuxer(AMediaMuxer* muxer) : mMuxer(muxer){};
69 DefaultMuxer() = delete;
70
71private:
72 AMediaMuxer* mMuxer;
73};
74
75MediaSampleWriter::~MediaSampleWriter() {
76 if (mState == STARTED) {
77 stop(); // Join thread.
78 }
79}
80
Linus Nilssone2cdd1f2020-07-07 17:29:26 -070081bool MediaSampleWriter::init(int fd, const std::weak_ptr<CallbackInterface>& callbacks) {
82 return init(DefaultMuxer::create(fd), callbacks);
Linus Nilssona85df7f2020-02-20 16:32:04 -080083}
84
85bool MediaSampleWriter::init(const std::shared_ptr<MediaSampleWriterMuxerInterface>& muxer,
Linus Nilssone2cdd1f2020-07-07 17:29:26 -070086 const std::weak_ptr<CallbackInterface>& callbacks) {
87 if (callbacks.lock() == nullptr) {
88 LOG(ERROR) << "Callback object cannot be null";
Linus Nilssona85df7f2020-02-20 16:32:04 -080089 return false;
90 } else if (muxer == nullptr) {
91 LOG(ERROR) << "Muxer cannot be null";
92 return false;
93 }
94
95 std::scoped_lock lock(mStateMutex);
96 if (mState != UNINITIALIZED) {
97 LOG(ERROR) << "Sample writer is already initialized";
98 return false;
99 }
100
101 mState = INITIALIZED;
102 mMuxer = muxer;
Linus Nilssone2cdd1f2020-07-07 17:29:26 -0700103 mCallbacks = callbacks;
Linus Nilssona85df7f2020-02-20 16:32:04 -0800104 return true;
105}
106
107bool MediaSampleWriter::addTrack(const std::shared_ptr<MediaSampleQueue>& sampleQueue,
108 const std::shared_ptr<AMediaFormat>& trackFormat) {
109 if (sampleQueue == nullptr || trackFormat == nullptr) {
110 LOG(ERROR) << "Sample queue and track format must be non-null";
111 return false;
112 }
113
114 std::scoped_lock lock(mStateMutex);
115 if (mState != INITIALIZED) {
116 LOG(ERROR) << "Muxer needs to be initialized when adding tracks.";
117 return false;
118 }
119 ssize_t trackIndex = mMuxer->addTrack(trackFormat.get());
120 if (trackIndex < 0) {
121 LOG(ERROR) << "Failed to add media track to muxer: " << trackIndex;
122 return false;
123 }
124
Linus Nilsson42a971b2020-07-01 16:41:11 -0700125 int64_t durationUs;
126 if (!AMediaFormat_getInt64(trackFormat.get(), AMEDIAFORMAT_KEY_DURATION, &durationUs)) {
127 durationUs = 0;
128 }
129
Linus Nilssonb09aac22020-07-29 11:56:53 -0700130 mAllTracks.push_back(std::make_unique<TrackRecord>(sampleQueue, static_cast<size_t>(trackIndex),
131 durationUs));
132 mSortedTracks.insert(mAllTracks.back().get());
Linus Nilssona85df7f2020-02-20 16:32:04 -0800133 return true;
134}
135
136bool MediaSampleWriter::start() {
137 std::scoped_lock lock(mStateMutex);
138
Linus Nilssonb09aac22020-07-29 11:56:53 -0700139 if (mAllTracks.size() == 0) {
Linus Nilssona85df7f2020-02-20 16:32:04 -0800140 LOG(ERROR) << "No tracks to write.";
141 return false;
142 } else if (mState != INITIALIZED) {
143 LOG(ERROR) << "Sample writer is not initialized";
144 return false;
145 }
146
147 mThread = std::thread([this] {
148 media_status_t status = writeSamples();
Linus Nilssone2cdd1f2020-07-07 17:29:26 -0700149 if (auto callbacks = mCallbacks.lock()) {
150 callbacks->onFinished(this, status);
151 }
Linus Nilssona85df7f2020-02-20 16:32:04 -0800152 });
153 mState = STARTED;
154 return true;
155}
156
157bool MediaSampleWriter::stop() {
158 std::scoped_lock lock(mStateMutex);
159
160 if (mState != STARTED) {
161 LOG(ERROR) << "Sample writer is not started.";
162 return false;
163 }
164
165 // Stop the sources, and wait for thread to join.
Linus Nilssonb09aac22020-07-29 11:56:53 -0700166 for (auto& track : mAllTracks) {
167 track->mSampleQueue->abort();
Linus Nilssona85df7f2020-02-20 16:32:04 -0800168 }
169 mThread.join();
170 mState = STOPPED;
171 return true;
172}
173
174media_status_t MediaSampleWriter::writeSamples() {
175 media_status_t muxerStatus = mMuxer->start();
176 if (muxerStatus != AMEDIA_OK) {
177 LOG(ERROR) << "Error starting muxer: " << muxerStatus;
178 return muxerStatus;
179 }
180
181 media_status_t writeStatus = runWriterLoop();
182 if (writeStatus != AMEDIA_OK) {
183 LOG(ERROR) << "Error writing samples: " << writeStatus;
184 }
185
186 muxerStatus = mMuxer->stop();
187 if (muxerStatus != AMEDIA_OK) {
188 LOG(ERROR) << "Error stopping muxer: " << muxerStatus;
189 }
190
191 return writeStatus != AMEDIA_OK ? writeStatus : muxerStatus;
192}
193
Linus Nilssonb09aac22020-07-29 11:56:53 -0700194std::multiset<MediaSampleWriter::TrackRecord*>::iterator MediaSampleWriter::getNextOutputTrack() {
195 // Find the first track that has samples ready in its queue AND is not more than
196 // mMaxTrackDivergenceUs ahead of the slowest track. If no such track exists then return the
197 // slowest track and let the writer wait for samples to become ready. Note that mSortedTracks is
198 // sorted by each track's previous sample timestamp in ascending order.
199 auto slowestTrack = mSortedTracks.begin();
200 if (slowestTrack == mSortedTracks.end() || !(*slowestTrack)->mSampleQueue->isEmpty()) {
201 return slowestTrack;
202 }
203
204 const int64_t slowestTimeUs = (*slowestTrack)->mPrevSampleTimeUs;
205 int64_t divergenceUs;
206
207 for (auto it = std::next(slowestTrack); it != mSortedTracks.end(); ++it) {
208 // If the current track has diverged then the rest will have too, so we can stop the search.
209 // If not and it has samples ready then return it, otherwise keep looking.
210 if (__builtin_sub_overflow((*it)->mPrevSampleTimeUs, slowestTimeUs, &divergenceUs) ||
211 divergenceUs >= mMaxTrackDivergenceUs) {
212 break;
213 } else if (!(*it)->mSampleQueue->isEmpty()) {
214 return it;
215 }
216 }
217
218 // No track with pending samples within acceptable time interval was found, so let the writer
219 // wait for the slowest track to produce a new sample.
220 return slowestTrack;
221}
222
Linus Nilssona85df7f2020-02-20 16:32:04 -0800223media_status_t MediaSampleWriter::runWriterLoop() {
224 AMediaCodecBufferInfo bufferInfo;
Linus Nilssone2cdd1f2020-07-07 17:29:26 -0700225 int32_t lastProgressUpdate = 0;
226
227 // Set the "primary" track that will be used to determine progress to the track with longest
228 // duration.
229 int primaryTrackIndex = -1;
230 int64_t longestDurationUs = 0;
Linus Nilssonb09aac22020-07-29 11:56:53 -0700231 for (auto& track : mAllTracks) {
232 if (track->mDurationUs > longestDurationUs) {
233 primaryTrackIndex = track->mTrackIndex;
234 longestDurationUs = track->mDurationUs;
Linus Nilssone2cdd1f2020-07-07 17:29:26 -0700235 }
236 }
Linus Nilssona85df7f2020-02-20 16:32:04 -0800237
Linus Nilssonb09aac22020-07-29 11:56:53 -0700238 while (true) {
239 auto outputTrackIter = getNextOutputTrack();
Linus Nilssona85df7f2020-02-20 16:32:04 -0800240
Linus Nilssonb09aac22020-07-29 11:56:53 -0700241 // Exit if all tracks have reached end of stream.
242 if (outputTrackIter == mSortedTracks.end()) {
243 break;
Linus Nilssona85df7f2020-02-20 16:32:04 -0800244 }
245
Linus Nilssonb09aac22020-07-29 11:56:53 -0700246 // Remove the track from the set, update it, and then reinsert it to keep the set in order.
247 TrackRecord* track = *outputTrackIter;
248 mSortedTracks.erase(outputTrackIter);
Linus Nilssone2cdd1f2020-07-07 17:29:26 -0700249
Linus Nilssonb09aac22020-07-29 11:56:53 -0700250 std::shared_ptr<MediaSample> sample;
251 if (track->mSampleQueue->dequeue(&sample)) {
252 // Track queue was aborted.
253 return AMEDIA_ERROR_UNKNOWN; // TODO(lnilsson): Custom error code.
254 } else if (sample->info.flags & SAMPLE_FLAG_END_OF_STREAM) {
255 // Track reached end of stream.
256 track->mReachedEos = true;
257
258 // Preserve source track duration by setting the appropriate timestamp on the
259 // empty End-Of-Stream sample.
260 if (track->mDurationUs > 0 && track->mFirstSampleTimeSet) {
261 sample->info.presentationTimeUs = track->mDurationUs + track->mFirstSampleTimeUs;
262 }
263 }
264
265 track->mPrevSampleTimeUs = sample->info.presentationTimeUs;
266 if (!track->mFirstSampleTimeSet) {
267 // Record the first sample's timestamp in order to translate duration to EOS
268 // time for tracks that does not start at 0.
269 track->mFirstSampleTimeUs = sample->info.presentationTimeUs;
270 track->mFirstSampleTimeSet = true;
271 }
272
273 bufferInfo.offset = sample->dataOffset;
274 bufferInfo.size = sample->info.size;
275 bufferInfo.flags = sample->info.flags;
276 bufferInfo.presentationTimeUs = sample->info.presentationTimeUs;
277
278 media_status_t status =
279 mMuxer->writeSampleData(track->mTrackIndex, sample->buffer, &bufferInfo);
280 if (status != AMEDIA_OK) {
281 LOG(ERROR) << "writeSampleData returned " << status;
282 return status;
283 }
284 sample.reset();
285
286 // TODO(lnilsson): Add option to toggle progress reporting on/off.
287 if (track->mTrackIndex == primaryTrackIndex) {
288 const int64_t elapsed = track->mPrevSampleTimeUs - track->mFirstSampleTimeUs;
289 int32_t progress = (elapsed * 100) / track->mDurationUs;
Linus Nilssone2cdd1f2020-07-07 17:29:26 -0700290 progress = std::clamp(progress, 0, 100);
291
292 if (progress > lastProgressUpdate) {
293 if (auto callbacks = mCallbacks.lock()) {
294 callbacks->onProgressUpdate(this, progress);
295 }
296 lastProgressUpdate = progress;
297 }
298 }
299
Linus Nilssonb09aac22020-07-29 11:56:53 -0700300 if (!track->mReachedEos) {
301 mSortedTracks.insert(track);
302 }
Linus Nilssona85df7f2020-02-20 16:32:04 -0800303 }
304
305 return AMEDIA_OK;
306}
Chong Zhangd6e4aec2020-06-22 14:13:07 -0700307} // namespace android