Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegtsenc.c @ 9dd94f83

History | View | Annotate | Download (32.1 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 2912e87a Mans Rullgard
 * This file is part of Libav.
6 b78e7197 Diego Biurrun
 *
7 2912e87a Mans Rullgard
 * Libav 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 2912e87a Mans Rullgard
 * Libav 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 2912e87a Mans Rullgard
 * License along with Libav; 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 445996aa Georgi Chorbadzhiyski
#include "libavutil/opt.h"
25 de34dc39 Baptiste Coudurier
#include "libavcodec/mpegvideo.h"
26 5dbafeb7 Fabrice Bellard
#include "avformat.h"
27 9a2cb05f Stefano Sabatini
#include "internal.h"
28 5dbafeb7 Fabrice Bellard
#include "mpegts.h"
29 8fdd542c Baptiste Coudurier
#include "adts.h"
30 5dbafeb7 Fabrice Bellard
31 66be80d6 Tomas Härdin
#define PCR_TIME_BASE 27000000
32
33 5dbafeb7 Fabrice Bellard
/* write DVB SI sections */
34
35
/*********************************************/
36
/* mpegts section writer */
37
38
typedef struct MpegTSSection {
39
    int pid;
40
    int cc;
41
    void (*write_packet)(struct MpegTSSection *s, const uint8_t *packet);
42
    void *opaque;
43
} MpegTSSection;
44
45 b5931348 Baptiste Coudurier
typedef struct MpegTSService {
46
    MpegTSSection pmt; /* MPEG2 pmt table context */
47
    int sid;           /* service ID */
48
    char *name;
49
    char *provider_name;
50
    int pcr_pid;
51
    int pcr_packet_count;
52 1aae3489 Niobos
    int pcr_packet_period;
53 b5931348 Baptiste Coudurier
} MpegTSService;
54
55
typedef struct MpegTSWrite {
56
    MpegTSSection pat; /* MPEG2 pat table */
57
    MpegTSSection sdt; /* MPEG2 sdt table context */
58
    MpegTSService **services;
59
    int sdt_packet_count;
60 1aae3489 Niobos
    int sdt_packet_period;
61 b5931348 Baptiste Coudurier
    int pat_packet_count;
62 1aae3489 Niobos
    int pat_packet_period;
63 b5931348 Baptiste Coudurier
    int nb_services;
64
    int onid;
65
    int tsid;
66 66be80d6 Tomas Härdin
    int64_t first_pcr;
67 7082ea56 Baptiste Coudurier
    int mux_rate; ///< set to 1 when VBR
68 445996aa Georgi Chorbadzhiyski
69
    int transport_stream_id;
70
    int original_network_id;
71
    int service_id;
72
73
    int pmt_start_pid;
74
    int start_pid;
75 b5931348 Baptiste Coudurier
} MpegTSWrite;
76
77 445996aa Georgi Chorbadzhiyski
static const AVOption options[] = {
78
    { "mpegts_transport_stream_id", "Set transport_stream_id field.",
79
      offsetof(MpegTSWrite, transport_stream_id), FF_OPT_TYPE_INT, 0x0001, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
80
    { "mpegts_original_network_id", "Set original_network_id field.",
81
      offsetof(MpegTSWrite, original_network_id), FF_OPT_TYPE_INT, 0x0001, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
82
    { "mpegts_service_id", "Set service_id field.",
83
      offsetof(MpegTSWrite, service_id), FF_OPT_TYPE_INT, 0x0001, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
84
    { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
85
      offsetof(MpegTSWrite, pmt_start_pid), FF_OPT_TYPE_INT, 0x1000, 0x1000, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM},
86
    { "mpegts_start_pid", "Set the first pid.",
87
      offsetof(MpegTSWrite, start_pid), FF_OPT_TYPE_INT, 0x0100, 0x0100, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM},
88
    { NULL },
89
};
90
91
static const AVClass mpegts_muxer_class = {
92
    "MPEGTS muxer",
93
    av_default_item_name,
94
    options,
95
    LIBAVUTIL_VERSION_INT,
96
};
97
98 5dbafeb7 Fabrice Bellard
/* NOTE: 4 bytes must be left at the end for the crc32 */
99 7b49ce2e Stefan Huehner
static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
100 5dbafeb7 Fabrice Bellard
{
101
    unsigned int crc;
102
    unsigned char packet[TS_PACKET_SIZE];
103
    const unsigned char *buf_ptr;
104
    unsigned char *q;
105
    int first, b, len1, left;
106
107 8fc0162a Måns Rullgård
    crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
108 5dbafeb7 Fabrice Bellard
    buf[len - 4] = (crc >> 24) & 0xff;
109
    buf[len - 3] = (crc >> 16) & 0xff;
110
    buf[len - 2] = (crc >> 8) & 0xff;
111
    buf[len - 1] = (crc) & 0xff;
112 115329f1 Diego Biurrun
113 5dbafeb7 Fabrice Bellard
    /* send each packet */
114
    buf_ptr = buf;
115
    while (len > 0) {
116
        first = (buf == buf_ptr);
117
        q = packet;
118
        *q++ = 0x47;
119
        b = (s->pid >> 8);
120
        if (first)
121
            b |= 0x40;
122
        *q++ = b;
123
        *q++ = s->pid;
124 3654a16d Baptiste Coudurier
        s->cc = (s->cc + 1) & 0xf;
125 8d819221 Yann Coupin
        *q++ = 0x10 | s->cc;
126 5dbafeb7 Fabrice Bellard
        if (first)
127
            *q++ = 0; /* 0 offset */
128
        len1 = TS_PACKET_SIZE - (q - packet);
129 115329f1 Diego Biurrun
        if (len1 > len)
130 5dbafeb7 Fabrice Bellard
            len1 = len;
131
        memcpy(q, buf_ptr, len1);
132
        q += len1;
133
        /* add known padding data */
134
        left = TS_PACKET_SIZE - (q - packet);
135
        if (left > 0)
136
            memset(q, 0xff, left);
137
138
        s->write_packet(s, packet);
139
140
        buf_ptr += len1;
141
        len -= len1;
142
    }
143
}
144
145
static inline void put16(uint8_t **q_ptr, int val)
146
{
147
    uint8_t *q;
148
    q = *q_ptr;
149
    *q++ = val >> 8;
150
    *q++ = val;
151
    *q_ptr = q;
152
}
153
154 7b49ce2e Stefan Huehner
static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
155 5dbafeb7 Fabrice Bellard
                          int version, int sec_num, int last_sec_num,
156
                          uint8_t *buf, int len)
157
{
158
    uint8_t section[1024], *q;
159
    unsigned int tot_len;
160 a7827a17 Georgi Chorbadzhiyski
    /* reserved_future_use field must be set to 1 for SDT */
161
    unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
162 115329f1 Diego Biurrun
163 5dbafeb7 Fabrice Bellard
    tot_len = 3 + 5 + len + 4;
164
    /* check if not too big */
165
    if (tot_len > 1024)
166
        return -1;
167
168
    q = section;
169
    *q++ = tid;
170 a7827a17 Georgi Chorbadzhiyski
    put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
171 5dbafeb7 Fabrice Bellard
    put16(&q, id);
172
    *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
173
    *q++ = sec_num;
174
    *q++ = last_sec_num;
175
    memcpy(q, buf, len);
176 115329f1 Diego Biurrun
177 5dbafeb7 Fabrice Bellard
    mpegts_write_section(s, section, tot_len);
178
    return 0;
179
}
180
181
/*********************************************/
182
/* mpegts writer */
183
184
#define DEFAULT_PROVIDER_NAME   "FFmpeg"
185
#define DEFAULT_SERVICE_NAME    "Service01"
186
187
/* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
188
#define DEFAULT_PES_HEADER_FREQ 16
189 69ef9450 Fabrice Bellard
#define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
190 5dbafeb7 Fabrice Bellard
191
/* we retransmit the SI info at this rate */
192
#define SDT_RETRANS_TIME 500
193
#define PAT_RETRANS_TIME 100
194 8b475508 Fabrice Bellard
#define PCR_RETRANS_TIME 20
195 5dbafeb7 Fabrice Bellard
196
typedef struct MpegTSWriteStream {
197 8b475508 Fabrice Bellard
    struct MpegTSService *service;
198 5dbafeb7 Fabrice Bellard
    int pid; /* stream associated pid */
199
    int cc;
200 69ef9450 Fabrice Bellard
    int payload_index;
201 b69017af Baptiste Coudurier
    int first_pts_check; ///< first pts check needed
202 69ef9450 Fabrice Bellard
    int64_t payload_pts;
203 700b9711 Måns Rullgård
    int64_t payload_dts;
204 69ef9450 Fabrice Bellard
    uint8_t payload[DEFAULT_PES_PAYLOAD_SIZE];
205 8fdd542c Baptiste Coudurier
    ADTSContext *adts;
206 5dbafeb7 Fabrice Bellard
} MpegTSWriteStream;
207
208
static void mpegts_write_pat(AVFormatContext *s)
209
{
210
    MpegTSWrite *ts = s->priv_data;
211
    MpegTSService *service;
212
    uint8_t data[1012], *q;
213
    int i;
214 115329f1 Diego Biurrun
215 5dbafeb7 Fabrice Bellard
    q = data;
216
    for(i = 0; i < ts->nb_services; i++) {
217
        service = ts->services[i];
218
        put16(&q, service->sid);
219
        put16(&q, 0xe000 | service->pmt.pid);
220
    }
221
    mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, 0, 0, 0,
222
                          data, q - data);
223
}
224
225
static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
226
{
227
    //    MpegTSWrite *ts = s->priv_data;
228
    uint8_t data[1012], *q, *desc_length_ptr, *program_info_length_ptr;
229
    int val, stream_type, i;
230
231
    q = data;
232
    put16(&q, 0xe000 | service->pcr_pid);
233
234
    program_info_length_ptr = q;
235
    q += 2; /* patched after */
236
237
    /* put program info here */
238
239
    val = 0xf000 | (q - program_info_length_ptr - 2);
240
    program_info_length_ptr[0] = val >> 8;
241
    program_info_length_ptr[1] = val;
242 115329f1 Diego Biurrun
243 5dbafeb7 Fabrice Bellard
    for(i = 0; i < s->nb_streams; i++) {
244
        AVStream *st = s->streams[i];
245
        MpegTSWriteStream *ts_st = st->priv_data;
246 4b358c3e Aurelien Jacobs
        AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL,0);
247 01f4895c Michael Niedermayer
        switch(st->codec->codec_id) {
248 278de475 Måns Rullgård
        case CODEC_ID_MPEG1VIDEO:
249
        case CODEC_ID_MPEG2VIDEO:
250
            stream_type = STREAM_TYPE_VIDEO_MPEG2;
251 5dbafeb7 Fabrice Bellard
            break;
252 278de475 Måns Rullgård
        case CODEC_ID_MPEG4:
253
            stream_type = STREAM_TYPE_VIDEO_MPEG4;
254
            break;
255
        case CODEC_ID_H264:
256
            stream_type = STREAM_TYPE_VIDEO_H264;
257
            break;
258 f4bba201 Anuradha Suraparaju
        case CODEC_ID_DIRAC:
259
            stream_type = STREAM_TYPE_VIDEO_DIRAC;
260
            break;
261 278de475 Måns Rullgård
        case CODEC_ID_MP2:
262
        case CODEC_ID_MP3:
263 ce34182d Michael Niedermayer
            stream_type = STREAM_TYPE_AUDIO_MPEG1;
264 5dbafeb7 Fabrice Bellard
            break;
265 278de475 Måns Rullgård
        case CODEC_ID_AAC:
266
            stream_type = STREAM_TYPE_AUDIO_AAC;
267
            break;
268 4d54df8e Peter Ross
        case CODEC_ID_AAC_LATM:
269
            stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
270
            break;
271 278de475 Måns Rullgård
        case CODEC_ID_AC3:
272 a1f42882 Baptiste Coudurier
            stream_type = STREAM_TYPE_AUDIO_AC3;
273 278de475 Måns Rullgård
            break;
274 5dbafeb7 Fabrice Bellard
        default:
275
            stream_type = STREAM_TYPE_PRIVATE_DATA;
276
            break;
277
        }
278
        *q++ = stream_type;
279
        put16(&q, 0xe000 | ts_st->pid);
280
        desc_length_ptr = q;
281
        q += 2; /* patched after */
282
283
        /* write optional descriptors here */
284 01f4895c Michael Niedermayer
        switch(st->codec->codec_type) {
285 72415b2a Stefano Sabatini
        case AVMEDIA_TYPE_AUDIO:
286 435cebd0 Anssi Hannula
            if (lang) {
287
                char *p;
288
                char *next = lang->value;
289
                uint8_t *len_ptr;
290
291 8b475508 Fabrice Bellard
                *q++ = 0x0a; /* ISO 639 language descriptor */
292 435cebd0 Anssi Hannula
                len_ptr = q++;
293
                *len_ptr = 0;
294
295
                for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
296
                    next = strchr(p, ',');
297
                    if (strlen(p) != 3 && (!next || next != p + 3))
298
                        continue; /* not a 3-letter code */
299
300
                    *q++ = *p++;
301
                    *q++ = *p++;
302
                    *q++ = *p++;
303
304 3f2d3a19 Anssi Hannula
                if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
305
                    *q++ = 0x01;
306
                else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
307
                    *q++ = 0x02;
308
                else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
309
                    *q++ = 0x03;
310
                else
311 2dd1ee4b Mans Rullgard
                    *q++ = 0; /* undefined type */
312 435cebd0 Anssi Hannula
313
                    *len_ptr += 4;
314
                }
315
316
                if (*len_ptr == 0)
317
                    q -= 2; /* no language codes were written */
318 8b475508 Fabrice Bellard
            }
319
            break;
320 72415b2a Stefano Sabatini
        case AVMEDIA_TYPE_SUBTITLE:
321 8b475508 Fabrice Bellard
            {
322
                const char *language;
323 4b358c3e Aurelien Jacobs
                language = lang && strlen(lang->value)==3 ? lang->value : "eng";
324 8b475508 Fabrice Bellard
                *q++ = 0x59;
325
                *q++ = 8;
326
                *q++ = language[0];
327
                *q++ = language[1];
328
                *q++ = language[2];
329
                *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */
330 d1ac0351 Tomas Härdin
                if(st->codec->extradata_size == 4) {
331
                    memcpy(q, st->codec->extradata, 4);
332
                    q += 4;
333
                } else {
334 16209390 Tomas Härdin
                    put16(&q, 1); /* page id */
335
                    put16(&q, 1); /* ancillary page id */
336 d1ac0351 Tomas Härdin
                }
337 8b475508 Fabrice Bellard
            }
338
            break;
339 72415b2a Stefano Sabatini
        case AVMEDIA_TYPE_VIDEO:
340 f4bba201 Anuradha Suraparaju
            if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
341
                *q++ = 0x05; /*MPEG-2 registration descriptor*/
342
                *q++ = 4;
343
                *q++ = 'd';
344
                *q++ = 'r';
345
                *q++ = 'a';
346
                *q++ = 'c';
347
            }
348
            break;
349 8b475508 Fabrice Bellard
        }
350 5dbafeb7 Fabrice Bellard
351
        val = 0xf000 | (q - desc_length_ptr - 2);
352
        desc_length_ptr[0] = val >> 8;
353
        desc_length_ptr[1] = val;
354
    }
355
    mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,
356
                          data, q - data);
357 115329f1 Diego Biurrun
}
358 5dbafeb7 Fabrice Bellard
359
/* NOTE: str == NULL is accepted for an empty string */
360
static void putstr8(uint8_t **q_ptr, const char *str)
361
{
362
    uint8_t *q;
363
    int len;
364
365
    q = *q_ptr;
366
    if (!str)
367
        len = 0;
368
    else
369
        len = strlen(str);
370
    *q++ = len;
371
    memcpy(q, str, len);
372
    q += len;
373
    *q_ptr = q;
374
}
375
376
static void mpegts_write_sdt(AVFormatContext *s)
377
{
378
    MpegTSWrite *ts = s->priv_data;
379
    MpegTSService *service;
380
    uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
381
    int i, running_status, free_ca_mode, val;
382 115329f1 Diego Biurrun
383 5dbafeb7 Fabrice Bellard
    q = data;
384
    put16(&q, ts->onid);
385
    *q++ = 0xff;
386
    for(i = 0; i < ts->nb_services; i++) {
387
        service = ts->services[i];
388
        put16(&q, service->sid);
389
        *q++ = 0xfc | 0x00; /* currently no EIT info */
390
        desc_list_len_ptr = q;
391
        q += 2;
392
        running_status = 4; /* running */
393
        free_ca_mode = 0;
394
395
        /* write only one descriptor for the service name and provider */
396
        *q++ = 0x48;
397
        desc_len_ptr = q;
398
        q++;
399
        *q++ = 0x01; /* digital television service */
400
        putstr8(&q, service->provider_name);
401
        putstr8(&q, service->name);
402
        desc_len_ptr[0] = q - desc_len_ptr - 1;
403
404
        /* fill descriptor length */
405 115329f1 Diego Biurrun
        val = (running_status << 13) | (free_ca_mode << 12) |
406 5dbafeb7 Fabrice Bellard
            (q - desc_list_len_ptr - 2);
407
        desc_list_len_ptr[0] = val >> 8;
408
        desc_list_len_ptr[1] = val;
409
    }
410
    mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, 0, 0, 0,
411
                          data, q - data);
412
}
413
414 115329f1 Diego Biurrun
static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
415
                                         int sid,
416
                                         const char *provider_name,
417 5dbafeb7 Fabrice Bellard
                                         const char *name)
418
{
419
    MpegTSService *service;
420
421
    service = av_mallocz(sizeof(MpegTSService));
422
    if (!service)
423
        return NULL;
424 740ad0d1 Mans Rullgard
    service->pmt.pid = ts->pmt_start_pid + ts->nb_services - 1;
425 5dbafeb7 Fabrice Bellard
    service->sid = sid;
426
    service->provider_name = av_strdup(provider_name);
427
    service->name = av_strdup(name);
428
    service->pcr_pid = 0x1fff;
429
    dynarray_add(&ts->services, &ts->nb_services, service);
430
    return service;
431
}
432
433
static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
434
{
435
    AVFormatContext *ctx = s->opaque;
436 77eb5504 Anton Khirnov
    avio_write(ctx->pb, packet, TS_PACKET_SIZE);
437 5dbafeb7 Fabrice Bellard
}
438
439
static int mpegts_write_header(AVFormatContext *s)
440
{
441
    MpegTSWrite *ts = s->priv_data;
442
    MpegTSWriteStream *ts_st;
443
    MpegTSService *service;
444 7082ea56 Baptiste Coudurier
    AVStream *st, *pcr_st = NULL;
445 69688e71 Georgi Chorbadzhiyski
    AVMetadataTag *title, *provider;
446 5fd48573 Mike Scheutzow
    int i, j;
447 8b475508 Fabrice Bellard
    const char *service_name;
448 69688e71 Georgi Chorbadzhiyski
    const char *provider_name;
449 5fd48573 Mike Scheutzow
    int *pids;
450 115329f1 Diego Biurrun
451 445996aa Georgi Chorbadzhiyski
    ts->tsid = ts->transport_stream_id;
452
    ts->onid = ts->original_network_id;
453 5dbafeb7 Fabrice Bellard
    /* allocate a single DVB service */
454 e5fe6551 Janne Grunau
    title = av_metadata_get(s->metadata, "service_name", NULL, 0);
455 69688e71 Georgi Chorbadzhiyski
    if (!title)
456 e5fe6551 Janne Grunau
        title = av_metadata_get(s->metadata, "title", NULL, 0);
457 4b358c3e Aurelien Jacobs
    service_name = title ? title->value : DEFAULT_SERVICE_NAME;
458 69688e71 Georgi Chorbadzhiyski
    provider = av_metadata_get(s->metadata, "service_provider", NULL, 0);
459
    provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
460 445996aa Georgi Chorbadzhiyski
    service = mpegts_add_service(ts, ts->service_id, provider_name, service_name);
461 5dbafeb7 Fabrice Bellard
    service->pmt.write_packet = section_write_packet;
462
    service->pmt.opaque = s;
463 677a1144 Baptiste Coudurier
    service->pmt.cc = 15;
464 5dbafeb7 Fabrice Bellard
465
    ts->pat.pid = PAT_PID;
466 8d819221 Yann Coupin
    ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
467 5dbafeb7 Fabrice Bellard
    ts->pat.write_packet = section_write_packet;
468
    ts->pat.opaque = s;
469
470
    ts->sdt.pid = SDT_PID;
471 8d819221 Yann Coupin
    ts->sdt.cc = 15;
472 5dbafeb7 Fabrice Bellard
    ts->sdt.write_packet = section_write_packet;
473
    ts->sdt.opaque = s;
474
475 ea59f489 Måns Rullgård
    pids = av_malloc(s->nb_streams * sizeof(*pids));
476 5fd48573 Mike Scheutzow
    if (!pids)
477
        return AVERROR(ENOMEM);
478
479 5dbafeb7 Fabrice Bellard
    /* assign pids to each stream */
480
    for(i = 0;i < s->nb_streams; i++) {
481
        st = s->streams[i];
482
        ts_st = av_mallocz(sizeof(MpegTSWriteStream));
483
        if (!ts_st)
484
            goto fail;
485
        st->priv_data = ts_st;
486 8b475508 Fabrice Bellard
        ts_st->service = service;
487 5fd48573 Mike Scheutzow
        /* MPEG pid values < 16 are reserved. Applications which set st->id in
488
         * this range are assigned a calculated pid. */
489
        if (st->id < 16) {
490 445996aa Georgi Chorbadzhiyski
            ts_st->pid = ts->start_pid + i;
491 5fd48573 Mike Scheutzow
        } else if (st->id < 0x1FFF) {
492
            ts_st->pid = st->id;
493
        } else {
494
            av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
495
            goto fail;
496
        }
497
        if (ts_st->pid == service->pmt.pid) {
498
            av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
499
            goto fail;
500
        }
501
        for (j = 0; j < i; j++)
502
            if (pids[j] == ts_st->pid) {
503
                av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
504
                goto fail;
505
            }
506
        pids[i] = ts_st->pid;
507 69ef9450 Fabrice Bellard
        ts_st->payload_pts = AV_NOPTS_VALUE;
508 700b9711 Måns Rullgård
        ts_st->payload_dts = AV_NOPTS_VALUE;
509 b69017af Baptiste Coudurier
        ts_st->first_pts_check = 1;
510 d73a458f Baptiste Coudurier
        ts_st->cc = 15;
511 8b475508 Fabrice Bellard
        /* update PCR pid by using the first video stream */
512 72415b2a Stefano Sabatini
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
513 7082ea56 Baptiste Coudurier
            service->pcr_pid == 0x1fff) {
514 5dbafeb7 Fabrice Bellard
            service->pcr_pid = ts_st->pid;
515 7082ea56 Baptiste Coudurier
            pcr_st = st;
516 9deba199 Niobos
        }
517 8fdd542c Baptiste Coudurier
        if (st->codec->codec_id == CODEC_ID_AAC &&
518
            st->codec->extradata_size > 0) {
519
            ts_st->adts = av_mallocz(sizeof(*ts_st->adts));
520
            if (!ts_st->adts)
521 2874c81c Stefano Sabatini
                return AVERROR(ENOMEM);
522 8fdd542c Baptiste Coudurier
            if (ff_adts_decode_extradata(s, ts_st->adts, st->codec->extradata,
523
                                         st->codec->extradata_size) < 0)
524
                return -1;
525
        }
526 5dbafeb7 Fabrice Bellard
    }
527 115329f1 Diego Biurrun
528 5fd48573 Mike Scheutzow
    av_free(pids);
529
530 8b475508 Fabrice Bellard
    /* if no video stream, use the first stream as PCR */
531
    if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
532 7082ea56 Baptiste Coudurier
        pcr_st = s->streams[0];
533
        ts_st = pcr_st->priv_data;
534 8b475508 Fabrice Bellard
        service->pcr_pid = ts_st->pid;
535
    }
536
537 7082ea56 Baptiste Coudurier
    ts->mux_rate = s->mux_rate ? s->mux_rate : 1;
538 3d0a94f6 Baptiste Coudurier
539 7082ea56 Baptiste Coudurier
    if (ts->mux_rate > 1) {
540 e3433702 Baptiste Coudurier
        service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
541
            (TS_PACKET_SIZE * 8 * 1000);
542
        ts->sdt_packet_period      = (ts->mux_rate * SDT_RETRANS_TIME) /
543
            (TS_PACKET_SIZE * 8 * 1000);
544
        ts->pat_packet_period      = (ts->mux_rate * PAT_RETRANS_TIME) /
545
            (TS_PACKET_SIZE * 8 * 1000);
546
547 66be80d6 Tomas Härdin
        ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
548 7082ea56 Baptiste Coudurier
    } else {
549
        /* Arbitrary values, PAT/PMT could be written on key frames */
550
        ts->sdt_packet_period = 200;
551
        ts->pat_packet_period = 40;
552 72415b2a Stefano Sabatini
        if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
553 7082ea56 Baptiste Coudurier
            if (!pcr_st->codec->frame_size) {
554
                av_log(s, AV_LOG_WARNING, "frame size not set\n");
555
                service->pcr_packet_period =
556
                    pcr_st->codec->sample_rate/(10*512);
557
            } else {
558
                service->pcr_packet_period =
559
                    pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
560
            }
561
        } else {
562
            // max delta PCR 0.1s
563
            service->pcr_packet_period =
564
                pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
565
        }
566
    }
567
568 6b18a3f5 Mike Scheutzow
    // output a PCR as soon as possible
569
    service->pcr_packet_count = service->pcr_packet_period;
570 7082ea56 Baptiste Coudurier
    ts->pat_packet_count = ts->pat_packet_period-1;
571
    ts->sdt_packet_count = ts->sdt_packet_period-1;
572 6b18a3f5 Mike Scheutzow
573 efdccce5 Baptiste Coudurier
    if (ts->mux_rate == 1)
574
        av_log(s, AV_LOG_INFO, "muxrate VBR, ");
575
    else
576
        av_log(s, AV_LOG_INFO, "muxrate %d, ", ts->mux_rate);
577
    av_log(s, AV_LOG_INFO, "pcr every %d pkts, "
578 907d9166 Mike Scheutzow
           "sdt every %d, pat/pmt every %d pkts\n",
579 efdccce5 Baptiste Coudurier
           service->pcr_packet_period,
580 7082ea56 Baptiste Coudurier
           ts->sdt_packet_period, ts->pat_packet_period);
581 907d9166 Mike Scheutzow
582 b7f2fdde Anton Khirnov
    avio_flush(s->pb);
583 5dbafeb7 Fabrice Bellard
584
    return 0;
585
586
 fail:
587 5fd48573 Mike Scheutzow
    av_free(pids);
588 5dbafeb7 Fabrice Bellard
    for(i = 0;i < s->nb_streams; i++) {
589
        st = s->streams[i];
590
        av_free(st->priv_data);
591
    }
592
    return -1;
593
}
594
595
/* send SDT, PAT and PMT tables regulary */
596
static void retransmit_si_info(AVFormatContext *s)
597
{
598
    MpegTSWrite *ts = s->priv_data;
599
    int i;
600
601 1aae3489 Niobos
    if (++ts->sdt_packet_count == ts->sdt_packet_period) {
602 5dbafeb7 Fabrice Bellard
        ts->sdt_packet_count = 0;
603
        mpegts_write_sdt(s);
604
    }
605 1aae3489 Niobos
    if (++ts->pat_packet_count == ts->pat_packet_period) {
606 5dbafeb7 Fabrice Bellard
        ts->pat_packet_count = 0;
607
        mpegts_write_pat(s);
608
        for(i = 0; i < ts->nb_services; i++) {
609
            mpegts_write_pmt(s, ts->services[i]);
610
        }
611
    }
612
}
613
614 ae628ec1 Anton Khirnov
static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
615 66be80d6 Tomas Härdin
{
616 a2704c97 Anton Khirnov
    return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
617 66be80d6 Tomas Härdin
           ts->first_pcr;
618
}
619
620
static uint8_t* write_pcr_bits(uint8_t *buf, int64_t pcr)
621
{
622
    int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
623
624
    *buf++ = pcr_high >> 25;
625
    *buf++ = pcr_high >> 17;
626
    *buf++ = pcr_high >> 9;
627
    *buf++ = pcr_high >> 1;
628 535638b5 Georgi Chorbadzhiyski
    *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
629 66be80d6 Tomas Härdin
    *buf++ = pcr_low;
630
631
    return buf;
632
}
633
634 4df3bbbc Mike Scheutzow
/* Write a single null transport stream packet */
635
static void mpegts_insert_null_packet(AVFormatContext *s)
636
{
637
    uint8_t *q;
638
    uint8_t buf[TS_PACKET_SIZE];
639
640
    q = buf;
641
    *q++ = 0x47;
642
    *q++ = 0x00 | 0x1f;
643
    *q++ = 0xff;
644
    *q++ = 0x10;
645
    memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
646 77eb5504 Anton Khirnov
    avio_write(s->pb, buf, TS_PACKET_SIZE);
647 4df3bbbc Mike Scheutzow
}
648
649
/* Write a single transport stream packet with a PCR and no payload */
650
static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
651
{
652
    MpegTSWrite *ts = s->priv_data;
653
    MpegTSWriteStream *ts_st = st->priv_data;
654
    uint8_t *q;
655
    uint8_t buf[TS_PACKET_SIZE];
656
657
    q = buf;
658
    *q++ = 0x47;
659
    *q++ = ts_st->pid >> 8;
660
    *q++ = ts_st->pid;
661
    *q++ = 0x20 | ts_st->cc;   /* Adaptation only */
662
    /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
663
    *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
664
    *q++ = 0x10;               /* Adaptation flags: PCR present */
665
666
    /* PCR coded into 6 bytes */
667 66be80d6 Tomas Härdin
    q = write_pcr_bits(q, get_pcr(ts, s->pb));
668 4df3bbbc Mike Scheutzow
669
    /* stuffing bytes */
670
    memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
671 77eb5504 Anton Khirnov
    avio_write(s->pb, buf, TS_PACKET_SIZE);
672 4df3bbbc Mike Scheutzow
}
673
674 700b9711 Måns Rullgård
static void write_pts(uint8_t *q, int fourbits, int64_t pts)
675
{
676
    int val;
677
678
    val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
679
    *q++ = val;
680
    val = (((pts >> 15) & 0x7fff) << 1) | 1;
681
    *q++ = val >> 8;
682
    *q++ = val;
683
    val = (((pts) & 0x7fff) << 1) | 1;
684
    *q++ = val >> 8;
685
    *q++ = val;
686
}
687
688 c054f372 Mike Scheutzow
/* Add a pes header to the front of payload, and segment into an integer number of
689
 * ts packets. The final ts packet is padded using an over-sized adaptation header
690
 * to exactly fill the last ts packet.
691
 * NOTE: 'payload' contains a complete PES payload.
692
 */
693 69ef9450 Fabrice Bellard
static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
694
                             const uint8_t *payload, int payload_size,
695 700b9711 Måns Rullgård
                             int64_t pts, int64_t dts)
696 5dbafeb7 Fabrice Bellard
{
697
    MpegTSWriteStream *ts_st = st->priv_data;
698 b5931348 Baptiste Coudurier
    MpegTSWrite *ts = s->priv_data;
699 69ef9450 Fabrice Bellard
    uint8_t buf[TS_PACKET_SIZE];
700 5dbafeb7 Fabrice Bellard
    uint8_t *q;
701 700b9711 Måns Rullgård
    int val, is_start, len, header_len, write_pcr, private_code, flags;
702 8b475508 Fabrice Bellard
    int afc_len, stuffing_len;
703
    int64_t pcr = -1; /* avoid warning */
704 4df3bbbc Mike Scheutzow
    int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
705 5dbafeb7 Fabrice Bellard
706 69ef9450 Fabrice Bellard
    is_start = 1;
707
    while (payload_size > 0) {
708
        retransmit_si_info(s);
709 5dbafeb7 Fabrice Bellard
710 8b475508 Fabrice Bellard
        write_pcr = 0;
711
        if (ts_st->pid == ts_st->service->pcr_pid) {
712 7082ea56 Baptiste Coudurier
            if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
713
                ts_st->service->pcr_packet_count++;
714 115329f1 Diego Biurrun
            if (ts_st->service->pcr_packet_count >=
715 1aae3489 Niobos
                ts_st->service->pcr_packet_period) {
716 8b475508 Fabrice Bellard
                ts_st->service->pcr_packet_count = 0;
717
                write_pcr = 1;
718
            }
719
        }
720
721 7082ea56 Baptiste Coudurier
        if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
722 66be80d6 Tomas Härdin
            (dts - get_pcr(ts, s->pb)/300) > delay) {
723 4df3bbbc Mike Scheutzow
            /* pcr insert gets priority over null packet insert */
724
            if (write_pcr)
725
                mpegts_insert_pcr_only(s, st);
726
            else
727
                mpegts_insert_null_packet(s);
728
            continue; /* recalculate write_pcr and possibly retransmit si_info */
729
        }
730
731 69ef9450 Fabrice Bellard
        /* prepare packet header */
732
        q = buf;
733
        *q++ = 0x47;
734
        val = (ts_st->pid >> 8);
735
        if (is_start)
736
            val |= 0x40;
737
        *q++ = val;
738
        *q++ = ts_st->pid;
739
        ts_st->cc = (ts_st->cc + 1) & 0xf;
740 8d819221 Yann Coupin
        *q++ = 0x10 | ts_st->cc | (write_pcr ? 0x20 : 0);
741 8b475508 Fabrice Bellard
        if (write_pcr) {
742 b5931348 Baptiste Coudurier
            // add 11, pcr references the last byte of program clock reference base
743 7082ea56 Baptiste Coudurier
            if (ts->mux_rate > 1)
744 66be80d6 Tomas Härdin
                pcr = get_pcr(ts, s->pb);
745 7082ea56 Baptiste Coudurier
            else
746 66be80d6 Tomas Härdin
                pcr = (dts - delay)*300;
747
            if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
748 811a0aa7 Baptiste Coudurier
                av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
749 8b475508 Fabrice Bellard
            *q++ = 7; /* AFC length */
750
            *q++ = 0x10; /* flags: PCR present */
751 66be80d6 Tomas Härdin
            q = write_pcr_bits(q, pcr);
752 8b475508 Fabrice Bellard
        }
753 69ef9450 Fabrice Bellard
        if (is_start) {
754 f4bba201 Anuradha Suraparaju
            int pes_extension = 0;
755 69ef9450 Fabrice Bellard
            /* write PES header */
756
            *q++ = 0x00;
757
            *q++ = 0x00;
758
            *q++ = 0x01;
759 8b475508 Fabrice Bellard
            private_code = 0;
760 72415b2a Stefano Sabatini
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
761 f4bba201 Anuradha Suraparaju
                if (st->codec->codec_id == CODEC_ID_DIRAC) {
762
                    *q++ = 0xfd;
763
                } else
764
                    *q++ = 0xe0;
765 72415b2a Stefano Sabatini
            } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
766 01f4895c Michael Niedermayer
                       (st->codec->codec_id == CODEC_ID_MP2 ||
767 6c065f0a Tony Strauss
                        st->codec->codec_id == CODEC_ID_MP3 ||
768
                        st->codec->codec_id == CODEC_ID_AAC)) {
769 115329f1 Diego Biurrun
                *q++ = 0xc0;
770 8b475508 Fabrice Bellard
            } else {
771
                *q++ = 0xbd;
772 72415b2a Stefano Sabatini
                if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
773 8b475508 Fabrice Bellard
                    private_code = 0x20;
774
                }
775
            }
776 700b9711 Måns Rullgård
            header_len = 0;
777
            flags = 0;
778
            if (pts != AV_NOPTS_VALUE) {
779
                header_len += 5;
780
                flags |= 0x80;
781
            }
782 8f14cdee Baptiste Coudurier
            if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
783 700b9711 Måns Rullgård
                header_len += 5;
784
                flags |= 0x40;
785
            }
786 72415b2a Stefano Sabatini
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
787 f4bba201 Anuradha Suraparaju
                st->codec->codec_id == CODEC_ID_DIRAC) {
788
                /* set PES_extension_flag */
789
                pes_extension = 1;
790
                flags |= 0x01;
791
792
                /*
793
                * One byte for PES2 extension flag +
794
                * one byte for extension length +
795
                * one byte for extension id
796
                */
797
                header_len += 3;
798
            }
799 700b9711 Måns Rullgård
            len = payload_size + header_len + 3;
800 8b475508 Fabrice Bellard
            if (private_code != 0)
801 700b9711 Måns Rullgård
                len++;
802 e4358e70 Baptiste Coudurier
            if (len > 0xffff)
803
                len = 0;
804 69ef9450 Fabrice Bellard
            *q++ = len >> 8;
805
            *q++ = len;
806 8b475508 Fabrice Bellard
            val = 0x80;
807
            /* data alignment indicator is required for subtitle data */
808 72415b2a Stefano Sabatini
            if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
809 8b475508 Fabrice Bellard
                val |= 0x04;
810
            *q++ = val;
811 700b9711 Måns Rullgård
            *q++ = flags;
812
            *q++ = header_len;
813 69ef9450 Fabrice Bellard
            if (pts != AV_NOPTS_VALUE) {
814 700b9711 Måns Rullgård
                write_pts(q, flags >> 6, pts);
815
                q += 5;
816
            }
817 8f14cdee Baptiste Coudurier
            if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
818 700b9711 Måns Rullgård
                write_pts(q, 1, dts);
819
                q += 5;
820 5dbafeb7 Fabrice Bellard
            }
821 f4bba201 Anuradha Suraparaju
            if (pes_extension && st->codec->codec_id == CODEC_ID_DIRAC) {
822
                flags = 0x01;  /* set PES_extension_flag_2 */
823
                *q++ = flags;
824
                *q++ = 0x80 | 0x01;  /* marker bit + extension length */
825
                /*
826
                * Set the stream id extension flag bit to 0 and
827
                * write the extended stream id
828
                */
829
                *q++ = 0x00 | 0x60;
830
            }
831 8b475508 Fabrice Bellard
            if (private_code != 0)
832
                *q++ = private_code;
833 69ef9450 Fabrice Bellard
            is_start = 0;
834 5dbafeb7 Fabrice Bellard
        }
835 8b475508 Fabrice Bellard
        /* header size */
836
        header_len = q - buf;
837
        /* data len */
838
        len = TS_PACKET_SIZE - header_len;
839 69ef9450 Fabrice Bellard
        if (len > payload_size)
840
            len = payload_size;
841 8b475508 Fabrice Bellard
        stuffing_len = TS_PACKET_SIZE - header_len - len;
842
        if (stuffing_len > 0) {
843
            /* add stuffing with AFC */
844
            if (buf[3] & 0x20) {
845
                /* stuffing already present: increase its size */
846
                afc_len = buf[4] + 1;
847
                memmove(buf + 4 + afc_len + stuffing_len,
848 115329f1 Diego Biurrun
                        buf + 4 + afc_len,
849 8b475508 Fabrice Bellard
                        header_len - (4 + afc_len));
850
                buf[4] += stuffing_len;
851
                memset(buf + 4 + afc_len, 0xff, stuffing_len);
852
            } else {
853
                /* add stuffing */
854
                memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
855
                buf[3] |= 0x20;
856
                buf[4] = stuffing_len - 1;
857
                if (stuffing_len >= 2) {
858
                    buf[5] = 0x00;
859
                    memset(buf + 6, 0xff, stuffing_len - 2);
860
                }
861
            }
862
        }
863
        memcpy(buf + TS_PACKET_SIZE - len, payload, len);
864 69ef9450 Fabrice Bellard
        payload += len;
865
        payload_size -= len;
866 77eb5504 Anton Khirnov
        avio_write(s->pb, buf, TS_PACKET_SIZE);
867 5dbafeb7 Fabrice Bellard
    }
868 b7f2fdde Anton Khirnov
    avio_flush(s->pb);
869 69ef9450 Fabrice Bellard
}
870
871 e928649b Michael Niedermayer
static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
872 69ef9450 Fabrice Bellard
{
873 e928649b Michael Niedermayer
    AVStream *st = s->streams[pkt->stream_index];
874 01d6bd52 Baptiste Coudurier
    int size = pkt->size;
875 e928649b Michael Niedermayer
    uint8_t *buf= pkt->data;
876 a57fb91c Baptiste Coudurier
    uint8_t *data= NULL;
877 69ef9450 Fabrice Bellard
    MpegTSWriteStream *ts_st = st->priv_data;
878 7082ea56 Baptiste Coudurier
    const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
879 f3ba7c54 Baptiste Coudurier
    int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
880
881
    if (pkt->pts != AV_NOPTS_VALUE)
882
        pts = pkt->pts + delay;
883
    if (pkt->dts != AV_NOPTS_VALUE)
884
        dts = pkt->dts + delay;
885 69ef9450 Fabrice Bellard
886 b69017af Baptiste Coudurier
    if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
887
        av_log(s, AV_LOG_ERROR, "first pts value must set\n");
888
        return -1;
889
    }
890
    ts_st->first_pts_check = 0;
891
892 e4358e70 Baptiste Coudurier
    if (st->codec->codec_id == CODEC_ID_H264) {
893 e17d77bb Baptiste Coudurier
        const uint8_t *p = buf, *buf_end = p+size;
894
        uint32_t state = -1;
895
896 a57fb91c Baptiste Coudurier
        if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
897 e17d77bb Baptiste Coudurier
            av_log(s, AV_LOG_ERROR, "h264 bitstream malformated, "
898
                   "no startcode found, use -vbsf h264_mp4toannexb\n");
899 a57fb91c Baptiste Coudurier
            return -1;
900
        }
901 e17d77bb Baptiste Coudurier
902
        do {
903
            p = ff_find_start_code(p, buf_end, &state);
904
            //av_log(s, AV_LOG_INFO, "nal %d\n", state & 0x1f);
905
        } while (p < buf_end && (state & 0x1f) != 9 &&
906
                 (state & 0x1f) != 5 && (state & 0x1f) != 1);
907
908
        if ((state & 0x1f) != 9) { // AUD NAL
909 a57fb91c Baptiste Coudurier
            data = av_malloc(pkt->size+6);
910
            if (!data)
911
                return -1;
912
            memcpy(data+6, pkt->data, pkt->size);
913
            AV_WB32(data, 0x00000001);
914
            data[4] = 0x09;
915 ef011e6d Baptiste Coudurier
            data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
916 a57fb91c Baptiste Coudurier
            buf  = data;
917
            size = pkt->size+6;
918
        }
919 8fdd542c Baptiste Coudurier
    } else if (st->codec->codec_id == CODEC_ID_AAC) {
920
        if (pkt->size < 2)
921
            return -1;
922
        if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
923
            ADTSContext *adts = ts_st->adts;
924
            int new_size;
925
            if (!adts) {
926
                av_log(s, AV_LOG_ERROR, "aac bitstream not in adts format "
927
                       "and extradata missing\n");
928
                return -1;
929
            }
930
            new_size = ADTS_HEADER_SIZE+adts->pce_size+pkt->size;
931
            if ((unsigned)new_size >= INT_MAX)
932
                return -1;
933
            data = av_malloc(new_size);
934
            if (!data)
935 2874c81c Stefano Sabatini
                return AVERROR(ENOMEM);
936 8fdd542c Baptiste Coudurier
            ff_adts_write_frame_header(adts, data, pkt->size, adts->pce_size);
937
            if (adts->pce_size) {
938
                memcpy(data+ADTS_HEADER_SIZE, adts->pce_data, adts->pce_size);
939
                adts->pce_size = 0;
940
            }
941
            memcpy(data+ADTS_HEADER_SIZE+adts->pce_size, pkt->data, pkt->size);
942
            buf = data;
943
            size = new_size;
944
        }
945 de34dc39 Baptiste Coudurier
    }
946
947 72415b2a Stefano Sabatini
    if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
948 e4358e70 Baptiste Coudurier
        // for video and subtitle, write a single pes packet
949
        mpegts_write_pes(s, st, buf, size, pts, dts);
950 24ac5052 Baptiste Coudurier
        av_free(data);
951 e4358e70 Baptiste Coudurier
        return 0;
952
    }
953
954 01d6bd52 Baptiste Coudurier
    if (ts_st->payload_index + size > DEFAULT_PES_PAYLOAD_SIZE) {
955
        mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
956
                         ts_st->payload_pts, ts_st->payload_dts);
957
        ts_st->payload_index = 0;
958 84df78b4 Baptiste Coudurier
    }
959
960 01d6bd52 Baptiste Coudurier
    if (!ts_st->payload_index) {
961
        ts_st->payload_pts = pts;
962
        ts_st->payload_dts = dts;
963 69ef9450 Fabrice Bellard
    }
964 a57fb91c Baptiste Coudurier
965 01d6bd52 Baptiste Coudurier
    memcpy(ts_st->payload + ts_st->payload_index, buf, size);
966
    ts_st->payload_index += size;
967
968 83c2bc7a Baptiste Coudurier
    av_free(data);
969
970 5dbafeb7 Fabrice Bellard
    return 0;
971
}
972
973
static int mpegts_write_end(AVFormatContext *s)
974
{
975
    MpegTSWrite *ts = s->priv_data;
976
    MpegTSWriteStream *ts_st;
977
    MpegTSService *service;
978
    AVStream *st;
979
    int i;
980
981
    /* flush current packets */
982
    for(i = 0; i < s->nb_streams; i++) {
983
        st = s->streams[i];
984
        ts_st = st->priv_data;
985 69ef9450 Fabrice Bellard
        if (ts_st->payload_index > 0) {
986
            mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
987 700b9711 Måns Rullgård
                             ts_st->payload_pts, ts_st->payload_dts);
988 5dbafeb7 Fabrice Bellard
        }
989 83c2bc7a Baptiste Coudurier
        av_freep(&ts_st->adts);
990 5dbafeb7 Fabrice Bellard
    }
991 b7f2fdde Anton Khirnov
    avio_flush(s->pb);
992 115329f1 Diego Biurrun
993 5dbafeb7 Fabrice Bellard
    for(i = 0; i < ts->nb_services; i++) {
994
        service = ts->services[i];
995
        av_freep(&service->provider_name);
996
        av_freep(&service->name);
997
        av_free(service);
998
    }
999
    av_free(ts->services);
1000
1001
    return 0;
1002
}
1003
1004 c6610a21 Diego Elio Pettenò
AVOutputFormat ff_mpegts_muxer = {
1005 5dbafeb7 Fabrice Bellard
    "mpegts",
1006 bde15e74 Stefano Sabatini
    NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1007 5dbafeb7 Fabrice Bellard
    "video/x-mpegts",
1008 d3ad044a Baptiste Coudurier
    "ts,m2t",
1009 5dbafeb7 Fabrice Bellard
    sizeof(MpegTSWrite),
1010
    CODEC_ID_MP2,
1011 69ef9450 Fabrice Bellard
    CODEC_ID_MPEG2VIDEO,
1012 5dbafeb7 Fabrice Bellard
    mpegts_write_header,
1013
    mpegts_write_packet,
1014
    mpegts_write_end,
1015 445996aa Georgi Chorbadzhiyski
    .priv_class = &mpegts_muxer_class,
1016 5dbafeb7 Fabrice Bellard
};