Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegtsenc.c @ a2704c97

History | View | Annotate | Download (31.6 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 && strlen(lang->value) == 3) {
287
                *q++ = 0x0a; /* ISO 639 language descriptor */
288
                *q++ = 4;
289
                *q++ = lang->value[0];
290
                *q++ = lang->value[1];
291
                *q++ = lang->value[2];
292
                if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
293
                    *q++ = 0x01;
294
                else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
295
                    *q++ = 0x02;
296
                else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
297
                    *q++ = 0x03;
298
                else
299
                    *q++ = 0; /* undefined type */
300
            }
301
            break;
302
        case AVMEDIA_TYPE_SUBTITLE:
303
            {
304
                const char *language;
305
                language = lang && strlen(lang->value)==3 ? lang->value : "eng";
306
                *q++ = 0x59;
307
                *q++ = 8;
308
                *q++ = language[0];
309
                *q++ = language[1];
310
                *q++ = language[2];
311
                *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */
312
                if(st->codec->extradata_size == 4) {
313
                    memcpy(q, st->codec->extradata, 4);
314
                    q += 4;
315
                } else {
316
                    put16(&q, 1); /* page id */
317
                    put16(&q, 1); /* ancillary page id */
318
                }
319
            }
320
            break;
321
        case AVMEDIA_TYPE_VIDEO:
322
            if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
323
                *q++ = 0x05; /*MPEG-2 registration descriptor*/
324
                *q++ = 4;
325
                *q++ = 'd';
326
                *q++ = 'r';
327
                *q++ = 'a';
328
                *q++ = 'c';
329
            }
330
            break;
331
        }
332

    
333
        val = 0xf000 | (q - desc_length_ptr - 2);
334
        desc_length_ptr[0] = val >> 8;
335
        desc_length_ptr[1] = val;
336
    }
337
    mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,
338
                          data, q - data);
339
}
340

    
341
/* NOTE: str == NULL is accepted for an empty string */
342
static void putstr8(uint8_t **q_ptr, const char *str)
343
{
344
    uint8_t *q;
345
    int len;
346

    
347
    q = *q_ptr;
348
    if (!str)
349
        len = 0;
350
    else
351
        len = strlen(str);
352
    *q++ = len;
353
    memcpy(q, str, len);
354
    q += len;
355
    *q_ptr = q;
356
}
357

    
358
static void mpegts_write_sdt(AVFormatContext *s)
359
{
360
    MpegTSWrite *ts = s->priv_data;
361
    MpegTSService *service;
362
    uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
363
    int i, running_status, free_ca_mode, val;
364

    
365
    q = data;
366
    put16(&q, ts->onid);
367
    *q++ = 0xff;
368
    for(i = 0; i < ts->nb_services; i++) {
369
        service = ts->services[i];
370
        put16(&q, service->sid);
371
        *q++ = 0xfc | 0x00; /* currently no EIT info */
372
        desc_list_len_ptr = q;
373
        q += 2;
374
        running_status = 4; /* running */
375
        free_ca_mode = 0;
376

    
377
        /* write only one descriptor for the service name and provider */
378
        *q++ = 0x48;
379
        desc_len_ptr = q;
380
        q++;
381
        *q++ = 0x01; /* digital television service */
382
        putstr8(&q, service->provider_name);
383
        putstr8(&q, service->name);
384
        desc_len_ptr[0] = q - desc_len_ptr - 1;
385

    
386
        /* fill descriptor length */
387
        val = (running_status << 13) | (free_ca_mode << 12) |
388
            (q - desc_list_len_ptr - 2);
389
        desc_list_len_ptr[0] = val >> 8;
390
        desc_list_len_ptr[1] = val;
391
    }
392
    mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, 0, 0, 0,
393
                          data, q - data);
394
}
395

    
396
static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
397
                                         int sid,
398
                                         const char *provider_name,
399
                                         const char *name)
400
{
401
    MpegTSService *service;
402

    
403
    service = av_mallocz(sizeof(MpegTSService));
404
    if (!service)
405
        return NULL;
406
    service->pmt.pid = ts->pmt_start_pid + ts->nb_services - 1;
407
    service->sid = sid;
408
    service->provider_name = av_strdup(provider_name);
409
    service->name = av_strdup(name);
410
    service->pcr_pid = 0x1fff;
411
    dynarray_add(&ts->services, &ts->nb_services, service);
412
    return service;
413
}
414

    
415
static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
416
{
417
    AVFormatContext *ctx = s->opaque;
418
    avio_write(ctx->pb, packet, TS_PACKET_SIZE);
419
}
420

    
421
static int mpegts_write_header(AVFormatContext *s)
422
{
423
    MpegTSWrite *ts = s->priv_data;
424
    MpegTSWriteStream *ts_st;
425
    MpegTSService *service;
426
    AVStream *st, *pcr_st = NULL;
427
    AVMetadataTag *title, *provider;
428
    int i, j;
429
    const char *service_name;
430
    const char *provider_name;
431
    int *pids;
432

    
433
    ts->tsid = ts->transport_stream_id;
434
    ts->onid = ts->original_network_id;
435
    /* allocate a single DVB service */
436
    title = av_metadata_get(s->metadata, "service_name", NULL, 0);
437
    if (!title)
438
        title = av_metadata_get(s->metadata, "title", NULL, 0);
439
    service_name = title ? title->value : DEFAULT_SERVICE_NAME;
440
    provider = av_metadata_get(s->metadata, "service_provider", NULL, 0);
441
    provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
442
    service = mpegts_add_service(ts, ts->service_id, provider_name, service_name);
443
    service->pmt.write_packet = section_write_packet;
444
    service->pmt.opaque = s;
445
    service->pmt.cc = 15;
446

    
447
    ts->pat.pid = PAT_PID;
448
    ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
449
    ts->pat.write_packet = section_write_packet;
450
    ts->pat.opaque = s;
451

    
452
    ts->sdt.pid = SDT_PID;
453
    ts->sdt.cc = 15;
454
    ts->sdt.write_packet = section_write_packet;
455
    ts->sdt.opaque = s;
456

    
457
    pids = av_malloc(s->nb_streams * sizeof(*pids));
458
    if (!pids)
459
        return AVERROR(ENOMEM);
460

    
461
    /* assign pids to each stream */
462
    for(i = 0;i < s->nb_streams; i++) {
463
        st = s->streams[i];
464
        ts_st = av_mallocz(sizeof(MpegTSWriteStream));
465
        if (!ts_st)
466
            goto fail;
467
        st->priv_data = ts_st;
468
        ts_st->service = service;
469
        /* MPEG pid values < 16 are reserved. Applications which set st->id in
470
         * this range are assigned a calculated pid. */
471
        if (st->id < 16) {
472
            ts_st->pid = ts->start_pid + i;
473
        } else if (st->id < 0x1FFF) {
474
            ts_st->pid = st->id;
475
        } else {
476
            av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
477
            goto fail;
478
        }
479
        if (ts_st->pid == service->pmt.pid) {
480
            av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
481
            goto fail;
482
        }
483
        for (j = 0; j < i; j++)
484
            if (pids[j] == ts_st->pid) {
485
                av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
486
                goto fail;
487
            }
488
        pids[i] = ts_st->pid;
489
        ts_st->payload_pts = AV_NOPTS_VALUE;
490
        ts_st->payload_dts = AV_NOPTS_VALUE;
491
        ts_st->first_pts_check = 1;
492
        ts_st->cc = 15;
493
        /* update PCR pid by using the first video stream */
494
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
495
            service->pcr_pid == 0x1fff) {
496
            service->pcr_pid = ts_st->pid;
497
            pcr_st = st;
498
        }
499
        if (st->codec->codec_id == CODEC_ID_AAC &&
500
            st->codec->extradata_size > 0) {
501
            ts_st->adts = av_mallocz(sizeof(*ts_st->adts));
502
            if (!ts_st->adts)
503
                return AVERROR(ENOMEM);
504
            if (ff_adts_decode_extradata(s, ts_st->adts, st->codec->extradata,
505
                                         st->codec->extradata_size) < 0)
506
                return -1;
507
        }
508
    }
509

    
510
    av_free(pids);
511

    
512
    /* if no video stream, use the first stream as PCR */
513
    if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
514
        pcr_st = s->streams[0];
515
        ts_st = pcr_st->priv_data;
516
        service->pcr_pid = ts_st->pid;
517
    }
518

    
519
    ts->mux_rate = s->mux_rate ? s->mux_rate : 1;
520

    
521
    if (ts->mux_rate > 1) {
522
        service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
523
            (TS_PACKET_SIZE * 8 * 1000);
524
        ts->sdt_packet_period      = (ts->mux_rate * SDT_RETRANS_TIME) /
525
            (TS_PACKET_SIZE * 8 * 1000);
526
        ts->pat_packet_period      = (ts->mux_rate * PAT_RETRANS_TIME) /
527
            (TS_PACKET_SIZE * 8 * 1000);
528

    
529
        ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
530
    } else {
531
        /* Arbitrary values, PAT/PMT could be written on key frames */
532
        ts->sdt_packet_period = 200;
533
        ts->pat_packet_period = 40;
534
        if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
535
            if (!pcr_st->codec->frame_size) {
536
                av_log(s, AV_LOG_WARNING, "frame size not set\n");
537
                service->pcr_packet_period =
538
                    pcr_st->codec->sample_rate/(10*512);
539
            } else {
540
                service->pcr_packet_period =
541
                    pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
542
            }
543
        } else {
544
            // max delta PCR 0.1s
545
            service->pcr_packet_period =
546
                pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
547
        }
548
    }
549

    
550
    // output a PCR as soon as possible
551
    service->pcr_packet_count = service->pcr_packet_period;
552
    ts->pat_packet_count = ts->pat_packet_period-1;
553
    ts->sdt_packet_count = ts->sdt_packet_period-1;
554

    
555
    if (ts->mux_rate == 1)
556
        av_log(s, AV_LOG_INFO, "muxrate VBR, ");
557
    else
558
        av_log(s, AV_LOG_INFO, "muxrate %d, ", ts->mux_rate);
559
    av_log(s, AV_LOG_INFO, "pcr every %d pkts, "
560
           "sdt every %d, pat/pmt every %d pkts\n",
561
           service->pcr_packet_period,
562
           ts->sdt_packet_period, ts->pat_packet_period);
563

    
564
    put_flush_packet(s->pb);
565

    
566
    return 0;
567

    
568
 fail:
569
    av_free(pids);
570
    for(i = 0;i < s->nb_streams; i++) {
571
        st = s->streams[i];
572
        av_free(st->priv_data);
573
    }
574
    return -1;
575
}
576

    
577
/* send SDT, PAT and PMT tables regulary */
578
static void retransmit_si_info(AVFormatContext *s)
579
{
580
    MpegTSWrite *ts = s->priv_data;
581
    int i;
582

    
583
    if (++ts->sdt_packet_count == ts->sdt_packet_period) {
584
        ts->sdt_packet_count = 0;
585
        mpegts_write_sdt(s);
586
    }
587
    if (++ts->pat_packet_count == ts->pat_packet_period) {
588
        ts->pat_packet_count = 0;
589
        mpegts_write_pat(s);
590
        for(i = 0; i < ts->nb_services; i++) {
591
            mpegts_write_pmt(s, ts->services[i]);
592
        }
593
    }
594
}
595

    
596
static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
597
{
598
    return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
599
           ts->first_pcr;
600
}
601

    
602
static uint8_t* write_pcr_bits(uint8_t *buf, int64_t pcr)
603
{
604
    int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
605

    
606
    *buf++ = pcr_high >> 25;
607
    *buf++ = pcr_high >> 17;
608
    *buf++ = pcr_high >> 9;
609
    *buf++ = pcr_high >> 1;
610
    *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
611
    *buf++ = pcr_low;
612

    
613
    return buf;
614
}
615

    
616
/* Write a single null transport stream packet */
617
static void mpegts_insert_null_packet(AVFormatContext *s)
618
{
619
    uint8_t *q;
620
    uint8_t buf[TS_PACKET_SIZE];
621

    
622
    q = buf;
623
    *q++ = 0x47;
624
    *q++ = 0x00 | 0x1f;
625
    *q++ = 0xff;
626
    *q++ = 0x10;
627
    memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
628
    avio_write(s->pb, buf, TS_PACKET_SIZE);
629
}
630

    
631
/* Write a single transport stream packet with a PCR and no payload */
632
static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
633
{
634
    MpegTSWrite *ts = s->priv_data;
635
    MpegTSWriteStream *ts_st = st->priv_data;
636
    uint8_t *q;
637
    uint8_t buf[TS_PACKET_SIZE];
638

    
639
    q = buf;
640
    *q++ = 0x47;
641
    *q++ = ts_st->pid >> 8;
642
    *q++ = ts_st->pid;
643
    *q++ = 0x20 | ts_st->cc;   /* Adaptation only */
644
    /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
645
    *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
646
    *q++ = 0x10;               /* Adaptation flags: PCR present */
647

    
648
    /* PCR coded into 6 bytes */
649
    q = write_pcr_bits(q, get_pcr(ts, s->pb));
650

    
651
    /* stuffing bytes */
652
    memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
653
    avio_write(s->pb, buf, TS_PACKET_SIZE);
654
}
655

    
656
static void write_pts(uint8_t *q, int fourbits, int64_t pts)
657
{
658
    int val;
659

    
660
    val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
661
    *q++ = val;
662
    val = (((pts >> 15) & 0x7fff) << 1) | 1;
663
    *q++ = val >> 8;
664
    *q++ = val;
665
    val = (((pts) & 0x7fff) << 1) | 1;
666
    *q++ = val >> 8;
667
    *q++ = val;
668
}
669

    
670
/* Add a pes header to the front of payload, and segment into an integer number of
671
 * ts packets. The final ts packet is padded using an over-sized adaptation header
672
 * to exactly fill the last ts packet.
673
 * NOTE: 'payload' contains a complete PES payload.
674
 */
675
static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
676
                             const uint8_t *payload, int payload_size,
677
                             int64_t pts, int64_t dts)
678
{
679
    MpegTSWriteStream *ts_st = st->priv_data;
680
    MpegTSWrite *ts = s->priv_data;
681
    uint8_t buf[TS_PACKET_SIZE];
682
    uint8_t *q;
683
    int val, is_start, len, header_len, write_pcr, private_code, flags;
684
    int afc_len, stuffing_len;
685
    int64_t pcr = -1; /* avoid warning */
686
    int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
687

    
688
    is_start = 1;
689
    while (payload_size > 0) {
690
        retransmit_si_info(s);
691

    
692
        write_pcr = 0;
693
        if (ts_st->pid == ts_st->service->pcr_pid) {
694
            if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
695
                ts_st->service->pcr_packet_count++;
696
            if (ts_st->service->pcr_packet_count >=
697
                ts_st->service->pcr_packet_period) {
698
                ts_st->service->pcr_packet_count = 0;
699
                write_pcr = 1;
700
            }
701
        }
702

    
703
        if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
704
            (dts - get_pcr(ts, s->pb)/300) > delay) {
705
            /* pcr insert gets priority over null packet insert */
706
            if (write_pcr)
707
                mpegts_insert_pcr_only(s, st);
708
            else
709
                mpegts_insert_null_packet(s);
710
            continue; /* recalculate write_pcr and possibly retransmit si_info */
711
        }
712

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

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

    
853
static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
854
{
855
    AVStream *st = s->streams[pkt->stream_index];
856
    int size = pkt->size;
857
    uint8_t *buf= pkt->data;
858
    uint8_t *data= NULL;
859
    MpegTSWriteStream *ts_st = st->priv_data;
860
    const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
861
    int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
862

    
863
    if (pkt->pts != AV_NOPTS_VALUE)
864
        pts = pkt->pts + delay;
865
    if (pkt->dts != AV_NOPTS_VALUE)
866
        dts = pkt->dts + delay;
867

    
868
    if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
869
        av_log(s, AV_LOG_ERROR, "first pts value must set\n");
870
        return -1;
871
    }
872
    ts_st->first_pts_check = 0;
873

    
874
    if (st->codec->codec_id == CODEC_ID_H264) {
875
        const uint8_t *p = buf, *buf_end = p+size;
876
        uint32_t state = -1;
877

    
878
        if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
879
            av_log(s, AV_LOG_ERROR, "h264 bitstream malformated, "
880
                   "no startcode found, use -vbsf h264_mp4toannexb\n");
881
            return -1;
882
        }
883

    
884
        do {
885
            p = ff_find_start_code(p, buf_end, &state);
886
            //av_log(s, AV_LOG_INFO, "nal %d\n", state & 0x1f);
887
        } while (p < buf_end && (state & 0x1f) != 9 &&
888
                 (state & 0x1f) != 5 && (state & 0x1f) != 1);
889

    
890
        if ((state & 0x1f) != 9) { // AUD NAL
891
            data = av_malloc(pkt->size+6);
892
            if (!data)
893
                return -1;
894
            memcpy(data+6, pkt->data, pkt->size);
895
            AV_WB32(data, 0x00000001);
896
            data[4] = 0x09;
897
            data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
898
            buf  = data;
899
            size = pkt->size+6;
900
        }
901
    } else if (st->codec->codec_id == CODEC_ID_AAC) {
902
        if (pkt->size < 2)
903
            return -1;
904
        if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
905
            ADTSContext *adts = ts_st->adts;
906
            int new_size;
907
            if (!adts) {
908
                av_log(s, AV_LOG_ERROR, "aac bitstream not in adts format "
909
                       "and extradata missing\n");
910
                return -1;
911
            }
912
            new_size = ADTS_HEADER_SIZE+adts->pce_size+pkt->size;
913
            if ((unsigned)new_size >= INT_MAX)
914
                return -1;
915
            data = av_malloc(new_size);
916
            if (!data)
917
                return AVERROR(ENOMEM);
918
            ff_adts_write_frame_header(adts, data, pkt->size, adts->pce_size);
919
            if (adts->pce_size) {
920
                memcpy(data+ADTS_HEADER_SIZE, adts->pce_data, adts->pce_size);
921
                adts->pce_size = 0;
922
            }
923
            memcpy(data+ADTS_HEADER_SIZE+adts->pce_size, pkt->data, pkt->size);
924
            buf = data;
925
            size = new_size;
926
        }
927
    }
928

    
929
    if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
930
        // for video and subtitle, write a single pes packet
931
        mpegts_write_pes(s, st, buf, size, pts, dts);
932
        av_free(data);
933
        return 0;
934
    }
935

    
936
    if (ts_st->payload_index + size > DEFAULT_PES_PAYLOAD_SIZE) {
937
        mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
938
                         ts_st->payload_pts, ts_st->payload_dts);
939
        ts_st->payload_index = 0;
940
    }
941

    
942
    if (!ts_st->payload_index) {
943
        ts_st->payload_pts = pts;
944
        ts_st->payload_dts = dts;
945
    }
946

    
947
    memcpy(ts_st->payload + ts_st->payload_index, buf, size);
948
    ts_st->payload_index += size;
949

    
950
    av_free(data);
951

    
952
    return 0;
953
}
954

    
955
static int mpegts_write_end(AVFormatContext *s)
956
{
957
    MpegTSWrite *ts = s->priv_data;
958
    MpegTSWriteStream *ts_st;
959
    MpegTSService *service;
960
    AVStream *st;
961
    int i;
962

    
963
    /* flush current packets */
964
    for(i = 0; i < s->nb_streams; i++) {
965
        st = s->streams[i];
966
        ts_st = st->priv_data;
967
        if (ts_st->payload_index > 0) {
968
            mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
969
                             ts_st->payload_pts, ts_st->payload_dts);
970
        }
971
        av_freep(&ts_st->adts);
972
    }
973
    put_flush_packet(s->pb);
974

    
975
    for(i = 0; i < ts->nb_services; i++) {
976
        service = ts->services[i];
977
        av_freep(&service->provider_name);
978
        av_freep(&service->name);
979
        av_free(service);
980
    }
981
    av_free(ts->services);
982

    
983
    return 0;
984
}
985

    
986
AVOutputFormat ff_mpegts_muxer = {
987
    "mpegts",
988
    NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
989
    "video/x-mpegts",
990
    "ts,m2t",
991
    sizeof(MpegTSWrite),
992
    CODEC_ID_MP2,
993
    CODEC_ID_MPEG2VIDEO,
994
    mpegts_write_header,
995
    mpegts_write_packet,
996
    mpegts_write_end,
997
    .priv_class = &mpegts_muxer_class,
998
};