blob: 0fdb0b76e81e2e92c0cabeeeacd3418a97868b90 [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
125 mTracks.emplace_back(sampleQueue, static_cast<size_t>(trackIndex));
126 return true;
127}
128
129bool MediaSampleWriter::start() {
130 std::scoped_lock lock(mStateMutex);
131
132 if (mTracks.size() == 0) {
133 LOG(ERROR) << "No tracks to write.";
134 return false;
135 } else if (mState != INITIALIZED) {
136 LOG(ERROR) << "Sample writer is not initialized";
137 return false;
138 }
139
140 mThread = std::thread([this] {
141 media_status_t status = writeSamples();
142 mWritingFinishedCallback(status);
143 });
144 mState = STARTED;
145 return true;
146}
147
148bool MediaSampleWriter::stop() {
149 std::scoped_lock lock(mStateMutex);
150
151 if (mState != STARTED) {
152 LOG(ERROR) << "Sample writer is not started.";
153 return false;
154 }
155
156 // Stop the sources, and wait for thread to join.
157 for (auto& track : mTracks) {
158 track.mSampleQueue->abort();
159 }
160 mThread.join();
161 mState = STOPPED;
162 return true;
163}
164
165media_status_t MediaSampleWriter::writeSamples() {
166 media_status_t muxerStatus = mMuxer->start();
167 if (muxerStatus != AMEDIA_OK) {
168 LOG(ERROR) << "Error starting muxer: " << muxerStatus;
169 return muxerStatus;
170 }
171
172 media_status_t writeStatus = runWriterLoop();
173 if (writeStatus != AMEDIA_OK) {
174 LOG(ERROR) << "Error writing samples: " << writeStatus;
175 }
176
177 muxerStatus = mMuxer->stop();
178 if (muxerStatus != AMEDIA_OK) {
179 LOG(ERROR) << "Error stopping muxer: " << muxerStatus;
180 }
181
182 return writeStatus != AMEDIA_OK ? writeStatus : muxerStatus;
183}
184
185media_status_t MediaSampleWriter::runWriterLoop() {
186 AMediaCodecBufferInfo bufferInfo;
187 uint32_t segmentEndTimeUs = mTrackSegmentLengthUs;
188 bool samplesLeft = true;
189
190 while (samplesLeft) {
191 samplesLeft = false;
192 for (auto& track : mTracks) {
193 if (track.mReachedEos) continue;
194
195 std::shared_ptr<MediaSample> sample;
196 do {
197 if (track.mSampleQueue->dequeue(&sample)) {
198 // Track queue was aborted.
199 return AMEDIA_ERROR_UNKNOWN; // TODO(lnilsson): Custom error code.
200 } else if (sample->info.flags & SAMPLE_FLAG_END_OF_STREAM) {
201 // Track reached end of stream.
202 track.mReachedEos = true;
203 break;
204 }
205
206 samplesLeft = true;
207
208 bufferInfo.offset = sample->dataOffset;
209 bufferInfo.size = sample->info.size;
210 bufferInfo.flags = sample->info.flags;
211 bufferInfo.presentationTimeUs = sample->info.presentationTimeUs;
212
213 media_status_t status =
214 mMuxer->writeSampleData(track.mTrackIndex, sample->buffer, &bufferInfo);
215 if (status != AMEDIA_OK) {
216 LOG(ERROR) << "writeSampleData returned " << status;
217 return status;
218 }
219
220 } while (sample->info.presentationTimeUs < segmentEndTimeUs);
221 }
222
223 segmentEndTimeUs += mTrackSegmentLengthUs;
224 }
225
226 return AMEDIA_OK;
227}
Chong Zhangd6e4aec2020-06-22 14:13:07 -0700228} // namespace android