blob: 53d567eb07ebf19b130b4fd8f1e47b92587ed0f7 [file] [log] [blame]
Linus Nilsson478df7e2020-01-29 15:34:24 -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 "MediaSampleReader"
19
20#include <android-base/logging.h>
21#include <media/MediaSampleReaderNDK.h>
22
23#include <algorithm>
Linus Nilsson800793f2020-07-31 16:16:38 -070024#include <cmath>
Linus Nilsson478df7e2020-01-29 15:34:24 -080025
26namespace android {
27
Linus Nilsson0da327a2020-01-31 16:22:18 -080028// Check that the extractor sample flags have the expected NDK meaning.
29static_assert(SAMPLE_FLAG_SYNC_SAMPLE == AMEDIAEXTRACTOR_SAMPLE_FLAG_SYNC,
30 "Sample flag mismatch: SYNC_SAMPLE");
31
Linus Nilsson478df7e2020-01-29 15:34:24 -080032// static
33std::shared_ptr<MediaSampleReader> MediaSampleReaderNDK::createFromFd(int fd, size_t offset,
34 size_t size) {
35 AMediaExtractor* extractor = AMediaExtractor_new();
36 if (extractor == nullptr) {
37 LOG(ERROR) << "Unable to allocate AMediaExtractor";
38 return nullptr;
39 }
40
41 media_status_t status = AMediaExtractor_setDataSourceFd(extractor, fd, offset, size);
42 if (status != AMEDIA_OK) {
43 LOG(ERROR) << "AMediaExtractor_setDataSourceFd returned error: " << status;
44 AMediaExtractor_delete(extractor);
45 return nullptr;
46 }
47
48 auto sampleReader = std::shared_ptr<MediaSampleReaderNDK>(new MediaSampleReaderNDK(extractor));
Linus Nilsson478df7e2020-01-29 15:34:24 -080049 return sampleReader;
50}
51
52MediaSampleReaderNDK::MediaSampleReaderNDK(AMediaExtractor* extractor)
53 : mExtractor(extractor), mTrackCount(AMediaExtractor_getTrackCount(mExtractor)) {
54 if (mTrackCount > 0) {
55 mTrackCursors.resize(mTrackCount);
Linus Nilsson478df7e2020-01-29 15:34:24 -080056 }
57}
58
Linus Nilsson478df7e2020-01-29 15:34:24 -080059MediaSampleReaderNDK::~MediaSampleReaderNDK() {
60 if (mExtractor != nullptr) {
61 AMediaExtractor_delete(mExtractor);
62 }
63}
64
Linus Nilsson6233fed2020-08-13 15:15:14 -070065void MediaSampleReaderNDK::advanceTrack_l(int trackIndex) {
66 if (!mEnforceSequentialAccess) {
67 // Note: Positioning the extractor before advancing the track is needed for two reasons:
68 // 1. To enable multiple advances without explicitly letting the extractor catch up.
69 // 2. To prevent the extractor from being farther than "next".
70 (void)moveToTrack_l(trackIndex);
71 }
72
73 SampleCursor& cursor = mTrackCursors[trackIndex];
74 cursor.previous = cursor.current;
75 cursor.current = cursor.next;
76 cursor.next.reset();
77
78 if (mEnforceSequentialAccess && trackIndex == mExtractorTrackIndex) {
79 while (advanceExtractor_l()) {
80 SampleCursor& cursor = mTrackCursors[mExtractorTrackIndex];
81 if (cursor.current.isSet && cursor.current.index == mExtractorSampleIndex) {
82 if (mExtractorTrackIndex != trackIndex) {
83 mTrackSignals[mExtractorTrackIndex].notify_all();
84 }
85 break;
86 }
87 }
88 }
89 return;
90}
91
Linus Nilsson478df7e2020-01-29 15:34:24 -080092bool MediaSampleReaderNDK::advanceExtractor_l() {
93 // Reset the "next" sample time whenever the extractor advances past a sample that is current,
94 // to ensure that "next" is appropriately updated when the extractor advances over the next
95 // sample of that track.
96 if (mTrackCursors[mExtractorTrackIndex].current.isSet &&
97 mTrackCursors[mExtractorTrackIndex].current.index == mExtractorSampleIndex) {
98 mTrackCursors[mExtractorTrackIndex].next.reset();
99 }
100
101 if (!AMediaExtractor_advance(mExtractor)) {
Linus Nilsson6233fed2020-08-13 15:15:14 -0700102 mEosReached = true;
103 for (auto it = mTrackSignals.begin(); it != mTrackSignals.end(); ++it) {
104 it->second.notify_all();
105 }
Linus Nilsson478df7e2020-01-29 15:34:24 -0800106 return false;
107 }
108
109 mExtractorTrackIndex = AMediaExtractor_getSampleTrackIndex(mExtractor);
110 mExtractorSampleIndex++;
111
112 SampleCursor& cursor = mTrackCursors[mExtractorTrackIndex];
113 if (mExtractorSampleIndex > cursor.previous.index) {
114 if (!cursor.current.isSet) {
115 cursor.current.set(mExtractorSampleIndex, AMediaExtractor_getSampleTime(mExtractor));
116 } else if (!cursor.next.isSet && mExtractorSampleIndex > cursor.current.index) {
117 cursor.next.set(mExtractorSampleIndex, AMediaExtractor_getSampleTime(mExtractor));
118 }
119 }
Linus Nilsson6233fed2020-08-13 15:15:14 -0700120
Linus Nilsson478df7e2020-01-29 15:34:24 -0800121 return true;
122}
123
124media_status_t MediaSampleReaderNDK::seekExtractorBackwards_l(int64_t targetTimeUs,
125 int targetTrackIndex,
126 uint64_t targetSampleIndex) {
127 if (targetSampleIndex > mExtractorSampleIndex) {
128 LOG(ERROR) << "Error: Forward seek is not supported";
129 return AMEDIA_ERROR_UNSUPPORTED;
130 }
131
132 // AMediaExtractor supports reading negative timestamps but does not support seeking to them.
133 const int64_t seekToTimeUs = std::max(targetTimeUs, (int64_t)0);
134 media_status_t status =
135 AMediaExtractor_seekTo(mExtractor, seekToTimeUs, AMEDIAEXTRACTOR_SEEK_PREVIOUS_SYNC);
136 if (status != AMEDIA_OK) {
137 LOG(ERROR) << "Unable to seek to " << seekToTimeUs << ", target " << targetTimeUs;
138 return status;
139 }
140 mExtractorTrackIndex = AMediaExtractor_getSampleTrackIndex(mExtractor);
141 int64_t sampleTimeUs = AMediaExtractor_getSampleTime(mExtractor);
142
143 while (sampleTimeUs != targetTimeUs || mExtractorTrackIndex != targetTrackIndex) {
144 if (!AMediaExtractor_advance(mExtractor)) {
145 return AMEDIA_ERROR_END_OF_STREAM;
146 }
147 mExtractorTrackIndex = AMediaExtractor_getSampleTrackIndex(mExtractor);
148 sampleTimeUs = AMediaExtractor_getSampleTime(mExtractor);
149 }
150 mExtractorSampleIndex = targetSampleIndex;
151 return AMEDIA_OK;
152}
153
Linus Nilsson6233fed2020-08-13 15:15:14 -0700154media_status_t MediaSampleReaderNDK::moveToSample_l(SamplePosition& pos, int trackIndex) {
155 // Seek backwards if the extractor is ahead of the sample.
156 if (pos.isSet && mExtractorSampleIndex > pos.index) {
157 media_status_t status = seekExtractorBackwards_l(pos.timeStampUs, trackIndex, pos.index);
Linus Nilsson478df7e2020-01-29 15:34:24 -0800158 if (status != AMEDIA_OK) return status;
159 }
160
Linus Nilsson6233fed2020-08-13 15:15:14 -0700161 // Advance until extractor points to the sample.
162 while (!(pos.isSet && pos.index == mExtractorSampleIndex)) {
Linus Nilsson478df7e2020-01-29 15:34:24 -0800163 if (!advanceExtractor_l()) {
164 return AMEDIA_ERROR_END_OF_STREAM;
165 }
166 }
167
168 return AMEDIA_OK;
169}
170
Linus Nilsson6233fed2020-08-13 15:15:14 -0700171media_status_t MediaSampleReaderNDK::moveToTrack_l(int trackIndex) {
172 return moveToSample_l(mTrackCursors[trackIndex].current, trackIndex);
173}
174
175media_status_t MediaSampleReaderNDK::waitForTrack_l(int trackIndex,
176 std::unique_lock<std::mutex>& lockHeld) {
177 while (trackIndex != mExtractorTrackIndex && !mEosReached && mEnforceSequentialAccess) {
178 mTrackSignals[trackIndex].wait(lockHeld);
179 }
180
181 if (mEosReached) {
182 return AMEDIA_ERROR_END_OF_STREAM;
183 }
184 return AMEDIA_OK;
185}
186
187media_status_t MediaSampleReaderNDK::primeExtractorForTrack_l(
188 int trackIndex, std::unique_lock<std::mutex>& lockHeld) {
189 if (mExtractorTrackIndex < 0) {
190 mExtractorTrackIndex = AMediaExtractor_getSampleTrackIndex(mExtractor);
191 if (mExtractorTrackIndex < 0) {
192 return AMEDIA_ERROR_END_OF_STREAM;
193 }
194 mTrackCursors[mExtractorTrackIndex].current.set(mExtractorSampleIndex,
195 AMediaExtractor_getSampleTime(mExtractor));
196 }
197
198 if (mEnforceSequentialAccess) {
199 return waitForTrack_l(trackIndex, lockHeld);
200 } else {
201 return moveToTrack_l(trackIndex);
202 }
203}
204
205media_status_t MediaSampleReaderNDK::selectTrack(int trackIndex) {
Linus Nilsson800793f2020-07-31 16:16:38 -0700206 std::scoped_lock lock(mExtractorMutex);
Linus Nilsson800793f2020-07-31 16:16:38 -0700207
208 if (trackIndex < 0 || trackIndex >= mTrackCount) {
209 LOG(ERROR) << "Invalid trackIndex " << trackIndex << " for trackCount " << mTrackCount;
210 return AMEDIA_ERROR_INVALID_PARAMETER;
Linus Nilsson6233fed2020-08-13 15:15:14 -0700211 } else if (mTrackSignals.find(trackIndex) != mTrackSignals.end()) {
212 LOG(ERROR) << "TrackIndex " << trackIndex << " already selected";
213 return AMEDIA_ERROR_INVALID_PARAMETER;
214 } else if (mExtractorTrackIndex >= 0) {
215 LOG(ERROR) << "Tracks must be selected before sample reading begins.";
216 return AMEDIA_ERROR_UNSUPPORTED;
217 }
218
219 media_status_t status = AMediaExtractor_selectTrack(mExtractor, trackIndex);
220 if (status != AMEDIA_OK) {
221 LOG(ERROR) << "AMediaExtractor_selectTrack returned error: " << status;
222 return status;
223 }
224
225 mTrackSignals.emplace(std::piecewise_construct, std::forward_as_tuple(trackIndex),
226 std::forward_as_tuple());
227 return AMEDIA_OK;
228}
229
230media_status_t MediaSampleReaderNDK::setEnforceSequentialAccess(bool enforce) {
231 std::scoped_lock lock(mExtractorMutex);
232
233 if (mEnforceSequentialAccess && !enforce) {
234 // If switching from enforcing to not enforcing sequential access there may be threads
235 // waiting that needs to be woken up.
236 for (auto it = mTrackSignals.begin(); it != mTrackSignals.end(); ++it) {
237 it->second.notify_all();
238 }
239 } else if (!mEnforceSequentialAccess && enforce && mExtractorTrackIndex >= 0) {
240 // If switching from not enforcing to enforcing sequential access the extractor needs to be
241 // positioned for the track farthest behind so that it won't get stuck waiting.
242 struct {
243 SamplePosition* pos = nullptr;
244 int trackIndex = -1;
245 } earliestSample;
246
247 for (int trackIndex = 0; trackIndex < mTrackCount; ++trackIndex) {
248 SamplePosition& lastKnownTrackPosition = mTrackCursors[trackIndex].current.isSet
249 ? mTrackCursors[trackIndex].current
250 : mTrackCursors[trackIndex].previous;
251
252 if (lastKnownTrackPosition.isSet) {
253 if (earliestSample.pos == nullptr ||
254 earliestSample.pos->index > lastKnownTrackPosition.index) {
255 earliestSample.pos = &lastKnownTrackPosition;
256 earliestSample.trackIndex = trackIndex;
257 }
258 }
259 }
260
261 if (earliestSample.pos == nullptr) {
262 LOG(ERROR) << "No known sample position found";
263 return AMEDIA_ERROR_UNKNOWN;
264 }
265
266 media_status_t status = moveToSample_l(*earliestSample.pos, earliestSample.trackIndex);
267 if (status != AMEDIA_OK) return status;
268
269 while (!(mTrackCursors[mExtractorTrackIndex].current.isSet &&
270 mTrackCursors[mExtractorTrackIndex].current.index == mExtractorSampleIndex)) {
271 if (!advanceExtractor_l()) {
272 return AMEDIA_ERROR_END_OF_STREAM;
273 }
274 }
275 }
276
277 mEnforceSequentialAccess = enforce;
278 return AMEDIA_OK;
279}
280
281media_status_t MediaSampleReaderNDK::getEstimatedBitrateForTrack(int trackIndex, int32_t* bitrate) {
282 std::scoped_lock lock(mExtractorMutex);
283 media_status_t status = AMEDIA_OK;
284
285 if (mTrackSignals.find(trackIndex) == mTrackSignals.end()) {
286 LOG(ERROR) << "Track is not selected.";
287 return AMEDIA_ERROR_INVALID_PARAMETER;
Linus Nilsson800793f2020-07-31 16:16:38 -0700288 } else if (bitrate == nullptr) {
289 LOG(ERROR) << "bitrate pointer is NULL.";
290 return AMEDIA_ERROR_INVALID_PARAMETER;
Linus Nilsson6233fed2020-08-13 15:15:14 -0700291 } else if (mExtractorTrackIndex >= 0) {
292 LOG(ERROR) << "getEstimatedBitrateForTrack must be called before sample reading begins.";
293 return AMEDIA_ERROR_UNSUPPORTED;
Linus Nilsson800793f2020-07-31 16:16:38 -0700294 }
295
296 // Sample the track.
297 static constexpr int64_t kSamplingDurationUs = 10 * 1000 * 1000; // 10 seconds
298 size_t lastSampleSize = 0;
299 size_t totalSampleSize = 0;
300 int64_t firstSampleTimeUs = 0;
301 int64_t lastSampleTimeUs = 0;
302
303 do {
Linus Nilsson6233fed2020-08-13 15:15:14 -0700304 if (AMediaExtractor_getSampleTrackIndex(mExtractor) == trackIndex) {
Linus Nilsson800793f2020-07-31 16:16:38 -0700305 lastSampleTimeUs = AMediaExtractor_getSampleTime(mExtractor);
306 if (totalSampleSize == 0) {
307 firstSampleTimeUs = lastSampleTimeUs;
308 }
309
310 lastSampleSize = AMediaExtractor_getSampleSize(mExtractor);
311 totalSampleSize += lastSampleSize;
312 }
Linus Nilsson6233fed2020-08-13 15:15:14 -0700313 } while ((lastSampleTimeUs - firstSampleTimeUs) < kSamplingDurationUs &&
314 AMediaExtractor_advance(mExtractor));
315
316 // Reset the extractor to the beginning.
317 status = AMediaExtractor_seekTo(mExtractor, 0, AMEDIAEXTRACTOR_SEEK_PREVIOUS_SYNC);
318 if (status != AMEDIA_OK) {
319 LOG(ERROR) << "Unable to reset extractor: " << status;
320 return status;
321 }
Linus Nilsson800793f2020-07-31 16:16:38 -0700322
323 int64_t durationUs = 0;
324 const int64_t sampledDurationUs = lastSampleTimeUs - firstSampleTimeUs;
325
326 if (sampledDurationUs < kSamplingDurationUs) {
327 // Track is shorter than the sampling duration so use the full track duration to get better
328 // accuracy (i.e. don't skip the last sample).
329 AMediaFormat* trackFormat = getTrackFormat(trackIndex);
330 if (!AMediaFormat_getInt64(trackFormat, AMEDIAFORMAT_KEY_DURATION, &durationUs)) {
331 durationUs = 0;
332 }
333 AMediaFormat_delete(trackFormat);
334 }
335
336 if (durationUs == 0) {
337 // The sampled duration does not account for the last sample's duration so its size should
338 // not be included either.
339 totalSampleSize -= lastSampleSize;
340 durationUs = sampledDurationUs;
341 }
342
343 if (totalSampleSize == 0 || durationUs <= 0) {
344 LOG(ERROR) << "Unable to estimate track bitrate";
345 return AMEDIA_ERROR_MALFORMED;
346 }
347
348 *bitrate = roundf((float)totalSampleSize * 8 * 1000000 / durationUs);
349 return AMEDIA_OK;
350}
351
Linus Nilsson478df7e2020-01-29 15:34:24 -0800352media_status_t MediaSampleReaderNDK::getSampleInfoForTrack(int trackIndex, MediaSampleInfo* info) {
Linus Nilsson6233fed2020-08-13 15:15:14 -0700353 std::unique_lock<std::mutex> lock(mExtractorMutex);
Linus Nilsson478df7e2020-01-29 15:34:24 -0800354
Linus Nilsson6233fed2020-08-13 15:15:14 -0700355 if (mTrackSignals.find(trackIndex) == mTrackSignals.end()) {
356 LOG(ERROR) << "Track not selected.";
Linus Nilsson478df7e2020-01-29 15:34:24 -0800357 return AMEDIA_ERROR_INVALID_PARAMETER;
358 } else if (info == nullptr) {
359 LOG(ERROR) << "MediaSampleInfo pointer is NULL.";
360 return AMEDIA_ERROR_INVALID_PARAMETER;
361 }
362
Linus Nilsson6233fed2020-08-13 15:15:14 -0700363 media_status_t status = primeExtractorForTrack_l(trackIndex, lock);
Linus Nilsson478df7e2020-01-29 15:34:24 -0800364 if (status == AMEDIA_OK) {
365 info->presentationTimeUs = AMediaExtractor_getSampleTime(mExtractor);
366 info->flags = AMediaExtractor_getSampleFlags(mExtractor);
367 info->size = AMediaExtractor_getSampleSize(mExtractor);
368 } else if (status == AMEDIA_ERROR_END_OF_STREAM) {
369 info->presentationTimeUs = 0;
370 info->flags = SAMPLE_FLAG_END_OF_STREAM;
371 info->size = 0;
372 }
Linus Nilsson478df7e2020-01-29 15:34:24 -0800373 return status;
374}
375
376media_status_t MediaSampleReaderNDK::readSampleDataForTrack(int trackIndex, uint8_t* buffer,
377 size_t bufferSize) {
Linus Nilsson6233fed2020-08-13 15:15:14 -0700378 std::unique_lock<std::mutex> lock(mExtractorMutex);
Linus Nilsson478df7e2020-01-29 15:34:24 -0800379
Linus Nilsson6233fed2020-08-13 15:15:14 -0700380 if (mTrackSignals.find(trackIndex) == mTrackSignals.end()) {
381 LOG(ERROR) << "Track not selected.";
Linus Nilsson478df7e2020-01-29 15:34:24 -0800382 return AMEDIA_ERROR_INVALID_PARAMETER;
383 } else if (buffer == nullptr) {
384 LOG(ERROR) << "buffer pointer is NULL";
385 return AMEDIA_ERROR_INVALID_PARAMETER;
386 }
387
Linus Nilsson6233fed2020-08-13 15:15:14 -0700388 media_status_t status = primeExtractorForTrack_l(trackIndex, lock);
389 if (status != AMEDIA_OK) {
390 return status;
391 }
Linus Nilsson478df7e2020-01-29 15:34:24 -0800392
393 ssize_t sampleSize = AMediaExtractor_getSampleSize(mExtractor);
394 if (bufferSize < sampleSize) {
395 LOG(ERROR) << "Buffer is too small for sample, " << bufferSize << " vs " << sampleSize;
396 return AMEDIA_ERROR_INVALID_PARAMETER;
397 }
398
399 ssize_t bytesRead = AMediaExtractor_readSampleData(mExtractor, buffer, bufferSize);
400 if (bytesRead < sampleSize) {
401 LOG(ERROR) << "Unable to read full sample, " << bytesRead << " vs " << sampleSize;
402 return AMEDIA_ERROR_INVALID_PARAMETER;
403 }
404
Linus Nilsson6233fed2020-08-13 15:15:14 -0700405 advanceTrack_l(trackIndex);
406
Linus Nilsson478df7e2020-01-29 15:34:24 -0800407 return AMEDIA_OK;
408}
409
Linus Nilsson6233fed2020-08-13 15:15:14 -0700410void MediaSampleReaderNDK::advanceTrack(int trackIndex) {
411 std::scoped_lock lock(mExtractorMutex);
412
413 if (mTrackSignals.find(trackIndex) != mTrackSignals.end()) {
414 advanceTrack_l(trackIndex);
415 } else {
416 LOG(ERROR) << "Trying to advance a track that is not selected (#" << trackIndex << ")";
417 }
418}
419
Linus Nilsson478df7e2020-01-29 15:34:24 -0800420AMediaFormat* MediaSampleReaderNDK::getFileFormat() {
421 return AMediaExtractor_getFileFormat(mExtractor);
422}
423
424size_t MediaSampleReaderNDK::getTrackCount() const {
425 return mTrackCount;
426}
427
428AMediaFormat* MediaSampleReaderNDK::getTrackFormat(int trackIndex) {
429 if (trackIndex < 0 || trackIndex >= mTrackCount) {
430 LOG(ERROR) << "Invalid trackIndex " << trackIndex << " for trackCount " << mTrackCount;
431 return AMediaFormat_new();
432 }
433
434 return AMediaExtractor_getTrackFormat(mExtractor, trackIndex);
435}
436
437} // namespace android