aboutsummaryrefslogtreecommitdiffstats
path: root/libavformat/mpegts.c
blob: 2947d960e8017e31c5a40a4d664a9a019f781688 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/*
 * MPEG2 transport stream (aka DVB) demux
 * Copyright (c) 2002 Fabrice Bellard.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#include "avformat.h"

#define TS_FEC_PACKET_SIZE 204
#define TS_PACKET_SIZE 188
#define NB_PID_MAX 8192

enum MpegTSState {
    MPEGTS_HEADER = 0,
    MPEGTS_PESHEADER_FILL,
    MPEGTS_PESHEADER_FLAGS,
    MPEGTS_PESHEADER_SIZE,
    MPEGTS_PESHEADER_READ,
    MPEGTS_PAYLOAD,
    MPEGTS_SKIP,
};

/* enough for PES header + length */
#define MAX_HEADER_SIZE 6

typedef struct MpegTSStream {
    int pid;
    enum MpegTSState state;
    int last_cc; /* last cc code (-1 if first packet) */
    /* used to get the format */
    int header_size;
    int payload_size;
    int pes_header_size;
    AVStream *st;
    unsigned char header[MAX_HEADER_SIZE];
} MpegTSStream;

typedef struct MpegTSContext {
    int raw_packet_size; /* raw packet size, including FEC if present */
    MpegTSStream *pids[NB_PID_MAX];
} MpegTSContext;

/* autodetect fec presence. Must have at least 1024 bytes  */
static int get_packet_size(const unsigned char *buf, int size)
{
    int i;

    if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
        return -1;
    for(i=0;i<5;i++) {
        if (buf[i * TS_PACKET_SIZE] != 0x47)
            goto try_fec;
    }
    return TS_PACKET_SIZE;
 try_fec:
    for(i=0;i<5;i++) {
        if (buf[i * TS_FEC_PACKET_SIZE] != 0x47)
            return -1;
    }
    return TS_FEC_PACKET_SIZE;
}

static int mpegts_probe(AVProbeData *p)
{
    int size;
    size = get_packet_size(p->buf, p->buf_size);
    if (size < 0)
        return 0;
    return AVPROBE_SCORE_MAX;
}

static int mpegts_read_header(AVFormatContext *s,
                              AVFormatParameters *ap)
{
    MpegTSContext *ts = s->priv_data;
    ByteIOContext *pb = &s->pb;
    unsigned char buf[1024];
    int len;
    INT64 pos;

    /* read the first 1024 bytes to get packet size */
    pos = url_ftell(pb);
    len = get_buffer(pb, buf, sizeof(buf));
    if (len != sizeof(buf))
        goto fail;
    ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
    if (ts->raw_packet_size <= 0)
        goto fail;
    /* go again to the start */
    url_fseek(pb, pos, SEEK_SET);
    return 0;
 fail:
    return -1;
}

/* return non zero if a packet could be constructed */
static int mpegts_push_data(AVFormatContext *s, MpegTSStream *tss,
                            AVPacket *pkt,
                            const unsigned char *buf, int buf_size, int is_start)
{
    AVStream *st;
    const unsigned char *p;
    int len, code, codec_type, codec_id;

    if (is_start) {
        tss->state = MPEGTS_HEADER;
        tss->header_size = 0;
    }
    p = buf;
    while (buf_size > 0) {
        len = buf_size;
        switch(tss->state) {
        case MPEGTS_HEADER:
            if (len > MAX_HEADER_SIZE - tss->header_size)
                len = MAX_HEADER_SIZE - tss->header_size;
            memcpy(tss->header, p, len);
            tss->header_size += len;
            p += len;
            buf_size -= len;
            if (tss->header_size == MAX_HEADER_SIZE) {
                /* we got all the PES or section header. We can now
                   decide */
#if 0
                av_hex_dump(tss->header, tss->header_size);
#endif
                if (tss->header[0] == 0x00 && tss->header[1] == 0x00 &&
                    tss->header[2] == 0x01) {
                    /* it must be an mpeg2 PES stream */
                    /* XXX: add AC3 support */
                    code = tss->header[3] | 0x100;
                    if (!((code >= 0x1c0 && code <= 0x1df) ||
                          (code >= 0x1e0 && code <= 0x1ef)))
                        goto skip;
                    if (!tss->st) {
                        /* allocate stream */
                        if (code >= 0x1c0 && code <= 0x1df) {
                            codec_type = CODEC_TYPE_AUDIO;
                            codec_id = CODEC_ID_MP2;
                        } else {
                            codec_type = CODEC_TYPE_VIDEO;
                            codec_id = CODEC_ID_MPEG1VIDEO;
                        }
                        st = av_new_stream(s, tss->pid);
                        if (st) {
                            st->priv_data = tss;
                            st->codec.codec_type = codec_type;
                            st->codec.codec_id = codec_id;
                            tss->st = st;
                        }
                    }
                    tss->state = MPEGTS_PESHEADER_FILL;
                    tss->payload_size = (tss->header[4] << 8) | tss->header[5];
                    if (tss->payload_size == 0)
                        tss->payload_size = 65536;
                } else {
                    /* otherwise, it should be a table */
                    /* skip packet */
                skip:
                    tss->state = MPEGTS_SKIP;
                    continue;
                }
            }
            break;
            /**********************************************/
            /* PES packing parsing */
        case MPEGTS_PESHEADER_FILL:
            /* skip filling */
            code = *p++;
            buf_size--;
            tss->payload_size--;
            if (code != 0xff) {
                if ((code & 0xc0) != 0x80)
                    goto skip;
                tss->state = MPEGTS_PESHEADER_FLAGS;
            }
            break;
        case MPEGTS_PESHEADER_FLAGS:
            code = *p++;
            buf_size--;
            tss->payload_size--;
            tss->state = MPEGTS_PESHEADER_SIZE;
            break;
        case MPEGTS_PESHEADER_SIZE:
            tss->pes_header_size = *p++;
            buf_size--;
            tss->payload_size--;
            tss->state = MPEGTS_PESHEADER_READ;
            break;
        case MPEGTS_PESHEADER_READ:
            /* currently we do nothing except skipping */
            if (len > tss->pes_header_size)
                len = tss->pes_header_size;
            p += len;
            buf_size -= len;
            tss->pes_header_size -= len;
            tss->payload_size -= len;
            if (tss->pes_header_size == 0)
                tss->state = MPEGTS_PAYLOAD;
            break;
        case MPEGTS_PAYLOAD:
            if (len > tss->payload_size)
                len = tss->payload_size;
            if (len > 0) {
                if (tss->st && av_new_packet(pkt, buf_size) == 0) {
                    memcpy(pkt->data, p, buf_size);
                    pkt->stream_index = tss->st->index;
                    return 1;
                }
                tss->payload_size -= len;
            }
            buf_size = 0;
            break;
        case MPEGTS_SKIP:
            buf_size = 0;
            break;
        }
    }
    return 0;
}

static int mpegts_read_packet(AVFormatContext *s,
                              AVPacket *pkt)
{
    MpegTSContext *ts = s->priv_data;
    MpegTSStream *tss;
    ByteIOContext *pb = &s->pb;
    unsigned char packet[TS_FEC_PACKET_SIZE];
    int len, pid, cc, cc_ok, afc;
    const unsigned char *p;
    
    for(;;) {
        len = get_buffer(pb, packet, ts->raw_packet_size);
        if (len != ts->raw_packet_size)
            return AVERROR_IO;
        /* check paquet sync byte */
        /* XXX: accept to resync ? */
        if (packet[0] != 0x47)
            return AVERROR_INVALIDDATA;
        
        pid = ((packet[1] & 0x1f) << 8) | packet[2];
        tss = ts->pids[pid];
        if (tss == NULL) {
            /* if no pid found, then add a pid context */
            tss = av_mallocz(sizeof(MpegTSStream));
            if (!tss) 
                continue;
            ts->pids[pid] = tss;
            tss->pid = pid;
            tss->last_cc = -1;
            //            printf("new pid=0x%x\n", pid);
        }

        /* continuity check (currently not used) */
        cc = (packet[3] & 0xf);
        cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
        tss->last_cc = cc;
        
        /* skip adaptation field */
        afc = (packet[3] >> 4) & 3;
        p = packet + 4;
        if (afc == 0) /* reserved value */
            continue;
        if (afc == 2) /* adaptation field only */
            continue;
        if (afc == 3) {
            /* skip adapation field */
            p += p[0] + 1;
        }
        /* if past the end of packet, ignore */
        if (p >= packet + TS_PACKET_SIZE)
            continue;
    
        if (mpegts_push_data(s, tss, pkt, p, TS_PACKET_SIZE - (p - packet), 
                             packet[1] & 0x40))
            break;
    }
    return 0;
}

static int mpegts_read_close(AVFormatContext *s)
{
    MpegTSContext *ts = s->priv_data;
    int i;
    for(i=0;i<NB_PID_MAX;i++)
        av_free(ts->pids[i]);
    return 0;
}

AVInputFormat mpegts_demux = {
    "mpegts",
    "MPEG2 transport stream format",
    sizeof(MpegTSContext),
    mpegts_probe,
    mpegts_read_header,
    mpegts_read_packet,
    mpegts_read_close,
    .flags = AVFMT_NOHEADER | AVFMT_SHOW_IDS,
};

int mpegts_init(void)
{
    av_register_input_format(&mpegts_demux);
    return 0;
}