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
33namespace android {
34
35struct 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
62protected:
63    virtual ~Track();
64
65private:
66    sp<AMessage> mFormat;
67
68    unsigned mPID;
69    unsigned mStreamType;
70    unsigned mStreamID;
71    unsigned mContinuityCounter;
72
73    AString mMIME;
74    Vector<sp<ABuffer> > mCSD;
75
76    Vector<sp<ABuffer> > mDescriptors;
77
78    bool mAudioLacksATDSHeaders;
79    bool mFinalized;
80
81    DISALLOW_EVIL_CONSTRUCTORS(Track);
82};
83
84TSPacketizer::Track::Track(
85        const sp<AMessage> &format,
86        unsigned PID, unsigned streamType, unsigned streamID)
87    : mFormat(format),
88      mPID(PID),
89      mStreamType(streamType),
90      mStreamID(streamID),
91      mContinuityCounter(0),
92      mAudioLacksATDSHeaders(false),
93      mFinalized(false) {
94    CHECK(format->findString("mime", &mMIME));
95
96    if (!strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_VIDEO_AVC)
97            || !strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
98        for (size_t i = 0;; ++i) {
99            sp<ABuffer> csd;
100            if (!format->findBuffer(StringPrintf("csd-%d", i).c_str(), &csd)) {
101                break;
102            }
103
104            mCSD.push(csd);
105        }
106
107        if (!strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
108            int32_t isADTS;
109            if (!mFormat->findInt32("is-adts", &isADTS) || isADTS == 0) {
110                mAudioLacksATDSHeaders = true;
111            }
112        }
113    }
114}
115
116TSPacketizer::Track::~Track() {
117}
118
119unsigned TSPacketizer::Track::PID() const {
120    return mPID;
121}
122
123unsigned TSPacketizer::Track::streamType() const {
124    return mStreamType;
125}
126
127unsigned TSPacketizer::Track::streamID() const {
128    return mStreamID;
129}
130
131unsigned TSPacketizer::Track::incrementContinuityCounter() {
132    unsigned prevCounter = mContinuityCounter;
133
134    if (++mContinuityCounter == 16) {
135        mContinuityCounter = 0;
136    }
137
138    return prevCounter;
139}
140
141bool TSPacketizer::Track::isAudio() const {
142    return !strncasecmp("audio/", mMIME.c_str(), 6);
143}
144
145bool TSPacketizer::Track::isVideo() const {
146    return !strncasecmp("video/", mMIME.c_str(), 6);
147}
148
149bool TSPacketizer::Track::isH264() const {
150    return !strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_VIDEO_AVC);
151}
152
153bool TSPacketizer::Track::isAAC() const {
154    return !strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_AUDIO_AAC);
155}
156
157bool TSPacketizer::Track::isPCMAudio() const {
158    return !strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_AUDIO_RAW);
159}
160
161bool TSPacketizer::Track::lacksADTSHeader() const {
162    return mAudioLacksATDSHeaders;
163}
164
165sp<ABuffer> TSPacketizer::Track::prependCSD(
166        const sp<ABuffer> &accessUnit) const {
167    size_t size = 0;
168    for (size_t i = 0; i < mCSD.size(); ++i) {
169        size += mCSD.itemAt(i)->size();
170    }
171
172    sp<ABuffer> dup = new ABuffer(accessUnit->size() + size);
173    size_t offset = 0;
174    for (size_t i = 0; i < mCSD.size(); ++i) {
175        const sp<ABuffer> &csd = mCSD.itemAt(i);
176
177        memcpy(dup->data() + offset, csd->data(), csd->size());
178        offset += csd->size();
179    }
180
181    memcpy(dup->data() + offset, accessUnit->data(), accessUnit->size());
182
183    return dup;
184}
185
186sp<ABuffer> TSPacketizer::Track::prependADTSHeader(
187        const sp<ABuffer> &accessUnit) const {
188    CHECK_EQ(mCSD.size(), 1u);
189
190    const uint8_t *codec_specific_data = mCSD.itemAt(0)->data();
191
192    const uint32_t aac_frame_length = accessUnit->size() + 7;
193
194    sp<ABuffer> dup = new ABuffer(aac_frame_length);
195
196    unsigned profile = (codec_specific_data[0] >> 3) - 1;
197
198    unsigned sampling_freq_index =
199        ((codec_specific_data[0] & 7) << 1)
200        | (codec_specific_data[1] >> 7);
201
202    unsigned channel_configuration =
203        (codec_specific_data[1] >> 3) & 0x0f;
204
205    uint8_t *ptr = dup->data();
206
207    *ptr++ = 0xff;
208    *ptr++ = 0xf1;  // b11110001, ID=0, layer=0, protection_absent=1
209
210    *ptr++ =
211        profile << 6
212        | sampling_freq_index << 2
213        | ((channel_configuration >> 2) & 1);  // private_bit=0
214
215    // original_copy=0, home=0, copyright_id_bit=0, copyright_id_start=0
216    *ptr++ =
217        (channel_configuration & 3) << 6
218        | aac_frame_length >> 11;
219    *ptr++ = (aac_frame_length >> 3) & 0xff;
220    *ptr++ = (aac_frame_length & 7) << 5;
221
222    // adts_buffer_fullness=0, number_of_raw_data_blocks_in_frame=0
223    *ptr++ = 0;
224
225    memcpy(ptr, accessUnit->data(), accessUnit->size());
226
227    return dup;
228}
229
230size_t TSPacketizer::Track::countDescriptors() const {
231    return mDescriptors.size();
232}
233
234sp<ABuffer> TSPacketizer::Track::descriptorAt(size_t index) const {
235    CHECK_LT(index, mDescriptors.size());
236    return mDescriptors.itemAt(index);
237}
238
239void TSPacketizer::Track::finalize() {
240    if (mFinalized) {
241        return;
242    }
243
244    if (isH264()) {
245        {
246            // AVC video descriptor (40)
247
248            sp<ABuffer> descriptor = new ABuffer(6);
249            uint8_t *data = descriptor->data();
250            data[0] = 40;  // descriptor_tag
251            data[1] = 4;  // descriptor_length
252
253            CHECK_EQ(mCSD.size(), 1u);
254            const sp<ABuffer> &sps = mCSD.itemAt(0);
255            CHECK(!memcmp("\x00\x00\x00\x01", sps->data(), 4));
256            CHECK_GE(sps->size(), 7u);
257            // profile_idc, constraint_set*, level_idc
258            memcpy(&data[2], sps->data() + 4, 3);
259
260            // AVC_still_present=0, AVC_24_hour_picture_flag=0, reserved
261            data[5] = 0x3f;
262
263            mDescriptors.push_back(descriptor);
264        }
265
266        {
267            // AVC timing and HRD descriptor (42)
268
269            sp<ABuffer> descriptor = new ABuffer(4);
270            uint8_t *data = descriptor->data();
271            data[0] = 42;  // descriptor_tag
272            data[1] = 2;  // descriptor_length
273
274            // hrd_management_valid_flag = 0
275            // reserved = 111111b
276            // picture_and_timing_info_present = 0
277
278            data[2] = 0x7e;
279
280            // fixed_frame_rate_flag = 0
281            // temporal_poc_flag = 0
282            // picture_to_display_conversion_flag = 0
283            // reserved = 11111b
284            data[3] = 0x1f;
285
286            mDescriptors.push_back(descriptor);
287        }
288    } else if (isPCMAudio()) {
289        // LPCM audio stream descriptor (0x83)
290
291        int32_t channelCount;
292        CHECK(mFormat->findInt32("channel-count", &channelCount));
293        CHECK_EQ(channelCount, 2);
294
295        int32_t sampleRate;
296        CHECK(mFormat->findInt32("sample-rate", &sampleRate));
297        CHECK(sampleRate == 44100 || sampleRate == 48000);
298
299        sp<ABuffer> descriptor = new ABuffer(4);
300        uint8_t *data = descriptor->data();
301        data[0] = 0x83;  // descriptor_tag
302        data[1] = 2;  // descriptor_length
303
304        unsigned sampling_frequency = (sampleRate == 44100) ? 1 : 2;
305
306        data[2] = (sampling_frequency << 5)
307                    | (3 /* reserved */ << 1)
308                    | 0 /* emphasis_flag */;
309
310        data[3] =
311            (1 /* number_of_channels = stereo */ << 5)
312            | 0xf /* reserved */;
313
314        mDescriptors.push_back(descriptor);
315    }
316
317    mFinalized = true;
318}
319
320////////////////////////////////////////////////////////////////////////////////
321
322TSPacketizer::TSPacketizer()
323    : mPATContinuityCounter(0),
324      mPMTContinuityCounter(0) {
325    initCrcTable();
326}
327
328TSPacketizer::~TSPacketizer() {
329}
330
331ssize_t TSPacketizer::addTrack(const sp<AMessage> &format) {
332    AString mime;
333    CHECK(format->findString("mime", &mime));
334
335    unsigned PIDStart;
336    bool isVideo = !strncasecmp("video/", mime.c_str(), 6);
337    bool isAudio = !strncasecmp("audio/", mime.c_str(), 6);
338
339    if (isVideo) {
340        PIDStart = 0x1011;
341    } else if (isAudio) {
342        PIDStart = 0x1100;
343    } else {
344        return ERROR_UNSUPPORTED;
345    }
346
347    unsigned streamType;
348    unsigned streamIDStart;
349    unsigned streamIDStop;
350
351    if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_VIDEO_AVC)) {
352        streamType = 0x1b;
353        streamIDStart = 0xe0;
354        streamIDStop = 0xef;
355    } else if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
356        streamType = 0x0f;
357        streamIDStart = 0xc0;
358        streamIDStop = 0xdf;
359    } else if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_RAW)) {
360        streamType = 0x83;
361        streamIDStart = 0xbd;
362        streamIDStop = 0xbd;
363    } else {
364        return ERROR_UNSUPPORTED;
365    }
366
367    size_t numTracksOfThisType = 0;
368    unsigned PID = PIDStart;
369
370    for (size_t i = 0; i < mTracks.size(); ++i) {
371        const sp<Track> &track = mTracks.itemAt(i);
372
373        if (track->streamType() == streamType) {
374            ++numTracksOfThisType;
375        }
376
377        if ((isAudio && track->isAudio()) || (isVideo && track->isVideo())) {
378            ++PID;
379        }
380    }
381
382    unsigned streamID = streamIDStart + numTracksOfThisType;
383    if (streamID > streamIDStop) {
384        return -ERANGE;
385    }
386
387    sp<Track> track = new Track(format, PID, streamType, streamID);
388    return mTracks.add(track);
389}
390
391status_t TSPacketizer::packetize(
392        size_t trackIndex,
393        const sp<ABuffer> &_accessUnit,
394        sp<ABuffer> *packets,
395        uint32_t flags,
396        const uint8_t *PES_private_data, size_t PES_private_data_len,
397        size_t numStuffingBytes) {
398    sp<ABuffer> accessUnit = _accessUnit;
399
400    int64_t timeUs;
401    CHECK(accessUnit->meta()->findInt64("timeUs", &timeUs));
402
403    packets->clear();
404
405    if (trackIndex >= mTracks.size()) {
406        return -ERANGE;
407    }
408
409    const sp<Track> &track = mTracks.itemAt(trackIndex);
410
411    if (track->isH264() && (flags & PREPEND_SPS_PPS_TO_IDR_FRAMES)
412            && IsIDR(accessUnit)) {
413        // prepend codec specific data, i.e. SPS and PPS.
414        accessUnit = track->prependCSD(accessUnit);
415    } else if (track->isAAC() && track->lacksADTSHeader()) {
416        CHECK(!(flags & IS_ENCRYPTED));
417        accessUnit = track->prependADTSHeader(accessUnit);
418    }
419
420    // 0x47
421    // transport_error_indicator = b0
422    // payload_unit_start_indicator = b1
423    // transport_priority = b0
424    // PID
425    // transport_scrambling_control = b00
426    // adaptation_field_control = b??
427    // continuity_counter = b????
428    // -- payload follows
429    // packet_startcode_prefix = 0x000001
430    // stream_id
431    // PES_packet_length = 0x????
432    // reserved = b10
433    // PES_scrambling_control = b00
434    // PES_priority = b0
435    // data_alignment_indicator = b1
436    // copyright = b0
437    // original_or_copy = b0
438    // PTS_DTS_flags = b10  (PTS only)
439    // ESCR_flag = b0
440    // ES_rate_flag = b0
441    // DSM_trick_mode_flag = b0
442    // additional_copy_info_flag = b0
443    // PES_CRC_flag = b0
444    // PES_extension_flag = b0
445    // PES_header_data_length = 0x05
446    // reserved = b0010 (PTS)
447    // PTS[32..30] = b???
448    // reserved = b1
449    // PTS[29..15] = b??? ???? ???? ???? (15 bits)
450    // reserved = b1
451    // PTS[14..0] = b??? ???? ???? ???? (15 bits)
452    // reserved = b1
453    // the first fragment of "buffer" follows
454
455    size_t PES_packet_length = accessUnit->size() + 8 + numStuffingBytes;
456    if (PES_private_data_len > 0) {
457        PES_packet_length += PES_private_data_len + 1;
458    }
459
460    size_t numTSPackets;
461    if (PES_packet_length <= 178) {
462        numTSPackets = 1;
463    } else {
464        numTSPackets = 1 + ((PES_packet_length - 178) + 183) / 184;
465    }
466
467    if (flags & EMIT_PAT_AND_PMT) {
468        numTSPackets += 2;
469    }
470
471    if (flags & EMIT_PCR) {
472        ++numTSPackets;
473    }
474
475    sp<ABuffer> buffer = new ABuffer(numTSPackets * 188);
476    uint8_t *packetDataStart = buffer->data();
477
478    if (flags & EMIT_PAT_AND_PMT) {
479        // Program Association Table (PAT):
480        // 0x47
481        // transport_error_indicator = b0
482        // payload_unit_start_indicator = b1
483        // transport_priority = b0
484        // PID = b0000000000000 (13 bits)
485        // transport_scrambling_control = b00
486        // adaptation_field_control = b01 (no adaptation field, payload only)
487        // continuity_counter = b????
488        // skip = 0x00
489        // --- payload follows
490        // table_id = 0x00
491        // section_syntax_indicator = b1
492        // must_be_zero = b0
493        // reserved = b11
494        // section_length = 0x00d
495        // transport_stream_id = 0x0000
496        // reserved = b11
497        // version_number = b00001
498        // current_next_indicator = b1
499        // section_number = 0x00
500        // last_section_number = 0x00
501        //   one program follows:
502        //   program_number = 0x0001
503        //   reserved = b111
504        //   program_map_PID = kPID_PMT (13 bits!)
505        // CRC = 0x????????
506
507        if (++mPATContinuityCounter == 16) {
508            mPATContinuityCounter = 0;
509        }
510
511        uint8_t *ptr = packetDataStart;
512        *ptr++ = 0x47;
513        *ptr++ = 0x40;
514        *ptr++ = 0x00;
515        *ptr++ = 0x10 | mPATContinuityCounter;
516        *ptr++ = 0x00;
517
518        uint8_t *crcDataStart = ptr;
519        *ptr++ = 0x00;
520        *ptr++ = 0xb0;
521        *ptr++ = 0x0d;
522        *ptr++ = 0x00;
523        *ptr++ = 0x00;
524        *ptr++ = 0xc3;
525        *ptr++ = 0x00;
526        *ptr++ = 0x00;
527        *ptr++ = 0x00;
528        *ptr++ = 0x01;
529        *ptr++ = 0xe0 | (kPID_PMT >> 8);
530        *ptr++ = kPID_PMT & 0xff;
531
532        CHECK_EQ(ptr - crcDataStart, 12);
533        uint32_t crc = htonl(crc32(crcDataStart, ptr - crcDataStart));
534        memcpy(ptr, &crc, 4);
535        ptr += 4;
536
537        size_t sizeLeft = packetDataStart + 188 - ptr;
538        memset(ptr, 0xff, sizeLeft);
539
540        packetDataStart += 188;
541
542        // Program Map (PMT):
543        // 0x47
544        // transport_error_indicator = b0
545        // payload_unit_start_indicator = b1
546        // transport_priority = b0
547        // PID = kPID_PMT (13 bits)
548        // transport_scrambling_control = b00
549        // adaptation_field_control = b01 (no adaptation field, payload only)
550        // continuity_counter = b????
551        // skip = 0x00
552        // -- payload follows
553        // table_id = 0x02
554        // section_syntax_indicator = b1
555        // must_be_zero = b0
556        // reserved = b11
557        // section_length = 0x???
558        // program_number = 0x0001
559        // reserved = b11
560        // version_number = b00001
561        // current_next_indicator = b1
562        // section_number = 0x00
563        // last_section_number = 0x00
564        // reserved = b111
565        // PCR_PID = kPCR_PID (13 bits)
566        // reserved = b1111
567        // program_info_length = 0x000
568        //   one or more elementary stream descriptions follow:
569        //   stream_type = 0x??
570        //   reserved = b111
571        //   elementary_PID = b? ???? ???? ???? (13 bits)
572        //   reserved = b1111
573        //   ES_info_length = 0x000
574        // CRC = 0x????????
575
576        if (++mPMTContinuityCounter == 16) {
577            mPMTContinuityCounter = 0;
578        }
579
580        ptr = packetDataStart;
581        *ptr++ = 0x47;
582        *ptr++ = 0x40 | (kPID_PMT >> 8);
583        *ptr++ = kPID_PMT & 0xff;
584        *ptr++ = 0x10 | mPMTContinuityCounter;
585        *ptr++ = 0x00;
586
587        crcDataStart = ptr;
588        *ptr++ = 0x02;
589
590        *ptr++ = 0x00;  // section_length to be filled in below.
591        *ptr++ = 0x00;
592
593        *ptr++ = 0x00;
594        *ptr++ = 0x01;
595        *ptr++ = 0xc3;
596        *ptr++ = 0x00;
597        *ptr++ = 0x00;
598        *ptr++ = 0xe0 | (kPID_PCR >> 8);
599        *ptr++ = kPID_PCR & 0xff;
600        *ptr++ = 0xf0;
601        *ptr++ = 0x00;
602
603        for (size_t i = 0; i < mTracks.size(); ++i) {
604            const sp<Track> &track = mTracks.itemAt(i);
605
606            // Make sure all the decriptors have been added.
607            track->finalize();
608
609            *ptr++ = track->streamType();
610            *ptr++ = 0xe0 | (track->PID() >> 8);
611            *ptr++ = track->PID() & 0xff;
612
613            size_t ES_info_length = 0;
614            for (size_t i = 0; i < track->countDescriptors(); ++i) {
615                ES_info_length += track->descriptorAt(i)->size();
616            }
617            CHECK_LE(ES_info_length, 0xfff);
618
619            *ptr++ = 0xf0 | (ES_info_length >> 8);
620            *ptr++ = (ES_info_length & 0xff);
621
622            for (size_t i = 0; i < track->countDescriptors(); ++i) {
623                const sp<ABuffer> &descriptor = track->descriptorAt(i);
624                memcpy(ptr, descriptor->data(), descriptor->size());
625                ptr += descriptor->size();
626            }
627        }
628
629        size_t section_length = ptr - (crcDataStart + 3) + 4 /* CRC */;
630
631        crcDataStart[1] = 0xb0 | (section_length >> 8);
632        crcDataStart[2] = section_length & 0xff;
633
634        crc = htonl(crc32(crcDataStart, ptr - crcDataStart));
635        memcpy(ptr, &crc, 4);
636        ptr += 4;
637
638        sizeLeft = packetDataStart + 188 - ptr;
639        memset(ptr, 0xff, sizeLeft);
640
641        packetDataStart += 188;
642    }
643
644    if (flags & EMIT_PCR) {
645        // PCR stream
646        // 0x47
647        // transport_error_indicator = b0
648        // payload_unit_start_indicator = b1
649        // transport_priority = b0
650        // PID = kPCR_PID (13 bits)
651        // transport_scrambling_control = b00
652        // adaptation_field_control = b10 (adaptation field only, no payload)
653        // continuity_counter = b0000 (does not increment)
654        // adaptation_field_length = 183
655        // discontinuity_indicator = b0
656        // random_access_indicator = b0
657        // elementary_stream_priority_indicator = b0
658        // PCR_flag = b1
659        // OPCR_flag = b0
660        // splicing_point_flag = b0
661        // transport_private_data_flag = b0
662        // adaptation_field_extension_flag = b0
663        // program_clock_reference_base = b?????????????????????????????????
664        // reserved = b111111
665        // program_clock_reference_extension = b?????????
666
667        int64_t nowUs = ALooper::GetNowUs();
668
669        uint64_t PCR = nowUs * 27;  // PCR based on a 27MHz clock
670        uint64_t PCR_base = PCR / 300;
671        uint32_t PCR_ext = PCR % 300;
672
673        uint8_t *ptr = packetDataStart;
674        *ptr++ = 0x47;
675        *ptr++ = 0x40 | (kPID_PCR >> 8);
676        *ptr++ = kPID_PCR & 0xff;
677        *ptr++ = 0x20;
678        *ptr++ = 0xb7;  // adaptation_field_length
679        *ptr++ = 0x10;
680        *ptr++ = (PCR_base >> 25) & 0xff;
681        *ptr++ = (PCR_base >> 17) & 0xff;
682        *ptr++ = (PCR_base >> 9) & 0xff;
683        *ptr++ = ((PCR_base & 1) << 7) | 0x7e | ((PCR_ext >> 8) & 1);
684        *ptr++ = (PCR_ext & 0xff);
685
686        size_t sizeLeft = packetDataStart + 188 - ptr;
687        memset(ptr, 0xff, sizeLeft);
688
689        packetDataStart += 188;
690    }
691
692    uint64_t PTS = (timeUs * 9ll) / 100ll;
693
694    bool padding = (PES_packet_length < (188 - 10));
695
696    if (PES_packet_length >= 65536) {
697        // This really should only happen for video.
698        CHECK(track->isVideo());
699
700        // It's valid to set this to 0 for video according to the specs.
701        PES_packet_length = 0;
702    }
703
704    uint8_t *ptr = packetDataStart;
705    *ptr++ = 0x47;
706    *ptr++ = 0x40 | (track->PID() >> 8);
707    *ptr++ = track->PID() & 0xff;
708    *ptr++ = (padding ? 0x30 : 0x10) | track->incrementContinuityCounter();
709
710    if (padding) {
711        size_t paddingSize = 188 - 10 - PES_packet_length;
712        *ptr++ = paddingSize - 1;
713        if (paddingSize >= 2) {
714            *ptr++ = 0x00;
715            memset(ptr, 0xff, paddingSize - 2);
716            ptr += paddingSize - 2;
717        }
718    }
719
720    *ptr++ = 0x00;
721    *ptr++ = 0x00;
722    *ptr++ = 0x01;
723    *ptr++ = track->streamID();
724    *ptr++ = PES_packet_length >> 8;
725    *ptr++ = PES_packet_length & 0xff;
726    *ptr++ = 0x84;
727    *ptr++ = (PES_private_data_len > 0) ? 0x81 : 0x80;
728
729    size_t headerLength = 0x05 + numStuffingBytes;
730    if (PES_private_data_len > 0) {
731        headerLength += 1 + PES_private_data_len;
732    }
733
734    *ptr++ = headerLength;
735
736    *ptr++ = 0x20 | (((PTS >> 30) & 7) << 1) | 1;
737    *ptr++ = (PTS >> 22) & 0xff;
738    *ptr++ = (((PTS >> 15) & 0x7f) << 1) | 1;
739    *ptr++ = (PTS >> 7) & 0xff;
740    *ptr++ = ((PTS & 0x7f) << 1) | 1;
741
742    if (PES_private_data_len > 0) {
743        *ptr++ = 0x8e;  // PES_private_data_flag, reserved.
744        memcpy(ptr, PES_private_data, PES_private_data_len);
745        ptr += PES_private_data_len;
746    }
747
748    for (size_t i = 0; i < numStuffingBytes; ++i) {
749        *ptr++ = 0xff;
750    }
751
752    // 18 bytes of TS/PES header leave 188 - 18 = 170 bytes for the payload
753
754    size_t sizeLeft = packetDataStart + 188 - ptr;
755    size_t copy = accessUnit->size();
756    if (copy > sizeLeft) {
757        copy = sizeLeft;
758    }
759
760    memcpy(ptr, accessUnit->data(), copy);
761    ptr += copy;
762    CHECK_EQ(sizeLeft, copy);
763    memset(ptr, 0xff, sizeLeft - copy);
764
765    packetDataStart += 188;
766
767    size_t offset = copy;
768    while (offset < accessUnit->size()) {
769        bool padding = (accessUnit->size() - offset) < (188 - 4);
770
771        // for subsequent fragments of "buffer":
772        // 0x47
773        // transport_error_indicator = b0
774        // payload_unit_start_indicator = b0
775        // transport_priority = b0
776        // PID = b0 0001 1110 ???? (13 bits) [0x1e0 + 1 + sourceIndex]
777        // transport_scrambling_control = b00
778        // adaptation_field_control = b??
779        // continuity_counter = b????
780        // the fragment of "buffer" follows.
781
782        uint8_t *ptr = packetDataStart;
783        *ptr++ = 0x47;
784        *ptr++ = 0x00 | (track->PID() >> 8);
785        *ptr++ = track->PID() & 0xff;
786
787        *ptr++ = (padding ? 0x30 : 0x10) | track->incrementContinuityCounter();
788
789        if (padding) {
790            size_t paddingSize = 188 - 4 - (accessUnit->size() - offset);
791            *ptr++ = paddingSize - 1;
792            if (paddingSize >= 2) {
793                *ptr++ = 0x00;
794                memset(ptr, 0xff, paddingSize - 2);
795                ptr += paddingSize - 2;
796            }
797        }
798
799        // 4 bytes of TS header leave 188 - 4 = 184 bytes for the payload
800
801        size_t sizeLeft = packetDataStart + 188 - ptr;
802        size_t copy = accessUnit->size() - offset;
803        if (copy > sizeLeft) {
804            copy = sizeLeft;
805        }
806
807        memcpy(ptr, accessUnit->data() + offset, copy);
808        ptr += copy;
809        CHECK_EQ(sizeLeft, copy);
810        memset(ptr, 0xff, sizeLeft - copy);
811
812        offset += copy;
813        packetDataStart += 188;
814    }
815
816    CHECK(packetDataStart == buffer->data() + buffer->capacity());
817
818    *packets = buffer;
819
820    return OK;
821}
822
823void TSPacketizer::initCrcTable() {
824    uint32_t poly = 0x04C11DB7;
825
826    for (int i = 0; i < 256; i++) {
827        uint32_t crc = i << 24;
828        for (int j = 0; j < 8; j++) {
829            crc = (crc << 1) ^ ((crc & 0x80000000) ? (poly) : 0);
830        }
831        mCrcTable[i] = crc;
832    }
833}
834
835uint32_t TSPacketizer::crc32(const uint8_t *start, size_t size) const {
836    uint32_t crc = 0xFFFFFFFF;
837    const uint8_t *p;
838
839    for (p = start; p < start + size; ++p) {
840        crc = (crc << 8) ^ mCrcTable[((crc >> 24) ^ *p) & 0xFF];
841    }
842
843    return crc;
844}
845
846sp<ABuffer> TSPacketizer::prependCSD(
847        size_t trackIndex, const sp<ABuffer> &accessUnit) const {
848    CHECK_LT(trackIndex, mTracks.size());
849
850    const sp<Track> &track = mTracks.itemAt(trackIndex);
851    CHECK(track->isH264() && IsIDR(accessUnit));
852
853    int64_t timeUs;
854    CHECK(accessUnit->meta()->findInt64("timeUs", &timeUs));
855
856    sp<ABuffer> accessUnit2 = track->prependCSD(accessUnit);
857
858    accessUnit2->meta()->setInt64("timeUs", timeUs);
859
860    return accessUnit2;
861}
862
863}  // namespace android
864
865