blob: d2f6c405566cd33ea10f83b83fb86765de2ce7b9 [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 }
Linus Nilssonfdb3e332020-09-18 17:11:41 -0700184
185 if (!mEnforceSequentialAccess) {
186 return moveToTrack_l(trackIndex);
187 }
188
Linus Nilsson6233fed2020-08-13 15:15:14 -0700189 return AMEDIA_OK;
190}
191
192media_status_t MediaSampleReaderNDK::primeExtractorForTrack_l(
193 int trackIndex, std::unique_lock<std::mutex>& lockHeld) {
194 if (mExtractorTrackIndex < 0) {
195 mExtractorTrackIndex = AMediaExtractor_getSampleTrackIndex(mExtractor);
196 if (mExtractorTrackIndex < 0) {
197 return AMEDIA_ERROR_END_OF_STREAM;
198 }
199 mTrackCursors[mExtractorTrackIndex].current.set(mExtractorSampleIndex,
200 AMediaExtractor_getSampleTime(mExtractor));
201 }
202
203 if (mEnforceSequentialAccess) {
204 return waitForTrack_l(trackIndex, lockHeld);
205 } else {
206 return moveToTrack_l(trackIndex);
207 }
208}
209
210media_status_t MediaSampleReaderNDK::selectTrack(int trackIndex) {
Linus Nilsson800793f2020-07-31 16:16:38 -0700211 std::scoped_lock lock(mExtractorMutex);
Linus Nilsson800793f2020-07-31 16:16:38 -0700212
213 if (trackIndex < 0 || trackIndex >= mTrackCount) {
214 LOG(ERROR) << "Invalid trackIndex " << trackIndex << " for trackCount " << mTrackCount;
215 return AMEDIA_ERROR_INVALID_PARAMETER;
Linus Nilsson6233fed2020-08-13 15:15:14 -0700216 } else if (mTrackSignals.find(trackIndex) != mTrackSignals.end()) {
217 LOG(ERROR) << "TrackIndex " << trackIndex << " already selected";
218 return AMEDIA_ERROR_INVALID_PARAMETER;
219 } else if (mExtractorTrackIndex >= 0) {
220 LOG(ERROR) << "Tracks must be selected before sample reading begins.";
221 return AMEDIA_ERROR_UNSUPPORTED;
222 }
223
224 media_status_t status = AMediaExtractor_selectTrack(mExtractor, trackIndex);
225 if (status != AMEDIA_OK) {
226 LOG(ERROR) << "AMediaExtractor_selectTrack returned error: " << status;
227 return status;
228 }
229
230 mTrackSignals.emplace(std::piecewise_construct, std::forward_as_tuple(trackIndex),
231 std::forward_as_tuple());
232 return AMEDIA_OK;
233}
234
235media_status_t MediaSampleReaderNDK::setEnforceSequentialAccess(bool enforce) {
236 std::scoped_lock lock(mExtractorMutex);
237
238 if (mEnforceSequentialAccess && !enforce) {
239 // If switching from enforcing to not enforcing sequential access there may be threads
240 // waiting that needs to be woken up.
241 for (auto it = mTrackSignals.begin(); it != mTrackSignals.end(); ++it) {
242 it->second.notify_all();
243 }
244 } else if (!mEnforceSequentialAccess && enforce && mExtractorTrackIndex >= 0) {
245 // If switching from not enforcing to enforcing sequential access the extractor needs to be
246 // positioned for the track farthest behind so that it won't get stuck waiting.
247 struct {
248 SamplePosition* pos = nullptr;
249 int trackIndex = -1;
250 } earliestSample;
251
252 for (int trackIndex = 0; trackIndex < mTrackCount; ++trackIndex) {
253 SamplePosition& lastKnownTrackPosition = mTrackCursors[trackIndex].current.isSet
254 ? mTrackCursors[trackIndex].current
255 : mTrackCursors[trackIndex].previous;
256
257 if (lastKnownTrackPosition.isSet) {
258 if (earliestSample.pos == nullptr ||
259 earliestSample.pos->index > lastKnownTrackPosition.index) {
260 earliestSample.pos = &lastKnownTrackPosition;
261 earliestSample.trackIndex = trackIndex;
262 }
263 }
264 }
265
266 if (earliestSample.pos == nullptr) {
267 LOG(ERROR) << "No known sample position found";
268 return AMEDIA_ERROR_UNKNOWN;
269 }
270
271 media_status_t status = moveToSample_l(*earliestSample.pos, earliestSample.trackIndex);
272 if (status != AMEDIA_OK) return status;
273
274 while (!(mTrackCursors[mExtractorTrackIndex].current.isSet &&
275 mTrackCursors[mExtractorTrackIndex].current.index == mExtractorSampleIndex)) {
276 if (!advanceExtractor_l()) {
277 return AMEDIA_ERROR_END_OF_STREAM;
278 }
279 }
280 }
281
282 mEnforceSequentialAccess = enforce;
283 return AMEDIA_OK;
284}
285
286media_status_t MediaSampleReaderNDK::getEstimatedBitrateForTrack(int trackIndex, int32_t* bitrate) {
287 std::scoped_lock lock(mExtractorMutex);
288 media_status_t status = AMEDIA_OK;
289
290 if (mTrackSignals.find(trackIndex) == mTrackSignals.end()) {
291 LOG(ERROR) << "Track is not selected.";
292 return AMEDIA_ERROR_INVALID_PARAMETER;
Linus Nilsson800793f2020-07-31 16:16:38 -0700293 } else if (bitrate == nullptr) {
294 LOG(ERROR) << "bitrate pointer is NULL.";
295 return AMEDIA_ERROR_INVALID_PARAMETER;
Linus Nilsson6233fed2020-08-13 15:15:14 -0700296 } else if (mExtractorTrackIndex >= 0) {
297 LOG(ERROR) << "getEstimatedBitrateForTrack must be called before sample reading begins.";
298 return AMEDIA_ERROR_UNSUPPORTED;
Linus Nilsson800793f2020-07-31 16:16:38 -0700299 }
300
301 // Sample the track.
302 static constexpr int64_t kSamplingDurationUs = 10 * 1000 * 1000; // 10 seconds
303 size_t lastSampleSize = 0;
304 size_t totalSampleSize = 0;
305 int64_t firstSampleTimeUs = 0;
306 int64_t lastSampleTimeUs = 0;
307
308 do {
Linus Nilsson6233fed2020-08-13 15:15:14 -0700309 if (AMediaExtractor_getSampleTrackIndex(mExtractor) == trackIndex) {
Linus Nilsson800793f2020-07-31 16:16:38 -0700310 lastSampleTimeUs = AMediaExtractor_getSampleTime(mExtractor);
311 if (totalSampleSize == 0) {
312 firstSampleTimeUs = lastSampleTimeUs;
313 }
314
315 lastSampleSize = AMediaExtractor_getSampleSize(mExtractor);
316 totalSampleSize += lastSampleSize;
317 }
Linus Nilsson6233fed2020-08-13 15:15:14 -0700318 } while ((lastSampleTimeUs - firstSampleTimeUs) < kSamplingDurationUs &&
319 AMediaExtractor_advance(mExtractor));
320
321 // Reset the extractor to the beginning.
322 status = AMediaExtractor_seekTo(mExtractor, 0, AMEDIAEXTRACTOR_SEEK_PREVIOUS_SYNC);
323 if (status != AMEDIA_OK) {
324 LOG(ERROR) << "Unable to reset extractor: " << status;
325 return status;
326 }
Linus Nilsson800793f2020-07-31 16:16:38 -0700327
328 int64_t durationUs = 0;
329 const int64_t sampledDurationUs = lastSampleTimeUs - firstSampleTimeUs;
330
331 if (sampledDurationUs < kSamplingDurationUs) {
332 // Track is shorter than the sampling duration so use the full track duration to get better
333 // accuracy (i.e. don't skip the last sample).
334 AMediaFormat* trackFormat = getTrackFormat(trackIndex);
335 if (!AMediaFormat_getInt64(trackFormat, AMEDIAFORMAT_KEY_DURATION, &durationUs)) {
336 durationUs = 0;
337 }
338 AMediaFormat_delete(trackFormat);
339 }
340
341 if (durationUs == 0) {
342 // The sampled duration does not account for the last sample's duration so its size should
343 // not be included either.
344 totalSampleSize -= lastSampleSize;
345 durationUs = sampledDurationUs;
346 }
347
348 if (totalSampleSize == 0 || durationUs <= 0) {
349 LOG(ERROR) << "Unable to estimate track bitrate";
350 return AMEDIA_ERROR_MALFORMED;
351 }
352
353 *bitrate = roundf((float)totalSampleSize * 8 * 1000000 / durationUs);
354 return AMEDIA_OK;
355}
356
Linus Nilsson478df7e2020-01-29 15:34:24 -0800357media_status_t MediaSampleReaderNDK::getSampleInfoForTrack(int trackIndex, MediaSampleInfo* info) {
Linus Nilsson6233fed2020-08-13 15:15:14 -0700358 std::unique_lock<std::mutex> lock(mExtractorMutex);
Linus Nilsson478df7e2020-01-29 15:34:24 -0800359
Linus Nilsson6233fed2020-08-13 15:15:14 -0700360 if (mTrackSignals.find(trackIndex) == mTrackSignals.end()) {
361 LOG(ERROR) << "Track not selected.";
Linus Nilsson478df7e2020-01-29 15:34:24 -0800362 return AMEDIA_ERROR_INVALID_PARAMETER;
363 } else if (info == nullptr) {
364 LOG(ERROR) << "MediaSampleInfo pointer is NULL.";
365 return AMEDIA_ERROR_INVALID_PARAMETER;
366 }
367
Linus Nilsson6233fed2020-08-13 15:15:14 -0700368 media_status_t status = primeExtractorForTrack_l(trackIndex, lock);
Linus Nilsson478df7e2020-01-29 15:34:24 -0800369 if (status == AMEDIA_OK) {
370 info->presentationTimeUs = AMediaExtractor_getSampleTime(mExtractor);
371 info->flags = AMediaExtractor_getSampleFlags(mExtractor);
372 info->size = AMediaExtractor_getSampleSize(mExtractor);
373 } else if (status == AMEDIA_ERROR_END_OF_STREAM) {
374 info->presentationTimeUs = 0;
375 info->flags = SAMPLE_FLAG_END_OF_STREAM;
376 info->size = 0;
377 }
Linus Nilsson478df7e2020-01-29 15:34:24 -0800378 return status;
379}
380
381media_status_t MediaSampleReaderNDK::readSampleDataForTrack(int trackIndex, uint8_t* buffer,
382 size_t bufferSize) {
Linus Nilsson6233fed2020-08-13 15:15:14 -0700383 std::unique_lock<std::mutex> lock(mExtractorMutex);
Linus Nilsson478df7e2020-01-29 15:34:24 -0800384
Linus Nilsson6233fed2020-08-13 15:15:14 -0700385 if (mTrackSignals.find(trackIndex) == mTrackSignals.end()) {
386 LOG(ERROR) << "Track not selected.";
Linus Nilsson478df7e2020-01-29 15:34:24 -0800387 return AMEDIA_ERROR_INVALID_PARAMETER;
388 } else if (buffer == nullptr) {
389 LOG(ERROR) << "buffer pointer is NULL";
390 return AMEDIA_ERROR_INVALID_PARAMETER;
391 }
392
Linus Nilsson6233fed2020-08-13 15:15:14 -0700393 media_status_t status = primeExtractorForTrack_l(trackIndex, lock);
394 if (status != AMEDIA_OK) {
395 return status;
396 }
Linus Nilsson478df7e2020-01-29 15:34:24 -0800397
398 ssize_t sampleSize = AMediaExtractor_getSampleSize(mExtractor);
399 if (bufferSize < sampleSize) {
400 LOG(ERROR) << "Buffer is too small for sample, " << bufferSize << " vs " << sampleSize;
401 return AMEDIA_ERROR_INVALID_PARAMETER;
402 }
403
404 ssize_t bytesRead = AMediaExtractor_readSampleData(mExtractor, buffer, bufferSize);
405 if (bytesRead < sampleSize) {
406 LOG(ERROR) << "Unable to read full sample, " << bytesRead << " vs " << sampleSize;
407 return AMEDIA_ERROR_INVALID_PARAMETER;
408 }
409
Linus Nilsson6233fed2020-08-13 15:15:14 -0700410 advanceTrack_l(trackIndex);
411
Linus Nilsson478df7e2020-01-29 15:34:24 -0800412 return AMEDIA_OK;
413}
414
Linus Nilsson6233fed2020-08-13 15:15:14 -0700415void MediaSampleReaderNDK::advanceTrack(int trackIndex) {
416 std::scoped_lock lock(mExtractorMutex);
417
418 if (mTrackSignals.find(trackIndex) != mTrackSignals.end()) {
419 advanceTrack_l(trackIndex);
420 } else {
421 LOG(ERROR) << "Trying to advance a track that is not selected (#" << trackIndex << ")";
422 }
423}
424
Linus Nilsson478df7e2020-01-29 15:34:24 -0800425AMediaFormat* MediaSampleReaderNDK::getFileFormat() {
426 return AMediaExtractor_getFileFormat(mExtractor);
427}
428
429size_t MediaSampleReaderNDK::getTrackCount() const {
430 return mTrackCount;
431}
432
433AMediaFormat* MediaSampleReaderNDK::getTrackFormat(int trackIndex) {
434 if (trackIndex < 0 || trackIndex >= mTrackCount) {
435 LOG(ERROR) << "Invalid trackIndex " << trackIndex << " for trackCount " << mTrackCount;
436 return AMediaFormat_new();
437 }
438
439 return AMediaExtractor_getTrackFormat(mExtractor, trackIndex);
440}
441
442} // namespace android