Home | History | Annotate | Download | only in source
      1 /*
      2  * Copyright 2012, 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 "TSPacketizer"
     19 #include <utils/Log.h>
     20 
     21 #include "TSPacketizer.h"
     22 #include "include/avc_utils.h"
     23 
     24 #include <media/stagefright/foundation/ABuffer.h>
     25 #include <media/stagefright/foundation/ADebug.h>
     26 #include <media/stagefright/foundation/AMessage.h>
     27 #include <media/stagefright/foundation/hexdump.h>
     28 #include <media/stagefright/MediaDefs.h>
     29 #include <media/stagefright/MediaErrors.h>
     30 
     31 #include <arpa/inet.h>
     32 
     33 namespace android {
     34 
     35 struct TSPacketizer::Track : public RefBase {
     36     Track(const sp<AMessage> &format,
     37           unsigned PID, unsigned streamType, unsigned streamID);
     38 
     39     unsigned PID() const;
     40     unsigned streamType() const;
     41     unsigned streamID() const;
     42 
     43     // Returns the previous value.
     44     unsigned incrementContinuityCounter();
     45 
     46     bool isAudio() const;
     47     bool isVideo() const;
     48 
     49     bool isH264() const;
     50     bool isAAC() const;
     51     bool lacksADTSHeader() const;
     52     bool isPCMAudio() const;
     53 
     54     sp<ABuffer> prependCSD(const sp<ABuffer> &accessUnit) const;
     55     sp<ABuffer> prependADTSHeader(const sp<ABuffer> &accessUnit) const;
     56 
     57     size_t countDescriptors() const;
     58     sp<ABuffer> descriptorAt(size_t index) const;
     59 
     60     void finalize();
     61     void extractCSDIfNecessary();
     62 
     63 protected:
     64     virtual ~Track();
     65 
     66 private:
     67     sp<AMessage> mFormat;
     68 
     69     unsigned mPID;
     70     unsigned mStreamType;
     71     unsigned mStreamID;
     72     unsigned mContinuityCounter;
     73 
     74     AString mMIME;
     75     Vector<sp<ABuffer> > mCSD;
     76 
     77     Vector<sp<ABuffer> > mDescriptors;
     78 
     79     bool mAudioLacksATDSHeaders;
     80     bool mFinalized;
     81     bool mExtractedCSD;
     82 
     83     DISALLOW_EVIL_CONSTRUCTORS(Track);
     84 };
     85 
     86 TSPacketizer::Track::Track(
     87         const sp<AMessage> &format,
     88         unsigned PID, unsigned streamType, unsigned streamID)
     89     : mFormat(format),
     90       mPID(PID),
     91       mStreamType(streamType),
     92       mStreamID(streamID),
     93       mContinuityCounter(0),
     94       mAudioLacksATDSHeaders(false),
     95       mFinalized(false),
     96       mExtractedCSD(false) {
     97     CHECK(format->findString("mime", &mMIME));
     98 }
     99 
    100 void TSPacketizer::Track::extractCSDIfNecessary() {
    101     if (mExtractedCSD) {
    102         return;
    103     }
    104 
    105     if (!strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_VIDEO_AVC)
    106             || !strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
    107         for (size_t i = 0;; ++i) {
    108             sp<ABuffer> csd;
    109             if (!mFormat->findBuffer(StringPrintf("csd-%d", i).c_str(), &csd)) {
    110                 break;
    111             }
    112 
    113             mCSD.push(csd);
    114         }
    115 
    116         if (!strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
    117             int32_t isADTS;
    118             if (!mFormat->findInt32("is-adts", &isADTS) || isADTS == 0) {
    119                 mAudioLacksATDSHeaders = true;
    120             }
    121         }
    122     }
    123 
    124     mExtractedCSD = true;
    125 }
    126 
    127 TSPacketizer::Track::~Track() {
    128 }
    129 
    130 unsigned TSPacketizer::Track::PID() const {
    131     return mPID;
    132 }
    133 
    134 unsigned TSPacketizer::Track::streamType() const {
    135     return mStreamType;
    136 }
    137 
    138 unsigned TSPacketizer::Track::streamID() const {
    139     return mStreamID;
    140 }
    141 
    142 unsigned TSPacketizer::Track::incrementContinuityCounter() {
    143     unsigned prevCounter = mContinuityCounter;
    144 
    145     if (++mContinuityCounter == 16) {
    146         mContinuityCounter = 0;
    147     }
    148 
    149     return prevCounter;
    150 }
    151 
    152 bool TSPacketizer::Track::isAudio() const {
    153     return !strncasecmp("audio/", mMIME.c_str(), 6);
    154 }
    155 
    156 bool TSPacketizer::Track::isVideo() const {
    157     return !strncasecmp("video/", mMIME.c_str(), 6);
    158 }
    159 
    160 bool TSPacketizer::Track::isH264() const {
    161     return !strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_VIDEO_AVC);
    162 }
    163 
    164 bool TSPacketizer::Track::isAAC() const {
    165     return !strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_AUDIO_AAC);
    166 }
    167 
    168 bool TSPacketizer::Track::isPCMAudio() const {
    169     return !strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_AUDIO_RAW);
    170 }
    171 
    172 bool TSPacketizer::Track::lacksADTSHeader() const {
    173     return mAudioLacksATDSHeaders;
    174 }
    175 
    176 sp<ABuffer> TSPacketizer::Track::prependCSD(
    177         const sp<ABuffer> &accessUnit) const {
    178     size_t size = 0;
    179     for (size_t i = 0; i < mCSD.size(); ++i) {
    180         size += mCSD.itemAt(i)->size();
    181     }
    182 
    183     sp<ABuffer> dup = new ABuffer(accessUnit->size() + size);
    184     size_t offset = 0;
    185     for (size_t i = 0; i < mCSD.size(); ++i) {
    186         const sp<ABuffer> &csd = mCSD.itemAt(i);
    187 
    188         memcpy(dup->data() + offset, csd->data(), csd->size());
    189         offset += csd->size();
    190     }
    191 
    192     memcpy(dup->data() + offset, accessUnit->data(), accessUnit->size());
    193 
    194     return dup;
    195 }
    196 
    197 sp<ABuffer> TSPacketizer::Track::prependADTSHeader(
    198         const sp<ABuffer> &accessUnit) const {
    199     CHECK_EQ(mCSD.size(), 1u);
    200 
    201     const uint8_t *codec_specific_data = mCSD.itemAt(0)->data();
    202 
    203     const uint32_t aac_frame_length = accessUnit->size() + 7;
    204 
    205     sp<ABuffer> dup = new ABuffer(aac_frame_length);
    206 
    207     unsigned profile = (codec_specific_data[0] >> 3) - 1;
    208 
    209     unsigned sampling_freq_index =
    210         ((codec_specific_data[0] & 7) << 1)
    211         | (codec_specific_data[1] >> 7);
    212 
    213     unsigned channel_configuration =
    214         (codec_specific_data[1] >> 3) & 0x0f;
    215 
    216     uint8_t *ptr = dup->data();
    217 
    218     *ptr++ = 0xff;
    219     *ptr++ = 0xf1;  // b11110001, ID=0, layer=0, protection_absent=1
    220 
    221     *ptr++ =
    222         profile << 6
    223         | sampling_freq_index << 2
    224         | ((channel_configuration >> 2) & 1);  // private_bit=0
    225 
    226     // original_copy=0, home=0, copyright_id_bit=0, copyright_id_start=0
    227     *ptr++ =
    228         (channel_configuration & 3) << 6
    229         | aac_frame_length >> 11;
    230     *ptr++ = (aac_frame_length >> 3) & 0xff;
    231     *ptr++ = (aac_frame_length & 7) << 5;
    232 
    233     // adts_buffer_fullness=0, number_of_raw_data_blocks_in_frame=0
    234     *ptr++ = 0;
    235 
    236     memcpy(ptr, accessUnit->data(), accessUnit->size());
    237 
    238     return dup;
    239 }
    240 
    241 size_t TSPacketizer::Track::countDescriptors() const {
    242     return mDescriptors.size();
    243 }
    244 
    245 sp<ABuffer> TSPacketizer::Track::descriptorAt(size_t index) const {
    246     CHECK_LT(index, mDescriptors.size());
    247     return mDescriptors.itemAt(index);
    248 }
    249 
    250 void TSPacketizer::Track::finalize() {
    251     if (mFinalized) {
    252         return;
    253     }
    254 
    255     if (isH264()) {
    256         {
    257             // AVC video descriptor (40)
    258 
    259             sp<ABuffer> descriptor = new ABuffer(6);
    260             uint8_t *data = descriptor->data();
    261             data[0] = 40;  // descriptor_tag
    262             data[1] = 4;  // descriptor_length
    263 
    264             if (mCSD.size() > 0) {
    265                 CHECK_GE(mCSD.size(), 1u);
    266                 const sp<ABuffer> &sps = mCSD.itemAt(0);
    267                 CHECK(!memcmp("\x00\x00\x00\x01", sps->data(), 4));
    268                 CHECK_GE(sps->size(), 7u);
    269                 // profile_idc, constraint_set*, level_idc
    270                 memcpy(&data[2], sps->data() + 4, 3);
    271             } else {
    272                 int32_t profileIdc, levelIdc, constraintSet;
    273                 CHECK(mFormat->findInt32("profile-idc", &profileIdc));
    274                 CHECK(mFormat->findInt32("level-idc", &levelIdc));
    275                 CHECK(mFormat->findInt32("constraint-set", &constraintSet));
    276                 CHECK_GE(profileIdc, 0u);
    277                 CHECK_GE(levelIdc, 0u);
    278                 data[2] = profileIdc;    // profile_idc
    279                 data[3] = constraintSet; // constraint_set*
    280                 data[4] = levelIdc;      // level_idc
    281             }
    282 
    283             // AVC_still_present=0, AVC_24_hour_picture_flag=0, reserved
    284             data[5] = 0x3f;
    285 
    286             mDescriptors.push_back(descriptor);
    287         }
    288 
    289         {
    290             // AVC timing and HRD descriptor (42)
    291 
    292             sp<ABuffer> descriptor = new ABuffer(4);
    293             uint8_t *data = descriptor->data();
    294             data[0] = 42;  // descriptor_tag
    295             data[1] = 2;  // descriptor_length
    296 
    297             // hrd_management_valid_flag = 0
    298             // reserved = 111111b
    299             // picture_and_timing_info_present = 0
    300 
    301             data[2] = 0x7e;
    302 
    303             // fixed_frame_rate_flag = 0
    304             // temporal_poc_flag = 0
    305             // picture_to_display_conversion_flag = 0
    306             // reserved = 11111b
    307             data[3] = 0x1f;
    308 
    309             mDescriptors.push_back(descriptor);
    310         }
    311     } else if (isPCMAudio()) {
    312         // LPCM audio stream descriptor (0x83)
    313 
    314         int32_t channelCount;
    315         CHECK(mFormat->findInt32("channel-count", &channelCount));
    316         CHECK_EQ(channelCount, 2);
    317 
    318         int32_t sampleRate;
    319         CHECK(mFormat->findInt32("sample-rate", &sampleRate));
    320         CHECK(sampleRate == 44100 || sampleRate == 48000);
    321 
    322         sp<ABuffer> descriptor = new ABuffer(4);
    323         uint8_t *data = descriptor->data();
    324         data[0] = 0x83;  // descriptor_tag
    325         data[1] = 2;  // descriptor_length
    326 
    327         unsigned sampling_frequency = (sampleRate == 44100) ? 1 : 2;
    328 
    329         data[2] = (sampling_frequency << 5)
    330                     | (3 /* reserved */ << 1)
    331                     | 0 /* emphasis_flag */;
    332 
    333         data[3] =
    334             (1 /* number_of_channels = stereo */ << 5)
    335             | 0xf /* reserved */;
    336 
    337         mDescriptors.push_back(descriptor);
    338     }
    339 
    340     mFinalized = true;
    341 }
    342 
    343 ////////////////////////////////////////////////////////////////////////////////
    344 
    345 TSPacketizer::TSPacketizer(uint32_t flags)
    346     : mFlags(flags),
    347       mPATContinuityCounter(0),
    348       mPMTContinuityCounter(0) {
    349     initCrcTable();
    350 
    351     if (flags & (EMIT_HDCP20_DESCRIPTOR | EMIT_HDCP21_DESCRIPTOR)) {
    352         int32_t hdcpVersion;
    353         if (flags & EMIT_HDCP20_DESCRIPTOR) {
    354             CHECK(!(flags & EMIT_HDCP21_DESCRIPTOR));
    355             hdcpVersion = 0x20;
    356         } else {
    357             CHECK(!(flags & EMIT_HDCP20_DESCRIPTOR));
    358 
    359             // HDCP2.0 _and_ HDCP 2.1 specs say to set the version
    360             // inside the HDCP descriptor to 0x20!!!
    361             hdcpVersion = 0x20;
    362         }
    363 
    364         // HDCP descriptor
    365         sp<ABuffer> descriptor = new ABuffer(7);
    366         uint8_t *data = descriptor->data();
    367         data[0] = 0x05;  // descriptor_tag
    368         data[1] = 5;  // descriptor_length
    369         data[2] = 'H';
    370         data[3] = 'D';
    371         data[4] = 'C';
    372         data[5] = 'P';
    373         data[6] = hdcpVersion;
    374 
    375         mProgramInfoDescriptors.push_back(descriptor);
    376     }
    377 }
    378 
    379 TSPacketizer::~TSPacketizer() {
    380 }
    381 
    382 ssize_t TSPacketizer::addTrack(const sp<AMessage> &format) {
    383     AString mime;
    384     CHECK(format->findString("mime", &mime));
    385 
    386     unsigned PIDStart;
    387     bool isVideo = !strncasecmp("video/", mime.c_str(), 6);
    388     bool isAudio = !strncasecmp("audio/", mime.c_str(), 6);
    389 
    390     if (isVideo) {
    391         PIDStart = 0x1011;
    392     } else if (isAudio) {
    393         PIDStart = 0x1100;
    394     } else {
    395         return ERROR_UNSUPPORTED;
    396     }
    397 
    398     unsigned streamType;
    399     unsigned streamIDStart;
    400     unsigned streamIDStop;
    401 
    402     if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_VIDEO_AVC)) {
    403         streamType = 0x1b;
    404         streamIDStart = 0xe0;
    405         streamIDStop = 0xef;
    406     } else if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
    407         streamType = 0x0f;
    408         streamIDStart = 0xc0;
    409         streamIDStop = 0xdf;
    410     } else if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_RAW)) {
    411         streamType = 0x83;
    412         streamIDStart = 0xbd;
    413         streamIDStop = 0xbd;
    414     } else {
    415         return ERROR_UNSUPPORTED;
    416     }
    417 
    418     size_t numTracksOfThisType = 0;
    419     unsigned PID = PIDStart;
    420 
    421     for (size_t i = 0; i < mTracks.size(); ++i) {
    422         const sp<Track> &track = mTracks.itemAt(i);
    423 
    424         if (track->streamType() == streamType) {
    425             ++numTracksOfThisType;
    426         }
    427 
    428         if ((isAudio && track->isAudio()) || (isVideo && track->isVideo())) {
    429             ++PID;
    430         }
    431     }
    432 
    433     unsigned streamID = streamIDStart + numTracksOfThisType;
    434     if (streamID > streamIDStop) {
    435         return -ERANGE;
    436     }
    437 
    438     sp<Track> track = new Track(format, PID, streamType, streamID);
    439     return mTracks.add(track);
    440 }
    441 
    442 status_t TSPacketizer::extractCSDIfNecessary(size_t trackIndex) {
    443     if (trackIndex >= mTracks.size()) {
    444         return -ERANGE;
    445     }
    446 
    447     const sp<Track> &track = mTracks.itemAt(trackIndex);
    448     track->extractCSDIfNecessary();
    449 
    450     return OK;
    451 }
    452 
    453 status_t TSPacketizer::packetize(
    454         size_t trackIndex,
    455         const sp<ABuffer> &_accessUnit,
    456         sp<ABuffer> *packets,
    457         uint32_t flags,
    458         const uint8_t *PES_private_data, size_t PES_private_data_len,
    459         size_t numStuffingBytes) {
    460     sp<ABuffer> accessUnit = _accessUnit;
    461 
    462     int64_t timeUs;
    463     CHECK(accessUnit->meta()->findInt64("timeUs", &timeUs));
    464 
    465     packets->clear();
    466 
    467     if (trackIndex >= mTracks.size()) {
    468         return -ERANGE;
    469     }
    470 
    471     const sp<Track> &track = mTracks.itemAt(trackIndex);
    472 
    473     if (track->isH264() && (flags & PREPEND_SPS_PPS_TO_IDR_FRAMES)
    474             && IsIDR(accessUnit)) {
    475         // prepend codec specific data, i.e. SPS and PPS.
    476         accessUnit = track->prependCSD(accessUnit);
    477     } else if (track->isAAC() && track->lacksADTSHeader()) {
    478         CHECK(!(flags & IS_ENCRYPTED));
    479         accessUnit = track->prependADTSHeader(accessUnit);
    480     }
    481 
    482     // 0x47
    483     // transport_error_indicator = b0
    484     // payload_unit_start_indicator = b1
    485     // transport_priority = b0
    486     // PID
    487     // transport_scrambling_control = b00
    488     // adaptation_field_control = b??
    489     // continuity_counter = b????
    490     // -- payload follows
    491     // packet_startcode_prefix = 0x000001
    492     // stream_id
    493     // PES_packet_length = 0x????
    494     // reserved = b10
    495     // PES_scrambling_control = b00
    496     // PES_priority = b0
    497     // data_alignment_indicator = b1
    498     // copyright = b0
    499     // original_or_copy = b0
    500     // PTS_DTS_flags = b10  (PTS only)
    501     // ESCR_flag = b0
    502     // ES_rate_flag = b0
    503     // DSM_trick_mode_flag = b0
    504     // additional_copy_info_flag = b0
    505     // PES_CRC_flag = b0
    506     // PES_extension_flag = b0
    507     // PES_header_data_length = 0x05
    508     // reserved = b0010 (PTS)
    509     // PTS[32..30] = b???
    510     // reserved = b1
    511     // PTS[29..15] = b??? ???? ???? ???? (15 bits)
    512     // reserved = b1
    513     // PTS[14..0] = b??? ???? ???? ???? (15 bits)
    514     // reserved = b1
    515     // the first fragment of "buffer" follows
    516 
    517     // Each transport packet (except for the last one contributing to the PES
    518     // payload) must contain a multiple of 16 bytes of payload per HDCP spec.
    519     bool alignPayload =
    520         (mFlags & (EMIT_HDCP20_DESCRIPTOR | EMIT_HDCP21_DESCRIPTOR));
    521 
    522     /*
    523        a) The very first PES transport stream packet contains
    524 
    525        4 bytes of TS header
    526        ... padding
    527        14 bytes of static PES header
    528        PES_private_data_len + 1 bytes (only if PES_private_data_len > 0)
    529        numStuffingBytes bytes
    530 
    531        followed by the payload
    532 
    533        b) Subsequent PES transport stream packets contain
    534 
    535        4 bytes of TS header
    536        ... padding
    537 
    538        followed by the payload
    539     */
    540 
    541     size_t PES_packet_length = accessUnit->size() + 8 + numStuffingBytes;
    542     if (PES_private_data_len > 0) {
    543         PES_packet_length += PES_private_data_len + 1;
    544     }
    545 
    546     size_t numTSPackets = 1;
    547 
    548     {
    549         // Make sure the PES header fits into a single TS packet:
    550         size_t PES_header_size = 14 + numStuffingBytes;
    551         if (PES_private_data_len > 0) {
    552             PES_header_size += PES_private_data_len + 1;
    553         }
    554 
    555         CHECK_LE(PES_header_size, 188u - 4u);
    556 
    557         size_t sizeAvailableForPayload = 188 - 4 - PES_header_size;
    558         size_t numBytesOfPayload = accessUnit->size();
    559 
    560         if (numBytesOfPayload > sizeAvailableForPayload) {
    561             numBytesOfPayload = sizeAvailableForPayload;
    562 
    563             if (alignPayload && numBytesOfPayload > 16) {
    564                 numBytesOfPayload -= (numBytesOfPayload % 16);
    565             }
    566         }
    567 
    568         // size_t numPaddingBytes = sizeAvailableForPayload - numBytesOfPayload;
    569         ALOGV("packet 1 contains %zd padding bytes and %zd bytes of payload",
    570               numPaddingBytes, numBytesOfPayload);
    571 
    572         size_t numBytesOfPayloadRemaining = accessUnit->size() - numBytesOfPayload;
    573 
    574 #if 0
    575         // The following hopefully illustrates the logic that led to the
    576         // more efficient computation in the #else block...
    577 
    578         while (numBytesOfPayloadRemaining > 0) {
    579             size_t sizeAvailableForPayload = 188 - 4;
    580 
    581             size_t numBytesOfPayload = numBytesOfPayloadRemaining;
    582 
    583             if (numBytesOfPayload > sizeAvailableForPayload) {
    584                 numBytesOfPayload = sizeAvailableForPayload;
    585 
    586                 if (alignPayload && numBytesOfPayload > 16) {
    587                     numBytesOfPayload -= (numBytesOfPayload % 16);
    588                 }
    589             }
    590 
    591             size_t numPaddingBytes = sizeAvailableForPayload - numBytesOfPayload;
    592             ALOGI("packet %zd contains %zd padding bytes and %zd bytes of payload",
    593                     numTSPackets + 1, numPaddingBytes, numBytesOfPayload);
    594 
    595             numBytesOfPayloadRemaining -= numBytesOfPayload;
    596             ++numTSPackets;
    597         }
    598 #else
    599         // This is how many bytes of payload each subsequent TS packet
    600         // can contain at most.
    601         sizeAvailableForPayload = 188 - 4;
    602         size_t sizeAvailableForAlignedPayload = sizeAvailableForPayload;
    603         if (alignPayload) {
    604             // We're only going to use a subset of the available space
    605             // since we need to make each fragment a multiple of 16 in size.
    606             sizeAvailableForAlignedPayload -=
    607                 (sizeAvailableForAlignedPayload % 16);
    608         }
    609 
    610         size_t numFullTSPackets =
    611             numBytesOfPayloadRemaining / sizeAvailableForAlignedPayload;
    612 
    613         numTSPackets += numFullTSPackets;
    614 
    615         numBytesOfPayloadRemaining -=
    616             numFullTSPackets * sizeAvailableForAlignedPayload;
    617 
    618         // numBytesOfPayloadRemaining < sizeAvailableForAlignedPayload
    619         if (numFullTSPackets == 0 && numBytesOfPayloadRemaining > 0) {
    620             // There wasn't enough payload left to form a full aligned payload,
    621             // the last packet doesn't have to be aligned.
    622             ++numTSPackets;
    623         } else if (numFullTSPackets > 0
    624                 && numBytesOfPayloadRemaining
    625                     + sizeAvailableForAlignedPayload > sizeAvailableForPayload) {
    626             // The last packet emitted had a full aligned payload and together
    627             // with the bytes remaining does exceed the unaligned payload
    628             // size, so we need another packet.
    629             ++numTSPackets;
    630         }
    631 #endif
    632     }
    633 
    634     if (flags & EMIT_PAT_AND_PMT) {
    635         numTSPackets += 2;
    636     }
    637 
    638     if (flags & EMIT_PCR) {
    639         ++numTSPackets;
    640     }
    641 
    642     sp<ABuffer> buffer = new ABuffer(numTSPackets * 188);
    643     uint8_t *packetDataStart = buffer->data();
    644 
    645     if (flags & EMIT_PAT_AND_PMT) {
    646         // Program Association Table (PAT):
    647         // 0x47
    648         // transport_error_indicator = b0
    649         // payload_unit_start_indicator = b1
    650         // transport_priority = b0
    651         // PID = b0000000000000 (13 bits)
    652         // transport_scrambling_control = b00
    653         // adaptation_field_control = b01 (no adaptation field, payload only)
    654         // continuity_counter = b????
    655         // skip = 0x00
    656         // --- payload follows
    657         // table_id = 0x00
    658         // section_syntax_indicator = b1
    659         // must_be_zero = b0
    660         // reserved = b11
    661         // section_length = 0x00d
    662         // transport_stream_id = 0x0000
    663         // reserved = b11
    664         // version_number = b00001
    665         // current_next_indicator = b1
    666         // section_number = 0x00
    667         // last_section_number = 0x00
    668         //   one program follows:
    669         //   program_number = 0x0001
    670         //   reserved = b111
    671         //   program_map_PID = kPID_PMT (13 bits!)
    672         // CRC = 0x????????
    673 
    674         if (++mPATContinuityCounter == 16) {
    675             mPATContinuityCounter = 0;
    676         }
    677 
    678         uint8_t *ptr = packetDataStart;
    679         *ptr++ = 0x47;
    680         *ptr++ = 0x40;
    681         *ptr++ = 0x00;
    682         *ptr++ = 0x10 | mPATContinuityCounter;
    683         *ptr++ = 0x00;
    684 
    685         uint8_t *crcDataStart = ptr;
    686         *ptr++ = 0x00;
    687         *ptr++ = 0xb0;
    688         *ptr++ = 0x0d;
    689         *ptr++ = 0x00;
    690         *ptr++ = 0x00;
    691         *ptr++ = 0xc3;
    692         *ptr++ = 0x00;
    693         *ptr++ = 0x00;
    694         *ptr++ = 0x00;
    695         *ptr++ = 0x01;
    696         *ptr++ = 0xe0 | (kPID_PMT >> 8);
    697         *ptr++ = kPID_PMT & 0xff;
    698 
    699         CHECK_EQ(ptr - crcDataStart, 12);
    700         uint32_t crc = htonl(crc32(crcDataStart, ptr - crcDataStart));
    701         memcpy(ptr, &crc, 4);
    702         ptr += 4;
    703 
    704         size_t sizeLeft = packetDataStart + 188 - ptr;
    705         memset(ptr, 0xff, sizeLeft);
    706 
    707         packetDataStart += 188;
    708 
    709         // Program Map (PMT):
    710         // 0x47
    711         // transport_error_indicator = b0
    712         // payload_unit_start_indicator = b1
    713         // transport_priority = b0
    714         // PID = kPID_PMT (13 bits)
    715         // transport_scrambling_control = b00
    716         // adaptation_field_control = b01 (no adaptation field, payload only)
    717         // continuity_counter = b????
    718         // skip = 0x00
    719         // -- payload follows
    720         // table_id = 0x02
    721         // section_syntax_indicator = b1
    722         // must_be_zero = b0
    723         // reserved = b11
    724         // section_length = 0x???
    725         // program_number = 0x0001
    726         // reserved = b11
    727         // version_number = b00001
    728         // current_next_indicator = b1
    729         // section_number = 0x00
    730         // last_section_number = 0x00
    731         // reserved = b111
    732         // PCR_PID = kPCR_PID (13 bits)
    733         // reserved = b1111
    734         // program_info_length = 0x???
    735         //   program_info_descriptors follow
    736         // one or more elementary stream descriptions follow:
    737         //   stream_type = 0x??
    738         //   reserved = b111
    739         //   elementary_PID = b? ???? ???? ???? (13 bits)
    740         //   reserved = b1111
    741         //   ES_info_length = 0x000
    742         // CRC = 0x????????
    743 
    744         if (++mPMTContinuityCounter == 16) {
    745             mPMTContinuityCounter = 0;
    746         }
    747 
    748         ptr = packetDataStart;
    749         *ptr++ = 0x47;
    750         *ptr++ = 0x40 | (kPID_PMT >> 8);
    751         *ptr++ = kPID_PMT & 0xff;
    752         *ptr++ = 0x10 | mPMTContinuityCounter;
    753         *ptr++ = 0x00;
    754 
    755         crcDataStart = ptr;
    756         *ptr++ = 0x02;
    757 
    758         *ptr++ = 0x00;  // section_length to be filled in below.
    759         *ptr++ = 0x00;
    760 
    761         *ptr++ = 0x00;
    762         *ptr++ = 0x01;
    763         *ptr++ = 0xc3;
    764         *ptr++ = 0x00;
    765         *ptr++ = 0x00;
    766         *ptr++ = 0xe0 | (kPID_PCR >> 8);
    767         *ptr++ = kPID_PCR & 0xff;
    768 
    769         size_t program_info_length = 0;
    770         for (size_t i = 0; i < mProgramInfoDescriptors.size(); ++i) {
    771             program_info_length += mProgramInfoDescriptors.itemAt(i)->size();
    772         }
    773 
    774         CHECK_LT(program_info_length, 0x400);
    775         *ptr++ = 0xf0 | (program_info_length >> 8);
    776         *ptr++ = (program_info_length & 0xff);
    777 
    778         for (size_t i = 0; i < mProgramInfoDescriptors.size(); ++i) {
    779             const sp<ABuffer> &desc = mProgramInfoDescriptors.itemAt(i);
    780             memcpy(ptr, desc->data(), desc->size());
    781             ptr += desc->size();
    782         }
    783 
    784         for (size_t i = 0; i < mTracks.size(); ++i) {
    785             const sp<Track> &track = mTracks.itemAt(i);
    786 
    787             // Make sure all the decriptors have been added.
    788             track->finalize();
    789 
    790             *ptr++ = track->streamType();
    791             *ptr++ = 0xe0 | (track->PID() >> 8);
    792             *ptr++ = track->PID() & 0xff;
    793 
    794             size_t ES_info_length = 0;
    795             for (size_t i = 0; i < track->countDescriptors(); ++i) {
    796                 ES_info_length += track->descriptorAt(i)->size();
    797             }
    798             CHECK_LE(ES_info_length, 0xfff);
    799 
    800             *ptr++ = 0xf0 | (ES_info_length >> 8);
    801             *ptr++ = (ES_info_length & 0xff);
    802 
    803             for (size_t i = 0; i < track->countDescriptors(); ++i) {
    804                 const sp<ABuffer> &descriptor = track->descriptorAt(i);
    805                 memcpy(ptr, descriptor->data(), descriptor->size());
    806                 ptr += descriptor->size();
    807             }
    808         }
    809 
    810         size_t section_length = ptr - (crcDataStart + 3) + 4 /* CRC */;
    811 
    812         crcDataStart[1] = 0xb0 | (section_length >> 8);
    813         crcDataStart[2] = section_length & 0xff;
    814 
    815         crc = htonl(crc32(crcDataStart, ptr - crcDataStart));
    816         memcpy(ptr, &crc, 4);
    817         ptr += 4;
    818 
    819         sizeLeft = packetDataStart + 188 - ptr;
    820         memset(ptr, 0xff, sizeLeft);
    821 
    822         packetDataStart += 188;
    823     }
    824 
    825     if (flags & EMIT_PCR) {
    826         // PCR stream
    827         // 0x47
    828         // transport_error_indicator = b0
    829         // payload_unit_start_indicator = b1
    830         // transport_priority = b0
    831         // PID = kPCR_PID (13 bits)
    832         // transport_scrambling_control = b00
    833         // adaptation_field_control = b10 (adaptation field only, no payload)
    834         // continuity_counter = b0000 (does not increment)
    835         // adaptation_field_length = 183
    836         // discontinuity_indicator = b0
    837         // random_access_indicator = b0
    838         // elementary_stream_priority_indicator = b0
    839         // PCR_flag = b1
    840         // OPCR_flag = b0
    841         // splicing_point_flag = b0
    842         // transport_private_data_flag = b0
    843         // adaptation_field_extension_flag = b0
    844         // program_clock_reference_base = b?????????????????????????????????
    845         // reserved = b111111
    846         // program_clock_reference_extension = b?????????
    847 
    848         int64_t nowUs = ALooper::GetNowUs();
    849 
    850         uint64_t PCR = nowUs * 27;  // PCR based on a 27MHz clock
    851         uint64_t PCR_base = PCR / 300;
    852         uint32_t PCR_ext = PCR % 300;
    853 
    854         uint8_t *ptr = packetDataStart;
    855         *ptr++ = 0x47;
    856         *ptr++ = 0x40 | (kPID_PCR >> 8);
    857         *ptr++ = kPID_PCR & 0xff;
    858         *ptr++ = 0x20;
    859         *ptr++ = 0xb7;  // adaptation_field_length
    860         *ptr++ = 0x10;
    861         *ptr++ = (PCR_base >> 25) & 0xff;
    862         *ptr++ = (PCR_base >> 17) & 0xff;
    863         *ptr++ = (PCR_base >> 9) & 0xff;
    864         *ptr++ = ((PCR_base & 1) << 7) | 0x7e | ((PCR_ext >> 8) & 1);
    865         *ptr++ = (PCR_ext & 0xff);
    866 
    867         size_t sizeLeft = packetDataStart + 188 - ptr;
    868         memset(ptr, 0xff, sizeLeft);
    869 
    870         packetDataStart += 188;
    871     }
    872 
    873     uint64_t PTS = (timeUs * 9ll) / 100ll;
    874 
    875     if (PES_packet_length >= 65536) {
    876         // This really should only happen for video.
    877         CHECK(track->isVideo());
    878 
    879         // It's valid to set this to 0 for video according to the specs.
    880         PES_packet_length = 0;
    881     }
    882 
    883     size_t sizeAvailableForPayload = 188 - 4 - 14 - numStuffingBytes;
    884     if (PES_private_data_len > 0) {
    885         sizeAvailableForPayload -= PES_private_data_len + 1;
    886     }
    887 
    888     size_t copy = accessUnit->size();
    889 
    890     if (copy > sizeAvailableForPayload) {
    891         copy = sizeAvailableForPayload;
    892 
    893         if (alignPayload && copy > 16) {
    894             copy -= (copy % 16);
    895         }
    896     }
    897 
    898     size_t numPaddingBytes = sizeAvailableForPayload - copy;
    899 
    900     uint8_t *ptr = packetDataStart;
    901     *ptr++ = 0x47;
    902     *ptr++ = 0x40 | (track->PID() >> 8);
    903     *ptr++ = track->PID() & 0xff;
    904 
    905     *ptr++ = (numPaddingBytes > 0 ? 0x30 : 0x10)
    906                 | track->incrementContinuityCounter();
    907 
    908     if (numPaddingBytes > 0) {
    909         *ptr++ = numPaddingBytes - 1;
    910         if (numPaddingBytes >= 2) {
    911             *ptr++ = 0x00;
    912             memset(ptr, 0xff, numPaddingBytes - 2);
    913             ptr += numPaddingBytes - 2;
    914         }
    915     }
    916 
    917     *ptr++ = 0x00;
    918     *ptr++ = 0x00;
    919     *ptr++ = 0x01;
    920     *ptr++ = track->streamID();
    921     *ptr++ = PES_packet_length >> 8;
    922     *ptr++ = PES_packet_length & 0xff;
    923     *ptr++ = 0x84;
    924     *ptr++ = (PES_private_data_len > 0) ? 0x81 : 0x80;
    925 
    926     size_t headerLength = 0x05 + numStuffingBytes;
    927     if (PES_private_data_len > 0) {
    928         headerLength += 1 + PES_private_data_len;
    929     }
    930 
    931     *ptr++ = headerLength;
    932 
    933     *ptr++ = 0x20 | (((PTS >> 30) & 7) << 1) | 1;
    934     *ptr++ = (PTS >> 22) & 0xff;
    935     *ptr++ = (((PTS >> 15) & 0x7f) << 1) | 1;
    936     *ptr++ = (PTS >> 7) & 0xff;
    937     *ptr++ = ((PTS & 0x7f) << 1) | 1;
    938 
    939     if (PES_private_data_len > 0) {
    940         *ptr++ = 0x8e;  // PES_private_data_flag, reserved.
    941         memcpy(ptr, PES_private_data, PES_private_data_len);
    942         ptr += PES_private_data_len;
    943     }
    944 
    945     for (size_t i = 0; i < numStuffingBytes; ++i) {
    946         *ptr++ = 0xff;
    947     }
    948 
    949     memcpy(ptr, accessUnit->data(), copy);
    950     ptr += copy;
    951 
    952     CHECK_EQ(ptr, packetDataStart + 188);
    953     packetDataStart += 188;
    954 
    955     size_t offset = copy;
    956     while (offset < accessUnit->size()) {
    957         // for subsequent fragments of "buffer":
    958         // 0x47
    959         // transport_error_indicator = b0
    960         // payload_unit_start_indicator = b0
    961         // transport_priority = b0
    962         // PID = b0 0001 1110 ???? (13 bits) [0x1e0 + 1 + sourceIndex]
    963         // transport_scrambling_control = b00
    964         // adaptation_field_control = b??
    965         // continuity_counter = b????
    966         // the fragment of "buffer" follows.
    967 
    968         size_t sizeAvailableForPayload = 188 - 4;
    969 
    970         size_t copy = accessUnit->size() - offset;
    971 
    972         if (copy > sizeAvailableForPayload) {
    973             copy = sizeAvailableForPayload;
    974 
    975             if (alignPayload && copy > 16) {
    976                 copy -= (copy % 16);
    977             }
    978         }
    979 
    980         size_t numPaddingBytes = sizeAvailableForPayload - copy;
    981 
    982         uint8_t *ptr = packetDataStart;
    983         *ptr++ = 0x47;
    984         *ptr++ = 0x00 | (track->PID() >> 8);
    985         *ptr++ = track->PID() & 0xff;
    986 
    987         *ptr++ = (numPaddingBytes > 0 ? 0x30 : 0x10)
    988                     | track->incrementContinuityCounter();
    989 
    990         if (numPaddingBytes > 0) {
    991             *ptr++ = numPaddingBytes - 1;
    992             if (numPaddingBytes >= 2) {
    993                 *ptr++ = 0x00;
    994                 memset(ptr, 0xff, numPaddingBytes - 2);
    995                 ptr += numPaddingBytes - 2;
    996             }
    997         }
    998 
    999         memcpy(ptr, accessUnit->data() + offset, copy);
   1000         ptr += copy;
   1001         CHECK_EQ(ptr, packetDataStart + 188);
   1002 
   1003         offset += copy;
   1004         packetDataStart += 188;
   1005     }
   1006 
   1007     CHECK(packetDataStart == buffer->data() + buffer->capacity());
   1008 
   1009     *packets = buffer;
   1010 
   1011     return OK;
   1012 }
   1013 
   1014 void TSPacketizer::initCrcTable() {
   1015     uint32_t poly = 0x04C11DB7;
   1016 
   1017     for (int i = 0; i < 256; i++) {
   1018         uint32_t crc = i << 24;
   1019         for (int j = 0; j < 8; j++) {
   1020             crc = (crc << 1) ^ ((crc & 0x80000000) ? (poly) : 0);
   1021         }
   1022         mCrcTable[i] = crc;
   1023     }
   1024 }
   1025 
   1026 uint32_t TSPacketizer::crc32(const uint8_t *start, size_t size) const {
   1027     uint32_t crc = 0xFFFFFFFF;
   1028     const uint8_t *p;
   1029 
   1030     for (p = start; p < start + size; ++p) {
   1031         crc = (crc << 8) ^ mCrcTable[((crc >> 24) ^ *p) & 0xFF];
   1032     }
   1033 
   1034     return crc;
   1035 }
   1036 
   1037 sp<ABuffer> TSPacketizer::prependCSD(
   1038         size_t trackIndex, const sp<ABuffer> &accessUnit) const {
   1039     CHECK_LT(trackIndex, mTracks.size());
   1040 
   1041     const sp<Track> &track = mTracks.itemAt(trackIndex);
   1042     CHECK(track->isH264() && IsIDR(accessUnit));
   1043 
   1044     int64_t timeUs;
   1045     CHECK(accessUnit->meta()->findInt64("timeUs", &timeUs));
   1046 
   1047     sp<ABuffer> accessUnit2 = track->prependCSD(accessUnit);
   1048 
   1049     accessUnit2->meta()->setInt64("timeUs", timeUs);
   1050 
   1051     return accessUnit2;
   1052 }
   1053 
   1054 }  // namespace android
   1055 
   1056