Home | History | Annotate | Download | only in mpeg2ts
      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/IStreamSource.h>
     36 #include <utils/KeyedVector.h>
     37 
     38 namespace android {
     39 
     40 // I want the expression "y" evaluated even if verbose logging is off.
     41 #define MY_LOGV(x, y) \
     42     do { unsigned tmp = y; LOGV(x, tmp); } while (0)
     43 
     44 static const size_t kTSPacketSize = 188;
     45 
     46 struct ATSParser::Program : public RefBase {
     47     Program(ATSParser *parser, unsigned programNumber, unsigned programMapPID);
     48 
     49     bool parsePID(
     50             unsigned pid, unsigned payload_unit_start_indicator,
     51             ABitReader *br, status_t *err);
     52 
     53     void signalDiscontinuity(
     54             DiscontinuityType type, const sp<AMessage> &extra);
     55 
     56     void signalEOS(status_t finalResult);
     57 
     58     sp<MediaSource> getSource(SourceType type);
     59 
     60     int64_t convertPTSToTimestamp(uint64_t PTS);
     61 
     62     bool PTSTimeDeltaEstablished() const {
     63         return mFirstPTSValid;
     64     }
     65 
     66     unsigned number() const { return mProgramNumber; }
     67 
     68     void updateProgramMapPID(unsigned programMapPID) {
     69         mProgramMapPID = programMapPID;
     70     }
     71 
     72 private:
     73     ATSParser *mParser;
     74     unsigned mProgramNumber;
     75     unsigned mProgramMapPID;
     76     KeyedVector<unsigned, sp<Stream> > mStreams;
     77     bool mFirstPTSValid;
     78     uint64_t mFirstPTS;
     79 
     80     status_t parseProgramMap(ABitReader *br);
     81 
     82     DISALLOW_EVIL_CONSTRUCTORS(Program);
     83 };
     84 
     85 struct ATSParser::Stream : public RefBase {
     86     Stream(Program *program, unsigned elementaryPID, unsigned streamType);
     87 
     88     unsigned type() const { return mStreamType; }
     89     unsigned pid() const { return mElementaryPID; }
     90     void setPID(unsigned pid) { mElementaryPID = pid; }
     91 
     92     status_t parse(
     93             unsigned payload_unit_start_indicator,
     94             ABitReader *br);
     95 
     96     void signalDiscontinuity(
     97             DiscontinuityType type, const sp<AMessage> &extra);
     98 
     99     void signalEOS(status_t finalResult);
    100 
    101     sp<MediaSource> getSource(SourceType type);
    102 
    103 protected:
    104     virtual ~Stream();
    105 
    106 private:
    107     Program *mProgram;
    108     unsigned mElementaryPID;
    109     unsigned mStreamType;
    110 
    111     sp<ABuffer> mBuffer;
    112     sp<AnotherPacketSource> mSource;
    113     bool mPayloadStarted;
    114 
    115     ElementaryStreamQueue *mQueue;
    116 
    117     status_t flush();
    118     status_t parsePES(ABitReader *br);
    119 
    120     void onPayloadData(
    121             unsigned PTS_DTS_flags, uint64_t PTS, uint64_t DTS,
    122             const uint8_t *data, size_t size);
    123 
    124     void extractAACFrames(const sp<ABuffer> &buffer);
    125 
    126     DISALLOW_EVIL_CONSTRUCTORS(Stream);
    127 };
    128 
    129 ////////////////////////////////////////////////////////////////////////////////
    130 
    131 ATSParser::Program::Program(
    132         ATSParser *parser, unsigned programNumber, unsigned programMapPID)
    133     : mParser(parser),
    134       mProgramNumber(programNumber),
    135       mProgramMapPID(programMapPID),
    136       mFirstPTSValid(false),
    137       mFirstPTS(0) {
    138     LOGV("new program number %u", programNumber);
    139 }
    140 
    141 bool ATSParser::Program::parsePID(
    142         unsigned pid, unsigned payload_unit_start_indicator,
    143         ABitReader *br, status_t *err) {
    144     *err = OK;
    145 
    146     if (pid == mProgramMapPID) {
    147         if (payload_unit_start_indicator) {
    148             unsigned skip = br->getBits(8);
    149             br->skipBits(skip * 8);
    150         }
    151 
    152         *err = parseProgramMap(br);
    153 
    154         return true;
    155     }
    156 
    157     ssize_t index = mStreams.indexOfKey(pid);
    158     if (index < 0) {
    159         return false;
    160     }
    161 
    162     *err = mStreams.editValueAt(index)->parse(
    163             payload_unit_start_indicator, br);
    164 
    165     return true;
    166 }
    167 
    168 void ATSParser::Program::signalDiscontinuity(
    169         DiscontinuityType type, const sp<AMessage> &extra) {
    170     for (size_t i = 0; i < mStreams.size(); ++i) {
    171         mStreams.editValueAt(i)->signalDiscontinuity(type, extra);
    172     }
    173 }
    174 
    175 void ATSParser::Program::signalEOS(status_t finalResult) {
    176     for (size_t i = 0; i < mStreams.size(); ++i) {
    177         mStreams.editValueAt(i)->signalEOS(finalResult);
    178     }
    179 }
    180 
    181 struct StreamInfo {
    182     unsigned mType;
    183     unsigned mPID;
    184 };
    185 
    186 status_t ATSParser::Program::parseProgramMap(ABitReader *br) {
    187     unsigned table_id = br->getBits(8);
    188     LOGV("  table_id = %u", table_id);
    189     CHECK_EQ(table_id, 0x02u);
    190 
    191     unsigned section_syntax_indicator = br->getBits(1);
    192     LOGV("  section_syntax_indicator = %u", section_syntax_indicator);
    193     CHECK_EQ(section_syntax_indicator, 1u);
    194 
    195     CHECK_EQ(br->getBits(1), 0u);
    196     MY_LOGV("  reserved = %u", br->getBits(2));
    197 
    198     unsigned section_length = br->getBits(12);
    199     LOGV("  section_length = %u", section_length);
    200     CHECK_EQ(section_length & 0xc00, 0u);
    201     CHECK_LE(section_length, 1021u);
    202 
    203     MY_LOGV("  program_number = %u", br->getBits(16));
    204     MY_LOGV("  reserved = %u", br->getBits(2));
    205     MY_LOGV("  version_number = %u", br->getBits(5));
    206     MY_LOGV("  current_next_indicator = %u", br->getBits(1));
    207     MY_LOGV("  section_number = %u", br->getBits(8));
    208     MY_LOGV("  last_section_number = %u", br->getBits(8));
    209     MY_LOGV("  reserved = %u", br->getBits(3));
    210     MY_LOGV("  PCR_PID = 0x%04x", br->getBits(13));
    211     MY_LOGV("  reserved = %u", br->getBits(4));
    212 
    213     unsigned program_info_length = br->getBits(12);
    214     LOGV("  program_info_length = %u", program_info_length);
    215     CHECK_EQ(program_info_length & 0xc00, 0u);
    216 
    217     br->skipBits(program_info_length * 8);  // skip descriptors
    218 
    219     Vector<StreamInfo> infos;
    220 
    221     // infoBytesRemaining is the number of bytes that make up the
    222     // variable length section of ES_infos. It does not include the
    223     // final CRC.
    224     size_t infoBytesRemaining = section_length - 9 - program_info_length - 4;
    225 
    226     while (infoBytesRemaining > 0) {
    227         CHECK_GE(infoBytesRemaining, 5u);
    228 
    229         unsigned streamType = br->getBits(8);
    230         LOGV("    stream_type = 0x%02x", streamType);
    231 
    232         MY_LOGV("    reserved = %u", br->getBits(3));
    233 
    234         unsigned elementaryPID = br->getBits(13);
    235         LOGV("    elementary_PID = 0x%04x", elementaryPID);
    236 
    237         MY_LOGV("    reserved = %u", br->getBits(4));
    238 
    239         unsigned ES_info_length = br->getBits(12);
    240         LOGV("    ES_info_length = %u", ES_info_length);
    241         CHECK_EQ(ES_info_length & 0xc00, 0u);
    242 
    243         CHECK_GE(infoBytesRemaining - 5, ES_info_length);
    244 
    245 #if 0
    246         br->skipBits(ES_info_length * 8);  // skip descriptors
    247 #else
    248         unsigned info_bytes_remaining = ES_info_length;
    249         while (info_bytes_remaining >= 2) {
    250             MY_LOGV("      tag = 0x%02x", br->getBits(8));
    251 
    252             unsigned descLength = br->getBits(8);
    253             LOGV("      len = %u", descLength);
    254 
    255             CHECK_GE(info_bytes_remaining, 2 + descLength);
    256 
    257             br->skipBits(descLength * 8);
    258 
    259             info_bytes_remaining -= descLength + 2;
    260         }
    261         CHECK_EQ(info_bytes_remaining, 0u);
    262 #endif
    263 
    264         StreamInfo info;
    265         info.mType = streamType;
    266         info.mPID = elementaryPID;
    267         infos.push(info);
    268 
    269         infoBytesRemaining -= 5 + ES_info_length;
    270     }
    271 
    272     CHECK_EQ(infoBytesRemaining, 0u);
    273     MY_LOGV("  CRC = 0x%08x", br->getBits(32));
    274 
    275     bool PIDsChanged = false;
    276     for (size_t i = 0; i < infos.size(); ++i) {
    277         StreamInfo &info = infos.editItemAt(i);
    278 
    279         ssize_t index = mStreams.indexOfKey(info.mPID);
    280 
    281         if (index >= 0 && mStreams.editValueAt(index)->type() != info.mType) {
    282             LOGI("uh oh. stream PIDs have changed.");
    283             PIDsChanged = true;
    284             break;
    285         }
    286     }
    287 
    288     if (PIDsChanged) {
    289 #if 0
    290         LOGI("before:");
    291         for (size_t i = 0; i < mStreams.size(); ++i) {
    292             sp<Stream> stream = mStreams.editValueAt(i);
    293 
    294             LOGI("PID 0x%08x => type 0x%02x", stream->pid(), stream->type());
    295         }
    296 
    297         LOGI("after:");
    298         for (size_t i = 0; i < infos.size(); ++i) {
    299             StreamInfo &info = infos.editItemAt(i);
    300 
    301             LOGI("PID 0x%08x => type 0x%02x", info.mPID, info.mType);
    302         }
    303 #endif
    304 
    305         // The only case we can recover from is if we have two streams
    306         // and they switched PIDs.
    307 
    308         bool success = false;
    309 
    310         if (mStreams.size() == 2 && infos.size() == 2) {
    311             const StreamInfo &info1 = infos.itemAt(0);
    312             const StreamInfo &info2 = infos.itemAt(1);
    313 
    314             sp<Stream> s1 = mStreams.editValueAt(0);
    315             sp<Stream> s2 = mStreams.editValueAt(1);
    316 
    317             bool caseA =
    318                 info1.mPID == s1->pid() && info1.mType == s2->type()
    319                     && info2.mPID == s2->pid() && info2.mType == s1->type();
    320 
    321             bool caseB =
    322                 info1.mPID == s2->pid() && info1.mType == s1->type()
    323                     && info2.mPID == s1->pid() && info2.mType == s2->type();
    324 
    325             if (caseA || caseB) {
    326                 unsigned pid1 = s1->pid();
    327                 unsigned pid2 = s2->pid();
    328                 s1->setPID(pid2);
    329                 s2->setPID(pid1);
    330 
    331                 mStreams.clear();
    332                 mStreams.add(s1->pid(), s1);
    333                 mStreams.add(s2->pid(), s2);
    334 
    335                 success = true;
    336             }
    337         }
    338 
    339         if (!success) {
    340             LOGI("Stream PIDs changed and we cannot recover.");
    341             return ERROR_MALFORMED;
    342         }
    343     }
    344 
    345     for (size_t i = 0; i < infos.size(); ++i) {
    346         StreamInfo &info = infos.editItemAt(i);
    347 
    348         ssize_t index = mStreams.indexOfKey(info.mPID);
    349 
    350         if (index < 0) {
    351             sp<Stream> stream = new Stream(this, info.mPID, info.mType);
    352             mStreams.add(info.mPID, stream);
    353         }
    354     }
    355 
    356     return OK;
    357 }
    358 
    359 sp<MediaSource> ATSParser::Program::getSource(SourceType type) {
    360     size_t index = (type == AUDIO) ? 0 : 0;
    361 
    362     for (size_t i = 0; i < mStreams.size(); ++i) {
    363         sp<MediaSource> source = mStreams.editValueAt(i)->getSource(type);
    364         if (source != NULL) {
    365             if (index == 0) {
    366                 return source;
    367             }
    368             --index;
    369         }
    370     }
    371 
    372     return NULL;
    373 }
    374 
    375 int64_t ATSParser::Program::convertPTSToTimestamp(uint64_t PTS) {
    376     if (!(mParser->mFlags & TS_TIMESTAMPS_ARE_ABSOLUTE)) {
    377         if (!mFirstPTSValid) {
    378             mFirstPTSValid = true;
    379             mFirstPTS = PTS;
    380             PTS = 0;
    381         } else if (PTS < mFirstPTS) {
    382             PTS = 0;
    383         } else {
    384             PTS -= mFirstPTS;
    385         }
    386     }
    387 
    388     return (PTS * 100) / 9;
    389 }
    390 
    391 ////////////////////////////////////////////////////////////////////////////////
    392 
    393 ATSParser::Stream::Stream(
    394         Program *program, unsigned elementaryPID, unsigned streamType)
    395     : mProgram(program),
    396       mElementaryPID(elementaryPID),
    397       mStreamType(streamType),
    398       mPayloadStarted(false),
    399       mQueue(NULL) {
    400     switch (mStreamType) {
    401         case STREAMTYPE_H264:
    402             mQueue = new ElementaryStreamQueue(ElementaryStreamQueue::H264);
    403             break;
    404         case STREAMTYPE_MPEG2_AUDIO_ATDS:
    405             mQueue = new ElementaryStreamQueue(ElementaryStreamQueue::AAC);
    406             break;
    407         case STREAMTYPE_MPEG1_AUDIO:
    408         case STREAMTYPE_MPEG2_AUDIO:
    409             mQueue = new ElementaryStreamQueue(
    410                     ElementaryStreamQueue::MPEG_AUDIO);
    411             break;
    412 
    413         case STREAMTYPE_MPEG1_VIDEO:
    414         case STREAMTYPE_MPEG2_VIDEO:
    415             mQueue = new ElementaryStreamQueue(
    416                     ElementaryStreamQueue::MPEG_VIDEO);
    417             break;
    418 
    419         case STREAMTYPE_MPEG4_VIDEO:
    420             mQueue = new ElementaryStreamQueue(
    421                     ElementaryStreamQueue::MPEG4_VIDEO);
    422             break;
    423 
    424         default:
    425             break;
    426     }
    427 
    428     LOGV("new stream PID 0x%02x, type 0x%02x", elementaryPID, streamType);
    429 
    430     if (mQueue != NULL) {
    431         mBuffer = new ABuffer(192 * 1024);
    432         mBuffer->setRange(0, 0);
    433     }
    434 }
    435 
    436 ATSParser::Stream::~Stream() {
    437     delete mQueue;
    438     mQueue = NULL;
    439 }
    440 
    441 status_t ATSParser::Stream::parse(
    442         unsigned payload_unit_start_indicator, ABitReader *br) {
    443     if (mQueue == NULL) {
    444         return OK;
    445     }
    446 
    447     if (payload_unit_start_indicator) {
    448         if (mPayloadStarted) {
    449             // Otherwise we run the danger of receiving the trailing bytes
    450             // of a PES packet that we never saw the start of and assuming
    451             // we have a a complete PES packet.
    452 
    453             status_t err = flush();
    454 
    455             if (err != OK) {
    456                 return err;
    457             }
    458         }
    459 
    460         mPayloadStarted = true;
    461     }
    462 
    463     if (!mPayloadStarted) {
    464         return OK;
    465     }
    466 
    467     size_t payloadSizeBits = br->numBitsLeft();
    468     CHECK_EQ(payloadSizeBits % 8, 0u);
    469 
    470     size_t neededSize = mBuffer->size() + payloadSizeBits / 8;
    471     if (mBuffer->capacity() < neededSize) {
    472         // Increment in multiples of 64K.
    473         neededSize = (neededSize + 65535) & ~65535;
    474 
    475         LOGI("resizing buffer to %d bytes", neededSize);
    476 
    477         sp<ABuffer> newBuffer = new ABuffer(neededSize);
    478         memcpy(newBuffer->data(), mBuffer->data(), mBuffer->size());
    479         newBuffer->setRange(0, mBuffer->size());
    480         mBuffer = newBuffer;
    481     }
    482 
    483     memcpy(mBuffer->data() + mBuffer->size(), br->data(), payloadSizeBits / 8);
    484     mBuffer->setRange(0, mBuffer->size() + payloadSizeBits / 8);
    485 
    486     return OK;
    487 }
    488 
    489 void ATSParser::Stream::signalDiscontinuity(
    490         DiscontinuityType type, const sp<AMessage> &extra) {
    491     if (mQueue == NULL) {
    492         return;
    493     }
    494 
    495     mPayloadStarted = false;
    496     mBuffer->setRange(0, 0);
    497 
    498     switch (type) {
    499         case DISCONTINUITY_SEEK:
    500         case DISCONTINUITY_FORMATCHANGE:
    501         {
    502             bool isASeek = (type == DISCONTINUITY_SEEK);
    503 
    504             mQueue->clear(!isASeek);
    505 
    506             uint64_t resumeAtPTS;
    507             if (extra != NULL
    508                     && extra->findInt64(
    509                         IStreamListener::kKeyResumeAtPTS,
    510                         (int64_t *)&resumeAtPTS)) {
    511                 int64_t resumeAtMediaTimeUs =
    512                     mProgram->convertPTSToTimestamp(resumeAtPTS);
    513 
    514                 extra->setInt64("resume-at-mediatimeUs", resumeAtMediaTimeUs);
    515             }
    516 
    517             if (mSource != NULL) {
    518                 mSource->queueDiscontinuity(type, extra);
    519             }
    520             break;
    521         }
    522 
    523         default:
    524             TRESPASS();
    525             break;
    526     }
    527 }
    528 
    529 void ATSParser::Stream::signalEOS(status_t finalResult) {
    530     if (mSource != NULL) {
    531         mSource->signalEOS(finalResult);
    532     }
    533 }
    534 
    535 status_t ATSParser::Stream::parsePES(ABitReader *br) {
    536     unsigned packet_startcode_prefix = br->getBits(24);
    537 
    538     LOGV("packet_startcode_prefix = 0x%08x", packet_startcode_prefix);
    539 
    540     if (packet_startcode_prefix != 1) {
    541         LOGV("Supposedly payload_unit_start=1 unit does not start "
    542              "with startcode.");
    543 
    544         return ERROR_MALFORMED;
    545     }
    546 
    547     CHECK_EQ(packet_startcode_prefix, 0x000001u);
    548 
    549     unsigned stream_id = br->getBits(8);
    550     LOGV("stream_id = 0x%02x", stream_id);
    551 
    552     unsigned PES_packet_length = br->getBits(16);
    553     LOGV("PES_packet_length = %u", PES_packet_length);
    554 
    555     if (stream_id != 0xbc  // program_stream_map
    556             && stream_id != 0xbe  // padding_stream
    557             && stream_id != 0xbf  // private_stream_2
    558             && stream_id != 0xf0  // ECM
    559             && stream_id != 0xf1  // EMM
    560             && stream_id != 0xff  // program_stream_directory
    561             && stream_id != 0xf2  // DSMCC
    562             && stream_id != 0xf8) {  // H.222.1 type E
    563         CHECK_EQ(br->getBits(2), 2u);
    564 
    565         MY_LOGV("PES_scrambling_control = %u", br->getBits(2));
    566         MY_LOGV("PES_priority = %u", br->getBits(1));
    567         MY_LOGV("data_alignment_indicator = %u", br->getBits(1));
    568         MY_LOGV("copyright = %u", br->getBits(1));
    569         MY_LOGV("original_or_copy = %u", br->getBits(1));
    570 
    571         unsigned PTS_DTS_flags = br->getBits(2);
    572         LOGV("PTS_DTS_flags = %u", PTS_DTS_flags);
    573 
    574         unsigned ESCR_flag = br->getBits(1);
    575         LOGV("ESCR_flag = %u", ESCR_flag);
    576 
    577         unsigned ES_rate_flag = br->getBits(1);
    578         LOGV("ES_rate_flag = %u", ES_rate_flag);
    579 
    580         unsigned DSM_trick_mode_flag = br->getBits(1);
    581         LOGV("DSM_trick_mode_flag = %u", DSM_trick_mode_flag);
    582 
    583         unsigned additional_copy_info_flag = br->getBits(1);
    584         LOGV("additional_copy_info_flag = %u", additional_copy_info_flag);
    585 
    586         MY_LOGV("PES_CRC_flag = %u", br->getBits(1));
    587         MY_LOGV("PES_extension_flag = %u", br->getBits(1));
    588 
    589         unsigned PES_header_data_length = br->getBits(8);
    590         LOGV("PES_header_data_length = %u", PES_header_data_length);
    591 
    592         unsigned optional_bytes_remaining = PES_header_data_length;
    593 
    594         uint64_t PTS = 0, DTS = 0;
    595 
    596         if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
    597             CHECK_GE(optional_bytes_remaining, 5u);
    598 
    599             CHECK_EQ(br->getBits(4), PTS_DTS_flags);
    600 
    601             PTS = ((uint64_t)br->getBits(3)) << 30;
    602             CHECK_EQ(br->getBits(1), 1u);
    603             PTS |= ((uint64_t)br->getBits(15)) << 15;
    604             CHECK_EQ(br->getBits(1), 1u);
    605             PTS |= br->getBits(15);
    606             CHECK_EQ(br->getBits(1), 1u);
    607 
    608             LOGV("PTS = %llu", PTS);
    609             // LOGI("PTS = %.2f secs", PTS / 90000.0f);
    610 
    611             optional_bytes_remaining -= 5;
    612 
    613             if (PTS_DTS_flags == 3) {
    614                 CHECK_GE(optional_bytes_remaining, 5u);
    615 
    616                 CHECK_EQ(br->getBits(4), 1u);
    617 
    618                 DTS = ((uint64_t)br->getBits(3)) << 30;
    619                 CHECK_EQ(br->getBits(1), 1u);
    620                 DTS |= ((uint64_t)br->getBits(15)) << 15;
    621                 CHECK_EQ(br->getBits(1), 1u);
    622                 DTS |= br->getBits(15);
    623                 CHECK_EQ(br->getBits(1), 1u);
    624 
    625                 LOGV("DTS = %llu", DTS);
    626 
    627                 optional_bytes_remaining -= 5;
    628             }
    629         }
    630 
    631         if (ESCR_flag) {
    632             CHECK_GE(optional_bytes_remaining, 6u);
    633 
    634             br->getBits(2);
    635 
    636             uint64_t ESCR = ((uint64_t)br->getBits(3)) << 30;
    637             CHECK_EQ(br->getBits(1), 1u);
    638             ESCR |= ((uint64_t)br->getBits(15)) << 15;
    639             CHECK_EQ(br->getBits(1), 1u);
    640             ESCR |= br->getBits(15);
    641             CHECK_EQ(br->getBits(1), 1u);
    642 
    643             LOGV("ESCR = %llu", ESCR);
    644             MY_LOGV("ESCR_extension = %u", br->getBits(9));
    645 
    646             CHECK_EQ(br->getBits(1), 1u);
    647 
    648             optional_bytes_remaining -= 6;
    649         }
    650 
    651         if (ES_rate_flag) {
    652             CHECK_GE(optional_bytes_remaining, 3u);
    653 
    654             CHECK_EQ(br->getBits(1), 1u);
    655             MY_LOGV("ES_rate = %u", br->getBits(22));
    656             CHECK_EQ(br->getBits(1), 1u);
    657 
    658             optional_bytes_remaining -= 3;
    659         }
    660 
    661         br->skipBits(optional_bytes_remaining * 8);
    662 
    663         // ES data follows.
    664 
    665         if (PES_packet_length != 0) {
    666             CHECK_GE(PES_packet_length, PES_header_data_length + 3);
    667 
    668             unsigned dataLength =
    669                 PES_packet_length - 3 - PES_header_data_length;
    670 
    671             if (br->numBitsLeft() < dataLength * 8) {
    672                 LOGE("PES packet does not carry enough data to contain "
    673                      "payload. (numBitsLeft = %d, required = %d)",
    674                      br->numBitsLeft(), dataLength * 8);
    675 
    676                 return ERROR_MALFORMED;
    677             }
    678 
    679             CHECK_GE(br->numBitsLeft(), dataLength * 8);
    680 
    681             onPayloadData(
    682                     PTS_DTS_flags, PTS, DTS, br->data(), dataLength);
    683 
    684             br->skipBits(dataLength * 8);
    685         } else {
    686             onPayloadData(
    687                     PTS_DTS_flags, PTS, DTS,
    688                     br->data(), br->numBitsLeft() / 8);
    689 
    690             size_t payloadSizeBits = br->numBitsLeft();
    691             CHECK_EQ(payloadSizeBits % 8, 0u);
    692 
    693             LOGV("There's %d bytes of payload.", payloadSizeBits / 8);
    694         }
    695     } else if (stream_id == 0xbe) {  // padding_stream
    696         CHECK_NE(PES_packet_length, 0u);
    697         br->skipBits(PES_packet_length * 8);
    698     } else {
    699         CHECK_NE(PES_packet_length, 0u);
    700         br->skipBits(PES_packet_length * 8);
    701     }
    702 
    703     return OK;
    704 }
    705 
    706 status_t ATSParser::Stream::flush() {
    707     if (mBuffer->size() == 0) {
    708         return OK;
    709     }
    710 
    711     LOGV("flushing stream 0x%04x size = %d", mElementaryPID, mBuffer->size());
    712 
    713     ABitReader br(mBuffer->data(), mBuffer->size());
    714 
    715     status_t err = parsePES(&br);
    716 
    717     mBuffer->setRange(0, 0);
    718 
    719     return err;
    720 }
    721 
    722 void ATSParser::Stream::onPayloadData(
    723         unsigned PTS_DTS_flags, uint64_t PTS, uint64_t DTS,
    724         const uint8_t *data, size_t size) {
    725     LOGV("onPayloadData mStreamType=0x%02x", mStreamType);
    726 
    727     int64_t timeUs = 0ll;  // no presentation timestamp available.
    728     if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
    729         timeUs = mProgram->convertPTSToTimestamp(PTS);
    730     }
    731 
    732     status_t err = mQueue->appendData(data, size, timeUs);
    733 
    734     if (err != OK) {
    735         return;
    736     }
    737 
    738     sp<ABuffer> accessUnit;
    739     while ((accessUnit = mQueue->dequeueAccessUnit()) != NULL) {
    740         if (mSource == NULL) {
    741             sp<MetaData> meta = mQueue->getFormat();
    742 
    743             if (meta != NULL) {
    744                 LOGV("Stream PID 0x%08x of type 0x%02x now has data.",
    745                      mElementaryPID, mStreamType);
    746 
    747                 mSource = new AnotherPacketSource(meta);
    748                 mSource->queueAccessUnit(accessUnit);
    749             }
    750         } else if (mQueue->getFormat() != NULL) {
    751             // After a discontinuity we invalidate the queue's format
    752             // and won't enqueue any access units to the source until
    753             // the queue has reestablished the new format.
    754 
    755             if (mSource->getFormat() == NULL) {
    756                 mSource->setFormat(mQueue->getFormat());
    757             }
    758             mSource->queueAccessUnit(accessUnit);
    759         }
    760     }
    761 }
    762 
    763 sp<MediaSource> ATSParser::Stream::getSource(SourceType type) {
    764     switch (type) {
    765         case VIDEO:
    766         {
    767             if (mStreamType == STREAMTYPE_H264
    768                     || mStreamType == STREAMTYPE_MPEG1_VIDEO
    769                     || mStreamType == STREAMTYPE_MPEG2_VIDEO
    770                     || mStreamType == STREAMTYPE_MPEG4_VIDEO) {
    771                 return mSource;
    772             }
    773             break;
    774         }
    775 
    776         case AUDIO:
    777         {
    778             if (mStreamType == STREAMTYPE_MPEG1_AUDIO
    779                     || mStreamType == STREAMTYPE_MPEG2_AUDIO
    780                     || mStreamType == STREAMTYPE_MPEG2_AUDIO_ATDS) {
    781                 return mSource;
    782             }
    783             break;
    784         }
    785 
    786         default:
    787             break;
    788     }
    789 
    790     return NULL;
    791 }
    792 
    793 ////////////////////////////////////////////////////////////////////////////////
    794 
    795 ATSParser::ATSParser(uint32_t flags)
    796     : mFlags(flags) {
    797 }
    798 
    799 ATSParser::~ATSParser() {
    800 }
    801 
    802 status_t ATSParser::feedTSPacket(const void *data, size_t size) {
    803     CHECK_EQ(size, kTSPacketSize);
    804 
    805     ABitReader br((const uint8_t *)data, kTSPacketSize);
    806     return parseTS(&br);
    807 }
    808 
    809 void ATSParser::signalDiscontinuity(
    810         DiscontinuityType type, const sp<AMessage> &extra) {
    811     for (size_t i = 0; i < mPrograms.size(); ++i) {
    812         mPrograms.editItemAt(i)->signalDiscontinuity(type, extra);
    813     }
    814 }
    815 
    816 void ATSParser::signalEOS(status_t finalResult) {
    817     CHECK_NE(finalResult, (status_t)OK);
    818 
    819     for (size_t i = 0; i < mPrograms.size(); ++i) {
    820         mPrograms.editItemAt(i)->signalEOS(finalResult);
    821     }
    822 }
    823 
    824 void ATSParser::parseProgramAssociationTable(ABitReader *br) {
    825     unsigned table_id = br->getBits(8);
    826     LOGV("  table_id = %u", table_id);
    827     CHECK_EQ(table_id, 0x00u);
    828 
    829     unsigned section_syntax_indictor = br->getBits(1);
    830     LOGV("  section_syntax_indictor = %u", section_syntax_indictor);
    831     CHECK_EQ(section_syntax_indictor, 1u);
    832 
    833     CHECK_EQ(br->getBits(1), 0u);
    834     MY_LOGV("  reserved = %u", br->getBits(2));
    835 
    836     unsigned section_length = br->getBits(12);
    837     LOGV("  section_length = %u", section_length);
    838     CHECK_EQ(section_length & 0xc00, 0u);
    839 
    840     MY_LOGV("  transport_stream_id = %u", br->getBits(16));
    841     MY_LOGV("  reserved = %u", br->getBits(2));
    842     MY_LOGV("  version_number = %u", br->getBits(5));
    843     MY_LOGV("  current_next_indicator = %u", br->getBits(1));
    844     MY_LOGV("  section_number = %u", br->getBits(8));
    845     MY_LOGV("  last_section_number = %u", br->getBits(8));
    846 
    847     size_t numProgramBytes = (section_length - 5 /* header */ - 4 /* crc */);
    848     CHECK_EQ((numProgramBytes % 4), 0u);
    849 
    850     for (size_t i = 0; i < numProgramBytes / 4; ++i) {
    851         unsigned program_number = br->getBits(16);
    852         LOGV("    program_number = %u", program_number);
    853 
    854         MY_LOGV("    reserved = %u", br->getBits(3));
    855 
    856         if (program_number == 0) {
    857             MY_LOGV("    network_PID = 0x%04x", br->getBits(13));
    858         } else {
    859             unsigned programMapPID = br->getBits(13);
    860 
    861             LOGV("    program_map_PID = 0x%04x", programMapPID);
    862 
    863             bool found = false;
    864             for (size_t index = 0; index < mPrograms.size(); ++index) {
    865                 const sp<Program> &program = mPrograms.itemAt(index);
    866 
    867                 if (program->number() == program_number) {
    868                     program->updateProgramMapPID(programMapPID);
    869                     found = true;
    870                     break;
    871                 }
    872             }
    873 
    874             if (!found) {
    875                 mPrograms.push(
    876                         new Program(this, program_number, programMapPID));
    877             }
    878         }
    879     }
    880 
    881     MY_LOGV("  CRC = 0x%08x", br->getBits(32));
    882 }
    883 
    884 status_t ATSParser::parsePID(
    885         ABitReader *br, unsigned PID,
    886         unsigned payload_unit_start_indicator) {
    887     if (PID == 0) {
    888         if (payload_unit_start_indicator) {
    889             unsigned skip = br->getBits(8);
    890             br->skipBits(skip * 8);
    891         }
    892         parseProgramAssociationTable(br);
    893         return OK;
    894     }
    895 
    896     bool handled = false;
    897     for (size_t i = 0; i < mPrograms.size(); ++i) {
    898         status_t err;
    899         if (mPrograms.editItemAt(i)->parsePID(
    900                     PID, payload_unit_start_indicator, br, &err)) {
    901             if (err != OK) {
    902                 return err;
    903             }
    904 
    905             handled = true;
    906             break;
    907         }
    908     }
    909 
    910     if (!handled) {
    911         LOGV("PID 0x%04x not handled.", PID);
    912     }
    913 
    914     return OK;
    915 }
    916 
    917 void ATSParser::parseAdaptationField(ABitReader *br) {
    918     unsigned adaptation_field_length = br->getBits(8);
    919     if (adaptation_field_length > 0) {
    920         br->skipBits(adaptation_field_length * 8);  // XXX
    921     }
    922 }
    923 
    924 status_t ATSParser::parseTS(ABitReader *br) {
    925     LOGV("---");
    926 
    927     unsigned sync_byte = br->getBits(8);
    928     CHECK_EQ(sync_byte, 0x47u);
    929 
    930     MY_LOGV("transport_error_indicator = %u", br->getBits(1));
    931 
    932     unsigned payload_unit_start_indicator = br->getBits(1);
    933     LOGV("payload_unit_start_indicator = %u", payload_unit_start_indicator);
    934 
    935     MY_LOGV("transport_priority = %u", br->getBits(1));
    936 
    937     unsigned PID = br->getBits(13);
    938     LOGV("PID = 0x%04x", PID);
    939 
    940     MY_LOGV("transport_scrambling_control = %u", br->getBits(2));
    941 
    942     unsigned adaptation_field_control = br->getBits(2);
    943     LOGV("adaptation_field_control = %u", adaptation_field_control);
    944 
    945     unsigned continuity_counter = br->getBits(4);
    946     LOGV("continuity_counter = %u", continuity_counter);
    947 
    948     // LOGI("PID = 0x%04x, continuity_counter = %u", PID, continuity_counter);
    949 
    950     if (adaptation_field_control == 2 || adaptation_field_control == 3) {
    951         parseAdaptationField(br);
    952     }
    953 
    954     if (adaptation_field_control == 1 || adaptation_field_control == 3) {
    955         return parsePID(br, PID, payload_unit_start_indicator);
    956     }
    957 
    958     return OK;
    959 }
    960 
    961 sp<MediaSource> ATSParser::getSource(SourceType type) {
    962     int which = -1;  // any
    963 
    964     for (size_t i = 0; i < mPrograms.size(); ++i) {
    965         const sp<Program> &program = mPrograms.editItemAt(i);
    966 
    967         if (which >= 0 && (int)program->number() != which) {
    968             continue;
    969         }
    970 
    971         sp<MediaSource> source = program->getSource(type);
    972 
    973         if (source != NULL) {
    974             return source;
    975         }
    976     }
    977 
    978     return NULL;
    979 }
    980 
    981 bool ATSParser::PTSTimeDeltaEstablished() {
    982     if (mPrograms.isEmpty()) {
    983         return false;
    984     }
    985 
    986     return mPrograms.editItemAt(0)->PTSTimeDeltaEstablished();
    987 }
    988 
    989 }  // namespace android
    990