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