Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegtsenc.c @ ef011e6d

History | View | Annotate | Download (29.7 KB)

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

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

    
30
/* write DVB SI sections */
31

    
32
/*********************************************/
33
/* mpegts section writer */
34

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

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

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

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

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

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

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

    
110
        buf_ptr += len1;
111
        len -= len1;
112

    
113
        ts->cur_pcr += TS_PACKET_SIZE*8*90000LL/ts->mux_rate;
114
    }
115
}
116

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
214
    /* put program info here */
215

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

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

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

    
295
        val = 0xf000 | (q - desc_length_ptr - 2);
296
        desc_length_ptr[0] = val >> 8;
297
        desc_length_ptr[1] = val;
298
    }
299
    mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,
300
                          data, q - data);
301
}
302

    
303
/* NOTE: str == NULL is accepted for an empty string */
304
static void putstr8(uint8_t **q_ptr, const char *str)
305
{
306
    uint8_t *q;
307
    int len;
308

    
309
    q = *q_ptr;
310
    if (!str)
311
        len = 0;
312
    else
313
        len = strlen(str);
314
    *q++ = len;
315
    memcpy(q, str, len);
316
    q += len;
317
    *q_ptr = q;
318
}
319

    
320
static void mpegts_write_sdt(AVFormatContext *s)
321
{
322
    MpegTSWrite *ts = s->priv_data;
323
    MpegTSService *service;
324
    uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
325
    int i, running_status, free_ca_mode, val;
326

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

    
339
        /* write only one descriptor for the service name and provider */
340
        *q++ = 0x48;
341
        desc_len_ptr = q;
342
        q++;
343
        *q++ = 0x01; /* digital television service */
344
        putstr8(&q, service->provider_name);
345
        putstr8(&q, service->name);
346
        desc_len_ptr[0] = q - desc_len_ptr - 1;
347

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

    
358
static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
359
                                         int sid,
360
                                         const char *provider_name,
361
                                         const char *name)
362
{
363
    MpegTSService *service;
364

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

    
377
static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
378
{
379
    AVFormatContext *ctx = s->opaque;
380
    put_buffer(ctx->pb, packet, TS_PACKET_SIZE);
381
}
382

    
383
static int mpegts_write_header(AVFormatContext *s)
384
{
385
    MpegTSWrite *ts = s->priv_data;
386
    MpegTSWriteStream *ts_st;
387
    MpegTSService *service;
388
    AVStream *st, *pcr_st = NULL;
389
    AVMetadataTag *title;
390
    int i, j;
391
    const char *service_name;
392
    int *pids;
393

    
394
    ts->tsid = DEFAULT_TSID;
395
    ts->onid = DEFAULT_ONID;
396
    /* allocate a single DVB service */
397
    title = av_metadata_get(s->metadata, "title", NULL, 0);
398
    service_name = title ? title->value : DEFAULT_SERVICE_NAME;
399
    service = mpegts_add_service(ts, DEFAULT_SID,
400
                                 DEFAULT_PROVIDER_NAME, service_name);
401
    service->pmt.write_packet = section_write_packet;
402
    service->pmt.opaque = s;
403
    service->pmt.cc = 15;
404

    
405
    ts->pat.pid = PAT_PID;
406
    ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
407
    ts->pat.write_packet = section_write_packet;
408
    ts->pat.opaque = s;
409

    
410
    ts->sdt.pid = SDT_PID;
411
    ts->sdt.cc = 15;
412
    ts->sdt.write_packet = section_write_packet;
413
    ts->sdt.opaque = s;
414

    
415
    pids = av_malloc(s->nb_streams * sizeof(*pids));
416
    if (!pids)
417
        return AVERROR(ENOMEM);
418

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

    
468
    av_free(pids);
469

    
470
    /* if no video stream, use the first stream as PCR */
471
    if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
472
        pcr_st = s->streams[0];
473
        ts_st = pcr_st->priv_data;
474
        service->pcr_pid = ts_st->pid;
475
    }
476

    
477
    ts->mux_rate = s->mux_rate ? s->mux_rate : 1;
478

    
479
    if (ts->mux_rate > 1) {
480
        service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
481
            (TS_PACKET_SIZE * 8 * 1000);
482
        ts->sdt_packet_period      = (ts->mux_rate * SDT_RETRANS_TIME) /
483
            (TS_PACKET_SIZE * 8 * 1000);
484
        ts->pat_packet_period      = (ts->mux_rate * PAT_RETRANS_TIME) /
485
            (TS_PACKET_SIZE * 8 * 1000);
486

    
487
        ts->cur_pcr = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
488
    } else {
489
        /* Arbitrary values, PAT/PMT could be written on key frames */
490
        ts->sdt_packet_period = 200;
491
        ts->pat_packet_period = 40;
492
        if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
493
            if (!pcr_st->codec->frame_size) {
494
                av_log(s, AV_LOG_WARNING, "frame size not set\n");
495
                service->pcr_packet_period =
496
                    pcr_st->codec->sample_rate/(10*512);
497
            } else {
498
                service->pcr_packet_period =
499
                    pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
500
            }
501
        } else {
502
            // max delta PCR 0.1s
503
            service->pcr_packet_period =
504
                pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
505
        }
506
    }
507

    
508
    // output a PCR as soon as possible
509
    service->pcr_packet_count = service->pcr_packet_period;
510
    ts->pat_packet_count = ts->pat_packet_period-1;
511
    ts->sdt_packet_count = ts->sdt_packet_period-1;
512

    
513
    if (ts->mux_rate == 1)
514
        av_log(s, AV_LOG_INFO, "muxrate VBR, ");
515
    else
516
        av_log(s, AV_LOG_INFO, "muxrate %d, ", ts->mux_rate);
517
    av_log(s, AV_LOG_INFO, "pcr every %d pkts, "
518
           "sdt every %d, pat/pmt every %d pkts\n",
519
           service->pcr_packet_period,
520
           ts->sdt_packet_period, ts->pat_packet_period);
521

    
522
    put_flush_packet(s->pb);
523

    
524
    return 0;
525

    
526
 fail:
527
    av_free(pids);
528
    for(i = 0;i < s->nb_streams; i++) {
529
        st = s->streams[i];
530
        av_free(st->priv_data);
531
    }
532
    return -1;
533
}
534

    
535
/* send SDT, PAT and PMT tables regulary */
536
static void retransmit_si_info(AVFormatContext *s)
537
{
538
    MpegTSWrite *ts = s->priv_data;
539
    int i;
540

    
541
    if (++ts->sdt_packet_count == ts->sdt_packet_period) {
542
        ts->sdt_packet_count = 0;
543
        mpegts_write_sdt(s);
544
    }
545
    if (++ts->pat_packet_count == ts->pat_packet_period) {
546
        ts->pat_packet_count = 0;
547
        mpegts_write_pat(s);
548
        for(i = 0; i < ts->nb_services; i++) {
549
            mpegts_write_pmt(s, ts->services[i]);
550
        }
551
    }
552
}
553

    
554
/* Write a single null transport stream packet */
555
static void mpegts_insert_null_packet(AVFormatContext *s)
556
{
557
    MpegTSWrite *ts = s->priv_data;
558
    uint8_t *q;
559
    uint8_t buf[TS_PACKET_SIZE];
560

    
561
    q = buf;
562
    *q++ = 0x47;
563
    *q++ = 0x00 | 0x1f;
564
    *q++ = 0xff;
565
    *q++ = 0x10;
566
    memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
567
    put_buffer(s->pb, buf, TS_PACKET_SIZE);
568
    ts->cur_pcr += TS_PACKET_SIZE*8*90000LL/ts->mux_rate;
569
}
570

    
571
/* Write a single transport stream packet with a PCR and no payload */
572
static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
573
{
574
    MpegTSWrite *ts = s->priv_data;
575
    MpegTSWriteStream *ts_st = st->priv_data;
576
    uint8_t *q;
577
    uint64_t pcr = ts->cur_pcr;
578
    uint8_t buf[TS_PACKET_SIZE];
579

    
580
    q = buf;
581
    *q++ = 0x47;
582
    *q++ = ts_st->pid >> 8;
583
    *q++ = ts_st->pid;
584
    *q++ = 0x20 | ts_st->cc;   /* Adaptation only */
585
    /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
586
    *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
587
    *q++ = 0x10;               /* Adaptation flags: PCR present */
588

    
589
    /* PCR coded into 6 bytes */
590
    *q++ = pcr >> 25;
591
    *q++ = pcr >> 17;
592
    *q++ = pcr >> 9;
593
    *q++ = pcr >> 1;
594
    *q++ = (pcr & 1) << 7;
595
    *q++ = 0;
596

    
597
    /* stuffing bytes */
598
    memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
599
    put_buffer(s->pb, buf, TS_PACKET_SIZE);
600
    ts->cur_pcr += TS_PACKET_SIZE*8*90000LL/ts->mux_rate;
601
}
602

    
603
static void write_pts(uint8_t *q, int fourbits, int64_t pts)
604
{
605
    int val;
606

    
607
    val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
608
    *q++ = val;
609
    val = (((pts >> 15) & 0x7fff) << 1) | 1;
610
    *q++ = val >> 8;
611
    *q++ = val;
612
    val = (((pts) & 0x7fff) << 1) | 1;
613
    *q++ = val >> 8;
614
    *q++ = val;
615
}
616

    
617
/* Add a pes header to the front of payload, and segment into an integer number of
618
 * ts packets. The final ts packet is padded using an over-sized adaptation header
619
 * to exactly fill the last ts packet.
620
 * NOTE: 'payload' contains a complete PES payload.
621
 */
622
static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
623
                             const uint8_t *payload, int payload_size,
624
                             int64_t pts, int64_t dts)
625
{
626
    MpegTSWriteStream *ts_st = st->priv_data;
627
    MpegTSWrite *ts = s->priv_data;
628
    uint8_t buf[TS_PACKET_SIZE];
629
    uint8_t *q;
630
    int val, is_start, len, header_len, write_pcr, private_code, flags;
631
    int afc_len, stuffing_len;
632
    int64_t pcr = -1; /* avoid warning */
633
    int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
634

    
635
    is_start = 1;
636
    while (payload_size > 0) {
637
        retransmit_si_info(s);
638

    
639
        write_pcr = 0;
640
        if (ts_st->pid == ts_st->service->pcr_pid) {
641
            if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
642
                ts_st->service->pcr_packet_count++;
643
            if (ts_st->service->pcr_packet_count >=
644
                ts_st->service->pcr_packet_period) {
645
                ts_st->service->pcr_packet_count = 0;
646
                write_pcr = 1;
647
            }
648
        }
649

    
650
        if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
651
            (dts - (int64_t)ts->cur_pcr) > delay) {
652
            /* pcr insert gets priority over null packet insert */
653
            if (write_pcr)
654
                mpegts_insert_pcr_only(s, st);
655
            else
656
                mpegts_insert_null_packet(s);
657
            continue; /* recalculate write_pcr and possibly retransmit si_info */
658
        }
659

    
660
        /* prepare packet header */
661
        q = buf;
662
        *q++ = 0x47;
663
        val = (ts_st->pid >> 8);
664
        if (is_start)
665
            val |= 0x40;
666
        *q++ = val;
667
        *q++ = ts_st->pid;
668
        ts_st->cc = (ts_st->cc + 1) & 0xf;
669
        *q++ = 0x10 | ts_st->cc | (write_pcr ? 0x20 : 0);
670
        if (write_pcr) {
671
            // add 11, pcr references the last byte of program clock reference base
672
            if (ts->mux_rate > 1)
673
                pcr = ts->cur_pcr + (4+7)*8*90000LL / ts->mux_rate;
674
            else
675
                pcr = dts - delay;
676
            if (dts != AV_NOPTS_VALUE && dts < pcr)
677
                av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
678
            *q++ = 7; /* AFC length */
679
            *q++ = 0x10; /* flags: PCR present */
680
            *q++ = pcr >> 25;
681
            *q++ = pcr >> 17;
682
            *q++ = pcr >> 9;
683
            *q++ = pcr >> 1;
684
            *q++ = (pcr & 1) << 7;
685
            *q++ = 0;
686
        }
687
        if (is_start) {
688
            int pes_extension = 0;
689
            /* write PES header */
690
            *q++ = 0x00;
691
            *q++ = 0x00;
692
            *q++ = 0x01;
693
            private_code = 0;
694
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
695
                if (st->codec->codec_id == CODEC_ID_DIRAC) {
696
                    *q++ = 0xfd;
697
                } else
698
                    *q++ = 0xe0;
699
            } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
700
                       (st->codec->codec_id == CODEC_ID_MP2 ||
701
                        st->codec->codec_id == CODEC_ID_MP3)) {
702
                *q++ = 0xc0;
703
            } else {
704
                *q++ = 0xbd;
705
                if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
706
                    private_code = 0x20;
707
                }
708
            }
709
            header_len = 0;
710
            flags = 0;
711
            if (pts != AV_NOPTS_VALUE) {
712
                header_len += 5;
713
                flags |= 0x80;
714
            }
715
            if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
716
                header_len += 5;
717
                flags |= 0x40;
718
            }
719
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
720
                st->codec->codec_id == CODEC_ID_DIRAC) {
721
                /* set PES_extension_flag */
722
                pes_extension = 1;
723
                flags |= 0x01;
724

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

    
805
static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
806
{
807
    AVStream *st = s->streams[pkt->stream_index];
808
    int size = pkt->size;
809
    uint8_t *buf= pkt->data;
810
    uint8_t *data= NULL;
811
    MpegTSWriteStream *ts_st = st->priv_data;
812
    const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
813
    int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
814

    
815
    if (pkt->pts != AV_NOPTS_VALUE)
816
        pts = pkt->pts + delay;
817
    if (pkt->dts != AV_NOPTS_VALUE)
818
        dts = pkt->dts + delay;
819

    
820
    if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
821
        av_log(s, AV_LOG_ERROR, "first pts value must set\n");
822
        return -1;
823
    }
824
    ts_st->first_pts_check = 0;
825

    
826
    if (st->codec->codec_id == CODEC_ID_H264) {
827
        const uint8_t *p = buf, *buf_end = p+size;
828
        uint32_t state = -1;
829

    
830
        if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
831
            av_log(s, AV_LOG_ERROR, "h264 bitstream malformated, "
832
                   "no startcode found, use -vbsf h264_mp4toannexb\n");
833
            return -1;
834
        }
835

    
836
        do {
837
            p = ff_find_start_code(p, buf_end, &state);
838
            //av_log(s, AV_LOG_INFO, "nal %d\n", state & 0x1f);
839
        } while (p < buf_end && (state & 0x1f) != 9 &&
840
                 (state & 0x1f) != 5 && (state & 0x1f) != 1);
841

    
842
        if ((state & 0x1f) != 9) { // AUD NAL
843
            data = av_malloc(pkt->size+6);
844
            if (!data)
845
                return -1;
846
            memcpy(data+6, pkt->data, pkt->size);
847
            AV_WB32(data, 0x00000001);
848
            data[4] = 0x09;
849
            data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
850
            buf  = data;
851
            size = pkt->size+6;
852
        }
853
    } else if (st->codec->codec_id == CODEC_ID_AAC) {
854
        if (pkt->size < 2)
855
            return -1;
856
        if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
857
            ADTSContext *adts = ts_st->adts;
858
            int new_size;
859
            if (!adts) {
860
                av_log(s, AV_LOG_ERROR, "aac bitstream not in adts format "
861
                       "and extradata missing\n");
862
                return -1;
863
            }
864
            new_size = ADTS_HEADER_SIZE+adts->pce_size+pkt->size;
865
            if ((unsigned)new_size >= INT_MAX)
866
                return -1;
867
            data = av_malloc(new_size);
868
            if (!data)
869
                return AVERROR(ENOMEM);
870
            ff_adts_write_frame_header(adts, data, pkt->size, adts->pce_size);
871
            if (adts->pce_size) {
872
                memcpy(data+ADTS_HEADER_SIZE, adts->pce_data, adts->pce_size);
873
                adts->pce_size = 0;
874
            }
875
            memcpy(data+ADTS_HEADER_SIZE+adts->pce_size, pkt->data, pkt->size);
876
            buf = data;
877
            size = new_size;
878
        }
879
    }
880

    
881
    if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
882
        // for video and subtitle, write a single pes packet
883
        mpegts_write_pes(s, st, buf, size, pts, dts);
884
        av_free(data);
885
        return 0;
886
    }
887

    
888
    if (ts_st->payload_index + size > DEFAULT_PES_PAYLOAD_SIZE) {
889
        mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
890
                         ts_st->payload_pts, ts_st->payload_dts);
891
        ts_st->payload_index = 0;
892
    }
893

    
894
    if (!ts_st->payload_index) {
895
        ts_st->payload_pts = pts;
896
        ts_st->payload_dts = dts;
897
    }
898

    
899
    memcpy(ts_st->payload + ts_st->payload_index, buf, size);
900
    ts_st->payload_index += size;
901

    
902
    av_free(data);
903

    
904
    return 0;
905
}
906

    
907
static int mpegts_write_end(AVFormatContext *s)
908
{
909
    MpegTSWrite *ts = s->priv_data;
910
    MpegTSWriteStream *ts_st;
911
    MpegTSService *service;
912
    AVStream *st;
913
    int i;
914

    
915
    /* flush current packets */
916
    for(i = 0; i < s->nb_streams; i++) {
917
        st = s->streams[i];
918
        ts_st = st->priv_data;
919
        if (ts_st->payload_index > 0) {
920
            mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
921
                             ts_st->payload_pts, ts_st->payload_dts);
922
        }
923
        av_freep(&ts_st->adts);
924
    }
925
    put_flush_packet(s->pb);
926

    
927
    for(i = 0; i < ts->nb_services; i++) {
928
        service = ts->services[i];
929
        av_freep(&service->provider_name);
930
        av_freep(&service->name);
931
        av_free(service);
932
    }
933
    av_free(ts->services);
934

    
935
    return 0;
936
}
937

    
938
AVOutputFormat mpegts_muxer = {
939
    "mpegts",
940
    NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
941
    "video/x-mpegts",
942
    "ts,m2t",
943
    sizeof(MpegTSWrite),
944
    CODEC_ID_MP2,
945
    CODEC_ID_MPEG2VIDEO,
946
    mpegts_write_header,
947
    mpegts_write_packet,
948
    mpegts_write_end,
949
};