blob: 3676d73640ced54522203b41235bf19773b153e4 [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 Nilssone2cdd1f2020-07-07 17:29:26 -0700130 const char* mime = nullptr;
131 const bool isVideo = AMediaFormat_getString(trackFormat.get(), AMEDIAFORMAT_KEY_MIME, &mime) &&
132 (strncmp(mime, "video/", 6) == 0);
133
134 mTracks.emplace_back(sampleQueue, static_cast<size_t>(trackIndex), durationUs, isVideo);
Linus Nilssona85df7f2020-02-20 16:32:04 -0800135 return true;
136}
137
138bool MediaSampleWriter::start() {
139 std::scoped_lock lock(mStateMutex);
140
141 if (mTracks.size() == 0) {
142 LOG(ERROR) << "No tracks to write.";
143 return false;
144 } else if (mState != INITIALIZED) {
145 LOG(ERROR) << "Sample writer is not initialized";
146 return false;
147 }
148
149 mThread = std::thread([this] {
150 media_status_t status = writeSamples();
Linus Nilssone2cdd1f2020-07-07 17:29:26 -0700151 if (auto callbacks = mCallbacks.lock()) {
152 callbacks->onFinished(this, status);
153 }
Linus Nilssona85df7f2020-02-20 16:32:04 -0800154 });
155 mState = STARTED;
156 return true;
157}
158
159bool MediaSampleWriter::stop() {
160 std::scoped_lock lock(mStateMutex);
161
162 if (mState != STARTED) {
163 LOG(ERROR) << "Sample writer is not started.";
164 return false;
165 }
166
167 // Stop the sources, and wait for thread to join.
168 for (auto& track : mTracks) {
169 track.mSampleQueue->abort();
170 }
171 mThread.join();
172 mState = STOPPED;
173 return true;
174}
175
176media_status_t MediaSampleWriter::writeSamples() {
177 media_status_t muxerStatus = mMuxer->start();
178 if (muxerStatus != AMEDIA_OK) {
179 LOG(ERROR) << "Error starting muxer: " << muxerStatus;
180 return muxerStatus;
181 }
182
183 media_status_t writeStatus = runWriterLoop();
184 if (writeStatus != AMEDIA_OK) {
185 LOG(ERROR) << "Error writing samples: " << writeStatus;
186 }
187
188 muxerStatus = mMuxer->stop();
189 if (muxerStatus != AMEDIA_OK) {
190 LOG(ERROR) << "Error stopping muxer: " << muxerStatus;
191 }
192
193 return writeStatus != AMEDIA_OK ? writeStatus : muxerStatus;
194}
195
196media_status_t MediaSampleWriter::runWriterLoop() {
197 AMediaCodecBufferInfo bufferInfo;
198 uint32_t segmentEndTimeUs = mTrackSegmentLengthUs;
199 bool samplesLeft = true;
Linus Nilssone2cdd1f2020-07-07 17:29:26 -0700200 int32_t lastProgressUpdate = 0;
201
202 // Set the "primary" track that will be used to determine progress to the track with longest
203 // duration.
204 int primaryTrackIndex = -1;
205 int64_t longestDurationUs = 0;
206 for (int trackIndex = 0; trackIndex < mTracks.size(); ++trackIndex) {
207 if (mTracks[trackIndex].mDurationUs > longestDurationUs) {
208 primaryTrackIndex = trackIndex;
209 longestDurationUs = mTracks[trackIndex].mDurationUs;
210 }
211 }
Linus Nilssona85df7f2020-02-20 16:32:04 -0800212
213 while (samplesLeft) {
214 samplesLeft = false;
215 for (auto& track : mTracks) {
216 if (track.mReachedEos) continue;
217
218 std::shared_ptr<MediaSample> sample;
219 do {
220 if (track.mSampleQueue->dequeue(&sample)) {
221 // Track queue was aborted.
222 return AMEDIA_ERROR_UNKNOWN; // TODO(lnilsson): Custom error code.
223 } else if (sample->info.flags & SAMPLE_FLAG_END_OF_STREAM) {
224 // Track reached end of stream.
225 track.mReachedEos = true;
Linus Nilsson42a971b2020-07-01 16:41:11 -0700226
227 // Preserve source track duration by setting the appropriate timestamp on the
228 // empty End-Of-Stream sample.
229 if (track.mDurationUs > 0 && track.mFirstSampleTimeSet) {
230 sample->info.presentationTimeUs =
231 track.mDurationUs + track.mFirstSampleTimeUs;
232 }
233 } else {
234 samplesLeft = true;
Linus Nilssona85df7f2020-02-20 16:32:04 -0800235 }
236
Linus Nilssone2cdd1f2020-07-07 17:29:26 -0700237 track.mPrevSampleTimeUs = sample->info.presentationTimeUs;
Linus Nilsson42a971b2020-07-01 16:41:11 -0700238 if (!track.mFirstSampleTimeSet) {
Linus Nilssone2cdd1f2020-07-07 17:29:26 -0700239 // Record the first sample's timestamp in order to translate duration to EOS
240 // time for tracks that does not start at 0.
Linus Nilsson42a971b2020-07-01 16:41:11 -0700241 track.mFirstSampleTimeUs = sample->info.presentationTimeUs;
242 track.mFirstSampleTimeSet = true;
243 }
Linus Nilssona85df7f2020-02-20 16:32:04 -0800244
245 bufferInfo.offset = sample->dataOffset;
246 bufferInfo.size = sample->info.size;
247 bufferInfo.flags = sample->info.flags;
248 bufferInfo.presentationTimeUs = sample->info.presentationTimeUs;
249
250 media_status_t status =
251 mMuxer->writeSampleData(track.mTrackIndex, sample->buffer, &bufferInfo);
252 if (status != AMEDIA_OK) {
253 LOG(ERROR) << "writeSampleData returned " << status;
254 return status;
255 }
256
Linus Nilsson42a971b2020-07-01 16:41:11 -0700257 } while (sample->info.presentationTimeUs < segmentEndTimeUs && !track.mReachedEos);
Linus Nilssona85df7f2020-02-20 16:32:04 -0800258 }
259
Linus Nilssone2cdd1f2020-07-07 17:29:26 -0700260 // TODO(lnilsson): Add option to toggle progress reporting on/off.
261 if (primaryTrackIndex >= 0) {
262 const TrackRecord& track = mTracks[primaryTrackIndex];
263
264 const int64_t elapsed = track.mPrevSampleTimeUs - track.mFirstSampleTimeUs;
265 int32_t progress = (elapsed * 100) / track.mDurationUs;
266 progress = std::clamp(progress, 0, 100);
267
268 if (progress > lastProgressUpdate) {
269 if (auto callbacks = mCallbacks.lock()) {
270 callbacks->onProgressUpdate(this, progress);
271 }
272 lastProgressUpdate = progress;
273 }
274 }
275
Linus Nilssona85df7f2020-02-20 16:32:04 -0800276 segmentEndTimeUs += mTrackSegmentLengthUs;
277 }
278
279 return AMEDIA_OK;
280}
Chong Zhangd6e4aec2020-06-22 14:13:07 -0700281} // namespace android