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 | e2cdd1f | 2020-07-07 17:29:26 -0700 | [diff] [blame] | 130 | 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 Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 135 | return true; |
| 136 | } |
| 137 | |
| 138 | bool 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 Nilsson | e2cdd1f | 2020-07-07 17:29:26 -0700 | [diff] [blame] | 151 | if (auto callbacks = mCallbacks.lock()) { |
| 152 | callbacks->onFinished(this, status); |
| 153 | } |
Linus Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 154 | }); |
| 155 | mState = STARTED; |
| 156 | return true; |
| 157 | } |
| 158 | |
| 159 | bool 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 | |
| 176 | media_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 | |
| 196 | media_status_t MediaSampleWriter::runWriterLoop() { |
| 197 | AMediaCodecBufferInfo bufferInfo; |
| 198 | uint32_t segmentEndTimeUs = mTrackSegmentLengthUs; |
| 199 | bool samplesLeft = true; |
Linus Nilsson | e2cdd1f | 2020-07-07 17:29:26 -0700 | [diff] [blame] | 200 | 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 Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 212 | |
| 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 Nilsson | 42a971b | 2020-07-01 16:41:11 -0700 | [diff] [blame] | 226 | |
| 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 Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 235 | } |
| 236 | |
Linus Nilsson | e2cdd1f | 2020-07-07 17:29:26 -0700 | [diff] [blame] | 237 | track.mPrevSampleTimeUs = sample->info.presentationTimeUs; |
Linus Nilsson | 42a971b | 2020-07-01 16:41:11 -0700 | [diff] [blame] | 238 | if (!track.mFirstSampleTimeSet) { |
Linus Nilsson | e2cdd1f | 2020-07-07 17:29:26 -0700 | [diff] [blame] | 239 | // Record the first sample's timestamp in order to translate duration to EOS |
| 240 | // time for tracks that does not start at 0. |
Linus Nilsson | 42a971b | 2020-07-01 16:41:11 -0700 | [diff] [blame] | 241 | track.mFirstSampleTimeUs = sample->info.presentationTimeUs; |
| 242 | track.mFirstSampleTimeSet = true; |
| 243 | } |
Linus Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 244 | |
| 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 Nilsson | 42a971b | 2020-07-01 16:41:11 -0700 | [diff] [blame] | 257 | } while (sample->info.presentationTimeUs < segmentEndTimeUs && !track.mReachedEos); |
Linus Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 258 | } |
| 259 | |
Linus Nilsson | e2cdd1f | 2020-07-07 17:29:26 -0700 | [diff] [blame] | 260 | // 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 Nilsson | a85df7f | 2020-02-20 16:32:04 -0800 | [diff] [blame] | 276 | segmentEndTimeUs += mTrackSegmentLengthUs; |
| 277 | } |
| 278 | |
| 279 | return AMEDIA_OK; |
| 280 | } |
Chong Zhang | d6e4aec | 2020-06-22 14:13:07 -0700 | [diff] [blame] | 281 | } // namespace android |