Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegtsenc.c @ a7827a17

History | View | Annotate | Download (30.2 KB)

1
/*
2
 * MPEG2 transport stream (aka DVB) muxer
3
 * Copyright (c) 2003 Fabrice Bellard
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21

    
22
#include "libavutil/bswap.h"
23
#include "libavutil/crc.h"
24
#include "libavcodec/mpegvideo.h"
25
#include "avformat.h"
26
#include "internal.h"
27
#include "mpegts.h"
28
#include "adts.h"
29

    
30
#define PCR_TIME_BASE 27000000
31

    
32
/* write DVB SI sections */
33

    
34
/*********************************************/
35
/* mpegts section writer */
36

    
37
typedef struct MpegTSSection {
38
    int pid;
39
    int cc;
40
    void (*write_packet)(struct MpegTSSection *s, const uint8_t *packet);
41
    void *opaque;
42
} MpegTSSection;
43

    
44
typedef struct MpegTSService {
45
    MpegTSSection pmt; /* MPEG2 pmt table context */
46
    int sid;           /* service ID */
47
    char *name;
48
    char *provider_name;
49
    int pcr_pid;
50
    int pcr_packet_count;
51
    int pcr_packet_period;
52
} MpegTSService;
53

    
54
typedef struct MpegTSWrite {
55
    MpegTSSection pat; /* MPEG2 pat table */
56
    MpegTSSection sdt; /* MPEG2 sdt table context */
57
    MpegTSService **services;
58
    int sdt_packet_count;
59
    int sdt_packet_period;
60
    int pat_packet_count;
61
    int pat_packet_period;
62
    int nb_services;
63
    int onid;
64
    int tsid;
65
    int64_t first_pcr;
66
    int mux_rate; ///< set to 1 when VBR
67
} MpegTSWrite;
68

    
69
/* NOTE: 4 bytes must be left at the end for the crc32 */
70
static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
71
{
72
    unsigned int crc;
73
    unsigned char packet[TS_PACKET_SIZE];
74
    const unsigned char *buf_ptr;
75
    unsigned char *q;
76
    int first, b, len1, left;
77

    
78
    crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
79
    buf[len - 4] = (crc >> 24) & 0xff;
80
    buf[len - 3] = (crc >> 16) & 0xff;
81
    buf[len - 2] = (crc >> 8) & 0xff;
82
    buf[len - 1] = (crc) & 0xff;
83

    
84
    /* send each packet */
85
    buf_ptr = buf;
86
    while (len > 0) {
87
        first = (buf == buf_ptr);
88
        q = packet;
89
        *q++ = 0x47;
90
        b = (s->pid >> 8);
91
        if (first)
92
            b |= 0x40;
93
        *q++ = b;
94
        *q++ = s->pid;
95
        s->cc = (s->cc + 1) & 0xf;
96
        *q++ = 0x10 | s->cc;
97
        if (first)
98
            *q++ = 0; /* 0 offset */
99
        len1 = TS_PACKET_SIZE - (q - packet);
100
        if (len1 > len)
101
            len1 = len;
102
        memcpy(q, buf_ptr, len1);
103
        q += len1;
104
        /* add known padding data */
105
        left = TS_PACKET_SIZE - (q - packet);
106
        if (left > 0)
107
            memset(q, 0xff, left);
108

    
109
        s->write_packet(s, packet);
110

    
111
        buf_ptr += len1;
112
        len -= len1;
113
    }
114
}
115

    
116
static inline void put16(uint8_t **q_ptr, int val)
117
{
118
    uint8_t *q;
119
    q = *q_ptr;
120
    *q++ = val >> 8;
121
    *q++ = val;
122
    *q_ptr = q;
123
}
124

    
125
static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
126
                          int version, int sec_num, int last_sec_num,
127
                          uint8_t *buf, int len)
128
{
129
    uint8_t section[1024], *q;
130
    unsigned int tot_len;
131
    /* reserved_future_use field must be set to 1 for SDT */
132
    unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
133

    
134
    tot_len = 3 + 5 + len + 4;
135
    /* check if not too big */
136
    if (tot_len > 1024)
137
        return -1;
138

    
139
    q = section;
140
    *q++ = tid;
141
    put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
142
    put16(&q, id);
143
    *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
144
    *q++ = sec_num;
145
    *q++ = last_sec_num;
146
    memcpy(q, buf, len);
147

    
148
    mpegts_write_section(s, section, tot_len);
149
    return 0;
150
}
151

    
152
/*********************************************/
153
/* mpegts writer */
154

    
155
#define DEFAULT_PMT_START_PID   0x1000
156
#define DEFAULT_START_PID       0x0100
157
#define DEFAULT_PROVIDER_NAME   "FFmpeg"
158
#define DEFAULT_SERVICE_NAME    "Service01"
159

    
160
/* default network id, transport stream and service identifiers */
161
#define DEFAULT_ONID            0x0001
162
#define DEFAULT_TSID            0x0001
163
#define DEFAULT_SID             0x0001
164

    
165
/* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
166
#define DEFAULT_PES_HEADER_FREQ 16
167
#define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
168

    
169
/* we retransmit the SI info at this rate */
170
#define SDT_RETRANS_TIME 500
171
#define PAT_RETRANS_TIME 100
172
#define PCR_RETRANS_TIME 20
173

    
174
typedef struct MpegTSWriteStream {
175
    struct MpegTSService *service;
176
    int pid; /* stream associated pid */
177
    int cc;
178
    int payload_index;
179
    int first_pts_check; ///< first pts check needed
180
    int64_t payload_pts;
181
    int64_t payload_dts;
182
    uint8_t payload[DEFAULT_PES_PAYLOAD_SIZE];
183
    ADTSContext *adts;
184
} MpegTSWriteStream;
185

    
186
static void mpegts_write_pat(AVFormatContext *s)
187
{
188
    MpegTSWrite *ts = s->priv_data;
189
    MpegTSService *service;
190
    uint8_t data[1012], *q;
191
    int i;
192

    
193
    q = data;
194
    for(i = 0; i < ts->nb_services; i++) {
195
        service = ts->services[i];
196
        put16(&q, service->sid);
197
        put16(&q, 0xe000 | service->pmt.pid);
198
    }
199
    mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, 0, 0, 0,
200
                          data, q - data);
201
}
202

    
203
static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
204
{
205
    //    MpegTSWrite *ts = s->priv_data;
206
    uint8_t data[1012], *q, *desc_length_ptr, *program_info_length_ptr;
207
    int val, stream_type, i;
208

    
209
    q = data;
210
    put16(&q, 0xe000 | service->pcr_pid);
211

    
212
    program_info_length_ptr = q;
213
    q += 2; /* patched after */
214

    
215
    /* put program info here */
216

    
217
    val = 0xf000 | (q - program_info_length_ptr - 2);
218
    program_info_length_ptr[0] = val >> 8;
219
    program_info_length_ptr[1] = val;
220

    
221
    for(i = 0; i < s->nb_streams; i++) {
222
        AVStream *st = s->streams[i];
223
        MpegTSWriteStream *ts_st = st->priv_data;
224
        AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL,0);
225
        switch(st->codec->codec_id) {
226
        case CODEC_ID_MPEG1VIDEO:
227
        case CODEC_ID_MPEG2VIDEO:
228
            stream_type = STREAM_TYPE_VIDEO_MPEG2;
229
            break;
230
        case CODEC_ID_MPEG4:
231
            stream_type = STREAM_TYPE_VIDEO_MPEG4;
232
            break;
233
        case CODEC_ID_H264:
234
            stream_type = STREAM_TYPE_VIDEO_H264;
235
            break;
236
        case CODEC_ID_DIRAC:
237
            stream_type = STREAM_TYPE_VIDEO_DIRAC;
238
            break;
239
        case CODEC_ID_MP2:
240
        case CODEC_ID_MP3:
241
            stream_type = STREAM_TYPE_AUDIO_MPEG1;
242
            break;
243
        case CODEC_ID_AAC:
244
            stream_type = STREAM_TYPE_AUDIO_AAC;
245
            break;
246
        case CODEC_ID_AC3:
247
            stream_type = STREAM_TYPE_AUDIO_AC3;
248
            break;
249
        default:
250
            stream_type = STREAM_TYPE_PRIVATE_DATA;
251
            break;
252
        }
253
        *q++ = stream_type;
254
        put16(&q, 0xe000 | ts_st->pid);
255
        desc_length_ptr = q;
256
        q += 2; /* patched after */
257

    
258
        /* write optional descriptors here */
259
        switch(st->codec->codec_type) {
260
        case AVMEDIA_TYPE_AUDIO:
261
            if (lang && strlen(lang->value) == 3) {
262
                *q++ = 0x0a; /* ISO 639 language descriptor */
263
                *q++ = 4;
264
                *q++ = lang->value[0];
265
                *q++ = lang->value[1];
266
                *q++ = lang->value[2];
267
                *q++ = 0; /* undefined type */
268
            }
269
            break;
270
        case AVMEDIA_TYPE_SUBTITLE:
271
            {
272
                const char *language;
273
                language = lang && strlen(lang->value)==3 ? lang->value : "eng";
274
                *q++ = 0x59;
275
                *q++ = 8;
276
                *q++ = language[0];
277
                *q++ = language[1];
278
                *q++ = language[2];
279
                *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */
280
                if(st->codec->extradata_size == 4) {
281
                    memcpy(q, st->codec->extradata, 4);
282
                    q += 4;
283
                } else {
284
                    put16(&q, 1); /* page id */
285
                    put16(&q, 1); /* ancillary page id */
286
                }
287
            }
288
            break;
289
        case AVMEDIA_TYPE_VIDEO:
290
            if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
291
                *q++ = 0x05; /*MPEG-2 registration descriptor*/
292
                *q++ = 4;
293
                *q++ = 'd';
294
                *q++ = 'r';
295
                *q++ = 'a';
296
                *q++ = 'c';
297
            }
298
            break;
299
        }
300

    
301
        val = 0xf000 | (q - desc_length_ptr - 2);
302
        desc_length_ptr[0] = val >> 8;
303
        desc_length_ptr[1] = val;
304
    }
305
    mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,
306
                          data, q - data);
307
}
308

    
309
/* NOTE: str == NULL is accepted for an empty string */
310
static void putstr8(uint8_t **q_ptr, const char *str)
311
{
312
    uint8_t *q;
313
    int len;
314

    
315
    q = *q_ptr;
316
    if (!str)
317
        len = 0;
318
    else
319
        len = strlen(str);
320
    *q++ = len;
321
    memcpy(q, str, len);
322
    q += len;
323
    *q_ptr = q;
324
}
325

    
326
static void mpegts_write_sdt(AVFormatContext *s)
327
{
328
    MpegTSWrite *ts = s->priv_data;
329
    MpegTSService *service;
330
    uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
331
    int i, running_status, free_ca_mode, val;
332

    
333
    q = data;
334
    put16(&q, ts->onid);
335
    *q++ = 0xff;
336
    for(i = 0; i < ts->nb_services; i++) {
337
        service = ts->services[i];
338
        put16(&q, service->sid);
339
        *q++ = 0xfc | 0x00; /* currently no EIT info */
340
        desc_list_len_ptr = q;
341
        q += 2;
342
        running_status = 4; /* running */
343
        free_ca_mode = 0;
344

    
345
        /* write only one descriptor for the service name and provider */
346
        *q++ = 0x48;
347
        desc_len_ptr = q;
348
        q++;
349
        *q++ = 0x01; /* digital television service */
350
        putstr8(&q, service->provider_name);
351
        putstr8(&q, service->name);
352
        desc_len_ptr[0] = q - desc_len_ptr - 1;
353

    
354
        /* fill descriptor length */
355
        val = (running_status << 13) | (free_ca_mode << 12) |
356
            (q - desc_list_len_ptr - 2);
357
        desc_list_len_ptr[0] = val >> 8;
358
        desc_list_len_ptr[1] = val;
359
    }
360
    mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, 0, 0, 0,
361
                          data, q - data);
362
}
363

    
364
static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
365
                                         int sid,
366
                                         const char *provider_name,
367
                                         const char *name)
368
{
369
    MpegTSService *service;
370

    
371
    service = av_mallocz(sizeof(MpegTSService));
372
    if (!service)
373
        return NULL;
374
    service->pmt.pid = DEFAULT_PMT_START_PID + ts->nb_services - 1;
375
    service->sid = sid;
376
    service->provider_name = av_strdup(provider_name);
377
    service->name = av_strdup(name);
378
    service->pcr_pid = 0x1fff;
379
    dynarray_add(&ts->services, &ts->nb_services, service);
380
    return service;
381
}
382

    
383
static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
384
{
385
    AVFormatContext *ctx = s->opaque;
386
    put_buffer(ctx->pb, packet, TS_PACKET_SIZE);
387
}
388

    
389
static int mpegts_write_header(AVFormatContext *s)
390
{
391
    MpegTSWrite *ts = s->priv_data;
392
    MpegTSWriteStream *ts_st;
393
    MpegTSService *service;
394
    AVStream *st, *pcr_st = NULL;
395
    AVMetadataTag *title, *provider;
396
    int i, j;
397
    const char *service_name;
398
    const char *provider_name;
399
    int *pids;
400

    
401
    ts->tsid = DEFAULT_TSID;
402
    ts->onid = DEFAULT_ONID;
403
    /* allocate a single DVB service */
404
    title = av_metadata_get(s->metadata, "service_name", NULL, 0);
405
    if (!title)
406
        title = av_metadata_get(s->metadata, "title", NULL, 0);
407
    service_name = title ? title->value : DEFAULT_SERVICE_NAME;
408
    provider = av_metadata_get(s->metadata, "service_provider", NULL, 0);
409
    provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
410
    service = mpegts_add_service(ts, DEFAULT_SID, provider_name, service_name);
411
    service->pmt.write_packet = section_write_packet;
412
    service->pmt.opaque = s;
413
    service->pmt.cc = 15;
414

    
415
    ts->pat.pid = PAT_PID;
416
    ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
417
    ts->pat.write_packet = section_write_packet;
418
    ts->pat.opaque = s;
419

    
420
    ts->sdt.pid = SDT_PID;
421
    ts->sdt.cc = 15;
422
    ts->sdt.write_packet = section_write_packet;
423
    ts->sdt.opaque = s;
424

    
425
    pids = av_malloc(s->nb_streams * sizeof(*pids));
426
    if (!pids)
427
        return AVERROR(ENOMEM);
428

    
429
    /* assign pids to each stream */
430
    for(i = 0;i < s->nb_streams; i++) {
431
        st = s->streams[i];
432
        ts_st = av_mallocz(sizeof(MpegTSWriteStream));
433
        if (!ts_st)
434
            goto fail;
435
        st->priv_data = ts_st;
436
        ts_st->service = service;
437
        /* MPEG pid values < 16 are reserved. Applications which set st->id in
438
         * this range are assigned a calculated pid. */
439
        if (st->id < 16) {
440
            ts_st->pid = DEFAULT_START_PID + i;
441
        } else if (st->id < 0x1FFF) {
442
            ts_st->pid = st->id;
443
        } else {
444
            av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
445
            goto fail;
446
        }
447
        if (ts_st->pid == service->pmt.pid) {
448
            av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
449
            goto fail;
450
        }
451
        for (j = 0; j < i; j++)
452
            if (pids[j] == ts_st->pid) {
453
                av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
454
                goto fail;
455
            }
456
        pids[i] = ts_st->pid;
457
        ts_st->payload_pts = AV_NOPTS_VALUE;
458
        ts_st->payload_dts = AV_NOPTS_VALUE;
459
        ts_st->first_pts_check = 1;
460
        ts_st->cc = 15;
461
        /* update PCR pid by using the first video stream */
462
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
463
            service->pcr_pid == 0x1fff) {
464
            service->pcr_pid = ts_st->pid;
465
            pcr_st = st;
466
        }
467
        if (st->codec->codec_id == CODEC_ID_AAC &&
468
            st->codec->extradata_size > 0) {
469
            ts_st->adts = av_mallocz(sizeof(*ts_st->adts));
470
            if (!ts_st->adts)
471
                return AVERROR(ENOMEM);
472
            if (ff_adts_decode_extradata(s, ts_st->adts, st->codec->extradata,
473
                                         st->codec->extradata_size) < 0)
474
                return -1;
475
        }
476
    }
477

    
478
    av_free(pids);
479

    
480
    /* if no video stream, use the first stream as PCR */
481
    if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
482
        pcr_st = s->streams[0];
483
        ts_st = pcr_st->priv_data;
484
        service->pcr_pid = ts_st->pid;
485
    }
486

    
487
    ts->mux_rate = s->mux_rate ? s->mux_rate : 1;
488

    
489
    if (ts->mux_rate > 1) {
490
        service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
491
            (TS_PACKET_SIZE * 8 * 1000);
492
        ts->sdt_packet_period      = (ts->mux_rate * SDT_RETRANS_TIME) /
493
            (TS_PACKET_SIZE * 8 * 1000);
494
        ts->pat_packet_period      = (ts->mux_rate * PAT_RETRANS_TIME) /
495
            (TS_PACKET_SIZE * 8 * 1000);
496

    
497
        ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
498
    } else {
499
        /* Arbitrary values, PAT/PMT could be written on key frames */
500
        ts->sdt_packet_period = 200;
501
        ts->pat_packet_period = 40;
502
        if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
503
            if (!pcr_st->codec->frame_size) {
504
                av_log(s, AV_LOG_WARNING, "frame size not set\n");
505
                service->pcr_packet_period =
506
                    pcr_st->codec->sample_rate/(10*512);
507
            } else {
508
                service->pcr_packet_period =
509
                    pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
510
            }
511
        } else {
512
            // max delta PCR 0.1s
513
            service->pcr_packet_period =
514
                pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
515
        }
516
    }
517

    
518
    // output a PCR as soon as possible
519
    service->pcr_packet_count = service->pcr_packet_period;
520
    ts->pat_packet_count = ts->pat_packet_period-1;
521
    ts->sdt_packet_count = ts->sdt_packet_period-1;
522

    
523
    if (ts->mux_rate == 1)
524
        av_log(s, AV_LOG_INFO, "muxrate VBR, ");
525
    else
526
        av_log(s, AV_LOG_INFO, "muxrate %d, ", ts->mux_rate);
527
    av_log(s, AV_LOG_INFO, "pcr every %d pkts, "
528
           "sdt every %d, pat/pmt every %d pkts\n",
529
           service->pcr_packet_period,
530
           ts->sdt_packet_period, ts->pat_packet_period);
531

    
532
    put_flush_packet(s->pb);
533

    
534
    return 0;
535

    
536
 fail:
537
    av_free(pids);
538
    for(i = 0;i < s->nb_streams; i++) {
539
        st = s->streams[i];
540
        av_free(st->priv_data);
541
    }
542
    return -1;
543
}
544

    
545
/* send SDT, PAT and PMT tables regulary */
546
static void retransmit_si_info(AVFormatContext *s)
547
{
548
    MpegTSWrite *ts = s->priv_data;
549
    int i;
550

    
551
    if (++ts->sdt_packet_count == ts->sdt_packet_period) {
552
        ts->sdt_packet_count = 0;
553
        mpegts_write_sdt(s);
554
    }
555
    if (++ts->pat_packet_count == ts->pat_packet_period) {
556
        ts->pat_packet_count = 0;
557
        mpegts_write_pat(s);
558
        for(i = 0; i < ts->nb_services; i++) {
559
            mpegts_write_pmt(s, ts->services[i]);
560
        }
561
    }
562
}
563

    
564
static int64_t get_pcr(const MpegTSWrite *ts, ByteIOContext *pb)
565
{
566
    return av_rescale(url_ftell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
567
           ts->first_pcr;
568
}
569

    
570
static uint8_t* write_pcr_bits(uint8_t *buf, int64_t pcr)
571
{
572
    int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
573

    
574
    *buf++ = pcr_high >> 25;
575
    *buf++ = pcr_high >> 17;
576
    *buf++ = pcr_high >> 9;
577
    *buf++ = pcr_high >> 1;
578
    *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
579
    *buf++ = pcr_low;
580

    
581
    return buf;
582
}
583

    
584
/* Write a single null transport stream packet */
585
static void mpegts_insert_null_packet(AVFormatContext *s)
586
{
587
    uint8_t *q;
588
    uint8_t buf[TS_PACKET_SIZE];
589

    
590
    q = buf;
591
    *q++ = 0x47;
592
    *q++ = 0x00 | 0x1f;
593
    *q++ = 0xff;
594
    *q++ = 0x10;
595
    memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
596
    put_buffer(s->pb, buf, TS_PACKET_SIZE);
597
}
598

    
599
/* Write a single transport stream packet with a PCR and no payload */
600
static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
601
{
602
    MpegTSWrite *ts = s->priv_data;
603
    MpegTSWriteStream *ts_st = st->priv_data;
604
    uint8_t *q;
605
    uint8_t buf[TS_PACKET_SIZE];
606

    
607
    q = buf;
608
    *q++ = 0x47;
609
    *q++ = ts_st->pid >> 8;
610
    *q++ = ts_st->pid;
611
    *q++ = 0x20 | ts_st->cc;   /* Adaptation only */
612
    /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
613
    *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
614
    *q++ = 0x10;               /* Adaptation flags: PCR present */
615

    
616
    /* PCR coded into 6 bytes */
617
    q = write_pcr_bits(q, get_pcr(ts, s->pb));
618

    
619
    /* stuffing bytes */
620
    memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
621
    put_buffer(s->pb, buf, TS_PACKET_SIZE);
622
}
623

    
624
static void write_pts(uint8_t *q, int fourbits, int64_t pts)
625
{
626
    int val;
627

    
628
    val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
629
    *q++ = val;
630
    val = (((pts >> 15) & 0x7fff) << 1) | 1;
631
    *q++ = val >> 8;
632
    *q++ = val;
633
    val = (((pts) & 0x7fff) << 1) | 1;
634
    *q++ = val >> 8;
635
    *q++ = val;
636
}
637

    
638
/* Add a pes header to the front of payload, and segment into an integer number of
639
 * ts packets. The final ts packet is padded using an over-sized adaptation header
640
 * to exactly fill the last ts packet.
641
 * NOTE: 'payload' contains a complete PES payload.
642
 */
643
static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
644
                             const uint8_t *payload, int payload_size,
645
                             int64_t pts, int64_t dts)
646
{
647
    MpegTSWriteStream *ts_st = st->priv_data;
648
    MpegTSWrite *ts = s->priv_data;
649
    uint8_t buf[TS_PACKET_SIZE];
650
    uint8_t *q;
651
    int val, is_start, len, header_len, write_pcr, private_code, flags;
652
    int afc_len, stuffing_len;
653
    int64_t pcr = -1; /* avoid warning */
654
    int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
655

    
656
    is_start = 1;
657
    while (payload_size > 0) {
658
        retransmit_si_info(s);
659

    
660
        write_pcr = 0;
661
        if (ts_st->pid == ts_st->service->pcr_pid) {
662
            if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
663
                ts_st->service->pcr_packet_count++;
664
            if (ts_st->service->pcr_packet_count >=
665
                ts_st->service->pcr_packet_period) {
666
                ts_st->service->pcr_packet_count = 0;
667
                write_pcr = 1;
668
            }
669
        }
670

    
671
        if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
672
            (dts - get_pcr(ts, s->pb)/300) > delay) {
673
            /* pcr insert gets priority over null packet insert */
674
            if (write_pcr)
675
                mpegts_insert_pcr_only(s, st);
676
            else
677
                mpegts_insert_null_packet(s);
678
            continue; /* recalculate write_pcr and possibly retransmit si_info */
679
        }
680

    
681
        /* prepare packet header */
682
        q = buf;
683
        *q++ = 0x47;
684
        val = (ts_st->pid >> 8);
685
        if (is_start)
686
            val |= 0x40;
687
        *q++ = val;
688
        *q++ = ts_st->pid;
689
        ts_st->cc = (ts_st->cc + 1) & 0xf;
690
        *q++ = 0x10 | ts_st->cc | (write_pcr ? 0x20 : 0);
691
        if (write_pcr) {
692
            // add 11, pcr references the last byte of program clock reference base
693
            if (ts->mux_rate > 1)
694
                pcr = get_pcr(ts, s->pb);
695
            else
696
                pcr = (dts - delay)*300;
697
            if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
698
                av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
699
            *q++ = 7; /* AFC length */
700
            *q++ = 0x10; /* flags: PCR present */
701
            q = write_pcr_bits(q, pcr);
702
        }
703
        if (is_start) {
704
            int pes_extension = 0;
705
            /* write PES header */
706
            *q++ = 0x00;
707
            *q++ = 0x00;
708
            *q++ = 0x01;
709
            private_code = 0;
710
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
711
                if (st->codec->codec_id == CODEC_ID_DIRAC) {
712
                    *q++ = 0xfd;
713
                } else
714
                    *q++ = 0xe0;
715
            } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
716
                       (st->codec->codec_id == CODEC_ID_MP2 ||
717
                        st->codec->codec_id == CODEC_ID_MP3)) {
718
                *q++ = 0xc0;
719
            } else {
720
                *q++ = 0xbd;
721
                if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
722
                    private_code = 0x20;
723
                }
724
            }
725
            header_len = 0;
726
            flags = 0;
727
            if (pts != AV_NOPTS_VALUE) {
728
                header_len += 5;
729
                flags |= 0x80;
730
            }
731
            if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
732
                header_len += 5;
733
                flags |= 0x40;
734
            }
735
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
736
                st->codec->codec_id == CODEC_ID_DIRAC) {
737
                /* set PES_extension_flag */
738
                pes_extension = 1;
739
                flags |= 0x01;
740

    
741
                /*
742
                * One byte for PES2 extension flag +
743
                * one byte for extension length +
744
                * one byte for extension id
745
                */
746
                header_len += 3;
747
            }
748
            len = payload_size + header_len + 3;
749
            if (private_code != 0)
750
                len++;
751
            if (len > 0xffff)
752
                len = 0;
753
            *q++ = len >> 8;
754
            *q++ = len;
755
            val = 0x80;
756
            /* data alignment indicator is required for subtitle data */
757
            if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
758
                val |= 0x04;
759
            *q++ = val;
760
            *q++ = flags;
761
            *q++ = header_len;
762
            if (pts != AV_NOPTS_VALUE) {
763
                write_pts(q, flags >> 6, pts);
764
                q += 5;
765
            }
766
            if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
767
                write_pts(q, 1, dts);
768
                q += 5;
769
            }
770
            if (pes_extension && st->codec->codec_id == CODEC_ID_DIRAC) {
771
                flags = 0x01;  /* set PES_extension_flag_2 */
772
                *q++ = flags;
773
                *q++ = 0x80 | 0x01;  /* marker bit + extension length */
774
                /*
775
                * Set the stream id extension flag bit to 0 and
776
                * write the extended stream id
777
                */
778
                *q++ = 0x00 | 0x60;
779
            }
780
            if (private_code != 0)
781
                *q++ = private_code;
782
            is_start = 0;
783
        }
784
        /* header size */
785
        header_len = q - buf;
786
        /* data len */
787
        len = TS_PACKET_SIZE - header_len;
788
        if (len > payload_size)
789
            len = payload_size;
790
        stuffing_len = TS_PACKET_SIZE - header_len - len;
791
        if (stuffing_len > 0) {
792
            /* add stuffing with AFC */
793
            if (buf[3] & 0x20) {
794
                /* stuffing already present: increase its size */
795
                afc_len = buf[4] + 1;
796
                memmove(buf + 4 + afc_len + stuffing_len,
797
                        buf + 4 + afc_len,
798
                        header_len - (4 + afc_len));
799
                buf[4] += stuffing_len;
800
                memset(buf + 4 + afc_len, 0xff, stuffing_len);
801
            } else {
802
                /* add stuffing */
803
                memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
804
                buf[3] |= 0x20;
805
                buf[4] = stuffing_len - 1;
806
                if (stuffing_len >= 2) {
807
                    buf[5] = 0x00;
808
                    memset(buf + 6, 0xff, stuffing_len - 2);
809
                }
810
            }
811
        }
812
        memcpy(buf + TS_PACKET_SIZE - len, payload, len);
813
        payload += len;
814
        payload_size -= len;
815
        put_buffer(s->pb, buf, TS_PACKET_SIZE);
816
    }
817
    put_flush_packet(s->pb);
818
}
819

    
820
static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
821
{
822
    AVStream *st = s->streams[pkt->stream_index];
823
    int size = pkt->size;
824
    uint8_t *buf= pkt->data;
825
    uint8_t *data= NULL;
826
    MpegTSWriteStream *ts_st = st->priv_data;
827
    const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
828
    int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
829

    
830
    if (pkt->pts != AV_NOPTS_VALUE)
831
        pts = pkt->pts + delay;
832
    if (pkt->dts != AV_NOPTS_VALUE)
833
        dts = pkt->dts + delay;
834

    
835
    if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
836
        av_log(s, AV_LOG_ERROR, "first pts value must set\n");
837
        return -1;
838
    }
839
    ts_st->first_pts_check = 0;
840

    
841
    if (st->codec->codec_id == CODEC_ID_H264) {
842
        const uint8_t *p = buf, *buf_end = p+size;
843
        uint32_t state = -1;
844

    
845
        if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
846
            av_log(s, AV_LOG_ERROR, "h264 bitstream malformated, "
847
                   "no startcode found, use -vbsf h264_mp4toannexb\n");
848
            return -1;
849
        }
850

    
851
        do {
852
            p = ff_find_start_code(p, buf_end, &state);
853
            //av_log(s, AV_LOG_INFO, "nal %d\n", state & 0x1f);
854
        } while (p < buf_end && (state & 0x1f) != 9 &&
855
                 (state & 0x1f) != 5 && (state & 0x1f) != 1);
856

    
857
        if ((state & 0x1f) != 9) { // AUD NAL
858
            data = av_malloc(pkt->size+6);
859
            if (!data)
860
                return -1;
861
            memcpy(data+6, pkt->data, pkt->size);
862
            AV_WB32(data, 0x00000001);
863
            data[4] = 0x09;
864
            data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
865
            buf  = data;
866
            size = pkt->size+6;
867
        }
868
    } else if (st->codec->codec_id == CODEC_ID_AAC) {
869
        if (pkt->size < 2)
870
            return -1;
871
        if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
872
            ADTSContext *adts = ts_st->adts;
873
            int new_size;
874
            if (!adts) {
875
                av_log(s, AV_LOG_ERROR, "aac bitstream not in adts format "
876
                       "and extradata missing\n");
877
                return -1;
878
            }
879
            new_size = ADTS_HEADER_SIZE+adts->pce_size+pkt->size;
880
            if ((unsigned)new_size >= INT_MAX)
881
                return -1;
882
            data = av_malloc(new_size);
883
            if (!data)
884
                return AVERROR(ENOMEM);
885
            ff_adts_write_frame_header(adts, data, pkt->size, adts->pce_size);
886
            if (adts->pce_size) {
887
                memcpy(data+ADTS_HEADER_SIZE, adts->pce_data, adts->pce_size);
888
                adts->pce_size = 0;
889
            }
890
            memcpy(data+ADTS_HEADER_SIZE+adts->pce_size, pkt->data, pkt->size);
891
            buf = data;
892
            size = new_size;
893
        }
894
    }
895

    
896
    if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
897
        // for video and subtitle, write a single pes packet
898
        mpegts_write_pes(s, st, buf, size, pts, dts);
899
        av_free(data);
900
        return 0;
901
    }
902

    
903
    if (ts_st->payload_index + size > DEFAULT_PES_PAYLOAD_SIZE) {
904
        mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
905
                         ts_st->payload_pts, ts_st->payload_dts);
906
        ts_st->payload_index = 0;
907
    }
908

    
909
    if (!ts_st->payload_index) {
910
        ts_st->payload_pts = pts;
911
        ts_st->payload_dts = dts;
912
    }
913

    
914
    memcpy(ts_st->payload + ts_st->payload_index, buf, size);
915
    ts_st->payload_index += size;
916

    
917
    av_free(data);
918

    
919
    return 0;
920
}
921

    
922
static int mpegts_write_end(AVFormatContext *s)
923
{
924
    MpegTSWrite *ts = s->priv_data;
925
    MpegTSWriteStream *ts_st;
926
    MpegTSService *service;
927
    AVStream *st;
928
    int i;
929

    
930
    /* flush current packets */
931
    for(i = 0; i < s->nb_streams; i++) {
932
        st = s->streams[i];
933
        ts_st = st->priv_data;
934
        if (ts_st->payload_index > 0) {
935
            mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
936
                             ts_st->payload_pts, ts_st->payload_dts);
937
        }
938
        av_freep(&ts_st->adts);
939
    }
940
    put_flush_packet(s->pb);
941

    
942
    for(i = 0; i < ts->nb_services; i++) {
943
        service = ts->services[i];
944
        av_freep(&service->provider_name);
945
        av_freep(&service->name);
946
        av_free(service);
947
    }
948
    av_free(ts->services);
949

    
950
    return 0;
951
}
952

    
953
AVOutputFormat ff_mpegts_muxer = {
954
    "mpegts",
955
    NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
956
    "video/x-mpegts",
957
    "ts,m2t",
958
    sizeof(MpegTSWrite),
959
    CODEC_ID_MP2,
960
    CODEC_ID_MPEG2VIDEO,
961
    mpegts_write_header,
962
    mpegts_write_packet,
963
    mpegts_write_end,
964
};