Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegtsenc.c @ f8fec050

History | View | Annotate | Download (32.2 KB)

1
/*
2
 * MPEG2 transport stream (aka DVB) muxer
3
 * Copyright (c) 2003 Fabrice Bellard
4
 *
5
 * This file is part of Libav.
6
 *
7
 * Libav 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
 * Libav 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 Libav; 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 "libavutil/opt.h"
25
#include "libavcodec/mpegvideo.h"
26
#include "avformat.h"
27
#include "internal.h"
28
#include "mpegts.h"
29
#include "adts.h"
30

    
31
#define PCR_TIME_BASE 27000000
32

    
33
/* write DVB SI sections */
34

    
35
/*********************************************/
36
/* mpegts section writer */
37

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

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

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

    
69
    int transport_stream_id;
70
    int original_network_id;
71
    int service_id;
72

    
73
    int pmt_start_pid;
74
    int start_pid;
75
} MpegTSWrite;
76

    
77
static const AVOption options[] = {
78
    { "mpegts_transport_stream_id", "Set transport_stream_id field.",
79
      offsetof(MpegTSWrite, transport_stream_id), FF_OPT_TYPE_INT, 0x0001, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
80
    { "mpegts_original_network_id", "Set original_network_id field.",
81
      offsetof(MpegTSWrite, original_network_id), FF_OPT_TYPE_INT, 0x0001, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
82
    { "mpegts_service_id", "Set service_id field.",
83
      offsetof(MpegTSWrite, service_id), FF_OPT_TYPE_INT, 0x0001, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
84
    { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
85
      offsetof(MpegTSWrite, pmt_start_pid), FF_OPT_TYPE_INT, 0x1000, 0x1000, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM},
86
    { "mpegts_start_pid", "Set the first pid.",
87
      offsetof(MpegTSWrite, start_pid), FF_OPT_TYPE_INT, 0x0100, 0x0100, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM},
88
    { NULL },
89
};
90

    
91
static const AVClass mpegts_muxer_class = {
92
    "MPEGTS muxer",
93
    av_default_item_name,
94
    options,
95
    LIBAVUTIL_VERSION_INT,
96
};
97

    
98
/* NOTE: 4 bytes must be left at the end for the crc32 */
99
static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
100
{
101
    unsigned int crc;
102
    unsigned char packet[TS_PACKET_SIZE];
103
    const unsigned char *buf_ptr;
104
    unsigned char *q;
105
    int first, b, len1, left;
106

    
107
    crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
108
    buf[len - 4] = (crc >> 24) & 0xff;
109
    buf[len - 3] = (crc >> 16) & 0xff;
110
    buf[len - 2] = (crc >> 8) & 0xff;
111
    buf[len - 1] = (crc) & 0xff;
112

    
113
    /* send each packet */
114
    buf_ptr = buf;
115
    while (len > 0) {
116
        first = (buf == buf_ptr);
117
        q = packet;
118
        *q++ = 0x47;
119
        b = (s->pid >> 8);
120
        if (first)
121
            b |= 0x40;
122
        *q++ = b;
123
        *q++ = s->pid;
124
        s->cc = (s->cc + 1) & 0xf;
125
        *q++ = 0x10 | s->cc;
126
        if (first)
127
            *q++ = 0; /* 0 offset */
128
        len1 = TS_PACKET_SIZE - (q - packet);
129
        if (len1 > len)
130
            len1 = len;
131
        memcpy(q, buf_ptr, len1);
132
        q += len1;
133
        /* add known padding data */
134
        left = TS_PACKET_SIZE - (q - packet);
135
        if (left > 0)
136
            memset(q, 0xff, left);
137

    
138
        s->write_packet(s, packet);
139

    
140
        buf_ptr += len1;
141
        len -= len1;
142
    }
143
}
144

    
145
static inline void put16(uint8_t **q_ptr, int val)
146
{
147
    uint8_t *q;
148
    q = *q_ptr;
149
    *q++ = val >> 8;
150
    *q++ = val;
151
    *q_ptr = q;
152
}
153

    
154
static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
155
                          int version, int sec_num, int last_sec_num,
156
                          uint8_t *buf, int len)
157
{
158
    uint8_t section[1024], *q;
159
    unsigned int tot_len;
160
    /* reserved_future_use field must be set to 1 for SDT */
161
    unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
162

    
163
    tot_len = 3 + 5 + len + 4;
164
    /* check if not too big */
165
    if (tot_len > 1024)
166
        return -1;
167

    
168
    q = section;
169
    *q++ = tid;
170
    put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
171
    put16(&q, id);
172
    *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
173
    *q++ = sec_num;
174
    *q++ = last_sec_num;
175
    memcpy(q, buf, len);
176

    
177
    mpegts_write_section(s, section, tot_len);
178
    return 0;
179
}
180

    
181
/*********************************************/
182
/* mpegts writer */
183

    
184
#define DEFAULT_PROVIDER_NAME   "Libav"
185
#define DEFAULT_SERVICE_NAME    "Service01"
186

    
187
/* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
188
#define DEFAULT_PES_HEADER_FREQ 16
189
#define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
190

    
191
/* we retransmit the SI info at this rate */
192
#define SDT_RETRANS_TIME 500
193
#define PAT_RETRANS_TIME 100
194
#define PCR_RETRANS_TIME 20
195

    
196
typedef struct MpegTSWriteStream {
197
    struct MpegTSService *service;
198
    int pid; /* stream associated pid */
199
    int cc;
200
    int payload_index;
201
    int first_pts_check; ///< first pts check needed
202
    int64_t payload_pts;
203
    int64_t payload_dts;
204
    uint8_t payload[DEFAULT_PES_PAYLOAD_SIZE];
205
    ADTSContext *adts;
206
} MpegTSWriteStream;
207

    
208
static void mpegts_write_pat(AVFormatContext *s)
209
{
210
    MpegTSWrite *ts = s->priv_data;
211
    MpegTSService *service;
212
    uint8_t data[1012], *q;
213
    int i;
214

    
215
    q = data;
216
    for(i = 0; i < ts->nb_services; i++) {
217
        service = ts->services[i];
218
        put16(&q, service->sid);
219
        put16(&q, 0xe000 | service->pmt.pid);
220
    }
221
    mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, 0, 0, 0,
222
                          data, q - data);
223
}
224

    
225
static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
226
{
227
    //    MpegTSWrite *ts = s->priv_data;
228
    uint8_t data[1012], *q, *desc_length_ptr, *program_info_length_ptr;
229
    int val, stream_type, i;
230

    
231
    q = data;
232
    put16(&q, 0xe000 | service->pcr_pid);
233

    
234
    program_info_length_ptr = q;
235
    q += 2; /* patched after */
236

    
237
    /* put program info here */
238

    
239
    val = 0xf000 | (q - program_info_length_ptr - 2);
240
    program_info_length_ptr[0] = val >> 8;
241
    program_info_length_ptr[1] = val;
242

    
243
    for(i = 0; i < s->nb_streams; i++) {
244
        AVStream *st = s->streams[i];
245
        MpegTSWriteStream *ts_st = st->priv_data;
246
        AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL,0);
247
        switch(st->codec->codec_id) {
248
        case CODEC_ID_MPEG1VIDEO:
249
        case CODEC_ID_MPEG2VIDEO:
250
            stream_type = STREAM_TYPE_VIDEO_MPEG2;
251
            break;
252
        case CODEC_ID_MPEG4:
253
            stream_type = STREAM_TYPE_VIDEO_MPEG4;
254
            break;
255
        case CODEC_ID_H264:
256
            stream_type = STREAM_TYPE_VIDEO_H264;
257
            break;
258
        case CODEC_ID_DIRAC:
259
            stream_type = STREAM_TYPE_VIDEO_DIRAC;
260
            break;
261
        case CODEC_ID_MP2:
262
        case CODEC_ID_MP3:
263
            stream_type = STREAM_TYPE_AUDIO_MPEG1;
264
            break;
265
        case CODEC_ID_AAC:
266
            stream_type = STREAM_TYPE_AUDIO_AAC;
267
            break;
268
        case CODEC_ID_AAC_LATM:
269
            stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
270
            break;
271
        case CODEC_ID_AC3:
272
            stream_type = STREAM_TYPE_AUDIO_AC3;
273
            break;
274
        default:
275
            stream_type = STREAM_TYPE_PRIVATE_DATA;
276
            break;
277
        }
278
        *q++ = stream_type;
279
        put16(&q, 0xe000 | ts_st->pid);
280
        desc_length_ptr = q;
281
        q += 2; /* patched after */
282

    
283
        /* write optional descriptors here */
284
        switch(st->codec->codec_type) {
285
        case AVMEDIA_TYPE_AUDIO:
286
            if (lang) {
287
                char *p;
288
                char *next = lang->value;
289
                uint8_t *len_ptr;
290

    
291
                *q++ = 0x0a; /* ISO 639 language descriptor */
292
                len_ptr = q++;
293
                *len_ptr = 0;
294

    
295
                for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
296
                    next = strchr(p, ',');
297
                    if (strlen(p) != 3 && (!next || next != p + 3))
298
                        continue; /* not a 3-letter code */
299

    
300
                    *q++ = *p++;
301
                    *q++ = *p++;
302
                    *q++ = *p++;
303

    
304
                if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
305
                    *q++ = 0x01;
306
                else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
307
                    *q++ = 0x02;
308
                else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
309
                    *q++ = 0x03;
310
                else
311
                    *q++ = 0; /* undefined type */
312

    
313
                    *len_ptr += 4;
314
                }
315

    
316
                if (*len_ptr == 0)
317
                    q -= 2; /* no language codes were written */
318
            }
319
            break;
320
        case AVMEDIA_TYPE_SUBTITLE:
321
            {
322
                const char *language;
323
                language = lang && strlen(lang->value)==3 ? lang->value : "eng";
324
                *q++ = 0x59;
325
                *q++ = 8;
326
                *q++ = language[0];
327
                *q++ = language[1];
328
                *q++ = language[2];
329
                *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */
330
                if(st->codec->extradata_size == 4) {
331
                    memcpy(q, st->codec->extradata, 4);
332
                    q += 4;
333
                } else {
334
                    put16(&q, 1); /* page id */
335
                    put16(&q, 1); /* ancillary page id */
336
                }
337
            }
338
            break;
339
        case AVMEDIA_TYPE_VIDEO:
340
            if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
341
                *q++ = 0x05; /*MPEG-2 registration descriptor*/
342
                *q++ = 4;
343
                *q++ = 'd';
344
                *q++ = 'r';
345
                *q++ = 'a';
346
                *q++ = 'c';
347
            }
348
            break;
349
        }
350

    
351
        val = 0xf000 | (q - desc_length_ptr - 2);
352
        desc_length_ptr[0] = val >> 8;
353
        desc_length_ptr[1] = val;
354
    }
355
    mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,
356
                          data, q - data);
357
}
358

    
359
/* NOTE: str == NULL is accepted for an empty string */
360
static void putstr8(uint8_t **q_ptr, const char *str)
361
{
362
    uint8_t *q;
363
    int len;
364

    
365
    q = *q_ptr;
366
    if (!str)
367
        len = 0;
368
    else
369
        len = strlen(str);
370
    *q++ = len;
371
    memcpy(q, str, len);
372
    q += len;
373
    *q_ptr = q;
374
}
375

    
376
static void mpegts_write_sdt(AVFormatContext *s)
377
{
378
    MpegTSWrite *ts = s->priv_data;
379
    MpegTSService *service;
380
    uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
381
    int i, running_status, free_ca_mode, val;
382

    
383
    q = data;
384
    put16(&q, ts->onid);
385
    *q++ = 0xff;
386
    for(i = 0; i < ts->nb_services; i++) {
387
        service = ts->services[i];
388
        put16(&q, service->sid);
389
        *q++ = 0xfc | 0x00; /* currently no EIT info */
390
        desc_list_len_ptr = q;
391
        q += 2;
392
        running_status = 4; /* running */
393
        free_ca_mode = 0;
394

    
395
        /* write only one descriptor for the service name and provider */
396
        *q++ = 0x48;
397
        desc_len_ptr = q;
398
        q++;
399
        *q++ = 0x01; /* digital television service */
400
        putstr8(&q, service->provider_name);
401
        putstr8(&q, service->name);
402
        desc_len_ptr[0] = q - desc_len_ptr - 1;
403

    
404
        /* fill descriptor length */
405
        val = (running_status << 13) | (free_ca_mode << 12) |
406
            (q - desc_list_len_ptr - 2);
407
        desc_list_len_ptr[0] = val >> 8;
408
        desc_list_len_ptr[1] = val;
409
    }
410
    mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, 0, 0, 0,
411
                          data, q - data);
412
}
413

    
414
static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
415
                                         int sid,
416
                                         const char *provider_name,
417
                                         const char *name)
418
{
419
    MpegTSService *service;
420

    
421
    service = av_mallocz(sizeof(MpegTSService));
422
    if (!service)
423
        return NULL;
424
    service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
425
    service->sid = sid;
426
    service->provider_name = av_strdup(provider_name);
427
    service->name = av_strdup(name);
428
    service->pcr_pid = 0x1fff;
429
    dynarray_add(&ts->services, &ts->nb_services, service);
430
    return service;
431
}
432

    
433
static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
434
{
435
    AVFormatContext *ctx = s->opaque;
436
    avio_write(ctx->pb, packet, TS_PACKET_SIZE);
437
}
438

    
439
static int mpegts_write_header(AVFormatContext *s)
440
{
441
    MpegTSWrite *ts = s->priv_data;
442
    MpegTSWriteStream *ts_st;
443
    MpegTSService *service;
444
    AVStream *st, *pcr_st = NULL;
445
    AVMetadataTag *title, *provider;
446
    int i, j;
447
    const char *service_name;
448
    const char *provider_name;
449
    int *pids;
450

    
451
    ts->tsid = ts->transport_stream_id;
452
    ts->onid = ts->original_network_id;
453
    /* allocate a single DVB service */
454
    title = av_metadata_get(s->metadata, "service_name", NULL, 0);
455
    if (!title)
456
        title = av_metadata_get(s->metadata, "title", NULL, 0);
457
    service_name = title ? title->value : DEFAULT_SERVICE_NAME;
458
    provider = av_metadata_get(s->metadata, "service_provider", NULL, 0);
459
    provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
460
    service = mpegts_add_service(ts, ts->service_id, provider_name, service_name);
461
    service->pmt.write_packet = section_write_packet;
462
    service->pmt.opaque = s;
463
    service->pmt.cc = 15;
464

    
465
    ts->pat.pid = PAT_PID;
466
    ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
467
    ts->pat.write_packet = section_write_packet;
468
    ts->pat.opaque = s;
469

    
470
    ts->sdt.pid = SDT_PID;
471
    ts->sdt.cc = 15;
472
    ts->sdt.write_packet = section_write_packet;
473
    ts->sdt.opaque = s;
474

    
475
    pids = av_malloc(s->nb_streams * sizeof(*pids));
476
    if (!pids)
477
        return AVERROR(ENOMEM);
478

    
479
    /* assign pids to each stream */
480
    for(i = 0;i < s->nb_streams; i++) {
481
        st = s->streams[i];
482
        av_set_pts_info(st, 33, 1, 90000);
483
        ts_st = av_mallocz(sizeof(MpegTSWriteStream));
484
        if (!ts_st)
485
            goto fail;
486
        st->priv_data = ts_st;
487
        ts_st->service = service;
488
        /* MPEG pid values < 16 are reserved. Applications which set st->id in
489
         * this range are assigned a calculated pid. */
490
        if (st->id < 16) {
491
            ts_st->pid = ts->start_pid + i;
492
        } else if (st->id < 0x1FFF) {
493
            ts_st->pid = st->id;
494
        } else {
495
            av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
496
            goto fail;
497
        }
498
        if (ts_st->pid == service->pmt.pid) {
499
            av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
500
            goto fail;
501
        }
502
        for (j = 0; j < i; j++)
503
            if (pids[j] == ts_st->pid) {
504
                av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
505
                goto fail;
506
            }
507
        pids[i] = ts_st->pid;
508
        ts_st->payload_pts = AV_NOPTS_VALUE;
509
        ts_st->payload_dts = AV_NOPTS_VALUE;
510
        ts_st->first_pts_check = 1;
511
        ts_st->cc = 15;
512
        /* update PCR pid by using the first video stream */
513
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
514
            service->pcr_pid == 0x1fff) {
515
            service->pcr_pid = ts_st->pid;
516
            pcr_st = st;
517
        }
518
        if (st->codec->codec_id == CODEC_ID_AAC &&
519
            st->codec->extradata_size > 0) {
520
            ts_st->adts = av_mallocz(sizeof(*ts_st->adts));
521
            if (!ts_st->adts)
522
                return AVERROR(ENOMEM);
523
            if (ff_adts_decode_extradata(s, ts_st->adts, st->codec->extradata,
524
                                         st->codec->extradata_size) < 0)
525
                return -1;
526
        }
527
    }
528

    
529
    av_free(pids);
530

    
531
    /* if no video stream, use the first stream as PCR */
532
    if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
533
        pcr_st = s->streams[0];
534
        ts_st = pcr_st->priv_data;
535
        service->pcr_pid = ts_st->pid;
536
    }
537

    
538
    ts->mux_rate = s->mux_rate ? s->mux_rate : 1;
539

    
540
    if (ts->mux_rate > 1) {
541
        service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
542
            (TS_PACKET_SIZE * 8 * 1000);
543
        ts->sdt_packet_period      = (ts->mux_rate * SDT_RETRANS_TIME) /
544
            (TS_PACKET_SIZE * 8 * 1000);
545
        ts->pat_packet_period      = (ts->mux_rate * PAT_RETRANS_TIME) /
546
            (TS_PACKET_SIZE * 8 * 1000);
547

    
548
        ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
549
    } else {
550
        /* Arbitrary values, PAT/PMT could be written on key frames */
551
        ts->sdt_packet_period = 200;
552
        ts->pat_packet_period = 40;
553
        if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
554
            if (!pcr_st->codec->frame_size) {
555
                av_log(s, AV_LOG_WARNING, "frame size not set\n");
556
                service->pcr_packet_period =
557
                    pcr_st->codec->sample_rate/(10*512);
558
            } else {
559
                service->pcr_packet_period =
560
                    pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
561
            }
562
        } else {
563
            // max delta PCR 0.1s
564
            service->pcr_packet_period =
565
                pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
566
        }
567
    }
568

    
569
    // output a PCR as soon as possible
570
    service->pcr_packet_count = service->pcr_packet_period;
571
    ts->pat_packet_count = ts->pat_packet_period-1;
572
    ts->sdt_packet_count = ts->sdt_packet_period-1;
573

    
574
    if (ts->mux_rate == 1)
575
        av_log(s, AV_LOG_INFO, "muxrate VBR, ");
576
    else
577
        av_log(s, AV_LOG_INFO, "muxrate %d, ", ts->mux_rate);
578
    av_log(s, AV_LOG_INFO, "pcr every %d pkts, "
579
           "sdt every %d, pat/pmt every %d pkts\n",
580
           service->pcr_packet_period,
581
           ts->sdt_packet_period, ts->pat_packet_period);
582

    
583
    avio_flush(s->pb);
584

    
585
    return 0;
586

    
587
 fail:
588
    av_free(pids);
589
    for(i = 0;i < s->nb_streams; i++) {
590
        st = s->streams[i];
591
        av_free(st->priv_data);
592
    }
593
    return -1;
594
}
595

    
596
/* send SDT, PAT and PMT tables regulary */
597
static void retransmit_si_info(AVFormatContext *s)
598
{
599
    MpegTSWrite *ts = s->priv_data;
600
    int i;
601

    
602
    if (++ts->sdt_packet_count == ts->sdt_packet_period) {
603
        ts->sdt_packet_count = 0;
604
        mpegts_write_sdt(s);
605
    }
606
    if (++ts->pat_packet_count == ts->pat_packet_period) {
607
        ts->pat_packet_count = 0;
608
        mpegts_write_pat(s);
609
        for(i = 0; i < ts->nb_services; i++) {
610
            mpegts_write_pmt(s, ts->services[i]);
611
        }
612
    }
613
}
614

    
615
static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
616
{
617
    return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
618
           ts->first_pcr;
619
}
620

    
621
static uint8_t* write_pcr_bits(uint8_t *buf, int64_t pcr)
622
{
623
    int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
624

    
625
    *buf++ = pcr_high >> 25;
626
    *buf++ = pcr_high >> 17;
627
    *buf++ = pcr_high >> 9;
628
    *buf++ = pcr_high >> 1;
629
    *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
630
    *buf++ = pcr_low;
631

    
632
    return buf;
633
}
634

    
635
/* Write a single null transport stream packet */
636
static void mpegts_insert_null_packet(AVFormatContext *s)
637
{
638
    uint8_t *q;
639
    uint8_t buf[TS_PACKET_SIZE];
640

    
641
    q = buf;
642
    *q++ = 0x47;
643
    *q++ = 0x00 | 0x1f;
644
    *q++ = 0xff;
645
    *q++ = 0x10;
646
    memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
647
    avio_write(s->pb, buf, TS_PACKET_SIZE);
648
}
649

    
650
/* Write a single transport stream packet with a PCR and no payload */
651
static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
652
{
653
    MpegTSWrite *ts = s->priv_data;
654
    MpegTSWriteStream *ts_st = st->priv_data;
655
    uint8_t *q;
656
    uint8_t buf[TS_PACKET_SIZE];
657

    
658
    q = buf;
659
    *q++ = 0x47;
660
    *q++ = ts_st->pid >> 8;
661
    *q++ = ts_st->pid;
662
    *q++ = 0x20 | ts_st->cc;   /* Adaptation only */
663
    /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
664
    *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
665
    *q++ = 0x10;               /* Adaptation flags: PCR present */
666

    
667
    /* PCR coded into 6 bytes */
668
    q = write_pcr_bits(q, get_pcr(ts, s->pb));
669

    
670
    /* stuffing bytes */
671
    memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
672
    avio_write(s->pb, buf, TS_PACKET_SIZE);
673
}
674

    
675
static void write_pts(uint8_t *q, int fourbits, int64_t pts)
676
{
677
    int val;
678

    
679
    val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
680
    *q++ = val;
681
    val = (((pts >> 15) & 0x7fff) << 1) | 1;
682
    *q++ = val >> 8;
683
    *q++ = val;
684
    val = (((pts) & 0x7fff) << 1) | 1;
685
    *q++ = val >> 8;
686
    *q++ = val;
687
}
688

    
689
/* Add a pes header to the front of payload, and segment into an integer number of
690
 * ts packets. The final ts packet is padded using an over-sized adaptation header
691
 * to exactly fill the last ts packet.
692
 * NOTE: 'payload' contains a complete PES payload.
693
 */
694
static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
695
                             const uint8_t *payload, int payload_size,
696
                             int64_t pts, int64_t dts)
697
{
698
    MpegTSWriteStream *ts_st = st->priv_data;
699
    MpegTSWrite *ts = s->priv_data;
700
    uint8_t buf[TS_PACKET_SIZE];
701
    uint8_t *q;
702
    int val, is_start, len, header_len, write_pcr, private_code, flags;
703
    int afc_len, stuffing_len;
704
    int64_t pcr = -1; /* avoid warning */
705
    int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
706

    
707
    is_start = 1;
708
    while (payload_size > 0) {
709
        retransmit_si_info(s);
710

    
711
        write_pcr = 0;
712
        if (ts_st->pid == ts_st->service->pcr_pid) {
713
            if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
714
                ts_st->service->pcr_packet_count++;
715
            if (ts_st->service->pcr_packet_count >=
716
                ts_st->service->pcr_packet_period) {
717
                ts_st->service->pcr_packet_count = 0;
718
                write_pcr = 1;
719
            }
720
        }
721

    
722
        if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
723
            (dts - get_pcr(ts, s->pb)/300) > delay) {
724
            /* pcr insert gets priority over null packet insert */
725
            if (write_pcr)
726
                mpegts_insert_pcr_only(s, st);
727
            else
728
                mpegts_insert_null_packet(s);
729
            continue; /* recalculate write_pcr and possibly retransmit si_info */
730
        }
731

    
732
        /* prepare packet header */
733
        q = buf;
734
        *q++ = 0x47;
735
        val = (ts_st->pid >> 8);
736
        if (is_start)
737
            val |= 0x40;
738
        *q++ = val;
739
        *q++ = ts_st->pid;
740
        ts_st->cc = (ts_st->cc + 1) & 0xf;
741
        *q++ = 0x10 | ts_st->cc | (write_pcr ? 0x20 : 0);
742
        if (write_pcr) {
743
            // add 11, pcr references the last byte of program clock reference base
744
            if (ts->mux_rate > 1)
745
                pcr = get_pcr(ts, s->pb);
746
            else
747
                pcr = (dts - delay)*300;
748
            if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
749
                av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
750
            *q++ = 7; /* AFC length */
751
            *q++ = 0x10; /* flags: PCR present */
752
            q = write_pcr_bits(q, pcr);
753
        }
754
        if (is_start) {
755
            int pes_extension = 0;
756
            /* write PES header */
757
            *q++ = 0x00;
758
            *q++ = 0x00;
759
            *q++ = 0x01;
760
            private_code = 0;
761
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
762
                if (st->codec->codec_id == CODEC_ID_DIRAC) {
763
                    *q++ = 0xfd;
764
                } else
765
                    *q++ = 0xe0;
766
            } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
767
                       (st->codec->codec_id == CODEC_ID_MP2 ||
768
                        st->codec->codec_id == CODEC_ID_MP3 ||
769
                        st->codec->codec_id == CODEC_ID_AAC)) {
770
                *q++ = 0xc0;
771
            } else {
772
                *q++ = 0xbd;
773
                if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
774
                    private_code = 0x20;
775
                }
776
            }
777
            header_len = 0;
778
            flags = 0;
779
            if (pts != AV_NOPTS_VALUE) {
780
                header_len += 5;
781
                flags |= 0x80;
782
            }
783
            if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
784
                header_len += 5;
785
                flags |= 0x40;
786
            }
787
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
788
                st->codec->codec_id == CODEC_ID_DIRAC) {
789
                /* set PES_extension_flag */
790
                pes_extension = 1;
791
                flags |= 0x01;
792

    
793
                /*
794
                * One byte for PES2 extension flag +
795
                * one byte for extension length +
796
                * one byte for extension id
797
                */
798
                header_len += 3;
799
            }
800
            len = payload_size + header_len + 3;
801
            if (private_code != 0)
802
                len++;
803
            if (len > 0xffff)
804
                len = 0;
805
            *q++ = len >> 8;
806
            *q++ = len;
807
            val = 0x80;
808
            /* data alignment indicator is required for subtitle data */
809
            if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
810
                val |= 0x04;
811
            *q++ = val;
812
            *q++ = flags;
813
            *q++ = header_len;
814
            if (pts != AV_NOPTS_VALUE) {
815
                write_pts(q, flags >> 6, pts);
816
                q += 5;
817
            }
818
            if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
819
                write_pts(q, 1, dts);
820
                q += 5;
821
            }
822
            if (pes_extension && st->codec->codec_id == CODEC_ID_DIRAC) {
823
                flags = 0x01;  /* set PES_extension_flag_2 */
824
                *q++ = flags;
825
                *q++ = 0x80 | 0x01;  /* marker bit + extension length */
826
                /*
827
                * Set the stream id extension flag bit to 0 and
828
                * write the extended stream id
829
                */
830
                *q++ = 0x00 | 0x60;
831
            }
832
            if (private_code != 0)
833
                *q++ = private_code;
834
            is_start = 0;
835
        }
836
        /* header size */
837
        header_len = q - buf;
838
        /* data len */
839
        len = TS_PACKET_SIZE - header_len;
840
        if (len > payload_size)
841
            len = payload_size;
842
        stuffing_len = TS_PACKET_SIZE - header_len - len;
843
        if (stuffing_len > 0) {
844
            /* add stuffing with AFC */
845
            if (buf[3] & 0x20) {
846
                /* stuffing already present: increase its size */
847
                afc_len = buf[4] + 1;
848
                memmove(buf + 4 + afc_len + stuffing_len,
849
                        buf + 4 + afc_len,
850
                        header_len - (4 + afc_len));
851
                buf[4] += stuffing_len;
852
                memset(buf + 4 + afc_len, 0xff, stuffing_len);
853
            } else {
854
                /* add stuffing */
855
                memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
856
                buf[3] |= 0x20;
857
                buf[4] = stuffing_len - 1;
858
                if (stuffing_len >= 2) {
859
                    buf[5] = 0x00;
860
                    memset(buf + 6, 0xff, stuffing_len - 2);
861
                }
862
            }
863
        }
864
        memcpy(buf + TS_PACKET_SIZE - len, payload, len);
865
        payload += len;
866
        payload_size -= len;
867
        avio_write(s->pb, buf, TS_PACKET_SIZE);
868
    }
869
    avio_flush(s->pb);
870
}
871

    
872
static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
873
{
874
    AVStream *st = s->streams[pkt->stream_index];
875
    int size = pkt->size;
876
    uint8_t *buf= pkt->data;
877
    uint8_t *data= NULL;
878
    MpegTSWriteStream *ts_st = st->priv_data;
879
    const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
880
    int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
881

    
882
    if (pkt->pts != AV_NOPTS_VALUE)
883
        pts = pkt->pts + delay;
884
    if (pkt->dts != AV_NOPTS_VALUE)
885
        dts = pkt->dts + delay;
886

    
887
    if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
888
        av_log(s, AV_LOG_ERROR, "first pts value must set\n");
889
        return -1;
890
    }
891
    ts_st->first_pts_check = 0;
892

    
893
    if (st->codec->codec_id == CODEC_ID_H264) {
894
        const uint8_t *p = buf, *buf_end = p+size;
895
        uint32_t state = -1;
896

    
897
        if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
898
            av_log(s, AV_LOG_ERROR, "h264 bitstream malformated, "
899
                   "no startcode found, use -vbsf h264_mp4toannexb\n");
900
            return -1;
901
        }
902

    
903
        do {
904
            p = ff_find_start_code(p, buf_end, &state);
905
            //av_log(s, AV_LOG_INFO, "nal %d\n", state & 0x1f);
906
        } while (p < buf_end && (state & 0x1f) != 9 &&
907
                 (state & 0x1f) != 5 && (state & 0x1f) != 1);
908

    
909
        if ((state & 0x1f) != 9) { // AUD NAL
910
            data = av_malloc(pkt->size+6);
911
            if (!data)
912
                return -1;
913
            memcpy(data+6, pkt->data, pkt->size);
914
            AV_WB32(data, 0x00000001);
915
            data[4] = 0x09;
916
            data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
917
            buf  = data;
918
            size = pkt->size+6;
919
        }
920
    } else if (st->codec->codec_id == CODEC_ID_AAC) {
921
        if (pkt->size < 2)
922
            return -1;
923
        if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
924
            ADTSContext *adts = ts_st->adts;
925
            int new_size;
926
            if (!adts) {
927
                av_log(s, AV_LOG_ERROR, "aac bitstream not in adts format "
928
                       "and extradata missing\n");
929
                return -1;
930
            }
931
            new_size = ADTS_HEADER_SIZE+adts->pce_size+pkt->size;
932
            if ((unsigned)new_size >= INT_MAX)
933
                return -1;
934
            data = av_malloc(new_size);
935
            if (!data)
936
                return AVERROR(ENOMEM);
937
            ff_adts_write_frame_header(adts, data, pkt->size, adts->pce_size);
938
            if (adts->pce_size) {
939
                memcpy(data+ADTS_HEADER_SIZE, adts->pce_data, adts->pce_size);
940
                adts->pce_size = 0;
941
            }
942
            memcpy(data+ADTS_HEADER_SIZE+adts->pce_size, pkt->data, pkt->size);
943
            buf = data;
944
            size = new_size;
945
        }
946
    }
947

    
948
    if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
949
        // for video and subtitle, write a single pes packet
950
        mpegts_write_pes(s, st, buf, size, pts, dts);
951
        av_free(data);
952
        return 0;
953
    }
954

    
955
    if (ts_st->payload_index + size > DEFAULT_PES_PAYLOAD_SIZE) {
956
        mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
957
                         ts_st->payload_pts, ts_st->payload_dts);
958
        ts_st->payload_index = 0;
959
    }
960

    
961
    if (!ts_st->payload_index) {
962
        ts_st->payload_pts = pts;
963
        ts_st->payload_dts = dts;
964
    }
965

    
966
    memcpy(ts_st->payload + ts_st->payload_index, buf, size);
967
    ts_st->payload_index += size;
968

    
969
    av_free(data);
970

    
971
    return 0;
972
}
973

    
974
static int mpegts_write_end(AVFormatContext *s)
975
{
976
    MpegTSWrite *ts = s->priv_data;
977
    MpegTSWriteStream *ts_st;
978
    MpegTSService *service;
979
    AVStream *st;
980
    int i;
981

    
982
    /* flush current packets */
983
    for(i = 0; i < s->nb_streams; i++) {
984
        st = s->streams[i];
985
        ts_st = st->priv_data;
986
        if (ts_st->payload_index > 0) {
987
            mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
988
                             ts_st->payload_pts, ts_st->payload_dts);
989
        }
990
        av_freep(&ts_st->adts);
991
    }
992
    avio_flush(s->pb);
993

    
994
    for(i = 0; i < ts->nb_services; i++) {
995
        service = ts->services[i];
996
        av_freep(&service->provider_name);
997
        av_freep(&service->name);
998
        av_free(service);
999
    }
1000
    av_free(ts->services);
1001

    
1002
    return 0;
1003
}
1004

    
1005
AVOutputFormat ff_mpegts_muxer = {
1006
    "mpegts",
1007
    NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1008
    "video/x-mpegts",
1009
    "ts,m2t",
1010
    sizeof(MpegTSWrite),
1011
    CODEC_ID_MP2,
1012
    CODEC_ID_MPEG2VIDEO,
1013
    mpegts_write_header,
1014
    mpegts_write_packet,
1015
    mpegts_write_end,
1016
    .priv_class = &mpegts_muxer_class,
1017
};