APacketSource.cpp revision 6e4c5c499999c04c2477b987f9e64f3ff2bf1a06
1/*
2 * Copyright (C) 2010 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 "APacketSource"
19#include <utils/Log.h>
20
21#include "APacketSource.h"
22
23#include "ASessionDescription.h"
24
25#include "avc_utils.h"
26
27#include <ctype.h>
28
29#include <media/stagefright/foundation/ABitReader.h>
30#include <media/stagefright/foundation/ABuffer.h>
31#include <media/stagefright/foundation/ADebug.h>
32#include <media/stagefright/foundation/AMessage.h>
33#include <media/stagefright/foundation/AString.h>
34#include <media/stagefright/foundation/base64.h>
35#include <media/stagefright/foundation/hexdump.h>
36#include <media/stagefright/MediaBuffer.h>
37#include <media/stagefright/MediaDefs.h>
38#include <media/stagefright/MetaData.h>
39#include <utils/Vector.h>
40
41namespace android {
42
43static bool GetAttribute(const char *s, const char *key, AString *value) {
44    value->clear();
45
46    size_t keyLen = strlen(key);
47
48    for (;;) {
49        while (isspace(*s)) {
50            ++s;
51        }
52
53        const char *colonPos = strchr(s, ';');
54
55        size_t len =
56            (colonPos == NULL) ? strlen(s) : colonPos - s;
57
58        if (len >= keyLen + 1 && s[keyLen] == '=' && !strncmp(s, key, keyLen)) {
59            value->setTo(&s[keyLen + 1], len - keyLen - 1);
60            return true;
61        }
62
63        if (colonPos == NULL) {
64            return false;
65        }
66
67        s = colonPos + 1;
68    }
69}
70
71static sp<ABuffer> decodeHex(const AString &s) {
72    if ((s.size() % 2) != 0) {
73        return NULL;
74    }
75
76    size_t outLen = s.size() / 2;
77    sp<ABuffer> buffer = new ABuffer(outLen);
78    uint8_t *out = buffer->data();
79
80    uint8_t accum = 0;
81    for (size_t i = 0; i < s.size(); ++i) {
82        char c = s.c_str()[i];
83        unsigned value;
84        if (c >= '0' && c <= '9') {
85            value = c - '0';
86        } else if (c >= 'a' && c <= 'f') {
87            value = c - 'a' + 10;
88        } else if (c >= 'A' && c <= 'F') {
89            value = c - 'A' + 10;
90        } else {
91            return NULL;
92        }
93
94        accum = (accum << 4) | value;
95
96        if (i & 1) {
97            *out++ = accum;
98
99            accum = 0;
100        }
101    }
102
103    return buffer;
104}
105
106static sp<ABuffer> MakeAVCCodecSpecificData(
107        const char *params, int32_t *width, int32_t *height) {
108    *width = 0;
109    *height = 0;
110
111    AString val;
112    if (!GetAttribute(params, "profile-level-id", &val)) {
113        return NULL;
114    }
115
116    sp<ABuffer> profileLevelID = decodeHex(val);
117    CHECK(profileLevelID != NULL);
118    CHECK_EQ(profileLevelID->size(), 3u);
119
120    Vector<sp<ABuffer> > paramSets;
121
122    size_t numSeqParameterSets = 0;
123    size_t totalSeqParameterSetSize = 0;
124    size_t numPicParameterSets = 0;
125    size_t totalPicParameterSetSize = 0;
126
127    if (!GetAttribute(params, "sprop-parameter-sets", &val)) {
128        return NULL;
129    }
130
131    size_t start = 0;
132    for (;;) {
133        ssize_t commaPos = val.find(",", start);
134        size_t end = (commaPos < 0) ? val.size() : commaPos;
135
136        AString nalString(val, start, end - start);
137        sp<ABuffer> nal = decodeBase64(nalString);
138        CHECK(nal != NULL);
139        CHECK_GT(nal->size(), 0u);
140        CHECK_LE(nal->size(), 65535u);
141
142        uint8_t nalType = nal->data()[0] & 0x1f;
143        if (numSeqParameterSets == 0) {
144            CHECK_EQ((unsigned)nalType, 7u);
145        } else if (numPicParameterSets > 0) {
146            CHECK_EQ((unsigned)nalType, 8u);
147        }
148        if (nalType == 7) {
149            ++numSeqParameterSets;
150            totalSeqParameterSetSize += nal->size();
151        } else  {
152            CHECK_EQ((unsigned)nalType, 8u);
153            ++numPicParameterSets;
154            totalPicParameterSetSize += nal->size();
155        }
156
157        paramSets.push(nal);
158
159        if (commaPos < 0) {
160            break;
161        }
162
163        start = commaPos + 1;
164    }
165
166    CHECK_LT(numSeqParameterSets, 32u);
167    CHECK_LE(numPicParameterSets, 255u);
168
169    size_t csdSize =
170        1 + 3 + 1 + 1
171        + 2 * numSeqParameterSets + totalSeqParameterSetSize
172        + 1 + 2 * numPicParameterSets + totalPicParameterSetSize;
173
174    sp<ABuffer> csd = new ABuffer(csdSize);
175    uint8_t *out = csd->data();
176
177    *out++ = 0x01;  // configurationVersion
178    memcpy(out, profileLevelID->data(), 3);
179    out += 3;
180    *out++ = (0x3f << 2) | 1;  // lengthSize == 2 bytes
181    *out++ = 0xe0 | numSeqParameterSets;
182
183    for (size_t i = 0; i < numSeqParameterSets; ++i) {
184        sp<ABuffer> nal = paramSets.editItemAt(i);
185
186        *out++ = nal->size() >> 8;
187        *out++ = nal->size() & 0xff;
188
189        memcpy(out, nal->data(), nal->size());
190
191        out += nal->size();
192
193        if (i == 0) {
194            FindAVCDimensions(nal, width, height);
195            LOGI("dimensions %dx%d", *width, *height);
196        }
197    }
198
199    *out++ = numPicParameterSets;
200
201    for (size_t i = 0; i < numPicParameterSets; ++i) {
202        sp<ABuffer> nal = paramSets.editItemAt(i + numSeqParameterSets);
203
204        *out++ = nal->size() >> 8;
205        *out++ = nal->size() & 0xff;
206
207        memcpy(out, nal->data(), nal->size());
208
209        out += nal->size();
210    }
211
212    // hexdump(csd->data(), csd->size());
213
214    return csd;
215}
216
217sp<ABuffer> MakeAACCodecSpecificData(const char *params) {
218    AString val;
219    CHECK(GetAttribute(params, "config", &val));
220
221    sp<ABuffer> config = decodeHex(val);
222    CHECK(config != NULL);
223    CHECK_GE(config->size(), 4u);
224
225    const uint8_t *data = config->data();
226    uint32_t x = data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3];
227    x = (x >> 1) & 0xffff;
228
229    static const uint8_t kStaticESDS[] = {
230        0x03, 22,
231        0x00, 0x00,     // ES_ID
232        0x00,           // streamDependenceFlag, URL_Flag, OCRstreamFlag
233
234        0x04, 17,
235        0x40,                       // Audio ISO/IEC 14496-3
236        0x00, 0x00, 0x00, 0x00,
237        0x00, 0x00, 0x00, 0x00,
238        0x00, 0x00, 0x00, 0x00,
239
240        0x05, 2,
241        // AudioSpecificInfo follows
242    };
243
244    sp<ABuffer> csd = new ABuffer(sizeof(kStaticESDS) + 2);
245    memcpy(csd->data(), kStaticESDS, sizeof(kStaticESDS));
246    csd->data()[sizeof(kStaticESDS)] = (x >> 8) & 0xff;
247    csd->data()[sizeof(kStaticESDS) + 1] = x & 0xff;
248
249    // hexdump(csd->data(), csd->size());
250
251    return csd;
252}
253
254// From mpeg4-generic configuration data.
255sp<ABuffer> MakeAACCodecSpecificData2(const char *params) {
256    AString val;
257    unsigned long objectType;
258    if (GetAttribute(params, "objectType", &val)) {
259        const char *s = val.c_str();
260        char *end;
261        objectType = strtoul(s, &end, 10);
262        CHECK(end > s && *end == '\0');
263    } else {
264        objectType = 0x40;  // Audio ISO/IEC 14496-3
265    }
266
267    CHECK(GetAttribute(params, "config", &val));
268
269    sp<ABuffer> config = decodeHex(val);
270    CHECK(config != NULL);
271
272    // Make sure size fits into a single byte and doesn't have to
273    // be encoded.
274    CHECK_LT(20 + config->size(), 128u);
275
276    const uint8_t *data = config->data();
277
278    static const uint8_t kStaticESDS[] = {
279        0x03, 22,
280        0x00, 0x00,     // ES_ID
281        0x00,           // streamDependenceFlag, URL_Flag, OCRstreamFlag
282
283        0x04, 17,
284        0x40,                       // Audio ISO/IEC 14496-3
285        0x00, 0x00, 0x00, 0x00,
286        0x00, 0x00, 0x00, 0x00,
287        0x00, 0x00, 0x00, 0x00,
288
289        0x05, 2,
290        // AudioSpecificInfo follows
291    };
292
293    sp<ABuffer> csd = new ABuffer(sizeof(kStaticESDS) + config->size());
294    uint8_t *dst = csd->data();
295    *dst++ = 0x03;
296    *dst++ = 20 + config->size();
297    *dst++ = 0x00;  // ES_ID
298    *dst++ = 0x00;
299    *dst++ = 0x00;  // streamDependenceFlag, URL_Flag, OCRstreamFlag
300    *dst++ = 0x04;
301    *dst++ = 15 + config->size();
302    *dst++ = objectType;
303    for (int i = 0; i < 12; ++i) { *dst++ = 0x00; }
304    *dst++ = 0x05;
305    *dst++ = config->size();
306    memcpy(dst, config->data(), config->size());
307
308    // hexdump(csd->data(), csd->size());
309
310    return csd;
311}
312
313static size_t GetSizeWidth(size_t x) {
314    size_t n = 1;
315    while (x > 127) {
316        ++n;
317        x >>= 7;
318    }
319    return n;
320}
321
322static uint8_t *EncodeSize(uint8_t *dst, size_t x) {
323    while (x > 127) {
324        *dst++ = (x & 0x7f) | 0x80;
325        x >>= 7;
326    }
327    *dst++ = x;
328    return dst;
329}
330
331static bool ExtractDimensionsFromVOLHeader(
332        const sp<ABuffer> &config, int32_t *width, int32_t *height) {
333    *width = 0;
334    *height = 0;
335
336    const uint8_t *ptr = config->data();
337    size_t offset = 0;
338    bool foundVOL = false;
339    while (offset + 3 < config->size()) {
340        if (memcmp("\x00\x00\x01", &ptr[offset], 3)
341                || (ptr[offset + 3] & 0xf0) != 0x20) {
342            ++offset;
343            continue;
344        }
345
346        foundVOL = true;
347        break;
348    }
349
350    if (!foundVOL) {
351        return false;
352    }
353
354    ABitReader br(&ptr[offset + 4], config->size() - offset - 4);
355    br.skipBits(1);  // random_accessible_vol
356    unsigned video_object_type_indication = br.getBits(8);
357
358    CHECK_NE(video_object_type_indication,
359             0x21u /* Fine Granularity Scalable */);
360
361    unsigned video_object_layer_verid;
362    unsigned video_object_layer_priority;
363    if (br.getBits(1)) {
364        video_object_layer_verid = br.getBits(4);
365        video_object_layer_priority = br.getBits(3);
366    }
367    unsigned aspect_ratio_info = br.getBits(4);
368    if (aspect_ratio_info == 0x0f /* extended PAR */) {
369        br.skipBits(8);  // par_width
370        br.skipBits(8);  // par_height
371    }
372    if (br.getBits(1)) {  // vol_control_parameters
373        br.skipBits(2);  // chroma_format
374        br.skipBits(1);  // low_delay
375        if (br.getBits(1)) {  // vbv_parameters
376            TRESPASS();
377        }
378    }
379    unsigned video_object_layer_shape = br.getBits(2);
380    CHECK_EQ(video_object_layer_shape, 0x00u /* rectangular */);
381
382    CHECK(br.getBits(1));  // marker_bit
383    unsigned vop_time_increment_resolution = br.getBits(16);
384    CHECK(br.getBits(1));  // marker_bit
385
386    if (br.getBits(1)) {  // fixed_vop_rate
387        // range [0..vop_time_increment_resolution)
388
389        // vop_time_increment_resolution
390        // 2 => 0..1, 1 bit
391        // 3 => 0..2, 2 bits
392        // 4 => 0..3, 2 bits
393        // 5 => 0..4, 3 bits
394        // ...
395
396        CHECK_GT(vop_time_increment_resolution, 0u);
397        --vop_time_increment_resolution;
398
399        unsigned numBits = 0;
400        while (vop_time_increment_resolution > 0) {
401            ++numBits;
402            vop_time_increment_resolution >>= 1;
403        }
404
405        br.skipBits(numBits);  // fixed_vop_time_increment
406    }
407
408    CHECK(br.getBits(1));  // marker_bit
409    unsigned video_object_layer_width = br.getBits(13);
410    CHECK(br.getBits(1));  // marker_bit
411    unsigned video_object_layer_height = br.getBits(13);
412    CHECK(br.getBits(1));  // marker_bit
413
414    unsigned interlaced = br.getBits(1);
415
416    *width = video_object_layer_width;
417    *height = video_object_layer_height;
418
419    LOGI("VOL dimensions = %dx%d", *width, *height);
420
421    return true;
422}
423
424sp<ABuffer> MakeMPEG4VideoCodecSpecificData(
425        const char *params, int32_t *width, int32_t *height) {
426    *width = 0;
427    *height = 0;
428
429    AString val;
430    CHECK(GetAttribute(params, "config", &val));
431
432    sp<ABuffer> config = decodeHex(val);
433    CHECK(config != NULL);
434
435    if (!ExtractDimensionsFromVOLHeader(config, width, height)) {
436        return NULL;
437    }
438
439    size_t len1 = config->size() + GetSizeWidth(config->size()) + 1;
440    size_t len2 = len1 + GetSizeWidth(len1) + 1 + 13;
441    size_t len3 = len2 + GetSizeWidth(len2) + 1 + 3;
442
443    sp<ABuffer> csd = new ABuffer(len3);
444    uint8_t *dst = csd->data();
445    *dst++ = 0x03;
446    dst = EncodeSize(dst, len2 + 3);
447    *dst++ = 0x00;  // ES_ID
448    *dst++ = 0x00;
449    *dst++ = 0x00;  // streamDependenceFlag, URL_Flag, OCRstreamFlag
450
451    *dst++ = 0x04;
452    dst = EncodeSize(dst, len1 + 13);
453    *dst++ = 0x01;  // Video ISO/IEC 14496-2 Simple Profile
454    for (size_t i = 0; i < 12; ++i) {
455        *dst++ = 0x00;
456    }
457
458    *dst++ = 0x05;
459    dst = EncodeSize(dst, config->size());
460    memcpy(dst, config->data(), config->size());
461    dst += config->size();
462
463    // hexdump(csd->data(), csd->size());
464
465    return csd;
466}
467
468static bool GetClockRate(const AString &desc, uint32_t *clockRate) {
469    ssize_t slashPos = desc.find("/");
470    if (slashPos < 0) {
471        return false;
472    }
473
474    const char *s = desc.c_str() + slashPos + 1;
475
476    char *end;
477    unsigned long x = strtoul(s, &end, 10);
478
479    if (end == s || (*end != '\0' && *end != '/')) {
480        return false;
481    }
482
483    *clockRate = x;
484
485    return true;
486}
487
488APacketSource::APacketSource(
489        const sp<ASessionDescription> &sessionDesc, size_t index)
490    : mInitCheck(NO_INIT),
491      mFormat(new MetaData),
492      mEOSResult(OK),
493      mRTPTimeBase(0),
494      mNormalPlayTimeBaseUs(0),
495      mLastNormalPlayTimeUs(0) {
496    unsigned long PT;
497    AString desc;
498    AString params;
499    sessionDesc->getFormatType(index, &PT, &desc, &params);
500
501    CHECK(GetClockRate(desc, &mClockRate));
502
503    int64_t durationUs;
504    if (sessionDesc->getDurationUs(&durationUs)) {
505        mFormat->setInt64(kKeyDuration, durationUs);
506    } else {
507        mFormat->setInt64(kKeyDuration, 60 * 60 * 1000000ll);
508    }
509
510    mInitCheck = OK;
511    if (!strncmp(desc.c_str(), "H264/", 5)) {
512        mFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
513
514        int32_t width, height;
515        if (!sessionDesc->getDimensions(index, PT, &width, &height)) {
516            width = -1;
517            height = -1;
518        }
519
520        int32_t encWidth, encHeight;
521        sp<ABuffer> codecSpecificData =
522            MakeAVCCodecSpecificData(params.c_str(), &encWidth, &encHeight);
523
524        if (codecSpecificData != NULL) {
525            if (width < 0) {
526                // If no explicit width/height given in the sdp, use the dimensions
527                // extracted from the first sequence parameter set.
528                width = encWidth;
529                height = encHeight;
530            }
531
532            mFormat->setData(
533                    kKeyAVCC, 0,
534                    codecSpecificData->data(), codecSpecificData->size());
535        } else if (width < 0) {
536            mInitCheck = ERROR_UNSUPPORTED;
537            return;
538        }
539
540        mFormat->setInt32(kKeyWidth, width);
541        mFormat->setInt32(kKeyHeight, height);
542    } else if (!strncmp(desc.c_str(), "H263-2000/", 10)
543            || !strncmp(desc.c_str(), "H263-1998/", 10)) {
544        mFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
545
546        int32_t width, height;
547        if (!sessionDesc->getDimensions(index, PT, &width, &height)) {
548            mInitCheck = ERROR_UNSUPPORTED;
549            return;
550        }
551
552        mFormat->setInt32(kKeyWidth, width);
553        mFormat->setInt32(kKeyHeight, height);
554    } else if (!strncmp(desc.c_str(), "MP4A-LATM/", 10)) {
555        mFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
556
557        int32_t sampleRate, numChannels;
558        ASessionDescription::ParseFormatDesc(
559                desc.c_str(), &sampleRate, &numChannels);
560
561        mFormat->setInt32(kKeySampleRate, sampleRate);
562        mFormat->setInt32(kKeyChannelCount, numChannels);
563
564        sp<ABuffer> codecSpecificData =
565            MakeAACCodecSpecificData(params.c_str());
566
567        mFormat->setData(
568                kKeyESDS, 0,
569                codecSpecificData->data(), codecSpecificData->size());
570    } else if (!strncmp(desc.c_str(), "AMR/", 4)) {
571        mFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_NB);
572
573        int32_t sampleRate, numChannels;
574        ASessionDescription::ParseFormatDesc(
575                desc.c_str(), &sampleRate, &numChannels);
576
577        mFormat->setInt32(kKeySampleRate, sampleRate);
578        mFormat->setInt32(kKeyChannelCount, numChannels);
579
580        if (sampleRate != 8000 || numChannels != 1) {
581            mInitCheck = ERROR_UNSUPPORTED;
582        }
583    } else if (!strncmp(desc.c_str(), "AMR-WB/", 7)) {
584        mFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_WB);
585
586        int32_t sampleRate, numChannels;
587        ASessionDescription::ParseFormatDesc(
588                desc.c_str(), &sampleRate, &numChannels);
589
590        mFormat->setInt32(kKeySampleRate, sampleRate);
591        mFormat->setInt32(kKeyChannelCount, numChannels);
592
593        if (sampleRate != 16000 || numChannels != 1) {
594            mInitCheck = ERROR_UNSUPPORTED;
595        }
596    } else if (!strncmp(desc.c_str(), "MP4V-ES/", 8)) {
597        mFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
598
599        int32_t width, height;
600        if (!sessionDesc->getDimensions(index, PT, &width, &height)) {
601            width = -1;
602            height = -1;
603        }
604
605        int32_t encWidth, encHeight;
606        sp<ABuffer> codecSpecificData =
607            MakeMPEG4VideoCodecSpecificData(
608                    params.c_str(), &encWidth, &encHeight);
609
610        if (codecSpecificData != NULL) {
611            mFormat->setData(
612                    kKeyESDS, 0,
613                    codecSpecificData->data(), codecSpecificData->size());
614
615            if (width < 0) {
616                width = encWidth;
617                height = encHeight;
618            }
619        } else if (width < 0) {
620            mInitCheck = ERROR_UNSUPPORTED;
621            return;
622        }
623
624        mFormat->setInt32(kKeyWidth, width);
625        mFormat->setInt32(kKeyHeight, height);
626    } else if (!strncmp(desc.c_str(), "mpeg4-generic/", 14)) {
627        AString val;
628        if (!GetAttribute(params.c_str(), "mode", &val)
629                || (strcasecmp(val.c_str(), "AAC-lbr")
630                    && strcasecmp(val.c_str(), "AAC-hbr"))) {
631            mInitCheck = ERROR_UNSUPPORTED;
632            return;
633        }
634
635        mFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
636
637        int32_t sampleRate, numChannels;
638        ASessionDescription::ParseFormatDesc(
639                desc.c_str(), &sampleRate, &numChannels);
640
641        mFormat->setInt32(kKeySampleRate, sampleRate);
642        mFormat->setInt32(kKeyChannelCount, numChannels);
643
644        sp<ABuffer> codecSpecificData =
645            MakeAACCodecSpecificData2(params.c_str());
646
647        mFormat->setData(
648                kKeyESDS, 0,
649                codecSpecificData->data(), codecSpecificData->size());
650    } else {
651        mInitCheck = ERROR_UNSUPPORTED;
652    }
653}
654
655APacketSource::~APacketSource() {
656}
657
658status_t APacketSource::initCheck() const {
659    return mInitCheck;
660}
661
662status_t APacketSource::start(MetaData *params) {
663    return OK;
664}
665
666status_t APacketSource::stop() {
667    return OK;
668}
669
670sp<MetaData> APacketSource::getFormat() {
671    return mFormat;
672}
673
674status_t APacketSource::read(
675        MediaBuffer **out, const ReadOptions *) {
676    *out = NULL;
677
678    Mutex::Autolock autoLock(mLock);
679    while (mEOSResult == OK && mBuffers.empty()) {
680        mCondition.wait(mLock);
681    }
682
683    if (!mBuffers.empty()) {
684        const sp<ABuffer> buffer = *mBuffers.begin();
685
686        updateNormalPlayTime_l(buffer);
687
688        MediaBuffer *mediaBuffer = new MediaBuffer(buffer->size());
689
690        int64_t timeUs;
691        CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
692
693        mediaBuffer->meta_data()->setInt64(kKeyTime, timeUs);
694
695        memcpy(mediaBuffer->data(), buffer->data(), buffer->size());
696        *out = mediaBuffer;
697
698        mBuffers.erase(mBuffers.begin());
699        return OK;
700    }
701
702    return mEOSResult;
703}
704
705void APacketSource::updateNormalPlayTime_l(const sp<ABuffer> &buffer) {
706    uint32_t rtpTime;
707    CHECK(buffer->meta()->findInt32("rtp-time", (int32_t *)&rtpTime));
708
709    mLastNormalPlayTimeUs =
710        (((double)rtpTime - (double)mRTPTimeBase) / mClockRate)
711            * 1000000ll
712            + mNormalPlayTimeBaseUs;
713}
714
715void APacketSource::queueAccessUnit(const sp<ABuffer> &buffer) {
716    int32_t damaged;
717    if (buffer->meta()->findInt32("damaged", &damaged) && damaged) {
718        LOGV("discarding damaged AU");
719        return;
720    }
721
722    Mutex::Autolock autoLock(mLock);
723    mBuffers.push_back(buffer);
724    mCondition.signal();
725}
726
727void APacketSource::signalEOS(status_t result) {
728    CHECK(result != OK);
729
730    Mutex::Autolock autoLock(mLock);
731    mEOSResult = result;
732    mCondition.signal();
733}
734
735void APacketSource::flushQueue() {
736    Mutex::Autolock autoLock(mLock);
737    mBuffers.clear();
738}
739
740int64_t APacketSource::getNormalPlayTimeUs() {
741    Mutex::Autolock autoLock(mLock);
742    return mLastNormalPlayTimeUs;
743}
744
745void APacketSource::setNormalPlayTimeMapping(
746        uint32_t rtpTime, int64_t normalPlayTimeUs) {
747    Mutex::Autolock autoLock(mLock);
748
749    mRTPTimeBase = rtpTime;
750    mNormalPlayTimeBaseUs = normalPlayTimeUs;
751}
752
753int64_t APacketSource::getQueueDurationUs(bool *eos) {
754    Mutex::Autolock autoLock(mLock);
755
756    *eos = (mEOSResult != OK);
757
758    if (mBuffers.size() < 2) {
759        return 0;
760    }
761
762    const sp<ABuffer> first = *mBuffers.begin();
763    const sp<ABuffer> last = *--mBuffers.end();
764
765    int64_t firstTimeUs;
766    CHECK(first->meta()->findInt64("timeUs", &firstTimeUs));
767
768    int64_t lastTimeUs;
769    CHECK(last->meta()->findInt64("timeUs", &lastTimeUs));
770
771    if (lastTimeUs < firstTimeUs) {
772        LOGE("Huh? Time moving backwards? %lld > %lld",
773             firstTimeUs, lastTimeUs);
774
775        return 0;
776    }
777
778    return lastTimeUs - firstTimeUs;
779}
780
781}  // namespace android
782