ATSParser.cpp revision f6d0c1fd6d9e697bb3a891fae14c7e9d4b685de6
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 "ATSParser"
19#include <utils/Log.h>
20
21#include "ATSParser.h"
22
23#include "AnotherPacketSource.h"
24#include "ESQueue.h"
25#include "include/avc_utils.h"
26
27#include <media/stagefright/foundation/ABitReader.h>
28#include <media/stagefright/foundation/ABuffer.h>
29#include <media/stagefright/foundation/ADebug.h>
30#include <media/stagefright/foundation/AMessage.h>
31#include <media/stagefright/foundation/hexdump.h>
32#include <media/stagefright/MediaDefs.h>
33#include <media/stagefright/MediaErrors.h>
34#include <media/stagefright/MetaData.h>
35#include <media/stagefright/Utils.h>
36#include <media/IStreamSource.h>
37#include <utils/KeyedVector.h>
38
39#include <inttypes.h>
40
41namespace android {
42
43// I want the expression "y" evaluated even if verbose logging is off.
44#define MY_LOGV(x, y) \
45    do { unsigned tmp = y; ALOGV(x, tmp); } while (0)
46
47static const size_t kTSPacketSize = 188;
48
49struct ATSParser::Program : public RefBase {
50    Program(ATSParser *parser, unsigned programNumber, unsigned programMapPID);
51
52    bool parsePSISection(
53            unsigned pid, ABitReader *br, status_t *err);
54
55    bool parsePID(
56            unsigned pid, unsigned continuity_counter,
57            unsigned payload_unit_start_indicator,
58            ABitReader *br, status_t *err);
59
60    void signalDiscontinuity(
61            DiscontinuityType type, const sp<AMessage> &extra);
62
63    void signalEOS(status_t finalResult);
64
65    sp<MediaSource> getSource(SourceType type);
66
67    int64_t convertPTSToTimestamp(uint64_t PTS);
68
69    bool PTSTimeDeltaEstablished() const {
70        return mFirstPTSValid;
71    }
72
73    unsigned number() const { return mProgramNumber; }
74
75    void updateProgramMapPID(unsigned programMapPID) {
76        mProgramMapPID = programMapPID;
77    }
78
79    unsigned programMapPID() const {
80        return mProgramMapPID;
81    }
82
83    uint32_t parserFlags() const {
84        return mParser->mFlags;
85    }
86
87private:
88    ATSParser *mParser;
89    unsigned mProgramNumber;
90    unsigned mProgramMapPID;
91    KeyedVector<unsigned, sp<Stream> > mStreams;
92    bool mFirstPTSValid;
93    uint64_t mFirstPTS;
94
95    status_t parseProgramMap(ABitReader *br);
96
97    DISALLOW_EVIL_CONSTRUCTORS(Program);
98};
99
100struct ATSParser::Stream : public RefBase {
101    Stream(Program *program,
102           unsigned elementaryPID,
103           unsigned streamType,
104           unsigned PCR_PID);
105
106    unsigned type() const { return mStreamType; }
107    unsigned pid() const { return mElementaryPID; }
108    void setPID(unsigned pid) { mElementaryPID = pid; }
109
110    status_t parse(
111            unsigned continuity_counter,
112            unsigned payload_unit_start_indicator,
113            ABitReader *br);
114
115    void signalDiscontinuity(
116            DiscontinuityType type, const sp<AMessage> &extra);
117
118    void signalEOS(status_t finalResult);
119
120    sp<MediaSource> getSource(SourceType type);
121
122protected:
123    virtual ~Stream();
124
125private:
126    Program *mProgram;
127    unsigned mElementaryPID;
128    unsigned mStreamType;
129    unsigned mPCR_PID;
130    int32_t mExpectedContinuityCounter;
131
132    sp<ABuffer> mBuffer;
133    sp<AnotherPacketSource> mSource;
134    bool mPayloadStarted;
135
136    uint64_t mPrevPTS;
137
138    ElementaryStreamQueue *mQueue;
139
140    status_t flush();
141    status_t parsePES(ABitReader *br);
142
143    void onPayloadData(
144            unsigned PTS_DTS_flags, uint64_t PTS, uint64_t DTS,
145            const uint8_t *data, size_t size);
146
147    void extractAACFrames(const sp<ABuffer> &buffer);
148
149    bool isAudio() const;
150    bool isVideo() const;
151
152    DISALLOW_EVIL_CONSTRUCTORS(Stream);
153};
154
155struct ATSParser::PSISection : public RefBase {
156    PSISection();
157
158    status_t append(const void *data, size_t size);
159    void clear();
160
161    bool isComplete() const;
162    bool isEmpty() const;
163
164    const uint8_t *data() const;
165    size_t size() const;
166
167protected:
168    virtual ~PSISection();
169
170private:
171    sp<ABuffer> mBuffer;
172
173    DISALLOW_EVIL_CONSTRUCTORS(PSISection);
174};
175
176////////////////////////////////////////////////////////////////////////////////
177
178ATSParser::Program::Program(
179        ATSParser *parser, unsigned programNumber, unsigned programMapPID)
180    : mParser(parser),
181      mProgramNumber(programNumber),
182      mProgramMapPID(programMapPID),
183      mFirstPTSValid(false),
184      mFirstPTS(0) {
185    ALOGV("new program number %u", programNumber);
186}
187
188bool ATSParser::Program::parsePSISection(
189        unsigned pid, ABitReader *br, status_t *err) {
190    *err = OK;
191
192    if (pid != mProgramMapPID) {
193        return false;
194    }
195
196    *err = parseProgramMap(br);
197
198    return true;
199}
200
201bool ATSParser::Program::parsePID(
202        unsigned pid, unsigned continuity_counter,
203        unsigned payload_unit_start_indicator,
204        ABitReader *br, status_t *err) {
205    *err = OK;
206
207    ssize_t index = mStreams.indexOfKey(pid);
208    if (index < 0) {
209        return false;
210    }
211
212    *err = mStreams.editValueAt(index)->parse(
213            continuity_counter, payload_unit_start_indicator, br);
214
215    return true;
216}
217
218void ATSParser::Program::signalDiscontinuity(
219        DiscontinuityType type, const sp<AMessage> &extra) {
220    int64_t mediaTimeUs;
221    if ((type & DISCONTINUITY_TIME)
222            && extra != NULL
223            && extra->findInt64(
224                IStreamListener::kKeyMediaTimeUs, &mediaTimeUs)) {
225        mFirstPTSValid = false;
226    }
227
228    for (size_t i = 0; i < mStreams.size(); ++i) {
229        mStreams.editValueAt(i)->signalDiscontinuity(type, extra);
230    }
231}
232
233void ATSParser::Program::signalEOS(status_t finalResult) {
234    for (size_t i = 0; i < mStreams.size(); ++i) {
235        mStreams.editValueAt(i)->signalEOS(finalResult);
236    }
237}
238
239struct StreamInfo {
240    unsigned mType;
241    unsigned mPID;
242};
243
244status_t ATSParser::Program::parseProgramMap(ABitReader *br) {
245    unsigned table_id = br->getBits(8);
246    ALOGV("  table_id = %u", table_id);
247    CHECK_EQ(table_id, 0x02u);
248
249    unsigned section_syntax_indicator = br->getBits(1);
250    ALOGV("  section_syntax_indicator = %u", section_syntax_indicator);
251    CHECK_EQ(section_syntax_indicator, 1u);
252
253    CHECK_EQ(br->getBits(1), 0u);
254    MY_LOGV("  reserved = %u", br->getBits(2));
255
256    unsigned section_length = br->getBits(12);
257    ALOGV("  section_length = %u", section_length);
258    CHECK_EQ(section_length & 0xc00, 0u);
259    CHECK_LE(section_length, 1021u);
260
261    MY_LOGV("  program_number = %u", br->getBits(16));
262    MY_LOGV("  reserved = %u", br->getBits(2));
263    MY_LOGV("  version_number = %u", br->getBits(5));
264    MY_LOGV("  current_next_indicator = %u", br->getBits(1));
265    MY_LOGV("  section_number = %u", br->getBits(8));
266    MY_LOGV("  last_section_number = %u", br->getBits(8));
267    MY_LOGV("  reserved = %u", br->getBits(3));
268
269    unsigned PCR_PID = br->getBits(13);
270    ALOGV("  PCR_PID = 0x%04x", PCR_PID);
271
272    MY_LOGV("  reserved = %u", br->getBits(4));
273
274    unsigned program_info_length = br->getBits(12);
275    ALOGV("  program_info_length = %u", program_info_length);
276    CHECK_EQ(program_info_length & 0xc00, 0u);
277
278    br->skipBits(program_info_length * 8);  // skip descriptors
279
280    Vector<StreamInfo> infos;
281
282    // infoBytesRemaining is the number of bytes that make up the
283    // variable length section of ES_infos. It does not include the
284    // final CRC.
285    size_t infoBytesRemaining = section_length - 9 - program_info_length - 4;
286
287    while (infoBytesRemaining > 0) {
288        CHECK_GE(infoBytesRemaining, 5u);
289
290        unsigned streamType = br->getBits(8);
291        ALOGV("    stream_type = 0x%02x", streamType);
292
293        MY_LOGV("    reserved = %u", br->getBits(3));
294
295        unsigned elementaryPID = br->getBits(13);
296        ALOGV("    elementary_PID = 0x%04x", elementaryPID);
297
298        MY_LOGV("    reserved = %u", br->getBits(4));
299
300        unsigned ES_info_length = br->getBits(12);
301        ALOGV("    ES_info_length = %u", ES_info_length);
302        CHECK_EQ(ES_info_length & 0xc00, 0u);
303
304        CHECK_GE(infoBytesRemaining - 5, ES_info_length);
305
306#if 0
307        br->skipBits(ES_info_length * 8);  // skip descriptors
308#else
309        unsigned info_bytes_remaining = ES_info_length;
310        while (info_bytes_remaining >= 2) {
311            MY_LOGV("      tag = 0x%02x", br->getBits(8));
312
313            unsigned descLength = br->getBits(8);
314            ALOGV("      len = %u", descLength);
315
316            CHECK_GE(info_bytes_remaining, 2 + descLength);
317
318            br->skipBits(descLength * 8);
319
320            info_bytes_remaining -= descLength + 2;
321        }
322        CHECK_EQ(info_bytes_remaining, 0u);
323#endif
324
325        StreamInfo info;
326        info.mType = streamType;
327        info.mPID = elementaryPID;
328        infos.push(info);
329
330        infoBytesRemaining -= 5 + ES_info_length;
331    }
332
333    CHECK_EQ(infoBytesRemaining, 0u);
334    MY_LOGV("  CRC = 0x%08x", br->getBits(32));
335
336    bool PIDsChanged = false;
337    for (size_t i = 0; i < infos.size(); ++i) {
338        StreamInfo &info = infos.editItemAt(i);
339
340        ssize_t index = mStreams.indexOfKey(info.mPID);
341
342        if (index >= 0 && mStreams.editValueAt(index)->type() != info.mType) {
343            ALOGI("uh oh. stream PIDs have changed.");
344            PIDsChanged = true;
345            break;
346        }
347    }
348
349    if (PIDsChanged) {
350#if 0
351        ALOGI("before:");
352        for (size_t i = 0; i < mStreams.size(); ++i) {
353            sp<Stream> stream = mStreams.editValueAt(i);
354
355            ALOGI("PID 0x%08x => type 0x%02x", stream->pid(), stream->type());
356        }
357
358        ALOGI("after:");
359        for (size_t i = 0; i < infos.size(); ++i) {
360            StreamInfo &info = infos.editItemAt(i);
361
362            ALOGI("PID 0x%08x => type 0x%02x", info.mPID, info.mType);
363        }
364#endif
365
366        // The only case we can recover from is if we have two streams
367        // and they switched PIDs.
368
369        bool success = false;
370
371        if (mStreams.size() == 2 && infos.size() == 2) {
372            const StreamInfo &info1 = infos.itemAt(0);
373            const StreamInfo &info2 = infos.itemAt(1);
374
375            sp<Stream> s1 = mStreams.editValueAt(0);
376            sp<Stream> s2 = mStreams.editValueAt(1);
377
378            bool caseA =
379                info1.mPID == s1->pid() && info1.mType == s2->type()
380                    && info2.mPID == s2->pid() && info2.mType == s1->type();
381
382            bool caseB =
383                info1.mPID == s2->pid() && info1.mType == s1->type()
384                    && info2.mPID == s1->pid() && info2.mType == s2->type();
385
386            if (caseA || caseB) {
387                unsigned pid1 = s1->pid();
388                unsigned pid2 = s2->pid();
389                s1->setPID(pid2);
390                s2->setPID(pid1);
391
392                mStreams.clear();
393                mStreams.add(s1->pid(), s1);
394                mStreams.add(s2->pid(), s2);
395
396                success = true;
397            }
398        }
399
400        if (!success) {
401            ALOGI("Stream PIDs changed and we cannot recover.");
402            return ERROR_MALFORMED;
403        }
404    }
405
406    for (size_t i = 0; i < infos.size(); ++i) {
407        StreamInfo &info = infos.editItemAt(i);
408
409        ssize_t index = mStreams.indexOfKey(info.mPID);
410
411        if (index < 0) {
412            sp<Stream> stream = new Stream(
413                    this, info.mPID, info.mType, PCR_PID);
414
415            mStreams.add(info.mPID, stream);
416        }
417    }
418
419    return OK;
420}
421
422sp<MediaSource> ATSParser::Program::getSource(SourceType type) {
423    size_t index = (type == AUDIO) ? 0 : 0;
424
425    for (size_t i = 0; i < mStreams.size(); ++i) {
426        sp<MediaSource> source = mStreams.editValueAt(i)->getSource(type);
427        if (source != NULL) {
428            if (index == 0) {
429                return source;
430            }
431            --index;
432        }
433    }
434
435    return NULL;
436}
437
438int64_t ATSParser::Program::convertPTSToTimestamp(uint64_t PTS) {
439    if (!(mParser->mFlags & TS_TIMESTAMPS_ARE_ABSOLUTE)) {
440        if (!mFirstPTSValid) {
441            mFirstPTSValid = true;
442            mFirstPTS = PTS;
443            PTS = 0;
444        } else if (PTS < mFirstPTS) {
445            PTS = 0;
446        } else {
447            PTS -= mFirstPTS;
448        }
449    }
450
451    int64_t timeUs = (PTS * 100) / 9;
452
453    if (mParser->mAbsoluteTimeAnchorUs >= 0ll) {
454        timeUs += mParser->mAbsoluteTimeAnchorUs;
455    }
456
457    if (mParser->mTimeOffsetValid) {
458        timeUs += mParser->mTimeOffsetUs;
459    }
460
461    return timeUs;
462}
463
464////////////////////////////////////////////////////////////////////////////////
465
466ATSParser::Stream::Stream(
467        Program *program,
468        unsigned elementaryPID,
469        unsigned streamType,
470        unsigned PCR_PID)
471    : mProgram(program),
472      mElementaryPID(elementaryPID),
473      mStreamType(streamType),
474      mPCR_PID(PCR_PID),
475      mExpectedContinuityCounter(-1),
476      mPayloadStarted(false),
477      mPrevPTS(0),
478      mQueue(NULL) {
479    switch (mStreamType) {
480        case STREAMTYPE_H264:
481            mQueue = new ElementaryStreamQueue(
482                    ElementaryStreamQueue::H264,
483                    (mProgram->parserFlags() & ALIGNED_VIDEO_DATA)
484                        ? ElementaryStreamQueue::kFlag_AlignedData : 0);
485            break;
486        case STREAMTYPE_MPEG2_AUDIO_ADTS:
487            mQueue = new ElementaryStreamQueue(ElementaryStreamQueue::AAC);
488            break;
489        case STREAMTYPE_MPEG1_AUDIO:
490        case STREAMTYPE_MPEG2_AUDIO:
491            mQueue = new ElementaryStreamQueue(
492                    ElementaryStreamQueue::MPEG_AUDIO);
493            break;
494
495        case STREAMTYPE_MPEG1_VIDEO:
496        case STREAMTYPE_MPEG2_VIDEO:
497            mQueue = new ElementaryStreamQueue(
498                    ElementaryStreamQueue::MPEG_VIDEO);
499            break;
500
501        case STREAMTYPE_MPEG4_VIDEO:
502            mQueue = new ElementaryStreamQueue(
503                    ElementaryStreamQueue::MPEG4_VIDEO);
504            break;
505
506        case STREAMTYPE_PCM_AUDIO:
507            mQueue = new ElementaryStreamQueue(
508                    ElementaryStreamQueue::PCM_AUDIO);
509            break;
510
511        default:
512            break;
513    }
514
515    ALOGV("new stream PID 0x%02x, type 0x%02x", elementaryPID, streamType);
516
517    if (mQueue != NULL) {
518        mBuffer = new ABuffer(192 * 1024);
519        mBuffer->setRange(0, 0);
520    }
521}
522
523ATSParser::Stream::~Stream() {
524    delete mQueue;
525    mQueue = NULL;
526}
527
528status_t ATSParser::Stream::parse(
529        unsigned continuity_counter,
530        unsigned payload_unit_start_indicator, ABitReader *br) {
531    if (mQueue == NULL) {
532        return OK;
533    }
534
535    if (mExpectedContinuityCounter >= 0
536            && (unsigned)mExpectedContinuityCounter != continuity_counter) {
537        ALOGI("discontinuity on stream pid 0x%04x", mElementaryPID);
538
539        mPayloadStarted = false;
540        mBuffer->setRange(0, 0);
541        mExpectedContinuityCounter = -1;
542
543#if 0
544        // Uncomment this if you'd rather see no corruption whatsoever on
545        // screen and suspend updates until we come across another IDR frame.
546
547        if (mStreamType == STREAMTYPE_H264) {
548            ALOGI("clearing video queue");
549            mQueue->clear(true /* clearFormat */);
550        }
551#endif
552
553        return OK;
554    }
555
556    mExpectedContinuityCounter = (continuity_counter + 1) & 0x0f;
557
558    if (payload_unit_start_indicator) {
559        if (mPayloadStarted) {
560            // Otherwise we run the danger of receiving the trailing bytes
561            // of a PES packet that we never saw the start of and assuming
562            // we have a a complete PES packet.
563
564            status_t err = flush();
565
566            if (err != OK) {
567                return err;
568            }
569        }
570
571        mPayloadStarted = true;
572    }
573
574    if (!mPayloadStarted) {
575        return OK;
576    }
577
578    size_t payloadSizeBits = br->numBitsLeft();
579    CHECK_EQ(payloadSizeBits % 8, 0u);
580
581    size_t neededSize = mBuffer->size() + payloadSizeBits / 8;
582    if (mBuffer->capacity() < neededSize) {
583        // Increment in multiples of 64K.
584        neededSize = (neededSize + 65535) & ~65535;
585
586        ALOGI("resizing buffer to %zu bytes", neededSize);
587
588        sp<ABuffer> newBuffer = new ABuffer(neededSize);
589        memcpy(newBuffer->data(), mBuffer->data(), mBuffer->size());
590        newBuffer->setRange(0, mBuffer->size());
591        mBuffer = newBuffer;
592    }
593
594    memcpy(mBuffer->data() + mBuffer->size(), br->data(), payloadSizeBits / 8);
595    mBuffer->setRange(0, mBuffer->size() + payloadSizeBits / 8);
596
597    return OK;
598}
599
600bool ATSParser::Stream::isVideo() const {
601    switch (mStreamType) {
602        case STREAMTYPE_H264:
603        case STREAMTYPE_MPEG1_VIDEO:
604        case STREAMTYPE_MPEG2_VIDEO:
605        case STREAMTYPE_MPEG4_VIDEO:
606            return true;
607
608        default:
609            return false;
610    }
611}
612
613bool ATSParser::Stream::isAudio() const {
614    switch (mStreamType) {
615        case STREAMTYPE_MPEG1_AUDIO:
616        case STREAMTYPE_MPEG2_AUDIO:
617        case STREAMTYPE_MPEG2_AUDIO_ADTS:
618        case STREAMTYPE_PCM_AUDIO:
619            return true;
620
621        default:
622            return false;
623    }
624}
625
626void ATSParser::Stream::signalDiscontinuity(
627        DiscontinuityType type, const sp<AMessage> &extra) {
628    mExpectedContinuityCounter = -1;
629
630    if (mQueue == NULL) {
631        return;
632    }
633
634    mPayloadStarted = false;
635    mBuffer->setRange(0, 0);
636
637    bool clearFormat = false;
638    if (isAudio()) {
639        if (type & DISCONTINUITY_AUDIO_FORMAT) {
640            clearFormat = true;
641        }
642    } else {
643        if (type & DISCONTINUITY_VIDEO_FORMAT) {
644            clearFormat = true;
645        }
646    }
647
648    mQueue->clear(clearFormat);
649
650    if (type & DISCONTINUITY_TIME) {
651        uint64_t resumeAtPTS;
652        if (extra != NULL
653                && extra->findInt64(
654                    IStreamListener::kKeyResumeAtPTS,
655                    (int64_t *)&resumeAtPTS)) {
656            int64_t resumeAtMediaTimeUs =
657                mProgram->convertPTSToTimestamp(resumeAtPTS);
658
659            extra->setInt64("resume-at-mediatimeUs", resumeAtMediaTimeUs);
660        }
661    }
662
663    if (mSource != NULL) {
664        mSource->queueDiscontinuity(type, extra);
665    }
666}
667
668void ATSParser::Stream::signalEOS(status_t finalResult) {
669    if (mSource != NULL) {
670        mSource->signalEOS(finalResult);
671    }
672}
673
674status_t ATSParser::Stream::parsePES(ABitReader *br) {
675    unsigned packet_startcode_prefix = br->getBits(24);
676
677    ALOGV("packet_startcode_prefix = 0x%08x", packet_startcode_prefix);
678
679    if (packet_startcode_prefix != 1) {
680        ALOGV("Supposedly payload_unit_start=1 unit does not start "
681             "with startcode.");
682
683        return ERROR_MALFORMED;
684    }
685
686    CHECK_EQ(packet_startcode_prefix, 0x000001u);
687
688    unsigned stream_id = br->getBits(8);
689    ALOGV("stream_id = 0x%02x", stream_id);
690
691    unsigned PES_packet_length = br->getBits(16);
692    ALOGV("PES_packet_length = %u", PES_packet_length);
693
694    if (stream_id != 0xbc  // program_stream_map
695            && stream_id != 0xbe  // padding_stream
696            && stream_id != 0xbf  // private_stream_2
697            && stream_id != 0xf0  // ECM
698            && stream_id != 0xf1  // EMM
699            && stream_id != 0xff  // program_stream_directory
700            && stream_id != 0xf2  // DSMCC
701            && stream_id != 0xf8) {  // H.222.1 type E
702        CHECK_EQ(br->getBits(2), 2u);
703
704        MY_LOGV("PES_scrambling_control = %u", br->getBits(2));
705        MY_LOGV("PES_priority = %u", br->getBits(1));
706        MY_LOGV("data_alignment_indicator = %u", br->getBits(1));
707        MY_LOGV("copyright = %u", br->getBits(1));
708        MY_LOGV("original_or_copy = %u", br->getBits(1));
709
710        unsigned PTS_DTS_flags = br->getBits(2);
711        ALOGV("PTS_DTS_flags = %u", PTS_DTS_flags);
712
713        unsigned ESCR_flag = br->getBits(1);
714        ALOGV("ESCR_flag = %u", ESCR_flag);
715
716        unsigned ES_rate_flag = br->getBits(1);
717        ALOGV("ES_rate_flag = %u", ES_rate_flag);
718
719        unsigned DSM_trick_mode_flag = br->getBits(1);
720        ALOGV("DSM_trick_mode_flag = %u", DSM_trick_mode_flag);
721
722        unsigned additional_copy_info_flag = br->getBits(1);
723        ALOGV("additional_copy_info_flag = %u", additional_copy_info_flag);
724
725        MY_LOGV("PES_CRC_flag = %u", br->getBits(1));
726        MY_LOGV("PES_extension_flag = %u", br->getBits(1));
727
728        unsigned PES_header_data_length = br->getBits(8);
729        ALOGV("PES_header_data_length = %u", PES_header_data_length);
730
731        unsigned optional_bytes_remaining = PES_header_data_length;
732
733        uint64_t PTS = 0, DTS = 0;
734
735        if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
736            CHECK_GE(optional_bytes_remaining, 5u);
737
738            CHECK_EQ(br->getBits(4), PTS_DTS_flags);
739
740            PTS = ((uint64_t)br->getBits(3)) << 30;
741            CHECK_EQ(br->getBits(1), 1u);
742            PTS |= ((uint64_t)br->getBits(15)) << 15;
743            CHECK_EQ(br->getBits(1), 1u);
744            PTS |= br->getBits(15);
745            CHECK_EQ(br->getBits(1), 1u);
746
747            ALOGV("PTS = 0x%016" PRIx64 " (%.2f)", PTS, PTS / 90000.0);
748
749            optional_bytes_remaining -= 5;
750
751            if (PTS_DTS_flags == 3) {
752                CHECK_GE(optional_bytes_remaining, 5u);
753
754                CHECK_EQ(br->getBits(4), 1u);
755
756                DTS = ((uint64_t)br->getBits(3)) << 30;
757                CHECK_EQ(br->getBits(1), 1u);
758                DTS |= ((uint64_t)br->getBits(15)) << 15;
759                CHECK_EQ(br->getBits(1), 1u);
760                DTS |= br->getBits(15);
761                CHECK_EQ(br->getBits(1), 1u);
762
763                ALOGV("DTS = %" PRIu64, DTS);
764
765                optional_bytes_remaining -= 5;
766            }
767        }
768
769        if (ESCR_flag) {
770            CHECK_GE(optional_bytes_remaining, 6u);
771
772            br->getBits(2);
773
774            uint64_t ESCR = ((uint64_t)br->getBits(3)) << 30;
775            CHECK_EQ(br->getBits(1), 1u);
776            ESCR |= ((uint64_t)br->getBits(15)) << 15;
777            CHECK_EQ(br->getBits(1), 1u);
778            ESCR |= br->getBits(15);
779            CHECK_EQ(br->getBits(1), 1u);
780
781            ALOGV("ESCR = %" PRIu64, ESCR);
782            MY_LOGV("ESCR_extension = %u", br->getBits(9));
783
784            CHECK_EQ(br->getBits(1), 1u);
785
786            optional_bytes_remaining -= 6;
787        }
788
789        if (ES_rate_flag) {
790            CHECK_GE(optional_bytes_remaining, 3u);
791
792            CHECK_EQ(br->getBits(1), 1u);
793            MY_LOGV("ES_rate = %u", br->getBits(22));
794            CHECK_EQ(br->getBits(1), 1u);
795
796            optional_bytes_remaining -= 3;
797        }
798
799        br->skipBits(optional_bytes_remaining * 8);
800
801        // ES data follows.
802
803        if (PES_packet_length != 0) {
804            CHECK_GE(PES_packet_length, PES_header_data_length + 3);
805
806            unsigned dataLength =
807                PES_packet_length - 3 - PES_header_data_length;
808
809            if (br->numBitsLeft() < dataLength * 8) {
810                ALOGE("PES packet does not carry enough data to contain "
811                     "payload. (numBitsLeft = %zu, required = %u)",
812                     br->numBitsLeft(), dataLength * 8);
813
814                return ERROR_MALFORMED;
815            }
816
817            CHECK_GE(br->numBitsLeft(), dataLength * 8);
818
819            onPayloadData(
820                    PTS_DTS_flags, PTS, DTS, br->data(), dataLength);
821
822            br->skipBits(dataLength * 8);
823        } else {
824            onPayloadData(
825                    PTS_DTS_flags, PTS, DTS,
826                    br->data(), br->numBitsLeft() / 8);
827
828            size_t payloadSizeBits = br->numBitsLeft();
829            CHECK_EQ(payloadSizeBits % 8, 0u);
830
831            ALOGV("There's %zu bytes of payload.", payloadSizeBits / 8);
832        }
833    } else if (stream_id == 0xbe) {  // padding_stream
834        CHECK_NE(PES_packet_length, 0u);
835        br->skipBits(PES_packet_length * 8);
836    } else {
837        CHECK_NE(PES_packet_length, 0u);
838        br->skipBits(PES_packet_length * 8);
839    }
840
841    return OK;
842}
843
844status_t ATSParser::Stream::flush() {
845    if (mBuffer->size() == 0) {
846        return OK;
847    }
848
849    ALOGV("flushing stream 0x%04x size = %zu", mElementaryPID, mBuffer->size());
850
851    ABitReader br(mBuffer->data(), mBuffer->size());
852
853    status_t err = parsePES(&br);
854
855    mBuffer->setRange(0, 0);
856
857    return err;
858}
859
860void ATSParser::Stream::onPayloadData(
861        unsigned PTS_DTS_flags, uint64_t PTS, uint64_t /* DTS */,
862        const uint8_t *data, size_t size) {
863#if 0
864    ALOGI("payload streamType 0x%02x, PTS = 0x%016llx, dPTS = %lld",
865          mStreamType,
866          PTS,
867          (int64_t)PTS - mPrevPTS);
868    mPrevPTS = PTS;
869#endif
870
871    ALOGV("onPayloadData mStreamType=0x%02x", mStreamType);
872
873    int64_t timeUs = 0ll;  // no presentation timestamp available.
874    if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
875        timeUs = mProgram->convertPTSToTimestamp(PTS);
876    }
877
878    status_t err = mQueue->appendData(data, size, timeUs);
879
880    if (err != OK) {
881        return;
882    }
883
884    sp<ABuffer> accessUnit;
885    while ((accessUnit = mQueue->dequeueAccessUnit()) != NULL) {
886        if (mSource == NULL) {
887            sp<MetaData> meta = mQueue->getFormat();
888
889            if (meta != NULL) {
890                ALOGV("Stream PID 0x%08x of type 0x%02x now has data.",
891                     mElementaryPID, mStreamType);
892
893                mSource = new AnotherPacketSource(meta);
894                mSource->queueAccessUnit(accessUnit);
895            }
896        } else if (mQueue->getFormat() != NULL) {
897            // After a discontinuity we invalidate the queue's format
898            // and won't enqueue any access units to the source until
899            // the queue has reestablished the new format.
900
901            if (mSource->getFormat() == NULL) {
902                mSource->setFormat(mQueue->getFormat());
903            }
904            mSource->queueAccessUnit(accessUnit);
905        }
906    }
907}
908
909sp<MediaSource> ATSParser::Stream::getSource(SourceType type) {
910    switch (type) {
911        case VIDEO:
912        {
913            if (isVideo()) {
914                return mSource;
915            }
916            break;
917        }
918
919        case AUDIO:
920        {
921            if (isAudio()) {
922                return mSource;
923            }
924            break;
925        }
926
927        default:
928            break;
929    }
930
931    return NULL;
932}
933
934////////////////////////////////////////////////////////////////////////////////
935
936ATSParser::ATSParser(uint32_t flags)
937    : mFlags(flags),
938      mAbsoluteTimeAnchorUs(-1ll),
939      mTimeOffsetValid(false),
940      mTimeOffsetUs(0ll),
941      mNumTSPacketsParsed(0),
942      mNumPCRs(0) {
943    mPSISections.add(0 /* PID */, new PSISection);
944}
945
946ATSParser::~ATSParser() {
947}
948
949status_t ATSParser::feedTSPacket(const void *data, size_t size) {
950    CHECK_EQ(size, kTSPacketSize);
951
952    ABitReader br((const uint8_t *)data, kTSPacketSize);
953    return parseTS(&br);
954}
955
956void ATSParser::signalDiscontinuity(
957        DiscontinuityType type, const sp<AMessage> &extra) {
958    int64_t mediaTimeUs;
959    if ((type & DISCONTINUITY_TIME)
960            && extra != NULL
961            && extra->findInt64(
962                IStreamListener::kKeyMediaTimeUs, &mediaTimeUs)) {
963        mAbsoluteTimeAnchorUs = mediaTimeUs;
964    } else if (type == DISCONTINUITY_ABSOLUTE_TIME) {
965        int64_t timeUs;
966        CHECK(extra->findInt64("timeUs", &timeUs));
967
968        CHECK(mPrograms.empty());
969        mAbsoluteTimeAnchorUs = timeUs;
970        return;
971    } else if (type == DISCONTINUITY_TIME_OFFSET) {
972        int64_t offset;
973        CHECK(extra->findInt64("offset", &offset));
974
975        mTimeOffsetValid = true;
976        mTimeOffsetUs = offset;
977        return;
978    }
979
980    for (size_t i = 0; i < mPrograms.size(); ++i) {
981        mPrograms.editItemAt(i)->signalDiscontinuity(type, extra);
982    }
983}
984
985void ATSParser::signalEOS(status_t finalResult) {
986    CHECK_NE(finalResult, (status_t)OK);
987
988    for (size_t i = 0; i < mPrograms.size(); ++i) {
989        mPrograms.editItemAt(i)->signalEOS(finalResult);
990    }
991}
992
993void ATSParser::parseProgramAssociationTable(ABitReader *br) {
994    unsigned table_id = br->getBits(8);
995    ALOGV("  table_id = %u", table_id);
996    CHECK_EQ(table_id, 0x00u);
997
998    unsigned section_syntax_indictor = br->getBits(1);
999    ALOGV("  section_syntax_indictor = %u", section_syntax_indictor);
1000    CHECK_EQ(section_syntax_indictor, 1u);
1001
1002    CHECK_EQ(br->getBits(1), 0u);
1003    MY_LOGV("  reserved = %u", br->getBits(2));
1004
1005    unsigned section_length = br->getBits(12);
1006    ALOGV("  section_length = %u", section_length);
1007    CHECK_EQ(section_length & 0xc00, 0u);
1008
1009    MY_LOGV("  transport_stream_id = %u", br->getBits(16));
1010    MY_LOGV("  reserved = %u", br->getBits(2));
1011    MY_LOGV("  version_number = %u", br->getBits(5));
1012    MY_LOGV("  current_next_indicator = %u", br->getBits(1));
1013    MY_LOGV("  section_number = %u", br->getBits(8));
1014    MY_LOGV("  last_section_number = %u", br->getBits(8));
1015
1016    size_t numProgramBytes = (section_length - 5 /* header */ - 4 /* crc */);
1017    CHECK_EQ((numProgramBytes % 4), 0u);
1018
1019    for (size_t i = 0; i < numProgramBytes / 4; ++i) {
1020        unsigned program_number = br->getBits(16);
1021        ALOGV("    program_number = %u", program_number);
1022
1023        MY_LOGV("    reserved = %u", br->getBits(3));
1024
1025        if (program_number == 0) {
1026            MY_LOGV("    network_PID = 0x%04x", br->getBits(13));
1027        } else {
1028            unsigned programMapPID = br->getBits(13);
1029
1030            ALOGV("    program_map_PID = 0x%04x", programMapPID);
1031
1032            bool found = false;
1033            for (size_t index = 0; index < mPrograms.size(); ++index) {
1034                const sp<Program> &program = mPrograms.itemAt(index);
1035
1036                if (program->number() == program_number) {
1037                    program->updateProgramMapPID(programMapPID);
1038                    found = true;
1039                    break;
1040                }
1041            }
1042
1043            if (!found) {
1044                mPrograms.push(
1045                        new Program(this, program_number, programMapPID));
1046            }
1047
1048            if (mPSISections.indexOfKey(programMapPID) < 0) {
1049                mPSISections.add(programMapPID, new PSISection);
1050            }
1051        }
1052    }
1053
1054    MY_LOGV("  CRC = 0x%08x", br->getBits(32));
1055}
1056
1057status_t ATSParser::parsePID(
1058        ABitReader *br, unsigned PID,
1059        unsigned continuity_counter,
1060        unsigned payload_unit_start_indicator) {
1061    ssize_t sectionIndex = mPSISections.indexOfKey(PID);
1062
1063    if (sectionIndex >= 0) {
1064        sp<PSISection> section = mPSISections.valueAt(sectionIndex);
1065
1066        if (payload_unit_start_indicator) {
1067            CHECK(section->isEmpty());
1068
1069            unsigned skip = br->getBits(8);
1070            br->skipBits(skip * 8);
1071        }
1072
1073        CHECK((br->numBitsLeft() % 8) == 0);
1074        status_t err = section->append(br->data(), br->numBitsLeft() / 8);
1075
1076        if (err != OK) {
1077            return err;
1078        }
1079
1080        if (!section->isComplete()) {
1081            return OK;
1082        }
1083
1084        ABitReader sectionBits(section->data(), section->size());
1085
1086        if (PID == 0) {
1087            parseProgramAssociationTable(&sectionBits);
1088        } else {
1089            bool handled = false;
1090            for (size_t i = 0; i < mPrograms.size(); ++i) {
1091                status_t err;
1092                if (!mPrograms.editItemAt(i)->parsePSISection(
1093                            PID, &sectionBits, &err)) {
1094                    continue;
1095                }
1096
1097                if (err != OK) {
1098                    return err;
1099                }
1100
1101                handled = true;
1102                break;
1103            }
1104
1105            if (!handled) {
1106                mPSISections.removeItem(PID);
1107                section.clear();
1108            }
1109        }
1110
1111        if (section != NULL) {
1112            section->clear();
1113        }
1114
1115        return OK;
1116    }
1117
1118    bool handled = false;
1119    for (size_t i = 0; i < mPrograms.size(); ++i) {
1120        status_t err;
1121        if (mPrograms.editItemAt(i)->parsePID(
1122                    PID, continuity_counter, payload_unit_start_indicator,
1123                    br, &err)) {
1124            if (err != OK) {
1125                return err;
1126            }
1127
1128            handled = true;
1129            break;
1130        }
1131    }
1132
1133    if (!handled) {
1134        ALOGV("PID 0x%04x not handled.", PID);
1135    }
1136
1137    return OK;
1138}
1139
1140void ATSParser::parseAdaptationField(ABitReader *br, unsigned PID) {
1141    unsigned adaptation_field_length = br->getBits(8);
1142
1143    if (adaptation_field_length > 0) {
1144        unsigned discontinuity_indicator = br->getBits(1);
1145
1146        if (discontinuity_indicator) {
1147            ALOGV("PID 0x%04x: discontinuity_indicator = 1 (!!!)", PID);
1148        }
1149
1150        br->skipBits(2);
1151        unsigned PCR_flag = br->getBits(1);
1152
1153        size_t numBitsRead = 4;
1154
1155        if (PCR_flag) {
1156            br->skipBits(4);
1157            uint64_t PCR_base = br->getBits(32);
1158            PCR_base = (PCR_base << 1) | br->getBits(1);
1159
1160            br->skipBits(6);
1161            unsigned PCR_ext = br->getBits(9);
1162
1163            // The number of bytes from the start of the current
1164            // MPEG2 transport stream packet up and including
1165            // the final byte of this PCR_ext field.
1166            size_t byteOffsetFromStartOfTSPacket =
1167                (188 - br->numBitsLeft() / 8);
1168
1169            uint64_t PCR = PCR_base * 300 + PCR_ext;
1170
1171            ALOGV("PID 0x%04x: PCR = 0x%016" PRIx64 " (%.2f)",
1172                  PID, PCR, PCR / 27E6);
1173
1174            // The number of bytes received by this parser up to and
1175            // including the final byte of this PCR_ext field.
1176            size_t byteOffsetFromStart =
1177                mNumTSPacketsParsed * 188 + byteOffsetFromStartOfTSPacket;
1178
1179            for (size_t i = 0; i < mPrograms.size(); ++i) {
1180                updatePCR(PID, PCR, byteOffsetFromStart);
1181            }
1182
1183            numBitsRead += 52;
1184        }
1185
1186        CHECK_GE(adaptation_field_length * 8, numBitsRead);
1187
1188        br->skipBits(adaptation_field_length * 8 - numBitsRead);
1189    }
1190}
1191
1192status_t ATSParser::parseTS(ABitReader *br) {
1193    ALOGV("---");
1194
1195    unsigned sync_byte = br->getBits(8);
1196    CHECK_EQ(sync_byte, 0x47u);
1197
1198    if (br->getBits(1)) {  // transport_error_indicator
1199        // silently ignore.
1200        return OK;
1201    }
1202
1203    unsigned payload_unit_start_indicator = br->getBits(1);
1204    ALOGV("payload_unit_start_indicator = %u", payload_unit_start_indicator);
1205
1206    MY_LOGV("transport_priority = %u", br->getBits(1));
1207
1208    unsigned PID = br->getBits(13);
1209    ALOGV("PID = 0x%04x", PID);
1210
1211    MY_LOGV("transport_scrambling_control = %u", br->getBits(2));
1212
1213    unsigned adaptation_field_control = br->getBits(2);
1214    ALOGV("adaptation_field_control = %u", adaptation_field_control);
1215
1216    unsigned continuity_counter = br->getBits(4);
1217    ALOGV("PID = 0x%04x, continuity_counter = %u", PID, continuity_counter);
1218
1219    // ALOGI("PID = 0x%04x, continuity_counter = %u", PID, continuity_counter);
1220
1221    if (adaptation_field_control == 2 || adaptation_field_control == 3) {
1222        parseAdaptationField(br, PID);
1223    }
1224
1225    status_t err = OK;
1226
1227    if (adaptation_field_control == 1 || adaptation_field_control == 3) {
1228        err = parsePID(
1229                br, PID, continuity_counter, payload_unit_start_indicator);
1230    }
1231
1232    ++mNumTSPacketsParsed;
1233
1234    return err;
1235}
1236
1237sp<MediaSource> ATSParser::getSource(SourceType type) {
1238    int which = -1;  // any
1239
1240    for (size_t i = 0; i < mPrograms.size(); ++i) {
1241        const sp<Program> &program = mPrograms.editItemAt(i);
1242
1243        if (which >= 0 && (int)program->number() != which) {
1244            continue;
1245        }
1246
1247        sp<MediaSource> source = program->getSource(type);
1248
1249        if (source != NULL) {
1250            return source;
1251        }
1252    }
1253
1254    return NULL;
1255}
1256
1257bool ATSParser::PTSTimeDeltaEstablished() {
1258    if (mPrograms.isEmpty()) {
1259        return false;
1260    }
1261
1262    return mPrograms.editItemAt(0)->PTSTimeDeltaEstablished();
1263}
1264
1265void ATSParser::updatePCR(
1266        unsigned /* PID */, uint64_t PCR, size_t byteOffsetFromStart) {
1267    ALOGV("PCR 0x%016" PRIx64 " @ %zu", PCR, byteOffsetFromStart);
1268
1269    if (mNumPCRs == 2) {
1270        mPCR[0] = mPCR[1];
1271        mPCRBytes[0] = mPCRBytes[1];
1272        mSystemTimeUs[0] = mSystemTimeUs[1];
1273        mNumPCRs = 1;
1274    }
1275
1276    mPCR[mNumPCRs] = PCR;
1277    mPCRBytes[mNumPCRs] = byteOffsetFromStart;
1278    mSystemTimeUs[mNumPCRs] = ALooper::GetNowUs();
1279
1280    ++mNumPCRs;
1281
1282    if (mNumPCRs == 2) {
1283        double transportRate =
1284            (mPCRBytes[1] - mPCRBytes[0]) * 27E6 / (mPCR[1] - mPCR[0]);
1285
1286        ALOGV("transportRate = %.2f bytes/sec", transportRate);
1287    }
1288}
1289
1290////////////////////////////////////////////////////////////////////////////////
1291
1292ATSParser::PSISection::PSISection() {
1293}
1294
1295ATSParser::PSISection::~PSISection() {
1296}
1297
1298status_t ATSParser::PSISection::append(const void *data, size_t size) {
1299    if (mBuffer == NULL || mBuffer->size() + size > mBuffer->capacity()) {
1300        size_t newCapacity =
1301            (mBuffer == NULL) ? size : mBuffer->capacity() + size;
1302
1303        newCapacity = (newCapacity + 1023) & ~1023;
1304
1305        sp<ABuffer> newBuffer = new ABuffer(newCapacity);
1306
1307        if (mBuffer != NULL) {
1308            memcpy(newBuffer->data(), mBuffer->data(), mBuffer->size());
1309            newBuffer->setRange(0, mBuffer->size());
1310        } else {
1311            newBuffer->setRange(0, 0);
1312        }
1313
1314        mBuffer = newBuffer;
1315    }
1316
1317    memcpy(mBuffer->data() + mBuffer->size(), data, size);
1318    mBuffer->setRange(0, mBuffer->size() + size);
1319
1320    return OK;
1321}
1322
1323void ATSParser::PSISection::clear() {
1324    if (mBuffer != NULL) {
1325        mBuffer->setRange(0, 0);
1326    }
1327}
1328
1329bool ATSParser::PSISection::isComplete() const {
1330    if (mBuffer == NULL || mBuffer->size() < 3) {
1331        return false;
1332    }
1333
1334    unsigned sectionLength = U16_AT(mBuffer->data() + 1) & 0xfff;
1335    return mBuffer->size() >= sectionLength + 3;
1336}
1337
1338bool ATSParser::PSISection::isEmpty() const {
1339    return mBuffer == NULL || mBuffer->size() == 0;
1340}
1341
1342const uint8_t *ATSParser::PSISection::data() const {
1343    return mBuffer == NULL ? NULL : mBuffer->data();
1344}
1345
1346size_t ATSParser::PSISection::size() const {
1347    return mBuffer == NULL ? 0 : mBuffer->size();
1348}
1349
1350}  // namespace android
1351