blob: aaa2adbb131b4688d1644579f66f4b5d7419c396 [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
29 ssize_t addTrack(const AMediaFormat* trackFormat) override {
30 return AMediaMuxer_addTrack(mMuxer, trackFormat);
31 }
32 media_status_t start() override { return AMediaMuxer_start(mMuxer); }
33 media_status_t writeSampleData(size_t trackIndex, const uint8_t* data,
34 const AMediaCodecBufferInfo* info) override {
35 return AMediaMuxer_writeSampleData(mMuxer, trackIndex, data, info);
36 }
37 media_status_t stop() override { return AMediaMuxer_stop(mMuxer); }
38 // ~MediaSampleWriterMuxerInterface
39
40 static std::shared_ptr<DefaultMuxer> create(int fd) {
41 AMediaMuxer* ndkMuxer = AMediaMuxer_new(fd, AMEDIAMUXER_OUTPUT_FORMAT_MPEG_4);
42 if (ndkMuxer == nullptr) {
43 LOG(ERROR) << "Unable to create AMediaMuxer";
44 return nullptr;
45 }
46
47 return std::make_shared<DefaultMuxer>(ndkMuxer);
48 }
49
50 ~DefaultMuxer() {
51 if (mMuxer != nullptr) {
52 AMediaMuxer_delete(mMuxer);
53 }
54 }
55
56 DefaultMuxer(AMediaMuxer* muxer) : mMuxer(muxer){};
57 DefaultMuxer() = delete;
58
59private:
60 AMediaMuxer* mMuxer;
61};
62
63MediaSampleWriter::~MediaSampleWriter() {
64 if (mState == STARTED) {
65 stop(); // Join thread.
66 }
67}
68
69bool MediaSampleWriter::init(int fd, const OnWritingFinishedCallback& callback) {
70 return init(DefaultMuxer::create(fd), callback);
71}
72
73bool MediaSampleWriter::init(const std::shared_ptr<MediaSampleWriterMuxerInterface>& muxer,
74 const OnWritingFinishedCallback& callback) {
75 if (callback == nullptr) {
76 LOG(ERROR) << "Callback cannot be null";
77 return false;
78 } else if (muxer == nullptr) {
79 LOG(ERROR) << "Muxer cannot be null";
80 return false;
81 }
82
83 std::scoped_lock lock(mStateMutex);
84 if (mState != UNINITIALIZED) {
85 LOG(ERROR) << "Sample writer is already initialized";
86 return false;
87 }
88
89 mState = INITIALIZED;
90 mMuxer = muxer;
91 mWritingFinishedCallback = callback;
92 return true;
93}
94
95bool MediaSampleWriter::addTrack(const std::shared_ptr<MediaSampleQueue>& sampleQueue,
96 const std::shared_ptr<AMediaFormat>& trackFormat) {
97 if (sampleQueue == nullptr || trackFormat == nullptr) {
98 LOG(ERROR) << "Sample queue and track format must be non-null";
99 return false;
100 }
101
102 std::scoped_lock lock(mStateMutex);
103 if (mState != INITIALIZED) {
104 LOG(ERROR) << "Muxer needs to be initialized when adding tracks.";
105 return false;
106 }
107 ssize_t trackIndex = mMuxer->addTrack(trackFormat.get());
108 if (trackIndex < 0) {
109 LOG(ERROR) << "Failed to add media track to muxer: " << trackIndex;
110 return false;
111 }
112
113 mTracks.emplace_back(sampleQueue, static_cast<size_t>(trackIndex));
114 return true;
115}
116
117bool MediaSampleWriter::start() {
118 std::scoped_lock lock(mStateMutex);
119
120 if (mTracks.size() == 0) {
121 LOG(ERROR) << "No tracks to write.";
122 return false;
123 } else if (mState != INITIALIZED) {
124 LOG(ERROR) << "Sample writer is not initialized";
125 return false;
126 }
127
128 mThread = std::thread([this] {
129 media_status_t status = writeSamples();
130 mWritingFinishedCallback(status);
131 });
132 mState = STARTED;
133 return true;
134}
135
136bool MediaSampleWriter::stop() {
137 std::scoped_lock lock(mStateMutex);
138
139 if (mState != STARTED) {
140 LOG(ERROR) << "Sample writer is not started.";
141 return false;
142 }
143
144 // Stop the sources, and wait for thread to join.
145 for (auto& track : mTracks) {
146 track.mSampleQueue->abort();
147 }
148 mThread.join();
149 mState = STOPPED;
150 return true;
151}
152
153media_status_t MediaSampleWriter::writeSamples() {
154 media_status_t muxerStatus = mMuxer->start();
155 if (muxerStatus != AMEDIA_OK) {
156 LOG(ERROR) << "Error starting muxer: " << muxerStatus;
157 return muxerStatus;
158 }
159
160 media_status_t writeStatus = runWriterLoop();
161 if (writeStatus != AMEDIA_OK) {
162 LOG(ERROR) << "Error writing samples: " << writeStatus;
163 }
164
165 muxerStatus = mMuxer->stop();
166 if (muxerStatus != AMEDIA_OK) {
167 LOG(ERROR) << "Error stopping muxer: " << muxerStatus;
168 }
169
170 return writeStatus != AMEDIA_OK ? writeStatus : muxerStatus;
171}
172
173media_status_t MediaSampleWriter::runWriterLoop() {
174 AMediaCodecBufferInfo bufferInfo;
175 uint32_t segmentEndTimeUs = mTrackSegmentLengthUs;
176 bool samplesLeft = true;
177
178 while (samplesLeft) {
179 samplesLeft = false;
180 for (auto& track : mTracks) {
181 if (track.mReachedEos) continue;
182
183 std::shared_ptr<MediaSample> sample;
184 do {
185 if (track.mSampleQueue->dequeue(&sample)) {
186 // Track queue was aborted.
187 return AMEDIA_ERROR_UNKNOWN; // TODO(lnilsson): Custom error code.
188 } else if (sample->info.flags & SAMPLE_FLAG_END_OF_STREAM) {
189 // Track reached end of stream.
190 track.mReachedEos = true;
191 break;
192 }
193
194 samplesLeft = true;
195
196 bufferInfo.offset = sample->dataOffset;
197 bufferInfo.size = sample->info.size;
198 bufferInfo.flags = sample->info.flags;
199 bufferInfo.presentationTimeUs = sample->info.presentationTimeUs;
200
201 media_status_t status =
202 mMuxer->writeSampleData(track.mTrackIndex, sample->buffer, &bufferInfo);
203 if (status != AMEDIA_OK) {
204 LOG(ERROR) << "writeSampleData returned " << status;
205 return status;
206 }
207
208 } while (sample->info.presentationTimeUs < segmentEndTimeUs);
209 }
210
211 segmentEndTimeUs += mTrackSegmentLengthUs;
212 }
213
214 return AMEDIA_OK;
215}
216} // namespace android