Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegtsenc.c @ 435cebd0

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

    
528
    av_free(pids);
529

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

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

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

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

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

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

    
582
    put_flush_packet(s->pb);
583

    
584
    return 0;
585

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

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

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

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

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

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

    
631
    return buf;
632
}
633

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
968
    av_free(data);
969

    
970
    return 0;
971
}
972

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

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

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

    
1001
    return 0;
1002
}
1003

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