Home | History | Annotate | Download | only in libstagefright
      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 "MPEG2TSWriter"
     19 #include <media/stagefright/foundation/ADebug.h>
     20 
     21 #include <media/stagefright/foundation/hexdump.h>
     22 #include <media/stagefright/foundation/ABuffer.h>
     23 #include <media/stagefright/foundation/AMessage.h>
     24 #include <media/stagefright/MPEG2TSWriter.h>
     25 #include <media/stagefright/MediaBuffer.h>
     26 #include <media/stagefright/MediaDefs.h>
     27 #include <media/stagefright/MediaErrors.h>
     28 #include <media/stagefright/MediaSource.h>
     29 #include <media/stagefright/MetaData.h>
     30 #include <media/stagefright/Utils.h>
     31 
     32 #include "include/ESDS.h"
     33 
     34 namespace android {
     35 
     36 struct MPEG2TSWriter::SourceInfo : public AHandler {
     37     SourceInfo(const sp<MediaSource> &source);
     38 
     39     void start(const sp<AMessage> &notify);
     40     void stop();
     41 
     42     unsigned streamType() const;
     43     unsigned incrementContinuityCounter();
     44 
     45     void readMore();
     46 
     47     enum {
     48         kNotifyStartFailed,
     49         kNotifyBuffer,
     50         kNotifyReachedEOS,
     51     };
     52 
     53     sp<ABuffer> lastAccessUnit();
     54     int64_t lastAccessUnitTimeUs();
     55     void setLastAccessUnit(const sp<ABuffer> &accessUnit);
     56 
     57     void setEOSReceived();
     58     bool eosReceived() const;
     59 
     60 protected:
     61     virtual void onMessageReceived(const sp<AMessage> &msg);
     62 
     63     virtual ~SourceInfo();
     64 
     65 private:
     66     enum {
     67         kWhatStart = 'strt',
     68         kWhatRead  = 'read',
     69     };
     70 
     71     sp<MediaSource> mSource;
     72     sp<ALooper> mLooper;
     73     sp<AMessage> mNotify;
     74 
     75     sp<ABuffer> mAACCodecSpecificData;
     76 
     77     sp<ABuffer> mAACBuffer;
     78 
     79     sp<ABuffer> mLastAccessUnit;
     80     bool mEOSReceived;
     81 
     82     unsigned mStreamType;
     83     unsigned mContinuityCounter;
     84 
     85     void extractCodecSpecificData();
     86 
     87     bool appendAACFrames(MediaBuffer *buffer);
     88     bool flushAACFrames();
     89 
     90     void postAVCFrame(MediaBuffer *buffer);
     91 
     92     DISALLOW_EVIL_CONSTRUCTORS(SourceInfo);
     93 };
     94 
     95 MPEG2TSWriter::SourceInfo::SourceInfo(const sp<MediaSource> &source)
     96     : mSource(source),
     97       mLooper(new ALooper),
     98       mEOSReceived(false),
     99       mStreamType(0),
    100       mContinuityCounter(0) {
    101     mLooper->setName("MPEG2TSWriter source");
    102 
    103     sp<MetaData> meta = mSource->getFormat();
    104     const char *mime;
    105     CHECK(meta->findCString(kKeyMIMEType, &mime));
    106 
    107     if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AAC)) {
    108         mStreamType = 0x0f;
    109     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) {
    110         mStreamType = 0x1b;
    111     } else {
    112         TRESPASS();
    113     }
    114 }
    115 
    116 MPEG2TSWriter::SourceInfo::~SourceInfo() {
    117 }
    118 
    119 unsigned MPEG2TSWriter::SourceInfo::streamType() const {
    120     return mStreamType;
    121 }
    122 
    123 unsigned MPEG2TSWriter::SourceInfo::incrementContinuityCounter() {
    124     if (++mContinuityCounter == 16) {
    125         mContinuityCounter = 0;
    126     }
    127 
    128     return mContinuityCounter;
    129 }
    130 
    131 void MPEG2TSWriter::SourceInfo::start(const sp<AMessage> &notify) {
    132     mLooper->registerHandler(this);
    133     mLooper->start();
    134 
    135     mNotify = notify;
    136 
    137     (new AMessage(kWhatStart, id()))->post();
    138 }
    139 
    140 void MPEG2TSWriter::SourceInfo::stop() {
    141     mLooper->unregisterHandler(id());
    142     mLooper->stop();
    143 
    144     mSource->stop();
    145 }
    146 
    147 void MPEG2TSWriter::SourceInfo::extractCodecSpecificData() {
    148     sp<MetaData> meta = mSource->getFormat();
    149 
    150     const char *mime;
    151     CHECK(meta->findCString(kKeyMIMEType, &mime));
    152 
    153     if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AAC)) {
    154         uint32_t type;
    155         const void *data;
    156         size_t size;
    157         if (!meta->findData(kKeyESDS, &type, &data, &size)) {
    158             // Codec specific data better be in the first data buffer.
    159             return;
    160         }
    161 
    162         ESDS esds((const char *)data, size);
    163         CHECK_EQ(esds.InitCheck(), (status_t)OK);
    164 
    165         const uint8_t *codec_specific_data;
    166         size_t codec_specific_data_size;
    167         esds.getCodecSpecificInfo(
    168                 (const void **)&codec_specific_data, &codec_specific_data_size);
    169 
    170         CHECK_GE(codec_specific_data_size, 2u);
    171 
    172         mAACCodecSpecificData = new ABuffer(codec_specific_data_size);
    173 
    174         memcpy(mAACCodecSpecificData->data(), codec_specific_data,
    175                codec_specific_data_size);
    176 
    177         return;
    178     }
    179 
    180     if (strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) {
    181         return;
    182     }
    183 
    184     uint32_t type;
    185     const void *data;
    186     size_t size;
    187     if (!meta->findData(kKeyAVCC, &type, &data, &size)) {
    188         // Codec specific data better be part of the data stream then.
    189         return;
    190     }
    191 
    192     sp<ABuffer> out = new ABuffer(1024);
    193     out->setRange(0, 0);
    194 
    195     const uint8_t *ptr = (const uint8_t *)data;
    196 
    197     size_t numSeqParameterSets = ptr[5] & 31;
    198 
    199     ptr += 6;
    200     size -= 6;
    201 
    202     for (size_t i = 0; i < numSeqParameterSets; ++i) {
    203         CHECK(size >= 2);
    204         size_t length = U16_AT(ptr);
    205 
    206         ptr += 2;
    207         size -= 2;
    208 
    209         CHECK(size >= length);
    210 
    211         CHECK_LE(out->size() + 4 + length, out->capacity());
    212         memcpy(out->data() + out->size(), "\x00\x00\x00\x01", 4);
    213         memcpy(out->data() + out->size() + 4, ptr, length);
    214         out->setRange(0, out->size() + length + 4);
    215 
    216         ptr += length;
    217         size -= length;
    218     }
    219 
    220     CHECK(size >= 1);
    221     size_t numPictureParameterSets = *ptr;
    222     ++ptr;
    223     --size;
    224 
    225     for (size_t i = 0; i < numPictureParameterSets; ++i) {
    226         CHECK(size >= 2);
    227         size_t length = U16_AT(ptr);
    228 
    229         ptr += 2;
    230         size -= 2;
    231 
    232         CHECK(size >= length);
    233 
    234         CHECK_LE(out->size() + 4 + length, out->capacity());
    235         memcpy(out->data() + out->size(), "\x00\x00\x00\x01", 4);
    236         memcpy(out->data() + out->size() + 4, ptr, length);
    237         out->setRange(0, out->size() + length + 4);
    238 
    239         ptr += length;
    240         size -= length;
    241     }
    242 
    243     out->meta()->setInt64("timeUs", 0ll);
    244 
    245     sp<AMessage> notify = mNotify->dup();
    246     notify->setInt32("what", kNotifyBuffer);
    247     notify->setBuffer("buffer", out);
    248     notify->setInt32("oob", true);
    249     notify->post();
    250 }
    251 
    252 void MPEG2TSWriter::SourceInfo::postAVCFrame(MediaBuffer *buffer) {
    253     sp<AMessage> notify = mNotify->dup();
    254     notify->setInt32("what", kNotifyBuffer);
    255 
    256     sp<ABuffer> copy =
    257         new ABuffer(buffer->range_length());
    258     memcpy(copy->data(),
    259            (const uint8_t *)buffer->data()
    260             + buffer->range_offset(),
    261            buffer->range_length());
    262 
    263     int64_t timeUs;
    264     CHECK(buffer->meta_data()->findInt64(kKeyTime, &timeUs));
    265     copy->meta()->setInt64("timeUs", timeUs);
    266 
    267     int32_t isSync;
    268     if (buffer->meta_data()->findInt32(kKeyIsSyncFrame, &isSync)
    269             && isSync != 0) {
    270         copy->meta()->setInt32("isSync", true);
    271     }
    272 
    273     notify->setBuffer("buffer", copy);
    274     notify->post();
    275 }
    276 
    277 bool MPEG2TSWriter::SourceInfo::appendAACFrames(MediaBuffer *buffer) {
    278     bool accessUnitPosted = false;
    279 
    280     if (mAACBuffer != NULL
    281             && mAACBuffer->size() + 7 + buffer->range_length()
    282                     > mAACBuffer->capacity()) {
    283         accessUnitPosted = flushAACFrames();
    284     }
    285 
    286     if (mAACBuffer == NULL) {
    287         size_t alloc = 4096;
    288         if (buffer->range_length() + 7 > alloc) {
    289             alloc = 7 + buffer->range_length();
    290         }
    291 
    292         mAACBuffer = new ABuffer(alloc);
    293 
    294         int64_t timeUs;
    295         CHECK(buffer->meta_data()->findInt64(kKeyTime, &timeUs));
    296 
    297         mAACBuffer->meta()->setInt64("timeUs", timeUs);
    298         mAACBuffer->meta()->setInt32("isSync", true);
    299 
    300         mAACBuffer->setRange(0, 0);
    301     }
    302 
    303     const uint8_t *codec_specific_data = mAACCodecSpecificData->data();
    304 
    305     unsigned profile = (codec_specific_data[0] >> 3) - 1;
    306 
    307     unsigned sampling_freq_index =
    308         ((codec_specific_data[0] & 7) << 1)
    309         | (codec_specific_data[1] >> 7);
    310 
    311     unsigned channel_configuration =
    312         (codec_specific_data[1] >> 3) & 0x0f;
    313 
    314     uint8_t *ptr = mAACBuffer->data() + mAACBuffer->size();
    315 
    316     const uint32_t aac_frame_length = buffer->range_length() + 7;
    317 
    318     *ptr++ = 0xff;
    319     *ptr++ = 0xf1;  // b11110001, ID=0, layer=0, protection_absent=1
    320 
    321     *ptr++ =
    322         profile << 6
    323         | sampling_freq_index << 2
    324         | ((channel_configuration >> 2) & 1);  // private_bit=0
    325 
    326     // original_copy=0, home=0, copyright_id_bit=0, copyright_id_start=0
    327     *ptr++ =
    328         (channel_configuration & 3) << 6
    329         | aac_frame_length >> 11;
    330     *ptr++ = (aac_frame_length >> 3) & 0xff;
    331     *ptr++ = (aac_frame_length & 7) << 5;
    332 
    333     // adts_buffer_fullness=0, number_of_raw_data_blocks_in_frame=0
    334     *ptr++ = 0;
    335 
    336     memcpy(ptr,
    337            (const uint8_t *)buffer->data() + buffer->range_offset(),
    338            buffer->range_length());
    339 
    340     ptr += buffer->range_length();
    341 
    342     mAACBuffer->setRange(0, ptr - mAACBuffer->data());
    343 
    344     return accessUnitPosted;
    345 }
    346 
    347 bool MPEG2TSWriter::SourceInfo::flushAACFrames() {
    348     if (mAACBuffer == NULL) {
    349         return false;
    350     }
    351 
    352     sp<AMessage> notify = mNotify->dup();
    353     notify->setInt32("what", kNotifyBuffer);
    354     notify->setBuffer("buffer", mAACBuffer);
    355     notify->post();
    356 
    357     mAACBuffer.clear();
    358 
    359     return true;
    360 }
    361 
    362 void MPEG2TSWriter::SourceInfo::readMore() {
    363     (new AMessage(kWhatRead, id()))->post();
    364 }
    365 
    366 void MPEG2TSWriter::SourceInfo::onMessageReceived(const sp<AMessage> &msg) {
    367     switch (msg->what()) {
    368         case kWhatStart:
    369         {
    370             status_t err = mSource->start();
    371             if (err != OK) {
    372                 sp<AMessage> notify = mNotify->dup();
    373                 notify->setInt32("what", kNotifyStartFailed);
    374                 notify->post();
    375                 break;
    376             }
    377 
    378             extractCodecSpecificData();
    379 
    380             readMore();
    381             break;
    382         }
    383 
    384         case kWhatRead:
    385         {
    386             MediaBuffer *buffer;
    387             status_t err = mSource->read(&buffer);
    388 
    389             if (err != OK && err != INFO_FORMAT_CHANGED) {
    390                 if (mStreamType == 0x0f) {
    391                     flushAACFrames();
    392                 }
    393 
    394                 sp<AMessage> notify = mNotify->dup();
    395                 notify->setInt32("what", kNotifyReachedEOS);
    396                 notify->setInt32("status", err);
    397                 notify->post();
    398                 break;
    399             }
    400 
    401             if (err == OK) {
    402                 if (mStreamType == 0x0f && mAACCodecSpecificData == NULL) {
    403                     // The first buffer contains codec specific data.
    404 
    405                     CHECK_GE(buffer->range_length(), 2u);
    406 
    407                     mAACCodecSpecificData = new ABuffer(buffer->range_length());
    408 
    409                     memcpy(mAACCodecSpecificData->data(),
    410                            (const uint8_t *)buffer->data()
    411                             + buffer->range_offset(),
    412                            buffer->range_length());
    413                 } else if (buffer->range_length() > 0) {
    414                     if (mStreamType == 0x0f) {
    415                         if (!appendAACFrames(buffer)) {
    416                             msg->post();
    417                         }
    418                     } else {
    419                         postAVCFrame(buffer);
    420                     }
    421                 }
    422 
    423                 buffer->release();
    424                 buffer = NULL;
    425             }
    426 
    427             // Do not read more data until told to.
    428             break;
    429         }
    430 
    431         default:
    432             TRESPASS();
    433     }
    434 }
    435 
    436 sp<ABuffer> MPEG2TSWriter::SourceInfo::lastAccessUnit() {
    437     return mLastAccessUnit;
    438 }
    439 
    440 void MPEG2TSWriter::SourceInfo::setLastAccessUnit(
    441         const sp<ABuffer> &accessUnit) {
    442     mLastAccessUnit = accessUnit;
    443 }
    444 
    445 int64_t MPEG2TSWriter::SourceInfo::lastAccessUnitTimeUs() {
    446     if (mLastAccessUnit == NULL) {
    447         return -1;
    448     }
    449 
    450     int64_t timeUs;
    451     CHECK(mLastAccessUnit->meta()->findInt64("timeUs", &timeUs));
    452 
    453     return timeUs;
    454 }
    455 
    456 void MPEG2TSWriter::SourceInfo::setEOSReceived() {
    457     CHECK(!mEOSReceived);
    458     mEOSReceived = true;
    459 }
    460 
    461 bool MPEG2TSWriter::SourceInfo::eosReceived() const {
    462     return mEOSReceived;
    463 }
    464 
    465 ////////////////////////////////////////////////////////////////////////////////
    466 
    467 MPEG2TSWriter::MPEG2TSWriter(int fd)
    468     : mFile(fdopen(dup(fd), "wb")),
    469       mWriteCookie(NULL),
    470       mWriteFunc(NULL),
    471       mStarted(false),
    472       mNumSourcesDone(0),
    473       mNumTSPacketsWritten(0),
    474       mNumTSPacketsBeforeMeta(0) {
    475     init();
    476 }
    477 
    478 MPEG2TSWriter::MPEG2TSWriter(const char *filename)
    479     : mFile(fopen(filename, "wb")),
    480       mWriteCookie(NULL),
    481       mWriteFunc(NULL),
    482       mStarted(false),
    483       mNumSourcesDone(0),
    484       mNumTSPacketsWritten(0),
    485       mNumTSPacketsBeforeMeta(0) {
    486     init();
    487 }
    488 
    489 MPEG2TSWriter::MPEG2TSWriter(
    490         void *cookie,
    491         ssize_t (*write)(void *cookie, const void *data, size_t size))
    492     : mFile(NULL),
    493       mWriteCookie(cookie),
    494       mWriteFunc(write),
    495       mStarted(false),
    496       mNumSourcesDone(0),
    497       mNumTSPacketsWritten(0),
    498       mNumTSPacketsBeforeMeta(0) {
    499     init();
    500 }
    501 
    502 void MPEG2TSWriter::init() {
    503     CHECK(mFile != NULL || mWriteFunc != NULL);
    504 
    505     mLooper = new ALooper;
    506     mLooper->setName("MPEG2TSWriter");
    507 
    508     mReflector = new AHandlerReflector<MPEG2TSWriter>(this);
    509 
    510     mLooper->registerHandler(mReflector);
    511     mLooper->start();
    512 }
    513 
    514 MPEG2TSWriter::~MPEG2TSWriter() {
    515     if (mStarted) {
    516         reset();
    517     }
    518 
    519     mLooper->unregisterHandler(mReflector->id());
    520     mLooper->stop();
    521 
    522     if (mFile != NULL) {
    523         fclose(mFile);
    524         mFile = NULL;
    525     }
    526 }
    527 
    528 status_t MPEG2TSWriter::addSource(const sp<MediaSource> &source) {
    529     CHECK(!mStarted);
    530 
    531     sp<MetaData> meta = source->getFormat();
    532     const char *mime;
    533     CHECK(meta->findCString(kKeyMIMEType, &mime));
    534 
    535     if (strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)
    536             && strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AAC)) {
    537         return ERROR_UNSUPPORTED;
    538     }
    539 
    540     sp<SourceInfo> info = new SourceInfo(source);
    541 
    542     mSources.push(info);
    543 
    544     return OK;
    545 }
    546 
    547 status_t MPEG2TSWriter::start(MetaData *param) {
    548     CHECK(!mStarted);
    549 
    550     mStarted = true;
    551     mNumSourcesDone = 0;
    552     mNumTSPacketsWritten = 0;
    553     mNumTSPacketsBeforeMeta = 0;
    554 
    555     for (size_t i = 0; i < mSources.size(); ++i) {
    556         sp<AMessage> notify =
    557             new AMessage(kWhatSourceNotify, mReflector->id());
    558 
    559         notify->setInt32("source-index", i);
    560 
    561         mSources.editItemAt(i)->start(notify);
    562     }
    563 
    564     return OK;
    565 }
    566 
    567 status_t MPEG2TSWriter::reset() {
    568     CHECK(mStarted);
    569 
    570     for (size_t i = 0; i < mSources.size(); ++i) {
    571         mSources.editItemAt(i)->stop();
    572     }
    573     mStarted = false;
    574 
    575     return OK;
    576 }
    577 
    578 status_t MPEG2TSWriter::pause() {
    579     CHECK(mStarted);
    580 
    581     return OK;
    582 }
    583 
    584 bool MPEG2TSWriter::reachedEOS() {
    585     return !mStarted || (mNumSourcesDone == mSources.size() ? true : false);
    586 }
    587 
    588 status_t MPEG2TSWriter::dump(int fd, const Vector<String16> &args) {
    589     return OK;
    590 }
    591 
    592 void MPEG2TSWriter::onMessageReceived(const sp<AMessage> &msg) {
    593     switch (msg->what()) {
    594         case kWhatSourceNotify:
    595         {
    596             int32_t sourceIndex;
    597             CHECK(msg->findInt32("source-index", &sourceIndex));
    598 
    599             int32_t what;
    600             CHECK(msg->findInt32("what", &what));
    601 
    602             if (what == SourceInfo::kNotifyReachedEOS
    603                     || what == SourceInfo::kNotifyStartFailed) {
    604                 sp<SourceInfo> source = mSources.editItemAt(sourceIndex);
    605                 source->setEOSReceived();
    606 
    607                 sp<ABuffer> buffer = source->lastAccessUnit();
    608                 source->setLastAccessUnit(NULL);
    609 
    610                 if (buffer != NULL) {
    611                     writeTS();
    612                     writeAccessUnit(sourceIndex, buffer);
    613                 }
    614 
    615                 ++mNumSourcesDone;
    616             } else if (what == SourceInfo::kNotifyBuffer) {
    617                 sp<ABuffer> buffer;
    618                 CHECK(msg->findBuffer("buffer", &buffer));
    619 
    620                 int32_t oob;
    621                 if (msg->findInt32("oob", &oob) && oob) {
    622                     // This is codec specific data delivered out of band.
    623                     // It can be written out immediately.
    624                     writeTS();
    625                     writeAccessUnit(sourceIndex, buffer);
    626                     break;
    627                 }
    628 
    629                 // We don't just write out data as we receive it from
    630                 // the various sources. That would essentially write them
    631                 // out in random order (as the thread scheduler determines
    632                 // how the messages are dispatched).
    633                 // Instead we gather an access unit for all tracks and
    634                 // write out the one with the smallest timestamp, then
    635                 // request more data for the written out track.
    636                 // Rinse, repeat.
    637                 // If we don't have data on any track we don't write
    638                 // anything just yet.
    639 
    640                 sp<SourceInfo> source = mSources.editItemAt(sourceIndex);
    641 
    642                 CHECK(source->lastAccessUnit() == NULL);
    643                 source->setLastAccessUnit(buffer);
    644 
    645                 ALOGV("lastAccessUnitTimeUs[%d] = %.2f secs",
    646                      sourceIndex, source->lastAccessUnitTimeUs() / 1E6);
    647 
    648                 int64_t minTimeUs = -1;
    649                 size_t minIndex = 0;
    650 
    651                 for (size_t i = 0; i < mSources.size(); ++i) {
    652                     const sp<SourceInfo> &source = mSources.editItemAt(i);
    653 
    654                     if (source->eosReceived()) {
    655                         continue;
    656                     }
    657 
    658                     int64_t timeUs = source->lastAccessUnitTimeUs();
    659                     if (timeUs < 0) {
    660                         minTimeUs = -1;
    661                         break;
    662                     } else if (minTimeUs < 0 || timeUs < minTimeUs) {
    663                         minTimeUs = timeUs;
    664                         minIndex = i;
    665                     }
    666                 }
    667 
    668                 if (minTimeUs < 0) {
    669                     ALOGV("not a all tracks have valid data.");
    670                     break;
    671                 }
    672 
    673                 ALOGV("writing access unit at time %.2f secs (index %d)",
    674                      minTimeUs / 1E6, minIndex);
    675 
    676                 source = mSources.editItemAt(minIndex);
    677 
    678                 buffer = source->lastAccessUnit();
    679                 source->setLastAccessUnit(NULL);
    680 
    681                 writeTS();
    682                 writeAccessUnit(minIndex, buffer);
    683 
    684                 source->readMore();
    685             }
    686             break;
    687         }
    688 
    689         default:
    690             TRESPASS();
    691     }
    692 }
    693 
    694 void MPEG2TSWriter::writeProgramAssociationTable() {
    695     // 0x47
    696     // transport_error_indicator = b0
    697     // payload_unit_start_indicator = b1
    698     // transport_priority = b0
    699     // PID = b0000000000000 (13 bits)
    700     // transport_scrambling_control = b00
    701     // adaptation_field_control = b01 (no adaptation field, payload only)
    702     // continuity_counter = b????
    703     // skip = 0x00
    704     // --- payload follows
    705     // table_id = 0x00
    706     // section_syntax_indicator = b1
    707     // must_be_zero = b0
    708     // reserved = b11
    709     // section_length = 0x00d
    710     // transport_stream_id = 0x0000
    711     // reserved = b11
    712     // version_number = b00001
    713     // current_next_indicator = b1
    714     // section_number = 0x00
    715     // last_section_number = 0x00
    716     //   one program follows:
    717     //   program_number = 0x0001
    718     //   reserved = b111
    719     //   program_map_PID = 0x01e0 (13 bits!)
    720     // CRC = 0x????????
    721 
    722     static const uint8_t kData[] = {
    723         0x47,
    724         0x40, 0x00, 0x10, 0x00,  // b0100 0000 0000 0000 0001 ???? 0000 0000
    725         0x00, 0xb0, 0x0d, 0x00,  // b0000 0000 1011 0000 0000 1101 0000 0000
    726         0x00, 0xc3, 0x00, 0x00,  // b0000 0000 1100 0011 0000 0000 0000 0000
    727         0x00, 0x01, 0xe1, 0xe0,  // b0000 0000 0000 0001 1110 0001 1110 0000
    728         0x00, 0x00, 0x00, 0x00   // b???? ???? ???? ???? ???? ???? ???? ????
    729     };
    730 
    731     sp<ABuffer> buffer = new ABuffer(188);
    732     memset(buffer->data(), 0, buffer->size());
    733     memcpy(buffer->data(), kData, sizeof(kData));
    734 
    735     static const unsigned kContinuityCounter = 5;
    736     buffer->data()[3] |= kContinuityCounter;
    737 
    738     CHECK_EQ(internalWrite(buffer->data(), buffer->size()), buffer->size());
    739 }
    740 
    741 void MPEG2TSWriter::writeProgramMap() {
    742     // 0x47
    743     // transport_error_indicator = b0
    744     // payload_unit_start_indicator = b1
    745     // transport_priority = b0
    746     // PID = b0 0001 1110 0000 (13 bits) [0x1e0]
    747     // transport_scrambling_control = b00
    748     // adaptation_field_control = b01 (no adaptation field, payload only)
    749     // continuity_counter = b????
    750     // skip = 0x00
    751     // -- payload follows
    752     // table_id = 0x02
    753     // section_syntax_indicator = b1
    754     // must_be_zero = b0
    755     // reserved = b11
    756     // section_length = 0x???
    757     // program_number = 0x0001
    758     // reserved = b11
    759     // version_number = b00001
    760     // current_next_indicator = b1
    761     // section_number = 0x00
    762     // last_section_number = 0x00
    763     // reserved = b111
    764     // PCR_PID = b? ???? ???? ???? (13 bits)
    765     // reserved = b1111
    766     // program_info_length = 0x000
    767     //   one or more elementary stream descriptions follow:
    768     //   stream_type = 0x??
    769     //   reserved = b111
    770     //   elementary_PID = b? ???? ???? ???? (13 bits)
    771     //   reserved = b1111
    772     //   ES_info_length = 0x000
    773     // CRC = 0x????????
    774 
    775     static const uint8_t kData[] = {
    776         0x47,
    777         0x41, 0xe0, 0x10, 0x00,  // b0100 0001 1110 0000 0001 ???? 0000 0000
    778         0x02, 0xb0, 0x00, 0x00,  // b0000 0010 1011 ???? ???? ???? 0000 0000
    779         0x01, 0xc3, 0x00, 0x00,  // b0000 0001 1100 0011 0000 0000 0000 0000
    780         0xe0, 0x00, 0xf0, 0x00   // b111? ???? ???? ???? 1111 0000 0000 0000
    781     };
    782 
    783     sp<ABuffer> buffer = new ABuffer(188);
    784     memset(buffer->data(), 0, buffer->size());
    785     memcpy(buffer->data(), kData, sizeof(kData));
    786 
    787     static const unsigned kContinuityCounter = 5;
    788     buffer->data()[3] |= kContinuityCounter;
    789 
    790     size_t section_length = 5 * mSources.size() + 4 + 9;
    791     buffer->data()[6] |= section_length >> 8;
    792     buffer->data()[7] = section_length & 0xff;
    793 
    794     static const unsigned kPCR_PID = 0x1e1;
    795     buffer->data()[13] |= (kPCR_PID >> 8) & 0x1f;
    796     buffer->data()[14] = kPCR_PID & 0xff;
    797 
    798     uint8_t *ptr = &buffer->data()[sizeof(kData)];
    799     for (size_t i = 0; i < mSources.size(); ++i) {
    800         *ptr++ = mSources.editItemAt(i)->streamType();
    801 
    802         const unsigned ES_PID = 0x1e0 + i + 1;
    803         *ptr++ = 0xe0 | (ES_PID >> 8);
    804         *ptr++ = ES_PID & 0xff;
    805         *ptr++ = 0xf0;
    806         *ptr++ = 0x00;
    807     }
    808 
    809     *ptr++ = 0x00;
    810     *ptr++ = 0x00;
    811     *ptr++ = 0x00;
    812     *ptr++ = 0x00;
    813 
    814     CHECK_EQ(internalWrite(buffer->data(), buffer->size()), buffer->size());
    815 }
    816 
    817 void MPEG2TSWriter::writeAccessUnit(
    818         int32_t sourceIndex, const sp<ABuffer> &accessUnit) {
    819     // 0x47
    820     // transport_error_indicator = b0
    821     // payload_unit_start_indicator = b1
    822     // transport_priority = b0
    823     // PID = b0 0001 1110 ???? (13 bits) [0x1e0 + 1 + sourceIndex]
    824     // transport_scrambling_control = b00
    825     // adaptation_field_control = b01 (no adaptation field, payload only)
    826     // continuity_counter = b????
    827     // -- payload follows
    828     // packet_startcode_prefix = 0x000001
    829     // stream_id = 0x?? (0xe0 for avc video, 0xc0 for aac audio)
    830     // PES_packet_length = 0x????
    831     // reserved = b10
    832     // PES_scrambling_control = b00
    833     // PES_priority = b0
    834     // data_alignment_indicator = b1
    835     // copyright = b0
    836     // original_or_copy = b0
    837     // PTS_DTS_flags = b10  (PTS only)
    838     // ESCR_flag = b0
    839     // ES_rate_flag = b0
    840     // DSM_trick_mode_flag = b0
    841     // additional_copy_info_flag = b0
    842     // PES_CRC_flag = b0
    843     // PES_extension_flag = b0
    844     // PES_header_data_length = 0x05
    845     // reserved = b0010 (PTS)
    846     // PTS[32..30] = b???
    847     // reserved = b1
    848     // PTS[29..15] = b??? ???? ???? ???? (15 bits)
    849     // reserved = b1
    850     // PTS[14..0] = b??? ???? ???? ???? (15 bits)
    851     // reserved = b1
    852     // the first fragment of "buffer" follows
    853 
    854     sp<ABuffer> buffer = new ABuffer(188);
    855     memset(buffer->data(), 0, buffer->size());
    856 
    857     const unsigned PID = 0x1e0 + sourceIndex + 1;
    858 
    859     const unsigned continuity_counter =
    860         mSources.editItemAt(sourceIndex)->incrementContinuityCounter();
    861 
    862     // XXX if there are multiple streams of a kind (more than 1 audio or
    863     // more than 1 video) they need distinct stream_ids.
    864     const unsigned stream_id =
    865         mSources.editItemAt(sourceIndex)->streamType() == 0x0f ? 0xc0 : 0xe0;
    866 
    867     int64_t timeUs;
    868     CHECK(accessUnit->meta()->findInt64("timeUs", &timeUs));
    869 
    870     uint32_t PTS = (timeUs * 9ll) / 100ll;
    871 
    872     size_t PES_packet_length = accessUnit->size() + 8;
    873 
    874     if (PES_packet_length >= 65536) {
    875         // This really should only happen for video.
    876         CHECK_EQ(stream_id, 0xe0u);
    877 
    878         // It's valid to set this to 0 for video according to the specs.
    879         PES_packet_length = 0;
    880     }
    881 
    882     uint8_t *ptr = buffer->data();
    883     *ptr++ = 0x47;
    884     *ptr++ = 0x40 | (PID >> 8);
    885     *ptr++ = PID & 0xff;
    886     *ptr++ = 0x10 | continuity_counter;
    887     *ptr++ = 0x00;
    888     *ptr++ = 0x00;
    889     *ptr++ = 0x01;
    890     *ptr++ = stream_id;
    891     *ptr++ = PES_packet_length >> 8;
    892     *ptr++ = PES_packet_length & 0xff;
    893     *ptr++ = 0x84;
    894     *ptr++ = 0x80;
    895     *ptr++ = 0x05;
    896     *ptr++ = 0x20 | (((PTS >> 30) & 7) << 1) | 1;
    897     *ptr++ = (PTS >> 22) & 0xff;
    898     *ptr++ = (((PTS >> 15) & 0x7f) << 1) | 1;
    899     *ptr++ = (PTS >> 7) & 0xff;
    900     *ptr++ = ((PTS & 0x7f) << 1) | 1;
    901 
    902     size_t sizeLeft = buffer->data() + buffer->size() - ptr;
    903     size_t copy = accessUnit->size();
    904     if (copy > sizeLeft) {
    905         copy = sizeLeft;
    906     }
    907 
    908     memcpy(ptr, accessUnit->data(), copy);
    909 
    910     CHECK_EQ(internalWrite(buffer->data(), buffer->size()), buffer->size());
    911 
    912     size_t offset = copy;
    913     while (offset < accessUnit->size()) {
    914         // for subsequent fragments of "buffer":
    915         // 0x47
    916         // transport_error_indicator = b0
    917         // payload_unit_start_indicator = b0
    918         // transport_priority = b0
    919         // PID = b0 0001 1110 ???? (13 bits) [0x1e0 + 1 + sourceIndex]
    920         // transport_scrambling_control = b00
    921         // adaptation_field_control = b01 (no adaptation field, payload only)
    922         // continuity_counter = b????
    923         // the fragment of "buffer" follows.
    924 
    925         memset(buffer->data(), 0, buffer->size());
    926 
    927         const unsigned continuity_counter =
    928             mSources.editItemAt(sourceIndex)->incrementContinuityCounter();
    929 
    930         ptr = buffer->data();
    931         *ptr++ = 0x47;
    932         *ptr++ = 0x00 | (PID >> 8);
    933         *ptr++ = PID & 0xff;
    934         *ptr++ = 0x10 | continuity_counter;
    935 
    936         size_t sizeLeft = buffer->data() + buffer->size() - ptr;
    937         size_t copy = accessUnit->size() - offset;
    938         if (copy > sizeLeft) {
    939             copy = sizeLeft;
    940         }
    941 
    942         memcpy(ptr, accessUnit->data() + offset, copy);
    943         CHECK_EQ(internalWrite(buffer->data(), buffer->size()),
    944                  buffer->size());
    945 
    946         offset += copy;
    947     }
    948 }
    949 
    950 void MPEG2TSWriter::writeTS() {
    951     if (mNumTSPacketsWritten >= mNumTSPacketsBeforeMeta) {
    952         writeProgramAssociationTable();
    953         writeProgramMap();
    954 
    955         mNumTSPacketsBeforeMeta = mNumTSPacketsWritten + 2500;
    956     }
    957 }
    958 
    959 ssize_t MPEG2TSWriter::internalWrite(const void *data, size_t size) {
    960     if (mFile != NULL) {
    961         return fwrite(data, 1, size, mFile);
    962     }
    963 
    964     return (*mWriteFunc)(mWriteCookie, data, size);
    965 }
    966 
    967 }  // namespace android
    968 
    969