Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegtsenc.c @ 677a1144

History | View | Annotate | Download (27.4 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 "mpegts.h"
27

    
28
/* write DVB SI sections */
29

    
30
/*********************************************/
31
/* mpegts section writer */
32

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

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

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

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

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

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

    
106
        s->write_packet(s, packet);
107

    
108
        buf_ptr += len1;
109
        len -= len1;
110

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

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

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

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

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

    
145
    mpegts_write_section(s, section, tot_len);
146
    return 0;
147
}
148

    
149
/*********************************************/
150
/* mpegts writer */
151

    
152
#define DEFAULT_PMT_START_PID   0x1000
153
#define DEFAULT_START_PID       0x0100
154
#define DEFAULT_PROVIDER_NAME   "FFmpeg"
155
#define DEFAULT_SERVICE_NAME    "Service01"
156

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

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

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

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

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

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

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

    
205
    q = data;
206
    put16(&q, 0xe000 | service->pcr_pid);
207

    
208
    program_info_length_ptr = q;
209
    q += 2; /* patched after */
210

    
211
    /* put program info here */
212

    
213
    val = 0xf000 | (q - program_info_length_ptr - 2);
214
    program_info_length_ptr[0] = val >> 8;
215
    program_info_length_ptr[1] = val;
216

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

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

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

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

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

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

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

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

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

    
355
static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
356
                                         int sid,
357
                                         const char *provider_name,
358
                                         const char *name)
359
{
360
    MpegTSService *service;
361

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

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

    
380
static int mpegts_write_header(AVFormatContext *s)
381
{
382
    MpegTSWrite *ts = s->priv_data;
383
    MpegTSWriteStream *ts_st;
384
    MpegTSService *service;
385
    AVStream *st;
386
    AVMetadataTag *title;
387
    int i, total_bit_rate;
388
    const char *service_name;
389
    uint64_t sdt_size, pat_pmt_size, pos;
390

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

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

    
407
    ts->sdt.pid = SDT_PID;
408
    ts->sdt.cc = 15;
409
    ts->sdt.write_packet = section_write_packet;
410
    ts->sdt.opaque = s;
411

    
412
    /* assign pids to each stream */
413
    total_bit_rate = 0;
414
    for(i = 0;i < s->nb_streams; i++) {
415
        st = s->streams[i];
416
        ts_st = av_mallocz(sizeof(MpegTSWriteStream));
417
        if (!ts_st)
418
            goto fail;
419
        st->priv_data = ts_st;
420
        ts_st->service = service;
421
        ts_st->pid = DEFAULT_START_PID + i;
422
        ts_st->payload_pts = AV_NOPTS_VALUE;
423
        ts_st->payload_dts = AV_NOPTS_VALUE;
424
        ts_st->first_pts_check = 1;
425
        ts_st->cc = 15;
426
        /* update PCR pid by using the first video stream */
427
        if (st->codec->codec_type == CODEC_TYPE_VIDEO &&
428
            service->pcr_pid == 0x1fff)
429
            service->pcr_pid = ts_st->pid;
430
        if (st->codec->rc_max_rate)
431
            total_bit_rate += st->codec->rc_max_rate;
432
        else {
433
            if (!st->codec->bit_rate) {
434
                av_log(s, AV_LOG_WARNING,
435
                       "stream %d, bit rate is not set, this will cause problems\n",
436
                       st->index);
437
            }
438
            total_bit_rate += st->codec->bit_rate;
439
        }
440
        /* PES header size */
441
        if (st->codec->codec_type == CODEC_TYPE_VIDEO ||
442
            st->codec->codec_type == CODEC_TYPE_SUBTITLE) {
443
            /* 1 PES per frame
444
             * 19 bytes of PES header
445
             * on average a half TS-packet (184/2) of padding-overhead every PES */
446
            total_bit_rate += (19 + 184/2)*8 / av_q2d(st->codec->time_base);
447
        } else {
448
            /* 1 PES per DEFAULT_PES_PAYLOAD_SIZE bytes of audio data
449
             * 14 bytes of PES header
450
             * on average a half TS-packet (184/2) of padding-overhead every PES */
451
            total_bit_rate += (14 + 184/2) *
452
                st->codec->bit_rate / DEFAULT_PES_PAYLOAD_SIZE;
453
        }
454
    }
455

    
456
    /* if no video stream, use the first stream as PCR */
457
    if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
458
        ts_st = s->streams[0]->priv_data;
459
        service->pcr_pid = ts_st->pid;
460
    }
461

    
462
    ts->mux_rate = 1; // avoid div by 0
463

    
464
    /* write info at the start of the file, so that it will be fast to
465
       find them */
466
    pos = url_ftell(s->pb);
467
    mpegts_write_sdt(s);
468
    sdt_size = url_ftell(s->pb) - pos;
469
    pos = url_ftell(s->pb);
470
    mpegts_write_pat(s);
471
    for(i = 0; i < ts->nb_services; i++) {
472
        mpegts_write_pmt(s, ts->services[i]);
473
    }
474
    pat_pmt_size = url_ftell(s->pb) - pos;
475

    
476
    if (total_bit_rate <= 8 * 1024)
477
        total_bit_rate = 8 * 1024;
478

    
479
    total_bit_rate +=
480
        total_bit_rate * 4 / (TS_PACKET_SIZE-4)        + /* TS header size */
481
        1000 * 8 * sdt_size     / SDT_RETRANS_TIME     + /* SDT size */
482
        1000 * 8 * pat_pmt_size / PAT_RETRANS_TIME     + /* PAT+PMT size */
483
        1000 * 8 * 8            / PCR_RETRANS_TIME;      /* PCR size */
484

    
485
    if (s->mux_rate)
486
        ts->mux_rate = s->mux_rate;
487
    else
488
        ts->mux_rate = total_bit_rate;
489

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

    
497
    // output a PCR as soon as possible
498
    service->pcr_packet_count = service->pcr_packet_period;
499

    
500
    av_log(s, AV_LOG_DEBUG,
501
           "calculated bitrate %d bps, muxrate %d bps, "
502
           "sdt every %d, pat/pmt every %d pkts\n",
503
           total_bit_rate, ts->mux_rate, ts->sdt_packet_period,
504
           ts->pat_packet_period);
505

    
506
    // adjust pcr
507
    ts->cur_pcr /= ts->mux_rate;
508

    
509
    put_flush_packet(s->pb);
510

    
511
    return 0;
512

    
513
 fail:
514
    for(i = 0;i < s->nb_streams; i++) {
515
        st = s->streams[i];
516
        av_free(st->priv_data);
517
    }
518
    return -1;
519
}
520

    
521
/* send SDT, PAT and PMT tables regulary */
522
static void retransmit_si_info(AVFormatContext *s)
523
{
524
    MpegTSWrite *ts = s->priv_data;
525
    int i;
526

    
527
    if (++ts->sdt_packet_count == ts->sdt_packet_period) {
528
        ts->sdt_packet_count = 0;
529
        mpegts_write_sdt(s);
530
    }
531
    if (++ts->pat_packet_count == ts->pat_packet_period) {
532
        ts->pat_packet_count = 0;
533
        mpegts_write_pat(s);
534
        for(i = 0; i < ts->nb_services; i++) {
535
            mpegts_write_pmt(s, ts->services[i]);
536
        }
537
    }
538
}
539

    
540
/* Write a single null transport stream packet */
541
static void mpegts_insert_null_packet(AVFormatContext *s)
542
{
543
    MpegTSWrite *ts = s->priv_data;
544
    uint8_t *q;
545
    uint8_t buf[TS_PACKET_SIZE];
546

    
547
    q = buf;
548
    *q++ = 0x47;
549
    *q++ = 0x00 | 0x1f;
550
    *q++ = 0xff;
551
    *q++ = 0x10;
552
    memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
553
    put_buffer(s->pb, buf, TS_PACKET_SIZE);
554
    ts->cur_pcr += TS_PACKET_SIZE*8*90000LL/ts->mux_rate;
555
}
556

    
557
/* Write a single transport stream packet with a PCR and no payload */
558
static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
559
{
560
    MpegTSWrite *ts = s->priv_data;
561
    MpegTSWriteStream *ts_st = st->priv_data;
562
    uint8_t *q;
563
    uint64_t pcr = ts->cur_pcr;
564
    uint8_t buf[TS_PACKET_SIZE];
565

    
566
    q = buf;
567
    *q++ = 0x47;
568
    *q++ = ts_st->pid >> 8;
569
    *q++ = ts_st->pid;
570
    *q++ = 0x20 | ts_st->cc;   /* Adaptation only */
571
    /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
572
    *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
573
    *q++ = 0x10;               /* Adaptation flags: PCR present */
574

    
575
    /* PCR coded into 6 bytes */
576
    *q++ = pcr >> 25;
577
    *q++ = pcr >> 17;
578
    *q++ = pcr >> 9;
579
    *q++ = pcr >> 1;
580
    *q++ = (pcr & 1) << 7;
581
    *q++ = 0;
582

    
583
    /* stuffing bytes */
584
    memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
585
    put_buffer(s->pb, buf, TS_PACKET_SIZE);
586
    ts->cur_pcr += TS_PACKET_SIZE*8*90000LL/ts->mux_rate;
587
}
588

    
589
static void write_pts(uint8_t *q, int fourbits, int64_t pts)
590
{
591
    int val;
592

    
593
    val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
594
    *q++ = val;
595
    val = (((pts >> 15) & 0x7fff) << 1) | 1;
596
    *q++ = val >> 8;
597
    *q++ = val;
598
    val = (((pts) & 0x7fff) << 1) | 1;
599
    *q++ = val >> 8;
600
    *q++ = val;
601
}
602

    
603
/* Add a pes header to the front of payload, and segment into an integer number of
604
 * ts packets. The final ts packet is padded using an over-sized adaptation header
605
 * to exactly fill the last ts packet.
606
 * NOTE: 'payload' contains a complete PES payload.
607
 */
608
static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
609
                             const uint8_t *payload, int payload_size,
610
                             int64_t pts, int64_t dts)
611
{
612
    MpegTSWriteStream *ts_st = st->priv_data;
613
    MpegTSWrite *ts = s->priv_data;
614
    uint8_t buf[TS_PACKET_SIZE];
615
    uint8_t *q;
616
    int val, is_start, len, header_len, write_pcr, private_code, flags;
617
    int afc_len, stuffing_len;
618
    int64_t pcr = -1; /* avoid warning */
619
    int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
620

    
621
    is_start = 1;
622
    while (payload_size > 0) {
623
        retransmit_si_info(s);
624

    
625
        write_pcr = 0;
626
        if (ts_st->pid == ts_st->service->pcr_pid) {
627
            ts_st->service->pcr_packet_count++;
628
            if (ts_st->service->pcr_packet_count >=
629
                ts_st->service->pcr_packet_period) {
630
                ts_st->service->pcr_packet_count = 0;
631
                write_pcr = 1;
632
            }
633
        }
634

    
635
        if (dts != AV_NOPTS_VALUE && (dts - (int64_t)ts->cur_pcr) > delay) {
636
            /* pcr insert gets priority over null packet insert */
637
            if (write_pcr)
638
                mpegts_insert_pcr_only(s, st);
639
            else
640
                mpegts_insert_null_packet(s);
641
            continue; /* recalculate write_pcr and possibly retransmit si_info */
642
        }
643

    
644
        /* prepare packet header */
645
        q = buf;
646
        *q++ = 0x47;
647
        val = (ts_st->pid >> 8);
648
        if (is_start)
649
            val |= 0x40;
650
        *q++ = val;
651
        *q++ = ts_st->pid;
652
        ts_st->cc = (ts_st->cc + 1) & 0xf;
653
        *q++ = 0x10 | ts_st->cc | (write_pcr ? 0x20 : 0);
654
        if (write_pcr) {
655
            // add 11, pcr references the last byte of program clock reference base
656
            pcr = ts->cur_pcr + (4+7)*8*90000LL / ts->mux_rate;
657
            if (dts != AV_NOPTS_VALUE && dts < pcr)
658
                av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
659
            *q++ = 7; /* AFC length */
660
            *q++ = 0x10; /* flags: PCR present */
661
            *q++ = pcr >> 25;
662
            *q++ = pcr >> 17;
663
            *q++ = pcr >> 9;
664
            *q++ = pcr >> 1;
665
            *q++ = (pcr & 1) << 7;
666
            *q++ = 0;
667
        }
668
        if (is_start) {
669
            int pes_extension = 0;
670
            /* write PES header */
671
            *q++ = 0x00;
672
            *q++ = 0x00;
673
            *q++ = 0x01;
674
            private_code = 0;
675
            if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
676
                if (st->codec->codec_id == CODEC_ID_DIRAC) {
677
                    *q++ = 0xfd;
678
                } else
679
                    *q++ = 0xe0;
680
            } else if (st->codec->codec_type == CODEC_TYPE_AUDIO &&
681
                       (st->codec->codec_id == CODEC_ID_MP2 ||
682
                        st->codec->codec_id == CODEC_ID_MP3)) {
683
                *q++ = 0xc0;
684
            } else {
685
                *q++ = 0xbd;
686
                if (st->codec->codec_type == CODEC_TYPE_SUBTITLE) {
687
                    private_code = 0x20;
688
                }
689
            }
690
            header_len = 0;
691
            flags = 0;
692
            if (pts != AV_NOPTS_VALUE) {
693
                header_len += 5;
694
                flags |= 0x80;
695
            }
696
            if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
697
                header_len += 5;
698
                flags |= 0x40;
699
            }
700
            if (st->codec->codec_type == CODEC_TYPE_VIDEO &&
701
                st->codec->codec_id == CODEC_ID_DIRAC) {
702
                /* set PES_extension_flag */
703
                pes_extension = 1;
704
                flags |= 0x01;
705

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

    
786
static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
787
{
788
    AVStream *st = s->streams[pkt->stream_index];
789
    int size = pkt->size;
790
    uint8_t *buf= pkt->data;
791
    uint8_t *data= NULL;
792
    MpegTSWriteStream *ts_st = st->priv_data;
793
    const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
794
    int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
795

    
796
    if (pkt->pts != AV_NOPTS_VALUE)
797
        pts = pkt->pts + delay;
798
    if (pkt->dts != AV_NOPTS_VALUE)
799
        dts = pkt->dts + delay;
800

    
801
    if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
802
        av_log(s, AV_LOG_ERROR, "first pts value must set\n");
803
        return -1;
804
    }
805
    ts_st->first_pts_check = 0;
806

    
807
    if (st->codec->codec_id == CODEC_ID_H264) {
808
        if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
809
            av_log(s, AV_LOG_ERROR, "h264 bitstream malformated\n");
810
            return -1;
811
        }
812
        if (pkt->data[4] != 0x09) { // AUD NAL
813
            data = av_malloc(pkt->size+6);
814
            if (!data)
815
                return -1;
816
            memcpy(data+6, pkt->data, pkt->size);
817
            AV_WB32(data, 0x00000001);
818
            data[4] = 0x09;
819
            data[5] = 0xe0; // any slice type
820
            buf  = data;
821
            size = pkt->size+6;
822
        }
823
    }
824

    
825
    if (st->codec->codec_type != CODEC_TYPE_AUDIO) {
826
        // for video and subtitle, write a single pes packet
827
        mpegts_write_pes(s, st, buf, size, pts, dts);
828
        av_free(data);
829
        return 0;
830
    }
831

    
832
    if (ts_st->payload_index + size > DEFAULT_PES_PAYLOAD_SIZE) {
833
        mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
834
                         ts_st->payload_pts, ts_st->payload_dts);
835
        ts_st->payload_index = 0;
836
    }
837

    
838
    if (!ts_st->payload_index) {
839
        ts_st->payload_pts = pts;
840
        ts_st->payload_dts = dts;
841
    }
842

    
843
    memcpy(ts_st->payload + ts_st->payload_index, buf, size);
844
    ts_st->payload_index += size;
845

    
846
    return 0;
847
}
848

    
849
static int mpegts_write_end(AVFormatContext *s)
850
{
851
    MpegTSWrite *ts = s->priv_data;
852
    MpegTSWriteStream *ts_st;
853
    MpegTSService *service;
854
    AVStream *st;
855
    int i;
856

    
857
    /* flush current packets */
858
    for(i = 0; i < s->nb_streams; i++) {
859
        st = s->streams[i];
860
        ts_st = st->priv_data;
861
        if (ts_st->payload_index > 0) {
862
            mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
863
                             ts_st->payload_pts, ts_st->payload_dts);
864
        }
865
    }
866
    put_flush_packet(s->pb);
867

    
868
    for(i = 0; i < ts->nb_services; i++) {
869
        service = ts->services[i];
870
        av_freep(&service->provider_name);
871
        av_freep(&service->name);
872
        av_free(service);
873
    }
874
    av_free(ts->services);
875

    
876
    return 0;
877
}
878

    
879
AVOutputFormat mpegts_muxer = {
880
    "mpegts",
881
    NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
882
    "video/x-mpegts",
883
    "ts,m2t",
884
    sizeof(MpegTSWrite),
885
    CODEC_ID_MP2,
886
    CODEC_ID_MPEG2VIDEO,
887
    mpegts_write_header,
888
    mpegts_write_packet,
889
    mpegts_write_end,
890
};