Linus Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 1 | /* |
| 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 | |
| 24 | namespace android { |
| 25 | |
| 26 | class DefaultMuxer : public MediaSampleWriterMuxerInterface { |
| 27 | public: |
| 28 | // MediaSampleWriterMuxerInterface |
Chong Zhang | d6e4aec | 2020-06-22 14:13:07 -0700 | [diff] [blame] | 29 | 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 Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 42 | 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 | |
| 71 | private: |
| 72 | AMediaMuxer* mMuxer; |
| 73 | }; |
| 74 | |
| 75 | MediaSampleWriter::~MediaSampleWriter() { |
| 76 | if (mState == STARTED) { |
| 77 | stop(); // Join thread. |
| 78 | } |
| 79 | } |
| 80 | |
Linus Nilsson | e2cdd1f | 2020-07-07 17:29:26 -0700 | [diff] [blame] | 81 | bool MediaSampleWriter::init(int fd, const std::weak_ptr<CallbackInterface>& callbacks) { |
| 82 | return init(DefaultMuxer::create(fd), callbacks); |
Linus Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 83 | } |
| 84 | |
| 85 | bool MediaSampleWriter::init(const std::shared_ptr<MediaSampleWriterMuxerInterface>& muxer, |
Linus Nilsson | e2cdd1f | 2020-07-07 17:29:26 -0700 | [diff] [blame] | 86 | const std::weak_ptr<CallbackInterface>& callbacks) { |
| 87 | if (callbacks.lock() == nullptr) { |
| 88 | LOG(ERROR) << "Callback object cannot be null"; |
Linus Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 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; |
Linus Nilsson | e2cdd1f | 2020-07-07 17:29:26 -0700 | [diff] [blame] | 103 | mCallbacks = callbacks; |
Linus Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 104 | return true; |
| 105 | } |
| 106 | |
| 107 | bool 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 Nilsson | 42a971b | 2020-07-01 16:41:11 -0700 | [diff] [blame] | 125 | int64_t durationUs; |
| 126 | if (!AMediaFormat_getInt64(trackFormat.get(), AMEDIAFORMAT_KEY_DURATION, &durationUs)) { |
| 127 | durationUs = 0; |
| 128 | } |
| 129 | |
Linus Nilsson | b09aac2 | 2020-07-29 11:56:53 -0700 | [diff] [blame] | 130 | mAllTracks.push_back(std::make_unique<TrackRecord>(sampleQueue, static_cast<size_t>(trackIndex), |
| 131 | durationUs)); |
| 132 | mSortedTracks.insert(mAllTracks.back().get()); |
Linus Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 133 | return true; |
| 134 | } |
| 135 | |
| 136 | bool MediaSampleWriter::start() { |
| 137 | std::scoped_lock lock(mStateMutex); |
| 138 | |
Linus Nilsson | b09aac2 | 2020-07-29 11:56:53 -0700 | [diff] [blame] | 139 | if (mAllTracks.size() == 0) { |
Linus Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 140 | 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 Nilsson | e2cdd1f | 2020-07-07 17:29:26 -0700 | [diff] [blame] | 149 | if (auto callbacks = mCallbacks.lock()) { |
| 150 | callbacks->onFinished(this, status); |
| 151 | } |
Linus Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 152 | }); |
| 153 | mState = STARTED; |
| 154 | return true; |
| 155 | } |
| 156 | |
| 157 | bool 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 Nilsson | b09aac2 | 2020-07-29 11:56:53 -0700 | [diff] [blame] | 166 | for (auto& track : mAllTracks) { |
| 167 | track->mSampleQueue->abort(); |
Linus Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 168 | } |
| 169 | mThread.join(); |
| 170 | mState = STOPPED; |
| 171 | return true; |
| 172 | } |
| 173 | |
| 174 | media_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 Nilsson | b09aac2 | 2020-07-29 11:56:53 -0700 | [diff] [blame] | 194 | std::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 Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 223 | media_status_t MediaSampleWriter::runWriterLoop() { |
| 224 | AMediaCodecBufferInfo bufferInfo; |
Linus Nilsson | e2cdd1f | 2020-07-07 17:29:26 -0700 | [diff] [blame] | 225 | 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 Nilsson | b09aac2 | 2020-07-29 11:56:53 -0700 | [diff] [blame] | 231 | for (auto& track : mAllTracks) { |
| 232 | if (track->mDurationUs > longestDurationUs) { |
| 233 | primaryTrackIndex = track->mTrackIndex; |
| 234 | longestDurationUs = track->mDurationUs; |
Linus Nilsson | e2cdd1f | 2020-07-07 17:29:26 -0700 | [diff] [blame] | 235 | } |
| 236 | } |
Linus Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 237 | |
Linus Nilsson | b09aac2 | 2020-07-29 11:56:53 -0700 | [diff] [blame] | 238 | while (true) { |
| 239 | auto outputTrackIter = getNextOutputTrack(); |
Linus Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 240 | |
Linus Nilsson | b09aac2 | 2020-07-29 11:56:53 -0700 | [diff] [blame] | 241 | // Exit if all tracks have reached end of stream. |
| 242 | if (outputTrackIter == mSortedTracks.end()) { |
| 243 | break; |
Linus Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 244 | } |
| 245 | |
Linus Nilsson | b09aac2 | 2020-07-29 11:56:53 -0700 | [diff] [blame] | 246 | // 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 Nilsson | e2cdd1f | 2020-07-07 17:29:26 -0700 | [diff] [blame] | 249 | |
Linus Nilsson | b09aac2 | 2020-07-29 11:56:53 -0700 | [diff] [blame] | 250 | 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 Nilsson | e2cdd1f | 2020-07-07 17:29:26 -0700 | [diff] [blame] | 290 | 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 Nilsson | b09aac2 | 2020-07-29 11:56:53 -0700 | [diff] [blame] | 300 | if (!track->mReachedEos) { |
| 301 | mSortedTracks.insert(track); |
| 302 | } |
Linus Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 303 | } |
| 304 | |
| 305 | return AMEDIA_OK; |
| 306 | } |
Chong Zhang | d6e4aec | 2020-06-22 14:13:07 -0700 | [diff] [blame] | 307 | } // namespace android |