blob: 91dbf782e6bd53707544644f6e8876c6f5d2e6dc [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
81bool MediaSampleWriter::init(int fd, const OnWritingFinishedCallback& callback) {
82 return init(DefaultMuxer::create(fd), callback);
83}
84
85bool MediaSampleWriter::init(const std::shared_ptr<MediaSampleWriterMuxerInterface>& muxer,
86 const OnWritingFinishedCallback& callback) {
87 if (callback == nullptr) {
88 LOG(ERROR) << "Callback cannot be null";
89 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;
103 mWritingFinishedCallback = callback;
104 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
130 mTracks.emplace_back(sampleQueue, static_cast<size_t>(trackIndex), durationUs);
Linus Nilssona85df7f2020-02-20 16:32:04 -0800131 return true;
132}
133
134bool MediaSampleWriter::start() {
135 std::scoped_lock lock(mStateMutex);
136
137 if (mTracks.size() == 0) {
138 LOG(ERROR) << "No tracks to write.";
139 return false;
140 } else if (mState != INITIALIZED) {
141 LOG(ERROR) << "Sample writer is not initialized";
142 return false;
143 }
144
145 mThread = std::thread([this] {
146 media_status_t status = writeSamples();
147 mWritingFinishedCallback(status);
148 });
149 mState = STARTED;
150 return true;
151}
152
153bool MediaSampleWriter::stop() {
154 std::scoped_lock lock(mStateMutex);
155
156 if (mState != STARTED) {
157 LOG(ERROR) << "Sample writer is not started.";
158 return false;
159 }
160
161 // Stop the sources, and wait for thread to join.
162 for (auto& track : mTracks) {
163 track.mSampleQueue->abort();
164 }
165 mThread.join();
166 mState = STOPPED;
167 return true;
168}
169
170media_status_t MediaSampleWriter::writeSamples() {
171 media_status_t muxerStatus = mMuxer->start();
172 if (muxerStatus != AMEDIA_OK) {
173 LOG(ERROR) << "Error starting muxer: " << muxerStatus;
174 return muxerStatus;
175 }
176
177 media_status_t writeStatus = runWriterLoop();
178 if (writeStatus != AMEDIA_OK) {
179 LOG(ERROR) << "Error writing samples: " << writeStatus;
180 }
181
182 muxerStatus = mMuxer->stop();
183 if (muxerStatus != AMEDIA_OK) {
184 LOG(ERROR) << "Error stopping muxer: " << muxerStatus;
185 }
186
187 return writeStatus != AMEDIA_OK ? writeStatus : muxerStatus;
188}
189
190media_status_t MediaSampleWriter::runWriterLoop() {
191 AMediaCodecBufferInfo bufferInfo;
192 uint32_t segmentEndTimeUs = mTrackSegmentLengthUs;
193 bool samplesLeft = true;
194
195 while (samplesLeft) {
196 samplesLeft = false;
197 for (auto& track : mTracks) {
198 if (track.mReachedEos) continue;
199
200 std::shared_ptr<MediaSample> sample;
201 do {
202 if (track.mSampleQueue->dequeue(&sample)) {
203 // Track queue was aborted.
204 return AMEDIA_ERROR_UNKNOWN; // TODO(lnilsson): Custom error code.
205 } else if (sample->info.flags & SAMPLE_FLAG_END_OF_STREAM) {
206 // Track reached end of stream.
207 track.mReachedEos = true;
Linus Nilsson42a971b2020-07-01 16:41:11 -0700208
209 // Preserve source track duration by setting the appropriate timestamp on the
210 // empty End-Of-Stream sample.
211 if (track.mDurationUs > 0 && track.mFirstSampleTimeSet) {
212 sample->info.presentationTimeUs =
213 track.mDurationUs + track.mFirstSampleTimeUs;
214 }
215 } else {
216 samplesLeft = true;
Linus Nilssona85df7f2020-02-20 16:32:04 -0800217 }
218
Linus Nilsson42a971b2020-07-01 16:41:11 -0700219 // Record the first sample's timestamp in order to translate duration to EOS time
220 // for tracks that does not start at 0.
221 if (!track.mFirstSampleTimeSet) {
222 track.mFirstSampleTimeUs = sample->info.presentationTimeUs;
223 track.mFirstSampleTimeSet = true;
224 }
Linus Nilssona85df7f2020-02-20 16:32:04 -0800225
226 bufferInfo.offset = sample->dataOffset;
227 bufferInfo.size = sample->info.size;
228 bufferInfo.flags = sample->info.flags;
229 bufferInfo.presentationTimeUs = sample->info.presentationTimeUs;
230
231 media_status_t status =
232 mMuxer->writeSampleData(track.mTrackIndex, sample->buffer, &bufferInfo);
233 if (status != AMEDIA_OK) {
234 LOG(ERROR) << "writeSampleData returned " << status;
235 return status;
236 }
237
Linus Nilsson42a971b2020-07-01 16:41:11 -0700238 } while (sample->info.presentationTimeUs < segmentEndTimeUs && !track.mReachedEos);
Linus Nilssona85df7f2020-02-20 16:32:04 -0800239 }
240
241 segmentEndTimeUs += mTrackSegmentLengthUs;
242 }
243
244 return AMEDIA_OK;
245}
Chong Zhangd6e4aec2020-06-22 14:13:07 -0700246} // namespace android