Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegtsenc.c @ 236bb68d

History | View | Annotate | Download (30.1 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
    MpegTSWrite *ts = ((AVFormatContext*)s->opaque)->priv_data;
73
    unsigned int crc;
74
    unsigned char packet[TS_PACKET_SIZE];
75
    const unsigned char *buf_ptr;
76
    unsigned char *q;
77
    int first, b, len1, left;
78

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

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

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

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

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

    
126
static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
127
                          int version, int sec_num, int last_sec_num,
128
                          uint8_t *buf, int len)
129
{
130
    uint8_t section[1024], *q;
131
    unsigned int tot_len;
132

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

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

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

    
151
/*********************************************/
152
/* mpegts writer */
153

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

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

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

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

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

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

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

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

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

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

    
214
    /* put program info here */
215

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
477
    av_free(pids);
478

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

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

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

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

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

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

    
531
    put_flush_packet(s->pb);
532

    
533
    return 0;
534

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

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

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

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

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

    
573
    *buf++ = pcr_high >> 25;
574
    *buf++ = pcr_high >> 17;
575
    *buf++ = pcr_high >> 9;
576
    *buf++ = pcr_high >> 1;
577
    *buf++ = ((pcr_high & 1) << 7) | (pcr_low >> 8);
578
    *buf++ = pcr_low;
579

    
580
    return buf;
581
}
582

    
583
/* Write a single null transport stream packet */
584
static void mpegts_insert_null_packet(AVFormatContext *s)
585
{
586
    MpegTSWrite *ts = s->priv_data;
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 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
};