Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegtsenc.c @ 99ed41a8

History | View | Annotate | Download (25.2 KB)

1 5dbafeb7 Fabrice Bellard
/*
2 7fbde343 Aurelien Jacobs
 * MPEG2 transport stream (aka DVB) muxer
3 406792e7 Diego Biurrun
 * Copyright (c) 2003 Fabrice Bellard
4 5dbafeb7 Fabrice Bellard
 *
5 b78e7197 Diego Biurrun
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8 5dbafeb7 Fabrice Bellard
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10 b78e7197 Diego Biurrun
 * version 2.1 of the License, or (at your option) any later version.
11 5dbafeb7 Fabrice Bellard
 *
12 b78e7197 Diego Biurrun
 * FFmpeg is distributed in the hope that it will be useful,
13 5dbafeb7 Fabrice Bellard
 * 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 b78e7197 Diego Biurrun
 * License along with FFmpeg; if not, write to the Free Software
19 5509bffa Diego Biurrun
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 5dbafeb7 Fabrice Bellard
 */
21 245976da Diego Biurrun
22 6a5d31ac Diego Biurrun
#include "libavutil/bswap.h"
23 245976da Diego Biurrun
#include "libavutil/crc.h"
24 de34dc39 Baptiste Coudurier
#include "libavcodec/mpegvideo.h"
25 5dbafeb7 Fabrice Bellard
#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 b5931348 Baptiste Coudurier
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 5dbafeb7 Fabrice Bellard
/* NOTE: 4 bytes must be left at the end for the crc32 */
66 7b49ce2e Stefan Huehner
static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
67 5dbafeb7 Fabrice Bellard
{
68 b5931348 Baptiste Coudurier
    MpegTSWrite *ts = ((AVFormatContext*)s->opaque)->priv_data;
69 5dbafeb7 Fabrice Bellard
    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 3abe5fbd Aurelien Jacobs
    crc = bswap_32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
76 5dbafeb7 Fabrice Bellard
    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 115329f1 Diego Biurrun
81 5dbafeb7 Fabrice Bellard
    /* 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 3654a16d Baptiste Coudurier
        s->cc = (s->cc + 1) & 0xf;
94 5dbafeb7 Fabrice Bellard
        if (first)
95
            *q++ = 0; /* 0 offset */
96
        len1 = TS_PACKET_SIZE - (q - packet);
97 115329f1 Diego Biurrun
        if (len1 > len)
98 5dbafeb7 Fabrice Bellard
            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 b5931348 Baptiste Coudurier
111
        ts->cur_pcr += TS_PACKET_SIZE*8*90000LL/ts->mux_rate;
112 5dbafeb7 Fabrice Bellard
    }
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 7b49ce2e Stefan Huehner
static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
125 5dbafeb7 Fabrice Bellard
                          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 115329f1 Diego Biurrun
131 5dbafeb7 Fabrice Bellard
    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 115329f1 Diego Biurrun
145 5dbafeb7 Fabrice Bellard
    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 69ef9450 Fabrice Bellard
#define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
165 5dbafeb7 Fabrice Bellard
166
/* we retransmit the SI info at this rate */
167
#define SDT_RETRANS_TIME 500
168
#define PAT_RETRANS_TIME 100
169 8b475508 Fabrice Bellard
#define PCR_RETRANS_TIME 20
170 5dbafeb7 Fabrice Bellard
171
typedef struct MpegTSWriteStream {
172 8b475508 Fabrice Bellard
    struct MpegTSService *service;
173 5dbafeb7 Fabrice Bellard
    int pid; /* stream associated pid */
174
    int cc;
175 69ef9450 Fabrice Bellard
    int payload_index;
176
    int64_t payload_pts;
177 700b9711 Måns Rullgård
    int64_t payload_dts;
178 69ef9450 Fabrice Bellard
    uint8_t payload[DEFAULT_PES_PAYLOAD_SIZE];
179 5dbafeb7 Fabrice Bellard
} 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 115329f1 Diego Biurrun
188 5dbafeb7 Fabrice Bellard
    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 115329f1 Diego Biurrun
216 5dbafeb7 Fabrice Bellard
    for(i = 0; i < s->nb_streams; i++) {
217
        AVStream *st = s->streams[i];
218
        MpegTSWriteStream *ts_st = st->priv_data;
219 01f4895c Michael Niedermayer
        switch(st->codec->codec_id) {
220 278de475 Måns Rullgård
        case CODEC_ID_MPEG1VIDEO:
221
        case CODEC_ID_MPEG2VIDEO:
222
            stream_type = STREAM_TYPE_VIDEO_MPEG2;
223 5dbafeb7 Fabrice Bellard
            break;
224 278de475 Måns Rullgård
        case CODEC_ID_MPEG4:
225
            stream_type = STREAM_TYPE_VIDEO_MPEG4;
226
            break;
227
        case CODEC_ID_H264:
228
            stream_type = STREAM_TYPE_VIDEO_H264;
229
            break;
230 f4bba201 Anuradha Suraparaju
        case CODEC_ID_DIRAC:
231
            stream_type = STREAM_TYPE_VIDEO_DIRAC;
232
            break;
233 278de475 Måns Rullgård
        case CODEC_ID_MP2:
234
        case CODEC_ID_MP3:
235 ce34182d Michael Niedermayer
            stream_type = STREAM_TYPE_AUDIO_MPEG1;
236 5dbafeb7 Fabrice Bellard
            break;
237 278de475 Måns Rullgård
        case CODEC_ID_AAC:
238
            stream_type = STREAM_TYPE_AUDIO_AAC;
239
            break;
240
        case CODEC_ID_AC3:
241
            stream_type = STREAM_TYPE_AUDIO_AC3;
242
            break;
243 5dbafeb7 Fabrice Bellard
        default:
244
            stream_type = STREAM_TYPE_PRIVATE_DATA;
245
            break;
246
        }
247
        *q++ = stream_type;
248
        put16(&q, 0xe000 | ts_st->pid);
249
        desc_length_ptr = q;
250
        q += 2; /* patched after */
251
252
        /* write optional descriptors here */
253 01f4895c Michael Niedermayer
        switch(st->codec->codec_type) {
254 8b475508 Fabrice Bellard
        case CODEC_TYPE_AUDIO:
255
            if (strlen(st->language) == 3) {
256
                *q++ = 0x0a; /* ISO 639 language descriptor */
257
                *q++ = 4;
258
                *q++ = st->language[0];
259
                *q++ = st->language[1];
260
                *q++ = st->language[2];
261
                *q++ = 0; /* undefined type */
262
            }
263
            break;
264
        case CODEC_TYPE_SUBTITLE:
265
            {
266
                const char *language;
267
                language = st->language;
268
                if (strlen(language) != 3)
269
                    language = "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 f4bba201 Anuradha Suraparaju
        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 8b475508 Fabrice Bellard
        }
291 5dbafeb7 Fabrice Bellard
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 115329f1 Diego Biurrun
}
299 5dbafeb7 Fabrice Bellard
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 115329f1 Diego Biurrun
324 5dbafeb7 Fabrice Bellard
    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 115329f1 Diego Biurrun
        val = (running_status << 13) | (free_ca_mode << 12) |
347 5dbafeb7 Fabrice Bellard
            (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 115329f1 Diego Biurrun
static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
356
                                         int sid,
357
                                         const char *provider_name,
358 5dbafeb7 Fabrice Bellard
                                         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 899681cd Björn Axelsson
    put_buffer(ctx->pb, packet, TS_PACKET_SIZE);
378 5dbafeb7 Fabrice Bellard
}
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
    int i, total_bit_rate;
387 8b475508 Fabrice Bellard
    const char *service_name;
388 3d0a94f6 Baptiste Coudurier
    uint64_t sdt_size, pat_pmt_size, pos;
389 115329f1 Diego Biurrun
390 5dbafeb7 Fabrice Bellard
    ts->tsid = DEFAULT_TSID;
391
    ts->onid = DEFAULT_ONID;
392
    /* allocate a single DVB service */
393 8b475508 Fabrice Bellard
    service_name = s->title;
394
    if (service_name[0] == '\0')
395
        service_name = DEFAULT_SERVICE_NAME;
396 115329f1 Diego Biurrun
    service = mpegts_add_service(ts, DEFAULT_SID,
397 8b475508 Fabrice Bellard
                                 DEFAULT_PROVIDER_NAME, service_name);
398 5dbafeb7 Fabrice Bellard
    service->pmt.write_packet = section_write_packet;
399
    service->pmt.opaque = s;
400
401
    ts->pat.pid = PAT_PID;
402
    ts->pat.cc = 0;
403
    ts->pat.write_packet = section_write_packet;
404
    ts->pat.opaque = s;
405
406
    ts->sdt.pid = SDT_PID;
407
    ts->sdt.cc = 0;
408
    ts->sdt.write_packet = section_write_packet;
409
    ts->sdt.opaque = s;
410
411
    /* assign pids to each stream */
412
    total_bit_rate = 0;
413
    for(i = 0;i < s->nb_streams; i++) {
414
        st = s->streams[i];
415
        ts_st = av_mallocz(sizeof(MpegTSWriteStream));
416
        if (!ts_st)
417
            goto fail;
418
        st->priv_data = ts_st;
419 8b475508 Fabrice Bellard
        ts_st->service = service;
420 5dbafeb7 Fabrice Bellard
        ts_st->pid = DEFAULT_START_PID + i;
421 69ef9450 Fabrice Bellard
        ts_st->payload_pts = AV_NOPTS_VALUE;
422 700b9711 Måns Rullgård
        ts_st->payload_dts = AV_NOPTS_VALUE;
423 8b475508 Fabrice Bellard
        /* update PCR pid by using the first video stream */
424 115329f1 Diego Biurrun
        if (st->codec->codec_type == CODEC_TYPE_VIDEO &&
425 5dbafeb7 Fabrice Bellard
            service->pcr_pid == 0x1fff)
426
            service->pcr_pid = ts_st->pid;
427 01f4895c Michael Niedermayer
        total_bit_rate += st->codec->bit_rate;
428 5dbafeb7 Fabrice Bellard
    }
429 115329f1 Diego Biurrun
430 8b475508 Fabrice Bellard
    /* if no video stream, use the first stream as PCR */
431
    if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
432
        ts_st = s->streams[0]->priv_data;
433
        service->pcr_pid = ts_st->pid;
434
    }
435
436 5dbafeb7 Fabrice Bellard
    if (total_bit_rate <= 8 * 1024)
437
        total_bit_rate = 8 * 1024;
438 115329f1 Diego Biurrun
    service->pcr_packet_freq = (total_bit_rate * PCR_RETRANS_TIME) /
439 8b475508 Fabrice Bellard
        (TS_PACKET_SIZE * 8 * 1000);
440 115329f1 Diego Biurrun
    ts->sdt_packet_freq = (total_bit_rate * SDT_RETRANS_TIME) /
441 5dbafeb7 Fabrice Bellard
        (TS_PACKET_SIZE * 8 * 1000);
442 115329f1 Diego Biurrun
    ts->pat_packet_freq = (total_bit_rate * PAT_RETRANS_TIME) /
443 5dbafeb7 Fabrice Bellard
        (TS_PACKET_SIZE * 8 * 1000);
444
445 3d0a94f6 Baptiste Coudurier
    ts->mux_rate = 1; // avoid div by 0
446 b5931348 Baptiste Coudurier
447 5dbafeb7 Fabrice Bellard
    /* write info at the start of the file, so that it will be fast to
448
       find them */
449 3d0a94f6 Baptiste Coudurier
    pos = url_ftell(s->pb);
450 5dbafeb7 Fabrice Bellard
    mpegts_write_sdt(s);
451 3d0a94f6 Baptiste Coudurier
    sdt_size = url_ftell(s->pb) - pos;
452
    pos = url_ftell(s->pb);
453 5dbafeb7 Fabrice Bellard
    mpegts_write_pat(s);
454
    for(i = 0; i < ts->nb_services; i++) {
455
        mpegts_write_pmt(s, ts->services[i]);
456
    }
457 3d0a94f6 Baptiste Coudurier
    pat_pmt_size = url_ftell(s->pb) - pos;
458
459
    total_bit_rate +=
460
        total_bit_rate * 25 / (8 * DEFAULT_PES_PAYLOAD_SIZE) + /* PES header size */
461
        total_bit_rate * 4 / (8 * TS_PACKET_SIZE) +            /* TS  header size */
462
        SDT_RETRANS_TIME * sdt_size +                          /* SDT size */
463
        PAT_RETRANS_TIME * pat_pmt_size +                      /* PAT+PMT size */
464
        PCR_RETRANS_TIME * 8;                                  /* PCR size */
465
466
    av_log(s, AV_LOG_DEBUG, "muxrate %d freq sdt %d pat %d\n",
467
           total_bit_rate, ts->sdt_packet_freq, ts->pat_packet_freq);
468
469
    if (s->mux_rate)
470
        ts->mux_rate = s->mux_rate;
471
    else
472
        ts->mux_rate = total_bit_rate;
473
474
    // adjust pcr
475
    ts->cur_pcr /= ts->mux_rate;
476
477 899681cd Björn Axelsson
    put_flush_packet(s->pb);
478 5dbafeb7 Fabrice Bellard
479
    return 0;
480
481
 fail:
482
    for(i = 0;i < s->nb_streams; i++) {
483
        st = s->streams[i];
484
        av_free(st->priv_data);
485
    }
486
    return -1;
487
}
488
489
/* send SDT, PAT and PMT tables regulary */
490
static void retransmit_si_info(AVFormatContext *s)
491
{
492
    MpegTSWrite *ts = s->priv_data;
493
    int i;
494
495
    if (++ts->sdt_packet_count == ts->sdt_packet_freq) {
496
        ts->sdt_packet_count = 0;
497
        mpegts_write_sdt(s);
498
    }
499
    if (++ts->pat_packet_count == ts->pat_packet_freq) {
500
        ts->pat_packet_count = 0;
501
        mpegts_write_pat(s);
502
        for(i = 0; i < ts->nb_services; i++) {
503
            mpegts_write_pmt(s, ts->services[i]);
504
        }
505
    }
506
}
507
508 700b9711 Måns Rullgård
static void write_pts(uint8_t *q, int fourbits, int64_t pts)
509
{
510
    int val;
511
512
    val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
513
    *q++ = val;
514
    val = (((pts >> 15) & 0x7fff) << 1) | 1;
515
    *q++ = val >> 8;
516
    *q++ = val;
517
    val = (((pts) & 0x7fff) << 1) | 1;
518
    *q++ = val >> 8;
519
    *q++ = val;
520
}
521
522 69ef9450 Fabrice Bellard
/* NOTE: pes_data contains all the PES packet */
523
static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
524
                             const uint8_t *payload, int payload_size,
525 700b9711 Måns Rullgård
                             int64_t pts, int64_t dts)
526 5dbafeb7 Fabrice Bellard
{
527
    MpegTSWriteStream *ts_st = st->priv_data;
528 b5931348 Baptiste Coudurier
    MpegTSWrite *ts = s->priv_data;
529 69ef9450 Fabrice Bellard
    uint8_t buf[TS_PACKET_SIZE];
530 5dbafeb7 Fabrice Bellard
    uint8_t *q;
531 700b9711 Måns Rullgård
    int val, is_start, len, header_len, write_pcr, private_code, flags;
532 8b475508 Fabrice Bellard
    int afc_len, stuffing_len;
533
    int64_t pcr = -1; /* avoid warning */
534 5dbafeb7 Fabrice Bellard
535 69ef9450 Fabrice Bellard
    is_start = 1;
536
    while (payload_size > 0) {
537
        retransmit_si_info(s);
538 5dbafeb7 Fabrice Bellard
539 8b475508 Fabrice Bellard
        write_pcr = 0;
540
        if (ts_st->pid == ts_st->service->pcr_pid) {
541
            ts_st->service->pcr_packet_count++;
542 115329f1 Diego Biurrun
            if (ts_st->service->pcr_packet_count >=
543 8b475508 Fabrice Bellard
                ts_st->service->pcr_packet_freq) {
544
                ts_st->service->pcr_packet_count = 0;
545
                write_pcr = 1;
546
            }
547
        }
548
549 69ef9450 Fabrice Bellard
        /* prepare packet header */
550
        q = buf;
551
        *q++ = 0x47;
552
        val = (ts_st->pid >> 8);
553
        if (is_start)
554
            val |= 0x40;
555
        *q++ = val;
556
        *q++ = ts_st->pid;
557 8b475508 Fabrice Bellard
        *q++ = 0x10 | ts_st->cc | (write_pcr ? 0x20 : 0);
558 69ef9450 Fabrice Bellard
        ts_st->cc = (ts_st->cc + 1) & 0xf;
559 8b475508 Fabrice Bellard
        if (write_pcr) {
560 b5931348 Baptiste Coudurier
            // add 11, pcr references the last byte of program clock reference base
561
            pcr = ts->cur_pcr + (4+7)*8*90000LL / ts->mux_rate;
562 811a0aa7 Baptiste Coudurier
            if (dts != AV_NOPTS_VALUE && dts < pcr)
563
                av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
564 8b475508 Fabrice Bellard
            *q++ = 7; /* AFC length */
565
            *q++ = 0x10; /* flags: PCR present */
566
            *q++ = pcr >> 25;
567
            *q++ = pcr >> 17;
568
            *q++ = pcr >> 9;
569
            *q++ = pcr >> 1;
570
            *q++ = (pcr & 1) << 7;
571
            *q++ = 0;
572
        }
573 69ef9450 Fabrice Bellard
        if (is_start) {
574 f4bba201 Anuradha Suraparaju
            int pes_extension = 0;
575 69ef9450 Fabrice Bellard
            /* write PES header */
576
            *q++ = 0x00;
577
            *q++ = 0x00;
578
            *q++ = 0x01;
579 8b475508 Fabrice Bellard
            private_code = 0;
580 01f4895c Michael Niedermayer
            if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
581 f4bba201 Anuradha Suraparaju
                if (st->codec->codec_id == CODEC_ID_DIRAC) {
582
                    *q++ = 0xfd;
583
                } else
584
                    *q++ = 0xe0;
585 01f4895c Michael Niedermayer
            } else if (st->codec->codec_type == CODEC_TYPE_AUDIO &&
586
                       (st->codec->codec_id == CODEC_ID_MP2 ||
587
                        st->codec->codec_id == CODEC_ID_MP3)) {
588 115329f1 Diego Biurrun
                *q++ = 0xc0;
589 8b475508 Fabrice Bellard
            } else {
590
                *q++ = 0xbd;
591 01f4895c Michael Niedermayer
                if (st->codec->codec_type == CODEC_TYPE_SUBTITLE) {
592 8b475508 Fabrice Bellard
                    private_code = 0x20;
593
                }
594
            }
595 700b9711 Måns Rullgård
            header_len = 0;
596
            flags = 0;
597
            if (pts != AV_NOPTS_VALUE) {
598
                header_len += 5;
599
                flags |= 0x80;
600
            }
601 5541759f Baptiste Coudurier
            if (dts != AV_NOPTS_VALUE && dts != pts) {
602 700b9711 Måns Rullgård
                header_len += 5;
603
                flags |= 0x40;
604
            }
605 f4bba201 Anuradha Suraparaju
            if (st->codec->codec_type == CODEC_TYPE_VIDEO &&
606
                st->codec->codec_id == CODEC_ID_DIRAC) {
607
                /* set PES_extension_flag */
608
                pes_extension = 1;
609
                flags |= 0x01;
610
611
                /*
612
                * One byte for PES2 extension flag +
613
                * one byte for extension length +
614
                * one byte for extension id
615
                */
616
                header_len += 3;
617
            }
618 700b9711 Måns Rullgård
            len = payload_size + header_len + 3;
619 8b475508 Fabrice Bellard
            if (private_code != 0)
620 700b9711 Måns Rullgård
                len++;
621 69ef9450 Fabrice Bellard
            *q++ = len >> 8;
622
            *q++ = len;
623 8b475508 Fabrice Bellard
            val = 0x80;
624
            /* data alignment indicator is required for subtitle data */
625 01f4895c Michael Niedermayer
            if (st->codec->codec_type == CODEC_TYPE_SUBTITLE)
626 8b475508 Fabrice Bellard
                val |= 0x04;
627
            *q++ = val;
628 700b9711 Måns Rullgård
            *q++ = flags;
629
            *q++ = header_len;
630 69ef9450 Fabrice Bellard
            if (pts != AV_NOPTS_VALUE) {
631 700b9711 Måns Rullgård
                write_pts(q, flags >> 6, pts);
632
                q += 5;
633
            }
634 5541759f Baptiste Coudurier
            if (dts != AV_NOPTS_VALUE && dts != pts) {
635 700b9711 Måns Rullgård
                write_pts(q, 1, dts);
636
                q += 5;
637 5dbafeb7 Fabrice Bellard
            }
638 f4bba201 Anuradha Suraparaju
            if (pes_extension && st->codec->codec_id == CODEC_ID_DIRAC) {
639
                flags = 0x01;  /* set PES_extension_flag_2 */
640
                *q++ = flags;
641
                *q++ = 0x80 | 0x01;  /* marker bit + extension length */
642
                /*
643
                * Set the stream id extension flag bit to 0 and
644
                * write the extended stream id
645
                */
646
                *q++ = 0x00 | 0x60;
647
            }
648 8b475508 Fabrice Bellard
            if (private_code != 0)
649
                *q++ = private_code;
650 69ef9450 Fabrice Bellard
            is_start = 0;
651 5dbafeb7 Fabrice Bellard
        }
652 8b475508 Fabrice Bellard
        /* header size */
653
        header_len = q - buf;
654
        /* data len */
655
        len = TS_PACKET_SIZE - header_len;
656 69ef9450 Fabrice Bellard
        if (len > payload_size)
657
            len = payload_size;
658 8b475508 Fabrice Bellard
        stuffing_len = TS_PACKET_SIZE - header_len - len;
659
        if (stuffing_len > 0) {
660
            /* add stuffing with AFC */
661
            if (buf[3] & 0x20) {
662
                /* stuffing already present: increase its size */
663
                afc_len = buf[4] + 1;
664
                memmove(buf + 4 + afc_len + stuffing_len,
665 115329f1 Diego Biurrun
                        buf + 4 + afc_len,
666 8b475508 Fabrice Bellard
                        header_len - (4 + afc_len));
667
                buf[4] += stuffing_len;
668
                memset(buf + 4 + afc_len, 0xff, stuffing_len);
669
            } else {
670
                /* add stuffing */
671
                memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
672
                buf[3] |= 0x20;
673
                buf[4] = stuffing_len - 1;
674
                if (stuffing_len >= 2) {
675
                    buf[5] = 0x00;
676
                    memset(buf + 6, 0xff, stuffing_len - 2);
677
                }
678
            }
679
        }
680
        memcpy(buf + TS_PACKET_SIZE - len, payload, len);
681 69ef9450 Fabrice Bellard
        payload += len;
682
        payload_size -= len;
683 899681cd Björn Axelsson
        put_buffer(s->pb, buf, TS_PACKET_SIZE);
684 b5931348 Baptiste Coudurier
        ts->cur_pcr += TS_PACKET_SIZE*8*90000LL/ts->mux_rate;
685 5dbafeb7 Fabrice Bellard
    }
686 899681cd Björn Axelsson
    put_flush_packet(s->pb);
687 69ef9450 Fabrice Bellard
}
688
689 e928649b Michael Niedermayer
static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
690 69ef9450 Fabrice Bellard
{
691 e928649b Michael Niedermayer
    AVStream *st = s->streams[pkt->stream_index];
692
    int size= pkt->size;
693
    uint8_t *buf= pkt->data;
694 a57fb91c Baptiste Coudurier
    uint8_t *data= NULL;
695 69ef9450 Fabrice Bellard
    MpegTSWriteStream *ts_st = st->priv_data;
696 8b475508 Fabrice Bellard
    int len, max_payload_size;
697 de34dc39 Baptiste Coudurier
    const uint8_t *access_unit_index = NULL;
698 46911c7a Baptiste Coudurier
    const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
699 f3ba7c54 Baptiste Coudurier
    int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
700
701
    if (pkt->pts != AV_NOPTS_VALUE)
702
        pts = pkt->pts + delay;
703
    if (pkt->dts != AV_NOPTS_VALUE)
704
        dts = pkt->dts + delay;
705 69ef9450 Fabrice Bellard
706 01f4895c Michael Niedermayer
    if (st->codec->codec_type == CODEC_TYPE_SUBTITLE) {
707 8b475508 Fabrice Bellard
        /* for subtitle, a single PES packet must be generated */
708 f3ba7c54 Baptiste Coudurier
        mpegts_write_pes(s, st, buf, size, pts, AV_NOPTS_VALUE);
709 8b475508 Fabrice Bellard
        return 0;
710
    }
711 115329f1 Diego Biurrun
712 67a38cee Anuradha Suraparaju
    if (st->codec->codec_id == CODEC_ID_DIRAC) {
713
        /* for Dirac, a single PES packet must be generated */
714 f3ba7c54 Baptiste Coudurier
        mpegts_write_pes(s, st, buf, size, pts, dts);
715 67a38cee Anuradha Suraparaju
        return 0;
716
    }
717 8b475508 Fabrice Bellard
    max_payload_size = DEFAULT_PES_PAYLOAD_SIZE;
718 de34dc39 Baptiste Coudurier
    if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO ||
719
        st->codec->codec_id == CODEC_ID_MPEG1VIDEO) {
720
        const uint8_t *p = pkt->data;
721
        const uint8_t *end = pkt->data+pkt->size;
722
        uint32_t state = -1;
723
        while (p < end) {
724
            p = ff_find_start_code(p, end, &state);
725
            if (state == PICTURE_START_CODE) {
726
                access_unit_index = p - 4;
727
                break;
728
            }
729
        }
730 a57fb91c Baptiste Coudurier
    } if (st->codec->codec_id == CODEC_ID_H264) {
731
        if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
732
            av_log(s, AV_LOG_ERROR, "h264 bitstream malformated\n");
733
            return -1;
734
        }
735
        if (pkt->data[4] != 0x09) { // AUD NAL
736
            data = av_malloc(pkt->size+6);
737
            if (!data)
738
                return -1;
739
            memcpy(data+6, pkt->data, pkt->size);
740
            AV_WB32(data, 0x00000001);
741
            data[4] = 0x09;
742
            data[5] = 0xe0; // any slice type
743
            buf  = data;
744
            size = pkt->size+6;
745
        }
746
        access_unit_index = buf;
747 89ac55ad Baptiste Coudurier
    } else {
748 de34dc39 Baptiste Coudurier
        access_unit_index = pkt->data;
749
    }
750
751
    if (!access_unit_index) {
752
        av_log(s, AV_LOG_ERROR, "error, could not find access unit start\n");
753
        return -1;
754
    }
755
756 69ef9450 Fabrice Bellard
    while (size > 0) {
757 8b475508 Fabrice Bellard
        len = max_payload_size - ts_st->payload_index;
758 69ef9450 Fabrice Bellard
        if (len > size)
759
            len = size;
760
        memcpy(ts_st->payload + ts_st->payload_index, buf, len);
761
        buf += len;
762
        size -= len;
763
        ts_st->payload_index += len;
764 de34dc39 Baptiste Coudurier
        if (access_unit_index && access_unit_index < buf &&
765
            ts_st->payload_pts == AV_NOPTS_VALUE &&
766
            ts_st->payload_dts == AV_NOPTS_VALUE) {
767 f3ba7c54 Baptiste Coudurier
            ts_st->payload_dts = dts;
768
            ts_st->payload_pts = pts;
769 de34dc39 Baptiste Coudurier
        }
770 8b475508 Fabrice Bellard
        if (ts_st->payload_index >= max_payload_size) {
771 69ef9450 Fabrice Bellard
            mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
772 700b9711 Måns Rullgård
                             ts_st->payload_pts, ts_st->payload_dts);
773 69ef9450 Fabrice Bellard
            ts_st->payload_pts = AV_NOPTS_VALUE;
774 700b9711 Måns Rullgård
            ts_st->payload_dts = AV_NOPTS_VALUE;
775 69ef9450 Fabrice Bellard
            ts_st->payload_index = 0;
776 de34dc39 Baptiste Coudurier
            access_unit_index = NULL; // unset access unit to avoid setting pts/dts again
777 69ef9450 Fabrice Bellard
        }
778
    }
779 a57fb91c Baptiste Coudurier
780
    av_free(data);
781
782 5dbafeb7 Fabrice Bellard
    return 0;
783
}
784
785
static int mpegts_write_end(AVFormatContext *s)
786
{
787
    MpegTSWrite *ts = s->priv_data;
788
    MpegTSWriteStream *ts_st;
789
    MpegTSService *service;
790
    AVStream *st;
791
    int i;
792
793
    /* flush current packets */
794
    for(i = 0; i < s->nb_streams; i++) {
795
        st = s->streams[i];
796
        ts_st = st->priv_data;
797 69ef9450 Fabrice Bellard
        if (ts_st->payload_index > 0) {
798
            mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
799 700b9711 Måns Rullgård
                             ts_st->payload_pts, ts_st->payload_dts);
800 5dbafeb7 Fabrice Bellard
        }
801
    }
802 899681cd Björn Axelsson
    put_flush_packet(s->pb);
803 115329f1 Diego Biurrun
804 5dbafeb7 Fabrice Bellard
    for(i = 0; i < ts->nb_services; i++) {
805
        service = ts->services[i];
806
        av_freep(&service->provider_name);
807
        av_freep(&service->name);
808
        av_free(service);
809
    }
810
    av_free(ts->services);
811
812
    return 0;
813
}
814
815 d2a067d1 Måns Rullgård
AVOutputFormat mpegts_muxer = {
816 5dbafeb7 Fabrice Bellard
    "mpegts",
817 bde15e74 Stefano Sabatini
    NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
818 5dbafeb7 Fabrice Bellard
    "video/x-mpegts",
819 d3ad044a Baptiste Coudurier
    "ts,m2t",
820 5dbafeb7 Fabrice Bellard
    sizeof(MpegTSWrite),
821
    CODEC_ID_MP2,
822 69ef9450 Fabrice Bellard
    CODEC_ID_MPEG2VIDEO,
823 5dbafeb7 Fabrice Bellard
    mpegts_write_header,
824
    mpegts_write_packet,
825
    mpegts_write_end,
826
};