Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegtsenc.c @ 4b358c3e

History | View | Annotate | Download (25.3 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_freq;
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_freq;
56
    int pat_packet_count;
57
    int pat_packet_freq;
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
        *q++ = 0x10 | s->cc;
93
        s->cc = (s->cc + 1) & 0xf;
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
    int64_t payload_pts;
177
    int64_t payload_dts;
178
    uint8_t payload[DEFAULT_PES_PAYLOAD_SIZE];
179
} MpegTSWriteStream;
180

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

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

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

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

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

    
210
    /* put program info here */
211

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
400
    ts->pat.pid = PAT_PID;
401
    ts->pat.cc = 0;
402
    ts->pat.write_packet = section_write_packet;
403
    ts->pat.opaque = s;
404

    
405
    ts->sdt.pid = SDT_PID;
406
    ts->sdt.cc = 0;
407
    ts->sdt.write_packet = section_write_packet;
408
    ts->sdt.opaque = s;
409

    
410
    /* assign pids to each stream */
411
    total_bit_rate = 0;
412
    for(i = 0;i < s->nb_streams; i++) {
413
        st = s->streams[i];
414
        ts_st = av_mallocz(sizeof(MpegTSWriteStream));
415
        if (!ts_st)
416
            goto fail;
417
        st->priv_data = ts_st;
418
        ts_st->service = service;
419
        ts_st->pid = DEFAULT_START_PID + i;
420
        ts_st->payload_pts = AV_NOPTS_VALUE;
421
        ts_st->payload_dts = AV_NOPTS_VALUE;
422
        /* update PCR pid by using the first video stream */
423
        if (st->codec->codec_type == CODEC_TYPE_VIDEO &&
424
            service->pcr_pid == 0x1fff)
425
            service->pcr_pid = ts_st->pid;
426
        total_bit_rate += st->codec->bit_rate;
427
    }
428

    
429
    /* if no video stream, use the first stream as PCR */
430
    if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
431
        ts_st = s->streams[0]->priv_data;
432
        service->pcr_pid = ts_st->pid;
433
    }
434

    
435
    if (total_bit_rate <= 8 * 1024)
436
        total_bit_rate = 8 * 1024;
437
    service->pcr_packet_freq = (total_bit_rate * PCR_RETRANS_TIME) /
438
        (TS_PACKET_SIZE * 8 * 1000);
439
    ts->sdt_packet_freq = (total_bit_rate * SDT_RETRANS_TIME) /
440
        (TS_PACKET_SIZE * 8 * 1000);
441
    ts->pat_packet_freq = (total_bit_rate * PAT_RETRANS_TIME) /
442
        (TS_PACKET_SIZE * 8 * 1000);
443

    
444
    ts->mux_rate = 1; // avoid div by 0
445

    
446
    /* write info at the start of the file, so that it will be fast to
447
       find them */
448
    pos = url_ftell(s->pb);
449
    mpegts_write_sdt(s);
450
    sdt_size = url_ftell(s->pb) - pos;
451
    pos = url_ftell(s->pb);
452
    mpegts_write_pat(s);
453
    for(i = 0; i < ts->nb_services; i++) {
454
        mpegts_write_pmt(s, ts->services[i]);
455
    }
456
    pat_pmt_size = url_ftell(s->pb) - pos;
457

    
458
    total_bit_rate +=
459
        total_bit_rate * 25 / (8 * DEFAULT_PES_PAYLOAD_SIZE) + /* PES header size */
460
        total_bit_rate * 4 / (8 * TS_PACKET_SIZE) +            /* TS  header size */
461
        SDT_RETRANS_TIME * sdt_size +                          /* SDT size */
462
        PAT_RETRANS_TIME * pat_pmt_size +                      /* PAT+PMT size */
463
        PCR_RETRANS_TIME * 8;                                  /* PCR size */
464

    
465
    av_log(s, AV_LOG_DEBUG, "muxrate %d freq sdt %d pat %d\n",
466
           total_bit_rate, ts->sdt_packet_freq, ts->pat_packet_freq);
467

    
468
    if (s->mux_rate)
469
        ts->mux_rate = s->mux_rate;
470
    else
471
        ts->mux_rate = total_bit_rate;
472

    
473
    // adjust pcr
474
    ts->cur_pcr /= ts->mux_rate;
475

    
476
    put_flush_packet(s->pb);
477

    
478
    return 0;
479

    
480
 fail:
481
    for(i = 0;i < s->nb_streams; i++) {
482
        st = s->streams[i];
483
        av_free(st->priv_data);
484
    }
485
    return -1;
486
}
487

    
488
/* send SDT, PAT and PMT tables regulary */
489
static void retransmit_si_info(AVFormatContext *s)
490
{
491
    MpegTSWrite *ts = s->priv_data;
492
    int i;
493

    
494
    if (++ts->sdt_packet_count == ts->sdt_packet_freq) {
495
        ts->sdt_packet_count = 0;
496
        mpegts_write_sdt(s);
497
    }
498
    if (++ts->pat_packet_count == ts->pat_packet_freq) {
499
        ts->pat_packet_count = 0;
500
        mpegts_write_pat(s);
501
        for(i = 0; i < ts->nb_services; i++) {
502
            mpegts_write_pmt(s, ts->services[i]);
503
        }
504
    }
505
}
506

    
507
static void write_pts(uint8_t *q, int fourbits, int64_t pts)
508
{
509
    int val;
510

    
511
    val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
512
    *q++ = val;
513
    val = (((pts >> 15) & 0x7fff) << 1) | 1;
514
    *q++ = val >> 8;
515
    *q++ = val;
516
    val = (((pts) & 0x7fff) << 1) | 1;
517
    *q++ = val >> 8;
518
    *q++ = val;
519
}
520

    
521
/* NOTE: pes_data contains all the PES packet */
522
static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
523
                             const uint8_t *payload, int payload_size,
524
                             int64_t pts, int64_t dts)
525
{
526
    MpegTSWriteStream *ts_st = st->priv_data;
527
    MpegTSWrite *ts = s->priv_data;
528
    uint8_t buf[TS_PACKET_SIZE];
529
    uint8_t *q;
530
    int val, is_start, len, header_len, write_pcr, private_code, flags;
531
    int afc_len, stuffing_len;
532
    int64_t pcr = -1; /* avoid warning */
533

    
534
    is_start = 1;
535
    while (payload_size > 0) {
536
        retransmit_si_info(s);
537

    
538
        write_pcr = 0;
539
        if (ts_st->pid == ts_st->service->pcr_pid) {
540
            ts_st->service->pcr_packet_count++;
541
            if (ts_st->service->pcr_packet_count >=
542
                ts_st->service->pcr_packet_freq) {
543
                ts_st->service->pcr_packet_count = 0;
544
                write_pcr = 1;
545
            }
546
        }
547

    
548
        /* prepare packet header */
549
        q = buf;
550
        *q++ = 0x47;
551
        val = (ts_st->pid >> 8);
552
        if (is_start)
553
            val |= 0x40;
554
        *q++ = val;
555
        *q++ = ts_st->pid;
556
        *q++ = 0x10 | ts_st->cc | (write_pcr ? 0x20 : 0);
557
        ts_st->cc = (ts_st->cc + 1) & 0xf;
558
        if (write_pcr) {
559
            // add 11, pcr references the last byte of program clock reference base
560
            pcr = ts->cur_pcr + (4+7)*8*90000LL / ts->mux_rate;
561
            if (dts != AV_NOPTS_VALUE && dts < pcr)
562
                av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
563
            *q++ = 7; /* AFC length */
564
            *q++ = 0x10; /* flags: PCR present */
565
            *q++ = pcr >> 25;
566
            *q++ = pcr >> 17;
567
            *q++ = pcr >> 9;
568
            *q++ = pcr >> 1;
569
            *q++ = (pcr & 1) << 7;
570
            *q++ = 0;
571
        }
572
        if (is_start) {
573
            int pes_extension = 0;
574
            /* write PES header */
575
            *q++ = 0x00;
576
            *q++ = 0x00;
577
            *q++ = 0x01;
578
            private_code = 0;
579
            if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
580
                if (st->codec->codec_id == CODEC_ID_DIRAC) {
581
                    *q++ = 0xfd;
582
                } else
583
                    *q++ = 0xe0;
584
            } else if (st->codec->codec_type == CODEC_TYPE_AUDIO &&
585
                       (st->codec->codec_id == CODEC_ID_MP2 ||
586
                        st->codec->codec_id == CODEC_ID_MP3)) {
587
                *q++ = 0xc0;
588
            } else {
589
                *q++ = 0xbd;
590
                if (st->codec->codec_type == CODEC_TYPE_SUBTITLE) {
591
                    private_code = 0x20;
592
                }
593
            }
594
            header_len = 0;
595
            flags = 0;
596
            if (pts != AV_NOPTS_VALUE) {
597
                header_len += 5;
598
                flags |= 0x80;
599
            }
600
            if (dts != AV_NOPTS_VALUE && dts != pts) {
601
                header_len += 5;
602
                flags |= 0x40;
603
            }
604
            if (st->codec->codec_type == CODEC_TYPE_VIDEO &&
605
                st->codec->codec_id == CODEC_ID_DIRAC) {
606
                /* set PES_extension_flag */
607
                pes_extension = 1;
608
                flags |= 0x01;
609

    
610
                /*
611
                * One byte for PES2 extension flag +
612
                * one byte for extension length +
613
                * one byte for extension id
614
                */
615
                header_len += 3;
616
            }
617
            len = payload_size + header_len + 3;
618
            if (private_code != 0)
619
                len++;
620
            *q++ = len >> 8;
621
            *q++ = len;
622
            val = 0x80;
623
            /* data alignment indicator is required for subtitle data */
624
            if (st->codec->codec_type == CODEC_TYPE_SUBTITLE)
625
                val |= 0x04;
626
            *q++ = val;
627
            *q++ = flags;
628
            *q++ = header_len;
629
            if (pts != AV_NOPTS_VALUE) {
630
                write_pts(q, flags >> 6, pts);
631
                q += 5;
632
            }
633
            if (dts != AV_NOPTS_VALUE && dts != pts) {
634
                write_pts(q, 1, dts);
635
                q += 5;
636
            }
637
            if (pes_extension && st->codec->codec_id == CODEC_ID_DIRAC) {
638
                flags = 0x01;  /* set PES_extension_flag_2 */
639
                *q++ = flags;
640
                *q++ = 0x80 | 0x01;  /* marker bit + extension length */
641
                /*
642
                * Set the stream id extension flag bit to 0 and
643
                * write the extended stream id
644
                */
645
                *q++ = 0x00 | 0x60;
646
            }
647
            if (private_code != 0)
648
                *q++ = private_code;
649
            is_start = 0;
650
        }
651
        /* header size */
652
        header_len = q - buf;
653
        /* data len */
654
        len = TS_PACKET_SIZE - header_len;
655
        if (len > payload_size)
656
            len = payload_size;
657
        stuffing_len = TS_PACKET_SIZE - header_len - len;
658
        if (stuffing_len > 0) {
659
            /* add stuffing with AFC */
660
            if (buf[3] & 0x20) {
661
                /* stuffing already present: increase its size */
662
                afc_len = buf[4] + 1;
663
                memmove(buf + 4 + afc_len + stuffing_len,
664
                        buf + 4 + afc_len,
665
                        header_len - (4 + afc_len));
666
                buf[4] += stuffing_len;
667
                memset(buf + 4 + afc_len, 0xff, stuffing_len);
668
            } else {
669
                /* add stuffing */
670
                memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
671
                buf[3] |= 0x20;
672
                buf[4] = stuffing_len - 1;
673
                if (stuffing_len >= 2) {
674
                    buf[5] = 0x00;
675
                    memset(buf + 6, 0xff, stuffing_len - 2);
676
                }
677
            }
678
        }
679
        memcpy(buf + TS_PACKET_SIZE - len, payload, len);
680
        payload += len;
681
        payload_size -= len;
682
        put_buffer(s->pb, buf, TS_PACKET_SIZE);
683
        ts->cur_pcr += TS_PACKET_SIZE*8*90000LL/ts->mux_rate;
684
    }
685
    put_flush_packet(s->pb);
686
}
687

    
688
static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
689
{
690
    AVStream *st = s->streams[pkt->stream_index];
691
    int size= pkt->size;
692
    uint8_t *buf= pkt->data;
693
    uint8_t *data= NULL;
694
    MpegTSWriteStream *ts_st = st->priv_data;
695
    int len, max_payload_size;
696
    const uint8_t *access_unit_index = NULL;
697
    const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
698
    int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
699

    
700
    if (pkt->pts != AV_NOPTS_VALUE)
701
        pts = pkt->pts + delay;
702
    if (pkt->dts != AV_NOPTS_VALUE)
703
        dts = pkt->dts + delay;
704

    
705
    if (st->codec->codec_type == CODEC_TYPE_SUBTITLE) {
706
        /* for subtitle, a single PES packet must be generated */
707
        mpegts_write_pes(s, st, buf, size, pts, AV_NOPTS_VALUE);
708
        return 0;
709
    }
710

    
711
    if (st->codec->codec_id == CODEC_ID_DIRAC) {
712
        /* for Dirac, a single PES packet must be generated */
713
        mpegts_write_pes(s, st, buf, size, pts, dts);
714
        return 0;
715
    }
716
    max_payload_size = DEFAULT_PES_PAYLOAD_SIZE;
717
    if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO ||
718
        st->codec->codec_id == CODEC_ID_MPEG1VIDEO) {
719
        const uint8_t *p = pkt->data;
720
        const uint8_t *end = pkt->data+pkt->size;
721
        uint32_t state = -1;
722
        while (p < end) {
723
            p = ff_find_start_code(p, end, &state);
724
            if (state == PICTURE_START_CODE) {
725
                access_unit_index = p - 4;
726
                break;
727
            }
728
        }
729
    } if (st->codec->codec_id == CODEC_ID_H264) {
730
        if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
731
            av_log(s, AV_LOG_ERROR, "h264 bitstream malformated\n");
732
            return -1;
733
        }
734
        if (pkt->data[4] != 0x09) { // AUD NAL
735
            data = av_malloc(pkt->size+6);
736
            if (!data)
737
                return -1;
738
            memcpy(data+6, pkt->data, pkt->size);
739
            AV_WB32(data, 0x00000001);
740
            data[4] = 0x09;
741
            data[5] = 0xe0; // any slice type
742
            buf  = data;
743
            size = pkt->size+6;
744
        }
745
        access_unit_index = buf;
746
    } else {
747
        access_unit_index = pkt->data;
748
    }
749

    
750
    if (!access_unit_index) {
751
        av_log(s, AV_LOG_ERROR, "error, could not find access unit start\n");
752
        return -1;
753
    }
754

    
755
    while (size > 0) {
756
        len = max_payload_size - ts_st->payload_index;
757
        if (len > size)
758
            len = size;
759
        memcpy(ts_st->payload + ts_st->payload_index, buf, len);
760
        buf += len;
761
        size -= len;
762
        ts_st->payload_index += len;
763
        if (access_unit_index && access_unit_index < buf &&
764
            ts_st->payload_pts == AV_NOPTS_VALUE &&
765
            ts_st->payload_dts == AV_NOPTS_VALUE) {
766
            ts_st->payload_dts = dts;
767
            ts_st->payload_pts = pts;
768
        }
769
        if (ts_st->payload_index >= max_payload_size) {
770
            mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
771
                             ts_st->payload_pts, ts_st->payload_dts);
772
            ts_st->payload_pts = AV_NOPTS_VALUE;
773
            ts_st->payload_dts = AV_NOPTS_VALUE;
774
            ts_st->payload_index = 0;
775
            access_unit_index = NULL; // unset access unit to avoid setting pts/dts again
776
        }
777
    }
778

    
779
    av_free(data);
780

    
781
    return 0;
782
}
783

    
784
static int mpegts_write_end(AVFormatContext *s)
785
{
786
    MpegTSWrite *ts = s->priv_data;
787
    MpegTSWriteStream *ts_st;
788
    MpegTSService *service;
789
    AVStream *st;
790
    int i;
791

    
792
    /* flush current packets */
793
    for(i = 0; i < s->nb_streams; i++) {
794
        st = s->streams[i];
795
        ts_st = st->priv_data;
796
        if (ts_st->payload_index > 0) {
797
            mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
798
                             ts_st->payload_pts, ts_st->payload_dts);
799
        }
800
    }
801
    put_flush_packet(s->pb);
802

    
803
    for(i = 0; i < ts->nb_services; i++) {
804
        service = ts->services[i];
805
        av_freep(&service->provider_name);
806
        av_freep(&service->name);
807
        av_free(service);
808
    }
809
    av_free(ts->services);
810

    
811
    return 0;
812
}
813

    
814
AVOutputFormat mpegts_muxer = {
815
    "mpegts",
816
    NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
817
    "video/x-mpegts",
818
    "ts,m2t",
819
    sizeof(MpegTSWrite),
820
    CODEC_ID_MP2,
821
    CODEC_ID_MPEG2VIDEO,
822
    mpegts_write_header,
823
    mpegts_write_packet,
824
    mpegts_write_end,
825
};