aboutsummaryrefslogtreecommitdiff
path: root/src/plugins/ffmpeg/libavformat
diff options
context:
space:
mode:
Diffstat (limited to 'src/plugins/ffmpeg/libavformat')
-rw-r--r--src/plugins/ffmpeg/libavformat/4xm.c337
-rw-r--r--src/plugins/ffmpeg/libavformat/Makefile205
-rw-r--r--src/plugins/ffmpeg/libavformat/adtsenc.c118
-rw-r--r--src/plugins/ffmpeg/libavformat/aiff.c464
-rw-r--r--src/plugins/ffmpeg/libavformat/allformats.c191
-rw-r--r--src/plugins/ffmpeg/libavformat/amr.c193
-rw-r--r--src/plugins/ffmpeg/libavformat/apc.c90
-rw-r--r--src/plugins/ffmpeg/libavformat/ape.c522
-rw-r--r--src/plugins/ffmpeg/libavformat/asf-enc.c855
-rw-r--r--src/plugins/ffmpeg/libavformat/asf.c1091
-rw-r--r--src/plugins/ffmpeg/libavformat/asf.h289
-rw-r--r--src/plugins/ffmpeg/libavformat/asfcrypt.c173
-rw-r--r--src/plugins/ffmpeg/libavformat/asfcrypt.h29
-rw-r--r--src/plugins/ffmpeg/libavformat/au.c203
-rw-r--r--src/plugins/ffmpeg/libavformat/avc.c135
-rw-r--r--src/plugins/ffmpeg/libavformat/avc.h32
-rw-r--r--src/plugins/ffmpeg/libavformat/avformat.h1087
-rw-r--r--src/plugins/ffmpeg/libavformat/avi.h37
-rw-r--r--src/plugins/ffmpeg/libavformat/avidec.c1096
-rw-r--r--src/plugins/ffmpeg/libavformat/avienc.c607
-rw-r--r--src/plugins/ffmpeg/libavformat/avio.c232
-rw-r--r--src/plugins/ffmpeg/libavformat/avio.h369
-rw-r--r--src/plugins/ffmpeg/libavformat/aviobuf.c839
-rw-r--r--src/plugins/ffmpeg/libavformat/avisynth.c222
-rw-r--r--src/plugins/ffmpeg/libavformat/avs.c226
-rw-r--r--src/plugins/ffmpeg/libavformat/bethsoftvid.c233
-rw-r--r--src/plugins/ffmpeg/libavformat/bfi.c167
-rw-r--r--src/plugins/ffmpeg/libavformat/c93.c198
-rw-r--r--src/plugins/ffmpeg/libavformat/crcenc.c68
-rw-r--r--src/plugins/ffmpeg/libavformat/cutils.c186
-rw-r--r--src/plugins/ffmpeg/libavformat/daud.c60
-rw-r--r--src/plugins/ffmpeg/libavformat/dsicin.c221
-rw-r--r--src/plugins/ffmpeg/libavformat/dv.c452
-rw-r--r--src/plugins/ffmpeg/libavformat/dv.h44
-rw-r--r--src/plugins/ffmpeg/libavformat/dvenc.c415
-rw-r--r--src/plugins/ffmpeg/libavformat/dxa.c212
-rw-r--r--src/plugins/ffmpeg/libavformat/eacdata.c100
-rw-r--r--src/plugins/ffmpeg/libavformat/electronicarts.c488
-rw-r--r--src/plugins/ffmpeg/libavformat/ffm.h56
-rw-r--r--src/plugins/ffmpeg/libavformat/ffmdec.c487
-rw-r--r--src/plugins/ffmpeg/libavformat/ffmenc.c250
-rw-r--r--src/plugins/ffmpeg/libavformat/file.c120
-rw-r--r--src/plugins/ffmpeg/libavformat/flic.c208
-rw-r--r--src/plugins/ffmpeg/libavformat/flv.h112
-rw-r--r--src/plugins/ffmpeg/libavformat/flvdec.c429
-rw-r--r--src/plugins/ffmpeg/libavformat/flvenc.c392
-rw-r--r--src/plugins/ffmpeg/libavformat/framecrcenc.c47
-rw-r--r--src/plugins/ffmpeg/libavformat/framehook.c120
-rw-r--r--src/plugins/ffmpeg/libavformat/framehook.h52
-rw-r--r--src/plugins/ffmpeg/libavformat/gif.c419
-rw-r--r--src/plugins/ffmpeg/libavformat/gxf.c503
-rw-r--r--src/plugins/ffmpeg/libavformat/gxf.h53
-rw-r--r--src/plugins/ffmpeg/libavformat/gxfenc.c828
-rw-r--r--src/plugins/ffmpeg/libavformat/http.c355
-rw-r--r--src/plugins/ffmpeg/libavformat/idcin.c290
-rw-r--r--src/plugins/ffmpeg/libavformat/idroq.c280
-rw-r--r--src/plugins/ffmpeg/libavformat/iff.c200
-rw-r--r--src/plugins/ffmpeg/libavformat/img2.c427
-rw-r--r--src/plugins/ffmpeg/libavformat/ipmovie.c617
-rw-r--r--src/plugins/ffmpeg/libavformat/isom.c258
-rw-r--r--src/plugins/ffmpeg/libavformat/isom.h43
-rw-r--r--src/plugins/ffmpeg/libavformat/libnut.c310
-rw-r--r--src/plugins/ffmpeg/libavformat/lmlm4.c126
-rw-r--r--src/plugins/ffmpeg/libavformat/matroska.c85
-rw-r--r--src/plugins/ffmpeg/libavformat/matroska.h231
-rw-r--r--src/plugins/ffmpeg/libavformat/matroskadec.c3202
-rw-r--r--src/plugins/ffmpeg/libavformat/matroskaenc.c847
-rw-r--r--src/plugins/ffmpeg/libavformat/mm.c191
-rw-r--r--src/plugins/ffmpeg/libavformat/mmf.c323
-rw-r--r--src/plugins/ffmpeg/libavformat/mov.c1925
-rw-r--r--src/plugins/ffmpeg/libavformat/movenc.c1788
-rw-r--r--src/plugins/ffmpeg/libavformat/mp3.c686
-rw-r--r--src/plugins/ffmpeg/libavformat/mpc.c230
-rw-r--r--src/plugins/ffmpeg/libavformat/mpc8.c245
-rw-r--r--src/plugins/ffmpeg/libavformat/mpeg.c590
-rw-r--r--src/plugins/ffmpeg/libavformat/mpeg.h72
-rw-r--r--src/plugins/ffmpeg/libavformat/mpegenc.c1294
-rw-r--r--src/plugins/ffmpeg/libavformat/mpegts.c1522
-rw-r--r--src/plugins/ffmpeg/libavformat/mpegts.h69
-rw-r--r--src/plugins/ffmpeg/libavformat/mpegtsenc.c696
-rw-r--r--src/plugins/ffmpeg/libavformat/mpjpeg.c67
-rw-r--r--src/plugins/ffmpeg/libavformat/msnwc_tcp.c140
-rw-r--r--src/plugins/ffmpeg/libavformat/mtv.c181
-rw-r--r--src/plugins/ffmpeg/libavformat/mvi.c135
-rw-r--r--src/plugins/ffmpeg/libavformat/mxf.c1074
-rw-r--r--src/plugins/ffmpeg/libavformat/network.h69
-rw-r--r--src/plugins/ffmpeg/libavformat/nsvdec.c763
-rw-r--r--src/plugins/ffmpeg/libavformat/nut.c81
-rw-r--r--src/plugins/ffmpeg/libavformat/nut.h115
-rw-r--r--src/plugins/ffmpeg/libavformat/nutdec.c920
-rw-r--r--src/plugins/ffmpeg/libavformat/nutenc.c825
-rw-r--r--src/plugins/ffmpeg/libavformat/nuv.c252
-rw-r--r--src/plugins/ffmpeg/libavformat/oggdec.c586
-rw-r--r--src/plugins/ffmpeg/libavformat/oggdec.h90
-rw-r--r--src/plugins/ffmpeg/libavformat/oggenc.c292
-rw-r--r--src/plugins/ffmpeg/libavformat/oggparseflac.c98
-rw-r--r--src/plugins/ffmpeg/libavformat/oggparseogm.c178
-rw-r--r--src/plugins/ffmpeg/libavformat/oggparsespeex.c61
-rw-r--r--src/plugins/ffmpeg/libavformat/oggparsetheora.c138
-rw-r--r--src/plugins/ffmpeg/libavformat/oggparsevorbis.c226
-rw-r--r--src/plugins/ffmpeg/libavformat/oma.c200
-rw-r--r--src/plugins/ffmpeg/libavformat/os_support.c155
-rw-r--r--src/plugins/ffmpeg/libavformat/os_support.h95
-rw-r--r--src/plugins/ffmpeg/libavformat/psxstr.c268
-rw-r--r--src/plugins/ffmpeg/libavformat/pva.c211
-rw-r--r--src/plugins/ffmpeg/libavformat/qtpalette.h313
-rw-r--r--src/plugins/ffmpeg/libavformat/raw.c997
-rw-r--r--src/plugins/ffmpeg/libavformat/raw.h30
-rw-r--r--src/plugins/ffmpeg/libavformat/riff.c434
-rw-r--r--src/plugins/ffmpeg/libavformat/riff.h54
-rw-r--r--src/plugins/ffmpeg/libavformat/rl2.c299
-rw-r--r--src/plugins/ffmpeg/libavformat/rm.h108
-rw-r--r--src/plugins/ffmpeg/libavformat/rmdec.c798
-rw-r--r--src/plugins/ffmpeg/libavformat/rmenc.c444
-rw-r--r--src/plugins/ffmpeg/libavformat/rpl.c356
-rw-r--r--src/plugins/ffmpeg/libavformat/rtp.c133
-rw-r--r--src/plugins/ffmpeg/libavformat/rtp.h113
-rw-r--r--src/plugins/ffmpeg/libavformat/rtp_aac.c88
-rw-r--r--src/plugins/ffmpeg/libavformat/rtp_aac.h27
-rw-r--r--src/plugins/ffmpeg/libavformat/rtp_h264.c416
-rw-r--r--src/plugins/ffmpeg/libavformat/rtp_h264.h30
-rw-r--r--src/plugins/ffmpeg/libavformat/rtp_internal.h131
-rw-r--r--src/plugins/ffmpeg/libavformat/rtp_mpv.c118
-rw-r--r--src/plugins/ffmpeg/libavformat/rtp_mpv.h27
-rw-r--r--src/plugins/ffmpeg/libavformat/rtpdec.c537
-rw-r--r--src/plugins/ffmpeg/libavformat/rtpenc.c360
-rw-r--r--src/plugins/ffmpeg/libavformat/rtpenc_h264.c78
-rw-r--r--src/plugins/ffmpeg/libavformat/rtpproto.c317
-rw-r--r--src/plugins/ffmpeg/libavformat/rtsp.c1538
-rw-r--r--src/plugins/ffmpeg/libavformat/rtsp.h97
-rw-r--r--src/plugins/ffmpeg/libavformat/rtspcodes.h40
-rw-r--r--src/plugins/ffmpeg/libavformat/sdp.c323
-rw-r--r--src/plugins/ffmpeg/libavformat/segafilm.c292
-rw-r--r--src/plugins/ffmpeg/libavformat/sierravmd.c300
-rw-r--r--src/plugins/ffmpeg/libavformat/siff.c236
-rw-r--r--src/plugins/ffmpeg/libavformat/smacker.c345
-rw-r--r--src/plugins/ffmpeg/libavformat/sol.c152
-rw-r--r--src/plugins/ffmpeg/libavformat/swf.h96
-rw-r--r--src/plugins/ffmpeg/libavformat/swfdec.c193
-rw-r--r--src/plugins/ffmpeg/libavformat/swfenc.c533
-rw-r--r--src/plugins/ffmpeg/libavformat/tcp.c194
-rw-r--r--src/plugins/ffmpeg/libavformat/thp.c197
-rw-r--r--src/plugins/ffmpeg/libavformat/tiertexseq.c313
-rw-r--r--src/plugins/ffmpeg/libavformat/tta.c150
-rw-r--r--src/plugins/ffmpeg/libavformat/txd.c98
-rw-r--r--src/plugins/ffmpeg/libavformat/udp.c496
-rw-r--r--src/plugins/ffmpeg/libavformat/utils.c3216
-rw-r--r--src/plugins/ffmpeg/libavformat/vc1test.c112
-rw-r--r--src/plugins/ffmpeg/libavformat/voc.c36
-rw-r--r--src/plugins/ffmpeg/libavformat/voc.h51
-rw-r--r--src/plugins/ffmpeg/libavformat/vocdec.c145
-rw-r--r--src/plugins/ffmpeg/libavformat/vocenc.c103
-rw-r--r--src/plugins/ffmpeg/libavformat/wav.c285
-rw-r--r--src/plugins/ffmpeg/libavformat/wc3movie.c394
-rw-r--r--src/plugins/ffmpeg/libavformat/westwood.c392
-rw-r--r--src/plugins/ffmpeg/libavformat/wv.c231
-rw-r--r--src/plugins/ffmpeg/libavformat/xa.c116
-rw-r--r--src/plugins/ffmpeg/libavformat/yuv4mpeg.c395
158 files changed, 0 insertions, 57961 deletions
diff --git a/src/plugins/ffmpeg/libavformat/4xm.c b/src/plugins/ffmpeg/libavformat/4xm.c
deleted file mode 100644
index 25c2080..0000000
--- a/src/plugins/ffmpeg/libavformat/4xm.c
+++ /dev/null
@@ -1,337 +0,0 @@
1/*
2 * 4X Technologies .4xm File Demuxer (no muxer)
3 * Copyright (c) 2003 The ffmpeg Project
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/**
23 * @file 4xm.c
24 * 4X Technologies file demuxer
25 * by Mike Melanson (melanson@pcisys.net)
26 * for more information on the .4xm file format, visit:
27 * http://www.pcisys.net/~melanson/codecs/
28 */
29
30#include "avformat.h"
31
32#define RIFF_TAG MKTAG('R', 'I', 'F', 'F')
33#define _4XMV_TAG MKTAG('4', 'X', 'M', 'V')
34#define LIST_TAG MKTAG('L', 'I', 'S', 'T')
35#define HEAD_TAG MKTAG('H', 'E', 'A', 'D')
36#define TRK__TAG MKTAG('T', 'R', 'K', '_')
37#define MOVI_TAG MKTAG('M', 'O', 'V', 'I')
38#define VTRK_TAG MKTAG('V', 'T', 'R', 'K')
39#define STRK_TAG MKTAG('S', 'T', 'R', 'K')
40#define std__TAG MKTAG('s', 't', 'd', '_')
41#define name_TAG MKTAG('n', 'a', 'm', 'e')
42#define vtrk_TAG MKTAG('v', 't', 'r', 'k')
43#define strk_TAG MKTAG('s', 't', 'r', 'k')
44#define ifrm_TAG MKTAG('i', 'f', 'r', 'm')
45#define pfrm_TAG MKTAG('p', 'f', 'r', 'm')
46#define cfrm_TAG MKTAG('c', 'f', 'r', 'm')
47#define ifr2_TAG MKTAG('i', 'f', 'r', '2')
48#define pfr2_TAG MKTAG('p', 'f', 'r', '2')
49#define cfr2_TAG MKTAG('c', 'f', 'r', '2')
50#define snd__TAG MKTAG('s', 'n', 'd', '_')
51
52#define vtrk_SIZE 0x44
53#define strk_SIZE 0x28
54
55#define GET_LIST_HEADER() \
56 fourcc_tag = get_le32(pb); \
57 size = get_le32(pb); \
58 if (fourcc_tag != LIST_TAG) \
59 return AVERROR_INVALIDDATA; \
60 fourcc_tag = get_le32(pb);
61
62typedef struct AudioTrack {
63 int sample_rate;
64 int bits;
65 int channels;
66 int stream_index;
67 int adpcm;
68} AudioTrack;
69
70typedef struct FourxmDemuxContext {
71 int width;
72 int height;
73 int video_stream_index;
74 int track_count;
75 AudioTrack *tracks;
76 int selected_track;
77
78 int64_t audio_pts;
79 int64_t video_pts;
80 float fps;
81} FourxmDemuxContext;
82
83static int fourxm_probe(AVProbeData *p)
84{
85 if ((AV_RL32(&p->buf[0]) != RIFF_TAG) ||
86 (AV_RL32(&p->buf[8]) != _4XMV_TAG))
87 return 0;
88
89 return AVPROBE_SCORE_MAX;
90}
91
92static int fourxm_read_header(AVFormatContext *s,
93 AVFormatParameters *ap)
94{
95 ByteIOContext *pb = s->pb;
96 unsigned int fourcc_tag;
97 unsigned int size;
98 int header_size;
99 FourxmDemuxContext *fourxm = s->priv_data;
100 unsigned char *header;
101 int i;
102 int current_track = -1;
103 AVStream *st;
104
105 fourxm->track_count = 0;
106 fourxm->tracks = NULL;
107 fourxm->selected_track = 0;
108 fourxm->fps = 1.0;
109
110 /* skip the first 3 32-bit numbers */
111 url_fseek(pb, 12, SEEK_CUR);
112
113 /* check for LIST-HEAD */
114 GET_LIST_HEADER();
115 header_size = size - 4;
116 if (fourcc_tag != HEAD_TAG)
117 return AVERROR_INVALIDDATA;
118
119 /* allocate space for the header and load the whole thing */
120 header = av_malloc(header_size);
121 if (!header)
122 return AVERROR(ENOMEM);
123 if (get_buffer(pb, header, header_size) != header_size)
124 return AVERROR(EIO);
125
126 /* take the lazy approach and search for any and all vtrk and strk chunks */
127 for (i = 0; i < header_size - 8; i++) {
128 fourcc_tag = AV_RL32(&header[i]);
129 size = AV_RL32(&header[i + 4]);
130
131 if (fourcc_tag == std__TAG) {
132 fourxm->fps = av_int2flt(AV_RL32(&header[i + 12]));
133 } else if (fourcc_tag == vtrk_TAG) {
134 /* check that there is enough data */
135 if (size != vtrk_SIZE) {
136 av_free(header);
137 return AVERROR_INVALIDDATA;
138 }
139 fourxm->width = AV_RL32(&header[i + 36]);
140 fourxm->height = AV_RL32(&header[i + 40]);
141
142 /* allocate a new AVStream */
143 st = av_new_stream(s, 0);
144 if (!st)
145 return AVERROR(ENOMEM);
146 av_set_pts_info(st, 60, 1, fourxm->fps);
147
148 fourxm->video_stream_index = st->index;
149
150 st->codec->codec_type = CODEC_TYPE_VIDEO;
151 st->codec->codec_id = CODEC_ID_4XM;
152 st->codec->extradata_size = 4;
153 st->codec->extradata = av_malloc(4);
154 AV_WL32(st->codec->extradata, AV_RL32(&header[i + 16]));
155 st->codec->width = fourxm->width;
156 st->codec->height = fourxm->height;
157
158 i += 8 + size;
159 } else if (fourcc_tag == strk_TAG) {
160 /* check that there is enough data */
161 if (size != strk_SIZE) {
162 av_free(header);
163 return AVERROR_INVALIDDATA;
164 }
165 current_track = AV_RL32(&header[i + 8]);
166 if (current_track + 1 > fourxm->track_count) {
167 fourxm->track_count = current_track + 1;
168 if((unsigned)fourxm->track_count >= UINT_MAX / sizeof(AudioTrack))
169 return -1;
170 fourxm->tracks = av_realloc(fourxm->tracks,
171 fourxm->track_count * sizeof(AudioTrack));
172 if (!fourxm->tracks) {
173 av_free(header);
174 return AVERROR(ENOMEM);
175 }
176 }
177 fourxm->tracks[current_track].adpcm = AV_RL32(&header[i + 12]);
178 fourxm->tracks[current_track].channels = AV_RL32(&header[i + 36]);
179 fourxm->tracks[current_track].sample_rate = AV_RL32(&header[i + 40]);
180 fourxm->tracks[current_track].bits = AV_RL32(&header[i + 44]);
181 i += 8 + size;
182
183 /* allocate a new AVStream */
184 st = av_new_stream(s, current_track);
185 if (!st)
186 return AVERROR(ENOMEM);
187
188 av_set_pts_info(st, 60, 1, fourxm->tracks[current_track].sample_rate);
189
190 fourxm->tracks[current_track].stream_index = st->index;
191
192 st->codec->codec_type = CODEC_TYPE_AUDIO;
193 st->codec->codec_tag = 0;
194 st->codec->channels = fourxm->tracks[current_track].channels;
195 st->codec->sample_rate = fourxm->tracks[current_track].sample_rate;
196 st->codec->bits_per_sample = fourxm->tracks[current_track].bits;
197 st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *
198 st->codec->bits_per_sample;
199 st->codec->block_align = st->codec->channels * st->codec->bits_per_sample;
200 if (fourxm->tracks[current_track].adpcm)
201 st->codec->codec_id = CODEC_ID_ADPCM_4XM;
202 else if (st->codec->bits_per_sample == 8)
203 st->codec->codec_id = CODEC_ID_PCM_U8;
204 else
205 st->codec->codec_id = CODEC_ID_PCM_S16LE;
206 }
207 }
208
209 av_free(header);
210
211 /* skip over the LIST-MOVI chunk (which is where the stream should be */
212 GET_LIST_HEADER();
213 if (fourcc_tag != MOVI_TAG)
214 return AVERROR_INVALIDDATA;
215
216 /* initialize context members */
217 fourxm->video_pts = -1; /* first frame will push to 0 */
218 fourxm->audio_pts = 0;
219
220 return 0;
221}
222
223static int fourxm_read_packet(AVFormatContext *s,
224 AVPacket *pkt)
225{
226 FourxmDemuxContext *fourxm = s->priv_data;
227 ByteIOContext *pb = s->pb;
228 unsigned int fourcc_tag;
229 unsigned int size, out_size;
230 int ret = 0;
231 int track_number;
232 int packet_read = 0;
233 unsigned char header[8];
234 int audio_frame_count;
235
236 while (!packet_read) {
237
238 if ((ret = get_buffer(s->pb, header, 8)) < 0)
239 return ret;
240 fourcc_tag = AV_RL32(&header[0]);
241 size = AV_RL32(&header[4]);
242 if (url_feof(pb))
243 return AVERROR(EIO);
244 switch (fourcc_tag) {
245
246 case LIST_TAG:
247 /* this is a good time to bump the video pts */
248 fourxm->video_pts ++;
249
250 /* skip the LIST-* tag and move on to the next fourcc */
251 get_le32(pb);
252 break;
253
254 case ifrm_TAG:
255 case pfrm_TAG:
256 case cfrm_TAG:
257 case ifr2_TAG:
258 case pfr2_TAG:
259 case cfr2_TAG:
260 {
261
262 /* allocate 8 more bytes than 'size' to account for fourcc
263 * and size */
264 if (size + 8 < size || av_new_packet(pkt, size + 8))
265 return AVERROR(EIO);
266 pkt->stream_index = fourxm->video_stream_index;
267 pkt->pts = fourxm->video_pts;
268 pkt->pos = url_ftell(s->pb);
269 memcpy(pkt->data, header, 8);
270 ret = get_buffer(s->pb, &pkt->data[8], size);
271
272 if (ret < 0)
273 av_free_packet(pkt);
274 else
275 packet_read = 1;
276 break;
277 }
278
279 case snd__TAG:
280 track_number = get_le32(pb);
281 out_size= get_le32(pb);
282 size-=8;
283
284 if (track_number == fourxm->selected_track) {
285 ret= av_get_packet(s->pb, pkt, size);
286 if(ret<0)
287 return AVERROR(EIO);
288 pkt->stream_index =
289 fourxm->tracks[fourxm->selected_track].stream_index;
290 pkt->pts = fourxm->audio_pts;
291 packet_read = 1;
292
293 /* pts accounting */
294 audio_frame_count = size;
295 if (fourxm->tracks[fourxm->selected_track].adpcm)
296 audio_frame_count -=
297 2 * (fourxm->tracks[fourxm->selected_track].channels);
298 audio_frame_count /=
299 fourxm->tracks[fourxm->selected_track].channels;
300 if (fourxm->tracks[fourxm->selected_track].adpcm)
301 audio_frame_count *= 2;
302 else
303 audio_frame_count /=
304 (fourxm->tracks[fourxm->selected_track].bits / 8);
305 fourxm->audio_pts += audio_frame_count;
306
307 } else {
308 url_fseek(pb, size, SEEK_CUR);
309 }
310 break;
311
312 default:
313 url_fseek(pb, size, SEEK_CUR);
314 break;
315 }
316 }
317 return ret;
318}
319
320static int fourxm_read_close(AVFormatContext *s)
321{
322 FourxmDemuxContext *fourxm = s->priv_data;
323
324 av_free(fourxm->tracks);
325
326 return 0;
327}
328
329AVInputFormat fourxm_demuxer = {
330 "4xm",
331 NULL_IF_CONFIG_SMALL("4X Technologies format"),
332 sizeof(FourxmDemuxContext),
333 fourxm_probe,
334 fourxm_read_header,
335 fourxm_read_packet,
336 fourxm_read_close,
337};
diff --git a/src/plugins/ffmpeg/libavformat/Makefile b/src/plugins/ffmpeg/libavformat/Makefile
deleted file mode 100644
index 1151439..0000000
--- a/src/plugins/ffmpeg/libavformat/Makefile
+++ /dev/null
@@ -1,205 +0,0 @@
1include $(SUBDIR)../config.mak
2
3NAME = avformat
4FFLIBS = avcodec avutil
5
6OBJS = allformats.o cutils.o os_support.o sdp.o utils.o
7
8HEADERS = avformat.h avio.h rtsp.h rtspcodes.h
9
10# muxers/demuxers
11OBJS-$(CONFIG_AAC_DEMUXER) += raw.o
12OBJS-$(CONFIG_AC3_DEMUXER) += raw.o
13OBJS-$(CONFIG_AC3_MUXER) += raw.o
14OBJS-$(CONFIG_ADTS_MUXER) += adtsenc.o
15OBJS-$(CONFIG_AIFF_DEMUXER) += aiff.o riff.o raw.o
16OBJS-$(CONFIG_AIFF_MUXER) += aiff.o riff.o
17OBJS-$(CONFIG_AMR_DEMUXER) += amr.o
18OBJS-$(CONFIG_AMR_MUXER) += amr.o
19OBJS-$(CONFIG_APC_DEMUXER) += apc.o
20OBJS-$(CONFIG_APE_DEMUXER) += ape.o
21OBJS-$(CONFIG_ASF_DEMUXER) += asf.o asfcrypt.o riff.o
22OBJS-$(CONFIG_ASF_MUXER) += asf-enc.o riff.o
23OBJS-$(CONFIG_ASF_STREAM_MUXER) += asf-enc.o riff.o
24OBJS-$(CONFIG_AU_DEMUXER) += au.o raw.o
25OBJS-$(CONFIG_AU_MUXER) += au.o
26OBJS-$(CONFIG_AVI_DEMUXER) += avidec.o riff.o
27OBJS-$(CONFIG_AVI_MUXER) += avienc.o riff.o
28OBJS-$(CONFIG_AVISYNTH) += avisynth.o
29OBJS-$(CONFIG_AVM2_MUXER) += swfenc.o
30OBJS-$(CONFIG_AVS_DEMUXER) += avs.o vocdec.o voc.o
31OBJS-$(CONFIG_BETHSOFTVID_DEMUXER) += bethsoftvid.o
32OBJS-$(CONFIG_BFI_DEMUXER) += bfi.o
33OBJS-$(CONFIG_C93_DEMUXER) += c93.o vocdec.o voc.o
34OBJS-$(CONFIG_CRC_MUXER) += crcenc.o
35OBJS-$(CONFIG_DAUD_DEMUXER) += daud.o
36OBJS-$(CONFIG_DIRAC_DEMUXER) += raw.o
37OBJS-$(CONFIG_DIRAC_MUXER) += raw.o
38OBJS-$(CONFIG_DSICIN_DEMUXER) += dsicin.o
39OBJS-$(CONFIG_DTS_DEMUXER) += raw.o
40OBJS-$(CONFIG_DTS_MUXER) += raw.o
41OBJS-$(CONFIG_DV_DEMUXER) += dv.o
42OBJS-$(CONFIG_DV_MUXER) += dvenc.o
43OBJS-$(CONFIG_DXA_DEMUXER) += dxa.o riff.o
44OBJS-$(CONFIG_EA_CDATA_DEMUXER) += eacdata.o
45OBJS-$(CONFIG_EA_DEMUXER) += electronicarts.o
46OBJS-$(CONFIG_FFM_DEMUXER) += ffmdec.o
47OBJS-$(CONFIG_FFM_MUXER) += ffmenc.o
48OBJS-$(CONFIG_FLAC_DEMUXER) += raw.o
49OBJS-$(CONFIG_FLAC_MUXER) += raw.o
50OBJS-$(CONFIG_FLIC_DEMUXER) += flic.o
51OBJS-$(CONFIG_FLV_DEMUXER) += flvdec.o
52OBJS-$(CONFIG_FLV_MUXER) += flvenc.o avc.o
53OBJS-$(CONFIG_FOURXM_DEMUXER) += 4xm.o
54OBJS-$(CONFIG_FRAMECRC_MUXER) += framecrcenc.o
55OBJS-$(CONFIG_GIF_MUXER) += gif.o
56OBJS-$(CONFIG_GSM_DEMUXER) += raw.o
57OBJS-$(CONFIG_GXF_DEMUXER) += gxf.o
58OBJS-$(CONFIG_GXF_MUXER) += gxfenc.o
59OBJS-$(CONFIG_H261_DEMUXER) += raw.o
60OBJS-$(CONFIG_H261_MUXER) += raw.o
61OBJS-$(CONFIG_H263_DEMUXER) += raw.o
62OBJS-$(CONFIG_H263_MUXER) += raw.o
63OBJS-$(CONFIG_H264_DEMUXER) += raw.o
64OBJS-$(CONFIG_H264_MUXER) += raw.o
65OBJS-$(CONFIG_IDCIN_DEMUXER) += idcin.o
66OBJS-$(CONFIG_IFF_DEMUXER) += iff.o
67OBJS-$(CONFIG_IMAGE2_DEMUXER) += img2.o
68OBJS-$(CONFIG_IMAGE2_MUXER) += img2.o
69OBJS-$(CONFIG_IMAGE2PIPE_DEMUXER) += img2.o
70OBJS-$(CONFIG_IMAGE2PIPE_MUXER) += img2.o
71OBJS-$(CONFIG_INGENIENT_DEMUXER) += raw.o
72OBJS-$(CONFIG_IPMOVIE_DEMUXER) += ipmovie.o
73OBJS-$(CONFIG_IPOD_MUXER) += movenc.o riff.o isom.o avc.o
74OBJS-$(CONFIG_LMLM4_DEMUXER) += lmlm4.o
75OBJS-$(CONFIG_M4V_DEMUXER) += raw.o
76OBJS-$(CONFIG_M4V_MUXER) += raw.o
77OBJS-$(CONFIG_MATROSKA_AUDIO_MUXER) += matroskaenc.o matroska.o riff.o avc.o
78OBJS-$(CONFIG_MATROSKA_DEMUXER) += matroskadec.o matroska.o riff.o
79OBJS-$(CONFIG_MATROSKA_MUXER) += matroskaenc.o matroska.o riff.o avc.o
80OBJS-$(CONFIG_MJPEG_DEMUXER) += raw.o
81OBJS-$(CONFIG_MJPEG_MUXER) += raw.o
82OBJS-$(CONFIG_MLP_DEMUXER) += raw.o
83OBJS-$(CONFIG_MM_DEMUXER) += mm.o
84OBJS-$(CONFIG_MMF_DEMUXER) += mmf.o raw.o
85OBJS-$(CONFIG_MMF_MUXER) += mmf.o riff.o
86OBJS-$(CONFIG_MOV_DEMUXER) += mov.o riff.o isom.o
87OBJS-$(CONFIG_MOV_MUXER) += movenc.o riff.o isom.o avc.o
88OBJS-$(CONFIG_MP2_MUXER) += mp3.o
89OBJS-$(CONFIG_MP3_DEMUXER) += mp3.o
90OBJS-$(CONFIG_MP3_MUXER) += mp3.o
91OBJS-$(CONFIG_MP4_MUXER) += movenc.o riff.o isom.o avc.o
92OBJS-$(CONFIG_MPC_DEMUXER) += mpc.o
93OBJS-$(CONFIG_MPC8_DEMUXER) += mpc8.o
94OBJS-$(CONFIG_MPEG1SYSTEM_MUXER) += mpegenc.o
95OBJS-$(CONFIG_MPEG1VCD_MUXER) += mpegenc.o
96OBJS-$(CONFIG_MPEG2DVD_MUXER) += mpegenc.o
97OBJS-$(CONFIG_MPEG2VOB_MUXER) += mpegenc.o
98OBJS-$(CONFIG_MPEG2SVCD_MUXER) += mpegenc.o
99OBJS-$(CONFIG_MPEG1VIDEO_MUXER) += raw.o
100OBJS-$(CONFIG_MPEG2VIDEO_MUXER) += raw.o
101OBJS-$(CONFIG_MPEGPS_DEMUXER) += mpeg.o
102OBJS-$(CONFIG_MPEGTS_DEMUXER) += mpegts.o
103OBJS-$(CONFIG_MPEGTSRAW_DEMUXER) += mpegts.o
104OBJS-$(CONFIG_MPEGTS_MUXER) += mpegtsenc.o
105OBJS-$(CONFIG_MPEGVIDEO_DEMUXER) += raw.o
106OBJS-$(CONFIG_MPJPEG_MUXER) += mpjpeg.o
107OBJS-$(CONFIG_MSNWC_TCP_DEMUXER) += msnwc_tcp.o
108OBJS-$(CONFIG_MTV_DEMUXER) += mtv.o
109OBJS-$(CONFIG_MVI_DEMUXER) += mvi.o
110OBJS-$(CONFIG_MXF_DEMUXER) += mxf.o
111OBJS-$(CONFIG_NSV_DEMUXER) += nsvdec.o
112OBJS-$(CONFIG_NULL_MUXER) += raw.o
113OBJS-$(CONFIG_NUT_DEMUXER) += nutdec.o nut.o riff.o
114OBJS-$(CONFIG_NUT_MUXER) += nutenc.o nut.o riff.o
115OBJS-$(CONFIG_NUV_DEMUXER) += nuv.o riff.o
116OBJS-$(CONFIG_OGG_DEMUXER) += oggdec.o \
117 oggparseflac.o \
118 oggparseogm.o \
119 oggparsespeex.o \
120 oggparsetheora.o \
121 oggparsevorbis.o \
122 riff.o
123OBJS-$(CONFIG_OGG_MUXER) += oggenc.o
124OBJS-$(CONFIG_OMA_DEMUXER) += oma.o raw.o
125OBJS-$(CONFIG_PCM_ALAW_DEMUXER) += raw.o
126OBJS-$(CONFIG_PCM_ALAW_MUXER) += raw.o
127OBJS-$(CONFIG_PCM_MULAW_DEMUXER) += raw.o
128OBJS-$(CONFIG_PCM_MULAW_MUXER) += raw.o
129OBJS-$(CONFIG_PCM_S16BE_DEMUXER) += raw.o
130OBJS-$(CONFIG_PCM_S16BE_MUXER) += raw.o
131OBJS-$(CONFIG_PCM_S16LE_DEMUXER) += raw.o
132OBJS-$(CONFIG_PCM_S16LE_MUXER) += raw.o
133OBJS-$(CONFIG_PCM_S8_DEMUXER) += raw.o
134OBJS-$(CONFIG_PCM_S8_MUXER) += raw.o
135OBJS-$(CONFIG_PCM_U16BE_DEMUXER) += raw.o
136OBJS-$(CONFIG_PCM_U16BE_MUXER) += raw.o
137OBJS-$(CONFIG_PCM_U16LE_DEMUXER) += raw.o
138OBJS-$(CONFIG_PCM_U16LE_MUXER) += raw.o
139OBJS-$(CONFIG_PCM_U8_DEMUXER) += raw.o
140OBJS-$(CONFIG_PCM_U8_MUXER) += raw.o
141OBJS-$(CONFIG_PSP_MUXER) += movenc.o riff.o isom.o avc.o
142OBJS-$(CONFIG_PVA_DEMUXER) += pva.o
143OBJS-$(CONFIG_RAWVIDEO_DEMUXER) += raw.o
144OBJS-$(CONFIG_RAWVIDEO_MUXER) += raw.o
145OBJS-$(CONFIG_REDIR_DEMUXER) += rtsp.o
146OBJS-$(CONFIG_RL2_DEMUXER) += rl2.o
147OBJS-$(CONFIG_RM_DEMUXER) += rmdec.o
148OBJS-$(CONFIG_RM_MUXER) += rmenc.o
149OBJS-$(CONFIG_ROQ_DEMUXER) += idroq.o
150OBJS-$(CONFIG_ROQ_MUXER) += raw.o
151OBJS-$(CONFIG_RPL_DEMUXER) += rpl.o
152OBJS-$(CONFIG_RTP_MUXER) += rtp.o \
153 rtpenc.o \
154 rtp_mpv.o \
155 rtp_aac.o \
156 rtpenc_h264.o \
157 avc.o
158OBJS-$(CONFIG_RTSP_DEMUXER) += rtsp.o
159OBJS-$(CONFIG_SDP_DEMUXER) += rtsp.o rtp.o rtpdec.o rtp_h264.o
160OBJS-$(CONFIG_SEGAFILM_DEMUXER) += segafilm.o
161OBJS-$(CONFIG_SHORTEN_DEMUXER) += raw.o
162OBJS-$(CONFIG_SIFF_DEMUXER) += siff.o
163OBJS-$(CONFIG_SMACKER_DEMUXER) += smacker.o
164OBJS-$(CONFIG_SOL_DEMUXER) += sol.o raw.o
165OBJS-$(CONFIG_STR_DEMUXER) += psxstr.o
166OBJS-$(CONFIG_SWF_DEMUXER) += swfdec.o
167OBJS-$(CONFIG_SWF_MUXER) += swfenc.o
168OBJS-$(CONFIG_TG2_MUXER) += movenc.o riff.o isom.o avc.o
169OBJS-$(CONFIG_TGP_MUXER) += movenc.o riff.o isom.o avc.o
170OBJS-$(CONFIG_THP_DEMUXER) += thp.o
171OBJS-$(CONFIG_TIERTEXSEQ_DEMUXER) += tiertexseq.o
172OBJS-$(CONFIG_TTA_DEMUXER) += tta.o
173OBJS-$(CONFIG_TXD_DEMUXER) += txd.o
174OBJS-$(CONFIG_VC1_DEMUXER) += raw.o
175OBJS-$(CONFIG_VC1T_DEMUXER) += vc1test.o
176OBJS-$(CONFIG_VMD_DEMUXER) += sierravmd.o
177OBJS-$(CONFIG_VOC_DEMUXER) += vocdec.o voc.o
178OBJS-$(CONFIG_VOC_MUXER) += vocenc.o voc.o
179OBJS-$(CONFIG_WAV_DEMUXER) += wav.o riff.o raw.o
180OBJS-$(CONFIG_WAV_MUXER) += wav.o riff.o
181OBJS-$(CONFIG_WC3_DEMUXER) += wc3movie.o
182OBJS-$(CONFIG_WSAUD_DEMUXER) += westwood.o
183OBJS-$(CONFIG_WSVQA_DEMUXER) += westwood.o
184OBJS-$(CONFIG_WV_DEMUXER) += wv.o
185OBJS-$(CONFIG_XA_DEMUXER) += xa.o
186OBJS-$(CONFIG_YUV4MPEGPIPE_MUXER) += yuv4mpeg.o
187OBJS-$(CONFIG_YUV4MPEGPIPE_DEMUXER) += yuv4mpeg.o
188
189# external libraries
190OBJS-$(CONFIG_LIBNUT_DEMUXER) += libnut.o riff.o
191OBJS-$(CONFIG_LIBNUT_MUXER) += libnut.o riff.o
192
193OBJS-$(CONFIG_VHOOK) += framehook.o
194
195# protocols I/O
196OBJS+= avio.o aviobuf.o
197
198OBJS-$(CONFIG_FILE_PROTOCOL) += file.o
199OBJS-$(CONFIG_HTTP_PROTOCOL) += http.o
200OBJS-$(CONFIG_PIPE_PROTOCOL) += file.o
201OBJS-$(CONFIG_RTP_PROTOCOL) += rtpproto.o
202OBJS-$(CONFIG_TCP_PROTOCOL) += tcp.o
203OBJS-$(CONFIG_UDP_PROTOCOL) += udp.o
204
205include $(SUBDIR)../subdir.mak
diff --git a/src/plugins/ffmpeg/libavformat/adtsenc.c b/src/plugins/ffmpeg/libavformat/adtsenc.c
deleted file mode 100644
index 5c65d36..0000000
--- a/src/plugins/ffmpeg/libavformat/adtsenc.c
+++ /dev/null
@@ -1,118 +0,0 @@
1/*
2 * ADTS muxer.
3 * Copyright (c) 2006 Baptiste Coudurier <baptiste.coudurier@smartjog.com>
4 * Mans Rullgard <mans@mansr.com>
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#include "libavcodec/bitstream.h"
24#include "avformat.h"
25
26#define ADTS_HEADER_SIZE 7
27
28typedef struct {
29 int write_adts;
30 int objecttype;
31 int sample_rate_index;
32 int channel_conf;
33} ADTSContext;
34
35static int decode_extradata(ADTSContext *adts, uint8_t *buf, int size)
36{
37 GetBitContext gb;
38
39 init_get_bits(&gb, buf, size * 8);
40 adts->objecttype = get_bits(&gb, 5) - 1;
41 adts->sample_rate_index = get_bits(&gb, 4);
42 adts->channel_conf = get_bits(&gb, 4);
43
44 adts->write_adts = 1;
45
46 return 0;
47}
48
49static int adts_write_header(AVFormatContext *s)
50{
51 ADTSContext *adts = s->priv_data;
52 AVCodecContext *avc = s->streams[0]->codec;
53
54 if(avc->extradata_size > 0)
55 decode_extradata(adts, avc->extradata, avc->extradata_size);
56
57 return 0;
58}
59
60static int adts_write_frame_header(AVFormatContext *s, int size)
61{
62 ADTSContext *ctx = s->priv_data;
63 PutBitContext pb;
64 uint8_t buf[ADTS_HEADER_SIZE];
65
66 init_put_bits(&pb, buf, ADTS_HEADER_SIZE);
67
68 /* adts_fixed_header */
69 put_bits(&pb, 12, 0xfff); /* syncword */
70 put_bits(&pb, 1, 0); /* ID */
71 put_bits(&pb, 2, 0); /* layer */
72 put_bits(&pb, 1, 1); /* protection_absent */
73 put_bits(&pb, 2, ctx->objecttype); /* profile_objecttype */
74 put_bits(&pb, 4, ctx->sample_rate_index);
75 put_bits(&pb, 1, 0); /* private_bit */
76 put_bits(&pb, 3, ctx->channel_conf); /* channel_configuration */
77 put_bits(&pb, 1, 0); /* original_copy */
78 put_bits(&pb, 1, 0); /* home */
79
80 /* adts_variable_header */
81 put_bits(&pb, 1, 0); /* copyright_identification_bit */
82 put_bits(&pb, 1, 0); /* copyright_identification_start */
83 put_bits(&pb, 13, ADTS_HEADER_SIZE + size); /* aac_frame_length */
84 put_bits(&pb, 11, 0x7ff); /* adts_buffer_fullness */
85 put_bits(&pb, 2, 0); /* number_of_raw_data_blocks_in_frame */
86
87 flush_put_bits(&pb);
88 put_buffer(s->pb, buf, ADTS_HEADER_SIZE);
89
90 return 0;
91}
92
93static int adts_write_packet(AVFormatContext *s, AVPacket *pkt)
94{
95 ADTSContext *adts = s->priv_data;
96 ByteIOContext *pb = s->pb;
97
98 if (!pkt->size)
99 return 0;
100 if(adts->write_adts)
101 adts_write_frame_header(s, pkt->size);
102 put_buffer(pb, pkt->data, pkt->size);
103 put_flush_packet(pb);
104
105 return 0;
106}
107
108AVOutputFormat adts_muxer = {
109 "adts",
110 NULL_IF_CONFIG_SMALL("ADTS AAC"),
111 "audio/aac",
112 "aac",
113 sizeof(ADTSContext),
114 CODEC_ID_AAC,
115 CODEC_ID_NONE,
116 adts_write_header,
117 adts_write_packet,
118};
diff --git a/src/plugins/ffmpeg/libavformat/aiff.c b/src/plugins/ffmpeg/libavformat/aiff.c
deleted file mode 100644
index 0ec8992..0000000
--- a/src/plugins/ffmpeg/libavformat/aiff.c
+++ /dev/null
@@ -1,464 +0,0 @@
1/*
2 * AIFF/AIFF-C muxer and demuxer
3 * Copyright (c) 2006 Patrick Guimond
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/intfloat_readwrite.h"
23#include "avformat.h"
24#include "raw.h"
25#include "riff.h"
26
27static const AVCodecTag codec_aiff_tags[] = {
28 { CODEC_ID_PCM_S16BE, MKTAG('N','O','N','E') },
29 { CODEC_ID_PCM_S8, MKTAG('N','O','N','E') },
30 { CODEC_ID_PCM_S24BE, MKTAG('N','O','N','E') },
31 { CODEC_ID_PCM_S32BE, MKTAG('N','O','N','E') },
32 { CODEC_ID_PCM_ALAW, MKTAG('a','l','a','w') },
33 { CODEC_ID_PCM_MULAW, MKTAG('u','l','a','w') },
34 { CODEC_ID_MACE3, MKTAG('M','A','C','3') },
35 { CODEC_ID_MACE6, MKTAG('M','A','C','6') },
36 { CODEC_ID_GSM, MKTAG('G','S','M',' ') },
37 { CODEC_ID_ADPCM_G726, MKTAG('G','7','2','6') },
38 { CODEC_ID_PCM_S16LE, MKTAG('s','o','w','t') },
39 { CODEC_ID_ADPCM_IMA_QT, MKTAG('i','m','a','4') },
40 { CODEC_ID_QDM2, MKTAG('Q','D','M','2') },
41 { 0, 0 },
42};
43
44#define AIFF 0
45#define AIFF_C_VERSION1 0xA2805140
46
47static int aiff_codec_get_id(int bps)
48{
49 if (bps <= 8)
50 return CODEC_ID_PCM_S8;
51 if (bps <= 16)
52 return CODEC_ID_PCM_S16BE;
53 if (bps <= 24)
54 return CODEC_ID_PCM_S24BE;
55 if (bps <= 32)
56 return CODEC_ID_PCM_S32BE;
57
58 /* bigger than 32 isn't allowed */
59 return 0;
60}
61
62/* returns the size of the found tag */
63static int get_tag(ByteIOContext *pb, uint32_t * tag)
64{
65 int size;
66
67 if (url_feof(pb))
68 return AVERROR(EIO);
69
70 *tag = get_le32(pb);
71 size = get_be32(pb);
72
73 if (size < 0)
74 size = 0x7fffffff;
75
76 return size;
77}
78
79/* Metadata string read */
80static void get_meta(ByteIOContext *pb, char * str, int strsize, int size)
81{
82 int res;
83
84 if (size > strsize-1)
85 res = get_buffer(pb, (uint8_t*)str, strsize-1);
86 else
87 res = get_buffer(pb, (uint8_t*)str, size);
88
89 if (res < 0)
90 return;
91
92 str[res] = 0;
93 if (size & 1)
94 size++;
95 size -= res;
96 if (size)
97 url_fskip(pb, size);
98}
99
100/* Returns the number of sound data frames or negative on error */
101static unsigned int get_aiff_header(ByteIOContext *pb, AVCodecContext *codec,
102 int size, unsigned version)
103{
104 AVExtFloat ext;
105 double sample_rate;
106 unsigned int num_frames;
107
108 if (size & 1)
109 size++;
110 codec->codec_type = CODEC_TYPE_AUDIO;
111 codec->channels = get_be16(pb);
112 num_frames = get_be32(pb);
113 codec->bits_per_sample = get_be16(pb);
114
115 get_buffer(pb, (uint8_t*)&ext, sizeof(ext));/* Sample rate is in */
116 sample_rate = av_ext2dbl(ext); /* 80 bits BE IEEE extended float */
117 codec->sample_rate = sample_rate;
118 size -= 18;
119
120 /* Got an AIFF-C? */
121 if (version == AIFF_C_VERSION1) {
122 codec->codec_tag = get_le32(pb);
123 codec->codec_id = codec_get_id(codec_aiff_tags, codec->codec_tag);
124
125 switch (codec->codec_id) {
126 case CODEC_ID_PCM_S16BE:
127 codec->codec_id = aiff_codec_get_id(codec->bits_per_sample);
128 codec->bits_per_sample = av_get_bits_per_sample(codec->codec_id);
129 break;
130 case CODEC_ID_ADPCM_IMA_QT:
131 codec->block_align = 34*codec->channels;
132 codec->frame_size = 64;
133 break;
134 case CODEC_ID_MACE3:
135 codec->block_align = 2*codec->channels;
136 codec->frame_size = 6;
137 break;
138 case CODEC_ID_MACE6:
139 codec->block_align = 1*codec->channels;
140 codec->frame_size = 6;
141 break;
142 default:
143 break;
144 }
145 size -= 4;
146 } else {
147 /* Need the codec type */
148 codec->codec_id = aiff_codec_get_id(codec->bits_per_sample);
149 codec->bits_per_sample = av_get_bits_per_sample(codec->codec_id);
150 }
151
152 /* Block align needs to be computed in all cases, as the definition
153 * is specific to applications -> here we use the WAVE format definition */
154 if (!codec->block_align)
155 codec->block_align = (codec->bits_per_sample * codec->channels) >> 3;
156
157 codec->bit_rate = (codec->frame_size ? codec->sample_rate/codec->frame_size :
158 codec->sample_rate) * (codec->block_align << 3);
159
160 /* Chunk is over */
161 if (size)
162 url_fseek(pb, size, SEEK_CUR);
163
164 return num_frames;
165}
166
167#ifdef CONFIG_MUXERS
168typedef struct {
169 offset_t form;
170 offset_t frames;
171 offset_t ssnd;
172} AIFFOutputContext;
173
174static int aiff_write_header(AVFormatContext *s)
175{
176 AIFFOutputContext *aiff = s->priv_data;
177 ByteIOContext *pb = s->pb;
178 AVCodecContext *enc = s->streams[0]->codec;
179 AVExtFloat sample_rate;
180 int aifc = 0;
181
182 /* First verify if format is ok */
183 if (!enc->codec_tag)
184 return -1;
185 if (enc->codec_tag != MKTAG('N','O','N','E'))
186 aifc = 1;
187
188 /* FORM AIFF header */
189 put_tag(pb, "FORM");
190 aiff->form = url_ftell(pb);
191 put_be32(pb, 0); /* file length */
192 put_tag(pb, aifc ? "AIFC" : "AIFF");
193
194 if (aifc) { // compressed audio
195 enc->bits_per_sample = 16;
196 if (!enc->block_align) {
197 av_log(s, AV_LOG_ERROR, "block align not set\n");
198 return -1;
199 }
200 /* Version chunk */
201 put_tag(pb, "FVER");
202 put_be32(pb, 4);
203 put_be32(pb, 0xA2805140);
204 }
205
206 /* Common chunk */
207 put_tag(pb, "COMM");
208 put_be32(pb, aifc ? 24 : 18); /* size */
209 put_be16(pb, enc->channels); /* Number of channels */
210
211 aiff->frames = url_ftell(pb);
212 put_be32(pb, 0); /* Number of frames */
213
214 if (!enc->bits_per_sample)
215 enc->bits_per_sample = av_get_bits_per_sample(enc->codec_id);
216 if (!enc->bits_per_sample) {
217 av_log(s, AV_LOG_ERROR, "could not compute bits per sample\n");
218 return -1;
219 }
220 if (!enc->block_align)
221 enc->block_align = (enc->bits_per_sample * enc->channels) >> 3;
222
223 put_be16(pb, enc->bits_per_sample); /* Sample size */
224
225 sample_rate = av_dbl2ext((double)enc->sample_rate);
226 put_buffer(pb, (uint8_t*)&sample_rate, sizeof(sample_rate));
227
228 if (aifc) {
229 put_le32(pb, enc->codec_tag);
230 put_be16(pb, 0);
231 }
232
233 /* Sound data chunk */
234 put_tag(pb, "SSND");
235 aiff->ssnd = url_ftell(pb); /* Sound chunk size */
236 put_be32(pb, 0); /* Sound samples data size */
237 put_be32(pb, 0); /* Data offset */
238 put_be32(pb, 0); /* Block-size (block align) */
239
240 av_set_pts_info(s->streams[0], 64, 1, s->streams[0]->codec->sample_rate);
241
242 /* Data is starting here */
243 put_flush_packet(pb);
244
245 return 0;
246}
247
248static int aiff_write_packet(AVFormatContext *s, AVPacket *pkt)
249{
250 ByteIOContext *pb = s->pb;
251 put_buffer(pb, pkt->data, pkt->size);
252 return 0;
253}
254
255static int aiff_write_trailer(AVFormatContext *s)
256{
257 ByteIOContext *pb = s->pb;
258 AIFFOutputContext *aiff = s->priv_data;
259 AVCodecContext *enc = s->streams[0]->codec;
260
261 /* Chunks sizes must be even */
262 offset_t file_size, end_size;
263 end_size = file_size = url_ftell(pb);
264 if (file_size & 1) {
265 put_byte(pb, 0);
266 end_size++;
267 }
268
269 if (!url_is_streamed(s->pb)) {
270 /* File length */
271 url_fseek(pb, aiff->form, SEEK_SET);
272 put_be32(pb, file_size - aiff->form - 4);
273
274 /* Number of sample frames */
275 url_fseek(pb, aiff->frames, SEEK_SET);
276 put_be32(pb, (file_size-aiff->ssnd-12)/enc->block_align);
277
278 /* Sound Data chunk size */
279 url_fseek(pb, aiff->ssnd, SEEK_SET);
280 put_be32(pb, file_size - aiff->ssnd - 4);
281
282 /* return to the end */
283 url_fseek(pb, end_size, SEEK_SET);
284
285 put_flush_packet(pb);
286 }
287
288 return 0;
289}
290#endif //CONFIG_MUXERS
291
292static int aiff_probe(AVProbeData *p)
293{
294 /* check file header */
295 if (p->buf[0] == 'F' && p->buf[1] == 'O' &&
296 p->buf[2] == 'R' && p->buf[3] == 'M' &&
297 p->buf[8] == 'A' && p->buf[9] == 'I' &&
298 p->buf[10] == 'F' && (p->buf[11] == 'F' || p->buf[11] == 'C'))
299 return AVPROBE_SCORE_MAX;
300 else
301 return 0;
302}
303
304/* aiff input */
305static int aiff_read_header(AVFormatContext *s,
306 AVFormatParameters *ap)
307{
308 int size, filesize;
309 offset_t offset = 0;
310 uint32_t tag;
311 unsigned version = AIFF_C_VERSION1;
312 ByteIOContext *pb = s->pb;
313 AVStream * st = s->streams[0];
314
315 /* check FORM header */
316 filesize = get_tag(pb, &tag);
317 if (filesize < 0 || tag != MKTAG('F', 'O', 'R', 'M'))
318 return AVERROR_INVALIDDATA;
319
320 /* AIFF data type */
321 tag = get_le32(pb);
322 if (tag == MKTAG('A', 'I', 'F', 'F')) /* Got an AIFF file */
323 version = AIFF;
324 else if (tag != MKTAG('A', 'I', 'F', 'C')) /* An AIFF-C file then */
325 return AVERROR_INVALIDDATA;
326
327 filesize -= 4;
328
329 st = av_new_stream(s, 0);
330 if (!st)
331 return AVERROR(ENOMEM);
332
333 while (filesize > 0) {
334 /* parse different chunks */
335 size = get_tag(pb, &tag);
336 if (size < 0)
337 return size;
338
339 filesize -= size + 8;
340
341 switch (tag) {
342 case MKTAG('C', 'O', 'M', 'M'): /* Common chunk */
343 /* Then for the complete header info */
344 st->nb_frames = get_aiff_header(pb, st->codec, size, version);
345 if (st->nb_frames < 0)
346 return st->nb_frames;
347 if (offset > 0) // COMM is after SSND
348 goto got_sound;
349 break;
350 case MKTAG('F', 'V', 'E', 'R'): /* Version chunk */
351 version = get_be32(pb);
352 break;
353 case MKTAG('N', 'A', 'M', 'E'): /* Sample name chunk */
354 get_meta(pb, s->title, sizeof(s->title), size);
355 break;
356 case MKTAG('A', 'U', 'T', 'H'): /* Author chunk */
357 get_meta(pb, s->author, sizeof(s->author), size);
358 break;
359 case MKTAG('(', 'c', ')', ' '): /* Copyright chunk */
360 get_meta(pb, s->copyright, sizeof(s->copyright), size);
361 break;
362 case MKTAG('A', 'N', 'N', 'O'): /* Annotation chunk */
363 get_meta(pb, s->comment, sizeof(s->comment), size);
364 break;
365 case MKTAG('S', 'S', 'N', 'D'): /* Sampled sound chunk */
366 offset = get_be32(pb); /* Offset of sound data */
367 get_be32(pb); /* BlockSize... don't care */
368 offset += url_ftell(pb); /* Compute absolute data offset */
369 if (st->codec->block_align) /* Assume COMM already parsed */
370 goto got_sound;
371 if (url_is_streamed(pb)) {
372 av_log(s, AV_LOG_ERROR, "file is not seekable\n");
373 return -1;
374 }
375 url_fskip(pb, size - 8);
376 break;
377 case MKTAG('w', 'a', 'v', 'e'):
378 if ((uint64_t)size > (1<<30))
379 return -1;
380 st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
381 if (!st->codec->extradata)
382 return AVERROR(ENOMEM);
383 st->codec->extradata_size = size;
384 get_buffer(pb, st->codec->extradata, size);
385 break;
386 default: /* Jump */
387 if (size & 1) /* Always even aligned */
388 size++;
389 url_fskip (pb, size);
390 }
391 }
392
393 if (!st->codec->block_align) {
394 av_log(s, AV_LOG_ERROR, "could not find COMM tag\n");
395 return -1;
396 }
397
398got_sound:
399 /* Now positioned, get the sound data start and end */
400 if (st->nb_frames)
401 s->file_size = st->nb_frames * st->codec->block_align;
402
403 av_set_pts_info(st, 64, 1, st->codec->sample_rate);
404 st->start_time = 0;
405 st->duration = st->codec->frame_size ?
406 st->nb_frames * st->codec->frame_size : st->nb_frames;
407
408 /* Position the stream at the first block */
409 url_fseek(pb, offset, SEEK_SET);
410
411 return 0;
412}
413
414#define MAX_SIZE 4096
415
416static int aiff_read_packet(AVFormatContext *s,
417 AVPacket *pkt)
418{
419 AVStream *st = s->streams[0];
420 int res;
421
422 /* End of stream may be reached */
423 if (url_feof(s->pb))
424 return AVERROR(EIO);
425
426 /* Now for that packet */
427 res = av_get_packet(s->pb, pkt, (MAX_SIZE / st->codec->block_align) * st->codec->block_align);
428 if (res < 0)
429 return res;
430
431 /* Only one stream in an AIFF file */
432 pkt->stream_index = 0;
433 return 0;
434}
435
436#ifdef CONFIG_AIFF_DEMUXER
437AVInputFormat aiff_demuxer = {
438 "aiff",
439 NULL_IF_CONFIG_SMALL("Audio IFF"),
440 0,
441 aiff_probe,
442 aiff_read_header,
443 aiff_read_packet,
444 NULL,
445 pcm_read_seek,
446 .codec_tag= (const AVCodecTag*[]){codec_aiff_tags, 0},
447};
448#endif
449
450#ifdef CONFIG_AIFF_MUXER
451AVOutputFormat aiff_muxer = {
452 "aiff",
453 NULL_IF_CONFIG_SMALL("Audio IFF"),
454 "audio/aiff",
455 "aif,aiff,afc,aifc",
456 sizeof(AIFFOutputContext),
457 CODEC_ID_PCM_S16BE,
458 CODEC_ID_NONE,
459 aiff_write_header,
460 aiff_write_packet,
461 aiff_write_trailer,
462 .codec_tag= (const AVCodecTag*[]){codec_aiff_tags, 0},
463};
464#endif
diff --git a/src/plugins/ffmpeg/libavformat/allformats.c b/src/plugins/ffmpeg/libavformat/allformats.c
deleted file mode 100644
index 81111af..0000000
--- a/src/plugins/ffmpeg/libavformat/allformats.c
+++ /dev/null
@@ -1,191 +0,0 @@
1/*
2 * Register all the formats and protocols
3 * Copyright (c) 2000, 2001, 2002 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#include "avformat.h"
22#include "rtp_internal.h"
23
24#define REGISTER_MUXER(X,x) { \
25 extern AVOutputFormat x##_muxer; \
26 if(ENABLE_##X##_MUXER) av_register_output_format(&x##_muxer); }
27#define REGISTER_DEMUXER(X,x) { \
28 extern AVInputFormat x##_demuxer; \
29 if(ENABLE_##X##_DEMUXER) av_register_input_format(&x##_demuxer); }
30#define REGISTER_MUXDEMUX(X,x) REGISTER_MUXER(X,x); REGISTER_DEMUXER(X,x)
31#define REGISTER_PROTOCOL(X,x) { \
32 extern URLProtocol x##_protocol; \
33 if(ENABLE_##X##_PROTOCOL) register_protocol(&x##_protocol); }
34
35/* If you do not call this function, then you can select exactly which
36 formats you want to support */
37
38/**
39 * Initialize libavformat and register all the (de)muxers and protocols.
40 */
41void av_register_all(void)
42{
43 static int initialized;
44
45 if (initialized)
46 return;
47 initialized = 1;
48
49 avcodec_init();
50 avcodec_register_all();
51
52 /* (de)muxers */
53 REGISTER_DEMUXER (AAC, aac);
54 REGISTER_MUXDEMUX (AC3, ac3);
55 REGISTER_MUXER (ADTS, adts);
56 REGISTER_MUXDEMUX (AIFF, aiff);
57 REGISTER_MUXDEMUX (AMR, amr);
58 REGISTER_DEMUXER (APC, apc);
59 REGISTER_DEMUXER (APE, ape);
60 REGISTER_MUXDEMUX (ASF, asf);
61 REGISTER_MUXER (ASF_STREAM, asf_stream);
62 REGISTER_MUXDEMUX (AU, au);
63 REGISTER_MUXDEMUX (AVI, avi);
64 REGISTER_DEMUXER (AVISYNTH, avisynth);
65 REGISTER_MUXER (AVM2, avm2);
66 REGISTER_DEMUXER (AVS, avs);
67 REGISTER_DEMUXER (BETHSOFTVID, bethsoftvid);
68 REGISTER_DEMUXER (BFI, bfi);
69 REGISTER_DEMUXER (C93, c93);
70 REGISTER_MUXER (CRC, crc);
71 REGISTER_DEMUXER (DAUD, daud);
72 REGISTER_MUXDEMUX (DIRAC, dirac);
73 REGISTER_DEMUXER (DSICIN, dsicin);
74 REGISTER_MUXDEMUX (DTS, dts);
75 REGISTER_MUXDEMUX (DV, dv);
76 REGISTER_DEMUXER (DXA, dxa);
77 REGISTER_DEMUXER (EA, ea);
78 REGISTER_DEMUXER (EA_CDATA, ea_cdata);
79 REGISTER_MUXDEMUX (FFM, ffm);
80 REGISTER_MUXDEMUX (FLAC, flac);
81 REGISTER_DEMUXER (FLIC, flic);
82 REGISTER_MUXDEMUX (FLV, flv);
83 REGISTER_DEMUXER (FOURXM, fourxm);
84 REGISTER_MUXER (FRAMECRC, framecrc);
85 REGISTER_MUXER (GIF, gif);
86 REGISTER_DEMUXER (GSM, gsm);
87 REGISTER_MUXDEMUX (GXF, gxf);
88 REGISTER_MUXDEMUX (H261, h261);
89 REGISTER_MUXDEMUX (H263, h263);
90 REGISTER_MUXDEMUX (H264, h264);
91 REGISTER_DEMUXER (IDCIN, idcin);
92 REGISTER_DEMUXER (IFF, iff);
93 REGISTER_MUXDEMUX (IMAGE2, image2);
94 REGISTER_MUXDEMUX (IMAGE2PIPE, image2pipe);
95 REGISTER_DEMUXER (INGENIENT, ingenient);
96 REGISTER_DEMUXER (IPMOVIE, ipmovie);
97 REGISTER_MUXER (IPOD, ipod);
98 REGISTER_DEMUXER (LMLM4, lmlm4);
99 REGISTER_MUXDEMUX (M4V, m4v);
100 REGISTER_MUXDEMUX (MATROSKA, matroska);
101 REGISTER_MUXER (MATROSKA_AUDIO, matroska_audio);
102 REGISTER_MUXDEMUX (MJPEG, mjpeg);
103 REGISTER_DEMUXER (MLP, mlp);
104 REGISTER_DEMUXER (MM, mm);
105 REGISTER_MUXDEMUX (MMF, mmf);
106 REGISTER_MUXDEMUX (MOV, mov);
107 REGISTER_MUXER (MP2, mp2);
108 REGISTER_MUXDEMUX (MP3, mp3);
109 REGISTER_MUXER (MP4, mp4);
110 REGISTER_DEMUXER (MPC, mpc);
111 REGISTER_DEMUXER (MPC8, mpc8);
112 REGISTER_MUXER (MPEG1SYSTEM, mpeg1system);
113 REGISTER_MUXER (MPEG1VCD, mpeg1vcd);
114 REGISTER_MUXER (MPEG1VIDEO, mpeg1video);
115 REGISTER_MUXER (MPEG2DVD, mpeg2dvd);
116 REGISTER_MUXER (MPEG2SVCD, mpeg2svcd);
117 REGISTER_MUXER (MPEG2VIDEO, mpeg2video);
118 REGISTER_MUXER (MPEG2VOB, mpeg2vob);
119 REGISTER_DEMUXER (MPEGPS, mpegps);
120 REGISTER_MUXDEMUX (MPEGTS, mpegts);
121 REGISTER_DEMUXER (MPEGTSRAW, mpegtsraw);
122 REGISTER_DEMUXER (MPEGVIDEO, mpegvideo);
123 REGISTER_MUXER (MPJPEG, mpjpeg);
124 REGISTER_DEMUXER (MSNWC_TCP, msnwc_tcp);
125 REGISTER_DEMUXER (MTV, mtv);
126 REGISTER_DEMUXER (MVI, mvi);
127 REGISTER_DEMUXER (MXF, mxf);
128 REGISTER_DEMUXER (NSV, nsv);
129 REGISTER_MUXER (NULL, null);
130 REGISTER_MUXDEMUX (NUT, nut);
131 REGISTER_DEMUXER (NUV, nuv);
132 REGISTER_MUXDEMUX (OGG, ogg);
133 REGISTER_DEMUXER (OMA, oma);
134 REGISTER_MUXDEMUX (PCM_ALAW, pcm_alaw);
135 REGISTER_MUXDEMUX (PCM_MULAW, pcm_mulaw);
136 REGISTER_MUXDEMUX (PCM_S16BE, pcm_s16be);
137 REGISTER_MUXDEMUX (PCM_S16LE, pcm_s16le);
138 REGISTER_MUXDEMUX (PCM_S8, pcm_s8);
139 REGISTER_MUXDEMUX (PCM_U16BE, pcm_u16be);
140 REGISTER_MUXDEMUX (PCM_U16LE, pcm_u16le);
141 REGISTER_MUXDEMUX (PCM_U8, pcm_u8);
142 REGISTER_MUXER (PSP, psp);
143 REGISTER_DEMUXER (PVA, pva);
144 REGISTER_MUXDEMUX (RAWVIDEO, rawvideo);
145 REGISTER_DEMUXER (REDIR, redir);
146 REGISTER_DEMUXER (RL2, rl2);
147 REGISTER_MUXDEMUX (RM, rm);
148 REGISTER_MUXDEMUX (ROQ, roq);
149 REGISTER_DEMUXER (RPL, rpl);
150 REGISTER_MUXER (RTP, rtp);
151 REGISTER_DEMUXER (RTSP, rtsp);
152 REGISTER_DEMUXER (SDP, sdp);
153#ifdef CONFIG_SDP_DEMUXER
154 av_register_rtp_dynamic_payload_handlers();
155#endif
156 REGISTER_DEMUXER (SEGAFILM, segafilm);
157 REGISTER_DEMUXER (SHORTEN, shorten);
158 REGISTER_DEMUXER (SIFF, siff);
159 REGISTER_DEMUXER (SMACKER, smacker);
160 REGISTER_DEMUXER (SOL, sol);
161 REGISTER_DEMUXER (STR, str);
162 REGISTER_MUXDEMUX (SWF, swf);
163 REGISTER_MUXER (TG2, tg2);
164 REGISTER_MUXER (TGP, tgp);
165 REGISTER_DEMUXER (THP, thp);
166 REGISTER_DEMUXER (TIERTEXSEQ, tiertexseq);
167 REGISTER_DEMUXER (TTA, tta);
168 REGISTER_DEMUXER (TXD, txd);
169 REGISTER_DEMUXER (VC1, vc1);
170 REGISTER_DEMUXER (VC1T, vc1t);
171 REGISTER_DEMUXER (VMD, vmd);
172 REGISTER_MUXDEMUX (VOC, voc);
173 REGISTER_MUXDEMUX (WAV, wav);
174 REGISTER_DEMUXER (WC3, wc3);
175 REGISTER_DEMUXER (WSAUD, wsaud);
176 REGISTER_DEMUXER (WSVQA, wsvqa);
177 REGISTER_DEMUXER (WV, wv);
178 REGISTER_DEMUXER (XA, xa);
179 REGISTER_MUXDEMUX (YUV4MPEGPIPE, yuv4mpegpipe);
180
181 /* external libraries */
182 REGISTER_MUXDEMUX (LIBNUT, libnut);
183
184 /* protocols */
185 REGISTER_PROTOCOL (FILE, file);
186 REGISTER_PROTOCOL (HTTP, http);
187 REGISTER_PROTOCOL (PIPE, pipe);
188 REGISTER_PROTOCOL (RTP, rtp);
189 REGISTER_PROTOCOL (TCP, tcp);
190 REGISTER_PROTOCOL (UDP, udp);
191}
diff --git a/src/plugins/ffmpeg/libavformat/amr.c b/src/plugins/ffmpeg/libavformat/amr.c
deleted file mode 100644
index edf8f8d..0000000
--- a/src/plugins/ffmpeg/libavformat/amr.c
+++ /dev/null
@@ -1,193 +0,0 @@
1/*
2 * amr file format
3 * Copyright (c) 2001 ffmpeg project
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/*
23Write and read amr data according to RFC3267, http://www.ietf.org/rfc/rfc3267.txt?number=3267
24
25Only mono files are supported.
26
27*/
28#include "avformat.h"
29
30static const char AMR_header [] = "#!AMR\n";
31static const char AMRWB_header [] = "#!AMR-WB\n";
32
33#ifdef CONFIG_MUXERS
34static int amr_write_header(AVFormatContext *s)
35{
36 ByteIOContext *pb = s->pb;
37 AVCodecContext *enc = s->streams[0]->codec;
38
39 s->priv_data = NULL;
40
41 if (enc->codec_id == CODEC_ID_AMR_NB)
42 {
43 put_tag(pb, AMR_header); /* magic number */
44 }
45 else if(enc->codec_id == CODEC_ID_AMR_WB)
46 {
47 put_tag(pb, AMRWB_header); /* magic number */
48 }
49 else
50 {
51 return -1;
52 }
53 put_flush_packet(pb);
54 return 0;
55}
56
57static int amr_write_packet(AVFormatContext *s, AVPacket *pkt)
58{
59 put_buffer(s->pb, pkt->data, pkt->size);
60 put_flush_packet(s->pb);
61 return 0;
62}
63#endif /* CONFIG_MUXERS */
64
65static int amr_probe(AVProbeData *p)
66{
67 //Only check for "#!AMR" which could be amr-wb, amr-nb.
68 //This will also trigger multichannel files: "#!AMR_MC1.0\n" and
69 //"#!AMR-WB_MC1.0\n" (not supported)
70
71 if(memcmp(p->buf,AMR_header,5)==0)
72 return AVPROBE_SCORE_MAX;
73 else
74 return 0;
75}
76
77/* amr input */
78static int amr_read_header(AVFormatContext *s,
79 AVFormatParameters *ap)
80{
81 ByteIOContext *pb = s->pb;
82 AVStream *st;
83 uint8_t header[9];
84
85 get_buffer(pb, header, 6);
86
87 st = av_new_stream(s, 0);
88 if (!st)
89 {
90 return AVERROR(ENOMEM);
91 }
92 if(memcmp(header,AMR_header,6)!=0)
93 {
94 get_buffer(pb, header+6, 3);
95 if(memcmp(header,AMRWB_header,9)!=0)
96 {
97 return -1;
98 }
99
100 st->codec->codec_tag = MKTAG('s', 'a', 'w', 'b');
101 st->codec->codec_id = CODEC_ID_AMR_WB;
102 st->codec->sample_rate = 16000;
103 }
104 else
105 {
106 st->codec->codec_tag = MKTAG('s', 'a', 'm', 'r');
107 st->codec->codec_id = CODEC_ID_AMR_NB;
108 st->codec->sample_rate = 8000;
109 }
110 st->codec->channels = 1;
111 st->codec->codec_type = CODEC_TYPE_AUDIO;
112 av_set_pts_info(st, 64, 1, st->codec->sample_rate);
113
114 return 0;
115}
116
117static int amr_read_packet(AVFormatContext *s,
118 AVPacket *pkt)
119{
120 AVCodecContext *enc = s->streams[0]->codec;
121 int read, size = 0, toc, mode;
122
123 if (url_feof(s->pb))
124 {
125 return AVERROR(EIO);
126 }
127
128//FIXME this is wrong, this should rather be in a AVParset
129 toc=get_byte(s->pb);
130 mode = (toc >> 3) & 0x0F;
131
132 if (enc->codec_id == CODEC_ID_AMR_NB)
133 {
134 static const uint8_t packed_size[16] = {12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0, 0, 0};
135
136 size=packed_size[mode]+1;
137 }
138 else if(enc->codec_id == CODEC_ID_AMR_WB)
139 {
140 static uint8_t packed_size[16] = {18, 24, 33, 37, 41, 47, 51, 59, 61, 6, 6, 0, 0, 0, 1, 1};
141
142 size=packed_size[mode];
143 }
144 else
145 {
146 assert(0);
147 }
148
149 if ( (size==0) || av_new_packet(pkt, size))
150 {
151 return AVERROR(EIO);
152 }
153
154 pkt->stream_index = 0;
155 pkt->pos= url_ftell(s->pb);
156 pkt->data[0]=toc;
157 pkt->duration= enc->codec_id == CODEC_ID_AMR_NB ? 160 : 320;
158 read = get_buffer(s->pb, pkt->data+1, size-1);
159
160 if (read != size-1)
161 {
162 av_free_packet(pkt);
163 return AVERROR(EIO);
164 }
165
166 return 0;
167}
168
169#ifdef CONFIG_AMR_DEMUXER
170AVInputFormat amr_demuxer = {
171 "amr",
172 NULL_IF_CONFIG_SMALL("3GPP AMR file format"),
173 0, /*priv_data_size*/
174 amr_probe,
175 amr_read_header,
176 amr_read_packet,
177 NULL,
178};
179#endif
180
181#ifdef CONFIG_AMR_MUXER
182AVOutputFormat amr_muxer = {
183 "amr",
184 NULL_IF_CONFIG_SMALL("3GPP AMR file format"),
185 "audio/amr",
186 "amr",
187 0,
188 CODEC_ID_AMR_NB,
189 CODEC_ID_NONE,
190 amr_write_header,
191 amr_write_packet,
192};
193#endif
diff --git a/src/plugins/ffmpeg/libavformat/apc.c b/src/plugins/ffmpeg/libavformat/apc.c
deleted file mode 100644
index 20de1c7..0000000
--- a/src/plugins/ffmpeg/libavformat/apc.c
+++ /dev/null
@@ -1,90 +0,0 @@
1/*
2 * CRYO APC audio format demuxer
3 * Copyright (c) 2007 Anssi Hannula <anssi.hannula@gmail.com>
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 <string.h>
23#include "avformat.h"
24
25static int apc_probe(AVProbeData *p)
26{
27 if (!strncmp(p->buf, "CRYO_APC", 8))
28 return AVPROBE_SCORE_MAX;
29
30 return 0;
31}
32
33static int apc_read_header(AVFormatContext *s, AVFormatParameters *ap)
34{
35 ByteIOContext *pb = s->pb;
36 AVStream *st;
37
38 get_le32(pb); /* CRYO */
39 get_le32(pb); /* _APC */
40 get_le32(pb); /* 1.20 */
41
42 st = av_new_stream(s, 0);
43 if (!st)
44 return AVERROR(ENOMEM);
45
46 st->codec->codec_type = CODEC_TYPE_AUDIO;
47 st->codec->codec_id = CODEC_ID_ADPCM_IMA_WS;
48
49 get_le32(pb); /* number of samples */
50 st->codec->sample_rate = get_le32(pb);
51
52 st->codec->extradata_size = 2 * 4;
53 st->codec->extradata = av_malloc(st->codec->extradata_size +
54 FF_INPUT_BUFFER_PADDING_SIZE);
55 if (!st->codec->extradata)
56 return AVERROR(ENOMEM);
57
58 /* initial predictor values for adpcm decoder */
59 get_buffer(pb, st->codec->extradata, 2 * 4);
60
61 st->codec->channels = 1;
62 if (get_le32(pb))
63 st->codec->channels = 2;
64
65 st->codec->bits_per_sample = 4;
66 st->codec->bit_rate = st->codec->bits_per_sample * st->codec->channels
67 * st->codec->sample_rate;
68 st->codec->block_align = 1;
69
70 return 0;
71}
72
73#define MAX_READ_SIZE 4096
74
75static int apc_read_packet(AVFormatContext *s, AVPacket *pkt)
76{
77 if (av_get_packet(s->pb, pkt, MAX_READ_SIZE) <= 0)
78 return AVERROR(EIO);
79 pkt->stream_index = 0;
80 return 0;
81}
82
83AVInputFormat apc_demuxer = {
84 "apc",
85 NULL_IF_CONFIG_SMALL("CRYO APC format"),
86 0,
87 apc_probe,
88 apc_read_header,
89 apc_read_packet,
90};
diff --git a/src/plugins/ffmpeg/libavformat/ape.c b/src/plugins/ffmpeg/libavformat/ape.c
deleted file mode 100644
index 4c5d046..0000000
--- a/src/plugins/ffmpeg/libavformat/ape.c
+++ /dev/null
@@ -1,522 +0,0 @@
1/*
2 * Monkey's Audio APE demuxer
3 * Copyright (c) 2007 Benjamin Zores <ben@geexbox.org>
4 * based upon libdemac from Dave Chapman.
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#include <stdio.h>
24
25#include "avformat.h"
26
27#define ENABLE_DEBUG 0
28
29/* The earliest and latest file formats supported by this library */
30#define APE_MIN_VERSION 3950
31#define APE_MAX_VERSION 3990
32
33#define MAC_FORMAT_FLAG_8_BIT 1 // is 8-bit [OBSOLETE]
34#define MAC_FORMAT_FLAG_CRC 2 // uses the new CRC32 error detection [OBSOLETE]
35#define MAC_FORMAT_FLAG_HAS_PEAK_LEVEL 4 // uint32 nPeakLevel after the header [OBSOLETE]
36#define MAC_FORMAT_FLAG_24_BIT 8 // is 24-bit [OBSOLETE]
37#define MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS 16 // has the number of seek elements after the peak level
38#define MAC_FORMAT_FLAG_CREATE_WAV_HEADER 32 // create the wave header on decompression (not stored)
39
40#define MAC_SUBFRAME_SIZE 4608
41
42#define APE_EXTRADATA_SIZE 6
43
44/* APE tags */
45#define APE_TAG_VERSION 2000
46#define APE_TAG_FOOTER_BYTES 32
47#define APE_TAG_FLAG_CONTAINS_HEADER (1 << 31)
48#define APE_TAG_FLAG_IS_HEADER (1 << 29)
49
50#define TAG(name, field) {name, offsetof(AVFormatContext, field), sizeof(((AVFormatContext *)0)->field)}
51
52static const struct {
53 const char *name;
54 int offset;
55 int size;
56} tags[] = {
57 TAG("Title" , title ),
58 TAG("Artist" , author ),
59 TAG("Copyright", copyright),
60 TAG("Comment" , comment ),
61 TAG("Album" , album ),
62 TAG("Year" , year ),
63 TAG("Track" , track ),
64 TAG("Genre" , genre ),
65 { NULL }
66};
67
68typedef struct {
69 int64_t pos;
70 int nblocks;
71 int size;
72 int skip;
73 int64_t pts;
74} APEFrame;
75
76typedef struct {
77 /* Derived fields */
78 uint32_t junklength;
79 uint32_t firstframe;
80 uint32_t totalsamples;
81 int currentframe;
82 APEFrame *frames;
83
84 /* Info from Descriptor Block */
85 char magic[4];
86 int16_t fileversion;
87 int16_t padding1;
88 uint32_t descriptorlength;
89 uint32_t headerlength;
90 uint32_t seektablelength;
91 uint32_t wavheaderlength;
92 uint32_t audiodatalength;
93 uint32_t audiodatalength_high;
94 uint32_t wavtaillength;
95 uint8_t md5[16];
96
97 /* Info from Header Block */
98 uint16_t compressiontype;
99 uint16_t formatflags;
100 uint32_t blocksperframe;
101 uint32_t finalframeblocks;
102 uint32_t totalframes;
103 uint16_t bps;
104 uint16_t channels;
105 uint32_t samplerate;
106
107 /* Seektable */
108 uint32_t *seektable;
109} APEContext;
110
111static void ape_tag_read_field(AVFormatContext *s)
112{
113 ByteIOContext *pb = s->pb;
114 uint8_t buf[1024];
115 uint32_t size;
116 int i;
117
118 memset(buf, 0, 1024);
119 size = get_le32(pb); /* field size */
120 url_fskip(pb, 4); /* skip field flags */
121
122 for (i=0; pb->buf_ptr[i]!='0' && pb->buf_ptr[i]>=0x20 && pb->buf_ptr[i]<=0x7E; i++);
123
124 get_buffer(pb, buf, FFMIN(i, 1024));
125 url_fskip(pb, 1);
126
127 for (i=0; tags[i].name; i++)
128 if (!strcmp (buf, tags[i].name)) {
129 if (tags[i].size == sizeof(int)) {
130 char tmp[16];
131 get_buffer(pb, tmp, FFMIN(sizeof(tmp), size));
132 *(int *)(((char *)s)+tags[i].offset) = atoi(tmp);
133 } else {
134 get_buffer(pb, ((char *)s) + tags[i].offset,
135 FFMIN(tags[i].size, size));
136 }
137 break;
138 }
139
140 if (!tags[i].name)
141 url_fskip(pb, size);
142}
143
144static void ape_parse_tag(AVFormatContext *s)
145{
146 ByteIOContext *pb = s->pb;
147 int file_size = url_fsize(pb);
148 uint32_t val, fields, tag_bytes;
149 uint8_t buf[8];
150 int i;
151
152 if (file_size < APE_TAG_FOOTER_BYTES)
153 return;
154
155 url_fseek(pb, file_size - APE_TAG_FOOTER_BYTES, SEEK_SET);
156
157 get_buffer(pb, buf, 8); /* APETAGEX */
158 if (strncmp(buf, "APETAGEX", 8)) {
159 return;
160 }
161
162 val = get_le32(pb); /* APE tag version */
163 if (val > APE_TAG_VERSION) {
164 av_log(NULL, AV_LOG_ERROR, "Unsupported tag version. (>=%d)\n", APE_TAG_VERSION);
165 return;
166 }
167
168 tag_bytes = get_le32(pb); /* tag size */
169 if (tag_bytes - APE_TAG_FOOTER_BYTES > (1024 * 1024 * 16)) {
170 av_log(NULL, AV_LOG_ERROR, "Tag size is way too big\n");
171 return;
172 }
173
174 fields = get_le32(pb); /* number of fields */
175 if (fields > 65536) {
176 av_log(NULL, AV_LOG_ERROR, "Too many tag fields (%d)\n", fields);
177 return;
178 }
179
180 val = get_le32(pb); /* flags */
181 if (val & APE_TAG_FLAG_IS_HEADER) {
182 av_log(NULL, AV_LOG_ERROR, "APE Tag is a header\n");
183 return;
184 }
185
186 if (val & APE_TAG_FLAG_CONTAINS_HEADER)
187 tag_bytes += 2*APE_TAG_FOOTER_BYTES;
188
189 url_fseek(pb, file_size - tag_bytes, SEEK_SET);
190
191 for (i=0; i<fields; i++)
192 ape_tag_read_field(s);
193
194#if ENABLE_DEBUG
195 av_log(NULL, AV_LOG_DEBUG, "\nAPE Tags:\n\n");
196 av_log(NULL, AV_LOG_DEBUG, "title = %s\n", s->title);
197 av_log(NULL, AV_LOG_DEBUG, "author = %s\n", s->author);
198 av_log(NULL, AV_LOG_DEBUG, "copyright = %s\n", s->copyright);
199 av_log(NULL, AV_LOG_DEBUG, "comment = %s\n", s->comment);
200 av_log(NULL, AV_LOG_DEBUG, "album = %s\n", s->album);
201 av_log(NULL, AV_LOG_DEBUG, "year = %d\n", s->year);
202 av_log(NULL, AV_LOG_DEBUG, "track = %d\n", s->track);
203 av_log(NULL, AV_LOG_DEBUG, "genre = %s\n", s->genre);
204#endif
205}
206
207static int ape_probe(AVProbeData * p)
208{
209 if (p->buf[0] == 'M' && p->buf[1] == 'A' && p->buf[2] == 'C' && p->buf[3] == ' ')
210 return AVPROBE_SCORE_MAX;
211
212 return 0;
213}
214
215static void ape_dumpinfo(APEContext * ape_ctx)
216{
217#if ENABLE_DEBUG
218 int i;
219
220 av_log(NULL, AV_LOG_DEBUG, "Descriptor Block:\n\n");
221 av_log(NULL, AV_LOG_DEBUG, "magic = \"%c%c%c%c\"\n", ape_ctx->magic[0], ape_ctx->magic[1], ape_ctx->magic[2], ape_ctx->magic[3]);
222 av_log(NULL, AV_LOG_DEBUG, "fileversion = %d\n", ape_ctx->fileversion);
223 av_log(NULL, AV_LOG_DEBUG, "descriptorlength = %d\n", ape_ctx->descriptorlength);
224 av_log(NULL, AV_LOG_DEBUG, "headerlength = %d\n", ape_ctx->headerlength);
225 av_log(NULL, AV_LOG_DEBUG, "seektablelength = %d\n", ape_ctx->seektablelength);
226 av_log(NULL, AV_LOG_DEBUG, "wavheaderlength = %d\n", ape_ctx->wavheaderlength);
227 av_log(NULL, AV_LOG_DEBUG, "audiodatalength = %d\n", ape_ctx->audiodatalength);
228 av_log(NULL, AV_LOG_DEBUG, "audiodatalength_high = %d\n", ape_ctx->audiodatalength_high);
229 av_log(NULL, AV_LOG_DEBUG, "wavtaillength = %d\n", ape_ctx->wavtaillength);
230 av_log(NULL, AV_LOG_DEBUG, "md5 = ");
231 for (i = 0; i < 16; i++)
232 av_log(NULL, AV_LOG_DEBUG, "%02x", ape_ctx->md5[i]);
233 av_log(NULL, AV_LOG_DEBUG, "\n");
234
235 av_log(NULL, AV_LOG_DEBUG, "\nHeader Block:\n\n");
236
237 av_log(NULL, AV_LOG_DEBUG, "compressiontype = %d\n", ape_ctx->compressiontype);
238 av_log(NULL, AV_LOG_DEBUG, "formatflags = %d\n", ape_ctx->formatflags);
239 av_log(NULL, AV_LOG_DEBUG, "blocksperframe = %d\n", ape_ctx->blocksperframe);
240 av_log(NULL, AV_LOG_DEBUG, "finalframeblocks = %d\n", ape_ctx->finalframeblocks);
241 av_log(NULL, AV_LOG_DEBUG, "totalframes = %d\n", ape_ctx->totalframes);
242 av_log(NULL, AV_LOG_DEBUG, "bps = %d\n", ape_ctx->bps);
243 av_log(NULL, AV_LOG_DEBUG, "channels = %d\n", ape_ctx->channels);
244 av_log(NULL, AV_LOG_DEBUG, "samplerate = %d\n", ape_ctx->samplerate);
245
246 av_log(NULL, AV_LOG_DEBUG, "\nSeektable\n\n");
247 if ((ape_ctx->seektablelength / sizeof(uint32_t)) != ape_ctx->totalframes) {
248 av_log(NULL, AV_LOG_DEBUG, "No seektable\n");
249 } else {
250 for (i = 0; i < ape_ctx->seektablelength / sizeof(uint32_t); i++) {
251 if (i < ape_ctx->totalframes - 1) {
252 av_log(NULL, AV_LOG_DEBUG, "%8d %d (%d bytes)\n", i, ape_ctx->seektable[i], ape_ctx->seektable[i + 1] - ape_ctx->seektable[i]);
253 } else {
254 av_log(NULL, AV_LOG_DEBUG, "%8d %d\n", i, ape_ctx->seektable[i]);
255 }
256 }
257 }
258
259 av_log(NULL, AV_LOG_DEBUG, "\nFrames\n\n");
260 for (i = 0; i < ape_ctx->totalframes; i++)
261 av_log(NULL, AV_LOG_DEBUG, "%8d %8lld %8d (%d samples)\n", i, ape_ctx->frames[i].pos, ape_ctx->frames[i].size, ape_ctx->frames[i].nblocks);
262
263 av_log(NULL, AV_LOG_DEBUG, "\nCalculated information:\n\n");
264 av_log(NULL, AV_LOG_DEBUG, "junklength = %d\n", ape_ctx->junklength);
265 av_log(NULL, AV_LOG_DEBUG, "firstframe = %d\n", ape_ctx->firstframe);
266 av_log(NULL, AV_LOG_DEBUG, "totalsamples = %d\n", ape_ctx->totalsamples);
267#endif
268}
269
270static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap)
271{
272 ByteIOContext *pb = s->pb;
273 APEContext *ape = s->priv_data;
274 AVStream *st;
275 uint32_t tag;
276 int i;
277 int total_blocks;
278 int64_t pts;
279
280 /* TODO: Skip any leading junk such as id3v2 tags */
281 ape->junklength = 0;
282
283 tag = get_le32(pb);
284 if (tag != MKTAG('M', 'A', 'C', ' '))
285 return -1;
286
287 ape->fileversion = get_le16(pb);
288
289 if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) {
290 av_log(s, AV_LOG_ERROR, "Unsupported file version - %d.%02d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10);
291 return -1;
292 }
293
294 if (ape->fileversion >= 3980) {
295 ape->padding1 = get_le16(pb);
296 ape->descriptorlength = get_le32(pb);
297 ape->headerlength = get_le32(pb);
298 ape->seektablelength = get_le32(pb);
299 ape->wavheaderlength = get_le32(pb);
300 ape->audiodatalength = get_le32(pb);
301 ape->audiodatalength_high = get_le32(pb);
302 ape->wavtaillength = get_le32(pb);
303 get_buffer(pb, ape->md5, 16);
304
305 /* Skip any unknown bytes at the end of the descriptor.
306 This is for future compatibility */
307 if (ape->descriptorlength > 52)
308 url_fseek(pb, ape->descriptorlength - 52, SEEK_CUR);
309
310 /* Read header data */
311 ape->compressiontype = get_le16(pb);
312 ape->formatflags = get_le16(pb);
313 ape->blocksperframe = get_le32(pb);
314 ape->finalframeblocks = get_le32(pb);
315 ape->totalframes = get_le32(pb);
316 ape->bps = get_le16(pb);
317 ape->channels = get_le16(pb);
318 ape->samplerate = get_le32(pb);
319 } else {
320 ape->descriptorlength = 0;
321 ape->headerlength = 32;
322
323 ape->compressiontype = get_le16(pb);
324 ape->formatflags = get_le16(pb);
325 ape->channels = get_le16(pb);
326 ape->samplerate = get_le32(pb);
327 ape->wavheaderlength = get_le32(pb);
328 ape->wavtaillength = get_le32(pb);
329 ape->totalframes = get_le32(pb);
330 ape->finalframeblocks = get_le32(pb);
331
332 if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) {
333 url_fseek(pb, 4, SEEK_CUR); /* Skip the peak level */
334 ape->headerlength += 4;
335 }
336
337 if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) {
338 ape->seektablelength = get_le32(pb);
339 ape->headerlength += 4;
340 ape->seektablelength *= sizeof(int32_t);
341 } else
342 ape->seektablelength = ape->totalframes * sizeof(int32_t);
343
344 if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT)
345 ape->bps = 8;
346 else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT)
347 ape->bps = 24;
348 else
349 ape->bps = 16;
350
351 if (ape->fileversion >= 3950)
352 ape->blocksperframe = 73728 * 4;
353 else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800 && ape->compressiontype >= 4000))
354 ape->blocksperframe = 73728;
355 else
356 ape->blocksperframe = 9216;
357
358 /* Skip any stored wav header */
359 if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER))
360 url_fskip(pb, ape->wavheaderlength);
361 }
362
363 if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){
364 av_log(s, AV_LOG_ERROR, "Too many frames: %d\n", ape->totalframes);
365 return -1;
366 }
367 ape->frames = av_malloc(ape->totalframes * sizeof(APEFrame));
368 if(!ape->frames)
369 return AVERROR_NOMEM;
370 ape->firstframe = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength;
371 ape->currentframe = 0;
372
373
374 ape->totalsamples = ape->finalframeblocks;
375 if (ape->totalframes > 1)
376 ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1);
377
378 if (ape->seektablelength > 0) {
379 ape->seektable = av_malloc(ape->seektablelength);
380 for (i = 0; i < ape->seektablelength / sizeof(uint32_t); i++)
381 ape->seektable[i] = get_le32(pb);
382 }
383
384 ape->frames[0].pos = ape->firstframe;
385 ape->frames[0].nblocks = ape->blocksperframe;
386 ape->frames[0].skip = 0;
387 for (i = 1; i < ape->totalframes; i++) {
388 ape->frames[i].pos = ape->seektable[i]; //ape->frames[i-1].pos + ape->blocksperframe;
389 ape->frames[i].nblocks = ape->blocksperframe;
390 ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos;
391 ape->frames[i].skip = (ape->frames[i].pos - ape->frames[0].pos) & 3;
392 }
393 ape->frames[ape->totalframes - 1].size = ape->finalframeblocks * 4;
394 ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks;
395
396 for (i = 0; i < ape->totalframes; i++) {
397 if(ape->frames[i].skip){
398 ape->frames[i].pos -= ape->frames[i].skip;
399 ape->frames[i].size += ape->frames[i].skip;
400 }
401 ape->frames[i].size = (ape->frames[i].size + 3) & ~3;
402 }
403
404
405 ape_dumpinfo(ape);
406
407 /* try to read APE tags */
408 if (!url_is_streamed(pb)) {
409 ape_parse_tag(s);
410 url_fseek(pb, 0, SEEK_SET);
411 }
412
413 av_log(s, AV_LOG_DEBUG, "Decoding file - v%d.%02d, compression level %d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10, ape->compressiontype);
414
415 /* now we are ready: build format streams */
416 st = av_new_stream(s, 0);
417 if (!st)
418 return -1;
419
420 total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks;
421
422 st->codec->codec_type = CODEC_TYPE_AUDIO;
423 st->codec->codec_id = CODEC_ID_APE;
424 st->codec->codec_tag = MKTAG('A', 'P', 'E', ' ');
425 st->codec->channels = ape->channels;
426 st->codec->sample_rate = ape->samplerate;
427 st->codec->bits_per_sample = ape->bps;
428 st->codec->frame_size = MAC_SUBFRAME_SIZE;
429
430 st->nb_frames = ape->totalframes;
431 s->start_time = 0;
432 s->duration = (int64_t) total_blocks * AV_TIME_BASE / ape->samplerate;
433 av_set_pts_info(st, 64, MAC_SUBFRAME_SIZE, ape->samplerate);
434
435 st->codec->extradata = av_malloc(APE_EXTRADATA_SIZE);
436 st->codec->extradata_size = APE_EXTRADATA_SIZE;
437 AV_WL16(st->codec->extradata + 0, ape->fileversion);
438 AV_WL16(st->codec->extradata + 2, ape->compressiontype);
439 AV_WL16(st->codec->extradata + 4, ape->formatflags);
440
441 pts = 0;
442 for (i = 0; i < ape->totalframes; i++) {
443 ape->frames[i].pts = pts;
444 av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME);
445 pts += ape->blocksperframe / MAC_SUBFRAME_SIZE;
446 }
447
448 return 0;
449}
450
451static int ape_read_packet(AVFormatContext * s, AVPacket * pkt)
452{
453 int ret;
454 int nblocks;
455 APEContext *ape = s->priv_data;
456 uint32_t extra_size = 8;
457
458 if (url_feof(s->pb))
459 return AVERROR_IO;
460 if (ape->currentframe > ape->totalframes)
461 return AVERROR_IO;
462
463 url_fseek (s->pb, ape->frames[ape->currentframe].pos, SEEK_SET);
464
465 /* Calculate how many blocks there are in this frame */
466 if (ape->currentframe == (ape->totalframes - 1))
467 nblocks = ape->finalframeblocks;
468 else
469 nblocks = ape->blocksperframe;
470
471 if (av_new_packet(pkt, ape->frames[ape->currentframe].size + extra_size) < 0)
472 return AVERROR_NOMEM;
473
474 AV_WL32(pkt->data , nblocks);
475 AV_WL32(pkt->data + 4, ape->frames[ape->currentframe].skip);
476 ret = get_buffer(s->pb, pkt->data + extra_size, ape->frames[ape->currentframe].size);
477
478 pkt->pts = ape->frames[ape->currentframe].pts;
479 pkt->stream_index = 0;
480
481 /* note: we need to modify the packet size here to handle the last
482 packet */
483 pkt->size = ret + extra_size;
484
485 ape->currentframe++;
486
487 return 0;
488}
489
490static int ape_read_close(AVFormatContext * s)
491{
492 APEContext *ape = s->priv_data;
493
494 av_freep(&ape->frames);
495 av_freep(&ape->seektable);
496 return 0;
497}
498
499static int ape_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
500{
501 AVStream *st = s->streams[stream_index];
502 APEContext *ape = s->priv_data;
503 int index = av_index_search_timestamp(st, timestamp, flags);
504
505 if (index < 0)
506 return -1;
507
508 ape->currentframe = index;
509 return 0;
510}
511
512AVInputFormat ape_demuxer = {
513 "ape",
514 NULL_IF_CONFIG_SMALL("Monkey's Audio"),
515 sizeof(APEContext),
516 ape_probe,
517 ape_read_header,
518 ape_read_packet,
519 ape_read_close,
520 ape_read_seek,
521 .extensions = "ape,apl,mac"
522};
diff --git a/src/plugins/ffmpeg/libavformat/asf-enc.c b/src/plugins/ffmpeg/libavformat/asf-enc.c
deleted file mode 100644
index 1817db0..0000000
--- a/src/plugins/ffmpeg/libavformat/asf-enc.c
+++ /dev/null
@@ -1,855 +0,0 @@
1/*
2 * Adaptive stream format muxer
3 * Copyright (c) 2000, 2001 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#include "avformat.h"
22#include "riff.h"
23#include "asf.h"
24
25#undef NDEBUG
26#include <assert.h>
27
28
29#define ASF_INDEXED_INTERVAL 10000000
30#define ASF_INDEX_BLOCK 600
31
32#define ASF_PACKET_ERROR_CORRECTION_DATA_SIZE 0x2
33#define ASF_PACKET_ERROR_CORRECTION_FLAGS (\
34 ASF_PACKET_FLAG_ERROR_CORRECTION_PRESENT | \
35 ASF_PACKET_ERROR_CORRECTION_DATA_SIZE\
36 )
37
38#if (ASF_PACKET_ERROR_CORRECTION_FLAGS != 0)
39# define ASF_PACKET_ERROR_CORRECTION_FLAGS_FIELD_SIZE 1
40#else
41# define ASF_PACKET_ERROR_CORRECTION_FLAGS_FIELD_SIZE 0
42#endif
43
44#define ASF_PPI_PROPERTY_FLAGS (\
45 ASF_PL_FLAG_REPLICATED_DATA_LENGTH_FIELD_IS_BYTE | \
46 ASF_PL_FLAG_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_IS_DWORD | \
47 ASF_PL_FLAG_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_IS_BYTE | \
48 ASF_PL_FLAG_STREAM_NUMBER_LENGTH_FIELD_IS_BYTE \
49 )
50
51#define ASF_PPI_LENGTH_TYPE_FLAGS 0
52
53#define ASF_PAYLOAD_FLAGS ASF_PL_FLAG_PAYLOAD_LENGTH_FIELD_IS_WORD
54
55#if (ASF_PPI_FLAG_SEQUENCE_FIELD_IS_BYTE == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_SEQUENCE_FIELD_SIZE))
56# define ASF_PPI_SEQUENCE_FIELD_SIZE 1
57#endif
58#if (ASF_PPI_FLAG_SEQUENCE_FIELD_IS_WORD == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_SEQUENCE_FIELD_SIZE))
59# define ASF_PPI_SEQUENCE_FIELD_SIZE 2
60#endif
61#if (ASF_PPI_FLAG_SEQUENCE_FIELD_IS_DWORD == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_SEQUENCE_FIELD_SIZE))
62# define ASF_PPI_SEQUENCE_FIELD_SIZE 4
63#endif
64#ifndef ASF_PPI_SEQUENCE_FIELD_SIZE
65# define ASF_PPI_SEQUENCE_FIELD_SIZE 0
66#endif
67
68
69#if (ASF_PPI_FLAG_PACKET_LENGTH_FIELD_IS_BYTE == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_PACKET_LENGTH_FIELD_SIZE))
70# define ASF_PPI_PACKET_LENGTH_FIELD_SIZE 1
71#endif
72#if (ASF_PPI_FLAG_PACKET_LENGTH_FIELD_IS_WORD == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_PACKET_LENGTH_FIELD_SIZE))
73# define ASF_PPI_PACKET_LENGTH_FIELD_SIZE 2
74#endif
75#if (ASF_PPI_FLAG_PACKET_LENGTH_FIELD_IS_DWORD == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_PACKET_LENGTH_FIELD_SIZE))
76# define ASF_PPI_PACKET_LENGTH_FIELD_SIZE 4
77#endif
78#ifndef ASF_PPI_PACKET_LENGTH_FIELD_SIZE
79# define ASF_PPI_PACKET_LENGTH_FIELD_SIZE 0
80#endif
81
82#if (ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_BYTE == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_PADDING_LENGTH_FIELD_SIZE))
83# define ASF_PPI_PADDING_LENGTH_FIELD_SIZE 1
84#endif
85#if (ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_WORD == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_PADDING_LENGTH_FIELD_SIZE))
86# define ASF_PPI_PADDING_LENGTH_FIELD_SIZE 2
87#endif
88#if (ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_DWORD == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_PADDING_LENGTH_FIELD_SIZE))
89# define ASF_PPI_PADDING_LENGTH_FIELD_SIZE 4
90#endif
91#ifndef ASF_PPI_PADDING_LENGTH_FIELD_SIZE
92# define ASF_PPI_PADDING_LENGTH_FIELD_SIZE 0
93#endif
94
95#if (ASF_PL_FLAG_REPLICATED_DATA_LENGTH_FIELD_IS_BYTE == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_REPLICATED_DATA_LENGTH_FIELD_SIZE))
96# define ASF_PAYLOAD_REPLICATED_DATA_LENGTH_FIELD_SIZE 1
97#endif
98#if (ASF_PL_FLAG_REPLICATED_DATA_LENGTH_FIELD_IS_WORD == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_REPLICATED_DATA_LENGTH_FIELD_SIZE))
99# define ASF_PAYLOAD_REPLICATED_DATA_LENGTH_FIELD_SIZE 2
100#endif
101#if (ASF_PL_FLAG_REPLICATED_DATA_LENGTH_FIELD_IS_DWORD == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_REPLICATED_DATA_LENGTH_FIELD_SIZE))
102# define ASF_PAYLOAD_REPLICATED_DATA_LENGTH_FIELD_SIZE 4
103#endif
104#ifndef ASF_PAYLOAD_REPLICATED_DATA_LENGTH_FIELD_SIZE
105# define ASF_PAYLOAD_REPLICATED_DATA_LENGTH_FIELD_SIZE 0
106#endif
107
108#if (ASF_PL_FLAG_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_IS_BYTE == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_SIZE))
109# define ASF_PAYLOAD_OFFSET_INTO_MEDIA_OBJECT_FIELD_SIZE 1
110#endif
111#if (ASF_PL_FLAG_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_IS_WORD == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_SIZE))
112# define ASF_PAYLOAD_OFFSET_INTO_MEDIA_OBJECT_FIELD_SIZE 2
113#endif
114#if (ASF_PL_FLAG_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_IS_DWORD == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_SIZE))
115# define ASF_PAYLOAD_OFFSET_INTO_MEDIA_OBJECT_FIELD_SIZE 4
116#endif
117#ifndef ASF_PAYLOAD_OFFSET_INTO_MEDIA_OBJECT_FIELD_SIZE
118# define ASF_PAYLOAD_OFFSET_INTO_MEDIA_OBJECT_FIELD_SIZE 0
119#endif
120
121#if (ASF_PL_FLAG_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_IS_BYTE == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_SIZE))
122# define ASF_PAYLOAD_MEDIA_OBJECT_NUMBER_FIELD_SIZE 1
123#endif
124#if (ASF_PL_FLAG_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_IS_WORD == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_SIZE))
125# define ASF_PAYLOAD_MEDIA_OBJECT_NUMBER_FIELD_SIZE 2
126#endif
127#if (ASF_PL_FLAG_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_IS_DWORD == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_SIZE))
128# define ASF_PAYLOAD_MEDIA_OBJECT_NUMBER_FIELD_SIZE 4
129#endif
130#ifndef ASF_PAYLOAD_MEDIA_OBJECT_NUMBER_FIELD_SIZE
131# define ASF_PAYLOAD_MEDIA_OBJECT_NUMBER_FIELD_SIZE 0
132#endif
133
134#if (ASF_PL_FLAG_PAYLOAD_LENGTH_FIELD_IS_BYTE == (ASF_PAYLOAD_FLAGS & ASF_PL_MASK_PAYLOAD_LENGTH_FIELD_SIZE))
135# define ASF_PAYLOAD_LENGTH_FIELD_SIZE 1
136#endif
137#if (ASF_PL_FLAG_PAYLOAD_LENGTH_FIELD_IS_WORD == (ASF_PAYLOAD_FLAGS & ASF_PL_MASK_PAYLOAD_LENGTH_FIELD_SIZE))
138# define ASF_PAYLOAD_LENGTH_FIELD_SIZE 2
139#endif
140#ifndef ASF_PAYLOAD_LENGTH_FIELD_SIZE
141# define ASF_PAYLOAD_LENGTH_FIELD_SIZE 0
142#endif
143
144#define PACKET_HEADER_MIN_SIZE (\
145 ASF_PACKET_ERROR_CORRECTION_FLAGS_FIELD_SIZE + \
146 ASF_PACKET_ERROR_CORRECTION_DATA_SIZE + \
147 1 + /*Length Type Flags*/ \
148 1 + /*Property Flags*/ \
149 ASF_PPI_PACKET_LENGTH_FIELD_SIZE + \
150 ASF_PPI_SEQUENCE_FIELD_SIZE + \
151 ASF_PPI_PADDING_LENGTH_FIELD_SIZE + \
152 4 + /*Send Time Field*/ \
153 2 /*Duration Field*/ \
154 )
155
156
157// Replicated Data shall be at least 8 bytes long.
158#define ASF_PAYLOAD_REPLICATED_DATA_LENGTH 0x08
159
160#define PAYLOAD_HEADER_SIZE_SINGLE_PAYLOAD (\
161 1 + /*Stream Number*/ \
162 ASF_PAYLOAD_MEDIA_OBJECT_NUMBER_FIELD_SIZE + \
163 ASF_PAYLOAD_OFFSET_INTO_MEDIA_OBJECT_FIELD_SIZE + \
164 ASF_PAYLOAD_REPLICATED_DATA_LENGTH_FIELD_SIZE + \
165 ASF_PAYLOAD_REPLICATED_DATA_LENGTH \
166 )
167
168#define PAYLOAD_HEADER_SIZE_MULTIPLE_PAYLOADS (\
169 1 + /*Stream Number*/ \
170 ASF_PAYLOAD_MEDIA_OBJECT_NUMBER_FIELD_SIZE + \
171 ASF_PAYLOAD_OFFSET_INTO_MEDIA_OBJECT_FIELD_SIZE + \
172 ASF_PAYLOAD_REPLICATED_DATA_LENGTH_FIELD_SIZE + \
173 ASF_PAYLOAD_REPLICATED_DATA_LENGTH + \
174 ASF_PAYLOAD_LENGTH_FIELD_SIZE \
175 )
176
177#define SINGLE_PAYLOAD_DATA_LENGTH (\
178 PACKET_SIZE - \
179 PACKET_HEADER_MIN_SIZE - \
180 PAYLOAD_HEADER_SIZE_SINGLE_PAYLOAD \
181 )
182
183#define MULTI_PAYLOAD_CONSTANT (\
184 PACKET_SIZE - \
185 PACKET_HEADER_MIN_SIZE - \
186 1 - /*Payload Flags*/ \
187 2*PAYLOAD_HEADER_SIZE_MULTIPLE_PAYLOADS \
188 )
189
190static const AVCodecTag codec_asf_bmp_tags[] = {
191 { CODEC_ID_MPEG4, MKTAG('M', 'P', '4', 'S') },
192 { CODEC_ID_MPEG4, MKTAG('M', '4', 'S', '2') },
193 { CODEC_ID_MSMPEG4V3, MKTAG('M', 'P', '4', '3') },
194 { CODEC_ID_NONE, 0 },
195};
196
197#define PREROLL_TIME 3100
198
199static void put_guid(ByteIOContext *s, const GUID *g)
200{
201 assert(sizeof(*g) == 16);
202 put_buffer(s, *g, sizeof(*g));
203}
204
205static void put_str16_nolen(ByteIOContext *s, const char *tag);
206static void put_str16(ByteIOContext *s, const char *tag)
207{
208 put_le16(s,strlen(tag) + 1);
209 put_str16_nolen(s, tag);
210}
211
212static void put_str16_nolen(ByteIOContext *s, const char *tag)
213{
214 int c;
215
216 do{
217 c = (uint8_t)*tag++;
218 put_le16(s, c);
219 }while(c);
220}
221
222static int64_t put_header(ByteIOContext *pb, const GUID *g)
223{
224 int64_t pos;
225
226 pos = url_ftell(pb);
227 put_guid(pb, g);
228 put_le64(pb, 24);
229 return pos;
230}
231
232/* update header size */
233static void end_header(ByteIOContext *pb, int64_t pos)
234{
235 int64_t pos1;
236
237 pos1 = url_ftell(pb);
238 url_fseek(pb, pos + 16, SEEK_SET);
239 put_le64(pb, pos1 - pos);
240 url_fseek(pb, pos1, SEEK_SET);
241}
242
243/* write an asf chunk (only used in streaming case) */
244static void put_chunk(AVFormatContext *s, int type, int payload_length, int flags)
245{
246 ASFContext *asf = s->priv_data;
247 ByteIOContext *pb = s->pb;
248 int length;
249
250 length = payload_length + 8;
251 put_le16(pb, type);
252 put_le16(pb, length); //size
253 put_le32(pb, asf->seqno);//sequence number
254 put_le16(pb, flags); /* unknown bytes */
255 put_le16(pb, length); //size_confirm
256 asf->seqno++;
257}
258
259/* convert from unix to windows time */
260static int64_t unix_to_file_time(int ti)
261{
262 int64_t t;
263
264 t = ti * INT64_C(10000000);
265 t += INT64_C(116444736000000000);
266 return t;
267}
268
269/* write the header (used two times if non streamed) */
270static int asf_write_header1(AVFormatContext *s, int64_t file_size, int64_t data_chunk_size)
271{
272 ASFContext *asf = s->priv_data;
273 ByteIOContext *pb = s->pb;
274 int header_size, n, extra_size, extra_size2, wav_extra_size, file_time;
275 int has_title;
276 AVCodecContext *enc;
277 int64_t header_offset, cur_pos, hpos;
278 int bit_rate;
279 int64_t duration;
280
281 duration = asf->duration + PREROLL_TIME * 10000;
282 has_title = (s->title[0] || s->author[0] || s->copyright[0] || s->comment[0]);
283
284 bit_rate = 0;
285 for(n=0;n<s->nb_streams;n++) {
286 enc = s->streams[n]->codec;
287
288 av_set_pts_info(s->streams[n], 32, 1, 1000); /* 32 bit pts in ms */
289
290 bit_rate += enc->bit_rate;
291 }
292
293 if (asf->is_streamed) {
294 put_chunk(s, 0x4824, 0, 0xc00); /* start of stream (length will be patched later) */
295 }
296
297 put_guid(pb, &asf_header);
298 put_le64(pb, -1); /* header length, will be patched after */
299 put_le32(pb, 3 + has_title + s->nb_streams); /* number of chunks in header */
300 put_byte(pb, 1); /* ??? */
301 put_byte(pb, 2); /* ??? */
302
303 /* file header */
304 header_offset = url_ftell(pb);
305 hpos = put_header(pb, &file_header);
306 put_guid(pb, &my_guid);
307 put_le64(pb, file_size);
308 file_time = 0;
309 put_le64(pb, unix_to_file_time(file_time));
310 put_le64(pb, asf->nb_packets); /* number of packets */
311 put_le64(pb, duration); /* end time stamp (in 100ns units) */
312 put_le64(pb, asf->duration); /* duration (in 100ns units) */
313 put_le64(pb, PREROLL_TIME); /* start time stamp */
314 put_le32(pb, (asf->is_streamed || url_is_streamed(pb)) ? 3 : 2); /* ??? */
315 put_le32(pb, asf->packet_size); /* packet size */
316 put_le32(pb, asf->packet_size); /* packet size */
317 put_le32(pb, bit_rate); /* Nominal data rate in bps */
318 end_header(pb, hpos);
319
320 /* unknown headers */
321 hpos = put_header(pb, &head1_guid);
322 put_guid(pb, &head2_guid);
323 put_le32(pb, 6);
324 put_le16(pb, 0);
325 end_header(pb, hpos);
326
327 /* title and other infos */
328 if (has_title) {
329 hpos = put_header(pb, &comment_header);
330 if ( s->title[0] ) { put_le16(pb, 2 * (strlen(s->title ) + 1)); } else { put_le16(pb, 0); }
331 if ( s->author[0] ) { put_le16(pb, 2 * (strlen(s->author ) + 1)); } else { put_le16(pb, 0); }
332 if ( s->copyright[0] ) { put_le16(pb, 2 * (strlen(s->copyright) + 1)); } else { put_le16(pb, 0); }
333 if ( s->comment[0] ) { put_le16(pb, 2 * (strlen(s->comment ) + 1)); } else { put_le16(pb, 0); }
334 put_le16(pb, 0);
335 if ( s->title[0] ) put_str16_nolen(pb, s->title);
336 if ( s->author[0] ) put_str16_nolen(pb, s->author);
337 if ( s->copyright[0] ) put_str16_nolen(pb, s->copyright);
338 if ( s->comment[0] ) put_str16_nolen(pb, s->comment);
339 end_header(pb, hpos);
340 }
341
342 /* stream headers */
343 for(n=0;n<s->nb_streams;n++) {
344 int64_t es_pos;
345 // ASFStream *stream = &asf->streams[n];
346
347 enc = s->streams[n]->codec;
348 asf->streams[n].num = n + 1;
349 asf->streams[n].seq = 0;
350
351
352 switch(enc->codec_type) {
353 case CODEC_TYPE_AUDIO:
354 wav_extra_size = 0;
355 extra_size = 18 + wav_extra_size;
356 extra_size2 = 8;
357 break;
358 default:
359 case CODEC_TYPE_VIDEO:
360 wav_extra_size = enc->extradata_size;
361 extra_size = 0x33 + wav_extra_size;
362 extra_size2 = 0;
363 break;
364 }
365
366 hpos = put_header(pb, &stream_header);
367 if (enc->codec_type == CODEC_TYPE_AUDIO) {
368 put_guid(pb, &audio_stream);
369 put_guid(pb, &audio_conceal_spread);
370 } else {
371 put_guid(pb, &video_stream);
372 put_guid(pb, &video_conceal_none);
373 }
374 put_le64(pb, 0); /* ??? */
375 es_pos = url_ftell(pb);
376 put_le32(pb, extra_size); /* wav header len */
377 put_le32(pb, extra_size2); /* additional data len */
378 put_le16(pb, n + 1); /* stream number */
379 put_le32(pb, 0); /* ??? */
380
381 if (enc->codec_type == CODEC_TYPE_AUDIO) {
382 /* WAVEFORMATEX header */
383 int wavsize = put_wav_header(pb, enc);
384 if ((enc->codec_id != CODEC_ID_MP3) && (enc->codec_id != CODEC_ID_MP2) && (enc->codec_id != CODEC_ID_ADPCM_IMA_WAV) && (enc->extradata_size==0)) {
385 wavsize += 2;
386 put_le16(pb, 0);
387 }
388
389 if (wavsize < 0)
390 return -1;
391 if (wavsize != extra_size) {
392 cur_pos = url_ftell(pb);
393 url_fseek(pb, es_pos, SEEK_SET);
394 put_le32(pb, wavsize); /* wav header len */
395 url_fseek(pb, cur_pos, SEEK_SET);
396 }
397 /* ERROR Correction */
398 put_byte(pb, 0x01);
399 if(enc->codec_id == CODEC_ID_ADPCM_G726 || !enc->block_align){
400 put_le16(pb, 0x0190);
401 put_le16(pb, 0x0190);
402 }else{
403 put_le16(pb, enc->block_align);
404 put_le16(pb, enc->block_align);
405 }
406 put_le16(pb, 0x01);
407 put_byte(pb, 0x00);
408 } else {
409 put_le32(pb, enc->width);
410 put_le32(pb, enc->height);
411 put_byte(pb, 2); /* ??? */
412 put_le16(pb, 40 + enc->extradata_size); /* size */
413
414 /* BITMAPINFOHEADER header */
415 put_bmp_header(pb, enc, codec_bmp_tags, 1);
416 }
417 end_header(pb, hpos);
418 }
419
420 /* media comments */
421
422 hpos = put_header(pb, &codec_comment_header);
423 put_guid(pb, &codec_comment1_header);
424 put_le32(pb, s->nb_streams);
425 for(n=0;n<s->nb_streams;n++) {
426 AVCodec *p;
427
428 enc = s->streams[n]->codec;
429 p = avcodec_find_encoder(enc->codec_id);
430
431 if(enc->codec_type == CODEC_TYPE_AUDIO)
432 put_le16(pb, 2);
433 else if(enc->codec_type == CODEC_TYPE_VIDEO)
434 put_le16(pb, 1);
435 else
436 put_le16(pb, -1);
437
438 if(enc->codec_id == CODEC_ID_WMAV2)
439 put_str16(pb, "Windows Media Audio V8");
440 else
441 put_str16(pb, p ? p->name : enc->codec_name);
442 put_le16(pb, 0); /* no parameters */
443
444
445 /* id */
446 if (enc->codec_type == CODEC_TYPE_AUDIO) {
447 put_le16(pb, 2);
448 put_le16(pb, enc->codec_tag);
449 } else {
450 put_le16(pb, 4);
451 put_le32(pb, enc->codec_tag);
452 }
453 if(!enc->codec_tag)
454 return -1;
455 }
456 end_header(pb, hpos);
457
458 /* patch the header size fields */
459
460 cur_pos = url_ftell(pb);
461 header_size = cur_pos - header_offset;
462 if (asf->is_streamed) {
463 header_size += 8 + 30 + 50;
464
465 url_fseek(pb, header_offset - 10 - 30, SEEK_SET);
466 put_le16(pb, header_size);
467 url_fseek(pb, header_offset - 2 - 30, SEEK_SET);
468 put_le16(pb, header_size);
469
470 header_size -= 8 + 30 + 50;
471 }
472 header_size += 24 + 6;
473 url_fseek(pb, header_offset - 14, SEEK_SET);
474 put_le64(pb, header_size);
475 url_fseek(pb, cur_pos, SEEK_SET);
476
477 /* movie chunk, followed by packets of packet_size */
478 asf->data_offset = cur_pos;
479 put_guid(pb, &data_header);
480 put_le64(pb, data_chunk_size);
481 put_guid(pb, &my_guid);
482 put_le64(pb, asf->nb_packets); /* nb packets */
483 put_byte(pb, 1); /* ??? */
484 put_byte(pb, 1); /* ??? */
485 return 0;
486}
487
488static int asf_write_header(AVFormatContext *s)
489{
490 ASFContext *asf = s->priv_data;
491
492 asf->packet_size = PACKET_SIZE;
493 asf->nb_packets = 0;
494
495 asf->last_indexed_pts = 0;
496 asf->index_ptr = av_malloc( sizeof(ASFIndex) * ASF_INDEX_BLOCK );
497 asf->nb_index_memory_alloc = ASF_INDEX_BLOCK;
498 asf->nb_index_count = 0;
499 asf->maximum_packet = 0;
500
501 /* the data-chunk-size has to be 50, which is data_size - asf->data_offset
502 * at the moment this function is done. It is needed to use asf as
503 * streamable format. */
504 if (asf_write_header1(s, 0, 50) < 0) {
505 //av_free(asf);
506 return -1;
507 }
508
509 put_flush_packet(s->pb);
510
511 asf->packet_nb_payloads = 0;
512 asf->packet_timestamp_start = -1;
513 asf->packet_timestamp_end = -1;
514 init_put_byte(&asf->pb, asf->packet_buf, asf->packet_size, 1,
515 NULL, NULL, NULL, NULL);
516
517 return 0;
518}
519
520static int asf_write_stream_header(AVFormatContext *s)
521{
522 ASFContext *asf = s->priv_data;
523
524 asf->is_streamed = 1;
525
526 return asf_write_header(s);
527}
528
529static int put_payload_parsing_info(
530 AVFormatContext *s,
531 unsigned int sendtime,
532 unsigned int duration,
533 int nb_payloads,
534 int padsize
535 )
536{
537 ASFContext *asf = s->priv_data;
538 ByteIOContext *pb = s->pb;
539 int ppi_size, i;
540 int64_t start= url_ftell(pb);
541
542 int iLengthTypeFlags = ASF_PPI_LENGTH_TYPE_FLAGS;
543
544 padsize -= PACKET_HEADER_MIN_SIZE;
545 if(asf->multi_payloads_present)
546 padsize--;
547 assert(padsize>=0);
548
549 put_byte(pb, ASF_PACKET_ERROR_CORRECTION_FLAGS);
550 for (i = 0; i < ASF_PACKET_ERROR_CORRECTION_DATA_SIZE; i++){
551 put_byte(pb, 0x0);
552 }
553
554 if (asf->multi_payloads_present)
555 iLengthTypeFlags |= ASF_PPI_FLAG_MULTIPLE_PAYLOADS_PRESENT;
556
557 if (padsize > 0) {
558 if (padsize < 256)
559 iLengthTypeFlags |= ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_BYTE;
560 else
561 iLengthTypeFlags |= ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_WORD;
562 }
563 put_byte(pb, iLengthTypeFlags);
564
565 put_byte(pb, ASF_PPI_PROPERTY_FLAGS);
566
567 if (iLengthTypeFlags & ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_WORD)
568 put_le16(pb, padsize - 2);
569 if (iLengthTypeFlags & ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_BYTE)
570 put_byte(pb, padsize - 1);
571
572 put_le32(pb, sendtime);
573 put_le16(pb, duration);
574 if (asf->multi_payloads_present)
575 put_byte(pb, nb_payloads | ASF_PAYLOAD_FLAGS);
576
577 ppi_size = url_ftell(pb) - start;
578
579 return ppi_size;
580}
581
582static void flush_packet(AVFormatContext *s)
583{
584 ASFContext *asf = s->priv_data;
585 int packet_hdr_size, packet_filled_size;
586
587 assert(asf->packet_timestamp_end >= asf->packet_timestamp_start);
588
589 if (asf->is_streamed) {
590 put_chunk(s, 0x4424, asf->packet_size, 0);
591 }
592
593 packet_hdr_size = put_payload_parsing_info(
594 s,
595 asf->packet_timestamp_start,
596 asf->packet_timestamp_end - asf->packet_timestamp_start,
597 asf->packet_nb_payloads,
598 asf->packet_size_left
599 );
600
601 packet_filled_size = PACKET_SIZE - asf->packet_size_left;
602 assert(packet_hdr_size <= asf->packet_size_left);
603 memset(asf->packet_buf + packet_filled_size, 0, asf->packet_size_left);
604
605 put_buffer(s->pb, asf->packet_buf, asf->packet_size - packet_hdr_size);
606
607 put_flush_packet(s->pb);
608 asf->nb_packets++;
609 asf->packet_nb_payloads = 0;
610 asf->packet_timestamp_start = -1;
611 asf->packet_timestamp_end = -1;
612 init_put_byte(&asf->pb, asf->packet_buf, asf->packet_size, 1,
613 NULL, NULL, NULL, NULL);
614}
615
616static void put_payload_header(
617 AVFormatContext *s,
618 ASFStream *stream,
619 int presentation_time,
620 int m_obj_size,
621 int m_obj_offset,
622 int payload_len,
623 int flags
624 )
625{
626 ASFContext *asf = s->priv_data;
627 ByteIOContext *pb = &asf->pb;
628 int val;
629
630 val = stream->num;
631 if (flags & PKT_FLAG_KEY)
632 val |= ASF_PL_FLAG_KEY_FRAME;
633 put_byte(pb, val);
634
635 put_byte(pb, stream->seq); //Media object number
636 put_le32(pb, m_obj_offset); //Offset Into Media Object
637
638 // Replicated Data shall be at least 8 bytes long.
639 // The first 4 bytes of data shall contain the
640 // Size of the Media Object that the payload belongs to.
641 // The next 4 bytes of data shall contain the
642 // Presentation Time for the media object that the payload belongs to.
643 put_byte(pb, ASF_PAYLOAD_REPLICATED_DATA_LENGTH);
644
645 put_le32(pb, m_obj_size); //Replicated Data - Media Object Size
646 put_le32(pb, presentation_time);//Replicated Data - Presentation Time
647
648 if (asf->multi_payloads_present){
649 put_le16(pb, payload_len); //payload length
650 }
651}
652
653static void put_frame(
654 AVFormatContext *s,
655 ASFStream *stream,
656 AVStream *avst,
657 int timestamp,
658 const uint8_t *buf,
659 int m_obj_size,
660 int flags
661 )
662{
663 ASFContext *asf = s->priv_data;
664 int m_obj_offset, payload_len, frag_len1;
665
666 m_obj_offset = 0;
667 while (m_obj_offset < m_obj_size) {
668 payload_len = m_obj_size - m_obj_offset;
669 if (asf->packet_timestamp_start == -1) {
670 asf->multi_payloads_present = (payload_len < MULTI_PAYLOAD_CONSTANT);
671
672 asf->packet_size_left = PACKET_SIZE;
673 if (asf->multi_payloads_present){
674 frag_len1 = MULTI_PAYLOAD_CONSTANT - 1;
675 }
676 else {
677 frag_len1 = SINGLE_PAYLOAD_DATA_LENGTH;
678 }
679 asf->packet_timestamp_start = timestamp;
680 }
681 else {
682 // multi payloads
683 frag_len1 = asf->packet_size_left - PAYLOAD_HEADER_SIZE_MULTIPLE_PAYLOADS - PACKET_HEADER_MIN_SIZE - 1;
684
685 if(frag_len1 < payload_len && avst->codec->codec_type == CODEC_TYPE_AUDIO){
686 flush_packet(s);
687 continue;
688 }
689 }
690 if (frag_len1 > 0) {
691 if (payload_len > frag_len1)
692 payload_len = frag_len1;
693 else if (payload_len == (frag_len1 - 1))
694 payload_len = frag_len1 - 2; //additional byte need to put padding length
695
696 put_payload_header(s, stream, timestamp+PREROLL_TIME, m_obj_size, m_obj_offset, payload_len, flags);
697 put_buffer(&asf->pb, buf, payload_len);
698
699 if (asf->multi_payloads_present)
700 asf->packet_size_left -= (payload_len + PAYLOAD_HEADER_SIZE_MULTIPLE_PAYLOADS);
701 else
702 asf->packet_size_left -= (payload_len + PAYLOAD_HEADER_SIZE_SINGLE_PAYLOAD);
703 asf->packet_timestamp_end = timestamp;
704
705 asf->packet_nb_payloads++;
706 } else {
707 payload_len = 0;
708 }
709 m_obj_offset += payload_len;
710 buf += payload_len;
711
712 if (!asf->multi_payloads_present)
713 flush_packet(s);
714 else if (asf->packet_size_left <= (PAYLOAD_HEADER_SIZE_MULTIPLE_PAYLOADS + PACKET_HEADER_MIN_SIZE + 1))
715 flush_packet(s);
716 }
717 stream->seq++;
718}
719
720static int asf_write_packet(AVFormatContext *s, AVPacket *pkt)
721{
722 ASFContext *asf = s->priv_data;
723 ASFStream *stream;
724 int64_t duration;
725 AVCodecContext *codec;
726 int64_t packet_st,pts;
727 int start_sec,i;
728 int flags= pkt->flags;
729
730 codec = s->streams[pkt->stream_index]->codec;
731 stream = &asf->streams[pkt->stream_index];
732
733 if(codec->codec_type == CODEC_TYPE_AUDIO)
734 flags &= ~PKT_FLAG_KEY;
735
736 pts = (pkt->pts != AV_NOPTS_VALUE) ? pkt->pts : pkt->dts;
737 assert(pts != AV_NOPTS_VALUE);
738 duration = pts * 10000;
739 asf->duration= FFMAX(asf->duration, duration + pkt->duration * 10000);
740
741 packet_st = asf->nb_packets;
742 put_frame(s, stream, s->streams[pkt->stream_index], pkt->dts, pkt->data, pkt->size, flags);
743
744 /* check index */
745 if ((!asf->is_streamed) && (flags & PKT_FLAG_KEY)) {
746 start_sec = (int)(duration / INT64_C(10000000));
747 if (start_sec != (int)(asf->last_indexed_pts / INT64_C(10000000))) {
748 for(i=asf->nb_index_count;i<start_sec;i++) {
749 if (i>=asf->nb_index_memory_alloc) {
750 asf->nb_index_memory_alloc += ASF_INDEX_BLOCK;
751 asf->index_ptr = (ASFIndex*)av_realloc( asf->index_ptr, sizeof(ASFIndex) * asf->nb_index_memory_alloc );
752 }
753 // store
754 asf->index_ptr[i].packet_number = (uint32_t)packet_st;
755 asf->index_ptr[i].packet_count = (uint16_t)(asf->nb_packets-packet_st);
756 asf->maximum_packet = FFMAX(asf->maximum_packet, (uint16_t)(asf->nb_packets-packet_st));
757 }
758 asf->nb_index_count = start_sec;
759 asf->last_indexed_pts = duration;
760 }
761 }
762 return 0;
763}
764
765//
766static int asf_write_index(AVFormatContext *s, ASFIndex *index, uint16_t max, uint32_t count)
767{
768 ByteIOContext *pb = s->pb;
769 int i;
770
771 put_guid(pb, &simple_index_header);
772 put_le64(pb, 24 + 16 + 8 + 4 + 4 + (4 + 2)*count);
773 put_guid(pb, &my_guid);
774 put_le64(pb, ASF_INDEXED_INTERVAL);
775 put_le32(pb, max);
776 put_le32(pb, count);
777 for(i=0; i<count; i++) {
778 put_le32(pb, index[i].packet_number);
779 put_le16(pb, index[i].packet_count);
780 }
781
782 return 0;
783}
784
785static int asf_write_trailer(AVFormatContext *s)
786{
787 ASFContext *asf = s->priv_data;
788 int64_t file_size,data_size;
789
790 /* flush the current packet */
791 if (asf->pb.buf_ptr > asf->pb.buffer)
792 flush_packet(s);
793
794 /* write index */
795 data_size = url_ftell(s->pb);
796 if ((!asf->is_streamed) && (asf->nb_index_count != 0)) {
797 asf_write_index(s, asf->index_ptr, asf->maximum_packet, asf->nb_index_count);
798 }
799 put_flush_packet(s->pb);
800
801 if (asf->is_streamed || url_is_streamed(s->pb)) {
802 put_chunk(s, 0x4524, 0, 0); /* end of stream */
803 } else {
804 /* rewrite an updated header */
805 file_size = url_ftell(s->pb);
806 url_fseek(s->pb, 0, SEEK_SET);
807 asf_write_header1(s, file_size, data_size - asf->data_offset);
808 }
809
810 put_flush_packet(s->pb);
811 av_free(asf->index_ptr);
812 return 0;
813}
814
815#ifdef CONFIG_ASF_MUXER
816AVOutputFormat asf_muxer = {
817 "asf",
818 NULL_IF_CONFIG_SMALL("ASF format"),
819 "video/x-ms-asf",
820 "asf,wmv,wma",
821 sizeof(ASFContext),
822#ifdef CONFIG_LIBMP3LAME
823 CODEC_ID_MP3,
824#else
825 CODEC_ID_MP2,
826#endif
827 CODEC_ID_MSMPEG4V3,
828 asf_write_header,
829 asf_write_packet,
830 asf_write_trailer,
831 .flags = AVFMT_GLOBALHEADER,
832 .codec_tag= (const AVCodecTag*[]){codec_asf_bmp_tags, codec_bmp_tags, codec_wav_tags, 0},
833};
834#endif
835
836#ifdef CONFIG_ASF_STREAM_MUXER
837AVOutputFormat asf_stream_muxer = {
838 "asf_stream",
839 NULL_IF_CONFIG_SMALL("ASF format"),
840 "video/x-ms-asf",
841 "asf,wmv,wma",
842 sizeof(ASFContext),
843#ifdef CONFIG_LIBMP3LAME
844 CODEC_ID_MP3,
845#else
846 CODEC_ID_MP2,
847#endif
848 CODEC_ID_MSMPEG4V3,
849 asf_write_stream_header,
850 asf_write_packet,
851 asf_write_trailer,
852 .flags = AVFMT_GLOBALHEADER,
853 .codec_tag= (const AVCodecTag*[]){codec_asf_bmp_tags, codec_bmp_tags, codec_wav_tags, 0},
854};
855#endif //CONFIG_ASF_STREAM_MUXER
diff --git a/src/plugins/ffmpeg/libavformat/asf.c b/src/plugins/ffmpeg/libavformat/asf.c
deleted file mode 100644
index fc0a86e..0000000
--- a/src/plugins/ffmpeg/libavformat/asf.c
+++ /dev/null
@@ -1,1091 +0,0 @@
1/*
2 * ASF compatible demuxer
3 * Copyright (c) 2000, 2001 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/common.h"
23#include "libavcodec/mpegaudio.h"
24#include "avformat.h"
25#include "riff.h"
26#include "asf.h"
27#include "asfcrypt.h"
28
29extern void ff_mms_set_stream_selection(URLContext *h, AVFormatContext *format);
30
31#undef NDEBUG
32#include <assert.h>
33
34#define FRAME_HEADER_SIZE 17
35// Fix Me! FRAME_HEADER_SIZE may be different.
36
37static const GUID index_guid = {
38 0x90, 0x08, 0x00, 0x33, 0xb1, 0xe5, 0xcf, 0x11, 0x89, 0xf4, 0x00, 0xa0, 0xc9, 0x03, 0x49, 0xcb
39};
40
41static const GUID stream_bitrate_guid = { /* (http://get.to/sdp) */
42 0xce, 0x75, 0xf8, 0x7b, 0x8d, 0x46, 0xd1, 0x11, 0x8d, 0x82, 0x00, 0x60, 0x97, 0xc9, 0xa2, 0xb2
43};
44/**********************************/
45/* decoding */
46
47//#define DEBUG
48
49#ifdef DEBUG
50#define PRINT_IF_GUID(g,cmp) \
51if (!memcmp(g, &cmp, sizeof(GUID))) \
52 dprintf(NULL, "(GUID: %s) ", #cmp)
53
54static void print_guid(const GUID *g)
55{
56 int i;
57 PRINT_IF_GUID(g, asf_header);
58 else PRINT_IF_GUID(g, file_header);
59 else PRINT_IF_GUID(g, stream_header);
60 else PRINT_IF_GUID(g, audio_stream);
61 else PRINT_IF_GUID(g, audio_conceal_none);
62 else PRINT_IF_GUID(g, video_stream);
63 else PRINT_IF_GUID(g, video_conceal_none);
64 else PRINT_IF_GUID(g, command_stream);
65 else PRINT_IF_GUID(g, comment_header);
66 else PRINT_IF_GUID(g, codec_comment_header);
67 else PRINT_IF_GUID(g, codec_comment1_header);
68 else PRINT_IF_GUID(g, data_header);
69 else PRINT_IF_GUID(g, index_guid);
70 else PRINT_IF_GUID(g, head1_guid);
71 else PRINT_IF_GUID(g, head2_guid);
72 else PRINT_IF_GUID(g, my_guid);
73 else PRINT_IF_GUID(g, ext_stream_header);
74 else PRINT_IF_GUID(g, extended_content_header);
75 else PRINT_IF_GUID(g, ext_stream_embed_stream_header);
76 else PRINT_IF_GUID(g, ext_stream_audio_stream);
77 else PRINT_IF_GUID(g, metadata_header);
78 else PRINT_IF_GUID(g, stream_bitrate_guid);
79 else
80 dprintf(NULL, "(GUID: unknown) ");
81 for(i=0;i<16;i++)
82 dprintf(NULL, " 0x%02x,", (*g)[i]);
83 dprintf(NULL, "}\n");
84}
85#undef PRINT_IF_GUID
86#else
87#define print_guid(g)
88#endif
89
90static void get_guid(ByteIOContext *s, GUID *g)
91{
92 assert(sizeof(*g) == 16);
93 get_buffer(s, *g, sizeof(*g));
94}
95
96#if 0
97static void get_str16(ByteIOContext *pb, char *buf, int buf_size)
98{
99 int len, c;
100 char *q;
101
102 len = get_le16(pb);
103 q = buf;
104 while (len > 0) {
105 c = get_le16(pb);
106 if ((q - buf) < buf_size - 1)
107 *q++ = c;
108 len--;
109 }
110 *q = '\0';
111}
112#endif
113
114static void get_str16_nolen(ByteIOContext *pb, int len, char *buf, int buf_size)
115{
116 char* q = buf;
117 len /= 2;
118 while (len--) {
119 uint8_t tmp;
120 PUT_UTF8(get_le16(pb), tmp, if (q - buf < buf_size - 1) *q++ = tmp;)
121 }
122 *q = '\0';
123}
124
125static int asf_probe(AVProbeData *pd)
126{
127 /* check file header */
128 if (!memcmp(pd->buf, &asf_header, sizeof(GUID)))
129 return AVPROBE_SCORE_MAX;
130 else
131 return 0;
132}
133
134static int get_value(ByteIOContext *pb, int type){
135 switch(type){
136 case 2: return get_le32(pb);
137 case 3: return get_le32(pb);
138 case 4: return get_le64(pb);
139 case 5: return get_le16(pb);
140 default:return INT_MIN;
141 }
142}
143
144static int asf_read_header(AVFormatContext *s, AVFormatParameters *ap)
145{
146 ASFContext *asf = s->priv_data;
147 GUID g;
148 ByteIOContext *pb = s->pb;
149 AVStream *st;
150 ASFStream *asf_st;
151 int size, i;
152 int64_t gsize;
153 AVRational dar[128];
154 uint32_t bitrate[128];
155
156 memset(dar, 0, sizeof(dar));
157 memset(bitrate, 0, sizeof(bitrate));
158
159 get_guid(pb, &g);
160 if (memcmp(&g, &asf_header, sizeof(GUID)))
161 return -1;
162 get_le64(pb);
163 get_le32(pb);
164 get_byte(pb);
165 get_byte(pb);
166 memset(&asf->asfid2avid, -1, sizeof(asf->asfid2avid));
167 for(;;) {
168 get_guid(pb, &g);
169 gsize = get_le64(pb);
170 dprintf(s, "%08"PRIx64": ", url_ftell(pb) - 24);
171 print_guid(&g);
172 dprintf(s, " size=0x%"PRIx64"\n", gsize);
173 if (!memcmp(&g, &data_header, sizeof(GUID))) {
174 asf->data_object_offset = url_ftell(pb);
175 // if not streaming, gsize is not unlimited (how?), and there is enough space in the file..
176 if (!(asf->hdr.flags & 0x01) && gsize >= 100) {
177 asf->data_object_size = gsize - 24;
178 } else {
179 asf->data_object_size = (uint64_t)-1;
180 }
181 break;
182 }
183 if (gsize < 24)
184 return -1;
185 if (!memcmp(&g, &file_header, sizeof(GUID))) {
186 get_guid(pb, &asf->hdr.guid);
187 asf->hdr.file_size = get_le64(pb);
188 asf->hdr.create_time = get_le64(pb);
189 asf->nb_packets = get_le64(pb);
190 asf->hdr.play_time = get_le64(pb);
191 asf->hdr.send_time = get_le64(pb);
192 asf->hdr.preroll = get_le32(pb);
193 asf->hdr.ignore = get_le32(pb);
194 asf->hdr.flags = get_le32(pb);
195 asf->hdr.min_pktsize = get_le32(pb);
196 asf->hdr.max_pktsize = get_le32(pb);
197 asf->hdr.max_bitrate = get_le32(pb);
198 asf->packet_size = asf->hdr.max_pktsize;
199 } else if (!memcmp(&g, &stream_header, sizeof(GUID))) {
200 int type, type_specific_size, sizeX;
201 uint64_t total_size;
202 unsigned int tag1;
203 int64_t pos1, pos2, start_time;
204 int test_for_ext_stream_audio, is_dvr_ms_audio=0;
205
206 pos1 = url_ftell(pb);
207
208 st = av_new_stream(s, 0);
209 if (!st)
210 return AVERROR(ENOMEM);
211 av_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
212 asf_st = av_mallocz(sizeof(ASFStream));
213 if (!asf_st)
214 return AVERROR(ENOMEM);
215 st->priv_data = asf_st;
216 start_time = asf->hdr.preroll;
217
218 if(!(asf->hdr.flags & 0x01)) { // if we aren't streaming...
219 st->duration = asf->hdr.send_time /
220 (10000000 / 1000) - start_time;
221 }
222 get_guid(pb, &g);
223
224 test_for_ext_stream_audio = 0;
225 if (!memcmp(&g, &audio_stream, sizeof(GUID))) {
226 type = CODEC_TYPE_AUDIO;
227 } else if (!memcmp(&g, &video_stream, sizeof(GUID))) {
228 type = CODEC_TYPE_VIDEO;
229 } else if (!memcmp(&g, &command_stream, sizeof(GUID))) {
230 type = CODEC_TYPE_DATA;
231 } else if (!memcmp(&g, &ext_stream_embed_stream_header, sizeof(GUID))) {
232 test_for_ext_stream_audio = 1;
233 type = CODEC_TYPE_UNKNOWN;
234 } else {
235 return -1;
236 }
237 get_guid(pb, &g);
238 total_size = get_le64(pb);
239 type_specific_size = get_le32(pb);
240 get_le32(pb);
241 st->id = get_le16(pb) & 0x7f; /* stream id */
242 // mapping of asf ID to AV stream ID;
243 asf->asfid2avid[st->id] = s->nb_streams - 1;
244
245 get_le32(pb);
246
247 if (test_for_ext_stream_audio) {
248 get_guid(pb, &g);
249 if (!memcmp(&g, &ext_stream_audio_stream, sizeof(GUID))) {
250 type = CODEC_TYPE_AUDIO;
251 is_dvr_ms_audio=1;
252 get_guid(pb, &g);
253 get_le32(pb);
254 get_le32(pb);
255 get_le32(pb);
256 get_guid(pb, &g);
257 get_le32(pb);
258 }
259 }
260
261 st->codec->codec_type = type;
262 if (type == CODEC_TYPE_AUDIO) {
263 get_wav_header(pb, st->codec, type_specific_size);
264 if (is_dvr_ms_audio) {
265 // codec_id and codec_tag are unreliable in dvr_ms
266 // files. Set them later by probing stream.
267 st->codec->codec_id = CODEC_ID_PROBE;
268 st->codec->codec_tag = 0;
269 }
270 st->need_parsing = AVSTREAM_PARSE_FULL;
271 /* We have to init the frame size at some point .... */
272 pos2 = url_ftell(pb);
273 if (gsize >= (pos2 + 8 - pos1 + 24)) {
274 asf_st->ds_span = get_byte(pb);
275 asf_st->ds_packet_size = get_le16(pb);
276 asf_st->ds_chunk_size = get_le16(pb);
277 get_le16(pb); //ds_data_size
278 get_byte(pb); //ds_silence_data
279 }
280 //printf("Descrambling: ps:%d cs:%d ds:%d s:%d sd:%d\n",
281 // asf_st->ds_packet_size, asf_st->ds_chunk_size,
282 // asf_st->ds_data_size, asf_st->ds_span, asf_st->ds_silence_data);
283 if (asf_st->ds_span > 1) {
284 if (!asf_st->ds_chunk_size
285 || (asf_st->ds_packet_size/asf_st->ds_chunk_size <= 1)
286 || asf_st->ds_packet_size % asf_st->ds_chunk_size)
287 asf_st->ds_span = 0; // disable descrambling
288 }
289 switch (st->codec->codec_id) {
290 case CODEC_ID_MP3:
291 st->codec->frame_size = MPA_FRAME_SIZE;
292 break;
293 case CODEC_ID_PCM_S16LE:
294 case CODEC_ID_PCM_S16BE:
295 case CODEC_ID_PCM_U16LE:
296 case CODEC_ID_PCM_U16BE:
297 case CODEC_ID_PCM_S8:
298 case CODEC_ID_PCM_U8:
299 case CODEC_ID_PCM_ALAW:
300 case CODEC_ID_PCM_MULAW:
301 st->codec->frame_size = 1;
302 break;
303 default:
304 /* This is probably wrong, but it prevents a crash later */
305 st->codec->frame_size = 1;
306 break;
307 }
308 } else if (type == CODEC_TYPE_VIDEO) {
309 get_le32(pb);
310 get_le32(pb);
311 get_byte(pb);
312 size = get_le16(pb); /* size */
313 sizeX= get_le32(pb); /* size */
314 st->codec->width = get_le32(pb);
315 st->codec->height = get_le32(pb);
316 /* not available for asf */
317 get_le16(pb); /* panes */
318 st->codec->bits_per_sample = get_le16(pb); /* depth */
319 tag1 = get_le32(pb);
320 url_fskip(pb, 20);
321// av_log(NULL, AV_LOG_DEBUG, "size:%d tsize:%d sizeX:%d\n", size, total_size, sizeX);
322 size= sizeX;
323 if (size > 40) {
324 st->codec->extradata_size = size - 40;
325 st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
326 get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
327 }
328
329 /* Extract palette from extradata if bpp <= 8 */
330 /* This code assumes that extradata contains only palette */
331 /* This is true for all paletted codecs implemented in ffmpeg */
332 if (st->codec->extradata_size && (st->codec->bits_per_sample <= 8)) {
333 st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
334#ifdef WORDS_BIGENDIAN
335 for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
336 st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
337#else
338 memcpy(st->codec->palctrl->palette, st->codec->extradata,
339 FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
340#endif
341 st->codec->palctrl->palette_changed = 1;
342 }
343
344 st->codec->codec_tag = tag1;
345 st->codec->codec_id = codec_get_id(codec_bmp_tags, tag1);
346 if(tag1 == MKTAG('D', 'V', 'R', ' '))
347 st->need_parsing = AVSTREAM_PARSE_FULL;
348 }
349 pos2 = url_ftell(pb);
350 url_fskip(pb, gsize - (pos2 - pos1 + 24));
351 } else if (!memcmp(&g, &comment_header, sizeof(GUID))) {
352 int len1, len2, len3, len4, len5;
353
354 len1 = get_le16(pb);
355 len2 = get_le16(pb);
356 len3 = get_le16(pb);
357 len4 = get_le16(pb);
358 len5 = get_le16(pb);
359 get_str16_nolen(pb, len1, s->title , sizeof(s->title));
360 get_str16_nolen(pb, len2, s->author , sizeof(s->author));
361 get_str16_nolen(pb, len3, s->copyright, sizeof(s->copyright));
362 get_str16_nolen(pb, len4, s->comment , sizeof(s->comment));
363 url_fskip(pb, len5);
364 } else if (!memcmp(&g, &stream_bitrate_guid, sizeof(GUID))) {
365 int stream_count = get_le16(pb);
366 int j;
367
368// av_log(NULL, AV_LOG_ERROR, "stream bitrate properties\n");
369// av_log(NULL, AV_LOG_ERROR, "streams %d\n", streams);
370 for(j = 0; j < stream_count; j++) {
371 int flags, bitrate, stream_id;
372
373 flags= get_le16(pb);
374 bitrate= get_le32(pb);
375 stream_id= (flags & 0x7f);
376// av_log(NULL, AV_LOG_ERROR, "flags: 0x%x stream id %d, bitrate %d\n", flags, stream_id, bitrate);
377 asf->stream_bitrates[stream_id]= bitrate;
378 }
379 } else if (!memcmp(&g, &extended_content_header, sizeof(GUID))) {
380 int desc_count, i;
381
382 desc_count = get_le16(pb);
383 for(i=0;i<desc_count;i++)
384 {
385 int name_len,value_type,value_len;
386 uint64_t value_num = 0;
387 char name[1024];
388
389 name_len = get_le16(pb);
390 get_str16_nolen(pb, name_len, name, sizeof(name));
391 value_type = get_le16(pb);
392 value_len = get_le16(pb);
393 if (value_type <= 1) // unicode or byte
394 {
395 if (!strcmp(name,"WM/AlbumTitle")) get_str16_nolen(pb, value_len, s->album, sizeof(s->album));
396 else if(!strcmp(name,"WM/Genre" )) get_str16_nolen(pb, value_len, s->genre, sizeof(s->genre));
397 else if(!strcmp(name,"WM/Year" )) {
398 char year[8];
399 get_str16_nolen(pb, value_len, year, sizeof(year));
400 s->year = atoi(year);
401 }
402 else if(!strcmp(name,"WM/Track") && s->track == 0) {
403 char track[8];
404 get_str16_nolen(pb, value_len, track, sizeof(track));
405 s->track = strtol(track, NULL, 10) + 1;
406 }
407 else if(!strcmp(name,"WM/TrackNumber")) {
408 char track[8];
409 get_str16_nolen(pb, value_len, track, sizeof(track));
410 s->track = strtol(track, NULL, 10);
411 }
412 else url_fskip(pb, value_len);
413 }
414 else if (value_type <= 5) // boolean or DWORD or QWORD or WORD
415 {
416 value_num= get_value(pb, value_type);
417 if (!strcmp(name,"WM/Track" ) && s->track == 0) s->track = value_num + 1;
418 if (!strcmp(name,"WM/TrackNumber")) s->track = value_num;
419 }else
420 url_fskip(pb, value_len);
421 }
422 } else if (!memcmp(&g, &metadata_header, sizeof(GUID))) {
423 int n, stream_num, name_len, value_len, value_type, value_num;
424 n = get_le16(pb);
425
426 for(i=0;i<n;i++) {
427 char name[1024];
428
429 get_le16(pb); //lang_list_index
430 stream_num= get_le16(pb);
431 name_len= get_le16(pb);
432 value_type= get_le16(pb);
433 value_len= get_le32(pb);
434
435 get_str16_nolen(pb, name_len, name, sizeof(name));
436//av_log(NULL, AV_LOG_ERROR, "%d %d %d %d %d <%s>\n", i, stream_num, name_len, value_type, value_len, name);
437 value_num= get_le16(pb);//we should use get_value() here but it does not work 2 is le16 here but le32 elsewhere
438 url_fskip(pb, value_len - 2);
439
440 if(stream_num<128){
441 if (!strcmp(name, "AspectRatioX")) dar[stream_num].num= value_num;
442 else if(!strcmp(name, "AspectRatioY")) dar[stream_num].den= value_num;
443 }
444 }
445 } else if (!memcmp(&g, &ext_stream_header, sizeof(GUID))) {
446 int ext_len, payload_ext_ct, stream_ct;
447 uint32_t ext_d, leak_rate, stream_num;
448 int64_t pos_ex_st;
449 pos_ex_st = url_ftell(pb);
450
451 get_le64(pb); // starttime
452 get_le64(pb); // endtime
453 leak_rate = get_le32(pb); // leak-datarate
454 get_le32(pb); // bucket-datasize
455 get_le32(pb); // init-bucket-fullness
456 get_le32(pb); // alt-leak-datarate
457 get_le32(pb); // alt-bucket-datasize
458 get_le32(pb); // alt-init-bucket-fullness
459 get_le32(pb); // max-object-size
460 get_le32(pb); // flags (reliable,seekable,no_cleanpoints?,resend-live-cleanpoints, rest of bits reserved)
461 stream_num = get_le16(pb); // stream-num
462 get_le16(pb); // stream-language-id-index
463 get_le64(pb); // avg frametime in 100ns units
464 stream_ct = get_le16(pb); //stream-name-count
465 payload_ext_ct = get_le16(pb); //payload-extension-system-count
466
467 if (stream_num < 128)
468 bitrate[stream_num] = leak_rate;
469
470 for (i=0; i<stream_ct; i++){
471 get_le16(pb);
472 ext_len = get_le16(pb);
473 url_fseek(pb, ext_len, SEEK_CUR);
474 }
475
476 for (i=0; i<payload_ext_ct; i++){
477 get_guid(pb, &g);
478 ext_d=get_le16(pb);
479 ext_len=get_le32(pb);
480 url_fseek(pb, ext_len, SEEK_CUR);
481 }
482
483 // there could be a optional stream properties object to follow
484 // if so the next iteration will pick it up
485 } else if (!memcmp(&g, &head1_guid, sizeof(GUID))) {
486 int v1, v2;
487 get_guid(pb, &g);
488 v1 = get_le32(pb);
489 v2 = get_le16(pb);
490#if 0
491 } else if (!memcmp(&g, &codec_comment_header, sizeof(GUID))) {
492 int len, v1, n, num;
493 char str[256], *q;
494 char tag[16];
495
496 get_guid(pb, &g);
497 print_guid(&g);
498
499 n = get_le32(pb);
500 for(i=0;i<n;i++) {
501 num = get_le16(pb); /* stream number */
502 get_str16(pb, str, sizeof(str));
503 get_str16(pb, str, sizeof(str));
504 len = get_le16(pb);
505 q = tag;
506 while (len > 0) {
507 v1 = get_byte(pb);
508 if ((q - tag) < sizeof(tag) - 1)
509 *q++ = v1;
510 len--;
511 }
512 *q = '\0';
513 }
514#endif
515 } else if (url_feof(pb)) {
516 return -1;
517 } else {
518 url_fseek(pb, gsize - 24, SEEK_CUR);
519 }
520 }
521 get_guid(pb, &g);
522 get_le64(pb);
523 get_byte(pb);
524 get_byte(pb);
525 if (url_feof(pb))
526 return -1;
527 asf->data_offset = url_ftell(pb);
528 asf->packet_size_left = 0;
529
530
531 for(i=0; i<128; i++){
532 int stream_num= asf->asfid2avid[i];
533 if(stream_num>=0){
534 AVCodecContext *codec= s->streams[stream_num]->codec;
535 if (!codec->bit_rate)
536 codec->bit_rate = bitrate[i];
537 if (dar[i].num > 0 && dar[i].den > 0)
538 av_reduce(&codec->sample_aspect_ratio.num,
539 &codec->sample_aspect_ratio.den,
540 dar[i].num, dar[i].den, INT_MAX);
541//av_log(NULL, AV_LOG_ERROR, "dar %d:%d sar=%d:%d\n", dar[i].num, dar[i].den, codec->sample_aspect_ratio.num, codec->sample_aspect_ratio.den);
542 }
543 }
544
545 return 0;
546}
547
548#define DO_2BITS(bits, var, defval) \
549 switch (bits & 3) \
550 { \
551 case 3: var = get_le32(pb); rsize += 4; break; \
552 case 2: var = get_le16(pb); rsize += 2; break; \
553 case 1: var = get_byte(pb); rsize++; break; \
554 default: var = defval; break; \
555 }
556
557/**
558 *
559 * @return <0 in case of an error
560 */
561static int asf_get_packet(AVFormatContext *s)
562{
563 ASFContext *asf = s->priv_data;
564 ByteIOContext *pb = s->pb;
565 uint32_t packet_length, padsize;
566 int rsize = 8;
567 int c, d, e, off;
568
569 off= (url_ftell(s->pb) - s->data_offset) % asf->packet_size + 3;
570
571 c=d=e=-1;
572 while(off-- > 0){
573 c=d; d=e;
574 e= get_byte(pb);
575 if(c == 0x82 && !d && !e)
576 break;
577 }
578
579 if (c != 0x82) {
580 if (!url_feof(pb))
581 av_log(s, AV_LOG_ERROR, "ff asf bad header %x at:%"PRId64"\n", c, url_ftell(pb));
582 }
583 if ((c & 0x8f) == 0x82) {
584 if (d || e) {
585 if (!url_feof(pb))
586 av_log(s, AV_LOG_ERROR, "ff asf bad non zero\n");
587 return -1;
588 }
589 c= get_byte(pb);
590 d= get_byte(pb);
591 rsize+=3;
592 }else{
593 url_fseek(pb, -1, SEEK_CUR); //FIXME
594 }
595
596 asf->packet_flags = c;
597 asf->packet_property = d;
598
599 DO_2BITS(asf->packet_flags >> 5, packet_length, asf->packet_size);
600 DO_2BITS(asf->packet_flags >> 1, padsize, 0); // sequence ignored
601 DO_2BITS(asf->packet_flags >> 3, padsize, 0); // padding length
602
603 //the following checks prevent overflows and infinite loops
604 if(packet_length >= (1U<<29)){
605 av_log(s, AV_LOG_ERROR, "invalid packet_length %d at:%"PRId64"\n", packet_length, url_ftell(pb));
606 return -1;
607 }
608 if(padsize >= packet_length){
609 av_log(s, AV_LOG_ERROR, "invalid padsize %d at:%"PRId64"\n", padsize, url_ftell(pb));
610 return -1;
611 }
612
613 asf->packet_timestamp = get_le32(pb);
614 get_le16(pb); /* duration */
615 // rsize has at least 11 bytes which have to be present
616
617 if (asf->packet_flags & 0x01) {
618 asf->packet_segsizetype = get_byte(pb); rsize++;
619 asf->packet_segments = asf->packet_segsizetype & 0x3f;
620 } else {
621 asf->packet_segments = 1;
622 asf->packet_segsizetype = 0x80;
623 }
624 asf->packet_size_left = packet_length - padsize - rsize;
625 if (packet_length < asf->hdr.min_pktsize)
626 padsize += asf->hdr.min_pktsize - packet_length;
627 asf->packet_padsize = padsize;
628 dprintf(s, "packet: size=%d padsize=%d left=%d\n", asf->packet_size, asf->packet_padsize, asf->packet_size_left);
629 return 0;
630}
631
632/**
633 *
634 * @return <0 if error
635 */
636static int asf_read_frame_header(AVFormatContext *s){
637 ASFContext *asf = s->priv_data;
638 ByteIOContext *pb = s->pb;
639 int rsize = 1;
640 int num = get_byte(pb);
641 int64_t ts0, ts1;
642
643 asf->packet_segments--;
644 asf->packet_key_frame = num >> 7;
645 asf->stream_index = asf->asfid2avid[num & 0x7f];
646 // sequence should be ignored!
647 DO_2BITS(asf->packet_property >> 4, asf->packet_seq, 0);
648 DO_2BITS(asf->packet_property >> 2, asf->packet_frag_offset, 0);
649 DO_2BITS(asf->packet_property, asf->packet_replic_size, 0);
650//printf("key:%d stream:%d seq:%d offset:%d replic_size:%d\n", asf->packet_key_frame, asf->stream_index, asf->packet_seq, //asf->packet_frag_offset, asf->packet_replic_size);
651 if (asf->packet_replic_size >= 8) {
652 asf->packet_obj_size = get_le32(pb);
653 if(asf->packet_obj_size >= (1<<24) || asf->packet_obj_size <= 0){
654 av_log(s, AV_LOG_ERROR, "packet_obj_size invalid\n");
655 return -1;
656 }
657 asf->packet_frag_timestamp = get_le32(pb); // timestamp
658 if(asf->packet_replic_size >= 8+38+4){
659// for(i=0; i<asf->packet_replic_size-8; i++)
660// av_log(s, AV_LOG_DEBUG, "%02X ",get_byte(pb));
661// av_log(s, AV_LOG_DEBUG, "\n");
662 url_fskip(pb, 10);
663 ts0= get_le64(pb);
664 ts1= get_le64(pb);
665 url_fskip(pb, 12);
666 get_le32(pb);
667 url_fskip(pb, asf->packet_replic_size - 8 - 38 - 4);
668 if(ts0!= -1) asf->packet_frag_timestamp= ts0/10000;
669 else asf->packet_frag_timestamp= AV_NOPTS_VALUE;
670 }else
671 url_fskip(pb, asf->packet_replic_size - 8);
672 rsize += asf->packet_replic_size; // FIXME - check validity
673 } else if (asf->packet_replic_size==1){
674 // multipacket - frag_offset is beginning timestamp
675 asf->packet_time_start = asf->packet_frag_offset;
676 asf->packet_frag_offset = 0;
677 asf->packet_frag_timestamp = asf->packet_timestamp;
678
679 asf->packet_time_delta = get_byte(pb);
680 rsize++;
681 }else if(asf->packet_replic_size!=0){
682 av_log(s, AV_LOG_ERROR, "unexpected packet_replic_size of %d\n", asf->packet_replic_size);
683 return -1;
684 }
685 if (asf->packet_flags & 0x01) {
686 DO_2BITS(asf->packet_segsizetype >> 6, asf->packet_frag_size, 0); // 0 is illegal
687 if(asf->packet_frag_size > asf->packet_size_left - rsize){
688 av_log(s, AV_LOG_ERROR, "packet_frag_size is invalid\n");
689 return -1;
690 }
691 //printf("Fragsize %d\n", asf->packet_frag_size);
692 } else {
693 asf->packet_frag_size = asf->packet_size_left - rsize;
694 //printf("Using rest %d %d %d\n", asf->packet_frag_size, asf->packet_size_left, rsize);
695 }
696 if (asf->packet_replic_size == 1) {
697 asf->packet_multi_size = asf->packet_frag_size;
698 if (asf->packet_multi_size > asf->packet_size_left)
699 return -1;
700 }
701 asf->packet_size_left -= rsize;
702 //printf("___objsize____ %d %d rs:%d\n", asf->packet_obj_size, asf->packet_frag_offset, rsize);
703
704 return 0;
705}
706
707static int asf_read_packet(AVFormatContext *s, AVPacket *pkt)
708{
709 ASFContext *asf = s->priv_data;
710 ASFStream *asf_st = 0;
711 ByteIOContext *pb = s->pb;
712 //static int pc = 0;
713 for (;;) {
714 if(url_feof(pb))
715 return AVERROR(EIO);
716 if (asf->packet_size_left < FRAME_HEADER_SIZE
717 || asf->packet_segments < 1) {
718 //asf->packet_size_left <= asf->packet_padsize) {
719 int ret = asf->packet_size_left + asf->packet_padsize;
720 //printf("PacketLeftSize:%d Pad:%d Pos:%"PRId64"\n", asf->packet_size_left, asf->packet_padsize, url_ftell(pb));
721 assert(ret>=0);
722 /* fail safe */
723 url_fskip(pb, ret);
724
725 asf->packet_pos= url_ftell(s->pb);
726 if (asf->data_object_size != (uint64_t)-1 &&
727 (asf->packet_pos - asf->data_object_offset >= asf->data_object_size))
728 return AVERROR(EIO); /* Do not exceed the size of the data object */
729 ret = asf_get_packet(s);
730 //printf("READ ASF PACKET %d r:%d c:%d\n", ret, asf->packet_size_left, pc++);
731 if (ret < 0)
732 assert(asf->packet_size_left < FRAME_HEADER_SIZE || asf->packet_segments < 1);
733 asf->packet_time_start = 0;
734 continue;
735 }
736 if (asf->packet_time_start == 0) {
737 if(asf_read_frame_header(s) < 0){
738 asf->packet_segments= 0;
739 continue;
740 }
741 if (asf->stream_index < 0
742 || s->streams[asf->stream_index]->discard >= AVDISCARD_ALL
743 || (!asf->packet_key_frame && s->streams[asf->stream_index]->discard >= AVDISCARD_NONKEY)
744 ) {
745 asf->packet_time_start = 0;
746 /* unhandled packet (should not happen) */
747 url_fskip(pb, asf->packet_frag_size);
748 asf->packet_size_left -= asf->packet_frag_size;
749 if(asf->stream_index < 0)
750 av_log(s, AV_LOG_ERROR, "ff asf skip %d (unknown stream)\n", asf->packet_frag_size);
751 continue;
752 }
753 asf->asf_st = s->streams[asf->stream_index]->priv_data;
754 }
755 asf_st = asf->asf_st;
756
757 if (asf->packet_replic_size == 1) {
758 // frag_offset is here used as the beginning timestamp
759 asf->packet_frag_timestamp = asf->packet_time_start;
760 asf->packet_time_start += asf->packet_time_delta;
761 asf->packet_obj_size = asf->packet_frag_size = get_byte(pb);
762 asf->packet_size_left--;
763 asf->packet_multi_size--;
764 if (asf->packet_multi_size < asf->packet_obj_size)
765 {
766 asf->packet_time_start = 0;
767 url_fskip(pb, asf->packet_multi_size);
768 asf->packet_size_left -= asf->packet_multi_size;
769 continue;
770 }
771 asf->packet_multi_size -= asf->packet_obj_size;
772 //printf("COMPRESS size %d %d %d ms:%d\n", asf->packet_obj_size, asf->packet_frag_timestamp, asf->packet_size_left, asf->packet_multi_size);
773 }
774 if( /*asf->packet_frag_size == asf->packet_obj_size*/
775 asf_st->frag_offset + asf->packet_frag_size <= asf_st->pkt.size
776 && asf_st->frag_offset + asf->packet_frag_size > asf->packet_obj_size){
777 av_log(s, AV_LOG_INFO, "ignoring invalid packet_obj_size (%d %d %d %d)\n",
778 asf_st->frag_offset, asf->packet_frag_size,
779 asf->packet_obj_size, asf_st->pkt.size);
780 asf->packet_obj_size= asf_st->pkt.size;
781 }
782
783 if ( asf_st->pkt.size != asf->packet_obj_size
784 || asf_st->frag_offset + asf->packet_frag_size > asf_st->pkt.size) { //FIXME is this condition sufficient?
785 if(asf_st->pkt.data){
786 av_log(s, AV_LOG_INFO, "freeing incomplete packet size %d, new %d\n", asf_st->pkt.size, asf->packet_obj_size);
787 asf_st->frag_offset = 0;
788 av_free_packet(&asf_st->pkt);
789 }
790 /* new packet */
791 av_new_packet(&asf_st->pkt, asf->packet_obj_size);
792 asf_st->seq = asf->packet_seq;
793 asf_st->pkt.pts = asf->packet_frag_timestamp;
794 asf_st->pkt.stream_index = asf->stream_index;
795 asf_st->pkt.pos =
796 asf_st->packet_pos= asf->packet_pos;
797//printf("new packet: stream:%d key:%d packet_key:%d audio:%d size:%d\n",
798//asf->stream_index, asf->packet_key_frame, asf_st->pkt.flags & PKT_FLAG_KEY,
799//s->streams[asf->stream_index]->codec->codec_type == CODEC_TYPE_AUDIO, asf->packet_obj_size);
800 if (s->streams[asf->stream_index]->codec->codec_type == CODEC_TYPE_AUDIO)
801 asf->packet_key_frame = 1;
802 if (asf->packet_key_frame)
803 asf_st->pkt.flags |= PKT_FLAG_KEY;
804 }
805
806 /* read data */
807 //printf("READ PACKET s:%d os:%d o:%d,%d l:%d DATA:%p\n",
808 // asf->packet_size, asf_st->pkt.size, asf->packet_frag_offset,
809 // asf_st->frag_offset, asf->packet_frag_size, asf_st->pkt.data);
810 asf->packet_size_left -= asf->packet_frag_size;
811 if (asf->packet_size_left < 0)
812 continue;
813
814 if( asf->packet_frag_offset >= asf_st->pkt.size
815 || asf->packet_frag_size > asf_st->pkt.size - asf->packet_frag_offset){
816 av_log(s, AV_LOG_ERROR, "packet fragment position invalid %u,%u not in %u\n",
817 asf->packet_frag_offset, asf->packet_frag_size, asf_st->pkt.size);
818 continue;
819 }
820
821 get_buffer(pb, asf_st->pkt.data + asf->packet_frag_offset,
822 asf->packet_frag_size);
823 if (s->key && s->keylen == 20)
824 ff_asfcrypt_dec(s->key, asf_st->pkt.data + asf->packet_frag_offset,
825 asf->packet_frag_size);
826 asf_st->frag_offset += asf->packet_frag_size;
827 /* test if whole packet is read */
828 if (asf_st->frag_offset == asf_st->pkt.size) {
829 //workaround for macroshit radio DVR-MS files
830 if( s->streams[asf->stream_index]->codec->codec_id == CODEC_ID_MPEG2VIDEO
831 && asf_st->pkt.size > 100){
832 int i;
833 for(i=0; i<asf_st->pkt.size && !asf_st->pkt.data[i]; i++);
834 if(i == asf_st->pkt.size){
835 av_log(s, AV_LOG_DEBUG, "discarding ms fart\n");
836 asf_st->frag_offset = 0;
837 av_free_packet(&asf_st->pkt);
838 continue;
839 }
840 }
841
842 /* return packet */
843 if (asf_st->ds_span > 1) {
844 if(asf_st->pkt.size != asf_st->ds_packet_size * asf_st->ds_span){
845 av_log(s, AV_LOG_ERROR, "pkt.size != ds_packet_size * ds_span (%d %d %d)\n", asf_st->pkt.size, asf_st->ds_packet_size, asf_st->ds_span);
846 }else{
847 /* packet descrambling */
848 uint8_t *newdata = av_malloc(asf_st->pkt.size);
849 if (newdata) {
850 int offset = 0;
851 while (offset < asf_st->pkt.size) {
852 int off = offset / asf_st->ds_chunk_size;
853 int row = off / asf_st->ds_span;
854 int col = off % asf_st->ds_span;
855 int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size;
856 //printf("off:%d row:%d col:%d idx:%d\n", off, row, col, idx);
857
858 assert(offset + asf_st->ds_chunk_size <= asf_st->pkt.size);
859 assert(idx+1 <= asf_st->pkt.size / asf_st->ds_chunk_size);
860 memcpy(newdata + offset,
861 asf_st->pkt.data + idx * asf_st->ds_chunk_size,
862 asf_st->ds_chunk_size);
863 offset += asf_st->ds_chunk_size;
864 }
865 av_free(asf_st->pkt.data);
866 asf_st->pkt.data = newdata;
867 }
868 }
869 }
870 asf_st->frag_offset = 0;
871 *pkt= asf_st->pkt;
872 //printf("packet %d %d\n", asf_st->pkt.size, asf->packet_frag_size);
873 asf_st->pkt.size = 0;
874 asf_st->pkt.data = 0;
875 break; // packet completed
876 }
877 }
878 return 0;
879}
880
881// Added to support seeking after packets have been read
882// If information is not reset, read_packet fails due to
883// leftover information from previous reads
884static void asf_reset_header(AVFormatContext *s)
885{
886 ASFContext *asf = s->priv_data;
887 ASFStream *asf_st;
888 int i;
889
890 asf->packet_nb_frames = 0;
891 asf->packet_size_left = 0;
892 asf->packet_segments = 0;
893 asf->packet_flags = 0;
894 asf->packet_property = 0;
895 asf->packet_timestamp = 0;
896 asf->packet_segsizetype = 0;
897 asf->packet_segments = 0;
898 asf->packet_seq = 0;
899 asf->packet_replic_size = 0;
900 asf->packet_key_frame = 0;
901 asf->packet_padsize = 0;
902 asf->packet_frag_offset = 0;
903 asf->packet_frag_size = 0;
904 asf->packet_frag_timestamp = 0;
905 asf->packet_multi_size = 0;
906 asf->packet_obj_size = 0;
907 asf->packet_time_delta = 0;
908 asf->packet_time_start = 0;
909
910 for(i=0; i<s->nb_streams; i++){
911 asf_st= s->streams[i]->priv_data;
912 av_free_packet(&asf_st->pkt);
913 asf_st->frag_offset=0;
914 asf_st->seq=0;
915 }
916 asf->asf_st= NULL;
917}
918
919static int asf_read_close(AVFormatContext *s)
920{
921 int i;
922
923 asf_reset_header(s);
924 for(i=0;i<s->nb_streams;i++) {
925 AVStream *st = s->streams[i];
926 av_free(st->codec->palctrl);
927 }
928 return 0;
929}
930
931static int64_t asf_read_pts(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit)
932{
933 ASFContext *asf = s->priv_data;
934 AVPacket pkt1, *pkt = &pkt1;
935 ASFStream *asf_st;
936 int64_t pts;
937 int64_t pos= *ppos;
938 int i;
939 int64_t start_pos[s->nb_streams];
940
941 for(i=0; i<s->nb_streams; i++){
942 start_pos[i]= pos;
943 }
944
945 pos= (pos+asf->packet_size-1-s->data_offset)/asf->packet_size*asf->packet_size+ s->data_offset;
946 *ppos= pos;
947 url_fseek(s->pb, pos, SEEK_SET);
948
949//printf("asf_read_pts\n");
950 asf_reset_header(s);
951 for(;;){
952 if (av_read_frame(s, pkt) < 0){
953 av_log(s, AV_LOG_INFO, "asf_read_pts failed\n");
954 return AV_NOPTS_VALUE;
955 }
956
957 pts= pkt->pts;
958
959 av_free_packet(pkt);
960 if(pkt->flags&PKT_FLAG_KEY){
961 i= pkt->stream_index;
962
963 asf_st= s->streams[i]->priv_data;
964
965// assert((asf_st->packet_pos - s->data_offset) % asf->packet_size == 0);
966 pos= asf_st->packet_pos;
967
968 av_add_index_entry(s->streams[i], pos, pts, pkt->size, pos - start_pos[i] + 1, AVINDEX_KEYFRAME);
969 start_pos[i]= asf_st->packet_pos + 1;
970
971 if(pkt->stream_index == stream_index)
972 break;
973 }
974 }
975
976 *ppos= pos;
977//printf("found keyframe at %"PRId64" stream %d stamp:%"PRId64"\n", *ppos, stream_index, pts);
978
979 return pts;
980}
981
982static void asf_build_simple_index(AVFormatContext *s, int stream_index)
983{
984 GUID g;
985 ASFContext *asf = s->priv_data;
986 int64_t gsize, itime;
987 int64_t pos, current_pos, index_pts;
988 int i;
989 int pct,ict;
990
991 current_pos = url_ftell(s->pb);
992
993 url_fseek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET);
994 get_guid(s->pb, &g);
995 if (!memcmp(&g, &index_guid, sizeof(GUID))) {
996 gsize = get_le64(s->pb);
997 get_guid(s->pb, &g);
998 itime=get_le64(s->pb);
999 pct=get_le32(s->pb);
1000 ict=get_le32(s->pb);
1001 av_log(NULL, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n",itime,pct,ict);
1002
1003 for (i=0;i<ict;i++){
1004 int pktnum=get_le32(s->pb);
1005 int pktct =get_le16(s->pb);
1006 av_log(NULL, AV_LOG_DEBUG, "pktnum:%d, pktct:%d\n", pktnum, pktct);
1007
1008 pos=s->data_offset + asf->packet_size*(int64_t)pktnum;
1009 index_pts=av_rescale(itime, i, 10000);
1010
1011 av_add_index_entry(s->streams[stream_index], pos, index_pts, asf->packet_size, 0, AVINDEX_KEYFRAME);
1012 }
1013 asf->index_read= 1;
1014 }
1015 url_fseek(s->pb, current_pos, SEEK_SET);
1016}
1017
1018static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags)
1019{
1020 ASFContext *asf = s->priv_data;
1021 AVStream *st = s->streams[stream_index];
1022 int64_t pos;
1023 int index;
1024
1025 if (asf->packet_size <= 0)
1026 return -1;
1027
1028 /* Try using the protocol's read_seek if available */
1029 if(s->pb) {
1030 int ret = av_url_read_fseek(s->pb, stream_index, pts, flags);
1031 if(ret >= 0)
1032 asf_reset_header(s);
1033 if (ret != AVERROR(ENOSYS))
1034 return ret;
1035 }
1036
1037 if (!asf->index_read)
1038 asf_build_simple_index(s, stream_index);
1039
1040 if(!(asf->index_read && st->index_entries)){
1041 if(av_seek_frame_binary(s, stream_index, pts, flags)<0)
1042 return -1;
1043 }else{
1044 index= av_index_search_timestamp(st, pts, flags);
1045 if(index<0)
1046 return -1;
1047
1048 /* find the position */
1049 pos = st->index_entries[index].pos;
1050 pts = st->index_entries[index].timestamp;
1051
1052 // various attempts to find key frame have failed so far
1053 // asf_reset_header(s);
1054 // url_fseek(s->pb, pos, SEEK_SET);
1055 // key_pos = pos;
1056 // for(i=0;i<16;i++){
1057 // pos = url_ftell(s->pb);
1058 // if (av_read_frame(s, &pkt) < 0){
1059 // av_log(s, AV_LOG_INFO, "seek failed\n");
1060 // return -1;
1061 // }
1062 // asf_st = s->streams[stream_index]->priv_data;
1063 // pos += st->parser->frame_offset;
1064 //
1065 // if (pkt.size > b) {
1066 // b = pkt.size;
1067 // key_pos = pos;
1068 // }
1069 //
1070 // av_free_packet(&pkt);
1071 // }
1072
1073 /* do the seek */
1074 av_log(NULL, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos);
1075 url_fseek(s->pb, pos, SEEK_SET);
1076 }
1077 asf_reset_header(s);
1078 return 0;
1079}
1080
1081AVInputFormat asf_demuxer = {
1082 "asf",
1083 NULL_IF_CONFIG_SMALL("ASF format"),
1084 sizeof(ASFContext),
1085 asf_probe,
1086 asf_read_header,
1087 asf_read_packet,
1088 asf_read_close,
1089 asf_read_seek,
1090 asf_read_pts,
1091};
diff --git a/src/plugins/ffmpeg/libavformat/asf.h b/src/plugins/ffmpeg/libavformat/asf.h
deleted file mode 100644
index 2486d8a..0000000
--- a/src/plugins/ffmpeg/libavformat/asf.h
+++ /dev/null
@@ -1,289 +0,0 @@
1/*
2 * Copyright (c) 2000, 2001 Fabrice Bellard.
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21#ifndef FFMPEG_ASF_H
22#define FFMPEG_ASF_H
23
24#include <stdint.h>
25#include "avformat.h"
26
27#define PACKET_SIZE 3200
28
29typedef struct {
30 int num;
31 unsigned char seq;
32 /* use for reading */
33 AVPacket pkt;
34 int frag_offset;
35 int timestamp;
36 int64_t duration;
37
38 int ds_span; /* descrambling */
39 int ds_packet_size;
40 int ds_chunk_size;
41
42 int64_t packet_pos;
43
44} ASFStream;
45
46typedef uint8_t GUID[16];
47
48typedef struct {
49 GUID guid; ///< generated by client computer
50 uint64_t file_size; /**< in bytes
51 * invalid if broadcasting */
52 uint64_t create_time; /**< time of creation, in 100-nanosecond units since 1.1.1601
53 * invalid if broadcasting */
54 uint64_t play_time; /**< play time, in 100-nanosecond units
55 * invalid if broadcasting */
56 uint64_t send_time; /**< time to send file, in 100-nanosecond units
57 * invalid if broadcasting (could be ignored) */
58 uint32_t preroll; /**< timestamp of the first packet, in milliseconds
59 * if nonzero - subtract from time */
60 uint32_t ignore; ///< preroll is 64bit - but let's just ignore it
61 uint32_t flags; /**< 0x01 - broadcast
62 * 0x02 - seekable
63 * rest is reserved should be 0 */
64 uint32_t min_pktsize; /**< size of a data packet
65 * invalid if broadcasting */
66 uint32_t max_pktsize; /**< shall be the same as for min_pktsize
67 * invalid if broadcasting */
68 uint32_t max_bitrate; /**< bandwith of stream in bps
69 * should be the sum of bitrates of the
70 * individual media streams */
71} ASFMainHeader;
72
73
74typedef struct {
75 uint32_t packet_number;
76 uint16_t packet_count;
77} ASFIndex;
78
79
80typedef struct {
81 uint32_t seqno;
82 unsigned int packet_size;
83 int is_streamed;
84 int asfid2avid[128]; ///< conversion table from asf ID 2 AVStream ID
85 ASFStream streams[128]; ///< it's max number and it's not that big
86 uint32_t stream_bitrates[128]; ///< max number of streams, bitrate for each (for streaming)
87 /* non streamed additonnal info */
88 uint64_t nb_packets; ///< how many packets are there in the file, invalid if broadcasting
89 int64_t duration; ///< in 100ns units
90 /* packet filling */
91 unsigned char multi_payloads_present;
92 int packet_size_left;
93 int packet_timestamp_start;
94 int packet_timestamp_end;
95 unsigned int packet_nb_payloads;
96 int packet_nb_frames;
97 uint8_t packet_buf[PACKET_SIZE];
98 ByteIOContext pb;
99 /* only for reading */
100 uint64_t data_offset; ///< beginning of the first data packet
101 uint64_t data_object_offset; ///< data object offset (excl. GUID & size)
102 uint64_t data_object_size; ///< size of the data object
103 int index_read;
104
105 ASFMainHeader hdr;
106
107 int packet_flags;
108 int packet_property;
109 int packet_timestamp;
110 int packet_segsizetype;
111 int packet_segments;
112 int packet_seq;
113 int packet_replic_size;
114 int packet_key_frame;
115 int packet_padsize;
116 unsigned int packet_frag_offset;
117 unsigned int packet_frag_size;
118 int64_t packet_frag_timestamp;
119 int packet_multi_size;
120 int packet_obj_size;
121 int packet_time_delta;
122 int packet_time_start;
123 int64_t packet_pos;
124
125 int stream_index;
126
127
128 int64_t last_indexed_pts;
129 ASFIndex* index_ptr;
130 uint32_t nb_index_count;
131 uint32_t nb_index_memory_alloc;
132 uint16_t maximum_packet;
133
134 ASFStream* asf_st; ///< currently decoded stream
135} ASFContext;
136
137static const GUID asf_header = {
138 0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9, 0x00, 0xAA, 0x00, 0x62, 0xCE, 0x6C
139};
140
141static const GUID file_header = {
142 0xA1, 0xDC, 0xAB, 0x8C, 0x47, 0xA9, 0xCF, 0x11, 0x8E, 0xE4, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65
143};
144
145static const GUID stream_header = {
146 0x91, 0x07, 0xDC, 0xB7, 0xB7, 0xA9, 0xCF, 0x11, 0x8E, 0xE6, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65
147};
148
149static const GUID ext_stream_header = {
150 0xCB, 0xA5, 0xE6, 0x14, 0x72, 0xC6, 0x32, 0x43, 0x83, 0x99, 0xA9, 0x69, 0x52, 0x06, 0x5B, 0x5A
151};
152
153static const GUID audio_stream = {
154 0x40, 0x9E, 0x69, 0xF8, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B
155};
156
157static const GUID audio_conceal_none = {
158 // 0x40, 0xa4, 0xf1, 0x49, 0x4ece, 0x11d0, 0xa3, 0xac, 0x00, 0xa0, 0xc9, 0x03, 0x48, 0xf6
159 // New value lifted from avifile
160 0x00, 0x57, 0xfb, 0x20, 0x55, 0x5B, 0xCF, 0x11, 0xa8, 0xfd, 0x00, 0x80, 0x5f, 0x5c, 0x44, 0x2b
161};
162
163static const GUID audio_conceal_spread = {
164 0x50, 0xCD, 0xC3, 0xBF, 0x8F, 0x61, 0xCF, 0x11, 0x8B, 0xB2, 0x00, 0xAA, 0x00, 0xB4, 0xE2, 0x20
165};
166
167static const GUID video_stream = {
168 0xC0, 0xEF, 0x19, 0xBC, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B
169};
170
171static const GUID video_conceal_none = {
172 0x00, 0x57, 0xFB, 0x20, 0x55, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B
173};
174
175static const GUID command_stream = {
176 0xC0, 0xCF, 0xDA, 0x59, 0xE6, 0x59, 0xD0, 0x11, 0xA3, 0xAC, 0x00, 0xA0, 0xC9, 0x03, 0x48, 0xF6
177};
178
179static const GUID comment_header = {
180 0x33, 0x26, 0xb2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xa6, 0xd9, 0x00, 0xaa, 0x00, 0x62, 0xce, 0x6c
181};
182
183static const GUID codec_comment_header = {
184 0x40, 0x52, 0xD1, 0x86, 0x1D, 0x31, 0xD0, 0x11, 0xA3, 0xA4, 0x00, 0xA0, 0xC9, 0x03, 0x48, 0xF6
185};
186static const GUID codec_comment1_header = {
187 0x41, 0x52, 0xd1, 0x86, 0x1D, 0x31, 0xD0, 0x11, 0xa3, 0xa4, 0x00, 0xa0, 0xc9, 0x03, 0x48, 0xf6
188};
189
190static const GUID data_header = {
191 0x36, 0x26, 0xb2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xa6, 0xd9, 0x00, 0xaa, 0x00, 0x62, 0xce, 0x6c
192};
193
194static const GUID head1_guid = {
195 0xb5, 0x03, 0xbf, 0x5f, 0x2E, 0xA9, 0xCF, 0x11, 0x8e, 0xe3, 0x00, 0xc0, 0x0c, 0x20, 0x53, 0x65
196};
197
198static const GUID head2_guid = {
199 0x11, 0xd2, 0xd3, 0xab, 0xBA, 0xA9, 0xCF, 0x11, 0x8e, 0xe6, 0x00, 0xc0, 0x0c, 0x20, 0x53, 0x65
200};
201
202static const GUID extended_content_header = {
203 0x40, 0xA4, 0xD0, 0xD2, 0x07, 0xE3, 0xD2, 0x11, 0x97, 0xF0, 0x00, 0xA0, 0xC9, 0x5E, 0xA8, 0x50
204};
205
206static const GUID simple_index_header = {
207 0x90, 0x08, 0x00, 0x33, 0xB1, 0xE5, 0xCF, 0x11, 0x89, 0xF4, 0x00, 0xA0, 0xC9, 0x03, 0x49, 0xCB
208};
209
210static const GUID ext_stream_embed_stream_header = {
211 0xe2, 0x65, 0xfb, 0x3a, 0xEF, 0x47, 0xF2, 0x40, 0xac, 0x2c, 0x70, 0xa9, 0x0d, 0x71, 0xd3, 0x43
212};
213
214static const GUID ext_stream_audio_stream = {
215 0x9d, 0x8c, 0x17, 0x31, 0xE1, 0x03, 0x28, 0x45, 0xb5, 0x82, 0x3d, 0xf9, 0xdb, 0x22, 0xf5, 0x03
216};
217
218static const GUID metadata_header = {
219 0xea, 0xcb, 0xf8, 0xc5, 0xaf, 0x5b, 0x77, 0x48, 0x84, 0x67, 0xaa, 0x8c, 0x44, 0xfa, 0x4c, 0xca
220};
221
222/* I am not a number !!! This GUID is the one found on the PC used to
223 generate the stream */
224static const GUID my_guid = {
225 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
226};
227
228#define ASF_PACKET_FLAG_ERROR_CORRECTION_PRESENT 0x80 //1000 0000
229
230
231// ASF data packet structure
232// =========================
233//
234//
235// -----------------------------------
236// | Error Correction Data | Optional
237// -----------------------------------
238// | Payload Parsing Information (PPI) |
239// -----------------------------------
240// | Payload Data |
241// -----------------------------------
242// | Padding Data |
243// -----------------------------------
244
245
246// PPI_FLAG - Payload parsing information flags
247#define ASF_PPI_FLAG_MULTIPLE_PAYLOADS_PRESENT 1
248
249#define ASF_PPI_FLAG_SEQUENCE_FIELD_IS_BYTE 0x02 //0000 0010
250#define ASF_PPI_FLAG_SEQUENCE_FIELD_IS_WORD 0x04 //0000 0100
251#define ASF_PPI_FLAG_SEQUENCE_FIELD_IS_DWORD 0x06 //0000 0110
252#define ASF_PPI_MASK_SEQUENCE_FIELD_SIZE 0x06 //0000 0110
253
254#define ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_BYTE 0x08 //0000 1000
255#define ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_WORD 0x10 //0001 0000
256#define ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_DWORD 0x18 //0001 1000
257#define ASF_PPI_MASK_PADDING_LENGTH_FIELD_SIZE 0x18 //0001 1000
258
259#define ASF_PPI_FLAG_PACKET_LENGTH_FIELD_IS_BYTE 0x20 //0010 0000
260#define ASF_PPI_FLAG_PACKET_LENGTH_FIELD_IS_WORD 0x40 //0100 0000
261#define ASF_PPI_FLAG_PACKET_LENGTH_FIELD_IS_DWORD 0x60 //0110 0000
262#define ASF_PPI_MASK_PACKET_LENGTH_FIELD_SIZE 0x60 //0110 0000
263
264// PL_FLAG - Payload flags
265#define ASF_PL_FLAG_REPLICATED_DATA_LENGTH_FIELD_IS_BYTE 0x01 //0000 0001
266#define ASF_PL_FLAG_REPLICATED_DATA_LENGTH_FIELD_IS_WORD 0x02 //0000 0010
267#define ASF_PL_FLAG_REPLICATED_DATA_LENGTH_FIELD_IS_DWORD 0x03 //0000 0011
268#define ASF_PL_MASK_REPLICATED_DATA_LENGTH_FIELD_SIZE 0x03 //0000 0011
269
270#define ASF_PL_FLAG_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_IS_BYTE 0x04 //0000 0100
271#define ASF_PL_FLAG_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_IS_WORD 0x08 //0000 1000
272#define ASF_PL_FLAG_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_IS_DWORD 0x0c //0000 1100
273#define ASF_PL_MASK_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_SIZE 0x0c //0000 1100
274
275#define ASF_PL_FLAG_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_IS_BYTE 0x10 //0001 0000
276#define ASF_PL_FLAG_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_IS_WORD 0x20 //0010 0000
277#define ASF_PL_FLAG_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_IS_DWORD 0x30 //0011 0000
278#define ASF_PL_MASK_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_SIZE 0x30 //0011 0000
279
280#define ASF_PL_FLAG_STREAM_NUMBER_LENGTH_FIELD_IS_BYTE 0x40 //0100 0000
281#define ASF_PL_MASK_STREAM_NUMBER_LENGTH_FIELD_SIZE 0xc0 //1100 0000
282
283#define ASF_PL_FLAG_PAYLOAD_LENGTH_FIELD_IS_BYTE 0x40 //0100 0000
284#define ASF_PL_FLAG_PAYLOAD_LENGTH_FIELD_IS_WORD 0x80 //1000 0000
285#define ASF_PL_MASK_PAYLOAD_LENGTH_FIELD_SIZE 0xc0 //1100 0000
286
287#define ASF_PL_FLAG_KEY_FRAME 0x80 //1000 0000
288
289#endif /* FFMPEG_ASF_H */
diff --git a/src/plugins/ffmpeg/libavformat/asfcrypt.c b/src/plugins/ffmpeg/libavformat/asfcrypt.c
deleted file mode 100644
index 74a3dcc..0000000
--- a/src/plugins/ffmpeg/libavformat/asfcrypt.c
+++ /dev/null
@@ -1,173 +0,0 @@
1/*
2 * ASF decryption
3 * Copyright (c) 2007 Reimar Doeffinger
4 * This is a rewrite of code contained in freeme/freeme2
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#include "libavutil/common.h"
24#include "libavutil/intreadwrite.h"
25#include "libavutil/bswap.h"
26#include "libavutil/des.h"
27#include "libavutil/rc4.h"
28#include "asfcrypt.h"
29
30/**
31 * \brief find multiplicative inverse modulo 2 ^ 32
32 * \param v number to invert, must be odd!
33 * \return number so that result * v = 1 (mod 2^32)
34 */
35static uint32_t inverse(uint32_t v) {
36 // v ^ 3 gives the inverse (mod 16), could also be implemented
37 // as table etc. (only lowest 4 bits matter!)
38 uint32_t inverse = v * v * v;
39 // uses a fixpoint-iteration that doubles the number
40 // of correct lowest bits each time
41 inverse *= 2 - v * inverse;
42 inverse *= 2 - v * inverse;
43 inverse *= 2 - v * inverse;
44 return inverse;
45}
46
47/**
48 * \brief read keys from keybuf into keys
49 * \param keybuf buffer containing the keys
50 * \param keys output key array containing the keys for encryption in
51 * native endianness
52 */
53static void multiswap_init(const uint8_t keybuf[48], uint32_t keys[12]) {
54 int i;
55 for (i = 0; i < 12; i++)
56 keys[i] = AV_RL32(keybuf + (i << 2)) | 1;
57}
58
59/**
60 * \brief invert the keys so that encryption become decryption keys and
61 * the other way round.
62 * \param keys key array of ints to invert
63 */
64static void multiswap_invert_keys(uint32_t keys[12]) {
65 int i;
66 for (i = 0; i < 5; i++)
67 keys[i] = inverse(keys[i]);
68 for (i = 6; i < 11; i++)
69 keys[i] = inverse(keys[i]);
70}
71
72static uint32_t multiswap_step(const uint32_t keys[12], uint32_t v) {
73 int i;
74 v *= keys[0];
75 for (i = 1; i < 5; i++) {
76 v = (v >> 16) | (v << 16);
77 v *= keys[i];
78 }
79 v += keys[5];
80 return v;
81}
82
83static uint32_t multiswap_inv_step(const uint32_t keys[12], uint32_t v) {
84 int i;
85 v -= keys[5];
86 for (i = 4; i > 0; i--) {
87 v *= keys[i];
88 v = (v >> 16) | (v << 16);
89 }
90 v *= keys[0];
91 return v;
92}
93
94/**
95 * \brief "MultiSwap" encryption
96 * \param keys 32 bit numbers in machine endianness,
97 * 0-4 and 6-10 must be inverted from decryption
98 * \param key another key, this one must be the same for the decryption
99 * \param data data to encrypt
100 * \return encrypted data
101 */
102static uint64_t multiswap_enc(const uint32_t keys[12], uint64_t key, uint64_t data) {
103 uint32_t a = data;
104 uint32_t b = data >> 32;
105 uint32_t c;
106 uint32_t tmp;
107 a += key;
108 tmp = multiswap_step(keys , a);
109 b += tmp;
110 c = (key >> 32) + tmp;
111 tmp = multiswap_step(keys + 6, b);
112 c += tmp;
113 return ((uint64_t)c << 32) | tmp;
114}
115
116/**
117 * \brief "MultiSwap" decryption
118 * \param keys 32 bit numbers in machine endianness,
119 * 0-4 and 6-10 must be inverted from encryption
120 * \param key another key, this one must be the same as for the encryption
121 * \param data data to decrypt
122 * \return decrypted data
123 */
124static uint64_t multiswap_dec(const uint32_t keys[12], uint64_t key, uint64_t data) {
125 uint32_t a;
126 uint32_t b;
127 uint32_t c = data >> 32;
128 uint32_t tmp = data;
129 c -= tmp;
130 b = multiswap_inv_step(keys + 6, tmp);
131 tmp = c - (key >> 32);
132 b -= tmp;
133 a = multiswap_inv_step(keys , tmp);
134 a -= key;
135 return ((uint64_t)b << 32) | a;
136}
137
138void ff_asfcrypt_dec(const uint8_t key[20], uint8_t *data, int len) {
139 int num_qwords = len >> 3;
140 uint64_t *qwords = (uint64_t *)data;
141 uint64_t rc4buff[8];
142 uint64_t packetkey;
143 uint32_t ms_keys[12];
144 uint64_t ms_state;
145 int i;
146 if (len < 16) {
147 for (i = 0; i < len; i++)
148 data[i] ^= key[i];
149 return;
150 }
151
152 memset(rc4buff, 0, sizeof(rc4buff));
153 ff_rc4_enc(key, 12, (uint8_t *)rc4buff, sizeof(rc4buff));
154 multiswap_init((uint8_t *)rc4buff, ms_keys);
155
156 packetkey = qwords[num_qwords - 1];
157 packetkey ^= rc4buff[7];
158 packetkey = be2me_64(packetkey);
159 packetkey = ff_des_encdec(packetkey, AV_RB64(key + 12), 1);
160 packetkey = be2me_64(packetkey);
161 packetkey ^= rc4buff[6];
162
163 ff_rc4_enc((uint8_t *)&packetkey, 8, data, len);
164
165 ms_state = 0;
166 for (i = 0; i < num_qwords - 1; i++, qwords++)
167 ms_state = multiswap_enc(ms_keys, ms_state, AV_RL64(qwords));
168 multiswap_invert_keys(ms_keys);
169 packetkey = (packetkey << 32) | (packetkey >> 32);
170 packetkey = le2me_64(packetkey);
171 packetkey = multiswap_dec(ms_keys, ms_state, packetkey);
172 AV_WL64(qwords, packetkey);
173}
diff --git a/src/plugins/ffmpeg/libavformat/asfcrypt.h b/src/plugins/ffmpeg/libavformat/asfcrypt.h
deleted file mode 100644
index dcd9c1d..0000000
--- a/src/plugins/ffmpeg/libavformat/asfcrypt.h
+++ /dev/null
@@ -1,29 +0,0 @@
1/*
2 * ASF decryption
3 * Copyright (c) 2007 Reimar Doeffinger
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#ifndef FFMPEG_ASFCRYPT_H
23#define FFMPEG_ASFCRYPT_H
24
25#include <inttypes.h>
26
27void ff_asfcrypt_dec(const uint8_t key[20], uint8_t *data, int len);
28
29#endif /* FFMPEG_ASFCRYPT_H */
diff --git a/src/plugins/ffmpeg/libavformat/au.c b/src/plugins/ffmpeg/libavformat/au.c
deleted file mode 100644
index 5e15517..0000000
--- a/src/plugins/ffmpeg/libavformat/au.c
+++ /dev/null
@@ -1,203 +0,0 @@
1/*
2 * AU muxer and demuxer
3 * Copyright (c) 2001 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/*
23 * First version by Francois Revol revol@free.fr
24 *
25 * Reference documents:
26 * http://www.opengroup.org/public/pubs/external/auformat.html
27 * http://www.goice.co.jp/member/mo/formats/au.html
28 */
29
30#include "avformat.h"
31#include "raw.h"
32#include "riff.h"
33
34/* if we don't know the size in advance */
35#define AU_UNKNOWN_SIZE ((uint32_t)(~0))
36
37/* The ffmpeg codecs we support, and the IDs they have in the file */
38static const AVCodecTag codec_au_tags[] = {
39 { CODEC_ID_PCM_MULAW, 1 },
40 { CODEC_ID_PCM_S8, 2 },
41 { CODEC_ID_PCM_S16BE, 3 },
42 { CODEC_ID_PCM_ALAW, 27 },
43 { 0, 0 },
44};
45
46#ifdef CONFIG_MUXERS
47/* AUDIO_FILE header */
48static int put_au_header(ByteIOContext *pb, AVCodecContext *enc)
49{
50 if(!enc->codec_tag)
51 return -1;
52 put_tag(pb, ".snd"); /* magic number */
53 put_be32(pb, 24); /* header size */
54 put_be32(pb, AU_UNKNOWN_SIZE); /* data size */
55 put_be32(pb, (uint32_t)enc->codec_tag); /* codec ID */
56 put_be32(pb, enc->sample_rate);
57 put_be32(pb, (uint32_t)enc->channels);
58 return 0;
59}
60
61static int au_write_header(AVFormatContext *s)
62{
63 ByteIOContext *pb = s->pb;
64
65 s->priv_data = NULL;
66
67 /* format header */
68 if (put_au_header(pb, s->streams[0]->codec) < 0) {
69 return -1;
70 }
71
72 put_flush_packet(pb);
73
74 return 0;
75}
76
77static int au_write_packet(AVFormatContext *s, AVPacket *pkt)
78{
79 ByteIOContext *pb = s->pb;
80 put_buffer(pb, pkt->data, pkt->size);
81 return 0;
82}
83
84static int au_write_trailer(AVFormatContext *s)
85{
86 ByteIOContext *pb = s->pb;
87 offset_t file_size;
88
89 if (!url_is_streamed(s->pb)) {
90
91 /* update file size */
92 file_size = url_ftell(pb);
93 url_fseek(pb, 8, SEEK_SET);
94 put_be32(pb, (uint32_t)(file_size - 24));
95 url_fseek(pb, file_size, SEEK_SET);
96
97 put_flush_packet(pb);
98 }
99
100 return 0;
101}
102#endif //CONFIG_MUXERS
103
104static int au_probe(AVProbeData *p)
105{
106 /* check file header */
107 if (p->buf[0] == '.' && p->buf[1] == 's' &&
108 p->buf[2] == 'n' && p->buf[3] == 'd')
109 return AVPROBE_SCORE_MAX;
110 else
111 return 0;
112}
113
114/* au input */
115static int au_read_header(AVFormatContext *s,
116 AVFormatParameters *ap)
117{
118 int size;
119 unsigned int tag;
120 ByteIOContext *pb = s->pb;
121 unsigned int id, codec, channels, rate;
122 AVStream *st;
123
124 /* check ".snd" header */
125 tag = get_le32(pb);
126 if (tag != MKTAG('.', 's', 'n', 'd'))
127 return -1;
128 size = get_be32(pb); /* header size */
129 get_be32(pb); /* data size */
130
131 id = get_be32(pb);
132 rate = get_be32(pb);
133 channels = get_be32(pb);
134
135 codec = codec_get_id(codec_au_tags, id);
136
137 if (size >= 24) {
138 /* skip unused data */
139 url_fseek(pb, size - 24, SEEK_CUR);
140 }
141
142 /* now we are ready: build format streams */
143 st = av_new_stream(s, 0);
144 if (!st)
145 return -1;
146 st->codec->codec_type = CODEC_TYPE_AUDIO;
147 st->codec->codec_tag = id;
148 st->codec->codec_id = codec;
149 st->codec->channels = channels;
150 st->codec->sample_rate = rate;
151 av_set_pts_info(st, 64, 1, rate);
152 return 0;
153}
154
155#define MAX_SIZE 4096
156
157static int au_read_packet(AVFormatContext *s,
158 AVPacket *pkt)
159{
160 int ret;
161
162 if (url_feof(s->pb))
163 return AVERROR(EIO);
164 ret= av_get_packet(s->pb, pkt, MAX_SIZE);
165 if (ret < 0)
166 return AVERROR(EIO);
167 pkt->stream_index = 0;
168
169 /* note: we need to modify the packet size here to handle the last
170 packet */
171 pkt->size = ret;
172 return 0;
173}
174
175#ifdef CONFIG_AU_DEMUXER
176AVInputFormat au_demuxer = {
177 "au",
178 NULL_IF_CONFIG_SMALL("SUN AU format"),
179 0,
180 au_probe,
181 au_read_header,
182 au_read_packet,
183 NULL,
184 pcm_read_seek,
185 .codec_tag= (const AVCodecTag*[]){codec_au_tags, 0},
186};
187#endif
188
189#ifdef CONFIG_AU_MUXER
190AVOutputFormat au_muxer = {
191 "au",
192 NULL_IF_CONFIG_SMALL("SUN AU format"),
193 "audio/basic",
194 "au",
195 0,
196 CODEC_ID_PCM_S16BE,
197 CODEC_ID_NONE,
198 au_write_header,
199 au_write_packet,
200 au_write_trailer,
201 .codec_tag= (const AVCodecTag*[]){codec_au_tags, 0},
202};
203#endif //CONFIG_AU_MUXER
diff --git a/src/plugins/ffmpeg/libavformat/avc.c b/src/plugins/ffmpeg/libavformat/avc.c
deleted file mode 100644
index 0c180c8..0000000
--- a/src/plugins/ffmpeg/libavformat/avc.c
+++ /dev/null
@@ -1,135 +0,0 @@
1/*
2 * AVC helper functions for muxers
3 * Copyright (c) 2006 Baptiste Coudurier <baptiste.coudurier@smartjog.com>
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#include "avformat.h"
22#include "avio.h"
23
24const uint8_t *ff_avc_find_startcode(const uint8_t *p, const uint8_t *end)
25{
26 const uint8_t *a = p + 4 - ((long)p & 3);
27
28 for( end -= 3; p < a && p < end; p++ ) {
29 if( p[0] == 0 && p[1] == 0 && p[2] == 1 )
30 return p;
31 }
32
33 for( end -= 3; p < end; p += 4 ) {
34 uint32_t x = *(const uint32_t*)p;
35// if( (x - 0x01000100) & (~x) & 0x80008000 ) // little endian
36// if( (x - 0x00010001) & (~x) & 0x00800080 ) // big endian
37 if( (x - 0x01010101) & (~x) & 0x80808080 ) { // generic
38 if( p[1] == 0 ) {
39 if( p[0] == 0 && p[2] == 1 )
40 return p-1;
41 if( p[2] == 0 && p[3] == 1 )
42 return p;
43 }
44 if( p[3] == 0 ) {
45 if( p[2] == 0 && p[4] == 1 )
46 return p+1;
47 if( p[4] == 0 && p[5] == 1 )
48 return p+2;
49 }
50 }
51 }
52
53 for( end += 3; p < end; p++ ) {
54 if( p[0] == 0 && p[1] == 0 && p[2] == 1 )
55 return p;
56 }
57
58 return end + 3;
59}
60
61int ff_avc_parse_nal_units(const uint8_t *buf_in, uint8_t **buf, int *size)
62{
63 ByteIOContext *pb;
64 const uint8_t *p = buf_in;
65 const uint8_t *end = p + *size;
66 const uint8_t *nal_start, *nal_end;
67 int ret = url_open_dyn_buf(&pb);
68 if(ret < 0)
69 return ret;
70
71 nal_start = ff_avc_find_startcode(p, end);
72 while (nal_start < end) {
73 while(!*(nal_start++));
74 nal_end = ff_avc_find_startcode(nal_start, end);
75 put_be32(pb, nal_end - nal_start);
76 put_buffer(pb, nal_start, nal_end - nal_start);
77 nal_start = nal_end;
78 }
79 av_freep(buf);
80 *size = url_close_dyn_buf(pb, buf);
81 return 0;
82}
83
84int ff_isom_write_avcc(ByteIOContext *pb, const uint8_t *data, int len)
85{
86 if (len > 6) {
87 /* check for h264 start code */
88 if (AV_RB32(data) == 0x00000001) {
89 uint8_t *buf=NULL, *end, *start;
90 uint32_t sps_size=0, pps_size=0;
91 uint8_t *sps=0, *pps=0;
92
93 int ret = ff_avc_parse_nal_units(data, &buf, &len);
94 if (ret < 0)
95 return ret;
96 start = buf;
97 end = buf + len;
98
99 /* look for sps and pps */
100 while (buf < end) {
101 unsigned int size;
102 uint8_t nal_type;
103 size = AV_RB32(buf);
104 nal_type = buf[4] & 0x1f;
105 if (nal_type == 7) { /* SPS */
106 sps = buf + 4;
107 sps_size = size;
108 } else if (nal_type == 8) { /* PPS */
109 pps = buf + 4;
110 pps_size = size;
111 }
112 buf += size + 4;
113 }
114 assert(sps);
115 assert(pps);
116
117 put_byte(pb, 1); /* version */
118 put_byte(pb, sps[1]); /* profile */
119 put_byte(pb, sps[2]); /* profile compat */
120 put_byte(pb, sps[3]); /* level */
121 put_byte(pb, 0xff); /* 6 bits reserved (111111) + 2 bits nal size length - 1 (11) */
122 put_byte(pb, 0xe1); /* 3 bits reserved (111) + 5 bits number of sps (00001) */
123
124 put_be16(pb, sps_size);
125 put_buffer(pb, sps, sps_size);
126 put_byte(pb, 1); /* number of pps */
127 put_be16(pb, pps_size);
128 put_buffer(pb, pps, pps_size);
129 av_free(start);
130 } else {
131 put_buffer(pb, data, len);
132 }
133 }
134 return 0;
135}
diff --git a/src/plugins/ffmpeg/libavformat/avc.h b/src/plugins/ffmpeg/libavformat/avc.h
deleted file mode 100644
index 334aa43..0000000
--- a/src/plugins/ffmpeg/libavformat/avc.h
+++ /dev/null
@@ -1,32 +0,0 @@
1/*
2 * AVC helper functions for muxers
3 * Copyright (c) 2008 Aurelien Jacobs <aurel@gnuage.org>
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#ifndef AVC_H
23#define AVC_H
24
25#include <stdint.h>
26#include "avio.h"
27
28int ff_avc_parse_nal_units(const uint8_t *buf_in, uint8_t **buf, int *size);
29int ff_isom_write_avcc(ByteIOContext *pb, const uint8_t *data, int len);
30const uint8_t *ff_avc_find_startcode(const uint8_t *p, const uint8_t *end);
31
32#endif /* AVC_H */
diff --git a/src/plugins/ffmpeg/libavformat/avformat.h b/src/plugins/ffmpeg/libavformat/avformat.h
deleted file mode 100644
index 737a4d8..0000000
--- a/src/plugins/ffmpeg/libavformat/avformat.h
+++ /dev/null
@@ -1,1087 +0,0 @@
1/*
2 * copyright (c) 2001 Fabrice Bellard
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21#ifndef FFMPEG_AVFORMAT_H
22#define FFMPEG_AVFORMAT_H
23
24#define LIBAVFORMAT_VERSION_MAJOR 52
25#define LIBAVFORMAT_VERSION_MINOR 17
26#define LIBAVFORMAT_VERSION_MICRO 0
27
28#define LIBAVFORMAT_VERSION_INT AV_VERSION_INT(LIBAVFORMAT_VERSION_MAJOR, \
29 LIBAVFORMAT_VERSION_MINOR, \
30 LIBAVFORMAT_VERSION_MICRO)
31#define LIBAVFORMAT_VERSION AV_VERSION(LIBAVFORMAT_VERSION_MAJOR, \
32 LIBAVFORMAT_VERSION_MINOR, \
33 LIBAVFORMAT_VERSION_MICRO)
34#define LIBAVFORMAT_BUILD LIBAVFORMAT_VERSION_INT
35
36#define LIBAVFORMAT_IDENT "Lavf" AV_STRINGIFY(LIBAVFORMAT_VERSION)
37
38#include <time.h>
39#include <stdio.h> /* FILE */
40#include "libavcodec/avcodec.h"
41
42#include "avio.h"
43
44/* packet functions */
45
46typedef struct AVPacket {
47 /**
48 * Presentation time stamp in time_base units.
49 * This is the time at which the decompressed packet will be presented
50 * to the user.
51 * Can be AV_NOPTS_VALUE if it is not stored in the file.
52 * pts MUST be larger or equal to dts as presentation can not happen before
53 * decompression, unless one wants to view hex dumps. Some formats misuse
54 * the terms dts and pts/cts to mean something different, these timestamps
55 * must be converted to true pts/dts before they are stored in AVPacket.
56 */
57 int64_t pts;
58 /**
59 * Decompression time stamp in time_base units.
60 * This is the time at which the packet is decompressed.
61 * Can be AV_NOPTS_VALUE if it is not stored in the file.
62 */
63 int64_t dts;
64 uint8_t *data;
65 int size;
66 int stream_index;
67 int flags;
68 int duration; ///< presentation duration in time_base units (0 if not available)
69 void (*destruct)(struct AVPacket *);
70 void *priv;
71 int64_t pos; ///< byte position in stream, -1 if unknown
72} AVPacket;
73#define PKT_FLAG_KEY 0x0001
74
75void av_destruct_packet_nofree(AVPacket *pkt);
76
77/**
78 * Default packet destructor.
79 */
80void av_destruct_packet(AVPacket *pkt);
81
82/**
83 * Initialize optional fields of a packet to default values.
84 *
85 * @param pkt packet
86 */
87void av_init_packet(AVPacket *pkt);
88
89/**
90 * Allocate the payload of a packet and initialize its fields to default values.
91 *
92 * @param pkt packet
93 * @param size wanted payload size
94 * @return 0 if OK. AVERROR_xxx otherwise.
95 */
96int av_new_packet(AVPacket *pkt, int size);
97
98/**
99 * Allocate and read the payload of a packet and initialize its fields to default values.
100 *
101 * @param pkt packet
102 * @param size wanted payload size
103 * @return >0 (read size) if OK. AVERROR_xxx otherwise.
104 */
105int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size);
106
107/**
108 * @warning This is a hack - the packet memory allocation stuff is broken. The
109 * packet is allocated if it was not really allocated
110 */
111int av_dup_packet(AVPacket *pkt);
112
113/**
114 * Free a packet
115 *
116 * @param pkt packet to free
117 */
118static inline void av_free_packet(AVPacket *pkt)
119{
120 if (pkt && pkt->destruct) {
121 pkt->destruct(pkt);
122 }
123}
124
125/*************************************************/
126/* fractional numbers for exact pts handling */
127
128/**
129 * the exact value of the fractional number is: 'val + num / den'.
130 * num is assumed to be such as 0 <= num < den
131*/
132typedef struct AVFrac {
133 int64_t val, num, den;
134} AVFrac;
135
136/*************************************************/
137/* input/output formats */
138
139struct AVCodecTag;
140
141struct AVFormatContext;
142
143/** this structure contains the data a format has to probe a file */
144typedef struct AVProbeData {
145 const char *filename;
146 unsigned char *buf;
147 int buf_size;
148} AVProbeData;
149
150#define AVPROBE_SCORE_MAX 100 ///< max score, half of that is used for file extension based detection
151#define AVPROBE_PADDING_SIZE 32 ///< extra allocated bytes at the end of the probe buffer
152
153typedef struct AVFormatParameters {
154 AVRational time_base;
155 int sample_rate;
156 int channels;
157 int width;
158 int height;
159 enum PixelFormat pix_fmt;
160 int channel; /**< used to select dv channel */
161 const char *standard; /**< tv standard, NTSC, PAL, SECAM */
162 unsigned int mpeg2ts_raw:1; /**< force raw MPEG2 transport stream output, if possible */
163 unsigned int mpeg2ts_compute_pcr:1; /**< compute exact PCR for each transport
164 stream packet (only meaningful if
165 mpeg2ts_raw is TRUE) */
166 unsigned int initial_pause:1; /**< do not begin to play the stream
167 immediately (RTSP only) */
168 unsigned int prealloced_context:1;
169#if LIBAVFORMAT_VERSION_INT < (53<<16)
170 enum CodecID video_codec_id;
171 enum CodecID audio_codec_id;
172#endif
173} AVFormatParameters;
174
175//! demuxer will use url_fopen, no opened file should be provided by the caller
176#define AVFMT_NOFILE 0x0001
177#define AVFMT_NEEDNUMBER 0x0002 /**< needs '%d' in filename */
178#define AVFMT_SHOW_IDS 0x0008 /**< show format stream IDs numbers */
179#define AVFMT_RAWPICTURE 0x0020 /**< format wants AVPicture structure for
180 raw picture data */
181#define AVFMT_GLOBALHEADER 0x0040 /**< format wants global header */
182#define AVFMT_NOTIMESTAMPS 0x0080 /**< format does not need / have any timestamps */
183#define AVFMT_GENERIC_INDEX 0x0100 /**< use generic index building code */
184
185typedef struct AVOutputFormat {
186 const char *name;
187 /**
188 * Descriptive name for the format, meant to be more human-readable
189 * than \p name. You \e should use the NULL_IF_CONFIG_SMALL() macro
190 * to define it.
191 */
192 const char *long_name;
193 const char *mime_type;
194 const char *extensions; /**< comma separated filename extensions */
195 /** size of private data so that it can be allocated in the wrapper */
196 int priv_data_size;
197 /* output support */
198 enum CodecID audio_codec; /**< default audio codec */
199 enum CodecID video_codec; /**< default video codec */
200 int (*write_header)(struct AVFormatContext *);
201 int (*write_packet)(struct AVFormatContext *, AVPacket *pkt);
202 int (*write_trailer)(struct AVFormatContext *);
203 /** can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_GLOBALHEADER */
204 int flags;
205 /** currently only used to set pixel format if not YUV420P */
206 int (*set_parameters)(struct AVFormatContext *, AVFormatParameters *);
207 int (*interleave_packet)(struct AVFormatContext *, AVPacket *out, AVPacket *in, int flush);
208
209 /**
210 * list of supported codec_id-codec_tag pairs, ordered by "better choice first"
211 * the arrays are all CODEC_ID_NONE terminated
212 */
213 const struct AVCodecTag **codec_tag;
214
215 enum CodecID subtitle_codec; /**< default subtitle codec */
216
217 /* private fields */
218 struct AVOutputFormat *next;
219} AVOutputFormat;
220
221typedef struct AVInputFormat {
222 const char *name;
223 /**
224 * Descriptive name for the format, meant to be more human-readable
225 * than \p name. You \e should use the NULL_IF_CONFIG_SMALL() macro
226 * to define it.
227 */
228 const char *long_name;
229 /** size of private data so that it can be allocated in the wrapper */
230 int priv_data_size;
231 /**
232 * Tell if a given file has a chance of being parsed by this format.
233 * The buffer provided is guaranteed to be AVPROBE_PADDING_SIZE bytes
234 * big so you do not have to check for that unless you need more.
235 */
236 int (*read_probe)(AVProbeData *);
237 /** read the format header and initialize the AVFormatContext
238 structure. Return 0 if OK. 'ap' if non NULL contains
239 additional paramters. Only used in raw format right
240 now. 'av_new_stream' should be called to create new streams. */
241 int (*read_header)(struct AVFormatContext *,
242 AVFormatParameters *ap);
243 /** read one packet and put it in 'pkt'. pts and flags are also
244 set. 'av_new_stream' can be called only if the flag
245 AVFMTCTX_NOHEADER is used. */
246 int (*read_packet)(struct AVFormatContext *, AVPacket *pkt);
247 /** close the stream. The AVFormatContext and AVStreams are not
248 freed by this function */
249 int (*read_close)(struct AVFormatContext *);
250 /**
251 * seek to a given timestamp relative to the frames in
252 * stream component stream_index
253 * @param stream_index must not be -1
254 * @param flags selects which direction should be preferred if no exact
255 * match is available
256 * @return >= 0 on success (but not necessarily the new offset)
257 */
258 int (*read_seek)(struct AVFormatContext *,
259 int stream_index, int64_t timestamp, int flags);
260 /**
261 * gets the next timestamp in stream[stream_index].time_base units.
262 * @return the timestamp or AV_NOPTS_VALUE if an error occurred
263 */
264 int64_t (*read_timestamp)(struct AVFormatContext *s, int stream_index,
265 int64_t *pos, int64_t pos_limit);
266 /** can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER */
267 int flags;
268 /** if extensions are defined, then no probe is done. You should
269 usually not use extension format guessing because it is not
270 reliable enough */
271 const char *extensions;
272 /** general purpose read only value that the format can use */
273 int value;
274
275 /** start/resume playing - only meaningful if using a network based format
276 (RTSP) */
277 int (*read_play)(struct AVFormatContext *);
278
279 /** pause playing - only meaningful if using a network based format
280 (RTSP) */
281 int (*read_pause)(struct AVFormatContext *);
282
283 const struct AVCodecTag **codec_tag;
284
285 /* private fields */
286 struct AVInputFormat *next;
287} AVInputFormat;
288
289enum AVStreamParseType {
290 AVSTREAM_PARSE_NONE,
291 AVSTREAM_PARSE_FULL, /**< full parsing and repack */
292 AVSTREAM_PARSE_HEADERS, /**< only parse headers, don't repack */
293 AVSTREAM_PARSE_TIMESTAMPS, /**< full parsing and interpolation of timestamps for frames not starting on packet boundary */
294};
295
296typedef struct AVIndexEntry {
297 int64_t pos;
298 int64_t timestamp;
299#define AVINDEX_KEYFRAME 0x0001
300 int flags:2;
301 int size:30; //Yeah, trying to keep the size of this small to reduce memory requirements (it is 24 vs 32 byte due to possible 8byte align).
302 int min_distance; /**< min distance between this and the previous keyframe, used to avoid unneeded searching */
303} AVIndexEntry;
304
305#define AV_DISPOSITION_DEFAULT 0x0001
306#define AV_DISPOSITION_DUB 0x0002
307#define AV_DISPOSITION_ORIGINAL 0x0004
308#define AV_DISPOSITION_COMMENT 0x0008
309#define AV_DISPOSITION_LYRICS 0x0010
310#define AV_DISPOSITION_KARAOKE 0x0020
311
312/**
313 * Stream structure.
314 * New fields can be added to the end with minor version bumps.
315 * Removal, reordering and changes to existing fields require a major
316 * version bump.
317 * sizeof(AVStream) must not be used outside libav*.
318 */
319typedef struct AVStream {
320 int index; /**< stream index in AVFormatContext */
321 int id; /**< format specific stream id */
322 AVCodecContext *codec; /**< codec context */
323 /**
324 * Real base frame rate of the stream.
325 * This is the lowest frame rate with which all timestamps can be
326 * represented accurately (it is the least common multiple of all
327 * frame rates in the stream), Note, this value is just a guess!
328 * For example if the timebase is 1/90000 and all frames have either
329 * approximately 3600 or 1800 timer ticks then r_frame_rate will be 50/1.
330 */
331 AVRational r_frame_rate;
332 void *priv_data;
333
334 /* internal data used in av_find_stream_info() */
335 int64_t first_dts;
336 /** encoding: PTS generation when outputing stream */
337 struct AVFrac pts;
338
339 /**
340 * This is the fundamental unit of time (in seconds) in terms
341 * of which frame timestamps are represented. For fixed-fps content,
342 * timebase should be 1/frame rate and timestamp increments should be
343 * identically 1.
344 */
345 AVRational time_base;
346 int pts_wrap_bits; /**< number of bits in pts (used for wrapping control) */
347 /* ffmpeg.c private use */
348 int stream_copy; /**< if set, just copy stream */
349 enum AVDiscard discard; ///< selects which packets can be discarded at will and do not need to be demuxed
350 //FIXME move stuff to a flags field?
351 /** quality, as it has been removed from AVCodecContext and put in AVVideoFrame
352 * MN: dunno if that is the right place for it */
353 float quality;
354 /**
355 * Decoding: pts of the first frame of the stream, in stream time base.
356 * Only set this if you are absolutely 100% sure that the value you set
357 * it to really is the pts of the first frame.
358 * This may be undefined (AV_NOPTS_VALUE).
359 * @note The ASF header does NOT contain a correct start_time the ASF
360 * demuxer must NOT set this.
361 */
362 int64_t start_time;
363 /**
364 * Decoding: duration of the stream, in stream time base.
365 * If a source file does not specify a duration, but does specify
366 * a bitrate, this value will be estimates from bit rate and file size.
367 */
368 int64_t duration;
369
370 char language[4]; /** ISO 639 3-letter language code (empty string if undefined) */
371
372 /* av_read_frame() support */
373 enum AVStreamParseType need_parsing;
374 struct AVCodecParserContext *parser;
375
376 int64_t cur_dts;
377 int last_IP_duration;
378 int64_t last_IP_pts;
379 /* av_seek_frame() support */
380 AVIndexEntry *index_entries; /**< only used if the format does not
381 support seeking natively */
382 int nb_index_entries;
383 unsigned int index_entries_allocated_size;
384
385 int64_t nb_frames; ///< number of frames in this stream if known or 0
386
387#define MAX_REORDER_DELAY 4
388 int64_t pts_buffer[MAX_REORDER_DELAY+1];
389
390 char *filename; /**< source filename of the stream */
391
392 int disposition; /**< AV_DISPOSITION_* bitfield */
393
394 AVProbeData probe_data;
395} AVStream;
396
397#define AV_PROGRAM_RUNNING 1
398
399/**
400 * New fields can be added to the end with minor version bumps.
401 * Removal, reordering and changes to existing fields require a major
402 * version bump.
403 * sizeof(AVProgram) must not be used outside libav*.
404 */
405typedef struct AVProgram {
406 int id;
407 char *provider_name; ///< Network name for DVB streams
408 char *name; ///< Service name for DVB streams
409 int flags;
410 enum AVDiscard discard; ///< selects which program to discard and which to feed to the caller
411 unsigned int *stream_index;
412 unsigned int nb_stream_indexes;
413} AVProgram;
414
415#define AVFMTCTX_NOHEADER 0x0001 /**< signal that no header is present
416 (streams are added dynamically) */
417
418typedef struct AVChapter {
419 int id; ///< Unique id to identify the chapter
420 AVRational time_base; ///< Timebase in which the start/end timestamps are specified
421 int64_t start, end; ///< chapter start/end time in time_base units
422 char *title; ///< chapter title
423} AVChapter;
424
425#define MAX_STREAMS 20
426
427/**
428 * format I/O context.
429 * New fields can be added to the end with minor version bumps.
430 * Removal, reordering and changes to existing fields require a major
431 * version bump.
432 * sizeof(AVFormatContext) must not be used outside libav*.
433 */
434typedef struct AVFormatContext {
435 const AVClass *av_class; /**< set by av_alloc_format_context */
436 /* can only be iformat or oformat, not both at the same time */
437 struct AVInputFormat *iformat;
438 struct AVOutputFormat *oformat;
439 void *priv_data;
440 ByteIOContext *pb;
441 unsigned int nb_streams;
442 AVStream *streams[MAX_STREAMS];
443 char filename[1024]; /**< input or output filename */
444 /* stream info */
445 int64_t timestamp;
446 char title[512];
447 char author[512];
448 char copyright[512];
449 char comment[512];
450 char album[512];
451 int year; /**< ID3 year, 0 if none */
452 int track; /**< track number, 0 if none */
453 char genre[32]; /**< ID3 genre */
454
455 int ctx_flags; /**< format specific flags, see AVFMTCTX_xx */
456 /* private data for pts handling (do not modify directly) */
457 /** This buffer is only needed when packets were already buffered but
458 not decoded, for example to get the codec parameters in mpeg
459 streams */
460 struct AVPacketList *packet_buffer;
461
462 /** decoding: position of the first frame of the component, in
463 AV_TIME_BASE fractional seconds. NEVER set this value directly:
464 it is deduced from the AVStream values. */
465 int64_t start_time;
466 /** decoding: duration of the stream, in AV_TIME_BASE fractional
467 seconds. NEVER set this value directly: it is deduced from the
468 AVStream values. */
469 int64_t duration;
470 /** decoding: total file size. 0 if unknown */
471 int64_t file_size;
472 /** decoding: total stream bitrate in bit/s, 0 if not
473 available. Never set it directly if the file_size and the
474 duration are known as ffmpeg can compute it automatically. */
475 int bit_rate;
476
477 /* av_read_frame() support */
478 AVStream *cur_st;
479 const uint8_t *cur_ptr;
480 int cur_len;
481 AVPacket cur_pkt;
482
483 /* av_seek_frame() support */
484 int64_t data_offset; /** offset of the first packet */
485 int index_built;
486
487 int mux_rate;
488 int packet_size;
489 int preload;
490 int max_delay;
491
492#define AVFMT_NOOUTPUTLOOP -1
493#define AVFMT_INFINITEOUTPUTLOOP 0
494 /** number of times to loop output in formats that support it */
495 int loop_output;
496
497 int flags;
498#define AVFMT_FLAG_GENPTS 0x0001 ///< generate pts if missing even if it requires parsing future frames
499#define AVFMT_FLAG_IGNIDX 0x0002 ///< ignore index
500#define AVFMT_FLAG_NONBLOCK 0x0004 ///< do not block when reading packets from input
501
502 int loop_input;
503 /** decoding: size of data to probe; encoding unused */
504 unsigned int probesize;
505
506 /**
507 * maximum duration in AV_TIME_BASE units over which the input should be analyzed in av_find_stream_info()
508 */
509 int max_analyze_duration;
510
511 const uint8_t *key;
512 int keylen;
513
514 unsigned int nb_programs;
515 AVProgram **programs;
516
517 /**
518 * Forced video codec_id.
519 * demuxing: set by user
520 */
521 enum CodecID video_codec_id;
522 /**
523 * Forced audio codec_id.
524 * demuxing: set by user
525 */
526 enum CodecID audio_codec_id;
527 /**
528 * Forced subtitle codec_id.
529 * demuxing: set by user
530 */
531 enum CodecID subtitle_codec_id;
532
533 /**
534 * Maximum amount of memory in bytes to use per stream for the index.
535 * If the needed index exceeds this size entries will be discarded as
536 * needed to maintain a smaller size. This can lead to slower or less
537 * accurate seeking (depends on demuxer).
538 * Demuxers for which a full in memory index is mandatory will ignore
539 * this.
540 * muxing : unused
541 * demuxing: set by user
542 */
543 unsigned int max_index_size;
544
545 /**
546 * Maximum amount of memory in bytes to use for buffering frames
547 * obtained from real-time capture devices.
548 */
549 unsigned int max_picture_buffer;
550
551 unsigned int nb_chapters;
552 AVChapter **chapters;
553
554 /**
555 * Flags to enable debuging.
556 */
557 int debug;
558#define FF_FDEBUG_TS 0x0001
559
560 /**
561 * raw packets from the demuxer, prior to parsing and decoding.
562 * This buffer is used for buffering packets until the codec can
563 * be identified, as parsing cannot be done without knowing the
564 * codec.
565 */
566 struct AVPacketList *raw_packet_buffer;
567} AVFormatContext;
568
569typedef struct AVPacketList {
570 AVPacket pkt;
571 struct AVPacketList *next;
572} AVPacketList;
573
574#if LIBAVFORMAT_VERSION_INT < (53<<16)
575extern AVInputFormat *first_iformat;
576extern AVOutputFormat *first_oformat;
577#endif
578
579AVInputFormat *av_iformat_next(AVInputFormat *f);
580AVOutputFormat *av_oformat_next(AVOutputFormat *f);
581
582enum CodecID av_guess_image2_codec(const char *filename);
583
584/* XXX: use automatic init with either ELF sections or C file parser */
585/* modules */
586
587/* utils.c */
588void av_register_input_format(AVInputFormat *format);
589void av_register_output_format(AVOutputFormat *format);
590AVOutputFormat *guess_stream_format(const char *short_name,
591 const char *filename, const char *mime_type);
592AVOutputFormat *guess_format(const char *short_name,
593 const char *filename, const char *mime_type);
594
595/**
596 * Guesses the codec id based upon muxer and filename.
597 */
598enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
599 const char *filename, const char *mime_type, enum CodecType type);
600
601/**
602 * Send a nice hexadecimal dump of a buffer to the specified file stream.
603 *
604 * @param f The file stream pointer where the dump should be sent to.
605 * @param buf buffer
606 * @param size buffer size
607 *
608 * @see av_hex_dump_log, av_pkt_dump, av_pkt_dump_log
609 */
610void av_hex_dump(FILE *f, uint8_t *buf, int size);
611
612/**
613 * Send a nice hexadecimal dump of a buffer to the log.
614 *
615 * @param avcl A pointer to an arbitrary struct of which the first field is a
616 * pointer to an AVClass struct.
617 * @param level The importance level of the message, lower values signifying
618 * higher importance.
619 * @param buf buffer
620 * @param size buffer size
621 *
622 * @see av_hex_dump, av_pkt_dump, av_pkt_dump_log
623 */
624void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size);
625
626/**
627 * Send a nice dump of a packet to the specified file stream.
628 *
629 * @param f The file stream pointer where the dump should be sent to.
630 * @param pkt packet to dump
631 * @param dump_payload true if the payload must be displayed too
632 */
633void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload);
634
635/**
636 * Send a nice dump of a packet to the log.
637 *
638 * @param avcl A pointer to an arbitrary struct of which the first field is a
639 * pointer to an AVClass struct.
640 * @param level The importance level of the message, lower values signifying
641 * higher importance.
642 * @param pkt packet to dump
643 * @param dump_payload true if the payload must be displayed too
644 */
645void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload);
646
647void av_register_all(void);
648
649/** codec tag <-> codec id */
650enum CodecID av_codec_get_id(const struct AVCodecTag **tags, unsigned int tag);
651unsigned int av_codec_get_tag(const struct AVCodecTag **tags, enum CodecID id);
652
653/* media file input */
654
655/**
656 * finds AVInputFormat based on input format's short name.
657 */
658AVInputFormat *av_find_input_format(const char *short_name);
659
660/**
661 * Guess file format.
662 *
663 * @param is_opened whether the file is already opened, determines whether
664 * demuxers with or without AVFMT_NOFILE are probed
665 */
666AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened);
667
668/**
669 * Allocates all the structures needed to read an input stream.
670 * This does not open the needed codecs for decoding the stream[s].
671 */
672int av_open_input_stream(AVFormatContext **ic_ptr,
673 ByteIOContext *pb, const char *filename,
674 AVInputFormat *fmt, AVFormatParameters *ap);
675
676/**
677 * Open a media file as input. The codecs are not opened. Only the file
678 * header (if present) is read.
679 *
680 * @param ic_ptr the opened media file handle is put here
681 * @param filename filename to open.
682 * @param fmt if non NULL, force the file format to use
683 * @param buf_size optional buffer size (zero if default is OK)
684 * @param ap additional parameters needed when opening the file (NULL if default)
685 * @return 0 if OK. AVERROR_xxx otherwise.
686 */
687int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
688 AVInputFormat *fmt,
689 int buf_size,
690 AVFormatParameters *ap);
691/**
692 * Allocate an AVFormatContext.
693 * Can be freed with av_free() but do not forget to free everything you
694 * explicitly allocated as well!
695 */
696AVFormatContext *av_alloc_format_context(void);
697
698/**
699 * Read packets of a media file to get stream information. This
700 * is useful for file formats with no headers such as MPEG. This
701 * function also computes the real frame rate in case of mpeg2 repeat
702 * frame mode.
703 * The logical file position is not changed by this function;
704 * examined packets may be buffered for later processing.
705 *
706 * @param ic media file handle
707 * @return >=0 if OK. AVERROR_xxx if error.
708 * @todo Let user decide somehow what information is needed so we do not waste time getting stuff the user does not need.
709 */
710int av_find_stream_info(AVFormatContext *ic);
711
712/**
713 * Read a transport packet from a media file.
714 *
715 * This function is obsolete and should never be used.
716 * Use av_read_frame() instead.
717 *
718 * @param s media file handle
719 * @param pkt is filled
720 * @return 0 if OK. AVERROR_xxx if error.
721 */
722int av_read_packet(AVFormatContext *s, AVPacket *pkt);
723
724/**
725 * Return the next frame of a stream.
726 *
727 * The returned packet is valid
728 * until the next av_read_frame() or until av_close_input_file() and
729 * must be freed with av_free_packet. For video, the packet contains
730 * exactly one frame. For audio, it contains an integer number of
731 * frames if each frame has a known fixed size (e.g. PCM or ADPCM
732 * data). If the audio frames have a variable size (e.g. MPEG audio),
733 * then it contains one frame.
734 *
735 * pkt->pts, pkt->dts and pkt->duration are always set to correct
736 * values in AVStream.timebase units (and guessed if the format cannot
737 * provided them). pkt->pts can be AV_NOPTS_VALUE if the video format
738 * has B frames, so it is better to rely on pkt->dts if you do not
739 * decompress the payload.
740 *
741 * @return 0 if OK, < 0 if error or end of file.
742 */
743int av_read_frame(AVFormatContext *s, AVPacket *pkt);
744
745/**
746 * Seek to the key frame at timestamp.
747 * 'timestamp' in 'stream_index'.
748 * @param stream_index If stream_index is (-1), a default
749 * stream is selected, and timestamp is automatically converted
750 * from AV_TIME_BASE units to the stream specific time_base.
751 * @param timestamp timestamp in AVStream.time_base units
752 * or if there is no stream specified then in AV_TIME_BASE units
753 * @param flags flags which select direction and seeking mode
754 * @return >= 0 on success
755 */
756int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags);
757
758/**
759 * start playing a network based stream (e.g. RTSP stream) at the
760 * current position
761 */
762int av_read_play(AVFormatContext *s);
763
764/**
765 * Pause a network based stream (e.g. RTSP stream).
766 *
767 * Use av_read_play() to resume it.
768 */
769int av_read_pause(AVFormatContext *s);
770
771/**
772 * Free a AVFormatContext allocated by av_open_input_stream.
773 * @param s context to free
774 */
775void av_close_input_stream(AVFormatContext *s);
776
777/**
778 * Close a media file (but not its codecs).
779 *
780 * @param s media file handle
781 */
782void av_close_input_file(AVFormatContext *s);
783
784/**
785 * Add a new stream to a media file.
786 *
787 * Can only be called in the read_header() function. If the flag
788 * AVFMTCTX_NOHEADER is in the format context, then new streams
789 * can be added in read_packet too.
790 *
791 * @param s media file handle
792 * @param id file format dependent stream id
793 */
794AVStream *av_new_stream(AVFormatContext *s, int id);
795AVProgram *av_new_program(AVFormatContext *s, int id);
796
797/**
798 * Add a new chapter.
799 * This function is NOT part of the public API
800 * and should be ONLY used by demuxers.
801 *
802 * @param s media file handle
803 * @param id unique id for this chapter
804 * @param start chapter start time in time_base units
805 * @param end chapter end time in time_base units
806 * @param title chapter title
807 *
808 * @return AVChapter or NULL if error.
809 */
810AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title);
811
812/**
813 * Set the pts for a given stream.
814 *
815 * @param s stream
816 * @param pts_wrap_bits number of bits effectively used by the pts
817 * (used for wrap control, 33 is the value for MPEG)
818 * @param pts_num numerator to convert to seconds (MPEG: 1)
819 * @param pts_den denominator to convert to seconds (MPEG: 90000)
820 */
821void av_set_pts_info(AVStream *s, int pts_wrap_bits,
822 int pts_num, int pts_den);
823
824#define AVSEEK_FLAG_BACKWARD 1 ///< seek backward
825#define AVSEEK_FLAG_BYTE 2 ///< seeking based on position in bytes
826#define AVSEEK_FLAG_ANY 4 ///< seek to any frame, even non keyframes
827
828int av_find_default_stream_index(AVFormatContext *s);
829
830/**
831 * Gets the index for a specific timestamp.
832 * @param flags if AVSEEK_FLAG_BACKWARD then the returned index will correspond to
833 * the timestamp which is <= the requested one, if backward is 0
834 * then it will be >=
835 * if AVSEEK_FLAG_ANY seek to any frame, only keyframes otherwise
836 * @return < 0 if no such timestamp could be found
837 */
838int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags);
839
840/**
841 * Ensures the index uses less memory than the maximum specified in
842 * AVFormatContext.max_index_size, by discarding entries if it grows
843 * too large.
844 * This function is not part of the public API and should only be called
845 * by demuxers.
846 */
847void ff_reduce_index(AVFormatContext *s, int stream_index);
848
849/**
850 * Add a index entry into a sorted list updateing if it is already there.
851 *
852 * @param timestamp timestamp in the timebase of the given stream
853 */
854int av_add_index_entry(AVStream *st,
855 int64_t pos, int64_t timestamp, int size, int distance, int flags);
856
857/**
858 * Does a binary search using av_index_search_timestamp() and AVCodec.read_timestamp().
859 * This is not supposed to be called directly by a user application, but by demuxers.
860 * @param target_ts target timestamp in the time base of the given stream
861 * @param stream_index stream number
862 */
863int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags);
864
865/**
866 * Updates cur_dts of all streams based on given timestamp and AVStream.
867 *
868 * Stream ref_st unchanged, others set cur_dts in their native timebase
869 * only needed for timestamp wrapping or if (dts not set and pts!=dts).
870 * @param timestamp new dts expressed in time_base of param ref_st
871 * @param ref_st reference stream giving time_base of param timestamp
872 */
873void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp);
874
875/**
876 * Does a binary search using read_timestamp().
877 * This is not supposed to be called directly by a user application, but by demuxers.
878 * @param target_ts target timestamp in the time base of the given stream
879 * @param stream_index stream number
880 */
881int64_t av_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts, int64_t pos_min, int64_t pos_max, int64_t pos_limit, int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret, int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ));
882
883/** media file output */
884int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap);
885
886/**
887 * Allocate the stream private data and write the stream header to an
888 * output media file.
889 *
890 * @param s media file handle
891 * @return 0 if OK. AVERROR_xxx if error.
892 */
893int av_write_header(AVFormatContext *s);
894
895/**
896 * Write a packet to an output media file.
897 *
898 * The packet shall contain one audio or video frame.
899 * The packet must be correctly interleaved according to the container specification,
900 * if not then av_interleaved_write_frame must be used
901 *
902 * @param s media file handle
903 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
904 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
905 */
906int av_write_frame(AVFormatContext *s, AVPacket *pkt);
907
908/**
909 * Writes a packet to an output media file ensuring correct interleaving.
910 *
911 * The packet must contain one audio or video frame.
912 * If the packets are already correctly interleaved the application should
913 * call av_write_frame() instead as it is slightly faster. It is also important
914 * to keep in mind that completely non-interleaved input will need huge amounts
915 * of memory to interleave with this, so it is preferable to interleave at the
916 * demuxer level.
917 *
918 * @param s media file handle
919 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
920 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
921 */
922int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt);
923
924/**
925 * Interleave a packet per DTS in an output media file.
926 *
927 * Packets with pkt->destruct == av_destruct_packet will be freed inside this function,
928 * so they cannot be used after it, note calling av_free_packet() on them is still safe.
929 *
930 * @param s media file handle
931 * @param out the interleaved packet will be output here
932 * @param in the input packet
933 * @param flush 1 if no further packets are available as input and all
934 * remaining packets should be output
935 * @return 1 if a packet was output, 0 if no packet could be output,
936 * < 0 if an error occurred
937 */
938int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush);
939
940/**
941 * @brief Write the stream trailer to an output media file and
942 * free the file private data.
943 *
944 * @param s media file handle
945 * @return 0 if OK. AVERROR_xxx if error.
946 */
947int av_write_trailer(AVFormatContext *s);
948
949void dump_format(AVFormatContext *ic,
950 int index,
951 const char *url,
952 int is_output);
953
954/**
955 * parses width and height out of string str.
956 * @deprecated Use av_parse_video_frame_size instead.
957 */
958attribute_deprecated int parse_image_size(int *width_ptr, int *height_ptr, const char *str);
959
960/**
961 * Converts frame rate from string to a fraction.
962 * @deprecated Use av_parse_video_frame_rate instead.
963 */
964attribute_deprecated int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg);
965
966/**
967 * Parses \p datestr and returns a corresponding number of microseconds.
968 * @param datestr String representing a date or a duration.
969 * - If a date the syntax is:
970 * @code
971 * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
972 * @endcode
973 * Time is localtime unless Z is appended, in which case it is
974 * interpreted as UTC.
975 * If the year-month-day part isn't specified it takes the current
976 * year-month-day.
977 * Returns the number of microseconds since 1st of January, 1970 up to
978 * the time of the parsed date or INT64_MIN if \p datestr cannot be
979 * successfully parsed.
980 * - If a duration the syntax is:
981 * @code
982 * [-]HH[:MM[:SS[.m...]]]
983 * [-]S+[.m...]
984 * @endcode
985 * Returns the number of microseconds contained in a time interval
986 * with the specified duration or INT64_MIN if \p datestr cannot be
987 * successfully parsed.
988 * @param duration Flag which tells how to interpret \p datestr, if
989 * not zero \p datestr is interpreted as a duration, otherwise as a
990 * date.
991 */
992int64_t parse_date(const char *datestr, int duration);
993
994int64_t av_gettime(void);
995
996/* ffm specific for ffserver */
997#define FFM_PACKET_SIZE 4096
998offset_t ffm_read_write_index(int fd);
999void ffm_write_write_index(int fd, offset_t pos);
1000void ffm_set_write_index(AVFormatContext *s, offset_t pos, offset_t file_size);
1001
1002/**
1003 * Attempts to find a specific tag in a URL.
1004 *
1005 * syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done.
1006 * Return 1 if found.
1007 */
1008int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info);
1009
1010/**
1011 * Returns in 'buf' the path with '%d' replaced by number.
1012
1013 * Also handles the '%0nd' format where 'n' is the total number
1014 * of digits and '%%'.
1015 *
1016 * @param buf destination buffer
1017 * @param buf_size destination buffer size
1018 * @param path numbered sequence string
1019 * @param number frame number
1020 * @return 0 if OK, -1 if format error.
1021 */
1022int av_get_frame_filename(char *buf, int buf_size,
1023 const char *path, int number);
1024
1025/**
1026 * Check whether filename actually is a numbered sequence generator.
1027 *
1028 * @param filename possible numbered sequence string
1029 * @return 1 if a valid numbered sequence string, 0 otherwise.
1030 */
1031int av_filename_number_test(const char *filename);
1032
1033/**
1034 * Generate an SDP for an RTP session.
1035 *
1036 * @param ac array of AVFormatContexts describing the RTP streams. If the
1037 * array is composed by only one context, such context can contain
1038 * multiple AVStreams (one AVStream per RTP stream). Otherwise,
1039 * all the contexts in the array (an AVCodecContext per RTP stream)
1040 * must contain only one AVStream
1041 * @param n_files number of AVCodecContexts contained in ac
1042 * @param buff buffer where the SDP will be stored (must be allocated by
1043 * the caller
1044 * @param size the size of the buffer
1045 * @return 0 if OK. AVERROR_xxx if error.
1046 */
1047int avf_sdp_create(AVFormatContext *ac[], int n_files, char *buff, int size);
1048
1049#ifdef HAVE_AV_CONFIG_H
1050
1051void ff_dynarray_add(unsigned long **tab_ptr, int *nb_ptr, unsigned long elem);
1052
1053#ifdef __GNUC__
1054#define dynarray_add(tab, nb_ptr, elem)\
1055do {\
1056 typeof(tab) _tab = (tab);\
1057 typeof(elem) _elem = (elem);\
1058 (void)sizeof(**_tab == _elem); /* check that types are compatible */\
1059 ff_dynarray_add((unsigned long **)_tab, nb_ptr, (unsigned long)_elem);\
1060} while(0)
1061#else
1062#define dynarray_add(tab, nb_ptr, elem)\
1063do {\
1064 ff_dynarray_add((unsigned long **)(tab), nb_ptr, (unsigned long)(elem));\
1065} while(0)
1066#endif
1067
1068time_t mktimegm(struct tm *tm);
1069struct tm *brktimegm(time_t secs, struct tm *tm);
1070const char *small_strptime(const char *p, const char *fmt,
1071 struct tm *dt);
1072
1073struct in_addr;
1074int resolve_host(struct in_addr *sin_addr, const char *hostname);
1075
1076void url_split(char *proto, int proto_size,
1077 char *authorization, int authorization_size,
1078 char *hostname, int hostname_size,
1079 int *port_ptr,
1080 char *path, int path_size,
1081 const char *url);
1082
1083int match_ext(const char *filename, const char *extensions);
1084
1085#endif /* HAVE_AV_CONFIG_H */
1086
1087#endif /* FFMPEG_AVFORMAT_H */
diff --git a/src/plugins/ffmpeg/libavformat/avi.h b/src/plugins/ffmpeg/libavformat/avi.h
deleted file mode 100644
index 3d3dd54..0000000
--- a/src/plugins/ffmpeg/libavformat/avi.h
+++ /dev/null
@@ -1,37 +0,0 @@
1/*
2 * copyright (c) 2001 Fabrice Bellard
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21#ifndef FFMPEG_AVI_H
22#define FFMPEG_AVI_H
23
24#define AVIF_HASINDEX 0x00000010 // Index at end of file?
25#define AVIF_MUSTUSEINDEX 0x00000020
26#define AVIF_ISINTERLEAVED 0x00000100
27#define AVIF_TRUSTCKTYPE 0x00000800 // Use CKType to find key frames?
28#define AVIF_WASCAPTUREFILE 0x00010000
29#define AVIF_COPYRIGHTED 0x00020000
30
31#define AVI_MAX_RIFF_SIZE 0x40000000LL
32#define AVI_MASTER_INDEX_SIZE 256
33
34/* index flags */
35#define AVIIF_INDEX 0x10
36
37#endif /* FFMPEG_AVI_H */
diff --git a/src/plugins/ffmpeg/libavformat/avidec.c b/src/plugins/ffmpeg/libavformat/avidec.c
deleted file mode 100644
index 0712dc3..0000000
--- a/src/plugins/ffmpeg/libavformat/avidec.c
+++ /dev/null
@@ -1,1096 +0,0 @@
1/*
2 * AVI demuxer
3 * Copyright (c) 2001 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#include "avformat.h"
22#include "avi.h"
23#include "dv.h"
24#include "riff.h"
25
26#undef NDEBUG
27#include <assert.h>
28
29//#define DEBUG
30//#define DEBUG_SEEK
31
32typedef struct AVIStream {
33 int64_t frame_offset; /* current frame (video) or byte (audio) counter
34 (used to compute the pts) */
35 int remaining;
36 int packet_size;
37
38 int scale;
39 int rate;
40 int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
41
42 int64_t cum_len; /* temporary storage (used during seek) */
43
44 int prefix; ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
45 int prefix_count;
46 uint32_t pal[256];
47 int has_pal;
48} AVIStream;
49
50typedef struct {
51 int64_t riff_end;
52 int64_t movi_end;
53 int64_t fsize;
54 offset_t movi_list;
55 int index_loaded;
56 int is_odml;
57 int non_interleaved;
58 int stream_index;
59 DVDemuxContext* dv_demux;
60} AVIContext;
61
62static const char avi_headers[][8] = {
63 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
64 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
65 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19},
66 { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
67 { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
68 { 0 }
69};
70
71static int avi_load_index(AVFormatContext *s);
72static int guess_ni_flag(AVFormatContext *s);
73
74#ifdef DEBUG
75static void print_tag(const char *str, unsigned int tag, int size)
76{
77 printf("%s: tag=%c%c%c%c size=0x%x\n",
78 str, tag & 0xff,
79 (tag >> 8) & 0xff,
80 (tag >> 16) & 0xff,
81 (tag >> 24) & 0xff,
82 size);
83}
84#endif
85
86static int get_riff(AVIContext *avi, ByteIOContext *pb)
87{
88 char header[8];
89 int i;
90
91 /* check RIFF header */
92 get_buffer(pb, header, 4);
93 avi->riff_end = get_le32(pb); /* RIFF chunk size */
94 avi->riff_end += url_ftell(pb); /* RIFF chunk end */
95 get_buffer(pb, header+4, 4);
96
97 for(i=0; avi_headers[i][0]; i++)
98 if(!memcmp(header, avi_headers[i], 8))
99 break;
100 if(!avi_headers[i][0])
101 return -1;
102
103 if(header[7] == 0x19)
104 av_log(NULL, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
105
106 return 0;
107}
108
109static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
110 AVIContext *avi = s->priv_data;
111 ByteIOContext *pb = s->pb;
112 int longs_pre_entry= get_le16(pb);
113 int index_sub_type = get_byte(pb);
114 int index_type = get_byte(pb);
115 int entries_in_use = get_le32(pb);
116 int chunk_id = get_le32(pb);
117 int64_t base = get_le64(pb);
118 int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
119 AVStream *st;
120 AVIStream *ast;
121 int i;
122 int64_t last_pos= -1;
123 int64_t filesize= url_fsize(s->pb);
124
125#ifdef DEBUG_SEEK
126 av_log(s, AV_LOG_ERROR, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
127 longs_pre_entry,index_type, entries_in_use, chunk_id, base);
128#endif
129
130 if(stream_id > s->nb_streams || stream_id < 0)
131 return -1;
132 st= s->streams[stream_id];
133 ast = st->priv_data;
134
135 if(index_sub_type)
136 return -1;
137
138 get_le32(pb);
139
140 if(index_type && longs_pre_entry != 2)
141 return -1;
142 if(index_type>1)
143 return -1;
144
145 if(filesize > 0 && base >= filesize){
146 av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
147 if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
148 base &= 0xFFFFFFFF;
149 else
150 return -1;
151 }
152
153 for(i=0; i<entries_in_use; i++){
154 if(index_type){
155 int64_t pos= get_le32(pb) + base - 8;
156 int len = get_le32(pb);
157 int key= len >= 0;
158 len &= 0x7FFFFFFF;
159
160#ifdef DEBUG_SEEK
161 av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
162#endif
163 if(last_pos == pos || pos == base - 8)
164 avi->non_interleaved= 1;
165 else
166 av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, key ? AVINDEX_KEYFRAME : 0);
167
168 if(ast->sample_size)
169 ast->cum_len += len;
170 else
171 ast->cum_len ++;
172 last_pos= pos;
173 }else{
174 int64_t offset, pos;
175 int duration;
176 offset = get_le64(pb);
177 get_le32(pb); /* size */
178 duration = get_le32(pb);
179 pos = url_ftell(pb);
180
181 url_fseek(pb, offset+8, SEEK_SET);
182 read_braindead_odml_indx(s, frame_num);
183 frame_num += duration;
184
185 url_fseek(pb, pos, SEEK_SET);
186 }
187 }
188 avi->index_loaded=1;
189 return 0;
190}
191
192static void clean_index(AVFormatContext *s){
193 int i;
194 int64_t j;
195
196 for(i=0; i<s->nb_streams; i++){
197 AVStream *st = s->streams[i];
198 AVIStream *ast = st->priv_data;
199 int n= st->nb_index_entries;
200 int max= ast->sample_size;
201 int64_t pos, size, ts;
202
203 if(n != 1 || ast->sample_size==0)
204 continue;
205
206 while(max < 1024) max+=max;
207
208 pos= st->index_entries[0].pos;
209 size= st->index_entries[0].size;
210 ts= st->index_entries[0].timestamp;
211
212 for(j=0; j<size; j+=max){
213 av_add_index_entry(st, pos+j, ts + j/ast->sample_size, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
214 }
215 }
216}
217
218static int avi_read_tag(ByteIOContext *pb, char *buf, int maxlen, unsigned int size)
219{
220 offset_t i = url_ftell(pb);
221 size += (size & 1);
222 get_strz(pb, buf, maxlen);
223 url_fseek(pb, i+size, SEEK_SET);
224 return 0;
225}
226
227static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
228{
229 AVIContext *avi = s->priv_data;
230 ByteIOContext *pb = s->pb;
231 uint32_t tag, tag1, handler;
232 int codec_type, stream_index, frame_period, bit_rate;
233 unsigned int size, nb_frames;
234 int i;
235 AVStream *st;
236 AVIStream *ast = NULL;
237 char str_track[4];
238 int avih_width=0, avih_height=0;
239 int amv_file_format=0;
240
241 avi->stream_index= -1;
242
243 if (get_riff(avi, pb) < 0)
244 return -1;
245
246 avi->fsize = url_fsize(pb);
247 if(avi->fsize<=0)
248 avi->fsize= avi->riff_end;
249
250 /* first list tag */
251 stream_index = -1;
252 codec_type = -1;
253 frame_period = 0;
254 for(;;) {
255 if (url_feof(pb))
256 goto fail;
257 tag = get_le32(pb);
258 size = get_le32(pb);
259#ifdef DEBUG
260 print_tag("tag", tag, size);
261#endif
262
263 switch(tag) {
264 case MKTAG('L', 'I', 'S', 'T'):
265 /* Ignored, except at start of video packets. */
266 tag1 = get_le32(pb);
267#ifdef DEBUG
268 print_tag("list", tag1, 0);
269#endif
270 if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
271 avi->movi_list = url_ftell(pb) - 4;
272 if(size) avi->movi_end = avi->movi_list + size + (size & 1);
273 else avi->movi_end = url_fsize(pb);
274#ifdef DEBUG
275 printf("movi end=%"PRIx64"\n", avi->movi_end);
276#endif
277 goto end_of_header;
278 }
279 break;
280 case MKTAG('d', 'm', 'l', 'h'):
281 avi->is_odml = 1;
282 url_fskip(pb, size + (size & 1));
283 break;
284 case MKTAG('a', 'm', 'v', 'h'):
285 amv_file_format=1;
286 case MKTAG('a', 'v', 'i', 'h'):
287 /* AVI header */
288 /* using frame_period is bad idea */
289 frame_period = get_le32(pb);
290 bit_rate = get_le32(pb) * 8;
291 get_le32(pb);
292 avi->non_interleaved |= get_le32(pb) & AVIF_MUSTUSEINDEX;
293
294 url_fskip(pb, 2 * 4);
295 get_le32(pb);
296 get_le32(pb);
297 avih_width=get_le32(pb);
298 avih_height=get_le32(pb);
299
300 url_fskip(pb, size - 10 * 4);
301 break;
302 case MKTAG('s', 't', 'r', 'h'):
303 /* stream header */
304
305 tag1 = get_le32(pb);
306 handler = get_le32(pb); /* codec tag */
307
308 if(tag1 == MKTAG('p', 'a', 'd', 's')){
309 url_fskip(pb, size - 8);
310 break;
311 }else{
312 stream_index++;
313 st = av_new_stream(s, stream_index);
314 if (!st)
315 goto fail;
316
317 ast = av_mallocz(sizeof(AVIStream));
318 if (!ast)
319 goto fail;
320 st->priv_data = ast;
321 }
322 if(amv_file_format)
323 tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
324
325#ifdef DEBUG
326 print_tag("strh", tag1, -1);
327#endif
328 if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
329 int64_t dv_dur;
330
331 /*
332 * After some consideration -- I don't think we
333 * have to support anything but DV in type1 AVIs.
334 */
335 if (s->nb_streams != 1)
336 goto fail;
337
338 if (handler != MKTAG('d', 'v', 's', 'd') &&
339 handler != MKTAG('d', 'v', 'h', 'd') &&
340 handler != MKTAG('d', 'v', 's', 'l'))
341 goto fail;
342
343 ast = s->streams[0]->priv_data;
344 av_freep(&s->streams[0]->codec->extradata);
345 av_freep(&s->streams[0]);
346 s->nb_streams = 0;
347 if (ENABLE_DV_DEMUXER) {
348 avi->dv_demux = dv_init_demux(s);
349 if (!avi->dv_demux)
350 goto fail;
351 }
352 s->streams[0]->priv_data = ast;
353 url_fskip(pb, 3 * 4);
354 ast->scale = get_le32(pb);
355 ast->rate = get_le32(pb);
356 url_fskip(pb, 4); /* start time */
357
358 dv_dur = get_le32(pb);
359 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
360 dv_dur *= AV_TIME_BASE;
361 s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
362 }
363 /*
364 * else, leave duration alone; timing estimation in utils.c
365 * will make a guess based on bitrate.
366 */
367
368 stream_index = s->nb_streams - 1;
369 url_fskip(pb, size - 9*4);
370 break;
371 }
372
373 assert(stream_index < s->nb_streams);
374 st->codec->stream_codec_tag= handler;
375
376 get_le32(pb); /* flags */
377 get_le16(pb); /* priority */
378 get_le16(pb); /* language */
379 get_le32(pb); /* initial frame */
380 ast->scale = get_le32(pb);
381 ast->rate = get_le32(pb);
382 if(!(ast->scale && ast->rate)){
383 av_log(s, AV_LOG_WARNING, "scale/rate is %u/%u which is invalid. (This file has been generated by broken software.)\n", ast->scale, ast->rate);
384 if(frame_period){
385 ast->rate = 1000000;
386 ast->scale = frame_period;
387 }else{
388 ast->rate = 25;
389 ast->scale = 1;
390 }
391 }
392 av_set_pts_info(st, 64, ast->scale, ast->rate);
393
394 ast->cum_len=get_le32(pb); /* start */
395 nb_frames = get_le32(pb);
396
397 st->start_time = 0;
398 st->duration = nb_frames;
399 get_le32(pb); /* buffer size */
400 get_le32(pb); /* quality */
401 ast->sample_size = get_le32(pb); /* sample ssize */
402 ast->cum_len *= FFMAX(1, ast->sample_size);
403// av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
404
405 switch(tag1) {
406 case MKTAG('v', 'i', 'd', 's'):
407 codec_type = CODEC_TYPE_VIDEO;
408
409 ast->sample_size = 0;
410 break;
411 case MKTAG('a', 'u', 'd', 's'):
412 codec_type = CODEC_TYPE_AUDIO;
413 break;
414 case MKTAG('t', 'x', 't', 's'):
415 //FIXME
416 codec_type = CODEC_TYPE_DATA; //CODEC_TYPE_SUB ? FIXME
417 break;
418 case MKTAG('d', 'a', 't', 's'):
419 codec_type = CODEC_TYPE_DATA;
420 break;
421 default:
422 av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
423 goto fail;
424 }
425 ast->frame_offset= ast->cum_len;
426 url_fskip(pb, size - 12 * 4);
427 break;
428 case MKTAG('s', 't', 'r', 'f'):
429 /* stream header */
430 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
431 url_fskip(pb, size);
432 } else {
433 st = s->streams[stream_index];
434 switch(codec_type) {
435 case CODEC_TYPE_VIDEO:
436 if(amv_file_format){
437 st->codec->width=avih_width;
438 st->codec->height=avih_height;
439 st->codec->codec_type = CODEC_TYPE_VIDEO;
440 st->codec->codec_id = CODEC_ID_AMV;
441 url_fskip(pb, size);
442 break;
443 }
444 get_le32(pb); /* size */
445 st->codec->width = get_le32(pb);
446 st->codec->height = get_le32(pb);
447 get_le16(pb); /* panes */
448 st->codec->bits_per_sample= get_le16(pb); /* depth */
449 tag1 = get_le32(pb);
450 get_le32(pb); /* ImageSize */
451 get_le32(pb); /* XPelsPerMeter */
452 get_le32(pb); /* YPelsPerMeter */
453 get_le32(pb); /* ClrUsed */
454 get_le32(pb); /* ClrImportant */
455
456 if (tag1 == MKTAG('D', 'X', 'S', 'B')) {
457 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
458 st->codec->codec_tag = tag1;
459 st->codec->codec_id = CODEC_ID_XSUB;
460 break;
461 }
462
463 if(size > 10*4 && size<(1<<30)){
464 st->codec->extradata_size= size - 10*4;
465 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
466 get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
467 }
468
469 if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
470 get_byte(pb);
471
472 /* Extract palette from extradata if bpp <= 8. */
473 /* This code assumes that extradata contains only palette. */
474 /* This is true for all paletted codecs implemented in FFmpeg. */
475 if (st->codec->extradata_size && (st->codec->bits_per_sample <= 8)) {
476 st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
477#ifdef WORDS_BIGENDIAN
478 for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
479 st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
480#else
481 memcpy(st->codec->palctrl->palette, st->codec->extradata,
482 FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
483#endif
484 st->codec->palctrl->palette_changed = 1;
485 }
486
487#ifdef DEBUG
488 print_tag("video", tag1, 0);
489#endif
490 st->codec->codec_type = CODEC_TYPE_VIDEO;
491 st->codec->codec_tag = tag1;
492 st->codec->codec_id = codec_get_id(codec_bmp_tags, tag1);
493 st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
494// url_fskip(pb, size - 5 * 4);
495 break;
496 case CODEC_TYPE_AUDIO:
497 get_wav_header(pb, st->codec, size);
498 if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
499 av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
500 ast->sample_size= st->codec->block_align;
501 }
502 if (size%2) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
503 url_fskip(pb, 1);
504 /* Force parsing as several audio frames can be in
505 * one packet and timestamps refer to packet start. */
506 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
507 /* ADTS header is in extradata, AAC without header must be
508 * stored as exact frames. Parser not needed and it will
509 * fail. */
510 if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
511 st->need_parsing = AVSTREAM_PARSE_NONE;
512 /* AVI files with Xan DPCM audio (wrongly) declare PCM
513 * audio in the header but have Axan as stream_code_tag. */
514 if (st->codec->stream_codec_tag == ff_get_fourcc("Axan")){
515 st->codec->codec_id = CODEC_ID_XAN_DPCM;
516 st->codec->codec_tag = 0;
517 }
518 if (amv_file_format)
519 st->codec->codec_id = CODEC_ID_ADPCM_IMA_AMV;
520 break;
521 default:
522 st->codec->codec_type = CODEC_TYPE_DATA;
523 st->codec->codec_id= CODEC_ID_NONE;
524 st->codec->codec_tag= 0;
525 url_fskip(pb, size);
526 break;
527 }
528 }
529 break;
530 case MKTAG('i', 'n', 'd', 'x'):
531 i= url_ftell(pb);
532 if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){
533 read_braindead_odml_indx(s, 0);
534 }
535 url_fseek(pb, i+size, SEEK_SET);
536 break;
537 case MKTAG('v', 'p', 'r', 'p'):
538 if(stream_index < (unsigned)s->nb_streams && size > 9*4){
539 AVRational active, active_aspect;
540
541 st = s->streams[stream_index];
542 get_le32(pb);
543 get_le32(pb);
544 get_le32(pb);
545 get_le32(pb);
546 get_le32(pb);
547
548 active_aspect.den= get_le16(pb);
549 active_aspect.num= get_le16(pb);
550 active.num = get_le32(pb);
551 active.den = get_le32(pb);
552 get_le32(pb); //nbFieldsPerFrame
553
554 if(active_aspect.num && active_aspect.den && active.num && active.den){
555 st->codec->sample_aspect_ratio= av_div_q(active_aspect, active);
556//av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
557 }
558 size -= 9*4;
559 }
560 url_fseek(pb, size, SEEK_CUR);
561 break;
562 case MKTAG('I', 'N', 'A', 'M'):
563 avi_read_tag(pb, s->title, sizeof(s->title), size);
564 break;
565 case MKTAG('I', 'A', 'R', 'T'):
566 avi_read_tag(pb, s->author, sizeof(s->author), size);
567 break;
568 case MKTAG('I', 'C', 'O', 'P'):
569 avi_read_tag(pb, s->copyright, sizeof(s->copyright), size);
570 break;
571 case MKTAG('I', 'C', 'M', 'T'):
572 avi_read_tag(pb, s->comment, sizeof(s->comment), size);
573 break;
574 case MKTAG('I', 'G', 'N', 'R'):
575 avi_read_tag(pb, s->genre, sizeof(s->genre), size);
576 break;
577 case MKTAG('I', 'P', 'R', 'D'):
578 avi_read_tag(pb, s->album, sizeof(s->album), size);
579 break;
580 case MKTAG('I', 'P', 'R', 'T'):
581 avi_read_tag(pb, str_track, sizeof(str_track), size);
582 sscanf(str_track, "%d", &s->track);
583 break;
584 default:
585 if(size > 1000000){
586 av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
587 "I will ignore it and try to continue anyway.\n");
588 avi->movi_list = url_ftell(pb) - 4;
589 avi->movi_end = url_fsize(pb);
590 goto end_of_header;
591 }
592 /* skip tag */
593 size += (size & 1);
594 url_fskip(pb, size);
595 break;
596 }
597 }
598 end_of_header:
599 /* check stream number */
600 if (stream_index != s->nb_streams - 1) {
601 fail:
602 return -1;
603 }
604
605 if(!avi->index_loaded && !url_is_streamed(pb))
606 avi_load_index(s);
607 avi->index_loaded = 1;
608 avi->non_interleaved |= guess_ni_flag(s);
609 if(avi->non_interleaved) {
610 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
611 clean_index(s);
612 }
613
614 return 0;
615}
616
617static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
618{
619 AVIContext *avi = s->priv_data;
620 ByteIOContext *pb = s->pb;
621 int n, d[8], size;
622 offset_t i, sync;
623 void* dstr;
624
625 if (ENABLE_DV_DEMUXER && avi->dv_demux) {
626 size = dv_get_packet(avi->dv_demux, pkt);
627 if (size >= 0)
628 return size;
629 }
630
631 if(avi->non_interleaved){
632 int best_stream_index = 0;
633 AVStream *best_st= NULL;
634 AVIStream *best_ast;
635 int64_t best_ts= INT64_MAX;
636 int i;
637
638 for(i=0; i<s->nb_streams; i++){
639 AVStream *st = s->streams[i];
640 AVIStream *ast = st->priv_data;
641 int64_t ts= ast->frame_offset;
642
643 if(ast->sample_size)
644 ts /= ast->sample_size;
645 ts= av_rescale(ts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
646
647// av_log(NULL, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
648 if(ts < best_ts && st->nb_index_entries){
649 best_ts= ts;
650 best_st= st;
651 best_stream_index= i;
652 }
653 }
654 if(!best_st)
655 return -1;
656
657 best_ast = best_st->priv_data;
658 best_ts= av_rescale(best_ts, best_st->time_base.den, AV_TIME_BASE * (int64_t)best_st->time_base.num); //FIXME a little ugly
659 if(best_ast->remaining)
660 i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
661 else
662 i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
663
664// av_log(NULL, AV_LOG_DEBUG, "%d\n", i);
665 if(i>=0){
666 int64_t pos= best_st->index_entries[i].pos;
667 pos += best_ast->packet_size - best_ast->remaining;
668 url_fseek(s->pb, pos + 8, SEEK_SET);
669// av_log(NULL, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
670
671 assert(best_ast->remaining <= best_ast->packet_size);
672
673 avi->stream_index= best_stream_index;
674 if(!best_ast->remaining)
675 best_ast->packet_size=
676 best_ast->remaining= best_st->index_entries[i].size;
677 }
678 }
679
680resync:
681 if(avi->stream_index >= 0){
682 AVStream *st= s->streams[ avi->stream_index ];
683 AVIStream *ast= st->priv_data;
684 int size;
685
686 if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
687 size= INT_MAX;
688 else if(ast->sample_size < 32)
689 size= 64*ast->sample_size;
690 else
691 size= ast->sample_size;
692
693 if(size > ast->remaining)
694 size= ast->remaining;
695 av_get_packet(pb, pkt, size);
696
697 if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
698 ast->has_pal=0;
699 pkt->size += 4*256;
700 pkt->data = av_realloc(pkt->data, pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
701 if(pkt->data)
702 memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
703 }
704
705 if (ENABLE_DV_DEMUXER && avi->dv_demux) {
706 dstr = pkt->destruct;
707 size = dv_produce_packet(avi->dv_demux, pkt,
708 pkt->data, pkt->size);
709 pkt->destruct = dstr;
710 pkt->flags |= PKT_FLAG_KEY;
711 } else {
712 /* XXX: How to handle B-frames in AVI? */
713 pkt->dts = ast->frame_offset;
714// pkt->dts += ast->start;
715 if(ast->sample_size)
716 pkt->dts /= ast->sample_size;
717//av_log(NULL, AV_LOG_DEBUG, "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d base:%d st:%d size:%d\n", pkt->dts, ast->frame_offset, ast->scale, ast->rate, ast->sample_size, AV_TIME_BASE, avi->stream_index, size);
718 pkt->stream_index = avi->stream_index;
719
720 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
721 AVIndexEntry *e;
722 int index;
723 assert(st->index_entries);
724
725 index= av_index_search_timestamp(st, pkt->dts, 0);
726 e= &st->index_entries[index];
727
728 if(index >= 0 && e->timestamp == ast->frame_offset){
729 if (e->flags & AVINDEX_KEYFRAME)
730 pkt->flags |= PKT_FLAG_KEY;
731 }
732 } else {
733 pkt->flags |= PKT_FLAG_KEY;
734 }
735 if(ast->sample_size)
736 ast->frame_offset += pkt->size;
737 else
738 ast->frame_offset++;
739 }
740 ast->remaining -= size;
741 if(!ast->remaining){
742 avi->stream_index= -1;
743 ast->packet_size= 0;
744 }
745
746 return size;
747 }
748
749 memset(d, -1, sizeof(int)*8);
750 for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
751 int j;
752
753 for(j=0; j<7; j++)
754 d[j]= d[j+1];
755 d[7]= get_byte(pb);
756
757 size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
758
759 if( d[2] >= '0' && d[2] <= '9'
760 && d[3] >= '0' && d[3] <= '9'){
761 n= (d[2] - '0') * 10 + (d[3] - '0');
762 }else{
763 n= 100; //invalid stream id
764 }
765//av_log(NULL, AV_LOG_DEBUG, "%X %X %X %X %X %X %X %X %"PRId64" %d %d\n", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
766 if(i + size > avi->fsize || d[0]<0)
767 continue;
768
769 //parse ix##
770 if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
771 //parse JUNK
772 ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
773 ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
774 url_fskip(pb, size);
775//av_log(NULL, AV_LOG_DEBUG, "SKIP\n");
776 goto resync;
777 }
778
779 if( d[0] >= '0' && d[0] <= '9'
780 && d[1] >= '0' && d[1] <= '9'){
781 n= (d[0] - '0') * 10 + (d[1] - '0');
782 }else{
783 n= 100; //invalid stream ID
784 }
785
786 //parse ##dc/##wb
787 if(n < s->nb_streams){
788 AVStream *st;
789 AVIStream *ast;
790 st = s->streams[n];
791 ast = st->priv_data;
792
793 if(s->nb_streams>=2){
794 AVStream *st1 = s->streams[1];
795 AVIStream *ast1= st1->priv_data;
796 //workaround for broken small-file-bug402.avi
797 if( d[2] == 'w' && d[3] == 'b'
798 && n==0
799 && st ->codec->codec_type == CODEC_TYPE_VIDEO
800 && st1->codec->codec_type == CODEC_TYPE_AUDIO
801 && ast->prefix == 'd'*256+'c'
802 && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
803 ){
804 n=1;
805 st = st1;
806 ast = ast1;
807 av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
808 }
809 }
810
811
812 if( (st->discard >= AVDISCARD_DEFAULT && size==0)
813 /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & PKT_FLAG_KEY))*/ //FIXME needs a little reordering
814 || st->discard >= AVDISCARD_ALL){
815 if(ast->sample_size) ast->frame_offset += pkt->size;
816 else ast->frame_offset++;
817 url_fskip(pb, size);
818 goto resync;
819 }
820
821 if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
822 int k = get_byte(pb);
823 int last = (k + get_byte(pb) - 1) & 0xFF;
824
825 get_le16(pb); //flags
826
827 for (; k <= last; k++)
828 ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
829 ast->has_pal= 1;
830 goto resync;
831 } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
832 d[2]*256+d[3] == ast->prefix /*||
833 (d[2] == 'd' && d[3] == 'c') ||
834 (d[2] == 'w' && d[3] == 'b')*/) {
835
836//av_log(NULL, AV_LOG_DEBUG, "OK\n");
837 if(d[2]*256+d[3] == ast->prefix)
838 ast->prefix_count++;
839 else{
840 ast->prefix= d[2]*256+d[3];
841 ast->prefix_count= 0;
842 }
843
844 avi->stream_index= n;
845 ast->packet_size= size + 8;
846 ast->remaining= size;
847
848 {
849 uint64_t pos= url_ftell(pb) - 8;
850 if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
851 av_add_index_entry(st, pos, ast->frame_offset / FFMAX(1, ast->sample_size), size, 0, AVINDEX_KEYFRAME);
852 }
853 }
854 goto resync;
855 }
856 }
857 }
858
859 return -1;
860}
861
862/* XXX: We make the implicit supposition that the positions are sorted
863 for each stream. */
864static int avi_read_idx1(AVFormatContext *s, int size)
865{
866 AVIContext *avi = s->priv_data;
867 ByteIOContext *pb = s->pb;
868 int nb_index_entries, i;
869 AVStream *st;
870 AVIStream *ast;
871 unsigned int index, tag, flags, pos, len;
872 unsigned last_pos= -1;
873
874 nb_index_entries = size / 16;
875 if (nb_index_entries <= 0)
876 return -1;
877
878 /* Read the entries and sort them in each stream component. */
879 for(i = 0; i < nb_index_entries; i++) {
880 tag = get_le32(pb);
881 flags = get_le32(pb);
882 pos = get_le32(pb);
883 len = get_le32(pb);
884#if defined(DEBUG_SEEK)
885 av_log(NULL, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
886 i, tag, flags, pos, len);
887#endif
888 if(i==0 && pos > avi->movi_list)
889 avi->movi_list= 0; //FIXME better check
890 pos += avi->movi_list;
891
892 index = ((tag & 0xff) - '0') * 10;
893 index += ((tag >> 8) & 0xff) - '0';
894 if (index >= s->nb_streams)
895 continue;
896 st = s->streams[index];
897 ast = st->priv_data;
898
899#if defined(DEBUG_SEEK)
900 av_log(NULL, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
901#endif
902 if(last_pos == pos)
903 avi->non_interleaved= 1;
904 else
905 av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
906 if(ast->sample_size)
907 ast->cum_len += len;
908 else
909 ast->cum_len ++;
910 last_pos= pos;
911 }
912 return 0;
913}
914
915static int guess_ni_flag(AVFormatContext *s){
916 int i;
917 int64_t last_start=0;
918 int64_t first_end= INT64_MAX;
919
920 for(i=0; i<s->nb_streams; i++){
921 AVStream *st = s->streams[i];
922 int n= st->nb_index_entries;
923
924 if(n <= 0)
925 continue;
926
927 if(st->index_entries[0].pos > last_start)
928 last_start= st->index_entries[0].pos;
929 if(st->index_entries[n-1].pos < first_end)
930 first_end= st->index_entries[n-1].pos;
931 }
932 return last_start > first_end;
933}
934
935static int avi_load_index(AVFormatContext *s)
936{
937 AVIContext *avi = s->priv_data;
938 ByteIOContext *pb = s->pb;
939 uint32_t tag, size;
940 offset_t pos= url_ftell(pb);
941
942 url_fseek(pb, avi->movi_end, SEEK_SET);
943#ifdef DEBUG_SEEK
944 printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
945#endif
946 for(;;) {
947 if (url_feof(pb))
948 break;
949 tag = get_le32(pb);
950 size = get_le32(pb);
951#ifdef DEBUG_SEEK
952 printf("tag=%c%c%c%c size=0x%x\n",
953 tag & 0xff,
954 (tag >> 8) & 0xff,
955 (tag >> 16) & 0xff,
956 (tag >> 24) & 0xff,
957 size);
958#endif
959 switch(tag) {
960 case MKTAG('i', 'd', 'x', '1'):
961 if (avi_read_idx1(s, size) < 0)
962 goto skip;
963 else
964 goto the_end;
965 break;
966 default:
967 skip:
968 size += (size & 1);
969 url_fskip(pb, size);
970 break;
971 }
972 }
973 the_end:
974 url_fseek(pb, pos, SEEK_SET);
975 return 0;
976}
977
978static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
979{
980 AVIContext *avi = s->priv_data;
981 AVStream *st;
982 int i, index;
983 int64_t pos;
984
985 if (!avi->index_loaded) {
986 /* we only load the index on demand */
987 avi_load_index(s);
988 avi->index_loaded = 1;
989 }
990 assert(stream_index>= 0);
991
992 st = s->streams[stream_index];
993 index= av_index_search_timestamp(st, timestamp, flags);
994 if(index<0)
995 return -1;
996
997 /* find the position */
998 pos = st->index_entries[index].pos;
999 timestamp = st->index_entries[index].timestamp;
1000
1001// av_log(NULL, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
1002
1003 if (ENABLE_DV_DEMUXER && avi->dv_demux) {
1004 /* One and only one real stream for DV in AVI, and it has video */
1005 /* offsets. Calling with other stream indexes should have failed */
1006 /* the av_index_search_timestamp call above. */
1007 assert(stream_index == 0);
1008
1009 /* Feed the DV video stream version of the timestamp to the */
1010 /* DV demux so it can synthesize correct timestamps. */
1011 dv_offset_reset(avi->dv_demux, timestamp);
1012
1013 url_fseek(s->pb, pos, SEEK_SET);
1014 avi->stream_index= -1;
1015 return 0;
1016 }
1017
1018 for(i = 0; i < s->nb_streams; i++) {
1019 AVStream *st2 = s->streams[i];
1020 AVIStream *ast2 = st2->priv_data;
1021
1022 ast2->packet_size=
1023 ast2->remaining= 0;
1024
1025 if (st2->nb_index_entries <= 0)
1026 continue;
1027
1028// assert(st2->codec->block_align);
1029 assert(st2->time_base.den == ast2->rate);
1030 assert(st2->time_base.num == ast2->scale);
1031 index = av_index_search_timestamp(
1032 st2,
1033 av_rescale(timestamp, st2->time_base.den*(int64_t)st->time_base.num, st->time_base.den * (int64_t)st2->time_base.num),
1034 flags | AVSEEK_FLAG_BACKWARD);
1035 if(index<0)
1036 index=0;
1037
1038 if(!avi->non_interleaved){
1039 while(index>0 && st2->index_entries[index].pos > pos)
1040 index--;
1041 while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
1042 index++;
1043 }
1044
1045// av_log(NULL, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
1046 /* extract the current frame number */
1047 ast2->frame_offset = st2->index_entries[index].timestamp;
1048 if(ast2->sample_size)
1049 ast2->frame_offset *=ast2->sample_size;
1050 }
1051
1052 /* do the seek */
1053 url_fseek(s->pb, pos, SEEK_SET);
1054 avi->stream_index= -1;
1055 return 0;
1056}
1057
1058static int avi_read_close(AVFormatContext *s)
1059{
1060 int i;
1061 AVIContext *avi = s->priv_data;
1062
1063 for(i=0;i<s->nb_streams;i++) {
1064 AVStream *st = s->streams[i];
1065 av_free(st->codec->palctrl);
1066 }
1067
1068 if (avi->dv_demux)
1069 av_free(avi->dv_demux);
1070
1071 return 0;
1072}
1073
1074static int avi_probe(AVProbeData *p)
1075{
1076 int i;
1077
1078 /* check file header */
1079 for(i=0; avi_headers[i][0]; i++)
1080 if(!memcmp(p->buf , avi_headers[i] , 4) &&
1081 !memcmp(p->buf+8, avi_headers[i]+4, 4))
1082 return AVPROBE_SCORE_MAX;
1083
1084 return 0;
1085}
1086
1087AVInputFormat avi_demuxer = {
1088 "avi",
1089 NULL_IF_CONFIG_SMALL("AVI format"),
1090 sizeof(AVIContext),
1091 avi_probe,
1092 avi_read_header,
1093 avi_read_packet,
1094 avi_read_close,
1095 avi_read_seek,
1096};
diff --git a/src/plugins/ffmpeg/libavformat/avienc.c b/src/plugins/ffmpeg/libavformat/avienc.c
deleted file mode 100644
index 63ada5d..0000000
--- a/src/plugins/ffmpeg/libavformat/avienc.c
+++ /dev/null
@@ -1,607 +0,0 @@
1/*
2 * AVI muxer
3 * Copyright (c) 2000 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#include "avformat.h"
22#include "avi.h"
23#include "riff.h"
24
25/*
26 * TODO:
27 * - fill all fields if non streamed (nb_frames for example)
28 */
29
30#ifdef CONFIG_AVI_MUXER
31typedef struct AVIIentry {
32 unsigned int flags, pos, len;
33} AVIIentry;
34
35#define AVI_INDEX_CLUSTER_SIZE 16384
36
37typedef struct AVIIndex {
38 offset_t indx_start;
39 int entry;
40 int ents_allocated;
41 AVIIentry** cluster;
42} AVIIndex;
43
44typedef struct {
45 offset_t riff_start, movi_list, odml_list;
46 offset_t frames_hdr_all, frames_hdr_strm[MAX_STREAMS];
47 int audio_strm_length[MAX_STREAMS];
48 int riff_id;
49 int packet_count[MAX_STREAMS];
50
51 AVIIndex indexes[MAX_STREAMS];
52} AVIContext;
53
54static inline AVIIentry* avi_get_ientry(AVIIndex* idx, int ent_id)
55{
56 int cl = ent_id / AVI_INDEX_CLUSTER_SIZE;
57 int id = ent_id % AVI_INDEX_CLUSTER_SIZE;
58 return &idx->cluster[cl][id];
59}
60
61static offset_t avi_start_new_riff(AVIContext *avi, ByteIOContext *pb,
62 const char* riff_tag, const char* list_tag)
63{
64 offset_t loff;
65 int i;
66
67 avi->riff_id++;
68 for (i=0; i<MAX_STREAMS; i++)
69 avi->indexes[i].entry = 0;
70
71 avi->riff_start = start_tag(pb, "RIFF");
72 put_tag(pb, riff_tag);
73 loff = start_tag(pb, "LIST");
74 put_tag(pb, list_tag);
75 return loff;
76}
77
78static char* avi_stream2fourcc(char* tag, int index, enum CodecType type)
79{
80 tag[0] = '0';
81 tag[1] = '0' + index;
82 if (type == CODEC_TYPE_VIDEO) {
83 tag[2] = 'd';
84 tag[3] = 'c';
85 } else {
86 tag[2] = 'w';
87 tag[3] = 'b';
88 }
89 tag[4] = '\0';
90 return tag;
91}
92
93static void avi_write_info_tag(ByteIOContext *pb, const char *tag, const char *str)
94{
95 int len = strlen(str);
96 if (len > 0) {
97 len++;
98 put_tag(pb, tag);
99 put_le32(pb, len);
100 put_strz(pb, str);
101 if (len & 1)
102 put_byte(pb, 0);
103 }
104}
105
106static int avi_write_counters(AVFormatContext* s, int riff_id)
107{
108 ByteIOContext *pb = s->pb;
109 AVIContext *avi = s->priv_data;
110 int n, au_byterate, au_ssize, au_scale, nb_frames = 0;
111 offset_t file_size;
112 AVCodecContext* stream;
113
114 file_size = url_ftell(pb);
115 for(n = 0; n < s->nb_streams; n++) {
116 assert(avi->frames_hdr_strm[n]);
117 stream = s->streams[n]->codec;
118 url_fseek(pb, avi->frames_hdr_strm[n], SEEK_SET);
119 ff_parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);
120 if(au_ssize == 0) {
121 put_le32(pb, avi->packet_count[n]);
122 } else {
123 put_le32(pb, avi->audio_strm_length[n] / au_ssize);
124 }
125 if(stream->codec_type == CODEC_TYPE_VIDEO)
126 nb_frames = FFMAX(nb_frames, avi->packet_count[n]);
127 }
128 if(riff_id == 1) {
129 assert(avi->frames_hdr_all);
130 url_fseek(pb, avi->frames_hdr_all, SEEK_SET);
131 put_le32(pb, nb_frames);
132 }
133 url_fseek(pb, file_size, SEEK_SET);
134
135 return 0;
136}
137
138static int avi_write_header(AVFormatContext *s)
139{
140 AVIContext *avi = s->priv_data;
141 ByteIOContext *pb = s->pb;
142 int bitrate, n, i, nb_frames, au_byterate, au_ssize, au_scale;
143 AVCodecContext *stream, *video_enc;
144 offset_t list1, list2, strh, strf;
145
146 /* header list */
147 avi->riff_id = 0;
148 list1 = avi_start_new_riff(avi, pb, "AVI ", "hdrl");
149
150 /* avi header */
151 put_tag(pb, "avih");
152 put_le32(pb, 14 * 4);
153 bitrate = 0;
154
155 video_enc = NULL;
156 for(n=0;n<s->nb_streams;n++) {
157 stream = s->streams[n]->codec;
158 bitrate += stream->bit_rate;
159 if (stream->codec_type == CODEC_TYPE_VIDEO)
160 video_enc = stream;
161 }
162
163 nb_frames = 0;
164
165 if(video_enc){
166 put_le32(pb, (uint32_t)(INT64_C(1000000) * video_enc->time_base.num / video_enc->time_base.den));
167 } else {
168 put_le32(pb, 0);
169 }
170 put_le32(pb, bitrate / 8); /* XXX: not quite exact */
171 put_le32(pb, 0); /* padding */
172 if (url_is_streamed(pb))
173 put_le32(pb, AVIF_TRUSTCKTYPE | AVIF_ISINTERLEAVED); /* flags */
174 else
175 put_le32(pb, AVIF_TRUSTCKTYPE | AVIF_HASINDEX | AVIF_ISINTERLEAVED); /* flags */
176 avi->frames_hdr_all = url_ftell(pb); /* remember this offset to fill later */
177 put_le32(pb, nb_frames); /* nb frames, filled later */
178 put_le32(pb, 0); /* initial frame */
179 put_le32(pb, s->nb_streams); /* nb streams */
180 put_le32(pb, 1024 * 1024); /* suggested buffer size */
181 if(video_enc){
182 put_le32(pb, video_enc->width);
183 put_le32(pb, video_enc->height);
184 } else {
185 put_le32(pb, 0);
186 put_le32(pb, 0);
187 }
188 put_le32(pb, 0); /* reserved */
189 put_le32(pb, 0); /* reserved */
190 put_le32(pb, 0); /* reserved */
191 put_le32(pb, 0); /* reserved */
192
193 /* stream list */
194 for(i=0;i<n;i++) {
195 list2 = start_tag(pb, "LIST");
196 put_tag(pb, "strl");
197
198 stream = s->streams[i]->codec;
199
200 /* stream generic header */
201 strh = start_tag(pb, "strh");
202 switch(stream->codec_type) {
203 case CODEC_TYPE_VIDEO: put_tag(pb, "vids"); break;
204 case CODEC_TYPE_AUDIO: put_tag(pb, "auds"); break;
205// case CODEC_TYPE_TEXT : put_tag(pb, "txts"); break;
206 case CODEC_TYPE_DATA : put_tag(pb, "dats"); break;
207 }
208 if(stream->codec_type == CODEC_TYPE_VIDEO)
209 put_le32(pb, stream->codec_tag);
210 else
211 put_le32(pb, 1);
212 put_le32(pb, 0); /* flags */
213 put_le16(pb, 0); /* priority */
214 put_le16(pb, 0); /* language */
215 put_le32(pb, 0); /* initial frame */
216
217 ff_parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);
218
219 put_le32(pb, au_scale); /* scale */
220 put_le32(pb, au_byterate); /* rate */
221 av_set_pts_info(s->streams[i], 64, au_scale, au_byterate);
222
223 put_le32(pb, 0); /* start */
224 avi->frames_hdr_strm[i] = url_ftell(pb); /* remember this offset to fill later */
225 if (url_is_streamed(pb))
226 put_le32(pb, AVI_MAX_RIFF_SIZE); /* FIXME: this may be broken, but who cares */
227 else
228 put_le32(pb, 0); /* length, XXX: filled later */
229
230 /* suggested buffer size */ //FIXME set at the end to largest chunk
231 if(stream->codec_type == CODEC_TYPE_VIDEO)
232 put_le32(pb, 1024 * 1024);
233 else if(stream->codec_type == CODEC_TYPE_AUDIO)
234 put_le32(pb, 12 * 1024);
235 else
236 put_le32(pb, 0);
237 put_le32(pb, -1); /* quality */
238 put_le32(pb, au_ssize); /* sample size */
239 put_le32(pb, 0);
240 put_le16(pb, stream->width);
241 put_le16(pb, stream->height);
242 end_tag(pb, strh);
243
244 if(stream->codec_type != CODEC_TYPE_DATA){
245 strf = start_tag(pb, "strf");
246 switch(stream->codec_type) {
247 case CODEC_TYPE_VIDEO:
248 put_bmp_header(pb, stream, codec_bmp_tags, 0);
249 break;
250 case CODEC_TYPE_AUDIO:
251 if (put_wav_header(pb, stream) < 0) {
252 av_free(avi);
253 return -1;
254 }
255 break;
256 default:
257 return -1;
258 }
259 end_tag(pb, strf);
260 }
261
262 if (!url_is_streamed(pb)) {
263 unsigned char tag[5];
264 int j;
265
266 /* Starting to lay out AVI OpenDML master index.
267 * We want to make it JUNK entry for now, since we'd
268 * like to get away without making AVI an OpenDML one
269 * for compatibility reasons.
270 */
271 avi->indexes[i].entry = avi->indexes[i].ents_allocated = 0;
272 avi->indexes[i].indx_start = start_tag(pb, "JUNK");
273 put_le16(pb, 4); /* wLongsPerEntry */
274 put_byte(pb, 0); /* bIndexSubType (0 == frame index) */
275 put_byte(pb, 0); /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */
276 put_le32(pb, 0); /* nEntriesInUse (will fill out later on) */
277 put_tag(pb, avi_stream2fourcc(&tag[0], i, stream->codec_type));
278 /* dwChunkId */
279 put_le64(pb, 0); /* dwReserved[3]
280 put_le32(pb, 0); Must be 0. */
281 for (j=0; j < AVI_MASTER_INDEX_SIZE * 2; j++)
282 put_le64(pb, 0);
283 end_tag(pb, avi->indexes[i].indx_start);
284 }
285
286 if( stream->codec_type == CODEC_TYPE_VIDEO
287 && stream->sample_aspect_ratio.num>0
288 && stream->sample_aspect_ratio.den>0){
289 int vprp= start_tag(pb, "vprp");
290 AVRational dar = av_mul_q(stream->sample_aspect_ratio,
291 (AVRational){stream->width, stream->height});
292 int num, den;
293 av_reduce(&num, &den, dar.num, dar.den, 0xFFFF);
294
295 put_le32(pb, 0); //video format = unknown
296 put_le32(pb, 0); //video standard= unknown
297 put_le32(pb, lrintf(1.0/av_q2d(stream->time_base)));
298 put_le32(pb, stream->width );
299 put_le32(pb, stream->height);
300 put_le16(pb, den);
301 put_le16(pb, num);
302 put_le32(pb, stream->width );
303 put_le32(pb, stream->height);
304 put_le32(pb, 1); //progressive FIXME
305
306 put_le32(pb, stream->height);
307 put_le32(pb, stream->width );
308 put_le32(pb, stream->height);
309 put_le32(pb, stream->width );
310 put_le32(pb, 0);
311 put_le32(pb, 0);
312
313 put_le32(pb, 0);
314 put_le32(pb, 0);
315 end_tag(pb, vprp);
316 }
317
318 end_tag(pb, list2);
319 }
320
321 if (!url_is_streamed(pb)) {
322 /* AVI could become an OpenDML one, if it grows beyond 2Gb range */
323 avi->odml_list = start_tag(pb, "JUNK");
324 put_tag(pb, "odml");
325 put_tag(pb, "dmlh");
326 put_le32(pb, 248);
327 for (i = 0; i < 248; i+= 4)
328 put_le32(pb, 0);
329 end_tag(pb, avi->odml_list);
330 }
331
332 end_tag(pb, list1);
333
334 list2 = start_tag(pb, "LIST");
335 put_tag(pb, "INFO");
336 avi_write_info_tag(pb, "INAM", s->title);
337 avi_write_info_tag(pb, "IART", s->author);
338 avi_write_info_tag(pb, "ICOP", s->copyright);
339 avi_write_info_tag(pb, "ICMT", s->comment);
340 avi_write_info_tag(pb, "IPRD", s->album);
341 avi_write_info_tag(pb, "IGNR", s->genre);
342 if (s->track) {
343 char str_track[4];
344 snprintf(str_track, 4, "%d", s->track);
345 avi_write_info_tag(pb, "IPRT", str_track);
346 }
347 if(!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT))
348 avi_write_info_tag(pb, "ISFT", LIBAVFORMAT_IDENT);
349 end_tag(pb, list2);
350
351 /* some padding for easier tag editing */
352 list2 = start_tag(pb, "JUNK");
353 for (i = 0; i < 1016; i += 4)
354 put_le32(pb, 0);
355 end_tag(pb, list2);
356
357 avi->movi_list = start_tag(pb, "LIST");
358 put_tag(pb, "movi");
359
360 put_flush_packet(pb);
361
362 return 0;
363}
364
365static int avi_write_ix(AVFormatContext *s)
366{
367 ByteIOContext *pb = s->pb;
368 AVIContext *avi = s->priv_data;
369 char tag[5];
370 char ix_tag[] = "ix00";
371 int i, j;
372
373 assert(!url_is_streamed(pb));
374
375 if (avi->riff_id > AVI_MASTER_INDEX_SIZE)
376 return -1;
377
378 for (i=0;i<s->nb_streams;i++) {
379 offset_t ix, pos;
380
381 avi_stream2fourcc(&tag[0], i, s->streams[i]->codec->codec_type);
382 ix_tag[3] = '0' + i;
383
384 /* Writing AVI OpenDML leaf index chunk */
385 ix = url_ftell(pb);
386 put_tag(pb, &ix_tag[0]); /* ix?? */
387 put_le32(pb, avi->indexes[i].entry * 8 + 24);
388 /* chunk size */
389 put_le16(pb, 2); /* wLongsPerEntry */
390 put_byte(pb, 0); /* bIndexSubType (0 == frame index) */
391 put_byte(pb, 1); /* bIndexType (1 == AVI_INDEX_OF_CHUNKS) */
392 put_le32(pb, avi->indexes[i].entry);
393 /* nEntriesInUse */
394 put_tag(pb, &tag[0]); /* dwChunkId */
395 put_le64(pb, avi->movi_list);/* qwBaseOffset */
396 put_le32(pb, 0); /* dwReserved_3 (must be 0) */
397
398 for (j=0; j<avi->indexes[i].entry; j++) {
399 AVIIentry* ie = avi_get_ientry(&avi->indexes[i], j);
400 put_le32(pb, ie->pos + 8);
401 put_le32(pb, ((uint32_t)ie->len & ~0x80000000) |
402 (ie->flags & 0x10 ? 0 : 0x80000000));
403 }
404 put_flush_packet(pb);
405 pos = url_ftell(pb);
406
407 /* Updating one entry in the AVI OpenDML master index */
408 url_fseek(pb, avi->indexes[i].indx_start - 8, SEEK_SET);
409 put_tag(pb, "indx"); /* enabling this entry */
410 url_fskip(pb, 8);
411 put_le32(pb, avi->riff_id); /* nEntriesInUse */
412 url_fskip(pb, 16*avi->riff_id);
413 put_le64(pb, ix); /* qwOffset */
414 put_le32(pb, pos - ix); /* dwSize */
415 put_le32(pb, avi->indexes[i].entry); /* dwDuration */
416
417 url_fseek(pb, pos, SEEK_SET);
418 }
419 return 0;
420}
421
422static int avi_write_idx1(AVFormatContext *s)
423{
424 ByteIOContext *pb = s->pb;
425 AVIContext *avi = s->priv_data;
426 offset_t idx_chunk;
427 int i;
428 char tag[5];
429
430 if (!url_is_streamed(pb)) {
431 AVIIentry* ie = 0, *tie;
432 int entry[MAX_STREAMS];
433 int empty, stream_id = -1;
434
435 idx_chunk = start_tag(pb, "idx1");
436 memset(&entry[0], 0, sizeof(entry));
437 do {
438 empty = 1;
439 for (i=0; i<s->nb_streams; i++) {
440 if (avi->indexes[i].entry <= entry[i])
441 continue;
442
443 tie = avi_get_ientry(&avi->indexes[i], entry[i]);
444 if (empty || tie->pos < ie->pos) {
445 ie = tie;
446 stream_id = i;
447 }
448 empty = 0;
449 }
450 if (!empty) {
451 avi_stream2fourcc(&tag[0], stream_id,
452 s->streams[stream_id]->codec->codec_type);
453 put_tag(pb, &tag[0]);
454 put_le32(pb, ie->flags);
455 put_le32(pb, ie->pos);
456 put_le32(pb, ie->len);
457 entry[stream_id]++;
458 }
459 } while (!empty);
460 end_tag(pb, idx_chunk);
461
462 avi_write_counters(s, avi->riff_id);
463 }
464 return 0;
465}
466
467static int avi_write_packet(AVFormatContext *s, AVPacket *pkt)
468{
469 AVIContext *avi = s->priv_data;
470 ByteIOContext *pb = s->pb;
471 unsigned char tag[5];
472 unsigned int flags=0;
473 const int stream_index= pkt->stream_index;
474 AVCodecContext *enc= s->streams[stream_index]->codec;
475 int size= pkt->size;
476
477// av_log(s, AV_LOG_DEBUG, "%"PRId64" %d %d\n", pkt->dts, avi->packet_count[stream_index], stream_index);
478 while(enc->block_align==0 && pkt->dts != AV_NOPTS_VALUE && pkt->dts > avi->packet_count[stream_index]){
479 AVPacket empty_packet;
480
481 av_init_packet(&empty_packet);
482 empty_packet.size= 0;
483 empty_packet.data= NULL;
484 empty_packet.stream_index= stream_index;
485 avi_write_packet(s, &empty_packet);
486// av_log(s, AV_LOG_DEBUG, "dup %"PRId64" %d\n", pkt->dts, avi->packet_count[stream_index]);
487 }
488 avi->packet_count[stream_index]++;
489
490 // Make sure to put an OpenDML chunk when the file size exceeds the limits
491 if (!url_is_streamed(pb) &&
492 (url_ftell(pb) - avi->riff_start > AVI_MAX_RIFF_SIZE)) {
493
494 avi_write_ix(s);
495 end_tag(pb, avi->movi_list);
496
497 if (avi->riff_id == 1)
498 avi_write_idx1(s);
499
500 end_tag(pb, avi->riff_start);
501 avi->movi_list = avi_start_new_riff(avi, pb, "AVIX", "movi");
502 }
503
504 avi_stream2fourcc(&tag[0], stream_index, enc->codec_type);
505 if(pkt->flags&PKT_FLAG_KEY)
506 flags = 0x10;
507 if (enc->codec_type == CODEC_TYPE_AUDIO) {
508 avi->audio_strm_length[stream_index] += size;
509 }
510
511 if (!url_is_streamed(s->pb)) {
512 AVIIndex* idx = &avi->indexes[stream_index];
513 int cl = idx->entry / AVI_INDEX_CLUSTER_SIZE;
514 int id = idx->entry % AVI_INDEX_CLUSTER_SIZE;
515 if (idx->ents_allocated <= idx->entry) {
516 idx->cluster = av_realloc(idx->cluster, (cl+1)*sizeof(void*));
517 if (!idx->cluster)
518 return -1;
519 idx->cluster[cl] = av_malloc(AVI_INDEX_CLUSTER_SIZE*sizeof(AVIIentry));
520 if (!idx->cluster[cl])
521 return -1;
522 idx->ents_allocated += AVI_INDEX_CLUSTER_SIZE;
523 }
524
525 idx->cluster[cl][id].flags = flags;
526 idx->cluster[cl][id].pos = url_ftell(pb) - avi->movi_list;
527 idx->cluster[cl][id].len = size;
528 idx->entry++;
529 }
530
531 put_buffer(pb, tag, 4);
532 put_le32(pb, size);
533 put_buffer(pb, pkt->data, size);
534 if (size & 1)
535 put_byte(pb, 0);
536
537 put_flush_packet(pb);
538 return 0;
539}
540
541static int avi_write_trailer(AVFormatContext *s)
542{
543 AVIContext *avi = s->priv_data;
544 ByteIOContext *pb = s->pb;
545 int res = 0;
546 int i, j, n, nb_frames;
547 offset_t file_size;
548
549 if (!url_is_streamed(pb)){
550 if (avi->riff_id == 1) {
551 end_tag(pb, avi->movi_list);
552 res = avi_write_idx1(s);
553 end_tag(pb, avi->riff_start);
554 } else {
555 avi_write_ix(s);
556 end_tag(pb, avi->movi_list);
557 end_tag(pb, avi->riff_start);
558
559 file_size = url_ftell(pb);
560 url_fseek(pb, avi->odml_list - 8, SEEK_SET);
561 put_tag(pb, "LIST"); /* Making this AVI OpenDML one */
562 url_fskip(pb, 16);
563
564 for (n=nb_frames=0;n<s->nb_streams;n++) {
565 AVCodecContext *stream = s->streams[n]->codec;
566 if (stream->codec_type == CODEC_TYPE_VIDEO) {
567 if (nb_frames < avi->packet_count[n])
568 nb_frames = avi->packet_count[n];
569 } else {
570 if (stream->codec_id == CODEC_ID_MP2 || stream->codec_id == CODEC_ID_MP3) {
571 nb_frames += avi->packet_count[n];
572 }
573 }
574 }
575 put_le32(pb, nb_frames);
576 url_fseek(pb, file_size, SEEK_SET);
577
578 avi_write_counters(s, avi->riff_id);
579 }
580 }
581 put_flush_packet(pb);
582
583 for (i=0; i<MAX_STREAMS; i++) {
584 for (j=0; j<avi->indexes[i].ents_allocated/AVI_INDEX_CLUSTER_SIZE; j++)
585 av_free(avi->indexes[i].cluster[j]);
586 av_free(avi->indexes[i].cluster);
587 avi->indexes[i].cluster = NULL;
588 avi->indexes[i].ents_allocated = avi->indexes[i].entry = 0;
589 }
590
591 return res;
592}
593
594AVOutputFormat avi_muxer = {
595 "avi",
596 NULL_IF_CONFIG_SMALL("AVI format"),
597 "video/x-msvideo",
598 "avi",
599 sizeof(AVIContext),
600 CODEC_ID_MP2,
601 CODEC_ID_MPEG4,
602 avi_write_header,
603 avi_write_packet,
604 avi_write_trailer,
605 .codec_tag= (const AVCodecTag*[]){codec_bmp_tags, codec_wav_tags, 0},
606};
607#endif //CONFIG_AVI_MUXER
diff --git a/src/plugins/ffmpeg/libavformat/avio.c b/src/plugins/ffmpeg/libavformat/avio.c
deleted file mode 100644
index 743cc88..0000000
--- a/src/plugins/ffmpeg/libavformat/avio.c
+++ /dev/null
@@ -1,232 +0,0 @@
1/*
2 * Unbuffered io for ffmpeg system
3 * Copyright (c) 2001 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/avstring.h"
23#include "libavcodec/opt.h"
24#include "avformat.h"
25
26#if LIBAVFORMAT_VERSION_MAJOR >= 53
27/** @name Logging context. */
28/*@{*/
29static const char *urlcontext_to_name(void *ptr)
30{
31 URLContext *h = (URLContext *)ptr;
32 if(h->prot) return h->prot->name;
33 else return "NULL";
34}
35static const AVOption options[] = {{NULL}};
36static const AVClass urlcontext_class =
37 { "URLContext", urlcontext_to_name, options };
38/*@}*/
39#endif
40
41static int default_interrupt_cb(void);
42
43URLProtocol *first_protocol = NULL;
44URLInterruptCB *url_interrupt_cb = default_interrupt_cb;
45
46URLProtocol *av_protocol_next(URLProtocol *p)
47{
48 if(p) return p->next;
49 else return first_protocol;
50}
51
52int register_protocol(URLProtocol *protocol)
53{
54 URLProtocol **p;
55 p = &first_protocol;
56 while (*p != NULL) p = &(*p)->next;
57 *p = protocol;
58 protocol->next = NULL;
59 return 0;
60}
61
62int url_open(URLContext **puc, const char *filename, int flags)
63{
64 URLContext *uc;
65 URLProtocol *up;
66 const char *p;
67 char proto_str[128], *q;
68 int err;
69
70 p = filename;
71 q = proto_str;
72 while (*p != '\0' && *p != ':') {
73 /* protocols can only contain alphabetic chars */
74 if (!isalpha(*p))
75 goto file_proto;
76 if ((q - proto_str) < sizeof(proto_str) - 1)
77 *q++ = *p;
78 p++;
79 }
80 /* if the protocol has length 1, we consider it is a dos drive */
81 if (*p == '\0' || (q - proto_str) <= 1) {
82 file_proto:
83 strcpy(proto_str, "file");
84 } else {
85 *q = '\0';
86 }
87
88 up = first_protocol;
89 while (up != NULL) {
90 if (!strcmp(proto_str, up->name))
91 goto found;
92 up = up->next;
93 }
94 err = AVERROR(ENOENT);
95 goto fail;
96 found:
97 uc = av_malloc(sizeof(URLContext) + strlen(filename) + 1);
98 if (!uc) {
99 err = AVERROR(ENOMEM);
100 goto fail;
101 }
102#if LIBAVFORMAT_VERSION_MAJOR >= 53
103 uc->av_class = &urlcontext_class;
104#endif
105 uc->filename = (char *) &uc[1];
106 strcpy(uc->filename, filename);
107 uc->prot = up;
108 uc->flags = flags;
109 uc->is_streamed = 0; /* default = not streamed */
110 uc->max_packet_size = 0; /* default: stream file */
111 err = up->url_open(uc, filename, flags);
112 if (err < 0) {
113 av_free(uc);
114 *puc = NULL;
115 return err;
116 }
117
118 //We must be carefull here as url_seek() could be slow, for example for http
119 if( (flags & (URL_WRONLY | URL_RDWR))
120 || !strcmp(proto_str, "file"))
121 if(!uc->is_streamed && url_seek(uc, 0, SEEK_SET) < 0)
122 uc->is_streamed= 1;
123 *puc = uc;
124 return 0;
125 fail:
126 *puc = NULL;
127 return err;
128}
129
130int url_read(URLContext *h, unsigned char *buf, int size)
131{
132 int ret;
133 if (h->flags & URL_WRONLY)
134 return AVERROR(EIO);
135 ret = h->prot->url_read(h, buf, size);
136 return ret;
137}
138
139int url_write(URLContext *h, unsigned char *buf, int size)
140{
141 int ret;
142 if (!(h->flags & (URL_WRONLY | URL_RDWR)))
143 return AVERROR(EIO);
144 /* avoid sending too big packets */
145 if (h->max_packet_size && size > h->max_packet_size)
146 return AVERROR(EIO);
147 ret = h->prot->url_write(h, buf, size);
148 return ret;
149}
150
151offset_t url_seek(URLContext *h, offset_t pos, int whence)
152{
153 offset_t ret;
154
155 if (!h->prot->url_seek)
156 return AVERROR(EPIPE);
157 ret = h->prot->url_seek(h, pos, whence);
158 return ret;
159}
160
161int url_close(URLContext *h)
162{
163 int ret = 0;
164 if (!h) return 0; /* can happen when url_open fails */
165
166 if (h->prot->url_close)
167 ret = h->prot->url_close(h);
168 av_free(h);
169 return ret;
170}
171
172int url_exist(const char *filename)
173{
174 URLContext *h;
175 if (url_open(&h, filename, URL_RDONLY) < 0)
176 return 0;
177 url_close(h);
178 return 1;
179}
180
181offset_t url_filesize(URLContext *h)
182{
183 offset_t pos, size;
184
185 size= url_seek(h, 0, AVSEEK_SIZE);
186 if(size<0){
187 pos = url_seek(h, 0, SEEK_CUR);
188 if ((size = url_seek(h, -1, SEEK_END)) < 0)
189 return size;
190 size++;
191 url_seek(h, pos, SEEK_SET);
192 }
193 return size;
194}
195
196int url_get_max_packet_size(URLContext *h)
197{
198 return h->max_packet_size;
199}
200
201void url_get_filename(URLContext *h, char *buf, int buf_size)
202{
203 av_strlcpy(buf, h->filename, buf_size);
204}
205
206
207static int default_interrupt_cb(void)
208{
209 return 0;
210}
211
212void url_set_interrupt_cb(URLInterruptCB *interrupt_cb)
213{
214 if (!interrupt_cb)
215 interrupt_cb = default_interrupt_cb;
216 url_interrupt_cb = interrupt_cb;
217}
218
219int av_url_read_pause(URLContext *h, int pause)
220{
221 if (!h->prot->url_read_pause)
222 return AVERROR(ENOSYS);
223 return h->prot->url_read_pause(h, pause);
224}
225
226offset_t av_url_read_seek(URLContext *h,
227 int stream_index, int64_t timestamp, int flags)
228{
229 if (!h->prot->url_read_seek)
230 return AVERROR(ENOSYS);
231 return h->prot->url_read_seek(h, stream_index, timestamp, flags);
232}
diff --git a/src/plugins/ffmpeg/libavformat/avio.h b/src/plugins/ffmpeg/libavformat/avio.h
deleted file mode 100644
index 2d2e269..0000000
--- a/src/plugins/ffmpeg/libavformat/avio.h
+++ /dev/null
@@ -1,369 +0,0 @@
1/*
2 * unbuffered io for ffmpeg system
3 * copyright (c) 2001 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#ifndef FFMPEG_AVIO_H
22#define FFMPEG_AVIO_H
23
24#include <stdint.h>
25
26/* output byte stream handling */
27
28typedef int64_t offset_t;
29
30/* unbuffered I/O */
31
32/**
33 * URL Context.
34 * New fields can be added to the end with minor version bumps.
35 * Removal, reordering and changes to existing fields require a major
36 * version bump.
37 * sizeof(URLContext) must not be used outside libav*.
38 */
39struct URLContext {
40#if LIBAVFORMAT_VERSION_MAJOR >= 53
41 const AVClass *av_class; ///< information for av_log(). Set by url_open().
42#endif
43 struct URLProtocol *prot;
44 int flags;
45 int is_streamed; /**< true if streamed (no seek possible), default = false */
46 int max_packet_size; /**< if non zero, the stream is packetized with this max packet size */
47 void *priv_data;
48 char *filename; /**< specified filename */
49};
50
51typedef struct URLContext URLContext;
52
53typedef struct URLPollEntry {
54 URLContext *handle;
55 int events;
56 int revents;
57} URLPollEntry;
58
59#define URL_RDONLY 0
60#define URL_WRONLY 1
61#define URL_RDWR 2
62
63typedef int URLInterruptCB(void);
64
65int url_open(URLContext **h, const char *filename, int flags);
66int url_read(URLContext *h, unsigned char *buf, int size);
67int url_write(URLContext *h, unsigned char *buf, int size);
68offset_t url_seek(URLContext *h, offset_t pos, int whence);
69int url_close(URLContext *h);
70int url_exist(const char *filename);
71offset_t url_filesize(URLContext *h);
72
73/**
74 * Return the maximum packet size associated to packetized file
75 * handle. If the file is not packetized (stream like HTTP or file on
76 * disk), then 0 is returned.
77 *
78 * @param h file handle
79 * @return maximum packet size in bytes
80 */
81int url_get_max_packet_size(URLContext *h);
82void url_get_filename(URLContext *h, char *buf, int buf_size);
83
84/**
85 * The callback is called in blocking functions to test regulary if
86 * asynchronous interruption is needed. AVERROR(EINTR) is returned
87 * in this case by the interrupted function. 'NULL' means no interrupt
88 * callback is given.
89 */
90void url_set_interrupt_cb(URLInterruptCB *interrupt_cb);
91
92/* not implemented */
93int url_poll(URLPollEntry *poll_table, int n, int timeout);
94
95/**
96 * Pause and resume playing - only meaningful if using a network streaming
97 * protocol (e.g. MMS).
98 * @param pause 1 for pause, 0 for resume
99 */
100int av_url_read_pause(URLContext *h, int pause);
101
102/**
103 * Seek to a given timestamp relative to some component stream.
104 * Only meaningful if using a network streaming protocol (e.g. MMS.).
105 * @param stream_index The stream index that the timestamp is relative to.
106 * If stream_index is (-1) the timestamp should be in AV_TIME_BASE
107 * units from the beginning of the presentation.
108 * If a stream_index >= 0 is used and the protocol does not support
109 * seeking based on component streams, the call will fail with ENOTSUP.
110 * @param timestamp timestamp in AVStream.time_base units
111 * or if there is no stream specified then in AV_TIME_BASE units.
112 * @param flags Optional combination of AVSEEK_FLAG_BACKWARD, AVSEEK_FLAG_BYTE
113 * and AVSEEK_FLAG_ANY. The protocol may silently ignore
114 * AVSEEK_FLAG_BACKWARD and AVSEEK_FLAG_ANY, but AVSEEK_FLAG_BYTE will
115 * fail with ENOTSUP if used and not supported.
116 * @return >= 0 on success
117 * @see AVInputFormat::read_seek
118 */
119offset_t av_url_read_seek(URLContext *h,
120 int stream_index, int64_t timestamp, int flags);
121
122/**
123 * Passing this as the "whence" parameter to a seek function causes it to
124 * return the filesize without seeking anywhere. Supporting this is optional.
125 * If it is not supported then the seek function will return <0.
126 */
127#define AVSEEK_SIZE 0x10000
128
129typedef struct URLProtocol {
130 const char *name;
131 int (*url_open)(URLContext *h, const char *filename, int flags);
132 int (*url_read)(URLContext *h, unsigned char *buf, int size);
133 int (*url_write)(URLContext *h, unsigned char *buf, int size);
134 offset_t (*url_seek)(URLContext *h, offset_t pos, int whence);
135 int (*url_close)(URLContext *h);
136 struct URLProtocol *next;
137 int (*url_read_pause)(URLContext *h, int pause);
138 offset_t (*url_read_seek)(URLContext *h,
139 int stream_index, int64_t timestamp, int flags);
140} URLProtocol;
141
142extern URLProtocol *first_protocol;
143extern URLInterruptCB *url_interrupt_cb;
144
145URLProtocol *av_protocol_next(URLProtocol *p);
146
147int register_protocol(URLProtocol *protocol);
148
149/**
150 * Bytestream IO Context.
151 * New fields can be added to the end with minor version bumps.
152 * Removal, reordering and changes to existing fields require a major
153 * version bump.
154 * sizeof(ByteIOContext) must not be used outside libav*.
155 */
156typedef struct {
157 unsigned char *buffer;
158 int buffer_size;
159 unsigned char *buf_ptr, *buf_end;
160 void *opaque;
161 int (*read_packet)(void *opaque, uint8_t *buf, int buf_size);
162 int (*write_packet)(void *opaque, uint8_t *buf, int buf_size);
163 offset_t (*seek)(void *opaque, offset_t offset, int whence);
164 offset_t pos; /**< position in the file of the current buffer */
165 int must_flush; /**< true if the next seek should flush */
166 int eof_reached; /**< true if eof reached */
167 int write_flag; /**< true if open for writing */
168 int is_streamed;
169 int max_packet_size;
170 unsigned long checksum;
171 unsigned char *checksum_ptr;
172 unsigned long (*update_checksum)(unsigned long checksum, const uint8_t *buf, unsigned int size);
173 int error; ///< contains the error code or 0 if no error happened
174 int (*read_pause)(void *opaque, int pause);
175 offset_t (*read_seek)(void *opaque,
176 int stream_index, int64_t timestamp, int flags);
177} ByteIOContext;
178
179int init_put_byte(ByteIOContext *s,
180 unsigned char *buffer,
181 int buffer_size,
182 int write_flag,
183 void *opaque,
184 int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
185 int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
186 offset_t (*seek)(void *opaque, offset_t offset, int whence));
187ByteIOContext *av_alloc_put_byte(
188 unsigned char *buffer,
189 int buffer_size,
190 int write_flag,
191 void *opaque,
192 int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
193 int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
194 offset_t (*seek)(void *opaque, offset_t offset, int whence));
195
196void put_byte(ByteIOContext *s, int b);
197void put_buffer(ByteIOContext *s, const unsigned char *buf, int size);
198void put_le64(ByteIOContext *s, uint64_t val);
199void put_be64(ByteIOContext *s, uint64_t val);
200void put_le32(ByteIOContext *s, unsigned int val);
201void put_be32(ByteIOContext *s, unsigned int val);
202void put_le24(ByteIOContext *s, unsigned int val);
203void put_be24(ByteIOContext *s, unsigned int val);
204void put_le16(ByteIOContext *s, unsigned int val);
205void put_be16(ByteIOContext *s, unsigned int val);
206void put_tag(ByteIOContext *s, const char *tag);
207
208void put_strz(ByteIOContext *s, const char *buf);
209
210/**
211 * fseek() equivalent for ByteIOContext.
212 * @return new position or AVERROR.
213 */
214offset_t url_fseek(ByteIOContext *s, offset_t offset, int whence);
215
216/**
217 * Skip given number of bytes forward.
218 * @param offset number of bytes
219 */
220void url_fskip(ByteIOContext *s, offset_t offset);
221
222/**
223 * ftell() equivalent for ByteIOContext.
224 * @return position or AVERROR.
225 */
226offset_t url_ftell(ByteIOContext *s);
227
228/**
229 * Gets the filesize.
230 * @return filesize or AVERROR
231 */
232offset_t url_fsize(ByteIOContext *s);
233
234/**
235 * feof() equivalent for ByteIOContext.
236 * @return non zero if and only if end of file
237 */
238int url_feof(ByteIOContext *s);
239
240int url_ferror(ByteIOContext *s);
241
242int av_url_read_fpause(ByteIOContext *h, int pause);
243offset_t av_url_read_fseek(ByteIOContext *h,
244 int stream_index, int64_t timestamp, int flags);
245
246#define URL_EOF (-1)
247/** @note return URL_EOF (-1) if EOF */
248int url_fgetc(ByteIOContext *s);
249
250/** @warning currently size is limited */
251#ifdef __GNUC__
252int url_fprintf(ByteIOContext *s, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 2, 3)));
253#else
254int url_fprintf(ByteIOContext *s, const char *fmt, ...);
255#endif
256
257/** @note unlike fgets, the EOL character is not returned and a whole
258 line is parsed. return NULL if first char read was EOF */
259char *url_fgets(ByteIOContext *s, char *buf, int buf_size);
260
261void put_flush_packet(ByteIOContext *s);
262
263
264/**
265 * Reads size bytes from ByteIOContext into buf.
266 * @returns number of bytes read or AVERROR
267 */
268int get_buffer(ByteIOContext *s, unsigned char *buf, int size);
269
270/**
271 * Reads size bytes from ByteIOContext into buf.
272 * This reads at most 1 packet. If that is not enough fewer bytes will be
273 * returned.
274 * @returns number of bytes read or AVERROR
275 */
276int get_partial_buffer(ByteIOContext *s, unsigned char *buf, int size);
277
278/** @note return 0 if EOF, so you cannot use it if EOF handling is
279 necessary */
280int get_byte(ByteIOContext *s);
281unsigned int get_le24(ByteIOContext *s);
282unsigned int get_le32(ByteIOContext *s);
283uint64_t get_le64(ByteIOContext *s);
284unsigned int get_le16(ByteIOContext *s);
285
286char *get_strz(ByteIOContext *s, char *buf, int maxlen);
287unsigned int get_be16(ByteIOContext *s);
288unsigned int get_be24(ByteIOContext *s);
289unsigned int get_be32(ByteIOContext *s);
290uint64_t get_be64(ByteIOContext *s);
291
292uint64_t ff_get_v(ByteIOContext *bc);
293
294static inline int url_is_streamed(ByteIOContext *s)
295{
296 return s->is_streamed;
297}
298
299/** @note when opened as read/write, the buffers are only used for
300 writing */
301int url_fdopen(ByteIOContext **s, URLContext *h);
302
303/** @warning must be called before any I/O */
304int url_setbufsize(ByteIOContext *s, int buf_size);
305/** Reset the buffer for reading or writing.
306 * @note Will drop any data currently in the buffer without transmitting it.
307 * @param flags URL_RDONLY to set up the buffer for reading, or URL_WRONLY
308 * to set up the buffer for writing. */
309int url_resetbuf(ByteIOContext *s, int flags);
310
311/** @note when opened as read/write, the buffers are only used for
312 writing */
313int url_fopen(ByteIOContext **s, const char *filename, int flags);
314int url_fclose(ByteIOContext *s);
315URLContext *url_fileno(ByteIOContext *s);
316
317/**
318 * Return the maximum packet size associated to packetized buffered file
319 * handle. If the file is not packetized (stream like http or file on
320 * disk), then 0 is returned.
321 *
322 * @param s buffered file handle
323 * @return maximum packet size in bytes
324 */
325int url_fget_max_packet_size(ByteIOContext *s);
326
327int url_open_buf(ByteIOContext **s, uint8_t *buf, int buf_size, int flags);
328
329/** return the written or read size */
330int url_close_buf(ByteIOContext *s);
331
332/**
333 * Open a write only memory stream.
334 *
335 * @param s new IO context
336 * @return zero if no error.
337 */
338int url_open_dyn_buf(ByteIOContext **s);
339
340/**
341 * Open a write only packetized memory stream with a maximum packet
342 * size of 'max_packet_size'. The stream is stored in a memory buffer
343 * with a big endian 4 byte header giving the packet size in bytes.
344 *
345 * @param s new IO context
346 * @param max_packet_size maximum packet size (must be > 0)
347 * @return zero if no error.
348 */
349int url_open_dyn_packet_buf(ByteIOContext **s, int max_packet_size);
350
351/**
352 * Return the written size and a pointer to the buffer. The buffer
353 * must be freed with av_free().
354 * @param s IO context
355 * @param pbuffer pointer to a byte buffer
356 * @return the length of the byte buffer
357 */
358int url_close_dyn_buf(ByteIOContext *s, uint8_t **pbuffer);
359
360unsigned long ff_crc04C11DB7_update(unsigned long checksum, const uint8_t *buf, unsigned int len);
361unsigned long get_checksum(ByteIOContext *s);
362void init_checksum(ByteIOContext *s, unsigned long (*update_checksum)(unsigned long c, const uint8_t *p, unsigned int len), unsigned long checksum);
363
364/* udp.c */
365int udp_set_remote_url(URLContext *h, const char *uri);
366int udp_get_local_port(URLContext *h);
367int udp_get_file_handle(URLContext *h);
368
369#endif /* FFMPEG_AVIO_H */
diff --git a/src/plugins/ffmpeg/libavformat/aviobuf.c b/src/plugins/ffmpeg/libavformat/aviobuf.c
deleted file mode 100644
index 0ea6a4a..0000000
--- a/src/plugins/ffmpeg/libavformat/aviobuf.c
+++ /dev/null
@@ -1,839 +0,0 @@
1/*
2 * Buffered I/O for ffmpeg system
3 * Copyright (c) 2000,2001 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/crc.h"
23#include "avformat.h"
24#include "avio.h"
25#include <stdarg.h>
26
27#define IO_BUFFER_SIZE 32768
28
29static void fill_buffer(ByteIOContext *s);
30
31int init_put_byte(ByteIOContext *s,
32 unsigned char *buffer,
33 int buffer_size,
34 int write_flag,
35 void *opaque,
36 int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
37 int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
38 offset_t (*seek)(void *opaque, offset_t offset, int whence))
39{
40 s->buffer = buffer;
41 s->buffer_size = buffer_size;
42 s->buf_ptr = buffer;
43 url_resetbuf(s, write_flag ? URL_WRONLY : URL_RDONLY);
44 s->opaque = opaque;
45 s->write_packet = write_packet;
46 s->read_packet = read_packet;
47 s->seek = seek;
48 s->pos = 0;
49 s->must_flush = 0;
50 s->eof_reached = 0;
51 s->error = 0;
52 s->is_streamed = 0;
53 s->max_packet_size = 0;
54 s->update_checksum= NULL;
55 if(!read_packet && !write_flag){
56 s->pos = buffer_size;
57 s->buf_end = s->buffer + buffer_size;
58 }
59 s->read_pause = NULL;
60 s->read_seek = NULL;
61 return 0;
62}
63
64ByteIOContext *av_alloc_put_byte(
65 unsigned char *buffer,
66 int buffer_size,
67 int write_flag,
68 void *opaque,
69 int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
70 int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
71 offset_t (*seek)(void *opaque, offset_t offset, int whence)) {
72 ByteIOContext *s = av_mallocz(sizeof(ByteIOContext));
73 init_put_byte(s, buffer, buffer_size, write_flag, opaque,
74 read_packet, write_packet, seek);
75 return s;
76}
77
78static void flush_buffer(ByteIOContext *s)
79{
80 if (s->buf_ptr > s->buffer) {
81 if (s->write_packet && !s->error){
82 int ret= s->write_packet(s->opaque, s->buffer, s->buf_ptr - s->buffer);
83 if(ret < 0){
84 s->error = ret;
85 }
86 }
87 if(s->update_checksum){
88 s->checksum= s->update_checksum(s->checksum, s->checksum_ptr, s->buf_ptr - s->checksum_ptr);
89 s->checksum_ptr= s->buffer;
90 }
91 s->pos += s->buf_ptr - s->buffer;
92 }
93 s->buf_ptr = s->buffer;
94}
95
96void put_byte(ByteIOContext *s, int b)
97{
98 *(s->buf_ptr)++ = b;
99 if (s->buf_ptr >= s->buf_end)
100 flush_buffer(s);
101}
102
103void put_buffer(ByteIOContext *s, const unsigned char *buf, int size)
104{
105 int len;
106
107 while (size > 0) {
108 len = (s->buf_end - s->buf_ptr);
109 if (len > size)
110 len = size;
111 memcpy(s->buf_ptr, buf, len);
112 s->buf_ptr += len;
113
114 if (s->buf_ptr >= s->buf_end)
115 flush_buffer(s);
116
117 buf += len;
118 size -= len;
119 }
120}
121
122void put_flush_packet(ByteIOContext *s)
123{
124 flush_buffer(s);
125 s->must_flush = 0;
126}
127
128offset_t url_fseek(ByteIOContext *s, offset_t offset, int whence)
129{
130 offset_t offset1;
131 offset_t pos;
132
133 if(!s)
134 return AVERROR(EINVAL);
135
136 pos = s->pos - (s->write_flag ? 0 : (s->buf_end - s->buffer));
137
138 if (whence != SEEK_CUR && whence != SEEK_SET)
139 return AVERROR(EINVAL);
140
141 if (whence == SEEK_CUR) {
142 offset1 = pos + (s->buf_ptr - s->buffer);
143 if (offset == 0)
144 return offset1;
145 offset += offset1;
146 }
147 offset1 = offset - pos;
148 if (!s->must_flush &&
149 offset1 >= 0 && offset1 < (s->buf_end - s->buffer)) {
150 /* can do the seek inside the buffer */
151 s->buf_ptr = s->buffer + offset1;
152 } else if(s->is_streamed && !s->write_flag &&
153 offset1 >= 0 && offset1 < (s->buf_end - s->buffer) + (1<<16)){
154 while(s->pos < offset && !s->eof_reached)
155 fill_buffer(s);
156 if (s->eof_reached)
157 return AVERROR(EPIPE);
158 s->buf_ptr = s->buf_end + offset - s->pos;
159 } else {
160 offset_t res = AVERROR(EPIPE);
161
162#if defined(CONFIG_MUXERS) || defined(CONFIG_NETWORK)
163 if (s->write_flag) {
164 flush_buffer(s);
165 s->must_flush = 1;
166 } else
167#endif /* defined(CONFIG_MUXERS) || defined(CONFIG_NETWORK) */
168 {
169 s->buf_end = s->buffer;
170 }
171 s->buf_ptr = s->buffer;
172 if (!s->seek || (res = s->seek(s->opaque, offset, SEEK_SET)) < 0)
173 return res;
174 s->pos = offset;
175 }
176 s->eof_reached = 0;
177 return offset;
178}
179
180void url_fskip(ByteIOContext *s, offset_t offset)
181{
182 url_fseek(s, offset, SEEK_CUR);
183}
184
185offset_t url_ftell(ByteIOContext *s)
186{
187 return url_fseek(s, 0, SEEK_CUR);
188}
189
190offset_t url_fsize(ByteIOContext *s)
191{
192 offset_t size;
193
194 if(!s)
195 return AVERROR(EINVAL);
196
197 if (!s->seek)
198 return AVERROR(EPIPE);
199 size = s->seek(s->opaque, 0, AVSEEK_SIZE);
200 if(size<0){
201 if ((size = s->seek(s->opaque, -1, SEEK_END)) < 0)
202 return size;
203 size++;
204 s->seek(s->opaque, s->pos, SEEK_SET);
205 }
206 return size;
207}
208
209int url_feof(ByteIOContext *s)
210{
211 if(!s)
212 return 0;
213 return s->eof_reached;
214}
215
216int url_ferror(ByteIOContext *s)
217{
218 if(!s)
219 return 0;
220 return s->error;
221}
222
223void put_le32(ByteIOContext *s, unsigned int val)
224{
225 put_byte(s, val);
226 put_byte(s, val >> 8);
227 put_byte(s, val >> 16);
228 put_byte(s, val >> 24);
229}
230
231void put_be32(ByteIOContext *s, unsigned int val)
232{
233 put_byte(s, val >> 24);
234 put_byte(s, val >> 16);
235 put_byte(s, val >> 8);
236 put_byte(s, val);
237}
238
239void put_strz(ByteIOContext *s, const char *str)
240{
241 if (str)
242 put_buffer(s, (const unsigned char *) str, strlen(str) + 1);
243 else
244 put_byte(s, 0);
245}
246
247void put_le64(ByteIOContext *s, uint64_t val)
248{
249 put_le32(s, (uint32_t)(val & 0xffffffff));
250 put_le32(s, (uint32_t)(val >> 32));
251}
252
253void put_be64(ByteIOContext *s, uint64_t val)
254{
255 put_be32(s, (uint32_t)(val >> 32));
256 put_be32(s, (uint32_t)(val & 0xffffffff));
257}
258
259void put_le16(ByteIOContext *s, unsigned int val)
260{
261 put_byte(s, val);
262 put_byte(s, val >> 8);
263}
264
265void put_be16(ByteIOContext *s, unsigned int val)
266{
267 put_byte(s, val >> 8);
268 put_byte(s, val);
269}
270
271void put_le24(ByteIOContext *s, unsigned int val)
272{
273 put_le16(s, val & 0xffff);
274 put_byte(s, val >> 16);
275}
276
277void put_be24(ByteIOContext *s, unsigned int val)
278{
279 put_be16(s, val >> 8);
280 put_byte(s, val);
281}
282
283void put_tag(ByteIOContext *s, const char *tag)
284{
285 while (*tag) {
286 put_byte(s, *tag++);
287 }
288}
289
290/* Input stream */
291
292static void fill_buffer(ByteIOContext *s)
293{
294 int len=0;
295
296 /* no need to do anything if EOF already reached */
297 if (s->eof_reached)
298 return;
299
300 if(s->update_checksum){
301 if(s->buf_end > s->checksum_ptr)
302 s->checksum= s->update_checksum(s->checksum, s->checksum_ptr, s->buf_end - s->checksum_ptr);
303 s->checksum_ptr= s->buffer;
304 }
305
306 if(s->read_packet)
307 len = s->read_packet(s->opaque, s->buffer, s->buffer_size);
308 if (len <= 0) {
309 /* do not modify buffer if EOF reached so that a seek back can
310 be done without rereading data */
311 s->eof_reached = 1;
312 if(len<0)
313 s->error= len;
314 } else {
315 s->pos += len;
316 s->buf_ptr = s->buffer;
317 s->buf_end = s->buffer + len;
318 }
319}
320
321unsigned long ff_crc04C11DB7_update(unsigned long checksum, const uint8_t *buf, unsigned int len){
322 return av_crc(av_crc_get_table(AV_CRC_32_IEEE), checksum, buf, len);
323}
324
325unsigned long get_checksum(ByteIOContext *s){
326 s->checksum= s->update_checksum(s->checksum, s->checksum_ptr, s->buf_ptr - s->checksum_ptr);
327 s->update_checksum= NULL;
328 return s->checksum;
329}
330
331void init_checksum(ByteIOContext *s, unsigned long (*update_checksum)(unsigned long c, const uint8_t *p, unsigned int len), unsigned long checksum){
332 s->update_checksum= update_checksum;
333 if(s->update_checksum){
334 s->checksum= checksum;
335 s->checksum_ptr= s->buf_ptr;
336 }
337}
338
339/* XXX: put an inline version */
340int get_byte(ByteIOContext *s)
341{
342 if (s->buf_ptr < s->buf_end) {
343 return *s->buf_ptr++;
344 } else {
345 fill_buffer(s);
346 if (s->buf_ptr < s->buf_end)
347 return *s->buf_ptr++;
348 else
349 return 0;
350 }
351}
352
353int url_fgetc(ByteIOContext *s)
354{
355 if (s->buf_ptr < s->buf_end) {
356 return *s->buf_ptr++;
357 } else {
358 fill_buffer(s);
359 if (s->buf_ptr < s->buf_end)
360 return *s->buf_ptr++;
361 else
362 return URL_EOF;
363 }
364}
365
366int get_buffer(ByteIOContext *s, unsigned char *buf, int size)
367{
368 int len, size1;
369
370 size1 = size;
371 while (size > 0) {
372 len = s->buf_end - s->buf_ptr;
373 if (len > size)
374 len = size;
375 if (len == 0) {
376 if(size > s->buffer_size && !s->update_checksum){
377 if(s->read_packet)
378 len = s->read_packet(s->opaque, buf, size);
379 if (len <= 0) {
380 /* do not modify buffer if EOF reached so that a seek back can
381 be done without rereading data */
382 s->eof_reached = 1;
383 if(len<0)
384 s->error= len;
385 break;
386 } else {
387 s->pos += len;
388 size -= len;
389 buf += len;
390 s->buf_ptr = s->buffer;
391 s->buf_end = s->buffer/* + len*/;
392 }
393 }else{
394 fill_buffer(s);
395 len = s->buf_end - s->buf_ptr;
396 if (len == 0)
397 break;
398 }
399 } else {
400 memcpy(buf, s->buf_ptr, len);
401 buf += len;
402 s->buf_ptr += len;
403 size -= len;
404 }
405 }
406 return size1 - size;
407}
408
409int get_partial_buffer(ByteIOContext *s, unsigned char *buf, int size)
410{
411 int len;
412
413 if(size<0)
414 return -1;
415
416 len = s->buf_end - s->buf_ptr;
417 if (len == 0) {
418 fill_buffer(s);
419 len = s->buf_end - s->buf_ptr;
420 }
421 if (len > size)
422 len = size;
423 memcpy(buf, s->buf_ptr, len);
424 s->buf_ptr += len;
425 return len;
426}
427
428unsigned int get_le16(ByteIOContext *s)
429{
430 unsigned int val;
431 val = get_byte(s);
432 val |= get_byte(s) << 8;
433 return val;
434}
435
436unsigned int get_le24(ByteIOContext *s)
437{
438 unsigned int val;
439 val = get_le16(s);
440 val |= get_byte(s) << 16;
441 return val;
442}
443
444unsigned int get_le32(ByteIOContext *s)
445{
446 unsigned int val;
447 val = get_le16(s);
448 val |= get_le16(s) << 16;
449 return val;
450}
451
452uint64_t get_le64(ByteIOContext *s)
453{
454 uint64_t val;
455 val = (uint64_t)get_le32(s);
456 val |= (uint64_t)get_le32(s) << 32;
457 return val;
458}
459
460unsigned int get_be16(ByteIOContext *s)
461{
462 unsigned int val;
463 val = get_byte(s) << 8;
464 val |= get_byte(s);
465 return val;
466}
467
468unsigned int get_be24(ByteIOContext *s)
469{
470 unsigned int val;
471 val = get_be16(s) << 8;
472 val |= get_byte(s);
473 return val;
474}
475unsigned int get_be32(ByteIOContext *s)
476{
477 unsigned int val;
478 val = get_be16(s) << 16;
479 val |= get_be16(s);
480 return val;
481}
482
483char *get_strz(ByteIOContext *s, char *buf, int maxlen)
484{
485 int i = 0;
486 char c;
487
488 while ((c = get_byte(s))) {
489 if (i < maxlen-1)
490 buf[i++] = c;
491 }
492
493 buf[i] = 0; /* Ensure null terminated, but may be truncated */
494
495 return buf;
496}
497
498uint64_t get_be64(ByteIOContext *s)
499{
500 uint64_t val;
501 val = (uint64_t)get_be32(s) << 32;
502 val |= (uint64_t)get_be32(s);
503 return val;
504}
505
506uint64_t ff_get_v(ByteIOContext *bc){
507 uint64_t val = 0;
508 int tmp;
509
510 do{
511 tmp = get_byte(bc);
512 val= (val<<7) + (tmp&127);
513 }while(tmp&128);
514 return val;
515}
516
517int url_fdopen(ByteIOContext **s, URLContext *h)
518{
519 uint8_t *buffer;
520 int buffer_size, max_packet_size;
521
522
523 max_packet_size = url_get_max_packet_size(h);
524 if (max_packet_size) {
525 buffer_size = max_packet_size; /* no need to bufferize more than one packet */
526 } else {
527 buffer_size = IO_BUFFER_SIZE;
528 }
529 buffer = av_malloc(buffer_size);
530 if (!buffer)
531 return AVERROR(ENOMEM);
532
533 *s = av_mallocz(sizeof(ByteIOContext));
534 if(!*s) {
535 av_free(buffer);
536 return AVERROR(ENOMEM);
537 }
538
539 if (init_put_byte(*s, buffer, buffer_size,
540 (h->flags & URL_WRONLY || h->flags & URL_RDWR), h,
541 (int (*)(void *, uint8_t*,int)) url_read,
542 (int (*)(void *, uint8_t*,int)) url_write,
543 (offset_t (*)(void *, offset_t, int)) url_seek) < 0) {
544 av_free(buffer);
545 av_freep(s);
546 return AVERROR(EIO);
547 }
548 (*s)->is_streamed = h->is_streamed;
549 (*s)->max_packet_size = max_packet_size;
550 if(h->prot) {
551 (*s)->read_pause = (int (*)(void *, int))h->prot->url_read_pause;
552 (*s)->read_seek = (offset_t (*)(void *, int, int64_t, int))h->prot->url_read_seek;
553 }
554 return 0;
555}
556
557int url_setbufsize(ByteIOContext *s, int buf_size)
558{
559 uint8_t *buffer;
560 buffer = av_malloc(buf_size);
561 if (!buffer)
562 return AVERROR(ENOMEM);
563
564 av_free(s->buffer);
565 s->buffer = buffer;
566 s->buffer_size = buf_size;
567 s->buf_ptr = buffer;
568 url_resetbuf(s, s->write_flag ? URL_WRONLY : URL_RDONLY);
569 return 0;
570}
571
572int url_resetbuf(ByteIOContext *s, int flags)
573{
574 URLContext *h = s->opaque;
575 if ((flags & URL_RDWR) || (h && h->flags != flags && !h->flags & URL_RDWR))
576 return AVERROR(EINVAL);
577
578 if (flags & URL_WRONLY) {
579 s->buf_end = s->buffer + s->buffer_size;
580 s->write_flag = 1;
581 } else {
582 s->buf_end = s->buffer;
583 s->write_flag = 0;
584 }
585 return 0;
586}
587
588int url_fopen(ByteIOContext **s, const char *filename, int flags)
589{
590 URLContext *h;
591 int err;
592
593 err = url_open(&h, filename, flags);
594 if (err < 0)
595 return err;
596 err = url_fdopen(s, h);
597 if (err < 0) {
598 url_close(h);
599 return err;
600 }
601 return 0;
602}
603
604int url_fclose(ByteIOContext *s)
605{
606 URLContext *h = s->opaque;
607
608 av_free(s->buffer);
609 av_free(s);
610 return url_close(h);
611}
612
613URLContext *url_fileno(ByteIOContext *s)
614{
615 return s->opaque;
616}
617
618#ifdef CONFIG_MUXERS
619int url_fprintf(ByteIOContext *s, const char *fmt, ...)
620{
621 va_list ap;
622 char buf[4096];
623 int ret;
624
625 va_start(ap, fmt);
626 ret = vsnprintf(buf, sizeof(buf), fmt, ap);
627 va_end(ap);
628 put_buffer(s, buf, strlen(buf));
629 return ret;
630}
631#endif //CONFIG_MUXERS
632
633char *url_fgets(ByteIOContext *s, char *buf, int buf_size)
634{
635 int c;
636 char *q;
637
638 c = url_fgetc(s);
639 if (c == EOF)
640 return NULL;
641 q = buf;
642 for(;;) {
643 if (c == EOF || c == '\n')
644 break;
645 if ((q - buf) < buf_size - 1)
646 *q++ = c;
647 c = url_fgetc(s);
648 }
649 if (buf_size > 0)
650 *q = '\0';
651 return buf;
652}
653
654int url_fget_max_packet_size(ByteIOContext *s)
655{
656 return s->max_packet_size;
657}
658
659int av_url_read_fpause(ByteIOContext *s, int pause)
660{
661 if (!s->read_pause)
662 return AVERROR(ENOSYS);
663 return s->read_pause(s->opaque, pause);
664}
665
666offset_t av_url_read_fseek(ByteIOContext *s,
667 int stream_index, int64_t timestamp, int flags)
668{
669 URLContext *h = s->opaque;
670 offset_t ret;
671 if (!s->read_seek)
672 return AVERROR(ENOSYS);
673 ret = s->read_seek(h, stream_index, timestamp, flags);
674 if(ret >= 0) {
675 s->buf_ptr = s->buf_end; // Flush buffer
676 s->pos = s->seek(h, 0, SEEK_CUR);
677 }
678 return ret;
679}
680
681/* url_open_dyn_buf and url_close_dyn_buf are used in rtp.c to send a response
682 * back to the server even if CONFIG_MUXERS is not set. */
683#if defined(CONFIG_MUXERS) || defined(CONFIG_NETWORK)
684/* buffer handling */
685int url_open_buf(ByteIOContext **s, uint8_t *buf, int buf_size, int flags)
686{
687 int ret;
688 *s = av_mallocz(sizeof(ByteIOContext));
689 if(!*s)
690 return AVERROR(ENOMEM);
691 ret = init_put_byte(*s, buf, buf_size,
692 (flags & URL_WRONLY || flags & URL_RDWR),
693 NULL, NULL, NULL, NULL);
694 if(ret != 0)
695 av_freep(s);
696 return ret;
697}
698
699int url_close_buf(ByteIOContext *s)
700{
701 put_flush_packet(s);
702 return s->buf_ptr - s->buffer;
703}
704
705/* output in a dynamic buffer */
706
707typedef struct DynBuffer {
708 int pos, size, allocated_size;
709 uint8_t *buffer;
710 int io_buffer_size;
711 uint8_t io_buffer[1];
712} DynBuffer;
713
714static int dyn_buf_write(void *opaque, uint8_t *buf, int buf_size)
715{
716 DynBuffer *d = opaque;
717 int new_size, new_allocated_size;
718
719 /* reallocate buffer if needed */
720 new_size = d->pos + buf_size;
721 new_allocated_size = d->allocated_size;
722 if(new_size < d->pos || new_size > INT_MAX/2)
723 return -1;
724 while (new_size > new_allocated_size) {
725 if (!new_allocated_size)
726 new_allocated_size = new_size;
727 else
728 new_allocated_size += new_allocated_size / 2 + 1;
729 }
730
731 if (new_allocated_size > d->allocated_size) {
732 d->buffer = av_realloc(d->buffer, new_allocated_size);
733 if(d->buffer == NULL)
734 return -1234;
735 d->allocated_size = new_allocated_size;
736 }
737 memcpy(d->buffer + d->pos, buf, buf_size);
738 d->pos = new_size;
739 if (d->pos > d->size)
740 d->size = d->pos;
741 return buf_size;
742}
743
744static int dyn_packet_buf_write(void *opaque, uint8_t *buf, int buf_size)
745{
746 unsigned char buf1[4];
747 int ret;
748
749 /* packetized write: output the header */
750 buf1[0] = (buf_size >> 24);
751 buf1[1] = (buf_size >> 16);
752 buf1[2] = (buf_size >> 8);
753 buf1[3] = (buf_size);
754 ret= dyn_buf_write(opaque, buf1, 4);
755 if(ret < 0)
756 return ret;
757
758 /* then the data */
759 return dyn_buf_write(opaque, buf, buf_size);
760}
761
762static offset_t dyn_buf_seek(void *opaque, offset_t offset, int whence)
763{
764 DynBuffer *d = opaque;
765
766 if (whence == SEEK_CUR)
767 offset += d->pos;
768 else if (whence == SEEK_END)
769 offset += d->size;
770 if (offset < 0 || offset > 0x7fffffffLL)
771 return -1;
772 d->pos = offset;
773 return 0;
774}
775
776static int url_open_dyn_buf_internal(ByteIOContext **s, int max_packet_size)
777{
778 DynBuffer *d;
779 int io_buffer_size, ret;
780
781 if (max_packet_size)
782 io_buffer_size = max_packet_size;
783 else
784 io_buffer_size = 1024;
785
786 if(sizeof(DynBuffer) + io_buffer_size < io_buffer_size)
787 return -1;
788 d = av_malloc(sizeof(DynBuffer) + io_buffer_size);
789 if (!d)
790 return -1;
791 *s = av_mallocz(sizeof(ByteIOContext));
792 if(!*s) {
793 av_free(d);
794 return AVERROR(ENOMEM);
795 }
796 d->io_buffer_size = io_buffer_size;
797 d->buffer = NULL;
798 d->pos = 0;
799 d->size = 0;
800 d->allocated_size = 0;
801 ret = init_put_byte(*s, d->io_buffer, io_buffer_size,
802 1, d, NULL,
803 max_packet_size ? dyn_packet_buf_write : dyn_buf_write,
804 max_packet_size ? NULL : dyn_buf_seek);
805 if (ret == 0) {
806 (*s)->max_packet_size = max_packet_size;
807 } else {
808 av_free(d);
809 av_freep(s);
810 }
811 return ret;
812}
813
814int url_open_dyn_buf(ByteIOContext **s)
815{
816 return url_open_dyn_buf_internal(s, 0);
817}
818
819int url_open_dyn_packet_buf(ByteIOContext **s, int max_packet_size)
820{
821 if (max_packet_size <= 0)
822 return -1;
823 return url_open_dyn_buf_internal(s, max_packet_size);
824}
825
826int url_close_dyn_buf(ByteIOContext *s, uint8_t **pbuffer)
827{
828 DynBuffer *d = s->opaque;
829 int size;
830
831 put_flush_packet(s);
832
833 *pbuffer = d->buffer;
834 size = d->size;
835 av_free(d);
836 av_free(s);
837 return size;
838}
839#endif /* CONFIG_MUXERS || CONFIG_NETWORK */
diff --git a/src/plugins/ffmpeg/libavformat/avisynth.c b/src/plugins/ffmpeg/libavformat/avisynth.c
deleted file mode 100644
index fdb8efa..0000000
--- a/src/plugins/ffmpeg/libavformat/avisynth.c
+++ /dev/null
@@ -1,222 +0,0 @@
1/*
2 * AVISynth support for ffmpeg system
3 * Copyright (c) 2006 DivX, Inc.
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 "avformat.h"
23#include "riff.h"
24
25#include <windows.h>
26#include <vfw.h>
27
28typedef struct {
29 PAVISTREAM handle;
30 AVISTREAMINFO info;
31 DWORD read;
32 LONG chunck_size;
33 LONG chunck_samples;
34} AVISynthStream;
35
36typedef struct {
37 PAVIFILE file;
38 AVISynthStream *streams;
39 int nb_streams;
40 int next_stream;
41} AVISynthContext;
42
43static int avisynth_read_header(AVFormatContext *s, AVFormatParameters *ap)
44{
45 AVISynthContext *avs = s->priv_data;
46 HRESULT res;
47 AVIFILEINFO info;
48 DWORD id;
49 AVStream *st;
50 AVISynthStream *stream;
51
52 AVIFileInit();
53
54 res = AVIFileOpen(&avs->file, s->filename, OF_READ|OF_SHARE_DENY_WRITE, NULL);
55 if (res != S_OK)
56 {
57 av_log(s, AV_LOG_ERROR, "AVIFileOpen failed with error %ld", res);
58 AVIFileExit();
59 return -1;
60 }
61
62 res = AVIFileInfo(avs->file, &info, sizeof(info));
63 if (res != S_OK)
64 {
65 av_log(s, AV_LOG_ERROR, "AVIFileInfo failed with error %ld", res);
66 AVIFileExit();
67 return -1;
68 }
69
70 avs->streams = av_mallocz(info.dwStreams * sizeof(AVISynthStream));
71
72 for (id=0; id<info.dwStreams; id++)
73 {
74 stream = &avs->streams[id];
75 stream->read = 0;
76 if (AVIFileGetStream(avs->file, &stream->handle, 0, id) == S_OK)
77 {
78 if (AVIStreamInfo(stream->handle, &stream->info, sizeof(stream->info)) == S_OK)
79 {
80 if (stream->info.fccType == streamtypeAUDIO)
81 {
82 WAVEFORMATEX wvfmt;
83 LONG struct_size = sizeof(WAVEFORMATEX);
84 if (AVIStreamReadFormat(stream->handle, 0, &wvfmt, &struct_size) != S_OK)
85 continue;
86
87 st = av_new_stream(s, id);
88 st->codec->codec_type = CODEC_TYPE_AUDIO;
89
90 st->codec->block_align = wvfmt.nBlockAlign;
91 st->codec->channels = wvfmt.nChannels;
92 st->codec->sample_rate = wvfmt.nSamplesPerSec;
93 st->codec->bit_rate = wvfmt.nAvgBytesPerSec * 8;
94 st->codec->bits_per_sample = wvfmt.wBitsPerSample;
95
96 stream->chunck_samples = wvfmt.nSamplesPerSec * (uint64_t)info.dwScale / (uint64_t)info.dwRate;
97 stream->chunck_size = stream->chunck_samples * wvfmt.nChannels * wvfmt.wBitsPerSample / 8;
98
99 st->codec->codec_tag = wvfmt.wFormatTag;
100 st->codec->codec_id = wav_codec_get_id(wvfmt.wFormatTag, st->codec->bits_per_sample);
101 }
102 else if (stream->info.fccType == streamtypeVIDEO)
103 {
104 BITMAPINFO imgfmt;
105 LONG struct_size = sizeof(BITMAPINFO);
106
107 stream->chunck_size = stream->info.dwSampleSize;
108 stream->chunck_samples = 1;
109
110 if (AVIStreamReadFormat(stream->handle, 0, &imgfmt, &struct_size) != S_OK)
111 continue;
112
113 st = av_new_stream(s, id);
114 st->codec->codec_type = CODEC_TYPE_VIDEO;
115 st->r_frame_rate.num = stream->info.dwRate;
116 st->r_frame_rate.den = stream->info.dwScale;
117
118 st->codec->width = imgfmt.bmiHeader.biWidth;
119 st->codec->height = imgfmt.bmiHeader.biHeight;
120
121 st->codec->bits_per_sample = imgfmt.bmiHeader.biBitCount;
122 st->codec->bit_rate = (uint64_t)stream->info.dwSampleSize * (uint64_t)stream->info.dwRate * 8 / (uint64_t)stream->info.dwScale;
123 st->codec->codec_tag = imgfmt.bmiHeader.biCompression;
124 st->codec->codec_id = codec_get_id(codec_bmp_tags, imgfmt.bmiHeader.biCompression);
125
126 st->duration = stream->info.dwLength;
127 }
128 else
129 {
130 AVIStreamRelease(stream->handle);
131 continue;
132 }
133
134 avs->nb_streams++;
135
136 st->codec->stream_codec_tag = stream->info.fccHandler;
137
138 av_set_pts_info(st, 64, info.dwScale, info.dwRate);
139 st->start_time = stream->info.dwStart;
140 }
141 }
142 }
143
144 return 0;
145}
146
147static int avisynth_read_packet(AVFormatContext *s, AVPacket *pkt)
148{
149 AVISynthContext *avs = s->priv_data;
150 HRESULT res;
151 AVISynthStream *stream;
152 int stream_id = avs->next_stream;
153 LONG read_size;
154
155 // handle interleaving manually...
156 stream = &avs->streams[stream_id];
157
158 if (stream->read >= stream->info.dwLength)
159 return AVERROR(EIO);
160
161 if (av_new_packet(pkt, stream->chunck_size))
162 return AVERROR(EIO);
163 pkt->stream_index = stream_id;
164 pkt->pts = avs->streams[stream_id].read / avs->streams[stream_id].chunck_samples;
165
166 res = AVIStreamRead(stream->handle, stream->read, stream->chunck_samples, pkt->data, stream->chunck_size, &read_size, NULL);
167
168 pkt->pts = stream->read;
169 pkt->size = read_size;
170
171 stream->read += stream->chunck_samples;
172
173 // prepare for the next stream to read
174 do {
175 avs->next_stream = (avs->next_stream+1) % avs->nb_streams;
176 } while (avs->next_stream != stream_id && s->streams[avs->next_stream]->discard >= AVDISCARD_ALL);
177
178 return (res == S_OK) ? pkt->size : -1;
179}
180
181static int avisynth_read_close(AVFormatContext *s)
182{
183 AVISynthContext *avs = s->priv_data;
184 int i;
185
186 for (i=0;i<avs->nb_streams;i++)
187 {
188 AVIStreamRelease(avs->streams[i].handle);
189 }
190
191 av_free(avs->streams);
192 AVIFileRelease(avs->file);
193 AVIFileExit();
194 return 0;
195}
196
197static int avisynth_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags)
198{
199 AVISynthContext *avs = s->priv_data;
200 int stream_id;
201
202 for (stream_id = 0; stream_id < avs->nb_streams; stream_id++)
203 {
204 avs->streams[stream_id].read = pts * avs->streams[stream_id].chunck_samples;
205 }
206
207 return 0;
208}
209
210AVInputFormat avisynth_demuxer = {
211 "avs",
212 NULL_IF_CONFIG_SMALL("AVISynth"),
213 sizeof(AVISynthContext),
214 NULL,
215 avisynth_read_header,
216 avisynth_read_packet,
217 avisynth_read_close,
218 avisynth_read_seek,
219 NULL,
220 0,
221 "avs",
222};
diff --git a/src/plugins/ffmpeg/libavformat/avs.c b/src/plugins/ffmpeg/libavformat/avs.c
deleted file mode 100644
index 16be4dc..0000000
--- a/src/plugins/ffmpeg/libavformat/avs.c
+++ /dev/null
@@ -1,226 +0,0 @@
1/*
2 * AVS demuxer.
3 * Copyright (c) 2006 Aurelien Jacobs <aurel@gnuage.org>
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 "avformat.h"
23#include "voc.h"
24
25
26typedef struct avs_format {
27 voc_dec_context_t voc;
28 AVStream *st_video;
29 AVStream *st_audio;
30 int width;
31 int height;
32 int bits_per_sample;
33 int fps;
34 int nb_frames;
35 int remaining_frame_size;
36 int remaining_audio_size;
37} avs_format_t;
38
39typedef enum avs_block_type {
40 AVS_NONE = 0x00,
41 AVS_VIDEO = 0x01,
42 AVS_AUDIO = 0x02,
43 AVS_PALETTE = 0x03,
44 AVS_GAME_DATA = 0x04,
45} avs_block_type_t;
46
47static int avs_probe(AVProbeData * p)
48{
49 const uint8_t *d;
50
51 d = p->buf;
52 if (d[0] == 'w' && d[1] == 'W' && d[2] == 0x10 && d[3] == 0)
53 return 50;
54
55 return 0;
56}
57
58static int avs_read_header(AVFormatContext * s, AVFormatParameters * ap)
59{
60 avs_format_t *avs = s->priv_data;
61
62 s->ctx_flags |= AVFMTCTX_NOHEADER;
63
64 url_fskip(s->pb, 4);
65 avs->width = get_le16(s->pb);
66 avs->height = get_le16(s->pb);
67 avs->bits_per_sample = get_le16(s->pb);
68 avs->fps = get_le16(s->pb);
69 avs->nb_frames = get_le32(s->pb);
70 avs->remaining_frame_size = 0;
71 avs->remaining_audio_size = 0;
72
73 avs->st_video = avs->st_audio = NULL;
74
75 if (avs->width != 318 || avs->height != 198)
76 av_log(s, AV_LOG_ERROR, "This avs pretend to be %dx%d "
77 "when the avs format is supposed to be 318x198 only.\n",
78 avs->width, avs->height);
79
80 return 0;
81}
82
83static int
84avs_read_video_packet(AVFormatContext * s, AVPacket * pkt,
85 avs_block_type_t type, int sub_type, int size,
86 uint8_t * palette, int palette_size)
87{
88 avs_format_t *avs = s->priv_data;
89 int ret;
90
91 ret = av_new_packet(pkt, size + palette_size);
92 if (ret < 0)
93 return ret;
94
95 if (palette_size) {
96 pkt->data[0] = 0x00;
97 pkt->data[1] = 0x03;
98 pkt->data[2] = palette_size & 0xFF;
99 pkt->data[3] = (palette_size >> 8) & 0xFF;
100 memcpy(pkt->data + 4, palette, palette_size - 4);
101 }
102
103 pkt->data[palette_size + 0] = sub_type;
104 pkt->data[palette_size + 1] = type;
105 pkt->data[palette_size + 2] = size & 0xFF;
106 pkt->data[palette_size + 3] = (size >> 8) & 0xFF;
107 ret = get_buffer(s->pb, pkt->data + palette_size + 4, size - 4) + 4;
108 if (ret < size) {
109 av_free_packet(pkt);
110 return AVERROR(EIO);
111 }
112
113 pkt->size = ret + palette_size;
114 pkt->stream_index = avs->st_video->index;
115 if (sub_type == 0)
116 pkt->flags |= PKT_FLAG_KEY;
117
118 return 0;
119}
120
121static int avs_read_audio_packet(AVFormatContext * s, AVPacket * pkt)
122{
123 avs_format_t *avs = s->priv_data;
124 int ret, size;
125
126 size = url_ftell(s->pb);
127 ret = voc_get_packet(s, pkt, avs->st_audio, avs->remaining_audio_size);
128 size = url_ftell(s->pb) - size;
129 avs->remaining_audio_size -= size;
130
131 if (ret == AVERROR(EIO))
132 return 0; /* this indicate EOS */
133 if (ret < 0)
134 return ret;
135
136 pkt->stream_index = avs->st_audio->index;
137 pkt->flags |= PKT_FLAG_KEY;
138
139 return size;
140}
141
142static int avs_read_packet(AVFormatContext * s, AVPacket * pkt)
143{
144 avs_format_t *avs = s->priv_data;
145 int sub_type = 0, size = 0;
146 avs_block_type_t type = AVS_NONE;
147 int palette_size = 0;
148 uint8_t palette[4 + 3 * 256];
149 int ret;
150
151 if (avs->remaining_audio_size > 0)
152 if (avs_read_audio_packet(s, pkt) > 0)
153 return 0;
154
155 while (1) {
156 if (avs->remaining_frame_size <= 0) {
157 if (!get_le16(s->pb)) /* found EOF */
158 return AVERROR(EIO);
159 avs->remaining_frame_size = get_le16(s->pb) - 4;
160 }
161
162 while (avs->remaining_frame_size > 0) {
163 sub_type = get_byte(s->pb);
164 type = get_byte(s->pb);
165 size = get_le16(s->pb);
166 avs->remaining_frame_size -= size;
167
168 switch (type) {
169 case AVS_PALETTE:
170 ret = get_buffer(s->pb, palette, size - 4);
171 if (ret < size - 4)
172 return AVERROR(EIO);
173 palette_size = size;
174 break;
175
176 case AVS_VIDEO:
177 if (!avs->st_video) {
178 avs->st_video = av_new_stream(s, AVS_VIDEO);
179 if (avs->st_video == NULL)
180 return AVERROR(ENOMEM);
181 avs->st_video->codec->codec_type = CODEC_TYPE_VIDEO;
182 avs->st_video->codec->codec_id = CODEC_ID_AVS;
183 avs->st_video->codec->width = avs->width;
184 avs->st_video->codec->height = avs->height;
185 avs->st_video->codec->bits_per_sample=avs->bits_per_sample;
186 avs->st_video->nb_frames = avs->nb_frames;
187 avs->st_video->codec->time_base = (AVRational) {
188 1, avs->fps};
189 }
190 return avs_read_video_packet(s, pkt, type, sub_type, size,
191 palette, palette_size);
192
193 case AVS_AUDIO:
194 if (!avs->st_audio) {
195 avs->st_audio = av_new_stream(s, AVS_AUDIO);
196 if (avs->st_audio == NULL)
197 return AVERROR(ENOMEM);
198 avs->st_audio->codec->codec_type = CODEC_TYPE_AUDIO;
199 }
200 avs->remaining_audio_size = size - 4;
201 size = avs_read_audio_packet(s, pkt);
202 if (size != 0)
203 return size;
204 break;
205
206 default:
207 url_fskip(s->pb, size - 4);
208 }
209 }
210 }
211}
212
213static int avs_read_close(AVFormatContext * s)
214{
215 return 0;
216}
217
218AVInputFormat avs_demuxer = {
219 "avs",
220 NULL_IF_CONFIG_SMALL("AVS format"),
221 sizeof(avs_format_t),
222 avs_probe,
223 avs_read_header,
224 avs_read_packet,
225 avs_read_close,
226};
diff --git a/src/plugins/ffmpeg/libavformat/bethsoftvid.c b/src/plugins/ffmpeg/libavformat/bethsoftvid.c
deleted file mode 100644
index e3024c2..0000000
--- a/src/plugins/ffmpeg/libavformat/bethsoftvid.c
+++ /dev/null
@@ -1,233 +0,0 @@
1/*
2 * Bethsoft VID format Demuxer
3 * Copyright (c) 2007 Nicholas Tung
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/**
23 * @file bethsoftvid.c
24 * @brief Bethesda Softworks VID (.vid) file demuxer
25 * @author Nicholas Tung [ntung (at. ntung com] (2007-03)
26 * @sa http://wiki.multimedia.cx/index.php?title=Bethsoft_VID
27 * @sa http://www.svatopluk.com/andux/docs/dfvid.html
28 */
29
30#include "avformat.h"
31#include "libavcodec/bethsoftvideo.h"
32
33typedef struct BVID_DemuxContext
34{
35 int nframes;
36 /** delay value between frames, added to individual frame delay.
37 * custom units, which will be added to other custom units (~=16ms according
38 * to free, unofficial documentation) */
39 int bethsoft_global_delay;
40
41 /** video presentation time stamp.
42 * delay = 16 milliseconds * (global_delay + per_frame_delay) */
43 int video_pts;
44
45 int is_finished;
46
47} BVID_DemuxContext;
48
49static int vid_probe(AVProbeData *p)
50{
51 // little endian VID tag, file starts with "VID\0"
52 if (AV_RL32(p->buf) != MKTAG('V', 'I', 'D', 0))
53 return 0;
54
55 return AVPROBE_SCORE_MAX;
56}
57
58static int vid_read_header(AVFormatContext *s,
59 AVFormatParameters *ap)
60{
61 BVID_DemuxContext *vid = s->priv_data;
62 ByteIOContext *pb = s->pb;
63 AVStream *stream;
64
65 /* load main header. Contents:
66 * bytes: 'V' 'I' 'D'
67 * int16s: always_512, nframes, width, height, delay, always_14
68 */
69 url_fseek(pb, 5, SEEK_CUR);
70 vid->nframes = get_le16(pb);
71
72 stream = av_new_stream(s, 0);
73 if (!stream)
74 return AVERROR(ENOMEM);
75 av_set_pts_info(stream, 32, 1, 60); // 16 ms increments, i.e. 60 fps
76 stream->codec->codec_type = CODEC_TYPE_VIDEO;
77 stream->codec->codec_id = CODEC_ID_BETHSOFTVID;
78 stream->codec->width = get_le16(pb);
79 stream->codec->height = get_le16(pb);
80 stream->codec->pix_fmt = PIX_FMT_PAL8;
81 vid->bethsoft_global_delay = get_le16(pb);
82 get_le16(pb);
83
84 // done with video codec, set up audio codec
85 stream = av_new_stream(s, 0);
86 if (!stream)
87 return AVERROR(ENOMEM);
88 stream->codec->codec_type = CODEC_TYPE_AUDIO;
89 stream->codec->codec_id = CODEC_ID_PCM_U8;
90 stream->codec->channels = 1;
91 stream->codec->sample_rate = 11025;
92 stream->codec->bits_per_sample = 8;
93 stream->codec->bit_rate = stream->codec->channels * stream->codec->sample_rate * stream->codec->bits_per_sample;
94
95 return 0;
96}
97
98#define BUFFER_PADDING_SIZE 1000
99static int read_frame(BVID_DemuxContext *vid, ByteIOContext *pb, AVPacket *pkt,
100 uint8_t block_type, AVFormatContext *s, int npixels)
101{
102 uint8_t * vidbuf_start = NULL;
103 int vidbuf_nbytes = 0;
104 int code;
105 int bytes_copied = 0;
106 int position;
107 unsigned int vidbuf_capacity;
108
109 vidbuf_start = av_malloc(vidbuf_capacity = BUFFER_PADDING_SIZE);
110 if(!vidbuf_start)
111 return AVERROR(ENOMEM);
112
113 // save the file position for the packet, include block type
114 position = url_ftell(pb) - 1;
115
116 vidbuf_start[vidbuf_nbytes++] = block_type;
117
118 // get the video delay (next int16), and set the presentation time
119 vid->video_pts += vid->bethsoft_global_delay + get_le16(pb);
120
121 // set the y offset if it exists (decoder header data should be in data section)
122 if(block_type == VIDEO_YOFF_P_FRAME){
123 if(get_buffer(pb, &vidbuf_start[vidbuf_nbytes], 2) != 2)
124 goto fail;
125 vidbuf_nbytes += 2;
126 }
127
128 do{
129 vidbuf_start = av_fast_realloc(vidbuf_start, &vidbuf_capacity, vidbuf_nbytes + BUFFER_PADDING_SIZE);
130 if(!vidbuf_start)
131 return AVERROR(ENOMEM);
132
133 code = get_byte(pb);
134 vidbuf_start[vidbuf_nbytes++] = code;
135
136 if(code >= 0x80){ // rle sequence
137 if(block_type == VIDEO_I_FRAME)
138 vidbuf_start[vidbuf_nbytes++] = get_byte(pb);
139 } else if(code){ // plain sequence
140 if(get_buffer(pb, &vidbuf_start[vidbuf_nbytes], code) != code)
141 goto fail;
142 vidbuf_nbytes += code;
143 }
144 bytes_copied += code & 0x7F;
145 if(bytes_copied == npixels){ // sometimes no stop character is given, need to keep track of bytes copied
146 // may contain a 0 byte even if read all pixels
147 if(get_byte(pb))
148 url_fseek(pb, -1, SEEK_CUR);
149 break;
150 }
151 if(bytes_copied > npixels)
152 goto fail;
153 } while(code);
154
155 // copy data into packet
156 if(av_new_packet(pkt, vidbuf_nbytes) < 0)
157 goto fail;
158 memcpy(pkt->data, vidbuf_start, vidbuf_nbytes);
159 av_free(vidbuf_start);
160
161 pkt->pos = position;
162 pkt->stream_index = 0; // use the video decoder, which was initialized as the first stream
163 pkt->pts = vid->video_pts;
164
165 vid->nframes--; // used to check if all the frames were read
166 return vidbuf_nbytes;
167fail:
168 av_free(vidbuf_start);
169 return -1;
170}
171
172static int vid_read_packet(AVFormatContext *s,
173 AVPacket *pkt)
174{
175 BVID_DemuxContext *vid = s->priv_data;
176 ByteIOContext *pb = s->pb;
177 unsigned char block_type;
178 int audio_length;
179 int ret_value;
180
181 if(vid->is_finished || url_feof(pb))
182 return AVERROR(EIO);
183
184 block_type = get_byte(pb);
185 switch(block_type){
186 case PALETTE_BLOCK:
187 url_fseek(pb, -1, SEEK_CUR); // include block type
188 ret_value = av_get_packet(pb, pkt, 3 * 256 + 1);
189 if(ret_value != 3 * 256 + 1){
190 av_free_packet(pkt);
191 return AVERROR(EIO);
192 }
193 pkt->stream_index = 0;
194 return ret_value;
195
196 case FIRST_AUDIO_BLOCK:
197 get_le16(pb);
198 // soundblaster DAC used for sample rate, as on specification page (link above)
199 s->streams[1]->codec->sample_rate = 1000000 / (256 - get_byte(pb));
200 s->streams[1]->codec->bit_rate = s->streams[1]->codec->channels * s->streams[1]->codec->sample_rate * s->streams[1]->codec->bits_per_sample;
201 case AUDIO_BLOCK:
202 audio_length = get_le16(pb);
203 ret_value = av_get_packet(pb, pkt, audio_length);
204 pkt->stream_index = 1;
205 return ret_value != audio_length ? AVERROR(EIO) : ret_value;
206
207 case VIDEO_P_FRAME:
208 case VIDEO_YOFF_P_FRAME:
209 case VIDEO_I_FRAME:
210 return read_frame(vid, pb, pkt, block_type, s,
211 s->streams[0]->codec->width * s->streams[0]->codec->height);
212
213 case EOF_BLOCK:
214 if(vid->nframes != 0)
215 av_log(s, AV_LOG_VERBOSE, "reached terminating character but not all frames read.\n");
216 vid->is_finished = 1;
217 return AVERROR(EIO);
218 default:
219 av_log(s, AV_LOG_ERROR, "unknown block (character = %c, decimal = %d, hex = %x)!!!\n",
220 block_type, block_type, block_type); return -1;
221 }
222
223 return 0;
224}
225
226AVInputFormat bethsoftvid_demuxer = {
227 "bethsoftvid",
228 NULL_IF_CONFIG_SMALL("Bethesda Softworks VID format"),
229 sizeof(BVID_DemuxContext),
230 vid_probe,
231 vid_read_header,
232 vid_read_packet,
233};
diff --git a/src/plugins/ffmpeg/libavformat/bfi.c b/src/plugins/ffmpeg/libavformat/bfi.c
deleted file mode 100644
index 5a8d569..0000000
--- a/src/plugins/ffmpeg/libavformat/bfi.c
+++ /dev/null
@@ -1,167 +0,0 @@
1/*
2 * Brute Force & Ignorance (BFI) demuxer
3 * Copyright (c) 2008 Sisir Koppaka
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/**
23 * @file bfi.c
24 * @brief Brute Force & Ignorance (.bfi) file demuxer
25 * @author Sisir Koppaka ( sisir.koppaka at gmail dot com )
26 * @sa http://wiki.multimedia.cx/index.php?title=BFI
27 */
28
29#include "avformat.h"
30
31typedef struct BFIContext {
32 int nframes;
33 int audio_frame;
34 int video_frame;
35 int video_size;
36 int avflag;
37} BFIContext;
38
39static int bfi_probe(AVProbeData * p)
40{
41 /* Check file header */
42 if (AV_RL32(p->buf) == MKTAG('B', 'F', '&', 'I'))
43 return AVPROBE_SCORE_MAX;
44 else
45 return 0;
46}
47
48static int bfi_read_header(AVFormatContext * s, AVFormatParameters * ap)
49{
50 BFIContext *bfi = s->priv_data;
51 ByteIOContext *pb = s->pb;
52 AVStream *vstream;
53 AVStream *astream;
54 int fps, chunk_header;
55
56 /* Initialize the video codec... */
57 vstream = av_new_stream(s, 0);
58 if (!vstream)
59 return AVERROR(ENOMEM);
60
61 /* Initialize the audio codec... */
62 astream = av_new_stream(s, 0);
63 if (!astream)
64 return AVERROR(ENOMEM);
65
66 /* Set the total number of frames. */
67 url_fskip(pb, 8);
68 chunk_header = get_le32(pb);
69 bfi->nframes = get_le32(pb);
70 get_le32(pb);
71 get_le32(pb);
72 get_le32(pb);
73 fps = get_le32(pb);
74 url_fskip(pb, 12);
75 vstream->codec->width = get_le32(pb);
76 vstream->codec->height = get_le32(pb);
77
78 /*Load the palette to extradata */
79 url_fskip(pb, 8);
80 vstream->codec->extradata = av_malloc(768);
81 vstream->codec->extradata_size = 768;
82 get_buffer(pb, vstream->codec->extradata,
83 vstream->codec->extradata_size);
84
85 astream->codec->sample_rate = get_le32(pb);
86
87 /* Set up the video codec... */
88 av_set_pts_info(vstream, 32, 1, fps);
89 vstream->codec->codec_type = CODEC_TYPE_VIDEO;
90 vstream->codec->codec_id = CODEC_ID_BFI;
91 vstream->codec->pix_fmt = PIX_FMT_PAL8;
92
93 /* Set up the audio codec now... */
94 astream->codec->codec_type = CODEC_TYPE_AUDIO;
95 astream->codec->codec_id = CODEC_ID_PCM_U8;
96 astream->codec->channels = 1;
97 astream->codec->bits_per_sample = 8;
98 astream->codec->bit_rate =
99 astream->codec->sample_rate * astream->codec->bits_per_sample;
100 url_fseek(pb, chunk_header - 3, SEEK_SET);
101 av_set_pts_info(astream, 64, 1, astream->codec->sample_rate);
102 return 0;
103}
104
105
106static int bfi_read_packet(AVFormatContext * s, AVPacket * pkt)
107{
108 BFIContext *bfi = s->priv_data;
109 ByteIOContext *pb = s->pb;
110 int ret, audio_offset, video_offset, chunk_size, audio_size = 0;
111 if (bfi->nframes == 0 || url_feof(pb)) {
112 return AVERROR(EIO);
113 }
114
115 /* If all previous chunks were completely read, then find a new one... */
116 if (!bfi->avflag) {
117 uint32_t state = 0;
118 while(state != MKTAG('S','A','V','I')){
119 if (url_feof(pb))
120 return AVERROR(EIO);
121 state = 256*state + get_byte(pb);
122 }
123 /* Now that the chunk's location is confirmed, we proceed... */
124 chunk_size = get_le32(pb);
125 get_le32(pb);
126 audio_offset = get_le32(pb);
127 get_le32(pb);
128 video_offset = get_le32(pb);
129 audio_size = video_offset - audio_offset;
130 bfi->video_size = chunk_size - video_offset;
131
132 //Tossing an audio packet at the audio decoder.
133 ret = av_get_packet(pb, pkt, audio_size);
134 if (ret < 0)
135 return ret;
136
137 pkt->pts = bfi->audio_frame;
138 bfi->audio_frame += ret;
139 }
140
141 else {
142
143 //Tossing a video packet at the video decoder.
144 ret = av_get_packet(pb, pkt, bfi->video_size);
145 if (ret < 0)
146 return ret;
147
148 pkt->pts = bfi->video_frame;
149 bfi->video_frame += ret / bfi->video_size;
150
151 /* One less frame to read. A cursory decrement. */
152 bfi->nframes--;
153 }
154
155 bfi->avflag = !bfi->avflag;
156 pkt->stream_index = bfi->avflag;
157 return ret;
158}
159
160AVInputFormat bfi_demuxer = {
161 "bfi",
162 NULL_IF_CONFIG_SMALL("Brute Force & Ignorance"),
163 sizeof(BFIContext),
164 bfi_probe,
165 bfi_read_header,
166 bfi_read_packet,
167};
diff --git a/src/plugins/ffmpeg/libavformat/c93.c b/src/plugins/ffmpeg/libavformat/c93.c
deleted file mode 100644
index be1577b..0000000
--- a/src/plugins/ffmpeg/libavformat/c93.c
+++ /dev/null
@@ -1,198 +0,0 @@
1/*
2 * Interplay C93 demuxer
3 * Copyright (c) 2007 Anssi Hannula <anssi.hannula@gmail.com>
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 "avformat.h"
23#include "voc.h"
24
25typedef struct {
26 uint16_t index;
27 uint8_t length;
28 uint8_t frames;
29} C93BlockRecord;
30
31typedef struct {
32 voc_dec_context_t voc;
33
34 C93BlockRecord block_records[512];
35 int current_block;
36
37 uint32_t frame_offsets[32];
38 int current_frame;
39 int next_pkt_is_audio;
40
41 AVStream *audio;
42} C93DemuxContext;
43
44static int probe(AVProbeData *p)
45{
46 if (p->buf[0] == 0x01 && p->buf[1] == 0x00 &&
47 p->buf[4] == 0x01 + p->buf[2] &&
48 p->buf[8] == p->buf[4] + p->buf[6] &&
49 p->buf[12] == p->buf[8] + p->buf[10])
50 return AVPROBE_SCORE_MAX;
51
52 return 0;
53}
54
55static int read_header(AVFormatContext *s,
56 AVFormatParameters *ap)
57{
58 AVStream *video;
59 ByteIOContext *pb = s->pb;
60 C93DemuxContext *c93 = s->priv_data;
61 int i;
62 int framecount = 0;
63
64 for (i = 0; i < 512; i++) {
65 c93->block_records[i].index = get_le16(pb);
66 c93->block_records[i].length = get_byte(pb);
67 c93->block_records[i].frames = get_byte(pb);
68 if (c93->block_records[i].frames > 32) {
69 av_log(s, AV_LOG_ERROR, "too many frames in block\n");
70 return AVERROR_INVALIDDATA;
71 }
72 framecount += c93->block_records[i].frames;
73 }
74
75 /* Audio streams are added if audio packets are found */
76 s->ctx_flags |= AVFMTCTX_NOHEADER;
77
78 video = av_new_stream(s, 0);
79 if (!video)
80 return AVERROR(ENOMEM);
81
82 video->codec->codec_type = CODEC_TYPE_VIDEO;
83 video->codec->codec_id = CODEC_ID_C93;
84 video->codec->width = 320;
85 video->codec->height = 192;
86 /* 4:3 320x200 with 8 empty lines */
87 video->codec->sample_aspect_ratio = (AVRational) { 5, 6 };
88 video->time_base = (AVRational) { 2, 25 };
89 video->nb_frames = framecount;
90 video->duration = framecount;
91 video->start_time = 0;
92
93 c93->current_block = 0;
94 c93->current_frame = 0;
95 c93->next_pkt_is_audio = 0;
96 return 0;
97}
98
99#define C93_HAS_PALETTE 0x01
100#define C93_FIRST_FRAME 0x02
101
102static int read_packet(AVFormatContext *s, AVPacket *pkt)
103{
104 ByteIOContext *pb = s->pb;
105 C93DemuxContext *c93 = s->priv_data;
106 C93BlockRecord *br = &c93->block_records[c93->current_block];
107 int datasize;
108 int ret, i;
109
110 if (c93->next_pkt_is_audio) {
111 c93->current_frame++;
112 c93->next_pkt_is_audio = 0;
113 datasize = get_le16(pb);
114 if (datasize > 42) {
115 if (!c93->audio) {
116 c93->audio = av_new_stream(s, 1);
117 if (!c93->audio)
118 return AVERROR(ENOMEM);
119 c93->audio->codec->codec_type = CODEC_TYPE_AUDIO;
120 }
121 url_fskip(pb, 26); /* VOC header */
122 ret = voc_get_packet(s, pkt, c93->audio, datasize - 26);
123 if (ret > 0) {
124 pkt->stream_index = 1;
125 pkt->flags |= PKT_FLAG_KEY;
126 return ret;
127 }
128 }
129 }
130 if (c93->current_frame >= br->frames) {
131 if (c93->current_block >= 511 || !br[1].length)
132 return AVERROR(EIO);
133 br++;
134 c93->current_block++;
135 c93->current_frame = 0;
136 }
137
138 if (c93->current_frame == 0) {
139 url_fseek(pb, br->index * 2048, SEEK_SET);
140 for (i = 0; i < 32; i++) {
141 c93->frame_offsets[i] = get_le32(pb);
142 }
143 }
144
145 url_fseek(pb,br->index * 2048 +
146 c93->frame_offsets[c93->current_frame], SEEK_SET);
147 datasize = get_le16(pb); /* video frame size */
148
149 ret = av_new_packet(pkt, datasize + 768 + 1);
150 if (ret < 0)
151 return ret;
152 pkt->data[0] = 0;
153 pkt->size = datasize + 1;
154
155 ret = get_buffer(pb, pkt->data + 1, datasize);
156 if (ret < datasize) {
157 ret = AVERROR(EIO);
158 goto fail;
159 }
160
161 datasize = get_le16(pb); /* palette size */
162 if (datasize) {
163 if (datasize != 768) {
164 av_log(s, AV_LOG_ERROR, "invalid palette size %u\n", datasize);
165 ret = AVERROR_INVALIDDATA;
166 goto fail;
167 }
168 pkt->data[0] |= C93_HAS_PALETTE;
169 ret = get_buffer(pb, pkt->data + pkt->size, datasize);
170 if (ret < datasize) {
171 ret = AVERROR(EIO);
172 goto fail;
173 }
174 pkt->size += 768;
175 }
176 pkt->stream_index = 0;
177 c93->next_pkt_is_audio = 1;
178
179 /* only the first frame is guaranteed to not reference previous frames */
180 if (c93->current_block == 0 && c93->current_frame == 0) {
181 pkt->flags |= PKT_FLAG_KEY;
182 pkt->data[0] |= C93_FIRST_FRAME;
183 }
184 return 0;
185
186 fail:
187 av_free_packet(pkt);
188 return ret;
189}
190
191AVInputFormat c93_demuxer = {
192 "c93",
193 NULL_IF_CONFIG_SMALL("Interplay C93"),
194 sizeof(C93DemuxContext),
195 probe,
196 read_header,
197 read_packet,
198};
diff --git a/src/plugins/ffmpeg/libavformat/crcenc.c b/src/plugins/ffmpeg/libavformat/crcenc.c
deleted file mode 100644
index a709c95..0000000
--- a/src/plugins/ffmpeg/libavformat/crcenc.c
+++ /dev/null
@@ -1,68 +0,0 @@
1/*
2 * CRC encoder (for codec/format testing)
3 * Copyright (c) 2002 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/adler32.h"
23#include "avformat.h"
24
25typedef struct CRCState {
26 uint32_t crcval;
27} CRCState;
28
29static int crc_write_header(struct AVFormatContext *s)
30{
31 CRCState *crc = s->priv_data;
32
33 /* init CRC */
34 crc->crcval = 1;
35
36 return 0;
37}
38
39static int crc_write_packet(struct AVFormatContext *s, AVPacket *pkt)
40{
41 CRCState *crc = s->priv_data;
42 crc->crcval = av_adler32_update(crc->crcval, pkt->data, pkt->size);
43 return 0;
44}
45
46static int crc_write_trailer(struct AVFormatContext *s)
47{
48 CRCState *crc = s->priv_data;
49 char buf[64];
50
51 snprintf(buf, sizeof(buf), "CRC=0x%08x\n", crc->crcval);
52 put_buffer(s->pb, buf, strlen(buf));
53 put_flush_packet(s->pb);
54 return 0;
55}
56
57AVOutputFormat crc_muxer = {
58 "crc",
59 NULL_IF_CONFIG_SMALL("CRC testing format"),
60 NULL,
61 "",
62 sizeof(CRCState),
63 CODEC_ID_PCM_S16LE,
64 CODEC_ID_RAWVIDEO,
65 crc_write_header,
66 crc_write_packet,
67 crc_write_trailer,
68};
diff --git a/src/plugins/ffmpeg/libavformat/cutils.c b/src/plugins/ffmpeg/libavformat/cutils.c
deleted file mode 100644
index 42ef599..0000000
--- a/src/plugins/ffmpeg/libavformat/cutils.c
+++ /dev/null
@@ -1,186 +0,0 @@
1/*
2 * Various simple utilities for ffmpeg system
3 * Copyright (c) 2000, 2001, 2002 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#include "avformat.h"
22
23/* add one element to a dynamic array */
24void ff_dynarray_add(unsigned long **tab_ptr, int *nb_ptr, unsigned long elem)
25{
26 int nb, nb_alloc;
27 unsigned long *tab;
28
29 nb = *nb_ptr;
30 tab = *tab_ptr;
31 if ((nb & (nb - 1)) == 0) {
32 if (nb == 0)
33 nb_alloc = 1;
34 else
35 nb_alloc = nb * 2;
36 tab = av_realloc(tab, nb_alloc * sizeof(unsigned long));
37 *tab_ptr = tab;
38 }
39 tab[nb++] = elem;
40 *nb_ptr = nb;
41}
42
43time_t mktimegm(struct tm *tm)
44{
45 time_t t;
46
47 int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
48
49 if (m < 3) {
50 m += 12;
51 y--;
52 }
53
54 t = 86400 *
55 (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 719469);
56
57 t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
58
59 return t;
60}
61
62#define ISLEAP(y) (((y) % 4 == 0) && (((y) % 100) != 0 || ((y) % 400) == 0))
63#define LEAPS_COUNT(y) ((y)/4 - (y)/100 + (y)/400)
64
65/* This is our own gmtime_r. It differs from its POSIX counterpart in a
66 couple of places, though. */
67struct tm *brktimegm(time_t secs, struct tm *tm)
68{
69 int days, y, ny, m;
70 int md[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
71
72 days = secs / 86400;
73 secs %= 86400;
74 tm->tm_hour = secs / 3600;
75 tm->tm_min = (secs % 3600) / 60;
76 tm->tm_sec = secs % 60;
77
78 /* oh well, may be someone some day will invent a formula for this stuff */
79 y = 1970; /* start "guessing" */
80 while (days > 365) {
81 ny = (y + days/366);
82 days -= (ny - y) * 365 + LEAPS_COUNT(ny - 1) - LEAPS_COUNT(y - 1);
83 y = ny;
84 }
85 if (days==365 && !ISLEAP(y)) { days=0; y++; }
86 md[1] = ISLEAP(y)?29:28;
87 for (m=0; days >= md[m]; m++)
88 days -= md[m];
89
90 tm->tm_year = y; /* unlike gmtime_r we store complete year here */
91 tm->tm_mon = m+1; /* unlike gmtime_r tm_mon is from 1 to 12 */
92 tm->tm_mday = days+1;
93
94 return tm;
95}
96
97/* get a positive number between n_min and n_max, for a maximum length
98 of len_max. Return -1 if error. */
99static int date_get_num(const char **pp,
100 int n_min, int n_max, int len_max)
101{
102 int i, val, c;
103 const char *p;
104
105 p = *pp;
106 val = 0;
107 for(i = 0; i < len_max; i++) {
108 c = *p;
109 if (!isdigit(c))
110 break;
111 val = (val * 10) + c - '0';
112 p++;
113 }
114 /* no number read ? */
115 if (p == *pp)
116 return -1;
117 if (val < n_min || val > n_max)
118 return -1;
119 *pp = p;
120 return val;
121}
122
123/* small strptime for ffmpeg */
124const char *small_strptime(const char *p, const char *fmt,
125 struct tm *dt)
126{
127 int c, val;
128
129 for(;;) {
130 c = *fmt++;
131 if (c == '\0') {
132 return p;
133 } else if (c == '%') {
134 c = *fmt++;
135 switch(c) {
136 case 'H':
137 val = date_get_num(&p, 0, 23, 2);
138 if (val == -1)
139 return NULL;
140 dt->tm_hour = val;
141 break;
142 case 'M':
143 val = date_get_num(&p, 0, 59, 2);
144 if (val == -1)
145 return NULL;
146 dt->tm_min = val;
147 break;
148 case 'S':
149 val = date_get_num(&p, 0, 59, 2);
150 if (val == -1)
151 return NULL;
152 dt->tm_sec = val;
153 break;
154 case 'Y':
155 val = date_get_num(&p, 0, 9999, 4);
156 if (val == -1)
157 return NULL;
158 dt->tm_year = val - 1900;
159 break;
160 case 'm':
161 val = date_get_num(&p, 1, 12, 2);
162 if (val == -1)
163 return NULL;
164 dt->tm_mon = val - 1;
165 break;
166 case 'd':
167 val = date_get_num(&p, 1, 31, 2);
168 if (val == -1)
169 return NULL;
170 dt->tm_mday = val;
171 break;
172 case '%':
173 goto match;
174 default:
175 return NULL;
176 }
177 } else {
178 match:
179 if (c != *p)
180 return NULL;
181 p++;
182 }
183 }
184 return p;
185}
186
diff --git a/src/plugins/ffmpeg/libavformat/daud.c b/src/plugins/ffmpeg/libavformat/daud.c
deleted file mode 100644
index 5f04e7a..0000000
--- a/src/plugins/ffmpeg/libavformat/daud.c
+++ /dev/null
@@ -1,60 +0,0 @@
1/*
2 * D-Cinema audio demuxer
3 * Copyright (c) 2005 Reimar Döffinger
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#include "avformat.h"
22
23static int daud_header(AVFormatContext *s, AVFormatParameters *ap) {
24 AVStream *st = av_new_stream(s, 0);
25 if (!st)
26 return AVERROR(ENOMEM);
27 st->codec->codec_type = CODEC_TYPE_AUDIO;
28 st->codec->codec_id = CODEC_ID_PCM_S24DAUD;
29 st->codec->codec_tag = MKTAG('d', 'a', 'u', 'd');
30 st->codec->channels = 6;
31 st->codec->sample_rate = 96000;
32 st->codec->bit_rate = 3 * 6 * 96000 * 8;
33 st->codec->block_align = 3 * 6;
34 st->codec->bits_per_sample = 24;
35 return 0;
36}
37
38static int daud_packet(AVFormatContext *s, AVPacket *pkt) {
39 ByteIOContext *pb = s->pb;
40 int ret, size;
41 if (url_feof(pb))
42 return AVERROR(EIO);
43 size = get_be16(pb);
44 get_be16(pb); // unknown
45 ret = av_get_packet(pb, pkt, size);
46 pkt->stream_index = 0;
47 return ret;
48}
49
50AVInputFormat daud_demuxer = {
51 "daud",
52 NULL_IF_CONFIG_SMALL("D-Cinema audio format"),
53 0,
54 NULL,
55 daud_header,
56 daud_packet,
57 NULL,
58 NULL,
59 .extensions = "302",
60};
diff --git a/src/plugins/ffmpeg/libavformat/dsicin.c b/src/plugins/ffmpeg/libavformat/dsicin.c
deleted file mode 100644
index eef205c..0000000
--- a/src/plugins/ffmpeg/libavformat/dsicin.c
+++ /dev/null
@@ -1,221 +0,0 @@
1/*
2 * Delphine Software International CIN File Demuxer
3 * Copyright (c) 2006 Gregory Montoir (cyx@users.sourceforge.net)
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/**
23 * @file dsicin.c
24 * Delphine Software International CIN file demuxer
25 */
26
27#include "avformat.h"
28
29
30typedef struct CinFileHeader {
31 int video_frame_size;
32 int video_frame_width;
33 int video_frame_height;
34 int audio_frequency;
35 int audio_bits;
36 int audio_stereo;
37 int audio_frame_size;
38} CinFileHeader;
39
40typedef struct CinFrameHeader {
41 int audio_frame_type;
42 int video_frame_type;
43 int pal_colors_count;
44 int audio_frame_size;
45 int video_frame_size;
46} CinFrameHeader;
47
48typedef struct CinDemuxContext {
49 int audio_stream_index;
50 int video_stream_index;
51 CinFileHeader file_header;
52 int64_t audio_stream_pts;
53 int64_t video_stream_pts;
54 CinFrameHeader frame_header;
55 int audio_buffer_size;
56} CinDemuxContext;
57
58
59static int cin_probe(AVProbeData *p)
60{
61 /* header starts with this special marker */
62 if (AV_RL32(&p->buf[0]) != 0x55AA0000)
63 return 0;
64
65 /* for accuracy, check some header field values */
66 if (AV_RL32(&p->buf[12]) != 22050 || p->buf[16] != 16 || p->buf[17] != 0)
67 return 0;
68
69 return AVPROBE_SCORE_MAX;
70}
71
72static int cin_read_file_header(CinDemuxContext *cin, ByteIOContext *pb) {
73 CinFileHeader *hdr = &cin->file_header;
74
75 if (get_le32(pb) != 0x55AA0000)
76 return AVERROR_INVALIDDATA;
77
78 hdr->video_frame_size = get_le32(pb);
79 hdr->video_frame_width = get_le16(pb);
80 hdr->video_frame_height = get_le16(pb);
81 hdr->audio_frequency = get_le32(pb);
82 hdr->audio_bits = get_byte(pb);
83 hdr->audio_stereo = get_byte(pb);
84 hdr->audio_frame_size = get_le16(pb);
85
86 if (hdr->audio_frequency != 22050 || hdr->audio_bits != 16 || hdr->audio_stereo != 0)
87 return AVERROR_INVALIDDATA;
88
89 return 0;
90}
91
92static int cin_read_header(AVFormatContext *s, AVFormatParameters *ap)
93{
94 int rc;
95 CinDemuxContext *cin = s->priv_data;
96 CinFileHeader *hdr = &cin->file_header;
97 ByteIOContext *pb = s->pb;
98 AVStream *st;
99
100 rc = cin_read_file_header(cin, pb);
101 if (rc)
102 return rc;
103
104 cin->video_stream_pts = 0;
105 cin->audio_stream_pts = 0;
106 cin->audio_buffer_size = 0;
107
108 /* initialize the video decoder stream */
109 st = av_new_stream(s, 0);
110 if (!st)
111 return AVERROR(ENOMEM);
112
113 av_set_pts_info(st, 32, 1, 12);
114 cin->video_stream_index = st->index;
115 st->codec->codec_type = CODEC_TYPE_VIDEO;
116 st->codec->codec_id = CODEC_ID_DSICINVIDEO;
117 st->codec->codec_tag = 0; /* no fourcc */
118 st->codec->width = hdr->video_frame_width;
119 st->codec->height = hdr->video_frame_height;
120
121 /* initialize the audio decoder stream */
122 st = av_new_stream(s, 0);
123 if (!st)
124 return AVERROR(ENOMEM);
125
126 av_set_pts_info(st, 32, 1, 22050);
127 cin->audio_stream_index = st->index;
128 st->codec->codec_type = CODEC_TYPE_AUDIO;
129 st->codec->codec_id = CODEC_ID_DSICINAUDIO;
130 st->codec->codec_tag = 0; /* no tag */
131 st->codec->channels = 1;
132 st->codec->sample_rate = 22050;
133 st->codec->bits_per_sample = 16;
134 st->codec->bit_rate = st->codec->sample_rate * st->codec->bits_per_sample * st->codec->channels;
135 st->codec->block_align = st->codec->channels * st->codec->bits_per_sample;
136
137 return 0;
138}
139
140static int cin_read_frame_header(CinDemuxContext *cin, ByteIOContext *pb) {
141 CinFrameHeader *hdr = &cin->frame_header;
142
143 hdr->video_frame_type = get_byte(pb);
144 hdr->audio_frame_type = get_byte(pb);
145 hdr->pal_colors_count = get_le16(pb);
146 hdr->video_frame_size = get_le32(pb);
147 hdr->audio_frame_size = get_le32(pb);
148
149 if (url_feof(pb) || url_ferror(pb))
150 return AVERROR(EIO);
151
152 if (get_le32(pb) != 0xAA55AA55)
153 return AVERROR_INVALIDDATA;
154
155 return 0;
156}
157
158static int cin_read_packet(AVFormatContext *s, AVPacket *pkt)
159{
160 CinDemuxContext *cin = s->priv_data;
161 ByteIOContext *pb = s->pb;
162 CinFrameHeader *hdr = &cin->frame_header;
163 int rc, palette_type, pkt_size;
164
165 if (cin->audio_buffer_size == 0) {
166 rc = cin_read_frame_header(cin, pb);
167 if (rc)
168 return rc;
169
170 if ((int16_t)hdr->pal_colors_count < 0) {
171 hdr->pal_colors_count = -(int16_t)hdr->pal_colors_count;
172 palette_type = 1;
173 } else {
174 palette_type = 0;
175 }
176
177 /* palette and video packet */
178 pkt_size = (palette_type + 3) * hdr->pal_colors_count + hdr->video_frame_size;
179
180 if (av_new_packet(pkt, 4 + pkt_size))
181 return AVERROR(ENOMEM);
182
183 pkt->stream_index = cin->video_stream_index;
184 pkt->pts = cin->video_stream_pts++;
185
186 pkt->data[0] = palette_type;
187 pkt->data[1] = hdr->pal_colors_count & 0xFF;
188 pkt->data[2] = hdr->pal_colors_count >> 8;
189 pkt->data[3] = hdr->video_frame_type;
190
191 if (get_buffer(pb, &pkt->data[4], pkt_size) != pkt_size)
192 return AVERROR(EIO);
193
194 /* sound buffer will be processed on next read_packet() call */
195 cin->audio_buffer_size = hdr->audio_frame_size;
196 return 0;
197 }
198
199 /* audio packet */
200 if (av_new_packet(pkt, cin->audio_buffer_size))
201 return AVERROR(ENOMEM);
202
203 pkt->stream_index = cin->audio_stream_index;
204 pkt->pts = cin->audio_stream_pts;
205 cin->audio_stream_pts += cin->audio_buffer_size * 2 / cin->file_header.audio_frame_size;
206
207 if (get_buffer(pb, pkt->data, cin->audio_buffer_size) != cin->audio_buffer_size)
208 return AVERROR(EIO);
209
210 cin->audio_buffer_size = 0;
211 return 0;
212}
213
214AVInputFormat dsicin_demuxer = {
215 "dsicin",
216 NULL_IF_CONFIG_SMALL("Delphine Software International CIN format"),
217 sizeof(CinDemuxContext),
218 cin_probe,
219 cin_read_header,
220 cin_read_packet,
221};
diff --git a/src/plugins/ffmpeg/libavformat/dv.c b/src/plugins/ffmpeg/libavformat/dv.c
deleted file mode 100644
index 2f91717..0000000
--- a/src/plugins/ffmpeg/libavformat/dv.c
+++ /dev/null
@@ -1,452 +0,0 @@
1/*
2 * General DV muxer/demuxer
3 * Copyright (c) 2003 Roman Shaposhnik
4 *
5 * Many thanks to Dan Dennedy <dan@dennedy.org> for providing wealth
6 * of DV technical info.
7 *
8 * Raw DV format
9 * Copyright (c) 2002 Fabrice Bellard.
10 *
11 * 50 Mbps (DVCPRO50) support
12 * Copyright (c) 2006 Daniel Maas <dmaas@maasdigital.com>
13 *
14 * This file is part of FFmpeg.
15 *
16 * FFmpeg is free software; you can redistribute it and/or
17 * modify it under the terms of the GNU Lesser General Public
18 * License as published by the Free Software Foundation; either
19 * version 2.1 of the License, or (at your option) any later version.
20 *
21 * FFmpeg is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24 * Lesser General Public License for more details.
25 *
26 * You should have received a copy of the GNU Lesser General Public
27 * License along with FFmpeg; if not, write to the Free Software
28 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 */
30#include <time.h>
31#include "avformat.h"
32#include "libavcodec/dvdata.h"
33#include "dv.h"
34
35struct DVDemuxContext {
36 const DVprofile* sys; /* Current DV profile. E.g.: 525/60, 625/50 */
37 AVFormatContext* fctx;
38 AVStream* vst;
39 AVStream* ast[2];
40 AVPacket audio_pkt[2];
41 uint8_t audio_buf[2][8192];
42 int ach;
43 int frames;
44 uint64_t abytes;
45};
46
47static inline uint16_t dv_audio_12to16(uint16_t sample)
48{
49 uint16_t shift, result;
50
51 sample = (sample < 0x800) ? sample : sample | 0xf000;
52 shift = (sample & 0xf00) >> 8;
53
54 if (shift < 0x2 || shift > 0xd) {
55 result = sample;
56 } else if (shift < 0x8) {
57 shift--;
58 result = (sample - (256 * shift)) << shift;
59 } else {
60 shift = 0xe - shift;
61 result = ((sample + ((256 * shift) + 1)) << shift) - 1;
62 }
63
64 return result;
65}
66
67/*
68 * This is the dumbest implementation of all -- it simply looks at
69 * a fixed offset and if pack isn't there -- fails. We might want
70 * to have a fallback mechanism for complete search of missing packs.
71 */
72static const uint8_t* dv_extract_pack(uint8_t* frame, enum dv_pack_type t)
73{
74 int offs;
75
76 switch (t) {
77 case dv_audio_source:
78 offs = (80*6 + 80*16*3 + 3);
79 break;
80 case dv_audio_control:
81 offs = (80*6 + 80*16*4 + 3);
82 break;
83 case dv_video_control:
84 offs = (80*5 + 48 + 5);
85 break;
86 default:
87 return NULL;
88 }
89
90 return frame[offs] == t ? &frame[offs] : NULL;
91}
92
93/*
94 * There's a couple of assumptions being made here:
95 * 1. By default we silence erroneous (0x8000/16bit 0x800/12bit) audio samples.
96 * We can pass them upwards when ffmpeg will be ready to deal with them.
97 * 2. We don't do software emphasis.
98 * 3. Audio is always returned as 16bit linear samples: 12bit nonlinear samples
99 * are converted into 16bit linear ones.
100 */
101static int dv_extract_audio(uint8_t* frame, uint8_t* pcm, uint8_t* pcm2,
102 const DVprofile *sys)
103{
104 int size, chan, i, j, d, of, smpls, freq, quant, half_ch;
105 uint16_t lc, rc;
106 const uint8_t* as_pack;
107
108 as_pack = dv_extract_pack(frame, dv_audio_source);
109 if (!as_pack) /* No audio ? */
110 return 0;
111
112 smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */
113 freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48KHz, 1 - 44,1kHz, 2 - 32 kHz */
114 quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */
115
116 if (quant > 1)
117 return -1; /* Unsupported quantization */
118
119 size = (sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */
120 half_ch = sys->difseg_size/2;
121
122 /* for each DIF channel */
123 for (chan = 0; chan < sys->n_difchan; chan++) {
124 /* for each DIF segment */
125 for (i = 0; i < sys->difseg_size; i++) {
126 frame += 6 * 80; /* skip DIF segment header */
127 if (quant == 1 && i == half_ch) {
128 /* next stereo channel (12bit mode only) */
129 if (!pcm2)
130 break;
131 else
132 pcm = pcm2;
133 }
134
135 /* for each AV sequence */
136 for (j = 0; j < 9; j++) {
137 for (d = 8; d < 80; d += 2) {
138 if (quant == 0) { /* 16bit quantization */
139 of = sys->audio_shuffle[i][j] + (d - 8)/2 * sys->audio_stride;
140 if (of*2 >= size)
141 continue;
142
143 pcm[of*2] = frame[d+1]; // FIXME: may be we have to admit
144 pcm[of*2+1] = frame[d]; // that DV is a big endian PCM
145 if (pcm[of*2+1] == 0x80 && pcm[of*2] == 0x00)
146 pcm[of*2+1] = 0;
147 } else { /* 12bit quantization */
148 lc = ((uint16_t)frame[d] << 4) |
149 ((uint16_t)frame[d+2] >> 4);
150 rc = ((uint16_t)frame[d+1] << 4) |
151 ((uint16_t)frame[d+2] & 0x0f);
152 lc = (lc == 0x800 ? 0 : dv_audio_12to16(lc));
153 rc = (rc == 0x800 ? 0 : dv_audio_12to16(rc));
154
155 of = sys->audio_shuffle[i%half_ch][j] + (d - 8)/3 * sys->audio_stride;
156 if (of*2 >= size)
157 continue;
158
159 pcm[of*2] = lc & 0xff; // FIXME: may be we have to admit
160 pcm[of*2+1] = lc >> 8; // that DV is a big endian PCM
161 of = sys->audio_shuffle[i%half_ch+half_ch][j] +
162 (d - 8)/3 * sys->audio_stride;
163 pcm[of*2] = rc & 0xff; // FIXME: may be we have to admit
164 pcm[of*2+1] = rc >> 8; // that DV is a big endian PCM
165 ++d;
166 }
167 }
168
169 frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */
170 }
171 }
172
173 /* next stereo channel (50Mbps only) */
174 if(!pcm2)
175 break;
176 pcm = pcm2;
177 }
178
179 return size;
180}
181
182static int dv_extract_audio_info(DVDemuxContext* c, uint8_t* frame)
183{
184 const uint8_t* as_pack;
185 int freq, stype, smpls, quant, i, ach;
186
187 as_pack = dv_extract_pack(frame, dv_audio_source);
188 if (!as_pack || !c->sys) { /* No audio ? */
189 c->ach = 0;
190 return 0;
191 }
192
193 smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */
194 freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48KHz, 1 - 44,1kHz, 2 - 32 kHz */
195 stype = (as_pack[3] & 0x1f); /* 0 - 2CH, 2 - 4CH */
196 quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */
197
198 /* note: ach counts PAIRS of channels (i.e. stereo channels) */
199 ach = (stype == 2 || (quant && (freq == 2))) ? 2 : 1;
200
201 /* Dynamic handling of the audio streams in DV */
202 for (i=0; i<ach; i++) {
203 if (!c->ast[i]) {
204 c->ast[i] = av_new_stream(c->fctx, 0);
205 if (!c->ast[i])
206 break;
207 av_set_pts_info(c->ast[i], 64, 1, 30000);
208 c->ast[i]->codec->codec_type = CODEC_TYPE_AUDIO;
209 c->ast[i]->codec->codec_id = CODEC_ID_PCM_S16LE;
210
211 av_init_packet(&c->audio_pkt[i]);
212 c->audio_pkt[i].size = 0;
213 c->audio_pkt[i].data = c->audio_buf[i];
214 c->audio_pkt[i].stream_index = c->ast[i]->index;
215 c->audio_pkt[i].flags |= PKT_FLAG_KEY;
216 }
217 c->ast[i]->codec->sample_rate = dv_audio_frequency[freq];
218 c->ast[i]->codec->channels = 2;
219 c->ast[i]->codec->bit_rate = 2 * dv_audio_frequency[freq] * 16;
220 c->ast[i]->start_time = 0;
221 }
222 c->ach = i;
223
224 return (c->sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */;
225}
226
227static int dv_extract_video_info(DVDemuxContext *c, uint8_t* frame)
228{
229 const uint8_t* vsc_pack;
230 AVCodecContext* avctx;
231 int apt, is16_9;
232 int size = 0;
233
234 if (c->sys) {
235 avctx = c->vst->codec;
236
237 av_set_pts_info(c->vst, 64, c->sys->frame_rate_base, c->sys->frame_rate);
238 avctx->time_base= (AVRational){c->sys->frame_rate_base, c->sys->frame_rate};
239 if(!avctx->width){
240 avctx->width = c->sys->width;
241 avctx->height = c->sys->height;
242 }
243 avctx->pix_fmt = c->sys->pix_fmt;
244
245 /* finding out SAR is a little bit messy */
246 vsc_pack = dv_extract_pack(frame, dv_video_control);
247 apt = frame[4] & 0x07;
248 is16_9 = (vsc_pack && ((vsc_pack[2] & 0x07) == 0x02 ||
249 (!apt && (vsc_pack[2] & 0x07) == 0x07)));
250 avctx->sample_aspect_ratio = c->sys->sar[is16_9];
251 avctx->bit_rate = av_rescale(c->sys->frame_size * 8,
252 c->sys->frame_rate,
253 c->sys->frame_rate_base);
254 size = c->sys->frame_size;
255 }
256 return size;
257}
258
259/*
260 * The following 3 functions constitute our interface to the world
261 */
262
263DVDemuxContext* dv_init_demux(AVFormatContext *s)
264{
265 DVDemuxContext *c;
266
267 c = av_mallocz(sizeof(DVDemuxContext));
268 if (!c)
269 return NULL;
270
271 c->vst = av_new_stream(s, 0);
272 if (!c->vst) {
273 av_free(c);
274 return NULL;
275 }
276
277 c->sys = NULL;
278 c->fctx = s;
279 c->ast[0] = c->ast[1] = NULL;
280 c->ach = 0;
281 c->frames = 0;
282 c->abytes = 0;
283
284 c->vst->codec->codec_type = CODEC_TYPE_VIDEO;
285 c->vst->codec->codec_id = CODEC_ID_DVVIDEO;
286 c->vst->codec->bit_rate = 25000000;
287 c->vst->start_time = 0;
288
289 return c;
290}
291
292int dv_get_packet(DVDemuxContext *c, AVPacket *pkt)
293{
294 int size = -1;
295 int i;
296
297 for (i=0; i<c->ach; i++) {
298 if (c->ast[i] && c->audio_pkt[i].size) {
299 *pkt = c->audio_pkt[i];
300 c->audio_pkt[i].size = 0;
301 size = pkt->size;
302 break;
303 }
304 }
305
306 return size;
307}
308
309int dv_produce_packet(DVDemuxContext *c, AVPacket *pkt,
310 uint8_t* buf, int buf_size)
311{
312 int size, i;
313
314 if (buf_size < DV_PROFILE_BYTES ||
315 !(c->sys = dv_frame_profile(buf)) ||
316 buf_size < c->sys->frame_size) {
317 return -1; /* Broken frame, or not enough data */
318 }
319
320 /* Queueing audio packet */
321 /* FIXME: in case of no audio/bad audio we have to do something */
322 size = dv_extract_audio_info(c, buf);
323 for (i=0; i<c->ach; i++) {
324 c->audio_pkt[i].size = size;
325 c->audio_pkt[i].pts = c->abytes * 30000*8 / c->ast[i]->codec->bit_rate;
326 }
327 dv_extract_audio(buf, c->audio_buf[0], c->audio_buf[1], c->sys);
328 c->abytes += size;
329
330 /* Now it's time to return video packet */
331 size = dv_extract_video_info(c, buf);
332 av_init_packet(pkt);
333 pkt->data = buf;
334 pkt->size = size;
335 pkt->flags |= PKT_FLAG_KEY;
336 pkt->stream_index = c->vst->id;
337 pkt->pts = c->frames;
338
339 c->frames++;
340
341 return size;
342}
343
344static int64_t dv_frame_offset(AVFormatContext *s, DVDemuxContext *c,
345 int64_t timestamp, int flags)
346{
347 // FIXME: sys may be wrong if last dv_read_packet() failed (buffer is junk)
348 const DVprofile* sys = dv_codec_profile(c->vst->codec);
349 int64_t offset;
350 int64_t size = url_fsize(s->pb);
351 int64_t max_offset = ((size-1) / sys->frame_size) * sys->frame_size;
352
353 offset = sys->frame_size * timestamp;
354
355 if (offset > max_offset) offset = max_offset;
356 else if (offset < 0) offset = 0;
357
358 return offset;
359}
360
361void dv_offset_reset(DVDemuxContext *c, int64_t frame_offset)
362{
363 c->frames= frame_offset;
364 if (c->ach)
365 c->abytes= av_rescale(c->frames,
366 c->ast[0]->codec->bit_rate * (int64_t)c->sys->frame_rate_base,
367 8*c->sys->frame_rate);
368 c->audio_pkt[0].size = c->audio_pkt[1].size = 0;
369}
370
371/************************************************************
372 * Implementation of the easiest DV storage of all -- raw DV.
373 ************************************************************/
374
375typedef struct RawDVContext {
376 DVDemuxContext* dv_demux;
377 uint8_t buf[DV_MAX_FRAME_SIZE];
378} RawDVContext;
379
380static int dv_read_header(AVFormatContext *s,
381 AVFormatParameters *ap)
382{
383 RawDVContext *c = s->priv_data;
384
385 c->dv_demux = dv_init_demux(s);
386 if (!c->dv_demux)
387 return -1;
388
389 if (get_buffer(s->pb, c->buf, DV_PROFILE_BYTES) <= 0 ||
390 url_fseek(s->pb, -DV_PROFILE_BYTES, SEEK_CUR) < 0)
391 return AVERROR(EIO);
392
393 c->dv_demux->sys = dv_frame_profile(c->buf);
394 s->bit_rate = av_rescale(c->dv_demux->sys->frame_size * 8,
395 c->dv_demux->sys->frame_rate,
396 c->dv_demux->sys->frame_rate_base);
397
398 return 0;
399}
400
401
402static int dv_read_packet(AVFormatContext *s, AVPacket *pkt)
403{
404 int size;
405 RawDVContext *c = s->priv_data;
406
407 size = dv_get_packet(c->dv_demux, pkt);
408
409 if (size < 0) {
410 size = c->dv_demux->sys->frame_size;
411 if (get_buffer(s->pb, c->buf, size) <= 0)
412 return AVERROR(EIO);
413
414 size = dv_produce_packet(c->dv_demux, pkt, c->buf, size);
415 }
416
417 return size;
418}
419
420static int dv_read_seek(AVFormatContext *s, int stream_index,
421 int64_t timestamp, int flags)
422{
423 RawDVContext *r = s->priv_data;
424 DVDemuxContext *c = r->dv_demux;
425 int64_t offset= dv_frame_offset(s, c, timestamp, flags);
426
427 dv_offset_reset(c, offset / c->sys->frame_size);
428
429 offset = url_fseek(s->pb, offset, SEEK_SET);
430 return (offset < 0)?offset:0;
431}
432
433static int dv_read_close(AVFormatContext *s)
434{
435 RawDVContext *c = s->priv_data;
436 av_free(c->dv_demux);
437 return 0;
438}
439
440#ifdef CONFIG_DV_DEMUXER
441AVInputFormat dv_demuxer = {
442 "dv",
443 NULL_IF_CONFIG_SMALL("DV video format"),
444 sizeof(RawDVContext),
445 NULL,
446 dv_read_header,
447 dv_read_packet,
448 dv_read_close,
449 dv_read_seek,
450 .extensions = "dv,dif",
451};
452#endif
diff --git a/src/plugins/ffmpeg/libavformat/dv.h b/src/plugins/ffmpeg/libavformat/dv.h
deleted file mode 100644
index cfe9353..0000000
--- a/src/plugins/ffmpeg/libavformat/dv.h
+++ /dev/null
@@ -1,44 +0,0 @@
1/*
2 * General DV muxer/demuxer
3 * Copyright (c) 2003 Roman Shaposhnik
4 *
5 * Many thanks to Dan Dennedy <dan@dennedy.org> for providing wealth
6 * of DV technical info.
7 *
8 * Raw DV format
9 * Copyright (c) 2002 Fabrice Bellard.
10 *
11 * This file is part of FFmpeg.
12 *
13 * FFmpeg is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU Lesser General Public
15 * License as published by the Free Software Foundation; either
16 * version 2.1 of the License, or (at your option) any later version.
17 *
18 * FFmpeg is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * Lesser General Public License for more details.
22 *
23 * You should have received a copy of the GNU Lesser General Public
24 * License along with FFmpeg; if not, write to the Free Software
25 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 */
27
28#ifndef FFMPEG_DV_H
29#define FFMPEG_DV_H
30
31#include "avformat.h"
32
33typedef struct DVDemuxContext DVDemuxContext;
34DVDemuxContext* dv_init_demux(AVFormatContext* s);
35int dv_get_packet(DVDemuxContext*, AVPacket *);
36int dv_produce_packet(DVDemuxContext*, AVPacket*, uint8_t*, int);
37void dv_offset_reset(DVDemuxContext *c, int64_t frame_offset);
38
39typedef struct DVMuxContext DVMuxContext;
40DVMuxContext* dv_init_mux(AVFormatContext* s);
41int dv_assemble_frame(DVMuxContext *c, AVStream*, const uint8_t*, int, uint8_t**);
42void dv_delete_mux(DVMuxContext*);
43
44#endif /* FFMPEG_DV_H */
diff --git a/src/plugins/ffmpeg/libavformat/dvenc.c b/src/plugins/ffmpeg/libavformat/dvenc.c
deleted file mode 100644
index 845b851..0000000
--- a/src/plugins/ffmpeg/libavformat/dvenc.c
+++ /dev/null
@@ -1,415 +0,0 @@
1/*
2 * General DV muxer/demuxer
3 * Copyright (c) 2003 Roman Shaposhnik
4 *
5 * Many thanks to Dan Dennedy <dan@dennedy.org> for providing wealth
6 * of DV technical info.
7 *
8 * Raw DV format
9 * Copyright (c) 2002 Fabrice Bellard.
10 *
11 * 50 Mbps (DVCPRO50) support
12 * Copyright (c) 2006 Daniel Maas <dmaas@maasdigital.com>
13 *
14 * This file is part of FFmpeg.
15 *
16 * FFmpeg is free software; you can redistribute it and/or
17 * modify it under the terms of the GNU Lesser General Public
18 * License as published by the Free Software Foundation; either
19 * version 2.1 of the License, or (at your option) any later version.
20 *
21 * FFmpeg is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24 * Lesser General Public License for more details.
25 *
26 * You should have received a copy of the GNU Lesser General Public
27 * License along with FFmpeg; if not, write to the Free Software
28 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 */
30#include <time.h>
31#include <stdarg.h>
32#include "avformat.h"
33#include "libavcodec/dvdata.h"
34#include "dv.h"
35#include "libavutil/fifo.h"
36
37struct DVMuxContext {
38 const DVprofile* sys; /* Current DV profile. E.g.: 525/60, 625/50 */
39 int n_ast; /* Number of stereo audio streams (up to 2) */
40 AVStream *ast[2]; /* Stereo audio streams */
41 AVFifoBuffer audio_data[2]; /* Fifo for storing excessive amounts of PCM */
42 int frames; /* Number of a current frame */
43 time_t start_time; /* Start time of recording */
44 int has_audio; /* frame under contruction has audio */
45 int has_video; /* frame under contruction has video */
46 uint8_t frame_buf[DV_MAX_FRAME_SIZE]; /* frame under contruction */
47};
48
49static const int dv_aaux_packs_dist[12][9] = {
50 { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
51 { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
52 { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
53 { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
54 { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
55 { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
56 { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
57 { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
58 { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
59 { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
60 { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
61 { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
62};
63
64static int dv_audio_frame_size(const DVprofile* sys, int frame)
65{
66 return sys->audio_samples_dist[frame % (sizeof(sys->audio_samples_dist)/
67 sizeof(sys->audio_samples_dist[0]))];
68}
69
70static int dv_write_pack(enum dv_pack_type pack_id, DVMuxContext *c, uint8_t* buf, ...)
71{
72 struct tm tc;
73 time_t ct;
74 int ltc_frame;
75 va_list ap;
76
77 buf[0] = (uint8_t)pack_id;
78 switch (pack_id) {
79 case dv_timecode:
80 ct = (time_t)(c->frames / ((float)c->sys->frame_rate /
81 (float)c->sys->frame_rate_base));
82 brktimegm(ct, &tc);
83 /*
84 * LTC drop-frame frame counter drops two frames (0 and 1) every
85 * minute, unless it is exactly divisible by 10
86 */
87 ltc_frame = (c->frames + 2*ct/60 - 2*ct/600) % c->sys->ltc_divisor;
88 buf[1] = (0 << 7) | /* Color fame: 0 - unsync; 1 - sync mode */
89 (1 << 6) | /* Drop frame timecode: 0 - nondrop; 1 - drop */
90 ((ltc_frame / 10) << 4) | /* Tens of frames */
91 (ltc_frame % 10); /* Units of frames */
92 buf[2] = (1 << 7) | /* Biphase mark polarity correction: 0 - even; 1 - odd */
93 ((tc.tm_sec / 10) << 4) | /* Tens of seconds */
94 (tc.tm_sec % 10); /* Units of seconds */
95 buf[3] = (1 << 7) | /* Binary group flag BGF0 */
96 ((tc.tm_min / 10) << 4) | /* Tens of minutes */
97 (tc.tm_min % 10); /* Units of minutes */
98 buf[4] = (1 << 7) | /* Binary group flag BGF2 */
99 (1 << 6) | /* Binary group flag BGF1 */
100 ((tc.tm_hour / 10) << 4) | /* Tens of hours */
101 (tc.tm_hour % 10); /* Units of hours */
102 break;
103 case dv_audio_source: /* AAUX source pack */
104 va_start(ap, buf);
105 buf[1] = (1 << 7) | /* locked mode -- SMPTE only supports locked mode */
106 (1 << 6) | /* reserved -- always 1 */
107 (dv_audio_frame_size(c->sys, c->frames) -
108 c->sys->audio_min_samples[0]);
109 /* # of samples */
110 buf[2] = (0 << 7) | /* multi-stereo */
111 (0 << 5) | /* #of audio channels per block: 0 -- 1 channel */
112 (0 << 4) | /* pair bit: 0 -- one pair of channels */
113 !!va_arg(ap, int); /* audio mode */
114 buf[3] = (1 << 7) | /* res */
115 (1 << 6) | /* multi-language flag */
116 (c->sys->dsf << 5) | /* system: 60fields/50fields */
117 (c->sys->n_difchan & 2); /* definition: 0 -- 25Mbps, 2 -- 50Mbps */
118 buf[4] = (1 << 7) | /* emphasis: 1 -- off */
119 (0 << 6) | /* emphasis time constant: 0 -- reserved */
120 (0 << 3) | /* frequency: 0 -- 48Khz, 1 -- 44,1Khz, 2 -- 32Khz */
121 0; /* quantization: 0 -- 16bit linear, 1 -- 12bit nonlinear */
122 va_end(ap);
123 break;
124 case dv_audio_control:
125 buf[1] = (0 << 6) | /* copy protection: 0 -- unrestricted */
126 (1 << 4) | /* input source: 1 -- digital input */
127 (3 << 2) | /* compression: 3 -- no information */
128 0; /* misc. info/SMPTE emphasis off */
129 buf[2] = (1 << 7) | /* recording start point: 1 -- no */
130 (1 << 6) | /* recording end point: 1 -- no */
131 (1 << 3) | /* recording mode: 1 -- original */
132 7;
133 buf[3] = (1 << 7) | /* direction: 1 -- forward */
134 (c->sys->pix_fmt == PIX_FMT_YUV420P ? 0x20 : /* speed */
135 c->sys->ltc_divisor*4);
136 buf[4] = (1 << 7) | /* reserved -- always 1 */
137 0x7f; /* genre category */
138 break;
139 case dv_audio_recdate:
140 case dv_video_recdate: /* VAUX recording date */
141 ct = c->start_time + (time_t)(c->frames /
142 ((float)c->sys->frame_rate / (float)c->sys->frame_rate_base));
143 brktimegm(ct, &tc);
144 buf[1] = 0xff; /* ds, tm, tens of time zone, units of time zone */
145 /* 0xff is very likely to be "unknown" */
146 buf[2] = (3 << 6) | /* reserved -- always 1 */
147 ((tc.tm_mday / 10) << 4) | /* Tens of day */
148 (tc.tm_mday % 10); /* Units of day */
149 buf[3] = /* we set high 4 bits to 0, shouldn't we set them to week? */
150 ((tc.tm_mon / 10) << 4) | /* Tens of month */
151 (tc.tm_mon % 10); /* Units of month */
152 buf[4] = (((tc.tm_year % 100) / 10) << 4) | /* Tens of year */
153 (tc.tm_year % 10); /* Units of year */
154 break;
155 case dv_audio_rectime: /* AAUX recording time */
156 case dv_video_rectime: /* VAUX recording time */
157 ct = c->start_time + (time_t)(c->frames /
158 ((float)c->sys->frame_rate / (float)c->sys->frame_rate_base));
159 brktimegm(ct, &tc);
160 buf[1] = (3 << 6) | /* reserved -- always 1 */
161 0x3f; /* tens of frame, units of frame: 0x3f - "unknown" ? */
162 buf[2] = (1 << 7) | /* reserved -- always 1 */
163 ((tc.tm_sec / 10) << 4) | /* Tens of seconds */
164 (tc.tm_sec % 10); /* Units of seconds */
165 buf[3] = (1 << 7) | /* reserved -- always 1 */
166 ((tc.tm_min / 10) << 4) | /* Tens of minutes */
167 (tc.tm_min % 10); /* Units of minutes */
168 buf[4] = (3 << 6) | /* reserved -- always 1 */
169 ((tc.tm_hour / 10) << 4) | /* Tens of hours */
170 (tc.tm_hour % 10); /* Units of hours */
171 break;
172 default:
173 buf[1] = buf[2] = buf[3] = buf[4] = 0xff;
174 }
175 return 5;
176}
177
178static void dv_inject_audio(DVMuxContext *c, int channel, uint8_t* frame_ptr)
179{
180 int i, j, d, of, size;
181 size = 4 * dv_audio_frame_size(c->sys, c->frames);
182 frame_ptr += channel * c->sys->difseg_size * 150 * 80;
183 for (i = 0; i < c->sys->difseg_size; i++) {
184 frame_ptr += 6 * 80; /* skip DIF segment header */
185 for (j = 0; j < 9; j++) {
186 dv_write_pack(dv_aaux_packs_dist[i][j], c, &frame_ptr[3], i >= c->sys->difseg_size/2);
187 for (d = 8; d < 80; d+=2) {
188 of = c->sys->audio_shuffle[i][j] + (d - 8)/2 * c->sys->audio_stride;
189 if (of*2 >= size)
190 continue;
191
192 frame_ptr[d] = av_fifo_peek(&c->audio_data[channel], of*2+1); // FIXME: may be we have to admit
193 frame_ptr[d+1] = av_fifo_peek(&c->audio_data[channel], of*2); // that DV is a big endian PCM
194 }
195 frame_ptr += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */
196 }
197 }
198}
199
200static void dv_inject_metadata(DVMuxContext *c, uint8_t* frame)
201{
202 int j, k;
203 uint8_t* buf;
204
205 for (buf = frame; buf < frame + c->sys->frame_size; buf += 150 * 80) {
206 /* DV subcode: 2nd and 3d DIFs */
207 for (j = 80; j < 80 * 3; j += 80) {
208 for (k = 6; k < 6 * 8; k += 8)
209 dv_write_pack(dv_timecode, c, &buf[j+k]);
210
211 if (((long)(buf-frame)/(c->sys->frame_size/(c->sys->difseg_size*c->sys->n_difchan))%c->sys->difseg_size) > 5) { /* FIXME: is this really needed ? */
212 dv_write_pack(dv_video_recdate, c, &buf[j+14]);
213 dv_write_pack(dv_video_rectime, c, &buf[j+22]);
214 dv_write_pack(dv_video_recdate, c, &buf[j+38]);
215 dv_write_pack(dv_video_rectime, c, &buf[j+46]);
216 }
217 }
218
219 /* DV VAUX: 4th, 5th and 6th 3DIFs */
220 for (j = 80*3 + 3; j < 80*6; j += 80) {
221 dv_write_pack(dv_video_recdate, c, &buf[j+5*2]);
222 dv_write_pack(dv_video_rectime, c, &buf[j+5*3]);
223 dv_write_pack(dv_video_recdate, c, &buf[j+5*11]);
224 dv_write_pack(dv_video_rectime, c, &buf[j+5*12]);
225 }
226 }
227}
228
229/*
230 * The following 3 functions constitute our interface to the world
231 */
232
233int dv_assemble_frame(DVMuxContext *c, AVStream* st,
234 const uint8_t* data, int data_size, uint8_t** frame)
235{
236 int i, reqasize;
237
238 *frame = &c->frame_buf[0];
239 reqasize = 4 * dv_audio_frame_size(c->sys, c->frames);
240
241 switch (st->codec->codec_type) {
242 case CODEC_TYPE_VIDEO:
243 /* FIXME: we have to have more sensible approach than this one */
244 if (c->has_video)
245 av_log(st->codec, AV_LOG_ERROR, "Can't process DV frame #%d. Insufficient audio data or severe sync problem.\n", c->frames);
246
247 memcpy(*frame, data, c->sys->frame_size);
248 c->has_video = 1;
249 break;
250 case CODEC_TYPE_AUDIO:
251 for (i = 0; i < c->n_ast && st != c->ast[i]; i++);
252
253 /* FIXME: we have to have more sensible approach than this one */
254 if (av_fifo_size(&c->audio_data[i]) + data_size >= 100*AVCODEC_MAX_AUDIO_FRAME_SIZE)
255 av_log(st->codec, AV_LOG_ERROR, "Can't process DV frame #%d. Insufficient video data or severe sync problem.\n", c->frames);
256 av_fifo_generic_write(&c->audio_data[i], data, data_size, NULL);
257
258 /* Lets see if we've got enough audio for one DV frame */
259 c->has_audio |= ((reqasize <= av_fifo_size(&c->audio_data[i])) << i);
260
261 break;
262 default:
263 break;
264 }
265
266 /* Lets see if we have enough data to construct one DV frame */
267 if (c->has_video == 1 && c->has_audio + 1 == 1<<c->n_ast) {
268 dv_inject_metadata(c, *frame);
269 c->has_audio = 0;
270 for (i=0; i<c->n_ast; i++) {
271 dv_inject_audio(c, i, *frame);
272 av_fifo_drain(&c->audio_data[i], reqasize);
273 c->has_audio |= ((reqasize <= av_fifo_size(&c->audio_data[i])) << i);
274 }
275
276 c->has_video = 0;
277
278 c->frames++;
279
280 return c->sys->frame_size;
281 }
282
283 return 0;
284}
285
286DVMuxContext* dv_init_mux(AVFormatContext* s)
287{
288 DVMuxContext *c = s->priv_data;
289 AVStream *vst = NULL;
290 int i;
291
292 /* we support at most 1 video and 2 audio streams */
293 if (s->nb_streams > 3)
294 return NULL;
295
296 c->n_ast = 0;
297 c->ast[0] = c->ast[1] = NULL;
298
299 /* We have to sort out where audio and where video stream is */
300 for (i=0; i<s->nb_streams; i++) {
301 switch (s->streams[i]->codec->codec_type) {
302 case CODEC_TYPE_VIDEO:
303 if (vst) return NULL;
304 vst = s->streams[i];
305 break;
306 case CODEC_TYPE_AUDIO:
307 if (c->n_ast > 1) return NULL;
308 c->ast[c->n_ast++] = s->streams[i];
309 break;
310 default:
311 goto bail_out;
312 }
313 }
314
315 /* Some checks -- DV format is very picky about its incoming streams */
316 if (!vst || vst->codec->codec_id != CODEC_ID_DVVIDEO)
317 goto bail_out;
318 for (i=0; i<c->n_ast; i++) {
319 if (c->ast[i] && (c->ast[i]->codec->codec_id != CODEC_ID_PCM_S16LE ||
320 c->ast[i]->codec->sample_rate != 48000 ||
321 c->ast[i]->codec->channels != 2))
322 goto bail_out;
323 }
324 c->sys = dv_codec_profile(vst->codec);
325 if (!c->sys)
326 goto bail_out;
327
328 if((c->n_ast > 1) && (c->sys->n_difchan < 2)) {
329 /* only 1 stereo pair is allowed in 25Mbps mode */
330 goto bail_out;
331 }
332
333 /* Ok, everything seems to be in working order */
334 c->frames = 0;
335 c->has_audio = 0;
336 c->has_video = 0;
337 c->start_time = (time_t)s->timestamp;
338
339 for (i=0; i<c->n_ast; i++) {
340 if (c->ast[i] && av_fifo_init(&c->audio_data[i], 100*AVCODEC_MAX_AUDIO_FRAME_SIZE) < 0) {
341 while (i>0) {
342 i--;
343 av_fifo_free(&c->audio_data[i]);
344 }
345 goto bail_out;
346 }
347 }
348
349 return c;
350
351bail_out:
352 return NULL;
353}
354
355void dv_delete_mux(DVMuxContext *c)
356{
357 int i;
358 for (i=0; i < c->n_ast; i++)
359 av_fifo_free(&c->audio_data[i]);
360}
361
362#ifdef CONFIG_MUXERS
363static int dv_write_header(AVFormatContext *s)
364{
365 if (!dv_init_mux(s)) {
366 av_log(s, AV_LOG_ERROR, "Can't initialize DV format!\n"
367 "Make sure that you supply exactly two streams:\n"
368 " video: 25fps or 29.97fps, audio: 2ch/48Khz/PCM\n"
369 " (50Mbps allows an optional second audio stream)\n");
370 return -1;
371 }
372 return 0;
373}
374
375static int dv_write_packet(struct AVFormatContext *s, AVPacket *pkt)
376{
377 uint8_t* frame;
378 int fsize;
379
380 fsize = dv_assemble_frame(s->priv_data, s->streams[pkt->stream_index],
381 pkt->data, pkt->size, &frame);
382 if (fsize > 0) {
383 put_buffer(s->pb, frame, fsize);
384 put_flush_packet(s->pb);
385 }
386 return 0;
387}
388
389/*
390 * We might end up with some extra A/V data without matching counterpart.
391 * E.g. video data without enough audio to write the complete frame.
392 * Currently we simply drop the last frame. I don't know whether this
393 * is the best strategy of all
394 */
395static int dv_write_trailer(struct AVFormatContext *s)
396{
397 dv_delete_mux(s->priv_data);
398 return 0;
399}
400#endif /* CONFIG_MUXERS */
401
402#ifdef CONFIG_DV_MUXER
403AVOutputFormat dv_muxer = {
404 "dv",
405 NULL_IF_CONFIG_SMALL("DV video format"),
406 NULL,
407 "dv",
408 sizeof(DVMuxContext),
409 CODEC_ID_PCM_S16LE,
410 CODEC_ID_DVVIDEO,
411 dv_write_header,
412 dv_write_packet,
413 dv_write_trailer,
414};
415#endif
diff --git a/src/plugins/ffmpeg/libavformat/dxa.c b/src/plugins/ffmpeg/libavformat/dxa.c
deleted file mode 100644
index 18fb529..0000000
--- a/src/plugins/ffmpeg/libavformat/dxa.c
+++ /dev/null
@@ -1,212 +0,0 @@
1/*
2 * DXA demuxer
3 * Copyright (c) 2007 Konstantin Shishkov.
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 "avformat.h"
23#include "riff.h"
24
25#define DXA_EXTRA_SIZE 9
26
27typedef struct{
28 int frames;
29 int has_sound;
30 int bpc;
31 uint32_t bytes_left;
32 int64_t wavpos, vidpos;
33 int readvid;
34}DXAContext;
35
36static int dxa_probe(AVProbeData *p)
37{
38 /* check file header */
39 if (p->buf[0] == 'D' && p->buf[1] == 'E' &&
40 p->buf[2] == 'X' && p->buf[3] == 'A')
41 return AVPROBE_SCORE_MAX;
42 else
43 return 0;
44}
45
46static int dxa_read_header(AVFormatContext *s, AVFormatParameters *ap)
47{
48 ByteIOContext *pb = s->pb;
49 DXAContext *c = s->priv_data;
50 AVStream *st, *ast;
51 uint32_t tag;
52 int32_t fps;
53 int w, h;
54 int num, den;
55 int flags;
56
57 tag = get_le32(pb);
58 if (tag != MKTAG('D', 'E', 'X', 'A'))
59 return -1;
60 flags = get_byte(pb);
61 c->frames = get_be16(pb);
62 if(!c->frames){
63 av_log(s, AV_LOG_ERROR, "File contains no frames ???\n");
64 return -1;
65 }
66
67 fps = get_be32(pb);
68 if(fps > 0){
69 den = 1000;
70 num = fps;
71 }else if (fps < 0){
72 den = 100000;
73 num = -fps;
74 }else{
75 den = 10;
76 num = 1;
77 }
78 w = get_be16(pb);
79 h = get_be16(pb);
80 c->has_sound = 0;
81
82 st = av_new_stream(s, 0);
83 if (!st)
84 return -1;
85
86 // Parse WAV data header
87 if(get_le32(pb) == MKTAG('W', 'A', 'V', 'E')){
88 uint32_t size, fsize;
89 c->has_sound = 1;
90 size = get_be32(pb);
91 c->vidpos = url_ftell(pb) + size;
92 url_fskip(pb, 16);
93 fsize = get_le32(pb);
94
95 ast = av_new_stream(s, 0);
96 if (!ast)
97 return -1;
98 get_wav_header(pb, ast->codec, fsize);
99 // find 'data' chunk
100 while(url_ftell(pb) < c->vidpos && !url_feof(pb)){
101 tag = get_le32(pb);
102 fsize = get_le32(pb);
103 if(tag == MKTAG('d', 'a', 't', 'a')) break;
104 url_fskip(pb, fsize);
105 }
106 c->bpc = (fsize + c->frames - 1) / c->frames;
107 if(ast->codec->block_align)
108 c->bpc = ((c->bpc + ast->codec->block_align - 1) / ast->codec->block_align) * ast->codec->block_align;
109 c->bytes_left = fsize;
110 c->wavpos = url_ftell(pb);
111 url_fseek(pb, c->vidpos, SEEK_SET);
112 }
113
114 /* now we are ready: build format streams */
115 st->codec->codec_type = CODEC_TYPE_VIDEO;
116 st->codec->codec_id = CODEC_ID_DXA;
117 st->codec->width = w;
118 st->codec->height = h;
119 av_reduce(&den, &num, den, num, (1UL<<31)-1);
120 av_set_pts_info(st, 33, num, den);
121 /* flags & 0x80 means that image is interlaced,
122 * flags & 0x40 means that image has double height
123 * either way set true height
124 */
125 if(flags & 0xC0){
126 st->codec->height >>= 1;
127 }
128 c->readvid = !c->has_sound;
129 c->vidpos = url_ftell(pb);
130 s->start_time = 0;
131 s->duration = (int64_t)c->frames * AV_TIME_BASE * num / den;
132 av_log(s, AV_LOG_DEBUG, "%d frame(s)\n",c->frames);
133
134 return 0;
135}
136
137static int dxa_read_packet(AVFormatContext *s, AVPacket *pkt)
138{
139 DXAContext *c = s->priv_data;
140 int ret;
141 uint32_t size;
142 uint8_t buf[DXA_EXTRA_SIZE], pal[768+4];
143 int pal_size = 0;
144
145 if(!c->readvid && c->has_sound && c->bytes_left){
146 c->readvid = 1;
147 url_fseek(s->pb, c->wavpos, SEEK_SET);
148 size = FFMIN(c->bytes_left, c->bpc);
149 ret = av_get_packet(s->pb, pkt, size);
150 pkt->stream_index = 1;
151 if(ret != size)
152 return AVERROR(EIO);
153 c->bytes_left -= size;
154 c->wavpos = url_ftell(s->pb);
155 return 0;
156 }
157 url_fseek(s->pb, c->vidpos, SEEK_SET);
158 while(!url_feof(s->pb) && c->frames){
159 get_buffer(s->pb, buf, 4);
160 switch(AV_RL32(buf)){
161 case MKTAG('N', 'U', 'L', 'L'):
162 if(av_new_packet(pkt, 4 + pal_size) < 0)
163 return AVERROR(ENOMEM);
164 pkt->stream_index = 0;
165 if(pal_size) memcpy(pkt->data, pal, pal_size);
166 memcpy(pkt->data + pal_size, buf, 4);
167 c->frames--;
168 c->vidpos = url_ftell(s->pb);
169 c->readvid = 0;
170 return 0;
171 case MKTAG('C', 'M', 'A', 'P'):
172 pal_size = 768+4;
173 memcpy(pal, buf, 4);
174 get_buffer(s->pb, pal + 4, 768);
175 break;
176 case MKTAG('F', 'R', 'A', 'M'):
177 get_buffer(s->pb, buf + 4, DXA_EXTRA_SIZE - 4);
178 size = AV_RB32(buf + 5);
179 if(size > 0xFFFFFF){
180 av_log(s, AV_LOG_ERROR, "Frame size is too big: %d\n", size);
181 return -1;
182 }
183 if(av_new_packet(pkt, size + DXA_EXTRA_SIZE + pal_size) < 0)
184 return AVERROR(ENOMEM);
185 memcpy(pkt->data + pal_size, buf, DXA_EXTRA_SIZE);
186 ret = get_buffer(s->pb, pkt->data + DXA_EXTRA_SIZE + pal_size, size);
187 if(ret != size){
188 av_free_packet(pkt);
189 return AVERROR(EIO);
190 }
191 if(pal_size) memcpy(pkt->data, pal, pal_size);
192 pkt->stream_index = 0;
193 c->frames--;
194 c->vidpos = url_ftell(s->pb);
195 c->readvid = 0;
196 return 0;
197 default:
198 av_log(s, AV_LOG_ERROR, "Unknown tag %c%c%c%c\n", buf[0], buf[1], buf[2], buf[3]);
199 return -1;
200 }
201 }
202 return AVERROR(EIO);
203}
204
205AVInputFormat dxa_demuxer = {
206 "dxa",
207 NULL_IF_CONFIG_SMALL("DXA"),
208 sizeof(DXAContext),
209 dxa_probe,
210 dxa_read_header,
211 dxa_read_packet,
212};
diff --git a/src/plugins/ffmpeg/libavformat/eacdata.c b/src/plugins/ffmpeg/libavformat/eacdata.c
deleted file mode 100644
index 6c021ef..0000000
--- a/src/plugins/ffmpeg/libavformat/eacdata.c
+++ /dev/null
@@ -1,100 +0,0 @@
1/*
2 * Electronic Arts .cdata file Demuxer
3 * Copyright (c) 2007 Peter Ross
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/**
23 * @file eacdata.c
24 * Electronic Arts cdata Format Demuxer
25 * by Peter Ross (suxen_drol at hotmail dot com)
26 *
27 * Technical details here:
28 * http://wiki.multimedia.cx/index.php?title=EA_Command_And_Conquer_3_Audio_Codec
29 */
30
31#include "avformat.h"
32
33typedef struct {
34 unsigned int channels;
35 unsigned int audio_pts;
36} CdataDemuxContext;
37
38static int cdata_probe(AVProbeData *p)
39{
40 const uint8_t *b = p->buf;
41
42 if (b[0] == 0x04 && (b[1] == 0x00 || b[1] == 0x04 || b[1] == 0x0C))
43 return AVPROBE_SCORE_MAX/8;
44 return 0;
45}
46
47static int cdata_read_header(AVFormatContext *s, AVFormatParameters *ap)
48{
49 CdataDemuxContext *cdata = s->priv_data;
50 ByteIOContext *pb = s->pb;
51 unsigned int sample_rate, header;
52 AVStream *st;
53
54 header = get_be16(pb);
55 switch (header) {
56 case 0x0400: cdata->channels = 1; break;
57 case 0x0404: cdata->channels = 2; break;
58 case 0x040C: cdata->channels = 4; break;
59 default:
60 av_log(s, AV_LOG_INFO, "unknown header 0x%04x\n", header);
61 return -1;
62 };
63
64 sample_rate = get_be16(pb);
65 url_fskip(pb, 12);
66
67 st = av_new_stream(s, 0);
68 if (!st)
69 return AVERROR(ENOMEM);
70 st->codec->codec_type = CODEC_TYPE_AUDIO;
71 st->codec->codec_tag = 0; /* no fourcc */
72 st->codec->codec_id = CODEC_ID_ADPCM_EA_XAS;
73 st->codec->channels = cdata->channels;
74 st->codec->sample_rate = sample_rate;
75 av_set_pts_info(st, 64, 1, sample_rate);
76
77 cdata->audio_pts = 0;
78 return 0;
79}
80
81static int cdata_read_packet(AVFormatContext *s, AVPacket *pkt)
82{
83 CdataDemuxContext *cdata = s->priv_data;
84 int packet_size = 76*cdata->channels;
85
86 if (av_get_packet(s->pb, pkt, packet_size) != packet_size)
87 return AVERROR(EIO);
88 pkt->pts = cdata->audio_pts++;
89 return 1;
90}
91
92AVInputFormat ea_cdata_demuxer = {
93 "ea_cdata",
94 NULL_IF_CONFIG_SMALL("Electronic Arts cdata"),
95 sizeof(CdataDemuxContext),
96 cdata_probe,
97 cdata_read_header,
98 cdata_read_packet,
99 .extensions = "cdata",
100};
diff --git a/src/plugins/ffmpeg/libavformat/electronicarts.c b/src/plugins/ffmpeg/libavformat/electronicarts.c
deleted file mode 100644
index 7a7207b..0000000
--- a/src/plugins/ffmpeg/libavformat/electronicarts.c
+++ /dev/null
@@ -1,488 +0,0 @@
1/* Electronic Arts Multimedia File Demuxer
2 * Copyright (c) 2004 The ffmpeg Project
3 * Copyright (c) 2006-2008 Peter Ross
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/**
23 * @file electronicarts.c
24 * Electronic Arts Multimedia file demuxer (WVE/UV2/etc.)
25 * by Robin Kay (komadori at gekkou.co.uk)
26 */
27
28#include "avformat.h"
29
30#define SCHl_TAG MKTAG('S', 'C', 'H', 'l')
31#define SEAD_TAG MKTAG('S', 'E', 'A', 'D') /* Sxxx header */
32#define SNDC_TAG MKTAG('S', 'N', 'D', 'C') /* Sxxx data */
33#define SEND_TAG MKTAG('S', 'E', 'N', 'D') /* Sxxx end */
34#define ISNh_TAG MKTAG('1', 'S', 'N', 'h') /* 1SNx header */
35#define EACS_TAG MKTAG('E', 'A', 'C', 'S')
36#define ISNd_TAG MKTAG('1', 'S', 'N', 'd') /* 1SNx data */
37#define ISNe_TAG MKTAG('1', 'S', 'N', 'e') /* 1SNx end */
38#define PT00_TAG MKTAG('P', 'T', 0x0, 0x0)
39#define GSTR_TAG MKTAG('G', 'S', 'T', 'R')
40#define SCDl_TAG MKTAG('S', 'C', 'D', 'l')
41#define SCEl_TAG MKTAG('S', 'C', 'E', 'l')
42#define kVGT_TAG MKTAG('k', 'V', 'G', 'T') /* TGV i-frame */
43#define MADk_TAG MKTAG('M', 'A', 'D', 'k') /* MAD i-frame */
44#define MPCh_TAG MKTAG('M', 'P', 'C', 'h') /* MPEG2 */
45#define MVhd_TAG MKTAG('M', 'V', 'h', 'd')
46#define MV0K_TAG MKTAG('M', 'V', '0', 'K')
47#define MV0F_TAG MKTAG('M', 'V', '0', 'F')
48#define MVIh_TAG MKTAG('M', 'V', 'I', 'h') /* CMV header */
49#define MVIf_TAG MKTAG('M', 'V', 'I', 'f') /* CMV i-frame */
50
51typedef struct EaDemuxContext {
52 int big_endian;
53
54 enum CodecID video_codec;
55 AVRational time_base;
56 int video_stream_index;
57
58 enum CodecID audio_codec;
59 int audio_stream_index;
60 int audio_frame_counter;
61
62 int64_t audio_pts;
63
64 int bytes;
65 int sample_rate;
66 int num_channels;
67 int num_samples;
68} EaDemuxContext;
69
70static uint32_t read_arbitary(ByteIOContext *pb) {
71 uint8_t size, byte;
72 int i;
73 uint32_t word;
74
75 size = get_byte(pb);
76
77 word = 0;
78 for (i = 0; i < size; i++) {
79 byte = get_byte(pb);
80 word <<= 8;
81 word |= byte;
82 }
83
84 return word;
85}
86
87/*
88 * Process PT/GSTR sound header
89 * return 1 if success, 0 if invalid format, otherwise AVERROR_xxx
90 */
91static int process_audio_header_elements(AVFormatContext *s)
92{
93 int inHeader = 1;
94 EaDemuxContext *ea = s->priv_data;
95 ByteIOContext *pb = s->pb;
96 int compression_type = -1, revision = -1, revision2 = -1;
97
98 ea->bytes = 2;
99 ea->sample_rate = -1;
100 ea->num_channels = 1;
101
102 while (inHeader) {
103 int inSubheader;
104 uint8_t byte;
105 byte = get_byte(pb);
106
107 switch (byte) {
108 case 0xFD:
109 av_log (s, AV_LOG_INFO, "entered audio subheader\n");
110 inSubheader = 1;
111 while (inSubheader) {
112 uint8_t subbyte;
113 subbyte = get_byte(pb);
114
115 switch (subbyte) {
116 case 0x80:
117 revision = read_arbitary(pb);
118 av_log (s, AV_LOG_INFO, "revision (element 0x80) set to 0x%08x\n", revision);
119 break;
120 case 0x82:
121 ea->num_channels = read_arbitary(pb);
122 av_log (s, AV_LOG_INFO, "num_channels (element 0x82) set to 0x%08x\n", ea->num_channels);
123 break;
124 case 0x83:
125 compression_type = read_arbitary(pb);
126 av_log (s, AV_LOG_INFO, "compression_type (element 0x83) set to 0x%08x\n", compression_type);
127 break;
128 case 0x84:
129 ea->sample_rate = read_arbitary(pb);
130 av_log (s, AV_LOG_INFO, "sample_rate (element 0x84) set to %i\n", ea->sample_rate);
131 break;
132 case 0x85:
133 ea->num_samples = read_arbitary(pb);
134 av_log (s, AV_LOG_INFO, "num_samples (element 0x85) set to 0x%08x\n", ea->num_samples);
135 break;
136 case 0x8A:
137 av_log (s, AV_LOG_INFO, "element 0x%02x set to 0x%08x\n", subbyte, read_arbitary(pb));
138 av_log (s, AV_LOG_INFO, "exited audio subheader\n");
139 inSubheader = 0;
140 break;
141 case 0xA0:
142 revision2 = read_arbitary(pb);
143 av_log (s, AV_LOG_INFO, "revision2 (element 0xA0) set to 0x%08x\n", revision2);
144 break;
145 case 0xFF:
146 av_log (s, AV_LOG_INFO, "end of header block reached (within audio subheader)\n");
147 inSubheader = 0;
148 inHeader = 0;
149 break;
150 default:
151 av_log (s, AV_LOG_INFO, "element 0x%02x set to 0x%08x\n", subbyte, read_arbitary(pb));
152 break;
153 }
154 }
155 break;
156 case 0xFF:
157 av_log (s, AV_LOG_INFO, "end of header block reached\n");
158 inHeader = 0;
159 break;
160 default:
161 av_log (s, AV_LOG_INFO, "header element 0x%02x set to 0x%08x\n", byte, read_arbitary(pb));
162 break;
163 }
164 }
165
166 switch (compression_type) {
167 case 0: ea->audio_codec = CODEC_ID_PCM_S16LE; break;
168 case 7: ea->audio_codec = CODEC_ID_ADPCM_EA; break;
169 case -1:
170 switch (revision) {
171 case 1: ea->audio_codec = CODEC_ID_ADPCM_EA_R1; break;
172 case 2: ea->audio_codec = CODEC_ID_ADPCM_EA_R2; break;
173 case 3: ea->audio_codec = CODEC_ID_ADPCM_EA_R3; break;
174 case -1: break;
175 default:
176 av_log(s, AV_LOG_ERROR, "unsupported stream type; revision=%i\n", revision);
177 return 0;
178 }
179 switch (revision2) {
180 case 8: ea->audio_codec = CODEC_ID_PCM_S16LE_PLANAR; break;
181 default:
182 av_log(s, AV_LOG_ERROR, "unsupported stream type; revision2=%i\n", revision2);
183 return 0;
184 }
185 break;
186 default:
187 av_log(s, AV_LOG_ERROR, "unsupported stream type; compression_type=%i\n", compression_type);
188 return 0;
189 }
190
191 if (ea->sample_rate == -1)
192 ea->sample_rate = revision==3 ? 48000 : 22050;
193
194 return 1;
195}
196
197/*
198 * Process EACS sound header
199 * return 1 if success, 0 if invalid format, otherwise AVERROR_xxx
200 */
201static int process_audio_header_eacs(AVFormatContext *s)
202{
203 EaDemuxContext *ea = s->priv_data;
204 ByteIOContext *pb = s->pb;
205 int compression_type;
206
207 ea->sample_rate = ea->big_endian ? get_be32(pb) : get_le32(pb);
208 ea->bytes = get_byte(pb); /* 1=8-bit, 2=16-bit */
209 ea->num_channels = get_byte(pb);
210 compression_type = get_byte(pb);
211 url_fskip(pb, 13);
212
213 switch (compression_type) {
214 case 0:
215 switch (ea->bytes) {
216 case 1: ea->audio_codec = CODEC_ID_PCM_S8; break;
217 case 2: ea->audio_codec = CODEC_ID_PCM_S16LE; break;
218 }
219 break;
220 case 1: ea->audio_codec = CODEC_ID_PCM_MULAW; ea->bytes = 1; break;
221 case 2: ea->audio_codec = CODEC_ID_ADPCM_IMA_EA_EACS; break;
222 default:
223 av_log (s, AV_LOG_ERROR, "unsupported stream type; audio compression_type=%i\n", compression_type);
224 }
225
226 return 1;
227}
228
229/*
230 * Process SEAD sound header
231 * return 1 if success, 0 if invalid format, otherwise AVERROR_xxx
232 */
233static int process_audio_header_sead(AVFormatContext *s)
234{
235 EaDemuxContext *ea = s->priv_data;
236 ByteIOContext *pb = s->pb;
237
238 ea->sample_rate = get_le32(pb);
239 ea->bytes = get_le32(pb); /* 1=8-bit, 2=16-bit */
240 ea->num_channels = get_le32(pb);
241 ea->audio_codec = CODEC_ID_ADPCM_IMA_EA_SEAD;
242
243 return 1;
244}
245
246static int process_video_header_vp6(AVFormatContext *s)
247{
248 EaDemuxContext *ea = s->priv_data;
249 ByteIOContext *pb = s->pb;
250
251 url_fskip(pb, 16);
252 ea->time_base.den = get_le32(pb);
253 ea->time_base.num = get_le32(pb);
254 ea->video_codec = CODEC_ID_VP6;
255
256 return 1;
257}
258
259/*
260 * Process EA file header
261 * Returns 1 if the EA file is valid and successfully opened, 0 otherwise
262 */
263static int process_ea_header(AVFormatContext *s) {
264 uint32_t blockid, size = 0;
265 EaDemuxContext *ea = s->priv_data;
266 ByteIOContext *pb = s->pb;
267 int i;
268
269 for (i=0; i<5 && (!ea->audio_codec || !ea->video_codec); i++) {
270 unsigned int startpos = url_ftell(pb);
271 int err = 0;
272
273 blockid = get_le32(pb);
274 size = get_le32(pb);
275 if (i == 0)
276 ea->big_endian = size > 0x000FFFFF;
277 if (ea->big_endian)
278 size = bswap_32(size);
279
280 switch (blockid) {
281 case ISNh_TAG:
282 if (get_le32(pb) != EACS_TAG) {
283 av_log (s, AV_LOG_ERROR, "unknown 1SNh headerid\n");
284 return 0;
285 }
286 err = process_audio_header_eacs(s);
287 break;
288
289 case SCHl_TAG :
290 blockid = get_le32(pb);
291 if (blockid == GSTR_TAG) {
292 url_fskip(pb, 4);
293 } else if (blockid != PT00_TAG) {
294 av_log (s, AV_LOG_ERROR, "unknown SCHl headerid\n");
295 return 0;
296 }
297 err = process_audio_header_elements(s);
298 break;
299
300 case SEAD_TAG:
301 err = process_audio_header_sead(s);
302 break;
303
304 case MVIh_TAG :
305 ea->video_codec = CODEC_ID_CMV;
306 ea->time_base = (AVRational){0,0};
307 break;
308
309 case MVhd_TAG :
310 err = process_video_header_vp6(s);
311 break;
312 }
313
314 if (err < 0) {
315 av_log(s, AV_LOG_ERROR, "error parsing header: %i\n", err);
316 return err;
317 }
318
319 url_fseek(pb, startpos + size, SEEK_SET);
320 }
321
322 url_fseek(pb, 0, SEEK_SET);
323
324 return 1;
325}
326
327
328static int ea_probe(AVProbeData *p)
329{
330 switch (AV_RL32(&p->buf[0])) {
331 case ISNh_TAG:
332 case SCHl_TAG:
333 case SEAD_TAG:
334 case kVGT_TAG:
335 case MADk_TAG:
336 case MPCh_TAG:
337 case MVhd_TAG:
338 case MVIh_TAG:
339 return AVPROBE_SCORE_MAX;
340 }
341 return 0;
342}
343
344static int ea_read_header(AVFormatContext *s,
345 AVFormatParameters *ap)
346{
347 EaDemuxContext *ea = s->priv_data;
348 AVStream *st;
349
350 if (!process_ea_header(s))
351 return AVERROR(EIO);
352
353 if (ea->video_codec) {
354 /* initialize the video decoder stream */
355 st = av_new_stream(s, 0);
356 if (!st)
357 return AVERROR(ENOMEM);
358 ea->video_stream_index = st->index;
359 st->codec->codec_type = CODEC_TYPE_VIDEO;
360 st->codec->codec_id = ea->video_codec;
361 st->codec->codec_tag = 0; /* no fourcc */
362 st->codec->time_base = ea->time_base;
363 }
364
365 if (ea->audio_codec) {
366 /* initialize the audio decoder stream */
367 st = av_new_stream(s, 0);
368 if (!st)
369 return AVERROR(ENOMEM);
370 av_set_pts_info(st, 33, 1, ea->sample_rate);
371 st->codec->codec_type = CODEC_TYPE_AUDIO;
372 st->codec->codec_id = ea->audio_codec;
373 st->codec->codec_tag = 0; /* no tag */
374 st->codec->channels = ea->num_channels;
375 st->codec->sample_rate = ea->sample_rate;
376 st->codec->bits_per_sample = ea->bytes * 8;
377 st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *
378 st->codec->bits_per_sample / 4;
379 st->codec->block_align = st->codec->channels*st->codec->bits_per_sample;
380 ea->audio_stream_index = st->index;
381 ea->audio_frame_counter = 0;
382 }
383
384 return 1;
385}
386
387static int ea_read_packet(AVFormatContext *s,
388 AVPacket *pkt)
389{
390 EaDemuxContext *ea = s->priv_data;
391 ByteIOContext *pb = s->pb;
392 int ret = 0;
393 int packet_read = 0;
394 unsigned int chunk_type, chunk_size;
395 int key = 0;
396
397 while (!packet_read) {
398 chunk_type = get_le32(pb);
399 chunk_size = (ea->big_endian ? get_be32(pb) : get_le32(pb)) - 8;
400
401 switch (chunk_type) {
402 /* audio data */
403 case ISNh_TAG:
404 /* header chunk also contains data; skip over the header portion*/
405 url_fskip(pb, 32);
406 chunk_size -= 32;
407 case ISNd_TAG:
408 case SCDl_TAG:
409 case SNDC_TAG:
410 if (!ea->audio_codec) {
411 url_fskip(pb, chunk_size);
412 break;
413 } else if (ea->audio_codec == CODEC_ID_PCM_S16LE_PLANAR) {
414 url_fskip(pb, 12); /* planar header */
415 chunk_size -= 12;
416 }
417 ret = av_get_packet(pb, pkt, chunk_size);
418 if (ret != chunk_size)
419 ret = AVERROR(EIO);
420 else {
421 pkt->stream_index = ea->audio_stream_index;
422 pkt->pts = 90000;
423 pkt->pts *= ea->audio_frame_counter;
424 pkt->pts /= ea->sample_rate;
425
426 switch (ea->audio_codec) {
427 case CODEC_ID_ADPCM_EA:
428 /* 2 samples/byte, 1 or 2 samples per frame depending
429 * on stereo; chunk also has 12-byte header */
430 ea->audio_frame_counter += ((chunk_size - 12) * 2) /
431 ea->num_channels;
432 break;
433 default:
434 ea->audio_frame_counter += chunk_size /
435 (ea->bytes * ea->num_channels);
436 }
437 }
438
439 packet_read = 1;
440 break;
441
442 /* ending tag */
443 case 0:
444 case ISNe_TAG:
445 case SCEl_TAG:
446 case SEND_TAG:
447 ret = AVERROR(EIO);
448 packet_read = 1;
449 break;
450
451 case MVIh_TAG:
452 key = PKT_FLAG_KEY;
453 case MVIf_TAG:
454 url_fseek(pb, -8, SEEK_CUR); // include chunk preamble
455 chunk_size += 8;
456 goto get_video_packet;
457
458 case MV0K_TAG:
459 key = PKT_FLAG_KEY;
460 case MV0F_TAG:
461get_video_packet:
462 ret = av_get_packet(pb, pkt, chunk_size);
463 if (ret != chunk_size)
464 ret = AVERROR_IO;
465 else {
466 pkt->stream_index = ea->video_stream_index;
467 pkt->flags |= key;
468 }
469 packet_read = 1;
470 break;
471
472 default:
473 url_fseek(pb, chunk_size, SEEK_CUR);
474 break;
475 }
476 }
477
478 return ret;
479}
480
481AVInputFormat ea_demuxer = {
482 "ea",
483 NULL_IF_CONFIG_SMALL("Electronic Arts Multimedia Format"),
484 sizeof(EaDemuxContext),
485 ea_probe,
486 ea_read_header,
487 ea_read_packet,
488};
diff --git a/src/plugins/ffmpeg/libavformat/ffm.h b/src/plugins/ffmpeg/libavformat/ffm.h
deleted file mode 100644
index 52a8409..0000000
--- a/src/plugins/ffmpeg/libavformat/ffm.h
+++ /dev/null
@@ -1,56 +0,0 @@
1/*
2 * FFM (ffserver live feed) common header
3 * Copyright (c) 2001 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#ifndef FFMPEG_FFM_H
23#define FFMPEG_FFM_H
24
25#include "avformat.h"
26
27/* The FFM file is made of blocks of fixed size */
28#define FFM_HEADER_SIZE 14
29#define PACKET_ID 0x666d
30
31/* each packet contains frames (which can span several packets */
32#define FRAME_HEADER_SIZE 16
33#define FLAG_KEY_FRAME 0x01
34#define FLAG_DTS 0x02
35
36enum {
37 READ_HEADER,
38 READ_DATA,
39};
40
41typedef struct FFMContext {
42 /* only reading mode */
43 offset_t write_index, file_size;
44 int read_state;
45 uint8_t header[FRAME_HEADER_SIZE+4];
46
47 /* read and write */
48 int first_packet; /* true if first packet, needed to set the discontinuity tag */
49 int packet_size;
50 int frame_offset;
51 int64_t dts;
52 uint8_t *packet_ptr, *packet_end;
53 uint8_t packet[FFM_PACKET_SIZE];
54} FFMContext;
55
56#endif /* FFMPEG_FFM_H */
diff --git a/src/plugins/ffmpeg/libavformat/ffmdec.c b/src/plugins/ffmpeg/libavformat/ffmdec.c
deleted file mode 100644
index f428228..0000000
--- a/src/plugins/ffmpeg/libavformat/ffmdec.c
+++ /dev/null
@@ -1,487 +0,0 @@
1/*
2 * FFM (ffserver live feed) demuxer
3 * Copyright (c) 2001 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 "avformat.h"
23#include "ffm.h"
24#ifdef CONFIG_FFSERVER
25#include <unistd.h>
26
27offset_t ffm_read_write_index(int fd)
28{
29 uint8_t buf[8];
30
31 lseek(fd, 8, SEEK_SET);
32 read(fd, buf, 8);
33 return AV_RB64(buf);
34}
35
36void ffm_write_write_index(int fd, offset_t pos)
37{
38 uint8_t buf[8];
39 int i;
40
41 for(i=0;i<8;i++)
42 buf[i] = (pos >> (56 - i * 8)) & 0xff;
43 lseek(fd, 8, SEEK_SET);
44 write(fd, buf, 8);
45}
46
47void ffm_set_write_index(AVFormatContext *s, offset_t pos, offset_t file_size)
48{
49 FFMContext *ffm = s->priv_data;
50 ffm->write_index = pos;
51 ffm->file_size = file_size;
52}
53#endif // CONFIG_FFSERVER
54
55static int ffm_is_avail_data(AVFormatContext *s, int size)
56{
57 FFMContext *ffm = s->priv_data;
58 offset_t pos, avail_size;
59 int len;
60
61 len = ffm->packet_end - ffm->packet_ptr;
62 if (size <= len)
63 return 1;
64 pos = url_ftell(s->pb);
65 if (pos == ffm->write_index) {
66 /* exactly at the end of stream */
67 return 0;
68 } else if (pos < ffm->write_index) {
69 avail_size = ffm->write_index - pos;
70 } else {
71 avail_size = (ffm->file_size - pos) + (ffm->write_index - FFM_PACKET_SIZE);
72 }
73 avail_size = (avail_size / ffm->packet_size) * (ffm->packet_size - FFM_HEADER_SIZE) + len;
74 if (size <= avail_size)
75 return 1;
76 else
77 return 0;
78}
79
80/* first is true if we read the frame header */
81static int ffm_read_data(AVFormatContext *s,
82 uint8_t *buf, int size, int header)
83{
84 FFMContext *ffm = s->priv_data;
85 ByteIOContext *pb = s->pb;
86 int len, fill_size, size1, frame_offset;
87
88 size1 = size;
89 while (size > 0) {
90 redo:
91 len = ffm->packet_end - ffm->packet_ptr;
92 if (len < 0)
93 return -1;
94 if (len > size)
95 len = size;
96 if (len == 0) {
97 if (url_ftell(pb) == ffm->file_size)
98 url_fseek(pb, ffm->packet_size, SEEK_SET);
99 retry_read:
100 get_be16(pb); /* PACKET_ID */
101 fill_size = get_be16(pb);
102 ffm->dts = get_be64(pb);
103 frame_offset = get_be16(pb);
104 get_buffer(pb, ffm->packet, ffm->packet_size - FFM_HEADER_SIZE);
105 ffm->packet_end = ffm->packet + (ffm->packet_size - FFM_HEADER_SIZE - fill_size);
106 if (ffm->packet_end < ffm->packet || frame_offset < 0)
107 return -1;
108 /* if first packet or resynchronization packet, we must
109 handle it specifically */
110 if (ffm->first_packet || (frame_offset & 0x8000)) {
111 if (!frame_offset) {
112 /* This packet has no frame headers in it */
113 if (url_ftell(pb) >= ffm->packet_size * 3) {
114 url_fseek(pb, -ffm->packet_size * 2, SEEK_CUR);
115 goto retry_read;
116 }
117 /* This is bad, we cannot find a valid frame header */
118 return 0;
119 }
120 ffm->first_packet = 0;
121 if ((frame_offset & 0x7fff) < FFM_HEADER_SIZE)
122 return -1;
123 ffm->packet_ptr = ffm->packet + (frame_offset & 0x7fff) - FFM_HEADER_SIZE;
124 if (!header)
125 break;
126 } else {
127 ffm->packet_ptr = ffm->packet;
128 }
129 goto redo;
130 }
131 memcpy(buf, ffm->packet_ptr, len);
132 buf += len;
133 ffm->packet_ptr += len;
134 size -= len;
135 header = 0;
136 }
137 return size1 - size;
138}
139
140//#define DEBUG_SEEK
141
142/* pos is between 0 and file_size - FFM_PACKET_SIZE. It is translated
143 by the write position inside this function */
144static void ffm_seek1(AVFormatContext *s, offset_t pos1)
145{
146 FFMContext *ffm = s->priv_data;
147 ByteIOContext *pb = s->pb;
148 offset_t pos;
149
150 pos = pos1 + ffm->write_index;
151 if (pos >= ffm->file_size)
152 pos -= (ffm->file_size - FFM_PACKET_SIZE);
153#ifdef DEBUG_SEEK
154 av_log(s, AV_LOG_DEBUG, "seek to %"PRIx64" -> %"PRIx64"\n", pos1, pos);
155#endif
156 url_fseek(pb, pos, SEEK_SET);
157}
158
159static int64_t get_dts(AVFormatContext *s, offset_t pos)
160{
161 ByteIOContext *pb = s->pb;
162 int64_t dts;
163
164 ffm_seek1(s, pos);
165 url_fskip(pb, 4);
166 dts = get_be64(pb);
167#ifdef DEBUG_SEEK
168 av_log(s, AV_LOG_DEBUG, "pts=%0.6f\n", pts / 1000000.0);
169#endif
170 return dts;
171}
172
173static void adjust_write_index(AVFormatContext *s)
174{
175 FFMContext *ffm = s->priv_data;
176 ByteIOContext *pb = s->pb;
177 int64_t pts;
178 //offset_t orig_write_index = ffm->write_index;
179 offset_t pos_min, pos_max;
180 int64_t pts_start;
181 offset_t ptr = url_ftell(pb);
182
183
184 pos_min = 0;
185 pos_max = ffm->file_size - 2 * FFM_PACKET_SIZE;
186
187 pts_start = get_dts(s, pos_min);
188
189 pts = get_dts(s, pos_max);
190
191 if (pts - 100000 > pts_start)
192 goto end;
193
194 ffm->write_index = FFM_PACKET_SIZE;
195
196 pts_start = get_dts(s, pos_min);
197
198 pts = get_dts(s, pos_max);
199
200 if (pts - 100000 <= pts_start) {
201 while (1) {
202 offset_t newpos;
203 int64_t newpts;
204
205 newpos = ((pos_max + pos_min) / (2 * FFM_PACKET_SIZE)) * FFM_PACKET_SIZE;
206
207 if (newpos == pos_min)
208 break;
209
210 newpts = get_dts(s, newpos);
211
212 if (newpts - 100000 <= pts) {
213 pos_max = newpos;
214 pts = newpts;
215 } else {
216 pos_min = newpos;
217 }
218 }
219 ffm->write_index += pos_max;
220 }
221
222 //printf("Adjusted write index from %"PRId64" to %"PRId64": pts=%0.6f\n", orig_write_index, ffm->write_index, pts / 1000000.);
223 //printf("pts range %0.6f - %0.6f\n", get_dts(s, 0) / 1000000. , get_dts(s, ffm->file_size - 2 * FFM_PACKET_SIZE) / 1000000. );
224
225 end:
226 url_fseek(pb, ptr, SEEK_SET);
227}
228
229
230static int ffm_read_header(AVFormatContext *s, AVFormatParameters *ap)
231{
232 FFMContext *ffm = s->priv_data;
233 AVStream *st;
234 ByteIOContext *pb = s->pb;
235 AVCodecContext *codec;
236 int i, nb_streams;
237 uint32_t tag;
238
239 /* header */
240 tag = get_le32(pb);
241 if (tag != MKTAG('F', 'F', 'M', '1'))
242 goto fail;
243 ffm->packet_size = get_be32(pb);
244 if (ffm->packet_size != FFM_PACKET_SIZE)
245 goto fail;
246 ffm->write_index = get_be64(pb);
247 /* get also filesize */
248 if (!url_is_streamed(pb)) {
249 ffm->file_size = url_fsize(pb);
250 adjust_write_index(s);
251 } else {
252 ffm->file_size = (UINT64_C(1) << 63) - 1;
253 }
254
255 nb_streams = get_be32(pb);
256 get_be32(pb); /* total bitrate */
257 /* read each stream */
258 for(i=0;i<nb_streams;i++) {
259 char rc_eq_buf[128];
260
261 st = av_new_stream(s, 0);
262 if (!st)
263 goto fail;
264 s->streams[i] = st;
265
266 av_set_pts_info(st, 64, 1, 1000000);
267
268 codec = st->codec;
269 /* generic info */
270 codec->codec_id = get_be32(pb);
271 codec->codec_type = get_byte(pb); /* codec_type */
272 codec->bit_rate = get_be32(pb);
273 st->quality = get_be32(pb);
274 codec->flags = get_be32(pb);
275 codec->flags2 = get_be32(pb);
276 codec->debug = get_be32(pb);
277 /* specific info */
278 switch(codec->codec_type) {
279 case CODEC_TYPE_VIDEO:
280 codec->time_base.num = get_be32(pb);
281 codec->time_base.den = get_be32(pb);
282 codec->width = get_be16(pb);
283 codec->height = get_be16(pb);
284 codec->gop_size = get_be16(pb);
285 codec->pix_fmt = get_be32(pb);
286 codec->qmin = get_byte(pb);
287 codec->qmax = get_byte(pb);
288 codec->max_qdiff = get_byte(pb);
289 codec->qcompress = get_be16(pb) / 10000.0;
290 codec->qblur = get_be16(pb) / 10000.0;
291 codec->bit_rate_tolerance = get_be32(pb);
292 codec->rc_eq = av_strdup(get_strz(pb, rc_eq_buf, sizeof(rc_eq_buf)));
293 codec->rc_max_rate = get_be32(pb);
294 codec->rc_min_rate = get_be32(pb);
295 codec->rc_buffer_size = get_be32(pb);
296 codec->i_quant_factor = av_int2dbl(get_be64(pb));
297 codec->b_quant_factor = av_int2dbl(get_be64(pb));
298 codec->i_quant_offset = av_int2dbl(get_be64(pb));
299 codec->b_quant_offset = av_int2dbl(get_be64(pb));
300 codec->dct_algo = get_be32(pb);
301 codec->strict_std_compliance = get_be32(pb);
302 codec->max_b_frames = get_be32(pb);
303 codec->luma_elim_threshold = get_be32(pb);
304 codec->chroma_elim_threshold = get_be32(pb);
305 codec->mpeg_quant = get_be32(pb);
306 codec->intra_dc_precision = get_be32(pb);
307 codec->me_method = get_be32(pb);
308 codec->mb_decision = get_be32(pb);
309 codec->nsse_weight = get_be32(pb);
310 codec->frame_skip_cmp = get_be32(pb);
311 codec->rc_buffer_aggressivity = av_int2dbl(get_be64(pb));
312 codec->codec_tag = get_be32(pb);
313 codec->thread_count = get_byte(pb);
314 break;
315 case CODEC_TYPE_AUDIO:
316 codec->sample_rate = get_be32(pb);
317 codec->channels = get_le16(pb);
318 codec->frame_size = get_le16(pb);
319 break;
320 default:
321 goto fail;
322 }
323 if (codec->flags & CODEC_FLAG_GLOBAL_HEADER) {
324 codec->extradata_size = get_be32(pb);
325 codec->extradata = av_malloc(codec->extradata_size);
326 if (!codec->extradata)
327 return AVERROR(ENOMEM);
328 get_buffer(pb, codec->extradata, codec->extradata_size);
329 }
330 }
331
332 /* get until end of block reached */
333 while ((url_ftell(pb) % ffm->packet_size) != 0)
334 get_byte(pb);
335
336 /* init packet demux */
337 ffm->packet_ptr = ffm->packet;
338 ffm->packet_end = ffm->packet;
339 ffm->frame_offset = 0;
340 ffm->dts = 0;
341 ffm->read_state = READ_HEADER;
342 ffm->first_packet = 1;
343 return 0;
344 fail:
345 for(i=0;i<s->nb_streams;i++) {
346 st = s->streams[i];
347 if (st) {
348 av_free(st);
349 }
350 }
351 return -1;
352}
353
354/* return < 0 if eof */
355static int ffm_read_packet(AVFormatContext *s, AVPacket *pkt)
356{
357 int size;
358 FFMContext *ffm = s->priv_data;
359 int duration;
360
361 switch(ffm->read_state) {
362 case READ_HEADER:
363 if (!ffm_is_avail_data(s, FRAME_HEADER_SIZE+4)) {
364 return AVERROR(EAGAIN);
365 }
366 dprintf(s, "pos=%08"PRIx64" spos=%"PRIx64", write_index=%"PRIx64" size=%"PRIx64"\n",
367 url_ftell(s->pb), s->pb->pos, ffm->write_index, ffm->file_size);
368 if (ffm_read_data(s, ffm->header, FRAME_HEADER_SIZE, 1) !=
369 FRAME_HEADER_SIZE)
370 return AVERROR(EAGAIN);
371 if (ffm->header[1] & FLAG_DTS)
372 if (ffm_read_data(s, ffm->header+16, 4, 1) != 4)
373 return AVERROR(EAGAIN);
374#if 0
375 av_hexdump_log(s, AV_LOG_DEBUG, ffm->header, FRAME_HEADER_SIZE);
376#endif
377 ffm->read_state = READ_DATA;
378 /* fall thru */
379 case READ_DATA:
380 size = AV_RB24(ffm->header + 2);
381 if (!ffm_is_avail_data(s, size)) {
382 return AVERROR(EAGAIN);
383 }
384
385 duration = AV_RB24(ffm->header + 5);
386
387 av_new_packet(pkt, size);
388 pkt->stream_index = ffm->header[0];
389 if ((unsigned)pkt->stream_index >= s->nb_streams) {
390 av_log(s, AV_LOG_ERROR, "invalid stream index %d\n", pkt->stream_index);
391 av_free_packet(pkt);
392 ffm->read_state = READ_HEADER;
393 return AVERROR(EAGAIN);
394 }
395 pkt->pos = url_ftell(s->pb);
396 if (ffm->header[1] & FLAG_KEY_FRAME)
397 pkt->flags |= PKT_FLAG_KEY;
398
399 ffm->read_state = READ_HEADER;
400 if (ffm_read_data(s, pkt->data, size, 0) != size) {
401 /* bad case: desynchronized packet. we cancel all the packet loading */
402 av_free_packet(pkt);
403 return AVERROR(EAGAIN);
404 }
405 pkt->pts = AV_RB64(ffm->header+8);
406 if (ffm->header[1] & FLAG_DTS)
407 pkt->dts = pkt->pts - AV_RB32(ffm->header+16);
408 else
409 pkt->dts = pkt->pts;
410 pkt->duration = duration;
411 break;
412 }
413 return 0;
414}
415
416/* seek to a given time in the file. The file read pointer is
417 positioned at or before pts. XXX: the following code is quite
418 approximative */
419static int ffm_seek(AVFormatContext *s, int stream_index, int64_t wanted_pts, int flags)
420{
421 FFMContext *ffm = s->priv_data;
422 offset_t pos_min, pos_max, pos;
423 int64_t pts_min, pts_max, pts;
424 double pos1;
425
426#ifdef DEBUG_SEEK
427 av_log(s, AV_LOG_DEBUG, "wanted_pts=%0.6f\n", wanted_pts / 1000000.0);
428#endif
429 /* find the position using linear interpolation (better than
430 dichotomy in typical cases) */
431 pos_min = 0;
432 pos_max = ffm->file_size - 2 * FFM_PACKET_SIZE;
433 while (pos_min <= pos_max) {
434 pts_min = get_dts(s, pos_min);
435 pts_max = get_dts(s, pos_max);
436 /* linear interpolation */
437 pos1 = (double)(pos_max - pos_min) * (double)(wanted_pts - pts_min) /
438 (double)(pts_max - pts_min);
439 pos = (((int64_t)pos1) / FFM_PACKET_SIZE) * FFM_PACKET_SIZE;
440 if (pos <= pos_min)
441 pos = pos_min;
442 else if (pos >= pos_max)
443 pos = pos_max;
444 pts = get_dts(s, pos);
445 /* check if we are lucky */
446 if (pts == wanted_pts) {
447 goto found;
448 } else if (pts > wanted_pts) {
449 pos_max = pos - FFM_PACKET_SIZE;
450 } else {
451 pos_min = pos + FFM_PACKET_SIZE;
452 }
453 }
454 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
455 if (pos > 0)
456 pos -= FFM_PACKET_SIZE;
457 found:
458 ffm_seek1(s, pos);
459
460 /* reset read state */
461 ffm->read_state = READ_HEADER;
462 ffm->packet_ptr = ffm->packet;
463 ffm->packet_end = ffm->packet;
464 ffm->first_packet = 1;
465
466 return 0;
467}
468
469static int ffm_probe(AVProbeData *p)
470{
471 if (
472 p->buf[0] == 'F' && p->buf[1] == 'F' && p->buf[2] == 'M' &&
473 p->buf[3] == '1')
474 return AVPROBE_SCORE_MAX + 1;
475 return 0;
476}
477
478AVInputFormat ffm_demuxer = {
479 "ffm",
480 NULL_IF_CONFIG_SMALL("ffm format"),
481 sizeof(FFMContext),
482 ffm_probe,
483 ffm_read_header,
484 ffm_read_packet,
485 NULL,
486 ffm_seek,
487};
diff --git a/src/plugins/ffmpeg/libavformat/ffmenc.c b/src/plugins/ffmpeg/libavformat/ffmenc.c
deleted file mode 100644
index 1e78306..0000000
--- a/src/plugins/ffmpeg/libavformat/ffmenc.c
+++ /dev/null
@@ -1,250 +0,0 @@
1/*
2 * FFM (ffserver live feed) muxer
3 * Copyright (c) 2001 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 "avformat.h"
23#include "ffm.h"
24
25static void flush_packet(AVFormatContext *s)
26{
27 FFMContext *ffm = s->priv_data;
28 int fill_size, h;
29 ByteIOContext *pb = s->pb;
30
31 fill_size = ffm->packet_end - ffm->packet_ptr;
32 memset(ffm->packet_ptr, 0, fill_size);
33
34 if (url_ftell(pb) % ffm->packet_size)
35 av_abort();
36
37 /* put header */
38 put_be16(pb, PACKET_ID);
39 put_be16(pb, fill_size);
40 put_be64(pb, ffm->dts);
41 h = ffm->frame_offset;
42 if (ffm->first_packet)
43 h |= 0x8000;
44 put_be16(pb, h);
45 put_buffer(pb, ffm->packet, ffm->packet_end - ffm->packet);
46 put_flush_packet(pb);
47
48 /* prepare next packet */
49 ffm->frame_offset = 0; /* no key frame */
50 ffm->packet_ptr = ffm->packet;
51 ffm->first_packet = 0;
52}
53
54/* 'first' is true if first data of a frame */
55static void ffm_write_data(AVFormatContext *s,
56 const uint8_t *buf, int size,
57 int64_t dts, int header)
58{
59 FFMContext *ffm = s->priv_data;
60 int len;
61
62 if (header && ffm->frame_offset == 0) {
63 ffm->frame_offset = ffm->packet_ptr - ffm->packet + FFM_HEADER_SIZE;
64 ffm->dts = dts;
65 }
66
67 /* write as many packets as needed */
68 while (size > 0) {
69 len = ffm->packet_end - ffm->packet_ptr;
70 if (len > size)
71 len = size;
72 memcpy(ffm->packet_ptr, buf, len);
73
74 ffm->packet_ptr += len;
75 buf += len;
76 size -= len;
77 if (ffm->packet_ptr >= ffm->packet_end)
78 flush_packet(s);
79 }
80}
81
82static int ffm_write_header(AVFormatContext *s)
83{
84 FFMContext *ffm = s->priv_data;
85 AVStream *st;
86 ByteIOContext *pb = s->pb;
87 AVCodecContext *codec;
88 int bit_rate, i;
89
90 ffm->packet_size = FFM_PACKET_SIZE;
91
92 /* header */
93 put_le32(pb, MKTAG('F', 'F', 'M', '1'));
94 put_be32(pb, ffm->packet_size);
95 /* XXX: store write position in other file ? */
96 put_be64(pb, ffm->packet_size); /* current write position */
97
98 put_be32(pb, s->nb_streams);
99 bit_rate = 0;
100 for(i=0;i<s->nb_streams;i++) {
101 st = s->streams[i];
102 bit_rate += st->codec->bit_rate;
103 }
104 put_be32(pb, bit_rate);
105
106 /* list of streams */
107 for(i=0;i<s->nb_streams;i++) {
108 st = s->streams[i];
109 av_set_pts_info(st, 64, 1, 1000000);
110
111 codec = st->codec;
112 /* generic info */
113 put_be32(pb, codec->codec_id);
114 put_byte(pb, codec->codec_type);
115 put_be32(pb, codec->bit_rate);
116 put_be32(pb, st->quality);
117 put_be32(pb, codec->flags);
118 put_be32(pb, codec->flags2);
119 put_be32(pb, codec->debug);
120 /* specific info */
121 switch(codec->codec_type) {
122 case CODEC_TYPE_VIDEO:
123 put_be32(pb, codec->time_base.num);
124 put_be32(pb, codec->time_base.den);
125 put_be16(pb, codec->width);
126 put_be16(pb, codec->height);
127 put_be16(pb, codec->gop_size);
128 put_be32(pb, codec->pix_fmt);
129 put_byte(pb, codec->qmin);
130 put_byte(pb, codec->qmax);
131 put_byte(pb, codec->max_qdiff);
132 put_be16(pb, (int) (codec->qcompress * 10000.0));
133 put_be16(pb, (int) (codec->qblur * 10000.0));
134 put_be32(pb, codec->bit_rate_tolerance);
135 put_strz(pb, codec->rc_eq);
136 put_be32(pb, codec->rc_max_rate);
137 put_be32(pb, codec->rc_min_rate);
138 put_be32(pb, codec->rc_buffer_size);
139 put_be64(pb, av_dbl2int(codec->i_quant_factor));
140 put_be64(pb, av_dbl2int(codec->b_quant_factor));
141 put_be64(pb, av_dbl2int(codec->i_quant_offset));
142 put_be64(pb, av_dbl2int(codec->b_quant_offset));
143 put_be32(pb, codec->dct_algo);
144 put_be32(pb, codec->strict_std_compliance);
145 put_be32(pb, codec->max_b_frames);
146 put_be32(pb, codec->luma_elim_threshold);
147 put_be32(pb, codec->chroma_elim_threshold);
148 put_be32(pb, codec->mpeg_quant);
149 put_be32(pb, codec->intra_dc_precision);
150 put_be32(pb, codec->me_method);
151 put_be32(pb, codec->mb_decision);
152 put_be32(pb, codec->nsse_weight);
153 put_be32(pb, codec->frame_skip_cmp);
154 put_be64(pb, av_dbl2int(codec->rc_buffer_aggressivity));
155 put_be32(pb, codec->codec_tag);
156 put_byte(pb, codec->thread_count);
157 break;
158 case CODEC_TYPE_AUDIO:
159 put_be32(pb, codec->sample_rate);
160 put_le16(pb, codec->channels);
161 put_le16(pb, codec->frame_size);
162 break;
163 default:
164 return -1;
165 }
166 if (codec->flags & CODEC_FLAG_GLOBAL_HEADER) {
167 put_be32(pb, codec->extradata_size);
168 put_buffer(pb, codec->extradata, codec->extradata_size);
169 }
170 }
171
172 /* flush until end of block reached */
173 while ((url_ftell(pb) % ffm->packet_size) != 0)
174 put_byte(pb, 0);
175
176 put_flush_packet(pb);
177
178 /* init packet mux */
179 ffm->packet_ptr = ffm->packet;
180 ffm->packet_end = ffm->packet + ffm->packet_size - FFM_HEADER_SIZE;
181 assert(ffm->packet_end >= ffm->packet);
182 ffm->frame_offset = 0;
183 ffm->dts = 0;
184 ffm->first_packet = 1;
185
186 return 0;
187}
188
189static int ffm_write_packet(AVFormatContext *s, AVPacket *pkt)
190{
191 int64_t dts;
192 uint8_t header[FRAME_HEADER_SIZE+4];
193 int header_size = FRAME_HEADER_SIZE;
194
195 dts = s->timestamp + pkt->dts;
196 /* packet size & key_frame */
197 header[0] = pkt->stream_index;
198 header[1] = 0;
199 if (pkt->flags & PKT_FLAG_KEY)
200 header[1] |= FLAG_KEY_FRAME;
201 AV_WB24(header+2, pkt->size);
202 AV_WB24(header+5, pkt->duration);
203 AV_WB64(header+8, s->timestamp + pkt->pts);
204 if (pkt->pts != pkt->dts) {
205 header[1] |= FLAG_DTS;
206 AV_WB32(header+16, pkt->pts - pkt->dts);
207 header_size += 4;
208 }
209 ffm_write_data(s, header, header_size, dts, 1);
210 ffm_write_data(s, pkt->data, pkt->size, dts, 0);
211
212 return 0;
213}
214
215static int ffm_write_trailer(AVFormatContext *s)
216{
217 ByteIOContext *pb = s->pb;
218 FFMContext *ffm = s->priv_data;
219
220 /* flush packets */
221 if (ffm->packet_ptr > ffm->packet)
222 flush_packet(s);
223
224 put_flush_packet(pb);
225
226 if (!url_is_streamed(pb)) {
227 int64_t size;
228 /* update the write offset */
229 size = url_ftell(pb);
230 url_fseek(pb, 8, SEEK_SET);
231 put_be64(pb, size);
232 put_flush_packet(pb);
233 }
234
235 return 0;
236}
237
238AVOutputFormat ffm_muxer = {
239 "ffm",
240 NULL_IF_CONFIG_SMALL("ffm format"),
241 "",
242 "ffm",
243 sizeof(FFMContext),
244 /* not really used */
245 CODEC_ID_MP2,
246 CODEC_ID_MPEG1VIDEO,
247 ffm_write_header,
248 ffm_write_packet,
249 ffm_write_trailer,
250};
diff --git a/src/plugins/ffmpeg/libavformat/file.c b/src/plugins/ffmpeg/libavformat/file.c
deleted file mode 100644
index 9640ff6..0000000
--- a/src/plugins/ffmpeg/libavformat/file.c
+++ /dev/null
@@ -1,120 +0,0 @@
1/*
2 * Buffered file io for ffmpeg system
3 * Copyright (c) 2001 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/avstring.h"
23#include "avformat.h"
24#include <fcntl.h>
25#include <unistd.h>
26#include <sys/time.h>
27#include <stdlib.h>
28#include "os_support.h"
29
30
31/* standard file protocol */
32
33static int file_open(URLContext *h, const char *filename, int flags)
34{
35 int access;
36 int fd;
37
38 av_strstart(filename, "file:", &filename);
39
40 if (flags & URL_RDWR) {
41 access = O_CREAT | O_TRUNC | O_RDWR;
42 } else if (flags & URL_WRONLY) {
43 access = O_CREAT | O_TRUNC | O_WRONLY;
44 } else {
45 access = O_RDONLY;
46 }
47#ifdef O_BINARY
48 access |= O_BINARY;
49#endif
50 fd = open(filename, access, 0666);
51 if (fd < 0)
52 return AVERROR(ENOENT);
53 h->priv_data = (void *)(size_t)fd;
54 return 0;
55}
56
57static int file_read(URLContext *h, unsigned char *buf, int size)
58{
59 int fd = (size_t)h->priv_data;
60 return read(fd, buf, size);
61}
62
63static int file_write(URLContext *h, unsigned char *buf, int size)
64{
65 int fd = (size_t)h->priv_data;
66 return write(fd, buf, size);
67}
68
69/* XXX: use llseek */
70static offset_t file_seek(URLContext *h, offset_t pos, int whence)
71{
72 int fd = (size_t)h->priv_data;
73 return lseek(fd, pos, whence);
74}
75
76static int file_close(URLContext *h)
77{
78 int fd = (size_t)h->priv_data;
79 return close(fd);
80}
81
82URLProtocol file_protocol = {
83 "file",
84 file_open,
85 file_read,
86 file_write,
87 file_seek,
88 file_close,
89};
90
91/* pipe protocol */
92
93static int pipe_open(URLContext *h, const char *filename, int flags)
94{
95 int fd;
96 char *final;
97 av_strstart(filename, "pipe:", &filename);
98
99 fd = strtol(filename, &final, 10);
100 if((filename == final) || *final ) {/* No digits found, or something like 10ab */
101 if (flags & URL_WRONLY) {
102 fd = 1;
103 } else {
104 fd = 0;
105 }
106 }
107#ifdef O_BINARY
108 setmode(fd, O_BINARY);
109#endif
110 h->priv_data = (void *)(size_t)fd;
111 h->is_streamed = 1;
112 return 0;
113}
114
115URLProtocol pipe_protocol = {
116 "pipe",
117 pipe_open,
118 file_read,
119 file_write,
120};
diff --git a/src/plugins/ffmpeg/libavformat/flic.c b/src/plugins/ffmpeg/libavformat/flic.c
deleted file mode 100644
index 62ea94e..0000000
--- a/src/plugins/ffmpeg/libavformat/flic.c
+++ /dev/null
@@ -1,208 +0,0 @@
1/*
2 * FLI/FLC Animation File Demuxer
3 * Copyright (c) 2003 The ffmpeg Project
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/**
23 * @file flic.c
24 * FLI/FLC file demuxer
25 * by Mike Melanson (melanson@pcisys.net)
26 * for more information on the .fli/.flc file format and all of its many
27 * variations, visit:
28 * http://www.compuphase.com/flic.htm
29 *
30 * This demuxer handles standard 0xAF11- and 0xAF12-type FLIs. It also
31 * handles special FLIs from the PC game "Magic Carpet".
32 */
33
34#include "avformat.h"
35
36#define FLIC_FILE_MAGIC_1 0xAF11
37#define FLIC_FILE_MAGIC_2 0xAF12
38#define FLIC_FILE_MAGIC_3 0xAF44 /* Flic Type for Extended FLX Format which
39 originated in Dave's Targa Animator (DTA) */
40#define FLIC_CHUNK_MAGIC_1 0xF1FA
41#define FLIC_CHUNK_MAGIC_2 0xF5FA
42#define FLIC_MC_SPEED 5 /* speed for Magic Carpet game FLIs */
43#define FLIC_DEFAULT_SPEED 5 /* for FLIs that have 0 speed */
44
45#define FLIC_HEADER_SIZE 128
46#define FLIC_PREAMBLE_SIZE 6
47
48typedef struct FlicDemuxContext {
49 int video_stream_index;
50 int frame_number;
51} FlicDemuxContext;
52
53static int flic_probe(AVProbeData *p)
54{
55 int magic_number;
56
57 if(p->buf_size < FLIC_HEADER_SIZE)
58 return 0;
59
60 magic_number = AV_RL16(&p->buf[4]);
61 if ((magic_number != FLIC_FILE_MAGIC_1) &&
62 (magic_number != FLIC_FILE_MAGIC_2) &&
63 (magic_number != FLIC_FILE_MAGIC_3))
64 return 0;
65
66 if(AV_RL16(&p->buf[0x10]) != FLIC_CHUNK_MAGIC_1){
67 if(AV_RL32(&p->buf[0x10]) > 2000)
68 return 0;
69 }
70
71 if( AV_RL16(&p->buf[0x08]) > 4096
72 || AV_RL16(&p->buf[0x0A]) > 4096)
73 return 0;
74
75
76 return AVPROBE_SCORE_MAX;
77}
78
79static int flic_read_header(AVFormatContext *s,
80 AVFormatParameters *ap)
81{
82 FlicDemuxContext *flic = s->priv_data;
83 ByteIOContext *pb = s->pb;
84 unsigned char header[FLIC_HEADER_SIZE];
85 AVStream *st;
86 int speed;
87 int magic_number;
88
89 flic->frame_number = 0;
90
91 /* load the whole header and pull out the width and height */
92 if (get_buffer(pb, header, FLIC_HEADER_SIZE) != FLIC_HEADER_SIZE)
93 return AVERROR(EIO);
94
95 magic_number = AV_RL16(&header[4]);
96 speed = AV_RL32(&header[0x10]);
97 if (speed == 0)
98 speed = FLIC_DEFAULT_SPEED;
99
100 /* initialize the decoder streams */
101 st = av_new_stream(s, 0);
102 if (!st)
103 return AVERROR(ENOMEM);
104 flic->video_stream_index = st->index;
105 st->codec->codec_type = CODEC_TYPE_VIDEO;
106 st->codec->codec_id = CODEC_ID_FLIC;
107 st->codec->codec_tag = 0; /* no fourcc */
108 st->codec->width = AV_RL16(&header[0x08]);
109 st->codec->height = AV_RL16(&header[0x0A]);
110
111 if (!st->codec->width || !st->codec->height) {
112 /* Ugly hack needed for the following sample: */
113 /* http://samples.mplayerhq.hu/fli-flc/fli-bugs/specular.flc */
114 av_log(s, AV_LOG_WARNING,
115 "File with no specified width/height. Trying 640x480.\n");
116 st->codec->width = 640;
117 st->codec->height = 480;
118 }
119
120 /* send over the whole 128-byte FLIC header */
121 st->codec->extradata_size = FLIC_HEADER_SIZE;
122 st->codec->extradata = av_malloc(FLIC_HEADER_SIZE);
123 memcpy(st->codec->extradata, header, FLIC_HEADER_SIZE);
124
125 /* Time to figure out the framerate: If there is a FLIC chunk magic
126 * number at offset 0x10, assume this is from the Bullfrog game,
127 * Magic Carpet. */
128 if (AV_RL16(&header[0x10]) == FLIC_CHUNK_MAGIC_1) {
129
130 av_set_pts_info(st, 64, FLIC_MC_SPEED, 70);
131
132 /* rewind the stream since the first chunk is at offset 12 */
133 url_fseek(pb, 12, SEEK_SET);
134
135 /* send over abbreviated FLIC header chunk */
136 av_free(st->codec->extradata);
137 st->codec->extradata_size = 12;
138 st->codec->extradata = av_malloc(12);
139 memcpy(st->codec->extradata, header, 12);
140
141 } else if (magic_number == FLIC_FILE_MAGIC_1) {
142 av_set_pts_info(st, 64, speed, 70);
143 } else if ((magic_number == FLIC_FILE_MAGIC_2) ||
144 (magic_number == FLIC_FILE_MAGIC_3)) {
145 av_set_pts_info(st, 64, speed, 1000);
146 } else {
147 av_log(s, AV_LOG_INFO, "Invalid or unsupported magic chunk in file\n");
148 return AVERROR_INVALIDDATA;
149 }
150
151 return 0;
152}
153
154static int flic_read_packet(AVFormatContext *s,
155 AVPacket *pkt)
156{
157 FlicDemuxContext *flic = s->priv_data;
158 ByteIOContext *pb = s->pb;
159 int packet_read = 0;
160 unsigned int size;
161 int magic;
162 int ret = 0;
163 unsigned char preamble[FLIC_PREAMBLE_SIZE];
164
165 while (!packet_read) {
166
167 if ((ret = get_buffer(pb, preamble, FLIC_PREAMBLE_SIZE)) !=
168 FLIC_PREAMBLE_SIZE) {
169 ret = AVERROR(EIO);
170 break;
171 }
172
173 size = AV_RL32(&preamble[0]);
174 magic = AV_RL16(&preamble[4]);
175
176 if (((magic == FLIC_CHUNK_MAGIC_1) || (magic == FLIC_CHUNK_MAGIC_2)) && size > FLIC_PREAMBLE_SIZE) {
177 if (av_new_packet(pkt, size)) {
178 ret = AVERROR(EIO);
179 break;
180 }
181 pkt->stream_index = flic->video_stream_index;
182 pkt->pts = flic->frame_number++;
183 pkt->pos = url_ftell(pb);
184 memcpy(pkt->data, preamble, FLIC_PREAMBLE_SIZE);
185 ret = get_buffer(pb, pkt->data + FLIC_PREAMBLE_SIZE,
186 size - FLIC_PREAMBLE_SIZE);
187 if (ret != size - FLIC_PREAMBLE_SIZE) {
188 av_free_packet(pkt);
189 ret = AVERROR(EIO);
190 }
191 packet_read = 1;
192 } else {
193 /* not interested in this chunk */
194 url_fseek(pb, size - 6, SEEK_CUR);
195 }
196 }
197
198 return ret;
199}
200
201AVInputFormat flic_demuxer = {
202 "flic",
203 NULL_IF_CONFIG_SMALL("FLI/FLC/FLX animation format"),
204 sizeof(FlicDemuxContext),
205 flic_probe,
206 flic_read_header,
207 flic_read_packet,
208};
diff --git a/src/plugins/ffmpeg/libavformat/flv.h b/src/plugins/ffmpeg/libavformat/flv.h
deleted file mode 100644
index ed02191..0000000
--- a/src/plugins/ffmpeg/libavformat/flv.h
+++ /dev/null
@@ -1,112 +0,0 @@
1/**
2 * @file flv.h
3 * FLV common header
4 *
5 * Copyright (c) 2006 The FFmpeg Project.
6 *
7 * This file is part of FFmpeg.
8 *
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23
24#ifndef FFMPEG_FLV_H
25#define FFMPEG_FLV_H
26
27/* offsets for packed values */
28#define FLV_AUDIO_SAMPLESSIZE_OFFSET 1
29#define FLV_AUDIO_SAMPLERATE_OFFSET 2
30#define FLV_AUDIO_CODECID_OFFSET 4
31
32#define FLV_VIDEO_FRAMETYPE_OFFSET 4
33
34/* bitmasks to isolate specific values */
35#define FLV_AUDIO_CHANNEL_MASK 0x01
36#define FLV_AUDIO_SAMPLESIZE_MASK 0x02
37#define FLV_AUDIO_SAMPLERATE_MASK 0x0c
38#define FLV_AUDIO_CODECID_MASK 0xf0
39
40#define FLV_VIDEO_CODECID_MASK 0x0f
41#define FLV_VIDEO_FRAMETYPE_MASK 0xf0
42
43#define AMF_END_OF_OBJECT 0x09
44
45enum {
46 FLV_HEADER_FLAG_HASVIDEO = 1,
47 FLV_HEADER_FLAG_HASAUDIO = 4,
48};
49
50enum {
51 FLV_TAG_TYPE_AUDIO = 0x08,
52 FLV_TAG_TYPE_VIDEO = 0x09,
53 FLV_TAG_TYPE_META = 0x12,
54};
55
56enum {
57 FLV_MONO = 0,
58 FLV_STEREO = 1,
59};
60
61enum {
62 FLV_SAMPLESSIZE_8BIT = 0,
63 FLV_SAMPLESSIZE_16BIT = 1 << FLV_AUDIO_SAMPLESSIZE_OFFSET,
64};
65
66enum {
67 FLV_SAMPLERATE_SPECIAL = 0, /**< signifies 5512Hz and 8000Hz in the case of NELLYMOSER */
68 FLV_SAMPLERATE_11025HZ = 1 << FLV_AUDIO_SAMPLERATE_OFFSET,
69 FLV_SAMPLERATE_22050HZ = 2 << FLV_AUDIO_SAMPLERATE_OFFSET,
70 FLV_SAMPLERATE_44100HZ = 3 << FLV_AUDIO_SAMPLERATE_OFFSET,
71};
72
73enum {
74 FLV_CODECID_PCM = 0,
75 FLV_CODECID_ADPCM = 1 << FLV_AUDIO_CODECID_OFFSET,
76 FLV_CODECID_MP3 = 2 << FLV_AUDIO_CODECID_OFFSET,
77 FLV_CODECID_PCM_LE = 3 << FLV_AUDIO_CODECID_OFFSET,
78 FLV_CODECID_NELLYMOSER_8HZ_MONO = 5 << FLV_AUDIO_CODECID_OFFSET,
79 FLV_CODECID_NELLYMOSER = 6 << FLV_AUDIO_CODECID_OFFSET,
80 FLV_CODECID_AAC = 10<< FLV_AUDIO_CODECID_OFFSET,
81};
82
83enum {
84 FLV_CODECID_H263 = 2,
85 FLV_CODECID_SCREEN = 3,
86 FLV_CODECID_VP6 = 4,
87 FLV_CODECID_VP6A = 5,
88 FLV_CODECID_SCREEN2 = 6,
89 FLV_CODECID_H264 = 7,
90};
91
92enum {
93 FLV_FRAME_KEY = 1 << FLV_VIDEO_FRAMETYPE_OFFSET,
94 FLV_FRAME_INTER = 2 << FLV_VIDEO_FRAMETYPE_OFFSET,
95 FLV_FRAME_DISP_INTER = 3 << FLV_VIDEO_FRAMETYPE_OFFSET,
96};
97
98typedef enum {
99 AMF_DATA_TYPE_NUMBER = 0x00,
100 AMF_DATA_TYPE_BOOL = 0x01,
101 AMF_DATA_TYPE_STRING = 0x02,
102 AMF_DATA_TYPE_OBJECT = 0x03,
103 AMF_DATA_TYPE_NULL = 0x05,
104 AMF_DATA_TYPE_UNDEFINED = 0x06,
105 AMF_DATA_TYPE_REFERENCE = 0x07,
106 AMF_DATA_TYPE_MIXEDARRAY = 0x08,
107 AMF_DATA_TYPE_ARRAY = 0x0a,
108 AMF_DATA_TYPE_DATE = 0x0b,
109 AMF_DATA_TYPE_UNSUPPORTED = 0x0d,
110} AMFDataType;
111
112#endif /* FFMPEG_FLV_H */
diff --git a/src/plugins/ffmpeg/libavformat/flvdec.c b/src/plugins/ffmpeg/libavformat/flvdec.c
deleted file mode 100644
index ad14d3b..0000000
--- a/src/plugins/ffmpeg/libavformat/flvdec.c
+++ /dev/null
@@ -1,429 +0,0 @@
1/*
2 * FLV demuxer
3 * Copyright (c) 2003 The FFmpeg Project.
4 *
5 * This demuxer will generate a 1 byte extradata for VP6F content.
6 * It is composed of:
7 * - upper 4bits: difference between encoded width and visible width
8 * - lower 4bits: difference between encoded height and visible height
9 *
10 * This file is part of FFmpeg.
11 *
12 * FFmpeg is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
16 *
17 * FFmpeg is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
21 *
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with FFmpeg; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 */
26#include "avformat.h"
27#include "flv.h"
28
29static int flv_probe(AVProbeData *p)
30{
31 const uint8_t *d;
32
33 d = p->buf;
34 if (d[0] == 'F' && d[1] == 'L' && d[2] == 'V' && d[3] < 5 && d[5]==0) {
35 return AVPROBE_SCORE_MAX;
36 }
37 return 0;
38}
39
40static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream, int flv_codecid) {
41 AVCodecContext *acodec = astream->codec;
42 switch(flv_codecid) {
43 //no distinction between S16 and S8 PCM codec flags
44 case FLV_CODECID_PCM:
45 acodec->codec_id = acodec->bits_per_sample == 8 ? CODEC_ID_PCM_S8 :
46#ifdef WORDS_BIGENDIAN
47 CODEC_ID_PCM_S16BE;
48#else
49 CODEC_ID_PCM_S16LE;
50#endif
51 break;
52 case FLV_CODECID_PCM_LE:
53 acodec->codec_id = acodec->bits_per_sample == 8 ? CODEC_ID_PCM_S8 : CODEC_ID_PCM_S16LE; break;
54 case FLV_CODECID_AAC : acodec->codec_id = CODEC_ID_AAC; break;
55 case FLV_CODECID_ADPCM: acodec->codec_id = CODEC_ID_ADPCM_SWF; break;
56 case FLV_CODECID_MP3 : acodec->codec_id = CODEC_ID_MP3 ; astream->need_parsing = AVSTREAM_PARSE_FULL; break;
57 case FLV_CODECID_NELLYMOSER_8HZ_MONO:
58 acodec->sample_rate = 8000; //in case metadata does not otherwise declare samplerate
59 case FLV_CODECID_NELLYMOSER:
60 acodec->codec_id = CODEC_ID_NELLYMOSER;
61 break;
62 default:
63 av_log(s, AV_LOG_INFO, "Unsupported audio codec (%x)\n", flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
64 acodec->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
65 }
66}
67
68static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid) {
69 AVCodecContext *vcodec = vstream->codec;
70 switch(flv_codecid) {
71 case FLV_CODECID_H263 : vcodec->codec_id = CODEC_ID_FLV1 ; break;
72 case FLV_CODECID_SCREEN: vcodec->codec_id = CODEC_ID_FLASHSV; break;
73 case FLV_CODECID_VP6 : vcodec->codec_id = CODEC_ID_VP6F ;
74 case FLV_CODECID_VP6A :
75 if(flv_codecid == FLV_CODECID_VP6A)
76 vcodec->codec_id = CODEC_ID_VP6A;
77 if(vcodec->extradata_size != 1) {
78 vcodec->extradata_size = 1;
79 vcodec->extradata = av_malloc(1);
80 }
81 vcodec->extradata[0] = get_byte(s->pb);
82 return 1; // 1 byte body size adjustment for flv_read_packet()
83 case FLV_CODECID_H264:
84 vcodec->codec_id = CODEC_ID_H264;
85 return 3; // not 4, reading packet type will consume one byte
86 default:
87 av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid);
88 vcodec->codec_tag = flv_codecid;
89 }
90
91 return 0;
92}
93
94static int amf_get_string(ByteIOContext *ioc, char *buffer, int buffsize) {
95 int length = get_be16(ioc);
96 if(length >= buffsize) {
97 url_fskip(ioc, length);
98 return -1;
99 }
100
101 get_buffer(ioc, buffer, length);
102
103 buffer[length] = '\0';
104
105 return length;
106}
107
108static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vstream, const char *key, unsigned int max_pos, int depth) {
109 AVCodecContext *acodec, *vcodec;
110 ByteIOContext *ioc;
111 AMFDataType amf_type;
112 char str_val[256];
113 double num_val;
114
115 num_val = 0;
116 ioc = s->pb;
117
118 amf_type = get_byte(ioc);
119
120 switch(amf_type) {
121 case AMF_DATA_TYPE_NUMBER:
122 num_val = av_int2dbl(get_be64(ioc)); break;
123 case AMF_DATA_TYPE_BOOL:
124 num_val = get_byte(ioc); break;
125 case AMF_DATA_TYPE_STRING:
126 if(amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
127 return -1;
128 break;
129 case AMF_DATA_TYPE_OBJECT: {
130 unsigned int keylen;
131
132 while(url_ftell(ioc) < max_pos - 2 && (keylen = get_be16(ioc))) {
133 url_fskip(ioc, keylen); //skip key string
134 if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
135 return -1; //if we couldn't skip, bomb out.
136 }
137 if(get_byte(ioc) != AMF_END_OF_OBJECT)
138 return -1;
139 }
140 break;
141 case AMF_DATA_TYPE_NULL:
142 case AMF_DATA_TYPE_UNDEFINED:
143 case AMF_DATA_TYPE_UNSUPPORTED:
144 break; //these take up no additional space
145 case AMF_DATA_TYPE_MIXEDARRAY:
146 url_fskip(ioc, 4); //skip 32-bit max array index
147 while(url_ftell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
148 //this is the only case in which we would want a nested parse to not skip over the object
149 if(amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
150 return -1;
151 }
152 if(get_byte(ioc) != AMF_END_OF_OBJECT)
153 return -1;
154 break;
155 case AMF_DATA_TYPE_ARRAY: {
156 unsigned int arraylen, i;
157
158 arraylen = get_be32(ioc);
159 for(i = 0; i < arraylen && url_ftell(ioc) < max_pos - 1; i++) {
160 if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
161 return -1; //if we couldn't skip, bomb out.
162 }
163 }
164 break;
165 case AMF_DATA_TYPE_DATE:
166 url_fskip(ioc, 8 + 2); //timestamp (double) and UTC offset (int16)
167 break;
168 default: //unsupported type, we couldn't skip
169 return -1;
170 }
171
172 if(depth == 1 && key) { //only look for metadata values when we are not nested and key != NULL
173 acodec = astream ? astream->codec : NULL;
174 vcodec = vstream ? vstream->codec : NULL;
175
176 if(amf_type == AMF_DATA_TYPE_BOOL) {
177 if(!strcmp(key, "stereo") && acodec) acodec->channels = num_val > 0 ? 2 : 1;
178 } else if(amf_type == AMF_DATA_TYPE_NUMBER) {
179 if(!strcmp(key, "duration")) s->duration = num_val * AV_TIME_BASE;
180// else if(!strcmp(key, "width") && vcodec && num_val > 0) vcodec->width = num_val;
181// else if(!strcmp(key, "height") && vcodec && num_val > 0) vcodec->height = num_val;
182 else if(!strcmp(key, "audiocodecid") && acodec && 0 <= (int)num_val)
183 flv_set_audio_codec(s, astream, (int)num_val << FLV_AUDIO_CODECID_OFFSET);
184 else if(!strcmp(key, "videocodecid") && vcodec && 0 <= (int)num_val)
185 flv_set_video_codec(s, vstream, (int)num_val);
186 else if(!strcmp(key, "audiosamplesize") && acodec && 0 < (int)num_val) {
187 acodec->bits_per_sample = num_val;
188 //we may have to rewrite a previously read codecid because FLV only marks PCM endianness.
189 if(num_val == 8 && (acodec->codec_id == CODEC_ID_PCM_S16BE || acodec->codec_id == CODEC_ID_PCM_S16LE))
190 acodec->codec_id = CODEC_ID_PCM_S8;
191 }
192 else if(!strcmp(key, "audiosamplerate") && acodec && num_val >= 0) {
193 //some tools, like FLVTool2, write consistently approximate metadata sample rates
194 if (!acodec->sample_rate) {
195 switch((int)num_val) {
196 case 44000: acodec->sample_rate = 44100 ; break;
197 case 22000: acodec->sample_rate = 22050 ; break;
198 case 11000: acodec->sample_rate = 11025 ; break;
199 case 5000 : acodec->sample_rate = 5512 ; break;
200 default : acodec->sample_rate = num_val;
201 }
202 }
203 }
204 }
205 }
206
207 return 0;
208}
209
210static int flv_read_metabody(AVFormatContext *s, unsigned int next_pos) {
211 AMFDataType type;
212 AVStream *stream, *astream, *vstream;
213 ByteIOContext *ioc;
214 int i, keylen;
215 char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want.
216
217 astream = NULL;
218 vstream = NULL;
219 keylen = 0;
220 ioc = s->pb;
221
222 //first object needs to be "onMetaData" string
223 type = get_byte(ioc);
224 if(type != AMF_DATA_TYPE_STRING || amf_get_string(ioc, buffer, sizeof(buffer)) < 0 || strcmp(buffer, "onMetaData"))
225 return -1;
226
227 //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called.
228 for(i = 0; i < s->nb_streams; i++) {
229 stream = s->streams[i];
230 if (stream->codec->codec_type == CODEC_TYPE_AUDIO) astream = stream;
231 else if(stream->codec->codec_type == CODEC_TYPE_VIDEO) vstream = stream;
232 }
233
234 //parse the second object (we want a mixed array)
235 if(amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
236 return -1;
237
238 return 0;
239}
240
241static AVStream *create_stream(AVFormatContext *s, int is_audio){
242 AVStream *st = av_new_stream(s, is_audio);
243 if (!st)
244 return NULL;
245 st->codec->codec_type = is_audio ? CODEC_TYPE_AUDIO : CODEC_TYPE_VIDEO;
246 av_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
247 return st;
248}
249
250static int flv_read_header(AVFormatContext *s,
251 AVFormatParameters *ap)
252{
253 int offset, flags;
254
255 url_fskip(s->pb, 4);
256 flags = get_byte(s->pb);
257 /* old flvtool cleared this field */
258 /* FIXME: better fix needed */
259 if (!flags) {
260 flags = FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO;
261 av_log(s, AV_LOG_WARNING, "Broken FLV file, which says no streams present, this might fail\n");
262 }
263
264 if((flags & (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
265 != (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
266 s->ctx_flags |= AVFMTCTX_NOHEADER;
267
268 if(flags & FLV_HEADER_FLAG_HASVIDEO){
269 if(!create_stream(s, 0))
270 return AVERROR(ENOMEM);
271 }
272 if(flags & FLV_HEADER_FLAG_HASAUDIO){
273 if(!create_stream(s, 1))
274 return AVERROR(ENOMEM);
275 }
276
277 offset = get_be32(s->pb);
278 url_fseek(s->pb, offset, SEEK_SET);
279
280 s->start_time = 0;
281
282 return 0;
283}
284
285static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
286{
287 av_free(st->codec->extradata);
288 st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
289 if (!st->codec->extradata)
290 return AVERROR(ENOMEM);
291 st->codec->extradata_size = size;
292 get_buffer(s->pb, st->codec->extradata, st->codec->extradata_size);
293 return 0;
294}
295
296static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
297{
298 int ret, i, type, size, flags, is_audio, next, pos;
299 unsigned dts;
300 AVStream *st = NULL;
301
302 retry:
303 for(;;){
304 pos = url_ftell(s->pb);
305 url_fskip(s->pb, 4); /* size of previous packet */
306 type = get_byte(s->pb);
307 size = get_be24(s->pb);
308 dts = get_be24(s->pb);
309 dts |= get_byte(s->pb) << 24;
310// av_log(s, AV_LOG_DEBUG, "type:%d, size:%d, dts:%d\n", type, size, dts);
311 if (url_feof(s->pb))
312 return AVERROR(EIO);
313 url_fskip(s->pb, 3); /* stream id, always 0 */
314 flags = 0;
315
316 if(size == 0)
317 continue;
318
319 next= size + url_ftell(s->pb);
320
321 if (type == FLV_TAG_TYPE_AUDIO) {
322 is_audio=1;
323 flags = get_byte(s->pb);
324 } else if (type == FLV_TAG_TYPE_VIDEO) {
325 is_audio=0;
326 flags = get_byte(s->pb);
327 } else {
328 if (type == FLV_TAG_TYPE_META && size > 13+1+4)
329 flv_read_metabody(s, next);
330 else /* skip packet */
331 av_log(s, AV_LOG_ERROR, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
332 url_fseek(s->pb, next, SEEK_SET);
333 continue;
334 }
335
336 /* now find stream */
337 for(i=0;i<s->nb_streams;i++) {
338 st = s->streams[i];
339 if (st->id == is_audio)
340 break;
341 }
342 if(i == s->nb_streams){
343 av_log(NULL, AV_LOG_ERROR, "invalid stream\n");
344 st= create_stream(s, is_audio);
345 s->ctx_flags &= ~AVFMTCTX_NOHEADER;
346 }
347// av_log(NULL, AV_LOG_DEBUG, "%d %X %d \n", is_audio, flags, st->discard);
348 if( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || is_audio))
349 ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && !is_audio))
350 || st->discard >= AVDISCARD_ALL
351 ){
352 url_fseek(s->pb, next, SEEK_SET);
353 continue;
354 }
355 if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
356 av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
357 break;
358 }
359
360 // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
361 if(!url_is_streamed(s->pb) && s->duration==AV_NOPTS_VALUE){
362 int size;
363 const int pos= url_ftell(s->pb);
364 const int fsize= url_fsize(s->pb);
365 url_fseek(s->pb, fsize-4, SEEK_SET);
366 size= get_be32(s->pb);
367 url_fseek(s->pb, fsize-3-size, SEEK_SET);
368 if(size == get_be24(s->pb) + 11){
369 s->duration= get_be24(s->pb) * (int64_t)AV_TIME_BASE / 1000;
370 }
371 url_fseek(s->pb, pos, SEEK_SET);
372 }
373
374 if(is_audio){
375 if(!st->codec->sample_rate || !st->codec->bits_per_sample || (!st->codec->codec_id && !st->codec->codec_tag)) {
376 st->codec->channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
377 if((flags & FLV_AUDIO_CODECID_MASK) == FLV_CODECID_NELLYMOSER_8HZ_MONO)
378 st->codec->sample_rate= 8000;
379 else
380 st->codec->sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
381 st->codec->bits_per_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
382 flv_set_audio_codec(s, st, flags & FLV_AUDIO_CODECID_MASK);
383 }
384 }else{
385 size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK);
386 }
387
388 if (st->codec->codec_id == CODEC_ID_AAC ||
389 st->codec->codec_id == CODEC_ID_H264) {
390 int type = get_byte(s->pb);
391 size--;
392 if (st->codec->codec_id == CODEC_ID_H264) {
393 // cts offset ignored because it might to be signed
394 // and would cause pts < dts
395 get_be24(s->pb);
396 }
397 if (type == 0) {
398 if ((ret = flv_get_extradata(s, st, size - 1)) < 0)
399 return ret;
400 goto retry;
401 }
402 }
403
404 ret= av_get_packet(s->pb, pkt, size - 1);
405 if (ret <= 0) {
406 return AVERROR(EIO);
407 }
408 /* note: we need to modify the packet size here to handle the last
409 packet */
410 pkt->size = ret;
411 pkt->dts = dts;
412 pkt->stream_index = st->index;
413
414 if (is_audio || ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY))
415 pkt->flags |= PKT_FLAG_KEY;
416
417 return ret;
418}
419
420AVInputFormat flv_demuxer = {
421 "flv",
422 NULL_IF_CONFIG_SMALL("FLV format"),
423 0,
424 flv_probe,
425 flv_read_header,
426 flv_read_packet,
427 .extensions = "flv",
428 .value = CODEC_ID_FLV1,
429};
diff --git a/src/plugins/ffmpeg/libavformat/flvenc.c b/src/plugins/ffmpeg/libavformat/flvenc.c
deleted file mode 100644
index 2941356..0000000
--- a/src/plugins/ffmpeg/libavformat/flvenc.c
+++ /dev/null
@@ -1,392 +0,0 @@
1/*
2 * FLV muxer
3 * Copyright (c) 2003 The FFmpeg Project.
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#include "avformat.h"
22#include "flv.h"
23#include "riff.h"
24#include "avc.h"
25
26#undef NDEBUG
27#include <assert.h>
28
29static const AVCodecTag flv_video_codec_ids[] = {
30 {CODEC_ID_FLV1, FLV_CODECID_H263 },
31 {CODEC_ID_FLASHSV, FLV_CODECID_SCREEN},
32 {CODEC_ID_VP6F, FLV_CODECID_VP6 },
33 {CODEC_ID_VP6, FLV_CODECID_VP6 },
34 {CODEC_ID_H264, FLV_CODECID_H264 },
35 {CODEC_ID_NONE, 0}
36};
37
38static const AVCodecTag flv_audio_codec_ids[] = {
39 {CODEC_ID_MP3, FLV_CODECID_MP3 >> FLV_AUDIO_CODECID_OFFSET},
40 {CODEC_ID_PCM_S8, FLV_CODECID_PCM >> FLV_AUDIO_CODECID_OFFSET},
41 {CODEC_ID_PCM_S16BE, FLV_CODECID_PCM >> FLV_AUDIO_CODECID_OFFSET},
42 {CODEC_ID_PCM_S16LE, FLV_CODECID_PCM_LE >> FLV_AUDIO_CODECID_OFFSET},
43 {CODEC_ID_ADPCM_SWF, FLV_CODECID_ADPCM >> FLV_AUDIO_CODECID_OFFSET},
44 {CODEC_ID_AAC, FLV_CODECID_AAC >> FLV_AUDIO_CODECID_OFFSET},
45 {CODEC_ID_NELLYMOSER, FLV_CODECID_NELLYMOSER >> FLV_AUDIO_CODECID_OFFSET},
46 {CODEC_ID_NONE, 0}
47};
48
49typedef struct FLVContext {
50 int reserved;
51 offset_t duration_offset;
52 offset_t filesize_offset;
53 int64_t duration;
54 int delay; ///< first dts delay for AVC
55} FLVContext;
56
57static int get_audio_flags(AVCodecContext *enc){
58 int flags = (enc->bits_per_sample == 16) ? FLV_SAMPLESSIZE_16BIT : FLV_SAMPLESSIZE_8BIT;
59
60 if (enc->codec_id == CODEC_ID_AAC) // specs force these parameters
61 return FLV_CODECID_AAC | FLV_SAMPLERATE_44100HZ | FLV_SAMPLESSIZE_16BIT | FLV_STEREO;
62 else {
63 switch (enc->sample_rate) {
64 case 44100:
65 flags |= FLV_SAMPLERATE_44100HZ;
66 break;
67 case 22050:
68 flags |= FLV_SAMPLERATE_22050HZ;
69 break;
70 case 11025:
71 flags |= FLV_SAMPLERATE_11025HZ;
72 break;
73 case 8000: //nellymoser only
74 case 5512: //not mp3
75 if(enc->codec_id != CODEC_ID_MP3){
76 flags |= FLV_SAMPLERATE_SPECIAL;
77 break;
78 }
79 default:
80 av_log(enc, AV_LOG_ERROR, "flv does not support that sample rate, choose from (44100, 22050, 11025).\n");
81 return -1;
82 }
83 }
84
85 if (enc->channels > 1) {
86 flags |= FLV_STEREO;
87 }
88
89 switch(enc->codec_id){
90 case CODEC_ID_MP3:
91 flags |= FLV_CODECID_MP3 | FLV_SAMPLESSIZE_16BIT;
92 break;
93 case CODEC_ID_PCM_S8:
94 flags |= FLV_CODECID_PCM | FLV_SAMPLESSIZE_8BIT;
95 break;
96 case CODEC_ID_PCM_S16BE:
97 flags |= FLV_CODECID_PCM | FLV_SAMPLESSIZE_16BIT;
98 break;
99 case CODEC_ID_PCM_S16LE:
100 flags |= FLV_CODECID_PCM_LE | FLV_SAMPLESSIZE_16BIT;
101 break;
102 case CODEC_ID_ADPCM_SWF:
103 flags |= FLV_CODECID_ADPCM | FLV_SAMPLESSIZE_16BIT;
104 break;
105 case CODEC_ID_NELLYMOSER:
106 flags |= FLV_CODECID_NELLYMOSER | FLV_SAMPLESSIZE_16BIT;
107 break;
108 case 0:
109 flags |= enc->codec_tag<<4;
110 break;
111 default:
112 av_log(enc, AV_LOG_ERROR, "codec not compatible with flv\n");
113 return -1;
114 }
115
116 return flags;
117}
118
119static void put_amf_string(ByteIOContext *pb, const char *str)
120{
121 size_t len = strlen(str);
122 put_be16(pb, len);
123 put_buffer(pb, str, len);
124}
125
126static void put_amf_double(ByteIOContext *pb, double d)
127{
128 put_byte(pb, AMF_DATA_TYPE_NUMBER);
129 put_be64(pb, av_dbl2int(d));
130}
131
132static void put_amf_bool(ByteIOContext *pb, int b) {
133 put_byte(pb, AMF_DATA_TYPE_BOOL);
134 put_byte(pb, !!b);
135}
136
137static int flv_write_header(AVFormatContext *s)
138{
139 ByteIOContext *pb = s->pb;
140 FLVContext *flv = s->priv_data;
141 AVCodecContext *audio_enc = NULL, *video_enc = NULL;
142 int i;
143 double framerate = 0.0;
144 int metadata_size_pos, data_size;
145
146 for(i=0; i<s->nb_streams; i++){
147 AVCodecContext *enc = s->streams[i]->codec;
148 if (enc->codec_type == CODEC_TYPE_VIDEO) {
149 if (s->streams[i]->r_frame_rate.den && s->streams[i]->r_frame_rate.num) {
150 framerate = av_q2d(s->streams[i]->r_frame_rate);
151 } else {
152 framerate = 1/av_q2d(s->streams[i]->codec->time_base);
153 }
154 video_enc = enc;
155 if(enc->codec_tag == 0) {
156 av_log(enc, AV_LOG_ERROR, "video codec not compatible with flv\n");
157 return -1;
158 }
159 } else {
160 audio_enc = enc;
161 if(get_audio_flags(enc)<0)
162 return -1;
163 }
164 av_set_pts_info(s->streams[i], 32, 1, 1000); /* 32 bit pts in ms */
165 }
166 put_tag(pb,"FLV");
167 put_byte(pb,1);
168 put_byte(pb, FLV_HEADER_FLAG_HASAUDIO * !!audio_enc
169 + FLV_HEADER_FLAG_HASVIDEO * !!video_enc);
170 put_be32(pb,9);
171 put_be32(pb,0);
172
173 for(i=0; i<s->nb_streams; i++){
174 if(s->streams[i]->codec->codec_tag == 5){
175 put_byte(pb,8); // message type
176 put_be24(pb,0); // include flags
177 put_be24(pb,0); // time stamp
178 put_be32(pb,0); // reserved
179 put_be32(pb,11); // size
180 flv->reserved=5;
181 }
182 }
183
184 /* write meta_tag */
185 put_byte(pb, 18); // tag type META
186 metadata_size_pos= url_ftell(pb);
187 put_be24(pb, 0); // size of data part (sum of all parts below)
188 put_be24(pb, 0); // time stamp
189 put_be32(pb, 0); // reserved
190
191 /* now data of data_size size */
192
193 /* first event name as a string */
194 put_byte(pb, AMF_DATA_TYPE_STRING);
195 put_amf_string(pb, "onMetaData"); // 12 bytes
196
197 /* mixed array (hash) with size and string/type/data tuples */
198 put_byte(pb, AMF_DATA_TYPE_MIXEDARRAY);
199 put_be32(pb, 5*!!video_enc + 4*!!audio_enc + 2); // +2 for duration and file size
200
201 put_amf_string(pb, "duration");
202 flv->duration_offset= url_ftell(pb);
203 put_amf_double(pb, 0); // delayed write
204
205 if(video_enc){
206 put_amf_string(pb, "width");
207 put_amf_double(pb, video_enc->width);
208
209 put_amf_string(pb, "height");
210 put_amf_double(pb, video_enc->height);
211
212 put_amf_string(pb, "videodatarate");
213 put_amf_double(pb, s->bit_rate / 1024.0);
214
215 put_amf_string(pb, "framerate");
216 put_amf_double(pb, framerate);
217
218 put_amf_string(pb, "videocodecid");
219 put_amf_double(pb, video_enc->codec_tag);
220 }
221
222 if(audio_enc){
223 put_amf_string(pb, "audiosamplerate");
224 put_amf_double(pb, audio_enc->sample_rate);
225
226 put_amf_string(pb, "audiosamplesize");
227 put_amf_double(pb, audio_enc->codec_id == CODEC_ID_PCM_S8 ? 8 : 16);
228
229 put_amf_string(pb, "stereo");
230 put_amf_bool(pb, audio_enc->channels == 2);
231
232 put_amf_string(pb, "audiocodecid");
233 put_amf_double(pb, audio_enc->codec_tag);
234 }
235
236 put_amf_string(pb, "filesize");
237 flv->filesize_offset= url_ftell(pb);
238 put_amf_double(pb, 0); // delayed write
239
240 put_amf_string(pb, "");
241 put_byte(pb, AMF_END_OF_OBJECT);
242
243 /* write total size of tag */
244 data_size= url_ftell(pb) - metadata_size_pos - 10;
245 url_fseek(pb, metadata_size_pos, SEEK_SET);
246 put_be24(pb, data_size);
247 url_fseek(pb, data_size + 10 - 3, SEEK_CUR);
248 put_be32(pb, data_size + 11);
249
250 for (i = 0; i < s->nb_streams; i++) {
251 AVCodecContext *enc = s->streams[i]->codec;
252 if (enc->codec_id == CODEC_ID_AAC || enc->codec_id == CODEC_ID_H264) {
253 offset_t pos;
254 put_byte(pb, enc->codec_type == CODEC_TYPE_VIDEO ?
255 FLV_TAG_TYPE_VIDEO : FLV_TAG_TYPE_AUDIO);
256 put_be24(pb, 0); // size patched later
257 put_be24(pb, 0); // ts
258 put_byte(pb, 0); // ts ext
259 put_be24(pb, 0); // streamid
260 pos = url_ftell(pb);
261 if (enc->codec_id == CODEC_ID_AAC) {
262 put_byte(pb, get_audio_flags(enc));
263 put_byte(pb, 0); // AAC sequence header
264 put_buffer(pb, enc->extradata, enc->extradata_size);
265 } else {
266 put_byte(pb, enc->codec_tag | FLV_FRAME_KEY); // flags
267 put_byte(pb, 0); // AVC sequence header
268 put_be24(pb, 0); // composition time
269 ff_isom_write_avcc(pb, enc->extradata, enc->extradata_size);
270 }
271 data_size = url_ftell(pb) - pos;
272 url_fseek(pb, -data_size - 10, SEEK_CUR);
273 put_be24(pb, data_size);
274 url_fseek(pb, data_size + 10 - 3, SEEK_CUR);
275 put_be32(pb, data_size + 11); // previous tag size
276 }
277 }
278
279 return 0;
280}
281
282static int flv_write_trailer(AVFormatContext *s)
283{
284 int64_t file_size;
285
286 ByteIOContext *pb = s->pb;
287 FLVContext *flv = s->priv_data;
288
289 file_size = url_ftell(pb);
290
291 /* update informations */
292 url_fseek(pb, flv->duration_offset, SEEK_SET);
293 put_amf_double(pb, flv->duration / (double)1000);
294 url_fseek(pb, flv->filesize_offset, SEEK_SET);
295 put_amf_double(pb, file_size);
296
297 url_fseek(pb, file_size, SEEK_SET);
298 return 0;
299}
300
301static int flv_write_packet(AVFormatContext *s, AVPacket *pkt)
302{
303 ByteIOContext *pb = s->pb;
304 AVCodecContext *enc = s->streams[pkt->stream_index]->codec;
305 FLVContext *flv = s->priv_data;
306 unsigned ts;
307 int size= pkt->size;
308 int flags, flags_size;
309
310// av_log(s, AV_LOG_DEBUG, "type:%d pts: %"PRId64" size:%d\n", enc->codec_type, timestamp, size);
311
312 if(enc->codec_id == CODEC_ID_VP6 || enc->codec_id == CODEC_ID_VP6F ||
313 enc->codec_id == CODEC_ID_AAC)
314 flags_size= 2;
315 else if(enc->codec_id == CODEC_ID_H264)
316 flags_size= 5;
317 else
318 flags_size= 1;
319
320 if (enc->codec_type == CODEC_TYPE_VIDEO) {
321 put_byte(pb, FLV_TAG_TYPE_VIDEO);
322
323 flags = enc->codec_tag;
324 if(flags == 0) {
325 av_log(enc, AV_LOG_ERROR, "video codec %X not compatible with flv\n",enc->codec_id);
326 return -1;
327 }
328
329 flags |= pkt->flags & PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER;
330 } else {
331 assert(enc->codec_type == CODEC_TYPE_AUDIO);
332 flags = get_audio_flags(enc);
333
334 assert(size);
335
336 put_byte(pb, FLV_TAG_TYPE_AUDIO);
337 }
338
339 if (enc->codec_id == CODEC_ID_H264 &&
340 /* check if extradata looks like mp4 formated */
341 enc->extradata_size > 0 && *(uint8_t*)enc->extradata != 1) {
342 if (ff_avc_parse_nal_units(pkt->data, &pkt->data, &pkt->size) < 0)
343 return -1;
344 assert(pkt->size);
345 size = pkt->size;
346 /* cast needed to get negative value */
347 if (!flv->delay && (int32_t)pkt->dts < 0)
348 flv->delay = -(int32_t)pkt->dts;
349 }
350
351 ts = pkt->dts + flv->delay; // add delay to force positive dts
352 put_be24(pb,size + flags_size);
353 put_be24(pb,ts);
354 put_byte(pb,ts >> 24);
355 put_be24(pb,flv->reserved);
356 put_byte(pb,flags);
357 if (enc->codec_id == CODEC_ID_VP6)
358 put_byte(pb,0);
359 if (enc->codec_id == CODEC_ID_VP6F)
360 put_byte(pb, enc->extradata_size ? enc->extradata[0] : 0);
361 else if (enc->codec_id == CODEC_ID_AAC)
362 put_byte(pb,1); // AAC raw
363 else if (enc->codec_id == CODEC_ID_H264) {
364 put_byte(pb,1); // AVC NALU
365 put_be24(pb,pkt->pts - (int32_t)pkt->dts);
366 }
367 put_buffer(pb, pkt->data, size);
368 put_be32(pb,size+flags_size+11); // previous tag size
369 flv->duration = FFMAX(flv->duration, pkt->pts + flv->delay + pkt->duration);
370
371 put_flush_packet(pb);
372 return 0;
373}
374
375AVOutputFormat flv_muxer = {
376 "flv",
377 NULL_IF_CONFIG_SMALL("FLV format"),
378 "video/x-flv",
379 "flv",
380 sizeof(FLVContext),
381#ifdef CONFIG_LIBMP3LAME
382 CODEC_ID_MP3,
383#else // CONFIG_LIBMP3LAME
384 CODEC_ID_ADPCM_SWF,
385#endif // CONFIG_LIBMP3LAME
386 CODEC_ID_FLV1,
387 flv_write_header,
388 flv_write_packet,
389 flv_write_trailer,
390 .codec_tag= (const AVCodecTag*[]){flv_video_codec_ids, flv_audio_codec_ids, 0},
391 .flags= AVFMT_GLOBALHEADER,
392};
diff --git a/src/plugins/ffmpeg/libavformat/framecrcenc.c b/src/plugins/ffmpeg/libavformat/framecrcenc.c
deleted file mode 100644
index beb1bde..0000000
--- a/src/plugins/ffmpeg/libavformat/framecrcenc.c
+++ /dev/null
@@ -1,47 +0,0 @@
1/*
2 * frame CRC encoder (for codec/format testing)
3 * Copyright (c) 2002 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/adler32.h"
23#include "avformat.h"
24
25static int framecrc_write_packet(struct AVFormatContext *s, AVPacket *pkt)
26{
27 uint32_t crc = av_adler32_update(0, pkt->data, pkt->size);
28 char buf[256];
29
30 snprintf(buf, sizeof(buf), "%d, %"PRId64", %d, 0x%08x\n", pkt->stream_index, pkt->dts, pkt->size, crc);
31 put_buffer(s->pb, buf, strlen(buf));
32 put_flush_packet(s->pb);
33 return 0;
34}
35
36AVOutputFormat framecrc_muxer = {
37 "framecrc",
38 NULL_IF_CONFIG_SMALL("framecrc testing format"),
39 NULL,
40 "",
41 0,
42 CODEC_ID_PCM_S16LE,
43 CODEC_ID_RAWVIDEO,
44 NULL,
45 framecrc_write_packet,
46 NULL,
47};
diff --git a/src/plugins/ffmpeg/libavformat/framehook.c b/src/plugins/ffmpeg/libavformat/framehook.c
deleted file mode 100644
index eb5184f..0000000
--- a/src/plugins/ffmpeg/libavformat/framehook.c
+++ /dev/null
@@ -1,120 +0,0 @@
1/*
2 * Video processing hooks
3 * Copyright (c) 2000, 2001 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#include <errno.h>
22#include "config.h"
23#include "avformat.h"
24#include "framehook.h"
25
26#ifdef HAVE_DLFCN_H
27#include <dlfcn.h>
28#endif
29
30
31typedef struct FrameHookEntry {
32 struct FrameHookEntry *next;
33 FrameHookConfigureFn Configure;
34 FrameHookProcessFn Process;
35 FrameHookReleaseFn Release;
36 void *ctx;
37} FrameHookEntry;
38
39static FrameHookEntry *first_hook;
40
41/* Returns 0 on OK */
42int frame_hook_add(int argc, char *argv[])
43{
44#ifdef CONFIG_VHOOK
45 void *loaded;
46 FrameHookEntry *fhe, **fhep;
47
48 if (argc < 1) {
49 return ENOENT;
50 }
51
52 loaded = dlopen(argv[0], RTLD_NOW);
53 if (!loaded) {
54 av_log(NULL, AV_LOG_ERROR, "%s\n", dlerror());
55 return -1;
56 }
57
58 fhe = av_mallocz(sizeof(*fhe));
59 if (!fhe) {
60 return AVERROR(ENOMEM);
61 }
62
63 fhe->Configure = dlsym(loaded, "Configure");
64 fhe->Process = dlsym(loaded, "Process");
65 fhe->Release = dlsym(loaded, "Release"); /* Optional */
66
67 if (!fhe->Process) {
68 av_log(NULL, AV_LOG_ERROR, "Failed to find Process entrypoint in %s\n", argv[0]);
69 return AVERROR(ENOENT);
70 }
71
72 if (!fhe->Configure && argc > 1) {
73 av_log(NULL, AV_LOG_ERROR, "Failed to find Configure entrypoint in %s\n", argv[0]);
74 return AVERROR(ENOENT);
75 }
76
77 if (argc > 1 || fhe->Configure) {
78 if (fhe->Configure(&fhe->ctx, argc, argv)) {
79 av_log(NULL, AV_LOG_ERROR, "Failed to Configure %s\n", argv[0]);
80 return AVERROR(EINVAL);
81 }
82 }
83
84 for (fhep = &first_hook; *fhep; fhep = &((*fhep)->next)) {
85 }
86
87 *fhep = fhe;
88
89 return 0;
90#else
91 av_log(NULL, AV_LOG_ERROR, "Video hooking not compiled into this version\n");
92 return 1;
93#endif
94}
95
96void frame_hook_process(AVPicture *pict, enum PixelFormat pix_fmt, int width, int height, int64_t pts)
97{
98 if (first_hook) {
99 FrameHookEntry *fhe;
100
101 for (fhe = first_hook; fhe; fhe = fhe->next) {
102 fhe->Process(fhe->ctx, pict, pix_fmt, width, height, pts);
103 }
104 }
105}
106
107void frame_hook_release(void)
108{
109 FrameHookEntry *fhe;
110 FrameHookEntry *fhenext;
111
112 for (fhe = first_hook; fhe; fhe = fhenext) {
113 fhenext = fhe->next;
114 if (fhe->Release)
115 fhe->Release(fhe->ctx);
116 av_free(fhe);
117 }
118
119 first_hook = NULL;
120}
diff --git a/src/plugins/ffmpeg/libavformat/framehook.h b/src/plugins/ffmpeg/libavformat/framehook.h
deleted file mode 100644
index ce068d7..0000000
--- a/src/plugins/ffmpeg/libavformat/framehook.h
+++ /dev/null
@@ -1,52 +0,0 @@
1/*
2 * video processing hooks
3 * copyright (c) 2000, 2001 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#ifndef FFMPEG_FRAMEHOOK_H
23#define FFMPEG_FRAMEHOOK_H
24
25#warning VHOOK is deprecated. Please help finishing libavfilter instead of wasting your time writing new filters for this crappy filter system.
26
27/*
28 * Prototypes for interface to .so that implement a video processing hook
29 */
30
31#include "libavcodec/avcodec.h"
32
33/* Function must be called 'Configure' */
34typedef int (FrameHookConfigure)(void **ctxp, int argc, char *argv[]);
35typedef FrameHookConfigure *FrameHookConfigureFn;
36extern FrameHookConfigure Configure;
37
38/* Function must be called 'Process' */
39typedef void (FrameHookProcess)(void *ctx, struct AVPicture *pict, enum PixelFormat pix_fmt, int width, int height, int64_t pts);
40typedef FrameHookProcess *FrameHookProcessFn;
41extern FrameHookProcess Process;
42
43/* Function must be called 'Release' */
44typedef void (FrameHookRelease)(void *ctx);
45typedef FrameHookRelease *FrameHookReleaseFn;
46extern FrameHookRelease Release;
47
48extern int frame_hook_add(int argc, char *argv[]);
49extern void frame_hook_process(struct AVPicture *pict, enum PixelFormat pix_fmt, int width, int height, int64_t pts);
50extern void frame_hook_release(void);
51
52#endif /* FFMPEG_FRAMEHOOK_H */
diff --git a/src/plugins/ffmpeg/libavformat/gif.c b/src/plugins/ffmpeg/libavformat/gif.c
deleted file mode 100644
index 0c6686f..0000000
--- a/src/plugins/ffmpeg/libavformat/gif.c
+++ /dev/null
@@ -1,419 +0,0 @@
1/*
2 * Animated GIF muxer
3 * Copyright (c) 2000 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/*
23 * First version by Francois Revol revol@free.fr
24 *
25 * Features and limitations:
26 * - currently no compression is performed,
27 * in fact the size of the data is 9/8 the size of the image in 8bpp
28 * - uses only a global standard palette
29 * - tested with IE 5.0, Opera for BeOS, NetPositive (BeOS), and Mozilla (BeOS).
30 *
31 * Reference documents:
32 * http://www.goice.co.jp/member/mo/formats/gif.html
33 * http://astronomy.swin.edu.au/pbourke/dataformats/gif/
34 * http://www.dcs.ed.ac.uk/home/mxr/gfx/2d/GIF89a.txt
35 *
36 * this url claims to have an LZW algorithm not covered by Unisys patent:
37 * http://www.msg.net/utility/whirlgif/gifencod.html
38 * could help reduce the size of the files _a lot_...
39 * some sites mentions an RLE type compression also.
40 */
41
42#include "avformat.h"
43#include "libavcodec/bitstream.h"
44
45/* bitstream minipacket size */
46#define GIF_CHUNKS 100
47
48/* slows down the decoding (and some browsers don't like it) */
49/* update on the 'some browsers don't like it issue from above: this was probably due to missing 'Data Sub-block Terminator' (byte 19) in the app_header */
50#define GIF_ADD_APP_HEADER // required to enable looping of animated gif
51
52typedef struct {
53 unsigned char r;
54 unsigned char g;
55 unsigned char b;
56} rgb_triplet;
57
58/* we use the standard 216 color palette */
59
60/* this script was used to create the palette:
61 * for r in 00 33 66 99 cc ff; do for g in 00 33 66 99 cc ff; do echo -n " "; for b in 00 33 66 99 cc ff; do
62 * echo -n "{ 0x$r, 0x$g, 0x$b }, "; done; echo ""; done; done
63 */
64
65static const rgb_triplet gif_clut[216] = {
66 { 0x00, 0x00, 0x00 }, { 0x00, 0x00, 0x33 }, { 0x00, 0x00, 0x66 }, { 0x00, 0x00, 0x99 }, { 0x00, 0x00, 0xcc }, { 0x00, 0x00, 0xff },
67 { 0x00, 0x33, 0x00 }, { 0x00, 0x33, 0x33 }, { 0x00, 0x33, 0x66 }, { 0x00, 0x33, 0x99 }, { 0x00, 0x33, 0xcc }, { 0x00, 0x33, 0xff },
68 { 0x00, 0x66, 0x00 }, { 0x00, 0x66, 0x33 }, { 0x00, 0x66, 0x66 }, { 0x00, 0x66, 0x99 }, { 0x00, 0x66, 0xcc }, { 0x00, 0x66, 0xff },
69 { 0x00, 0x99, 0x00 }, { 0x00, 0x99, 0x33 }, { 0x00, 0x99, 0x66 }, { 0x00, 0x99, 0x99 }, { 0x00, 0x99, 0xcc }, { 0x00, 0x99, 0xff },
70 { 0x00, 0xcc, 0x00 }, { 0x00, 0xcc, 0x33 }, { 0x00, 0xcc, 0x66 }, { 0x00, 0xcc, 0x99 }, { 0x00, 0xcc, 0xcc }, { 0x00, 0xcc, 0xff },
71 { 0x00, 0xff, 0x00 }, { 0x00, 0xff, 0x33 }, { 0x00, 0xff, 0x66 }, { 0x00, 0xff, 0x99 }, { 0x00, 0xff, 0xcc }, { 0x00, 0xff, 0xff },
72 { 0x33, 0x00, 0x00 }, { 0x33, 0x00, 0x33 }, { 0x33, 0x00, 0x66 }, { 0x33, 0x00, 0x99 }, { 0x33, 0x00, 0xcc }, { 0x33, 0x00, 0xff },
73 { 0x33, 0x33, 0x00 }, { 0x33, 0x33, 0x33 }, { 0x33, 0x33, 0x66 }, { 0x33, 0x33, 0x99 }, { 0x33, 0x33, 0xcc }, { 0x33, 0x33, 0xff },
74 { 0x33, 0x66, 0x00 }, { 0x33, 0x66, 0x33 }, { 0x33, 0x66, 0x66 }, { 0x33, 0x66, 0x99 }, { 0x33, 0x66, 0xcc }, { 0x33, 0x66, 0xff },
75 { 0x33, 0x99, 0x00 }, { 0x33, 0x99, 0x33 }, { 0x33, 0x99, 0x66 }, { 0x33, 0x99, 0x99 }, { 0x33, 0x99, 0xcc }, { 0x33, 0x99, 0xff },
76 { 0x33, 0xcc, 0x00 }, { 0x33, 0xcc, 0x33 }, { 0x33, 0xcc, 0x66 }, { 0x33, 0xcc, 0x99 }, { 0x33, 0xcc, 0xcc }, { 0x33, 0xcc, 0xff },
77 { 0x33, 0xff, 0x00 }, { 0x33, 0xff, 0x33 }, { 0x33, 0xff, 0x66 }, { 0x33, 0xff, 0x99 }, { 0x33, 0xff, 0xcc }, { 0x33, 0xff, 0xff },
78 { 0x66, 0x00, 0x00 }, { 0x66, 0x00, 0x33 }, { 0x66, 0x00, 0x66 }, { 0x66, 0x00, 0x99 }, { 0x66, 0x00, 0xcc }, { 0x66, 0x00, 0xff },
79 { 0x66, 0x33, 0x00 }, { 0x66, 0x33, 0x33 }, { 0x66, 0x33, 0x66 }, { 0x66, 0x33, 0x99 }, { 0x66, 0x33, 0xcc }, { 0x66, 0x33, 0xff },
80 { 0x66, 0x66, 0x00 }, { 0x66, 0x66, 0x33 }, { 0x66, 0x66, 0x66 }, { 0x66, 0x66, 0x99 }, { 0x66, 0x66, 0xcc }, { 0x66, 0x66, 0xff },
81 { 0x66, 0x99, 0x00 }, { 0x66, 0x99, 0x33 }, { 0x66, 0x99, 0x66 }, { 0x66, 0x99, 0x99 }, { 0x66, 0x99, 0xcc }, { 0x66, 0x99, 0xff },
82 { 0x66, 0xcc, 0x00 }, { 0x66, 0xcc, 0x33 }, { 0x66, 0xcc, 0x66 }, { 0x66, 0xcc, 0x99 }, { 0x66, 0xcc, 0xcc }, { 0x66, 0xcc, 0xff },
83 { 0x66, 0xff, 0x00 }, { 0x66, 0xff, 0x33 }, { 0x66, 0xff, 0x66 }, { 0x66, 0xff, 0x99 }, { 0x66, 0xff, 0xcc }, { 0x66, 0xff, 0xff },
84 { 0x99, 0x00, 0x00 }, { 0x99, 0x00, 0x33 }, { 0x99, 0x00, 0x66 }, { 0x99, 0x00, 0x99 }, { 0x99, 0x00, 0xcc }, { 0x99, 0x00, 0xff },
85 { 0x99, 0x33, 0x00 }, { 0x99, 0x33, 0x33 }, { 0x99, 0x33, 0x66 }, { 0x99, 0x33, 0x99 }, { 0x99, 0x33, 0xcc }, { 0x99, 0x33, 0xff },
86 { 0x99, 0x66, 0x00 }, { 0x99, 0x66, 0x33 }, { 0x99, 0x66, 0x66 }, { 0x99, 0x66, 0x99 }, { 0x99, 0x66, 0xcc }, { 0x99, 0x66, 0xff },
87 { 0x99, 0x99, 0x00 }, { 0x99, 0x99, 0x33 }, { 0x99, 0x99, 0x66 }, { 0x99, 0x99, 0x99 }, { 0x99, 0x99, 0xcc }, { 0x99, 0x99, 0xff },
88 { 0x99, 0xcc, 0x00 }, { 0x99, 0xcc, 0x33 }, { 0x99, 0xcc, 0x66 }, { 0x99, 0xcc, 0x99 }, { 0x99, 0xcc, 0xcc }, { 0x99, 0xcc, 0xff },
89 { 0x99, 0xff, 0x00 }, { 0x99, 0xff, 0x33 }, { 0x99, 0xff, 0x66 }, { 0x99, 0xff, 0x99 }, { 0x99, 0xff, 0xcc }, { 0x99, 0xff, 0xff },
90 { 0xcc, 0x00, 0x00 }, { 0xcc, 0x00, 0x33 }, { 0xcc, 0x00, 0x66 }, { 0xcc, 0x00, 0x99 }, { 0xcc, 0x00, 0xcc }, { 0xcc, 0x00, 0xff },
91 { 0xcc, 0x33, 0x00 }, { 0xcc, 0x33, 0x33 }, { 0xcc, 0x33, 0x66 }, { 0xcc, 0x33, 0x99 }, { 0xcc, 0x33, 0xcc }, { 0xcc, 0x33, 0xff },
92 { 0xcc, 0x66, 0x00 }, { 0xcc, 0x66, 0x33 }, { 0xcc, 0x66, 0x66 }, { 0xcc, 0x66, 0x99 }, { 0xcc, 0x66, 0xcc }, { 0xcc, 0x66, 0xff },
93 { 0xcc, 0x99, 0x00 }, { 0xcc, 0x99, 0x33 }, { 0xcc, 0x99, 0x66 }, { 0xcc, 0x99, 0x99 }, { 0xcc, 0x99, 0xcc }, { 0xcc, 0x99, 0xff },
94 { 0xcc, 0xcc, 0x00 }, { 0xcc, 0xcc, 0x33 }, { 0xcc, 0xcc, 0x66 }, { 0xcc, 0xcc, 0x99 }, { 0xcc, 0xcc, 0xcc }, { 0xcc, 0xcc, 0xff },
95 { 0xcc, 0xff, 0x00 }, { 0xcc, 0xff, 0x33 }, { 0xcc, 0xff, 0x66 }, { 0xcc, 0xff, 0x99 }, { 0xcc, 0xff, 0xcc }, { 0xcc, 0xff, 0xff },
96 { 0xff, 0x00, 0x00 }, { 0xff, 0x00, 0x33 }, { 0xff, 0x00, 0x66 }, { 0xff, 0x00, 0x99 }, { 0xff, 0x00, 0xcc }, { 0xff, 0x00, 0xff },
97 { 0xff, 0x33, 0x00 }, { 0xff, 0x33, 0x33 }, { 0xff, 0x33, 0x66 }, { 0xff, 0x33, 0x99 }, { 0xff, 0x33, 0xcc }, { 0xff, 0x33, 0xff },
98 { 0xff, 0x66, 0x00 }, { 0xff, 0x66, 0x33 }, { 0xff, 0x66, 0x66 }, { 0xff, 0x66, 0x99 }, { 0xff, 0x66, 0xcc }, { 0xff, 0x66, 0xff },
99 { 0xff, 0x99, 0x00 }, { 0xff, 0x99, 0x33 }, { 0xff, 0x99, 0x66 }, { 0xff, 0x99, 0x99 }, { 0xff, 0x99, 0xcc }, { 0xff, 0x99, 0xff },
100 { 0xff, 0xcc, 0x00 }, { 0xff, 0xcc, 0x33 }, { 0xff, 0xcc, 0x66 }, { 0xff, 0xcc, 0x99 }, { 0xff, 0xcc, 0xcc }, { 0xff, 0xcc, 0xff },
101 { 0xff, 0xff, 0x00 }, { 0xff, 0xff, 0x33 }, { 0xff, 0xff, 0x66 }, { 0xff, 0xff, 0x99 }, { 0xff, 0xff, 0xcc }, { 0xff, 0xff, 0xff },
102};
103
104/* The GIF format uses reversed order for bitstreams... */
105/* at least they don't use PDP_ENDIAN :) */
106/* so we 'extend' PutBitContext. hmmm, OOP :) */
107/* seems this thing changed slightly since I wrote it... */
108
109#ifdef ALT_BITSTREAM_WRITER
110# error no ALT_BITSTREAM_WRITER support for now
111#endif
112
113static void gif_put_bits_rev(PutBitContext *s, int n, unsigned int value)
114{
115 unsigned int bit_buf;
116 int bit_cnt;
117
118 // printf("put_bits=%d %x\n", n, value);
119 assert(n == 32 || value < (1U << n));
120
121 bit_buf = s->bit_buf;
122 bit_cnt = 32 - s->bit_left; /* XXX:lazyness... was = s->bit_cnt; */
123
124 // printf("n=%d value=%x cnt=%d buf=%x\n", n, value, bit_cnt, bit_buf);
125 /* XXX: optimize */
126 if (n < (32-bit_cnt)) {
127 bit_buf |= value << (bit_cnt);
128 bit_cnt+=n;
129 } else {
130 bit_buf |= value << (bit_cnt);
131
132 *s->buf_ptr = bit_buf & 0xff;
133 s->buf_ptr[1] = (bit_buf >> 8) & 0xff;
134 s->buf_ptr[2] = (bit_buf >> 16) & 0xff;
135 s->buf_ptr[3] = (bit_buf >> 24) & 0xff;
136
137 //printf("bitbuf = %08x\n", bit_buf);
138 s->buf_ptr+=4;
139 if (s->buf_ptr >= s->buf_end)
140 abort();
141// flush_buffer_rev(s);
142 bit_cnt=bit_cnt + n - 32;
143 if (bit_cnt == 0) {
144 bit_buf = 0;
145 } else {
146 bit_buf = value >> (n - bit_cnt);
147 }
148 }
149
150 s->bit_buf = bit_buf;
151 s->bit_left = 32 - bit_cnt;
152}
153
154/* pad the end of the output stream with zeros */
155static void gif_flush_put_bits_rev(PutBitContext *s)
156{
157 while (s->bit_left < 32) {
158 /* XXX: should test end of buffer */
159 *s->buf_ptr++=s->bit_buf & 0xff;
160 s->bit_buf>>=8;
161 s->bit_left+=8;
162 }
163// flush_buffer_rev(s);
164 s->bit_left=32;
165 s->bit_buf=0;
166}
167
168/* !RevPutBitContext */
169
170/* GIF header */
171static int gif_image_write_header(ByteIOContext *pb,
172 int width, int height, int loop_count,
173 uint32_t *palette)
174{
175 int i;
176 unsigned int v;
177
178 put_tag(pb, "GIF");
179 put_tag(pb, "89a");
180 put_le16(pb, width);
181 put_le16(pb, height);
182
183 put_byte(pb, 0xf7); /* flags: global clut, 256 entries */
184 put_byte(pb, 0x1f); /* background color index */
185 put_byte(pb, 0); /* aspect ratio */
186
187 /* the global palette */
188 if (!palette) {
189 put_buffer(pb, (const unsigned char *)gif_clut, 216*3);
190 for(i=0;i<((256-216)*3);i++)
191 put_byte(pb, 0);
192 } else {
193 for(i=0;i<256;i++) {
194 v = palette[i];
195 put_byte(pb, (v >> 16) & 0xff);
196 put_byte(pb, (v >> 8) & 0xff);
197 put_byte(pb, (v) & 0xff);
198 }
199 }
200
201 /* update: this is the 'NETSCAPE EXTENSION' that allows for looped animated gif
202 see http://members.aol.com/royalef/gifabout.htm#net-extension
203
204 byte 1 : 33 (hex 0x21) GIF Extension code
205 byte 2 : 255 (hex 0xFF) Application Extension Label
206 byte 3 : 11 (hex (0x0B) Length of Application Block
207 (eleven bytes of data to follow)
208 bytes 4 to 11 : "NETSCAPE"
209 bytes 12 to 14 : "2.0"
210 byte 15 : 3 (hex 0x03) Length of Data Sub-Block
211 (three bytes of data to follow)
212 byte 16 : 1 (hex 0x01)
213 bytes 17 to 18 : 0 to 65535, an unsigned integer in
214 lo-hi byte format. This indicate the
215 number of iterations the loop should
216 be executed.
217 bytes 19 : 0 (hex 0x00) a Data Sub-block Terminator
218 */
219
220 /* application extension header */
221#ifdef GIF_ADD_APP_HEADER
222 if (loop_count >= 0 && loop_count <= 65535) {
223 put_byte(pb, 0x21);
224 put_byte(pb, 0xff);
225 put_byte(pb, 0x0b);
226 put_tag(pb, "NETSCAPE2.0"); // bytes 4 to 14
227 put_byte(pb, 0x03); // byte 15
228 put_byte(pb, 0x01); // byte 16
229 put_le16(pb, (uint16_t)loop_count);
230 put_byte(pb, 0x00); // byte 19
231 }
232#endif
233 return 0;
234}
235
236/* this is maybe slow, but allows for extensions */
237static inline unsigned char gif_clut_index(uint8_t r, uint8_t g, uint8_t b)
238{
239 return (((r) / 47) % 6) * 6 * 6 + (((g) / 47) % 6) * 6 + (((b) / 47) % 6);
240}
241
242
243static int gif_image_write_image(ByteIOContext *pb,
244 int x1, int y1, int width, int height,
245 const uint8_t *buf, int linesize, int pix_fmt)
246{
247 PutBitContext p;
248 uint8_t buffer[200]; /* 100 * 9 / 8 = 113 */
249 int i, left, w, v;
250 const uint8_t *ptr;
251 /* image block */
252
253 put_byte(pb, 0x2c);
254 put_le16(pb, x1);
255 put_le16(pb, y1);
256 put_le16(pb, width);
257 put_le16(pb, height);
258 put_byte(pb, 0x00); /* flags */
259 /* no local clut */
260
261 put_byte(pb, 0x08);
262
263 left= width * height;
264
265 init_put_bits(&p, buffer, 130);
266
267/*
268 * the thing here is the bitstream is written as little packets, with a size byte before
269 * but it's still the same bitstream between packets (no flush !)
270 */
271 ptr = buf;
272 w = width;
273 while(left>0) {
274
275 gif_put_bits_rev(&p, 9, 0x0100); /* clear code */
276
277 for(i=(left<GIF_CHUNKS)?left:GIF_CHUNKS;i;i--) {
278 if (pix_fmt == PIX_FMT_RGB24) {
279 v = gif_clut_index(ptr[0], ptr[1], ptr[2]);
280 ptr+=3;
281 } else {
282 v = *ptr++;
283 }
284 gif_put_bits_rev(&p, 9, v);
285 if (--w == 0) {
286 w = width;
287 buf += linesize;
288 ptr = buf;
289 }
290 }
291
292 if(left<=GIF_CHUNKS) {
293 gif_put_bits_rev(&p, 9, 0x101); /* end of stream */
294 gif_flush_put_bits_rev(&p);
295 }
296 if(pbBufPtr(&p) - p.buf > 0) {
297 put_byte(pb, pbBufPtr(&p) - p.buf); /* byte count of the packet */
298 put_buffer(pb, p.buf, pbBufPtr(&p) - p.buf); /* the actual buffer */
299 p.buf_ptr = p.buf; /* dequeue the bytes off the bitstream */
300 }
301 left-=GIF_CHUNKS;
302 }
303 put_byte(pb, 0x00); /* end of image block */
304
305 return 0;
306}
307
308typedef struct {
309 int64_t time, file_time;
310 uint8_t buffer[100]; /* data chunks */
311} GIFContext;
312
313static int gif_write_header(AVFormatContext *s)
314{
315 GIFContext *gif = s->priv_data;
316 ByteIOContext *pb = s->pb;
317 AVCodecContext *enc, *video_enc;
318 int i, width, height, loop_count /*, rate*/;
319
320/* XXX: do we reject audio streams or just ignore them ?
321 if(s->nb_streams > 1)
322 return -1;
323*/
324 gif->time = 0;
325 gif->file_time = 0;
326
327 video_enc = NULL;
328 for(i=0;i<s->nb_streams;i++) {
329 enc = s->streams[i]->codec;
330 if (enc->codec_type != CODEC_TYPE_AUDIO)
331 video_enc = enc;
332 }
333
334 if (!video_enc) {
335 av_free(gif);
336 return -1;
337 } else {
338 width = video_enc->width;
339 height = video_enc->height;
340 loop_count = s->loop_output;
341// rate = video_enc->time_base.den;
342 }
343
344 if (video_enc->pix_fmt != PIX_FMT_RGB24) {
345 av_log(s, AV_LOG_ERROR, "ERROR: gif only handles the rgb24 pixel format. Use -pix_fmt rgb24.\n");
346 return AVERROR(EIO);
347 }
348
349 gif_image_write_header(pb, width, height, loop_count, NULL);
350
351 put_flush_packet(s->pb);
352 return 0;
353}
354
355static int gif_write_video(AVFormatContext *s,
356 AVCodecContext *enc, const uint8_t *buf, int size)
357{
358 ByteIOContext *pb = s->pb;
359 GIFContext *gif = s->priv_data;
360 int jiffies;
361 int64_t delay;
362
363 /* graphic control extension block */
364 put_byte(pb, 0x21);
365 put_byte(pb, 0xf9);
366 put_byte(pb, 0x04); /* block size */
367 put_byte(pb, 0x04); /* flags */
368
369 /* 1 jiffy is 1/70 s */
370 /* the delay_time field indicates the number of jiffies - 1 */
371 delay = gif->file_time - gif->time;
372
373 /* XXX: should use delay, in order to be more accurate */
374 /* instead of using the same rounded value each time */
375 /* XXX: don't even remember if I really use it for now */
376 jiffies = (70*enc->time_base.num/enc->time_base.den) - 1;
377
378 put_le16(pb, jiffies);
379
380 put_byte(pb, 0x1f); /* transparent color index */
381 put_byte(pb, 0x00);
382
383 gif_image_write_image(pb, 0, 0, enc->width, enc->height,
384 buf, enc->width * 3, PIX_FMT_RGB24);
385
386 put_flush_packet(s->pb);
387 return 0;
388}
389
390static int gif_write_packet(AVFormatContext *s, AVPacket *pkt)
391{
392 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
393 if (codec->codec_type == CODEC_TYPE_AUDIO)
394 return 0; /* just ignore audio */
395 else
396 return gif_write_video(s, codec, pkt->data, pkt->size);
397}
398
399static int gif_write_trailer(AVFormatContext *s)
400{
401 ByteIOContext *pb = s->pb;
402
403 put_byte(pb, 0x3b);
404 put_flush_packet(s->pb);
405 return 0;
406}
407
408AVOutputFormat gif_muxer = {
409 "gif",
410 NULL_IF_CONFIG_SMALL("GIF Animation"),
411 "image/gif",
412 "gif",
413 sizeof(GIFContext),
414 CODEC_ID_NONE,
415 CODEC_ID_RAWVIDEO,
416 gif_write_header,
417 gif_write_packet,
418 gif_write_trailer,
419};
diff --git a/src/plugins/ffmpeg/libavformat/gxf.c b/src/plugins/ffmpeg/libavformat/gxf.c
deleted file mode 100644
index 43193be..0000000
--- a/src/plugins/ffmpeg/libavformat/gxf.c
+++ /dev/null
@@ -1,503 +0,0 @@
1/*
2 * GXF demuxer.
3 * Copyright (c) 2006 Reimar Doeffinger.
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/common.h"
23#include "avformat.h"
24#include "gxf.h"
25
26typedef struct {
27 int64_t first_field;
28 int64_t last_field;
29 AVRational frames_per_second;
30 int32_t fields_per_frame;
31} st_info_t;
32
33/**
34 * \brief parses a packet header, extracting type and length
35 * \param pb ByteIOContext to read header from
36 * \param type detected packet type is stored here
37 * \param length detected packet length, excluding header is stored here
38 * \return 0 if header not found or contains invalid data, 1 otherwise
39 */
40static int parse_packet_header(ByteIOContext *pb, pkt_type_t *type, int *length) {
41 if (get_be32(pb))
42 return 0;
43 if (get_byte(pb) != 1)
44 return 0;
45 *type = get_byte(pb);
46 *length = get_be32(pb);
47 if ((*length >> 24) || *length < 16)
48 return 0;
49 *length -= 16;
50 if (get_be32(pb))
51 return 0;
52 if (get_byte(pb) != 0xe1)
53 return 0;
54 if (get_byte(pb) != 0xe2)
55 return 0;
56 return 1;
57}
58
59/**
60 * \brief check if file starts with a PKT_MAP header
61 */
62static int gxf_probe(AVProbeData *p) {
63 static const uint8_t startcode[] = {0, 0, 0, 0, 1, 0xbc}; // start with map packet
64 static const uint8_t endcode[] = {0, 0, 0, 0, 0xe1, 0xe2};
65 if (!memcmp(p->buf, startcode, sizeof(startcode)) &&
66 !memcmp(&p->buf[16 - sizeof(endcode)], endcode, sizeof(endcode)))
67 return AVPROBE_SCORE_MAX;
68 return 0;
69}
70
71/**
72 * \brief gets the stream index for the track with the specified id, creates new
73 * stream if not found
74 * \param stream id of stream to find / add
75 * \param format stream format identifier
76 */
77static int get_sindex(AVFormatContext *s, int id, int format) {
78 int i;
79 AVStream *st = NULL;
80 for (i = 0; i < s->nb_streams; i++) {
81 if (s->streams[i]->id == id)
82 return i;
83 }
84 st = av_new_stream(s, id);
85 if (!st)
86 return AVERROR(ENOMEM);
87 switch (format) {
88 case 3:
89 case 4:
90 st->codec->codec_type = CODEC_TYPE_VIDEO;
91 st->codec->codec_id = CODEC_ID_MJPEG;
92 break;
93 case 13:
94 case 15:
95 st->codec->codec_type = CODEC_TYPE_VIDEO;
96 st->codec->codec_id = CODEC_ID_DVVIDEO;
97 break;
98 case 14:
99 case 16:
100 st->codec->codec_type = CODEC_TYPE_VIDEO;
101 st->codec->codec_id = CODEC_ID_DVVIDEO;
102 break;
103 case 11:
104 case 12:
105 case 20:
106 st->codec->codec_type = CODEC_TYPE_VIDEO;
107 st->codec->codec_id = CODEC_ID_MPEG2VIDEO;
108 st->need_parsing = AVSTREAM_PARSE_HEADERS; //get keyframe flag etc.
109 break;
110 case 22:
111 case 23:
112 st->codec->codec_type = CODEC_TYPE_VIDEO;
113 st->codec->codec_id = CODEC_ID_MPEG1VIDEO;
114 st->need_parsing = AVSTREAM_PARSE_HEADERS; //get keyframe flag etc.
115 break;
116 case 9:
117 st->codec->codec_type = CODEC_TYPE_AUDIO;
118 st->codec->codec_id = CODEC_ID_PCM_S24LE;
119 st->codec->channels = 1;
120 st->codec->sample_rate = 48000;
121 st->codec->bit_rate = 3 * 1 * 48000 * 8;
122 st->codec->block_align = 3 * 1;
123 st->codec->bits_per_sample = 24;
124 break;
125 case 10:
126 st->codec->codec_type = CODEC_TYPE_AUDIO;
127 st->codec->codec_id = CODEC_ID_PCM_S16LE;
128 st->codec->channels = 1;
129 st->codec->sample_rate = 48000;
130 st->codec->bit_rate = 2 * 1 * 48000 * 8;
131 st->codec->block_align = 2 * 1;
132 st->codec->bits_per_sample = 16;
133 break;
134 case 17:
135 st->codec->codec_type = CODEC_TYPE_AUDIO;
136 st->codec->codec_id = CODEC_ID_AC3;
137 st->codec->channels = 2;
138 st->codec->sample_rate = 48000;
139 break;
140 // timecode tracks:
141 case 7:
142 case 8:
143 case 24:
144 st->codec->codec_type = CODEC_TYPE_DATA;
145 st->codec->codec_id = CODEC_ID_NONE;
146 break;
147 default:
148 st->codec->codec_type = CODEC_TYPE_UNKNOWN;
149 st->codec->codec_id = CODEC_ID_NONE;
150 break;
151 }
152 return s->nb_streams - 1;
153}
154
155/**
156 * \brief filters out interesting tags from material information.
157 * \param len length of tag section, will be adjusted to contain remaining bytes
158 * \param si struct to store collected information into
159 */
160static void gxf_material_tags(ByteIOContext *pb, int *len, st_info_t *si) {
161 si->first_field = AV_NOPTS_VALUE;
162 si->last_field = AV_NOPTS_VALUE;
163 while (*len >= 2) {
164 mat_tag_t tag = get_byte(pb);
165 int tlen = get_byte(pb);
166 *len -= 2;
167 if (tlen > *len)
168 return;
169 *len -= tlen;
170 if (tlen == 4) {
171 uint32_t value = get_be32(pb);
172 if (tag == MAT_FIRST_FIELD)
173 si->first_field = value;
174 else if (tag == MAT_LAST_FIELD)
175 si->last_field = value;
176 } else
177 url_fskip(pb, tlen);
178 }
179}
180
181/**
182 * \brief convert fps tag value to AVRational fps
183 * \param fps fps value from tag
184 * \return fps as AVRational, or 0 / 0 if unknown
185 */
186static AVRational fps_tag2avr(int32_t fps) {
187 extern const AVRational ff_frame_rate_tab[];
188 if (fps < 1 || fps > 9) fps = 9;
189 return ff_frame_rate_tab[9 - fps]; // values have opposite order
190}
191
192/**
193 * \brief convert UMF attributes flags to AVRational fps
194 * \param fps fps value from flags
195 * \return fps as AVRational, or 0 / 0 if unknown
196 */
197static AVRational fps_umf2avr(uint32_t flags) {
198 static const AVRational map[] = {{50, 1}, {60000, 1001}, {24, 1},
199 {25, 1}, {30000, 1001}};
200 int idx = av_log2((flags & 0x7c0) >> 6);
201 return map[idx];
202}
203
204/**
205 * \brief filters out interesting tags from track information.
206 * \param len length of tag section, will be adjusted to contain remaining bytes
207 * \param si struct to store collected information into
208 */
209static void gxf_track_tags(ByteIOContext *pb, int *len, st_info_t *si) {
210 si->frames_per_second = (AVRational){0, 0};
211 si->fields_per_frame = 0;
212 while (*len >= 2) {
213 track_tag_t tag = get_byte(pb);
214 int tlen = get_byte(pb);
215 *len -= 2;
216 if (tlen > *len)
217 return;
218 *len -= tlen;
219 if (tlen == 4) {
220 uint32_t value = get_be32(pb);
221 if (tag == TRACK_FPS)
222 si->frames_per_second = fps_tag2avr(value);
223 else if (tag == TRACK_FPF && (value == 1 || value == 2))
224 si->fields_per_frame = value;
225 } else
226 url_fskip(pb, tlen);
227 }
228}
229
230/**
231 * \brief read index from FLT packet into stream 0 av_index
232 */
233static void gxf_read_index(AVFormatContext *s, int pkt_len) {
234 ByteIOContext *pb = s->pb;
235 AVStream *st = s->streams[0];
236 uint32_t fields_per_map = get_le32(pb);
237 uint32_t map_cnt = get_le32(pb);
238 int i;
239 pkt_len -= 8;
240 if (map_cnt > 1000) {
241 av_log(s, AV_LOG_ERROR, "GXF: too many index entries %u (%x)\n", map_cnt, map_cnt);
242 map_cnt = 1000;
243 }
244 if (pkt_len < 4 * map_cnt) {
245 av_log(s, AV_LOG_ERROR, "GXF: invalid index length\n");
246 url_fskip(pb, pkt_len);
247 return;
248 }
249 pkt_len -= 4 * map_cnt;
250 av_add_index_entry(st, 0, 0, 0, 0, 0);
251 for (i = 0; i < map_cnt; i++)
252 av_add_index_entry(st, (uint64_t)get_le32(pb) * 1024,
253 i * (uint64_t)fields_per_map + 1, 0, 0, 0);
254 url_fskip(pb, pkt_len);
255}
256
257static int gxf_header(AVFormatContext *s, AVFormatParameters *ap) {
258 ByteIOContext *pb = s->pb;
259 pkt_type_t pkt_type;
260 int map_len;
261 int len;
262 AVRational main_timebase = {0, 0};
263 st_info_t si;
264 int i;
265 if (!parse_packet_header(pb, &pkt_type, &map_len) || pkt_type != PKT_MAP) {
266 av_log(s, AV_LOG_ERROR, "GXF: map packet not found\n");
267 return 0;
268 }
269 map_len -= 2;
270 if (get_byte(pb) != 0x0e0 || get_byte(pb) != 0xff) {
271 av_log(s, AV_LOG_ERROR, "GXF: unknown version or invalid map preamble\n");
272 return 0;
273 }
274 map_len -= 2;
275 len = get_be16(pb); // length of material data section
276 if (len > map_len) {
277 av_log(s, AV_LOG_ERROR, "GXF: material data longer than map data\n");
278 return 0;
279 }
280 map_len -= len;
281 gxf_material_tags(pb, &len, &si);
282 url_fskip(pb, len);
283 map_len -= 2;
284 len = get_be16(pb); // length of track description
285 if (len > map_len) {
286 av_log(s, AV_LOG_ERROR, "GXF: track description longer than map data\n");
287 return 0;
288 }
289 map_len -= len;
290 while (len > 0) {
291 int track_type, track_id, track_len;
292 AVStream *st;
293 int idx;
294 len -= 4;
295 track_type = get_byte(pb);
296 track_id = get_byte(pb);
297 track_len = get_be16(pb);
298 len -= track_len;
299 gxf_track_tags(pb, &track_len, &si);
300 url_fskip(pb, track_len);
301 if (!(track_type & 0x80)) {
302 av_log(s, AV_LOG_ERROR, "GXF: invalid track type %x\n", track_type);
303 continue;
304 }
305 track_type &= 0x7f;
306 if ((track_id & 0xc0) != 0xc0) {
307 av_log(s, AV_LOG_ERROR, "GXF: invalid track id %x\n", track_id);
308 continue;
309 }
310 track_id &= 0x3f;
311 idx = get_sindex(s, track_id, track_type);
312 if (idx < 0) continue;
313 st = s->streams[idx];
314 if (!main_timebase.num || !main_timebase.den) {
315 main_timebase.num = si.frames_per_second.den;
316 main_timebase.den = si.frames_per_second.num * si.fields_per_frame;
317 }
318 st->start_time = si.first_field;
319 if (si.first_field != AV_NOPTS_VALUE && si.last_field != AV_NOPTS_VALUE)
320 st->duration = si.last_field - si.first_field;
321 }
322 if (len < 0)
323 av_log(s, AV_LOG_ERROR, "GXF: invalid track description length specified\n");
324 if (map_len)
325 url_fskip(pb, map_len);
326 if (!parse_packet_header(pb, &pkt_type, &len)) {
327 av_log(s, AV_LOG_ERROR, "GXF: sync lost in header\n");
328 return -1;
329 }
330 if (pkt_type == PKT_FLT) {
331 gxf_read_index(s, len);
332 if (!parse_packet_header(pb, &pkt_type, &len)) {
333 av_log(s, AV_LOG_ERROR, "GXF: sync lost in header\n");
334 return -1;
335 }
336 }
337 if (pkt_type == PKT_UMF) {
338 if (len >= 0x39) {
339 AVRational fps;
340 len -= 0x39;
341 url_fskip(pb, 5); // preamble
342 url_fskip(pb, 0x30); // payload description
343 fps = fps_umf2avr(get_le32(pb));
344 if (!main_timebase.num || !main_timebase.den) {
345 // this may not always be correct, but simply the best we can get
346 main_timebase.num = fps.den;
347 main_timebase.den = fps.num;
348 }
349 } else
350 av_log(s, AV_LOG_INFO, "GXF: UMF packet too short\n");
351 } else
352 av_log(s, AV_LOG_INFO, "GXF: UMF packet missing\n");
353 url_fskip(pb, len);
354 if (!main_timebase.num || !main_timebase.den)
355 main_timebase = (AVRational){1, 50}; // set some arbitrary fallback
356 for (i = 0; i < s->nb_streams; i++) {
357 AVStream *st = s->streams[i];
358 av_set_pts_info(st, 32, main_timebase.num, main_timebase.den);
359 }
360 return 0;
361}
362
363#define READ_ONE() \
364 { \
365 if (!max_interval-- || url_feof(pb)) \
366 goto out; \
367 tmp = tmp << 8 | get_byte(pb); \
368 }
369
370/**
371 * \brief resync the stream on the next media packet with specified properties
372 * \param max_interval how many bytes to search for matching packet at most
373 * \param track track id the media packet must belong to, -1 for any
374 * \param timestamp minimum timestamp (== field number) the packet must have, -1 for any
375 * \return timestamp of packet found
376 */
377static int64_t gxf_resync_media(AVFormatContext *s, uint64_t max_interval, int track, int timestamp) {
378 uint32_t tmp;
379 uint64_t last_pos;
380 uint64_t last_found_pos = 0;
381 int cur_track;
382 int64_t cur_timestamp = AV_NOPTS_VALUE;
383 int len;
384 ByteIOContext *pb = s->pb;
385 pkt_type_t type;
386 tmp = get_be32(pb);
387start:
388 while (tmp)
389 READ_ONE();
390 READ_ONE();
391 if (tmp != 1)
392 goto start;
393 last_pos = url_ftell(pb);
394 url_fseek(pb, -5, SEEK_CUR);
395 if (!parse_packet_header(pb, &type, &len) || type != PKT_MEDIA) {
396 url_fseek(pb, last_pos, SEEK_SET);
397 goto start;
398 }
399 get_byte(pb);
400 cur_track = get_byte(pb);
401 cur_timestamp = get_be32(pb);
402 last_found_pos = url_ftell(pb) - 16 - 6;
403 if ((track >= 0 && track != cur_track) || (timestamp >= 0 && timestamp > cur_timestamp)) {
404 url_fseek(pb, last_pos, SEEK_SET);
405 goto start;
406 }
407out:
408 if (last_found_pos)
409 url_fseek(pb, last_found_pos, SEEK_SET);
410 return cur_timestamp;
411}
412
413static int gxf_packet(AVFormatContext *s, AVPacket *pkt) {
414 ByteIOContext *pb = s->pb;
415 pkt_type_t pkt_type;
416 int pkt_len;
417 while (!url_feof(pb)) {
418 int track_type, track_id, ret;
419 int field_nr;
420 int stream_index;
421 if (!parse_packet_header(pb, &pkt_type, &pkt_len)) {
422 if (!url_feof(pb))
423 av_log(s, AV_LOG_ERROR, "GXF: sync lost\n");
424 return -1;
425 }
426 if (pkt_type == PKT_FLT) {
427 gxf_read_index(s, pkt_len);
428 continue;
429 }
430 if (pkt_type != PKT_MEDIA) {
431 url_fskip(pb, pkt_len);
432 continue;
433 }
434 if (pkt_len < 16) {
435 av_log(s, AV_LOG_ERROR, "GXF: invalid media packet length\n");
436 continue;
437 }
438 pkt_len -= 16;
439 track_type = get_byte(pb);
440 track_id = get_byte(pb);
441 stream_index = get_sindex(s, track_id, track_type);
442 if (stream_index < 0)
443 return stream_index;
444 field_nr = get_be32(pb);
445 get_be32(pb); // field information
446 get_be32(pb); // "timeline" field number
447 get_byte(pb); // flags
448 get_byte(pb); // reserved
449 // NOTE: there is also data length information in the
450 // field information, it might be better to take this into account
451 // as well.
452 ret = av_get_packet(pb, pkt, pkt_len);
453 pkt->stream_index = stream_index;
454 pkt->dts = field_nr;
455 return ret;
456 }
457 return AVERROR(EIO);
458}
459
460static int gxf_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {
461 uint64_t pos;
462 uint64_t maxlen = 100 * 1024 * 1024;
463 AVStream *st = s->streams[0];
464 int64_t start_time = s->streams[stream_index]->start_time;
465 int64_t found;
466 int idx;
467 if (timestamp < start_time) timestamp = start_time;
468 idx = av_index_search_timestamp(st, timestamp - start_time,
469 AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
470 if (idx < 0)
471 return -1;
472 pos = st->index_entries[idx].pos;
473 if (idx < st->nb_index_entries - 2)
474 maxlen = st->index_entries[idx + 2].pos - pos;
475 maxlen = FFMAX(maxlen, 200 * 1024);
476 url_fseek(s->pb, pos, SEEK_SET);
477 found = gxf_resync_media(s, maxlen, -1, timestamp);
478 if (FFABS(found - timestamp) > 4)
479 return -1;
480 return 0;
481}
482
483static int64_t gxf_read_timestamp(AVFormatContext *s, int stream_index,
484 int64_t *pos, int64_t pos_limit) {
485 ByteIOContext *pb = s->pb;
486 int64_t res;
487 url_fseek(pb, *pos, SEEK_SET);
488 res = gxf_resync_media(s, pos_limit - *pos, -1, -1);
489 *pos = url_ftell(pb);
490 return res;
491}
492
493AVInputFormat gxf_demuxer = {
494 "gxf",
495 NULL_IF_CONFIG_SMALL("GXF format"),
496 0,
497 gxf_probe,
498 gxf_header,
499 gxf_packet,
500 NULL,
501 gxf_seek,
502 gxf_read_timestamp,
503};
diff --git a/src/plugins/ffmpeg/libavformat/gxf.h b/src/plugins/ffmpeg/libavformat/gxf.h
deleted file mode 100644
index ab37cb9..0000000
--- a/src/plugins/ffmpeg/libavformat/gxf.h
+++ /dev/null
@@ -1,53 +0,0 @@
1/*
2 * GXF demuxer
3 * copyright (c) 2006 Reimar Doeffinger
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#ifndef FFMPEG_GXF_H
23#define FFMPEG_GXF_H
24
25/* gxf.c */
26typedef enum {
27 PKT_MAP = 0xbc,
28 PKT_MEDIA = 0xbf,
29 PKT_EOS = 0xfb,
30 PKT_FLT = 0xfc,
31 PKT_UMF = 0xfd,
32} pkt_type_t;
33
34typedef enum {
35 MAT_NAME = 0x40,
36 MAT_FIRST_FIELD = 0x41,
37 MAT_LAST_FIELD = 0x42,
38 MAT_MARK_IN = 0x43,
39 MAT_MARK_OUT = 0x44,
40 MAT_SIZE = 0x45,
41} mat_tag_t;
42
43typedef enum {
44 TRACK_NAME = 0x4c,
45 TRACK_AUX = 0x4d,
46 TRACK_VER = 0x4e,
47 TRACK_MPG_AUX = 0x4f,
48 TRACK_FPS = 0x50,
49 TRACK_LINES = 0x51,
50 TRACK_FPF = 0x52,
51} track_tag_t;
52
53#endif /* FFMPEG_GXF_H */
diff --git a/src/plugins/ffmpeg/libavformat/gxfenc.c b/src/plugins/ffmpeg/libavformat/gxfenc.c
deleted file mode 100644
index 20d0947..0000000
--- a/src/plugins/ffmpeg/libavformat/gxfenc.c
+++ /dev/null
@@ -1,828 +0,0 @@
1/*
2 * GXF muxer.
3 * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>.
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/fifo.h"
23#include "avformat.h"
24#include "gxf.h"
25#include "riff.h"
26
27#define GXF_AUDIO_PACKET_SIZE 65536
28
29typedef struct GXFStreamContext {
30 AVCodecContext *codec;
31 AVFifoBuffer audio_buffer;
32 uint32_t track_type;
33 uint32_t sample_size;
34 uint32_t sample_rate;
35 uint16_t media_type;
36 uint16_t media_info;
37 uint8_t index;
38 int frame_rate_index;
39 int lines_index;
40 int fields;
41 int iframes;
42 int pframes;
43 int bframes;
44 int p_per_gop;
45 int b_per_gop;
46 int first_gop_closed;
47 int64_t current_dts;
48 int dts_delay;
49} GXFStreamContext;
50
51typedef struct GXFContext {
52 uint32_t nb_frames;
53 uint32_t material_flags;
54 uint16_t audio_tracks;
55 uint16_t mpeg_tracks;
56 int64_t creation_time;
57 uint32_t umf_start_offset;
58 uint32_t umf_track_offset;
59 uint32_t umf_media_offset;
60 uint32_t umf_user_data_offset;
61 uint32_t umf_user_data_size;
62 uint32_t umf_length;
63 uint16_t umf_track_size;
64 uint16_t umf_media_size;
65 int audio_written;
66 int sample_rate;
67 int flags;
68 AVFormatContext *fc;
69 GXFStreamContext streams[48];
70} GXFContext;
71
72typedef struct GXF_Lines {
73 int height;
74 int index;
75} GXF_Lines;
76
77
78/* FIXME check if it is relevant */
79static const GXF_Lines gxf_lines_tab[] = {
80 { 480, 1 }, /* NTSC */
81 { 512, 1 }, /* NTSC + VBI */
82 { 576, 2 }, /* PAL */
83 { 608, 2 }, /* PAL + VBI */
84 { 1080, 4 },
85 { 720, 6 },
86};
87
88static const AVCodecTag gxf_media_types[] = {
89 { CODEC_ID_MJPEG , 3 }, /* NTSC */
90 { CODEC_ID_MJPEG , 4 }, /* PAL */
91 { CODEC_ID_PCM_S24LE , 9 },
92 { CODEC_ID_PCM_S16LE , 10 },
93 { CODEC_ID_MPEG2VIDEO, 11 }, /* NTSC */
94 { CODEC_ID_MPEG2VIDEO, 12 }, /* PAL */
95 { CODEC_ID_DVVIDEO , 13 }, /* NTSC */
96 { CODEC_ID_DVVIDEO , 14 }, /* PAL */
97 { CODEC_ID_DVVIDEO , 15 }, /* 50M NTSC */
98 { CODEC_ID_DVVIDEO , 16 }, /* 50M PAL */
99 { CODEC_ID_AC3 , 17 },
100 //{ CODEC_ID_NONE, , 18 }, /* Non compressed 24 bit audio */
101 { CODEC_ID_MPEG2VIDEO, 20 }, /* MPEG HD */
102 { CODEC_ID_MPEG1VIDEO, 22 }, /* NTSC */
103 { CODEC_ID_MPEG1VIDEO, 23 }, /* PAL */
104 { 0, 0 },
105};
106
107#define SERVER_PATH "/space/"
108#define ES_NAME_PATTERN "ES."
109
110static int gxf_find_lines_index(GXFStreamContext *ctx)
111{
112 int i;
113
114 for (i = 0; i < 6; ++i) {
115 if (ctx->codec->height == gxf_lines_tab[i].height) {
116 ctx->lines_index = gxf_lines_tab[i].index;
117 return 0;
118 }
119 }
120 return -1;
121}
122
123static void gxf_write_padding(ByteIOContext *pb, offset_t to_pad)
124{
125 for (; to_pad > 0; to_pad--) {
126 put_byte(pb, 0);
127 }
128}
129
130static offset_t updatePacketSize(ByteIOContext *pb, offset_t pos)
131{
132 offset_t curpos;
133 int size;
134
135 size = url_ftell(pb) - pos;
136 if (size % 4) {
137 gxf_write_padding(pb, 4 - size % 4);
138 size = url_ftell(pb) - pos;
139 }
140 curpos = url_ftell(pb);
141 url_fseek(pb, pos + 6, SEEK_SET);
142 put_be32(pb, size);
143 url_fseek(pb, curpos, SEEK_SET);
144 return curpos - pos;
145}
146
147static offset_t updateSize(ByteIOContext *pb, offset_t pos)
148{
149 offset_t curpos;
150
151 curpos = url_ftell(pb);
152 url_fseek(pb, pos, SEEK_SET);
153 put_be16(pb, curpos - pos - 2);
154 url_fseek(pb, curpos, SEEK_SET);
155 return curpos - pos;
156}
157
158static void gxf_write_packet_header(ByteIOContext *pb, pkt_type_t type)
159{
160 put_be32(pb, 0); /* packet leader for synchro */
161 put_byte(pb, 1);
162 put_byte(pb, type); /* map packet */
163 put_be32(pb, 0); /* size */
164 put_be32(pb, 0); /* reserved */
165 put_byte(pb, 0xE1); /* trailer 1 */
166 put_byte(pb, 0xE2); /* trailer 2 */
167}
168
169static int gxf_write_mpeg_auxiliary(ByteIOContext *pb, GXFStreamContext *ctx)
170{
171 char buffer[1024];
172 int size;
173
174 if (ctx->iframes) {
175 ctx->p_per_gop = ctx->pframes / ctx->iframes;
176 if (ctx->pframes % ctx->iframes)
177 ctx->p_per_gop++;
178 if (ctx->pframes)
179 ctx->b_per_gop = ctx->bframes / ctx->pframes;
180 if (ctx->p_per_gop > 9)
181 ctx->p_per_gop = 9; /* ensure value won't take more than one char */
182 if (ctx->b_per_gop > 9)
183 ctx->b_per_gop = 9; /* ensure value won't take more than one char */
184 }
185 size = snprintf(buffer, 1024, "Ver 1\nBr %.6f\nIpg 1\nPpi %d\nBpiop %d\n"
186 "Pix 0\nCf %d\nCg %d\nSl 7\nnl16 %d\nVi 1\nf1 1\n",
187 (float)ctx->codec->bit_rate, ctx->p_per_gop, ctx->b_per_gop,
188 ctx->codec->pix_fmt == PIX_FMT_YUV422P ? 2 : 1, ctx->first_gop_closed == 1,
189 ctx->codec->height / 16);
190 put_byte(pb, TRACK_MPG_AUX);
191 put_byte(pb, size + 1);
192 put_buffer(pb, (uint8_t *)buffer, size + 1);
193 return size + 3;
194}
195
196static int gxf_write_timecode_auxiliary(ByteIOContext *pb, GXFStreamContext *ctx)
197{
198 /* FIXME implement that */
199 put_byte(pb, 0); /* fields */
200 put_byte(pb, 0); /* seconds */
201 put_byte(pb, 0); /* minutes */
202 put_byte(pb, 0); /* flags + hours */
203 /* reserved */
204 put_be32(pb, 0);
205 return 8;
206}
207
208static int gxf_write_track_description(ByteIOContext *pb, GXFStreamContext *stream)
209{
210 offset_t pos;
211
212 /* track description section */
213 put_byte(pb, stream->media_type + 0x80);
214 put_byte(pb, stream->index + 0xC0);
215
216 pos = url_ftell(pb);
217 put_be16(pb, 0); /* size */
218
219 /* media file name */
220 put_byte(pb, TRACK_NAME);
221 put_byte(pb, strlen(ES_NAME_PATTERN) + 3);
222 put_tag(pb, ES_NAME_PATTERN);
223 put_be16(pb, stream->media_info);
224 put_byte(pb, 0);
225
226 if (stream->codec->codec_id != CODEC_ID_MPEG2VIDEO) {
227 /* auxiliary information */
228 put_byte(pb, TRACK_AUX);
229 put_byte(pb, 8);
230 if (stream->codec->codec_id == CODEC_ID_NONE)
231 gxf_write_timecode_auxiliary(pb, stream);
232 else
233 put_le64(pb, 0);
234 }
235
236 /* file system version */
237 put_byte(pb, TRACK_VER);
238 put_byte(pb, 4);
239 put_be32(pb, 0);
240
241 if (stream->codec->codec_id == CODEC_ID_MPEG2VIDEO)
242 gxf_write_mpeg_auxiliary(pb, stream);
243
244 /* frame rate */
245 put_byte(pb, TRACK_FPS);
246 put_byte(pb, 4);
247 put_be32(pb, stream->frame_rate_index);
248
249 /* lines per frame */
250 put_byte(pb, TRACK_LINES);
251 put_byte(pb, 4);
252 put_be32(pb, stream->lines_index);
253
254 /* fields per frame */
255 put_byte(pb, TRACK_FPF);
256 put_byte(pb, 4);
257 put_be32(pb, stream->fields);
258
259 return updateSize(pb, pos);
260}
261
262static int gxf_write_material_data_section(ByteIOContext *pb, GXFContext *ctx)
263{
264 offset_t pos;
265 const char *filename = strrchr(ctx->fc->filename, '/');
266
267 pos = url_ftell(pb);
268 put_be16(pb, 0); /* size */
269
270 /* name */
271 if (filename)
272 filename++;
273 else
274 filename = ctx->fc->filename;
275 put_byte(pb, MAT_NAME);
276 put_byte(pb, strlen(SERVER_PATH) + strlen(filename) + 1);
277 put_tag(pb, SERVER_PATH);
278 put_tag(pb, filename);
279 put_byte(pb, 0);
280
281 /* first field */
282 put_byte(pb, MAT_FIRST_FIELD);
283 put_byte(pb, 4);
284 put_be32(pb, 0);
285
286 /* last field */
287 put_byte(pb, MAT_LAST_FIELD);
288 put_byte(pb, 4);
289 put_be32(pb, ctx->nb_frames);
290
291 /* reserved */
292 put_byte(pb, MAT_MARK_IN);
293 put_byte(pb, 4);
294 put_be32(pb, 0);
295
296 put_byte(pb, MAT_MARK_OUT);
297 put_byte(pb, 4);
298 put_be32(pb, ctx->nb_frames);
299
300 /* estimated size */
301 put_byte(pb, MAT_SIZE);
302 put_byte(pb, 4);
303 put_be32(pb, url_fsize(pb) / 1024);
304
305 return updateSize(pb, pos);
306}
307
308static int gxf_write_track_description_section(ByteIOContext *pb, GXFContext *ctx)
309{
310 offset_t pos;
311 int i;
312
313 pos = url_ftell(pb);
314 put_be16(pb, 0); /* size */
315 for (i = 0; i < ctx->fc->nb_streams; ++i)
316 gxf_write_track_description(pb, &ctx->streams[i]);
317 return updateSize(pb, pos);
318}
319
320static int gxf_write_map_packet(ByteIOContext *pb, GXFContext *ctx)
321{
322 offset_t pos = url_ftell(pb);
323
324 gxf_write_packet_header(pb, PKT_MAP);
325
326 /* preamble */
327 put_byte(pb, 0xE0); /* version */
328 put_byte(pb, 0xFF); /* reserved */
329
330 gxf_write_material_data_section(pb, ctx);
331 gxf_write_track_description_section(pb, ctx);
332
333 return updatePacketSize(pb, pos);
334}
335
336#if 0
337static int gxf_write_flt_packet(ByteIOContext *pb, GXFContext *ctx)
338{
339 offset_t pos = url_ftell(pb);
340 int i;
341
342 gxf_write_packet_header(pb, PKT_FLT);
343
344 put_le32(pb, 1000); /* number of fields */
345 put_le32(pb, 0); /* number of active flt entries */
346
347 for (i = 0; i < 1000; ++i) {
348 put_le32(pb, 0);
349 }
350 return updatePacketSize(pb, pos);
351}
352#endif
353
354static int gxf_write_umf_material_description(ByteIOContext *pb, GXFContext *ctx)
355{
356 put_le32(pb, ctx->flags);
357 put_le32(pb, ctx->nb_frames); /* length of the longest track */
358 put_le32(pb, ctx->nb_frames); /* length of the shortest track */
359 put_le32(pb, 0); /* mark in */
360 put_le32(pb, ctx->nb_frames); /* mark out */
361 put_le32(pb, 0); /* timecode mark in */
362 put_le32(pb, ctx->nb_frames); /* timecode mark out */
363 put_le64(pb, ctx->fc->timestamp); /* modification time */
364 put_le64(pb, ctx->fc->timestamp); /* creation time */
365 put_le16(pb, 0); /* reserved */
366 put_le16(pb, 0); /* reserved */
367 put_le16(pb, ctx->audio_tracks);
368 put_le16(pb, 0); /* timecode track count */
369 put_le16(pb, 0); /* reserved */
370 put_le16(pb, ctx->mpeg_tracks);
371 return 48;
372}
373
374static int gxf_write_umf_payload(ByteIOContext *pb, GXFContext *ctx)
375{
376 put_le32(pb, ctx->umf_length); /* total length of the umf data */
377 put_le32(pb, 3); /* version */
378 put_le32(pb, ctx->fc->nb_streams);
379 put_le32(pb, ctx->umf_track_offset); /* umf track section offset */
380 put_le32(pb, ctx->umf_track_size);
381 put_le32(pb, ctx->fc->nb_streams);
382 put_le32(pb, ctx->umf_media_offset);
383 put_le32(pb, ctx->umf_media_size);
384 put_le32(pb, ctx->umf_user_data_offset); /* user data offset */
385 put_le32(pb, ctx->umf_user_data_size); /* user data size */
386 put_le32(pb, 0); /* reserved */
387 put_le32(pb, 0); /* reserved */
388 return 48;
389}
390
391static int gxf_write_umf_track_description(ByteIOContext *pb, GXFContext *ctx)
392{
393 offset_t pos = url_ftell(pb);
394 int tracks[255]={0};
395 int i;
396
397 ctx->umf_track_offset = pos - ctx->umf_start_offset;
398 for (i = 0; i < ctx->fc->nb_streams; ++i) {
399 AVStream *st = ctx->fc->streams[i];
400 GXFStreamContext *sc = &ctx->streams[i];
401 int id = 0;
402
403 switch (st->codec->codec_id) {
404 case CODEC_ID_MPEG1VIDEO: id= 'L'; break;
405 case CODEC_ID_MPEG2VIDEO: id= 'M'; break;
406 case CODEC_ID_PCM_S16LE: id= 'A'; break;
407 case CODEC_ID_DVVIDEO: id= sc->track_type == 6 ? 'E' : 'D'; break;
408 case CODEC_ID_MJPEG: id= 'V'; break;
409 default: break;
410 }
411 sc->media_info= id << 8;
412 /* FIXME first 10 audio tracks are 0 to 9 next 22 are A to V */
413 sc->media_info |= '0' + (tracks[id]++);
414 put_le16(pb, sc->media_info);
415 put_le16(pb, 1);
416 }
417 return url_ftell(pb) - pos;
418}
419
420static int gxf_write_umf_media_mpeg(ByteIOContext *pb, GXFStreamContext *stream)
421{
422 if (stream->codec->pix_fmt == PIX_FMT_YUV422P)
423 put_le32(pb, 2);
424 else
425 put_le32(pb, 1); /* default to 420 */
426 put_le32(pb, stream->first_gop_closed == 1); /* closed = 1, open = 0, unknown = 255 */
427 put_le32(pb, 3); /* top = 1, bottom = 2, frame = 3, unknown = 0 */
428 put_le32(pb, 1); /* I picture per GOP */
429 put_le32(pb, stream->p_per_gop);
430 put_le32(pb, stream->b_per_gop);
431 if (stream->codec->codec_id == CODEC_ID_MPEG2VIDEO)
432 put_le32(pb, 2);
433 else if (stream->codec->codec_id == CODEC_ID_MPEG1VIDEO)
434 put_le32(pb, 1);
435 else
436 put_le32(pb, 0);
437 put_le32(pb, 0); /* reserved */
438 return 32;
439}
440
441static int gxf_write_umf_media_timecode(ByteIOContext *pb, GXFStreamContext *track)
442{
443 /* FIXME implement */
444 put_be32(pb, 0); /* drop frame flag */
445 put_be32(pb, 0); /* reserved */
446 put_be32(pb, 0); /* reserved */
447 put_be32(pb, 0); /* reserved */
448 put_be32(pb, 0); /* reserved */
449 put_be32(pb, 0); /* reserved */
450 put_be32(pb, 0); /* reserved */
451 put_be32(pb, 0); /* reserved */
452 return 32;
453}
454
455static int gxf_write_umf_media_dv(ByteIOContext *pb, GXFStreamContext *track)
456{
457 int i;
458
459 for (i = 0; i < 8; i++) {
460 put_be32(pb, 0);
461 }
462 return 32;
463}
464
465static int gxf_write_umf_media_audio(ByteIOContext *pb, GXFStreamContext *track)
466{
467 put_le64(pb, av_dbl2int(1)); /* sound level to begin to */
468 put_le64(pb, av_dbl2int(1)); /* sound level to begin to */
469 put_le32(pb, 0); /* number of fields over which to ramp up sound level */
470 put_le32(pb, 0); /* number of fields over which to ramp down sound level */
471 put_le32(pb, 0); /* reserved */
472 put_le32(pb, 0); /* reserved */
473 return 32;
474}
475
476#if 0
477static int gxf_write_umf_media_mjpeg(ByteIOContext *pb, GXFStreamContext *track)
478{
479 put_be64(pb, 0); /* FIXME FLOAT max chroma quant level */
480 put_be64(pb, 0); /* FIXME FLOAT max luma quant level */
481 put_be64(pb, 0); /* FIXME FLOAT min chroma quant level */
482 put_be64(pb, 0); /* FIXME FLOAT min luma quant level */
483 return 32;
484}
485#endif
486
487static int gxf_write_umf_media_description(ByteIOContext *pb, GXFContext *ctx)
488{
489 offset_t pos;
490 int i;
491
492 pos = url_ftell(pb);
493 ctx->umf_media_offset = pos - ctx->umf_start_offset;
494 for (i = 0; i < ctx->fc->nb_streams; ++i) {
495 GXFStreamContext *sc = &ctx->streams[i];
496 char buffer[88];
497 offset_t startpos, curpos;
498 int path_size = strlen(ES_NAME_PATTERN);
499
500 memset(buffer, 0, 88);
501 startpos = url_ftell(pb);
502 put_le16(pb, 0); /* length */
503 put_le16(pb, sc->media_info);
504 put_le16(pb, 0); /* reserved */
505 put_le16(pb, 0); /* reserved */
506 put_le32(pb, ctx->nb_frames);
507 put_le32(pb, 0); /* attributes rw, ro */
508 put_le32(pb, 0); /* mark in */
509 put_le32(pb, ctx->nb_frames); /* mark out */
510 strncpy(buffer, ES_NAME_PATTERN, path_size);
511 put_buffer(pb, (uint8_t *)buffer, path_size);
512 put_be16(pb, sc->media_info);
513 put_buffer(pb, (uint8_t *)buffer + path_size + 2, 88 - path_size - 2);
514 put_le32(pb, sc->track_type);
515 put_le32(pb, sc->sample_rate);
516 put_le32(pb, sc->sample_size);
517 put_le32(pb, 0); /* reserved */
518 switch (sc->codec->codec_id) {
519 case CODEC_ID_MPEG2VIDEO:
520 gxf_write_umf_media_mpeg(pb, sc);
521 break;
522 case CODEC_ID_PCM_S16LE:
523 gxf_write_umf_media_audio(pb, sc);
524 break;
525 case CODEC_ID_DVVIDEO:
526 gxf_write_umf_media_dv(pb, sc);
527 break;
528 default:
529 gxf_write_umf_media_timecode(pb, sc); /* 8 0bytes */
530 }
531 curpos = url_ftell(pb);
532 url_fseek(pb, startpos, SEEK_SET);
533 put_le16(pb, curpos - startpos);
534 url_fseek(pb, curpos, SEEK_SET);
535 }
536 return url_ftell(pb) - pos;
537}
538
539static int gxf_write_umf_user_data(ByteIOContext *pb, GXFContext *ctx)
540{
541 offset_t pos = url_ftell(pb);
542 ctx->umf_user_data_offset = pos - ctx->umf_start_offset;
543 put_le32(pb, 20);
544 put_le32(pb, 0);
545 put_le16(pb, 0);
546 put_le16(pb, 0);
547 put_le32(pb, 0);
548 put_byte(pb, 0);
549 put_byte(pb, 0);
550 put_byte(pb, 0);
551 put_byte(pb, 0);
552 return 20;
553}
554
555static int gxf_write_umf_packet(ByteIOContext *pb, GXFContext *ctx)
556{
557 offset_t pos = url_ftell(pb);
558
559 gxf_write_packet_header(pb, PKT_UMF);
560
561 /* preamble */
562 put_byte(pb, 3); /* first and last (only) packet */
563 put_be32(pb, ctx->umf_length); /* data length */
564
565 ctx->umf_start_offset = url_ftell(pb);
566 gxf_write_umf_payload(pb, ctx);
567 gxf_write_umf_material_description(pb, ctx);
568 ctx->umf_track_size = gxf_write_umf_track_description(pb, ctx);
569 ctx->umf_media_size = gxf_write_umf_media_description(pb, ctx);
570 ctx->umf_user_data_size = gxf_write_umf_user_data(pb, ctx);
571 ctx->umf_length = url_ftell(pb) - ctx->umf_start_offset;
572 return updatePacketSize(pb, pos);
573}
574
575#define GXF_NODELAY -5000
576
577static int gxf_write_header(AVFormatContext *s)
578{
579 ByteIOContext *pb = s->pb;
580 GXFContext *gxf = s->priv_data;
581 int i;
582
583 gxf->fc = s;
584 gxf->flags |= 0x00080000; /* material is simple clip */
585 for (i = 0; i < s->nb_streams; ++i) {
586 AVStream *st = s->streams[i];
587 GXFStreamContext *sc = &gxf->streams[i];
588
589 sc->codec = st->codec;
590 sc->index = i;
591 sc->media_type = codec_get_tag(gxf_media_types, sc->codec->codec_id);
592 if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
593 if (st->codec->codec_id != CODEC_ID_PCM_S16LE) {
594 av_log(s, AV_LOG_ERROR, "only 16 BIT PCM LE allowed for now\n");
595 return -1;
596 }
597 if (st->codec->sample_rate != 48000) {
598 av_log(s, AV_LOG_ERROR, "only 48000hz sampling rate is allowed\n");
599 return -1;
600 }
601 if (st->codec->channels != 1) {
602 av_log(s, AV_LOG_ERROR, "only mono tracks are allowed\n");
603 return -1;
604 }
605 sc->track_type = 2;
606 sc->sample_rate = st->codec->sample_rate;
607 av_set_pts_info(st, 64, 1, sc->sample_rate);
608 sc->sample_size = 16;
609 sc->frame_rate_index = -2;
610 sc->lines_index = -2;
611 sc->fields = -2;
612 gxf->audio_tracks++;
613 gxf->flags |= 0x04000000; /* audio is 16 bit pcm */
614 av_fifo_init(&sc->audio_buffer, 3*GXF_AUDIO_PACKET_SIZE);
615 } else if (sc->codec->codec_type == CODEC_TYPE_VIDEO) {
616 /* FIXME check from time_base ? */
617 if (sc->codec->height == 480 || sc->codec->height == 512) { /* NTSC or NTSC+VBI */
618 sc->frame_rate_index = 5;
619 sc->sample_rate = 60;
620 gxf->flags |= 0x00000080;
621 } else { /* assume PAL */
622 sc->frame_rate_index = 6;
623 sc->media_type++;
624 sc->sample_rate = 50;
625 gxf->flags |= 0x00000040;
626 }
627 gxf->sample_rate = sc->sample_rate;
628 av_set_pts_info(st, 64, 1, st->codec->time_base.den);
629 sc->dts_delay = GXF_NODELAY;
630 if (gxf_find_lines_index(sc) < 0)
631 sc->lines_index = -1;
632 sc->sample_size = st->codec->bit_rate;
633 sc->fields = 2; /* interlaced */
634 switch (sc->codec->codec_id) {
635 case CODEC_ID_MPEG2VIDEO:
636 sc->first_gop_closed = -1;
637 sc->track_type = 4;
638 gxf->mpeg_tracks++;
639 gxf->flags |= 0x00008000;
640 break;
641 case CODEC_ID_DVVIDEO:
642 if (sc->codec->pix_fmt == PIX_FMT_YUV422P) {
643 sc->media_type += 2;
644 sc->track_type = 6;
645 gxf->flags |= 0x00002000;
646 } else {
647 sc->track_type = 5;
648 gxf->flags |= 0x00001000;
649 }
650 break;
651 default:
652 av_log(s, AV_LOG_ERROR, "video codec not supported\n");
653 return -1;
654 }
655 }
656 }
657 gxf_write_map_packet(pb, gxf);
658 //gxf_write_flt_packet(pb, gxf);
659 gxf_write_umf_packet(pb, gxf);
660 put_flush_packet(pb);
661 return 0;
662}
663
664static int gxf_write_eos_packet(ByteIOContext *pb, GXFContext *ctx)
665{
666 offset_t pos = url_ftell(pb);
667
668 gxf_write_packet_header(pb, PKT_EOS);
669 return updatePacketSize(pb, pos);
670}
671
672static int gxf_write_trailer(AVFormatContext *s)
673{
674 ByteIOContext *pb = s->pb;
675 GXFContext *gxf = s->priv_data;
676 offset_t end;
677 int i;
678
679 for (i = 0; i < s->nb_streams; ++i) {
680 if (s->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO) {
681 av_fifo_free(&gxf->streams[i].audio_buffer);
682 } else if (s->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO) {
683 gxf->nb_frames = 2 * s->streams[i]->codec->frame_number;
684 }
685 }
686
687 gxf_write_eos_packet(pb, gxf);
688 end = url_ftell(pb);
689 url_fseek(pb, 0, SEEK_SET);
690 /* overwrite map and umf packets with new values */
691 gxf_write_map_packet(pb, gxf);
692 //gxf_write_flt_packet(pb, gxf);
693 gxf_write_umf_packet(pb, gxf);
694 url_fseek(pb, end, SEEK_SET);
695 return 0;
696}
697
698static int gxf_parse_mpeg_frame(GXFStreamContext *sc, const uint8_t *buf, int size)
699{
700 uint32_t c=-1;
701 int i;
702 for(i=0; i<size-4 && c!=0x100; i++){
703 c = (c<<8) + buf[i];
704 if(c == 0x1B8 && sc->first_gop_closed == -1) /* GOP start code */
705 sc->first_gop_closed= (buf[i+4]>>6)&1;
706 }
707 return (buf[i+1]>>3)&7;
708}
709
710static int gxf_write_media_preamble(ByteIOContext *pb, GXFContext *ctx, AVPacket *pkt, int size)
711{
712 GXFStreamContext *sc = &ctx->streams[pkt->stream_index];
713 int64_t dts = av_rescale_rnd(pkt->dts, ctx->sample_rate, sc->codec->time_base.den, AV_ROUND_UP);
714
715 put_byte(pb, sc->media_type);
716 put_byte(pb, sc->index);
717 put_be32(pb, dts);
718 if (sc->codec->codec_type == CODEC_TYPE_AUDIO) {
719 put_be16(pb, 0);
720 put_be16(pb, size / 2);
721 } else if (sc->codec->codec_id == CODEC_ID_MPEG2VIDEO) {
722 int frame_type = gxf_parse_mpeg_frame(sc, pkt->data, pkt->size);
723 if (frame_type == FF_I_TYPE) {
724 put_byte(pb, 0x0d);
725 sc->iframes++;
726 } else if (frame_type == FF_B_TYPE) {
727 put_byte(pb, 0x0f);
728 sc->bframes++;
729 } else {
730 put_byte(pb, 0x0e);
731 sc->pframes++;
732 }
733 put_be24(pb, size);
734 } else if (sc->codec->codec_id == CODEC_ID_DVVIDEO) {
735 put_byte(pb, size / 4096);
736 put_be24(pb, 0);
737 } else
738 put_be32(pb, size);
739 put_be32(pb, dts);
740 put_byte(pb, 1); /* flags */
741 put_byte(pb, 0); /* reserved */
742 return 16;
743}
744
745static int gxf_write_media_packet(ByteIOContext *pb, GXFContext *ctx, AVPacket *pkt)
746{
747 GXFStreamContext *sc = &ctx->streams[pkt->stream_index];
748 offset_t pos = url_ftell(pb);
749 int padding = 0;
750
751 gxf_write_packet_header(pb, PKT_MEDIA);
752 if (sc->codec->codec_id == CODEC_ID_MPEG2VIDEO && pkt->size % 4) /* MPEG-2 frames must be padded */
753 padding = 4 - pkt->size % 4;
754 else if (sc->codec->codec_type == CODEC_TYPE_AUDIO)
755 padding = GXF_AUDIO_PACKET_SIZE - pkt->size;
756 gxf_write_media_preamble(pb, ctx, pkt, pkt->size + padding);
757 put_buffer(pb, pkt->data, pkt->size);
758 gxf_write_padding(pb, padding);
759 return updatePacketSize(pb, pos);
760}
761
762static int gxf_write_packet(AVFormatContext *s, AVPacket *pkt)
763{
764 GXFContext *gxf = s->priv_data;
765
766 gxf_write_media_packet(s->pb, gxf, pkt);
767 put_flush_packet(s->pb);
768 return 0;
769}
770
771static int gxf_new_audio_packet(GXFContext *gxf, GXFStreamContext *sc, AVPacket *pkt, int flush)
772{
773 int size = flush ? av_fifo_size(&sc->audio_buffer) : GXF_AUDIO_PACKET_SIZE;
774
775 if (!size)
776 return 0;
777 av_new_packet(pkt, size);
778 av_fifo_read(&sc->audio_buffer, pkt->data, size);
779 pkt->stream_index = sc->index;
780 pkt->dts = sc->current_dts;
781 sc->current_dts += size / 2; /* we only support 16 bit pcm mono for now */
782 return size;
783}
784
785static int gxf_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
786{
787 GXFContext *gxf = s->priv_data;
788 AVPacket new_pkt;
789 int i;
790
791 for (i = 0; i < s->nb_streams; i++) {
792 AVStream *st = s->streams[i];
793 GXFStreamContext *sc = &gxf->streams[i];
794 if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
795 if (pkt && pkt->stream_index == i) {
796 av_fifo_generic_write(&sc->audio_buffer, pkt->data, pkt->size, NULL);
797 pkt = NULL;
798 }
799 if (flush || av_fifo_size(&sc->audio_buffer) >= GXF_AUDIO_PACKET_SIZE) {
800 if (!pkt && gxf_new_audio_packet(gxf, sc, &new_pkt, flush) > 0) {
801 pkt = &new_pkt;
802 break; /* add pkt right now into list */
803 }
804 }
805 } else if (pkt && pkt->stream_index == i) {
806 if (sc->dts_delay == GXF_NODELAY) /* adjust dts if needed */
807 sc->dts_delay = pkt->dts;
808 pkt->dts -= sc->dts_delay;
809 }
810 }
811 return av_interleave_packet_per_dts(s, out, pkt, flush);
812}
813
814AVOutputFormat gxf_muxer = {
815 "gxf",
816 NULL_IF_CONFIG_SMALL("GXF format"),
817 NULL,
818 "gxf",
819 sizeof(GXFContext),
820 CODEC_ID_PCM_S16LE,
821 CODEC_ID_MPEG2VIDEO,
822 gxf_write_header,
823 gxf_write_packet,
824 gxf_write_trailer,
825 0,
826 NULL,
827 gxf_interleave_packet,
828};
diff --git a/src/plugins/ffmpeg/libavformat/http.c b/src/plugins/ffmpeg/libavformat/http.c
deleted file mode 100644
index fc9cac4..0000000
--- a/src/plugins/ffmpeg/libavformat/http.c
+++ /dev/null
@@ -1,355 +0,0 @@
1/*
2 * HTTP protocol for ffmpeg client
3 * Copyright (c) 2000, 2001 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/base64.h"
23#include "libavutil/avstring.h"
24#include "avformat.h"
25#include <unistd.h>
26#include "network.h"
27#include "os_support.h"
28
29/* XXX: POST protocol is not completely implemented because ffmpeg uses
30 only a subset of it. */
31
32//#define DEBUG
33
34/* used for protocol handling */
35#define BUFFER_SIZE 1024
36#define URL_SIZE 4096
37#define MAX_REDIRECTS 8
38
39typedef struct {
40 URLContext *hd;
41 unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
42 int line_count;
43 int http_code;
44 offset_t off, filesize;
45 char location[URL_SIZE];
46} HTTPContext;
47
48static int http_connect(URLContext *h, const char *path, const char *hoststr,
49 const char *auth, int *new_location);
50static int http_write(URLContext *h, uint8_t *buf, int size);
51
52
53/* return non zero if error */
54static int http_open_cnx(URLContext *h)
55{
56 const char *path, *proxy_path;
57 char hostname[1024], hoststr[1024];
58 char auth[1024];
59 char path1[1024];
60 char buf[1024];
61 int port, use_proxy, err, location_changed = 0, redirects = 0;
62 HTTPContext *s = h->priv_data;
63 URLContext *hd = NULL;
64
65 proxy_path = getenv("http_proxy");
66 use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
67 av_strstart(proxy_path, "http://", NULL);
68
69 /* fill the dest addr */
70 redo:
71 /* needed in any case to build the host string */
72 url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
73 path1, sizeof(path1), s->location);
74 if (port > 0) {
75 snprintf(hoststr, sizeof(hoststr), "%s:%d", hostname, port);
76 } else {
77 av_strlcpy(hoststr, hostname, sizeof(hoststr));
78 }
79
80 if (use_proxy) {
81 url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
82 NULL, 0, proxy_path);
83 path = s->location;
84 } else {
85 if (path1[0] == '\0')
86 path = "/";
87 else
88 path = path1;
89 }
90 if (port < 0)
91 port = 80;
92
93 snprintf(buf, sizeof(buf), "tcp://%s:%d", hostname, port);
94 err = url_open(&hd, buf, URL_RDWR);
95 if (err < 0)
96 goto fail;
97
98 s->hd = hd;
99 if (http_connect(h, path, hoststr, auth, &location_changed) < 0)
100 goto fail;
101 if ((s->http_code == 302 || s->http_code == 303) && location_changed == 1) {
102 /* url moved, get next */
103 url_close(hd);
104 if (redirects++ >= MAX_REDIRECTS)
105 return AVERROR(EIO);
106 location_changed = 0;
107 goto redo;
108 }
109 return 0;
110 fail:
111 if (hd)
112 url_close(hd);
113 return AVERROR(EIO);
114}
115
116static int http_open(URLContext *h, const char *uri, int flags)
117{
118 HTTPContext *s;
119 int ret;
120
121 h->is_streamed = 1;
122
123 s = av_malloc(sizeof(HTTPContext));
124 if (!s) {
125 return AVERROR(ENOMEM);
126 }
127 h->priv_data = s;
128 s->filesize = -1;
129 s->off = 0;
130 av_strlcpy(s->location, uri, URL_SIZE);
131
132 ret = http_open_cnx(h);
133 if (ret != 0)
134 av_free (s);
135 return ret;
136}
137static int http_getc(HTTPContext *s)
138{
139 int len;
140 if (s->buf_ptr >= s->buf_end) {
141 len = url_read(s->hd, s->buffer, BUFFER_SIZE);
142 if (len < 0) {
143 return AVERROR(EIO);
144 } else if (len == 0) {
145 return -1;
146 } else {
147 s->buf_ptr = s->buffer;
148 s->buf_end = s->buffer + len;
149 }
150 }
151 return *s->buf_ptr++;
152}
153
154static int process_line(URLContext *h, char *line, int line_count,
155 int *new_location)
156{
157 HTTPContext *s = h->priv_data;
158 char *tag, *p;
159
160 /* end of header */
161 if (line[0] == '\0')
162 return 0;
163
164 p = line;
165 if (line_count == 0) {
166 while (!isspace(*p) && *p != '\0')
167 p++;
168 while (isspace(*p))
169 p++;
170 s->http_code = strtol(p, NULL, 10);
171#ifdef DEBUG
172 printf("http_code=%d\n", s->http_code);
173#endif
174 /* error codes are 4xx and 5xx */
175 if (s->http_code >= 400 && s->http_code < 600)
176 return -1;
177 } else {
178 while (*p != '\0' && *p != ':')
179 p++;
180 if (*p != ':')
181 return 1;
182
183 *p = '\0';
184 tag = line;
185 p++;
186 while (isspace(*p))
187 p++;
188 if (!strcmp(tag, "Location")) {
189 strcpy(s->location, p);
190 *new_location = 1;
191 } else if (!strcmp (tag, "Content-Length") && s->filesize == -1) {
192 s->filesize = atoll(p);
193 } else if (!strcmp (tag, "Content-Range")) {
194 /* "bytes $from-$to/$document_size" */
195 const char *slash;
196 if (!strncmp (p, "bytes ", 6)) {
197 p += 6;
198 s->off = atoll(p);
199 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
200 s->filesize = atoll(slash+1);
201 }
202 h->is_streamed = 0; /* we _can_ in fact seek */
203 }
204 }
205 return 1;
206}
207
208static int http_connect(URLContext *h, const char *path, const char *hoststr,
209 const char *auth, int *new_location)
210{
211 HTTPContext *s = h->priv_data;
212 int post, err, ch;
213 char line[1024], *q;
214 char *auth_b64;
215 int auth_b64_len = strlen(auth)* 4 / 3 + 12;
216 offset_t off = s->off;
217
218
219 /* send http header */
220 post = h->flags & URL_WRONLY;
221 auth_b64 = av_malloc(auth_b64_len);
222 av_base64_encode(auth_b64, auth_b64_len, auth, strlen(auth));
223 snprintf(s->buffer, sizeof(s->buffer),
224 "%s %s HTTP/1.1\r\n"
225 "User-Agent: %s\r\n"
226 "Accept: */*\r\n"
227 "Range: bytes=%"PRId64"-\r\n"
228 "Host: %s\r\n"
229 "Authorization: Basic %s\r\n"
230 "Connection: close\r\n"
231 "\r\n",
232 post ? "POST" : "GET",
233 path,
234 LIBAVFORMAT_IDENT,
235 s->off,
236 hoststr,
237 auth_b64);
238
239 av_freep(&auth_b64);
240 if (http_write(h, s->buffer, strlen(s->buffer)) < 0)
241 return AVERROR(EIO);
242
243 /* init input buffer */
244 s->buf_ptr = s->buffer;
245 s->buf_end = s->buffer;
246 s->line_count = 0;
247 s->off = 0;
248 s->filesize = -1;
249 if (post) {
250 return 0;
251 }
252
253 /* wait for header */
254 q = line;
255 for(;;) {
256 ch = http_getc(s);
257 if (ch < 0)
258 return AVERROR(EIO);
259 if (ch == '\n') {
260 /* process line */
261 if (q > line && q[-1] == '\r')
262 q--;
263 *q = '\0';
264#ifdef DEBUG
265 printf("header='%s'\n", line);
266#endif
267 err = process_line(h, line, s->line_count, new_location);
268 if (err < 0)
269 return err;
270 if (err == 0)
271 break;
272 s->line_count++;
273 q = line;
274 } else {
275 if ((q - line) < sizeof(line) - 1)
276 *q++ = ch;
277 }
278 }
279
280 return (off == s->off) ? 0 : -1;
281}
282
283
284static int http_read(URLContext *h, uint8_t *buf, int size)
285{
286 HTTPContext *s = h->priv_data;
287 int len;
288
289 /* read bytes from input buffer first */
290 len = s->buf_end - s->buf_ptr;
291 if (len > 0) {
292 if (len > size)
293 len = size;
294 memcpy(buf, s->buf_ptr, len);
295 s->buf_ptr += len;
296 } else {
297 len = url_read(s->hd, buf, size);
298 }
299 if (len > 0)
300 s->off += len;
301 return len;
302}
303
304/* used only when posting data */
305static int http_write(URLContext *h, uint8_t *buf, int size)
306{
307 HTTPContext *s = h->priv_data;
308 return url_write(s->hd, buf, size);
309}
310
311static int http_close(URLContext *h)
312{
313 HTTPContext *s = h->priv_data;
314 url_close(s->hd);
315 av_free(s);
316 return 0;
317}
318
319static offset_t http_seek(URLContext *h, offset_t off, int whence)
320{
321 HTTPContext *s = h->priv_data;
322 URLContext *old_hd = s->hd;
323 offset_t old_off = s->off;
324
325 if (whence == AVSEEK_SIZE)
326 return s->filesize;
327 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
328 return -1;
329
330 /* we save the old context in case the seek fails */
331 s->hd = NULL;
332 if (whence == SEEK_CUR)
333 off += s->off;
334 else if (whence == SEEK_END)
335 off += s->filesize;
336 s->off = off;
337
338 /* if it fails, continue on old connection */
339 if (http_open_cnx(h) < 0) {
340 s->hd = old_hd;
341 s->off = old_off;
342 return -1;
343 }
344 url_close(old_hd);
345 return off;
346}
347
348URLProtocol http_protocol = {
349 "http",
350 http_open,
351 http_read,
352 http_write,
353 http_seek,
354 http_close,
355};
diff --git a/src/plugins/ffmpeg/libavformat/idcin.c b/src/plugins/ffmpeg/libavformat/idcin.c
deleted file mode 100644
index 1a8e558..0000000
--- a/src/plugins/ffmpeg/libavformat/idcin.c
+++ /dev/null
@@ -1,290 +0,0 @@
1/*
2 * id Quake II CIN File Demuxer
3 * Copyright (c) 2003 The ffmpeg Project
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/**
23 * @file idcin.c
24 * id Quake II CIN file demuxer by Mike Melanson (melanson@pcisys.net)
25 * For more information about the id CIN format, visit:
26 * http://www.csse.monash.edu.au/~timf/
27 *
28 * CIN is a somewhat quirky and ill-defined format. Here are some notes
29 * for anyone trying to understand the technical details of this format:
30 *
31 * The format has no definite file signature. This is problematic for a
32 * general-purpose media player that wants to automatically detect file
33 * types. However, a CIN file does start with 5 32-bit numbers that
34 * specify audio and video parameters. This demuxer gets around the lack
35 * of file signature by performing sanity checks on those parameters.
36 * Probabalistically, this is a reasonable solution since the number of
37 * valid combinations of the 5 parameters is a very small subset of the
38 * total 160-bit number space.
39 *
40 * Refer to the function idcin_probe() for the precise A/V parameters
41 * that this demuxer allows.
42 *
43 * Next, each audio and video frame has a duration of 1/14 sec. If the
44 * audio sample rate is a multiple of the common frequency 22050 Hz it will
45 * divide evenly by 14. However, if the sample rate is 11025 Hz:
46 * 11025 (samples/sec) / 14 (frames/sec) = 787.5 (samples/frame)
47 * The way the CIN stores audio in this case is by storing 787 sample
48 * frames in the first audio frame and 788 sample frames in the second
49 * audio frame. Therefore, the total number of bytes in an audio frame
50 * is given as:
51 * audio frame #0: 787 * (bytes/sample) * (# channels) bytes in frame
52 * audio frame #1: 788 * (bytes/sample) * (# channels) bytes in frame
53 * audio frame #2: 787 * (bytes/sample) * (# channels) bytes in frame
54 * audio frame #3: 788 * (bytes/sample) * (# channels) bytes in frame
55 *
56 * Finally, not all id CIN creation tools agree on the resolution of the
57 * color palette, apparently. Some creation tools specify red, green, and
58 * blue palette components in terms of 6-bit VGA color DAC values which
59 * range from 0..63. Other tools specify the RGB components as full 8-bit
60 * values that range from 0..255. Since there are no markers in the file to
61 * differentiate between the two variants, this demuxer uses the following
62 * heuristic:
63 * - load the 768 palette bytes from disk
64 * - assume that they will need to be shifted left by 2 bits to
65 * transform them from 6-bit values to 8-bit values
66 * - scan through all 768 palette bytes
67 * - if any bytes exceed 63, do not shift the bytes at all before
68 * transmitting them to the video decoder
69 */
70
71#include "avformat.h"
72
73#define HUFFMAN_TABLE_SIZE (64 * 1024)
74#define IDCIN_FPS 14
75
76typedef struct IdcinDemuxContext {
77 int video_stream_index;
78 int audio_stream_index;
79 int audio_chunk_size1;
80 int audio_chunk_size2;
81
82 /* demux state variables */
83 int current_audio_chunk;
84 int next_chunk_is_video;
85 int audio_present;
86
87 int64_t pts;
88
89 AVPaletteControl palctrl;
90} IdcinDemuxContext;
91
92static int idcin_probe(AVProbeData *p)
93{
94 unsigned int number;
95
96 /*
97 * This is what you could call a "probabilistic" file check: id CIN
98 * files don't have a definite file signature. In lieu of such a marker,
99 * perform sanity checks on the 5 32-bit header fields:
100 * width, height: greater than 0, less than or equal to 1024
101 * audio sample rate: greater than or equal to 8000, less than or
102 * equal to 48000, or 0 for no audio
103 * audio sample width (bytes/sample): 0 for no audio, or 1 or 2
104 * audio channels: 0 for no audio, or 1 or 2
105 */
106
107 /* check the video width */
108 number = AV_RL32(&p->buf[0]);
109 if ((number == 0) || (number > 1024))
110 return 0;
111
112 /* check the video height */
113 number = AV_RL32(&p->buf[4]);
114 if ((number == 0) || (number > 1024))
115 return 0;
116
117 /* check the audio sample rate */
118 number = AV_RL32(&p->buf[8]);
119 if ((number != 0) && ((number < 8000) | (number > 48000)))
120 return 0;
121
122 /* check the audio bytes/sample */
123 number = AV_RL32(&p->buf[12]);
124 if (number > 2)
125 return 0;
126
127 /* check the audio channels */
128 number = AV_RL32(&p->buf[16]);
129 if (number > 2)
130 return 0;
131
132 /* return half certainly since this check is a bit sketchy */
133 return AVPROBE_SCORE_MAX / 2;
134}
135
136static int idcin_read_header(AVFormatContext *s,
137 AVFormatParameters *ap)
138{
139 ByteIOContext *pb = s->pb;
140 IdcinDemuxContext *idcin = s->priv_data;
141 AVStream *st;
142 unsigned int width, height;
143 unsigned int sample_rate, bytes_per_sample, channels;
144
145 /* get the 5 header parameters */
146 width = get_le32(pb);
147 height = get_le32(pb);
148 sample_rate = get_le32(pb);
149 bytes_per_sample = get_le32(pb);
150 channels = get_le32(pb);
151
152 st = av_new_stream(s, 0);
153 if (!st)
154 return AVERROR(ENOMEM);
155 av_set_pts_info(st, 33, 1, IDCIN_FPS);
156 idcin->video_stream_index = st->index;
157 st->codec->codec_type = CODEC_TYPE_VIDEO;
158 st->codec->codec_id = CODEC_ID_IDCIN;
159 st->codec->codec_tag = 0; /* no fourcc */
160 st->codec->width = width;
161 st->codec->height = height;
162
163 /* load up the Huffman tables into extradata */
164 st->codec->extradata_size = HUFFMAN_TABLE_SIZE;
165 st->codec->extradata = av_malloc(HUFFMAN_TABLE_SIZE);
166 if (get_buffer(pb, st->codec->extradata, HUFFMAN_TABLE_SIZE) !=
167 HUFFMAN_TABLE_SIZE)
168 return AVERROR(EIO);
169 /* save a reference in order to transport the palette */
170 st->codec->palctrl = &idcin->palctrl;
171
172 /* if sample rate is 0, assume no audio */
173 if (sample_rate) {
174 idcin->audio_present = 1;
175 st = av_new_stream(s, 0);
176 if (!st)
177 return AVERROR(ENOMEM);
178 av_set_pts_info(st, 33, 1, IDCIN_FPS);
179 idcin->audio_stream_index = st->index;
180 st->codec->codec_type = CODEC_TYPE_AUDIO;
181 st->codec->codec_tag = 1;
182 st->codec->channels = channels;
183 st->codec->sample_rate = sample_rate;
184 st->codec->bits_per_sample = bytes_per_sample * 8;
185 st->codec->bit_rate = sample_rate * bytes_per_sample * 8 * channels;
186 st->codec->block_align = bytes_per_sample * channels;
187 if (bytes_per_sample == 1)
188 st->codec->codec_id = CODEC_ID_PCM_U8;
189 else
190 st->codec->codec_id = CODEC_ID_PCM_S16LE;
191
192 if (sample_rate % 14 != 0) {
193 idcin->audio_chunk_size1 = (sample_rate / 14) *
194 bytes_per_sample * channels;
195 idcin->audio_chunk_size2 = (sample_rate / 14 + 1) *
196 bytes_per_sample * channels;
197 } else {
198 idcin->audio_chunk_size1 = idcin->audio_chunk_size2 =
199 (sample_rate / 14) * bytes_per_sample * channels;
200 }
201 idcin->current_audio_chunk = 0;
202 } else
203 idcin->audio_present = 1;
204
205 idcin->next_chunk_is_video = 1;
206 idcin->pts = 0;
207
208 return 0;
209}
210
211static int idcin_read_packet(AVFormatContext *s,
212 AVPacket *pkt)
213{
214 int ret;
215 unsigned int command;
216 unsigned int chunk_size;
217 IdcinDemuxContext *idcin = s->priv_data;
218 ByteIOContext *pb = s->pb;
219 int i;
220 int palette_scale;
221 unsigned char r, g, b;
222 unsigned char palette_buffer[768];
223
224 if (url_feof(s->pb))
225 return AVERROR(EIO);
226
227 if (idcin->next_chunk_is_video) {
228 command = get_le32(pb);
229 if (command == 2) {
230 return AVERROR(EIO);
231 } else if (command == 1) {
232 /* trigger a palette change */
233 idcin->palctrl.palette_changed = 1;
234 if (get_buffer(pb, palette_buffer, 768) != 768)
235 return AVERROR(EIO);
236 /* scale the palette as necessary */
237 palette_scale = 2;
238 for (i = 0; i < 768; i++)
239 if (palette_buffer[i] > 63) {
240 palette_scale = 0;
241 break;
242 }
243
244 for (i = 0; i < 256; i++) {
245 r = palette_buffer[i * 3 ] << palette_scale;
246 g = palette_buffer[i * 3 + 1] << palette_scale;
247 b = palette_buffer[i * 3 + 2] << palette_scale;
248 idcin->palctrl.palette[i] = (r << 16) | (g << 8) | (b);
249 }
250 }
251
252 chunk_size = get_le32(pb);
253 /* skip the number of decoded bytes (always equal to width * height) */
254 url_fseek(pb, 4, SEEK_CUR);
255 chunk_size -= 4;
256 ret= av_get_packet(pb, pkt, chunk_size);
257 if (ret != chunk_size)
258 return AVERROR(EIO);
259 pkt->stream_index = idcin->video_stream_index;
260 pkt->pts = idcin->pts;
261 } else {
262 /* send out the audio chunk */
263 if (idcin->current_audio_chunk)
264 chunk_size = idcin->audio_chunk_size2;
265 else
266 chunk_size = idcin->audio_chunk_size1;
267 ret= av_get_packet(pb, pkt, chunk_size);
268 if (ret != chunk_size)
269 return AVERROR(EIO);
270 pkt->stream_index = idcin->audio_stream_index;
271 pkt->pts = idcin->pts;
272
273 idcin->current_audio_chunk ^= 1;
274 idcin->pts++;
275 }
276
277 if (idcin->audio_present)
278 idcin->next_chunk_is_video ^= 1;
279
280 return ret;
281}
282
283AVInputFormat idcin_demuxer = {
284 "idcin",
285 NULL_IF_CONFIG_SMALL("id CIN format"),
286 sizeof(IdcinDemuxContext),
287 idcin_probe,
288 idcin_read_header,
289 idcin_read_packet,
290};
diff --git a/src/plugins/ffmpeg/libavformat/idroq.c b/src/plugins/ffmpeg/libavformat/idroq.c
deleted file mode 100644
index 801f3dc..0000000
--- a/src/plugins/ffmpeg/libavformat/idroq.c
+++ /dev/null
@@ -1,280 +0,0 @@
1/*
2 * id RoQ (.roq) File Demuxer
3 * Copyright (c) 2003 The ffmpeg Project
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/**
23 * @file idroq.c
24 * id RoQ format file demuxer
25 * by Mike Melanson (melanson@pcisys.net)
26 * for more information on the .roq file format, visit:
27 * http://www.csse.monash.edu.au/~timf/
28 */
29
30#include "avformat.h"
31
32#define RoQ_MAGIC_NUMBER 0x1084
33#define RoQ_CHUNK_PREAMBLE_SIZE 8
34#define RoQ_AUDIO_SAMPLE_RATE 22050
35#define RoQ_CHUNKS_TO_SCAN 30
36
37#define RoQ_INFO 0x1001
38#define RoQ_QUAD_CODEBOOK 0x1002
39#define RoQ_QUAD_VQ 0x1011
40#define RoQ_SOUND_MONO 0x1020
41#define RoQ_SOUND_STEREO 0x1021
42
43typedef struct RoqDemuxContext {
44
45 int width;
46 int height;
47 int audio_channels;
48 int framerate;
49 int frame_pts_inc;
50
51 int video_stream_index;
52 int audio_stream_index;
53
54 int64_t video_pts;
55 unsigned int audio_frame_count;
56
57} RoqDemuxContext;
58
59static int roq_probe(AVProbeData *p)
60{
61 if ((AV_RL16(&p->buf[0]) != RoQ_MAGIC_NUMBER) ||
62 (AV_RL32(&p->buf[2]) != 0xFFFFFFFF))
63 return 0;
64
65 return AVPROBE_SCORE_MAX;
66}
67
68static int roq_read_header(AVFormatContext *s,
69 AVFormatParameters *ap)
70{
71 RoqDemuxContext *roq = s->priv_data;
72 ByteIOContext *pb = s->pb;
73 AVStream *st;
74 unsigned char preamble[RoQ_CHUNK_PREAMBLE_SIZE];
75 int i;
76 unsigned int chunk_size;
77 unsigned int chunk_type;
78
79 /* get the main header */
80 if (get_buffer(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) !=
81 RoQ_CHUNK_PREAMBLE_SIZE)
82 return AVERROR(EIO);
83 roq->framerate = AV_RL16(&preamble[6]);
84 roq->frame_pts_inc = 90000 / roq->framerate;
85
86 /* init private context parameters */
87 roq->width = roq->height = roq->audio_channels = roq->video_pts =
88 roq->audio_frame_count = 0;
89
90 /* scan the first n chunks searching for A/V parameters */
91 for (i = 0; i < RoQ_CHUNKS_TO_SCAN; i++) {
92 if (get_buffer(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) !=
93 RoQ_CHUNK_PREAMBLE_SIZE)
94 return AVERROR(EIO);
95
96 chunk_type = AV_RL16(&preamble[0]);
97 chunk_size = AV_RL32(&preamble[2]);
98
99 switch (chunk_type) {
100
101 case RoQ_INFO:
102 /* fetch the width and height; reuse the preamble bytes */
103 if (get_buffer(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) !=
104 RoQ_CHUNK_PREAMBLE_SIZE)
105 return AVERROR(EIO);
106 roq->width = AV_RL16(&preamble[0]);
107 roq->height = AV_RL16(&preamble[2]);
108 break;
109
110 case RoQ_QUAD_CODEBOOK:
111 case RoQ_QUAD_VQ:
112 /* ignore during this scan */
113 url_fseek(pb, chunk_size, SEEK_CUR);
114 break;
115
116 case RoQ_SOUND_MONO:
117 roq->audio_channels = 1;
118 url_fseek(pb, chunk_size, SEEK_CUR);
119 break;
120
121 case RoQ_SOUND_STEREO:
122 roq->audio_channels = 2;
123 url_fseek(pb, chunk_size, SEEK_CUR);
124 break;
125
126 default:
127 av_log(s, AV_LOG_ERROR, " unknown RoQ chunk type (%04X)\n", AV_RL16(&preamble[0]));
128 return AVERROR_INVALIDDATA;
129 break;
130 }
131
132 /* if all necessary parameters have been gathered, exit early */
133 if ((roq->width && roq->height) && roq->audio_channels)
134 break;
135 }
136
137 /* seek back to the first chunk */
138 url_fseek(pb, RoQ_CHUNK_PREAMBLE_SIZE, SEEK_SET);
139
140 /* initialize the decoders */
141 st = av_new_stream(s, 0);
142 if (!st)
143 return AVERROR(ENOMEM);
144 /* set the pts reference (1 pts = 1/90000) */
145 av_set_pts_info(st, 33, 1, 90000);
146 roq->video_stream_index = st->index;
147 st->codec->codec_type = CODEC_TYPE_VIDEO;
148 st->codec->codec_id = CODEC_ID_ROQ;
149 st->codec->codec_tag = 0; /* no fourcc */
150 st->codec->width = roq->width;
151 st->codec->height = roq->height;
152
153 if (roq->audio_channels) {
154 st = av_new_stream(s, 0);
155 if (!st)
156 return AVERROR(ENOMEM);
157 av_set_pts_info(st, 33, 1, 90000);
158 roq->audio_stream_index = st->index;
159 st->codec->codec_type = CODEC_TYPE_AUDIO;
160 st->codec->codec_id = CODEC_ID_ROQ_DPCM;
161 st->codec->codec_tag = 0; /* no tag */
162 st->codec->channels = roq->audio_channels;
163 st->codec->sample_rate = RoQ_AUDIO_SAMPLE_RATE;
164 st->codec->bits_per_sample = 16;
165 st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *
166 st->codec->bits_per_sample;
167 st->codec->block_align = st->codec->channels * st->codec->bits_per_sample;
168 }
169
170 return 0;
171}
172
173static int roq_read_packet(AVFormatContext *s,
174 AVPacket *pkt)
175{
176 RoqDemuxContext *roq = s->priv_data;
177 ByteIOContext *pb = s->pb;
178 int ret = 0;
179 unsigned int chunk_size;
180 unsigned int chunk_type;
181 unsigned int codebook_size;
182 unsigned char preamble[RoQ_CHUNK_PREAMBLE_SIZE];
183 int packet_read = 0;
184 offset_t codebook_offset;
185
186 while (!packet_read) {
187
188 if (url_feof(s->pb))
189 return AVERROR(EIO);
190
191 /* get the next chunk preamble */
192 if ((ret = get_buffer(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE)) !=
193 RoQ_CHUNK_PREAMBLE_SIZE)
194 return AVERROR(EIO);
195
196 chunk_type = AV_RL16(&preamble[0]);
197 chunk_size = AV_RL32(&preamble[2]);
198 if(chunk_size > INT_MAX)
199 return AVERROR_INVALIDDATA;
200
201 switch (chunk_type) {
202
203 case RoQ_INFO:
204 /* don't care about this chunk anymore */
205 url_fseek(pb, RoQ_CHUNK_PREAMBLE_SIZE, SEEK_CUR);
206 break;
207
208 case RoQ_QUAD_CODEBOOK:
209 /* packet needs to contain both this codebook and next VQ chunk */
210 codebook_offset = url_ftell(pb) - RoQ_CHUNK_PREAMBLE_SIZE;
211 codebook_size = chunk_size;
212 url_fseek(pb, codebook_size, SEEK_CUR);
213 if (get_buffer(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) !=
214 RoQ_CHUNK_PREAMBLE_SIZE)
215 return AVERROR(EIO);
216 chunk_size = AV_RL32(&preamble[2]) + RoQ_CHUNK_PREAMBLE_SIZE * 2 +
217 codebook_size;
218
219 /* rewind */
220 url_fseek(pb, codebook_offset, SEEK_SET);
221
222 /* load up the packet */
223 ret= av_get_packet(pb, pkt, chunk_size);
224 if (ret != chunk_size)
225 return AVERROR(EIO);
226 pkt->stream_index = roq->video_stream_index;
227 pkt->pts = roq->video_pts;
228
229 roq->video_pts += roq->frame_pts_inc;
230 packet_read = 1;
231 break;
232
233 case RoQ_SOUND_MONO:
234 case RoQ_SOUND_STEREO:
235 case RoQ_QUAD_VQ:
236 /* load up the packet */
237 if (av_new_packet(pkt, chunk_size + RoQ_CHUNK_PREAMBLE_SIZE))
238 return AVERROR(EIO);
239 /* copy over preamble */
240 memcpy(pkt->data, preamble, RoQ_CHUNK_PREAMBLE_SIZE);
241
242 if (chunk_type == RoQ_QUAD_VQ) {
243 pkt->stream_index = roq->video_stream_index;
244 pkt->pts = roq->video_pts;
245 roq->video_pts += roq->frame_pts_inc;
246 } else {
247 pkt->stream_index = roq->audio_stream_index;
248 pkt->pts = roq->audio_frame_count;
249 pkt->pts *= 90000;
250 pkt->pts /= RoQ_AUDIO_SAMPLE_RATE;
251 roq->audio_frame_count += (chunk_size / roq->audio_channels);
252 }
253
254 pkt->pos= url_ftell(pb);
255 ret = get_buffer(pb, pkt->data + RoQ_CHUNK_PREAMBLE_SIZE,
256 chunk_size);
257 if (ret != chunk_size)
258 ret = AVERROR(EIO);
259
260 packet_read = 1;
261 break;
262
263 default:
264 av_log(s, AV_LOG_ERROR, " unknown RoQ chunk (%04X)\n", chunk_type);
265 return AVERROR_INVALIDDATA;
266 break;
267 }
268 }
269
270 return ret;
271}
272
273AVInputFormat roq_demuxer = {
274 "RoQ",
275 NULL_IF_CONFIG_SMALL("id RoQ format"),
276 sizeof(RoqDemuxContext),
277 roq_probe,
278 roq_read_header,
279 roq_read_packet,
280};
diff --git a/src/plugins/ffmpeg/libavformat/iff.c b/src/plugins/ffmpeg/libavformat/iff.c
deleted file mode 100644
index a996a7f..0000000
--- a/src/plugins/ffmpeg/libavformat/iff.c
+++ /dev/null
@@ -1,200 +0,0 @@
1/*
2 * IFF (.iff) file demuxer
3 * Copyright (c) 2008 Jaikrishnan Menon <realityman@gmx.net>
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/**
23 * @file iff.c
24 * IFF file demuxer
25 * by Jaikrishnan Menon
26 * for more information on the .iff file format, visit:
27 * http://wiki.multimedia.cx/index.php?title=IFF
28 */
29
30#include "avformat.h"
31
32#define ID_8SVX MKTAG('8','S','V','X')
33#define ID_VHDR MKTAG('V','H','D','R')
34#define ID_ATAK MKTAG('A','T','A','K')
35#define ID_RLSE MKTAG('R','L','S','E')
36#define ID_CHAN MKTAG('C','H','A','N')
37
38#define ID_FORM MKTAG('F','O','R','M')
39#define ID_ANNO MKTAG('A','N','N','O')
40#define ID_AUTH MKTAG('A','U','T','H')
41#define ID_CHRS MKTAG('C','H','R','S')
42#define ID_COPYRIGHT MKTAG('(','c',')',' ')
43#define ID_CSET MKTAG('C','S','E','T')
44#define ID_FVER MKTAG('F','V','E','R')
45#define ID_NAME MKTAG('N','A','M','E')
46#define ID_TEXT MKTAG('T','E','X','T')
47#define ID_BODY MKTAG('B','O','D','Y')
48
49#define LEFT 2
50#define RIGHT 4
51#define STEREO 6
52
53#define PACKET_SIZE 1024
54
55typedef enum {COMP_NONE, COMP_FIB, COMP_EXP} svx8_compression_t;
56
57typedef struct {
58 uint32_t body_size;
59 uint32_t sent_bytes;
60 uint32_t audio_frame_count;
61} IffDemuxContext;
62
63
64static void interleave_stereo(const uint8_t *src, uint8_t *dest, int size)
65{
66 uint8_t *end = dest + size;
67 size = size>>1;
68
69 while(dest < end) {
70 *dest++ = *src;
71 *dest++ = *(src+size);
72 src++;
73 }
74}
75
76static int iff_probe(AVProbeData *p)
77{
78 const uint8_t *d = p->buf;
79
80 if ( AV_RL32(d) == ID_FORM &&
81 AV_RL32(d+8) == ID_8SVX)
82 return AVPROBE_SCORE_MAX;
83 return 0;
84}
85
86static int iff_read_header(AVFormatContext *s,
87 AVFormatParameters *ap)
88{
89 IffDemuxContext *iff = s->priv_data;
90 ByteIOContext *pb = s->pb;
91 AVStream *st;
92 uint32_t chunk_id, data_size;
93 int padding, done = 0;
94
95 st = av_new_stream(s, 0);
96 if (!st)
97 return AVERROR(ENOMEM);
98
99 st->codec->channels = 1;
100 url_fskip(pb, 12);
101
102 while(!done && !url_feof(pb)) {
103 chunk_id = get_le32(pb);
104 data_size = get_be32(pb);
105 padding = data_size & 1;
106
107 switch(chunk_id) {
108 case ID_VHDR:
109 url_fskip(pb, 12);
110 st->codec->sample_rate = get_be16(pb);
111 url_fskip(pb, 1);
112 st->codec->codec_tag = get_byte(pb);
113 url_fskip(pb, 4);
114 break;
115
116 case ID_BODY:
117 iff->body_size = data_size;
118 done = 1;
119 break;
120
121 case ID_CHAN:
122 st->codec->channels = (get_be32(pb) < 6) ? 1 : 2;
123 break;
124
125 default:
126 url_fseek(pb, data_size + padding, SEEK_CUR);
127 break;
128 }
129 }
130
131 if(!st->codec->sample_rate)
132 return AVERROR_INVALIDDATA;
133
134 av_set_pts_info(st, 32, 1, st->codec->sample_rate);
135 st->codec->codec_type = CODEC_TYPE_AUDIO;
136
137 switch(st->codec->codec_tag) {
138 case COMP_NONE:
139 st->codec->codec_id = CODEC_ID_PCM_S8;
140 break;
141 case COMP_FIB:
142 st->codec->codec_id = CODEC_ID_8SVX_FIB;
143 break;
144 case COMP_EXP:
145 st->codec->codec_id = CODEC_ID_8SVX_EXP;
146 break;
147 default:
148 av_log(s, AV_LOG_ERROR, "iff: unknown compression method\n");
149 return -1;
150 }
151
152 st->codec->bits_per_sample = 8;
153 st->codec->bit_rate = st->codec->channels * st->codec->sample_rate * st->codec->bits_per_sample;
154 st->codec->block_align = st->codec->channels * st->codec->bits_per_sample;
155
156 return 0;
157}
158
159static int iff_read_packet(AVFormatContext *s,
160 AVPacket *pkt)
161{
162 IffDemuxContext *iff = s->priv_data;
163 ByteIOContext *pb = s->pb;
164 int ret;
165
166 if(iff->sent_bytes > iff->body_size)
167 return AVERROR(EIO);
168
169 if(s->streams[0]->codec->channels == 2) {
170 uint8_t sample_buffer[PACKET_SIZE];
171
172 ret = get_buffer(pb, sample_buffer, PACKET_SIZE);
173 if(av_new_packet(pkt, PACKET_SIZE) < 0) {
174 av_log(s, AV_LOG_ERROR, "iff: cannot allocate packet \n");
175 return AVERROR(ENOMEM);
176 }
177 interleave_stereo(sample_buffer, pkt->data, PACKET_SIZE);
178 }
179 else {
180 ret = av_get_packet(pb, pkt, PACKET_SIZE);
181 }
182
183 if(iff->sent_bytes == 0)
184 pkt->flags |= PKT_FLAG_KEY;
185
186 iff->sent_bytes += PACKET_SIZE;
187 pkt->stream_index = 0;
188 pkt->pts = iff->audio_frame_count;
189 iff->audio_frame_count += ret / s->streams[0]->codec->channels;
190 return ret;
191}
192
193AVInputFormat iff_demuxer = {
194 "IFF",
195 NULL_IF_CONFIG_SMALL("IFF format"),
196 sizeof(IffDemuxContext),
197 iff_probe,
198 iff_read_header,
199 iff_read_packet,
200};
diff --git a/src/plugins/ffmpeg/libavformat/img2.c b/src/plugins/ffmpeg/libavformat/img2.c
deleted file mode 100644
index 2e570dd..0000000
--- a/src/plugins/ffmpeg/libavformat/img2.c
+++ /dev/null
@@ -1,427 +0,0 @@
1/*
2 * Image format
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard.
4 * Copyright (c) 2004 Michael Niedermayer
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#include "libavutil/avstring.h"
24#include "avformat.h"
25#include <strings.h>
26
27typedef struct {
28 int img_first;
29 int img_last;
30 int img_number;
31 int img_count;
32 int is_pipe;
33 char path[1024];
34} VideoData;
35
36typedef struct {
37 enum CodecID id;
38 const char *str;
39} IdStrMap;
40
41static const IdStrMap img_tags[] = {
42 { CODEC_ID_MJPEG , "jpeg"},
43 { CODEC_ID_MJPEG , "jpg"},
44 { CODEC_ID_LJPEG , "ljpg"},
45 { CODEC_ID_PNG , "png"},
46 { CODEC_ID_PNG , "mng"},
47 { CODEC_ID_PPM , "ppm"},
48 { CODEC_ID_PGM , "pgm"},
49 { CODEC_ID_PGMYUV , "pgmyuv"},
50 { CODEC_ID_PBM , "pbm"},
51 { CODEC_ID_PAM , "pam"},
52 { CODEC_ID_MPEG1VIDEO, "mpg1-img"},
53 { CODEC_ID_MPEG2VIDEO, "mpg2-img"},
54 { CODEC_ID_MPEG4 , "mpg4-img"},
55 { CODEC_ID_FFV1 , "ffv1-img"},
56 { CODEC_ID_RAWVIDEO , "y"},
57 { CODEC_ID_BMP , "bmp"},
58 { CODEC_ID_GIF , "gif"},
59 { CODEC_ID_TARGA , "tga"},
60 { CODEC_ID_TIFF , "tiff"},
61 { CODEC_ID_TIFF , "tif"},
62 { CODEC_ID_SGI , "sgi"},
63 { CODEC_ID_PTX , "ptx"},
64 { CODEC_ID_PCX , "pcx"},
65 { CODEC_ID_SUNRAST , "sun"},
66 { CODEC_ID_SUNRAST , "ras"},
67 { CODEC_ID_SUNRAST , "rs"},
68 { CODEC_ID_SUNRAST , "im1"},
69 { CODEC_ID_SUNRAST , "im8"},
70 { CODEC_ID_SUNRAST , "im24"},
71 { CODEC_ID_SUNRAST , "sunras"},
72 { CODEC_ID_NONE , NULL}
73};
74
75static int sizes[][2] = {
76 { 640, 480 },
77 { 720, 480 },
78 { 720, 576 },
79 { 352, 288 },
80 { 352, 240 },
81 { 160, 128 },
82 { 512, 384 },
83 { 640, 352 },
84 { 640, 240 },
85};
86
87static int infer_size(int *width_ptr, int *height_ptr, int size)
88{
89 int i;
90
91 for(i=0;i<sizeof(sizes)/sizeof(sizes[0]);i++) {
92 if ((sizes[i][0] * sizes[i][1]) == size) {
93 *width_ptr = sizes[i][0];
94 *height_ptr = sizes[i][1];
95 return 0;
96 }
97 }
98 return -1;
99}
100static enum CodecID av_str2id(const IdStrMap *tags, const char *str)
101{
102 str= strrchr(str, '.');
103 if(!str) return CODEC_ID_NONE;
104 str++;
105
106 while (tags->id) {
107 if (!strcasecmp(str, tags->str))
108 return tags->id;
109
110 tags++;
111 }
112 return CODEC_ID_NONE;
113}
114
115/* return -1 if no image found */
116static int find_image_range(int *pfirst_index, int *plast_index,
117 const char *path)
118{
119 char buf[1024];
120 int range, last_index, range1, first_index;
121
122 /* find the first image */
123 for(first_index = 0; first_index < 5; first_index++) {
124 if (av_get_frame_filename(buf, sizeof(buf), path, first_index) < 0){
125 *pfirst_index =
126 *plast_index = 1;
127 return 0;
128 }
129 if (url_exist(buf))
130 break;
131 }
132 if (first_index == 5)
133 goto fail;
134
135 /* find the last image */
136 last_index = first_index;
137 for(;;) {
138 range = 0;
139 for(;;) {
140 if (!range)
141 range1 = 1;
142 else
143 range1 = 2 * range;
144 if (av_get_frame_filename(buf, sizeof(buf), path,
145 last_index + range1) < 0)
146 goto fail;
147 if (!url_exist(buf))
148 break;
149 range = range1;
150 /* just in case... */
151 if (range >= (1 << 30))
152 goto fail;
153 }
154 /* we are sure than image last_index + range exists */
155 if (!range)
156 break;
157 last_index += range;
158 }
159 *pfirst_index = first_index;
160 *plast_index = last_index;
161 return 0;
162 fail:
163 return -1;
164}
165
166
167static int image_probe(AVProbeData *p)
168{
169 if (p->filename && av_str2id(img_tags, p->filename)) {
170 if (av_filename_number_test(p->filename))
171 return AVPROBE_SCORE_MAX;
172 else
173 return AVPROBE_SCORE_MAX/2;
174 }
175 return 0;
176}
177
178enum CodecID av_guess_image2_codec(const char *filename){
179 return av_str2id(img_tags, filename);
180}
181
182static int img_read_header(AVFormatContext *s1, AVFormatParameters *ap)
183{
184 VideoData *s = s1->priv_data;
185 int first_index, last_index;
186 AVStream *st;
187
188 s1->ctx_flags |= AVFMTCTX_NOHEADER;
189
190 st = av_new_stream(s1, 0);
191 if (!st) {
192 return AVERROR(ENOMEM);
193 }
194
195 av_strlcpy(s->path, s1->filename, sizeof(s->path));
196 s->img_number = 0;
197 s->img_count = 0;
198
199 /* find format */
200 if (s1->iformat->flags & AVFMT_NOFILE)
201 s->is_pipe = 0;
202 else{
203 s->is_pipe = 1;
204 st->need_parsing = AVSTREAM_PARSE_FULL;
205 }
206
207 if (!ap->time_base.num) {
208 av_set_pts_info(st, 60, 1, 25);
209 } else {
210 av_set_pts_info(st, 60, ap->time_base.num, ap->time_base.den);
211 }
212
213 if(ap->width && ap->height){
214 st->codec->width = ap->width;
215 st->codec->height= ap->height;
216 }
217
218 if (!s->is_pipe) {
219 if (find_image_range(&first_index, &last_index, s->path) < 0)
220 return AVERROR(EIO);
221 s->img_first = first_index;
222 s->img_last = last_index;
223 s->img_number = first_index;
224 /* compute duration */
225 st->start_time = 0;
226 st->duration = last_index - first_index + 1;
227 }
228
229 if(ap->video_codec_id){
230 st->codec->codec_type = CODEC_TYPE_VIDEO;
231 st->codec->codec_id = ap->video_codec_id;
232 }else if(ap->audio_codec_id){
233 st->codec->codec_type = CODEC_TYPE_AUDIO;
234 st->codec->codec_id = ap->audio_codec_id;
235 }else{
236 st->codec->codec_type = CODEC_TYPE_VIDEO;
237 st->codec->codec_id = av_str2id(img_tags, s->path);
238 }
239 if(st->codec->codec_type == CODEC_TYPE_VIDEO && ap->pix_fmt != PIX_FMT_NONE)
240 st->codec->pix_fmt = ap->pix_fmt;
241
242 return 0;
243}
244
245static int img_read_packet(AVFormatContext *s1, AVPacket *pkt)
246{
247 VideoData *s = s1->priv_data;
248 char filename[1024];
249 int i;
250 int size[3]={0}, ret[3]={0};
251 ByteIOContext *f[3];
252 AVCodecContext *codec= s1->streams[0]->codec;
253
254 if (!s->is_pipe) {
255 /* loop over input */
256 if (s1->loop_input && s->img_number > s->img_last) {
257 s->img_number = s->img_first;
258 }
259 if (av_get_frame_filename(filename, sizeof(filename),
260 s->path, s->img_number)<0 && s->img_number > 1)
261 return AVERROR(EIO);
262 for(i=0; i<3; i++){
263 if (url_fopen(&f[i], filename, URL_RDONLY) < 0)
264 return AVERROR(EIO);
265 size[i]= url_fsize(f[i]);
266
267 if(codec->codec_id != CODEC_ID_RAWVIDEO)
268 break;
269 filename[ strlen(filename) - 1 ]= 'U' + i;
270 }
271
272 if(codec->codec_id == CODEC_ID_RAWVIDEO && !codec->width)
273 infer_size(&codec->width, &codec->height, size[0]);
274 } else {
275 f[0] = s1->pb;
276 if (url_feof(f[0]))
277 return AVERROR(EIO);
278 size[0]= 4096;
279 }
280
281 av_new_packet(pkt, size[0] + size[1] + size[2]);
282 pkt->stream_index = 0;
283 pkt->flags |= PKT_FLAG_KEY;
284
285 pkt->size= 0;
286 for(i=0; i<3; i++){
287 if(size[i]){
288 ret[i]= get_buffer(f[i], pkt->data + pkt->size, size[i]);
289 if (!s->is_pipe)
290 url_fclose(f[i]);
291 if(ret[i]>0)
292 pkt->size += ret[i];
293 }
294 }
295
296 if (ret[0] <= 0 || ret[1]<0 || ret[2]<0) {
297 av_free_packet(pkt);
298 return AVERROR(EIO); /* signal EOF */
299 } else {
300 s->img_count++;
301 s->img_number++;
302 return 0;
303 }
304}
305
306#ifdef CONFIG_MUXERS
307/******************************************************/
308/* image output */
309
310static int img_write_header(AVFormatContext *s)
311{
312 VideoData *img = s->priv_data;
313
314 img->img_number = 1;
315 av_strlcpy(img->path, s->filename, sizeof(img->path));
316
317 /* find format */
318 if (s->oformat->flags & AVFMT_NOFILE)
319 img->is_pipe = 0;
320 else
321 img->is_pipe = 1;
322
323 return 0;
324}
325
326static int img_write_packet(AVFormatContext *s, AVPacket *pkt)
327{
328 VideoData *img = s->priv_data;
329 ByteIOContext *pb[3];
330 char filename[1024];
331 AVCodecContext *codec= s->streams[ pkt->stream_index ]->codec;
332 int i;
333
334 if (!img->is_pipe) {
335 if (av_get_frame_filename(filename, sizeof(filename),
336 img->path, img->img_number) < 0 && img->img_number>1)
337 return AVERROR(EIO);
338 for(i=0; i<3; i++){
339 if (url_fopen(&pb[i], filename, URL_WRONLY) < 0)
340 return AVERROR(EIO);
341
342 if(codec->codec_id != CODEC_ID_RAWVIDEO)
343 break;
344 filename[ strlen(filename) - 1 ]= 'U' + i;
345 }
346 } else {
347 pb[0] = s->pb;
348 }
349
350 if(codec->codec_id == CODEC_ID_RAWVIDEO){
351 int ysize = codec->width * codec->height;
352 put_buffer(pb[0], pkt->data , ysize);
353 put_buffer(pb[1], pkt->data + ysize, (pkt->size - ysize)/2);
354 put_buffer(pb[2], pkt->data + ysize +(pkt->size - ysize)/2, (pkt->size - ysize)/2);
355 put_flush_packet(pb[1]);
356 put_flush_packet(pb[2]);
357 url_fclose(pb[1]);
358 url_fclose(pb[2]);
359 }else{
360 put_buffer(pb[0], pkt->data, pkt->size);
361 }
362 put_flush_packet(pb[0]);
363 if (!img->is_pipe) {
364 url_fclose(pb[0]);
365 }
366
367 img->img_number++;
368 return 0;
369}
370
371#endif /* CONFIG_MUXERS */
372
373/* input */
374#ifdef CONFIG_IMAGE2_DEMUXER
375AVInputFormat image2_demuxer = {
376 "image2",
377 NULL_IF_CONFIG_SMALL("image2 sequence"),
378 sizeof(VideoData),
379 image_probe,
380 img_read_header,
381 img_read_packet,
382 NULL,
383 NULL,
384 NULL,
385 AVFMT_NOFILE,
386};
387#endif
388#ifdef CONFIG_IMAGE2PIPE_DEMUXER
389AVInputFormat image2pipe_demuxer = {
390 "image2pipe",
391 NULL_IF_CONFIG_SMALL("piped image2 sequence"),
392 sizeof(VideoData),
393 NULL, /* no probe */
394 img_read_header,
395 img_read_packet,
396};
397#endif
398
399/* output */
400#ifdef CONFIG_IMAGE2_MUXER
401AVOutputFormat image2_muxer = {
402 "image2",
403 NULL_IF_CONFIG_SMALL("image2 sequence"),
404 "",
405 "",
406 sizeof(VideoData),
407 CODEC_ID_NONE,
408 CODEC_ID_MJPEG,
409 img_write_header,
410 img_write_packet,
411 NULL,
412 AVFMT_NOFILE,
413};
414#endif
415#ifdef CONFIG_IMAGE2PIPE_MUXER
416AVOutputFormat image2pipe_muxer = {
417 "image2pipe",
418 NULL_IF_CONFIG_SMALL("piped image2 sequence"),
419 "",
420 "",
421 sizeof(VideoData),
422 CODEC_ID_NONE,
423 CODEC_ID_MJPEG,
424 img_write_header,
425 img_write_packet,
426};
427#endif
diff --git a/src/plugins/ffmpeg/libavformat/ipmovie.c b/src/plugins/ffmpeg/libavformat/ipmovie.c
deleted file mode 100644
index c2c5585..0000000
--- a/src/plugins/ffmpeg/libavformat/ipmovie.c
+++ /dev/null
@@ -1,617 +0,0 @@
1/*
2 * Interplay MVE File Demuxer
3 * Copyright (c) 2003 The ffmpeg Project
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/**
23 * @file ipmovie.c
24 * Interplay MVE file demuxer
25 * by Mike Melanson (melanson@pcisys.net)
26 * For more information regarding the Interplay MVE file format, visit:
27 * http://www.pcisys.net/~melanson/codecs/
28 * The aforementioned site also contains a command line utility for parsing
29 * IP MVE files so that you can get a good idea of the typical structure of
30 * such files. This demuxer is not the best example to use if you are trying
31 * to write your own as it uses a rather roundabout approach for splitting
32 * up and sending out the chunks.
33 */
34
35#include "avformat.h"
36
37/* debugging support: #define DEBUG_IPMOVIE as non-zero to see extremely
38 * verbose information about the demux process */
39#define DEBUG_IPMOVIE 0
40
41#if DEBUG_IPMOVIE
42#define debug_ipmovie printf
43#else
44static inline void debug_ipmovie(const char *format, ...) { }
45#endif
46
47#define IPMOVIE_SIGNATURE "Interplay MVE File\x1A\0"
48#define IPMOVIE_SIGNATURE_SIZE 20
49#define CHUNK_PREAMBLE_SIZE 4
50#define OPCODE_PREAMBLE_SIZE 4
51
52#define CHUNK_INIT_AUDIO 0x0000
53#define CHUNK_AUDIO_ONLY 0x0001
54#define CHUNK_INIT_VIDEO 0x0002
55#define CHUNK_VIDEO 0x0003
56#define CHUNK_SHUTDOWN 0x0004
57#define CHUNK_END 0x0005
58/* these last types are used internally */
59#define CHUNK_DONE 0xFFFC
60#define CHUNK_NOMEM 0xFFFD
61#define CHUNK_EOF 0xFFFE
62#define CHUNK_BAD 0xFFFF
63
64#define OPCODE_END_OF_STREAM 0x00
65#define OPCODE_END_OF_CHUNK 0x01
66#define OPCODE_CREATE_TIMER 0x02
67#define OPCODE_INIT_AUDIO_BUFFERS 0x03
68#define OPCODE_START_STOP_AUDIO 0x04
69#define OPCODE_INIT_VIDEO_BUFFERS 0x05
70#define OPCODE_UNKNOWN_06 0x06
71#define OPCODE_SEND_BUFFER 0x07
72#define OPCODE_AUDIO_FRAME 0x08
73#define OPCODE_SILENCE_FRAME 0x09
74#define OPCODE_INIT_VIDEO_MODE 0x0A
75#define OPCODE_CREATE_GRADIENT 0x0B
76#define OPCODE_SET_PALETTE 0x0C
77#define OPCODE_SET_PALETTE_COMPRESSED 0x0D
78#define OPCODE_UNKNOWN_0E 0x0E
79#define OPCODE_SET_DECODING_MAP 0x0F
80#define OPCODE_UNKNOWN_10 0x10
81#define OPCODE_VIDEO_DATA 0x11
82#define OPCODE_UNKNOWN_12 0x12
83#define OPCODE_UNKNOWN_13 0x13
84#define OPCODE_UNKNOWN_14 0x14
85#define OPCODE_UNKNOWN_15 0x15
86
87#define PALETTE_COUNT 256
88
89typedef struct IPMVEContext {
90
91 unsigned char *buf;
92 int buf_size;
93
94 float fps;
95 int frame_pts_inc;
96
97 unsigned int video_width;
98 unsigned int video_height;
99 int64_t video_pts;
100
101 unsigned int audio_bits;
102 unsigned int audio_channels;
103 unsigned int audio_sample_rate;
104 unsigned int audio_type;
105 unsigned int audio_frame_count;
106
107 int video_stream_index;
108 int audio_stream_index;
109
110 offset_t audio_chunk_offset;
111 int audio_chunk_size;
112 offset_t video_chunk_offset;
113 int video_chunk_size;
114 offset_t decode_map_chunk_offset;
115 int decode_map_chunk_size;
116
117 offset_t next_chunk_offset;
118
119 AVPaletteControl palette_control;
120
121} IPMVEContext;
122
123static int load_ipmovie_packet(IPMVEContext *s, ByteIOContext *pb,
124 AVPacket *pkt) {
125
126 int chunk_type;
127 int64_t audio_pts = 0;
128
129 if (s->audio_chunk_offset) {
130
131 /* adjust for PCM audio by skipping chunk header */
132 if (s->audio_type != CODEC_ID_INTERPLAY_DPCM) {
133 s->audio_chunk_offset += 6;
134 s->audio_chunk_size -= 6;
135 }
136
137 url_fseek(pb, s->audio_chunk_offset, SEEK_SET);
138 s->audio_chunk_offset = 0;
139
140 /* figure out the audio pts */
141 audio_pts = 90000;
142 audio_pts *= s->audio_frame_count;
143 audio_pts /= s->audio_sample_rate;
144
145 if (s->audio_chunk_size != av_get_packet(pb, pkt, s->audio_chunk_size))
146 return CHUNK_EOF;
147
148 pkt->stream_index = s->audio_stream_index;
149 pkt->pts = audio_pts;
150
151 /* audio frame maintenance */
152 if (s->audio_type != CODEC_ID_INTERPLAY_DPCM)
153 s->audio_frame_count +=
154 (s->audio_chunk_size / s->audio_channels / (s->audio_bits / 8));
155 else
156 s->audio_frame_count +=
157 (s->audio_chunk_size - 6) / s->audio_channels;
158
159 debug_ipmovie("sending audio frame with pts %"PRId64" (%d audio frames)\n",
160 audio_pts, s->audio_frame_count);
161
162 chunk_type = CHUNK_VIDEO;
163
164 } else if (s->decode_map_chunk_offset) {
165
166 /* send both the decode map and the video data together */
167
168 if (av_new_packet(pkt, s->decode_map_chunk_size + s->video_chunk_size))
169 return CHUNK_NOMEM;
170
171 pkt->pos= s->decode_map_chunk_offset;
172 url_fseek(pb, s->decode_map_chunk_offset, SEEK_SET);
173 s->decode_map_chunk_offset = 0;
174
175 if (get_buffer(pb, pkt->data, s->decode_map_chunk_size) !=
176 s->decode_map_chunk_size) {
177 av_free_packet(pkt);
178 return CHUNK_EOF;
179 }
180
181 url_fseek(pb, s->video_chunk_offset, SEEK_SET);
182 s->video_chunk_offset = 0;
183
184 if (get_buffer(pb, pkt->data + s->decode_map_chunk_size,
185 s->video_chunk_size) != s->video_chunk_size) {
186 av_free_packet(pkt);
187 return CHUNK_EOF;
188 }
189
190 pkt->stream_index = s->video_stream_index;
191 pkt->pts = s->video_pts;
192
193 debug_ipmovie("sending video frame with pts %"PRId64"\n",
194 pkt->pts);
195
196 s->video_pts += s->frame_pts_inc;
197
198 chunk_type = CHUNK_VIDEO;
199
200 } else {
201
202 url_fseek(pb, s->next_chunk_offset, SEEK_SET);
203 chunk_type = CHUNK_DONE;
204
205 }
206
207 return chunk_type;
208}
209
210/* This function loads and processes a single chunk in an IP movie file.
211 * It returns the type of chunk that was processed. */
212static int process_ipmovie_chunk(IPMVEContext *s, ByteIOContext *pb,
213 AVPacket *pkt)
214{
215 unsigned char chunk_preamble[CHUNK_PREAMBLE_SIZE];
216 int chunk_type;
217 int chunk_size;
218 unsigned char opcode_preamble[OPCODE_PREAMBLE_SIZE];
219 unsigned char opcode_type;
220 unsigned char opcode_version;
221 int opcode_size;
222 unsigned char scratch[1024];
223 int i, j;
224 int first_color, last_color;
225 int audio_flags;
226 unsigned char r, g, b;
227
228 /* see if there are any pending packets */
229 chunk_type = load_ipmovie_packet(s, pb, pkt);
230 if (chunk_type != CHUNK_DONE)
231 return chunk_type;
232
233 /* read the next chunk, wherever the file happens to be pointing */
234 if (url_feof(pb))
235 return CHUNK_EOF;
236 if (get_buffer(pb, chunk_preamble, CHUNK_PREAMBLE_SIZE) !=
237 CHUNK_PREAMBLE_SIZE)
238 return CHUNK_BAD;
239 chunk_size = AV_RL16(&chunk_preamble[0]);
240 chunk_type = AV_RL16(&chunk_preamble[2]);
241
242 debug_ipmovie("chunk type 0x%04X, 0x%04X bytes: ", chunk_type, chunk_size);
243
244 switch (chunk_type) {
245
246 case CHUNK_INIT_AUDIO:
247 debug_ipmovie("initialize audio\n");
248 break;
249
250 case CHUNK_AUDIO_ONLY:
251 debug_ipmovie("audio only\n");
252 break;
253
254 case CHUNK_INIT_VIDEO:
255 debug_ipmovie("initialize video\n");
256 break;
257
258 case CHUNK_VIDEO:
259 debug_ipmovie("video (and audio)\n");
260 break;
261
262 case CHUNK_SHUTDOWN:
263 debug_ipmovie("shutdown\n");
264 break;
265
266 case CHUNK_END:
267 debug_ipmovie("end\n");
268 break;
269
270 default:
271 debug_ipmovie("invalid chunk\n");
272 chunk_type = CHUNK_BAD;
273 break;
274
275 }
276
277 while ((chunk_size > 0) && (chunk_type != CHUNK_BAD)) {
278
279 /* read the next chunk, wherever the file happens to be pointing */
280 if (url_feof(pb)) {
281 chunk_type = CHUNK_EOF;
282 break;
283 }
284 if (get_buffer(pb, opcode_preamble, CHUNK_PREAMBLE_SIZE) !=
285 CHUNK_PREAMBLE_SIZE) {
286 chunk_type = CHUNK_BAD;
287 break;
288 }
289
290 opcode_size = AV_RL16(&opcode_preamble[0]);
291 opcode_type = opcode_preamble[2];
292 opcode_version = opcode_preamble[3];
293
294 chunk_size -= OPCODE_PREAMBLE_SIZE;
295 chunk_size -= opcode_size;
296 if (chunk_size < 0) {
297 debug_ipmovie("chunk_size countdown just went negative\n");
298 chunk_type = CHUNK_BAD;
299 break;
300 }
301
302 debug_ipmovie(" opcode type %02X, version %d, 0x%04X bytes: ",
303 opcode_type, opcode_version, opcode_size);
304 switch (opcode_type) {
305
306 case OPCODE_END_OF_STREAM:
307 debug_ipmovie("end of stream\n");
308 url_fseek(pb, opcode_size, SEEK_CUR);
309 break;
310
311 case OPCODE_END_OF_CHUNK:
312 debug_ipmovie("end of chunk\n");
313 url_fseek(pb, opcode_size, SEEK_CUR);
314 break;
315
316 case OPCODE_CREATE_TIMER:
317 debug_ipmovie("create timer\n");
318 if ((opcode_version > 0) || (opcode_size > 6)) {
319 debug_ipmovie("bad create_timer opcode\n");
320 chunk_type = CHUNK_BAD;
321 break;
322 }
323 if (get_buffer(pb, scratch, opcode_size) !=
324 opcode_size) {
325 chunk_type = CHUNK_BAD;
326 break;
327 }
328 s->fps = 1000000.0 / (AV_RL32(&scratch[0]) * AV_RL16(&scratch[4]));
329 s->frame_pts_inc = 90000 / s->fps;
330 debug_ipmovie(" %.2f frames/second (timer div = %d, subdiv = %d)\n",
331 s->fps, AV_RL32(&scratch[0]), AV_RL16(&scratch[4]));
332 break;
333
334 case OPCODE_INIT_AUDIO_BUFFERS:
335 debug_ipmovie("initialize audio buffers\n");
336 if ((opcode_version > 1) || (opcode_size > 10)) {
337 debug_ipmovie("bad init_audio_buffers opcode\n");
338 chunk_type = CHUNK_BAD;
339 break;
340 }
341 if (get_buffer(pb, scratch, opcode_size) !=
342 opcode_size) {
343 chunk_type = CHUNK_BAD;
344 break;
345 }
346 s->audio_sample_rate = AV_RL16(&scratch[4]);
347 audio_flags = AV_RL16(&scratch[2]);
348 /* bit 0 of the flags: 0 = mono, 1 = stereo */
349 s->audio_channels = (audio_flags & 1) + 1;
350 /* bit 1 of the flags: 0 = 8 bit, 1 = 16 bit */
351 s->audio_bits = (((audio_flags >> 1) & 1) + 1) * 8;
352 /* bit 2 indicates compressed audio in version 1 opcode */
353 if ((opcode_version == 1) && (audio_flags & 0x4))
354 s->audio_type = CODEC_ID_INTERPLAY_DPCM;
355 else if (s->audio_bits == 16)
356 s->audio_type = CODEC_ID_PCM_S16LE;
357 else
358 s->audio_type = CODEC_ID_PCM_U8;
359 debug_ipmovie("audio: %d bits, %d Hz, %s, %s format\n",
360 s->audio_bits,
361 s->audio_sample_rate,
362 (s->audio_channels == 2) ? "stereo" : "mono",
363 (s->audio_type == CODEC_ID_INTERPLAY_DPCM) ?
364 "Interplay audio" : "PCM");
365 break;
366
367 case OPCODE_START_STOP_AUDIO:
368 debug_ipmovie("start/stop audio\n");
369 url_fseek(pb, opcode_size, SEEK_CUR);
370 break;
371
372 case OPCODE_INIT_VIDEO_BUFFERS:
373 debug_ipmovie("initialize video buffers\n");
374 if ((opcode_version > 2) || (opcode_size > 8)) {
375 debug_ipmovie("bad init_video_buffers opcode\n");
376 chunk_type = CHUNK_BAD;
377 break;
378 }
379 if (get_buffer(pb, scratch, opcode_size) !=
380 opcode_size) {
381 chunk_type = CHUNK_BAD;
382 break;
383 }
384 s->video_width = AV_RL16(&scratch[0]) * 8;
385 s->video_height = AV_RL16(&scratch[2]) * 8;
386 debug_ipmovie("video resolution: %d x %d\n",
387 s->video_width, s->video_height);
388 break;
389
390 case OPCODE_UNKNOWN_06:
391 case OPCODE_UNKNOWN_0E:
392 case OPCODE_UNKNOWN_10:
393 case OPCODE_UNKNOWN_12:
394 case OPCODE_UNKNOWN_13:
395 case OPCODE_UNKNOWN_14:
396 case OPCODE_UNKNOWN_15:
397 debug_ipmovie("unknown (but documented) opcode %02X\n", opcode_type);
398 url_fseek(pb, opcode_size, SEEK_CUR);
399 break;
400
401 case OPCODE_SEND_BUFFER:
402 debug_ipmovie("send buffer\n");
403 url_fseek(pb, opcode_size, SEEK_CUR);
404 break;
405
406 case OPCODE_AUDIO_FRAME:
407 debug_ipmovie("audio frame\n");
408
409 /* log position and move on for now */
410 s->audio_chunk_offset = url_ftell(pb);
411 s->audio_chunk_size = opcode_size;
412 url_fseek(pb, opcode_size, SEEK_CUR);
413 break;
414
415 case OPCODE_SILENCE_FRAME:
416 debug_ipmovie("silence frame\n");
417 url_fseek(pb, opcode_size, SEEK_CUR);
418 break;
419
420 case OPCODE_INIT_VIDEO_MODE:
421 debug_ipmovie("initialize video mode\n");
422 url_fseek(pb, opcode_size, SEEK_CUR);
423 break;
424
425 case OPCODE_CREATE_GRADIENT:
426 debug_ipmovie("create gradient\n");
427 url_fseek(pb, opcode_size, SEEK_CUR);
428 break;
429
430 case OPCODE_SET_PALETTE:
431 debug_ipmovie("set palette\n");
432 /* check for the logical maximum palette size
433 * (3 * 256 + 4 bytes) */
434 if (opcode_size > 0x304) {
435 debug_ipmovie("demux_ipmovie: set_palette opcode too large\n");
436 chunk_type = CHUNK_BAD;
437 break;
438 }
439 if (get_buffer(pb, scratch, opcode_size) != opcode_size) {
440 chunk_type = CHUNK_BAD;
441 break;
442 }
443
444 /* load the palette into internal data structure */
445 first_color = AV_RL16(&scratch[0]);
446 last_color = first_color + AV_RL16(&scratch[2]) - 1;
447 /* sanity check (since they are 16 bit values) */
448 if ((first_color > 0xFF) || (last_color > 0xFF)) {
449 debug_ipmovie("demux_ipmovie: set_palette indexes out of range (%d -> %d)\n",
450 first_color, last_color);
451 chunk_type = CHUNK_BAD;
452 break;
453 }
454 j = 4; /* offset of first palette data */
455 for (i = first_color; i <= last_color; i++) {
456 /* the palette is stored as a 6-bit VGA palette, thus each
457 * component is shifted up to a 8-bit range */
458 r = scratch[j++] * 4;
459 g = scratch[j++] * 4;
460 b = scratch[j++] * 4;
461 s->palette_control.palette[i] = (r << 16) | (g << 8) | (b);
462 }
463 /* indicate a palette change */
464 s->palette_control.palette_changed = 1;
465 break;
466
467 case OPCODE_SET_PALETTE_COMPRESSED:
468 debug_ipmovie("set palette compressed\n");
469 url_fseek(pb, opcode_size, SEEK_CUR);
470 break;
471
472 case OPCODE_SET_DECODING_MAP:
473 debug_ipmovie("set decoding map\n");
474
475 /* log position and move on for now */
476 s->decode_map_chunk_offset = url_ftell(pb);
477 s->decode_map_chunk_size = opcode_size;
478 url_fseek(pb, opcode_size, SEEK_CUR);
479 break;
480
481 case OPCODE_VIDEO_DATA:
482 debug_ipmovie("set video data\n");
483
484 /* log position and move on for now */
485 s->video_chunk_offset = url_ftell(pb);
486 s->video_chunk_size = opcode_size;
487 url_fseek(pb, opcode_size, SEEK_CUR);
488 break;
489
490 default:
491 debug_ipmovie("*** unknown opcode type\n");
492 chunk_type = CHUNK_BAD;
493 break;
494
495 }
496 }
497
498 /* make a note of where the stream is sitting */
499 s->next_chunk_offset = url_ftell(pb);
500
501 /* dispatch the first of any pending packets */
502 if ((chunk_type == CHUNK_VIDEO) || (chunk_type == CHUNK_AUDIO_ONLY))
503 chunk_type = load_ipmovie_packet(s, pb, pkt);
504
505 return chunk_type;
506}
507
508static int ipmovie_probe(AVProbeData *p)
509{
510 if (strncmp(p->buf, IPMOVIE_SIGNATURE, IPMOVIE_SIGNATURE_SIZE) != 0)
511 return 0;
512
513 return AVPROBE_SCORE_MAX;
514}
515
516static int ipmovie_read_header(AVFormatContext *s,
517 AVFormatParameters *ap)
518{
519 IPMVEContext *ipmovie = s->priv_data;
520 ByteIOContext *pb = s->pb;
521 AVPacket pkt;
522 AVStream *st;
523 unsigned char chunk_preamble[CHUNK_PREAMBLE_SIZE];
524 int chunk_type;
525
526 /* initialize private context members */
527 ipmovie->video_pts = ipmovie->audio_frame_count = 0;
528 ipmovie->audio_chunk_offset = ipmovie->video_chunk_offset =
529 ipmovie->decode_map_chunk_offset = 0;
530
531 /* on the first read, this will position the stream at the first chunk */
532 ipmovie->next_chunk_offset = IPMOVIE_SIGNATURE_SIZE + 6;
533
534 /* process the first chunk which should be CHUNK_INIT_VIDEO */
535 if (process_ipmovie_chunk(ipmovie, pb, &pkt) != CHUNK_INIT_VIDEO)
536 return AVERROR_INVALIDDATA;
537
538 /* peek ahead to the next chunk-- if it is an init audio chunk, process
539 * it; if it is the first video chunk, this is a silent file */
540 if (get_buffer(pb, chunk_preamble, CHUNK_PREAMBLE_SIZE) !=
541 CHUNK_PREAMBLE_SIZE)
542 return AVERROR(EIO);
543 chunk_type = AV_RL16(&chunk_preamble[2]);
544 url_fseek(pb, -CHUNK_PREAMBLE_SIZE, SEEK_CUR);
545
546 if (chunk_type == CHUNK_VIDEO)
547 ipmovie->audio_type = 0; /* no audio */
548 else if (process_ipmovie_chunk(ipmovie, pb, &pkt) != CHUNK_INIT_AUDIO)
549 return AVERROR_INVALIDDATA;
550
551 /* initialize the stream decoders */
552 st = av_new_stream(s, 0);
553 if (!st)
554 return AVERROR(ENOMEM);
555 av_set_pts_info(st, 33, 1, 90000);
556 ipmovie->video_stream_index = st->index;
557 st->codec->codec_type = CODEC_TYPE_VIDEO;
558 st->codec->codec_id = CODEC_ID_INTERPLAY_VIDEO;
559 st->codec->codec_tag = 0; /* no fourcc */
560 st->codec->width = ipmovie->video_width;
561 st->codec->height = ipmovie->video_height;
562
563 /* palette considerations */
564 st->codec->palctrl = &ipmovie->palette_control;
565
566 if (ipmovie->audio_type) {
567 st = av_new_stream(s, 0);
568 if (!st)
569 return AVERROR(ENOMEM);
570 av_set_pts_info(st, 33, 1, 90000);
571 ipmovie->audio_stream_index = st->index;
572 st->codec->codec_type = CODEC_TYPE_AUDIO;
573 st->codec->codec_id = ipmovie->audio_type;
574 st->codec->codec_tag = 0; /* no tag */
575 st->codec->channels = ipmovie->audio_channels;
576 st->codec->sample_rate = ipmovie->audio_sample_rate;
577 st->codec->bits_per_sample = ipmovie->audio_bits;
578 st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *
579 st->codec->bits_per_sample;
580 if (st->codec->codec_id == CODEC_ID_INTERPLAY_DPCM)
581 st->codec->bit_rate /= 2;
582 st->codec->block_align = st->codec->channels * st->codec->bits_per_sample;
583 }
584
585 return 0;
586}
587
588static int ipmovie_read_packet(AVFormatContext *s,
589 AVPacket *pkt)
590{
591 IPMVEContext *ipmovie = s->priv_data;
592 ByteIOContext *pb = s->pb;
593 int ret;
594
595 ret = process_ipmovie_chunk(ipmovie, pb, pkt);
596 if (ret == CHUNK_BAD)
597 ret = AVERROR_INVALIDDATA;
598 else if (ret == CHUNK_EOF)
599 ret = AVERROR(EIO);
600 else if (ret == CHUNK_NOMEM)
601 ret = AVERROR(ENOMEM);
602 else if (ret == CHUNK_VIDEO)
603 ret = 0;
604 else
605 ret = -1;
606
607 return ret;
608}
609
610AVInputFormat ipmovie_demuxer = {
611 "ipmovie",
612 NULL_IF_CONFIG_SMALL("Interplay MVE format"),
613 sizeof(IPMVEContext),
614 ipmovie_probe,
615 ipmovie_read_header,
616 ipmovie_read_packet,
617};
diff --git a/src/plugins/ffmpeg/libavformat/isom.c b/src/plugins/ffmpeg/libavformat/isom.c
deleted file mode 100644
index 4a5e3f9..0000000
--- a/src/plugins/ffmpeg/libavformat/isom.c
+++ /dev/null
@@ -1,258 +0,0 @@
1/*
2 * ISO Media common code
3 * Copyright (c) 2001 Fabrice Bellard.
4 * Copyright (c) 2002 Francois Revol <revol@free.fr>
5 * Copyright (c) 2006 Baptiste Coudurier <baptiste.coudurier@free.fr>
6 *
7 * This file is part of FFmpeg.
8 *
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23
24#include "avformat.h"
25#include "riff.h"
26#include "isom.h"
27
28/* http://www.mp4ra.org */
29/* ordered by muxing preference */
30const AVCodecTag ff_mp4_obj_type[] = {
31 { CODEC_ID_MPEG4 , 32 },
32 { CODEC_ID_H264 , 33 },
33 { CODEC_ID_AAC , 64 },
34 { CODEC_ID_MPEG2VIDEO, 97 }, /* MPEG2 Main */
35 { CODEC_ID_MPEG2VIDEO, 96 }, /* MPEG2 Simple */
36 { CODEC_ID_MPEG2VIDEO, 98 }, /* MPEG2 SNR */
37 { CODEC_ID_MPEG2VIDEO, 99 }, /* MPEG2 Spatial */
38 { CODEC_ID_MPEG2VIDEO, 100 }, /* MPEG2 High */
39 { CODEC_ID_MPEG2VIDEO, 101 }, /* MPEG2 422 */
40 { CODEC_ID_AAC , 102 }, /* MPEG2 AAC Main */
41 { CODEC_ID_AAC , 103 }, /* MPEG2 AAC Low */
42 { CODEC_ID_AAC , 104 }, /* MPEG2 AAC SSR */
43 { CODEC_ID_MP3 , 107 }, /* 11172-3 */
44 { CODEC_ID_MP3 , 105 }, /* 13818-3 */
45 { CODEC_ID_MPEG1VIDEO, 106 }, /* 11172-2 */
46 { CODEC_ID_MJPEG , 108 }, /* 10918-1 */
47 { CODEC_ID_PNG , 109 },
48 { CODEC_ID_JPEG2000 , 110 }, /* 15444-1 */
49 { CODEC_ID_VC1 , 163 },
50 { CODEC_ID_VORBIS , 221 }, /* non standard, gpac uses it */
51 { CODEC_ID_DVD_SUBTITLE, 224 }, /* non standard, see unsupported-embedded-subs-2.mp4 */
52 { CODEC_ID_QCELP , 225 },
53 { 0, 0 },
54};
55
56const AVCodecTag codec_movvideo_tags[] = {
57/* { CODEC_ID_, MKTAG('I', 'V', '5', '0') }, *//* Indeo 5.0 */
58
59 { CODEC_ID_RAWVIDEO, MKTAG('r', 'a', 'w', ' ') }, /* Uncompressed RGB */
60/* { CODEC_ID_RAWVIDEO, MKTAG('Y', 'u', 'v', '2') }, *//* Uncompressed YUV422 */
61 { CODEC_ID_RAWVIDEO, MKTAG('A', 'V', 'U', 'I') }, /* YUV with alpha-channel (AVID Uncompressed) */
62 { CODEC_ID_RAWVIDEO, MKTAG('2', 'v', 'u', 'y') }, /* UNCOMPRESSED 8BIT 4:2:2 */
63
64 { CODEC_ID_MJPEG, MKTAG('j', 'p', 'e', 'g') }, /* PhotoJPEG */
65 { CODEC_ID_MJPEG, MKTAG('m', 'j', 'p', 'a') }, /* Motion-JPEG (format A) */
66 { CODEC_ID_MJPEG, MKTAG('A', 'V', 'D', 'J') }, /* MJPEG with alpha-channel (AVID JFIF meridien compressed) */
67/* { CODEC_ID_MJPEG, MKTAG('A', 'V', 'R', 'n') }, *//* MJPEG with alpha-channel (AVID ABVB/Truevision NuVista) */
68 { CODEC_ID_MJPEG, MKTAG('d', 'm', 'b', '1') }, /* Motion JPEG OpenDML */
69 { CODEC_ID_MJPEGB, MKTAG('m', 'j', 'p', 'b') }, /* Motion-JPEG (format B) */
70
71 { CODEC_ID_SVQ1, MKTAG('S', 'V', 'Q', '1') }, /* Sorenson Video v1 */
72 { CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', '1') }, /* Sorenson Video v1 */
73 { CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', 'i') }, /* Sorenson Video v1 (from QT specs)*/
74 { CODEC_ID_SVQ3, MKTAG('S', 'V', 'Q', '3') }, /* Sorenson Video v3 */
75
76 { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
77 { CODEC_ID_MPEG4, MKTAG('D', 'I', 'V', 'X') }, /* OpenDiVX *//* sample files at http://heroinewarrior.com/xmovie.php3 use this tag */
78 { CODEC_ID_MPEG4, MKTAG('X', 'V', 'I', 'D') },
79 { CODEC_ID_MPEG4, MKTAG('3', 'I', 'V', '2') }, /* experimental: 3IVX files before ivx D4 4.5.1 */
80
81 { CODEC_ID_H263, MKTAG('h', '2', '6', '3') }, /* H263 */
82 { CODEC_ID_H263, MKTAG('s', '2', '6', '3') }, /* H263 ?? works */
83
84 { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', 'p') }, /* DV PAL */
85 { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', ' ') }, /* DV NTSC */
86 { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'p', 'p') }, /* DVCPRO PAL produced by FCP */
87 { CODEC_ID_DVVIDEO, MKTAG('d', 'v', '5', 'p') }, /* DVCPRO50 PAL produced by FCP */
88 { CODEC_ID_DVVIDEO, MKTAG('d', 'v', '5', 'n') }, /* DVCPRO50 NTSC produced by FCP */
89 { CODEC_ID_DVVIDEO, MKTAG('A', 'V', 'd', 'v') }, /* AVID DV */
90 //{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'h', '5') }, /* DVCPRO HD 50i produced by FCP */
91 //{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'h', '6') }, /* DVCPRO HD 60i produced by FCP */
92
93 { CODEC_ID_VP3, MKTAG('V', 'P', '3', '1') }, /* On2 VP3 */
94 { CODEC_ID_RPZA, MKTAG('r', 'p', 'z', 'a') }, /* Apple Video (RPZA) */
95 { CODEC_ID_CINEPAK, MKTAG('c', 'v', 'i', 'd') }, /* Cinepak */
96 { CODEC_ID_8BPS, MKTAG('8', 'B', 'P', 'S') }, /* Planar RGB (8BPS) */
97 { CODEC_ID_SMC, MKTAG('s', 'm', 'c', ' ') }, /* Apple Graphics (SMC) */
98 { CODEC_ID_QTRLE, MKTAG('r', 'l', 'e', ' ') }, /* Apple Animation (RLE) */
99 { CODEC_ID_MSRLE, MKTAG('W', 'R', 'L', 'E') },
100 { CODEC_ID_QDRAW, MKTAG('q', 'd', 'r', 'w') }, /* QuickDraw */
101
102 { CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') }, /* AVC-1/H.264 */
103
104 { CODEC_ID_MPEG1VIDEO, MKTAG('m', 'p', 'e', 'g') }, /* MPEG */
105 { CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '1') }, /* HDV 720p30 */
106 { CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '2') }, /* MPEG2 produced by Sony HD camera */
107 { CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '3') }, /* HDV produced by FCP */
108 { CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '5') }, /* HDV 720p25 */
109 { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '5', 'n') }, /* MPEG2 IMX NTSC 525/60 50mb/s produced by FCP */
110 { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '5', 'p') }, /* MPEG2 IMX PAL 625/50 50mb/s produced by FCP */
111 { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '4', 'n') }, /* MPEG2 IMX NTSC 525/60 40mb/s produced by FCP */
112 { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '4', 'p') }, /* MPEG2 IMX PAL 625/50 40mb/s produced by FCP */
113 { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '3', 'n') }, /* MPEG2 IMX NTSC 525/60 30mb/s produced by FCP */
114 { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '3', 'p') }, /* MPEG2 IMX PAL 625/50 30mb/s produced by FCP */
115 { CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', '2') }, /* XDCAM HD 1080i60 */
116 { CODEC_ID_MPEG2VIDEO, MKTAG('A', 'V', 'm', 'p') }, /* AVID IMX PAL */
117
118 //{ CODEC_ID_JPEG2000, MKTAG('m', 'j', 'p', '2') }, /* JPEG 2000 produced by FCP */
119
120 { CODEC_ID_TARGA, MKTAG('t', 'g', 'a', ' ') }, /* Truevision Targa */
121 { CODEC_ID_TIFF, MKTAG('t', 'i', 'f', 'f') }, /* TIFF embedded in MOV */
122 { CODEC_ID_GIF, MKTAG('g', 'i', 'f', ' ') }, /* embedded gif files as frames (usually one "click to play movie" frame) */
123 { CODEC_ID_PNG, MKTAG('p', 'n', 'g', ' ') },
124
125 { CODEC_ID_VC1, MKTAG('v', 'c', '-', '1') }, /* SMPTE RP 2025 */
126 { CODEC_ID_CAVS, MKTAG('a', 'v', 's', '2') },
127
128 { CODEC_ID_DNXHD, MKTAG('A', 'V', 'd', 'n') }, /* AVID DNxHD */
129 { CODEC_ID_SGI, MKTAG('s', 'g', 'i', ' ') }, /* SGI */
130
131 { CODEC_ID_NONE, 0 },
132};
133
134const AVCodecTag codec_movaudio_tags[] = {
135 { CODEC_ID_PCM_S32BE, MKTAG('i', 'n', '3', '2') },
136 { CODEC_ID_PCM_S32LE, MKTAG('i', 'n', '3', '2') },
137 { CODEC_ID_PCM_S24BE, MKTAG('i', 'n', '2', '4') },
138 { CODEC_ID_PCM_S24LE, MKTAG('i', 'n', '2', '4') },
139 { CODEC_ID_PCM_S16BE, MKTAG('t', 'w', 'o', 's') }, /* 16 bits */
140 { CODEC_ID_PCM_S16LE, MKTAG('s', 'o', 'w', 't') }, /* */
141 { CODEC_ID_PCM_S16LE, MKTAG('l', 'p', 'c', 'm') },
142 { CODEC_ID_PCM_S8, MKTAG('s', 'o', 'w', 't') },
143 { CODEC_ID_PCM_U8, MKTAG('r', 'a', 'w', ' ') }, /* 8 bits unsigned */
144 { CODEC_ID_PCM_U8, MKTAG('N', 'O', 'N', 'E') }, /* uncompressed */
145 { CODEC_ID_PCM_MULAW, MKTAG('u', 'l', 'a', 'w') }, /* */
146 { CODEC_ID_PCM_ALAW, MKTAG('a', 'l', 'a', 'w') }, /* */
147
148 { CODEC_ID_ADPCM_IMA_QT, MKTAG('i', 'm', 'a', '4') }, /* IMA-4 ADPCM */
149
150 { CODEC_ID_MACE3, MKTAG('M', 'A', 'C', '3') }, /* Macintosh Audio Compression and Expansion 3:1 */
151 { CODEC_ID_MACE6, MKTAG('M', 'A', 'C', '6') }, /* Macintosh Audio Compression and Expansion 6:1 */
152
153 { CODEC_ID_MP3, MKTAG('.', 'm', 'p', '3') }, /* MPEG layer 3 */ /* sample files at http://www.3ivx.com/showcase.html use this tag */
154 { CODEC_ID_MP3, 0x6D730055 }, /* MPEG layer 3 */
155
156/* { CODEC_ID_OGG_VORBIS, MKTAG('O', 'g', 'g', 'S') }, *//* sample files at http://heroinewarrior.com/xmovie.php3 use this tag */
157
158 { CODEC_ID_AAC, MKTAG('m', 'p', '4', 'a') }, /* MPEG-4 AAC */
159
160 { CODEC_ID_AMR_NB, MKTAG('s', 'a', 'm', 'r') }, /* AMR-NB 3gp */
161 { CODEC_ID_AMR_WB, MKTAG('s', 'a', 'w', 'b') }, /* AMR-WB 3gp */
162
163 { CODEC_ID_GSM, MKTAG('a', 'g', 's', 'm') },
164 { CODEC_ID_ALAC, MKTAG('a', 'l', 'a', 'c') }, /* Apple Lossless */
165
166 { CODEC_ID_QCELP, MKTAG('Q','c','l','p') },
167 { CODEC_ID_QCELP, MKTAG('s','q','c','p') }, /* ISO Media fourcc */
168
169 { CODEC_ID_QDM2, MKTAG('Q', 'D', 'M', '2') }, /* QDM2 */
170
171 { CODEC_ID_DVAUDIO, MKTAG('v', 'd', 'v', 'a') },
172 { CODEC_ID_DVAUDIO, MKTAG('d', 'v', 'c', 'a') },
173
174 { CODEC_ID_WMAV2, MKTAG('W', 'M', 'A', '2') },
175
176 { CODEC_ID_NONE, 0 },
177};
178
179const AVCodecTag ff_codec_movsubtitle_tags[] = {
180 { CODEC_ID_MOV_TEXT, MKTAG('t', 'e', 'x', 't') },
181 { CODEC_ID_MOV_TEXT, MKTAG('t', 'x', '3', 'g') },
182 { CODEC_ID_NONE, 0 },
183};
184
185/* map numeric codes from mdhd atom to ISO 639 */
186/* cf. QTFileFormat.pdf p253, qtff.pdf p205 */
187/* http://developer.apple.com/documentation/mac/Text/Text-368.html */
188/* deprecated by putting the code as 3*5bit ascii */
189static const char *mov_mdhd_language_map[] = {
190 /* 0-9 */
191 "eng", "fra", "ger", "ita", "dut", "sve", "spa", "dan", "por", "nor",
192 "heb", "jpn", "ara", "fin", "gre", "ice", "mlt", "tur", "hr "/*scr*/, "chi"/*ace?*/,
193 "urd", "hin", "tha", "kor", "lit", "pol", "hun", "est", "lav", NULL,
194 "fo ", NULL, "rus", "chi", NULL, "iri", "alb", "ron", "ces", "slk",
195 "slv", "yid", "sr ", "mac", "bul", "ukr", "bel", "uzb", "kaz", "aze",
196 /*?*/
197 "aze", "arm", "geo", "mol", "kir", "tgk", "tuk", "mon", NULL, "pus",
198 "kur", "kas", "snd", "tib", "nep", "san", "mar", "ben", "asm", "guj",
199 "pa ", "ori", "mal", "kan", "tam", "tel", NULL, "bur", "khm", "lao",
200 /* roman? arabic? */
201 "vie", "ind", "tgl", "may", "may", "amh", "tir", "orm", "som", "swa",
202 /*==rundi?*/
203 NULL, "run", NULL, "mlg", "epo", NULL, NULL, NULL, NULL, NULL,
204 /* 100 */
205 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
206 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
207 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "wel", "baq",
208 "cat", "lat", "que", "grn", "aym", "tat", "uig", "dzo", "jav"
209};
210
211int ff_mov_iso639_to_lang(const char *lang, int mp4)
212{
213 int i, code = 0;
214
215 /* old way, only for QT? */
216 for (i = 0; !mp4 && (i < (sizeof(mov_mdhd_language_map)/sizeof(char *))); i++) {
217 if (mov_mdhd_language_map[i] && !strcmp(lang, mov_mdhd_language_map[i]))
218 return i;
219 }
220 /* XXX:can we do that in mov too? */
221 if (!mp4)
222 return 0;
223 /* handle undefined as such */
224 if (lang[0] == '\0')
225 lang = "und";
226 /* 5bit ascii */
227 for (i = 0; i < 3; i++) {
228 unsigned char c = (unsigned char)lang[i];
229 if (c < 0x60)
230 return 0;
231 if (c > 0x60 + 0x1f)
232 return 0;
233 code <<= 5;
234 code |= (c - 0x60);
235 }
236 return code;
237}
238
239int ff_mov_lang_to_iso639(int code, char *to)
240{
241 int i;
242 /* is it the mangled iso code? */
243 /* see http://www.geocities.com/xhelmboyx/quicktime/formats/mp4-layout.txt */
244 if (code > 138) {
245 for (i = 2; i >= 0; i--) {
246 to[i] = 0x60 + (code & 0x1f);
247 code >>= 5;
248 }
249 return 1;
250 }
251 /* old fashion apple lang code */
252 if (code >= (sizeof(mov_mdhd_language_map)/sizeof(char *)))
253 return 0;
254 if (!mov_mdhd_language_map[code])
255 return 0;
256 strncpy(to, mov_mdhd_language_map[code], 4);
257 return 1;
258}
diff --git a/src/plugins/ffmpeg/libavformat/isom.h b/src/plugins/ffmpeg/libavformat/isom.h
deleted file mode 100644
index 7a66ce5..0000000
--- a/src/plugins/ffmpeg/libavformat/isom.h
+++ /dev/null
@@ -1,43 +0,0 @@
1/*
2 * ISO Media common code
3 * copyright (c) 2001 Fabrice Bellard.
4 * copyright (c) 2002 Francois Revol <revol@free.fr>
5 * copyright (c) 2006 Baptiste Coudurier <baptiste.coudurier@free.fr>
6 *
7 * This file is part of FFmpeg.
8 *
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23
24#ifndef FFMPEG_ISOM_H
25#define FFMPEG_ISOM_H
26
27#include "riff.h"
28
29/* isom.c */
30extern const AVCodecTag ff_mp4_obj_type[];
31extern const AVCodecTag codec_movvideo_tags[];
32extern const AVCodecTag codec_movaudio_tags[];
33extern const AVCodecTag ff_codec_movsubtitle_tags[];
34
35int ff_mov_iso639_to_lang(const char *lang, int mp4);
36int ff_mov_lang_to_iso639(int code, char *to);
37
38typedef struct {
39 int count;
40 int duration;
41} MOV_stts_t;
42
43#endif /* FFMPEG_ISOM_H */
diff --git a/src/plugins/ffmpeg/libavformat/libnut.c b/src/plugins/ffmpeg/libavformat/libnut.c
deleted file mode 100644
index 2cadaef..0000000
--- a/src/plugins/ffmpeg/libavformat/libnut.c
+++ /dev/null
@@ -1,310 +0,0 @@
1/*
2 * NUT (de)muxing via libnut
3 * copyright (c) 2006 Oded Shimon <ods15@ods15.dyndns.org>
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/**
23 * @file libnut.c
24 * NUT demuxing and muxing via libnut.
25 * @author Oded Shimon <ods15@ods15.dyndns.org>
26 */
27
28#include "avformat.h"
29#include "riff.h"
30#include <libnut.h>
31
32#define ID_STRING "nut/multimedia container"
33#define ID_LENGTH (strlen(ID_STRING) + 1)
34
35typedef struct {
36 nut_context_t * nut;
37 nut_stream_header_t * s;
38} NUTContext;
39
40static const AVCodecTag nut_tags[] = {
41 { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
42 { CODEC_ID_MP3, MKTAG('m', 'p', '3', ' ') },
43 { CODEC_ID_VORBIS, MKTAG('v', 'r', 'b', 's') },
44 { 0, 0 },
45};
46
47#ifdef CONFIG_MUXERS
48static int av_write(void * h, size_t len, const uint8_t * buf) {
49 ByteIOContext * bc = h;
50 put_buffer(bc, buf, len);
51 //put_flush_packet(bc);
52 return len;
53}
54
55static int nut_write_header(AVFormatContext * avf) {
56 NUTContext * priv = avf->priv_data;
57 ByteIOContext * bc = avf->pb;
58 nut_muxer_opts_t mopts = {
59 .output = {
60 .priv = bc,
61 .write = av_write,
62 },
63 .alloc = { av_malloc, av_realloc, av_free },
64 .write_index = 1,
65 .realtime_stream = 0,
66 .max_distance = 32768,
67 .fti = NULL,
68 };
69 nut_stream_header_t * s;
70 int i;
71
72 priv->s = s = av_mallocz((avf->nb_streams + 1) * sizeof*s);
73
74 for (i = 0; i < avf->nb_streams; i++) {
75 AVCodecContext * codec = avf->streams[i]->codec;
76 int j;
77 int fourcc = 0;
78 int num, denom, ssize;
79
80 s[i].type = codec->codec_type == CODEC_TYPE_VIDEO ? NUT_VIDEO_CLASS : NUT_AUDIO_CLASS;
81
82 if (codec->codec_tag) fourcc = codec->codec_tag;
83 else fourcc = codec_get_tag(nut_tags, codec->codec_id);
84
85 if (!fourcc) {
86 if (codec->codec_type == CODEC_TYPE_VIDEO) fourcc = codec_get_tag(codec_bmp_tags, codec->codec_id);
87 if (codec->codec_type == CODEC_TYPE_AUDIO) fourcc = codec_get_tag(codec_wav_tags, codec->codec_id);
88 }
89
90 s[i].fourcc_len = 4;
91 s[i].fourcc = av_malloc(s[i].fourcc_len);
92 for (j = 0; j < s[i].fourcc_len; j++) s[i].fourcc[j] = (fourcc >> (j*8)) & 0xFF;
93
94 ff_parse_specific_params(codec, &num, &ssize, &denom);
95 av_set_pts_info(avf->streams[i], 60, denom, num);
96
97 s[i].time_base.num = denom;
98 s[i].time_base.den = num;
99
100 s[i].fixed_fps = 0;
101 s[i].decode_delay = codec->has_b_frames;
102 s[i].codec_specific_len = codec->extradata_size;
103 s[i].codec_specific = codec->extradata;
104
105 if (codec->codec_type == CODEC_TYPE_VIDEO) {
106 s[i].width = codec->width;
107 s[i].height = codec->height;
108 s[i].sample_width = 0;
109 s[i].sample_height = 0;
110 s[i].colorspace_type = 0;
111 } else {
112 s[i].samplerate_num = codec->sample_rate;
113 s[i].samplerate_denom = 1;
114 s[i].channel_count = codec->channels;
115 }
116 }
117
118 s[avf->nb_streams].type = -1;
119 priv->nut = nut_muxer_init(&mopts, s, NULL);
120
121 return 0;
122}
123
124static int nut_write_packet(AVFormatContext * avf, AVPacket * pkt) {
125 NUTContext * priv = avf->priv_data;
126 nut_packet_t p;
127
128 p.len = pkt->size;
129 p.stream = pkt->stream_index;
130 p.pts = pkt->pts;
131 p.flags = pkt->flags & PKT_FLAG_KEY ? NUT_FLAG_KEY : 0;
132 p.next_pts = 0;
133
134 nut_write_frame_reorder(priv->nut, &p, pkt->data);
135
136 return 0;
137}
138
139static int nut_write_trailer(AVFormatContext * avf) {
140 ByteIOContext * bc = avf->pb;
141 NUTContext * priv = avf->priv_data;
142 int i;
143
144 nut_muxer_uninit_reorder(priv->nut);
145 put_flush_packet(bc);
146
147 for(i = 0; priv->s[i].type != -1; i++ ) av_freep(&priv->s[i].fourcc);
148 av_freep(&priv->s);
149
150 return 0;
151}
152
153AVOutputFormat libnut_muxer = {
154 "libnut",
155 "nut format",
156 "video/x-nut",
157 "nut",
158 sizeof(NUTContext),
159 CODEC_ID_VORBIS,
160 CODEC_ID_MPEG4,
161 nut_write_header,
162 nut_write_packet,
163 nut_write_trailer,
164 .flags = AVFMT_GLOBALHEADER,
165};
166#endif //CONFIG_MUXERS
167
168static int nut_probe(AVProbeData *p) {
169 if (!memcmp(p->buf, ID_STRING, ID_LENGTH)) return AVPROBE_SCORE_MAX;
170
171 return 0;
172}
173
174static size_t av_read(void * h, size_t len, uint8_t * buf) {
175 ByteIOContext * bc = h;
176 return get_buffer(bc, buf, len);
177}
178
179static off_t av_seek(void * h, long long pos, int whence) {
180 ByteIOContext * bc = h;
181 if (whence == SEEK_END) {
182 pos = url_fsize(bc) + pos;
183 whence = SEEK_SET;
184 }
185 return url_fseek(bc, pos, whence);
186}
187
188static int nut_read_header(AVFormatContext * avf, AVFormatParameters * ap) {
189 NUTContext * priv = avf->priv_data;
190 ByteIOContext * bc = avf->pb;
191 nut_demuxer_opts_t dopts = {
192 .input = {
193 .priv = bc,
194 .seek = av_seek,
195 .read = av_read,
196 .eof = NULL,
197 .file_pos = 0,
198 },
199 .alloc = { av_malloc, av_realloc, av_free },
200 .read_index = 1,
201 .cache_syncpoints = 1,
202 };
203 nut_context_t * nut = priv->nut = nut_demuxer_init(&dopts);
204 nut_stream_header_t * s;
205 int ret, i;
206
207 if ((ret = nut_read_headers(nut, &s, NULL))) {
208 av_log(avf, AV_LOG_ERROR, " NUT error: %s\n", nut_error(ret));
209 nut_demuxer_uninit(nut);
210 return -1;
211 }
212
213 priv->s = s;
214
215 for (i = 0; s[i].type != -1 && i < 2; i++) {
216 AVStream * st = av_new_stream(avf, i);
217 int j;
218
219 for (j = 0; j < s[i].fourcc_len && j < 8; j++) st->codec->codec_tag |= s[i].fourcc[j]<<(j*8);
220
221 st->codec->has_b_frames = s[i].decode_delay;
222
223 st->codec->extradata_size = s[i].codec_specific_len;
224 if (st->codec->extradata_size) {
225 st->codec->extradata = av_mallocz(st->codec->extradata_size);
226 memcpy(st->codec->extradata, s[i].codec_specific, st->codec->extradata_size);
227 }
228
229 av_set_pts_info(avf->streams[i], 60, s[i].time_base.num, s[i].time_base.den);
230 st->start_time = 0;
231 st->duration = s[i].max_pts;
232
233 st->codec->codec_id = codec_get_id(nut_tags, st->codec->codec_tag);
234
235 switch(s[i].type) {
236 case NUT_AUDIO_CLASS:
237 st->codec->codec_type = CODEC_TYPE_AUDIO;
238 if (st->codec->codec_id == CODEC_ID_NONE) st->codec->codec_id = codec_get_id(codec_wav_tags, st->codec->codec_tag);
239
240 st->codec->channels = s[i].channel_count;
241 st->codec->sample_rate = s[i].samplerate_num / s[i].samplerate_denom;
242 break;
243 case NUT_VIDEO_CLASS:
244 st->codec->codec_type = CODEC_TYPE_VIDEO;
245 if (st->codec->codec_id == CODEC_ID_NONE) st->codec->codec_id = codec_get_id(codec_bmp_tags, st->codec->codec_tag);
246
247 st->codec->width = s[i].width;
248 st->codec->height = s[i].height;
249 st->codec->sample_aspect_ratio.num = s[i].sample_width;
250 st->codec->sample_aspect_ratio.den = s[i].sample_height;
251 break;
252 }
253 if (st->codec->codec_id == CODEC_ID_NONE) av_log(avf, AV_LOG_ERROR, "Unknown codec?!\n");
254 }
255
256 return 0;
257}
258
259static int nut_read_packet(AVFormatContext * avf, AVPacket * pkt) {
260 NUTContext * priv = avf->priv_data;
261 nut_packet_t pd;
262 int ret;
263
264 ret = nut_read_next_packet(priv->nut, &pd);
265
266 if (ret || av_new_packet(pkt, pd.len) < 0) {
267 if (ret != NUT_ERR_EOF)
268 av_log(avf, AV_LOG_ERROR, " NUT error: %s\n", nut_error(ret));
269 return -1;
270 }
271
272 if (pd.flags & NUT_FLAG_KEY) pkt->flags |= PKT_FLAG_KEY;
273 pkt->pts = pd.pts;
274 pkt->stream_index = pd.stream;
275 pkt->pos = url_ftell(avf->pb);
276
277 ret = nut_read_frame(priv->nut, &pd.len, pkt->data);
278
279 return ret;
280}
281
282static int nut_read_seek(AVFormatContext * avf, int stream_index, int64_t target_ts, int flags) {
283 NUTContext * priv = avf->priv_data;
284 int active_streams[] = { stream_index, -1 };
285 double time_pos = target_ts * priv->s[stream_index].time_base.num / (double)priv->s[stream_index].time_base.den;
286
287 if (nut_seek(priv->nut, time_pos, 2*!(flags & AVSEEK_FLAG_BACKWARD), active_streams)) return -1;
288
289 return 0;
290}
291
292static int nut_read_close(AVFormatContext *s) {
293 NUTContext * priv = s->priv_data;
294
295 nut_demuxer_uninit(priv->nut);
296
297 return 0;
298}
299
300AVInputFormat libnut_demuxer = {
301 "libnut",
302 NULL_IF_CONFIG_SMALL("NUT format"),
303 sizeof(NUTContext),
304 nut_probe,
305 nut_read_header,
306 nut_read_packet,
307 nut_read_close,
308 nut_read_seek,
309 .extensions = "nut",
310};
diff --git a/src/plugins/ffmpeg/libavformat/lmlm4.c b/src/plugins/ffmpeg/libavformat/lmlm4.c
deleted file mode 100644
index 7f01124..0000000
--- a/src/plugins/ffmpeg/libavformat/lmlm4.c
+++ /dev/null
@@ -1,126 +0,0 @@
1/*
2 * Linux Media Labs MPEG-4 demuxer
3 * Copyright (c) 2008 Ivo van Poorten
4 *
5 * Due to a lack of sample files, only files with one channel are supported.
6 * u-law and ADPCM audio are unsupported for the same reason.
7 *
8 * This file is part of FFmpeg.
9 *
10 * FFmpeg is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
14 *
15 * FFmpeg is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with FFmpeg; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 */
24
25#include "avformat.h"
26
27#define LMLM4_I_FRAME 0x00
28#define LMLM4_P_FRAME 0x01
29#define LMLM4_B_FRAME 0x02
30#define LMLM4_INVALID 0x03
31#define LMLM4_MPEG1L2 0x04
32
33#define LMLM4_MAX_PACKET_SIZE 1024 * 1024
34
35static int lmlm4_probe(AVProbeData * pd) {
36 unsigned char *buf = pd->buf;
37 unsigned int frame_type, packet_size;
38
39 frame_type = AV_RB16(buf+2);
40 packet_size = AV_RB32(buf+4);
41
42 if (!AV_RB16(buf) && frame_type <= LMLM4_MPEG1L2 && packet_size &&
43 frame_type != LMLM4_INVALID && packet_size <= LMLM4_MAX_PACKET_SIZE) {
44
45 if (frame_type == LMLM4_MPEG1L2) {
46 if ((AV_RB16(buf+8) & 0xfffe) != 0xfffc)
47 return 0;
48 /* I could calculate the audio framesize and compare with
49 * packet_size-8, but that seems overkill */
50 return AVPROBE_SCORE_MAX / 3;
51 } else if (AV_RB24(buf+8) == 0x000001) { /* PES Signal */
52 return AVPROBE_SCORE_MAX / 5;
53 }
54 }
55
56 return 0;
57}
58
59static int lmlm4_read_header(AVFormatContext *s, AVFormatParameters *ap) {
60 AVStream *st;
61
62 if (!(st = av_new_stream(s, 0)))
63 return AVERROR(ENOMEM);
64 st->codec->codec_type = CODEC_TYPE_VIDEO;
65 st->codec->codec_id = CODEC_ID_MPEG4;
66 st->need_parsing = AVSTREAM_PARSE_HEADERS;
67 av_set_pts_info(st, 64, 1001, 30000);
68
69 if (!(st = av_new_stream(s, 1)))
70 return AVERROR(ENOMEM);
71 st->codec->codec_type = CODEC_TYPE_AUDIO;
72 st->codec->codec_id = CODEC_ID_MP2;
73 st->need_parsing = AVSTREAM_PARSE_HEADERS;
74
75 /* the parameters will be extracted from the compressed bitstream */
76 return 0;
77}
78
79static int lmlm4_read_packet(AVFormatContext *s, AVPacket *pkt) {
80 ByteIOContext *pb = s->pb;
81 int ret;
82 unsigned int frame_type, packet_size, padding, frame_size;
83
84 get_be16(pb); /* channel number */
85 frame_type = get_be16(pb);
86 packet_size = get_be32(pb);
87 padding = -packet_size & 511;
88 frame_size = packet_size - 8;
89
90 if (frame_type > LMLM4_MPEG1L2 || frame_type == LMLM4_INVALID) {
91 av_log(s, AV_LOG_ERROR, "invalid or unsupported frame_type\n");
92 return AVERROR(EIO);
93 }
94 if (packet_size > LMLM4_MAX_PACKET_SIZE) {
95 av_log(s, AV_LOG_ERROR, "packet size exceeds maximum\n");
96 return AVERROR(EIO);
97 }
98
99 if ((ret = av_get_packet(pb, pkt, frame_size)) <= 0)
100 return AVERROR(EIO);
101
102 url_fskip(pb, padding);
103
104 switch (frame_type) {
105 case LMLM4_I_FRAME:
106 pkt->flags = PKT_FLAG_KEY;
107 case LMLM4_P_FRAME:
108 case LMLM4_B_FRAME:
109 pkt->stream_index = 0;
110 break;
111 case LMLM4_MPEG1L2:
112 pkt->stream_index = 1;
113 break;
114 }
115
116 return ret;
117}
118
119AVInputFormat lmlm4_demuxer = {
120 "lmlm4",
121 NULL_IF_CONFIG_SMALL("lmlm4 raw format"),
122 0,
123 lmlm4_probe,
124 lmlm4_read_header,
125 lmlm4_read_packet,
126};
diff --git a/src/plugins/ffmpeg/libavformat/matroska.c b/src/plugins/ffmpeg/libavformat/matroska.c
deleted file mode 100644
index b62511f..0000000
--- a/src/plugins/ffmpeg/libavformat/matroska.c
+++ /dev/null
@@ -1,85 +0,0 @@
1/*
2 * Matroska common data
3 * Copyright (c) 2003-2004 The ffmpeg Project
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 "matroska.h"
23
24const CodecTags ff_mkv_codec_tags[]={
25// {"V_MS/VFW/FOURCC" , CODEC_ID_NONE},
26 {"V_UNCOMPRESSED" , CODEC_ID_RAWVIDEO},
27 {"V_MPEG4/ISO/ASP" , CODEC_ID_MPEG4},
28 {"V_MPEG4/ISO/SP" , CODEC_ID_MPEG4},
29 {"V_MPEG4/ISO/AP" , CODEC_ID_MPEG4},
30 {"V_MPEG4/ISO/AVC" , CODEC_ID_H264},
31 {"V_MPEG4/MS/V3" , CODEC_ID_MSMPEG4V3},
32 {"V_MPEG1" , CODEC_ID_MPEG1VIDEO},
33 {"V_MPEG2" , CODEC_ID_MPEG2VIDEO},
34 {"V_MJPEG" , CODEC_ID_MJPEG},
35 {"V_REAL/RV10" , CODEC_ID_RV10},
36 {"V_REAL/RV20" , CODEC_ID_RV20},
37 {"V_REAL/RV30" , CODEC_ID_RV30},
38 {"V_REAL/RV40" , CODEC_ID_RV40},
39 {"V_THEORA" , CODEC_ID_THEORA},
40 {"V_SNOW" , CODEC_ID_SNOW},
41/* TODO: Real/Quicktime */
42
43// {"A_MS/ACM" , CODEC_ID_NONE},
44 {"A_MPEG/L3" , CODEC_ID_MP3},
45 {"A_MPEG/L2" , CODEC_ID_MP2},
46 {"A_MPEG/L1" , CODEC_ID_MP2},
47 {"A_PCM/INT/BIG" , CODEC_ID_PCM_U16BE},
48 {"A_PCM/INT/LIT" , CODEC_ID_PCM_U16LE},
49// {"A_PCM/FLOAT/IEEE" , CODEC_ID_NONE},
50 {"A_AC3" , CODEC_ID_AC3},
51 {"A_DTS" , CODEC_ID_DTS},
52 {"A_VORBIS" , CODEC_ID_VORBIS},
53 {"A_AAC" , CODEC_ID_AAC},
54 {"A_FLAC" , CODEC_ID_FLAC},
55 {"A_WAVPACK4" , CODEC_ID_WAVPACK},
56 {"A_TTA1" , CODEC_ID_TTA},
57 {"A_REAL/14_4" , CODEC_ID_RA_144},
58 {"A_REAL/28_8" , CODEC_ID_RA_288},
59 {"A_REAL/ATRC" , CODEC_ID_ATRAC3},
60 {"A_REAL/COOK" , CODEC_ID_COOK},
61// {"A_REAL/SIPR" , CODEC_ID_SIPRO},
62
63 {"S_TEXT/UTF8" , CODEC_ID_TEXT},
64 {"S_TEXT/ASCII" , CODEC_ID_TEXT},
65 {"S_TEXT/ASS" , CODEC_ID_SSA},
66 {"S_TEXT/SSA" , CODEC_ID_SSA},
67 {"S_ASS" , CODEC_ID_SSA},
68 {"S_SSA" , CODEC_ID_SSA},
69 {"S_VOBSUB" , CODEC_ID_DVD_SUBTITLE},
70
71 {"" , CODEC_ID_NONE}
72/* TODO: AC3-9/10 (?), Real, Musepack, Quicktime */
73};
74
75const CodecMime ff_mkv_mime_tags[] = {
76 {"text/plain" , CODEC_ID_TEXT},
77 {"image/gif" , CODEC_ID_GIF},
78 {"image/jpeg" , CODEC_ID_MJPEG},
79 {"image/png" , CODEC_ID_PNG},
80 {"image/tiff" , CODEC_ID_TIFF},
81 {"application/x-truetype-font", CODEC_ID_TTF},
82 {"application/x-font" , CODEC_ID_TTF},
83
84 {"" , CODEC_ID_NONE}
85};
diff --git a/src/plugins/ffmpeg/libavformat/matroska.h b/src/plugins/ffmpeg/libavformat/matroska.h
deleted file mode 100644
index 26f4666..0000000
--- a/src/plugins/ffmpeg/libavformat/matroska.h
+++ /dev/null
@@ -1,231 +0,0 @@
1/*
2 * Matroska constants
3 * Copyright (c) 2003-2004 The ffmpeg Project
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#ifndef FFMPEG_MATROSKA_H
23#define FFMPEG_MATROSKA_H
24
25#include "libavcodec/avcodec.h"
26
27/* EBML version supported */
28#define EBML_VERSION 1
29
30/* top-level master-IDs */
31#define EBML_ID_HEADER 0x1A45DFA3
32
33/* IDs in the HEADER master */
34#define EBML_ID_EBMLVERSION 0x4286
35#define EBML_ID_EBMLREADVERSION 0x42F7
36#define EBML_ID_EBMLMAXIDLENGTH 0x42F2
37#define EBML_ID_EBMLMAXSIZELENGTH 0x42F3
38#define EBML_ID_DOCTYPE 0x4282
39#define EBML_ID_DOCTYPEVERSION 0x4287
40#define EBML_ID_DOCTYPEREADVERSION 0x4285
41
42/* general EBML types */
43#define EBML_ID_VOID 0xEC
44
45/*
46 * Matroska element IDs. max. 32-bit.
47 */
48
49/* toplevel segment */
50#define MATROSKA_ID_SEGMENT 0x18538067
51
52/* matroska top-level master IDs */
53#define MATROSKA_ID_INFO 0x1549A966
54#define MATROSKA_ID_TRACKS 0x1654AE6B
55#define MATROSKA_ID_CUES 0x1C53BB6B
56#define MATROSKA_ID_TAGS 0x1254C367
57#define MATROSKA_ID_SEEKHEAD 0x114D9B74
58#define MATROSKA_ID_ATTACHMENTS 0x1941A469
59#define MATROSKA_ID_CLUSTER 0x1F43B675
60#define MATROSKA_ID_CHAPTERS 0x1043A770
61
62/* IDs in the info master */
63#define MATROSKA_ID_TIMECODESCALE 0x2AD7B1
64#define MATROSKA_ID_DURATION 0x4489
65#define MATROSKA_ID_TITLE 0x7BA9
66#define MATROSKA_ID_WRITINGAPP 0x5741
67#define MATROSKA_ID_MUXINGAPP 0x4D80
68#define MATROSKA_ID_DATEUTC 0x4461
69#define MATROSKA_ID_SEGMENTUID 0x73A4
70
71/* ID in the tracks master */
72#define MATROSKA_ID_TRACKENTRY 0xAE
73
74/* IDs in the trackentry master */
75#define MATROSKA_ID_TRACKNUMBER 0xD7
76#define MATROSKA_ID_TRACKUID 0x73C5
77#define MATROSKA_ID_TRACKTYPE 0x83
78#define MATROSKA_ID_TRACKAUDIO 0xE1
79#define MATROSKA_ID_TRACKVIDEO 0xE0
80#define MATROSKA_ID_CODECID 0x86
81#define MATROSKA_ID_CODECPRIVATE 0x63A2
82#define MATROSKA_ID_CODECNAME 0x258688
83#define MATROSKA_ID_CODECINFOURL 0x3B4040
84#define MATROSKA_ID_CODECDOWNLOADURL 0x26B240
85#define MATROSKA_ID_CODECDECODEALL 0xAA
86#define MATROSKA_ID_TRACKNAME 0x536E
87#define MATROSKA_ID_TRACKLANGUAGE 0x22B59C
88#define MATROSKA_ID_TRACKFLAGENABLED 0xB9
89#define MATROSKA_ID_TRACKFLAGDEFAULT 0x88
90#define MATROSKA_ID_TRACKFLAGFORCED 0x55AA
91#define MATROSKA_ID_TRACKFLAGLACING 0x9C
92#define MATROSKA_ID_TRACKMINCACHE 0x6DE7
93#define MATROSKA_ID_TRACKMAXCACHE 0x6DF8
94#define MATROSKA_ID_TRACKDEFAULTDURATION 0x23E383
95#define MATROSKA_ID_TRACKCONTENTENCODINGS 0x6D80
96#define MATROSKA_ID_TRACKCONTENTENCODING 0x6240
97#define MATROSKA_ID_TRACKTIMECODESCALE 0x23314F
98
99/* IDs in the trackvideo master */
100#define MATROSKA_ID_VIDEOFRAMERATE 0x2383E3
101#define MATROSKA_ID_VIDEODISPLAYWIDTH 0x54B0
102#define MATROSKA_ID_VIDEODISPLAYHEIGHT 0x54BA
103#define MATROSKA_ID_VIDEOPIXELWIDTH 0xB0
104#define MATROSKA_ID_VIDEOPIXELHEIGHT 0xBA
105#define MATROSKA_ID_VIDEOFLAGINTERLACED 0x9A
106#define MATROSKA_ID_VIDEOSTEREOMODE 0x53B9
107#define MATROSKA_ID_VIDEOASPECTRATIO 0x54B3
108#define MATROSKA_ID_VIDEOCOLORSPACE 0x2EB524
109
110/* IDs in the trackaudio master */
111#define MATROSKA_ID_AUDIOSAMPLINGFREQ 0xB5
112#define MATROSKA_ID_AUDIOOUTSAMPLINGFREQ 0x78B5
113
114#define MATROSKA_ID_AUDIOBITDEPTH 0x6264
115#define MATROSKA_ID_AUDIOCHANNELS 0x9F
116
117/* IDs in the content encoding master */
118#define MATROSKA_ID_ENCODINGSCOPE 0x5032
119#define MATROSKA_ID_ENCODINGTYPE 0x5033
120#define MATROSKA_ID_ENCODINGCOMPRESSION 0x5034
121#define MATROSKA_ID_ENCODINGCOMPALGO 0x4254
122#define MATROSKA_ID_ENCODINGCOMPSETTINGS 0x4255
123
124/* ID in the cues master */
125#define MATROSKA_ID_POINTENTRY 0xBB
126
127/* IDs in the pointentry master */
128#define MATROSKA_ID_CUETIME 0xB3
129#define MATROSKA_ID_CUETRACKPOSITION 0xB7
130
131/* IDs in the cuetrackposition master */
132#define MATROSKA_ID_CUETRACK 0xF7
133#define MATROSKA_ID_CUECLUSTERPOSITION 0xF1
134
135/* IDs in the tags master */
136/* TODO */
137
138/* IDs in the seekhead master */
139#define MATROSKA_ID_SEEKENTRY 0x4DBB
140
141/* IDs in the seekpoint master */
142#define MATROSKA_ID_SEEKID 0x53AB
143#define MATROSKA_ID_SEEKPOSITION 0x53AC
144
145/* IDs in the cluster master */
146#define MATROSKA_ID_CLUSTERTIMECODE 0xE7
147#define MATROSKA_ID_BLOCKGROUP 0xA0
148#define MATROSKA_ID_SIMPLEBLOCK 0xA3
149
150/* IDs in the blockgroup master */
151#define MATROSKA_ID_BLOCK 0xA1
152#define MATROSKA_ID_BLOCKDURATION 0x9B
153#define MATROSKA_ID_BLOCKREFERENCE 0xFB
154
155/* IDs in the attachments master */
156#define MATROSKA_ID_ATTACHEDFILE 0x61A7
157#define MATROSKA_ID_FILENAME 0x466E
158#define MATROSKA_ID_FILEMIMETYPE 0x4660
159#define MATROSKA_ID_FILEDATA 0x465C
160#define MATROSKA_ID_FILEUID 0x46AE
161
162/* IDs in the chapters master */
163#define MATROSKA_ID_EDITIONENTRY 0x45B9
164#define MATROSKA_ID_CHAPTERATOM 0xB6
165#define MATROSKA_ID_CHAPTERTIMESTART 0x91
166#define MATROSKA_ID_CHAPTERTIMEEND 0x92
167#define MATROSKA_ID_CHAPTERDISPLAY 0x80
168#define MATROSKA_ID_CHAPSTRING 0x85
169#define MATROSKA_ID_EDITIONUID 0x45BC
170#define MATROSKA_ID_EDITIONFLAGHIDDEN 0x45BD
171#define MATROSKA_ID_EDITIONFLAGDEFAULT 0x45DB
172#define MATROSKA_ID_CHAPTERUID 0x73C4
173#define MATROSKA_ID_CHAPTERFLAGHIDDEN 0x98
174
175typedef enum {
176 MATROSKA_TRACK_TYPE_NONE = 0x0,
177 MATROSKA_TRACK_TYPE_VIDEO = 0x1,
178 MATROSKA_TRACK_TYPE_AUDIO = 0x2,
179 MATROSKA_TRACK_TYPE_COMPLEX = 0x3,
180 MATROSKA_TRACK_TYPE_LOGO = 0x10,
181 MATROSKA_TRACK_TYPE_SUBTITLE = 0x11,
182 MATROSKA_TRACK_TYPE_CONTROL = 0x20,
183} MatroskaTrackType;
184
185typedef enum {
186 MATROSKA_TRACK_ENCODING_COMP_ZLIB = 0,
187 MATROSKA_TRACK_ENCODING_COMP_BZLIB = 1,
188 MATROSKA_TRACK_ENCODING_COMP_LZO = 2,
189 MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP = 3,
190} MatroskaTrackEncodingCompAlgo;
191
192/*
193 * These aren't in any way "matroska-form" things,
194 * it's just something I use in the muxer/demuxer.
195 */
196
197typedef enum {
198 MATROSKA_TRACK_ENABLED = (1<<0),
199 MATROSKA_TRACK_DEFAULT = (1<<1),
200 MATROSKA_TRACK_LACING = (1<<2),
201 MATROSKA_TRACK_SHIFT = (1<<16)
202} MatroskaTrackFlags;
203
204typedef enum {
205 MATROSKA_VIDEOTRACK_INTERLACED = (MATROSKA_TRACK_SHIFT<<0)
206} MatroskaVideoTrackFlags;
207
208/*
209 * Matroska Codec IDs. Strings.
210 */
211
212typedef struct CodecTags{
213 char str[16];
214 enum CodecID id;
215}CodecTags;
216
217typedef struct CodecMime{
218 char str[32];
219 enum CodecID id;
220}CodecMime;
221
222#define MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC "V_MS/VFW/FOURCC"
223#define MATROSKA_CODEC_ID_AUDIO_ACM "A_MS/ACM"
224
225/* max. depth in the EBML tree structure */
226#define EBML_MAX_DEPTH 16
227
228extern const CodecTags ff_mkv_codec_tags[];
229extern const CodecMime ff_mkv_mime_tags[];
230
231#endif /* FFMPEG_MATROSKA_H */
diff --git a/src/plugins/ffmpeg/libavformat/matroskadec.c b/src/plugins/ffmpeg/libavformat/matroskadec.c
deleted file mode 100644
index bea76f4..0000000
--- a/src/plugins/ffmpeg/libavformat/matroskadec.c
+++ /dev/null
@@ -1,3202 +0,0 @@
1/*
2 * Matroska file demuxer (no muxer yet)
3 * Copyright (c) 2003-2004 The ffmpeg Project
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/**
23 * @file matroskadec.c
24 * Matroska file demuxer
25 * by Ronald Bultje <rbultje@ronald.bitfreak.net>
26 * with a little help from Moritz Bunkus <moritz@bunkus.org>
27 * Specs available on the matroska project page:
28 * http://www.matroska.org/.
29 */
30
31#include "avformat.h"
32/* For codec_get_id(). */
33#include "riff.h"
34#include "matroska.h"
35#include "libavcodec/mpeg4audio.h"
36#include "libavutil/intfloat_readwrite.h"
37#include "libavutil/lzo.h"
38#ifdef CONFIG_ZLIB
39#include <zlib.h>
40#endif
41#ifdef CONFIG_BZLIB
42#include <bzlib.h>
43#endif
44
45typedef struct Track {
46 MatroskaTrackType type;
47
48 /* Unique track number and track ID. stream_index is the index that
49 * the calling app uses for this track. */
50 uint32_t num;
51 uint32_t uid;
52 int stream_index;
53
54 char *name;
55 char language[4];
56
57 char *codec_id;
58
59 unsigned char *codec_priv;
60 int codec_priv_size;
61
62 double time_scale;
63 uint64_t default_duration;
64 MatroskaTrackFlags flags;
65
66 int encoding_scope;
67 MatroskaTrackEncodingCompAlgo encoding_algo;
68 uint8_t *encoding_settings;
69 int encoding_settings_len;
70} MatroskaTrack;
71
72typedef struct MatroskaVideoTrack {
73 MatroskaTrack track;
74
75 int pixel_width;
76 int pixel_height;
77 int display_width;
78 int display_height;
79
80 uint32_t fourcc;
81
82 //..
83} MatroskaVideoTrack;
84
85typedef struct MatroskaAudioTrack {
86 MatroskaTrack track;
87
88 int channels;
89 int bitdepth;
90 int internal_samplerate;
91 int samplerate;
92 int block_align;
93
94 /* real audio header */
95 int coded_framesize;
96 int sub_packet_h;
97 int frame_size;
98 int sub_packet_size;
99 int sub_packet_cnt;
100 int pkt_cnt;
101 uint8_t *buf;
102 //..
103} MatroskaAudioTrack;
104
105typedef struct MatroskaSubtitleTrack {
106 MatroskaTrack track;
107 //..
108} MatroskaSubtitleTrack;
109
110#define MAX_TRACK_SIZE (FFMAX3(sizeof(MatroskaVideoTrack), \
111 sizeof(MatroskaAudioTrack), \
112 sizeof(MatroskaSubtitleTrack)))
113
114typedef struct MatroskaLevel {
115 uint64_t start;
116 uint64_t length;
117} MatroskaLevel;
118
119typedef struct MatroskaDemuxIndex {
120 uint64_t pos; /* of the corresponding *cluster*! */
121 uint16_t track; /* reference to 'num' */
122 uint64_t time; /* in nanoseconds */
123} MatroskaDemuxIndex;
124
125typedef struct MatroskaDemuxContext {
126 AVFormatContext *ctx;
127
128 /* ebml stuff */
129 int num_levels;
130 MatroskaLevel levels[EBML_MAX_DEPTH];
131 int level_up;
132
133 /* timescale in the file */
134 int64_t time_scale;
135
136 /* num_streams is the number of streams that av_new_stream() was called
137 * for ( = that are available to the calling program). */
138 int num_tracks;
139 int num_streams;
140 MatroskaTrack *tracks[MAX_STREAMS];
141
142 /* cache for ID peeking */
143 uint32_t peek_id;
144
145 /* byte position of the segment inside the stream */
146 offset_t segment_start;
147
148 /* The packet queue. */
149 AVPacket **packets;
150 int num_packets;
151
152 /* have we already parse metadata/cues/clusters? */
153 int metadata_parsed;
154 int index_parsed;
155 int done;
156
157 /* The index for seeking. */
158 int num_indexes;
159 MatroskaDemuxIndex *index;
160
161 /* What to skip before effectively reading a packet. */
162 int skip_to_keyframe;
163 AVStream *skip_to_stream;
164} MatroskaDemuxContext;
165
166#define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
167
168/*
169 * The first few functions handle EBML file parsing. The rest
170 * is the document interpretation. Matroska really just is a
171 * EBML file.
172 */
173
174/*
175 * Return: the amount of levels in the hierarchy that the
176 * current element lies higher than the previous one.
177 * The opposite isn't done - that's auto-done using master
178 * element reading.
179 */
180
181static int
182ebml_read_element_level_up (MatroskaDemuxContext *matroska)
183{
184 ByteIOContext *pb = matroska->ctx->pb;
185 offset_t pos = url_ftell(pb);
186 int num = 0;
187
188 while (matroska->num_levels > 0) {
189 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
190
191 if (pos >= level->start + level->length) {
192 matroska->num_levels--;
193 num++;
194 } else {
195 break;
196 }
197 }
198
199 return num;
200}
201
202/*
203 * Read: an "EBML number", which is defined as a variable-length
204 * array of bytes. The first byte indicates the length by giving a
205 * number of 0-bits followed by a one. The position of the first
206 * "one" bit inside the first byte indicates the length of this
207 * number.
208 * Returns: num. of bytes read. < 0 on error.
209 */
210
211static int
212ebml_read_num (MatroskaDemuxContext *matroska,
213 int max_size,
214 uint64_t *number)
215{
216 ByteIOContext *pb = matroska->ctx->pb;
217 int len_mask = 0x80, read = 1, n = 1;
218 int64_t total = 0;
219
220 /* the first byte tells us the length in bytes - get_byte() can normally
221 * return 0, but since that's not a valid first ebmlID byte, we can
222 * use it safely here to catch EOS. */
223 if (!(total = get_byte(pb))) {
224 /* we might encounter EOS here */
225 if (!url_feof(pb)) {
226 offset_t pos = url_ftell(pb);
227 av_log(matroska->ctx, AV_LOG_ERROR,
228 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
229 pos, pos);
230 }
231 return AVERROR(EIO); /* EOS or actual I/O error */
232 }
233
234 /* get the length of the EBML number */
235 while (read <= max_size && !(total & len_mask)) {
236 read++;
237 len_mask >>= 1;
238 }
239 if (read > max_size) {
240 offset_t pos = url_ftell(pb) - 1;
241 av_log(matroska->ctx, AV_LOG_ERROR,
242 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
243 (uint8_t) total, pos, pos);
244 return AVERROR_INVALIDDATA;
245 }
246
247 /* read out length */
248 total &= ~len_mask;
249 while (n++ < read)
250 total = (total << 8) | get_byte(pb);
251
252 *number = total;
253
254 return read;
255}
256
257/*
258 * Read: the element content data ID.
259 * Return: the number of bytes read or < 0 on error.
260 */
261
262static int
263ebml_read_element_id (MatroskaDemuxContext *matroska,
264 uint32_t *id,
265 int *level_up)
266{
267 int read;
268 uint64_t total;
269
270 /* if we re-call this, use our cached ID */
271 if (matroska->peek_id != 0) {
272 if (level_up)
273 *level_up = 0;
274 *id = matroska->peek_id;
275 return 0;
276 }
277
278 /* read out the "EBML number", include tag in ID */
279 if ((read = ebml_read_num(matroska, 4, &total)) < 0)
280 return read;
281 *id = matroska->peek_id = total | (1 << (read * 7));
282
283 /* level tracking */
284 if (level_up)
285 *level_up = ebml_read_element_level_up(matroska);
286
287 return read;
288}
289
290/*
291 * Read: element content length.
292 * Return: the number of bytes read or < 0 on error.
293 */
294
295static int
296ebml_read_element_length (MatroskaDemuxContext *matroska,
297 uint64_t *length)
298{
299 /* clear cache since we're now beyond that data point */
300 matroska->peek_id = 0;
301
302 /* read out the "EBML number", include tag in ID */
303 return ebml_read_num(matroska, 8, length);
304}
305
306/*
307 * Return: the ID of the next element, or 0 on error.
308 * Level_up contains the amount of levels that this
309 * next element lies higher than the previous one.
310 */
311
312static uint32_t
313ebml_peek_id (MatroskaDemuxContext *matroska,
314 int *level_up)
315{
316 uint32_t id;
317
318 if (ebml_read_element_id(matroska, &id, level_up) < 0)
319 return 0;
320
321 return id;
322}
323
324/*
325 * Seek to a given offset.
326 * 0 is success, -1 is failure.
327 */
328
329static int
330ebml_read_seek (MatroskaDemuxContext *matroska,
331 offset_t offset)
332{
333 ByteIOContext *pb = matroska->ctx->pb;
334
335 /* clear ID cache, if any */
336 matroska->peek_id = 0;
337
338 return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
339}
340
341/*
342 * Skip the next element.
343 * 0 is success, -1 is failure.
344 */
345
346static int
347ebml_read_skip (MatroskaDemuxContext *matroska)
348{
349 ByteIOContext *pb = matroska->ctx->pb;
350 uint32_t id;
351 uint64_t length;
352 int res;
353
354 if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
355 (res = ebml_read_element_length(matroska, &length)) < 0)
356 return res;
357
358 url_fskip(pb, length);
359
360 return 0;
361}
362
363/*
364 * Read the next element as an unsigned int.
365 * 0 is success, < 0 is failure.
366 */
367
368static int
369ebml_read_uint (MatroskaDemuxContext *matroska,
370 uint32_t *id,
371 uint64_t *num)
372{
373 ByteIOContext *pb = matroska->ctx->pb;
374 int n = 0, size, res;
375 uint64_t rlength;
376
377 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
378 (res = ebml_read_element_length(matroska, &rlength)) < 0)
379 return res;
380 size = rlength;
381 if (size < 1 || size > 8) {
382 offset_t pos = url_ftell(pb);
383 av_log(matroska->ctx, AV_LOG_ERROR,
384 "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
385 size, pos, pos);
386 return AVERROR_INVALIDDATA;
387 }
388
389 /* big-endian ordening; build up number */
390 *num = 0;
391 while (n++ < size)
392 *num = (*num << 8) | get_byte(pb);
393
394 return 0;
395}
396
397/*
398 * Read the next element as a signed int.
399 * 0 is success, < 0 is failure.
400 */
401
402static int
403ebml_read_sint (MatroskaDemuxContext *matroska,
404 uint32_t *id,
405 int64_t *num)
406{
407 ByteIOContext *pb = matroska->ctx->pb;
408 int size, n = 1, negative = 0, res;
409 uint64_t rlength;
410
411 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
412 (res = ebml_read_element_length(matroska, &rlength)) < 0)
413 return res;
414 size = rlength;
415 if (size < 1 || size > 8) {
416 offset_t pos = url_ftell(pb);
417 av_log(matroska->ctx, AV_LOG_ERROR,
418 "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
419 size, pos, pos);
420 return AVERROR_INVALIDDATA;
421 }
422 if ((*num = get_byte(pb)) & 0x80) {
423 negative = 1;
424 *num &= ~0x80;
425 }
426 while (n++ < size)
427 *num = (*num << 8) | get_byte(pb);
428
429 /* make signed */
430 if (negative)
431 *num = *num - (1LL << ((8 * size) - 1));
432
433 return 0;
434}
435
436/*
437 * Read the next element as a float.
438 * 0 is success, < 0 is failure.
439 */
440
441static int
442ebml_read_float (MatroskaDemuxContext *matroska,
443 uint32_t *id,
444 double *num)
445{
446 ByteIOContext *pb = matroska->ctx->pb;
447 int size, res;
448 uint64_t rlength;
449
450 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
451 (res = ebml_read_element_length(matroska, &rlength)) < 0)
452 return res;
453 size = rlength;
454
455 if (size == 4) {
456 *num= av_int2flt(get_be32(pb));
457 } else if(size==8){
458 *num= av_int2dbl(get_be64(pb));
459 } else{
460 offset_t pos = url_ftell(pb);
461 av_log(matroska->ctx, AV_LOG_ERROR,
462 "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
463 size, pos, pos);
464 return AVERROR_INVALIDDATA;
465 }
466
467 return 0;
468}
469
470/*
471 * Read the next element as an ASCII string.
472 * 0 is success, < 0 is failure.
473 */
474
475static int
476ebml_read_ascii (MatroskaDemuxContext *matroska,
477 uint32_t *id,
478 char **str)
479{
480 ByteIOContext *pb = matroska->ctx->pb;
481 int size, res;
482 uint64_t rlength;
483
484 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
485 (res = ebml_read_element_length(matroska, &rlength)) < 0)
486 return res;
487 size = rlength;
488
489 /* ebml strings are usually not 0-terminated, so we allocate one
490 * byte more, read the string and NULL-terminate it ourselves. */
491 if (size < 0 || !(*str = av_malloc(size + 1))) {
492 av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
493 return AVERROR(ENOMEM);
494 }
495 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
496 offset_t pos = url_ftell(pb);
497 av_log(matroska->ctx, AV_LOG_ERROR,
498 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
499 av_free(*str);
500 return AVERROR(EIO);
501 }
502 (*str)[size] = '\0';
503
504 return 0;
505}
506
507/*
508 * Read the next element as a UTF-8 string.
509 * 0 is success, < 0 is failure.
510 */
511
512static int
513ebml_read_utf8 (MatroskaDemuxContext *matroska,
514 uint32_t *id,
515 char **str)
516{
517 return ebml_read_ascii(matroska, id, str);
518}
519
520/*
521 * Read the next element, but only the header. The contents
522 * are supposed to be sub-elements which can be read separately.
523 * 0 is success, < 0 is failure.
524 */
525
526static int
527ebml_read_master (MatroskaDemuxContext *matroska,
528 uint32_t *id)
529{
530 ByteIOContext *pb = matroska->ctx->pb;
531 uint64_t length;
532 MatroskaLevel *level;
533 int res;
534
535 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
536 (res = ebml_read_element_length(matroska, &length)) < 0)
537 return res;
538
539 /* protect... (Heaven forbids that the '>' is true) */
540 if (matroska->num_levels >= EBML_MAX_DEPTH) {
541 av_log(matroska->ctx, AV_LOG_ERROR,
542 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
543 return AVERROR(ENOSYS);
544 }
545
546 /* remember level */
547 level = &matroska->levels[matroska->num_levels++];
548 level->start = url_ftell(pb);
549 level->length = length;
550
551 return 0;
552}
553
554/*
555 * Read the next element as binary data.
556 * 0 is success, < 0 is failure.
557 */
558
559static int
560ebml_read_binary (MatroskaDemuxContext *matroska,
561 uint32_t *id,
562 uint8_t **binary,
563 int *size)
564{
565 ByteIOContext *pb = matroska->ctx->pb;
566 uint64_t rlength;
567 int res;
568
569 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
570 (res = ebml_read_element_length(matroska, &rlength)) < 0)
571 return res;
572 *size = rlength;
573
574 if (!(*binary = av_malloc(*size))) {
575 av_log(matroska->ctx, AV_LOG_ERROR,
576 "Memory allocation error\n");
577 return AVERROR(ENOMEM);
578 }
579
580 if (get_buffer(pb, *binary, *size) != *size) {
581 offset_t pos = url_ftell(pb);
582 av_log(matroska->ctx, AV_LOG_ERROR,
583 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
584 return AVERROR(EIO);
585 }
586
587 return 0;
588}
589
590/*
591 * Read signed/unsigned "EBML" numbers.
592 * Return: number of bytes processed, < 0 on error.
593 * XXX: use ebml_read_num().
594 */
595
596static int
597matroska_ebmlnum_uint (uint8_t *data,
598 uint32_t size,
599 uint64_t *num)
600{
601 int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
602 uint64_t total;
603
604 if (size <= 0)
605 return AVERROR_INVALIDDATA;
606
607 total = data[0];
608 while (read <= 8 && !(total & len_mask)) {
609 read++;
610 len_mask >>= 1;
611 }
612 if (read > 8)
613 return AVERROR_INVALIDDATA;
614
615 if ((total &= (len_mask - 1)) == len_mask - 1)
616 num_ffs++;
617 if (size < read)
618 return AVERROR_INVALIDDATA;
619 while (n < read) {
620 if (data[n] == 0xff)
621 num_ffs++;
622 total = (total << 8) | data[n];
623 n++;
624 }
625
626 if (read == num_ffs)
627 *num = (uint64_t)-1;
628 else
629 *num = total;
630
631 return read;
632}
633
634/*
635 * Same as above, but signed.
636 */
637
638static int
639matroska_ebmlnum_sint (uint8_t *data,
640 uint32_t size,
641 int64_t *num)
642{
643 uint64_t unum;
644 int res;
645
646 /* read as unsigned number first */
647 if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
648 return res;
649
650 /* make signed (weird way) */
651 if (unum == (uint64_t)-1)
652 *num = INT64_MAX;
653 else
654 *num = unum - ((1LL << ((7 * res) - 1)) - 1);
655
656 return res;
657}
658
659/*
660 * Read an EBML header.
661 * 0 is success, < 0 is failure.
662 */
663
664static int
665ebml_read_header (MatroskaDemuxContext *matroska,
666 char **doctype,
667 int *version)
668{
669 uint32_t id;
670 int level_up, res = 0;
671
672 /* default init */
673 if (doctype)
674 *doctype = NULL;
675 if (version)
676 *version = 1;
677
678 if (!(id = ebml_peek_id(matroska, &level_up)) ||
679 level_up != 0 || id != EBML_ID_HEADER) {
680 av_log(matroska->ctx, AV_LOG_ERROR,
681 "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
682 return AVERROR_INVALIDDATA;
683 }
684 if ((res = ebml_read_master(matroska, &id)) < 0)
685 return res;
686
687 while (res == 0) {
688 if (!(id = ebml_peek_id(matroska, &level_up)))
689 return AVERROR(EIO);
690
691 /* end-of-header */
692 if (level_up)
693 break;
694
695 switch (id) {
696 /* is our read version uptodate? */
697 case EBML_ID_EBMLREADVERSION: {
698 uint64_t num;
699
700 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
701 return res;
702 if (num > EBML_VERSION) {
703 av_log(matroska->ctx, AV_LOG_ERROR,
704 "EBML version %"PRIu64" (> %d) is not supported\n",
705 num, EBML_VERSION);
706 return AVERROR_INVALIDDATA;
707 }
708 break;
709 }
710
711 /* we only handle 8 byte lengths at max */
712 case EBML_ID_EBMLMAXSIZELENGTH: {
713 uint64_t num;
714
715 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
716 return res;
717 if (num > sizeof(uint64_t)) {
718 av_log(matroska->ctx, AV_LOG_ERROR,
719 "Integers of size %"PRIu64" (> %zd) not supported\n",
720 num, sizeof(uint64_t));
721 return AVERROR_INVALIDDATA;
722 }
723 break;
724 }
725
726 /* we handle 4 byte IDs at max */
727 case EBML_ID_EBMLMAXIDLENGTH: {
728 uint64_t num;
729
730 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
731 return res;
732 if (num > sizeof(uint32_t)) {
733 av_log(matroska->ctx, AV_LOG_ERROR,
734 "IDs of size %"PRIu64" (> %zu) not supported\n",
735 num, sizeof(uint32_t));
736 return AVERROR_INVALIDDATA;
737 }
738 break;
739 }
740
741 case EBML_ID_DOCTYPE: {
742 char *text;
743
744 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
745 return res;
746 if (doctype) {
747 if (*doctype)
748 av_free(*doctype);
749 *doctype = text;
750 } else
751 av_free(text);
752 break;
753 }
754
755 case EBML_ID_DOCTYPEREADVERSION: {
756 uint64_t num;
757
758 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
759 return res;
760 if (version)
761 *version = num;
762 break;
763 }
764
765 default:
766 av_log(matroska->ctx, AV_LOG_INFO,
767 "Unknown data type 0x%x in EBML header", id);
768 /* pass-through */
769
770 case EBML_ID_VOID:
771 /* we ignore these two, as they don't tell us anything we
772 * care about */
773 case EBML_ID_EBMLVERSION:
774 case EBML_ID_DOCTYPEVERSION:
775 res = ebml_read_skip (matroska);
776 break;
777 }
778 }
779
780 return 0;
781}
782
783
784static int
785matroska_find_track_by_num (MatroskaDemuxContext *matroska,
786 int num)
787{
788 int i;
789
790 for (i = 0; i < matroska->num_tracks; i++)
791 if (matroska->tracks[i]->num == num)
792 return i;
793
794 return -1;
795}
796
797
798/*
799 * Put one packet in an application-supplied AVPacket struct.
800 * Returns 0 on success or -1 on failure.
801 */
802
803static int
804matroska_deliver_packet (MatroskaDemuxContext *matroska,
805 AVPacket *pkt)
806{
807 if (matroska->num_packets > 0) {
808 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
809 av_free(matroska->packets[0]);
810 if (matroska->num_packets > 1) {
811 memmove(&matroska->packets[0], &matroska->packets[1],
812 (matroska->num_packets - 1) * sizeof(AVPacket *));
813 matroska->packets =
814 av_realloc(matroska->packets, (matroska->num_packets - 1) *
815 sizeof(AVPacket *));
816 } else {
817 av_freep(&matroska->packets);
818 }
819 matroska->num_packets--;
820 return 0;
821 }
822
823 return -1;
824}
825
826/*
827 * Put a packet into our internal queue. Will be delivered to the
828 * user/application during the next get_packet() call.
829 */
830
831static void
832matroska_queue_packet (MatroskaDemuxContext *matroska,
833 AVPacket *pkt)
834{
835 matroska->packets =
836 av_realloc(matroska->packets, (matroska->num_packets + 1) *
837 sizeof(AVPacket *));
838 matroska->packets[matroska->num_packets] = pkt;
839 matroska->num_packets++;
840}
841
842/*
843 * Free all packets in our internal queue.
844 */
845static void
846matroska_clear_queue (MatroskaDemuxContext *matroska)
847{
848 if (matroska->packets) {
849 int n;
850 for (n = 0; n < matroska->num_packets; n++) {
851 av_free_packet(matroska->packets[n]);
852 av_free(matroska->packets[n]);
853 }
854 av_free(matroska->packets);
855 matroska->packets = NULL;
856 matroska->num_packets = 0;
857 }
858}
859
860
861/*
862 * Autodetecting...
863 */
864
865static int
866matroska_probe (AVProbeData *p)
867{
868 uint64_t total = 0;
869 int len_mask = 0x80, size = 1, n = 1;
870 uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
871
872 /* ebml header? */
873 if (AV_RB32(p->buf) != EBML_ID_HEADER)
874 return 0;
875
876 /* length of header */
877 total = p->buf[4];
878 while (size <= 8 && !(total & len_mask)) {
879 size++;
880 len_mask >>= 1;
881 }
882 if (size > 8)
883 return 0;
884 total &= (len_mask - 1);
885 while (n < size)
886 total = (total << 8) | p->buf[4 + n++];
887
888 /* does the probe data contain the whole header? */
889 if (p->buf_size < 4 + size + total)
890 return 0;
891
892 /* the header must contain the document type 'matroska'. For now,
893 * we don't parse the whole header but simply check for the
894 * availability of that array of characters inside the header.
895 * Not fully fool-proof, but good enough. */
896 for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
897 if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
898 return AVPROBE_SCORE_MAX;
899
900 return 0;
901}
902
903/*
904 * From here on, it's all XML-style DTD stuff... Needs no comments.
905 */
906
907static int
908matroska_parse_info (MatroskaDemuxContext *matroska)
909{
910 int res = 0;
911 uint32_t id;
912
913 av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
914
915 while (res == 0) {
916 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
917 res = AVERROR(EIO);
918 break;
919 } else if (matroska->level_up) {
920 matroska->level_up--;
921 break;
922 }
923
924 switch (id) {
925 /* cluster timecode */
926 case MATROSKA_ID_TIMECODESCALE: {
927 uint64_t num;
928 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
929 break;
930 matroska->time_scale = num;
931 break;
932 }
933
934 case MATROSKA_ID_DURATION: {
935 double num;
936 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
937 break;
938 matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
939 break;
940 }
941
942 case MATROSKA_ID_TITLE: {
943 char *text;
944 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
945 break;
946 strncpy(matroska->ctx->title, text,
947 sizeof(matroska->ctx->title)-1);
948 av_free(text);
949 break;
950 }
951
952 default:
953 av_log(matroska->ctx, AV_LOG_INFO,
954 "Unknown entry 0x%x in info header\n", id);
955 /* fall-through */
956
957 case MATROSKA_ID_WRITINGAPP:
958 case MATROSKA_ID_MUXINGAPP:
959 case MATROSKA_ID_DATEUTC:
960 case MATROSKA_ID_SEGMENTUID:
961 case EBML_ID_VOID:
962 res = ebml_read_skip(matroska);
963 break;
964 }
965
966 if (matroska->level_up) {
967 matroska->level_up--;
968 break;
969 }
970 }
971
972 return res;
973}
974
975static int
976matroska_decode_buffer(uint8_t** buf, int* buf_size, MatroskaTrack *track)
977{
978 uint8_t* data = *buf;
979 int isize = *buf_size;
980 uint8_t* pkt_data = NULL;
981 int pkt_size = isize;
982 int result = 0;
983 int olen;
984
985 switch (track->encoding_algo) {
986 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
987 return track->encoding_settings_len;
988 case MATROSKA_TRACK_ENCODING_COMP_LZO:
989 do {
990 olen = pkt_size *= 3;
991 pkt_data = av_realloc(pkt_data,
992 pkt_size+LZO_OUTPUT_PADDING);
993 result = lzo1x_decode(pkt_data, &olen, data, &isize);
994 } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
995 if (result)
996 goto failed;
997 pkt_size -= olen;
998 break;
999#ifdef CONFIG_ZLIB
1000 case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1001 z_stream zstream = {0};
1002 if (inflateInit(&zstream) != Z_OK)
1003 return -1;
1004 zstream.next_in = data;
1005 zstream.avail_in = isize;
1006 do {
1007 pkt_size *= 3;
1008 pkt_data = av_realloc(pkt_data, pkt_size);
1009 zstream.avail_out = pkt_size - zstream.total_out;
1010 zstream.next_out = pkt_data + zstream.total_out;
1011 result = inflate(&zstream, Z_NO_FLUSH);
1012 } while (result==Z_OK && pkt_size<10000000);
1013 pkt_size = zstream.total_out;
1014 inflateEnd(&zstream);
1015 if (result != Z_STREAM_END)
1016 goto failed;
1017 break;
1018 }
1019#endif
1020#ifdef CONFIG_BZLIB
1021 case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1022 bz_stream bzstream = {0};
1023 if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1024 return -1;
1025 bzstream.next_in = data;
1026 bzstream.avail_in = isize;
1027 do {
1028 pkt_size *= 3;
1029 pkt_data = av_realloc(pkt_data, pkt_size);
1030 bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1031 bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1032 result = BZ2_bzDecompress(&bzstream);
1033 } while (result==BZ_OK && pkt_size<10000000);
1034 pkt_size = bzstream.total_out_lo32;
1035 BZ2_bzDecompressEnd(&bzstream);
1036 if (result != BZ_STREAM_END)
1037 goto failed;
1038 break;
1039 }
1040#endif
1041 }
1042
1043 *buf = pkt_data;
1044 *buf_size = pkt_size;
1045 return 0;
1046 failed:
1047 av_free(pkt_data);
1048 return -1;
1049}
1050
1051static int
1052matroska_add_stream (MatroskaDemuxContext *matroska)
1053{
1054 int res = 0;
1055 uint32_t id;
1056 MatroskaTrack *track;
1057
1058 /* start with the master */
1059 if ((res = ebml_read_master(matroska, &id)) < 0)
1060 return res;
1061
1062 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
1063
1064 /* Allocate a generic track. */
1065 track = av_mallocz(MAX_TRACK_SIZE);
1066 track->time_scale = 1.0;
1067 strcpy(track->language, "eng");
1068
1069 /* try reading the trackentry headers */
1070 while (res == 0) {
1071 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1072 res = AVERROR(EIO);
1073 break;
1074 } else if (matroska->level_up > 0) {
1075 matroska->level_up--;
1076 break;
1077 }
1078
1079 switch (id) {
1080 /* track number (unique stream ID) */
1081 case MATROSKA_ID_TRACKNUMBER: {
1082 uint64_t num;
1083 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1084 break;
1085 track->num = num;
1086 break;
1087 }
1088
1089 /* track UID (unique identifier) */
1090 case MATROSKA_ID_TRACKUID: {
1091 uint64_t num;
1092 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1093 break;
1094 track->uid = num;
1095 break;
1096 }
1097
1098 /* track type (video, audio, combined, subtitle, etc.) */
1099 case MATROSKA_ID_TRACKTYPE: {
1100 uint64_t num;
1101 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1102 break;
1103 if (track->type && track->type != num) {
1104 av_log(matroska->ctx, AV_LOG_INFO,
1105 "More than one tracktype in an entry - skip\n");
1106 break;
1107 }
1108 track->type = num;
1109
1110 switch (track->type) {
1111 case MATROSKA_TRACK_TYPE_VIDEO:
1112 case MATROSKA_TRACK_TYPE_AUDIO:
1113 case MATROSKA_TRACK_TYPE_SUBTITLE:
1114 break;
1115 case MATROSKA_TRACK_TYPE_COMPLEX:
1116 case MATROSKA_TRACK_TYPE_LOGO:
1117 case MATROSKA_TRACK_TYPE_CONTROL:
1118 default:
1119 av_log(matroska->ctx, AV_LOG_INFO,
1120 "Unknown or unsupported track type 0x%x\n",
1121 track->type);
1122 track->type = MATROSKA_TRACK_TYPE_NONE;
1123 break;
1124 }
1125 break;
1126 }
1127
1128 /* tracktype specific stuff for video */
1129 case MATROSKA_ID_TRACKVIDEO: {
1130 MatroskaVideoTrack *videotrack;
1131 if (!track->type)
1132 track->type = MATROSKA_TRACK_TYPE_VIDEO;
1133 if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1134 av_log(matroska->ctx, AV_LOG_INFO,
1135 "video data in non-video track - ignoring\n");
1136 res = AVERROR_INVALIDDATA;
1137 break;
1138 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1139 break;
1140 videotrack = (MatroskaVideoTrack *)track;
1141
1142 while (res == 0) {
1143 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1144 res = AVERROR(EIO);
1145 break;
1146 } else if (matroska->level_up > 0) {
1147 matroska->level_up--;
1148 break;
1149 }
1150
1151 switch (id) {
1152 /* fixme, this should be one-up, but I get it here */
1153 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1154 uint64_t num;
1155 if ((res = ebml_read_uint (matroska, &id,
1156 &num)) < 0)
1157 break;
1158 track->default_duration = num;
1159 break;
1160 }
1161
1162 /* video framerate */
1163 case MATROSKA_ID_VIDEOFRAMERATE: {
1164 double num;
1165 if ((res = ebml_read_float(matroska, &id,
1166 &num)) < 0)
1167 break;
1168 if (!track->default_duration)
1169 track->default_duration = 1000000000/num;
1170 break;
1171 }
1172
1173 /* width of the size to display the video at */
1174 case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1175 uint64_t num;
1176 if ((res = ebml_read_uint(matroska, &id,
1177 &num)) < 0)
1178 break;
1179 videotrack->display_width = num;
1180 break;
1181 }
1182
1183 /* height of the size to display the video at */
1184 case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1185 uint64_t num;
1186 if ((res = ebml_read_uint(matroska, &id,
1187 &num)) < 0)
1188 break;
1189 videotrack->display_height = num;
1190 break;
1191 }
1192
1193 /* width of the video in the file */
1194 case MATROSKA_ID_VIDEOPIXELWIDTH: {
1195 uint64_t num;
1196 if ((res = ebml_read_uint(matroska, &id,
1197 &num)) < 0)
1198 break;
1199 videotrack->pixel_width = num;
1200 break;
1201 }
1202
1203 /* height of the video in the file */
1204 case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1205 uint64_t num;
1206 if ((res = ebml_read_uint(matroska, &id,
1207 &num)) < 0)
1208 break;
1209 videotrack->pixel_height = num;
1210 break;
1211 }
1212
1213 /* whether the video is interlaced */
1214 case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1215 uint64_t num;
1216 if ((res = ebml_read_uint(matroska, &id,
1217 &num)) < 0)
1218 break;
1219 if (num)
1220 track->flags |=
1221 MATROSKA_VIDEOTRACK_INTERLACED;
1222 else
1223 track->flags &=
1224 ~MATROSKA_VIDEOTRACK_INTERLACED;
1225 break;
1226 }
1227
1228 /* colorspace (only matters for raw video)
1229 * fourcc */
1230 case MATROSKA_ID_VIDEOCOLORSPACE: {
1231 uint64_t num;
1232 if ((res = ebml_read_uint(matroska, &id,
1233 &num)) < 0)
1234 break;
1235 videotrack->fourcc = num;
1236 break;
1237 }
1238
1239 default:
1240 av_log(matroska->ctx, AV_LOG_INFO,
1241 "Unknown video track header entry "
1242 "0x%x - ignoring\n", id);
1243 /* pass-through */
1244
1245 case MATROSKA_ID_VIDEOSTEREOMODE:
1246 case MATROSKA_ID_VIDEOASPECTRATIO:
1247 case EBML_ID_VOID:
1248 res = ebml_read_skip(matroska);
1249 break;
1250 }
1251
1252 if (matroska->level_up) {
1253 matroska->level_up--;
1254 break;
1255 }
1256 }
1257 break;
1258 }
1259
1260 /* tracktype specific stuff for audio */
1261 case MATROSKA_ID_TRACKAUDIO: {
1262 MatroskaAudioTrack *audiotrack;
1263 if (!track->type)
1264 track->type = MATROSKA_TRACK_TYPE_AUDIO;
1265 if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1266 av_log(matroska->ctx, AV_LOG_INFO,
1267 "audio data in non-audio track - ignoring\n");
1268 res = AVERROR_INVALIDDATA;
1269 break;
1270 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1271 break;
1272 audiotrack = (MatroskaAudioTrack *)track;
1273 audiotrack->channels = 1;
1274 audiotrack->samplerate = 8000;
1275
1276 while (res == 0) {
1277 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1278 res = AVERROR(EIO);
1279 break;
1280 } else if (matroska->level_up > 0) {
1281 matroska->level_up--;
1282 break;
1283 }
1284
1285 switch (id) {
1286 /* samplerate */
1287 case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1288 double num;
1289 if ((res = ebml_read_float(matroska, &id,
1290 &num)) < 0)
1291 break;
1292 audiotrack->internal_samplerate =
1293 audiotrack->samplerate = num;
1294 break;
1295 }
1296
1297 case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1298 double num;
1299 if ((res = ebml_read_float(matroska, &id,
1300 &num)) < 0)
1301 break;
1302 audiotrack->samplerate = num;
1303 break;
1304 }
1305
1306 /* bitdepth */
1307 case MATROSKA_ID_AUDIOBITDEPTH: {
1308 uint64_t num;
1309 if ((res = ebml_read_uint(matroska, &id,
1310 &num)) < 0)
1311 break;
1312 audiotrack->bitdepth = num;
1313 break;
1314 }
1315
1316 /* channels */
1317 case MATROSKA_ID_AUDIOCHANNELS: {
1318 uint64_t num;
1319 if ((res = ebml_read_uint(matroska, &id,
1320 &num)) < 0)
1321 break;
1322 audiotrack->channels = num;
1323 break;
1324 }
1325
1326 default:
1327 av_log(matroska->ctx, AV_LOG_INFO,
1328 "Unknown audio track header entry "
1329 "0x%x - ignoring\n", id);
1330 /* pass-through */
1331
1332 case EBML_ID_VOID:
1333 res = ebml_read_skip(matroska);
1334 break;
1335 }
1336
1337 if (matroska->level_up) {
1338 matroska->level_up--;
1339 break;
1340 }
1341 }
1342 break;
1343 }
1344
1345 /* codec identifier */
1346 case MATROSKA_ID_CODECID: {
1347 char *text;
1348 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1349 break;
1350 track->codec_id = text;
1351 break;
1352 }
1353
1354 /* codec private data */
1355 case MATROSKA_ID_CODECPRIVATE: {
1356 uint8_t *data;
1357 int size;
1358 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1359 break;
1360 track->codec_priv = data;
1361 track->codec_priv_size = size;
1362 break;
1363 }
1364
1365 /* name of this track */
1366 case MATROSKA_ID_TRACKNAME: {
1367 char *text;
1368 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1369 break;
1370 track->name = text;
1371 break;
1372 }
1373
1374 /* language (matters for audio/subtitles, mostly) */
1375 case MATROSKA_ID_TRACKLANGUAGE: {
1376 char *text, *end;
1377 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1378 break;
1379 if ((end = strchr(text, '-')))
1380 *end = '\0';
1381 if (strlen(text) == 3)
1382 strcpy(track->language, text);
1383 av_free(text);
1384 break;
1385 }
1386
1387 /* whether this is actually used */
1388 case MATROSKA_ID_TRACKFLAGENABLED: {
1389 uint64_t num;
1390 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1391 break;
1392 if (num)
1393 track->flags |= MATROSKA_TRACK_ENABLED;
1394 else
1395 track->flags &= ~MATROSKA_TRACK_ENABLED;
1396 break;
1397 }
1398
1399 /* whether it's the default for this track type */
1400 case MATROSKA_ID_TRACKFLAGDEFAULT: {
1401 uint64_t num;
1402 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1403 break;
1404 if (num)
1405 track->flags |= MATROSKA_TRACK_DEFAULT;
1406 else
1407 track->flags &= ~MATROSKA_TRACK_DEFAULT;
1408 break;
1409 }
1410
1411 /* lacing (like MPEG, where blocks don't end/start on frame
1412 * boundaries) */
1413 case MATROSKA_ID_TRACKFLAGLACING: {
1414 uint64_t num;
1415 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1416 break;
1417 if (num)
1418 track->flags |= MATROSKA_TRACK_LACING;
1419 else
1420 track->flags &= ~MATROSKA_TRACK_LACING;
1421 break;
1422 }
1423
1424 /* default length (in time) of one data block in this track */
1425 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1426 uint64_t num;
1427 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1428 break;
1429 track->default_duration = num;
1430 break;
1431 }
1432
1433 case MATROSKA_ID_TRACKCONTENTENCODINGS: {
1434 if ((res = ebml_read_master(matroska, &id)) < 0)
1435 break;
1436
1437 while (res == 0) {
1438 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1439 res = AVERROR(EIO);
1440 break;
1441 } else if (matroska->level_up > 0) {
1442 matroska->level_up--;
1443 break;
1444 }
1445
1446 switch (id) {
1447 case MATROSKA_ID_TRACKCONTENTENCODING: {
1448 int encoding_scope = 1;
1449 if ((res = ebml_read_master(matroska, &id)) < 0)
1450 break;
1451
1452 while (res == 0) {
1453 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1454 res = AVERROR(EIO);
1455 break;
1456 } else if (matroska->level_up > 0) {
1457 matroska->level_up--;
1458 break;
1459 }
1460
1461 switch (id) {
1462 case MATROSKA_ID_ENCODINGSCOPE: {
1463 uint64_t num;
1464 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1465 break;
1466 encoding_scope = num;
1467 break;
1468 }
1469
1470 case MATROSKA_ID_ENCODINGTYPE: {
1471 uint64_t num;
1472 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1473 break;
1474 if (num)
1475 av_log(matroska->ctx, AV_LOG_ERROR,
1476 "Unsupported encoding type");
1477 break;
1478 }
1479
1480 case MATROSKA_ID_ENCODINGCOMPRESSION: {
1481 if ((res = ebml_read_master(matroska, &id)) < 0)
1482 break;
1483
1484 while (res == 0) {
1485 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1486 res = AVERROR(EIO);
1487 break;
1488 } else if (matroska->level_up > 0) {
1489 matroska->level_up--;
1490 break;
1491 }
1492
1493 switch (id) {
1494 case MATROSKA_ID_ENCODINGCOMPALGO: {
1495 uint64_t num;
1496 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1497 break;
1498 if (num != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1499#ifdef CONFIG_ZLIB
1500 num != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1501#endif
1502#ifdef CONFIG_BZLIB
1503 num != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1504#endif
1505 num != MATROSKA_TRACK_ENCODING_COMP_LZO)
1506 av_log(matroska->ctx, AV_LOG_ERROR,
1507 "Unsupported compression algo\n");
1508 track->encoding_algo = num;
1509 break;
1510 }
1511
1512 case MATROSKA_ID_ENCODINGCOMPSETTINGS: {
1513 uint8_t *data;
1514 int size;
1515 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1516 break;
1517 track->encoding_settings = data;
1518 track->encoding_settings_len = size;
1519 break;
1520 }
1521
1522 default:
1523 av_log(matroska->ctx, AV_LOG_INFO,
1524 "Unknown compression header entry "
1525 "0x%x - ignoring\n", id);
1526 /* pass-through */
1527
1528 case EBML_ID_VOID:
1529 res = ebml_read_skip(matroska);
1530 break;
1531 }
1532
1533 if (matroska->level_up) {
1534 matroska->level_up--;
1535 break;
1536 }
1537 }
1538 break;
1539 }
1540
1541 default:
1542 av_log(matroska->ctx, AV_LOG_INFO,
1543 "Unknown content encoding header entry "
1544 "0x%x - ignoring\n", id);
1545 /* pass-through */
1546
1547 case EBML_ID_VOID:
1548 res = ebml_read_skip(matroska);
1549 break;
1550 }
1551
1552 if (matroska->level_up) {
1553 matroska->level_up--;
1554 break;
1555 }
1556 }
1557
1558 track->encoding_scope = encoding_scope;
1559 break;
1560 }
1561
1562 default:
1563 av_log(matroska->ctx, AV_LOG_INFO,
1564 "Unknown content encodings header entry "
1565 "0x%x - ignoring\n", id);
1566 /* pass-through */
1567
1568 case EBML_ID_VOID:
1569 res = ebml_read_skip(matroska);
1570 break;
1571 }
1572
1573 if (matroska->level_up) {
1574 matroska->level_up--;
1575 break;
1576 }
1577 }
1578 break;
1579 }
1580
1581 case MATROSKA_ID_TRACKTIMECODESCALE: {
1582 double num;
1583 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
1584 break;
1585 track->time_scale = num;
1586 break;
1587 }
1588
1589 default:
1590 av_log(matroska->ctx, AV_LOG_INFO,
1591 "Unknown track header entry 0x%x - ignoring\n", id);
1592 /* pass-through */
1593
1594 case EBML_ID_VOID:
1595 /* we ignore these because they're nothing useful. */
1596 case MATROSKA_ID_TRACKFLAGFORCED:
1597 case MATROSKA_ID_CODECNAME:
1598 case MATROSKA_ID_CODECDECODEALL:
1599 case MATROSKA_ID_CODECINFOURL:
1600 case MATROSKA_ID_CODECDOWNLOADURL:
1601 case MATROSKA_ID_TRACKMINCACHE:
1602 case MATROSKA_ID_TRACKMAXCACHE:
1603 res = ebml_read_skip(matroska);
1604 break;
1605 }
1606
1607 if (matroska->level_up) {
1608 matroska->level_up--;
1609 break;
1610 }
1611 }
1612
1613 if (track->codec_priv_size && track->encoding_scope & 2) {
1614 uint8_t *orig_priv = track->codec_priv;
1615 int offset = matroska_decode_buffer(&track->codec_priv,
1616 &track->codec_priv_size, track);
1617 if (offset > 0) {
1618 track->codec_priv = av_malloc(track->codec_priv_size + offset);
1619 memcpy(track->codec_priv, track->encoding_settings, offset);
1620 memcpy(track->codec_priv+offset, orig_priv, track->codec_priv_size);
1621 track->codec_priv_size += offset;
1622 av_free(orig_priv);
1623 } else if (!offset) {
1624 av_free(orig_priv);
1625 } else
1626 av_log(matroska->ctx, AV_LOG_ERROR,
1627 "Failed to decode codec private data\n");
1628 }
1629
1630 if (track->type && matroska->num_tracks < ARRAY_SIZE(matroska->tracks)) {
1631 matroska->tracks[matroska->num_tracks++] = track;
1632 } else {
1633 av_free(track);
1634 }
1635 return res;
1636}
1637
1638static int
1639matroska_parse_tracks (MatroskaDemuxContext *matroska)
1640{
1641 int res = 0;
1642 uint32_t id;
1643
1644 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1645
1646 while (res == 0) {
1647 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1648 res = AVERROR(EIO);
1649 break;
1650 } else if (matroska->level_up) {
1651 matroska->level_up--;
1652 break;
1653 }
1654
1655 switch (id) {
1656 /* one track within the "all-tracks" header */
1657 case MATROSKA_ID_TRACKENTRY:
1658 res = matroska_add_stream(matroska);
1659 break;
1660
1661 default:
1662 av_log(matroska->ctx, AV_LOG_INFO,
1663 "Unknown entry 0x%x in track header\n", id);
1664 /* fall-through */
1665
1666 case EBML_ID_VOID:
1667 res = ebml_read_skip(matroska);
1668 break;
1669 }
1670
1671 if (matroska->level_up) {
1672 matroska->level_up--;
1673 break;
1674 }
1675 }
1676
1677 return res;
1678}
1679
1680static int
1681matroska_parse_index (MatroskaDemuxContext *matroska)
1682{
1683 int res = 0;
1684 uint32_t id;
1685 MatroskaDemuxIndex idx;
1686
1687 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1688
1689 while (res == 0) {
1690 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1691 res = AVERROR(EIO);
1692 break;
1693 } else if (matroska->level_up) {
1694 matroska->level_up--;
1695 break;
1696 }
1697
1698 switch (id) {
1699 /* one single index entry ('point') */
1700 case MATROSKA_ID_POINTENTRY:
1701 if ((res = ebml_read_master(matroska, &id)) < 0)
1702 break;
1703
1704 /* in the end, we hope to fill one entry with a
1705 * timestamp, a file position and a tracknum */
1706 idx.pos = (uint64_t) -1;
1707 idx.time = (uint64_t) -1;
1708 idx.track = (uint16_t) -1;
1709
1710 while (res == 0) {
1711 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1712 res = AVERROR(EIO);
1713 break;
1714 } else if (matroska->level_up) {
1715 matroska->level_up--;
1716 break;
1717 }
1718
1719 switch (id) {
1720 /* one single index entry ('point') */
1721 case MATROSKA_ID_CUETIME: {
1722 uint64_t time;
1723 if ((res = ebml_read_uint(matroska, &id,
1724 &time)) < 0)
1725 break;
1726 idx.time = time * matroska->time_scale;
1727 break;
1728 }
1729
1730 /* position in the file + track to which it
1731 * belongs */
1732 case MATROSKA_ID_CUETRACKPOSITION:
1733 if ((res = ebml_read_master(matroska, &id)) < 0)
1734 break;
1735
1736 while (res == 0) {
1737 if (!(id = ebml_peek_id (matroska,
1738 &matroska->level_up))) {
1739 res = AVERROR(EIO);
1740 break;
1741 } else if (matroska->level_up) {
1742 matroska->level_up--;
1743 break;
1744 }
1745
1746 switch (id) {
1747 /* track number */
1748 case MATROSKA_ID_CUETRACK: {
1749 uint64_t num;
1750 if ((res = ebml_read_uint(matroska,
1751 &id, &num)) < 0)
1752 break;
1753 idx.track = num;
1754 break;
1755 }
1756
1757 /* position in file */
1758 case MATROSKA_ID_CUECLUSTERPOSITION: {
1759 uint64_t num;
1760 if ((res = ebml_read_uint(matroska,
1761 &id, &num)) < 0)
1762 break;
1763 idx.pos = num+matroska->segment_start;
1764 break;
1765 }
1766
1767 default:
1768 av_log(matroska->ctx, AV_LOG_INFO,
1769 "Unknown entry 0x%x in "
1770 "CuesTrackPositions\n", id);
1771 /* fall-through */
1772
1773 case EBML_ID_VOID:
1774 res = ebml_read_skip(matroska);
1775 break;
1776 }
1777
1778 if (matroska->level_up) {
1779 matroska->level_up--;
1780 break;
1781 }
1782 }
1783
1784 break;
1785
1786 default:
1787 av_log(matroska->ctx, AV_LOG_INFO,
1788 "Unknown entry 0x%x in cuespoint "
1789 "index\n", id);
1790 /* fall-through */
1791
1792 case EBML_ID_VOID:
1793 res = ebml_read_skip(matroska);
1794 break;
1795 }
1796
1797 if (matroska->level_up) {
1798 matroska->level_up--;
1799 break;
1800 }
1801 }
1802
1803 /* so let's see if we got what we wanted */
1804 if (idx.pos != (uint64_t) -1 &&
1805 idx.time != (uint64_t) -1 &&
1806 idx.track != (uint16_t) -1) {
1807 if (matroska->num_indexes % 32 == 0) {
1808 /* re-allocate bigger index */
1809 matroska->index =
1810 av_realloc(matroska->index,
1811 (matroska->num_indexes + 32) *
1812 sizeof(MatroskaDemuxIndex));
1813 }
1814 matroska->index[matroska->num_indexes] = idx;
1815 matroska->num_indexes++;
1816 }
1817 break;
1818
1819 default:
1820 av_log(matroska->ctx, AV_LOG_INFO,
1821 "Unknown entry 0x%x in cues header\n", id);
1822 /* fall-through */
1823
1824 case EBML_ID_VOID:
1825 res = ebml_read_skip(matroska);
1826 break;
1827 }
1828
1829 if (matroska->level_up) {
1830 matroska->level_up--;
1831 break;
1832 }
1833 }
1834
1835 return res;
1836}
1837
1838static int
1839matroska_parse_metadata (MatroskaDemuxContext *matroska)
1840{
1841 int res = 0;
1842 uint32_t id;
1843
1844 while (res == 0) {
1845 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1846 res = AVERROR(EIO);
1847 break;
1848 } else if (matroska->level_up) {
1849 matroska->level_up--;
1850 break;
1851 }
1852
1853 switch (id) {
1854 /* Hm, this is unsupported... */
1855 default:
1856 av_log(matroska->ctx, AV_LOG_INFO,
1857 "Unknown entry 0x%x in metadata header\n", id);
1858 /* fall-through */
1859
1860 case EBML_ID_VOID:
1861 res = ebml_read_skip(matroska);
1862 break;
1863 }
1864
1865 if (matroska->level_up) {
1866 matroska->level_up--;
1867 break;
1868 }
1869 }
1870
1871 return res;
1872}
1873
1874static int
1875matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1876{
1877 int res = 0;
1878 uint32_t id;
1879
1880 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1881
1882 while (res == 0) {
1883 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1884 res = AVERROR(EIO);
1885 break;
1886 } else if (matroska->level_up) {
1887 matroska->level_up--;
1888 break;
1889 }
1890
1891 switch (id) {
1892 case MATROSKA_ID_SEEKENTRY: {
1893 uint32_t seek_id = 0, peek_id_cache = 0;
1894 uint64_t seek_pos = (uint64_t) -1, t;
1895 int dummy_level = 0;
1896
1897 if ((res = ebml_read_master(matroska, &id)) < 0)
1898 break;
1899
1900 while (res == 0) {
1901 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1902 res = AVERROR(EIO);
1903 break;
1904 } else if (matroska->level_up) {
1905 matroska->level_up--;
1906 break;
1907 }
1908
1909 switch (id) {
1910 case MATROSKA_ID_SEEKID:
1911 res = ebml_read_uint(matroska, &id, &t);
1912 seek_id = t;
1913 break;
1914
1915 case MATROSKA_ID_SEEKPOSITION:
1916 res = ebml_read_uint(matroska, &id, &seek_pos);
1917 break;
1918
1919 default:
1920 av_log(matroska->ctx, AV_LOG_INFO,
1921 "Unknown seekhead ID 0x%x\n", id);
1922 /* fall-through */
1923
1924 case EBML_ID_VOID:
1925 res = ebml_read_skip(matroska);
1926 break;
1927 }
1928
1929 if (matroska->level_up) {
1930 matroska->level_up--;
1931 break;
1932 }
1933 }
1934
1935 if (!seek_id || seek_pos == (uint64_t) -1) {
1936 av_log(matroska->ctx, AV_LOG_INFO,
1937 "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1938 seek_id, seek_pos);
1939 break;
1940 }
1941
1942 switch (seek_id) {
1943 case MATROSKA_ID_CUES:
1944 case MATROSKA_ID_TAGS: {
1945 uint32_t level_up = matroska->level_up;
1946 offset_t before_pos;
1947 uint64_t length;
1948 MatroskaLevel level;
1949
1950 /* remember the peeked ID and the current position */
1951 peek_id_cache = matroska->peek_id;
1952 before_pos = url_ftell(matroska->ctx->pb);
1953
1954 /* seek */
1955 if ((res = ebml_read_seek(matroska, seek_pos +
1956 matroska->segment_start)) < 0)
1957 goto finish;
1958
1959 /* we don't want to lose our seekhead level, so we add
1960 * a dummy. This is a crude hack. */
1961 if (matroska->num_levels == EBML_MAX_DEPTH) {
1962 av_log(matroska->ctx, AV_LOG_INFO,
1963 "Max EBML element depth (%d) reached, "
1964 "cannot parse further.\n", EBML_MAX_DEPTH);
1965 return AVERROR_UNKNOWN;
1966 }
1967
1968 level.start = 0;
1969 level.length = (uint64_t)-1;
1970 matroska->levels[matroska->num_levels] = level;
1971 matroska->num_levels++;
1972 dummy_level = 1;
1973
1974 /* check ID */
1975 if (!(id = ebml_peek_id (matroska,
1976 &matroska->level_up)))
1977 goto finish;
1978 if (id != seek_id) {
1979 av_log(matroska->ctx, AV_LOG_INFO,
1980 "We looked for ID=0x%x but got "
1981 "ID=0x%x (pos=%"PRIu64")",
1982 seek_id, id, seek_pos +
1983 matroska->segment_start);
1984 goto finish;
1985 }
1986
1987 /* read master + parse */
1988 if ((res = ebml_read_master(matroska, &id)) < 0)
1989 goto finish;
1990 switch (id) {
1991 case MATROSKA_ID_CUES:
1992 if (!(res = matroska_parse_index(matroska)) ||
1993 url_feof(matroska->ctx->pb)) {
1994 matroska->index_parsed = 1;
1995 res = 0;
1996 }
1997 break;
1998 case MATROSKA_ID_TAGS:
1999 if (!(res = matroska_parse_metadata(matroska)) ||
2000 url_feof(matroska->ctx->pb)) {
2001 matroska->metadata_parsed = 1;
2002 res = 0;
2003 }
2004 break;
2005 }
2006
2007 finish:
2008 /* remove dummy level */
2009 if (dummy_level)
2010 while (matroska->num_levels) {
2011 matroska->num_levels--;
2012 length =
2013 matroska->levels[matroska->num_levels].length;
2014 if (length == (uint64_t)-1)
2015 break;
2016 }
2017
2018 /* seek back */
2019 if ((res = ebml_read_seek(matroska, before_pos)) < 0)
2020 return res;
2021 matroska->peek_id = peek_id_cache;
2022 matroska->level_up = level_up;
2023 break;
2024 }
2025
2026 default:
2027 av_log(matroska->ctx, AV_LOG_INFO,
2028 "Ignoring seekhead entry for ID=0x%x\n",
2029 seek_id);
2030 break;
2031 }
2032
2033 break;
2034 }
2035
2036 default:
2037 av_log(matroska->ctx, AV_LOG_INFO,
2038 "Unknown seekhead ID 0x%x\n", id);
2039 /* fall-through */
2040
2041 case EBML_ID_VOID:
2042 res = ebml_read_skip(matroska);
2043 break;
2044 }
2045
2046 if (matroska->level_up) {
2047 matroska->level_up--;
2048 break;
2049 }
2050 }
2051
2052 return res;
2053}
2054
2055static int
2056matroska_parse_attachments(AVFormatContext *s)
2057{
2058 MatroskaDemuxContext *matroska = s->priv_data;
2059 int res = 0;
2060 uint32_t id;
2061
2062 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing attachments...\n");
2063
2064 while (res == 0) {
2065 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2066 res = AVERROR(EIO);
2067 break;
2068 } else if (matroska->level_up) {
2069 matroska->level_up--;
2070 break;
2071 }
2072
2073 switch (id) {
2074 case MATROSKA_ID_ATTACHEDFILE: {
2075 char* name = NULL;
2076 char* mime = NULL;
2077 uint8_t* data = NULL;
2078 int i, data_size = 0;
2079 AVStream *st;
2080
2081 if ((res = ebml_read_master(matroska, &id)) < 0)
2082 break;
2083
2084 while (res == 0) {
2085 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2086 res = AVERROR(EIO);
2087 break;
2088 } else if (matroska->level_up) {
2089 matroska->level_up--;
2090 break;
2091 }
2092
2093 switch (id) {
2094 case MATROSKA_ID_FILENAME:
2095 res = ebml_read_utf8 (matroska, &id, &name);
2096 break;
2097
2098 case MATROSKA_ID_FILEMIMETYPE:
2099 res = ebml_read_ascii (matroska, &id, &mime);
2100 break;
2101
2102 case MATROSKA_ID_FILEDATA:
2103 res = ebml_read_binary(matroska, &id, &data, &data_size);
2104 break;
2105
2106 default:
2107 av_log(matroska->ctx, AV_LOG_INFO,
2108 "Unknown attachedfile ID 0x%x\n", id);
2109 case MATROSKA_ID_FILEUID:
2110 case EBML_ID_VOID:
2111 res = ebml_read_skip(matroska);
2112 break;
2113 }
2114
2115 if (matroska->level_up) {
2116 matroska->level_up--;
2117 break;
2118 }
2119 }
2120
2121 if (!(name && mime && data && data_size > 0)) {
2122 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
2123 break;
2124 }
2125
2126 st = av_new_stream(s, matroska->num_streams++);
2127 if (st == NULL)
2128 return AVERROR(ENOMEM);
2129 st->filename = av_strdup(name);
2130 st->codec->codec_id = CODEC_ID_NONE;
2131 st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
2132 st->codec->extradata = av_malloc(data_size);
2133 if(st->codec->extradata == NULL)
2134 return AVERROR(ENOMEM);
2135 st->codec->extradata_size = data_size;
2136 memcpy(st->codec->extradata, data, data_size);
2137
2138 for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
2139 if (!strncmp(ff_mkv_mime_tags[i].str, mime,
2140 strlen(ff_mkv_mime_tags[i].str))) {
2141 st->codec->codec_id = ff_mkv_mime_tags[i].id;
2142 break;
2143 }
2144 }
2145
2146 av_log(matroska->ctx, AV_LOG_DEBUG, "new attachment: %s, %s, size %d \n", name, mime, data_size);
2147 break;
2148 }
2149
2150 default:
2151 av_log(matroska->ctx, AV_LOG_INFO,
2152 "Unknown attachments ID 0x%x\n", id);
2153 /* fall-through */
2154
2155 case EBML_ID_VOID:
2156 res = ebml_read_skip(matroska);
2157 break;
2158 }
2159
2160 if (matroska->level_up) {
2161 matroska->level_up--;
2162 break;
2163 }
2164 }
2165
2166 return res;
2167}
2168
2169static int
2170matroska_parse_chapters(AVFormatContext *s)
2171{
2172 MatroskaDemuxContext *matroska = s->priv_data;
2173 int res = 0;
2174 uint32_t id;
2175
2176 av_log(s, AV_LOG_DEBUG, "parsing chapters...\n");
2177
2178 while (res == 0) {
2179 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2180 res = AVERROR(EIO);
2181 break;
2182 } else if (matroska->level_up) {
2183 matroska->level_up--;
2184 break;
2185 }
2186
2187 switch (id) {
2188 case MATROSKA_ID_EDITIONENTRY: {
2189 uint64_t end = AV_NOPTS_VALUE, start = AV_NOPTS_VALUE;
2190 int64_t uid= -1;
2191 char* title = NULL;
2192 /* if there is more than one chapter edition
2193 we take only the first one */
2194 if(s->chapters) {
2195 ebml_read_skip(matroska);
2196 break;
2197 }
2198
2199 if ((res = ebml_read_master(matroska, &id)) < 0)
2200 break;
2201
2202 while (res == 0) {
2203 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2204 res = AVERROR(EIO);
2205 break;
2206 } else if (matroska->level_up) {
2207 matroska->level_up--;
2208 break;
2209 }
2210
2211 switch (id) {
2212 case MATROSKA_ID_CHAPTERATOM:
2213 if ((res = ebml_read_master(matroska, &id)) < 0)
2214 break;
2215
2216 while (res == 0) {
2217 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2218 res = AVERROR(EIO);
2219 break;
2220 } else if (matroska->level_up) {
2221 matroska->level_up--;
2222 break;
2223 }
2224
2225 switch (id) {
2226 case MATROSKA_ID_CHAPTERTIMEEND:
2227 res = ebml_read_uint(matroska, &id, &end);
2228 break;
2229
2230 case MATROSKA_ID_CHAPTERTIMESTART:
2231 res = ebml_read_uint(matroska, &id, &start);
2232 break;
2233
2234 case MATROSKA_ID_CHAPTERDISPLAY:
2235 if ((res = ebml_read_master(matroska, &id)) < 0)
2236 break;
2237
2238 while (res == 0) {
2239 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2240 res = AVERROR(EIO);
2241 break;
2242 } else if (matroska->level_up) {
2243 matroska->level_up--;
2244 break;
2245 }
2246
2247 switch (id) {
2248 case MATROSKA_ID_CHAPSTRING:
2249 res = ebml_read_utf8(matroska, &id, &title);
2250 break;
2251
2252 default:
2253 av_log(s, AV_LOG_INFO, "Ignoring unknown Chapter display ID 0x%x\n", id);
2254 case EBML_ID_VOID:
2255 res = ebml_read_skip(matroska);
2256 break;
2257 }
2258
2259 if (matroska->level_up) {
2260 matroska->level_up--;
2261 break;
2262 }
2263 }
2264 break;
2265
2266 case MATROSKA_ID_CHAPTERUID:
2267 res = ebml_read_uint(matroska, &id, &uid);
2268 break;
2269 default:
2270 av_log(s, AV_LOG_INFO, "Ignoring unknown Chapter atom ID 0x%x\n", id);
2271 case MATROSKA_ID_CHAPTERFLAGHIDDEN:
2272 case EBML_ID_VOID:
2273 res = ebml_read_skip(matroska);
2274 break;
2275 }
2276
2277 if (matroska->level_up) {
2278 matroska->level_up--;
2279 break;
2280 }
2281 }
2282
2283 if (start != AV_NOPTS_VALUE && uid != -1) {
2284 if(!ff_new_chapter(s, uid, (AVRational){1, 1000000000}, start, end, title))
2285 res= AVERROR(ENOMEM);
2286 }
2287 av_free(title);
2288 break;
2289
2290 default:
2291 av_log(s, AV_LOG_INFO, "Ignoring unknown Edition entry ID 0x%x\n", id);
2292 case MATROSKA_ID_EDITIONUID:
2293 case MATROSKA_ID_EDITIONFLAGHIDDEN:
2294 case MATROSKA_ID_EDITIONFLAGDEFAULT:
2295 case EBML_ID_VOID:
2296 res = ebml_read_skip(matroska);
2297 break;
2298 }
2299
2300
2301 if (matroska->level_up) {
2302 matroska->level_up--;
2303 break;
2304 }
2305 }
2306 break;
2307 }
2308
2309 default:
2310 av_log(s, AV_LOG_INFO, "Expected an Edition entry (0x%x), but found 0x%x\n", MATROSKA_ID_EDITIONENTRY, id);
2311 case EBML_ID_VOID:
2312 res = ebml_read_skip(matroska);
2313 break;
2314 }
2315
2316 if (matroska->level_up) {
2317 matroska->level_up--;
2318 break;
2319 }
2320 }
2321
2322 return res;
2323}
2324
2325static int
2326matroska_aac_profile (char *codec_id)
2327{
2328 static const char *aac_profiles[] = {
2329 "MAIN", "LC", "SSR"
2330 };
2331 int profile;
2332
2333 for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
2334 if (strstr(codec_id, aac_profiles[profile]))
2335 break;
2336 return profile + 1;
2337}
2338
2339static int
2340matroska_aac_sri (int samplerate)
2341{
2342 int sri;
2343
2344 for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
2345 if (ff_mpeg4audio_sample_rates[sri] == samplerate)
2346 break;
2347 return sri;
2348}
2349
2350static int
2351matroska_read_header (AVFormatContext *s,
2352 AVFormatParameters *ap)
2353{
2354 MatroskaDemuxContext *matroska = s->priv_data;
2355 char *doctype;
2356 int version, last_level, res = 0;
2357 uint32_t id;
2358
2359 matroska->ctx = s;
2360
2361 /* First read the EBML header. */
2362 doctype = NULL;
2363 if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
2364 return res;
2365 if ((doctype == NULL) || strcmp(doctype, "matroska")) {
2366 av_log(matroska->ctx, AV_LOG_ERROR,
2367 "Wrong EBML doctype ('%s' != 'matroska').\n",
2368 doctype ? doctype : "(none)");
2369 if (doctype)
2370 av_free(doctype);
2371 return AVERROR_NOFMT;
2372 }
2373 av_free(doctype);
2374 if (version > 2) {
2375 av_log(matroska->ctx, AV_LOG_ERROR,
2376 "Matroska demuxer version 2 too old for file version %d\n",
2377 version);
2378 return AVERROR_NOFMT;
2379 }
2380
2381 /* The next thing is a segment. */
2382 while (1) {
2383 if (!(id = ebml_peek_id(matroska, &last_level)))
2384 return AVERROR(EIO);
2385 if (id == MATROSKA_ID_SEGMENT)
2386 break;
2387
2388 /* oi! */
2389 av_log(matroska->ctx, AV_LOG_INFO,
2390 "Expected a Segment ID (0x%x), but received 0x%x!\n",
2391 MATROSKA_ID_SEGMENT, id);
2392 if ((res = ebml_read_skip(matroska)) < 0)
2393 return res;
2394 }
2395
2396 /* We now have a Matroska segment.
2397 * Seeks are from the beginning of the segment,
2398 * after the segment ID/length. */
2399 if ((res = ebml_read_master(matroska, &id)) < 0)
2400 return res;
2401 matroska->segment_start = url_ftell(s->pb);
2402
2403 matroska->time_scale = 1000000;
2404 /* we've found our segment, start reading the different contents in here */
2405 while (res == 0) {
2406 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2407 res = AVERROR(EIO);
2408 break;
2409 } else if (matroska->level_up) {
2410 matroska->level_up--;
2411 break;
2412 }
2413
2414 switch (id) {
2415 /* stream info */
2416 case MATROSKA_ID_INFO: {
2417 if ((res = ebml_read_master(matroska, &id)) < 0)
2418 break;
2419 res = matroska_parse_info(matroska);
2420 break;
2421 }
2422
2423 /* track info headers */
2424 case MATROSKA_ID_TRACKS: {
2425 if ((res = ebml_read_master(matroska, &id)) < 0)
2426 break;
2427 res = matroska_parse_tracks(matroska);
2428 break;
2429 }
2430
2431 /* stream index */
2432 case MATROSKA_ID_CUES: {
2433 if (!matroska->index_parsed) {
2434 if ((res = ebml_read_master(matroska, &id)) < 0)
2435 break;
2436 res = matroska_parse_index(matroska);
2437 } else
2438 res = ebml_read_skip(matroska);
2439 break;
2440 }
2441
2442 /* metadata */
2443 case MATROSKA_ID_TAGS: {
2444 if (!matroska->metadata_parsed) {
2445 if ((res = ebml_read_master(matroska, &id)) < 0)
2446 break;
2447 res = matroska_parse_metadata(matroska);
2448 } else
2449 res = ebml_read_skip(matroska);
2450 break;
2451 }
2452
2453 /* file index (if seekable, seek to Cues/Tags to parse it) */
2454 case MATROSKA_ID_SEEKHEAD: {
2455 if ((res = ebml_read_master(matroska, &id)) < 0)
2456 break;
2457 res = matroska_parse_seekhead(matroska);
2458 break;
2459 }
2460
2461 case MATROSKA_ID_ATTACHMENTS: {
2462 if ((res = ebml_read_master(matroska, &id)) < 0)
2463 break;
2464 res = matroska_parse_attachments(s);
2465 break;
2466 }
2467
2468 case MATROSKA_ID_CLUSTER: {
2469 /* Do not read the master - this will be done in the next
2470 * call to matroska_read_packet. */
2471 res = 1;
2472 break;
2473 }
2474
2475 case MATROSKA_ID_CHAPTERS: {
2476 if ((res = ebml_read_master(matroska, &id)) < 0)
2477 return res;
2478 res = matroska_parse_chapters(s);
2479 break;
2480 }
2481
2482 default:
2483 av_log(matroska->ctx, AV_LOG_INFO,
2484 "Unknown matroska file header ID 0x%x\n", id);
2485 /* fall-through */
2486
2487 case EBML_ID_VOID:
2488 res = ebml_read_skip(matroska);
2489 break;
2490 }
2491
2492 if (matroska->level_up) {
2493 matroska->level_up--;
2494 break;
2495 }
2496 }
2497
2498 /* Have we found a cluster? */
2499 if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2500 int i, j;
2501 MatroskaTrack *track;
2502 AVStream *st;
2503
2504 for (i = 0; i < matroska->num_tracks; i++) {
2505 enum CodecID codec_id = CODEC_ID_NONE;
2506 uint8_t *extradata = NULL;
2507 int extradata_size = 0;
2508 int extradata_offset = 0;
2509 track = matroska->tracks[i];
2510 track->stream_index = -1;
2511
2512 /* Apply some sanity checks. */
2513 if (track->codec_id == NULL)
2514 continue;
2515
2516 for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
2517 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
2518 strlen(ff_mkv_codec_tags[j].str))){
2519 codec_id= ff_mkv_codec_tags[j].id;
2520 break;
2521 }
2522 }
2523
2524 /* Set the FourCC from the CodecID. */
2525 /* This is the MS compatibility mode which stores a
2526 * BITMAPINFOHEADER in the CodecPrivate. */
2527 if (!strcmp(track->codec_id,
2528 MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2529 (track->codec_priv_size >= 40) &&
2530 (track->codec_priv != NULL)) {
2531 MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
2532
2533 /* Offset of biCompression. Stored in LE. */
2534 vtrack->fourcc = AV_RL32(track->codec_priv + 16);
2535 codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);
2536
2537 }
2538
2539 /* This is the MS compatibility mode which stores a
2540 * WAVEFORMATEX in the CodecPrivate. */
2541 else if (!strcmp(track->codec_id,
2542 MATROSKA_CODEC_ID_AUDIO_ACM) &&
2543 (track->codec_priv_size >= 18) &&
2544 (track->codec_priv != NULL)) {
2545 uint16_t tag;
2546
2547 /* Offset of wFormatTag. Stored in LE. */
2548 tag = AV_RL16(track->codec_priv);
2549 codec_id = codec_get_id(codec_wav_tags, tag);
2550
2551 }
2552
2553 else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2554 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2555 int profile = matroska_aac_profile(track->codec_id);
2556 int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2557 extradata = av_malloc(5);
2558 if (extradata == NULL)
2559 return AVERROR(ENOMEM);
2560 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2561 extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2562 if (strstr(track->codec_id, "SBR")) {
2563 sri = matroska_aac_sri(audiotrack->samplerate);
2564 extradata[2] = 0x56;
2565 extradata[3] = 0xE5;
2566 extradata[4] = 0x80 | (sri<<3);
2567 extradata_size = 5;
2568 } else {
2569 extradata_size = 2;
2570 }
2571 }
2572
2573 else if (codec_id == CODEC_ID_TTA) {
2574 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2575 ByteIOContext b;
2576 extradata_size = 30;
2577 extradata = av_mallocz(extradata_size);
2578 if (extradata == NULL)
2579 return AVERROR(ENOMEM);
2580 init_put_byte(&b, extradata, extradata_size, 1,
2581 NULL, NULL, NULL, NULL);
2582 put_buffer(&b, "TTA1", 4);
2583 put_le16(&b, 1);
2584 put_le16(&b, audiotrack->channels);
2585 put_le16(&b, audiotrack->bitdepth);
2586 put_le32(&b, audiotrack->samplerate);
2587 put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2588 }
2589
2590 else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2591 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2592 extradata_offset = 26;
2593 track->codec_priv_size -= extradata_offset;
2594 }
2595
2596 else if (codec_id == CODEC_ID_RA_144) {
2597 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2598 audiotrack->samplerate = 8000;
2599 audiotrack->channels = 1;
2600 }
2601
2602 else if (codec_id == CODEC_ID_RA_288 ||
2603 codec_id == CODEC_ID_COOK ||
2604 codec_id == CODEC_ID_ATRAC3) {
2605 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2606 ByteIOContext b;
2607
2608 init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
2609 NULL, NULL, NULL, NULL);
2610 url_fskip(&b, 24);
2611 audiotrack->coded_framesize = get_be32(&b);
2612 url_fskip(&b, 12);
2613 audiotrack->sub_packet_h = get_be16(&b);
2614 audiotrack->frame_size = get_be16(&b);
2615 audiotrack->sub_packet_size = get_be16(&b);
2616 audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
2617 if (codec_id == CODEC_ID_RA_288) {
2618 audiotrack->block_align = audiotrack->coded_framesize;
2619 track->codec_priv_size = 0;
2620 } else {
2621 audiotrack->block_align = audiotrack->sub_packet_size;
2622 extradata_offset = 78;
2623 track->codec_priv_size -= extradata_offset;
2624 }
2625 }
2626
2627 if (codec_id == CODEC_ID_NONE) {
2628 av_log(matroska->ctx, AV_LOG_INFO,
2629 "Unknown/unsupported CodecID %s.\n",
2630 track->codec_id);
2631 }
2632
2633 track->stream_index = matroska->num_streams;
2634
2635 matroska->num_streams++;
2636 st = av_new_stream(s, track->stream_index);
2637 if (st == NULL)
2638 return AVERROR(ENOMEM);
2639 av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2640
2641 st->codec->codec_id = codec_id;
2642 st->start_time = 0;
2643 if (strcmp(track->language, "und"))
2644 strcpy(st->language, track->language);
2645
2646 if (track->flags & MATROSKA_TRACK_DEFAULT)
2647 st->disposition |= AV_DISPOSITION_DEFAULT;
2648
2649 if (track->default_duration)
2650 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2651 track->default_duration, 1000000000, 30000);
2652
2653 if(extradata){
2654 st->codec->extradata = extradata;
2655 st->codec->extradata_size = extradata_size;
2656 } else if(track->codec_priv && track->codec_priv_size > 0){
2657 st->codec->extradata = av_malloc(track->codec_priv_size);
2658 if(st->codec->extradata == NULL)
2659 return AVERROR(ENOMEM);
2660 st->codec->extradata_size = track->codec_priv_size;
2661 memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2662 track->codec_priv_size);
2663 }
2664
2665 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2666 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2667
2668 st->codec->codec_type = CODEC_TYPE_VIDEO;
2669 st->codec->codec_tag = videotrack->fourcc;
2670 st->codec->width = videotrack->pixel_width;
2671 st->codec->height = videotrack->pixel_height;
2672 if (videotrack->display_width == 0)
2673 videotrack->display_width= videotrack->pixel_width;
2674 if (videotrack->display_height == 0)
2675 videotrack->display_height= videotrack->pixel_height;
2676 av_reduce(&st->codec->sample_aspect_ratio.num,
2677 &st->codec->sample_aspect_ratio.den,
2678 st->codec->height * videotrack->display_width,
2679 st->codec-> width * videotrack->display_height,
2680 255);
2681 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2682 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2683 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2684
2685 st->codec->codec_type = CODEC_TYPE_AUDIO;
2686 st->codec->sample_rate = audiotrack->samplerate;
2687 st->codec->channels = audiotrack->channels;
2688 st->codec->block_align = audiotrack->block_align;
2689 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2690 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2691 }
2692
2693 /* What do we do with private data? E.g. for Vorbis. */
2694 }
2695 res = 0;
2696 }
2697
2698 if (matroska->index_parsed) {
2699 int i, track, stream;
2700 for (i=0; i<matroska->num_indexes; i++) {
2701 MatroskaDemuxIndex *idx = &matroska->index[i];
2702 track = matroska_find_track_by_num(matroska, idx->track);
2703 if (track < 0) continue;
2704 stream = matroska->tracks[track]->stream_index;
2705 if (stream >= 0 && stream < matroska->ctx->nb_streams)
2706 av_add_index_entry(matroska->ctx->streams[stream],
2707 idx->pos, idx->time/AV_TIME_BASE,
2708 0, 0, AVINDEX_KEYFRAME);
2709 }
2710 }
2711
2712 return res;
2713}
2714
2715static int
2716matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2717 int64_t pos, uint64_t cluster_time, uint64_t duration,
2718 int is_keyframe, int is_bframe)
2719{
2720 int res = 0;
2721 int track;
2722 AVStream *st;
2723 AVPacket *pkt;
2724 uint8_t *origdata = data;
2725 int16_t block_time;
2726 uint32_t *lace_size = NULL;
2727 int n, flags, laces = 0;
2728 uint64_t num;
2729 int stream_index;
2730
2731 /* first byte(s): tracknum */
2732 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2733 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2734 av_free(origdata);
2735 return res;
2736 }
2737 data += n;
2738 size -= n;
2739
2740 /* fetch track from num */
2741 track = matroska_find_track_by_num(matroska, num);
2742 if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2743 av_log(matroska->ctx, AV_LOG_INFO,
2744 "Invalid stream %d or size %u\n", track, size);
2745 av_free(origdata);
2746 return res;
2747 }
2748 stream_index = matroska->tracks[track]->stream_index;
2749 if (stream_index < 0 || stream_index >= matroska->ctx->nb_streams) {
2750 av_free(origdata);
2751 return res;
2752 }
2753 st = matroska->ctx->streams[stream_index];
2754 if (st->discard >= AVDISCARD_ALL) {
2755 av_free(origdata);
2756 return res;
2757 }
2758 if (duration == AV_NOPTS_VALUE)
2759 duration = matroska->tracks[track]->default_duration / matroska->time_scale;
2760
2761 /* block_time (relative to cluster time) */
2762 block_time = AV_RB16(data);
2763 data += 2;
2764 flags = *data++;
2765 size -= 3;
2766 if (is_keyframe == -1)
2767 is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
2768
2769 if (matroska->skip_to_keyframe) {
2770 if (!is_keyframe || st != matroska->skip_to_stream) {
2771 av_free(origdata);
2772 return res;
2773 }
2774 matroska->skip_to_keyframe = 0;
2775 }
2776
2777 switch ((flags & 0x06) >> 1) {
2778 case 0x0: /* no lacing */
2779 laces = 1;
2780 lace_size = av_mallocz(sizeof(int));
2781 lace_size[0] = size;
2782 break;
2783
2784 case 0x1: /* xiph lacing */
2785 case 0x2: /* fixed-size lacing */
2786 case 0x3: /* EBML lacing */
2787 assert(size>0); // size <=3 is checked before size-=3 above
2788 laces = (*data) + 1;
2789 data += 1;
2790 size -= 1;
2791 lace_size = av_mallocz(laces * sizeof(int));
2792
2793 switch ((flags & 0x06) >> 1) {
2794 case 0x1: /* xiph lacing */ {
2795 uint8_t temp;
2796 uint32_t total = 0;
2797 for (n = 0; res == 0 && n < laces - 1; n++) {
2798 while (1) {
2799 if (size == 0) {
2800 res = -1;
2801 break;
2802 }
2803 temp = *data;
2804 lace_size[n] += temp;
2805 data += 1;
2806 size -= 1;
2807 if (temp != 0xff)
2808 break;
2809 }
2810 total += lace_size[n];
2811 }
2812 lace_size[n] = size - total;
2813 break;
2814 }
2815
2816 case 0x2: /* fixed-size lacing */
2817 for (n = 0; n < laces; n++)
2818 lace_size[n] = size / laces;
2819 break;
2820
2821 case 0x3: /* EBML lacing */ {
2822 uint32_t total;
2823 n = matroska_ebmlnum_uint(data, size, &num);
2824 if (n < 0) {
2825 av_log(matroska->ctx, AV_LOG_INFO,
2826 "EBML block data error\n");
2827 break;
2828 }
2829 data += n;
2830 size -= n;
2831 total = lace_size[0] = num;
2832 for (n = 1; res == 0 && n < laces - 1; n++) {
2833 int64_t snum;
2834 int r;
2835 r = matroska_ebmlnum_sint (data, size, &snum);
2836 if (r < 0) {
2837 av_log(matroska->ctx, AV_LOG_INFO,
2838 "EBML block data error\n");
2839 break;
2840 }
2841 data += r;
2842 size -= r;
2843 lace_size[n] = lace_size[n - 1] + snum;
2844 total += lace_size[n];
2845 }
2846 lace_size[n] = size - total;
2847 break;
2848 }
2849 }
2850 break;
2851 }
2852
2853 if (res == 0) {
2854 uint64_t timecode = AV_NOPTS_VALUE;
2855
2856 if (cluster_time != (uint64_t)-1
2857 && (block_time >= 0 || cluster_time >= -block_time))
2858 timecode = cluster_time + block_time;
2859
2860 for (n = 0; n < laces; n++) {
2861 if (st->codec->codec_id == CODEC_ID_RA_288 ||
2862 st->codec->codec_id == CODEC_ID_COOK ||
2863 st->codec->codec_id == CODEC_ID_ATRAC3) {
2864 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
2865 int a = st->codec->block_align;
2866 int sps = audiotrack->sub_packet_size;
2867 int cfs = audiotrack->coded_framesize;
2868 int h = audiotrack->sub_packet_h;
2869 int y = audiotrack->sub_packet_cnt;
2870 int w = audiotrack->frame_size;
2871 int x;
2872
2873 if (!audiotrack->pkt_cnt) {
2874 if (st->codec->codec_id == CODEC_ID_RA_288)
2875 for (x=0; x<h/2; x++)
2876 memcpy(audiotrack->buf+x*2*w+y*cfs,
2877 data+x*cfs, cfs);
2878 else
2879 for (x=0; x<w/sps; x++)
2880 memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2881
2882 if (++audiotrack->sub_packet_cnt >= h) {
2883 audiotrack->sub_packet_cnt = 0;
2884 audiotrack->pkt_cnt = h*w / a;
2885 }
2886 }
2887 while (audiotrack->pkt_cnt) {
2888 pkt = av_mallocz(sizeof(AVPacket));
2889 av_new_packet(pkt, a);
2890 memcpy(pkt->data, audiotrack->buf
2891 + a * (h*w / a - audiotrack->pkt_cnt--), a);
2892 pkt->pos = pos;
2893 pkt->stream_index = stream_index;
2894 matroska_queue_packet(matroska, pkt);
2895 }
2896 } else {
2897 int offset = 0, pkt_size = lace_size[n];
2898 uint8_t *pkt_data = data;
2899
2900 if (matroska->tracks[track]->encoding_scope & 1) {
2901 offset = matroska_decode_buffer(&pkt_data, &pkt_size,
2902 matroska->tracks[track]);
2903 if (offset < 0)
2904 continue;
2905 }
2906
2907 pkt = av_mallocz(sizeof(AVPacket));
2908 /* XXX: prevent data copy... */
2909 if (av_new_packet(pkt, pkt_size+offset) < 0) {
2910 av_free(pkt);
2911 res = AVERROR(ENOMEM);
2912 n = laces-1;
2913 break;
2914 }
2915 if (offset)
2916 memcpy (pkt->data, matroska->tracks[track]->encoding_settings, offset);
2917 memcpy (pkt->data+offset, pkt_data, pkt_size);
2918
2919 if (pkt_data != data)
2920 av_free(pkt_data);
2921
2922 if (n == 0)
2923 pkt->flags = is_keyframe;
2924 pkt->stream_index = stream_index;
2925
2926 pkt->pts = timecode;
2927 pkt->pos = pos;
2928 pkt->duration = duration;
2929
2930 matroska_queue_packet(matroska, pkt);
2931 }
2932
2933 if (timecode != AV_NOPTS_VALUE)
2934 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2935 data += lace_size[n];
2936 }
2937 }
2938
2939 av_free(lace_size);
2940 av_free(origdata);
2941 return res;
2942}
2943
2944static int
2945matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2946 uint64_t cluster_time)
2947{
2948 int res = 0;
2949 uint32_t id;
2950 int is_bframe = 0;
2951 int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2952 uint64_t duration = AV_NOPTS_VALUE;
2953 uint8_t *data;
2954 int size = 0;
2955 int64_t pos = 0;
2956
2957 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2958
2959 while (res == 0) {
2960 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2961 res = AVERROR(EIO);
2962 break;
2963 } else if (matroska->level_up) {
2964 matroska->level_up--;
2965 break;
2966 }
2967
2968 switch (id) {
2969 /* one block inside the group. Note, block parsing is one
2970 * of the harder things, so this code is a bit complicated.
2971 * See http://www.matroska.org/ for documentation. */
2972 case MATROSKA_ID_BLOCK: {
2973 pos = url_ftell(matroska->ctx->pb);
2974 res = ebml_read_binary(matroska, &id, &data, &size);
2975 break;
2976 }
2977
2978 case MATROSKA_ID_BLOCKDURATION: {
2979 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2980 break;
2981 break;
2982 }
2983
2984 case MATROSKA_ID_BLOCKREFERENCE: {
2985 int64_t num;
2986 /* We've found a reference, so not even the first frame in
2987 * the lace is a key frame. */
2988 is_keyframe = 0;
2989 if (last_num_packets != matroska->num_packets)
2990 matroska->packets[last_num_packets]->flags = 0;
2991 if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2992 break;
2993 if (num > 0)
2994 is_bframe = 1;
2995 break;
2996 }
2997
2998 default:
2999 av_log(matroska->ctx, AV_LOG_INFO,
3000 "Unknown entry 0x%x in blockgroup data\n", id);
3001 /* fall-through */
3002
3003 case EBML_ID_VOID:
3004 res = ebml_read_skip(matroska);
3005 break;
3006 }
3007
3008 if (matroska->level_up) {
3009 matroska->level_up--;
3010 break;
3011 }
3012 }
3013
3014 if (res)
3015 return res;
3016
3017 if (size > 0)
3018 res = matroska_parse_block(matroska, data, size, pos, cluster_time,
3019 duration, is_keyframe, is_bframe);
3020
3021 return res;
3022}
3023
3024static int
3025matroska_parse_cluster (MatroskaDemuxContext *matroska)
3026{
3027 int res = 0;
3028 uint32_t id;
3029 uint64_t cluster_time = 0;
3030 uint8_t *data;
3031 int64_t pos;
3032 int size;
3033
3034 av_log(matroska->ctx, AV_LOG_DEBUG,
3035 "parsing cluster at %"PRId64"\n", url_ftell(matroska->ctx->pb));
3036
3037 while (res == 0) {
3038 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
3039 res = AVERROR(EIO);
3040 break;
3041 } else if (matroska->level_up) {
3042 matroska->level_up--;
3043 break;
3044 }
3045
3046 switch (id) {
3047 /* cluster timecode */
3048 case MATROSKA_ID_CLUSTERTIMECODE: {
3049 uint64_t num;
3050 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
3051 break;
3052 cluster_time = num;
3053 break;
3054 }
3055
3056 /* a group of blocks inside a cluster */
3057 case MATROSKA_ID_BLOCKGROUP:
3058 if ((res = ebml_read_master(matroska, &id)) < 0)
3059 break;
3060 res = matroska_parse_blockgroup(matroska, cluster_time);
3061 break;
3062
3063 case MATROSKA_ID_SIMPLEBLOCK:
3064 pos = url_ftell(matroska->ctx->pb);
3065 res = ebml_read_binary(matroska, &id, &data, &size);
3066 if (res == 0)
3067 res = matroska_parse_block(matroska, data, size, pos,
3068 cluster_time, AV_NOPTS_VALUE,
3069 -1, 0);
3070 break;
3071
3072 default:
3073 av_log(matroska->ctx, AV_LOG_INFO,
3074 "Unknown entry 0x%x in cluster data\n", id);
3075 /* fall-through */
3076
3077 case EBML_ID_VOID:
3078 res = ebml_read_skip(matroska);
3079 break;
3080 }
3081
3082 if (matroska->level_up) {
3083 matroska->level_up--;
3084 break;
3085 }
3086 }
3087
3088 return res;
3089}
3090
3091static int
3092matroska_read_packet (AVFormatContext *s,
3093 AVPacket *pkt)
3094{
3095 MatroskaDemuxContext *matroska = s->priv_data;
3096 int res;
3097 uint32_t id;
3098
3099 /* Read stream until we have a packet queued. */
3100 while (matroska_deliver_packet(matroska, pkt)) {
3101
3102 /* Have we already reached the end? */
3103 if (matroska->done)
3104 return AVERROR(EIO);
3105
3106 res = 0;
3107 while (res == 0) {
3108 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
3109 return AVERROR(EIO);
3110 } else if (matroska->level_up) {
3111 matroska->level_up--;
3112 break;
3113 }
3114
3115 switch (id) {
3116 case MATROSKA_ID_CLUSTER:
3117 if ((res = ebml_read_master(matroska, &id)) < 0)
3118 break;
3119 if ((res = matroska_parse_cluster(matroska)) == 0)
3120 res = 1; /* Parsed one cluster, let's get out. */
3121 break;
3122
3123 default:
3124 case EBML_ID_VOID:
3125 res = ebml_read_skip(matroska);
3126 break;
3127 }
3128
3129 if (matroska->level_up) {
3130 matroska->level_up--;
3131 break;
3132 }
3133 }
3134
3135 if (res == -1)
3136 matroska->done = 1;
3137 }
3138
3139 return 0;
3140}
3141
3142static int
3143matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
3144 int flags)
3145{
3146 MatroskaDemuxContext *matroska = s->priv_data;
3147 AVStream *st = s->streams[stream_index];
3148 int index;
3149
3150 /* find index entry */
3151 index = av_index_search_timestamp(st, timestamp, flags);
3152 if (index < 0)
3153 return 0;
3154
3155 matroska_clear_queue(matroska);
3156
3157 /* do the seek */
3158 url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
3159 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
3160 matroska->skip_to_stream = st;
3161 matroska->peek_id = 0;
3162 av_update_cur_dts(s, st, st->index_entries[index].timestamp);
3163 return 0;
3164}
3165
3166static int
3167matroska_read_close (AVFormatContext *s)
3168{
3169 MatroskaDemuxContext *matroska = s->priv_data;
3170 int n = 0;
3171
3172 av_free(matroska->index);
3173
3174 matroska_clear_queue(matroska);
3175
3176 for (n = 0; n < matroska->num_tracks; n++) {
3177 MatroskaTrack *track = matroska->tracks[n];
3178 av_free(track->codec_id);
3179 av_free(track->codec_priv);
3180 av_free(track->name);
3181
3182 if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
3183 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
3184 av_free(audiotrack->buf);
3185 }
3186
3187 av_free(track);
3188 }
3189
3190 return 0;
3191}
3192
3193AVInputFormat matroska_demuxer = {
3194 "matroska",
3195 NULL_IF_CONFIG_SMALL("Matroska file format"),
3196 sizeof(MatroskaDemuxContext),
3197 matroska_probe,
3198 matroska_read_header,
3199 matroska_read_packet,
3200 matroska_read_close,
3201 matroska_read_seek,
3202};
diff --git a/src/plugins/ffmpeg/libavformat/matroskaenc.c b/src/plugins/ffmpeg/libavformat/matroskaenc.c
deleted file mode 100644
index a138437..0000000
--- a/src/plugins/ffmpeg/libavformat/matroskaenc.c
+++ /dev/null
@@ -1,847 +0,0 @@
1/*
2 * Matroska muxer
3 * Copyright (c) 2007 David Conrad
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 "avformat.h"
23#include "riff.h"
24#include "matroska.h"
25#include "avc.h"
26#include "libavutil/md5.h"
27#include "libavcodec/xiph.h"
28#include "libavcodec/mpeg4audio.h"
29
30typedef struct ebml_master {
31 offset_t pos; ///< absolute offset in the file where the master's elements start
32 int sizebytes; ///< how many bytes were reserved for the size
33} ebml_master;
34
35typedef struct mkv_seekhead_entry {
36 unsigned int elementid;
37 uint64_t segmentpos;
38} mkv_seekhead_entry;
39
40typedef struct mkv_seekhead {
41 offset_t filepos;
42 offset_t segment_offset; ///< the file offset to the beginning of the segment
43 int reserved_size; ///< -1 if appending to file
44 int max_entries;
45 mkv_seekhead_entry *entries;
46 int num_entries;
47} mkv_seekhead;
48
49typedef struct {
50 uint64_t pts;
51 int tracknum;
52 offset_t cluster_pos; ///< file offset of the cluster containing the block
53} mkv_cuepoint;
54
55typedef struct {
56 offset_t segment_offset;
57 mkv_cuepoint *entries;
58 int num_entries;
59} mkv_cues;
60
61typedef struct MatroskaMuxContext {
62 ebml_master segment;
63 offset_t segment_offset;
64 offset_t segment_uid;
65 ebml_master cluster;
66 offset_t cluster_pos; ///< file offset of the current cluster
67 uint64_t cluster_pts;
68 offset_t duration_offset;
69 uint64_t duration;
70 mkv_seekhead *main_seekhead;
71 mkv_seekhead *cluster_seekhead;
72 mkv_cues *cues;
73
74 struct AVMD5 *md5_ctx;
75} MatroskaMuxContext;
76
77
78/** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
79 * offset, 4 bytes for target EBML ID */
80#define MAX_SEEKENTRY_SIZE 21
81
82/** per-cuepoint-track - 3 1-byte EBML IDs, 3 1-byte EBML sizes, 2
83 * 8-byte uint max */
84#define MAX_CUETRACKPOS_SIZE 22
85
86/** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
87#define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE*num_tracks
88
89
90static int ebml_id_size(unsigned int id)
91{
92 return (av_log2(id+1)-1)/7+1;
93}
94
95static void put_ebml_id(ByteIOContext *pb, unsigned int id)
96{
97 int i = ebml_id_size(id);
98 while (i--)
99 put_byte(pb, id >> (i*8));
100}
101
102/**
103 * Write an EBML size meaning "unknown size".
104 *
105 * @param bytes The number of bytes the size should occupy (maximum: 8).
106 */
107static void put_ebml_size_unknown(ByteIOContext *pb, int bytes)
108{
109 assert(bytes <= 8);
110 put_byte(pb, 0x1ff >> bytes);
111 while (--bytes)
112 put_byte(pb, 0xff);
113}
114
115/**
116 * Calculate how many bytes are needed to represent a given number in EBML.
117 */
118static int ebml_num_size(uint64_t num)
119{
120 int bytes = 1;
121 while ((num+1) >> bytes*7) bytes++;
122 return bytes;
123}
124
125/**
126 * Write a number in EBML variable length format.
127 *
128 * @param bytes The number of bytes that need to be used to write the number.
129 * If zero, any number of bytes can be used.
130 */
131static void put_ebml_num(ByteIOContext *pb, uint64_t num, int bytes)
132{
133 int i, needed_bytes = ebml_num_size(num);
134
135 // sizes larger than this are currently undefined in EBML
136 assert(num < (1ULL<<56)-1);
137
138 if (bytes == 0)
139 // don't care how many bytes are used, so use the min
140 bytes = needed_bytes;
141 // the bytes needed to write the given size would exceed the bytes
142 // that we need to use, so write unknown size. This shouldn't happen.
143 assert(bytes >= needed_bytes);
144
145 num |= 1ULL << bytes*7;
146 for (i = bytes - 1; i >= 0; i--)
147 put_byte(pb, num >> i*8);
148}
149
150static void put_ebml_uint(ByteIOContext *pb, unsigned int elementid, uint64_t val)
151{
152 int i, bytes = 1;
153 uint64_t tmp = val;
154 while (tmp>>=8) bytes++;
155
156 put_ebml_id(pb, elementid);
157 put_ebml_num(pb, bytes, 0);
158 for (i = bytes - 1; i >= 0; i--)
159 put_byte(pb, val >> i*8);
160}
161
162static void put_ebml_float(ByteIOContext *pb, unsigned int elementid, double val)
163{
164 put_ebml_id(pb, elementid);
165 put_ebml_num(pb, 8, 0);
166 put_be64(pb, av_dbl2int(val));
167}
168
169static void put_ebml_binary(ByteIOContext *pb, unsigned int elementid,
170 const uint8_t *buf, int size)
171{
172 put_ebml_id(pb, elementid);
173 put_ebml_num(pb, size, 0);
174 put_buffer(pb, buf, size);
175}
176
177static void put_ebml_string(ByteIOContext *pb, unsigned int elementid, const char *str)
178{
179 put_ebml_binary(pb, elementid, str, strlen(str));
180}
181
182/**
183 * Writes a void element of a given size. Useful for reserving space in
184 * the file to be written to later.
185 *
186 * @param size The number of bytes to reserve, which must be at least 2.
187 */
188static void put_ebml_void(ByteIOContext *pb, uint64_t size)
189{
190 offset_t currentpos = url_ftell(pb);
191
192 assert(size >= 2);
193
194 put_ebml_id(pb, EBML_ID_VOID);
195 // we need to subtract the length needed to store the size from the
196 // size we need to reserve so 2 cases, we use 8 bytes to store the
197 // size if possible, 1 byte otherwise
198 if (size < 10)
199 put_ebml_num(pb, size-1, 0);
200 else
201 put_ebml_num(pb, size-9, 8);
202 while(url_ftell(pb) < currentpos + size)
203 put_byte(pb, 0);
204}
205
206static ebml_master start_ebml_master(ByteIOContext *pb, unsigned int elementid, uint64_t expectedsize)
207{
208 int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
209 put_ebml_id(pb, elementid);
210 put_ebml_size_unknown(pb, bytes);
211 return (ebml_master){ url_ftell(pb), bytes };
212}
213
214static void end_ebml_master(ByteIOContext *pb, ebml_master master)
215{
216 offset_t pos = url_ftell(pb);
217
218 // leave the unknown size for masters when streaming
219 if (url_is_streamed(pb))
220 return;
221
222 url_fseek(pb, master.pos - master.sizebytes, SEEK_SET);
223 put_ebml_num(pb, pos - master.pos, master.sizebytes);
224 url_fseek(pb, pos, SEEK_SET);
225}
226
227static void put_xiph_size(ByteIOContext *pb, int size)
228{
229 int i;
230 for (i = 0; i < size / 255; i++)
231 put_byte(pb, 255);
232 put_byte(pb, size % 255);
233}
234
235/**
236 * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
237 * elements. If a maximum number of elements is specified, enough space
238 * will be reserved at the current file location to write a seek head of
239 * that size.
240 *
241 * @param segment_offset The absolute offset to the position in the file
242 * where the segment begins.
243 * @param numelements The maximum number of elements that will be indexed
244 * by this seek head, 0 if unlimited.
245 */
246static mkv_seekhead * mkv_start_seekhead(ByteIOContext *pb, offset_t segment_offset, int numelements)
247{
248 mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
249 if (new_seekhead == NULL)
250 return NULL;
251
252 new_seekhead->segment_offset = segment_offset;
253
254 if (numelements > 0) {
255 new_seekhead->filepos = url_ftell(pb);
256 // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
257 // and size, and 3 bytes to guarantee that an EBML void element
258 // will fit afterwards
259 new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
260 new_seekhead->max_entries = numelements;
261 put_ebml_void(pb, new_seekhead->reserved_size);
262 }
263 return new_seekhead;
264}
265
266static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
267{
268 mkv_seekhead_entry *entries = seekhead->entries;
269
270 // don't store more elements than we reserved space for
271 if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
272 return -1;
273
274 entries = av_realloc(entries, (seekhead->num_entries + 1) * sizeof(mkv_seekhead_entry));
275 if (entries == NULL)
276 return AVERROR(ENOMEM);
277
278 entries[seekhead->num_entries ].elementid = elementid;
279 entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
280
281 seekhead->entries = entries;
282 return 0;
283}
284
285/**
286 * Write the seek head to the file and free it. If a maximum number of
287 * elements was specified to mkv_start_seekhead(), the seek head will
288 * be written at the location reserved for it. Otherwise, it is written
289 * at the current location in the file.
290 *
291 * @return The file offset where the seekhead was written.
292 */
293static offset_t mkv_write_seekhead(ByteIOContext *pb, mkv_seekhead *seekhead)
294{
295 ebml_master metaseek, seekentry;
296 offset_t currentpos;
297 int i;
298
299 currentpos = url_ftell(pb);
300
301 if (seekhead->reserved_size > 0)
302 url_fseek(pb, seekhead->filepos, SEEK_SET);
303
304 metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
305 for (i = 0; i < seekhead->num_entries; i++) {
306 mkv_seekhead_entry *entry = &seekhead->entries[i];
307
308 seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
309
310 put_ebml_id(pb, MATROSKA_ID_SEEKID);
311 put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
312 put_ebml_id(pb, entry->elementid);
313
314 put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
315 end_ebml_master(pb, seekentry);
316 }
317 end_ebml_master(pb, metaseek);
318
319 if (seekhead->reserved_size > 0) {
320 uint64_t remaining = seekhead->filepos + seekhead->reserved_size - url_ftell(pb);
321 put_ebml_void(pb, remaining);
322 url_fseek(pb, currentpos, SEEK_SET);
323
324 currentpos = seekhead->filepos;
325 }
326 av_free(seekhead->entries);
327 av_free(seekhead);
328
329 return currentpos;
330}
331
332static mkv_cues * mkv_start_cues(offset_t segment_offset)
333{
334 mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
335 if (cues == NULL)
336 return NULL;
337
338 cues->segment_offset = segment_offset;
339 return cues;
340}
341
342static int mkv_add_cuepoint(mkv_cues *cues, AVPacket *pkt, offset_t cluster_pos)
343{
344 mkv_cuepoint *entries = cues->entries;
345
346 entries = av_realloc(entries, (cues->num_entries + 1) * sizeof(mkv_cuepoint));
347 if (entries == NULL)
348 return AVERROR(ENOMEM);
349
350 entries[cues->num_entries ].pts = pkt->pts;
351 entries[cues->num_entries ].tracknum = pkt->stream_index + 1;
352 entries[cues->num_entries++].cluster_pos = cluster_pos - cues->segment_offset;
353
354 cues->entries = entries;
355 return 0;
356}
357
358static offset_t mkv_write_cues(ByteIOContext *pb, mkv_cues *cues, int num_tracks)
359{
360 ebml_master cues_element;
361 offset_t currentpos;
362 int i, j;
363
364 currentpos = url_ftell(pb);
365 cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
366
367 for (i = 0; i < cues->num_entries; i++) {
368 ebml_master cuepoint, track_positions;
369 mkv_cuepoint *entry = &cues->entries[i];
370 uint64_t pts = entry->pts;
371
372 cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
373 put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
374
375 // put all the entries from different tracks that have the exact same
376 // timestamp into the same CuePoint
377 for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
378 track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
379 put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
380 put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
381 end_ebml_master(pb, track_positions);
382 }
383 i += j - 1;
384 end_ebml_master(pb, cuepoint);
385 }
386 end_ebml_master(pb, cues_element);
387
388 av_free(cues->entries);
389 av_free(cues);
390 return currentpos;
391}
392
393static int put_xiph_codecpriv(AVFormatContext *s, ByteIOContext *pb, AVCodecContext *codec)
394{
395 uint8_t *header_start[3];
396 int header_len[3];
397 int first_header_size;
398 int j;
399
400 if (codec->codec_id == CODEC_ID_VORBIS)
401 first_header_size = 30;
402 else
403 first_header_size = 42;
404
405 if (ff_split_xiph_headers(codec->extradata, codec->extradata_size,
406 first_header_size, header_start, header_len) < 0) {
407 av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
408 return -1;
409 }
410
411 put_byte(pb, 2); // number packets - 1
412 for (j = 0; j < 2; j++) {
413 put_xiph_size(pb, header_len[j]);
414 }
415 for (j = 0; j < 3; j++)
416 put_buffer(pb, header_start[j], header_len[j]);
417
418 return 0;
419}
420
421#define FLAC_STREAMINFO_SIZE 34
422
423static int put_flac_codecpriv(AVFormatContext *s, ByteIOContext *pb, AVCodecContext *codec)
424{
425 // if the extradata_size is greater than FLAC_STREAMINFO_SIZE,
426 // assume that it's in Matroska's format already
427 if (codec->extradata_size < FLAC_STREAMINFO_SIZE) {
428 av_log(s, AV_LOG_ERROR, "Invalid FLAC extradata\n");
429 return -1;
430 } else if (codec->extradata_size == FLAC_STREAMINFO_SIZE) {
431 // only the streaminfo packet
432 put_buffer(pb, "fLaC", 4);
433 put_byte(pb, 0x80);
434 put_be24(pb, FLAC_STREAMINFO_SIZE);
435 } else if(memcmp("fLaC", codec->extradata, 4)) {
436 av_log(s, AV_LOG_ERROR, "Invalid FLAC extradata\n");
437 return -1;
438 }
439 put_buffer(pb, codec->extradata, codec->extradata_size);
440 return 0;
441}
442
443static void get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
444{
445 int sri;
446
447 if (codec->extradata_size < 2) {
448 av_log(s, AV_LOG_WARNING, "No AAC extradata, unable to determine samplerate.\n");
449 return;
450 }
451
452 sri = ((codec->extradata[0] << 1) & 0xE) | (codec->extradata[1] >> 7);
453 if (sri > 12) {
454 av_log(s, AV_LOG_WARNING, "AAC samplerate index out of bounds\n");
455 return;
456 }
457 *sample_rate = ff_mpeg4audio_sample_rates[sri];
458
459 // if sbr, get output sample rate as well
460 if (codec->extradata_size == 5) {
461 sri = (codec->extradata[4] >> 3) & 0xF;
462 if (sri > 12) {
463 av_log(s, AV_LOG_WARNING, "AAC output samplerate index out of bounds\n");
464 return;
465 }
466 *output_sample_rate = ff_mpeg4audio_sample_rates[sri];
467 }
468}
469
470static int mkv_write_codecprivate(AVFormatContext *s, ByteIOContext *pb, AVCodecContext *codec, int native_id)
471{
472 ByteIOContext *dyn_cp;
473 uint8_t *codecpriv;
474 int ret, codecpriv_size;
475
476 ret = url_open_dyn_buf(&dyn_cp);
477 if(ret < 0)
478 return ret;
479
480 if (native_id) {
481 if (codec->codec_id == CODEC_ID_VORBIS || codec->codec_id == CODEC_ID_THEORA)
482 ret = put_xiph_codecpriv(s, dyn_cp, codec);
483 else if (codec->codec_id == CODEC_ID_FLAC)
484 ret = put_flac_codecpriv(s, dyn_cp, codec);
485 else if (codec->codec_id == CODEC_ID_H264)
486 ret = ff_isom_write_avcc(dyn_cp, codec->extradata, codec->extradata_size);
487 else if (codec->extradata_size)
488 put_buffer(dyn_cp, codec->extradata, codec->extradata_size);
489 } else if (codec->codec_type == CODEC_TYPE_VIDEO) {
490 if (!codec->codec_tag)
491 codec->codec_tag = codec_get_tag(codec_bmp_tags, codec->codec_id);
492 if (!codec->codec_tag) {
493 av_log(s, AV_LOG_ERROR, "No bmp codec ID found.");
494 ret = -1;
495 }
496
497 put_bmp_header(dyn_cp, codec, codec_bmp_tags, 0);
498
499 } else if (codec->codec_type == CODEC_TYPE_AUDIO) {
500 if (!codec->codec_tag)
501 codec->codec_tag = codec_get_tag(codec_wav_tags, codec->codec_id);
502 if (!codec->codec_tag) {
503 av_log(s, AV_LOG_ERROR, "No wav codec ID found.");
504 ret = -1;
505 }
506
507 put_wav_header(dyn_cp, codec);
508 }
509
510 codecpriv_size = url_close_dyn_buf(dyn_cp, &codecpriv);
511 if (codecpriv_size)
512 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv, codecpriv_size);
513 av_free(codecpriv);
514 return ret;
515}
516
517static int mkv_write_tracks(AVFormatContext *s)
518{
519 MatroskaMuxContext *mkv = s->priv_data;
520 ByteIOContext *pb = s->pb;
521 ebml_master tracks;
522 int i, j, ret;
523
524 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, url_ftell(pb));
525 if (ret < 0) return ret;
526
527 tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
528 for (i = 0; i < s->nb_streams; i++) {
529 AVStream *st = s->streams[i];
530 AVCodecContext *codec = st->codec;
531 ebml_master subinfo, track;
532 int native_id = 0;
533 int bit_depth = av_get_bits_per_sample(codec->codec_id);
534 int sample_rate = codec->sample_rate;
535 int output_sample_rate = 0;
536
537 if (!bit_depth)
538 bit_depth = av_get_bits_per_sample_format(codec->sample_fmt);
539
540 if (codec->codec_id == CODEC_ID_AAC)
541 get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
542
543 track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
544 put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER , i + 1);
545 put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
546 put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
547
548 if (st->language[0])
549 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, st->language);
550 else
551 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, "und");
552
553 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
554
555 // look for a codec ID string specific to mkv to use,
556 // if none are found, use AVI codes
557 for (j = 0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++) {
558 if (ff_mkv_codec_tags[j].id == codec->codec_id) {
559 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
560 native_id = 1;
561 break;
562 }
563 }
564
565 switch (codec->codec_type) {
566 case CODEC_TYPE_VIDEO:
567 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
568
569 if (!native_id)
570 // if there is no mkv-specific codec ID, use VFW mode
571 put_ebml_string(pb, MATROSKA_ID_CODECID, MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC);
572
573 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
574 // XXX: interlace flag?
575 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
576 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
577 if (codec->sample_aspect_ratio.num) {
578 AVRational dar = av_mul_q(codec->sample_aspect_ratio,
579 (AVRational){codec->width, codec->height});
580 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , dar.num);
581 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, dar.den);
582 }
583 end_ebml_master(pb, subinfo);
584 break;
585
586 case CODEC_TYPE_AUDIO:
587 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
588
589 if (!native_id)
590 // no mkv-specific ID, use ACM mode
591 put_ebml_string(pb, MATROSKA_ID_CODECID, MATROSKA_CODEC_ID_AUDIO_ACM);
592
593 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
594 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
595 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
596 if (output_sample_rate)
597 put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
598 if (bit_depth)
599 put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
600 end_ebml_master(pb, subinfo);
601 break;
602
603 case CODEC_TYPE_SUBTITLE:
604 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);
605 break;
606 default:
607 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.");
608 break;
609 }
610 ret = mkv_write_codecprivate(s, pb, codec, native_id);
611 if (ret < 0) return ret;
612
613 end_ebml_master(pb, track);
614
615 // ms precision is the de-facto standard timescale for mkv files
616 av_set_pts_info(st, 64, 1, 1000);
617 }
618 end_ebml_master(pb, tracks);
619 return 0;
620}
621
622static int mkv_write_header(AVFormatContext *s)
623{
624 MatroskaMuxContext *mkv = s->priv_data;
625 ByteIOContext *pb = s->pb;
626 ebml_master ebml_header, segment_info;
627 int ret;
628
629 mkv->md5_ctx = av_mallocz(av_md5_size);
630 av_md5_init(mkv->md5_ctx);
631
632 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
633 put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
634 put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
635 put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
636 put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
637 put_ebml_string (pb, EBML_ID_DOCTYPE , "matroska");
638 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , 2);
639 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
640 end_ebml_master(pb, ebml_header);
641
642 mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
643 mkv->segment_offset = url_ftell(pb);
644
645 // we write 2 seek heads - one at the end of the file to point to each
646 // cluster, and one at the beginning to point to all other level one
647 // elements (including the seek head at the end of the file), which
648 // isn't more than 10 elements if we only write one of each other
649 // currently defined level 1 element
650 mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
651 mkv->cluster_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 0);
652 if (mkv->main_seekhead == NULL || mkv->cluster_seekhead == NULL)
653 return AVERROR(ENOMEM);
654
655 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, url_ftell(pb));
656 if (ret < 0) return ret;
657
658 segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
659 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
660 if (strlen(s->title))
661 put_ebml_string(pb, MATROSKA_ID_TITLE, s->title);
662 if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
663 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
664 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
665
666 // reserve space to write the segment UID later
667 mkv->segment_uid = url_ftell(pb);
668 put_ebml_void(pb, 19);
669 }
670
671 // reserve space for the duration
672 mkv->duration = 0;
673 mkv->duration_offset = url_ftell(pb);
674 put_ebml_void(pb, 11); // assumes double-precision float to be written
675 end_ebml_master(pb, segment_info);
676
677 ret = mkv_write_tracks(s);
678 if (ret < 0) return ret;
679
680 ret = mkv_add_seekhead_entry(mkv->cluster_seekhead, MATROSKA_ID_CLUSTER, url_ftell(pb));
681 if (ret < 0) return ret;
682
683 mkv->cluster_pos = url_ftell(pb);
684 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
685 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, 0);
686 mkv->cluster_pts = 0;
687
688 mkv->cues = mkv_start_cues(mkv->segment_offset);
689 if (mkv->cues == NULL)
690 return AVERROR(ENOMEM);
691
692 return 0;
693}
694
695static int mkv_block_size(AVPacket *pkt)
696{
697 int size = 4; // track num + timecode + flags
698 return size + pkt->size;
699}
700
701static int mkv_blockgroup_size(AVPacket *pkt)
702{
703 int size = mkv_block_size(pkt);
704 size += ebml_num_size(size);
705 size += 2; // EBML ID for block and block duration
706 size += 8; // max size of block duration
707 size += ebml_num_size(size);
708 size += 1; // blockgroup EBML ID
709 return size;
710}
711
712static void mkv_write_block(AVFormatContext *s, unsigned int blockid, AVPacket *pkt, int flags)
713{
714 MatroskaMuxContext *mkv = s->priv_data;
715 ByteIOContext *pb = s->pb;
716
717 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
718 "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
719 url_ftell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
720 put_ebml_id(pb, blockid);
721 put_ebml_num(pb, mkv_block_size(pkt), 0);
722 put_byte(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
723 put_be16(pb, pkt->pts - mkv->cluster_pts);
724 put_byte(pb, flags);
725 put_buffer(pb, pkt->data, pkt->size);
726}
727
728static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
729{
730 MatroskaMuxContext *mkv = s->priv_data;
731 ByteIOContext *pb = s->pb;
732 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
733 int keyframe = !!(pkt->flags & PKT_FLAG_KEY);
734 int ret;
735
736 // start a new cluster every 5 MB or 5 sec
737 if (url_ftell(pb) > mkv->cluster_pos + 5*1024*1024 || pkt->pts > mkv->cluster_pts + 5000) {
738 av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
739 " bytes, pts %" PRIu64 "\n", url_ftell(pb), pkt->pts);
740 end_ebml_master(pb, mkv->cluster);
741
742 ret = mkv_add_seekhead_entry(mkv->cluster_seekhead, MATROSKA_ID_CLUSTER, url_ftell(pb));
743 if (ret < 0) return ret;
744
745 mkv->cluster_pos = url_ftell(pb);
746 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
747 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, pkt->pts);
748 mkv->cluster_pts = pkt->pts;
749 av_md5_update(mkv->md5_ctx, pkt->data, FFMIN(200, pkt->size));
750 }
751
752 if (codec->codec_id == CODEC_ID_H264 &&
753 codec->extradata_size > 0 && AV_RB32(codec->extradata) == 0x00000001) {
754 /* from x264 or from bytestream h264 */
755 /* nal reformating needed */
756 int ret = ff_avc_parse_nal_units(pkt->data, &pkt->data, &pkt->size);
757 if (ret < 0)
758 return ret;
759 assert(pkt->size);
760 }
761
762 if (codec->codec_type != CODEC_TYPE_SUBTITLE) {
763 mkv_write_block(s, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
764 } else {
765 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt));
766 mkv_write_block(s, MATROSKA_ID_BLOCK, pkt, 0);
767 put_ebml_uint(pb, MATROSKA_ID_DURATION, pkt->duration);
768 end_ebml_master(pb, blockgroup);
769 }
770
771 if (codec->codec_type == CODEC_TYPE_VIDEO && keyframe) {
772 ret = mkv_add_cuepoint(mkv->cues, pkt, mkv->cluster_pos);
773 if (ret < 0) return ret;
774 }
775
776 mkv->duration = FFMAX(mkv->duration, pkt->pts + pkt->duration);
777 return 0;
778}
779
780static int mkv_write_trailer(AVFormatContext *s)
781{
782 MatroskaMuxContext *mkv = s->priv_data;
783 ByteIOContext *pb = s->pb;
784 offset_t currentpos, second_seekhead, cuespos;
785 int ret;
786
787 end_ebml_master(pb, mkv->cluster);
788
789 if (!url_is_streamed(pb)) {
790 cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
791 second_seekhead = mkv_write_seekhead(pb, mkv->cluster_seekhead);
792
793 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES , cuespos);
794 if (ret < 0) return ret;
795 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_SEEKHEAD, second_seekhead);
796 if (ret < 0) return ret;
797 mkv_write_seekhead(pb, mkv->main_seekhead);
798
799 // update the duration
800 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
801 currentpos = url_ftell(pb);
802 url_fseek(pb, mkv->duration_offset, SEEK_SET);
803 put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
804
805 // write the md5sum of some frames as the segment UID
806 if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
807 uint8_t segment_uid[16];
808 av_md5_final(mkv->md5_ctx, segment_uid);
809 url_fseek(pb, mkv->segment_uid, SEEK_SET);
810 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
811 }
812 url_fseek(pb, currentpos, SEEK_SET);
813 }
814
815 end_ebml_master(pb, mkv->segment);
816 av_free(mkv->md5_ctx);
817 return 0;
818}
819
820AVOutputFormat matroska_muxer = {
821 "matroska",
822 NULL_IF_CONFIG_SMALL("Matroska file format"),
823 "video/x-matroska",
824 "mkv",
825 sizeof(MatroskaMuxContext),
826 CODEC_ID_MP2,
827 CODEC_ID_MPEG4,
828 mkv_write_header,
829 mkv_write_packet,
830 mkv_write_trailer,
831 .codec_tag = (const AVCodecTag*[]){codec_bmp_tags, codec_wav_tags, 0},
832 .subtitle_codec = CODEC_ID_TEXT,
833};
834
835AVOutputFormat matroska_audio_muxer = {
836 "matroska",
837 NULL_IF_CONFIG_SMALL("Matroska file format"),
838 "audio/x-matroska",
839 "mka",
840 sizeof(MatroskaMuxContext),
841 CODEC_ID_MP2,
842 CODEC_ID_NONE,
843 mkv_write_header,
844 mkv_write_packet,
845 mkv_write_trailer,
846 .codec_tag = (const AVCodecTag*[]){codec_wav_tags, 0},
847};
diff --git a/src/plugins/ffmpeg/libavformat/mm.c b/src/plugins/ffmpeg/libavformat/mm.c
deleted file mode 100644
index 67d2a94..0000000
--- a/src/plugins/ffmpeg/libavformat/mm.c
+++ /dev/null
@@ -1,191 +0,0 @@
1/*
2 * American Laser Games MM Format Demuxer
3 * Copyright (c) 2006 Peter Ross
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/**
23 * @file mm.c
24 * American Laser Games MM Format Demuxer
25 * by Peter Ross (suxen_drol at hotmail dot com)
26 *
27 * The MM format was used by IBM-PC ports of ALG's "arcade shooter" games,
28 * including Mad Dog McCree and Crime Patrol.
29 *
30 * Technical details here:
31 * http://wiki.multimedia.cx/index.php?title=American_Laser_Games_MM
32 */
33
34#include "avformat.h"
35
36#define MM_PREAMBLE_SIZE 6
37
38#define MM_TYPE_HEADER 0x0
39#define MM_TYPE_INTER 0x5
40#define MM_TYPE_INTRA 0x8
41#define MM_TYPE_INTRA_HH 0xc
42#define MM_TYPE_INTER_HH 0xd
43#define MM_TYPE_INTRA_HHV 0xe
44#define MM_TYPE_INTER_HHV 0xf
45#define MM_TYPE_AUDIO 0x15
46#define MM_TYPE_PALETTE 0x31
47
48#define MM_HEADER_LEN_V 0x16 /* video only */
49#define MM_HEADER_LEN_AV 0x18 /* video + audio */
50
51#define MM_PALETTE_COUNT 128
52#define MM_PALETTE_SIZE (MM_PALETTE_COUNT*3)
53
54typedef struct {
55 unsigned int audio_pts, video_pts;
56} MmDemuxContext;
57
58static int mm_probe(AVProbeData *p)
59{
60 /* the first chunk is always the header */
61 if (AV_RL16(&p->buf[0]) != MM_TYPE_HEADER)
62 return 0;
63 if (AV_RL32(&p->buf[2]) != MM_HEADER_LEN_V && AV_RL32(&p->buf[2]) != MM_HEADER_LEN_AV)
64 return 0;
65
66 /* only return half certainty since this check is a bit sketchy */
67 return AVPROBE_SCORE_MAX / 2;
68}
69
70static int mm_read_header(AVFormatContext *s,
71 AVFormatParameters *ap)
72{
73 MmDemuxContext *mm = s->priv_data;
74 ByteIOContext *pb = s->pb;
75 AVStream *st;
76
77 unsigned int type, length;
78 unsigned int frame_rate, width, height;
79
80 type = get_le16(pb);
81 length = get_le32(pb);
82
83 if (type != MM_TYPE_HEADER)
84 return AVERROR_INVALIDDATA;
85
86 /* read header */
87 get_le16(pb); /* total number of chunks */
88 frame_rate = get_le16(pb);
89 get_le16(pb); /* ibm-pc video bios mode */
90 width = get_le16(pb);
91 height = get_le16(pb);
92 url_fseek(pb, length - 10, SEEK_CUR); /* unknown data */
93
94 /* video stream */
95 st = av_new_stream(s, 0);
96 if (!st)
97 return AVERROR(ENOMEM);
98 st->codec->codec_type = CODEC_TYPE_VIDEO;
99 st->codec->codec_id = CODEC_ID_MMVIDEO;
100 st->codec->codec_tag = 0; /* no fourcc */
101 st->codec->width = width;
102 st->codec->height = height;
103 av_set_pts_info(st, 64, 1, frame_rate);
104
105 /* audio stream */
106 if (length == MM_HEADER_LEN_AV) {
107 st = av_new_stream(s, 0);
108 if (!st)
109 return AVERROR(ENOMEM);
110 st->codec->codec_type = CODEC_TYPE_AUDIO;
111 st->codec->codec_tag = 0; /* no fourcc */
112 st->codec->codec_id = CODEC_ID_PCM_U8;
113 st->codec->channels = 1;
114 st->codec->sample_rate = 8000;
115 av_set_pts_info(st, 64, 1, 8000); /* 8000 hz */
116 }
117
118 mm->audio_pts = 0;
119 mm->video_pts = 0;
120 return 0;
121}
122
123static int mm_read_packet(AVFormatContext *s,
124 AVPacket *pkt)
125{
126 MmDemuxContext *mm = s->priv_data;
127 ByteIOContext *pb = s->pb;
128 unsigned char preamble[MM_PREAMBLE_SIZE];
129 unsigned int type, length;
130
131 while(1) {
132
133 if (get_buffer(pb, preamble, MM_PREAMBLE_SIZE) != MM_PREAMBLE_SIZE) {
134 return AVERROR(EIO);
135 }
136
137 type = AV_RL16(&preamble[0]);
138 length = AV_RL16(&preamble[2]);
139
140 switch(type) {
141 case MM_TYPE_PALETTE :
142 case MM_TYPE_INTER :
143 case MM_TYPE_INTRA :
144 case MM_TYPE_INTRA_HH :
145 case MM_TYPE_INTER_HH :
146 case MM_TYPE_INTRA_HHV :
147 case MM_TYPE_INTER_HHV :
148 /* output preamble + data */
149 if (av_new_packet(pkt, length + MM_PREAMBLE_SIZE))
150 return AVERROR(ENOMEM);
151 memcpy(pkt->data, preamble, MM_PREAMBLE_SIZE);
152 if (get_buffer(pb, pkt->data + MM_PREAMBLE_SIZE, length) != length)
153 return AVERROR(EIO);
154 pkt->size = length + MM_PREAMBLE_SIZE;
155 pkt->stream_index = 0;
156 pkt->pts = mm->video_pts;
157 if (type!=MM_TYPE_PALETTE)
158 mm->video_pts++;
159 return 0;
160
161 case MM_TYPE_AUDIO :
162 if (av_get_packet(s->pb, pkt, length)<0)
163 return AVERROR(ENOMEM);
164 pkt->size = length;
165 pkt->stream_index = 1;
166 pkt->pts = mm->audio_pts++;
167 return 0;
168
169 default :
170 av_log(NULL, AV_LOG_INFO, "mm: unknown chunk type 0x%x\n", type);
171 url_fseek(pb, length, SEEK_CUR);
172 }
173 }
174
175 return 0;
176}
177
178static int mm_read_close(AVFormatContext *s)
179{
180 return 0;
181}
182
183AVInputFormat mm_demuxer = {
184 "mm",
185 NULL_IF_CONFIG_SMALL("American Laser Games MM format"),
186 sizeof(MmDemuxContext),
187 mm_probe,
188 mm_read_header,
189 mm_read_packet,
190 mm_read_close,
191};
diff --git a/src/plugins/ffmpeg/libavformat/mmf.c b/src/plugins/ffmpeg/libavformat/mmf.c
deleted file mode 100644
index 47b84e8..0000000
--- a/src/plugins/ffmpeg/libavformat/mmf.c
+++ /dev/null
@@ -1,323 +0,0 @@
1/*
2 * Yamaha SMAF format
3 * Copyright (c) 2005 Vidar Madsen
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#include "avformat.h"
22#include "raw.h"
23#include "riff.h"
24
25typedef struct {
26 offset_t atrpos, atsqpos, awapos;
27 offset_t data_size;
28} MMFContext;
29
30static int mmf_rates[] = { 4000, 8000, 11025, 22050, 44100 };
31
32static int mmf_rate(int code)
33{
34 if((code < 0) || (code > 4))
35 return -1;
36 return mmf_rates[code];
37}
38
39#ifdef CONFIG_MUXERS
40static int mmf_rate_code(int rate)
41{
42 int i;
43 for(i = 0; i < 5; i++)
44 if(mmf_rates[i] == rate)
45 return i;
46 return -1;
47}
48
49/* Copy of end_tag() from avienc.c, but for big-endian chunk size */
50static void end_tag_be(ByteIOContext *pb, offset_t start)
51{
52 offset_t pos;
53
54 pos = url_ftell(pb);
55 url_fseek(pb, start - 4, SEEK_SET);
56 put_be32(pb, (uint32_t)(pos - start));
57 url_fseek(pb, pos, SEEK_SET);
58}
59
60static int mmf_write_header(AVFormatContext *s)
61{
62 MMFContext *mmf = s->priv_data;
63 ByteIOContext *pb = s->pb;
64 offset_t pos;
65 int rate;
66
67 rate = mmf_rate_code(s->streams[0]->codec->sample_rate);
68 if(rate < 0) {
69 av_log(s, AV_LOG_ERROR, "Unsupported sample rate %d\n", s->streams[0]->codec->sample_rate);
70 return -1;
71 }
72
73 put_tag(pb, "MMMD");
74 put_be32(pb, 0);
75 pos = start_tag(pb, "CNTI");
76 put_byte(pb, 0); /* class */
77 put_byte(pb, 0); /* type */
78 put_byte(pb, 0); /* code type */
79 put_byte(pb, 0); /* status */
80 put_byte(pb, 0); /* counts */
81 put_tag(pb, "VN:libavcodec,"); /* metadata ("ST:songtitle,VN:version,...") */
82 end_tag_be(pb, pos);
83
84 put_buffer(pb, "ATR\x00", 4);
85 put_be32(pb, 0);
86 mmf->atrpos = url_ftell(pb);
87 put_byte(pb, 0); /* format type */
88 put_byte(pb, 0); /* sequence type */
89 put_byte(pb, (0 << 7) | (1 << 4) | rate); /* (channel << 7) | (format << 4) | rate */
90 put_byte(pb, 0); /* wave base bit */
91 put_byte(pb, 2); /* time base d */
92 put_byte(pb, 2); /* time base g */
93
94 put_tag(pb, "Atsq");
95 put_be32(pb, 16);
96 mmf->atsqpos = url_ftell(pb);
97 /* Will be filled on close */
98 put_buffer(pb, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 16);
99
100 mmf->awapos = start_tag(pb, "Awa\x01");
101
102 av_set_pts_info(s->streams[0], 64, 1, s->streams[0]->codec->sample_rate);
103
104 put_flush_packet(pb);
105
106 return 0;
107}
108
109static int mmf_write_packet(AVFormatContext *s, AVPacket *pkt)
110{
111 ByteIOContext *pb = s->pb;
112 put_buffer(pb, pkt->data, pkt->size);
113 return 0;
114}
115
116/* Write a variable-length symbol */
117static void put_varlength(ByteIOContext *pb, int val)
118{
119 if(val < 128)
120 put_byte(pb, val);
121 else {
122 val -= 128;
123 put_byte(pb, 0x80 | val >> 7);
124 put_byte(pb, 0x7f & val);
125 }
126}
127
128static int mmf_write_trailer(AVFormatContext *s)
129{
130 ByteIOContext *pb = s->pb;
131 MMFContext *mmf = s->priv_data;
132 offset_t pos, size;
133 int gatetime;
134
135 if (!url_is_streamed(s->pb)) {
136 /* Fill in length fields */
137 end_tag_be(pb, mmf->awapos);
138 end_tag_be(pb, mmf->atrpos);
139 end_tag_be(pb, 8);
140
141 pos = url_ftell(pb);
142 size = pos - mmf->awapos;
143
144 /* Fill Atsq chunk */
145 url_fseek(pb, mmf->atsqpos, SEEK_SET);
146
147 /* "play wav" */
148 put_byte(pb, 0); /* start time */
149 put_byte(pb, 1); /* (channel << 6) | wavenum */
150 gatetime = size * 500 / s->streams[0]->codec->sample_rate;
151 put_varlength(pb, gatetime); /* duration */
152
153 /* "nop" */
154 put_varlength(pb, gatetime); /* start time */
155 put_buffer(pb, "\xff\x00", 2); /* nop */
156
157 /* "end of sequence" */
158 put_buffer(pb, "\x00\x00\x00\x00", 4);
159
160 url_fseek(pb, pos, SEEK_SET);
161
162 put_flush_packet(pb);
163 }
164 return 0;
165}
166#endif //CONFIG_MUXERS
167
168static int mmf_probe(AVProbeData *p)
169{
170 /* check file header */
171 if (p->buf[0] == 'M' && p->buf[1] == 'M' &&
172 p->buf[2] == 'M' && p->buf[3] == 'D' &&
173 p->buf[8] == 'C' && p->buf[9] == 'N' &&
174 p->buf[10] == 'T' && p->buf[11] == 'I')
175 return AVPROBE_SCORE_MAX;
176 else
177 return 0;
178}
179
180/* mmf input */
181static int mmf_read_header(AVFormatContext *s,
182 AVFormatParameters *ap)
183{
184 MMFContext *mmf = s->priv_data;
185 unsigned int tag;
186 ByteIOContext *pb = s->pb;
187 AVStream *st;
188 offset_t file_size, size;
189 int rate, params;
190
191 tag = get_le32(pb);
192 if (tag != MKTAG('M', 'M', 'M', 'D'))
193 return -1;
194 file_size = get_be32(pb);
195
196 /* Skip some unused chunks that may or may not be present */
197 for(;; url_fseek(pb, size, SEEK_CUR)) {
198 tag = get_le32(pb);
199 size = get_be32(pb);
200 if(tag == MKTAG('C','N','T','I')) continue;
201 if(tag == MKTAG('O','P','D','A')) continue;
202 break;
203 }
204
205 /* Tag = "ATRx", where "x" = track number */
206 if ((tag & 0xffffff) == MKTAG('M', 'T', 'R', 0)) {
207 av_log(s, AV_LOG_ERROR, "MIDI like format found, unsupported\n");
208 return -1;
209 }
210 if ((tag & 0xffffff) != MKTAG('A', 'T', 'R', 0)) {
211 av_log(s, AV_LOG_ERROR, "Unsupported SMAF chunk %08x\n", tag);
212 return -1;
213 }
214
215 get_byte(pb); /* format type */
216 get_byte(pb); /* sequence type */
217 params = get_byte(pb); /* (channel << 7) | (format << 4) | rate */
218 rate = mmf_rate(params & 0x0f);
219 if(rate < 0) {
220 av_log(s, AV_LOG_ERROR, "Invalid sample rate\n");
221 return -1;
222 }
223 get_byte(pb); /* wave base bit */
224 get_byte(pb); /* time base d */
225 get_byte(pb); /* time base g */
226
227 /* Skip some unused chunks that may or may not be present */
228 for(;; url_fseek(pb, size, SEEK_CUR)) {
229 tag = get_le32(pb);
230 size = get_be32(pb);
231 if(tag == MKTAG('A','t','s','q')) continue;
232 if(tag == MKTAG('A','s','p','I')) continue;
233 break;
234 }
235
236 /* Make sure it's followed by an Awa chunk, aka wave data */
237 if ((tag & 0xffffff) != MKTAG('A', 'w', 'a', 0)) {
238 av_log(s, AV_LOG_ERROR, "Unexpected SMAF chunk %08x\n", tag);
239 return -1;
240 }
241 mmf->data_size = size;
242
243 st = av_new_stream(s, 0);
244 if (!st)
245 return AVERROR(ENOMEM);
246
247 st->codec->codec_type = CODEC_TYPE_AUDIO;
248 st->codec->codec_id = CODEC_ID_ADPCM_YAMAHA;
249 st->codec->sample_rate = rate;
250 st->codec->channels = 1;
251 st->codec->bits_per_sample = 4;
252 st->codec->bit_rate = st->codec->sample_rate * st->codec->bits_per_sample;
253
254 av_set_pts_info(st, 64, 1, st->codec->sample_rate);
255
256 return 0;
257}
258
259#define MAX_SIZE 4096
260
261static int mmf_read_packet(AVFormatContext *s,
262 AVPacket *pkt)
263{
264 MMFContext *mmf = s->priv_data;
265 AVStream *st;
266 int ret, size;
267
268 if (url_feof(s->pb))
269 return AVERROR(EIO);
270 st = s->streams[0];
271
272 size = MAX_SIZE;
273 if(size > mmf->data_size)
274 size = mmf->data_size;
275
276 if(!size)
277 return AVERROR(EIO);
278
279 if (av_new_packet(pkt, size))
280 return AVERROR(EIO);
281 pkt->stream_index = 0;
282
283 ret = get_buffer(s->pb, pkt->data, pkt->size);
284 if (ret < 0)
285 av_free_packet(pkt);
286
287 mmf->data_size -= ret;
288
289 pkt->size = ret;
290 return ret;
291}
292
293static int mmf_read_close(AVFormatContext *s)
294{
295 return 0;
296}
297
298#ifdef CONFIG_MMF_DEMUXER
299AVInputFormat mmf_demuxer = {
300 "mmf",
301 NULL_IF_CONFIG_SMALL("mmf format"),
302 sizeof(MMFContext),
303 mmf_probe,
304 mmf_read_header,
305 mmf_read_packet,
306 mmf_read_close,
307 pcm_read_seek,
308};
309#endif
310#ifdef CONFIG_MMF_MUXER
311AVOutputFormat mmf_muxer = {
312 "mmf",
313 NULL_IF_CONFIG_SMALL("mmf format"),
314 "application/vnd.smaf",
315 "mmf",
316 sizeof(MMFContext),
317 CODEC_ID_ADPCM_YAMAHA,
318 CODEC_ID_NONE,
319 mmf_write_header,
320 mmf_write_packet,
321 mmf_write_trailer,
322};
323#endif
diff --git a/src/plugins/ffmpeg/libavformat/mov.c b/src/plugins/ffmpeg/libavformat/mov.c
deleted file mode 100644
index c13f877..0000000
--- a/src/plugins/ffmpeg/libavformat/mov.c
+++ /dev/null
@@ -1,1925 +0,0 @@
1/*
2 * MOV demuxer
3 * Copyright (c) 2001 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 <limits.h>
23
24//#define DEBUG
25
26#include "avformat.h"
27#include "riff.h"
28#include "isom.h"
29#include "dv.h"
30#include "libavcodec/mpeg4audio.h"
31#include "libavcodec/mpegaudiodata.h"
32
33#ifdef CONFIG_ZLIB
34#include <zlib.h>
35#endif
36
37/*
38 * First version by Francois Revol revol@free.fr
39 * Seek function by Gael Chardon gael.dev@4now.net
40 *
41 * Features and limitations:
42 * - reads most of the QT files I have (at least the structure),
43 * Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
44 * - the code is quite ugly... maybe I won't do it recursive next time :-)
45 *
46 * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
47 * when coding this :) (it's a writer anyway)
48 *
49 * Reference documents:
50 * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
51 * Apple:
52 * http://developer.apple.com/documentation/QuickTime/QTFF/
53 * http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
54 * QuickTime is a trademark of Apple (AFAIK :))
55 */
56
57#include "qtpalette.h"
58
59
60#undef NDEBUG
61#include <assert.h>
62
63/* the QuickTime file format is quite convoluted...
64 * it has lots of index tables, each indexing something in another one...
65 * Here we just use what is needed to read the chunks
66 */
67
68typedef struct {
69 int first;
70 int count;
71 int id;
72} MOV_stsc_t;
73
74typedef struct {
75 uint32_t type;
76 char *path;
77} MOV_dref_t;
78
79typedef struct {
80 uint32_t type;
81 int64_t offset;
82 int64_t size; /* total size (excluding the size and type fields) */
83} MOV_atom_t;
84
85struct MOVParseTableEntry;
86
87typedef struct {
88 unsigned track_id;
89 uint64_t base_data_offset;
90 uint64_t moof_offset;
91 unsigned stsd_id;
92 unsigned duration;
93 unsigned size;
94 unsigned flags;
95} MOVFragment;
96
97typedef struct {
98 unsigned track_id;
99 unsigned stsd_id;
100 unsigned duration;
101 unsigned size;
102 unsigned flags;
103} MOVTrackExt;
104
105typedef struct MOVStreamContext {
106 ByteIOContext *pb;
107 int ffindex; /* the ffmpeg stream id */
108 int next_chunk;
109 unsigned int chunk_count;
110 int64_t *chunk_offsets;
111 unsigned int stts_count;
112 MOV_stts_t *stts_data;
113 unsigned int ctts_count;
114 MOV_stts_t *ctts_data;
115 unsigned int edit_count; /* number of 'edit' (elst atom) */
116 unsigned int sample_to_chunk_sz;
117 MOV_stsc_t *sample_to_chunk;
118 int sample_to_ctime_index;
119 int sample_to_ctime_sample;
120 unsigned int sample_size;
121 unsigned int sample_count;
122 int *sample_sizes;
123 unsigned int keyframe_count;
124 int *keyframes;
125 int time_scale;
126 int time_rate;
127 int current_sample;
128 unsigned int bytes_per_frame;
129 unsigned int samples_per_frame;
130 int dv_audio_container;
131 int pseudo_stream_id; ///< -1 means demux all ids
132 int16_t audio_cid; ///< stsd audio compression id
133 unsigned drefs_count;
134 MOV_dref_t *drefs;
135 int dref_id;
136} MOVStreamContext;
137
138typedef struct MOVContext {
139 AVFormatContext *fc;
140 int time_scale;
141 int64_t duration; /* duration of the longest track */
142 int found_moov; /* when both 'moov' and 'mdat' sections has been found */
143 int found_mdat; /* we suppose we have enough data to read the file */
144 AVPaletteControl palette_control;
145 DVDemuxContext *dv_demux;
146 AVFormatContext *dv_fctx;
147 int isom; /* 1 if file is ISO Media (mp4/3gp) */
148 MOVFragment fragment; ///< current fragment in moof atom
149 MOVTrackExt *trex_data;
150 unsigned trex_count;
151} MOVContext;
152
153
154/* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
155
156/* those functions parse an atom */
157/* return code:
158 0: continue to parse next atom
159 <0: error occurred, exit
160*/
161/* links atom IDs to parse functions */
162typedef struct MOVParseTableEntry {
163 uint32_t type;
164 int (*parse)(MOVContext *ctx, ByteIOContext *pb, MOV_atom_t atom);
165} MOVParseTableEntry;
166
167static const MOVParseTableEntry mov_default_parse_table[];
168
169static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
170{
171 int64_t total_size = 0;
172 MOV_atom_t a;
173 int i;
174 int err = 0;
175
176 a.offset = atom.offset;
177
178 if (atom.size < 0)
179 atom.size = INT64_MAX;
180 while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
181 a.size = atom.size;
182 a.type=0;
183 if(atom.size >= 8) {
184 a.size = get_be32(pb);
185 a.type = get_le32(pb);
186 }
187 total_size += 8;
188 a.offset += 8;
189 dprintf(c->fc, "type: %08x %.4s sz: %"PRIx64" %"PRIx64" %"PRIx64"\n",
190 a.type, (char*)&a.type, a.size, atom.size, total_size);
191 if (a.size == 1) { /* 64 bit extended size */
192 a.size = get_be64(pb) - 8;
193 a.offset += 8;
194 total_size += 8;
195 }
196 if (a.size == 0) {
197 a.size = atom.size - total_size;
198 if (a.size <= 8)
199 break;
200 }
201 a.size -= 8;
202 if(a.size < 0)
203 break;
204 a.size = FFMIN(a.size, atom.size - total_size);
205
206 for (i = 0; mov_default_parse_table[i].type != 0
207 && mov_default_parse_table[i].type != a.type; i++)
208 /* empty */;
209
210 if (mov_default_parse_table[i].type == 0) { /* skip leaf atoms data */
211 url_fskip(pb, a.size);
212 } else {
213 offset_t start_pos = url_ftell(pb);
214 int64_t left;
215 err = mov_default_parse_table[i].parse(c, pb, a);
216 if (url_is_streamed(pb) && c->found_moov && c->found_mdat)
217 break;
218 left = a.size - url_ftell(pb) + start_pos;
219 if (left > 0) /* skip garbage at atom end */
220 url_fskip(pb, left);
221 }
222
223 a.offset += a.size;
224 total_size += a.size;
225 }
226
227 if (!err && total_size < atom.size && atom.size < 0x7ffff)
228 url_fskip(pb, atom.size - total_size);
229
230 return err;
231}
232
233static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
234{
235 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
236 MOVStreamContext *sc = st->priv_data;
237 int entries, i, j;
238
239 get_be32(pb); // version + flags
240 entries = get_be32(pb);
241 if (entries >= UINT_MAX / sizeof(*sc->drefs))
242 return -1;
243 sc->drefs_count = entries;
244 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
245
246 for (i = 0; i < sc->drefs_count; i++) {
247 MOV_dref_t *dref = &sc->drefs[i];
248 uint32_t size = get_be32(pb);
249 offset_t next = url_ftell(pb) + size - 4;
250
251 dref->type = get_le32(pb);
252 get_be32(pb); // version + flags
253 dprintf(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
254
255 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
256 /* macintosh alias record */
257 uint16_t volume_len, len;
258 char volume[28];
259 int16_t type;
260
261 url_fskip(pb, 10);
262
263 volume_len = get_byte(pb);
264 volume_len = FFMIN(volume_len, 27);
265 get_buffer(pb, volume, 27);
266 volume[volume_len] = 0;
267 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", volume, volume_len);
268
269 url_fskip(pb, 112);
270
271 for (type = 0; type != -1 && url_ftell(pb) < next; ) {
272 type = get_be16(pb);
273 len = get_be16(pb);
274 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
275 if (len&1)
276 len += 1;
277 if (type == 2) { // absolute path
278 av_free(dref->path);
279 dref->path = av_mallocz(len+1);
280 if (!dref->path)
281 return AVERROR(ENOMEM);
282 get_buffer(pb, dref->path, len);
283 if (len > volume_len && !strncmp(dref->path, volume, volume_len)) {
284 len -= volume_len;
285 memmove(dref->path, dref->path+volume_len, len);
286 dref->path[len] = 0;
287 }
288 for (j = 0; j < len; j++)
289 if (dref->path[j] == ':')
290 dref->path[j] = '/';
291 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
292 } else
293 url_fskip(pb, len);
294 }
295 }
296 url_fseek(pb, next, SEEK_SET);
297 }
298 return 0;
299}
300
301static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
302{
303 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
304 uint32_t type;
305 uint32_t ctype;
306
307 get_byte(pb); /* version */
308 get_be24(pb); /* flags */
309
310 /* component type */
311 ctype = get_le32(pb);
312 type = get_le32(pb); /* component subtype */
313
314 dprintf(c->fc, "ctype= %c%c%c%c (0x%08x)\n", *((char *)&ctype), ((char *)&ctype)[1],
315 ((char *)&ctype)[2], ((char *)&ctype)[3], (int) ctype);
316 dprintf(c->fc, "stype= %c%c%c%c\n",
317 *((char *)&type), ((char *)&type)[1], ((char *)&type)[2], ((char *)&type)[3]);
318 if(!ctype)
319 c->isom = 1;
320 if (type == MKTAG('v','i','d','e'))
321 st->codec->codec_type = CODEC_TYPE_VIDEO;
322 else if(type == MKTAG('s','o','u','n'))
323 st->codec->codec_type = CODEC_TYPE_AUDIO;
324 else if(type == MKTAG('m','1','a',' '))
325 st->codec->codec_id = CODEC_ID_MP2;
326 else if(type == MKTAG('s','u','b','p')) {
327 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
328 }
329 get_be32(pb); /* component manufacture */
330 get_be32(pb); /* component flags */
331 get_be32(pb); /* component flags mask */
332
333 if(atom.size <= 24)
334 return 0; /* nothing left to read */
335
336 url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
337 return 0;
338}
339
340static int mp4_read_descr_len(ByteIOContext *pb)
341{
342 int len = 0;
343 int count = 4;
344 while (count--) {
345 int c = get_byte(pb);
346 len = (len << 7) | (c & 0x7f);
347 if (!(c & 0x80))
348 break;
349 }
350 return len;
351}
352
353static int mp4_read_descr(MOVContext *c, ByteIOContext *pb, int *tag)
354{
355 int len;
356 *tag = get_byte(pb);
357 len = mp4_read_descr_len(pb);
358 dprintf(c->fc, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
359 return len;
360}
361
362#define MP4ESDescrTag 0x03
363#define MP4DecConfigDescrTag 0x04
364#define MP4DecSpecificDescrTag 0x05
365
366static const AVCodecTag mp4_audio_types[] = {
367 { CODEC_ID_MP3ON4, 29 }, /* old mp3on4 draft */
368 { CODEC_ID_MP3ON4, 32 }, /* layer 1 */
369 { CODEC_ID_MP3ON4, 33 }, /* layer 2 */
370 { CODEC_ID_MP3ON4, 34 }, /* layer 3 */
371 { CODEC_ID_NONE, 0 },
372};
373
374static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
375{
376 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
377 int tag, len;
378
379 get_be32(pb); /* version + flags */
380 len = mp4_read_descr(c, pb, &tag);
381 if (tag == MP4ESDescrTag) {
382 get_be16(pb); /* ID */
383 get_byte(pb); /* priority */
384 } else
385 get_be16(pb); /* ID */
386
387 len = mp4_read_descr(c, pb, &tag);
388 if (tag == MP4DecConfigDescrTag) {
389 int object_type_id = get_byte(pb);
390 get_byte(pb); /* stream type */
391 get_be24(pb); /* buffer size db */
392 get_be32(pb); /* max bitrate */
393 get_be32(pb); /* avg bitrate */
394
395 st->codec->codec_id= codec_get_id(ff_mp4_obj_type, object_type_id);
396 dprintf(c->fc, "esds object type id %d\n", object_type_id);
397 len = mp4_read_descr(c, pb, &tag);
398 if (tag == MP4DecSpecificDescrTag) {
399 dprintf(c->fc, "Specific MPEG4 header len=%d\n", len);
400 if((uint64_t)len > (1<<30))
401 return -1;
402 st->codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
403 if (!st->codec->extradata)
404 return AVERROR(ENOMEM);
405 get_buffer(pb, st->codec->extradata, len);
406 st->codec->extradata_size = len;
407 if (st->codec->codec_id == CODEC_ID_AAC) {
408 MPEG4AudioConfig cfg;
409 ff_mpeg4audio_get_config(&cfg, st->codec->extradata,
410 st->codec->extradata_size);
411 if (cfg.chan_config > 7)
412 return -1;
413 st->codec->channels = ff_mpeg4audio_channels[cfg.chan_config];
414 if (cfg.object_type == 29 && cfg.sampling_index < 3) // old mp3on4
415 st->codec->sample_rate = ff_mpa_freq_tab[cfg.sampling_index];
416 else
417 st->codec->sample_rate = cfg.sample_rate; // ext sample rate ?
418 dprintf(c->fc, "mp4a config channels %d obj %d ext obj %d "
419 "sample rate %d ext sample rate %d\n", st->codec->channels,
420 cfg.object_type, cfg.ext_object_type,
421 cfg.sample_rate, cfg.ext_sample_rate);
422 if (!(st->codec->codec_id = codec_get_id(mp4_audio_types,
423 cfg.object_type)))
424 st->codec->codec_id = CODEC_ID_AAC;
425 }
426 }
427 }
428 return 0;
429}
430
431/* this atom contains actual media data */
432static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
433{
434 if(atom.size == 0) /* wrong one (MP4) */
435 return 0;
436 c->found_mdat=1;
437 return 0; /* now go for moov */
438}
439
440static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
441{
442 uint32_t type = get_le32(pb);
443
444 if (type != MKTAG('q','t',' ',' '))
445 c->isom = 1;
446 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
447 get_be32(pb); /* minor version */
448 url_fskip(pb, atom.size - 8);
449 return 0;
450}
451
452/* this atom should contain all header atoms */
453static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
454{
455 if (mov_read_default(c, pb, atom) < 0)
456 return -1;
457 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
458 /* so we don't parse the whole file if over a network */
459 c->found_moov=1;
460 return 0; /* now go for mdat */
461}
462
463static int mov_read_moof(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
464{
465 c->fragment.moof_offset = url_ftell(pb) - 8;
466 dprintf(c->fc, "moof offset %llx\n", c->fragment.moof_offset);
467 return mov_read_default(c, pb, atom);
468}
469
470static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
471{
472 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
473 MOVStreamContext *sc = st->priv_data;
474 int version = get_byte(pb);
475 int lang;
476
477 if (version > 1)
478 return -1; /* unsupported */
479
480 get_be24(pb); /* flags */
481 if (version == 1) {
482 get_be64(pb);
483 get_be64(pb);
484 } else {
485 get_be32(pb); /* creation time */
486 get_be32(pb); /* modification time */
487 }
488
489 sc->time_scale = get_be32(pb);
490 st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
491
492 lang = get_be16(pb); /* language */
493 ff_mov_lang_to_iso639(lang, st->language);
494 get_be16(pb); /* quality */
495
496 return 0;
497}
498
499static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
500{
501 int version = get_byte(pb); /* version */
502 get_be24(pb); /* flags */
503
504 if (version == 1) {
505 get_be64(pb);
506 get_be64(pb);
507 } else {
508 get_be32(pb); /* creation time */
509 get_be32(pb); /* modification time */
510 }
511 c->time_scale = get_be32(pb); /* time scale */
512
513 dprintf(c->fc, "time scale = %i\n", c->time_scale);
514
515 c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
516 get_be32(pb); /* preferred scale */
517
518 get_be16(pb); /* preferred volume */
519
520 url_fskip(pb, 10); /* reserved */
521
522 url_fskip(pb, 36); /* display matrix */
523
524 get_be32(pb); /* preview time */
525 get_be32(pb); /* preview duration */
526 get_be32(pb); /* poster time */
527 get_be32(pb); /* selection time */
528 get_be32(pb); /* selection duration */
529 get_be32(pb); /* current time */
530 get_be32(pb); /* next track ID */
531
532 return 0;
533}
534
535static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
536{
537 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
538
539 if((uint64_t)atom.size > (1<<30))
540 return -1;
541
542 // currently SVQ3 decoder expect full STSD header - so let's fake it
543 // this should be fixed and just SMI header should be passed
544 av_free(st->codec->extradata);
545 st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
546 if (!st->codec->extradata)
547 return AVERROR(ENOMEM);
548 st->codec->extradata_size = 0x5a + atom.size;
549 memcpy(st->codec->extradata, "SVQ3", 4); // fake
550 get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
551 dprintf(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
552 return 0;
553}
554
555static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
556{
557 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
558 int little_endian = get_be16(pb);
559
560 if (little_endian) {
561 switch (st->codec->codec_id) {
562 case CODEC_ID_PCM_S24BE:
563 st->codec->codec_id = CODEC_ID_PCM_S24LE;
564 break;
565 case CODEC_ID_PCM_S32BE:
566 st->codec->codec_id = CODEC_ID_PCM_S32LE;
567 break;
568 default:
569 break;
570 }
571 }
572 return 0;
573}
574
575/* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
576static int mov_read_extradata(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
577{
578 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
579 uint64_t size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
580 uint8_t *buf;
581 if(size > INT_MAX || (uint64_t)atom.size > INT_MAX)
582 return -1;
583 buf= av_realloc(st->codec->extradata, size);
584 if(!buf)
585 return -1;
586 st->codec->extradata= buf;
587 buf+= st->codec->extradata_size;
588 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
589 AV_WB32( buf , atom.size + 8);
590 AV_WL32( buf + 4, atom.type);
591 get_buffer(pb, buf + 8, atom.size);
592 return 0;
593}
594
595static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
596{
597 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
598
599 if((uint64_t)atom.size > (1<<30))
600 return -1;
601
602 if (st->codec->codec_id == CODEC_ID_QDM2) {
603 // pass all frma atom to codec, needed at least for QDM2
604 av_free(st->codec->extradata);
605 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
606 if (!st->codec->extradata)
607 return AVERROR(ENOMEM);
608 st->codec->extradata_size = atom.size;
609 get_buffer(pb, st->codec->extradata, atom.size);
610 } else if (atom.size > 8) { /* to read frma, esds atoms */
611 if (mov_read_default(c, pb, atom) < 0)
612 return -1;
613 } else
614 url_fskip(pb, atom.size);
615 return 0;
616}
617
618/**
619 * This function reads atom content and puts data in extradata without tag
620 * nor size unlike mov_read_extradata.
621 */
622static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
623{
624 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
625
626 if((uint64_t)atom.size > (1<<30))
627 return -1;
628
629 av_free(st->codec->extradata);
630 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
631 if (!st->codec->extradata)
632 return AVERROR(ENOMEM);
633 st->codec->extradata_size = atom.size;
634 get_buffer(pb, st->codec->extradata, atom.size);
635 return 0;
636}
637
638static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
639{
640 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
641 MOVStreamContext *sc = st->priv_data;
642 unsigned int i, entries;
643
644 get_byte(pb); /* version */
645 get_be24(pb); /* flags */
646
647 entries = get_be32(pb);
648
649 if(entries >= UINT_MAX/sizeof(int64_t))
650 return -1;
651
652 sc->chunk_count = entries;
653 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
654 if (!sc->chunk_offsets)
655 return -1;
656 if (atom.type == MKTAG('s','t','c','o'))
657 for(i=0; i<entries; i++)
658 sc->chunk_offsets[i] = get_be32(pb);
659 else if (atom.type == MKTAG('c','o','6','4'))
660 for(i=0; i<entries; i++)
661 sc->chunk_offsets[i] = get_be64(pb);
662 else
663 return -1;
664
665 return 0;
666}
667
668static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
669{
670 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
671 MOVStreamContext *sc = st->priv_data;
672 int j, entries, pseudo_stream_id;
673
674 get_byte(pb); /* version */
675 get_be24(pb); /* flags */
676
677 entries = get_be32(pb);
678
679 for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
680 //Parsing Sample description table
681 enum CodecID id;
682 int dref_id;
683 MOV_atom_t a = { 0, 0, 0 };
684 offset_t start_pos = url_ftell(pb);
685 int size = get_be32(pb); /* size */
686 uint32_t format = get_le32(pb); /* data format */
687
688 get_be32(pb); /* reserved */
689 get_be16(pb); /* reserved */
690 dref_id = get_be16(pb);
691
692 if (st->codec->codec_tag &&
693 st->codec->codec_tag != format &&
694 (c->fc->video_codec_id ? codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
695 : st->codec->codec_tag != MKTAG('j','p','e','g'))
696 ){
697 /* Multiple fourcc, we skip JPEG. This is not correct, we should
698 * export it as a separate AVStream but this needs a few changes
699 * in the MOV demuxer, patch welcome. */
700 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
701 url_fskip(pb, size - (url_ftell(pb) - start_pos));
702 continue;
703 }
704 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
705 sc->dref_id= dref_id;
706
707 st->codec->codec_tag = format;
708 id = codec_get_id(codec_movaudio_tags, format);
709 if (id<=0 && (format&0xFFFF) == 'm'+('s'<<8))
710 id = codec_get_id(codec_wav_tags, bswap_32(format)&0xFFFF);
711
712 if (st->codec->codec_type != CODEC_TYPE_VIDEO && id > 0) {
713 st->codec->codec_type = CODEC_TYPE_AUDIO;
714 } else if (st->codec->codec_type != CODEC_TYPE_AUDIO && /* do not overwrite codec type */
715 format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
716 id = codec_get_id(codec_movvideo_tags, format);
717 if (id <= 0)
718 id = codec_get_id(codec_bmp_tags, format);
719 if (id > 0)
720 st->codec->codec_type = CODEC_TYPE_VIDEO;
721 else if(st->codec->codec_type == CODEC_TYPE_DATA){
722 id = codec_get_id(ff_codec_movsubtitle_tags, format);
723 if(id > 0)
724 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
725 }
726 }
727
728 dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
729 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
730 (format >> 24) & 0xff, st->codec->codec_type);
731
732 if(st->codec->codec_type==CODEC_TYPE_VIDEO) {
733 uint8_t codec_name[32];
734 unsigned int color_depth;
735 int color_greyscale;
736
737 st->codec->codec_id = id;
738 get_be16(pb); /* version */
739 get_be16(pb); /* revision level */
740 get_be32(pb); /* vendor */
741 get_be32(pb); /* temporal quality */
742 get_be32(pb); /* spatial quality */
743
744 st->codec->width = get_be16(pb); /* width */
745 st->codec->height = get_be16(pb); /* height */
746
747 get_be32(pb); /* horiz resolution */
748 get_be32(pb); /* vert resolution */
749 get_be32(pb); /* data size, always 0 */
750 get_be16(pb); /* frames per samples */
751
752 get_buffer(pb, codec_name, 32); /* codec name, pascal string */
753 if (codec_name[0] <= 31) {
754 memcpy(st->codec->codec_name, &codec_name[1],codec_name[0]);
755 st->codec->codec_name[codec_name[0]] = 0;
756 }
757
758 st->codec->bits_per_sample = get_be16(pb); /* depth */
759 st->codec->color_table_id = get_be16(pb); /* colortable id */
760 dprintf(c->fc, "depth %d, ctab id %d\n",
761 st->codec->bits_per_sample, st->codec->color_table_id);
762 /* figure out the palette situation */
763 color_depth = st->codec->bits_per_sample & 0x1F;
764 color_greyscale = st->codec->bits_per_sample & 0x20;
765
766 /* if the depth is 2, 4, or 8 bpp, file is palettized */
767 if ((color_depth == 2) || (color_depth == 4) ||
768 (color_depth == 8)) {
769 /* for palette traversal */
770 unsigned int color_start, color_count, color_end;
771 unsigned char r, g, b;
772
773 if (color_greyscale) {
774 int color_index, color_dec;
775 /* compute the greyscale palette */
776 st->codec->bits_per_sample = color_depth;
777 color_count = 1 << color_depth;
778 color_index = 255;
779 color_dec = 256 / (color_count - 1);
780 for (j = 0; j < color_count; j++) {
781 r = g = b = color_index;
782 c->palette_control.palette[j] =
783 (r << 16) | (g << 8) | (b);
784 color_index -= color_dec;
785 if (color_index < 0)
786 color_index = 0;
787 }
788 } else if (st->codec->color_table_id) {
789 const uint8_t *color_table;
790 /* if flag bit 3 is set, use the default palette */
791 color_count = 1 << color_depth;
792 if (color_depth == 2)
793 color_table = ff_qt_default_palette_4;
794 else if (color_depth == 4)
795 color_table = ff_qt_default_palette_16;
796 else
797 color_table = ff_qt_default_palette_256;
798
799 for (j = 0; j < color_count; j++) {
800 r = color_table[j * 4 + 0];
801 g = color_table[j * 4 + 1];
802 b = color_table[j * 4 + 2];
803 c->palette_control.palette[j] =
804 (r << 16) | (g << 8) | (b);
805 }
806 } else {
807 /* load the palette from the file */
808 color_start = get_be32(pb);
809 color_count = get_be16(pb);
810 color_end = get_be16(pb);
811 if ((color_start <= 255) &&
812 (color_end <= 255)) {
813 for (j = color_start; j <= color_end; j++) {
814 /* each R, G, or B component is 16 bits;
815 * only use the top 8 bits; skip alpha bytes
816 * up front */
817 get_byte(pb);
818 get_byte(pb);
819 r = get_byte(pb);
820 get_byte(pb);
821 g = get_byte(pb);
822 get_byte(pb);
823 b = get_byte(pb);
824 get_byte(pb);
825 c->palette_control.palette[j] =
826 (r << 16) | (g << 8) | (b);
827 }
828 }
829 }
830 st->codec->palctrl = &c->palette_control;
831 st->codec->palctrl->palette_changed = 1;
832 } else
833 st->codec->palctrl = NULL;
834 } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {
835 int bits_per_sample;
836 uint16_t version = get_be16(pb);
837
838 st->codec->codec_id = id;
839 get_be16(pb); /* revision level */
840 get_be32(pb); /* vendor */
841
842 st->codec->channels = get_be16(pb); /* channel count */
843 dprintf(c->fc, "audio channels %d\n", st->codec->channels);
844 st->codec->bits_per_sample = get_be16(pb); /* sample size */
845
846 sc->audio_cid = get_be16(pb);
847 get_be16(pb); /* packet size = 0 */
848
849 st->codec->sample_rate = ((get_be32(pb) >> 16));
850
851 switch (st->codec->codec_id) {
852 case CODEC_ID_PCM_S8:
853 case CODEC_ID_PCM_U8:
854 if (st->codec->bits_per_sample == 16)
855 st->codec->codec_id = CODEC_ID_PCM_S16BE;
856 break;
857 case CODEC_ID_PCM_S16LE:
858 case CODEC_ID_PCM_S16BE:
859 if (st->codec->bits_per_sample == 8)
860 st->codec->codec_id = CODEC_ID_PCM_S8;
861 else if (st->codec->bits_per_sample == 24)
862 st->codec->codec_id = CODEC_ID_PCM_S24BE;
863 break;
864 /* set values for old format before stsd version 1 appeared */
865 case CODEC_ID_MACE3:
866 sc->samples_per_frame = 6;
867 sc->bytes_per_frame = 2*st->codec->channels;
868 break;
869 case CODEC_ID_MACE6:
870 sc->samples_per_frame = 6;
871 sc->bytes_per_frame = 1*st->codec->channels;
872 break;
873 case CODEC_ID_ADPCM_IMA_QT:
874 sc->samples_per_frame = 64;
875 sc->bytes_per_frame = 34*st->codec->channels;
876 break;
877 case CODEC_ID_GSM:
878 sc->samples_per_frame = 160;
879 sc->bytes_per_frame = 33;
880 break;
881 default:
882 break;
883 }
884
885 //Read QT version 1 fields. In version 0 these do not exist.
886 dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);
887 if(!c->isom) {
888 if(version==1) {
889 sc->samples_per_frame = get_be32(pb);
890 get_be32(pb); /* bytes per packet */
891 sc->bytes_per_frame = get_be32(pb);
892 get_be32(pb); /* bytes per sample */
893 } else if(version==2) {
894 get_be32(pb); /* sizeof struct only */
895 st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
896 st->codec->channels = get_be32(pb);
897 get_be32(pb); /* always 0x7F000000 */
898 get_be32(pb); /* bits per channel if sound is uncompressed */
899 get_be32(pb); /* lcpm format specific flag */
900 get_be32(pb); /* bytes per audio packet if constant */
901 get_be32(pb); /* lpcm frames per audio packet if constant */
902 }
903 }
904
905 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
906 if (bits_per_sample) {
907 st->codec->bits_per_sample = bits_per_sample;
908 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
909 }
910 } else if(st->codec->codec_type==CODEC_TYPE_SUBTITLE){
911 st->codec->codec_id= id;
912 } else {
913 /* other codec type, just skip (rtp, mp4s, tmcd ...) */
914 url_fskip(pb, size - (url_ftell(pb) - start_pos));
915 }
916 /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
917 a.size = size - (url_ftell(pb) - start_pos);
918 if (a.size > 8) {
919 if (mov_read_default(c, pb, a) < 0)
920 return -1;
921 } else if (a.size > 0)
922 url_fskip(pb, a.size);
923 }
924
925 if(st->codec->codec_type==CODEC_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
926 st->codec->sample_rate= sc->time_scale;
927
928 /* special codec parameters handling */
929 switch (st->codec->codec_id) {
930#ifdef CONFIG_DV_DEMUXER
931 case CODEC_ID_DVAUDIO:
932 c->dv_fctx = av_alloc_format_context();
933 c->dv_demux = dv_init_demux(c->dv_fctx);
934 if (!c->dv_demux) {
935 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
936 return -1;
937 }
938 sc->dv_audio_container = 1;
939 st->codec->codec_id = CODEC_ID_PCM_S16LE;
940 break;
941#endif
942 /* no ifdef since parameters are always those */
943 case CODEC_ID_AMR_WB:
944 st->codec->sample_rate= 16000;
945 st->codec->channels= 1; /* really needed */
946 break;
947 case CODEC_ID_QCELP:
948 case CODEC_ID_AMR_NB:
949 st->codec->frame_size= sc->samples_per_frame;
950 st->codec->sample_rate= 8000;
951 st->codec->channels= 1; /* really needed */
952 break;
953 case CODEC_ID_MP2:
954 case CODEC_ID_MP3:
955 st->codec->codec_type = CODEC_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
956 st->need_parsing = AVSTREAM_PARSE_FULL;
957 break;
958 case CODEC_ID_GSM:
959 case CODEC_ID_ADPCM_MS:
960 case CODEC_ID_ADPCM_IMA_WAV:
961 st->codec->block_align = sc->bytes_per_frame;
962 break;
963 case CODEC_ID_ALAC:
964 if (st->codec->extradata_size == 36)
965 st->codec->frame_size = AV_RB32((st->codec->extradata+12));
966 break;
967 default:
968 break;
969 }
970
971 return 0;
972}
973
974static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
975{
976 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
977 MOVStreamContext *sc = st->priv_data;
978 unsigned int i, entries;
979
980 get_byte(pb); /* version */
981 get_be24(pb); /* flags */
982
983 entries = get_be32(pb);
984
985 if(entries >= UINT_MAX / sizeof(MOV_stsc_t))
986 return -1;
987
988 dprintf(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
989
990 sc->sample_to_chunk_sz = entries;
991 sc->sample_to_chunk = av_malloc(entries * sizeof(MOV_stsc_t));
992 if (!sc->sample_to_chunk)
993 return -1;
994 for(i=0; i<entries; i++) {
995 sc->sample_to_chunk[i].first = get_be32(pb);
996 sc->sample_to_chunk[i].count = get_be32(pb);
997 sc->sample_to_chunk[i].id = get_be32(pb);
998 }
999 return 0;
1000}
1001
1002static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1003{
1004 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1005 MOVStreamContext *sc = st->priv_data;
1006 unsigned int i, entries;
1007
1008 get_byte(pb); /* version */
1009 get_be24(pb); /* flags */
1010
1011 entries = get_be32(pb);
1012
1013 if(entries >= UINT_MAX / sizeof(int))
1014 return -1;
1015
1016 sc->keyframe_count = entries;
1017
1018 dprintf(c->fc, "keyframe_count = %d\n", sc->keyframe_count);
1019
1020 sc->keyframes = av_malloc(entries * sizeof(int));
1021 if (!sc->keyframes)
1022 return -1;
1023 for(i=0; i<entries; i++) {
1024 sc->keyframes[i] = get_be32(pb);
1025 //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1026 }
1027 return 0;
1028}
1029
1030static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1031{
1032 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1033 MOVStreamContext *sc = st->priv_data;
1034 unsigned int i, entries, sample_size;
1035
1036 get_byte(pb); /* version */
1037 get_be24(pb); /* flags */
1038
1039 sample_size = get_be32(pb);
1040 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1041 sc->sample_size = sample_size;
1042 entries = get_be32(pb);
1043 if(entries >= UINT_MAX / sizeof(int))
1044 return -1;
1045
1046 sc->sample_count = entries;
1047 if (sample_size)
1048 return 0;
1049
1050 dprintf(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, sc->sample_count);
1051
1052 sc->sample_sizes = av_malloc(entries * sizeof(int));
1053 if (!sc->sample_sizes)
1054 return -1;
1055 for(i=0; i<entries; i++)
1056 sc->sample_sizes[i] = get_be32(pb);
1057 return 0;
1058}
1059
1060static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1061{
1062 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1063 MOVStreamContext *sc = st->priv_data;
1064 unsigned int i, entries;
1065 int64_t duration=0;
1066 int64_t total_sample_count=0;
1067
1068 get_byte(pb); /* version */
1069 get_be24(pb); /* flags */
1070 entries = get_be32(pb);
1071 if(entries >= UINT_MAX / sizeof(MOV_stts_t))
1072 return -1;
1073
1074 sc->stts_count = entries;
1075 sc->stts_data = av_malloc(entries * sizeof(MOV_stts_t));
1076 if (!sc->stts_data)
1077 return -1;
1078 dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
1079
1080 sc->time_rate=0;
1081
1082 for(i=0; i<entries; i++) {
1083 int sample_duration;
1084 int sample_count;
1085
1086 sample_count=get_be32(pb);
1087 sample_duration = get_be32(pb);
1088 sc->stts_data[i].count= sample_count;
1089 sc->stts_data[i].duration= sample_duration;
1090
1091 sc->time_rate= ff_gcd(sc->time_rate, sample_duration);
1092
1093 dprintf(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
1094
1095 duration+=(int64_t)sample_duration*sample_count;
1096 total_sample_count+=sample_count;
1097 }
1098
1099 st->nb_frames= total_sample_count;
1100 if(duration)
1101 st->duration= duration;
1102 return 0;
1103}
1104
1105static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1106{
1107 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1108 MOVStreamContext *sc = st->priv_data;
1109 unsigned int i, entries;
1110
1111 get_byte(pb); /* version */
1112 get_be24(pb); /* flags */
1113 entries = get_be32(pb);
1114 if(entries >= UINT_MAX / sizeof(MOV_stts_t))
1115 return -1;
1116
1117 sc->ctts_count = entries;
1118 sc->ctts_data = av_malloc(entries * sizeof(MOV_stts_t));
1119 if (!sc->ctts_data)
1120 return -1;
1121 dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1122
1123 for(i=0; i<entries; i++) {
1124 int count =get_be32(pb);
1125 int duration =get_be32(pb);
1126
1127 if (duration < 0) {
1128 av_log(c->fc, AV_LOG_ERROR, "negative ctts, ignoring\n");
1129 sc->ctts_count = 0;
1130 url_fskip(pb, 8 * (entries - i - 1));
1131 break;
1132 }
1133 sc->ctts_data[i].count = count;
1134 sc->ctts_data[i].duration= duration;
1135
1136 sc->time_rate= ff_gcd(sc->time_rate, duration);
1137 }
1138 return 0;
1139}
1140
1141static void mov_build_index(MOVContext *mov, AVStream *st)
1142{
1143 MOVStreamContext *sc = st->priv_data;
1144 offset_t current_offset;
1145 int64_t current_dts = 0;
1146 unsigned int stts_index = 0;
1147 unsigned int stsc_index = 0;
1148 unsigned int stss_index = 0;
1149 unsigned int i, j;
1150
1151 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1152 if (!(st->codec->codec_type == CODEC_TYPE_AUDIO &&
1153 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1154 unsigned int current_sample = 0;
1155 unsigned int stts_sample = 0;
1156 unsigned int keyframe, sample_size;
1157 unsigned int distance = 0;
1158 int key_off = sc->keyframes && sc->keyframes[0] == 1;
1159
1160 st->nb_frames = sc->sample_count;
1161 for (i = 0; i < sc->chunk_count; i++) {
1162 current_offset = sc->chunk_offsets[i];
1163 if (stsc_index + 1 < sc->sample_to_chunk_sz &&
1164 i + 1 == sc->sample_to_chunk[stsc_index + 1].first)
1165 stsc_index++;
1166 for (j = 0; j < sc->sample_to_chunk[stsc_index].count; j++) {
1167 if (current_sample >= sc->sample_count) {
1168 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1169 goto out;
1170 }
1171 keyframe = !sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index];
1172 if (keyframe) {
1173 distance = 0;
1174 if (stss_index + 1 < sc->keyframe_count)
1175 stss_index++;
1176 }
1177 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1178 if(sc->pseudo_stream_id == -1 ||
1179 sc->sample_to_chunk[stsc_index].id - 1 == sc->pseudo_stream_id) {
1180 av_add_index_entry(st, current_offset, current_dts, sample_size, distance,
1181 keyframe ? AVINDEX_KEYFRAME : 0);
1182 dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1183 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1184 current_offset, current_dts, sample_size, distance, keyframe);
1185 }
1186 current_offset += sample_size;
1187 assert(sc->stts_data[stts_index].duration % sc->time_rate == 0);
1188 current_dts += sc->stts_data[stts_index].duration / sc->time_rate;
1189 distance++;
1190 stts_sample++;
1191 current_sample++;
1192 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1193 stts_sample = 0;
1194 stts_index++;
1195 }
1196 }
1197 }
1198 } else { /* read whole chunk */
1199 unsigned int chunk_samples, chunk_size, chunk_duration;
1200 unsigned int frames = 1;
1201 for (i = 0; i < sc->chunk_count; i++) {
1202 current_offset = sc->chunk_offsets[i];
1203 if (stsc_index + 1 < sc->sample_to_chunk_sz &&
1204 i + 1 == sc->sample_to_chunk[stsc_index + 1].first)
1205 stsc_index++;
1206 chunk_samples = sc->sample_to_chunk[stsc_index].count;
1207 /* get chunk size, beware of alaw/ulaw/mace */
1208 if (sc->samples_per_frame > 0 &&
1209 (chunk_samples * sc->bytes_per_frame % sc->samples_per_frame == 0)) {
1210 if (sc->samples_per_frame < 160)
1211 chunk_size = chunk_samples * sc->bytes_per_frame / sc->samples_per_frame;
1212 else {
1213 chunk_size = sc->bytes_per_frame;
1214 frames = chunk_samples / sc->samples_per_frame;
1215 chunk_samples = sc->samples_per_frame;
1216 }
1217 } else
1218 chunk_size = chunk_samples * sc->sample_size;
1219 for (j = 0; j < frames; j++) {
1220 av_add_index_entry(st, current_offset, current_dts, chunk_size, 0, AVINDEX_KEYFRAME);
1221 /* get chunk duration */
1222 chunk_duration = 0;
1223 while (chunk_samples > 0) {
1224 if (chunk_samples < sc->stts_data[stts_index].count) {
1225 chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1226 sc->stts_data[stts_index].count -= chunk_samples;
1227 break;
1228 } else {
1229 chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1230 chunk_samples -= sc->stts_data[stts_index].count;
1231 if (stts_index + 1 < sc->stts_count)
1232 stts_index++;
1233 }
1234 }
1235 current_offset += sc->bytes_per_frame;
1236 dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1237 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
1238 chunk_size, chunk_duration);
1239 assert(chunk_duration % sc->time_rate == 0);
1240 current_dts += chunk_duration / sc->time_rate;
1241 }
1242 }
1243 }
1244 out:
1245 /* adjust sample count to avindex entries */
1246 sc->sample_count = st->nb_index_entries;
1247}
1248
1249static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1250{
1251 AVStream *st;
1252 MOVStreamContext *sc;
1253 int ret;
1254
1255 st = av_new_stream(c->fc, c->fc->nb_streams);
1256 if (!st) return AVERROR(ENOMEM);
1257 sc = av_mallocz(sizeof(MOVStreamContext));
1258 if (!sc) return AVERROR(ENOMEM);
1259
1260 st->priv_data = sc;
1261 st->codec->codec_type = CODEC_TYPE_DATA;
1262 st->start_time = 0; /* XXX: check */
1263
1264 if ((ret = mov_read_default(c, pb, atom)) < 0)
1265 return ret;
1266
1267 /* sanity checks */
1268 if(sc->chunk_count && (!sc->stts_count || !sc->sample_to_chunk_sz ||
1269 (!sc->sample_size && !sc->sample_count))){
1270 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
1271 st->index);
1272 sc->sample_count = 0; //ignore track
1273 return 0;
1274 }
1275 if(!sc->time_rate)
1276 sc->time_rate=1;
1277 if(!sc->time_scale)
1278 sc->time_scale= c->time_scale;
1279 av_set_pts_info(st, 64, sc->time_rate, sc->time_scale);
1280
1281 if (st->codec->codec_type == CODEC_TYPE_AUDIO &&
1282 !st->codec->frame_size && sc->stts_count == 1)
1283 st->codec->frame_size = av_rescale(sc->time_rate, st->codec->sample_rate, sc->time_scale);
1284
1285 if(st->duration != AV_NOPTS_VALUE){
1286 assert(st->duration % sc->time_rate == 0);
1287 st->duration /= sc->time_rate;
1288 }
1289 sc->ffindex = st->index;
1290 mov_build_index(c, st);
1291
1292 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
1293 if (url_fopen(&sc->pb, sc->drefs[sc->dref_id-1].path, URL_RDONLY) < 0)
1294 av_log(c->fc, AV_LOG_ERROR, "stream %d, error opening file %s: %s\n",
1295 st->index, sc->drefs[sc->dref_id-1].path, strerror(errno));
1296 } else
1297 sc->pb = c->fc->pb;
1298
1299 switch (st->codec->codec_id) {
1300#ifdef CONFIG_H261_DECODER
1301 case CODEC_ID_H261:
1302#endif
1303#ifdef CONFIG_H263_DECODER
1304 case CODEC_ID_H263:
1305#endif
1306#ifdef CONFIG_MPEG4_DECODER
1307 case CODEC_ID_MPEG4:
1308#endif
1309 st->codec->width= 0; /* let decoder init width/height */
1310 st->codec->height= 0;
1311 break;
1312#ifdef CONFIG_VORBIS_DECODER
1313 case CODEC_ID_VORBIS:
1314#endif
1315 st->codec->sample_rate= 0; /* let decoder init parameters properly */
1316 break;
1317 }
1318
1319 /* Do not need those anymore. */
1320 av_freep(&sc->chunk_offsets);
1321 av_freep(&sc->sample_to_chunk);
1322 av_freep(&sc->sample_sizes);
1323 av_freep(&sc->keyframes);
1324 av_freep(&sc->stts_data);
1325
1326 return 0;
1327}
1328
1329static void mov_parse_udta_string(ByteIOContext *pb, char *str, int size)
1330{
1331 uint16_t str_size = get_be16(pb); /* string length */;
1332
1333 get_be16(pb); /* skip language */
1334 get_buffer(pb, str, FFMIN(size, str_size));
1335}
1336
1337static int mov_read_udta(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1338{
1339 uint64_t end = url_ftell(pb) + atom.size;
1340
1341 while (url_ftell(pb) + 8 < end) {
1342 uint32_t tag_size = get_be32(pb);
1343 uint32_t tag = get_le32(pb);
1344 uint64_t next = url_ftell(pb) + tag_size - 8;
1345
1346 if (next > end) // stop if tag_size is wrong
1347 break;
1348
1349 switch (tag) {
1350 case MKTAG(0xa9,'n','a','m'):
1351 mov_parse_udta_string(pb, c->fc->title, sizeof(c->fc->title));
1352 break;
1353 case MKTAG(0xa9,'w','r','t'):
1354 mov_parse_udta_string(pb, c->fc->author, sizeof(c->fc->author));
1355 break;
1356 case MKTAG(0xa9,'c','p','y'):
1357 mov_parse_udta_string(pb, c->fc->copyright, sizeof(c->fc->copyright));
1358 break;
1359 case MKTAG(0xa9,'i','n','f'):
1360 mov_parse_udta_string(pb, c->fc->comment, sizeof(c->fc->comment));
1361 break;
1362 default:
1363 break;
1364 }
1365
1366 url_fseek(pb, next, SEEK_SET);
1367 }
1368
1369 return 0;
1370}
1371
1372static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1373{
1374 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1375 int version = get_byte(pb);
1376
1377 get_be24(pb); /* flags */
1378 /*
1379 MOV_TRACK_ENABLED 0x0001
1380 MOV_TRACK_IN_MOVIE 0x0002
1381 MOV_TRACK_IN_PREVIEW 0x0004
1382 MOV_TRACK_IN_POSTER 0x0008
1383 */
1384
1385 if (version == 1) {
1386 get_be64(pb);
1387 get_be64(pb);
1388 } else {
1389 get_be32(pb); /* creation time */
1390 get_be32(pb); /* modification time */
1391 }
1392 st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1393 get_be32(pb); /* reserved */
1394 st->start_time = 0; /* check */
1395 /* highlevel (considering edits) duration in movie timebase */
1396 (version == 1) ? get_be64(pb) : get_be32(pb);
1397 get_be32(pb); /* reserved */
1398 get_be32(pb); /* reserved */
1399
1400 get_be16(pb); /* layer */
1401 get_be16(pb); /* alternate group */
1402 get_be16(pb); /* volume */
1403 get_be16(pb); /* reserved */
1404
1405 url_fskip(pb, 36); /* display matrix */
1406
1407 /* those are fixed-point */
1408 get_be32(pb); /* track width */
1409 get_be32(pb); /* track height */
1410
1411 return 0;
1412}
1413
1414static int mov_read_tfhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1415{
1416 MOVFragment *frag = &c->fragment;
1417 MOVTrackExt *trex = NULL;
1418 int flags, track_id, i;
1419
1420 get_byte(pb); /* version */
1421 flags = get_be24(pb);
1422
1423 track_id = get_be32(pb);
1424 if (!track_id || track_id > c->fc->nb_streams)
1425 return -1;
1426 frag->track_id = track_id;
1427 for (i = 0; i < c->trex_count; i++)
1428 if (c->trex_data[i].track_id == frag->track_id) {
1429 trex = &c->trex_data[i];
1430 break;
1431 }
1432 if (!trex) {
1433 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
1434 return -1;
1435 }
1436
1437 if (flags & 0x01) frag->base_data_offset = get_be64(pb);
1438 else frag->base_data_offset = frag->moof_offset;
1439 if (flags & 0x02) frag->stsd_id = get_be32(pb);
1440 else frag->stsd_id = trex->stsd_id;
1441
1442 frag->duration = flags & 0x08 ? get_be32(pb) : trex->duration;
1443 frag->size = flags & 0x10 ? get_be32(pb) : trex->size;
1444 frag->flags = flags & 0x20 ? get_be32(pb) : trex->flags;
1445 dprintf(c->fc, "frag flags 0x%x\n", frag->flags);
1446 return 0;
1447}
1448
1449static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1450{
1451 MOVTrackExt *trex;
1452
1453 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
1454 return -1;
1455 c->trex_data = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
1456 if (!c->trex_data)
1457 return AVERROR(ENOMEM);
1458 trex = &c->trex_data[c->trex_count++];
1459 get_byte(pb); /* version */
1460 get_be24(pb); /* flags */
1461 trex->track_id = get_be32(pb);
1462 trex->stsd_id = get_be32(pb);
1463 trex->duration = get_be32(pb);
1464 trex->size = get_be32(pb);
1465 trex->flags = get_be32(pb);
1466 return 0;
1467}
1468
1469static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1470{
1471 MOVFragment *frag = &c->fragment;
1472 AVStream *st;
1473 MOVStreamContext *sc;
1474 uint64_t offset;
1475 int64_t dts;
1476 int data_offset = 0;
1477 unsigned entries, first_sample_flags = frag->flags;
1478 int flags, distance, i;
1479
1480 if (!frag->track_id || frag->track_id > c->fc->nb_streams)
1481 return -1;
1482 st = c->fc->streams[frag->track_id-1];
1483 sc = st->priv_data;
1484 if (sc->pseudo_stream_id+1 != frag->stsd_id)
1485 return 0;
1486 get_byte(pb); /* version */
1487 flags = get_be24(pb);
1488 entries = get_be32(pb);
1489 dprintf(c->fc, "flags 0x%x entries %d\n", flags, entries);
1490 if (flags & 0x001) data_offset = get_be32(pb);
1491 if (flags & 0x004) first_sample_flags = get_be32(pb);
1492 if (flags & 0x800) {
1493 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
1494 return -1;
1495 sc->ctts_data = av_realloc(sc->ctts_data,
1496 (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
1497 if (!sc->ctts_data)
1498 return AVERROR(ENOMEM);
1499 }
1500 dts = st->duration;
1501 offset = frag->base_data_offset + data_offset;
1502 distance = 0;
1503 dprintf(c->fc, "first sample flags 0x%x\n", first_sample_flags);
1504 for (i = 0; i < entries; i++) {
1505 unsigned sample_size = frag->size;
1506 int sample_flags = i ? frag->flags : first_sample_flags;
1507 unsigned sample_duration = frag->duration;
1508 int keyframe;
1509
1510 if (flags & 0x100) sample_duration = get_be32(pb);
1511 if (flags & 0x200) sample_size = get_be32(pb);
1512 if (flags & 0x400) sample_flags = get_be32(pb);
1513 if (flags & 0x800) {
1514 sc->ctts_data[sc->ctts_count].count = 1;
1515 sc->ctts_data[sc->ctts_count].duration = get_be32(pb);
1516 sc->ctts_count++;
1517 }
1518 if ((keyframe = st->codec->codec_type == CODEC_TYPE_AUDIO ||
1519 (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
1520 distance = 0;
1521 av_add_index_entry(st, offset, dts, sample_size, distance,
1522 keyframe ? AVINDEX_KEYFRAME : 0);
1523 dprintf(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1524 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
1525 offset, dts, sample_size, distance, keyframe);
1526 distance++;
1527 assert(sample_duration % sc->time_rate == 0);
1528 dts += sample_duration / sc->time_rate;
1529 offset += sample_size;
1530 }
1531 frag->moof_offset = offset;
1532 sc->sample_count = st->nb_index_entries;
1533 st->duration = dts;
1534 return 0;
1535}
1536
1537/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
1538/* like the files created with Adobe Premiere 5.0, for samples see */
1539/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
1540static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1541{
1542 int err;
1543
1544 if (atom.size < 8)
1545 return 0; /* continue */
1546 if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
1547 url_fskip(pb, atom.size - 4);
1548 return 0;
1549 }
1550 atom.type = get_le32(pb);
1551 atom.offset += 8;
1552 atom.size -= 8;
1553 if (atom.type != MKTAG('m','d','a','t')) {
1554 url_fskip(pb, atom.size);
1555 return 0;
1556 }
1557 err = mov_read_mdat(c, pb, atom);
1558 return err;
1559}
1560
1561static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1562{
1563#ifdef CONFIG_ZLIB
1564 ByteIOContext ctx;
1565 uint8_t *cmov_data;
1566 uint8_t *moov_data; /* uncompressed data */
1567 long cmov_len, moov_len;
1568 int ret = -1;
1569
1570 get_be32(pb); /* dcom atom */
1571 if (get_le32(pb) != MKTAG('d','c','o','m'))
1572 return -1;
1573 if (get_le32(pb) != MKTAG('z','l','i','b')) {
1574 av_log(NULL, AV_LOG_ERROR, "unknown compression for cmov atom !");
1575 return -1;
1576 }
1577 get_be32(pb); /* cmvd atom */
1578 if (get_le32(pb) != MKTAG('c','m','v','d'))
1579 return -1;
1580 moov_len = get_be32(pb); /* uncompressed size */
1581 cmov_len = atom.size - 6 * 4;
1582
1583 cmov_data = av_malloc(cmov_len);
1584 if (!cmov_data)
1585 return -1;
1586 moov_data = av_malloc(moov_len);
1587 if (!moov_data) {
1588 av_free(cmov_data);
1589 return -1;
1590 }
1591 get_buffer(pb, cmov_data, cmov_len);
1592 if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
1593 goto free_and_return;
1594 if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
1595 goto free_and_return;
1596 atom.type = MKTAG('m','o','o','v');
1597 atom.offset = 0;
1598 atom.size = moov_len;
1599#ifdef DEBUG
1600// { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
1601#endif
1602 ret = mov_read_default(c, &ctx, atom);
1603free_and_return:
1604 av_free(moov_data);
1605 av_free(cmov_data);
1606 return ret;
1607#else
1608 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
1609 return -1;
1610#endif
1611}
1612
1613/* edit list atom */
1614static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1615{
1616 MOVStreamContext *sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
1617 int i, edit_count;
1618
1619 get_byte(pb); /* version */
1620 get_be24(pb); /* flags */
1621 edit_count= sc->edit_count = get_be32(pb); /* entries */
1622
1623 for(i=0; i<edit_count; i++){
1624 int time;
1625 get_be32(pb); /* Track duration */
1626 time = get_be32(pb); /* Media time */
1627 get_be32(pb); /* Media rate */
1628 if (time != 0)
1629 av_log(c->fc, AV_LOG_WARNING, "edit list not starting at 0, "
1630 "a/v desync might occur, patch welcome\n");
1631 }
1632 dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, sc->edit_count);
1633 return 0;
1634}
1635
1636static const MOVParseTableEntry mov_default_parse_table[] = {
1637{ MKTAG('a','v','s','s'), mov_read_extradata },
1638{ MKTAG('c','o','6','4'), mov_read_stco },
1639{ MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
1640{ MKTAG('d','i','n','f'), mov_read_default },
1641{ MKTAG('d','r','e','f'), mov_read_dref },
1642{ MKTAG('e','d','t','s'), mov_read_default },
1643{ MKTAG('e','l','s','t'), mov_read_elst },
1644{ MKTAG('e','n','d','a'), mov_read_enda },
1645{ MKTAG('f','i','e','l'), mov_read_extradata },
1646{ MKTAG('f','t','y','p'), mov_read_ftyp },
1647{ MKTAG('g','l','b','l'), mov_read_glbl },
1648{ MKTAG('h','d','l','r'), mov_read_hdlr },
1649{ MKTAG('j','p','2','h'), mov_read_extradata },
1650{ MKTAG('m','d','a','t'), mov_read_mdat },
1651{ MKTAG('m','d','h','d'), mov_read_mdhd },
1652{ MKTAG('m','d','i','a'), mov_read_default },
1653{ MKTAG('m','i','n','f'), mov_read_default },
1654{ MKTAG('m','o','o','f'), mov_read_moof },
1655{ MKTAG('m','o','o','v'), mov_read_moov },
1656{ MKTAG('m','v','e','x'), mov_read_default },
1657{ MKTAG('m','v','h','d'), mov_read_mvhd },
1658{ MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
1659{ MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
1660{ MKTAG('a','v','c','C'), mov_read_glbl },
1661{ MKTAG('s','t','b','l'), mov_read_default },
1662{ MKTAG('s','t','c','o'), mov_read_stco },
1663{ MKTAG('s','t','s','c'), mov_read_stsc },
1664{ MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
1665{ MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
1666{ MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
1667{ MKTAG('s','t','t','s'), mov_read_stts },
1668{ MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
1669{ MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
1670{ MKTAG('t','r','a','k'), mov_read_trak },
1671{ MKTAG('t','r','a','f'), mov_read_default },
1672{ MKTAG('t','r','e','x'), mov_read_trex },
1673{ MKTAG('t','r','u','n'), mov_read_trun },
1674{ MKTAG('u','d','t','a'), mov_read_udta },
1675{ MKTAG('w','a','v','e'), mov_read_wave },
1676{ MKTAG('e','s','d','s'), mov_read_esds },
1677{ MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
1678{ MKTAG('c','m','o','v'), mov_read_cmov },
1679{ 0, NULL }
1680};
1681
1682static int mov_probe(AVProbeData *p)
1683{
1684 unsigned int offset;
1685 uint32_t tag;
1686 int score = 0;
1687
1688 /* check file header */
1689 offset = 0;
1690 for(;;) {
1691 /* ignore invalid offset */
1692 if ((offset + 8) > (unsigned int)p->buf_size)
1693 return score;
1694 tag = AV_RL32(p->buf + offset + 4);
1695 switch(tag) {
1696 /* check for obvious tags */
1697 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
1698 case MKTAG('m','o','o','v'):
1699 case MKTAG('m','d','a','t'):
1700 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
1701 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
1702 case MKTAG('f','t','y','p'):
1703 return AVPROBE_SCORE_MAX;
1704 /* those are more common words, so rate then a bit less */
1705 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
1706 case MKTAG('w','i','d','e'):
1707 case MKTAG('f','r','e','e'):
1708 case MKTAG('j','u','n','k'):
1709 case MKTAG('p','i','c','t'):
1710 return AVPROBE_SCORE_MAX - 5;
1711 case MKTAG(0x82,0x82,0x7f,0x7d):
1712 case MKTAG('s','k','i','p'):
1713 case MKTAG('u','u','i','d'):
1714 case MKTAG('p','r','f','l'):
1715 offset = AV_RB32(p->buf+offset) + offset;
1716 /* if we only find those cause probedata is too small at least rate them */
1717 score = AVPROBE_SCORE_MAX - 50;
1718 break;
1719 default:
1720 /* unrecognized tag */
1721 return score;
1722 }
1723 }
1724 return score;
1725}
1726
1727static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
1728{
1729 MOVContext *mov = s->priv_data;
1730 ByteIOContext *pb = s->pb;
1731 int err;
1732 MOV_atom_t atom = { 0, 0, 0 };
1733
1734 mov->fc = s;
1735 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
1736 if(!url_is_streamed(pb))
1737 atom.size = url_fsize(pb);
1738 else
1739 atom.size = INT64_MAX;
1740
1741 /* check MOV header */
1742 if ((err = mov_read_default(mov, pb, atom)) < 0) {
1743 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
1744 return err;
1745 }
1746 if (!mov->found_moov) {
1747 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
1748 return -1;
1749 }
1750 dprintf(mov->fc, "on_parse_exit_offset=%lld\n", url_ftell(pb));
1751
1752 return 0;
1753}
1754
1755static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
1756{
1757 MOVContext *mov = s->priv_data;
1758 MOVStreamContext *sc = 0;
1759 AVIndexEntry *sample = 0;
1760 int64_t best_dts = INT64_MAX;
1761 int i;
1762 retry:
1763 for (i = 0; i < s->nb_streams; i++) {
1764 AVStream *st = s->streams[i];
1765 MOVStreamContext *msc = st->priv_data;
1766 if (st->discard != AVDISCARD_ALL && msc->pb && msc->current_sample < msc->sample_count) {
1767 AVIndexEntry *current_sample = &st->index_entries[msc->current_sample];
1768 int64_t dts = av_rescale(current_sample->timestamp * (int64_t)msc->time_rate,
1769 AV_TIME_BASE, msc->time_scale);
1770 dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
1771 if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
1772 (!url_is_streamed(s->pb) &&
1773 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
1774 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
1775 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
1776 sample = current_sample;
1777 best_dts = dts;
1778 sc = msc;
1779 }
1780 }
1781 }
1782 if (!sample) {
1783 mov->found_mdat = 0;
1784 if (!url_is_streamed(s->pb) ||
1785 mov_read_default(mov, s->pb, (MOV_atom_t){ 0, 0, INT64_MAX }) < 0 ||
1786 url_feof(s->pb))
1787 return -1;
1788 dprintf(s, "read fragments, offset 0x%llx\n", url_ftell(s->pb));
1789 goto retry;
1790 }
1791 /* must be done just before reading, to avoid infinite loop on sample */
1792 sc->current_sample++;
1793 if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
1794 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
1795 sc->ffindex, sample->pos);
1796 return -1;
1797 }
1798 av_get_packet(sc->pb, pkt, sample->size);
1799#ifdef CONFIG_DV_DEMUXER
1800 if (mov->dv_demux && sc->dv_audio_container) {
1801 dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
1802 av_free(pkt->data);
1803 pkt->size = 0;
1804 if (dv_get_packet(mov->dv_demux, pkt) < 0)
1805 return -1;
1806 }
1807#endif
1808 pkt->stream_index = sc->ffindex;
1809 pkt->dts = sample->timestamp;
1810 if (sc->ctts_data) {
1811 assert(sc->ctts_data[sc->sample_to_ctime_index].duration % sc->time_rate == 0);
1812 pkt->pts = pkt->dts + sc->ctts_data[sc->sample_to_ctime_index].duration / sc->time_rate;
1813 /* update ctts context */
1814 sc->sample_to_ctime_sample++;
1815 if (sc->sample_to_ctime_index < sc->ctts_count &&
1816 sc->ctts_data[sc->sample_to_ctime_index].count == sc->sample_to_ctime_sample) {
1817 sc->sample_to_ctime_index++;
1818 sc->sample_to_ctime_sample = 0;
1819 }
1820 } else {
1821 AVStream *st = s->streams[sc->ffindex];
1822 int64_t next_dts = (sc->current_sample < sc->sample_count) ?
1823 st->index_entries[sc->current_sample].timestamp : st->duration;
1824 pkt->duration = next_dts - pkt->dts;
1825 pkt->pts = pkt->dts;
1826 }
1827 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? PKT_FLAG_KEY : 0;
1828 pkt->pos = sample->pos;
1829 dprintf(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
1830 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
1831 return 0;
1832}
1833
1834static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
1835{
1836 MOVStreamContext *sc = st->priv_data;
1837 int sample, time_sample;
1838 int i;
1839
1840 sample = av_index_search_timestamp(st, timestamp, flags);
1841 dprintf(st->codec, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
1842 if (sample < 0) /* not sure what to do */
1843 return -1;
1844 sc->current_sample = sample;
1845 dprintf(st->codec, "stream %d, found sample %d\n", st->index, sc->current_sample);
1846 /* adjust ctts index */
1847 if (sc->ctts_data) {
1848 time_sample = 0;
1849 for (i = 0; i < sc->ctts_count; i++) {
1850 int next = time_sample + sc->ctts_data[i].count;
1851 if (next > sc->current_sample) {
1852 sc->sample_to_ctime_index = i;
1853 sc->sample_to_ctime_sample = sc->current_sample - time_sample;
1854 break;
1855 }
1856 time_sample = next;
1857 }
1858 }
1859 return sample;
1860}
1861
1862static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
1863{
1864 AVStream *st;
1865 int64_t seek_timestamp, timestamp;
1866 int sample;
1867 int i;
1868
1869 if (stream_index >= s->nb_streams)
1870 return -1;
1871
1872 st = s->streams[stream_index];
1873 sample = mov_seek_stream(st, sample_time, flags);
1874 if (sample < 0)
1875 return -1;
1876
1877 /* adjust seek timestamp to found sample timestamp */
1878 seek_timestamp = st->index_entries[sample].timestamp;
1879
1880 for (i = 0; i < s->nb_streams; i++) {
1881 st = s->streams[i];
1882 if (stream_index == i || st->discard == AVDISCARD_ALL)
1883 continue;
1884
1885 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
1886 mov_seek_stream(st, timestamp, flags);
1887 }
1888 return 0;
1889}
1890
1891static int mov_read_close(AVFormatContext *s)
1892{
1893 int i, j;
1894 MOVContext *mov = s->priv_data;
1895 for(i=0; i<s->nb_streams; i++) {
1896 MOVStreamContext *sc = s->streams[i]->priv_data;
1897 av_freep(&sc->ctts_data);
1898 for (j=0; j<sc->drefs_count; j++)
1899 av_freep(&sc->drefs[j].path);
1900 av_freep(&sc->drefs);
1901 if (sc->pb && sc->pb != s->pb)
1902 url_fclose(sc->pb);
1903 }
1904 if(mov->dv_demux){
1905 for(i=0; i<mov->dv_fctx->nb_streams; i++){
1906 av_freep(&mov->dv_fctx->streams[i]->codec);
1907 av_freep(&mov->dv_fctx->streams[i]);
1908 }
1909 av_freep(&mov->dv_fctx);
1910 av_freep(&mov->dv_demux);
1911 }
1912 av_freep(&mov->trex_data);
1913 return 0;
1914}
1915
1916AVInputFormat mov_demuxer = {
1917 "mov,mp4,m4a,3gp,3g2,mj2",
1918 NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
1919 sizeof(MOVContext),
1920 mov_probe,
1921 mov_read_header,
1922 mov_read_packet,
1923 mov_read_close,
1924 mov_read_seek,
1925};
diff --git a/src/plugins/ffmpeg/libavformat/movenc.c b/src/plugins/ffmpeg/libavformat/movenc.c
deleted file mode 100644
index b7601a1..0000000
--- a/src/plugins/ffmpeg/libavformat/movenc.c
+++ /dev/null
@@ -1,1788 +0,0 @@
1/*
2 * MOV, 3GP, MP4 muxer
3 * Copyright (c) 2003 Thomas Raivio.
4 * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>.
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22#include "avformat.h"
23#include "riff.h"
24#include "avio.h"
25#include "isom.h"
26#include "avc.h"
27
28#undef NDEBUG
29#include <assert.h>
30
31#define MOV_INDEX_CLUSTER_SIZE 16384
32#define globalTimescale 1000
33
34#define MODE_MP4 0x01
35#define MODE_MOV 0x02
36#define MODE_3GP 0x04
37#define MODE_PSP 0x08 // example working PSP command line:
38// ffmpeg -i testinput.avi -f psp -r 14.985 -s 320x240 -b 768 -ar 24000 -ab 32 M4V00001.MP4
39#define MODE_3G2 0x10
40#define MODE_IPOD 0x20
41
42typedef struct MOVIentry {
43 unsigned int flags, size;
44 uint64_t pos;
45 unsigned int samplesInChunk;
46 char key_frame;
47 unsigned int entries;
48 int64_t cts;
49 int64_t dts;
50} MOVIentry;
51
52typedef struct MOVIndex {
53 int mode;
54 int entry;
55 long timescale;
56 long time;
57 int64_t trackDuration;
58 long sampleCount;
59 long sampleSize;
60 int hasKeyframes;
61 int hasBframes;
62 int language;
63 int trackID;
64 int tag; ///< stsd fourcc
65 AVCodecContext *enc;
66
67 int vosLen;
68 uint8_t *vosData;
69 MOVIentry *cluster;
70 int audio_vbr;
71} MOVTrack;
72
73typedef struct MOVContext {
74 int mode;
75 int64_t time;
76 int nb_streams;
77 offset_t mdat_pos;
78 uint64_t mdat_size;
79 long timescale;
80 MOVTrack tracks[MAX_STREAMS];
81} MOVContext;
82
83//FIXME support 64 bit variant with wide placeholders
84static offset_t updateSize(ByteIOContext *pb, offset_t pos)
85{
86 offset_t curpos = url_ftell(pb);
87 url_fseek(pb, pos, SEEK_SET);
88 put_be32(pb, curpos - pos); /* rewrite size */
89 url_fseek(pb, curpos, SEEK_SET);
90
91 return curpos - pos;
92}
93
94/* Chunk offset atom */
95static int mov_write_stco_tag(ByteIOContext *pb, MOVTrack *track)
96{
97 int i;
98 int mode64 = 0; // use 32 bit size variant if possible
99 offset_t pos = url_ftell(pb);
100 put_be32(pb, 0); /* size */
101 if (pos > UINT32_MAX) {
102 mode64 = 1;
103 put_tag(pb, "co64");
104 } else
105 put_tag(pb, "stco");
106 put_be32(pb, 0); /* version & flags */
107 put_be32(pb, track->entry); /* entry count */
108 for (i=0; i<track->entry; i++) {
109 if(mode64 == 1)
110 put_be64(pb, track->cluster[i].pos);
111 else
112 put_be32(pb, track->cluster[i].pos);
113 }
114 return updateSize(pb, pos);
115}
116
117/* Sample size atom */
118static int mov_write_stsz_tag(ByteIOContext *pb, MOVTrack *track)
119{
120 int equalChunks = 1;
121 int i, j, entries = 0, tst = -1, oldtst = -1;
122
123 offset_t pos = url_ftell(pb);
124 put_be32(pb, 0); /* size */
125 put_tag(pb, "stsz");
126 put_be32(pb, 0); /* version & flags */
127
128 for (i=0; i<track->entry; i++) {
129 tst = track->cluster[i].size/track->cluster[i].entries;
130 if(oldtst != -1 && tst != oldtst) {
131 equalChunks = 0;
132 }
133 oldtst = tst;
134 entries += track->cluster[i].entries;
135 }
136 if (equalChunks) {
137 int sSize = track->cluster[0].size/track->cluster[0].entries;
138 put_be32(pb, sSize); // sample size
139 put_be32(pb, entries); // sample count
140 }
141 else {
142 put_be32(pb, 0); // sample size
143 put_be32(pb, entries); // sample count
144 for (i=0; i<track->entry; i++) {
145 for (j=0; j<track->cluster[i].entries; j++) {
146 put_be32(pb, track->cluster[i].size /
147 track->cluster[i].entries);
148 }
149 }
150 }
151 return updateSize(pb, pos);
152}
153
154/* Sample to chunk atom */
155static int mov_write_stsc_tag(ByteIOContext *pb, MOVTrack *track)
156{
157 int index = 0, oldval = -1, i;
158 offset_t entryPos, curpos;
159
160 offset_t pos = url_ftell(pb);
161 put_be32(pb, 0); /* size */
162 put_tag(pb, "stsc");
163 put_be32(pb, 0); // version & flags
164 entryPos = url_ftell(pb);
165 put_be32(pb, track->entry); // entry count
166 for (i=0; i<track->entry; i++) {
167 if(oldval != track->cluster[i].samplesInChunk)
168 {
169 put_be32(pb, i+1); // first chunk
170 put_be32(pb, track->cluster[i].samplesInChunk); // samples per chunk
171 put_be32(pb, 0x1); // sample description index
172 oldval = track->cluster[i].samplesInChunk;
173 index++;
174 }
175 }
176 curpos = url_ftell(pb);
177 url_fseek(pb, entryPos, SEEK_SET);
178 put_be32(pb, index); // rewrite size
179 url_fseek(pb, curpos, SEEK_SET);
180
181 return updateSize(pb, pos);
182}
183
184/* Sync sample atom */
185static int mov_write_stss_tag(ByteIOContext *pb, MOVTrack *track)
186{
187 offset_t curpos, entryPos;
188 int i, index = 0;
189 offset_t pos = url_ftell(pb);
190 put_be32(pb, 0); // size
191 put_tag(pb, "stss");
192 put_be32(pb, 0); // version & flags
193 entryPos = url_ftell(pb);
194 put_be32(pb, track->entry); // entry count
195 for (i=0; i<track->entry; i++) {
196 if(track->cluster[i].key_frame == 1) {
197 put_be32(pb, i+1);
198 index++;
199 }
200 }
201 curpos = url_ftell(pb);
202 url_fseek(pb, entryPos, SEEK_SET);
203 put_be32(pb, index); // rewrite size
204 url_fseek(pb, curpos, SEEK_SET);
205 return updateSize(pb, pos);
206}
207
208static int mov_write_amr_tag(ByteIOContext *pb, MOVTrack *track)
209{
210 put_be32(pb, 0x11); /* size */
211 if (track->mode == MODE_MOV) put_tag(pb, "samr");
212 else put_tag(pb, "damr");
213 put_tag(pb, "FFMP");
214 put_byte(pb, 0); /* decoder version */
215
216 put_be16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
217 put_byte(pb, 0x00); /* Mode change period (no restriction) */
218 put_byte(pb, 0x01); /* Frames per sample */
219 return 0x11;
220}
221
222/**
223 * This function writes extradata "as is".
224 * Extradata must be formated like a valid atom (with size and tag)
225 */
226static int mov_write_extradata_tag(ByteIOContext *pb, MOVTrack *track)
227{
228 put_buffer(pb, track->enc->extradata, track->enc->extradata_size);
229 return track->enc->extradata_size;
230}
231
232static int mov_write_enda_tag(ByteIOContext *pb)
233{
234 put_be32(pb, 10);
235 put_tag(pb, "enda");
236 put_be16(pb, 1); /* little endian */
237 return 10;
238}
239
240static unsigned int descrLength(unsigned int len)
241{
242 int i;
243 for(i=1; len>>(7*i); i++);
244 return len + 1 + i;
245}
246
247static void putDescr(ByteIOContext *pb, int tag, unsigned int size)
248{
249 int i= descrLength(size) - size - 2;
250 put_byte(pb, tag);
251 for(; i>0; i--)
252 put_byte(pb, (size>>(7*i)) | 0x80);
253 put_byte(pb, size & 0x7F);
254}
255
256static int mov_write_esds_tag(ByteIOContext *pb, MOVTrack *track) // Basic
257{
258 offset_t pos = url_ftell(pb);
259 int decoderSpecificInfoLen = track->vosLen ? descrLength(track->vosLen):0;
260
261 put_be32(pb, 0); // size
262 put_tag(pb, "esds");
263 put_be32(pb, 0); // Version
264
265 // ES descriptor
266 putDescr(pb, 0x03, 3 + descrLength(13 + decoderSpecificInfoLen) +
267 descrLength(1));
268 put_be16(pb, track->trackID);
269 put_byte(pb, 0x00); // flags (= no flags)
270
271 // DecoderConfig descriptor
272 putDescr(pb, 0x04, 13 + decoderSpecificInfoLen);
273
274 // Object type indication
275 put_byte(pb, codec_get_tag(ff_mp4_obj_type, track->enc->codec_id));
276
277 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
278 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
279 if(track->enc->codec_type == CODEC_TYPE_AUDIO)
280 put_byte(pb, 0x15); // flags (= Audiostream)
281 else
282 put_byte(pb, 0x11); // flags (= Visualstream)
283
284 put_byte(pb, track->enc->rc_buffer_size>>(3+16)); // Buffersize DB (24 bits)
285 put_be16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF); // Buffersize DB
286
287 put_be32(pb, FFMAX(track->enc->bit_rate, track->enc->rc_max_rate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
288 if(track->enc->rc_max_rate != track->enc->rc_min_rate || track->enc->rc_min_rate==0)
289 put_be32(pb, 0); // vbr
290 else
291 put_be32(pb, track->enc->rc_max_rate); // avg bitrate
292
293 if (track->vosLen) {
294 // DecoderSpecific info descriptor
295 putDescr(pb, 0x05, track->vosLen);
296 put_buffer(pb, track->vosData, track->vosLen);
297 }
298
299 // SL descriptor
300 putDescr(pb, 0x06, 1);
301 put_byte(pb, 0x02);
302 return updateSize(pb, pos);
303}
304
305static int mov_write_wave_tag(ByteIOContext *pb, MOVTrack *track)
306{
307 offset_t pos = url_ftell(pb);
308
309 put_be32(pb, 0); /* size */
310 put_tag(pb, "wave");
311
312 put_be32(pb, 12); /* size */
313 put_tag(pb, "frma");
314 put_le32(pb, track->tag);
315
316 if (track->enc->codec_id == CODEC_ID_AAC) {
317 /* useless atom needed by mplayer, ipod, not needed by quicktime */
318 put_be32(pb, 12); /* size */
319 put_tag(pb, "mp4a");
320 put_be32(pb, 0);
321 mov_write_esds_tag(pb, track);
322 } else if (track->enc->codec_id == CODEC_ID_PCM_S24LE ||
323 track->enc->codec_id == CODEC_ID_PCM_S32LE) {
324 mov_write_enda_tag(pb);
325 } else if (track->enc->codec_id == CODEC_ID_AMR_NB) {
326 mov_write_amr_tag(pb, track);
327 } else if (track->enc->codec_id == CODEC_ID_ALAC) {
328 mov_write_extradata_tag(pb, track);
329 }
330
331 put_be32(pb, 8); /* size */
332 put_be32(pb, 0); /* null tag */
333
334 return updateSize(pb, pos);
335}
336
337static int mov_write_glbl_tag(ByteIOContext *pb, MOVTrack *track)
338{
339 put_be32(pb, track->vosLen+8);
340 put_tag(pb, "glbl");
341 put_buffer(pb, track->vosData, track->vosLen);
342 return 8+track->vosLen;
343}
344
345static int mov_write_audio_tag(ByteIOContext *pb, MOVTrack *track)
346{
347 offset_t pos = url_ftell(pb);
348 int version = track->mode == MODE_MOV &&
349 (track->audio_vbr ||
350 track->enc->codec_id == CODEC_ID_PCM_S32LE ||
351 track->enc->codec_id == CODEC_ID_PCM_S24LE);
352
353 put_be32(pb, 0); /* size */
354 put_le32(pb, track->tag); // store it byteswapped
355 put_be32(pb, 0); /* Reserved */
356 put_be16(pb, 0); /* Reserved */
357 put_be16(pb, 1); /* Data-reference index, XXX == 1 */
358
359 /* SoundDescription */
360 put_be16(pb, version); /* Version */
361 put_be16(pb, 0); /* Revision level */
362 put_be32(pb, 0); /* Reserved */
363
364 if (track->mode == MODE_MOV) {
365 put_be16(pb, track->enc->channels);
366 if (track->enc->codec_id == CODEC_ID_PCM_U8 ||
367 track->enc->codec_id == CODEC_ID_PCM_S8)
368 put_be16(pb, 8); /* bits per sample */
369 else
370 put_be16(pb, 16);
371 put_be16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
372 } else { /* reserved for mp4/3gp */
373 put_be16(pb, 2);
374 put_be16(pb, 16);
375 put_be16(pb, 0);
376 }
377
378 put_be16(pb, 0); /* packet size (= 0) */
379 put_be16(pb, track->timescale); /* Time scale */
380 put_be16(pb, 0); /* Reserved */
381
382 if(version == 1) { /* SoundDescription V1 extended info */
383 put_be32(pb, track->enc->frame_size); /* Samples per packet */
384 put_be32(pb, track->sampleSize / track->enc->channels); /* Bytes per packet */
385 put_be32(pb, track->sampleSize); /* Bytes per frame */
386 put_be32(pb, 2); /* Bytes per sample */
387 }
388
389 if(track->mode == MODE_MOV &&
390 (track->enc->codec_id == CODEC_ID_AAC ||
391 track->enc->codec_id == CODEC_ID_AMR_NB ||
392 track->enc->codec_id == CODEC_ID_PCM_S24LE ||
393 track->enc->codec_id == CODEC_ID_PCM_S32LE ||
394 track->enc->codec_id == CODEC_ID_ALAC))
395 mov_write_wave_tag(pb, track);
396 else if(track->tag == MKTAG('m','p','4','a'))
397 mov_write_esds_tag(pb, track);
398 else if(track->enc->codec_id == CODEC_ID_AMR_NB)
399 mov_write_amr_tag(pb, track);
400 else if (track->enc->codec_id == CODEC_ID_ALAC)
401 mov_write_extradata_tag(pb, track);
402 else if(track->vosLen > 0)
403 mov_write_glbl_tag(pb, track);
404
405 return updateSize(pb, pos);
406}
407
408static int mov_write_d263_tag(ByteIOContext *pb)
409{
410 put_be32(pb, 0xf); /* size */
411 put_tag(pb, "d263");
412 put_tag(pb, "FFMP");
413 put_byte(pb, 0); /* decoder version */
414 /* FIXME use AVCodecContext level/profile, when encoder will set values */
415 put_byte(pb, 0xa); /* level */
416 put_byte(pb, 0); /* profile */
417 return 0xf;
418}
419
420/* TODO: No idea about these values */
421static int mov_write_svq3_tag(ByteIOContext *pb)
422{
423 put_be32(pb, 0x15);
424 put_tag(pb, "SMI ");
425 put_tag(pb, "SEQH");
426 put_be32(pb, 0x5);
427 put_be32(pb, 0xe2c0211d);
428 put_be32(pb, 0xc0000000);
429 put_byte(pb, 0);
430 return 0x15;
431}
432
433static int mov_write_avcc_tag(ByteIOContext *pb, MOVTrack *track)
434{
435 offset_t pos = url_ftell(pb);
436
437 put_be32(pb, 0);
438 put_tag(pb, "avcC");
439 ff_isom_write_avcc(pb, track->vosData, track->vosLen);
440 return updateSize(pb, pos);
441}
442
443/* also used by all avid codecs (dv, imx, meridien) and their variants */
444static int mov_write_avid_tag(ByteIOContext *pb, MOVTrack *track)
445{
446 int i;
447 put_be32(pb, 24); /* size */
448 put_tag(pb, "ACLR");
449 put_tag(pb, "ACLR");
450 put_tag(pb, "0001");
451 put_be32(pb, 1); /* yuv 1 / rgb 2 ? */
452 put_be32(pb, 0); /* unknown */
453
454 put_be32(pb, 24); /* size */
455 put_tag(pb, "APRG");
456 put_tag(pb, "APRG");
457 put_tag(pb, "0001");
458 put_be32(pb, 1); /* unknown */
459 put_be32(pb, 0); /* unknown */
460
461 put_be32(pb, 120); /* size */
462 put_tag(pb, "ARES");
463 put_tag(pb, "ARES");
464 put_tag(pb, "0001");
465 put_be32(pb, AV_RB32(track->vosData + 0x28)); /* dnxhd cid, some id ? */
466 put_be32(pb, track->enc->width);
467 /* values below are based on samples created with quicktime and avid codecs */
468 if (track->vosData[5] & 2) { // interlaced
469 put_be32(pb, track->enc->height/2);
470 put_be32(pb, 2); /* unknown */
471 put_be32(pb, 0); /* unknown */
472 put_be32(pb, 4); /* unknown */
473 } else {
474 put_be32(pb, track->enc->height);
475 put_be32(pb, 1); /* unknown */
476 put_be32(pb, 0); /* unknown */
477 if (track->enc->height == 1080)
478 put_be32(pb, 5); /* unknown */
479 else
480 put_be32(pb, 6); /* unknown */
481 }
482 /* padding */
483 for (i = 0; i < 10; i++)
484 put_be64(pb, 0);
485
486 /* extra padding for stsd needed */
487 put_be32(pb, 0);
488 return 0;
489}
490
491static const AVCodecTag codec_3gp_tags[] = {
492 { CODEC_ID_H263, MKTAG('s','2','6','3') },
493 { CODEC_ID_H264, MKTAG('a','v','c','1') },
494 { CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
495 { CODEC_ID_AAC, MKTAG('m','p','4','a') },
496 { CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
497 { CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
498};
499
500static const AVCodecTag mov_pix_fmt_tags[] = {
501 { PIX_FMT_YUYV422, MKTAG('y','u','v','s') },
502 { PIX_FMT_UYVY422, MKTAG('2','v','u','y') },
503 { PIX_FMT_BGR555, MKTAG('r','a','w',' ') },
504 { PIX_FMT_RGB24, MKTAG('r','a','w',' ') },
505 { PIX_FMT_BGR32_1, MKTAG('r','a','w',' ') },
506};
507
508static const AVCodecTag codec_ipod_tags[] = {
509 { CODEC_ID_H264, MKTAG('a','v','c','1') },
510 { CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
511 { CODEC_ID_AAC, MKTAG('m','p','4','a') },
512 { CODEC_ID_ALAC, MKTAG('a','l','a','c') },
513};
514
515static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
516{
517 int tag = track->enc->codec_tag;
518 if (track->mode == MODE_MP4 || track->mode == MODE_PSP) {
519 if (!codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
520 return 0;
521 if (track->enc->codec_id == CODEC_ID_H264) tag = MKTAG('a','v','c','1');
522 else if (track->enc->codec_type == CODEC_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
523 else if (track->enc->codec_type == CODEC_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
524 } else if (track->mode == MODE_IPOD) {
525 tag = codec_get_tag(codec_ipod_tags, track->enc->codec_id);
526 if (!match_ext(s->filename, "m4a") && !match_ext(s->filename, "m4v"))
527 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
528 "Quicktime/Ipod might not play the file\n");
529 } else if (track->mode & MODE_3GP) {
530 tag = codec_get_tag(codec_3gp_tags, track->enc->codec_id);
531 } else if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
532 (tag == MKTAG('d','v','c','p') ||
533 track->enc->codec_id == CODEC_ID_RAWVIDEO))) {
534 if (track->enc->codec_id == CODEC_ID_DVVIDEO) {
535 if (track->enc->height == 480) /* NTSC */
536 if (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
537 else tag = MKTAG('d','v','c',' ');
538 else if (track->enc->pix_fmt == PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
539 else if (track->enc->pix_fmt == PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
540 else tag = MKTAG('d','v','p','p');
541 } else if (track->enc->codec_id == CODEC_ID_RAWVIDEO) {
542 tag = codec_get_tag(mov_pix_fmt_tags, track->enc->pix_fmt);
543 if (!tag) // restore tag
544 tag = track->enc->codec_tag;
545 } else {
546 if (track->enc->codec_type == CODEC_TYPE_VIDEO) {
547 tag = codec_get_tag(codec_movvideo_tags, track->enc->codec_id);
548 if (!tag) { // if no mac fcc found, try with Microsoft tags
549 tag = codec_get_tag(codec_bmp_tags, track->enc->codec_id);
550 if (tag)
551 av_log(s, AV_LOG_INFO, "Warning, using MS style video codec tag, "
552 "the file may be unplayable!\n");
553 }
554 } else if (track->enc->codec_type == CODEC_TYPE_AUDIO) {
555 tag = codec_get_tag(codec_movaudio_tags, track->enc->codec_id);
556 if (!tag) { // if no mac fcc found, try with Microsoft tags
557 int ms_tag = codec_get_tag(codec_wav_tags, track->enc->codec_id);
558 if (ms_tag) {
559 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
560 av_log(s, AV_LOG_INFO, "Warning, using MS style audio codec tag, "
561 "the file may be unplayable!\n");
562 }
563 }
564 }
565 }
566 }
567 return tag;
568}
569
570/** Write uuid atom.
571 * Needed to make file play in iPods running newest firmware
572 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
573 */
574static int mov_write_uuid_tag_ipod(ByteIOContext *pb)
575{
576 put_be32(pb, 28);
577 put_tag(pb, "uuid");
578 put_be32(pb, 0x6b6840f2);
579 put_be32(pb, 0x5f244fc5);
580 put_be32(pb, 0xba39a51b);
581 put_be32(pb, 0xcf0323f3);
582 put_be32(pb, 0x0);
583 return 28;
584}
585
586static int mov_write_video_tag(ByteIOContext *pb, MOVTrack *track)
587{
588 offset_t pos = url_ftell(pb);
589 char compressor_name[32];
590
591 put_be32(pb, 0); /* size */
592 put_le32(pb, track->tag); // store it byteswapped
593 put_be32(pb, 0); /* Reserved */
594 put_be16(pb, 0); /* Reserved */
595 put_be16(pb, 1); /* Data-reference index */
596
597 put_be16(pb, 0); /* Codec stream version */
598 put_be16(pb, 0); /* Codec stream revision (=0) */
599 if (track->mode == MODE_MOV) {
600 put_tag(pb, "FFMP"); /* Vendor */
601 if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
602 put_be32(pb, 0); /* Temporal Quality */
603 put_be32(pb, 0x400); /* Spatial Quality = lossless*/
604 } else {
605 put_be32(pb, 0x200); /* Temporal Quality = normal */
606 put_be32(pb, 0x200); /* Spatial Quality = normal */
607 }
608 } else {
609 put_be32(pb, 0); /* Reserved */
610 put_be32(pb, 0); /* Reserved */
611 put_be32(pb, 0); /* Reserved */
612 }
613 put_be16(pb, track->enc->width); /* Video width */
614 put_be16(pb, track->enc->height); /* Video height */
615 put_be32(pb, 0x00480000); /* Horizontal resolution 72dpi */
616 put_be32(pb, 0x00480000); /* Vertical resolution 72dpi */
617 put_be32(pb, 0); /* Data size (= 0) */
618 put_be16(pb, 1); /* Frame count (= 1) */
619
620 memset(compressor_name,0,32);
621 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
622 if (track->mode == MODE_MOV && track->enc->codec && track->enc->codec->name)
623 strncpy(compressor_name,track->enc->codec->name,31);
624 put_byte(pb, strlen(compressor_name));
625 put_buffer(pb, compressor_name, 31);
626
627 if (track->mode == MODE_MOV && track->enc->bits_per_sample)
628 put_be16(pb, track->enc->bits_per_sample);
629 else
630 put_be16(pb, 0x18); /* Reserved */
631 put_be16(pb, 0xffff); /* Reserved */
632 if(track->tag == MKTAG('m','p','4','v'))
633 mov_write_esds_tag(pb, track);
634 else if(track->enc->codec_id == CODEC_ID_H263)
635 mov_write_d263_tag(pb);
636 else if(track->enc->codec_id == CODEC_ID_SVQ3)
637 mov_write_svq3_tag(pb);
638 else if(track->enc->codec_id == CODEC_ID_DNXHD)
639 mov_write_avid_tag(pb, track);
640 else if(track->enc->codec_id == CODEC_ID_H264) {
641 mov_write_avcc_tag(pb, track);
642 if(track->mode == MODE_IPOD)
643 mov_write_uuid_tag_ipod(pb);
644 } else if(track->vosLen > 0)
645 mov_write_glbl_tag(pb, track);
646
647 return updateSize(pb, pos);
648}
649
650static int mov_write_stsd_tag(ByteIOContext *pb, MOVTrack *track)
651{
652 offset_t pos = url_ftell(pb);
653 put_be32(pb, 0); /* size */
654 put_tag(pb, "stsd");
655 put_be32(pb, 0); /* version & flags */
656 put_be32(pb, 1); /* entry count */
657 if (track->enc->codec_type == CODEC_TYPE_VIDEO)
658 mov_write_video_tag(pb, track);
659 else if (track->enc->codec_type == CODEC_TYPE_AUDIO)
660 mov_write_audio_tag(pb, track);
661 return updateSize(pb, pos);
662}
663
664static int mov_write_ctts_tag(ByteIOContext *pb, MOVTrack *track)
665{
666 MOV_stts_t *ctts_entries;
667 uint32_t entries = 0;
668 uint32_t atom_size;
669 int i;
670
671 ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
672 ctts_entries[0].count = 1;
673 ctts_entries[0].duration = track->cluster[0].cts;
674 for (i=1; i<track->entry; i++) {
675 if (track->cluster[i].cts == ctts_entries[entries].duration) {
676 ctts_entries[entries].count++; /* compress */
677 } else {
678 entries++;
679 ctts_entries[entries].duration = track->cluster[i].cts;
680 ctts_entries[entries].count = 1;
681 }
682 }
683 entries++; /* last one */
684 atom_size = 16 + (entries * 8);
685 put_be32(pb, atom_size); /* size */
686 put_tag(pb, "ctts");
687 put_be32(pb, 0); /* version & flags */
688 put_be32(pb, entries); /* entry count */
689 for (i=0; i<entries; i++) {
690 put_be32(pb, ctts_entries[i].count);
691 put_be32(pb, ctts_entries[i].duration);
692 }
693 av_free(ctts_entries);
694 return atom_size;
695}
696
697/* Time to sample atom */
698static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack *track)
699{
700 MOV_stts_t *stts_entries;
701 uint32_t entries = -1;
702 uint32_t atom_size;
703 int i;
704
705 if (track->enc->codec_type == CODEC_TYPE_AUDIO && !track->audio_vbr) {
706 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
707 stts_entries[0].count = track->sampleCount;
708 stts_entries[0].duration = 1;
709 entries = 1;
710 } else {
711 stts_entries = av_malloc(track->entry * sizeof(*stts_entries)); /* worst case */
712 for (i=0; i<track->entry; i++) {
713 int64_t duration = i + 1 == track->entry ?
714 track->trackDuration - track->cluster[i].dts + track->cluster[0].dts : /* readjusting */
715 track->cluster[i+1].dts - track->cluster[i].dts;
716 if (i && duration == stts_entries[entries].duration) {
717 stts_entries[entries].count++; /* compress */
718 } else {
719 entries++;
720 stts_entries[entries].duration = duration;
721 stts_entries[entries].count = 1;
722 }
723 }
724 entries++; /* last one */
725 }
726 atom_size = 16 + (entries * 8);
727 put_be32(pb, atom_size); /* size */
728 put_tag(pb, "stts");
729 put_be32(pb, 0); /* version & flags */
730 put_be32(pb, entries); /* entry count */
731 for (i=0; i<entries; i++) {
732 put_be32(pb, stts_entries[i].count);
733 put_be32(pb, stts_entries[i].duration);
734 }
735 av_free(stts_entries);
736 return atom_size;
737}
738
739static int mov_write_dref_tag(ByteIOContext *pb)
740{
741 put_be32(pb, 28); /* size */
742 put_tag(pb, "dref");
743 put_be32(pb, 0); /* version & flags */
744 put_be32(pb, 1); /* entry count */
745
746 put_be32(pb, 0xc); /* size */
747 put_tag(pb, "url ");
748 put_be32(pb, 1); /* version & flags */
749
750 return 28;
751}
752
753static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack *track)
754{
755 offset_t pos = url_ftell(pb);
756 put_be32(pb, 0); /* size */
757 put_tag(pb, "stbl");
758 mov_write_stsd_tag(pb, track);
759 mov_write_stts_tag(pb, track);
760 if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
761 track->hasKeyframes && track->hasKeyframes < track->entry)
762 mov_write_stss_tag(pb, track);
763 if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
764 track->hasBframes)
765 mov_write_ctts_tag(pb, track);
766 mov_write_stsc_tag(pb, track);
767 mov_write_stsz_tag(pb, track);
768 mov_write_stco_tag(pb, track);
769 return updateSize(pb, pos);
770}
771
772static int mov_write_dinf_tag(ByteIOContext *pb)
773{
774 offset_t pos = url_ftell(pb);
775 put_be32(pb, 0); /* size */
776 put_tag(pb, "dinf");
777 mov_write_dref_tag(pb);
778 return updateSize(pb, pos);
779}
780
781static int mov_write_smhd_tag(ByteIOContext *pb)
782{
783 put_be32(pb, 16); /* size */
784 put_tag(pb, "smhd");
785 put_be32(pb, 0); /* version & flags */
786 put_be16(pb, 0); /* reserved (balance, normally = 0) */
787 put_be16(pb, 0); /* reserved */
788 return 16;
789}
790
791static int mov_write_vmhd_tag(ByteIOContext *pb)
792{
793 put_be32(pb, 0x14); /* size (always 0x14) */
794 put_tag(pb, "vmhd");
795 put_be32(pb, 0x01); /* version & flags */
796 put_be64(pb, 0); /* reserved (graphics mode = copy) */
797 return 0x14;
798}
799
800static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack *track)
801{
802 const char *descr, *hdlr, *hdlr_type;
803 offset_t pos = url_ftell(pb);
804
805 if (!track) { /* no media --> data handler */
806 hdlr = "dhlr";
807 hdlr_type = "url ";
808 descr = "DataHandler";
809 } else {
810 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
811 if (track->enc->codec_type == CODEC_TYPE_VIDEO) {
812 hdlr_type = "vide";
813 descr = "VideoHandler";
814 } else {
815 hdlr_type = "soun";
816 descr = "SoundHandler";
817 }
818 }
819
820 put_be32(pb, 0); /* size */
821 put_tag(pb, "hdlr");
822 put_be32(pb, 0); /* Version & flags */
823 put_buffer(pb, hdlr, 4); /* handler */
824 put_tag(pb, hdlr_type); /* handler type */
825 put_be32(pb ,0); /* reserved */
826 put_be32(pb ,0); /* reserved */
827 put_be32(pb ,0); /* reserved */
828 put_byte(pb, strlen(descr)); /* string counter */
829 put_buffer(pb, descr, strlen(descr)); /* handler description */
830 return updateSize(pb, pos);
831}
832
833static int mov_write_minf_tag(ByteIOContext *pb, MOVTrack *track)
834{
835 offset_t pos = url_ftell(pb);
836 put_be32(pb, 0); /* size */
837 put_tag(pb, "minf");
838 if(track->enc->codec_type == CODEC_TYPE_VIDEO)
839 mov_write_vmhd_tag(pb);
840 else
841 mov_write_smhd_tag(pb);
842 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
843 mov_write_hdlr_tag(pb, NULL);
844 mov_write_dinf_tag(pb);
845 mov_write_stbl_tag(pb, track);
846 return updateSize(pb, pos);
847}
848
849static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack *track)
850{
851 int version = track->trackDuration < INT32_MAX ? 0 : 1;
852
853 (version == 1) ? put_be32(pb, 44) : put_be32(pb, 32); /* size */
854 put_tag(pb, "mdhd");
855 put_byte(pb, version);
856 put_be24(pb, 0); /* flags */
857 if (version == 1) {
858 put_be64(pb, track->time);
859 put_be64(pb, track->time);
860 } else {
861 put_be32(pb, track->time); /* creation time */
862 put_be32(pb, track->time); /* modification time */
863 }
864 put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
865 (version == 1) ? put_be64(pb, track->trackDuration) : put_be32(pb, track->trackDuration); /* duration */
866 put_be16(pb, track->language); /* language */
867 put_be16(pb, 0); /* reserved (quality) */
868
869 if(version!=0 && track->mode == MODE_MOV){
870 av_log(NULL, AV_LOG_ERROR,
871 "FATAL error, file duration too long for timebase, this file will not be\n"
872 "playable with quicktime. Choose a different timebase or a different\n"
873 "container format\n");
874 }
875
876 return 32;
877}
878
879static int mov_write_mdia_tag(ByteIOContext *pb, MOVTrack *track)
880{
881 offset_t pos = url_ftell(pb);
882 put_be32(pb, 0); /* size */
883 put_tag(pb, "mdia");
884 mov_write_mdhd_tag(pb, track);
885 mov_write_hdlr_tag(pb, track);
886 mov_write_minf_tag(pb, track);
887 return updateSize(pb, pos);
888}
889
890static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack *track)
891{
892 int64_t duration = av_rescale_rnd(track->trackDuration, globalTimescale, track->timescale, AV_ROUND_UP);
893 int version = duration < INT32_MAX ? 0 : 1;
894
895 (version == 1) ? put_be32(pb, 104) : put_be32(pb, 92); /* size */
896 put_tag(pb, "tkhd");
897 put_byte(pb, version);
898 put_be24(pb, 0xf); /* flags (track enabled) */
899 if (version == 1) {
900 put_be64(pb, track->time);
901 put_be64(pb, track->time);
902 } else {
903 put_be32(pb, track->time); /* creation time */
904 put_be32(pb, track->time); /* modification time */
905 }
906 put_be32(pb, track->trackID); /* track-id */
907 put_be32(pb, 0); /* reserved */
908 (version == 1) ? put_be64(pb, duration) : put_be32(pb, duration);
909
910 put_be32(pb, 0); /* reserved */
911 put_be32(pb, 0); /* reserved */
912 put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
913 /* Volume, only for audio */
914 if(track->enc->codec_type == CODEC_TYPE_AUDIO)
915 put_be16(pb, 0x0100);
916 else
917 put_be16(pb, 0);
918 put_be16(pb, 0); /* reserved */
919
920 /* Matrix structure */
921 put_be32(pb, 0x00010000); /* reserved */
922 put_be32(pb, 0x0); /* reserved */
923 put_be32(pb, 0x0); /* reserved */
924 put_be32(pb, 0x0); /* reserved */
925 put_be32(pb, 0x00010000); /* reserved */
926 put_be32(pb, 0x0); /* reserved */
927 put_be32(pb, 0x0); /* reserved */
928 put_be32(pb, 0x0); /* reserved */
929 put_be32(pb, 0x40000000); /* reserved */
930
931 /* Track width and height, for visual only */
932 if(track->enc->codec_type == CODEC_TYPE_VIDEO) {
933 double sample_aspect_ratio = av_q2d(track->enc->sample_aspect_ratio);
934 if(!sample_aspect_ratio) sample_aspect_ratio = 1;
935 put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
936 put_be32(pb, track->enc->height*0x10000);
937 }
938 else {
939 put_be32(pb, 0);
940 put_be32(pb, 0);
941 }
942 return 0x5c;
943}
944
945// This box seems important for the psp playback ... without it the movie seems to hang
946static int mov_write_edts_tag(ByteIOContext *pb, MOVTrack *track)
947{
948 put_be32(pb, 0x24); /* size */
949 put_tag(pb, "edts");
950 put_be32(pb, 0x1c); /* size */
951 put_tag(pb, "elst");
952 put_be32(pb, 0x0);
953 put_be32(pb, 0x1);
954
955 put_be32(pb, av_rescale_rnd(track->trackDuration, globalTimescale, track->timescale, AV_ROUND_UP)); /* duration ... doesn't seem to effect psp */
956
957 put_be32(pb, track->cluster[0].cts); /* first pts is cts since dts is 0 */
958 put_be32(pb, 0x00010000);
959 return 0x24;
960}
961
962// goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
963static int mov_write_uuid_tag_psp(ByteIOContext *pb, MOVTrack *mov)
964{
965 put_be32(pb, 0x34); /* size ... reports as 28 in mp4box! */
966 put_tag(pb, "uuid");
967 put_tag(pb, "USMT");
968 put_be32(pb, 0x21d24fce);
969 put_be32(pb, 0xbb88695c);
970 put_be32(pb, 0xfac9c740);
971 put_be32(pb, 0x1c); // another size here!
972 put_tag(pb, "MTDT");
973 put_be32(pb, 0x00010012);
974 put_be32(pb, 0x0a);
975 put_be32(pb, 0x55c40000);
976 put_be32(pb, 0x1);
977 put_be32(pb, 0x0);
978 return 0x34;
979}
980
981static int mov_write_trak_tag(ByteIOContext *pb, MOVTrack *track)
982{
983 offset_t pos = url_ftell(pb);
984 put_be32(pb, 0); /* size */
985 put_tag(pb, "trak");
986 mov_write_tkhd_tag(pb, track);
987 if (track->mode == MODE_PSP || track->hasBframes)
988 mov_write_edts_tag(pb, track); // PSP Movies require edts box
989 mov_write_mdia_tag(pb, track);
990 if (track->mode == MODE_PSP)
991 mov_write_uuid_tag_psp(pb,track); // PSP Movies require this uuid box
992 return updateSize(pb, pos);
993}
994
995#if 0
996/* TODO: Not sorted out, but not necessary either */
997static int mov_write_iods_tag(ByteIOContext *pb, MOVContext *mov)
998{
999 put_be32(pb, 0x15); /* size */
1000 put_tag(pb, "iods");
1001 put_be32(pb, 0); /* version & flags */
1002 put_be16(pb, 0x1007);
1003 put_byte(pb, 0);
1004 put_be16(pb, 0x4fff);
1005 put_be16(pb, 0xfffe);
1006 put_be16(pb, 0x01ff);
1007 return 0x15;
1008}
1009#endif
1010
1011static int mov_write_mvhd_tag(ByteIOContext *pb, MOVContext *mov)
1012{
1013 int maxTrackID = 1, i;
1014 int64_t maxTrackLenTemp, maxTrackLen = 0;
1015 int version;
1016
1017 for (i=0; i<mov->nb_streams; i++) {
1018 if(mov->tracks[i].entry > 0) {
1019 maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration, globalTimescale, mov->tracks[i].timescale, AV_ROUND_UP);
1020 if(maxTrackLen < maxTrackLenTemp)
1021 maxTrackLen = maxTrackLenTemp;
1022 if(maxTrackID < mov->tracks[i].trackID)
1023 maxTrackID = mov->tracks[i].trackID;
1024 }
1025 }
1026
1027 version = maxTrackLen < UINT32_MAX ? 0 : 1;
1028 (version == 1) ? put_be32(pb, 120) : put_be32(pb, 108); /* size */
1029 put_tag(pb, "mvhd");
1030 put_byte(pb, version);
1031 put_be24(pb, 0); /* flags */
1032 if (version == 1) {
1033 put_be64(pb, mov->time);
1034 put_be64(pb, mov->time);
1035 } else {
1036 put_be32(pb, mov->time); /* creation time */
1037 put_be32(pb, mov->time); /* modification time */
1038 }
1039 put_be32(pb, mov->timescale); /* timescale */
1040 (version == 1) ? put_be64(pb, maxTrackLen) : put_be32(pb, maxTrackLen); /* duration of longest track */
1041
1042 put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1043 put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1044 put_be16(pb, 0); /* reserved */
1045 put_be32(pb, 0); /* reserved */
1046 put_be32(pb, 0); /* reserved */
1047
1048 /* Matrix structure */
1049 put_be32(pb, 0x00010000); /* reserved */
1050 put_be32(pb, 0x0); /* reserved */
1051 put_be32(pb, 0x0); /* reserved */
1052 put_be32(pb, 0x0); /* reserved */
1053 put_be32(pb, 0x00010000); /* reserved */
1054 put_be32(pb, 0x0); /* reserved */
1055 put_be32(pb, 0x0); /* reserved */
1056 put_be32(pb, 0x0); /* reserved */
1057 put_be32(pb, 0x40000000); /* reserved */
1058
1059 put_be32(pb, 0); /* reserved (preview time) */
1060 put_be32(pb, 0); /* reserved (preview duration) */
1061 put_be32(pb, 0); /* reserved (poster time) */
1062 put_be32(pb, 0); /* reserved (selection time) */
1063 put_be32(pb, 0); /* reserved (selection duration) */
1064 put_be32(pb, 0); /* reserved (current time) */
1065 put_be32(pb, maxTrackID+1); /* Next track id */
1066 return 0x6c;
1067}
1068
1069static int mov_write_itunes_hdlr_tag(ByteIOContext *pb, MOVContext *mov,
1070 AVFormatContext *s)
1071{
1072 offset_t pos = url_ftell(pb);
1073 put_be32(pb, 0); /* size */
1074 put_tag(pb, "hdlr");
1075 put_be32(pb, 0);
1076 put_be32(pb, 0);
1077 put_tag(pb, "mdir");
1078 put_tag(pb, "appl");
1079 put_be32(pb, 0);
1080 put_be32(pb, 0);
1081 put_be16(pb, 0);
1082 return updateSize(pb, pos);
1083}
1084
1085/* helper function to write a data tag with the specified string as data */
1086static int mov_write_string_data_tag(ByteIOContext *pb, const char *data, int long_style)
1087{
1088 if(long_style){
1089 offset_t pos = url_ftell(pb);
1090 put_be32(pb, 0); /* size */
1091 put_tag(pb, "data");
1092 put_be32(pb, 1);
1093 put_be32(pb, 0);
1094 put_buffer(pb, data, strlen(data));
1095 return updateSize(pb, pos);
1096 }else{
1097 put_be16(pb, strlen(data)); /* string length */
1098 put_be16(pb, 0);
1099 put_buffer(pb, data, strlen(data));
1100 return strlen(data) + 4;
1101 }
1102}
1103
1104static int mov_write_string_tag(ByteIOContext *pb, const char *name, const char *value, int long_style){
1105 int size = 0;
1106 if (value && value[0]) {
1107 offset_t pos = url_ftell(pb);
1108 put_be32(pb, 0); /* size */
1109 put_tag(pb, name);
1110 mov_write_string_data_tag(pb, value, long_style);
1111 size= updateSize(pb, pos);
1112 }
1113 return size;
1114}
1115
1116/* iTunes year */
1117static int mov_write_day_tag(ByteIOContext *pb, int year, int long_style)
1118{
1119 if(year){
1120 char year_str[5];
1121 snprintf(year_str, sizeof(year_str), "%04d", year);
1122 return mov_write_string_tag(pb, "\251day", year_str, long_style);
1123 }else
1124 return 0;
1125}
1126
1127/* iTunes track number */
1128static int mov_write_trkn_tag(ByteIOContext *pb, MOVContext *mov,
1129 AVFormatContext *s)
1130{
1131 int size = 0;
1132 if (s->track) {
1133 offset_t pos = url_ftell(pb);
1134 put_be32(pb, 0); /* size */
1135 put_tag(pb, "trkn");
1136 {
1137 offset_t pos = url_ftell(pb);
1138 put_be32(pb, 0); /* size */
1139 put_tag(pb, "data");
1140 put_be32(pb, 0); // 8 bytes empty
1141 put_be32(pb, 0);
1142 put_be16(pb, 0); // empty
1143 put_be16(pb, s->track); // track number
1144 put_be16(pb, 0); // total track number
1145 put_be16(pb, 0); // empty
1146 updateSize(pb, pos);
1147 }
1148 size = updateSize(pb, pos);
1149 }
1150 return size;
1151}
1152
1153/* iTunes meta data list */
1154static int mov_write_ilst_tag(ByteIOContext *pb, MOVContext *mov,
1155 AVFormatContext *s)
1156{
1157 offset_t pos = url_ftell(pb);
1158 put_be32(pb, 0); /* size */
1159 put_tag(pb, "ilst");
1160 mov_write_string_tag(pb, "\251nam", s->title , 1);
1161 mov_write_string_tag(pb, "\251ART", s->author , 1);
1162 mov_write_string_tag(pb, "\251wrt", s->author , 1);
1163 mov_write_string_tag(pb, "\251alb", s->album , 1);
1164 mov_write_day_tag(pb, s->year ,1);
1165 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 1);
1166 mov_write_string_tag(pb, "\251cmt", s->comment , 1);
1167 mov_write_string_tag(pb, "\251gen", s->genre , 1);
1168 mov_write_trkn_tag(pb, mov, s);
1169 return updateSize(pb, pos);
1170}
1171
1172/* iTunes meta data tag */
1173static int mov_write_meta_tag(ByteIOContext *pb, MOVContext *mov,
1174 AVFormatContext *s)
1175{
1176 int size = 0;
1177
1178 // only save meta tag if required
1179 if (s->title[0] || s->author[0] || s->album[0] || s->year ||
1180 s->comment[0] || s->genre[0] || s->track) {
1181 offset_t pos = url_ftell(pb);
1182 put_be32(pb, 0); /* size */
1183 put_tag(pb, "meta");
1184 put_be32(pb, 0);
1185 mov_write_itunes_hdlr_tag(pb, mov, s);
1186 mov_write_ilst_tag(pb, mov, s);
1187 size = updateSize(pb, pos);
1188 }
1189 return size;
1190}
1191
1192static int utf8len(const uint8_t *b)
1193{
1194 int len=0;
1195 int val;
1196 while(*b){
1197 GET_UTF8(val, *b++, return -1;)
1198 len++;
1199 }
1200 return len;
1201}
1202
1203static int ascii_to_wc(ByteIOContext *pb, const uint8_t *b)
1204{
1205 int val;
1206 while(*b){
1207 GET_UTF8(val, *b++, return -1;)
1208 put_be16(pb, val);
1209 }
1210 put_be16(pb, 0x00);
1211 return 0;
1212}
1213
1214static uint16_t language_code(const char *str)
1215{
1216 return (((str[0]-0x60) & 0x1F) << 10) + (((str[1]-0x60) & 0x1F) << 5) + ((str[2]-0x60) & 0x1F);
1217}
1218
1219static int mov_write_3gp_udta_tag(ByteIOContext *pb, AVFormatContext *s,
1220 const char *tag, const char *str)
1221{
1222 offset_t pos = url_ftell(pb);
1223 if (!utf8len(str))
1224 return 0;
1225 put_be32(pb, 0); /* size */
1226 put_tag (pb, tag); /* type */
1227 put_be32(pb, 0); /* version + flags */
1228 if (!strcmp(tag, "yrrc"))
1229 put_be16(pb, s->year);
1230 else {
1231 put_be16(pb, language_code("eng")); /* language */
1232 ascii_to_wc(pb, str);
1233 if (!strcmp(tag, "albm") && s->year)
1234 put_byte(pb, s->year);
1235 }
1236 return updateSize(pb, pos);
1237}
1238
1239static int mov_write_udta_tag(ByteIOContext *pb, MOVContext *mov,
1240 AVFormatContext *s)
1241{
1242 int i;
1243 int bitexact = 0;
1244
1245 for (i = 0; i < s->nb_streams; i++)
1246 if (mov->tracks[i].enc->flags & CODEC_FLAG_BITEXACT) {
1247 bitexact = 1;
1248 break;
1249 }
1250
1251 if (!bitexact && (s->title[0] || s->author[0] || s->album[0] || s->year ||
1252 s->comment[0] || s->genre[0] || s->track)) {
1253 offset_t pos = url_ftell(pb);
1254
1255 put_be32(pb, 0); /* size */
1256 put_tag(pb, "udta");
1257
1258 if (mov->mode & MODE_3GP) {
1259 mov_write_3gp_udta_tag(pb, s, "titl", s->title);
1260 mov_write_3gp_udta_tag(pb, s, "auth", s->author);
1261 mov_write_3gp_udta_tag(pb, s, "gnre", s->genre);
1262 mov_write_3gp_udta_tag(pb, s, "dscp", s->comment);
1263 mov_write_3gp_udta_tag(pb, s, "albm", s->album);
1264 mov_write_3gp_udta_tag(pb, s, "yrrc", "nil");
1265 } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
1266 mov_write_string_tag(pb, "\251nam", s->title , 0);
1267 mov_write_string_tag(pb, "\251aut", s->author , 0);
1268 mov_write_string_tag(pb, "\251alb", s->album , 0);
1269 mov_write_day_tag(pb, s->year, 0);
1270 mov_write_string_tag(pb, "\251enc", LIBAVFORMAT_IDENT, 0);
1271 mov_write_string_tag(pb, "\251des", s->comment , 0);
1272 mov_write_string_tag(pb, "\251gen", s->genre , 0);
1273 } else {
1274 /* iTunes meta data */
1275 mov_write_meta_tag(pb, mov, s);
1276 }
1277 return updateSize(pb, pos);
1278 }
1279
1280 return 0;
1281}
1282
1283static void mov_write_psp_udta_tag(ByteIOContext *pb,
1284 const char *str, const char *lang, int type)
1285{
1286 int len = utf8len(str)+1;
1287 if(len<=0)
1288 return;
1289 put_be16(pb, len*2+10); /* size */
1290 put_be32(pb, type); /* type */
1291 put_be16(pb, language_code(lang)); /* language */
1292 put_be16(pb, 0x01); /* ? */
1293 ascii_to_wc(pb, str);
1294}
1295
1296static int mov_write_uuidusmt_tag(ByteIOContext *pb, AVFormatContext *s)
1297{
1298 offset_t pos, pos2;
1299
1300 if (s->title[0]) {
1301 pos = url_ftell(pb);
1302 put_be32(pb, 0); /* size placeholder*/
1303 put_tag(pb, "uuid");
1304 put_tag(pb, "USMT");
1305 put_be32(pb, 0x21d24fce); /* 96 bit UUID */
1306 put_be32(pb, 0xbb88695c);
1307 put_be32(pb, 0xfac9c740);
1308
1309 pos2 = url_ftell(pb);
1310 put_be32(pb, 0); /* size placeholder*/
1311 put_tag(pb, "MTDT");
1312 put_be16(pb, 4);
1313
1314 // ?
1315 put_be16(pb, 0x0C); /* size */
1316 put_be32(pb, 0x0B); /* type */
1317 put_be16(pb, language_code("und")); /* language */
1318 put_be16(pb, 0x0); /* ? */
1319 put_be16(pb, 0x021C); /* data */
1320
1321 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
1322 mov_write_psp_udta_tag(pb, s->title, "eng", 0x01);
1323// snprintf(dt,32,"%04d/%02d/%02d %02d:%02d:%02d",t_st->tm_year+1900,t_st->tm_mon+1,t_st->tm_mday,t_st->tm_hour,t_st->tm_min,t_st->tm_sec);
1324 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
1325
1326 updateSize(pb, pos2);
1327 return updateSize(pb, pos);
1328 }
1329
1330 return 0;
1331}
1332
1333static int mov_write_moov_tag(ByteIOContext *pb, MOVContext *mov,
1334 AVFormatContext *s)
1335{
1336 int i;
1337 offset_t pos = url_ftell(pb);
1338 put_be32(pb, 0); /* size placeholder*/
1339 put_tag(pb, "moov");
1340 mov->timescale = globalTimescale;
1341
1342 for (i=0; i<mov->nb_streams; i++) {
1343 if(mov->tracks[i].entry <= 0) continue;
1344
1345 mov->tracks[i].time = mov->time;
1346 mov->tracks[i].trackID = i+1;
1347 }
1348
1349 mov_write_mvhd_tag(pb, mov);
1350 //mov_write_iods_tag(pb, mov);
1351 for (i=0; i<mov->nb_streams; i++) {
1352 if(mov->tracks[i].entry > 0) {
1353 mov_write_trak_tag(pb, &(mov->tracks[i]));
1354 }
1355 }
1356
1357 if (mov->mode == MODE_PSP)
1358 mov_write_uuidusmt_tag(pb, s);
1359 else
1360 mov_write_udta_tag(pb, mov, s);
1361
1362 return updateSize(pb, pos);
1363}
1364
1365static int mov_write_mdat_tag(ByteIOContext *pb, MOVContext *mov)
1366{
1367 put_be32(pb, 8); // placeholder for extended size field (64 bit)
1368 put_tag(pb, mov->mode == MODE_MOV ? "wide" : "free");
1369
1370 mov->mdat_pos = url_ftell(pb);
1371 put_be32(pb, 0); /* size placeholder*/
1372 put_tag(pb, "mdat");
1373 return 0;
1374}
1375
1376/* TODO: This needs to be more general */
1377static int mov_write_ftyp_tag(ByteIOContext *pb, AVFormatContext *s)
1378{
1379 MOVContext *mov = s->priv_data;
1380 offset_t pos = url_ftell(pb);
1381 int has_h264 = 0, has_video = 0;
1382 int minor = 0x200;
1383 int i;
1384
1385 for (i = 0; i < s->nb_streams; i++) {
1386 AVStream *st = s->streams[i];
1387 if (st->codec->codec_type == CODEC_TYPE_VIDEO)
1388 has_video = 1;
1389 if (st->codec->codec_id == CODEC_ID_H264)
1390 has_h264 = 1;
1391 }
1392
1393 put_be32(pb, 0); /* size */
1394 put_tag(pb, "ftyp");
1395
1396 if (mov->mode == MODE_3GP) {
1397 put_tag(pb, has_h264 ? "3gp6" : "3gp4");
1398 minor = has_h264 ? 0x100 : 0x200;
1399 } else if (mov->mode & MODE_3G2) {
1400 put_tag(pb, has_h264 ? "3g2b" : "3g2a");
1401 minor = has_h264 ? 0x20000 : 0x10000;
1402 }else if (mov->mode == MODE_PSP)
1403 put_tag(pb, "MSNV");
1404 else if (mov->mode == MODE_MP4)
1405 put_tag(pb, "isom");
1406 else if (mov->mode == MODE_IPOD)
1407 put_tag(pb, has_video ? "M4V ":"M4A ");
1408 else
1409 put_tag(pb, "qt ");
1410
1411 put_be32(pb, minor);
1412
1413 if(mov->mode == MODE_MOV)
1414 put_tag(pb, "qt ");
1415 else{
1416 put_tag(pb, "isom");
1417 put_tag(pb, "iso2");
1418 if(has_h264)
1419 put_tag(pb, "avc1");
1420 }
1421
1422 if (mov->mode == MODE_3GP)
1423 put_tag(pb, has_h264 ? "3gp6":"3gp4");
1424 else if (mov->mode & MODE_3G2)
1425 put_tag(pb, has_h264 ? "3g2b":"3g2a");
1426 else if (mov->mode == MODE_PSP)
1427 put_tag(pb, "MSNV");
1428 else if (mov->mode == MODE_MP4)
1429 put_tag(pb, "mp41");
1430 return updateSize(pb, pos);
1431}
1432
1433static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
1434{
1435 AVCodecContext *VideoCodec = s->streams[0]->codec;
1436 AVCodecContext *AudioCodec = s->streams[1]->codec;
1437 int AudioRate = AudioCodec->sample_rate;
1438 int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1439 int audio_kbitrate= AudioCodec->bit_rate / 1000;
1440 int video_kbitrate= FFMIN(VideoCodec->bit_rate / 1000, 800 - audio_kbitrate);
1441
1442 put_be32(pb, 0x94); /* size */
1443 put_tag(pb, "uuid");
1444 put_tag(pb, "PROF");
1445
1446 put_be32(pb, 0x21d24fce); /* 96 bit UUID */
1447 put_be32(pb, 0xbb88695c);
1448 put_be32(pb, 0xfac9c740);
1449
1450 put_be32(pb, 0x0); /* ? */
1451 put_be32(pb, 0x3); /* 3 sections ? */
1452
1453 put_be32(pb, 0x14); /* size */
1454 put_tag(pb, "FPRF");
1455 put_be32(pb, 0x0); /* ? */
1456 put_be32(pb, 0x0); /* ? */
1457 put_be32(pb, 0x0); /* ? */
1458
1459 put_be32(pb, 0x2c); /* size */
1460 put_tag(pb, "APRF"); /* audio */
1461 put_be32(pb, 0x0);
1462 put_be32(pb, 0x2); /* TrackID */
1463 put_tag(pb, "mp4a");
1464 put_be32(pb, 0x20f);
1465 put_be32(pb, 0x0);
1466 put_be32(pb, audio_kbitrate);
1467 put_be32(pb, audio_kbitrate);
1468 put_be32(pb, AudioRate);
1469 put_be32(pb, AudioCodec->channels);
1470
1471 put_be32(pb, 0x34); /* size */
1472 put_tag(pb, "VPRF"); /* video */
1473 put_be32(pb, 0x0);
1474 put_be32(pb, 0x1); /* TrackID */
1475 if (VideoCodec->codec_id == CODEC_ID_H264) {
1476 put_tag(pb, "avc1");
1477 put_be16(pb, 0x014D);
1478 put_be16(pb, 0x0015);
1479 } else {
1480 put_tag(pb, "mp4v");
1481 put_be16(pb, 0x0000);
1482 put_be16(pb, 0x0103);
1483 }
1484 put_be32(pb, 0x0);
1485 put_be32(pb, video_kbitrate);
1486 put_be32(pb, video_kbitrate);
1487 put_be32(pb, FrameRate);
1488 put_be32(pb, FrameRate);
1489 put_be16(pb, VideoCodec->width);
1490 put_be16(pb, VideoCodec->height);
1491 put_be32(pb, 0x010001); /* ? */
1492}
1493
1494static int mov_write_header(AVFormatContext *s)
1495{
1496 ByteIOContext *pb = s->pb;
1497 MOVContext *mov = s->priv_data;
1498 int i;
1499
1500 if (url_is_streamed(s->pb)) {
1501 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
1502 return -1;
1503 }
1504
1505 /* Default mode == MP4 */
1506 mov->mode = MODE_MP4;
1507
1508 if (s->oformat != NULL) {
1509 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
1510 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
1511 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
1512 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
1513 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
1514
1515 mov_write_ftyp_tag(pb,s);
1516 if (mov->mode == MODE_PSP) {
1517 if (s->nb_streams != 2) {
1518 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
1519 return -1;
1520 }
1521 mov_write_uuidprof_tag(pb,s);
1522 }
1523 }
1524
1525 for(i=0; i<s->nb_streams; i++){
1526 AVStream *st= s->streams[i];
1527 MOVTrack *track= &mov->tracks[i];
1528
1529 track->enc = st->codec;
1530 track->language = ff_mov_iso639_to_lang(st->language, mov->mode != MODE_MOV);
1531 track->mode = mov->mode;
1532 track->tag = mov_find_codec_tag(s, track);
1533 if (!track->tag) {
1534 av_log(s, AV_LOG_ERROR, "track %d: could not find tag, "
1535 "codec not currently supported in container\n", i);
1536 return -1;
1537 }
1538 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
1539 track->timescale = st->codec->time_base.den;
1540 av_set_pts_info(st, 64, 1, st->codec->time_base.den);
1541 if (track->mode == MODE_MOV && track->timescale > 100000)
1542 av_log(s, AV_LOG_WARNING,
1543 "WARNING codec timebase is very high. If duration is too long,\n"
1544 "file may not be playable by quicktime. Specify a shorter timebase\n"
1545 "or choose different container.\n");
1546 }else if(st->codec->codec_type == CODEC_TYPE_AUDIO){
1547 track->timescale = st->codec->sample_rate;
1548 av_set_pts_info(st, 64, 1, st->codec->sample_rate);
1549 if(!st->codec->frame_size){
1550 av_log(s, AV_LOG_ERROR, "track %d: codec frame size is not set\n", i);
1551 return -1;
1552 }else if(st->codec->frame_size > 1){ /* assume compressed audio */
1553 track->audio_vbr = 1;
1554 }else{
1555 track->sampleSize = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
1556 }
1557 }
1558 }
1559
1560 mov_write_mdat_tag(pb, mov);
1561 mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
1562 mov->nb_streams = s->nb_streams;
1563
1564 put_flush_packet(pb);
1565
1566 return 0;
1567}
1568
1569static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1570{
1571 MOVContext *mov = s->priv_data;
1572 ByteIOContext *pb = s->pb;
1573 MOVTrack *trk = &mov->tracks[pkt->stream_index];
1574 AVCodecContext *enc = trk->enc;
1575 unsigned int samplesInChunk = 0;
1576 int size= pkt->size;
1577
1578 if (url_is_streamed(s->pb)) return 0; /* Can't handle that */
1579 if (!size) return 0; /* Discard 0 sized packets */
1580
1581 if (enc->codec_id == CODEC_ID_AMR_NB) {
1582 /* We must find out how many AMR blocks there are in one packet */
1583 static uint16_t packed_size[16] =
1584 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1585 int len = 0;
1586
1587 while (len < size && samplesInChunk < 100) {
1588 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1589 samplesInChunk++;
1590 }
1591 if(samplesInChunk > 1){
1592 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
1593 return -1;
1594 }
1595 } else if (trk->sampleSize)
1596 samplesInChunk = size/trk->sampleSize;
1597 else
1598 samplesInChunk = 1;
1599
1600 /* copy extradata if it exists */
1601 if (trk->vosLen == 0 && enc->extradata_size > 0) {
1602 trk->vosLen = enc->extradata_size;
1603 trk->vosData = av_malloc(trk->vosLen);
1604 memcpy(trk->vosData, enc->extradata, trk->vosLen);
1605 }
1606
1607 if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {
1608 /* from x264 or from bytestream h264 */
1609 /* nal reformating needed */
1610 int ret = ff_avc_parse_nal_units(pkt->data, &pkt->data, &pkt->size);
1611 if (ret < 0)
1612 return ret;
1613 assert(pkt->size);
1614 size = pkt->size;
1615 } else if (enc->codec_id == CODEC_ID_DNXHD && !trk->vosLen) {
1616 /* copy frame header to create needed atoms */
1617 if (size < 640)
1618 return -1;
1619 trk->vosLen = 640;
1620 trk->vosData = av_malloc(trk->vosLen);
1621 memcpy(trk->vosData, pkt->data, 640);
1622 }
1623
1624 if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
1625 trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));
1626 if (!trk->cluster)
1627 return -1;
1628 }
1629
1630 trk->cluster[trk->entry].pos = url_ftell(pb);
1631 trk->cluster[trk->entry].samplesInChunk = samplesInChunk;
1632 trk->cluster[trk->entry].size = size;
1633 trk->cluster[trk->entry].entries = samplesInChunk;
1634 trk->cluster[trk->entry].dts = pkt->dts;
1635 trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration;
1636
1637 if (pkt->pts == AV_NOPTS_VALUE) {
1638 av_log(s, AV_LOG_WARNING, "pts has no value\n");
1639 pkt->pts = pkt->dts;
1640 }
1641 if (pkt->dts != pkt->pts)
1642 trk->hasBframes = 1;
1643 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
1644 trk->cluster[trk->entry].key_frame = !!(pkt->flags & PKT_FLAG_KEY);
1645 if(trk->cluster[trk->entry].key_frame)
1646 trk->hasKeyframes++;
1647 trk->entry++;
1648 trk->sampleCount += samplesInChunk;
1649 mov->mdat_size += size;
1650
1651 put_buffer(pb, pkt->data, size);
1652
1653 put_flush_packet(pb);
1654 return 0;
1655}
1656
1657static int mov_write_trailer(AVFormatContext *s)
1658{
1659 MOVContext *mov = s->priv_data;
1660 ByteIOContext *pb = s->pb;
1661 int res = 0;
1662 int i;
1663
1664 offset_t moov_pos = url_ftell(pb);
1665
1666 /* Write size of mdat tag */
1667 if (mov->mdat_size+8 <= UINT32_MAX) {
1668 url_fseek(pb, mov->mdat_pos, SEEK_SET);
1669 put_be32(pb, mov->mdat_size+8);
1670 } else {
1671 /* overwrite 'wide' placeholder atom */
1672 url_fseek(pb, mov->mdat_pos - 8, SEEK_SET);
1673 put_be32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
1674 put_tag(pb, "mdat");
1675 put_be64(pb, mov->mdat_size+16);
1676 }
1677 url_fseek(pb, moov_pos, SEEK_SET);
1678
1679 mov_write_moov_tag(pb, mov, s);
1680
1681 for (i=0; i<mov->nb_streams; i++) {
1682 av_freep(&mov->tracks[i].cluster);
1683
1684 if(mov->tracks[i].vosLen) av_free(mov->tracks[i].vosData);
1685
1686 }
1687
1688 put_flush_packet(pb);
1689
1690 return res;
1691}
1692
1693#ifdef CONFIG_MOV_MUXER
1694AVOutputFormat mov_muxer = {
1695 "mov",
1696 NULL_IF_CONFIG_SMALL("MOV format"),
1697 NULL,
1698 "mov",
1699 sizeof(MOVContext),
1700 CODEC_ID_AAC,
1701 CODEC_ID_MPEG4,
1702 mov_write_header,
1703 mov_write_packet,
1704 mov_write_trailer,
1705 .flags = AVFMT_GLOBALHEADER,
1706 .codec_tag = (const AVCodecTag*[]){codec_movvideo_tags, codec_movaudio_tags, 0},
1707};
1708#endif
1709#ifdef CONFIG_TGP_MUXER
1710AVOutputFormat tgp_muxer = {
1711 "3gp",
1712 NULL_IF_CONFIG_SMALL("3GP format"),
1713 NULL,
1714 "3gp",
1715 sizeof(MOVContext),
1716 CODEC_ID_AMR_NB,
1717 CODEC_ID_H263,
1718 mov_write_header,
1719 mov_write_packet,
1720 mov_write_trailer,
1721 .flags = AVFMT_GLOBALHEADER,
1722 .codec_tag = (const AVCodecTag*[]){codec_3gp_tags, 0},
1723};
1724#endif
1725#ifdef CONFIG_MP4_MUXER
1726AVOutputFormat mp4_muxer = {
1727 "mp4",
1728 NULL_IF_CONFIG_SMALL("MP4 format"),
1729 "application/mp4",
1730 "mp4",
1731 sizeof(MOVContext),
1732 CODEC_ID_AAC,
1733 CODEC_ID_MPEG4,
1734 mov_write_header,
1735 mov_write_packet,
1736 mov_write_trailer,
1737 .flags = AVFMT_GLOBALHEADER,
1738 .codec_tag = (const AVCodecTag*[]){ff_mp4_obj_type, 0},
1739};
1740#endif
1741#ifdef CONFIG_PSP_MUXER
1742AVOutputFormat psp_muxer = {
1743 "psp",
1744 NULL_IF_CONFIG_SMALL("PSP MP4 format"),
1745 NULL,
1746 "mp4,psp",
1747 sizeof(MOVContext),
1748 CODEC_ID_AAC,
1749 CODEC_ID_MPEG4,
1750 mov_write_header,
1751 mov_write_packet,
1752 mov_write_trailer,
1753 .flags = AVFMT_GLOBALHEADER,
1754 .codec_tag = (const AVCodecTag*[]){ff_mp4_obj_type, 0},
1755};
1756#endif
1757#ifdef CONFIG_TG2_MUXER
1758AVOutputFormat tg2_muxer = {
1759 "3g2",
1760 NULL_IF_CONFIG_SMALL("3GP2 format"),
1761 NULL,
1762 "3g2",
1763 sizeof(MOVContext),
1764 CODEC_ID_AMR_NB,
1765 CODEC_ID_H263,
1766 mov_write_header,
1767 mov_write_packet,
1768 mov_write_trailer,
1769 .flags = AVFMT_GLOBALHEADER,
1770 .codec_tag = (const AVCodecTag*[]){codec_3gp_tags, 0},
1771};
1772#endif
1773#ifdef CONFIG_IPOD_MUXER
1774AVOutputFormat ipod_muxer = {
1775 "ipod",
1776 NULL_IF_CONFIG_SMALL("iPod H.264 MP4 format"),
1777 "application/mp4",
1778 "m4v,m4a",
1779 sizeof(MOVContext),
1780 CODEC_ID_AAC,
1781 CODEC_ID_H264,
1782 mov_write_header,
1783 mov_write_packet,
1784 mov_write_trailer,
1785 .flags = AVFMT_GLOBALHEADER,
1786 .codec_tag = (const AVCodecTag*[]){ff_mp4_obj_type, 0},
1787};
1788#endif
diff --git a/src/plugins/ffmpeg/libavformat/mp3.c b/src/plugins/ffmpeg/libavformat/mp3.c
deleted file mode 100644
index 346c7ea..0000000
--- a/src/plugins/ffmpeg/libavformat/mp3.c
+++ /dev/null
@@ -1,686 +0,0 @@
1/*
2 * MP3 muxer and demuxer
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/avstring.h"
23#include "libavcodec/mpegaudio.h"
24#include "libavcodec/mpegaudiodecheader.h"
25#include "avformat.h"
26
27#define ID3v2_HEADER_SIZE 10
28#define ID3v1_TAG_SIZE 128
29
30#define ID3v1_GENRE_MAX 125
31
32static const char *id3v1_genre_str[ID3v1_GENRE_MAX + 1] = {
33 [0] = "Blues",
34 [1] = "Classic Rock",
35 [2] = "Country",
36 [3] = "Dance",
37 [4] = "Disco",
38 [5] = "Funk",
39 [6] = "Grunge",
40 [7] = "Hip-Hop",
41 [8] = "Jazz",
42 [9] = "Metal",
43 [10] = "New Age",
44 [11] = "Oldies",
45 [12] = "Other",
46 [13] = "Pop",
47 [14] = "R&B",
48 [15] = "Rap",
49 [16] = "Reggae",
50 [17] = "Rock",
51 [18] = "Techno",
52 [19] = "Industrial",
53 [20] = "Alternative",
54 [21] = "Ska",
55 [22] = "Death Metal",
56 [23] = "Pranks",
57 [24] = "Soundtrack",
58 [25] = "Euro-Techno",
59 [26] = "Ambient",
60 [27] = "Trip-Hop",
61 [28] = "Vocal",
62 [29] = "Jazz+Funk",
63 [30] = "Fusion",
64 [31] = "Trance",
65 [32] = "Classical",
66 [33] = "Instrumental",
67 [34] = "Acid",
68 [35] = "House",
69 [36] = "Game",
70 [37] = "Sound Clip",
71 [38] = "Gospel",
72 [39] = "Noise",
73 [40] = "AlternRock",
74 [41] = "Bass",
75 [42] = "Soul",
76 [43] = "Punk",
77 [44] = "Space",
78 [45] = "Meditative",
79 [46] = "Instrumental Pop",
80 [47] = "Instrumental Rock",
81 [48] = "Ethnic",
82 [49] = "Gothic",
83 [50] = "Darkwave",
84 [51] = "Techno-Industrial",
85 [52] = "Electronic",
86 [53] = "Pop-Folk",
87 [54] = "Eurodance",
88 [55] = "Dream",
89 [56] = "Southern Rock",
90 [57] = "Comedy",
91 [58] = "Cult",
92 [59] = "Gangsta",
93 [60] = "Top 40",
94 [61] = "Christian Rap",
95 [62] = "Pop/Funk",
96 [63] = "Jungle",
97 [64] = "Native American",
98 [65] = "Cabaret",
99 [66] = "New Wave",
100 [67] = "Psychadelic",
101 [68] = "Rave",
102 [69] = "Showtunes",
103 [70] = "Trailer",
104 [71] = "Lo-Fi",
105 [72] = "Tribal",
106 [73] = "Acid Punk",
107 [74] = "Acid Jazz",
108 [75] = "Polka",
109 [76] = "Retro",
110 [77] = "Musical",
111 [78] = "Rock & Roll",
112 [79] = "Hard Rock",
113 [80] = "Folk",
114 [81] = "Folk-Rock",
115 [82] = "National Folk",
116 [83] = "Swing",
117 [84] = "Fast Fusion",
118 [85] = "Bebob",
119 [86] = "Latin",
120 [87] = "Revival",
121 [88] = "Celtic",
122 [89] = "Bluegrass",
123 [90] = "Avantgarde",
124 [91] = "Gothic Rock",
125 [92] = "Progressive Rock",
126 [93] = "Psychedelic Rock",
127 [94] = "Symphonic Rock",
128 [95] = "Slow Rock",
129 [96] = "Big Band",
130 [97] = "Chorus",
131 [98] = "Easy Listening",
132 [99] = "Acoustic",
133 [100] = "Humour",
134 [101] = "Speech",
135 [102] = "Chanson",
136 [103] = "Opera",
137 [104] = "Chamber Music",
138 [105] = "Sonata",
139 [106] = "Symphony",
140 [107] = "Booty Bass",
141 [108] = "Primus",
142 [109] = "Porn Groove",
143 [110] = "Satire",
144 [111] = "Slow Jam",
145 [112] = "Club",
146 [113] = "Tango",
147 [114] = "Samba",
148 [115] = "Folklore",
149 [116] = "Ballad",
150 [117] = "Power Ballad",
151 [118] = "Rhythmic Soul",
152 [119] = "Freestyle",
153 [120] = "Duet",
154 [121] = "Punk Rock",
155 [122] = "Drum Solo",
156 [123] = "A capella",
157 [124] = "Euro-House",
158 [125] = "Dance Hall",
159};
160
161/* buf must be ID3v2_HEADER_SIZE byte long */
162static int id3v2_match(const uint8_t *buf)
163{
164 return buf[0] == 'I' &&
165 buf[1] == 'D' &&
166 buf[2] == '3' &&
167 buf[3] != 0xff &&
168 buf[4] != 0xff &&
169 (buf[6] & 0x80) == 0 &&
170 (buf[7] & 0x80) == 0 &&
171 (buf[8] & 0x80) == 0 &&
172 (buf[9] & 0x80) == 0;
173}
174
175static unsigned int id3v2_get_size(ByteIOContext *s, int len)
176{
177 int v=0;
178 while(len--)
179 v= (v<<7) + (get_byte(s)&0x7F);
180 return v;
181}
182
183static void id3v2_read_ttag(AVFormatContext *s, int taglen, char *dst, int dstlen)
184{
185 char *q;
186 int len;
187
188 if(dstlen > 0)
189 dst[0]= 0;
190 if(taglen < 1)
191 return;
192
193 taglen--; /* account for encoding type byte */
194 dstlen--; /* Leave space for zero terminator */
195
196 switch(get_byte(s->pb)) { /* encoding type */
197
198 case 0: /* ISO-8859-1 (0 - 255 maps directly into unicode) */
199 q = dst;
200 while(taglen--) {
201 uint8_t tmp;
202 PUT_UTF8(get_byte(s->pb), tmp, if (q - dst < dstlen - 1) *q++ = tmp;)
203 }
204 *q = '\0';
205 break;
206
207 case 3: /* UTF-8 */
208 len = FFMIN(taglen, dstlen-1);
209 get_buffer(s->pb, dst, len);
210 dst[len] = 0;
211 break;
212 }
213}
214
215/**
216 * ID3v2 parser
217 *
218 * Handles ID3v2.2, 2.3 and 2.4.
219 *
220 */
221
222static void id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags)
223{
224 int isv34, tlen;
225 uint32_t tag;
226 offset_t next;
227 char tmp[16];
228 int taghdrlen;
229 const char *reason;
230
231 switch(version) {
232 case 2:
233 if(flags & 0x40) {
234 reason = "compression";
235 goto error;
236 }
237 isv34 = 0;
238 taghdrlen = 6;
239 break;
240
241 case 3:
242 case 4:
243 isv34 = 1;
244 taghdrlen = 10;
245 break;
246
247 default:
248 reason = "version";
249 goto error;
250 }
251
252 if(flags & 0x80) {
253 reason = "unsynchronization";
254 goto error;
255 }
256
257 if(isv34 && flags & 0x40) /* Extended header present, just skip over it */
258 url_fskip(s->pb, id3v2_get_size(s->pb, 4));
259
260 while(len >= taghdrlen) {
261 if(isv34) {
262 tag = get_be32(s->pb);
263 tlen = id3v2_get_size(s->pb, 4);
264 get_be16(s->pb); /* flags */
265 } else {
266 tag = get_be24(s->pb);
267 tlen = id3v2_get_size(s->pb, 3);
268 }
269 len -= taghdrlen + tlen;
270
271 if(len < 0)
272 break;
273
274 next = url_ftell(s->pb) + tlen;
275
276 switch(tag) {
277 case MKBETAG('T', 'I', 'T', '2'):
278 case MKBETAG(0, 'T', 'T', '2'):
279 id3v2_read_ttag(s, tlen, s->title, sizeof(s->title));
280 break;
281 case MKBETAG('T', 'P', 'E', '1'):
282 case MKBETAG(0, 'T', 'P', '1'):
283 id3v2_read_ttag(s, tlen, s->author, sizeof(s->author));
284 break;
285 case MKBETAG('T', 'A', 'L', 'B'):
286 case MKBETAG(0, 'T', 'A', 'L'):
287 id3v2_read_ttag(s, tlen, s->album, sizeof(s->album));
288 break;
289 case MKBETAG('T', 'C', 'O', 'N'):
290 case MKBETAG(0, 'T', 'C', 'O'):
291 id3v2_read_ttag(s, tlen, s->genre, sizeof(s->genre));
292 break;
293 case MKBETAG('T', 'C', 'O', 'P'):
294 case MKBETAG(0, 'T', 'C', 'R'):
295 id3v2_read_ttag(s, tlen, s->copyright, sizeof(s->copyright));
296 break;
297 case MKBETAG('T', 'R', 'C', 'K'):
298 case MKBETAG(0, 'T', 'R', 'K'):
299 id3v2_read_ttag(s, tlen, tmp, sizeof(tmp));
300 s->track = atoi(tmp);
301 break;
302 case 0:
303 /* padding, skip to end */
304 url_fskip(s->pb, len);
305 len = 0;
306 continue;
307 }
308 /* Skip to end of tag */
309 url_fseek(s->pb, next, SEEK_SET);
310 }
311
312 if(version == 4 && flags & 0x10) /* Footer preset, always 10 bytes, skip over it */
313 url_fskip(s->pb, 10);
314 return;
315
316 error:
317 av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n", version, reason);
318 url_fskip(s->pb, len);
319}
320
321static void id3v1_get_string(char *str, int str_size,
322 const uint8_t *buf, int buf_size)
323{
324 int i, c;
325 char *q;
326
327 q = str;
328 for(i = 0; i < buf_size; i++) {
329 c = buf[i];
330 if (c == '\0')
331 break;
332 if ((q - str) >= str_size - 1)
333 break;
334 *q++ = c;
335 }
336 *q = '\0';
337}
338
339/* 'buf' must be ID3v1_TAG_SIZE byte long */
340static int id3v1_parse_tag(AVFormatContext *s, const uint8_t *buf)
341{
342 char str[5];
343 int genre;
344
345 if (!(buf[0] == 'T' &&
346 buf[1] == 'A' &&
347 buf[2] == 'G'))
348 return -1;
349 id3v1_get_string(s->title, sizeof(s->title), buf + 3, 30);
350 id3v1_get_string(s->author, sizeof(s->author), buf + 33, 30);
351 id3v1_get_string(s->album, sizeof(s->album), buf + 63, 30);
352 id3v1_get_string(str, sizeof(str), buf + 93, 4);
353 s->year = atoi(str);
354 id3v1_get_string(s->comment, sizeof(s->comment), buf + 97, 30);
355 if (buf[125] == 0 && buf[126] != 0)
356 s->track = buf[126];
357 genre = buf[127];
358 if (genre <= ID3v1_GENRE_MAX)
359 av_strlcpy(s->genre, id3v1_genre_str[genre], sizeof(s->genre));
360 return 0;
361}
362
363/* mp3 read */
364
365static int mp3_read_probe(AVProbeData *p)
366{
367 int max_frames, first_frames = 0;
368 int fsize, frames, sample_rate;
369 uint32_t header;
370 uint8_t *buf, *buf2, *end;
371 AVCodecContext avctx;
372
373 if(id3v2_match(p->buf))
374 return AVPROBE_SCORE_MAX/2+1; // this must be less than mpeg-ps because some retards put id3v2 tags before mpeg-ps files
375
376 max_frames = 0;
377 buf = p->buf;
378 end = buf + p->buf_size - sizeof(uint32_t);
379
380 for(; buf < end; buf= buf2+1) {
381 buf2 = buf;
382
383 for(frames = 0; buf2 < end; frames++) {
384 header = AV_RB32(buf2);
385 fsize = ff_mpa_decode_header(&avctx, header, &sample_rate);
386 if(fsize < 0)
387 break;
388 buf2 += fsize;
389 }
390 max_frames = FFMAX(max_frames, frames);
391 if(buf == p->buf)
392 first_frames= frames;
393 }
394 if (first_frames>=3) return AVPROBE_SCORE_MAX/2+1;
395 else if(max_frames>500)return AVPROBE_SCORE_MAX/2;
396 else if(max_frames>=3) return AVPROBE_SCORE_MAX/4;
397 else if(max_frames>=1) return 1;
398 else return 0;
399}
400
401/**
402 * Try to find Xing/Info/VBRI tags and compute duration from info therein
403 */
404static void mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, offset_t base)
405{
406 uint32_t v, spf;
407 int frames = -1; /* Total number of frames in file */
408 const offset_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
409 MPADecodeContext c;
410
411 v = get_be32(s->pb);
412 if(ff_mpa_check_header(v) < 0)
413 return;
414
415 ff_mpegaudio_decode_header(&c, v);
416 if(c.layer != 3)
417 return;
418
419 /* Check for Xing / Info tag */
420 url_fseek(s->pb, xing_offtbl[c.lsf == 1][c.nb_channels == 1], SEEK_CUR);
421 v = get_be32(s->pb);
422 if(v == MKBETAG('X', 'i', 'n', 'g') || v == MKBETAG('I', 'n', 'f', 'o')) {
423 v = get_be32(s->pb);
424 if(v & 0x1)
425 frames = get_be32(s->pb);
426 }
427
428 /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
429 url_fseek(s->pb, base + 4 + 32, SEEK_SET);
430 v = get_be32(s->pb);
431 if(v == MKBETAG('V', 'B', 'R', 'I')) {
432 /* Check tag version */
433 if(get_be16(s->pb) == 1) {
434 /* skip delay, quality and total bytes */
435 url_fseek(s->pb, 8, SEEK_CUR);
436 frames = get_be32(s->pb);
437 }
438 }
439
440 if(frames < 0)
441 return;
442
443 spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
444 st->duration = av_rescale_q(frames, (AVRational){spf, c.sample_rate},
445 st->time_base);
446}
447
448static int mp3_read_header(AVFormatContext *s,
449 AVFormatParameters *ap)
450{
451 AVStream *st;
452 uint8_t buf[ID3v1_TAG_SIZE];
453 int len, ret, filesize;
454 offset_t off;
455
456 st = av_new_stream(s, 0);
457 if (!st)
458 return AVERROR(ENOMEM);
459
460 st->codec->codec_type = CODEC_TYPE_AUDIO;
461 st->codec->codec_id = CODEC_ID_MP3;
462 st->need_parsing = AVSTREAM_PARSE_FULL;
463 st->start_time = 0;
464
465 /* try to get the TAG */
466 if (!url_is_streamed(s->pb)) {
467 /* XXX: change that */
468 filesize = url_fsize(s->pb);
469 if (filesize > 128) {
470 url_fseek(s->pb, filesize - 128, SEEK_SET);
471 ret = get_buffer(s->pb, buf, ID3v1_TAG_SIZE);
472 if (ret == ID3v1_TAG_SIZE) {
473 id3v1_parse_tag(s, buf);
474 }
475 url_fseek(s->pb, 0, SEEK_SET);
476 }
477 }
478
479 /* if ID3v2 header found, skip it */
480 ret = get_buffer(s->pb, buf, ID3v2_HEADER_SIZE);
481 if (ret != ID3v2_HEADER_SIZE)
482 return -1;
483 if (id3v2_match(buf)) {
484 /* parse ID3v2 header */
485 len = ((buf[6] & 0x7f) << 21) |
486 ((buf[7] & 0x7f) << 14) |
487 ((buf[8] & 0x7f) << 7) |
488 (buf[9] & 0x7f);
489 id3v2_parse(s, len, buf[3], buf[5]);
490 } else {
491 url_fseek(s->pb, 0, SEEK_SET);
492 }
493
494 off = url_ftell(s->pb);
495 mp3_parse_vbr_tags(s, st, off);
496 url_fseek(s->pb, off, SEEK_SET);
497
498 /* the parameters will be extracted from the compressed bitstream */
499 return 0;
500}
501
502#define MP3_PACKET_SIZE 1024
503
504static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
505{
506 int ret, size;
507 // AVStream *st = s->streams[0];
508
509 size= MP3_PACKET_SIZE;
510
511 ret= av_get_packet(s->pb, pkt, size);
512
513 pkt->stream_index = 0;
514 if (ret <= 0) {
515 return AVERROR(EIO);
516 }
517 /* note: we need to modify the packet size here to handle the last
518 packet */
519 pkt->size = ret;
520 return ret;
521}
522
523#ifdef CONFIG_MUXERS
524static void id3v1_create_tag(AVFormatContext *s, uint8_t *buf)
525{
526 int v, i;
527
528 memset(buf, 0, ID3v1_TAG_SIZE); /* fail safe */
529 buf[0] = 'T';
530 buf[1] = 'A';
531 buf[2] = 'G';
532 strncpy(buf + 3, s->title, 30);
533 strncpy(buf + 33, s->author, 30);
534 strncpy(buf + 63, s->album, 30);
535 v = s->year;
536 if (v > 0) {
537 for(i = 0;i < 4; i++) {
538 buf[96 - i] = '0' + (v % 10);
539 v = v / 10;
540 }
541 }
542 strncpy(buf + 97, s->comment, 30);
543 if (s->track != 0) {
544 buf[125] = 0;
545 buf[126] = s->track;
546 }
547 for(i = 0; i <= ID3v1_GENRE_MAX; i++) {
548 if (!strcasecmp(s->genre, id3v1_genre_str[i])) {
549 buf[127] = i;
550 break;
551 }
552 }
553}
554
555/* simple formats */
556
557static void id3v2_put_size(AVFormatContext *s, int size)
558{
559 put_byte(s->pb, size >> 21 & 0x7f);
560 put_byte(s->pb, size >> 14 & 0x7f);
561 put_byte(s->pb, size >> 7 & 0x7f);
562 put_byte(s->pb, size & 0x7f);
563}
564
565static void id3v2_put_ttag(AVFormatContext *s, const char *string, uint32_t tag)
566{
567 int len = strlen(string);
568 put_be32(s->pb, tag);
569 id3v2_put_size(s, len + 1);
570 put_be16(s->pb, 0);
571 put_byte(s->pb, 3); /* UTF-8 */
572 put_buffer(s->pb, string, len);
573}
574
575
576/**
577 * Write an ID3v2.4 header at beginning of stream
578 */
579
580static int mp3_write_header(struct AVFormatContext *s)
581{
582 int totlen = 0;
583 char tracktxt[10];
584 char yeartxt[10];
585
586 if(s->track)
587 snprintf(tracktxt, sizeof(tracktxt), "%d", s->track);
588 if(s->year)
589 snprintf( yeartxt, sizeof(yeartxt) , "%d", s->year );
590
591 if(s->title[0]) totlen += 11 + strlen(s->title);
592 if(s->author[0]) totlen += 11 + strlen(s->author);
593 if(s->album[0]) totlen += 11 + strlen(s->album);
594 if(s->genre[0]) totlen += 11 + strlen(s->genre);
595 if(s->copyright[0]) totlen += 11 + strlen(s->copyright);
596 if(s->track) totlen += 11 + strlen(tracktxt);
597 if(s->year) totlen += 11 + strlen(yeartxt);
598 if(!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT))
599 totlen += strlen(LIBAVFORMAT_IDENT) + 11;
600
601 if(totlen == 0)
602 return 0;
603
604 put_be32(s->pb, MKBETAG('I', 'D', '3', 0x04)); /* ID3v2.4 */
605 put_byte(s->pb, 0);
606 put_byte(s->pb, 0); /* flags */
607
608 id3v2_put_size(s, totlen);
609
610 if(s->title[0]) id3v2_put_ttag(s, s->title, MKBETAG('T', 'I', 'T', '2'));
611 if(s->author[0]) id3v2_put_ttag(s, s->author, MKBETAG('T', 'P', 'E', '1'));
612 if(s->album[0]) id3v2_put_ttag(s, s->album, MKBETAG('T', 'A', 'L', 'B'));
613 if(s->genre[0]) id3v2_put_ttag(s, s->genre, MKBETAG('T', 'C', 'O', 'N'));
614 if(s->copyright[0]) id3v2_put_ttag(s, s->copyright, MKBETAG('T', 'C', 'O', 'P'));
615 if(s->track) id3v2_put_ttag(s, tracktxt, MKBETAG('T', 'R', 'C', 'K'));
616 if(s->year) id3v2_put_ttag(s, yeartxt, MKBETAG('T', 'Y', 'E', 'R'));
617 if(!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT))
618 id3v2_put_ttag(s, LIBAVFORMAT_IDENT, MKBETAG('T', 'E', 'N', 'C'));
619 return 0;
620}
621
622static int mp3_write_packet(struct AVFormatContext *s, AVPacket *pkt)
623{
624 put_buffer(s->pb, pkt->data, pkt->size);
625 put_flush_packet(s->pb);
626 return 0;
627}
628
629static int mp3_write_trailer(struct AVFormatContext *s)
630{
631 uint8_t buf[ID3v1_TAG_SIZE];
632
633 /* write the id3v1 tag */
634 if (s->title[0] != '\0') {
635 id3v1_create_tag(s, buf);
636 put_buffer(s->pb, buf, ID3v1_TAG_SIZE);
637 put_flush_packet(s->pb);
638 }
639 return 0;
640}
641#endif //CONFIG_MUXERS
642
643#ifdef CONFIG_MP3_DEMUXER
644AVInputFormat mp3_demuxer = {
645 "mp3",
646 NULL_IF_CONFIG_SMALL("MPEG audio"),
647 0,
648 mp3_read_probe,
649 mp3_read_header,
650 mp3_read_packet,
651 .flags= AVFMT_GENERIC_INDEX,
652 .extensions = "mp2,mp3,m2a", /* XXX: use probe */
653};
654#endif
655#ifdef CONFIG_MP2_MUXER
656AVOutputFormat mp2_muxer = {
657 "mp2",
658 NULL_IF_CONFIG_SMALL("MPEG audio layer 2"),
659 "audio/x-mpeg",
660#ifdef CONFIG_LIBMP3LAME
661 "mp2,m2a",
662#else
663 "mp2,mp3,m2a",
664#endif
665 0,
666 CODEC_ID_MP2,
667 CODEC_ID_NONE,
668 NULL,
669 mp3_write_packet,
670 mp3_write_trailer,
671};
672#endif
673#ifdef CONFIG_MP3_MUXER
674AVOutputFormat mp3_muxer = {
675 "mp3",
676 NULL_IF_CONFIG_SMALL("MPEG audio layer 3"),
677 "audio/x-mpeg",
678 "mp3",
679 0,
680 CODEC_ID_MP3,
681 CODEC_ID_NONE,
682 mp3_write_header,
683 mp3_write_packet,
684 mp3_write_trailer,
685};
686#endif
diff --git a/src/plugins/ffmpeg/libavformat/mpc.c b/src/plugins/ffmpeg/libavformat/mpc.c
deleted file mode 100644
index 7ed574d..0000000
--- a/src/plugins/ffmpeg/libavformat/mpc.c
+++ /dev/null
@@ -1,230 +0,0 @@
1/*
2 * Musepack demuxer
3 * Copyright (c) 2006 Konstantin Shishkov
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 "libavcodec/bitstream.h"
23#include "avformat.h"
24
25#define MPC_FRAMESIZE 1152
26#define DELAY_FRAMES 32
27
28static const int mpc_rate[4] = { 44100, 48000, 37800, 32000 };
29typedef struct {
30 int64_t pos;
31 int size, skip;
32}MPCFrame;
33
34typedef struct {
35 int ver;
36 uint32_t curframe, lastframe;
37 uint32_t fcount;
38 MPCFrame *frames;
39 int curbits;
40 int frames_noted;
41} MPCContext;
42
43static int mpc_probe(AVProbeData *p)
44{
45 const uint8_t *d = p->buf;
46 if (d[0] == 'M' && d[1] == 'P' && d[2] == '+' && (d[3] == 0x17 || d[3] == 0x7))
47 return AVPROBE_SCORE_MAX;
48 if (d[0] == 'I' && d[1] == 'D' && d[2] == '3')
49 return AVPROBE_SCORE_MAX / 2;
50 return 0;
51}
52
53static int mpc_read_header(AVFormatContext *s, AVFormatParameters *ap)
54{
55 MPCContext *c = s->priv_data;
56 AVStream *st;
57 int t;
58
59 t = get_le24(s->pb);
60 if(t != MKTAG('M', 'P', '+', 0)){
61 if(t != MKTAG('I', 'D', '3', 0)){
62 av_log(s, AV_LOG_ERROR, "Not a Musepack file\n");
63 return -1;
64 }
65 /* skip ID3 tags and try again */
66 url_fskip(s->pb, 3);
67 t = get_byte(s->pb) << 21;
68 t |= get_byte(s->pb) << 14;
69 t |= get_byte(s->pb) << 7;
70 t |= get_byte(s->pb);
71 av_log(s, AV_LOG_DEBUG, "Skipping %d(%X) bytes of ID3 data\n", t, t);
72 url_fskip(s->pb, t);
73 if(get_le24(s->pb) != MKTAG('M', 'P', '+', 0)){
74 av_log(s, AV_LOG_ERROR, "Not a Musepack file\n");
75 return -1;
76 }
77 }
78 c->ver = get_byte(s->pb);
79 if(c->ver != 0x07 && c->ver != 0x17){
80 av_log(s, AV_LOG_ERROR, "Can demux Musepack SV7, got version %02X\n", c->ver);
81 return -1;
82 }
83 c->fcount = get_le32(s->pb);
84 if((int64_t)c->fcount * sizeof(MPCFrame) >= UINT_MAX){
85 av_log(s, AV_LOG_ERROR, "Too many frames, seeking is not possible\n");
86 return -1;
87 }
88 c->frames = av_malloc(c->fcount * sizeof(MPCFrame));
89 c->curframe = 0;
90 c->lastframe = -1;
91 c->curbits = 8;
92 c->frames_noted = 0;
93
94 st = av_new_stream(s, 0);
95 if (!st)
96 return AVERROR(ENOMEM);
97 st->codec->codec_type = CODEC_TYPE_AUDIO;
98 st->codec->codec_id = CODEC_ID_MUSEPACK7;
99 st->codec->channels = 2;
100 st->codec->bits_per_sample = 16;
101
102 st->codec->extradata_size = 16;
103 st->codec->extradata = av_mallocz(st->codec->extradata_size+FF_INPUT_BUFFER_PADDING_SIZE);
104 get_buffer(s->pb, st->codec->extradata, 16);
105 st->codec->sample_rate = mpc_rate[st->codec->extradata[2] & 3];
106 av_set_pts_info(st, 32, MPC_FRAMESIZE, st->codec->sample_rate);
107 /* scan for seekpoints */
108 s->start_time = 0;
109 s->duration = (int64_t)c->fcount * MPC_FRAMESIZE * AV_TIME_BASE / st->codec->sample_rate;
110
111 return 0;
112}
113
114static int mpc_read_packet(AVFormatContext *s, AVPacket *pkt)
115{
116 MPCContext *c = s->priv_data;
117 int ret, size, size2, curbits, cur = c->curframe;
118 int64_t tmp, pos;
119
120 if (c->curframe >= c->fcount)
121 return -1;
122
123 if(c->curframe != c->lastframe + 1){
124 url_fseek(s->pb, c->frames[c->curframe].pos, SEEK_SET);
125 c->curbits = c->frames[c->curframe].skip;
126 }
127 c->lastframe = c->curframe;
128 c->curframe++;
129 curbits = c->curbits;
130 pos = url_ftell(s->pb);
131 tmp = get_le32(s->pb);
132 if(curbits <= 12){
133 size2 = (tmp >> (12 - curbits)) & 0xFFFFF;
134 }else{
135 tmp = (tmp << 32) | get_le32(s->pb);
136 size2 = (tmp >> (44 - curbits)) & 0xFFFFF;
137 }
138 curbits += 20;
139 url_fseek(s->pb, pos, SEEK_SET);
140
141 size = ((size2 + curbits + 31) & ~31) >> 3;
142 if(cur == c->frames_noted){
143 c->frames[cur].pos = pos;
144 c->frames[cur].size = size;
145 c->frames[cur].skip = curbits - 20;
146 av_add_index_entry(s->streams[0], cur, cur, size, 0, AVINDEX_KEYFRAME);
147 c->frames_noted++;
148 }
149 c->curbits = (curbits + size2) & 0x1F;
150
151 if (av_new_packet(pkt, size) < 0)
152 return AVERROR(EIO);
153
154 pkt->data[0] = curbits;
155 pkt->data[1] = (c->curframe > c->fcount);
156
157 pkt->stream_index = 0;
158 pkt->pts = cur;
159 ret = get_buffer(s->pb, pkt->data + 4, size);
160 if(c->curbits)
161 url_fseek(s->pb, -4, SEEK_CUR);
162 if(ret < size){
163 av_free_packet(pkt);
164 return AVERROR(EIO);
165 }
166 pkt->size = ret + 4;
167
168 return 0;
169}
170
171static int mpc_read_close(AVFormatContext *s)
172{
173 MPCContext *c = s->priv_data;
174
175 av_freep(&c->frames);
176 return 0;
177}
178
179/**
180 * Seek to the given position
181 * If position is unknown but is within the limits of file
182 * then packets are skipped unless desired position is reached
183 *
184 * Also this function makes use of the fact that timestamp == frameno
185 */
186static int mpc_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
187{
188 AVStream *st = s->streams[stream_index];
189 MPCContext *c = s->priv_data;
190 AVPacket pkt1, *pkt = &pkt1;
191 int ret;
192 int index = av_index_search_timestamp(st, timestamp - DELAY_FRAMES, flags);
193 uint32_t lastframe;
194
195 /* if found, seek there */
196 if (index >= 0){
197 c->curframe = st->index_entries[index].pos;
198 return 0;
199 }
200 /* if timestamp is out of bounds, return error */
201 if(timestamp < 0 || timestamp >= c->fcount)
202 return -1;
203 timestamp -= DELAY_FRAMES;
204 /* seek to the furthest known position and read packets until
205 we reach desired position */
206 lastframe = c->curframe;
207 if(c->frames_noted) c->curframe = c->frames_noted - 1;
208 while(c->curframe < timestamp){
209 ret = av_read_frame(s, pkt);
210 if (ret < 0){
211 c->curframe = lastframe;
212 return -1;
213 }
214 av_free_packet(pkt);
215 }
216 return 0;
217}
218
219
220AVInputFormat mpc_demuxer = {
221 "mpc",
222 NULL_IF_CONFIG_SMALL("Musepack"),
223 sizeof(MPCContext),
224 mpc_probe,
225 mpc_read_header,
226 mpc_read_packet,
227 mpc_read_close,
228 mpc_read_seek,
229 .extensions = "mpc",
230};
diff --git a/src/plugins/ffmpeg/libavformat/mpc8.c b/src/plugins/ffmpeg/libavformat/mpc8.c
deleted file mode 100644
index 6ede777..0000000
--- a/src/plugins/ffmpeg/libavformat/mpc8.c
+++ /dev/null
@@ -1,245 +0,0 @@
1/*
2 * Musepack SV8 demuxer
3 * Copyright (c) 2007 Konstantin Shishkov
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 "libavcodec/bitstream.h"
23#include "libavcodec/unary.h"
24#include "avformat.h"
25
26/// Two-byte MPC tag
27#define MKMPCTAG(a, b) (a | (b << 8))
28
29#define TAG_MPCK MKTAG('M','P','C','K')
30
31/// Reserved MPC tags
32enum MPCPacketTags{
33 TAG_STREAMHDR = MKMPCTAG('S','H'),
34 TAG_STREAMEND = MKMPCTAG('S','E'),
35
36 TAG_AUDIOPACKET = MKMPCTAG('A','P'),
37
38 TAG_SEEKTBLOFF = MKMPCTAG('S','O'),
39 TAG_SEEKTABLE = MKMPCTAG('S','T'),
40
41 TAG_REPLAYGAIN = MKMPCTAG('R','G'),
42 TAG_ENCINFO = MKMPCTAG('E','I'),
43};
44
45static const int mpc8_rate[8] = { 44100, 48000, 37800, 32000, -1, -1, -1, -1 };
46
47typedef struct {
48 int ver;
49 int frame;
50 int64_t header_pos;
51 int64_t samples;
52} MPCContext;
53
54static int mpc8_probe(AVProbeData *p)
55{
56 if (AV_RL32(p->buf) == TAG_MPCK)
57 return AVPROBE_SCORE_MAX;
58 return 0;
59}
60
61static inline int64_t gb_get_v(GetBitContext *gb)
62{
63 int64_t v = 0;
64 int bits = 0;
65 while(get_bits1(gb) && bits < 64-7){
66 v <<= 7;
67 v |= get_bits(gb, 7);
68 bits += 7;
69 }
70 v <<= 7;
71 v |= get_bits(gb, 7);
72
73 return v;
74}
75
76static void mpc8_get_chunk_header(ByteIOContext *pb, int *tag, int64_t *size)
77{
78 int64_t pos;
79 pos = url_ftell(pb);
80 *tag = get_le16(pb);
81 *size = ff_get_v(pb);
82 *size -= url_ftell(pb) - pos;
83}
84
85static void mpc8_parse_seektable(AVFormatContext *s, int64_t off)
86{
87 MPCContext *c = s->priv_data;
88 int tag;
89 int64_t size, pos, ppos[2];
90 uint8_t *buf;
91 int i, t, seekd;
92 GetBitContext gb;
93
94 url_fseek(s->pb, off, SEEK_SET);
95 mpc8_get_chunk_header(s->pb, &tag, &size);
96 if(tag != TAG_SEEKTABLE){
97 av_log(s, AV_LOG_ERROR, "No seek table at given position\n");
98 return;
99 }
100 if(!(buf = av_malloc(size)))
101 return;
102 get_buffer(s->pb, buf, size);
103 init_get_bits(&gb, buf, size * 8);
104 size = gb_get_v(&gb);
105 if(size > UINT_MAX/4 || size > c->samples/1152){
106 av_log(s, AV_LOG_ERROR, "Seek table is too big\n");
107 return;
108 }
109 seekd = get_bits(&gb, 4);
110 for(i = 0; i < 2; i++){
111 pos = gb_get_v(&gb) + c->header_pos;
112 ppos[1 - i] = pos;
113 av_add_index_entry(s->streams[0], pos, i, 0, 0, AVINDEX_KEYFRAME);
114 }
115 for(; i < size; i++){
116 t = get_unary(&gb, 1, 33) << 12;
117 t += get_bits(&gb, 12);
118 if(t & 1)
119 t = -(t & ~1);
120 pos = (t >> 1) + ppos[0]*2 - ppos[1];
121 av_add_index_entry(s->streams[0], pos, i << seekd, 0, 0, AVINDEX_KEYFRAME);
122 ppos[1] = ppos[0];
123 ppos[0] = pos;
124 }
125 av_free(buf);
126}
127
128static void mpc8_handle_chunk(AVFormatContext *s, int tag, int64_t chunk_pos, int64_t size)
129{
130 ByteIOContext *pb = s->pb;
131 int64_t pos, off;
132
133 switch(tag){
134 case TAG_SEEKTBLOFF:
135 pos = url_ftell(pb) + size;
136 off = ff_get_v(pb);
137 mpc8_parse_seektable(s, chunk_pos + off);
138 url_fseek(pb, pos, SEEK_SET);
139 break;
140 default:
141 url_fskip(pb, size);
142 }
143}
144
145static int mpc8_read_header(AVFormatContext *s, AVFormatParameters *ap)
146{
147 MPCContext *c = s->priv_data;
148 ByteIOContext *pb = s->pb;
149 AVStream *st;
150 int tag = 0;
151 int64_t size, pos;
152
153 c->header_pos = url_ftell(pb);
154 if(get_le32(pb) != TAG_MPCK){
155 av_log(s, AV_LOG_ERROR, "Not a Musepack8 file\n");
156 return -1;
157 }
158
159 while(!url_feof(pb)){
160 pos = url_ftell(pb);
161 mpc8_get_chunk_header(pb, &tag, &size);
162 if(tag == TAG_STREAMHDR)
163 break;
164 mpc8_handle_chunk(s, tag, pos, size);
165 }
166 if(tag != TAG_STREAMHDR){
167 av_log(s, AV_LOG_ERROR, "Stream header not found\n");
168 return -1;
169 }
170 pos = url_ftell(pb);
171 url_fskip(pb, 4); //CRC
172 c->ver = get_byte(pb);
173 if(c->ver != 8){
174 av_log(s, AV_LOG_ERROR, "Unknown stream version %d\n", c->ver);
175 return -1;
176 }
177 c->samples = ff_get_v(pb);
178 ff_get_v(pb); //silence samples at the beginning
179
180 st = av_new_stream(s, 0);
181 if (!st)
182 return AVERROR(ENOMEM);
183 st->codec->codec_type = CODEC_TYPE_AUDIO;
184 st->codec->codec_id = CODEC_ID_MUSEPACK8;
185 st->codec->bits_per_sample = 16;
186
187 st->codec->extradata_size = 2;
188 st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
189 get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
190
191 st->codec->channels = (st->codec->extradata[1] >> 4) + 1;
192 st->codec->sample_rate = mpc8_rate[st->codec->extradata[0] >> 5];
193 av_set_pts_info(st, 32, 1152 << (st->codec->extradata[1]&3)*2, st->codec->sample_rate);
194 st->duration = c->samples / (1152 << (st->codec->extradata[1]&3)*2);
195 size -= url_ftell(pb) - pos;
196
197 return 0;
198}
199
200static int mpc8_read_packet(AVFormatContext *s, AVPacket *pkt)
201{
202 MPCContext *c = s->priv_data;
203 int tag;
204 int64_t pos, size;
205
206 while(!url_feof(s->pb)){
207 pos = url_ftell(s->pb);
208 mpc8_get_chunk_header(s->pb, &tag, &size);
209 if(tag == TAG_AUDIOPACKET){
210 if(av_get_packet(s->pb, pkt, size) < 0)
211 return AVERROR(ENOMEM);
212 pkt->stream_index = 0;
213 pkt->pts = c->frame;
214 return 0;
215 }
216 if(tag == TAG_STREAMEND)
217 return AVERROR(EIO);
218 mpc8_handle_chunk(s, tag, pos, size);
219 }
220 return 0;
221}
222
223static int mpc8_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
224{
225 AVStream *st = s->streams[stream_index];
226 MPCContext *c = s->priv_data;
227 int index = av_index_search_timestamp(st, timestamp, flags);
228
229 if(index < 0) return -1;
230 url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
231 c->frame = st->index_entries[index].timestamp;
232 return 0;
233}
234
235
236AVInputFormat mpc8_demuxer = {
237 "mpc8",
238 NULL_IF_CONFIG_SMALL("Musepack SV8"),
239 sizeof(MPCContext),
240 mpc8_probe,
241 mpc8_read_header,
242 mpc8_read_packet,
243 NULL,
244 mpc8_read_seek,
245};
diff --git a/src/plugins/ffmpeg/libavformat/mpeg.c b/src/plugins/ffmpeg/libavformat/mpeg.c
deleted file mode 100644
index 78fceee..0000000
--- a/src/plugins/ffmpeg/libavformat/mpeg.c
+++ /dev/null
@@ -1,590 +0,0 @@
1/*
2 * MPEG1/2 demuxer
3 * Copyright (c) 2000, 2001, 2002 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 "avformat.h"
23#include "mpeg.h"
24
25//#define DEBUG_SEEK
26
27#undef NDEBUG
28#include <assert.h>
29
30/*********************************************/
31/* demux code */
32
33#define MAX_SYNC_SIZE 100000
34
35static int check_pes(uint8_t *p, uint8_t *end){
36 int pes1;
37 int pes2= (p[3] & 0xC0) == 0x80
38 && (p[4] & 0xC0) != 0x40
39 &&((p[4] & 0xC0) == 0x00 || (p[4]&0xC0)>>2 == (p[6]&0xF0));
40
41 for(p+=3; p<end && *p == 0xFF; p++);
42 if((*p&0xC0) == 0x40) p+=2;
43 if((*p&0xF0) == 0x20){
44 pes1= p[0]&p[2]&p[4]&1;
45 p+=5;
46 }else if((*p&0xF0) == 0x30){
47 pes1= p[0]&p[2]&p[4]&p[5]&p[7]&p[9]&1;
48 p+=10;
49 }else
50 pes1 = *p == 0x0F;
51
52 return pes1||pes2;
53}
54
55static int mpegps_probe(AVProbeData *p)
56{
57 uint32_t code= -1;
58 int sys=0, pspack=0, priv1=0, vid=0, audio=0, invalid=0;
59 int i;
60 int score=0;
61
62 for(i=0; i<p->buf_size; i++){
63 code = (code<<8) + p->buf[i];
64 if ((code & 0xffffff00) == 0x100) {
65 int pes= check_pes(p->buf+i, p->buf+p->buf_size);
66
67 if(code == SYSTEM_HEADER_START_CODE) sys++;
68 else if(code == PRIVATE_STREAM_1) priv1++;
69 else if(code == PACK_START_CODE) pspack++;
70 else if((code & 0xf0) == VIDEO_ID && pes) vid++;
71 else if((code & 0xe0) == AUDIO_ID && pes) audio++;
72
73 else if((code & 0xf0) == VIDEO_ID && !pes) invalid++;
74 else if((code & 0xe0) == AUDIO_ID && !pes) invalid++;
75 }
76 }
77
78 if(vid+audio > invalid) /* invalid VDR files nd short PES streams */
79 score= AVPROBE_SCORE_MAX/4;
80
81//av_log(NULL, AV_LOG_ERROR, "%d %d %d %d %d len:%d\n", sys, priv1, pspack,vid, audio, p->buf_size);
82 if(sys>invalid && sys*9 <= pspack*10)
83 return AVPROBE_SCORE_MAX/2+2; // +1 for .mpg
84 if(priv1 + vid + audio > invalid && (priv1+vid+audio)*9 <= pspack*10)
85 return AVPROBE_SCORE_MAX/2+2; // +1 for .mpg
86 if((!!vid ^ !!audio) && (audio+vid > 1) && !sys && !pspack && p->buf_size>2048) /* PES stream */
87 return AVPROBE_SCORE_MAX/2+2;
88
89 //02-Penguin.flac has sys:0 priv1:0 pspack:0 vid:0 audio:1
90 return score;
91}
92
93
94typedef struct MpegDemuxContext {
95 int32_t header_state;
96 unsigned char psm_es_type[256];
97 int sofdec;
98} MpegDemuxContext;
99
100static int mpegps_read_header(AVFormatContext *s,
101 AVFormatParameters *ap)
102{
103 MpegDemuxContext *m = s->priv_data;
104 const char *sofdec = "Sofdec";
105 int v, i = 0;
106
107 m->header_state = 0xff;
108 s->ctx_flags |= AVFMTCTX_NOHEADER;
109
110 m->sofdec = -1;
111 do {
112 v = get_byte(s->pb);
113 m->header_state = m->header_state << 8 | v;
114 m->sofdec++;
115 } while (v == sofdec[i] && i++ < 6);
116
117 /* no need to do more */
118 return 0;
119}
120
121static int64_t get_pts(ByteIOContext *pb, int c)
122{
123 uint8_t buf[5];
124
125 buf[0] = c<0 ? get_byte(pb) : c;
126 get_buffer(pb, buf+1, 4);
127
128 return ff_parse_pes_pts(buf);
129}
130
131static int find_next_start_code(ByteIOContext *pb, int *size_ptr,
132 int32_t *header_state)
133{
134 unsigned int state, v;
135 int val, n;
136
137 state = *header_state;
138 n = *size_ptr;
139 while (n > 0) {
140 if (url_feof(pb))
141 break;
142 v = get_byte(pb);
143 n--;
144 if (state == 0x000001) {
145 state = ((state << 8) | v) & 0xffffff;
146 val = state;
147 goto found;
148 }
149 state = ((state << 8) | v) & 0xffffff;
150 }
151 val = -1;
152 found:
153 *header_state = state;
154 *size_ptr = n;
155 return val;
156}
157
158#if 0 /* unused, remove? */
159/* XXX: optimize */
160static int find_prev_start_code(ByteIOContext *pb, int *size_ptr)
161{
162 int64_t pos, pos_start;
163 int max_size, start_code;
164
165 max_size = *size_ptr;
166 pos_start = url_ftell(pb);
167
168 /* in order to go faster, we fill the buffer */
169 pos = pos_start - 16386;
170 if (pos < 0)
171 pos = 0;
172 url_fseek(pb, pos, SEEK_SET);
173 get_byte(pb);
174
175 pos = pos_start;
176 for(;;) {
177 pos--;
178 if (pos < 0 || (pos_start - pos) >= max_size) {
179 start_code = -1;
180 goto the_end;
181 }
182 url_fseek(pb, pos, SEEK_SET);
183 start_code = get_be32(pb);
184 if ((start_code & 0xffffff00) == 0x100)
185 break;
186 }
187 the_end:
188 *size_ptr = pos_start - pos;
189 return start_code;
190}
191#endif
192
193/**
194 * Extracts stream types from a program stream map
195 * According to ISO/IEC 13818-1 ('MPEG-2 Systems') table 2-35
196 *
197 * @return number of bytes occupied by PSM in the bitstream
198 */
199static long mpegps_psm_parse(MpegDemuxContext *m, ByteIOContext *pb)
200{
201 int psm_length, ps_info_length, es_map_length;
202
203 psm_length = get_be16(pb);
204 get_byte(pb);
205 get_byte(pb);
206 ps_info_length = get_be16(pb);
207
208 /* skip program_stream_info */
209 url_fskip(pb, ps_info_length);
210 es_map_length = get_be16(pb);
211
212 /* at least one es available? */
213 while (es_map_length >= 4){
214 unsigned char type = get_byte(pb);
215 unsigned char es_id = get_byte(pb);
216 uint16_t es_info_length = get_be16(pb);
217 /* remember mapping from stream id to stream type */
218 m->psm_es_type[es_id] = type;
219 /* skip program_stream_info */
220 url_fskip(pb, es_info_length);
221 es_map_length -= 4 + es_info_length;
222 }
223 get_be32(pb); /* crc32 */
224 return 2 + psm_length;
225}
226
227/* read the next PES header. Return its position in ppos
228 (if not NULL), and its start code, pts and dts.
229 */
230static int mpegps_read_pes_header(AVFormatContext *s,
231 int64_t *ppos, int *pstart_code,
232 int64_t *ppts, int64_t *pdts)
233{
234 MpegDemuxContext *m = s->priv_data;
235 int len, size, startcode, c, flags, header_len;
236 int pes_ext, ext2_len, id_ext, skip;
237 int64_t pts, dts;
238 int64_t last_sync= url_ftell(s->pb);
239
240 error_redo:
241 url_fseek(s->pb, last_sync, SEEK_SET);
242 redo:
243 /* next start code (should be immediately after) */
244 m->header_state = 0xff;
245 size = MAX_SYNC_SIZE;
246 startcode = find_next_start_code(s->pb, &size, &m->header_state);
247 last_sync = url_ftell(s->pb);
248 //printf("startcode=%x pos=0x%"PRIx64"\n", startcode, url_ftell(s->pb));
249 if (startcode < 0)
250 return AVERROR(EIO);
251 if (startcode == PACK_START_CODE)
252 goto redo;
253 if (startcode == SYSTEM_HEADER_START_CODE)
254 goto redo;
255 if (startcode == PADDING_STREAM) {
256 url_fskip(s->pb, get_be16(s->pb));
257 goto redo;
258 }
259 if (startcode == PRIVATE_STREAM_2) {
260 len = get_be16(s->pb);
261 if (!m->sofdec) {
262 while (len-- >= 6) {
263 if (get_byte(s->pb) == 'S') {
264 uint8_t buf[5];
265 get_buffer(s->pb, buf, sizeof(buf));
266 m->sofdec = !memcmp(buf, "ofdec", 5);
267 len -= sizeof(buf);
268 break;
269 }
270 }
271 m->sofdec -= !m->sofdec;
272 }
273 url_fskip(s->pb, len);
274 goto redo;
275 }
276 if (startcode == PROGRAM_STREAM_MAP) {
277 mpegps_psm_parse(m, s->pb);
278 goto redo;
279 }
280
281 /* find matching stream */
282 if (!((startcode >= 0x1c0 && startcode <= 0x1df) ||
283 (startcode >= 0x1e0 && startcode <= 0x1ef) ||
284 (startcode == 0x1bd) || (startcode == 0x1fd)))
285 goto redo;
286 if (ppos) {
287 *ppos = url_ftell(s->pb) - 4;
288 }
289 len = get_be16(s->pb);
290 pts =
291 dts = AV_NOPTS_VALUE;
292 /* stuffing */
293 for(;;) {
294 if (len < 1)
295 goto error_redo;
296 c = get_byte(s->pb);
297 len--;
298 /* XXX: for mpeg1, should test only bit 7 */
299 if (c != 0xff)
300 break;
301 }
302 if ((c & 0xc0) == 0x40) {
303 /* buffer scale & size */
304 get_byte(s->pb);
305 c = get_byte(s->pb);
306 len -= 2;
307 }
308 if ((c & 0xe0) == 0x20) {
309 dts = pts = get_pts(s->pb, c);
310 len -= 4;
311 if (c & 0x10){
312 dts = get_pts(s->pb, -1);
313 len -= 5;
314 }
315 } else if ((c & 0xc0) == 0x80) {
316 /* mpeg 2 PES */
317#if 0 /* some streams have this field set for no apparent reason */
318 if ((c & 0x30) != 0) {
319 /* Encrypted multiplex not handled */
320 goto redo;
321 }
322#endif
323 flags = get_byte(s->pb);
324 header_len = get_byte(s->pb);
325 len -= 2;
326 if (header_len > len)
327 goto error_redo;
328 len -= header_len;
329 if (flags & 0x80) {
330 dts = pts = get_pts(s->pb, -1);
331 header_len -= 5;
332 if (flags & 0x40) {
333 dts = get_pts(s->pb, -1);
334 header_len -= 5;
335 }
336 }
337 if (flags & 0x3f && header_len == 0){
338 flags &= 0xC0;
339 av_log(s, AV_LOG_WARNING, "Further flags set but no bytes left\n");
340 }
341 if (flags & 0x01) { /* PES extension */
342 pes_ext = get_byte(s->pb);
343 header_len--;
344 /* Skip PES private data, program packet sequence counter and P-STD buffer */
345 skip = (pes_ext >> 4) & 0xb;
346 skip += skip & 0x9;
347 if (pes_ext & 0x40 || skip > header_len){
348 av_log(s, AV_LOG_WARNING, "pes_ext %X is invalid\n", pes_ext);
349 pes_ext=skip=0;
350 }
351 url_fskip(s->pb, skip);
352 header_len -= skip;
353
354 if (pes_ext & 0x01) { /* PES extension 2 */
355 ext2_len = get_byte(s->pb);
356 header_len--;
357 if ((ext2_len & 0x7f) > 0) {
358 id_ext = get_byte(s->pb);
359 if ((id_ext & 0x80) == 0)
360 startcode = ((startcode & 0xff) << 8) | id_ext;
361 header_len--;
362 }
363 }
364 }
365 if(header_len < 0)
366 goto error_redo;
367 url_fskip(s->pb, header_len);
368 }
369 else if( c!= 0xf )
370 goto redo;
371
372 if (startcode == PRIVATE_STREAM_1 && !m->psm_es_type[startcode & 0xff]) {
373 startcode = get_byte(s->pb);
374 len--;
375 if (startcode >= 0x80 && startcode <= 0xcf) {
376 /* audio: skip header */
377 get_byte(s->pb);
378 get_byte(s->pb);
379 get_byte(s->pb);
380 len -= 3;
381 if (startcode >= 0xb0 && startcode <= 0xbf) {
382 /* MLP/TrueHD audio has a 4-byte header */
383 get_byte(s->pb);
384 len--;
385 }
386 }
387 }
388 if(len<0)
389 goto error_redo;
390 if(dts != AV_NOPTS_VALUE && ppos){
391 int i;
392 for(i=0; i<s->nb_streams; i++){
393 if(startcode == s->streams[i]->id &&
394 !url_is_streamed(s->pb) /* index useless on streams anyway */) {
395 ff_reduce_index(s, i);
396 av_add_index_entry(s->streams[i], *ppos, dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
397 }
398 }
399 }
400
401 *pstart_code = startcode;
402 *ppts = pts;
403 *pdts = dts;
404 return len;
405}
406
407static int mpegps_read_packet(AVFormatContext *s,
408 AVPacket *pkt)
409{
410 MpegDemuxContext *m = s->priv_data;
411 AVStream *st;
412 int len, startcode, i, type, codec_id = 0, es_type;
413 int64_t pts, dts, dummy_pos; //dummy_pos is needed for the index building to work
414
415 redo:
416 len = mpegps_read_pes_header(s, &dummy_pos, &startcode, &pts, &dts);
417 if (len < 0)
418 return len;
419
420 /* now find stream */
421 for(i=0;i<s->nb_streams;i++) {
422 st = s->streams[i];
423 if (st->id == startcode)
424 goto found;
425 }
426
427 es_type = m->psm_es_type[startcode & 0xff];
428 if(es_type > 0){
429 if(es_type == STREAM_TYPE_VIDEO_MPEG1){
430 codec_id = CODEC_ID_MPEG2VIDEO;
431 type = CODEC_TYPE_VIDEO;
432 } else if(es_type == STREAM_TYPE_VIDEO_MPEG2){
433 codec_id = CODEC_ID_MPEG2VIDEO;
434 type = CODEC_TYPE_VIDEO;
435 } else if(es_type == STREAM_TYPE_AUDIO_MPEG1 ||
436 es_type == STREAM_TYPE_AUDIO_MPEG2){
437 codec_id = CODEC_ID_MP3;
438 type = CODEC_TYPE_AUDIO;
439 } else if(es_type == STREAM_TYPE_AUDIO_AAC){
440 codec_id = CODEC_ID_AAC;
441 type = CODEC_TYPE_AUDIO;
442 } else if(es_type == STREAM_TYPE_VIDEO_MPEG4){
443 codec_id = CODEC_ID_MPEG4;
444 type = CODEC_TYPE_VIDEO;
445 } else if(es_type == STREAM_TYPE_VIDEO_H264){
446 codec_id = CODEC_ID_H264;
447 type = CODEC_TYPE_VIDEO;
448 } else if(es_type == STREAM_TYPE_AUDIO_AC3){
449 codec_id = CODEC_ID_AC3;
450 type = CODEC_TYPE_AUDIO;
451 } else {
452 goto skip;
453 }
454 } else if (startcode >= 0x1e0 && startcode <= 0x1ef) {
455 static const unsigned char avs_seqh[4] = { 0, 0, 1, 0xb0 };
456 unsigned char buf[8];
457 get_buffer(s->pb, buf, 8);
458 url_fseek(s->pb, -8, SEEK_CUR);
459 if(!memcmp(buf, avs_seqh, 4) && (buf[6] != 0 || buf[7] != 1))
460 codec_id = CODEC_ID_CAVS;
461 else
462 codec_id = CODEC_ID_PROBE;
463 type = CODEC_TYPE_VIDEO;
464 } else if (startcode >= 0x1c0 && startcode <= 0x1df) {
465 type = CODEC_TYPE_AUDIO;
466 codec_id = m->sofdec > 0 ? CODEC_ID_ADPCM_ADX : CODEC_ID_MP2;
467 } else if (startcode >= 0x80 && startcode <= 0x87) {
468 type = CODEC_TYPE_AUDIO;
469 codec_id = CODEC_ID_AC3;
470 } else if ((startcode >= 0x88 && startcode <= 0x8f)
471 ||( startcode >= 0x98 && startcode <= 0x9f)) {
472 /* 0x90 - 0x97 is reserved for SDDS in DVD specs */
473 type = CODEC_TYPE_AUDIO;
474 codec_id = CODEC_ID_DTS;
475 } else if (startcode >= 0xa0 && startcode <= 0xaf) {
476 type = CODEC_TYPE_AUDIO;
477 /* 16 bit form will be handled as CODEC_ID_PCM_S16BE */
478 codec_id = CODEC_ID_PCM_DVD;
479 } else if (startcode >= 0xb0 && startcode <= 0xbf) {
480 type = CODEC_TYPE_AUDIO;
481 codec_id = CODEC_ID_MLP;
482 } else if (startcode >= 0xc0 && startcode <= 0xcf) {
483 /* Used for both AC-3 and E-AC-3 in EVOB files */
484 type = CODEC_TYPE_AUDIO;
485 codec_id = CODEC_ID_AC3;
486 } else if (startcode >= 0x20 && startcode <= 0x3f) {
487 type = CODEC_TYPE_SUBTITLE;
488 codec_id = CODEC_ID_DVD_SUBTITLE;
489 } else if (startcode >= 0xfd55 && startcode <= 0xfd5f) {
490 type = CODEC_TYPE_VIDEO;
491 codec_id = CODEC_ID_VC1;
492 } else {
493 skip:
494 /* skip packet */
495 url_fskip(s->pb, len);
496 goto redo;
497 }
498 /* no stream found: add a new stream */
499 st = av_new_stream(s, startcode);
500 if (!st)
501 goto skip;
502 st->codec->codec_type = type;
503 st->codec->codec_id = codec_id;
504 if (codec_id != CODEC_ID_PCM_S16BE)
505 st->need_parsing = AVSTREAM_PARSE_FULL;
506 found:
507 if(st->discard >= AVDISCARD_ALL)
508 goto skip;
509 if (startcode >= 0xa0 && startcode <= 0xaf) {
510 int b1, freq;
511
512 /* for LPCM, we just skip the header and consider it is raw
513 audio data */
514 if (len <= 3)
515 goto skip;
516 get_byte(s->pb); /* emphasis (1), muse(1), reserved(1), frame number(5) */
517 b1 = get_byte(s->pb); /* quant (2), freq(2), reserved(1), channels(3) */
518 get_byte(s->pb); /* dynamic range control (0x80 = off) */
519 len -= 3;
520 freq = (b1 >> 4) & 3;
521 st->codec->sample_rate = lpcm_freq_tab[freq];
522 st->codec->channels = 1 + (b1 & 7);
523 st->codec->bits_per_sample = 16 + ((b1 >> 6) & 3) * 4;
524 st->codec->bit_rate = st->codec->channels *
525 st->codec->sample_rate *
526 st->codec->bits_per_sample;
527 if (st->codec->bits_per_sample == 16)
528 st->codec->codec_id = CODEC_ID_PCM_S16BE;
529 else if (st->codec->bits_per_sample == 28)
530 return AVERROR(EINVAL);
531 }
532 av_new_packet(pkt, len);
533 get_buffer(s->pb, pkt->data, pkt->size);
534 pkt->pts = pts;
535 pkt->dts = dts;
536 pkt->stream_index = st->index;
537#if 0
538 av_log(s, AV_LOG_DEBUG, "%d: pts=%0.3f dts=%0.3f size=%d\n",
539 pkt->stream_index, pkt->pts / 90000.0, pkt->dts / 90000.0, pkt->size);
540#endif
541
542 return 0;
543}
544
545static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index,
546 int64_t *ppos, int64_t pos_limit)
547{
548 int len, startcode;
549 int64_t pos, pts, dts;
550
551 pos = *ppos;
552#ifdef DEBUG_SEEK
553 printf("read_dts: pos=0x%"PRIx64" next=%d -> ", pos, find_next);
554#endif
555 if (url_fseek(s->pb, pos, SEEK_SET) < 0)
556 return AV_NOPTS_VALUE;
557
558 for(;;) {
559 len = mpegps_read_pes_header(s, &pos, &startcode, &pts, &dts);
560 if (len < 0) {
561#ifdef DEBUG_SEEK
562 printf("none (ret=%d)\n", len);
563#endif
564 return AV_NOPTS_VALUE;
565 }
566 if (startcode == s->streams[stream_index]->id &&
567 dts != AV_NOPTS_VALUE) {
568 break;
569 }
570 url_fskip(s->pb, len);
571 }
572#ifdef DEBUG_SEEK
573 printf("pos=0x%"PRIx64" dts=0x%"PRIx64" %0.3f\n", pos, dts, dts / 90000.0);
574#endif
575 *ppos = pos;
576 return dts;
577}
578
579AVInputFormat mpegps_demuxer = {
580 "mpeg",
581 NULL_IF_CONFIG_SMALL("MPEG-PS format"),
582 sizeof(MpegDemuxContext),
583 mpegps_probe,
584 mpegps_read_header,
585 mpegps_read_packet,
586 NULL,
587 NULL, //mpegps_read_seek,
588 mpegps_read_dts,
589 .flags = AVFMT_SHOW_IDS,
590};
diff --git a/src/plugins/ffmpeg/libavformat/mpeg.h b/src/plugins/ffmpeg/libavformat/mpeg.h
deleted file mode 100644
index c1675ee..0000000
--- a/src/plugins/ffmpeg/libavformat/mpeg.h
+++ /dev/null
@@ -1,72 +0,0 @@
1/*
2 * MPEG1/2 muxer and demuxer common defines
3 * Copyright (c) 2000, 2001, 2002 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#ifndef FFMPEG_MPEG_H
23#define FFMPEG_MPEG_H
24
25#include <stdint.h>
26#include "libavutil/intreadwrite.h"
27
28#define PACK_START_CODE ((unsigned int)0x000001ba)
29#define SYSTEM_HEADER_START_CODE ((unsigned int)0x000001bb)
30#define SEQUENCE_END_CODE ((unsigned int)0x000001b7)
31#define PACKET_START_CODE_MASK ((unsigned int)0xffffff00)
32#define PACKET_START_CODE_PREFIX ((unsigned int)0x00000100)
33#define ISO_11172_END_CODE ((unsigned int)0x000001b9)
34
35/* mpeg2 */
36#define PROGRAM_STREAM_MAP 0x1bc
37#define PRIVATE_STREAM_1 0x1bd
38#define PADDING_STREAM 0x1be
39#define PRIVATE_STREAM_2 0x1bf
40
41#define AUDIO_ID 0xc0
42#define VIDEO_ID 0xe0
43#define AC3_ID 0x80
44#define DTS_ID 0x8a
45#define LPCM_ID 0xa0
46#define SUB_ID 0x20
47
48#define STREAM_TYPE_VIDEO_MPEG1 0x01
49#define STREAM_TYPE_VIDEO_MPEG2 0x02
50#define STREAM_TYPE_AUDIO_MPEG1 0x03
51#define STREAM_TYPE_AUDIO_MPEG2 0x04
52#define STREAM_TYPE_PRIVATE_SECTION 0x05
53#define STREAM_TYPE_PRIVATE_DATA 0x06
54#define STREAM_TYPE_AUDIO_AAC 0x0f
55#define STREAM_TYPE_VIDEO_MPEG4 0x10
56#define STREAM_TYPE_VIDEO_H264 0x1b
57
58#define STREAM_TYPE_AUDIO_AC3 0x81
59#define STREAM_TYPE_AUDIO_DTS 0x8a
60
61static const int lpcm_freq_tab[4] = { 48000, 96000, 44100, 32000 };
62
63/**
64 * Parse MPEG-PES five-byte timestamp
65 */
66static inline int64_t ff_parse_pes_pts(uint8_t *buf) {
67 return (int64_t)(*buf & 0x0e) << 29 |
68 (AV_RB16(buf+1) >> 1) << 15 |
69 AV_RB16(buf+3) >> 1;
70}
71
72#endif /* FFMPEG_MPEG_H */
diff --git a/src/plugins/ffmpeg/libavformat/mpegenc.c b/src/plugins/ffmpeg/libavformat/mpegenc.c
deleted file mode 100644
index 1606edc..0000000
--- a/src/plugins/ffmpeg/libavformat/mpegenc.c
+++ /dev/null
@@ -1,1294 +0,0 @@
1/*
2 * MPEG1/2 muxer
3 * Copyright (c) 2000, 2001, 2002 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/fifo.h"
23#include "libavcodec/bitstream.h"
24#include "avformat.h"
25#include "mpeg.h"
26
27#define MAX_PAYLOAD_SIZE 4096
28//#define DEBUG_SEEK
29
30#undef NDEBUG
31#include <assert.h>
32
33typedef struct PacketDesc {
34 int64_t pts;
35 int64_t dts;
36 int size;
37 int unwritten_size;
38 int flags;
39 struct PacketDesc *next;
40} PacketDesc;
41
42typedef struct {
43 AVFifoBuffer fifo;
44 uint8_t id;
45 int max_buffer_size; /* in bytes */
46 int buffer_index;
47 PacketDesc *predecode_packet;
48 PacketDesc *premux_packet;
49 PacketDesc **next_packet;
50 int packet_number;
51 uint8_t lpcm_header[3];
52 int lpcm_align;
53 int bytes_to_iframe;
54 int align_iframe;
55 int64_t vobu_start_pts;
56} StreamInfo;
57
58typedef struct {
59 int packet_size; /* required packet size */
60 int packet_number;
61 int pack_header_freq; /* frequency (in packets^-1) at which we send pack headers */
62 int system_header_freq;
63 int system_header_size;
64 int mux_rate; /* bitrate in units of 50 bytes/s */
65 /* stream info */
66 int audio_bound;
67 int video_bound;
68 int is_mpeg2;
69 int is_vcd;
70 int is_svcd;
71 int is_dvd;
72 int64_t last_scr; /* current system clock */
73
74 double vcd_padding_bitrate; //FIXME floats
75 int64_t vcd_padding_bytes_written;
76
77} MpegMuxContext;
78
79extern AVOutputFormat mpeg1vcd_muxer;
80extern AVOutputFormat mpeg2dvd_muxer;
81extern AVOutputFormat mpeg2svcd_muxer;
82extern AVOutputFormat mpeg2vob_muxer;
83
84static int put_pack_header(AVFormatContext *ctx,
85 uint8_t *buf, int64_t timestamp)
86{
87 MpegMuxContext *s = ctx->priv_data;
88 PutBitContext pb;
89
90 init_put_bits(&pb, buf, 128);
91
92 put_bits(&pb, 32, PACK_START_CODE);
93 if (s->is_mpeg2) {
94 put_bits(&pb, 2, 0x1);
95 } else {
96 put_bits(&pb, 4, 0x2);
97 }
98 put_bits(&pb, 3, (uint32_t)((timestamp >> 30) & 0x07));
99 put_bits(&pb, 1, 1);
100 put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff));
101 put_bits(&pb, 1, 1);
102 put_bits(&pb, 15, (uint32_t)((timestamp) & 0x7fff));
103 put_bits(&pb, 1, 1);
104 if (s->is_mpeg2) {
105 /* clock extension */
106 put_bits(&pb, 9, 0);
107 }
108 put_bits(&pb, 1, 1);
109 put_bits(&pb, 22, s->mux_rate);
110 put_bits(&pb, 1, 1);
111 if (s->is_mpeg2) {
112 put_bits(&pb, 1, 1);
113 put_bits(&pb, 5, 0x1f); /* reserved */
114 put_bits(&pb, 3, 0); /* stuffing length */
115 }
116 flush_put_bits(&pb);
117 return pbBufPtr(&pb) - pb.buf;
118}
119
120static int put_system_header(AVFormatContext *ctx, uint8_t *buf,int only_for_stream_id)
121{
122 MpegMuxContext *s = ctx->priv_data;
123 int size, i, private_stream_coded, id;
124 PutBitContext pb;
125
126 init_put_bits(&pb, buf, 128);
127
128 put_bits(&pb, 32, SYSTEM_HEADER_START_CODE);
129 put_bits(&pb, 16, 0);
130 put_bits(&pb, 1, 1);
131
132 put_bits(&pb, 22, s->mux_rate); /* maximum bit rate of the multiplexed stream */
133 put_bits(&pb, 1, 1); /* marker */
134 if (s->is_vcd && only_for_stream_id==VIDEO_ID) {
135 /* This header applies only to the video stream (see VCD standard p. IV-7)*/
136 put_bits(&pb, 6, 0);
137 } else
138 put_bits(&pb, 6, s->audio_bound);
139
140 if (s->is_vcd) {
141 /* see VCD standard, p. IV-7*/
142 put_bits(&pb, 1, 0);
143 put_bits(&pb, 1, 1);
144 } else {
145 put_bits(&pb, 1, 0); /* variable bitrate*/
146 put_bits(&pb, 1, 0); /* non constrainted bit stream */
147 }
148
149 if (s->is_vcd || s->is_dvd) {
150 /* see VCD standard p IV-7 */
151 put_bits(&pb, 1, 1); /* audio locked */
152 put_bits(&pb, 1, 1); /* video locked */
153 } else {
154 put_bits(&pb, 1, 0); /* audio locked */
155 put_bits(&pb, 1, 0); /* video locked */
156 }
157
158 put_bits(&pb, 1, 1); /* marker */
159
160 if (s->is_vcd && only_for_stream_id==AUDIO_ID) {
161 /* This header applies only to the audio stream (see VCD standard p. IV-7)*/
162 put_bits(&pb, 5, 0);
163 } else
164 put_bits(&pb, 5, s->video_bound);
165
166 if (s->is_dvd) {
167 put_bits(&pb, 1, 0); /* packet_rate_restriction_flag */
168 put_bits(&pb, 7, 0x7f); /* reserved byte */
169 } else
170 put_bits(&pb, 8, 0xff); /* reserved byte */
171
172 /* DVD-Video Stream_bound entries
173 id (0xB9) video, maximum P-STD for stream 0xE0. (P-STD_buffer_bound_scale = 1)
174 id (0xB8) audio, maximum P-STD for any MPEG audio (0xC0 to 0xC7) streams. If there are none set to 4096 (32x128). (P-STD_buffer_bound_scale = 0)
175 id (0xBD) private stream 1 (audio other than MPEG and subpictures). (P-STD_buffer_bound_scale = 1)
176 id (0xBF) private stream 2, NAV packs, set to 2x1024. */
177 if (s->is_dvd) {
178
179 int P_STD_max_video = 0;
180 int P_STD_max_mpeg_audio = 0;
181 int P_STD_max_mpeg_PS1 = 0;
182
183 for(i=0;i<ctx->nb_streams;i++) {
184 StreamInfo *stream = ctx->streams[i]->priv_data;
185
186 id = stream->id;
187 if (id == 0xbd && stream->max_buffer_size > P_STD_max_mpeg_PS1) {
188 P_STD_max_mpeg_PS1 = stream->max_buffer_size;
189 } else if (id >= 0xc0 && id <= 0xc7 && stream->max_buffer_size > P_STD_max_mpeg_audio) {
190 P_STD_max_mpeg_audio = stream->max_buffer_size;
191 } else if (id == 0xe0 && stream->max_buffer_size > P_STD_max_video) {
192 P_STD_max_video = stream->max_buffer_size;
193 }
194 }
195
196 /* video */
197 put_bits(&pb, 8, 0xb9); /* stream ID */
198 put_bits(&pb, 2, 3);
199 put_bits(&pb, 1, 1);
200 put_bits(&pb, 13, P_STD_max_video / 1024);
201
202 /* audio */
203 if (P_STD_max_mpeg_audio == 0)
204 P_STD_max_mpeg_audio = 4096;
205 put_bits(&pb, 8, 0xb8); /* stream ID */
206 put_bits(&pb, 2, 3);
207 put_bits(&pb, 1, 0);
208 put_bits(&pb, 13, P_STD_max_mpeg_audio / 128);
209
210 /* private stream 1 */
211 put_bits(&pb, 8, 0xbd); /* stream ID */
212 put_bits(&pb, 2, 3);
213 put_bits(&pb, 1, 0);
214 put_bits(&pb, 13, P_STD_max_mpeg_PS1 / 128);
215
216 /* private stream 2 */
217 put_bits(&pb, 8, 0xbf); /* stream ID */
218 put_bits(&pb, 2, 3);
219 put_bits(&pb, 1, 1);
220 put_bits(&pb, 13, 2);
221 }
222 else {
223 /* audio stream info */
224 private_stream_coded = 0;
225 for(i=0;i<ctx->nb_streams;i++) {
226 StreamInfo *stream = ctx->streams[i]->priv_data;
227
228
229 /* For VCDs, only include the stream info for the stream
230 that the pack which contains this system belongs to.
231 (see VCD standard p. IV-7) */
232 if ( !s->is_vcd || stream->id==only_for_stream_id
233 || only_for_stream_id==0) {
234
235 id = stream->id;
236 if (id < 0xc0) {
237 /* special case for private streams (AC3 use that) */
238 if (private_stream_coded)
239 continue;
240 private_stream_coded = 1;
241 id = 0xbd;
242 }
243 put_bits(&pb, 8, id); /* stream ID */
244 put_bits(&pb, 2, 3);
245 if (id < 0xe0) {
246 /* audio */
247 put_bits(&pb, 1, 0);
248 put_bits(&pb, 13, stream->max_buffer_size / 128);
249 } else {
250 /* video */
251 put_bits(&pb, 1, 1);
252 put_bits(&pb, 13, stream->max_buffer_size / 1024);
253 }
254 }
255 }
256 }
257
258 flush_put_bits(&pb);
259 size = pbBufPtr(&pb) - pb.buf;
260 /* patch packet size */
261 buf[4] = (size - 6) >> 8;
262 buf[5] = (size - 6) & 0xff;
263
264 return size;
265}
266
267static int get_system_header_size(AVFormatContext *ctx)
268{
269 int buf_index, i, private_stream_coded;
270 StreamInfo *stream;
271 MpegMuxContext *s = ctx->priv_data;
272
273 if (s->is_dvd)
274 return 18; // DVD-Video system headers are 18 bytes fixed length.
275
276 buf_index = 12;
277 private_stream_coded = 0;
278 for(i=0;i<ctx->nb_streams;i++) {
279 stream = ctx->streams[i]->priv_data;
280 if (stream->id < 0xc0) {
281 if (private_stream_coded)
282 continue;
283 private_stream_coded = 1;
284 }
285 buf_index += 3;
286 }
287 return buf_index;
288}
289
290static int mpeg_mux_init(AVFormatContext *ctx)
291{
292 MpegMuxContext *s = ctx->priv_data;
293 int bitrate, i, mpa_id, mpv_id, mps_id, ac3_id, dts_id, lpcm_id, j;
294 AVStream *st;
295 StreamInfo *stream;
296 int audio_bitrate;
297 int video_bitrate;
298
299 s->packet_number = 0;
300 s->is_vcd = (ENABLE_MPEG1VCD_MUXER && ctx->oformat == &mpeg1vcd_muxer);
301 s->is_svcd = (ENABLE_MPEG2SVCD_MUXER && ctx->oformat == &mpeg2svcd_muxer);
302 s->is_mpeg2 = ((ENABLE_MPEG2VOB_MUXER && ctx->oformat == &mpeg2vob_muxer) ||
303 (ENABLE_MPEG2DVD_MUXER && ctx->oformat == &mpeg2dvd_muxer) ||
304 (ENABLE_MPEG2SVCD_MUXER && ctx->oformat == &mpeg2svcd_muxer));
305 s->is_dvd = (ENABLE_MPEG2DVD_MUXER && ctx->oformat == &mpeg2dvd_muxer);
306
307 if(ctx->packet_size)
308 s->packet_size = ctx->packet_size;
309 else
310 s->packet_size = 2048;
311
312 s->vcd_padding_bytes_written = 0;
313 s->vcd_padding_bitrate=0;
314
315 s->audio_bound = 0;
316 s->video_bound = 0;
317 mpa_id = AUDIO_ID;
318 ac3_id = AC3_ID;
319 dts_id = DTS_ID;
320 mpv_id = VIDEO_ID;
321 mps_id = SUB_ID;
322 lpcm_id = LPCM_ID;
323 for(i=0;i<ctx->nb_streams;i++) {
324 st = ctx->streams[i];
325 stream = av_mallocz(sizeof(StreamInfo));
326 if (!stream)
327 goto fail;
328 st->priv_data = stream;
329
330 av_set_pts_info(st, 64, 1, 90000);
331
332 switch(st->codec->codec_type) {
333 case CODEC_TYPE_AUDIO:
334 if (st->codec->codec_id == CODEC_ID_AC3) {
335 stream->id = ac3_id++;
336 } else if (st->codec->codec_id == CODEC_ID_DTS) {
337 stream->id = dts_id++;
338 } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
339 stream->id = lpcm_id++;
340 for(j = 0; j < 4; j++) {
341 if (lpcm_freq_tab[j] == st->codec->sample_rate)
342 break;
343 }
344 if (j == 4)
345 goto fail;
346 if (st->codec->channels > 8)
347 return -1;
348 stream->lpcm_header[0] = 0x0c;
349 stream->lpcm_header[1] = (st->codec->channels - 1) | (j << 4);
350 stream->lpcm_header[2] = 0x80;
351 stream->lpcm_align = st->codec->channels * 2;
352 } else {
353 stream->id = mpa_id++;
354 }
355
356 /* This value HAS to be used for VCD (see VCD standard, p. IV-7).
357 Right now it is also used for everything else.*/
358 stream->max_buffer_size = 4 * 1024;
359 s->audio_bound++;
360 break;
361 case CODEC_TYPE_VIDEO:
362 stream->id = mpv_id++;
363 if (st->codec->rc_buffer_size)
364 stream->max_buffer_size = 6*1024 + st->codec->rc_buffer_size/8;
365 else
366 stream->max_buffer_size = 230*1024; //FIXME this is probably too small as default
367#if 0
368 /* see VCD standard, p. IV-7*/
369 stream->max_buffer_size = 46 * 1024;
370 else
371 /* This value HAS to be used for SVCD (see SVCD standard, p. 26 V.2.3.2).
372 Right now it is also used for everything else.*/
373 stream->max_buffer_size = 230 * 1024;
374#endif
375 s->video_bound++;
376 break;
377 case CODEC_TYPE_SUBTITLE:
378 stream->id = mps_id++;
379 stream->max_buffer_size = 16 * 1024;
380 break;
381 default:
382 return -1;
383 }
384 av_fifo_init(&stream->fifo, 16);
385 }
386 bitrate = 0;
387 audio_bitrate = 0;
388 video_bitrate = 0;
389 for(i=0;i<ctx->nb_streams;i++) {
390 int codec_rate;
391 st = ctx->streams[i];
392 stream = (StreamInfo*) st->priv_data;
393
394 if(st->codec->rc_max_rate || stream->id==VIDEO_ID)
395 codec_rate= st->codec->rc_max_rate;
396 else
397 codec_rate= st->codec->bit_rate;
398
399 if(!codec_rate)
400 codec_rate= (1<<21)*8*50/ctx->nb_streams;
401
402 bitrate += codec_rate;
403
404 if (stream->id==AUDIO_ID)
405 audio_bitrate += codec_rate;
406 else if (stream->id==VIDEO_ID)
407 video_bitrate += codec_rate;
408 }
409
410 if(ctx->mux_rate){
411 s->mux_rate= (ctx->mux_rate + (8 * 50) - 1) / (8 * 50);
412 } else {
413 /* we increase slightly the bitrate to take into account the
414 headers. XXX: compute it exactly */
415 bitrate += bitrate*5/100;
416 bitrate += 10000;
417 s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);
418 }
419
420 if (s->is_vcd) {
421 double overhead_rate;
422
423 /* The VCD standard mandates that the mux_rate field is 3528
424 (see standard p. IV-6).
425 The value is actually "wrong", i.e. if you calculate
426 it using the normal formula and the 75 sectors per second transfer
427 rate you get a different value because the real pack size is 2324,
428 not 2352. But the standard explicitly specifies that the mux_rate
429 field in the header must have this value.*/
430// s->mux_rate=2352 * 75 / 50; /* = 3528*/
431
432 /* The VCD standard states that the muxed stream must be
433 exactly 75 packs / second (the data rate of a single speed cdrom).
434 Since the video bitrate (probably 1150000 bits/sec) will be below
435 the theoretical maximum we have to add some padding packets
436 to make up for the lower data rate.
437 (cf. VCD standard p. IV-6 )*/
438
439 /* Add the header overhead to the data rate.
440 2279 data bytes per audio pack, 2294 data bytes per video pack*/
441 overhead_rate = ((audio_bitrate / 8.0) / 2279) * (2324 - 2279);
442 overhead_rate += ((video_bitrate / 8.0) / 2294) * (2324 - 2294);
443 overhead_rate *= 8;
444
445 /* Add padding so that the full bitrate is 2324*75 bytes/sec */
446 s->vcd_padding_bitrate = 2324 * 75 * 8 - (bitrate + overhead_rate);
447 }
448
449 if (s->is_vcd || s->is_mpeg2)
450 /* every packet */
451 s->pack_header_freq = 1;
452 else
453 /* every 2 seconds */
454 s->pack_header_freq = 2 * bitrate / s->packet_size / 8;
455
456 /* the above seems to make pack_header_freq zero sometimes */
457 if (s->pack_header_freq == 0)
458 s->pack_header_freq = 1;
459
460 if (s->is_mpeg2)
461 /* every 200 packets. Need to look at the spec. */
462 s->system_header_freq = s->pack_header_freq * 40;
463 else if (s->is_vcd)
464 /* the standard mandates that there are only two system headers
465 in the whole file: one in the first packet of each stream.
466 (see standard p. IV-7 and IV-8) */
467 s->system_header_freq = 0x7fffffff;
468 else
469 s->system_header_freq = s->pack_header_freq * 5;
470
471 for(i=0;i<ctx->nb_streams;i++) {
472 stream = ctx->streams[i]->priv_data;
473 stream->packet_number = 0;
474 }
475 s->system_header_size = get_system_header_size(ctx);
476 s->last_scr = 0;
477 return 0;
478 fail:
479 for(i=0;i<ctx->nb_streams;i++) {
480 av_free(ctx->streams[i]->priv_data);
481 }
482 return AVERROR(ENOMEM);
483}
484
485static inline void put_timestamp(ByteIOContext *pb, int id, int64_t timestamp)
486{
487 put_byte(pb,
488 (id << 4) |
489 (((timestamp >> 30) & 0x07) << 1) |
490 1);
491 put_be16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
492 put_be16(pb, (uint16_t)((((timestamp) & 0x7fff) << 1) | 1));
493}
494
495
496/* return the number of padding bytes that should be inserted into
497 the multiplexed stream.*/
498static int get_vcd_padding_size(AVFormatContext *ctx, int64_t pts)
499{
500 MpegMuxContext *s = ctx->priv_data;
501 int pad_bytes = 0;
502
503 if (s->vcd_padding_bitrate > 0 && pts!=AV_NOPTS_VALUE)
504 {
505 int64_t full_pad_bytes;
506
507 full_pad_bytes = (int64_t)((s->vcd_padding_bitrate * (pts / 90000.0)) / 8.0); //FIXME this is wrong
508 pad_bytes = (int) (full_pad_bytes - s->vcd_padding_bytes_written);
509
510 if (pad_bytes<0)
511 /* might happen if we have already padded to a later timestamp. This
512 can occur if another stream has already advanced further.*/
513 pad_bytes=0;
514 }
515
516 return pad_bytes;
517}
518
519
520#if 0 /* unused, remove? */
521/* return the exact available payload size for the next packet for
522 stream 'stream_index'. 'pts' and 'dts' are only used to know if
523 timestamps are needed in the packet header. */
524static int get_packet_payload_size(AVFormatContext *ctx, int stream_index,
525 int64_t pts, int64_t dts)
526{
527 MpegMuxContext *s = ctx->priv_data;
528 int buf_index;
529 StreamInfo *stream;
530
531 stream = ctx->streams[stream_index]->priv_data;
532
533 buf_index = 0;
534 if (((s->packet_number % s->pack_header_freq) == 0)) {
535 /* pack header size */
536 if (s->is_mpeg2)
537 buf_index += 14;
538 else
539 buf_index += 12;
540
541 if (s->is_vcd) {
542 /* there is exactly one system header for each stream in a VCD MPEG,
543 One in the very first video packet and one in the very first
544 audio packet (see VCD standard p. IV-7 and IV-8).*/
545
546 if (stream->packet_number==0)
547 /* The system headers refer only to the stream they occur in,
548 so they have a constant size.*/
549 buf_index += 15;
550
551 } else {
552 if ((s->packet_number % s->system_header_freq) == 0)
553 buf_index += s->system_header_size;
554 }
555 }
556
557 if ((s->is_vcd && stream->packet_number==0)
558 || (s->is_svcd && s->packet_number==0))
559 /* the first pack of each stream contains only the pack header,
560 the system header and some padding (see VCD standard p. IV-6)
561 Add the padding size, so that the actual payload becomes 0.*/
562 buf_index += s->packet_size - buf_index;
563 else {
564 /* packet header size */
565 buf_index += 6;
566 if (s->is_mpeg2) {
567 buf_index += 3;
568 if (stream->packet_number==0)
569 buf_index += 3; /* PES extension */
570 buf_index += 1; /* obligatory stuffing byte */
571 }
572 if (pts != AV_NOPTS_VALUE) {
573 if (dts != pts)
574 buf_index += 5 + 5;
575 else
576 buf_index += 5;
577
578 } else {
579 if (!s->is_mpeg2)
580 buf_index++;
581 }
582
583 if (stream->id < 0xc0) {
584 /* AC3/LPCM private data header */
585 buf_index += 4;
586 if (stream->id >= 0xa0) {
587 int n;
588 buf_index += 3;
589 /* NOTE: we round the payload size to an integer number of
590 LPCM samples */
591 n = (s->packet_size - buf_index) % stream->lpcm_align;
592 if (n)
593 buf_index += (stream->lpcm_align - n);
594 }
595 }
596
597 if (s->is_vcd && stream->id == AUDIO_ID)
598 /* The VCD standard demands that 20 zero bytes follow
599 each audio packet (see standard p. IV-8).*/
600 buf_index+=20;
601 }
602 return s->packet_size - buf_index;
603}
604#endif
605
606/* Write an MPEG padding packet header. */
607static void put_padding_packet(AVFormatContext *ctx, ByteIOContext *pb,int packet_bytes)
608{
609 MpegMuxContext *s = ctx->priv_data;
610 int i;
611
612 put_be32(pb, PADDING_STREAM);
613 put_be16(pb, packet_bytes - 6);
614 if (!s->is_mpeg2) {
615 put_byte(pb, 0x0f);
616 packet_bytes -= 7;
617 } else
618 packet_bytes -= 6;
619
620 for(i=0;i<packet_bytes;i++)
621 put_byte(pb, 0xff);
622}
623
624static int get_nb_frames(AVFormatContext *ctx, StreamInfo *stream, int len){
625 int nb_frames=0;
626 PacketDesc *pkt_desc= stream->premux_packet;
627
628 while(len>0){
629 if(pkt_desc->size == pkt_desc->unwritten_size)
630 nb_frames++;
631 len -= pkt_desc->unwritten_size;
632 pkt_desc= pkt_desc->next;
633 }
634
635 return nb_frames;
636}
637
638/* flush the packet on stream stream_index */
639static int flush_packet(AVFormatContext *ctx, int stream_index,
640 int64_t pts, int64_t dts, int64_t scr, int trailer_size)
641{
642 MpegMuxContext *s = ctx->priv_data;
643 StreamInfo *stream = ctx->streams[stream_index]->priv_data;
644 uint8_t *buf_ptr;
645 int size, payload_size, startcode, id, stuffing_size, i, header_len;
646 int packet_size;
647 uint8_t buffer[128];
648 int zero_trail_bytes = 0;
649 int pad_packet_bytes = 0;
650 int pes_flags;
651 int general_pack = 0; /*"general" pack without data specific to one stream?*/
652 int nb_frames;
653
654 id = stream->id;
655
656#if 0
657 printf("packet ID=%2x PTS=%0.3f\n",
658 id, pts / 90000.0);
659#endif
660
661 buf_ptr = buffer;
662
663 if ((s->packet_number % s->pack_header_freq) == 0 || s->last_scr != scr) {
664 /* output pack and systems header if needed */
665 size = put_pack_header(ctx, buf_ptr, scr);
666 buf_ptr += size;
667 s->last_scr= scr;
668
669 if (s->is_vcd) {
670 /* there is exactly one system header for each stream in a VCD MPEG,
671 One in the very first video packet and one in the very first
672 audio packet (see VCD standard p. IV-7 and IV-8).*/
673
674 if (stream->packet_number==0) {
675 size = put_system_header(ctx, buf_ptr, id);
676 buf_ptr += size;
677 }
678 } else if (s->is_dvd) {
679 if (stream->align_iframe || s->packet_number == 0){
680 int PES_bytes_to_fill = s->packet_size - size - 10;
681
682 if (pts != AV_NOPTS_VALUE) {
683 if (dts != pts)
684 PES_bytes_to_fill -= 5 + 5;
685 else
686 PES_bytes_to_fill -= 5;
687 }
688
689 if (stream->bytes_to_iframe == 0 || s->packet_number == 0) {
690 size = put_system_header(ctx, buf_ptr, 0);
691 buf_ptr += size;
692 size = buf_ptr - buffer;
693 put_buffer(ctx->pb, buffer, size);
694
695 put_be32(ctx->pb, PRIVATE_STREAM_2);
696 put_be16(ctx->pb, 0x03d4); // length
697 put_byte(ctx->pb, 0x00); // substream ID, 00=PCI
698 for (i = 0; i < 979; i++)
699 put_byte(ctx->pb, 0x00);
700
701 put_be32(ctx->pb, PRIVATE_STREAM_2);
702 put_be16(ctx->pb, 0x03fa); // length
703 put_byte(ctx->pb, 0x01); // substream ID, 01=DSI
704 for (i = 0; i < 1017; i++)
705 put_byte(ctx->pb, 0x00);
706
707 memset(buffer, 0, 128);
708 buf_ptr = buffer;
709 s->packet_number++;
710 stream->align_iframe = 0;
711 scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
712 size = put_pack_header(ctx, buf_ptr, scr);
713 s->last_scr= scr;
714 buf_ptr += size;
715 /* GOP Start */
716 } else if (stream->bytes_to_iframe < PES_bytes_to_fill) {
717 pad_packet_bytes = PES_bytes_to_fill - stream->bytes_to_iframe;
718 }
719 }
720 } else {
721 if ((s->packet_number % s->system_header_freq) == 0) {
722 size = put_system_header(ctx, buf_ptr, 0);
723 buf_ptr += size;
724 }
725 }
726 }
727 size = buf_ptr - buffer;
728 put_buffer(ctx->pb, buffer, size);
729
730 packet_size = s->packet_size - size;
731
732 if (s->is_vcd && id == AUDIO_ID)
733 /* The VCD standard demands that 20 zero bytes follow
734 each audio pack (see standard p. IV-8).*/
735 zero_trail_bytes += 20;
736
737 if ((s->is_vcd && stream->packet_number==0)
738 || (s->is_svcd && s->packet_number==0)) {
739 /* for VCD the first pack of each stream contains only the pack header,
740 the system header and lots of padding (see VCD standard p. IV-6).
741 In the case of an audio pack, 20 zero bytes are also added at
742 the end.*/
743 /* For SVCD we fill the very first pack to increase compatibility with
744 some DVD players. Not mandated by the standard.*/
745 if (s->is_svcd)
746 general_pack = 1; /* the system header refers to both streams and no stream data*/
747 pad_packet_bytes = packet_size - zero_trail_bytes;
748 }
749
750 packet_size -= pad_packet_bytes + zero_trail_bytes;
751
752 if (packet_size > 0) {
753
754 /* packet header size */
755 packet_size -= 6;
756
757 /* packet header */
758 if (s->is_mpeg2) {
759 header_len = 3;
760 if (stream->packet_number==0)
761 header_len += 3; /* PES extension */
762 header_len += 1; /* obligatory stuffing byte */
763 } else {
764 header_len = 0;
765 }
766 if (pts != AV_NOPTS_VALUE) {
767 if (dts != pts)
768 header_len += 5 + 5;
769 else
770 header_len += 5;
771 } else {
772 if (!s->is_mpeg2)
773 header_len++;
774 }
775
776 payload_size = packet_size - header_len;
777 if (id < 0xc0) {
778 startcode = PRIVATE_STREAM_1;
779 payload_size -= 1;
780 if (id >= 0x40) {
781 payload_size -= 3;
782 if (id >= 0xa0)
783 payload_size -= 3;
784 }
785 } else {
786 startcode = 0x100 + id;
787 }
788
789 stuffing_size = payload_size - av_fifo_size(&stream->fifo);
790
791 // first byte does not fit -> reset pts/dts + stuffing
792 if(payload_size <= trailer_size && pts != AV_NOPTS_VALUE){
793 int timestamp_len=0;
794 if(dts != pts)
795 timestamp_len += 5;
796 if(pts != AV_NOPTS_VALUE)
797 timestamp_len += s->is_mpeg2 ? 5 : 4;
798 pts=dts= AV_NOPTS_VALUE;
799 header_len -= timestamp_len;
800 if (s->is_dvd && stream->align_iframe) {
801 pad_packet_bytes += timestamp_len;
802 packet_size -= timestamp_len;
803 } else {
804 payload_size += timestamp_len;
805 }
806 stuffing_size += timestamp_len;
807 if(payload_size > trailer_size)
808 stuffing_size += payload_size - trailer_size;
809 }
810
811 if (pad_packet_bytes > 0 && pad_packet_bytes <= 7) { // can't use padding, so use stuffing
812 packet_size += pad_packet_bytes;
813 payload_size += pad_packet_bytes; // undo the previous adjustment
814 if (stuffing_size < 0) {
815 stuffing_size = pad_packet_bytes;
816 } else {
817 stuffing_size += pad_packet_bytes;
818 }
819 pad_packet_bytes = 0;
820 }
821
822 if (stuffing_size < 0)
823 stuffing_size = 0;
824 if (stuffing_size > 16) { /*<=16 for MPEG-1, <=32 for MPEG-2*/
825 pad_packet_bytes += stuffing_size;
826 packet_size -= stuffing_size;
827 payload_size -= stuffing_size;
828 stuffing_size = 0;
829 }
830
831 nb_frames= get_nb_frames(ctx, stream, payload_size - stuffing_size);
832
833 put_be32(ctx->pb, startcode);
834
835 put_be16(ctx->pb, packet_size);
836
837 if (!s->is_mpeg2)
838 for(i=0;i<stuffing_size;i++)
839 put_byte(ctx->pb, 0xff);
840
841 if (s->is_mpeg2) {
842 put_byte(ctx->pb, 0x80); /* mpeg2 id */
843
844 pes_flags=0;
845
846 if (pts != AV_NOPTS_VALUE) {
847 pes_flags |= 0x80;
848 if (dts != pts)
849 pes_flags |= 0x40;
850 }
851
852 /* Both the MPEG-2 and the SVCD standards demand that the
853 P-STD_buffer_size field be included in the first packet of
854 every stream. (see SVCD standard p. 26 V.2.3.1 and V.2.3.2
855 and MPEG-2 standard 2.7.7) */
856 if (stream->packet_number == 0)
857 pes_flags |= 0x01;
858
859 put_byte(ctx->pb, pes_flags); /* flags */
860 put_byte(ctx->pb, header_len - 3 + stuffing_size);
861
862 if (pes_flags & 0x80) /*write pts*/
863 put_timestamp(ctx->pb, (pes_flags & 0x40) ? 0x03 : 0x02, pts);
864 if (pes_flags & 0x40) /*write dts*/
865 put_timestamp(ctx->pb, 0x01, dts);
866
867 if (pes_flags & 0x01) { /*write pes extension*/
868 put_byte(ctx->pb, 0x10); /* flags */
869
870 /* P-STD buffer info */
871 if (id == AUDIO_ID)
872 put_be16(ctx->pb, 0x4000 | stream->max_buffer_size/128);
873 else
874 put_be16(ctx->pb, 0x6000 | stream->max_buffer_size/1024);
875 }
876
877 } else {
878 if (pts != AV_NOPTS_VALUE) {
879 if (dts != pts) {
880 put_timestamp(ctx->pb, 0x03, pts);
881 put_timestamp(ctx->pb, 0x01, dts);
882 } else {
883 put_timestamp(ctx->pb, 0x02, pts);
884 }
885 } else {
886 put_byte(ctx->pb, 0x0f);
887 }
888 }
889
890 if (s->is_mpeg2) {
891 /* special stuffing byte that is always written
892 to prevent accidental generation of start codes. */
893 put_byte(ctx->pb, 0xff);
894
895 for(i=0;i<stuffing_size;i++)
896 put_byte(ctx->pb, 0xff);
897 }
898
899 if (startcode == PRIVATE_STREAM_1) {
900 put_byte(ctx->pb, id);
901 if (id >= 0xa0) {
902 /* LPCM (XXX: check nb_frames) */
903 put_byte(ctx->pb, 7);
904 put_be16(ctx->pb, 4); /* skip 3 header bytes */
905 put_byte(ctx->pb, stream->lpcm_header[0]);
906 put_byte(ctx->pb, stream->lpcm_header[1]);
907 put_byte(ctx->pb, stream->lpcm_header[2]);
908 } else if (id >= 0x40) {
909 /* AC3 */
910 put_byte(ctx->pb, nb_frames);
911 put_be16(ctx->pb, trailer_size+1);
912 }
913 }
914
915 /* output data */
916 assert(payload_size - stuffing_size <= av_fifo_size(&stream->fifo));
917 av_fifo_generic_read(&stream->fifo, payload_size - stuffing_size, &put_buffer, ctx->pb);
918 stream->bytes_to_iframe -= payload_size - stuffing_size;
919 }else{
920 payload_size=
921 stuffing_size= 0;
922 }
923
924 if (pad_packet_bytes > 0)
925 put_padding_packet(ctx,ctx->pb, pad_packet_bytes);
926
927 for(i=0;i<zero_trail_bytes;i++)
928 put_byte(ctx->pb, 0x00);
929
930 put_flush_packet(ctx->pb);
931
932 s->packet_number++;
933
934 /* only increase the stream packet number if this pack actually contains
935 something that is specific to this stream! I.e. a dedicated header
936 or some data.*/
937 if (!general_pack)
938 stream->packet_number++;
939
940 return payload_size - stuffing_size;
941}
942
943static void put_vcd_padding_sector(AVFormatContext *ctx)
944{
945 /* There are two ways to do this padding: writing a sector/pack
946 of 0 values, or writing an MPEG padding pack. Both seem to
947 work with most decoders, BUT the VCD standard only allows a 0-sector
948 (see standard p. IV-4, IV-5).
949 So a 0-sector it is...*/
950
951 MpegMuxContext *s = ctx->priv_data;
952 int i;
953
954 for(i=0;i<s->packet_size;i++)
955 put_byte(ctx->pb, 0);
956
957 s->vcd_padding_bytes_written += s->packet_size;
958
959 put_flush_packet(ctx->pb);
960
961 /* increasing the packet number is correct. The SCR of the following packs
962 is calculated from the packet_number and it has to include the padding
963 sector (it represents the sector index, not the MPEG pack index)
964 (see VCD standard p. IV-6)*/
965 s->packet_number++;
966}
967
968#if 0 /* unused, remove? */
969static int64_t get_vcd_scr(AVFormatContext *ctx,int stream_index,int64_t pts)
970{
971 MpegMuxContext *s = ctx->priv_data;
972 int64_t scr;
973
974 /* Since the data delivery rate is constant, SCR is computed
975 using the formula C + i * 1200 where C is the start constant
976 and i is the pack index.
977 It is recommended that SCR 0 is at the beginning of the VCD front
978 margin (a sequence of empty Form 2 sectors on the CD).
979 It is recommended that the front margin is 30 sectors long, so
980 we use C = 30*1200 = 36000
981 (Note that even if the front margin is not 30 sectors the file
982 will still be correct according to the standard. It just won't have
983 the "recommended" value).*/
984 scr = 36000 + s->packet_number * 1200;
985
986 return scr;
987}
988#endif
989
990static int remove_decoded_packets(AVFormatContext *ctx, int64_t scr){
991// MpegMuxContext *s = ctx->priv_data;
992 int i;
993
994 for(i=0; i<ctx->nb_streams; i++){
995 AVStream *st = ctx->streams[i];
996 StreamInfo *stream = st->priv_data;
997 PacketDesc *pkt_desc;
998
999 while((pkt_desc= stream->predecode_packet)
1000 && scr > pkt_desc->dts){ //FIXME > vs >=
1001 if(stream->buffer_index < pkt_desc->size ||
1002 stream->predecode_packet == stream->premux_packet){
1003 av_log(ctx, AV_LOG_ERROR,
1004 "buffer underflow i=%d bufi=%d size=%d\n",
1005 i, stream->buffer_index, pkt_desc->size);
1006 break;
1007 }
1008 stream->buffer_index -= pkt_desc->size;
1009
1010 stream->predecode_packet= pkt_desc->next;
1011 av_freep(&pkt_desc);
1012 }
1013 }
1014
1015 return 0;
1016}
1017
1018static int output_packet(AVFormatContext *ctx, int flush){
1019 MpegMuxContext *s = ctx->priv_data;
1020 AVStream *st;
1021 StreamInfo *stream;
1022 int i, avail_space=0, es_size, trailer_size;
1023 int best_i= -1;
1024 int best_score= INT_MIN;
1025 int ignore_constraints=0;
1026 int64_t scr= s->last_scr;
1027 PacketDesc *timestamp_packet;
1028 const int64_t max_delay= av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);
1029
1030retry:
1031 for(i=0; i<ctx->nb_streams; i++){
1032 AVStream *st = ctx->streams[i];
1033 StreamInfo *stream = st->priv_data;
1034 const int avail_data= av_fifo_size(&stream->fifo);
1035 const int space= stream->max_buffer_size - stream->buffer_index;
1036 int rel_space= 1024*space / stream->max_buffer_size;
1037 PacketDesc *next_pkt= stream->premux_packet;
1038
1039 /* for subtitle, a single PES packet must be generated,
1040 so we flush after every single subtitle packet */
1041 if(s->packet_size > avail_data && !flush
1042 && st->codec->codec_type != CODEC_TYPE_SUBTITLE)
1043 return 0;
1044 if(avail_data==0)
1045 continue;
1046 assert(avail_data>0);
1047
1048 if(space < s->packet_size && !ignore_constraints)
1049 continue;
1050
1051 if(next_pkt && next_pkt->dts - scr > max_delay)
1052 continue;
1053
1054 if(rel_space > best_score){
1055 best_score= rel_space;
1056 best_i = i;
1057 avail_space= space;
1058 }
1059 }
1060
1061 if(best_i < 0){
1062 int64_t best_dts= INT64_MAX;
1063
1064 for(i=0; i<ctx->nb_streams; i++){
1065 AVStream *st = ctx->streams[i];
1066 StreamInfo *stream = st->priv_data;
1067 PacketDesc *pkt_desc= stream->predecode_packet;
1068 if(pkt_desc && pkt_desc->dts < best_dts)
1069 best_dts= pkt_desc->dts;
1070 }
1071
1072#if 0
1073 av_log(ctx, AV_LOG_DEBUG, "bumping scr, scr:%f, dts:%f\n",
1074 scr/90000.0, best_dts/90000.0);
1075#endif
1076 if(best_dts == INT64_MAX)
1077 return 0;
1078
1079 if(scr >= best_dts+1 && !ignore_constraints){
1080 av_log(ctx, AV_LOG_ERROR, "packet too large, ignoring buffer limits to mux it\n");
1081 ignore_constraints= 1;
1082 }
1083 scr= FFMAX(best_dts+1, scr);
1084 if(remove_decoded_packets(ctx, scr) < 0)
1085 return -1;
1086 goto retry;
1087 }
1088
1089 assert(best_i >= 0);
1090
1091 st = ctx->streams[best_i];
1092 stream = st->priv_data;
1093
1094 assert(av_fifo_size(&stream->fifo) > 0);
1095
1096 assert(avail_space >= s->packet_size || ignore_constraints);
1097
1098 timestamp_packet= stream->premux_packet;
1099 if(timestamp_packet->unwritten_size == timestamp_packet->size){
1100 trailer_size= 0;
1101 }else{
1102 trailer_size= timestamp_packet->unwritten_size;
1103 timestamp_packet= timestamp_packet->next;
1104 }
1105
1106 if(timestamp_packet){
1107//av_log(ctx, AV_LOG_DEBUG, "dts:%f pts:%f scr:%f stream:%d\n", timestamp_packet->dts/90000.0, timestamp_packet->pts/90000.0, scr/90000.0, best_i);
1108 es_size= flush_packet(ctx, best_i, timestamp_packet->pts, timestamp_packet->dts, scr, trailer_size);
1109 }else{
1110 assert(av_fifo_size(&stream->fifo) == trailer_size);
1111 es_size= flush_packet(ctx, best_i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, scr, trailer_size);
1112 }
1113
1114 if (s->is_vcd) {
1115 /* Write one or more padding sectors, if necessary, to reach
1116 the constant overall bitrate.*/
1117 int vcd_pad_bytes;
1118
1119 while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->premux_packet->pts) ) >= s->packet_size){ //FIXME pts cannot be correct here
1120 put_vcd_padding_sector(ctx);
1121 s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1122 }
1123 }
1124
1125 stream->buffer_index += es_size;
1126 s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1127
1128 while(stream->premux_packet && stream->premux_packet->unwritten_size <= es_size){
1129 es_size -= stream->premux_packet->unwritten_size;
1130 stream->premux_packet= stream->premux_packet->next;
1131 }
1132 if(es_size)
1133 stream->premux_packet->unwritten_size -= es_size;
1134
1135 if(remove_decoded_packets(ctx, s->last_scr) < 0)
1136 return -1;
1137
1138 return 1;
1139}
1140
1141static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)
1142{
1143 MpegMuxContext *s = ctx->priv_data;
1144 int stream_index= pkt->stream_index;
1145 int size= pkt->size;
1146 uint8_t *buf= pkt->data;
1147 AVStream *st = ctx->streams[stream_index];
1148 StreamInfo *stream = st->priv_data;
1149 int64_t pts, dts;
1150 PacketDesc *pkt_desc;
1151 const int preload= av_rescale(ctx->preload, 90000, AV_TIME_BASE);
1152 const int is_iframe = st->codec->codec_type == CODEC_TYPE_VIDEO && (pkt->flags & PKT_FLAG_KEY);
1153
1154 pts= pkt->pts;
1155 dts= pkt->dts;
1156
1157 if(pts != AV_NOPTS_VALUE) pts += preload;
1158 if(dts != AV_NOPTS_VALUE) dts += preload;
1159
1160//av_log(ctx, AV_LOG_DEBUG, "dts:%f pts:%f flags:%d stream:%d nopts:%d\n", dts/90000.0, pts/90000.0, pkt->flags, pkt->stream_index, pts != AV_NOPTS_VALUE);
1161 if (!stream->premux_packet)
1162 stream->next_packet = &stream->premux_packet;
1163 *stream->next_packet=
1164 pkt_desc= av_mallocz(sizeof(PacketDesc));
1165 pkt_desc->pts= pts;
1166 pkt_desc->dts= dts;
1167 pkt_desc->unwritten_size=
1168 pkt_desc->size= size;
1169 if(!stream->predecode_packet)
1170 stream->predecode_packet= pkt_desc;
1171 stream->next_packet= &pkt_desc->next;
1172
1173 av_fifo_realloc(&stream->fifo, av_fifo_size(&stream->fifo) + size);
1174
1175 if (s->is_dvd){
1176 if (is_iframe && (s->packet_number == 0 || (pts - stream->vobu_start_pts >= 36000))) { // min VOBU length 0.4 seconds (mpucoder)
1177 stream->bytes_to_iframe = av_fifo_size(&stream->fifo);
1178 stream->align_iframe = 1;
1179 stream->vobu_start_pts = pts;
1180 }
1181 }
1182
1183 av_fifo_generic_write(&stream->fifo, buf, size, NULL);
1184
1185 for(;;){
1186 int ret= output_packet(ctx, 0);
1187 if(ret<=0)
1188 return ret;
1189 }
1190}
1191
1192static int mpeg_mux_end(AVFormatContext *ctx)
1193{
1194// MpegMuxContext *s = ctx->priv_data;
1195 StreamInfo *stream;
1196 int i;
1197
1198 for(;;){
1199 int ret= output_packet(ctx, 1);
1200 if(ret<0)
1201 return ret;
1202 else if(ret==0)
1203 break;
1204 }
1205
1206 /* End header according to MPEG1 systems standard. We do not write
1207 it as it is usually not needed by decoders and because it
1208 complicates MPEG stream concatenation. */
1209 //put_be32(ctx->pb, ISO_11172_END_CODE);
1210 //put_flush_packet(ctx->pb);
1211
1212 for(i=0;i<ctx->nb_streams;i++) {
1213 stream = ctx->streams[i]->priv_data;
1214
1215 assert(av_fifo_size(&stream->fifo) == 0);
1216 av_fifo_free(&stream->fifo);
1217 }
1218 return 0;
1219}
1220
1221#ifdef CONFIG_MPEG1SYSTEM_MUXER
1222AVOutputFormat mpeg1system_muxer = {
1223 "mpeg",
1224 NULL_IF_CONFIG_SMALL("MPEG-1 System format"),
1225 "video/mpeg",
1226 "mpg,mpeg",
1227 sizeof(MpegMuxContext),
1228 CODEC_ID_MP2,
1229 CODEC_ID_MPEG1VIDEO,
1230 mpeg_mux_init,
1231 mpeg_mux_write_packet,
1232 mpeg_mux_end,
1233};
1234#endif
1235#ifdef CONFIG_MPEG1VCD_MUXER
1236AVOutputFormat mpeg1vcd_muxer = {
1237 "vcd",
1238 NULL_IF_CONFIG_SMALL("MPEG-1 System format (VCD)"),
1239 "video/mpeg",
1240 NULL,
1241 sizeof(MpegMuxContext),
1242 CODEC_ID_MP2,
1243 CODEC_ID_MPEG1VIDEO,
1244 mpeg_mux_init,
1245 mpeg_mux_write_packet,
1246 mpeg_mux_end,
1247};
1248#endif
1249#ifdef CONFIG_MPEG2VOB_MUXER
1250AVOutputFormat mpeg2vob_muxer = {
1251 "vob",
1252 NULL_IF_CONFIG_SMALL("MPEG-2 PS format (VOB)"),
1253 "video/mpeg",
1254 "vob",
1255 sizeof(MpegMuxContext),
1256 CODEC_ID_MP2,
1257 CODEC_ID_MPEG2VIDEO,
1258 mpeg_mux_init,
1259 mpeg_mux_write_packet,
1260 mpeg_mux_end,
1261};
1262#endif
1263
1264/* Same as mpeg2vob_mux except that the pack size is 2324 */
1265#ifdef CONFIG_MPEG2SVCD_MUXER
1266AVOutputFormat mpeg2svcd_muxer = {
1267 "svcd",
1268 NULL_IF_CONFIG_SMALL("MPEG-2 PS format (VOB)"),
1269 "video/mpeg",
1270 "vob",
1271 sizeof(MpegMuxContext),
1272 CODEC_ID_MP2,
1273 CODEC_ID_MPEG2VIDEO,
1274 mpeg_mux_init,
1275 mpeg_mux_write_packet,
1276 mpeg_mux_end,
1277};
1278#endif
1279
1280/* Same as mpeg2vob_mux except the 'is_dvd' flag is set to produce NAV pkts */
1281#ifdef CONFIG_MPEG2DVD_MUXER
1282AVOutputFormat mpeg2dvd_muxer = {
1283 "dvd",
1284 NULL_IF_CONFIG_SMALL("MPEG-2 PS format (DVD VOB)"),
1285 "video/mpeg",
1286 "dvd",
1287 sizeof(MpegMuxContext),
1288 CODEC_ID_MP2,
1289 CODEC_ID_MPEG2VIDEO,
1290 mpeg_mux_init,
1291 mpeg_mux_write_packet,
1292 mpeg_mux_end,
1293};
1294#endif
diff --git a/src/plugins/ffmpeg/libavformat/mpegts.c b/src/plugins/ffmpeg/libavformat/mpegts.c
deleted file mode 100644
index 5067f77..0000000
--- a/src/plugins/ffmpeg/libavformat/mpegts.c
+++ /dev/null
@@ -1,1522 +0,0 @@
1/*
2 * MPEG2 transport stream (aka DVB) demuxer
3 * Copyright (c) 2002-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/crc.h"
23#include "avformat.h"
24#include "mpegts.h"
25
26//#define DEBUG_SI
27//#define DEBUG_SEEK
28
29/* 1.0 second at 24Mbit/s */
30#define MAX_SCAN_PACKETS 32000
31
32/* maximum size in which we look for synchronisation if
33 synchronisation is lost */
34#define MAX_RESYNC_SIZE 4096
35#define REGISTRATION_DESCRIPTOR 5
36
37typedef struct PESContext PESContext;
38
39static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type);
40static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code);
41extern void av_set_program_name(AVProgram *program, char *provider_name, char *name);
42extern void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx);
43
44enum MpegTSFilterType {
45 MPEGTS_PES,
46 MPEGTS_SECTION,
47};
48
49typedef struct MpegTSFilter MpegTSFilter;
50
51typedef void PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start);
52
53typedef struct MpegTSPESFilter {
54 PESCallback *pes_cb;
55 void *opaque;
56} MpegTSPESFilter;
57
58typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
59
60typedef void SetServiceCallback(void *opaque, int ret);
61
62typedef struct MpegTSSectionFilter {
63 int section_index;
64 int section_h_size;
65 uint8_t *section_buf;
66 unsigned int check_crc:1;
67 unsigned int end_of_section_reached:1;
68 SectionCallback *section_cb;
69 void *opaque;
70} MpegTSSectionFilter;
71
72struct MpegTSFilter {
73 int pid;
74 int last_cc; /* last cc code (-1 if first packet) */
75 enum MpegTSFilterType type;
76 union {
77 MpegTSPESFilter pes_filter;
78 MpegTSSectionFilter section_filter;
79 } u;
80};
81
82#define MAX_PIDS_PER_PROGRAM 64
83typedef struct {
84 unsigned int id; //program id/service id
85 unsigned int nb_pids;
86 unsigned int pids[MAX_PIDS_PER_PROGRAM];
87} Program_t;
88
89struct MpegTSContext {
90 /* user data */
91 AVFormatContext *stream;
92 /** raw packet size, including FEC if present */
93 int raw_packet_size;
94
95 int pos47;
96
97 /** if true, all pids are analyzed to find streams */
98 int auto_guess;
99
100 /** compute exact PCR for each transport stream packet */
101 int mpeg2ts_compute_pcr;
102
103 int64_t cur_pcr; /**< used to estimate the exact PCR */
104 int pcr_incr; /**< used to estimate the exact PCR */
105
106 /* data needed to handle file based ts */
107 /** stop parsing loop */
108 int stop_parse;
109 /** packet containing Audio/Video data */
110 AVPacket *pkt;
111
112 /******************************************/
113 /* private mpegts data */
114 /* scan context */
115 /** structure to keep track of Program->pids mapping */
116 unsigned int nb_prg;
117 Program_t *prg;
118
119
120 /** filters for various streams specified by PMT + for the PAT and PMT */
121 MpegTSFilter *pids[NB_PID_MAX];
122};
123
124/* TS stream handling */
125
126enum MpegTSState {
127 MPEGTS_HEADER = 0,
128 MPEGTS_PESHEADER_FILL,
129 MPEGTS_PAYLOAD,
130 MPEGTS_SKIP,
131};
132
133/* enough for PES header + length */
134#define PES_START_SIZE 9
135#define MAX_PES_HEADER_SIZE (9 + 255)
136
137struct PESContext {
138 int pid;
139 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
140 int stream_type;
141 MpegTSContext *ts;
142 AVFormatContext *stream;
143 AVStream *st;
144 enum MpegTSState state;
145 /* used to get the format */
146 int data_index;
147 int total_size;
148 int pes_header_size;
149 int64_t pts, dts;
150 uint8_t header[MAX_PES_HEADER_SIZE];
151};
152
153extern AVInputFormat mpegts_demuxer;
154
155static void clear_program(MpegTSContext *ts, unsigned int programid)
156{
157 int i;
158
159 for(i=0; i<ts->nb_prg; i++)
160 if(ts->prg[i].id == programid)
161 ts->prg[i].nb_pids = 0;
162}
163
164static void clear_programs(MpegTSContext *ts)
165{
166 av_freep(&ts->prg);
167 ts->nb_prg=0;
168}
169
170static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
171{
172 Program_t *p;
173 void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(Program_t));
174 if(!tmp)
175 return;
176 ts->prg = tmp;
177 p = &ts->prg[ts->nb_prg];
178 p->id = programid;
179 p->nb_pids = 0;
180 ts->nb_prg++;
181}
182
183static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
184{
185 int i;
186 Program_t *p = NULL;
187 for(i=0; i<ts->nb_prg; i++) {
188 if(ts->prg[i].id == programid) {
189 p = &ts->prg[i];
190 break;
191 }
192 }
193 if(!p)
194 return;
195
196 if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
197 return;
198 p->pids[p->nb_pids++] = pid;
199}
200
201/**
202 * \brief discard_pid() decides if the pid is to be discarded according
203 * to caller's programs selection
204 * \param ts : - TS context
205 * \param pid : - pid
206 * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
207 * 0 otherwise
208 */
209static int discard_pid(MpegTSContext *ts, unsigned int pid)
210{
211 int i, j, k;
212 int used = 0, discarded = 0;
213 Program_t *p;
214 for(i=0; i<ts->nb_prg; i++) {
215 p = &ts->prg[i];
216 for(j=0; j<p->nb_pids; j++) {
217 if(p->pids[j] != pid)
218 continue;
219 //is program with id p->id set to be discarded?
220 for(k=0; k<ts->stream->nb_programs; k++) {
221 if(ts->stream->programs[k]->id == p->id) {
222 if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
223 discarded++;
224 else
225 used++;
226 }
227 }
228 }
229 }
230
231 return !used && discarded;
232}
233
234/**
235 * Assembles PES packets out of TS packets, and then calls the "section_cb"
236 * function when they are complete.
237 */
238static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
239 const uint8_t *buf, int buf_size, int is_start)
240{
241 MpegTSSectionFilter *tss = &tss1->u.section_filter;
242 int len;
243
244 if (is_start) {
245 memcpy(tss->section_buf, buf, buf_size);
246 tss->section_index = buf_size;
247 tss->section_h_size = -1;
248 tss->end_of_section_reached = 0;
249 } else {
250 if (tss->end_of_section_reached)
251 return;
252 len = 4096 - tss->section_index;
253 if (buf_size < len)
254 len = buf_size;
255 memcpy(tss->section_buf + tss->section_index, buf, len);
256 tss->section_index += len;
257 }
258
259 /* compute section length if possible */
260 if (tss->section_h_size == -1 && tss->section_index >= 3) {
261 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
262 if (len > 4096)
263 return;
264 tss->section_h_size = len;
265 }
266
267 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
268 tss->end_of_section_reached = 1;
269 if (!tss->check_crc ||
270 av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
271 tss->section_buf, tss->section_h_size) == 0)
272 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
273 }
274}
275
276static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
277 SectionCallback *section_cb, void *opaque,
278 int check_crc)
279
280{
281 MpegTSFilter *filter;
282 MpegTSSectionFilter *sec;
283
284#ifdef DEBUG_SI
285 av_log(ts->stream, AV_LOG_DEBUG, "Filter: pid=0x%x\n", pid);
286#endif
287 if (pid >= NB_PID_MAX || ts->pids[pid])
288 return NULL;
289 filter = av_mallocz(sizeof(MpegTSFilter));
290 if (!filter)
291 return NULL;
292 ts->pids[pid] = filter;
293 filter->type = MPEGTS_SECTION;
294 filter->pid = pid;
295 filter->last_cc = -1;
296 sec = &filter->u.section_filter;
297 sec->section_cb = section_cb;
298 sec->opaque = opaque;
299 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
300 sec->check_crc = check_crc;
301 if (!sec->section_buf) {
302 av_free(filter);
303 return NULL;
304 }
305 return filter;
306}
307
308static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
309 PESCallback *pes_cb,
310 void *opaque)
311{
312 MpegTSFilter *filter;
313 MpegTSPESFilter *pes;
314
315 if (pid >= NB_PID_MAX || ts->pids[pid])
316 return NULL;
317 filter = av_mallocz(sizeof(MpegTSFilter));
318 if (!filter)
319 return NULL;
320 ts->pids[pid] = filter;
321 filter->type = MPEGTS_PES;
322 filter->pid = pid;
323 filter->last_cc = -1;
324 pes = &filter->u.pes_filter;
325 pes->pes_cb = pes_cb;
326 pes->opaque = opaque;
327 return filter;
328}
329
330static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
331{
332 int pid;
333
334 pid = filter->pid;
335 if (filter->type == MPEGTS_SECTION)
336 av_freep(&filter->u.section_filter.section_buf);
337
338 av_free(filter);
339 ts->pids[pid] = NULL;
340}
341
342static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
343 int stat[packet_size];
344 int i;
345 int x=0;
346 int best_score=0;
347
348 memset(stat, 0, packet_size*sizeof(int));
349
350 for(x=i=0; i<size-3; i++){
351 if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
352 stat[x]++;
353 if(stat[x] > best_score){
354 best_score= stat[x];
355 if(index) *index= x;
356 }
357 }
358
359 x++;
360 if(x == packet_size) x= 0;
361 }
362
363 return best_score;
364}
365
366/* autodetect fec presence. Must have at least 1024 bytes */
367static int get_packet_size(const uint8_t *buf, int size)
368{
369 int score, fec_score, dvhs_score;
370
371 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
372 return -1;
373
374 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
375 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
376 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
377// av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
378
379 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
380 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
381 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
382 else return -1;
383}
384
385typedef struct SectionHeader {
386 uint8_t tid;
387 uint16_t id;
388 uint8_t version;
389 uint8_t sec_num;
390 uint8_t last_sec_num;
391} SectionHeader;
392
393static inline int get8(const uint8_t **pp, const uint8_t *p_end)
394{
395 const uint8_t *p;
396 int c;
397
398 p = *pp;
399 if (p >= p_end)
400 return -1;
401 c = *p++;
402 *pp = p;
403 return c;
404}
405
406static inline int get16(const uint8_t **pp, const uint8_t *p_end)
407{
408 const uint8_t *p;
409 int c;
410
411 p = *pp;
412 if ((p + 1) >= p_end)
413 return -1;
414 c = AV_RB16(p);
415 p += 2;
416 *pp = p;
417 return c;
418}
419
420/* read and allocate a DVB string preceeded by its length */
421static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
422{
423 int len;
424 const uint8_t *p;
425 char *str;
426
427 p = *pp;
428 len = get8(&p, p_end);
429 if (len < 0)
430 return NULL;
431 if ((p + len) > p_end)
432 return NULL;
433 str = av_malloc(len + 1);
434 if (!str)
435 return NULL;
436 memcpy(str, p, len);
437 str[len] = '\0';
438 p += len;
439 *pp = p;
440 return str;
441}
442
443static int parse_section_header(SectionHeader *h,
444 const uint8_t **pp, const uint8_t *p_end)
445{
446 int val;
447
448 val = get8(pp, p_end);
449 if (val < 0)
450 return -1;
451 h->tid = val;
452 *pp += 2;
453 val = get16(pp, p_end);
454 if (val < 0)
455 return -1;
456 h->id = val;
457 val = get8(pp, p_end);
458 if (val < 0)
459 return -1;
460 h->version = (val >> 1) & 0x1f;
461 val = get8(pp, p_end);
462 if (val < 0)
463 return -1;
464 h->sec_num = val;
465 val = get8(pp, p_end);
466 if (val < 0)
467 return -1;
468 h->last_sec_num = val;
469 return 0;
470}
471
472
473static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
474{
475 MpegTSContext *ts = filter->u.section_filter.opaque;
476 SectionHeader h1, *h = &h1;
477 PESContext *pes;
478 AVStream *st;
479 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
480 int program_info_length, pcr_pid, pid, stream_type;
481 int desc_list_len, desc_len, desc_tag;
482 int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
483 char language[4] = {0}; /* initialize to kill warnings */
484 int has_hdmv_descr = 0;
485
486#ifdef DEBUG_SI
487 av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
488 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
489#endif
490 p_end = section + section_len - 4;
491 p = section;
492 if (parse_section_header(h, &p, p_end) < 0)
493 return;
494#ifdef DEBUG_SI
495 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
496 h->id, h->sec_num, h->last_sec_num);
497#endif
498 if (h->tid != PMT_TID)
499 return;
500
501 clear_program(ts, h->id);
502 pcr_pid = get16(&p, p_end) & 0x1fff;
503 if (pcr_pid < 0)
504 return;
505 add_pid_to_pmt(ts, h->id, pcr_pid);
506#ifdef DEBUG_SI
507 av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);
508#endif
509 program_info_length = get16(&p, p_end) & 0xfff;
510 if (program_info_length < 0)
511 return;
512 while(program_info_length >= 2) {
513 uint8_t tag, len;
514 tag = get8(&p, p_end);
515 len = get8(&p, p_end);
516 if(len > program_info_length - 2)
517 //something else is broken, exit the program_descriptors_loop
518 break;
519 program_info_length -= len + 2;
520 if(tag == REGISTRATION_DESCRIPTOR && len >= 4) {
521 uint8_t bytes[4];
522 bytes[0] = get8(&p, p_end);
523 bytes[1] = get8(&p, p_end);
524 bytes[2] = get8(&p, p_end);
525 bytes[3] = get8(&p, p_end);
526 len -= 4;
527 if(bytes[0] == 'H' && bytes[1] == 'D' &&
528 bytes[2] == 'M' && bytes[3] == 'V')
529 has_hdmv_descr = 1;
530 }
531 p += len;
532 }
533 p += program_info_length;
534 if (p >= p_end)
535 return;
536 for(;;) {
537 language[0] = 0;
538 st = 0;
539 stream_type = get8(&p, p_end);
540 if (stream_type < 0)
541 break;
542 pid = get16(&p, p_end) & 0x1fff;
543 if (pid < 0)
544 break;
545 desc_list_len = get16(&p, p_end) & 0xfff;
546 if (desc_list_len < 0)
547 break;
548 desc_list_end = p + desc_list_len;
549 if (desc_list_end > p_end)
550 break;
551 for(;;) {
552 desc_tag = get8(&p, desc_list_end);
553 if (desc_tag < 0)
554 break;
555 if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
556 if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
557 /*assume DVB AC-3 Audio*/
558 stream_type = STREAM_TYPE_AUDIO_AC3;
559 } else if(desc_tag == 0x7B) {
560 /* DVB DTS audio */
561 stream_type = STREAM_TYPE_AUDIO_DTS;
562 }
563 }
564 desc_len = get8(&p, desc_list_end);
565 desc_end = p + desc_len;
566 if (desc_end > desc_list_end)
567 break;
568#ifdef DEBUG_SI
569 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
570 desc_tag, desc_len);
571#endif
572 switch(desc_tag) {
573 case DVB_SUBT_DESCID:
574 if (stream_type == STREAM_TYPE_PRIVATE_DATA)
575 stream_type = STREAM_TYPE_SUBTITLE_DVB;
576
577 language[0] = get8(&p, desc_end);
578 language[1] = get8(&p, desc_end);
579 language[2] = get8(&p, desc_end);
580 language[3] = 0;
581 get8(&p, desc_end);
582 comp_page = get16(&p, desc_end);
583 anc_page = get16(&p, desc_end);
584
585 break;
586 case 0x0a: /* ISO 639 language descriptor */
587 language[0] = get8(&p, desc_end);
588 language[1] = get8(&p, desc_end);
589 language[2] = get8(&p, desc_end);
590 language[3] = 0;
591 break;
592 default:
593 break;
594 }
595 p = desc_end;
596 }
597 p = desc_list_end;
598
599#ifdef DEBUG_SI
600 av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
601 stream_type, pid);
602#endif
603
604 /* now create ffmpeg stream */
605 switch(stream_type) {
606 case STREAM_TYPE_AUDIO_MPEG1:
607 case STREAM_TYPE_AUDIO_MPEG2:
608 case STREAM_TYPE_VIDEO_MPEG1:
609 case STREAM_TYPE_VIDEO_MPEG2:
610 case STREAM_TYPE_VIDEO_MPEG4:
611 case STREAM_TYPE_VIDEO_H264:
612 case STREAM_TYPE_VIDEO_VC1:
613 case STREAM_TYPE_AUDIO_AAC:
614 case STREAM_TYPE_AUDIO_AC3:
615 case STREAM_TYPE_AUDIO_DTS:
616 case STREAM_TYPE_AUDIO_HDMV_DTS:
617 case STREAM_TYPE_SUBTITLE_DVB:
618 if(stream_type == STREAM_TYPE_AUDIO_HDMV_DTS && !has_hdmv_descr)
619 break;
620 if(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES){
621 pes= ts->pids[pid]->u.pes_filter.opaque;
622 st= pes->st;
623 }else{
624 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
625 pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
626 if (pes)
627 st = new_pes_av_stream(pes, 0);
628 }
629 add_pid_to_pmt(ts, h->id, pid);
630 if(st)
631 av_program_add_stream_index(ts->stream, h->id, st->index);
632 break;
633 default:
634 /* we ignore the other streams */
635 break;
636 }
637
638 if (st) {
639 if (language[0] != 0) {
640 memcpy(st->language, language, 4);
641 }
642
643 if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
644 st->codec->sub_id = (anc_page << 16) | comp_page;
645 }
646 }
647 }
648 /* all parameters are there */
649 ts->stop_parse++;
650 mpegts_close_filter(ts, filter);
651}
652
653static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
654{
655 MpegTSContext *ts = filter->u.section_filter.opaque;
656 SectionHeader h1, *h = &h1;
657 const uint8_t *p, *p_end;
658 int sid, pmt_pid;
659
660#ifdef DEBUG_SI
661 av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
662 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
663#endif
664 p_end = section + section_len - 4;
665 p = section;
666 if (parse_section_header(h, &p, p_end) < 0)
667 return;
668 if (h->tid != PAT_TID)
669 return;
670
671 clear_programs(ts);
672 for(;;) {
673 sid = get16(&p, p_end);
674 if (sid < 0)
675 break;
676 pmt_pid = get16(&p, p_end) & 0x1fff;
677 if (pmt_pid < 0)
678 break;
679#ifdef DEBUG_SI
680 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
681#endif
682 if (sid == 0x0000) {
683 /* NIT info */
684 } else {
685 av_new_program(ts->stream, sid);
686 ts->stop_parse--;
687 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
688 add_pat_entry(ts, sid);
689 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
690 add_pid_to_pmt(ts, sid, pmt_pid);
691 }
692 }
693 /* not found */
694 ts->stop_parse++;
695
696 mpegts_close_filter(ts, filter);
697}
698
699static void mpegts_set_service(MpegTSContext *ts)
700{
701 mpegts_open_section_filter(ts, PAT_PID,
702 pat_cb, ts, 1);
703}
704
705static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
706{
707 MpegTSContext *ts = filter->u.section_filter.opaque;
708 SectionHeader h1, *h = &h1;
709 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
710 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
711 char *name, *provider_name;
712
713#ifdef DEBUG_SI
714 av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
715 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
716#endif
717
718 p_end = section + section_len - 4;
719 p = section;
720 if (parse_section_header(h, &p, p_end) < 0)
721 return;
722 if (h->tid != SDT_TID)
723 return;
724 onid = get16(&p, p_end);
725 if (onid < 0)
726 return;
727 val = get8(&p, p_end);
728 if (val < 0)
729 return;
730 for(;;) {
731 sid = get16(&p, p_end);
732 if (sid < 0)
733 break;
734 val = get8(&p, p_end);
735 if (val < 0)
736 break;
737 desc_list_len = get16(&p, p_end) & 0xfff;
738 if (desc_list_len < 0)
739 break;
740 desc_list_end = p + desc_list_len;
741 if (desc_list_end > p_end)
742 break;
743 for(;;) {
744 desc_tag = get8(&p, desc_list_end);
745 if (desc_tag < 0)
746 break;
747 desc_len = get8(&p, desc_list_end);
748 desc_end = p + desc_len;
749 if (desc_end > desc_list_end)
750 break;
751#ifdef DEBUG_SI
752 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
753 desc_tag, desc_len);
754#endif
755 switch(desc_tag) {
756 case 0x48:
757 service_type = get8(&p, p_end);
758 if (service_type < 0)
759 break;
760 provider_name = getstr8(&p, p_end);
761 if (!provider_name)
762 break;
763 name = getstr8(&p, p_end);
764 if (name) {
765 AVProgram *program = av_new_program(ts->stream, sid);
766 if(program)
767 av_set_program_name(program, provider_name, name);
768 }
769 av_free(name);
770 av_free(provider_name);
771 break;
772 default:
773 break;
774 }
775 p = desc_end;
776 }
777 p = desc_list_end;
778 }
779}
780
781/* scan services in a transport stream by looking at the SDT */
782static void mpegts_scan_sdt(MpegTSContext *ts)
783{
784 mpegts_open_section_filter(ts, SDT_PID,
785 sdt_cb, ts, 1);
786}
787
788static int64_t get_pts(const uint8_t *p)
789{
790 int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
791 pts |= (AV_RB16(p + 1) >> 1) << 15;
792 pts |= AV_RB16(p + 3) >> 1;
793 return pts;
794}
795
796/* return non zero if a packet could be constructed */
797static void mpegts_push_data(MpegTSFilter *filter,
798 const uint8_t *buf, int buf_size, int is_start)
799{
800 PESContext *pes = filter->u.pes_filter.opaque;
801 MpegTSContext *ts = pes->ts;
802 const uint8_t *p;
803 int len, code;
804
805 if(!ts->pkt)
806 return;
807
808 if (is_start) {
809 pes->state = MPEGTS_HEADER;
810 pes->data_index = 0;
811 }
812 p = buf;
813 while (buf_size > 0) {
814 switch(pes->state) {
815 case MPEGTS_HEADER:
816 len = PES_START_SIZE - pes->data_index;
817 if (len > buf_size)
818 len = buf_size;
819 memcpy(pes->header + pes->data_index, p, len);
820 pes->data_index += len;
821 p += len;
822 buf_size -= len;
823 if (pes->data_index == PES_START_SIZE) {
824 /* we got all the PES or section header. We can now
825 decide */
826#if 0
827 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
828#endif
829 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
830 pes->header[2] == 0x01) {
831 /* it must be an mpeg2 PES stream */
832 code = pes->header[3] | 0x100;
833 if (!((code >= 0x1c0 && code <= 0x1df) ||
834 (code >= 0x1e0 && code <= 0x1ef) ||
835 (code == 0x1bd) || (code == 0x1fd)))
836 goto skip;
837 if (!pes->st) {
838 /* allocate stream */
839 new_pes_av_stream(pes, code);
840 }
841 pes->state = MPEGTS_PESHEADER_FILL;
842 pes->total_size = AV_RB16(pes->header + 4);
843 /* NOTE: a zero total size means the PES size is
844 unbounded */
845 if (pes->total_size)
846 pes->total_size += 6;
847 pes->pes_header_size = pes->header[8] + 9;
848 } else {
849 /* otherwise, it should be a table */
850 /* skip packet */
851 skip:
852 pes->state = MPEGTS_SKIP;
853 continue;
854 }
855 }
856 break;
857 /**********************************************/
858 /* PES packing parsing */
859 case MPEGTS_PESHEADER_FILL:
860 len = pes->pes_header_size - pes->data_index;
861 if (len > buf_size)
862 len = buf_size;
863 memcpy(pes->header + pes->data_index, p, len);
864 pes->data_index += len;
865 p += len;
866 buf_size -= len;
867 if (pes->data_index == pes->pes_header_size) {
868 const uint8_t *r;
869 unsigned int flags;
870
871 flags = pes->header[7];
872 r = pes->header + 9;
873 pes->pts = AV_NOPTS_VALUE;
874 pes->dts = AV_NOPTS_VALUE;
875 if ((flags & 0xc0) == 0x80) {
876 pes->pts = get_pts(r);
877 r += 5;
878 } else if ((flags & 0xc0) == 0xc0) {
879 pes->pts = get_pts(r);
880 r += 5;
881 pes->dts = get_pts(r);
882 r += 5;
883 }
884 /* we got the full header. We parse it and get the payload */
885 pes->state = MPEGTS_PAYLOAD;
886 }
887 break;
888 case MPEGTS_PAYLOAD:
889 if (pes->total_size) {
890 len = pes->total_size - pes->data_index;
891 if (len > buf_size)
892 len = buf_size;
893 } else {
894 len = buf_size;
895 }
896 if (len > 0) {
897 AVPacket *pkt = ts->pkt;
898 if (pes->st && av_new_packet(pkt, len) == 0) {
899 memcpy(pkt->data, p, len);
900 pkt->stream_index = pes->st->index;
901 pkt->pts = pes->pts;
902 pkt->dts = pes->dts;
903 /* reset pts values */
904 pes->pts = AV_NOPTS_VALUE;
905 pes->dts = AV_NOPTS_VALUE;
906 ts->stop_parse = 1;
907 return;
908 }
909 }
910 buf_size = 0;
911 break;
912 case MPEGTS_SKIP:
913 buf_size = 0;
914 break;
915 }
916 }
917}
918
919static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
920{
921 AVStream *st;
922 int codec_type, codec_id;
923
924 switch(pes->stream_type){
925 case STREAM_TYPE_AUDIO_MPEG1:
926 case STREAM_TYPE_AUDIO_MPEG2:
927 codec_type = CODEC_TYPE_AUDIO;
928 codec_id = CODEC_ID_MP3;
929 break;
930 case STREAM_TYPE_VIDEO_MPEG1:
931 case STREAM_TYPE_VIDEO_MPEG2:
932 codec_type = CODEC_TYPE_VIDEO;
933 codec_id = CODEC_ID_MPEG2VIDEO;
934 break;
935 case STREAM_TYPE_VIDEO_MPEG4:
936 codec_type = CODEC_TYPE_VIDEO;
937 codec_id = CODEC_ID_MPEG4;
938 break;
939 case STREAM_TYPE_VIDEO_H264:
940 codec_type = CODEC_TYPE_VIDEO;
941 codec_id = CODEC_ID_H264;
942 break;
943 case STREAM_TYPE_VIDEO_VC1:
944 codec_type = CODEC_TYPE_VIDEO;
945 codec_id = CODEC_ID_VC1;
946 break;
947 case STREAM_TYPE_AUDIO_AAC:
948 codec_type = CODEC_TYPE_AUDIO;
949 codec_id = CODEC_ID_AAC;
950 break;
951 case STREAM_TYPE_AUDIO_AC3:
952 codec_type = CODEC_TYPE_AUDIO;
953 codec_id = CODEC_ID_AC3;
954 break;
955 case STREAM_TYPE_AUDIO_DTS:
956 case STREAM_TYPE_AUDIO_HDMV_DTS:
957 codec_type = CODEC_TYPE_AUDIO;
958 codec_id = CODEC_ID_DTS;
959 break;
960 case STREAM_TYPE_SUBTITLE_DVB:
961 codec_type = CODEC_TYPE_SUBTITLE;
962 codec_id = CODEC_ID_DVB_SUBTITLE;
963 break;
964 default:
965 if (code >= 0x1c0 && code <= 0x1df) {
966 codec_type = CODEC_TYPE_AUDIO;
967 codec_id = CODEC_ID_MP2;
968 } else if (code == 0x1bd) {
969 codec_type = CODEC_TYPE_AUDIO;
970 codec_id = CODEC_ID_AC3;
971 } else {
972 codec_type = CODEC_TYPE_VIDEO;
973 codec_id = CODEC_ID_MPEG1VIDEO;
974 }
975 break;
976 }
977 st = av_new_stream(pes->stream, pes->pid);
978 if (st) {
979 av_set_pts_info(st, 33, 1, 90000);
980 st->priv_data = pes;
981 st->codec->codec_type = codec_type;
982 st->codec->codec_id = codec_id;
983 st->need_parsing = AVSTREAM_PARSE_FULL;
984 pes->st = st;
985 }
986 return st;
987}
988
989
990static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
991{
992 MpegTSFilter *tss;
993 PESContext *pes;
994
995 /* if no pid found, then add a pid context */
996 pes = av_mallocz(sizeof(PESContext));
997 if (!pes)
998 return 0;
999 pes->ts = ts;
1000 pes->stream = ts->stream;
1001 pes->pid = pid;
1002 pes->pcr_pid = pcr_pid;
1003 pes->stream_type = stream_type;
1004 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1005 if (!tss) {
1006 av_free(pes);
1007 return 0;
1008 }
1009 return pes;
1010}
1011
1012/* handle one TS packet */
1013static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
1014{
1015 AVFormatContext *s = ts->stream;
1016 MpegTSFilter *tss;
1017 int len, pid, cc, cc_ok, afc, is_start;
1018 const uint8_t *p, *p_end;
1019
1020 pid = AV_RB16(packet + 1) & 0x1fff;
1021 if(pid && discard_pid(ts, pid))
1022 return;
1023 is_start = packet[1] & 0x40;
1024 tss = ts->pids[pid];
1025 if (ts->auto_guess && tss == NULL && is_start) {
1026 add_pes_stream(ts, pid, -1, 0);
1027 tss = ts->pids[pid];
1028 }
1029 if (!tss)
1030 return;
1031
1032 /* continuity check (currently not used) */
1033 cc = (packet[3] & 0xf);
1034 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1035 tss->last_cc = cc;
1036
1037 /* skip adaptation field */
1038 afc = (packet[3] >> 4) & 3;
1039 p = packet + 4;
1040 if (afc == 0) /* reserved value */
1041 return;
1042 if (afc == 2) /* adaptation field only */
1043 return;
1044 if (afc == 3) {
1045 /* skip adapation field */
1046 p += p[0] + 1;
1047 }
1048 /* if past the end of packet, ignore */
1049 p_end = packet + TS_PACKET_SIZE;
1050 if (p >= p_end)
1051 return;
1052
1053 ts->pos47= url_ftell(ts->stream->pb) % ts->raw_packet_size;
1054
1055 if (tss->type == MPEGTS_SECTION) {
1056 if (is_start) {
1057 /* pointer field present */
1058 len = *p++;
1059 if (p + len > p_end)
1060 return;
1061 if (len && cc_ok) {
1062 /* write remaining section bytes */
1063 write_section_data(s, tss,
1064 p, len, 0);
1065 /* check whether filter has been closed */
1066 if (!ts->pids[pid])
1067 return;
1068 }
1069 p += len;
1070 if (p < p_end) {
1071 write_section_data(s, tss,
1072 p, p_end - p, 1);
1073 }
1074 } else {
1075 if (cc_ok) {
1076 write_section_data(s, tss,
1077 p, p_end - p, 0);
1078 }
1079 }
1080 } else {
1081 tss->u.pes_filter.pes_cb(tss,
1082 p, p_end - p, is_start);
1083 }
1084}
1085
1086/* XXX: try to find a better synchro over several packets (use
1087 get_packet_size() ?) */
1088static int mpegts_resync(ByteIOContext *pb)
1089{
1090 int c, i;
1091
1092 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1093 c = url_fgetc(pb);
1094 if (c < 0)
1095 return -1;
1096 if (c == 0x47) {
1097 url_fseek(pb, -1, SEEK_CUR);
1098 return 0;
1099 }
1100 }
1101 /* no sync found */
1102 return -1;
1103}
1104
1105/* return -1 if error or EOF. Return 0 if OK. */
1106static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1107{
1108 int skip, len;
1109
1110 for(;;) {
1111 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1112 if (len != TS_PACKET_SIZE)
1113 return AVERROR(EIO);
1114 /* check paquet sync byte */
1115 if (buf[0] != 0x47) {
1116 /* find a new packet start */
1117 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1118 if (mpegts_resync(pb) < 0)
1119 return AVERROR_INVALIDDATA;
1120 else
1121 continue;
1122 } else {
1123 skip = raw_packet_size - TS_PACKET_SIZE;
1124 if (skip > 0)
1125 url_fskip(pb, skip);
1126 break;
1127 }
1128 }
1129 return 0;
1130}
1131
1132static int handle_packets(MpegTSContext *ts, int nb_packets)
1133{
1134 AVFormatContext *s = ts->stream;
1135 ByteIOContext *pb = s->pb;
1136 uint8_t packet[TS_PACKET_SIZE];
1137 int packet_num, ret;
1138
1139 ts->stop_parse = 0;
1140 packet_num = 0;
1141 for(;;) {
1142 if (ts->stop_parse>0)
1143 break;
1144 packet_num++;
1145 if (nb_packets != 0 && packet_num >= nb_packets)
1146 break;
1147 ret = read_packet(pb, packet, ts->raw_packet_size);
1148 if (ret != 0)
1149 return ret;
1150 handle_packet(ts, packet);
1151 }
1152 return 0;
1153}
1154
1155static int mpegts_probe(AVProbeData *p)
1156{
1157#if 1
1158 const int size= p->buf_size;
1159 int score, fec_score, dvhs_score;
1160#define CHECK_COUNT 10
1161
1162 if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1163 return -1;
1164
1165 score = analyze(p->buf, TS_PACKET_SIZE *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1166 dvhs_score = analyze(p->buf, TS_DVHS_PACKET_SIZE *CHECK_COUNT, TS_DVHS_PACKET_SIZE, NULL);
1167 fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1168// av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1169
1170// we need a clear definition for the returned score otherwise things will become messy sooner or later
1171 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1172 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1173 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1174 else return -1;
1175#else
1176 /* only use the extension for safer guess */
1177 if (match_ext(p->filename, "ts"))
1178 return AVPROBE_SCORE_MAX;
1179 else
1180 return 0;
1181#endif
1182}
1183
1184/* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1185 (-1) if not available */
1186static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1187 const uint8_t *packet)
1188{
1189 int afc, len, flags;
1190 const uint8_t *p;
1191 unsigned int v;
1192
1193 afc = (packet[3] >> 4) & 3;
1194 if (afc <= 1)
1195 return -1;
1196 p = packet + 4;
1197 len = p[0];
1198 p++;
1199 if (len == 0)
1200 return -1;
1201 flags = *p++;
1202 len--;
1203 if (!(flags & 0x10))
1204 return -1;
1205 if (len < 6)
1206 return -1;
1207 v = AV_RB32(p);
1208 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1209 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1210 return 0;
1211}
1212
1213static int mpegts_read_header(AVFormatContext *s,
1214 AVFormatParameters *ap)
1215{
1216 MpegTSContext *ts = s->priv_data;
1217 ByteIOContext *pb = s->pb;
1218 uint8_t buf[1024];
1219 int len;
1220 int64_t pos;
1221
1222 if (ap) {
1223 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1224 if(ap->mpeg2ts_raw){
1225 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1226 return -1;
1227 }
1228 }
1229
1230 /* read the first 1024 bytes to get packet size */
1231 pos = url_ftell(pb);
1232 len = get_buffer(pb, buf, sizeof(buf));
1233 if (len != sizeof(buf))
1234 goto fail;
1235 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1236 if (ts->raw_packet_size <= 0)
1237 goto fail;
1238 ts->stream = s;
1239 ts->auto_guess = 0;
1240
1241 if (s->iformat == &mpegts_demuxer) {
1242 /* normal demux */
1243
1244 /* first do a scaning to get all the services */
1245 url_fseek(pb, pos, SEEK_SET);
1246 mpegts_scan_sdt(ts);
1247
1248 mpegts_set_service(ts);
1249
1250 handle_packets(ts, s->probesize);
1251 /* if could not find service, enable auto_guess */
1252
1253 ts->auto_guess = 1;
1254
1255#ifdef DEBUG_SI
1256 av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1257#endif
1258 s->ctx_flags |= AVFMTCTX_NOHEADER;
1259 } else {
1260 AVStream *st;
1261 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1262 int64_t pcrs[2], pcr_h;
1263 int packet_count[2];
1264 uint8_t packet[TS_PACKET_SIZE];
1265
1266 /* only read packets */
1267
1268 st = av_new_stream(s, 0);
1269 if (!st)
1270 goto fail;
1271 av_set_pts_info(st, 60, 1, 27000000);
1272 st->codec->codec_type = CODEC_TYPE_DATA;
1273 st->codec->codec_id = CODEC_ID_MPEG2TS;
1274
1275 /* we iterate until we find two PCRs to estimate the bitrate */
1276 pcr_pid = -1;
1277 nb_pcrs = 0;
1278 nb_packets = 0;
1279 for(;;) {
1280 ret = read_packet(s->pb, packet, ts->raw_packet_size);
1281 if (ret < 0)
1282 return -1;
1283 pid = AV_RB16(packet + 1) & 0x1fff;
1284 if ((pcr_pid == -1 || pcr_pid == pid) &&
1285 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1286 pcr_pid = pid;
1287 packet_count[nb_pcrs] = nb_packets;
1288 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1289 nb_pcrs++;
1290 if (nb_pcrs >= 2)
1291 break;
1292 }
1293 nb_packets++;
1294 }
1295
1296 /* NOTE1: the bitrate is computed without the FEC */
1297 /* NOTE2: it is only the bitrate of the start of the stream */
1298 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1299 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1300 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1301 st->codec->bit_rate = s->bit_rate;
1302 st->start_time = ts->cur_pcr;
1303#if 0
1304 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1305 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1306#endif
1307 }
1308
1309 url_fseek(pb, pos, SEEK_SET);
1310 return 0;
1311 fail:
1312 return -1;
1313}
1314
1315#define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1316
1317static int mpegts_raw_read_packet(AVFormatContext *s,
1318 AVPacket *pkt)
1319{
1320 MpegTSContext *ts = s->priv_data;
1321 int ret, i;
1322 int64_t pcr_h, next_pcr_h, pos;
1323 int pcr_l, next_pcr_l;
1324 uint8_t pcr_buf[12];
1325
1326 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1327 return AVERROR(ENOMEM);
1328 pkt->pos= url_ftell(s->pb);
1329 ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
1330 if (ret < 0) {
1331 av_free_packet(pkt);
1332 return ret;
1333 }
1334 if (ts->mpeg2ts_compute_pcr) {
1335 /* compute exact PCR for each packet */
1336 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1337 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1338 pos = url_ftell(s->pb);
1339 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1340 url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1341 get_buffer(s->pb, pcr_buf, 12);
1342 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1343 /* XXX: not precise enough */
1344 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1345 (i + 1);
1346 break;
1347 }
1348 }
1349 url_fseek(s->pb, pos, SEEK_SET);
1350 /* no next PCR found: we use previous increment */
1351 ts->cur_pcr = pcr_h * 300 + pcr_l;
1352 }
1353 pkt->pts = ts->cur_pcr;
1354 pkt->duration = ts->pcr_incr;
1355 ts->cur_pcr += ts->pcr_incr;
1356 }
1357 pkt->stream_index = 0;
1358 return 0;
1359}
1360
1361static int mpegts_read_packet(AVFormatContext *s,
1362 AVPacket *pkt)
1363{
1364 MpegTSContext *ts = s->priv_data;
1365
1366 ts->pkt = pkt;
1367 return handle_packets(ts, 0);
1368}
1369
1370static int mpegts_read_close(AVFormatContext *s)
1371{
1372 MpegTSContext *ts = s->priv_data;
1373 int i;
1374
1375 clear_programs(ts);
1376
1377 for(i=0;i<NB_PID_MAX;i++)
1378 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1379
1380 return 0;
1381}
1382
1383static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1384 int64_t *ppos, int64_t pos_limit)
1385{
1386 MpegTSContext *ts = s->priv_data;
1387 int64_t pos, timestamp;
1388 uint8_t buf[TS_PACKET_SIZE];
1389 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1390 const int find_next= 1;
1391 pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1392 if (find_next) {
1393 for(;;) {
1394 url_fseek(s->pb, pos, SEEK_SET);
1395 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1396 return AV_NOPTS_VALUE;
1397 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1398 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1399 break;
1400 }
1401 pos += ts->raw_packet_size;
1402 }
1403 } else {
1404 for(;;) {
1405 pos -= ts->raw_packet_size;
1406 if (pos < 0)
1407 return AV_NOPTS_VALUE;
1408 url_fseek(s->pb, pos, SEEK_SET);
1409 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1410 return AV_NOPTS_VALUE;
1411 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1412 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1413 break;
1414 }
1415 }
1416 }
1417 *ppos = pos;
1418
1419 return timestamp;
1420}
1421
1422static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1423 MpegTSContext *ts = s->priv_data;
1424 uint8_t buf[TS_PACKET_SIZE];
1425 int64_t pos;
1426
1427 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1428 return -1;
1429
1430 pos= url_ftell(s->pb);
1431
1432 for(;;) {
1433 url_fseek(s->pb, pos, SEEK_SET);
1434 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1435 return -1;
1436// pid = AV_RB16(buf + 1) & 0x1fff;
1437 if(buf[1] & 0x40) break;
1438 pos += ts->raw_packet_size;
1439 }
1440 url_fseek(s->pb, pos, SEEK_SET);
1441
1442 return 0;
1443}
1444
1445/**************************************************************/
1446/* parsing functions - called from other demuxers such as RTP */
1447
1448MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1449{
1450 MpegTSContext *ts;
1451
1452 ts = av_mallocz(sizeof(MpegTSContext));
1453 if (!ts)
1454 return NULL;
1455 /* no stream case, currently used by RTP */
1456 ts->raw_packet_size = TS_PACKET_SIZE;
1457 ts->stream = s;
1458 ts->auto_guess = 1;
1459 return ts;
1460}
1461
1462/* return the consumed length if a packet was output, or -1 if no
1463 packet is output */
1464int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1465 const uint8_t *buf, int len)
1466{
1467 int len1;
1468
1469 len1 = len;
1470 ts->pkt = pkt;
1471 ts->stop_parse = 0;
1472 for(;;) {
1473 if (ts->stop_parse>0)
1474 break;
1475 if (len < TS_PACKET_SIZE)
1476 return -1;
1477 if (buf[0] != 0x47) {
1478 buf++;
1479 len--;
1480 } else {
1481 handle_packet(ts, buf);
1482 buf += TS_PACKET_SIZE;
1483 len -= TS_PACKET_SIZE;
1484 }
1485 }
1486 return len1 - len;
1487}
1488
1489void mpegts_parse_close(MpegTSContext *ts)
1490{
1491 int i;
1492
1493 for(i=0;i<NB_PID_MAX;i++)
1494 av_free(ts->pids[i]);
1495 av_free(ts);
1496}
1497
1498AVInputFormat mpegts_demuxer = {
1499 "mpegts",
1500 NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1501 sizeof(MpegTSContext),
1502 mpegts_probe,
1503 mpegts_read_header,
1504 mpegts_read_packet,
1505 mpegts_read_close,
1506 read_seek,
1507 mpegts_get_pcr,
1508 .flags = AVFMT_SHOW_IDS,
1509};
1510
1511AVInputFormat mpegtsraw_demuxer = {
1512 "mpegtsraw",
1513 NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1514 sizeof(MpegTSContext),
1515 NULL,
1516 mpegts_read_header,
1517 mpegts_raw_read_packet,
1518 mpegts_read_close,
1519 read_seek,
1520 mpegts_get_pcr,
1521 .flags = AVFMT_SHOW_IDS,
1522};
diff --git a/src/plugins/ffmpeg/libavformat/mpegts.h b/src/plugins/ffmpeg/libavformat/mpegts.h
deleted file mode 100644
index bdfc760..0000000
--- a/src/plugins/ffmpeg/libavformat/mpegts.h
+++ /dev/null
@@ -1,69 +0,0 @@
1/*
2 * MPEG2 transport stream defines
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#ifndef FFMPEG_MPEGTS_H
23#define FFMPEG_MPEGTS_H
24
25#include "avformat.h"
26
27#define TS_FEC_PACKET_SIZE 204
28#define TS_DVHS_PACKET_SIZE 192
29#define TS_PACKET_SIZE 188
30#define NB_PID_MAX 8192
31#define MAX_SECTION_SIZE 4096
32
33/* pids */
34#define PAT_PID 0x0000
35#define SDT_PID 0x0011
36
37/* table ids */
38#define PAT_TID 0x00
39#define PMT_TID 0x02
40#define SDT_TID 0x42
41
42/* descriptor ids */
43#define DVB_SUBT_DESCID 0x59
44
45#define STREAM_TYPE_VIDEO_MPEG1 0x01
46#define STREAM_TYPE_VIDEO_MPEG2 0x02
47#define STREAM_TYPE_AUDIO_MPEG1 0x03
48#define STREAM_TYPE_AUDIO_MPEG2 0x04
49#define STREAM_TYPE_PRIVATE_SECTION 0x05
50#define STREAM_TYPE_PRIVATE_DATA 0x06
51#define STREAM_TYPE_AUDIO_AAC 0x0f
52#define STREAM_TYPE_VIDEO_MPEG4 0x10
53#define STREAM_TYPE_VIDEO_H264 0x1b
54#define STREAM_TYPE_VIDEO_VC1 0xea
55
56#define STREAM_TYPE_AUDIO_AC3 0x81
57#define STREAM_TYPE_AUDIO_DTS 0x8a
58#define STREAM_TYPE_AUDIO_HDMV_DTS 0x82
59
60#define STREAM_TYPE_SUBTITLE_DVB 0x100
61
62typedef struct MpegTSContext MpegTSContext;
63
64MpegTSContext *mpegts_parse_open(AVFormatContext *s);
65int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
66 const uint8_t *buf, int len);
67void mpegts_parse_close(MpegTSContext *ts);
68
69#endif /* FFMPEG_MPEGTS_H */
diff --git a/src/plugins/ffmpeg/libavformat/mpegtsenc.c b/src/plugins/ffmpeg/libavformat/mpegtsenc.c
deleted file mode 100644
index 4a70a15..0000000
--- a/src/plugins/ffmpeg/libavformat/mpegtsenc.c
+++ /dev/null
@@ -1,696 +0,0 @@
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/crc.h"
23#include "avformat.h"
24#include "mpegts.h"
25
26/* write DVB SI sections */
27
28/*********************************************/
29/* mpegts section writer */
30
31typedef struct MpegTSSection {
32 int pid;
33 int cc;
34 void (*write_packet)(struct MpegTSSection *s, const uint8_t *packet);
35 void *opaque;
36} MpegTSSection;
37
38/* NOTE: 4 bytes must be left at the end for the crc32 */
39static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
40{
41 unsigned int crc;
42 unsigned char packet[TS_PACKET_SIZE];
43 const unsigned char *buf_ptr;
44 unsigned char *q;
45 int first, b, len1, left;
46
47 crc = bswap_32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
48 buf[len - 4] = (crc >> 24) & 0xff;
49 buf[len - 3] = (crc >> 16) & 0xff;
50 buf[len - 2] = (crc >> 8) & 0xff;
51 buf[len - 1] = (crc) & 0xff;
52
53 /* send each packet */
54 buf_ptr = buf;
55 while (len > 0) {
56 first = (buf == buf_ptr);
57 q = packet;
58 *q++ = 0x47;
59 b = (s->pid >> 8);
60 if (first)
61 b |= 0x40;
62 *q++ = b;
63 *q++ = s->pid;
64 *q++ = 0x10 | s->cc;
65 s->cc = (s->cc + 1) & 0xf;
66 if (first)
67 *q++ = 0; /* 0 offset */
68 len1 = TS_PACKET_SIZE - (q - packet);
69 if (len1 > len)
70 len1 = len;
71 memcpy(q, buf_ptr, len1);
72 q += len1;
73 /* add known padding data */
74 left = TS_PACKET_SIZE - (q - packet);
75 if (left > 0)
76 memset(q, 0xff, left);
77
78 s->write_packet(s, packet);
79
80 buf_ptr += len1;
81 len -= len1;
82 }
83}
84
85static inline void put16(uint8_t **q_ptr, int val)
86{
87 uint8_t *q;
88 q = *q_ptr;
89 *q++ = val >> 8;
90 *q++ = val;
91 *q_ptr = q;
92}
93
94static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
95 int version, int sec_num, int last_sec_num,
96 uint8_t *buf, int len)
97{
98 uint8_t section[1024], *q;
99 unsigned int tot_len;
100
101 tot_len = 3 + 5 + len + 4;
102 /* check if not too big */
103 if (tot_len > 1024)
104 return -1;
105
106 q = section;
107 *q++ = tid;
108 put16(&q, 0xb000 | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
109 put16(&q, id);
110 *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
111 *q++ = sec_num;
112 *q++ = last_sec_num;
113 memcpy(q, buf, len);
114
115 mpegts_write_section(s, section, tot_len);
116 return 0;
117}
118
119/*********************************************/
120/* mpegts writer */
121
122#define DEFAULT_PMT_START_PID 0x1000
123#define DEFAULT_START_PID 0x0100
124#define DEFAULT_PROVIDER_NAME "FFmpeg"
125#define DEFAULT_SERVICE_NAME "Service01"
126
127/* default network id, transport stream and service identifiers */
128#define DEFAULT_ONID 0x0001
129#define DEFAULT_TSID 0x0001
130#define DEFAULT_SID 0x0001
131
132/* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
133#define DEFAULT_PES_HEADER_FREQ 16
134#define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
135
136/* we retransmit the SI info at this rate */
137#define SDT_RETRANS_TIME 500
138#define PAT_RETRANS_TIME 100
139#define PCR_RETRANS_TIME 20
140
141typedef struct MpegTSWriteStream {
142 struct MpegTSService *service;
143 int pid; /* stream associated pid */
144 int cc;
145 int payload_index;
146 int64_t payload_pts;
147 int64_t payload_dts;
148 uint8_t payload[DEFAULT_PES_PAYLOAD_SIZE];
149} MpegTSWriteStream;
150
151typedef struct MpegTSService {
152 MpegTSSection pmt; /* MPEG2 pmt table context */
153 int sid; /* service ID */
154 char *name;
155 char *provider_name;
156 int pcr_pid;
157 int pcr_packet_count;
158 int pcr_packet_freq;
159} MpegTSService;
160
161typedef struct MpegTSWrite {
162 MpegTSSection pat; /* MPEG2 pat table */
163 MpegTSSection sdt; /* MPEG2 sdt table context */
164 MpegTSService **services;
165 int sdt_packet_count;
166 int sdt_packet_freq;
167 int pat_packet_count;
168 int pat_packet_freq;
169 int nb_services;
170 int onid;
171 int tsid;
172} MpegTSWrite;
173
174static void mpegts_write_pat(AVFormatContext *s)
175{
176 MpegTSWrite *ts = s->priv_data;
177 MpegTSService *service;
178 uint8_t data[1012], *q;
179 int i;
180
181 q = data;
182 for(i = 0; i < ts->nb_services; i++) {
183 service = ts->services[i];
184 put16(&q, service->sid);
185 put16(&q, 0xe000 | service->pmt.pid);
186 }
187 mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, 0, 0, 0,
188 data, q - data);
189}
190
191static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
192{
193 // MpegTSWrite *ts = s->priv_data;
194 uint8_t data[1012], *q, *desc_length_ptr, *program_info_length_ptr;
195 int val, stream_type, i;
196
197 q = data;
198 put16(&q, 0xe000 | service->pcr_pid);
199
200 program_info_length_ptr = q;
201 q += 2; /* patched after */
202
203 /* put program info here */
204
205 val = 0xf000 | (q - program_info_length_ptr - 2);
206 program_info_length_ptr[0] = val >> 8;
207 program_info_length_ptr[1] = val;
208
209 for(i = 0; i < s->nb_streams; i++) {
210 AVStream *st = s->streams[i];
211 MpegTSWriteStream *ts_st = st->priv_data;
212 switch(st->codec->codec_id) {
213 case CODEC_ID_MPEG1VIDEO:
214 case CODEC_ID_MPEG2VIDEO:
215 stream_type = STREAM_TYPE_VIDEO_MPEG2;
216 break;
217 case CODEC_ID_MPEG4:
218 stream_type = STREAM_TYPE_VIDEO_MPEG4;
219 break;
220 case CODEC_ID_H264:
221 stream_type = STREAM_TYPE_VIDEO_H264;
222 break;
223 case CODEC_ID_MP2:
224 case CODEC_ID_MP3:
225 stream_type = STREAM_TYPE_AUDIO_MPEG1;
226 break;
227 case CODEC_ID_AAC:
228 stream_type = STREAM_TYPE_AUDIO_AAC;
229 break;
230 case CODEC_ID_AC3:
231 stream_type = STREAM_TYPE_AUDIO_AC3;
232 break;
233 default:
234 stream_type = STREAM_TYPE_PRIVATE_DATA;
235 break;
236 }
237 *q++ = stream_type;
238 put16(&q, 0xe000 | ts_st->pid);
239 desc_length_ptr = q;
240 q += 2; /* patched after */
241
242 /* write optional descriptors here */
243 switch(st->codec->codec_type) {
244 case CODEC_TYPE_AUDIO:
245 if (strlen(st->language) == 3) {
246 *q++ = 0x0a; /* ISO 639 language descriptor */
247 *q++ = 4;
248 *q++ = st->language[0];
249 *q++ = st->language[1];
250 *q++ = st->language[2];
251 *q++ = 0; /* undefined type */
252 }
253 break;
254 case CODEC_TYPE_SUBTITLE:
255 {
256 const char *language;
257 language = st->language;
258 if (strlen(language) != 3)
259 language = "eng";
260 *q++ = 0x59;
261 *q++ = 8;
262 *q++ = language[0];
263 *q++ = language[1];
264 *q++ = language[2];
265 *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */
266 put16(&q, 1); /* page id */
267 put16(&q, 1); /* ancillary page id */
268 }
269 break;
270 }
271
272 val = 0xf000 | (q - desc_length_ptr - 2);
273 desc_length_ptr[0] = val >> 8;
274 desc_length_ptr[1] = val;
275 }
276 mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,
277 data, q - data);
278}
279
280/* NOTE: str == NULL is accepted for an empty string */
281static void putstr8(uint8_t **q_ptr, const char *str)
282{
283 uint8_t *q;
284 int len;
285
286 q = *q_ptr;
287 if (!str)
288 len = 0;
289 else
290 len = strlen(str);
291 *q++ = len;
292 memcpy(q, str, len);
293 q += len;
294 *q_ptr = q;
295}
296
297static void mpegts_write_sdt(AVFormatContext *s)
298{
299 MpegTSWrite *ts = s->priv_data;
300 MpegTSService *service;
301 uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
302 int i, running_status, free_ca_mode, val;
303
304 q = data;
305 put16(&q, ts->onid);
306 *q++ = 0xff;
307 for(i = 0; i < ts->nb_services; i++) {
308 service = ts->services[i];
309 put16(&q, service->sid);
310 *q++ = 0xfc | 0x00; /* currently no EIT info */
311 desc_list_len_ptr = q;
312 q += 2;
313 running_status = 4; /* running */
314 free_ca_mode = 0;
315
316 /* write only one descriptor for the service name and provider */
317 *q++ = 0x48;
318 desc_len_ptr = q;
319 q++;
320 *q++ = 0x01; /* digital television service */
321 putstr8(&q, service->provider_name);
322 putstr8(&q, service->name);
323 desc_len_ptr[0] = q - desc_len_ptr - 1;
324
325 /* fill descriptor length */
326 val = (running_status << 13) | (free_ca_mode << 12) |
327 (q - desc_list_len_ptr - 2);
328 desc_list_len_ptr[0] = val >> 8;
329 desc_list_len_ptr[1] = val;
330 }
331 mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, 0, 0, 0,
332 data, q - data);
333}
334
335static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
336 int sid,
337 const char *provider_name,
338 const char *name)
339{
340 MpegTSService *service;
341
342 service = av_mallocz(sizeof(MpegTSService));
343 if (!service)
344 return NULL;
345 service->pmt.pid = DEFAULT_PMT_START_PID + ts->nb_services - 1;
346 service->sid = sid;
347 service->provider_name = av_strdup(provider_name);
348 service->name = av_strdup(name);
349 service->pcr_pid = 0x1fff;
350 dynarray_add(&ts->services, &ts->nb_services, service);
351 return service;
352}
353
354static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
355{
356 AVFormatContext *ctx = s->opaque;
357 put_buffer(ctx->pb, packet, TS_PACKET_SIZE);
358}
359
360static int mpegts_write_header(AVFormatContext *s)
361{
362 MpegTSWrite *ts = s->priv_data;
363 MpegTSWriteStream *ts_st;
364 MpegTSService *service;
365 AVStream *st;
366 int i, total_bit_rate;
367 const char *service_name;
368
369 ts->tsid = DEFAULT_TSID;
370 ts->onid = DEFAULT_ONID;
371 /* allocate a single DVB service */
372 service_name = s->title;
373 if (service_name[0] == '\0')
374 service_name = DEFAULT_SERVICE_NAME;
375 service = mpegts_add_service(ts, DEFAULT_SID,
376 DEFAULT_PROVIDER_NAME, service_name);
377 service->pmt.write_packet = section_write_packet;
378 service->pmt.opaque = s;
379
380 ts->pat.pid = PAT_PID;
381 ts->pat.cc = 0;
382 ts->pat.write_packet = section_write_packet;
383 ts->pat.opaque = s;
384
385 ts->sdt.pid = SDT_PID;
386 ts->sdt.cc = 0;
387 ts->sdt.write_packet = section_write_packet;
388 ts->sdt.opaque = s;
389
390 /* assign pids to each stream */
391 total_bit_rate = 0;
392 for(i = 0;i < s->nb_streams; i++) {
393 st = s->streams[i];
394 ts_st = av_mallocz(sizeof(MpegTSWriteStream));
395 if (!ts_st)
396 goto fail;
397 st->priv_data = ts_st;
398 ts_st->service = service;
399 ts_st->pid = DEFAULT_START_PID + i;
400 ts_st->payload_pts = AV_NOPTS_VALUE;
401 ts_st->payload_dts = AV_NOPTS_VALUE;
402 /* update PCR pid by using the first video stream */
403 if (st->codec->codec_type == CODEC_TYPE_VIDEO &&
404 service->pcr_pid == 0x1fff)
405 service->pcr_pid = ts_st->pid;
406 total_bit_rate += st->codec->bit_rate;
407 }
408
409 /* if no video stream, use the first stream as PCR */
410 if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
411 ts_st = s->streams[0]->priv_data;
412 service->pcr_pid = ts_st->pid;
413 }
414
415 if (total_bit_rate <= 8 * 1024)
416 total_bit_rate = 8 * 1024;
417 service->pcr_packet_freq = (total_bit_rate * PCR_RETRANS_TIME) /
418 (TS_PACKET_SIZE * 8 * 1000);
419 ts->sdt_packet_freq = (total_bit_rate * SDT_RETRANS_TIME) /
420 (TS_PACKET_SIZE * 8 * 1000);
421 ts->pat_packet_freq = (total_bit_rate * PAT_RETRANS_TIME) /
422 (TS_PACKET_SIZE * 8 * 1000);
423#if 0
424 printf("%d %d %d\n",
425 total_bit_rate, ts->sdt_packet_freq, ts->pat_packet_freq);
426#endif
427
428 /* write info at the start of the file, so that it will be fast to
429 find them */
430 mpegts_write_sdt(s);
431 mpegts_write_pat(s);
432 for(i = 0; i < ts->nb_services; i++) {
433 mpegts_write_pmt(s, ts->services[i]);
434 }
435 put_flush_packet(s->pb);
436
437 return 0;
438
439 fail:
440 for(i = 0;i < s->nb_streams; i++) {
441 st = s->streams[i];
442 av_free(st->priv_data);
443 }
444 return -1;
445}
446
447/* send SDT, PAT and PMT tables regulary */
448static void retransmit_si_info(AVFormatContext *s)
449{
450 MpegTSWrite *ts = s->priv_data;
451 int i;
452
453 if (++ts->sdt_packet_count == ts->sdt_packet_freq) {
454 ts->sdt_packet_count = 0;
455 mpegts_write_sdt(s);
456 }
457 if (++ts->pat_packet_count == ts->pat_packet_freq) {
458 ts->pat_packet_count = 0;
459 mpegts_write_pat(s);
460 for(i = 0; i < ts->nb_services; i++) {
461 mpegts_write_pmt(s, ts->services[i]);
462 }
463 }
464}
465
466static void write_pts(uint8_t *q, int fourbits, int64_t pts)
467{
468 int val;
469
470 val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
471 *q++ = val;
472 val = (((pts >> 15) & 0x7fff) << 1) | 1;
473 *q++ = val >> 8;
474 *q++ = val;
475 val = (((pts) & 0x7fff) << 1) | 1;
476 *q++ = val >> 8;
477 *q++ = val;
478}
479
480/* NOTE: pes_data contains all the PES packet */
481static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
482 const uint8_t *payload, int payload_size,
483 int64_t pts, int64_t dts)
484{
485 MpegTSWriteStream *ts_st = st->priv_data;
486 uint8_t buf[TS_PACKET_SIZE];
487 uint8_t *q;
488 int val, is_start, len, header_len, write_pcr, private_code, flags;
489 int afc_len, stuffing_len;
490 int64_t pcr = -1; /* avoid warning */
491
492 is_start = 1;
493 while (payload_size > 0) {
494 retransmit_si_info(s);
495
496 write_pcr = 0;
497 if (ts_st->pid == ts_st->service->pcr_pid) {
498 ts_st->service->pcr_packet_count++;
499 if (ts_st->service->pcr_packet_count >=
500 ts_st->service->pcr_packet_freq) {
501 ts_st->service->pcr_packet_count = 0;
502 write_pcr = 1;
503 /* XXX: this is incorrect, but at least we have a PCR
504 value */
505 pcr = pts;
506 }
507 }
508
509 /* prepare packet header */
510 q = buf;
511 *q++ = 0x47;
512 val = (ts_st->pid >> 8);
513 if (is_start)
514 val |= 0x40;
515 *q++ = val;
516 *q++ = ts_st->pid;
517 *q++ = 0x10 | ts_st->cc | (write_pcr ? 0x20 : 0);
518 ts_st->cc = (ts_st->cc + 1) & 0xf;
519 if (write_pcr) {
520 *q++ = 7; /* AFC length */
521 *q++ = 0x10; /* flags: PCR present */
522 *q++ = pcr >> 25;
523 *q++ = pcr >> 17;
524 *q++ = pcr >> 9;
525 *q++ = pcr >> 1;
526 *q++ = (pcr & 1) << 7;
527 *q++ = 0;
528 }
529 if (is_start) {
530 /* write PES header */
531 *q++ = 0x00;
532 *q++ = 0x00;
533 *q++ = 0x01;
534 private_code = 0;
535 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
536 *q++ = 0xe0;
537 } else if (st->codec->codec_type == CODEC_TYPE_AUDIO &&
538 (st->codec->codec_id == CODEC_ID_MP2 ||
539 st->codec->codec_id == CODEC_ID_MP3)) {
540 *q++ = 0xc0;
541 } else {
542 *q++ = 0xbd;
543 if (st->codec->codec_type == CODEC_TYPE_SUBTITLE) {
544 private_code = 0x20;
545 }
546 }
547 header_len = 0;
548 flags = 0;
549 if (pts != AV_NOPTS_VALUE) {
550 header_len += 5;
551 flags |= 0x80;
552 }
553 if (dts != AV_NOPTS_VALUE) {
554 header_len += 5;
555 flags |= 0x40;
556 }
557 len = payload_size + header_len + 3;
558 if (private_code != 0)
559 len++;
560 *q++ = len >> 8;
561 *q++ = len;
562 val = 0x80;
563 /* data alignment indicator is required for subtitle data */
564 if (st->codec->codec_type == CODEC_TYPE_SUBTITLE)
565 val |= 0x04;
566 *q++ = val;
567 *q++ = flags;
568 *q++ = header_len;
569 if (pts != AV_NOPTS_VALUE) {
570 write_pts(q, flags >> 6, pts);
571 q += 5;
572 }
573 if (dts != AV_NOPTS_VALUE) {
574 write_pts(q, 1, dts);
575 q += 5;
576 }
577 if (private_code != 0)
578 *q++ = private_code;
579 is_start = 0;
580 }
581 /* header size */
582 header_len = q - buf;
583 /* data len */
584 len = TS_PACKET_SIZE - header_len;
585 if (len > payload_size)
586 len = payload_size;
587 stuffing_len = TS_PACKET_SIZE - header_len - len;
588 if (stuffing_len > 0) {
589 /* add stuffing with AFC */
590 if (buf[3] & 0x20) {
591 /* stuffing already present: increase its size */
592 afc_len = buf[4] + 1;
593 memmove(buf + 4 + afc_len + stuffing_len,
594 buf + 4 + afc_len,
595 header_len - (4 + afc_len));
596 buf[4] += stuffing_len;
597 memset(buf + 4 + afc_len, 0xff, stuffing_len);
598 } else {
599 /* add stuffing */
600 memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
601 buf[3] |= 0x20;
602 buf[4] = stuffing_len - 1;
603 if (stuffing_len >= 2) {
604 buf[5] = 0x00;
605 memset(buf + 6, 0xff, stuffing_len - 2);
606 }
607 }
608 }
609 memcpy(buf + TS_PACKET_SIZE - len, payload, len);
610 payload += len;
611 payload_size -= len;
612 put_buffer(s->pb, buf, TS_PACKET_SIZE);
613 }
614 put_flush_packet(s->pb);
615}
616
617static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
618{
619 AVStream *st = s->streams[pkt->stream_index];
620 int size= pkt->size;
621 uint8_t *buf= pkt->data;
622 MpegTSWriteStream *ts_st = st->priv_data;
623 int len, max_payload_size;
624
625 if (st->codec->codec_type == CODEC_TYPE_SUBTITLE) {
626 /* for subtitle, a single PES packet must be generated */
627 mpegts_write_pes(s, st, buf, size, pkt->pts, AV_NOPTS_VALUE);
628 return 0;
629 }
630
631 max_payload_size = DEFAULT_PES_PAYLOAD_SIZE;
632 while (size > 0) {
633 len = max_payload_size - ts_st->payload_index;
634 if (len > size)
635 len = size;
636 memcpy(ts_st->payload + ts_st->payload_index, buf, len);
637 buf += len;
638 size -= len;
639 ts_st->payload_index += len;
640 if (ts_st->payload_pts == AV_NOPTS_VALUE)
641 ts_st->payload_pts = pkt->pts;
642 if (ts_st->payload_dts == AV_NOPTS_VALUE)
643 ts_st->payload_dts = pkt->dts;
644 if (ts_st->payload_index >= max_payload_size) {
645 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
646 ts_st->payload_pts, ts_st->payload_dts);
647 ts_st->payload_pts = AV_NOPTS_VALUE;
648 ts_st->payload_dts = AV_NOPTS_VALUE;
649 ts_st->payload_index = 0;
650 }
651 }
652 return 0;
653}
654
655static int mpegts_write_end(AVFormatContext *s)
656{
657 MpegTSWrite *ts = s->priv_data;
658 MpegTSWriteStream *ts_st;
659 MpegTSService *service;
660 AVStream *st;
661 int i;
662
663 /* flush current packets */
664 for(i = 0; i < s->nb_streams; i++) {
665 st = s->streams[i];
666 ts_st = st->priv_data;
667 if (ts_st->payload_index > 0) {
668 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
669 ts_st->payload_pts, ts_st->payload_dts);
670 }
671 }
672 put_flush_packet(s->pb);
673
674 for(i = 0; i < ts->nb_services; i++) {
675 service = ts->services[i];
676 av_freep(&service->provider_name);
677 av_freep(&service->name);
678 av_free(service);
679 }
680 av_free(ts->services);
681
682 return 0;
683}
684
685AVOutputFormat mpegts_muxer = {
686 "mpegts",
687 NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
688 "video/x-mpegts",
689 "ts,m2t",
690 sizeof(MpegTSWrite),
691 CODEC_ID_MP2,
692 CODEC_ID_MPEG2VIDEO,
693 mpegts_write_header,
694 mpegts_write_packet,
695 mpegts_write_end,
696};
diff --git a/src/plugins/ffmpeg/libavformat/mpjpeg.c b/src/plugins/ffmpeg/libavformat/mpjpeg.c
deleted file mode 100644
index ecaad55..0000000
--- a/src/plugins/ffmpeg/libavformat/mpjpeg.c
+++ /dev/null
@@ -1,67 +0,0 @@
1/*
2 * Multipart JPEG format
3 * Copyright (c) 2000, 2001, 2002, 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#include "avformat.h"
22
23/* Multipart JPEG */
24
25#define BOUNDARY_TAG "ffserver"
26
27static int mpjpeg_write_header(AVFormatContext *s)
28{
29 uint8_t buf1[256];
30
31 snprintf(buf1, sizeof(buf1), "--%s\n", BOUNDARY_TAG);
32 put_buffer(s->pb, buf1, strlen(buf1));
33 put_flush_packet(s->pb);
34 return 0;
35}
36
37static int mpjpeg_write_packet(AVFormatContext *s, AVPacket *pkt)
38{
39 uint8_t buf1[256];
40
41 snprintf(buf1, sizeof(buf1), "Content-type: image/jpeg\n\n");
42 put_buffer(s->pb, buf1, strlen(buf1));
43 put_buffer(s->pb, pkt->data, pkt->size);
44
45 snprintf(buf1, sizeof(buf1), "\n--%s\n", BOUNDARY_TAG);
46 put_buffer(s->pb, buf1, strlen(buf1));
47 put_flush_packet(s->pb);
48 return 0;
49}
50
51static int mpjpeg_write_trailer(AVFormatContext *s)
52{
53 return 0;
54}
55
56AVOutputFormat mpjpeg_muxer = {
57 "mpjpeg",
58 NULL_IF_CONFIG_SMALL("Mime multipart JPEG format"),
59 "multipart/x-mixed-replace;boundary=" BOUNDARY_TAG,
60 "mjpg",
61 0,
62 CODEC_ID_NONE,
63 CODEC_ID_MJPEG,
64 mpjpeg_write_header,
65 mpjpeg_write_packet,
66 mpjpeg_write_trailer,
67};
diff --git a/src/plugins/ffmpeg/libavformat/msnwc_tcp.c b/src/plugins/ffmpeg/libavformat/msnwc_tcp.c
deleted file mode 100644
index 34ab9d9..0000000
--- a/src/plugins/ffmpeg/libavformat/msnwc_tcp.c
+++ /dev/null
@@ -1,140 +0,0 @@
1/*
2 * Copyright (C) 2008 Ramiro Polla <ramiro@lisha.ufsc.br>
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21#include "libavcodec/bytestream.h"
22#include "avformat.h"
23
24#define HEADER_SIZE 24
25
26/*
27 * Header structure:
28 * uint16_t ss; // struct size
29 * uint16_t width; // frame width
30 * uint16_t height; // frame height
31 * uint16_t ff; // keyframe + some other info(???)
32 * uint32_t size; // size of data
33 * uint32_t fourcc; // ML20
34 * uint32_t u3; // ?
35 * uint32_t ts; // time
36 */
37
38static int msnwc_tcp_probe(AVProbeData *p)
39{
40 int i;
41
42 for(i = 0 ; i + HEADER_SIZE <= p->buf_size ; i++) {
43 uint16_t width, height;
44 uint32_t fourcc;
45 const uint8_t *bytestream = p->buf+i;
46
47 if(bytestream_get_le16(&bytestream) != HEADER_SIZE)
48 continue;
49 width = bytestream_get_le16(&bytestream);
50 height = bytestream_get_le16(&bytestream);
51 if(!(width==320 && height==240) && !(width==160 && height==120))
52 continue;
53 bytestream += 2; // keyframe
54 bytestream += 4; // size
55 fourcc = bytestream_get_le32(&bytestream);
56 if(fourcc != MKTAG('M', 'L', '2', '0'))
57 continue;
58
59 if(i) {
60 if(i < 14) /* starts with SwitchBoard connection info */
61 return AVPROBE_SCORE_MAX / 2;
62 else /* starts in the middle of stream */
63 return AVPROBE_SCORE_MAX / 3;
64 } else {
65 return AVPROBE_SCORE_MAX;
66 }
67 }
68
69 return -1;
70}
71
72static int msnwc_tcp_read_header(AVFormatContext *ctx, AVFormatParameters *ap)
73{
74 ByteIOContext *pb = ctx->pb;
75 AVCodecContext *codec;
76 AVStream *st;
77
78 st = av_new_stream(ctx, 0);
79 if(!st)
80 return AVERROR_NOMEM;
81
82 codec = st->codec;
83 codec->codec_type = CODEC_TYPE_VIDEO;
84 codec->codec_id = CODEC_ID_MIMIC;
85 codec->codec_tag = MKTAG('M', 'L', '2', '0');
86
87 av_set_pts_info(st, 32, 1, 1000);
88
89 /* Some files start with "connected\r\n\r\n".
90 * So skip until we find the first byte of struct size */
91 while(get_byte(pb) != HEADER_SIZE && !url_feof(pb));
92
93 if(url_feof(pb)) {
94 av_log(ctx, AV_LOG_ERROR, "Could not find valid start.");
95 return -1;
96 }
97
98 return 0;
99}
100
101static int msnwc_tcp_read_packet(AVFormatContext *ctx, AVPacket *pkt)
102{
103 ByteIOContext *pb = ctx->pb;
104 uint16_t keyframe;
105 uint32_t size, timestamp;
106
107 url_fskip(pb, 1); /* one byte has been read ahead */
108 url_fskip(pb, 2);
109 url_fskip(pb, 2);
110 keyframe = get_le16(pb);
111 size = get_le32(pb);
112 url_fskip(pb, 4);
113 url_fskip(pb, 4);
114 timestamp = get_le32(pb);
115
116 if(!size || av_get_packet(pb, pkt, size) != size)
117 return -1;
118
119 url_fskip(pb, 1); /* Read ahead one byte of struct size like read_header */
120
121 pkt->pts = timestamp;
122 pkt->dts = timestamp;
123 pkt->stream_index = 0;
124
125 /* Some aMsn generated videos (or was it Mercury Messenger?) don't set
126 * this bit and rely on the codec to get keyframe information */
127 if(keyframe&1)
128 pkt->flags |= PKT_FLAG_KEY;
129
130 return HEADER_SIZE + size;
131}
132
133AVInputFormat msnwc_tcp_demuxer = {
134 "msnwctcp",
135 NULL_IF_CONFIG_SMALL("MSN TCP Webcam stream"),
136 0,
137 msnwc_tcp_probe,
138 msnwc_tcp_read_header,
139 msnwc_tcp_read_packet,
140};
diff --git a/src/plugins/ffmpeg/libavformat/mtv.c b/src/plugins/ffmpeg/libavformat/mtv.c
deleted file mode 100644
index d97b9cd..0000000
--- a/src/plugins/ffmpeg/libavformat/mtv.c
+++ /dev/null
@@ -1,181 +0,0 @@
1/*
2 * mtv demuxer
3 * Copyright (c) 2006 Reynaldo H. Verdejo Pinochet
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/**
23 * @file mtv.c
24 * MTV demuxer.
25 */
26
27#include "libavutil/bswap.h"
28#include "avformat.h"
29
30#define MTV_ASUBCHUNK_DATA_SIZE 500
31#define MTV_HEADER_SIZE 512
32#define MTV_AUDIO_PADDING_SIZE 12
33#define AUDIO_SAMPLING_RATE 44100
34#define VIDEO_SID 0
35#define AUDIO_SID 1
36
37typedef struct MTVDemuxContext {
38
39 unsigned int file_size; ///< filesize, not always right
40 unsigned int segments; ///< number of 512 byte segments
41 unsigned int audio_identifier; ///< 'MP3' on all files I have seen
42 unsigned int audio_br; ///< bitrate of audio chanel (mp3)
43 unsigned int img_colorfmt; ///< frame colorfmt rgb 565/555
44 unsigned int img_bpp; ///< frame bits per pixel
45 unsigned int img_width; //
46 unsigned int img_height; //
47 unsigned int img_segment_size; ///< size of image segment
48 unsigned int video_fps; //
49 unsigned int full_segment_size;
50
51} MTVDemuxContext;
52
53static int mtv_probe(AVProbeData *p)
54{
55 /* Magic is 'AMV' */
56
57 if(*(p->buf) != 'A' || *(p->buf+1) != 'M' || *(p->buf+2) != 'V')
58 return 0;
59
60 return AVPROBE_SCORE_MAX;
61}
62
63static int mtv_read_header(AVFormatContext *s, AVFormatParameters *ap)
64{
65 MTVDemuxContext *mtv = s->priv_data;
66 ByteIOContext *pb = s->pb;
67 AVStream *st;
68 unsigned int audio_subsegments;
69
70
71 url_fskip(pb, 3);
72 mtv->file_size = get_le32(pb);
73 mtv->segments = get_le32(pb);
74 url_fskip(pb, 32);
75 mtv->audio_identifier = get_le24(pb);
76 mtv->audio_br = get_le16(pb);
77 mtv->img_colorfmt = get_le24(pb);
78 mtv->img_bpp = get_byte(pb);
79 mtv->img_width = get_le16(pb);
80 mtv->img_height = get_le16(pb);
81 mtv->img_segment_size = get_le16(pb);
82 url_fskip(pb, 4);
83 audio_subsegments = get_le16(pb);
84 mtv->full_segment_size =
85 audio_subsegments * (MTV_AUDIO_PADDING_SIZE + MTV_ASUBCHUNK_DATA_SIZE) +
86 mtv->img_segment_size;
87 mtv->video_fps = (mtv->audio_br / 4) / audio_subsegments;
88
89 /* FIXME Add sanity check here */
90
91 /* all systems go! init decoders */
92
93 /* video - raw rgb565 */
94
95 st = av_new_stream(s, VIDEO_SID);
96 if(!st)
97 return AVERROR(ENOMEM);
98
99 av_set_pts_info(st, 64, 1, mtv->video_fps);
100 st->codec->codec_type = CODEC_TYPE_VIDEO;
101 st->codec->codec_id = CODEC_ID_RAWVIDEO;
102 st->codec->codec_tag = MKTAG('R', 'G', 'B', mtv->img_bpp);
103 st->codec->width = mtv->img_width;
104 st->codec->height = mtv->img_height;
105 st->codec->bits_per_sample = mtv->img_bpp;
106 st->codec->sample_rate = mtv->video_fps;
107
108 /* audio - mp3 */
109
110 st = av_new_stream(s, AUDIO_SID);
111 if(!st)
112 return AVERROR(ENOMEM);
113
114 av_set_pts_info(st, 64, 1, AUDIO_SAMPLING_RATE);
115 st->codec->codec_type = CODEC_TYPE_AUDIO;
116 st->codec->codec_id = CODEC_ID_MP3;
117 st->codec->bit_rate = mtv->audio_br;
118 st->need_parsing = AVSTREAM_PARSE_FULL;
119
120 /* Jump over header */
121
122 if(url_fseek(pb, MTV_HEADER_SIZE, SEEK_SET) != MTV_HEADER_SIZE)
123 return AVERROR(EIO);
124
125 return 0;
126
127}
128
129static int mtv_read_packet(AVFormatContext *s, AVPacket *pkt)
130{
131 MTVDemuxContext *mtv = s->priv_data;
132 ByteIOContext *pb = s->pb;
133 int ret;
134#ifndef WORDS_BIGENDIAN
135 int i;
136#endif
137
138 ret = 0;
139
140 if((url_ftell(pb) - s->data_offset + mtv->img_segment_size) % mtv->full_segment_size)
141 {
142 url_fskip(pb, MTV_AUDIO_PADDING_SIZE);
143
144 ret = av_get_packet(pb, pkt, MTV_ASUBCHUNK_DATA_SIZE);
145 if(ret != MTV_ASUBCHUNK_DATA_SIZE)
146 return AVERROR(EIO);
147
148 pkt->pos -= MTV_AUDIO_PADDING_SIZE;
149 pkt->stream_index = AUDIO_SID;
150
151 }else
152 {
153 ret = av_get_packet(pb, pkt, mtv->img_segment_size);
154 if(ret != mtv->img_segment_size)
155 return AVERROR(EIO);
156
157#ifndef WORDS_BIGENDIAN
158
159 /* pkt->data is GGGRRRR BBBBBGGG
160 * and we need RRRRRGGG GGGBBBBB
161 * for PIX_FMT_RGB565 so here we
162 * just swap bytes as they come
163 */
164
165 for(i=0;i<mtv->img_segment_size/2;i++)
166 *((uint16_t *)pkt->data+i) = bswap_16(*((uint16_t *)pkt->data+i));
167#endif
168 pkt->stream_index = VIDEO_SID;
169 }
170
171 return ret;
172}
173
174AVInputFormat mtv_demuxer = {
175 "MTV",
176 NULL_IF_CONFIG_SMALL("MTV format"),
177 sizeof(MTVDemuxContext),
178 mtv_probe,
179 mtv_read_header,
180 mtv_read_packet,
181};
diff --git a/src/plugins/ffmpeg/libavformat/mvi.c b/src/plugins/ffmpeg/libavformat/mvi.c
deleted file mode 100644
index 03d4a5d..0000000
--- a/src/plugins/ffmpeg/libavformat/mvi.c
+++ /dev/null
@@ -1,135 +0,0 @@
1/*
2 * Motion Pixels MVI Demuxer
3 * Copyright (c) 2008 Gregory Montoir (cyx@users.sourceforge.net)
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 "avformat.h"
23
24#define MVI_FRAC_BITS 10
25
26#define MVI_AUDIO_STREAM_INDEX 0
27#define MVI_VIDEO_STREAM_INDEX 1
28
29typedef struct MviDemuxContext {
30 unsigned int (*get_int)(ByteIOContext *);
31 uint32_t audio_data_size;
32 uint64_t audio_size_counter;
33 uint64_t audio_frame_size;
34 int audio_size_left;
35 int video_frame_size;
36} MviDemuxContext;
37
38static int read_header(AVFormatContext *s, AVFormatParameters *ap)
39{
40 MviDemuxContext *mvi = s->priv_data;
41 ByteIOContext *pb = s->pb;
42 AVStream *ast, *vst;
43 unsigned int version, frames_count, msecs_per_frame, player_version;
44
45 ast = av_new_stream(s, 0);
46 if (!ast)
47 return AVERROR(ENOMEM);
48
49 vst = av_new_stream(s, 0);
50 if (!vst)
51 return AVERROR(ENOMEM);
52
53 vst->codec->extradata_size = 2;
54 vst->codec->extradata = av_mallocz(2 + FF_INPUT_BUFFER_PADDING_SIZE);
55
56 version = get_byte(pb);
57 vst->codec->extradata[0] = get_byte(pb);
58 vst->codec->extradata[1] = get_byte(pb);
59 frames_count = get_le32(pb);
60 msecs_per_frame = get_le32(pb);
61 vst->codec->width = get_le16(pb);
62 vst->codec->height = get_le16(pb);
63 get_byte(pb);
64 ast->codec->sample_rate = get_le16(pb);
65 mvi->audio_data_size = get_le32(pb);
66 get_byte(pb);
67 player_version = get_le32(pb);
68 get_le16(pb);
69 get_byte(pb);
70
71 if (frames_count == 0 || mvi->audio_data_size == 0)
72 return AVERROR_INVALIDDATA;
73
74 if (version != 7 || player_version > 213) {
75 av_log(s, AV_LOG_ERROR, "unhandled version (%d,%d)\n", version, player_version);
76 return AVERROR_INVALIDDATA;
77 }
78
79 av_set_pts_info(ast, 64, 1, ast->codec->sample_rate);
80 ast->codec->codec_type = CODEC_TYPE_AUDIO;
81 ast->codec->codec_id = CODEC_ID_PCM_U8;
82 ast->codec->channels = 1;
83 ast->codec->bits_per_sample = 8;
84 ast->codec->bit_rate = ast->codec->sample_rate * 8;
85
86 av_set_pts_info(vst, 64, msecs_per_frame, 1000000);
87 vst->codec->codec_type = CODEC_TYPE_VIDEO;
88 vst->codec->codec_id = CODEC_ID_MOTIONPIXELS;
89 vst->codec->pix_fmt = PIX_FMT_RGB555;
90
91 mvi->get_int = (vst->codec->width * vst->codec->height < (1 << 16)) ? get_le16 : get_le24;
92
93 mvi->audio_frame_size = ((uint64_t)mvi->audio_data_size << MVI_FRAC_BITS) / frames_count;
94 mvi->audio_size_counter = (ast->codec->sample_rate * 830 / mvi->audio_frame_size - 1) * mvi->audio_frame_size;
95 mvi->audio_size_left = mvi->audio_data_size;
96
97 return 0;
98}
99
100static int read_packet(AVFormatContext *s, AVPacket *pkt)
101{
102 int ret, count;
103 MviDemuxContext *mvi = s->priv_data;
104 ByteIOContext *pb = s->pb;
105
106 if (mvi->video_frame_size == 0) {
107 mvi->video_frame_size = (mvi->get_int)(pb);
108 if (mvi->audio_size_left == 0)
109 return AVERROR(EIO);
110 count = (mvi->audio_size_counter + mvi->audio_frame_size + 512) >> MVI_FRAC_BITS;
111 if (count > mvi->audio_size_left)
112 count = mvi->audio_size_left;
113 if ((ret = av_get_packet(pb, pkt, count)) < 0)
114 return ret;
115 pkt->stream_index = MVI_AUDIO_STREAM_INDEX;
116 mvi->audio_size_left -= count;
117 mvi->audio_size_counter += mvi->audio_frame_size - (count << MVI_FRAC_BITS);
118 } else {
119 if ((ret = av_get_packet(pb, pkt, mvi->video_frame_size)) < 0)
120 return ret;
121 pkt->stream_index = MVI_VIDEO_STREAM_INDEX;
122 mvi->video_frame_size = 0;
123 }
124 return 0;
125}
126
127AVInputFormat mvi_demuxer = {
128 "mvi",
129 NULL_IF_CONFIG_SMALL("Motion Pixels MVI format"),
130 sizeof(MviDemuxContext),
131 NULL,
132 read_header,
133 read_packet,
134 .extensions = "mvi"
135};
diff --git a/src/plugins/ffmpeg/libavformat/mxf.c b/src/plugins/ffmpeg/libavformat/mxf.c
deleted file mode 100644
index ccba07d..0000000
--- a/src/plugins/ffmpeg/libavformat/mxf.c
+++ /dev/null
@@ -1,1074 +0,0 @@
1/*
2 * MXF demuxer.
3 * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>.
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/*
23 * References
24 * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
25 * SMPTE 377M MXF File Format Specifications
26 * SMPTE 378M Operational Pattern 1a
27 * SMPTE 379M MXF Generic Container
28 * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
29 * SMPTE 382M Mapping AES3 and Broadcast Wave Audio into the MXF Generic Container
30 * SMPTE 383M Mapping DV-DIF Data to the MXF Generic Container
31 *
32 * Principle
33 * Search for Track numbers which will identify essence element KLV packets.
34 * Search for SourcePackage which define tracks which contains Track numbers.
35 * Material Package contains tracks with reference to SourcePackage tracks.
36 * Search for Descriptors (Picture, Sound) which contains codec info and parameters.
37 * Assign Descriptors to correct Tracks.
38 *
39 * Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext.
40 * Metadata parsing resolves Strong References to objects.
41 *
42 * Simple demuxer, only OP1A supported and some files might not work at all.
43 * Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1
44 */
45
46//#define DEBUG
47
48#include "libavutil/aes.h"
49#include "libavcodec/bytestream.h"
50#include "avformat.h"
51
52typedef uint8_t UID[16];
53
54enum MXFMetadataSetType {
55 AnyType,
56 MaterialPackage,
57 SourcePackage,
58 SourceClip,
59 TimecodeComponent,
60 Sequence,
61 MultipleDescriptor,
62 Descriptor,
63 Track,
64 CryptoContext,
65};
66
67typedef struct {
68 UID uid;
69 enum MXFMetadataSetType type;
70 UID source_container_ul;
71} MXFCryptoContext;
72
73typedef struct {
74 UID uid;
75 enum MXFMetadataSetType type;
76 UID source_package_uid;
77 UID data_definition_ul;
78 int64_t duration;
79 int64_t start_position;
80 int source_track_id;
81} MXFStructuralComponent;
82
83typedef struct {
84 UID uid;
85 enum MXFMetadataSetType type;
86 UID data_definition_ul;
87 UID *structural_components_refs;
88 int structural_components_count;
89 int64_t duration;
90} MXFSequence;
91
92typedef struct {
93 UID uid;
94 enum MXFMetadataSetType type;
95 MXFSequence *sequence; /* mandatory, and only one */
96 UID sequence_ref;
97 int track_id;
98 uint8_t track_number[4];
99 AVRational edit_rate;
100} MXFTrack;
101
102typedef struct {
103 UID uid;
104 enum MXFMetadataSetType type;
105 UID essence_container_ul;
106 UID essence_codec_ul;
107 AVRational sample_rate;
108 AVRational aspect_ratio;
109 int width;
110 int height;
111 int channels;
112 int bits_per_sample;
113 UID *sub_descriptors_refs;
114 int sub_descriptors_count;
115 int linked_track_id;
116 uint8_t *extradata;
117 int extradata_size;
118} MXFDescriptor;
119
120typedef struct {
121 UID uid;
122 enum MXFMetadataSetType type;
123 UID package_uid;
124 UID *tracks_refs;
125 int tracks_count;
126 MXFDescriptor *descriptor; /* only one */
127 UID descriptor_ref;
128} MXFPackage;
129
130typedef struct {
131 UID uid;
132 enum MXFMetadataSetType type;
133} MXFMetadataSet;
134
135typedef struct {
136 UID *packages_refs;
137 int packages_count;
138 MXFMetadataSet **metadata_sets;
139 int metadata_sets_count;
140 AVFormatContext *fc;
141 struct AVAES *aesc;
142 uint8_t *local_tags;
143 int local_tags_count;
144} MXFContext;
145
146typedef struct {
147 UID key;
148 offset_t offset;
149 uint64_t length;
150} KLVPacket;
151
152enum MXFWrappingScheme {
153 Frame,
154 Clip,
155};
156
157typedef struct {
158 UID uid;
159 unsigned matching_len;
160 enum CodecID id;
161} MXFCodecUL;
162
163typedef struct {
164 UID uid;
165 enum CodecType type;
166} MXFDataDefinitionUL;
167
168typedef struct {
169 const UID key;
170 int (*read)();
171 int ctx_size;
172 enum MXFMetadataSetType type;
173} MXFMetadataReadTableEntry;
174
175/* partial keys to match */
176static const uint8_t mxf_header_partition_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
177static const uint8_t mxf_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
178static const uint8_t mxf_klv_key[] = { 0x06,0x0e,0x2b,0x34 };
179/* complete keys to match */
180static const uint8_t mxf_crypto_source_container_ul[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x09,0x06,0x01,0x01,0x02,0x02,0x00,0x00,0x00 };
181static const uint8_t mxf_encrypted_triplet_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
182static const uint8_t mxf_encrypted_essence_container[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
183static const uint8_t mxf_sony_mpeg4_extradata[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
184
185#define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
186
187#define PRINT_KEY(pc, s, x) dprintf(pc, "%s %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X\n", s, \
188 (x)[0], (x)[1], (x)[2], (x)[3], (x)[4], (x)[5], (x)[6], (x)[7], (x)[8], (x)[9], (x)[10], (x)[11], (x)[12], (x)[13], (x)[14], (x)[15])
189
190static int64_t klv_decode_ber_length(ByteIOContext *pb)
191{
192 uint64_t size = get_byte(pb);
193 if (size & 0x80) { /* long form */
194 int bytes_num = size & 0x7f;
195 /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
196 if (bytes_num > 8)
197 return -1;
198 size = 0;
199 while (bytes_num--)
200 size = size << 8 | get_byte(pb);
201 }
202 return size;
203}
204
205static int mxf_read_sync(ByteIOContext *pb, const uint8_t *key, unsigned size)
206{
207 int i, b;
208 for (i = 0; i < size && !url_feof(pb); i++) {
209 b = get_byte(pb);
210 if (b == key[0])
211 i = 0;
212 else if (b != key[i])
213 i = -1;
214 }
215 return i == size;
216}
217
218static int klv_read_packet(KLVPacket *klv, ByteIOContext *pb)
219{
220 if (!mxf_read_sync(pb, mxf_klv_key, 4))
221 return -1;
222 klv->offset = url_ftell(pb) - 4;
223 memcpy(klv->key, mxf_klv_key, 4);
224 get_buffer(pb, klv->key + 4, 12);
225 klv->length = klv_decode_ber_length(pb);
226 return klv->length == -1 ? -1 : 0;
227}
228
229static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv)
230{
231 int i;
232
233 for (i = 0; i < s->nb_streams; i++) {
234 MXFTrack *track = s->streams[i]->priv_data;
235 /* SMPTE 379M 7.3 */
236 if (!memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
237 return i;
238 }
239 /* return 0 if only one stream, for OP Atom files with 0 as track number */
240 return s->nb_streams == 1 ? 0 : -1;
241}
242
243/* XXX: use AVBitStreamFilter */
244static int mxf_get_d10_aes3_packet(ByteIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
245{
246 uint8_t buffer[61444];
247 const uint8_t *buf_ptr, *end_ptr;
248 uint8_t *data_ptr;
249 int i;
250
251 if (length > 61444) /* worst case PAL 1920 samples 8 channels */
252 return -1;
253 get_buffer(pb, buffer, length);
254 av_new_packet(pkt, length);
255 data_ptr = pkt->data;
256 end_ptr = buffer + length;
257 buf_ptr = buffer + 4; /* skip SMPTE 331M header */
258 for (; buf_ptr < end_ptr; ) {
259 for (i = 0; i < st->codec->channels; i++) {
260 uint32_t sample = bytestream_get_le32(&buf_ptr);
261 if (st->codec->bits_per_sample == 24)
262 bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
263 else
264 bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
265 }
266 buf_ptr += 32 - st->codec->channels*4; // always 8 channels stored SMPTE 331M
267 }
268 pkt->size = data_ptr - pkt->data;
269 return 0;
270}
271
272static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv)
273{
274 static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
275 MXFContext *mxf = s->priv_data;
276 ByteIOContext *pb = s->pb;
277 offset_t end = url_ftell(pb) + klv->length;
278 uint64_t size;
279 uint64_t orig_size;
280 uint64_t plaintext_size;
281 uint8_t ivec[16];
282 uint8_t tmpbuf[16];
283 int index;
284
285 if (!mxf->aesc && s->key && s->keylen == 16) {
286 mxf->aesc = av_malloc(av_aes_size);
287 if (!mxf->aesc)
288 return -1;
289 av_aes_init(mxf->aesc, s->key, 128, 1);
290 }
291 // crypto context
292 url_fskip(pb, klv_decode_ber_length(pb));
293 // plaintext offset
294 klv_decode_ber_length(pb);
295 plaintext_size = get_be64(pb);
296 // source klv key
297 klv_decode_ber_length(pb);
298 get_buffer(pb, klv->key, 16);
299 if (!IS_KLV_KEY(klv, mxf_essence_element_key))
300 return -1;
301 index = mxf_get_stream_index(s, klv);
302 if (index < 0)
303 return -1;
304 // source size
305 klv_decode_ber_length(pb);
306 orig_size = get_be64(pb);
307 if (orig_size < plaintext_size)
308 return -1;
309 // enc. code
310 size = klv_decode_ber_length(pb);
311 if (size < 32 || size - 32 < orig_size)
312 return -1;
313 get_buffer(pb, ivec, 16);
314 get_buffer(pb, tmpbuf, 16);
315 if (mxf->aesc)
316 av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
317 if (memcmp(tmpbuf, checkv, 16))
318 av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
319 size -= 32;
320 av_get_packet(pb, pkt, size);
321 size -= plaintext_size;
322 if (mxf->aesc)
323 av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
324 &pkt->data[plaintext_size], size >> 4, ivec, 1);
325 pkt->size = orig_size;
326 pkt->stream_index = index;
327 url_fskip(pb, end - url_ftell(pb));
328 return 0;
329}
330
331static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
332{
333 KLVPacket klv;
334
335 while (!url_feof(s->pb)) {
336 if (klv_read_packet(&klv, s->pb) < 0)
337 return -1;
338#ifdef DEBUG
339 PRINT_KEY(s, "read packet", klv.key);
340#endif
341 if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
342 int res = mxf_decrypt_triplet(s, pkt, &klv);
343 if (res < 0) {
344 av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
345 return -1;
346 }
347 return 0;
348 }
349 if (IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
350 int index = mxf_get_stream_index(s, &klv);
351 if (index < 0) {
352 av_log(s, AV_LOG_ERROR, "error getting stream index %x\n", AV_RB32(klv.key+12));
353 goto skip;
354 }
355 if (s->streams[index]->discard == AVDISCARD_ALL)
356 goto skip;
357 /* check for 8 channels AES3 element */
358 if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
359 if (mxf_get_d10_aes3_packet(s->pb, s->streams[index], pkt, klv.length) < 0) {
360 av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
361 return -1;
362 }
363 } else
364 av_get_packet(s->pb, pkt, klv.length);
365 pkt->stream_index = index;
366 pkt->pos = klv.offset;
367 return 0;
368 } else
369 skip:
370 url_fskip(s->pb, klv.length);
371 }
372 return AVERROR(EIO);
373}
374
375static int mxf_read_primer_pack(MXFContext *mxf)
376{
377 ByteIOContext *pb = mxf->fc->pb;
378 int item_num = get_be32(pb);
379 int item_len = get_be32(pb);
380
381 if (item_len != 18) {
382 av_log(mxf->fc, AV_LOG_ERROR, "unsupported primer pack item length\n");
383 return -1;
384 }
385 if (item_num > UINT_MAX / item_len)
386 return -1;
387 mxf->local_tags_count = item_num;
388 mxf->local_tags = av_malloc(item_num*item_len);
389 if (!mxf->local_tags)
390 return -1;
391 get_buffer(pb, mxf->local_tags, item_num*item_len);
392 return 0;
393}
394
395static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
396{
397 mxf->metadata_sets = av_realloc(mxf->metadata_sets, (mxf->metadata_sets_count + 1) * sizeof(*mxf->metadata_sets));
398 if (!mxf->metadata_sets)
399 return -1;
400 mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;
401 mxf->metadata_sets_count++;
402 return 0;
403}
404
405static int mxf_read_cryptographic_context(MXFCryptoContext *cryptocontext, ByteIOContext *pb, int tag, int size, UID uid)
406{
407 if (size != 16)
408 return -1;
409 if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul))
410 get_buffer(pb, cryptocontext->source_container_ul, 16);
411 return 0;
412}
413
414static int mxf_read_content_storage(MXFContext *mxf, ByteIOContext *pb, int tag)
415{
416 switch (tag) {
417 case 0x1901:
418 mxf->packages_count = get_be32(pb);
419 if (mxf->packages_count >= UINT_MAX / sizeof(UID))
420 return -1;
421 mxf->packages_refs = av_malloc(mxf->packages_count * sizeof(UID));
422 if (!mxf->packages_refs)
423 return -1;
424 url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
425 get_buffer(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));
426 break;
427 }
428 return 0;
429}
430
431static int mxf_read_source_clip(MXFStructuralComponent *source_clip, ByteIOContext *pb, int tag)
432{
433 switch(tag) {
434 case 0x0202:
435 source_clip->duration = get_be64(pb);
436 break;
437 case 0x1201:
438 source_clip->start_position = get_be64(pb);
439 break;
440 case 0x1101:
441 /* UMID, only get last 16 bytes */
442 url_fskip(pb, 16);
443 get_buffer(pb, source_clip->source_package_uid, 16);
444 break;
445 case 0x1102:
446 source_clip->source_track_id = get_be32(pb);
447 break;
448 }
449 return 0;
450}
451
452static int mxf_read_material_package(MXFPackage *package, ByteIOContext *pb, int tag)
453{
454 switch(tag) {
455 case 0x4403:
456 package->tracks_count = get_be32(pb);
457 if (package->tracks_count >= UINT_MAX / sizeof(UID))
458 return -1;
459 package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
460 if (!package->tracks_refs)
461 return -1;
462 url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
463 get_buffer(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
464 break;
465 }
466 return 0;
467}
468
469static int mxf_read_track(MXFTrack *track, ByteIOContext *pb, int tag)
470{
471 switch(tag) {
472 case 0x4801:
473 track->track_id = get_be32(pb);
474 break;
475 case 0x4804:
476 get_buffer(pb, track->track_number, 4);
477 break;
478 case 0x4B01:
479 track->edit_rate.den = get_be32(pb);
480 track->edit_rate.num = get_be32(pb);
481 break;
482 case 0x4803:
483 get_buffer(pb, track->sequence_ref, 16);
484 break;
485 }
486 return 0;
487}
488
489static int mxf_read_sequence(MXFSequence *sequence, ByteIOContext *pb, int tag)
490{
491 switch(tag) {
492 case 0x0202:
493 sequence->duration = get_be64(pb);
494 break;
495 case 0x0201:
496 get_buffer(pb, sequence->data_definition_ul, 16);
497 break;
498 case 0x1001:
499 sequence->structural_components_count = get_be32(pb);
500 if (sequence->structural_components_count >= UINT_MAX / sizeof(UID))
501 return -1;
502 sequence->structural_components_refs = av_malloc(sequence->structural_components_count * sizeof(UID));
503 if (!sequence->structural_components_refs)
504 return -1;
505 url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
506 get_buffer(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
507 break;
508 }
509 return 0;
510}
511
512static int mxf_read_source_package(MXFPackage *package, ByteIOContext *pb, int tag)
513{
514 switch(tag) {
515 case 0x4403:
516 package->tracks_count = get_be32(pb);
517 if (package->tracks_count >= UINT_MAX / sizeof(UID))
518 return -1;
519 package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
520 if (!package->tracks_refs)
521 return -1;
522 url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
523 get_buffer(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
524 break;
525 case 0x4401:
526 /* UMID, only get last 16 bytes */
527 url_fskip(pb, 16);
528 get_buffer(pb, package->package_uid, 16);
529 break;
530 case 0x4701:
531 get_buffer(pb, package->descriptor_ref, 16);
532 break;
533 }
534 return 0;
535}
536
537static void mxf_read_pixel_layout(ByteIOContext *pb, MXFDescriptor *descriptor)
538{
539 int code;
540
541 do {
542 code = get_byte(pb);
543 dprintf(NULL, "pixel layout: code 0x%x\n", code);
544 switch (code) {
545 case 0x52: /* R */
546 descriptor->bits_per_sample += get_byte(pb);
547 break;
548 case 0x47: /* G */
549 descriptor->bits_per_sample += get_byte(pb);
550 break;
551 case 0x42: /* B */
552 descriptor->bits_per_sample += get_byte(pb);
553 break;
554 default:
555 get_byte(pb);
556 }
557 } while (code != 0); /* SMPTE 377M E.2.46 */
558}
559
560static int mxf_read_generic_descriptor(MXFDescriptor *descriptor, ByteIOContext *pb, int tag, int size, UID uid)
561{
562 switch(tag) {
563 case 0x3F01:
564 descriptor->sub_descriptors_count = get_be32(pb);
565 if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))
566 return -1;
567 descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));
568 if (!descriptor->sub_descriptors_refs)
569 return -1;
570 url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
571 get_buffer(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
572 break;
573 case 0x3004:
574 get_buffer(pb, descriptor->essence_container_ul, 16);
575 break;
576 case 0x3006:
577 descriptor->linked_track_id = get_be32(pb);
578 break;
579 case 0x3201: /* PictureEssenceCoding */
580 get_buffer(pb, descriptor->essence_codec_ul, 16);
581 break;
582 case 0x3203:
583 descriptor->width = get_be32(pb);
584 break;
585 case 0x3202:
586 descriptor->height = get_be32(pb);
587 break;
588 case 0x320E:
589 descriptor->aspect_ratio.num = get_be32(pb);
590 descriptor->aspect_ratio.den = get_be32(pb);
591 break;
592 case 0x3D03:
593 descriptor->sample_rate.num = get_be32(pb);
594 descriptor->sample_rate.den = get_be32(pb);
595 break;
596 case 0x3D06: /* SoundEssenceCompression */
597 get_buffer(pb, descriptor->essence_codec_ul, 16);
598 break;
599 case 0x3D07:
600 descriptor->channels = get_be32(pb);
601 break;
602 case 0x3D01:
603 descriptor->bits_per_sample = get_be32(pb);
604 break;
605 case 0x3401:
606 mxf_read_pixel_layout(pb, descriptor);
607 break;
608 default:
609 /* Private uid used by SONY C0023S01.mxf */
610 if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {
611 descriptor->extradata = av_malloc(size);
612 if (!descriptor->extradata)
613 return -1;
614 descriptor->extradata_size = size;
615 get_buffer(pb, descriptor->extradata, size);
616 }
617 break;
618 }
619 return 0;
620}
621
622/* SMPTE RP224 http://www.smpte-ra.org/mdd/index.html */
623static const MXFDataDefinitionUL mxf_data_definition_uls[] = {
624 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x01,0x03,0x02,0x02,0x01,0x00,0x00,0x00 }, CODEC_TYPE_VIDEO },
625 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x01,0x03,0x02,0x02,0x02,0x00,0x00,0x00 }, CODEC_TYPE_AUDIO },
626 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x05,0x01,0x03,0x02,0x02,0x02,0x02,0x00,0x00 }, CODEC_TYPE_AUDIO },
627 { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, CODEC_TYPE_DATA },
628};
629
630static const MXFCodecUL mxf_codec_uls[] = {
631 /* PictureEssenceCoding */
632 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, 14, CODEC_ID_MPEG2VIDEO }, /* MP@ML Long GoP */
633 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x01 }, 14, CODEC_ID_MPEG2VIDEO }, /* D-10 50Mbps PAL */
634 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, 14, CODEC_ID_MPEG2VIDEO }, /* MP@HL Long GoP */
635 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x02,0x00 }, 14, CODEC_ID_MPEG2VIDEO }, /* 422P@HL I-Frame */
636 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x20,0x02,0x03 }, 14, CODEC_ID_MPEG4 }, /* XDCAM proxy_pal030926.mxf */
637 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x01,0x02,0x00 }, 13, CODEC_ID_DVVIDEO }, /* DV25 IEC PAL */
638 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x07,0x04,0x01,0x02,0x02,0x03,0x01,0x01,0x00 }, 14, CODEC_ID_JPEG2000 }, /* JPEG2000 Codestream */
639 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x01,0x7F,0x00,0x00,0x00 }, 13, CODEC_ID_RAWVIDEO }, /* Uncompressed */
640 /* SoundEssenceCompression */
641 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 }, 13, CODEC_ID_PCM_S16LE }, /* Uncompressed */
642 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x7F,0x00,0x00,0x00 }, 13, CODEC_ID_PCM_S16LE },
643 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x07,0x04,0x02,0x02,0x01,0x7E,0x00,0x00,0x00 }, 13, CODEC_ID_PCM_S16BE }, /* From Omneon MXF file */
644 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x04,0x04,0x02,0x02,0x02,0x03,0x01,0x01,0x00 }, 15, CODEC_ID_PCM_ALAW }, /* XDCAM Proxy C0023S01.mxf */
645 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x02,0x03,0x02,0x01,0x00 }, 15, CODEC_ID_AC3 },
646 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x02,0x03,0x02,0x05,0x00 }, 15, CODEC_ID_MP2 }, /* MP2 or MP3 */
647 //{ { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x02,0x03,0x02,0x1C,0x00 }, 15, CODEC_ID_DOLBY_E }, /* Dolby-E */
648 { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, CODEC_ID_NONE },
649};
650
651static const MXFCodecUL mxf_picture_essence_container_uls[] = {
652 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, CODEC_ID_MPEG2VIDEO }, /* MPEG-ES Frame wrapped */
653 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14, CODEC_ID_DVVIDEO }, /* DV 625 25mbps */
654 { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, CODEC_ID_NONE },
655};
656
657static const MXFCodecUL mxf_sound_essence_container_uls[] = {
658 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, CODEC_ID_PCM_S16LE }, /* BWF Frame wrapped */
659 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x40,0x01 }, 14, CODEC_ID_MP2 }, /* MPEG-ES Frame wrapped, 0x40 ??? stream id */
660 { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, 14, CODEC_ID_PCM_S16LE }, /* D-10 Mapping 50Mbps PAL Extended Template */
661 { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, CODEC_ID_NONE },
662};
663
664/*
665 * Match an uid independently of the version byte and up to len common bytes
666 * Returns: boolean
667 */
668static int mxf_match_uid(const UID key, const UID uid, int len)
669{
670 int i;
671 for (i = 0; i < len; i++) {
672 if (i != 7 && key[i] != uid[i])
673 return 0;
674 }
675 return 1;
676}
677
678static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
679{
680 while (uls->id != CODEC_ID_NONE) {
681 if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
682 break;
683 uls++;
684 }
685 return uls;
686}
687
688static enum CodecType mxf_get_codec_type(const MXFDataDefinitionUL *uls, UID *uid)
689{
690 while (uls->type != CODEC_TYPE_DATA) {
691 if(mxf_match_uid(uls->uid, *uid, 16))
692 break;
693 uls++;
694 }
695 return uls->type;
696}
697
698static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
699{
700 int i;
701
702 if (!strong_ref)
703 return NULL;
704 for (i = 0; i < mxf->metadata_sets_count; i++) {
705 if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
706 (type == AnyType || mxf->metadata_sets[i]->type == type)) {
707 return mxf->metadata_sets[i];
708 }
709 }
710 return NULL;
711}
712
713static int mxf_parse_structural_metadata(MXFContext *mxf)
714{
715 MXFPackage *material_package = NULL;
716 MXFPackage *temp_package = NULL;
717 int i, j, k;
718
719 dprintf(mxf->fc, "metadata sets count %d\n", mxf->metadata_sets_count);
720 /* TODO: handle multiple material packages (OP3x) */
721 for (i = 0; i < mxf->packages_count; i++) {
722 material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
723 if (material_package) break;
724 }
725 if (!material_package) {
726 av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
727 return -1;
728 }
729
730 for (i = 0; i < material_package->tracks_count; i++) {
731 MXFPackage *source_package = NULL;
732 MXFTrack *material_track = NULL;
733 MXFTrack *source_track = NULL;
734 MXFTrack *temp_track = NULL;
735 MXFDescriptor *descriptor = NULL;
736 MXFStructuralComponent *component = NULL;
737 UID *essence_container_ul = NULL;
738 const MXFCodecUL *codec_ul = NULL;
739 const MXFCodecUL *container_ul = NULL;
740 AVStream *st;
741
742 if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
743 av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
744 continue;
745 }
746
747 if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
748 av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
749 return -1;
750 }
751
752 /* TODO: handle multiple source clips */
753 for (j = 0; j < material_track->sequence->structural_components_count; j++) {
754 /* TODO: handle timecode component */
755 component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], SourceClip);
756 if (!component)
757 continue;
758
759 for (k = 0; k < mxf->packages_count; k++) {
760 temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[k], SourcePackage);
761 if (!temp_package)
762 continue;
763 if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)) {
764 source_package = temp_package;
765 break;
766 }
767 }
768 if (!source_package) {
769 av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source package found\n", material_track->track_id);
770 break;
771 }
772 for (k = 0; k < source_package->tracks_count; k++) {
773 if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
774 av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
775 return -1;
776 }
777 if (temp_track->track_id == component->source_track_id) {
778 source_track = temp_track;
779 break;
780 }
781 }
782 if (!source_track) {
783 av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
784 break;
785 }
786 }
787 if (!source_track)
788 continue;
789
790 st = av_new_stream(mxf->fc, source_track->track_id);
791 if (!st) {
792 av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
793 return -1;
794 }
795 st->priv_data = source_track;
796 st->duration = component->duration;
797 if (st->duration == -1)
798 st->duration = AV_NOPTS_VALUE;
799 st->start_time = component->start_position;
800 av_set_pts_info(st, 64, material_track->edit_rate.num, material_track->edit_rate.den);
801
802 if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
803 av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
804 return -1;
805 }
806
807#ifdef DEBUG
808 PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul);
809#endif
810 st->codec->codec_type = mxf_get_codec_type(mxf_data_definition_uls, &source_track->sequence->data_definition_ul);
811
812 source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
813 if (source_package->descriptor) {
814 if (source_package->descriptor->type == MultipleDescriptor) {
815 for (j = 0; j < source_package->descriptor->sub_descriptors_count; j++) {
816 MXFDescriptor *sub_descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor->sub_descriptors_refs[j], Descriptor);
817
818 if (!sub_descriptor) {
819 av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
820 continue;
821 }
822 if (sub_descriptor->linked_track_id == source_track->track_id) {
823 descriptor = sub_descriptor;
824 break;
825 }
826 }
827 } else if (source_package->descriptor->type == Descriptor)
828 descriptor = source_package->descriptor;
829 }
830 if (!descriptor) {
831 av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
832 continue;
833 }
834#ifdef DEBUG
835 PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul);
836 PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
837#endif
838 essence_container_ul = &descriptor->essence_container_ul;
839 /* HACK: replacing the original key with mxf_encrypted_essence_container
840 * is not allowed according to s429-6, try to find correct information anyway */
841 if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
842 av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
843 for (k = 0; k < mxf->metadata_sets_count; k++) {
844 MXFMetadataSet *metadata = mxf->metadata_sets[k];
845 if (metadata->type == CryptoContext) {
846 essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
847 break;
848 }
849 }
850 }
851 /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
852 codec_ul = mxf_get_codec_ul(mxf_codec_uls, &descriptor->essence_codec_ul);
853 st->codec->codec_id = codec_ul->id;
854 if (descriptor->extradata) {
855 st->codec->extradata = descriptor->extradata;
856 st->codec->extradata_size = descriptor->extradata_size;
857 }
858 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
859 container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul);
860 if (st->codec->codec_id == CODEC_ID_NONE)
861 st->codec->codec_id = container_ul->id;
862 st->codec->width = descriptor->width;
863 st->codec->height = descriptor->height;
864 st->codec->bits_per_sample = descriptor->bits_per_sample; /* Uncompressed */
865 st->need_parsing = AVSTREAM_PARSE_HEADERS;
866 } else if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
867 container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul);
868 if (st->codec->codec_id == CODEC_ID_NONE)
869 st->codec->codec_id = container_ul->id;
870 st->codec->channels = descriptor->channels;
871 st->codec->bits_per_sample = descriptor->bits_per_sample;
872 st->codec->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
873 /* TODO: implement CODEC_ID_RAWAUDIO */
874 if (st->codec->codec_id == CODEC_ID_PCM_S16LE) {
875 if (descriptor->bits_per_sample == 24)
876 st->codec->codec_id = CODEC_ID_PCM_S24LE;
877 else if (descriptor->bits_per_sample == 32)
878 st->codec->codec_id = CODEC_ID_PCM_S32LE;
879 } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
880 if (descriptor->bits_per_sample == 24)
881 st->codec->codec_id = CODEC_ID_PCM_S24BE;
882 else if (descriptor->bits_per_sample == 32)
883 st->codec->codec_id = CODEC_ID_PCM_S32BE;
884 } else if (st->codec->codec_id == CODEC_ID_MP2) {
885 st->need_parsing = AVSTREAM_PARSE_FULL;
886 }
887 }
888 if (st->codec->codec_type != CODEC_TYPE_DATA && (*essence_container_ul)[15] > 0x01) {
889 av_log(mxf->fc, AV_LOG_WARNING, "only frame wrapped mappings are correctly supported\n");
890 st->need_parsing = AVSTREAM_PARSE_FULL;
891 }
892 }
893 return 0;
894}
895
896static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
897 { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
898 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
899 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_source_package, sizeof(MXFPackage), SourcePackage },
900 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_material_package, sizeof(MXFPackage), MaterialPackage },
901 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0F,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
902 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
903 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
904 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x42,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Generic Sound */
905 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
906 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */
907 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG 2 Video */
908 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */
909 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */
910 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */
911 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */
912 { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
913 { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
914};
915
916static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, int (*read_child)(), int ctx_size, enum MXFMetadataSetType type)
917{
918 ByteIOContext *pb = mxf->fc->pb;
919 MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf;
920 uint64_t klv_end = url_ftell(pb) + klv->length;
921
922 if (!ctx)
923 return -1;
924 while (url_ftell(pb) + 4 < klv_end) {
925 int tag = get_be16(pb);
926 int size = get_be16(pb); /* KLV specified by 0x53 */
927 uint64_t next = url_ftell(pb) + size;
928 UID uid = {0};
929
930 if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
931 av_log(mxf->fc, AV_LOG_ERROR, "local tag 0x%04X with 0 size\n", tag);
932 continue;
933 }
934 if (tag > 0x7FFF) { /* dynamic tag */
935 int i;
936 for (i = 0; i < mxf->local_tags_count; i++) {
937 int local_tag = AV_RB16(mxf->local_tags+i*18);
938 if (local_tag == tag) {
939 memcpy(uid, mxf->local_tags+i*18+2, 16);
940 dprintf(mxf->fc, "local tag 0x%04X\n", local_tag);
941#ifdef DEBUG
942 PRINT_KEY(mxf->fc, "uid", uid);
943#endif
944 }
945 }
946 }
947 if (ctx_size && tag == 0x3C0A)
948 get_buffer(pb, ctx->uid, 16);
949 else if (read_child(ctx, pb, tag, size, uid) < 0)
950 return -1;
951
952 url_fseek(pb, next, SEEK_SET);
953 }
954 if (ctx_size) ctx->type = type;
955 return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0;
956}
957
958static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
959{
960 MXFContext *mxf = s->priv_data;
961 KLVPacket klv;
962
963 if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {
964 av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
965 return -1;
966 }
967 url_fseek(s->pb, -14, SEEK_CUR);
968 mxf->fc = s;
969 while (!url_feof(s->pb)) {
970 const MXFMetadataReadTableEntry *metadata;
971
972 if (klv_read_packet(&klv, s->pb) < 0)
973 return -1;
974#ifdef DEBUG
975 PRINT_KEY(s, "read header", klv.key);
976#endif
977 if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||
978 IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
979 /* FIXME avoid seek */
980 url_fseek(s->pb, klv.offset, SEEK_SET);
981 break;
982 }
983
984 for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
985 if (IS_KLV_KEY(klv.key, metadata->key)) {
986 int (*read)() = klv.key[5] == 0x53 ? mxf_read_local_tags : metadata->read;
987 if (read(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type) < 0) {
988 av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
989 return -1;
990 }
991 break;
992 }
993 }
994 if (!metadata->read)
995 url_fskip(s->pb, klv.length);
996 }
997 return mxf_parse_structural_metadata(mxf);
998}
999
1000static int mxf_read_close(AVFormatContext *s)
1001{
1002 MXFContext *mxf = s->priv_data;
1003 int i;
1004
1005 av_freep(&mxf->packages_refs);
1006 for (i = 0; i < mxf->metadata_sets_count; i++) {
1007 switch (mxf->metadata_sets[i]->type) {
1008 case MultipleDescriptor:
1009 av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->sub_descriptors_refs);
1010 break;
1011 case Sequence:
1012 av_freep(&((MXFSequence *)mxf->metadata_sets[i])->structural_components_refs);
1013 break;
1014 case SourcePackage:
1015 case MaterialPackage:
1016 av_freep(&((MXFPackage *)mxf->metadata_sets[i])->tracks_refs);
1017 break;
1018 case Track:
1019 mxf->metadata_sets[i] = NULL; /* will be freed later */
1020 break;
1021 default:
1022 break;
1023 }
1024 av_freep(&mxf->metadata_sets[i]);
1025 }
1026 av_freep(&mxf->metadata_sets);
1027 av_freep(&mxf->aesc);
1028 av_freep(&mxf->local_tags);
1029 return 0;
1030}
1031
1032static int mxf_probe(AVProbeData *p) {
1033 uint8_t *bufp = p->buf;
1034 uint8_t *end = p->buf + p->buf_size;
1035
1036 if (p->buf_size < sizeof(mxf_header_partition_pack_key))
1037 return 0;
1038
1039 /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
1040 end -= sizeof(mxf_header_partition_pack_key);
1041 for (; bufp < end; bufp++) {
1042 if (IS_KLV_KEY(bufp, mxf_header_partition_pack_key))
1043 return AVPROBE_SCORE_MAX;
1044 }
1045 return 0;
1046}
1047
1048/* rudimentary byte seek */
1049/* XXX: use MXF Index */
1050static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
1051{
1052 AVStream *st = s->streams[stream_index];
1053 int64_t seconds;
1054
1055 if (!s->bit_rate)
1056 return -1;
1057 if (sample_time < 0)
1058 sample_time = 0;
1059 seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
1060 url_fseek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET);
1061 av_update_cur_dts(s, st, sample_time);
1062 return 0;
1063}
1064
1065AVInputFormat mxf_demuxer = {
1066 "mxf",
1067 NULL_IF_CONFIG_SMALL("Material eXchange Format"),
1068 sizeof(MXFContext),
1069 mxf_probe,
1070 mxf_read_header,
1071 mxf_read_packet,
1072 mxf_read_close,
1073 mxf_read_seek,
1074};
diff --git a/src/plugins/ffmpeg/libavformat/network.h b/src/plugins/ffmpeg/libavformat/network.h
deleted file mode 100644
index d897722..0000000
--- a/src/plugins/ffmpeg/libavformat/network.h
+++ /dev/null
@@ -1,69 +0,0 @@
1/*
2 * Copyright (c) 2007 The FFmpeg Project.
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21#ifndef FFMPEG_NETWORK_H
22#define FFMPEG_NETWORK_H
23
24#ifdef HAVE_WINSOCK2_H
25#include <winsock2.h>
26#include <ws2tcpip.h>
27
28#define ff_neterrno() WSAGetLastError()
29#define FF_NETERROR(err) WSA##err
30#define WSAEAGAIN WSAEWOULDBLOCK
31#else
32#include <sys/types.h>
33#include <sys/socket.h>
34#include <netinet/in.h>
35#include <netdb.h>
36
37#define ff_neterrno() errno
38#define FF_NETERROR(err) err
39#endif
40
41#ifdef HAVE_ARPA_INET_H
42#include <arpa/inet.h>
43#endif
44
45int ff_socket_nonblock(int socket, int enable);
46
47static inline int ff_network_init(void)
48{
49#ifdef HAVE_WINSOCK2_H
50 WSADATA wsaData;
51 if (WSAStartup(MAKEWORD(1,1), &wsaData))
52 return 0;
53#endif
54 return 1;
55}
56
57static inline void ff_network_close(void)
58{
59#ifdef HAVE_WINSOCK2_H
60 WSACleanup();
61#endif
62}
63
64#if !defined(HAVE_INET_ATON)
65/* in os_support.c */
66int inet_aton (const char * str, struct in_addr * add);
67#endif
68
69#endif /* FFMPEG_NETWORK_H */
diff --git a/src/plugins/ffmpeg/libavformat/nsvdec.c b/src/plugins/ffmpeg/libavformat/nsvdec.c
deleted file mode 100644
index 9fdb1a8..0000000
--- a/src/plugins/ffmpeg/libavformat/nsvdec.c
+++ /dev/null
@@ -1,763 +0,0 @@
1/*
2 * NSV demuxer
3 * Copyright (c) 2004 The FFmpeg Project.
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#include "avformat.h"
22#include "riff.h"
23
24//#define DEBUG
25//#define DEBUG_DUMP_INDEX // XXX dumbdriving-271.nsv breaks with it commented!!
26//#define DEBUG_SEEK
27#define CHECK_SUBSEQUENT_NSVS
28//#define DISABLE_AUDIO
29
30/* max bytes to crawl for trying to resync
31 * stupid streaming servers don't start at chunk boundaries...
32 */
33#define NSV_MAX_RESYNC (500*1024)
34#define NSV_MAX_RESYNC_TRIES 300
35
36/*
37 * First version by Francois Revol - revol@free.fr
38 * References:
39 * (1) http://www.multimedia.cx/nsv-format.txt
40 * seems someone came to the same conclusions as me, and updated it:
41 * (2) http://www.stud.ktu.lt/~vitslav/nsv/nsv-format.txt
42 * http://www.stud.ktu.lt/~vitslav/nsv/
43 * official docs
44 * (3) http://ultravox.aol.com/NSVFormat.rtf
45 * Sample files:
46 * (S1) http://www.nullsoft.com/nsv/samples/
47 * http://www.nullsoft.com/nsv/samples/faster.nsv
48 * http://streamripper.sourceforge.net/openbb/read.php?TID=492&page=4
49 */
50
51/*
52 * notes on the header (Francois Revol):
53 *
54 * It is followed by strings, then a table, but nothing tells
55 * where the table begins according to (1). After checking faster.nsv,
56 * I believe NVSf[16-19] gives the size of the strings data
57 * (that is the offset of the data table after the header).
58 * After checking all samples from (S1) all confirms this.
59 *
60 * Then, about NSVf[12-15], faster.nsf has 179700. When veiwing it in VLC,
61 * I noticed there was about 1 NVSs chunk/s, so I ran
62 * strings faster.nsv | grep NSVs | wc -l
63 * which gave me 180. That leads me to think that NSVf[12-15] might be the
64 * file length in milliseconds.
65 * Let's try that:
66 * for f in *.nsv; do HTIME="$(od -t x4 "$f" | head -1 | sed 's/.* //')"; echo "'$f' $((0x$HTIME))s = $((0x$HTIME/1000/60)):$((0x$HTIME/1000%60))"; done
67 * except for nstrailer (which doesn't have an NSVf header), it repports correct time.
68 *
69 * nsvtrailer.nsv (S1) does not have any NSVf header, only NSVs chunks,
70 * so the header seems to not be mandatory. (for streaming).
71 *
72 * index slice duration check (excepts nsvtrailer.nsv):
73 * for f in [^n]*.nsv; do DUR="$(ffmpeg -i "$f" 2>/dev/null | grep 'NSVf duration' | cut -d ' ' -f 4)"; IC="$(ffmpeg -i "$f" 2>/dev/null | grep 'INDEX ENTRIES' | cut -d ' ' -f 2)"; echo "duration $DUR, slite time $(($DUR/$IC))"; done
74 */
75
76/*
77 * TODO:
78 * - handle timestamps !!!
79 * - use index
80 * - mime-type in probe()
81 * - seek
82 */
83
84#ifdef DEBUG
85#define PRINT(_v) printf _v
86#else
87#define PRINT(_v)
88#endif
89
90#if 0
91struct NSVf_header {
92 uint32_t chunk_tag; /* 'NSVf' */
93 uint32_t chunk_size;
94 uint32_t file_size; /* max 4GB ??? no one learns anything it seems :^) */
95 uint32_t file_length; //unknown1; /* what about MSB of file_size ? */
96 uint32_t info_strings_size; /* size of the info strings */ //unknown2;
97 uint32_t table_entries;
98 uint32_t table_entries_used; /* the left ones should be -1 */
99};
100
101struct NSVs_header {
102 uint32_t chunk_tag; /* 'NSVs' */
103 uint32_t v4cc; /* or 'NONE' */
104 uint32_t a4cc; /* or 'NONE' */
105 uint16_t vwidth; /* assert(vwidth%16==0) */
106 uint16_t vheight; /* assert(vheight%16==0) */
107 uint8_t framerate; /* value = (framerate&0x80)?frtable[frameratex0x7f]:framerate */
108 uint16_t unknown;
109};
110
111struct nsv_avchunk_header {
112 uint8_t vchunk_size_lsb;
113 uint16_t vchunk_size_msb; /* value = (vchunk_size_msb << 4) | (vchunk_size_lsb >> 4) */
114 uint16_t achunk_size;
115};
116
117struct nsv_pcm_header {
118 uint8_t bits_per_sample;
119 uint8_t channel_count;
120 uint16_t sample_rate;
121};
122#endif
123
124/* variation from avi.h */
125/*typedef struct CodecTag {
126 int id;
127 unsigned int tag;
128} CodecTag;*/
129
130/* tags */
131
132#define T_NSVF MKTAG('N', 'S', 'V', 'f') /* file header */
133#define T_NSVS MKTAG('N', 'S', 'V', 's') /* chunk header */
134#define T_TOC2 MKTAG('T', 'O', 'C', '2') /* extra index marker */
135#define T_NONE MKTAG('N', 'O', 'N', 'E') /* null a/v 4CC */
136#define T_SUBT MKTAG('S', 'U', 'B', 'T') /* subtitle aux data */
137#define T_ASYN MKTAG('A', 'S', 'Y', 'N') /* async a/v aux marker */
138#define T_KEYF MKTAG('K', 'E', 'Y', 'F') /* video keyframe aux marker (addition) */
139
140#define TB_NSVF MKBETAG('N', 'S', 'V', 'f')
141#define TB_NSVS MKBETAG('N', 'S', 'V', 's')
142
143/* hardcoded stream indexes */
144#define NSV_ST_VIDEO 0
145#define NSV_ST_AUDIO 1
146#define NSV_ST_SUBT 2
147
148enum NSVStatus {
149 NSV_UNSYNC,
150 NSV_FOUND_NSVF,
151 NSV_HAS_READ_NSVF,
152 NSV_FOUND_NSVS,
153 NSV_HAS_READ_NSVS,
154 NSV_FOUND_BEEF,
155 NSV_GOT_VIDEO,
156 NSV_GOT_AUDIO,
157};
158
159typedef struct NSVStream {
160 int frame_offset; /* current frame (video) or byte (audio) counter
161 (used to compute the pts) */
162 int scale;
163 int rate;
164 int sample_size; /* audio only data */
165 int start;
166
167 int new_frame_offset; /* temporary storage (used during seek) */
168 int cum_len; /* temporary storage (used during seek) */
169} NSVStream;
170
171typedef struct {
172 int base_offset;
173 int NSVf_end;
174 uint32_t *nsvf_index_data;
175 int index_entries;
176 enum NSVStatus state;
177 AVPacket ahead[2]; /* [v, a] if .data is !NULL there is something */
178 /* cached */
179 int64_t duration;
180 uint32_t vtag, atag;
181 uint16_t vwidth, vheight;
182 int16_t avsync;
183 AVRational framerate;
184 //DVDemuxContext* dv_demux;
185} NSVContext;
186
187static const AVCodecTag nsv_codec_video_tags[] = {
188 { CODEC_ID_VP3, MKTAG('V', 'P', '3', ' ') },
189 { CODEC_ID_VP3, MKTAG('V', 'P', '3', '0') },
190 { CODEC_ID_VP3, MKTAG('V', 'P', '3', '1') },
191 { CODEC_ID_VP5, MKTAG('V', 'P', '5', ' ') },
192 { CODEC_ID_VP5, MKTAG('V', 'P', '5', '0') },
193 { CODEC_ID_VP6, MKTAG('V', 'P', '6', ' ') },
194 { CODEC_ID_VP6, MKTAG('V', 'P', '6', '0') },
195 { CODEC_ID_VP6, MKTAG('V', 'P', '6', '1') },
196 { CODEC_ID_VP6, MKTAG('V', 'P', '6', '2') },
197/*
198 { CODEC_ID_VP4, MKTAG('V', 'P', '4', ' ') },
199 { CODEC_ID_VP4, MKTAG('V', 'P', '4', '0') },
200*/
201 { CODEC_ID_MPEG4, MKTAG('X', 'V', 'I', 'D') }, /* cf sample xvid decoder from nsv_codec_sdk.zip */
202 { CODEC_ID_RAWVIDEO, MKTAG('R', 'G', 'B', '3') },
203 { 0, 0 },
204};
205
206static const AVCodecTag nsv_codec_audio_tags[] = {
207 { CODEC_ID_MP3, MKTAG('M', 'P', '3', ' ') },
208 { CODEC_ID_AAC, MKTAG('A', 'A', 'C', ' ') },
209 { CODEC_ID_AAC, MKTAG('A', 'A', 'C', 'P') }, /* _CUTTED__MUXED_2 Heads - Out Of The City.nsv */
210 { CODEC_ID_PCM_U16LE, MKTAG('P', 'C', 'M', ' ') },
211 { 0, 0 },
212};
213
214//static int nsv_load_index(AVFormatContext *s);
215static int nsv_read_chunk(AVFormatContext *s, int fill_header);
216
217#ifdef DEBUG
218static void print_tag(const char *str, unsigned int tag, int size)
219{
220 printf("%s: tag=%c%c%c%c\n",
221 str, tag & 0xff,
222 (tag >> 8) & 0xff,
223 (tag >> 16) & 0xff,
224 (tag >> 24) & 0xff);
225}
226#endif
227
228/* try to find something we recognize, and set the state accordingly */
229static int nsv_resync(AVFormatContext *s)
230{
231 NSVContext *nsv = s->priv_data;
232 ByteIOContext *pb = s->pb;
233 uint32_t v = 0;
234 int i;
235
236 PRINT(("%s(), offset = %"PRId64", state = %d\n", __FUNCTION__, url_ftell(pb), nsv->state));
237
238 //nsv->state = NSV_UNSYNC;
239
240 for (i = 0; i < NSV_MAX_RESYNC; i++) {
241 if (url_feof(pb)) {
242 PRINT(("NSV EOF\n"));
243 nsv->state = NSV_UNSYNC;
244 return -1;
245 }
246 v <<= 8;
247 v |= get_byte(pb);
248/*
249 if (i < 8) {
250 PRINT(("NSV resync: [%d] = %02x\n", i, v & 0x0FF));
251 }
252*/
253
254 if ((v & 0x0000ffff) == 0xefbe) { /* BEEF */
255 PRINT(("NSV resynced on BEEF after %d bytes\n", i+1));
256 nsv->state = NSV_FOUND_BEEF;
257 return 0;
258 }
259 /* we read as big endian, thus the MK*BE* */
260 if (v == TB_NSVF) { /* NSVf */
261 PRINT(("NSV resynced on NSVf after %d bytes\n", i+1));
262 nsv->state = NSV_FOUND_NSVF;
263 return 0;
264 }
265 if (v == MKBETAG('N', 'S', 'V', 's')) { /* NSVs */
266 PRINT(("NSV resynced on NSVs after %d bytes\n", i+1));
267 nsv->state = NSV_FOUND_NSVS;
268 return 0;
269 }
270
271 }
272 PRINT(("NSV sync lost\n"));
273 return -1;
274}
275
276static int nsv_parse_NSVf_header(AVFormatContext *s, AVFormatParameters *ap)
277{
278 NSVContext *nsv = s->priv_data;
279 ByteIOContext *pb = s->pb;
280 unsigned int file_size, size;
281 int64_t duration;
282 int strings_size;
283 int table_entries;
284 int table_entries_used;
285
286 PRINT(("%s()\n", __FUNCTION__));
287
288 nsv->state = NSV_UNSYNC; /* in case we fail */
289
290 size = get_le32(pb);
291 if (size < 28)
292 return -1;
293 nsv->NSVf_end = size;
294
295 //s->file_size = (uint32_t)get_le32(pb);
296 file_size = (uint32_t)get_le32(pb);
297 PRINT(("NSV NSVf chunk_size %u\n", size));
298 PRINT(("NSV NSVf file_size %u\n", file_size));
299
300 nsv->duration = duration = get_le32(pb); /* in ms */
301 PRINT(("NSV NSVf duration %"PRId64" ms\n", duration));
302 // XXX: store it in AVStreams
303
304 strings_size = get_le32(pb);
305 table_entries = get_le32(pb);
306 table_entries_used = get_le32(pb);
307 PRINT(("NSV NSVf info-strings size: %d, table entries: %d, bis %d\n",
308 strings_size, table_entries, table_entries_used));
309 if (url_feof(pb))
310 return -1;
311
312 PRINT(("NSV got header; filepos %"PRId64"\n", url_ftell(pb)));
313
314 if (strings_size > 0) {
315 char *strings; /* last byte will be '\0' to play safe with str*() */
316 char *p, *endp;
317 char *token, *value;
318 char quote;
319
320 p = strings = av_mallocz(strings_size + 1);
321 endp = strings + strings_size;
322 get_buffer(pb, strings, strings_size);
323 while (p < endp) {
324 while (*p == ' ')
325 p++; /* strip out spaces */
326 if (p >= endp-2)
327 break;
328 token = p;
329 p = strchr(p, '=');
330 if (!p || p >= endp-2)
331 break;
332 *p++ = '\0';
333 quote = *p++;
334 value = p;
335 p = strchr(p, quote);
336 if (!p || p >= endp)
337 break;
338 *p++ = '\0';
339 PRINT(("NSV NSVf INFO: %s='%s'\n", token, value));
340 if (!strcmp(token, "ASPECT")) {
341 /* don't care */
342 } else if (!strcmp(token, "CREATOR") || !strcmp(token, "Author")) {
343 strncpy(s->author, value, 512-1);
344 } else if (!strcmp(token, "Copyright")) {
345 strncpy(s->copyright, value, 512-1);
346 } else if (!strcmp(token, "TITLE") || !strcmp(token, "Title")) {
347 strncpy(s->title, value, 512-1);
348 }
349 }
350 av_free(strings);
351 }
352 if (url_feof(pb))
353 return -1;
354
355 PRINT(("NSV got infos; filepos %"PRId64"\n", url_ftell(pb)));
356
357 if (table_entries_used > 0) {
358 nsv->index_entries = table_entries_used;
359 if((unsigned)table_entries >= UINT_MAX / sizeof(uint32_t))
360 return -1;
361 nsv->nsvf_index_data = av_malloc(table_entries * sizeof(uint32_t));
362#warning "FIXME: Byteswap buffer as needed"
363 get_buffer(pb, (unsigned char *)nsv->nsvf_index_data, table_entries * sizeof(uint32_t));
364 }
365
366 PRINT(("NSV got index; filepos %"PRId64"\n", url_ftell(pb)));
367
368#ifdef DEBUG_DUMP_INDEX
369#define V(v) ((v<0x20 || v > 127)?'.':v)
370 /* dump index */
371 PRINT(("NSV %d INDEX ENTRIES:\n", table_entries));
372 PRINT(("NSV [dataoffset][fileoffset]\n", table_entries));
373 for (i = 0; i < table_entries; i++) {
374 unsigned char b[8];
375 url_fseek(pb, size + nsv->nsvf_index_data[i], SEEK_SET);
376 get_buffer(pb, b, 8);
377 PRINT(("NSV [0x%08lx][0x%08lx]: %02x %02x %02x %02x %02x %02x %02x %02x"
378 "%c%c%c%c%c%c%c%c\n",
379 nsv->nsvf_index_data[i], size + nsv->nsvf_index_data[i],
380 b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
381 V(b[0]), V(b[1]), V(b[2]), V(b[3]), V(b[4]), V(b[5]), V(b[6]), V(b[7]) ));
382 }
383 //url_fseek(pb, size, SEEK_SET); /* go back to end of header */
384#undef V
385#endif
386
387 url_fseek(pb, nsv->base_offset + size, SEEK_SET); /* required for dumbdriving-271.nsv (2 extra bytes) */
388
389 if (url_feof(pb))
390 return -1;
391 nsv->state = NSV_HAS_READ_NSVF;
392 return 0;
393}
394
395static int nsv_parse_NSVs_header(AVFormatContext *s, AVFormatParameters *ap)
396{
397 NSVContext *nsv = s->priv_data;
398 ByteIOContext *pb = s->pb;
399 uint32_t vtag, atag;
400 uint16_t vwidth, vheight;
401 AVRational framerate;
402 int i;
403 AVStream *st;
404 NSVStream *nst;
405 PRINT(("%s()\n", __FUNCTION__));
406
407 vtag = get_le32(pb);
408 atag = get_le32(pb);
409 vwidth = get_le16(pb);
410 vheight = get_le16(pb);
411 i = get_byte(pb);
412
413 PRINT(("NSV NSVs framerate code %2x\n", i));
414 if(i&0x80) { /* odd way of giving native framerates from docs */
415 int t=(i & 0x7F)>>2;
416 if(t<16) framerate = (AVRational){1, t+1};
417 else framerate = (AVRational){t-15, 1};
418
419 if(i&1){
420 framerate.num *= 1000;
421 framerate.den *= 1001;
422 }
423
424 if((i&3)==3) framerate.num *= 24;
425 else if((i&3)==2) framerate.num *= 25;
426 else framerate.num *= 30;
427 }
428 else
429 framerate= (AVRational){i, 1};
430
431 nsv->avsync = get_le16(pb);
432 nsv->framerate = framerate;
433#ifdef DEBUG
434 print_tag("NSV NSVs vtag", vtag, 0);
435 print_tag("NSV NSVs atag", atag, 0);
436 PRINT(("NSV NSVs vsize %dx%d\n", vwidth, vheight));
437#endif
438
439 /* XXX change to ap != NULL ? */
440 if (s->nb_streams == 0) { /* streams not yet published, let's do that */
441 nsv->vtag = vtag;
442 nsv->atag = atag;
443 nsv->vwidth = vwidth;
444 nsv->vheight = vwidth;
445 if (vtag != T_NONE) {
446 st = av_new_stream(s, NSV_ST_VIDEO);
447 if (!st)
448 goto fail;
449
450 nst = av_mallocz(sizeof(NSVStream));
451 if (!nst)
452 goto fail;
453 st->priv_data = nst;
454 st->codec->codec_type = CODEC_TYPE_VIDEO;
455 st->codec->codec_tag = vtag;
456 st->codec->codec_id = codec_get_id(nsv_codec_video_tags, vtag);
457 st->codec->width = vwidth;
458 st->codec->height = vheight;
459 st->codec->bits_per_sample = 24; /* depth XXX */
460
461 av_set_pts_info(st, 64, framerate.den, framerate.num);
462 st->start_time = 0;
463 st->duration = av_rescale(nsv->duration, framerate.num, 1000*framerate.den);
464 }
465 if (atag != T_NONE) {
466#ifndef DISABLE_AUDIO
467 st = av_new_stream(s, NSV_ST_AUDIO);
468 if (!st)
469 goto fail;
470
471 nst = av_mallocz(sizeof(NSVStream));
472 if (!nst)
473 goto fail;
474 st->priv_data = nst;
475 st->codec->codec_type = CODEC_TYPE_AUDIO;
476 st->codec->codec_tag = atag;
477 st->codec->codec_id = codec_get_id(nsv_codec_audio_tags, atag);
478
479 st->need_parsing = AVSTREAM_PARSE_FULL; /* for PCM we will read a chunk later and put correct info */
480
481 /* set timebase to common denominator of ms and framerate */
482 av_set_pts_info(st, 64, 1, framerate.num*1000);
483 st->start_time = 0;
484 st->duration = (int64_t)nsv->duration * framerate.num;
485#endif
486 }
487#ifdef CHECK_SUBSEQUENT_NSVS
488 } else {
489 if (nsv->vtag != vtag || nsv->atag != atag || nsv->vwidth != vwidth || nsv->vheight != vwidth) {
490 PRINT(("NSV NSVs header values differ from the first one!!!\n"));
491 //return -1;
492 }
493#endif /* CHECK_SUBSEQUENT_NSVS */
494 }
495
496 nsv->state = NSV_HAS_READ_NSVS;
497 return 0;
498fail:
499 /* XXX */
500 nsv->state = NSV_UNSYNC;
501 return -1;
502}
503
504static int nsv_read_header(AVFormatContext *s, AVFormatParameters *ap)
505{
506 NSVContext *nsv = s->priv_data;
507 int i, err;
508
509 PRINT(("%s()\n", __FUNCTION__));
510 PRINT(("filename '%s'\n", s->filename));
511
512 nsv->state = NSV_UNSYNC;
513 nsv->ahead[0].data = nsv->ahead[1].data = NULL;
514
515 for (i = 0; i < NSV_MAX_RESYNC_TRIES; i++) {
516 if (nsv_resync(s) < 0)
517 return -1;
518 if (nsv->state == NSV_FOUND_NSVF)
519 err = nsv_parse_NSVf_header(s, ap);
520 /* we need the first NSVs also... */
521 if (nsv->state == NSV_FOUND_NSVS) {
522 err = nsv_parse_NSVs_header(s, ap);
523 break; /* we just want the first one */
524 }
525 }
526 if (s->nb_streams < 1) /* no luck so far */
527 return -1;
528 /* now read the first chunk, so we can attempt to decode more info */
529 err = nsv_read_chunk(s, 1);
530
531 PRINT(("parsed header\n"));
532 return 0;
533}
534
535static int nsv_read_chunk(AVFormatContext *s, int fill_header)
536{
537 NSVContext *nsv = s->priv_data;
538 ByteIOContext *pb = s->pb;
539 AVStream *st[2] = {NULL, NULL};
540 NSVStream *nst;
541 AVPacket *pkt;
542 int i, err = 0;
543 uint8_t auxcount; /* number of aux metadata, also 4 bits of vsize */
544 uint32_t vsize;
545 uint16_t asize;
546 uint16_t auxsize;
547 uint32_t auxtag;
548
549 PRINT(("%s(%d)\n", __FUNCTION__, fill_header));
550
551 if (nsv->ahead[0].data || nsv->ahead[1].data)
552 return 0; //-1; /* hey! eat what you've in your plate first! */
553
554null_chunk_retry:
555 if (url_feof(pb))
556 return -1;
557
558 for (i = 0; i < NSV_MAX_RESYNC_TRIES && nsv->state < NSV_FOUND_NSVS && !err; i++)
559 err = nsv_resync(s);
560 if (err < 0)
561 return err;
562 if (nsv->state == NSV_FOUND_NSVS)
563 err = nsv_parse_NSVs_header(s, NULL);
564 if (err < 0)
565 return err;
566 if (nsv->state != NSV_HAS_READ_NSVS && nsv->state != NSV_FOUND_BEEF)
567 return -1;
568
569 auxcount = get_byte(pb);
570 vsize = get_le16(pb);
571 asize = get_le16(pb);
572 vsize = (vsize << 4) | (auxcount >> 4);
573 auxcount &= 0x0f;
574 PRINT(("NSV CHUNK %d aux, %u bytes video, %d bytes audio\n", auxcount, vsize, asize));
575 /* skip aux stuff */
576 for (i = 0; i < auxcount; i++) {
577 auxsize = get_le16(pb);
578 auxtag = get_le32(pb);
579 PRINT(("NSV aux data: '%c%c%c%c', %d bytes\n",
580 (auxtag & 0x0ff),
581 ((auxtag >> 8) & 0x0ff),
582 ((auxtag >> 16) & 0x0ff),
583 ((auxtag >> 24) & 0x0ff),
584 auxsize));
585 url_fskip(pb, auxsize);
586 vsize -= auxsize + sizeof(uint16_t) + sizeof(uint32_t); /* that's becoming braindead */
587 }
588
589 if (url_feof(pb))
590 return -1;
591 if (!vsize && !asize) {
592 nsv->state = NSV_UNSYNC;
593 goto null_chunk_retry;
594 }
595
596 /* map back streams to v,a */
597 if (s->streams[0])
598 st[s->streams[0]->id] = s->streams[0];
599 if (s->streams[1])
600 st[s->streams[1]->id] = s->streams[1];
601
602 if (vsize/* && st[NSV_ST_VIDEO]*/) {
603 nst = st[NSV_ST_VIDEO]->priv_data;
604 pkt = &nsv->ahead[NSV_ST_VIDEO];
605 av_get_packet(pb, pkt, vsize);
606 pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO;
607 pkt->dts = nst->frame_offset;
608 pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */
609/*
610 for (i = 0; i < MIN(8, vsize); i++)
611 PRINT(("NSV video: [%d] = %02x\n", i, pkt->data[i]));
612*/
613 }
614 if(st[NSV_ST_VIDEO])
615 ((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++;
616
617 if (asize/*st[NSV_ST_AUDIO]*/) {
618 nst = st[NSV_ST_AUDIO]->priv_data;
619 pkt = &nsv->ahead[NSV_ST_AUDIO];
620 /* read raw audio specific header on the first audio chunk... */
621 /* on ALL audio chunks ?? seems so! */
622 if (asize && st[NSV_ST_AUDIO]->codec->codec_tag == MKTAG('P', 'C', 'M', ' ')/* && fill_header*/) {
623 uint8_t bps;
624 uint8_t channels;
625 uint16_t samplerate;
626 bps = get_byte(pb);
627 channels = get_byte(pb);
628 samplerate = get_le16(pb);
629 asize-=4;
630 PRINT(("NSV RAWAUDIO: bps %d, nchan %d, srate %d\n", bps, channels, samplerate));
631 if (fill_header) {
632 st[NSV_ST_AUDIO]->need_parsing = AVSTREAM_PARSE_NONE; /* we know everything */
633 if (bps != 16) {
634 PRINT(("NSV AUDIO bit/sample != 16 (%d)!!!\n", bps));
635 }
636 bps /= channels; // ???
637 if (bps == 8)
638 st[NSV_ST_AUDIO]->codec->codec_id = CODEC_ID_PCM_U8;
639 samplerate /= 4;/* UGH ??? XXX */
640 channels = 1;
641 st[NSV_ST_AUDIO]->codec->channels = channels;
642 st[NSV_ST_AUDIO]->codec->sample_rate = samplerate;
643 PRINT(("NSV RAWAUDIO: bps %d, nchan %d, srate %d\n", bps, channels, samplerate));
644 }
645 }
646 av_get_packet(pb, pkt, asize);
647 pkt->stream_index = st[NSV_ST_AUDIO]->index;//NSV_ST_AUDIO;
648 pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */
649 if( nsv->state == NSV_HAS_READ_NSVS && st[NSV_ST_VIDEO] ) {
650 /* on a nsvs frame we have new information on a/v sync */
651 pkt->dts = (((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset-1);
652 pkt->dts *= (int64_t)1000 * nsv->framerate.den;
653 pkt->dts += (int64_t)nsv->avsync * nsv->framerate.num;
654 PRINT(("NSV AUDIO: sync:%d, dts:%"PRId64, nsv->avsync, pkt->dts));
655 }
656 nst->frame_offset++;
657 }
658
659 nsv->state = NSV_UNSYNC;
660 return 0;
661}
662
663
664static int nsv_read_packet(AVFormatContext *s, AVPacket *pkt)
665{
666 NSVContext *nsv = s->priv_data;
667 int i, err = 0;
668
669 PRINT(("%s()\n", __FUNCTION__));
670
671 /* in case we don't already have something to eat ... */
672 if (nsv->ahead[0].data == NULL && nsv->ahead[1].data == NULL)
673 err = nsv_read_chunk(s, 0);
674 if (err < 0)
675 return err;
676
677 /* now pick one of the plates */
678 for (i = 0; i < 2; i++) {
679 if (nsv->ahead[i].data) {
680 PRINT(("%s: using cached packet[%d]\n", __FUNCTION__, i));
681 /* avoid the cost of new_packet + memcpy(->data) */
682 memcpy(pkt, &nsv->ahead[i], sizeof(AVPacket));
683 nsv->ahead[i].data = NULL; /* we ate that one */
684 return pkt->size;
685 }
686 }
687
688 /* this restaurant is not approvisionned :^] */
689 return -1;
690}
691
692static int nsv_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
693{
694#if 0
695 NSVContext *avi = s->priv_data;
696 AVStream *st;
697 NSVStream *ast;
698 int frame_number, i;
699 int64_t pos;
700#endif
701
702 return -1;
703}
704
705static int nsv_read_close(AVFormatContext *s)
706{
707/* int i; */
708 NSVContext *nsv = s->priv_data;
709
710 if (nsv->index_entries)
711 av_free(nsv->nsvf_index_data);
712
713#if 0
714
715 for(i=0;i<s->nb_streams;i++) {
716 AVStream *st = s->streams[i];
717 NSVStream *ast = st->priv_data;
718 if(ast){
719 av_free(ast->index_entries);
720 av_free(ast);
721 }
722 av_free(st->codec->palctrl);
723 }
724
725#endif
726 return 0;
727}
728
729static int nsv_probe(AVProbeData *p)
730{
731 int i;
732// PRINT(("nsv_probe(), buf_size %d\n", p->buf_size));
733 /* check file header */
734 /* streamed files might not have any header */
735 if (p->buf[0] == 'N' && p->buf[1] == 'S' &&
736 p->buf[2] == 'V' && (p->buf[3] == 'f' || p->buf[3] == 's'))
737 return AVPROBE_SCORE_MAX;
738 /* XXX: do streamed files always start at chunk boundary ?? */
739 /* or do we need to search NSVs in the byte stream ? */
740 /* seems the servers don't bother starting clean chunks... */
741 /* sometimes even the first header is at 9KB or something :^) */
742 for (i = 1; i < p->buf_size - 3; i++) {
743 if (p->buf[i+0] == 'N' && p->buf[i+1] == 'S' &&
744 p->buf[i+2] == 'V' && p->buf[i+3] == 's')
745 return AVPROBE_SCORE_MAX-20;
746 }
747 /* so we'll have more luck on extension... */
748 if (match_ext(p->filename, "nsv"))
749 return AVPROBE_SCORE_MAX/2;
750 /* FIXME: add mime-type check */
751 return 0;
752}
753
754AVInputFormat nsv_demuxer = {
755 "nsv",
756 NULL_IF_CONFIG_SMALL("NullSoft Video format"),
757 sizeof(NSVContext),
758 nsv_probe,
759 nsv_read_header,
760 nsv_read_packet,
761 nsv_read_close,
762 nsv_read_seek,
763};
diff --git a/src/plugins/ffmpeg/libavformat/nut.c b/src/plugins/ffmpeg/libavformat/nut.c
deleted file mode 100644
index 7a978a5..0000000
--- a/src/plugins/ffmpeg/libavformat/nut.c
+++ /dev/null
@@ -1,81 +0,0 @@
1/*
2 * nut
3 * Copyright (c) 2004-2007 Michael Niedermayer
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/tree.h"
23#include "nut.h"
24
25const AVCodecTag ff_nut_subtitle_tags[] = {
26 { CODEC_ID_TEXT , MKTAG('U', 'T', 'F', '8') },
27 { CODEC_ID_SSA , MKTAG('S', 'S', 'A', 0 ) },
28 { CODEC_ID_DVD_SUBTITLE, MKTAG('D', 'V', 'D', 'S') },
29 { CODEC_ID_DVB_SUBTITLE, MKTAG('D', 'V', 'B', 'S') },
30 { CODEC_ID_NONE , 0 }
31};
32
33void ff_nut_reset_ts(NUTContext *nut, AVRational time_base, int64_t val){
34 int i;
35 for(i=0; i<nut->avf->nb_streams; i++){
36 nut->stream[i].last_pts= av_rescale_rnd(
37 val,
38 time_base.num * (int64_t)nut->stream[i].time_base->den,
39 time_base.den * (int64_t)nut->stream[i].time_base->num,
40 AV_ROUND_DOWN);
41 }
42}
43
44int64_t ff_lsb2full(StreamContext *stream, int64_t lsb){
45 int64_t mask = (1<<stream->msb_pts_shift)-1;
46 int64_t delta= stream->last_pts - mask/2;
47 return ((lsb - delta)&mask) + delta;
48}
49
50int ff_nut_sp_pos_cmp(syncpoint_t *a, syncpoint_t *b){
51 return ((a->pos - b->pos) >> 32) - ((b->pos - a->pos) >> 32);
52}
53
54int ff_nut_sp_pts_cmp(syncpoint_t *a, syncpoint_t *b){
55 return ((a->ts - b->ts) >> 32) - ((b->ts - a->ts) >> 32);
56}
57
58void ff_nut_add_sp(NUTContext *nut, int64_t pos, int64_t back_ptr, int64_t ts){
59 syncpoint_t *sp= av_mallocz(sizeof(syncpoint_t));
60 struct AVTreeNode *node= av_mallocz(av_tree_node_size);
61
62 sp->pos= pos;
63 sp->back_ptr= back_ptr;
64 sp->ts= ts;
65 av_tree_insert(&nut->syncpoints, sp, ff_nut_sp_pos_cmp, &node);
66 if(node){
67 av_free(sp);
68 av_free(node);
69 }
70}
71
72const Dispositions ff_nut_dispositions[] = {
73 {"default" , AV_DISPOSITION_DEFAULT},
74 {"dub" , AV_DISPOSITION_DUB},
75 {"original" , AV_DISPOSITION_ORIGINAL},
76 {"comment" , AV_DISPOSITION_COMMENT},
77 {"lyrics" , AV_DISPOSITION_LYRICS},
78 {"karaoke" , AV_DISPOSITION_KARAOKE},
79 {"" , 0}
80};
81
diff --git a/src/plugins/ffmpeg/libavformat/nut.h b/src/plugins/ffmpeg/libavformat/nut.h
deleted file mode 100644
index 6acebc3..0000000
--- a/src/plugins/ffmpeg/libavformat/nut.h
+++ /dev/null
@@ -1,115 +0,0 @@
1/*
2 * "NUT" Container Format (de)muxer
3 * Copyright (c) 2006 Michael Niedermayer
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#ifndef FFMPEG_NUT_H
23#define FFMPEG_NUT_H
24
25//#include <limits.h>
26//#include "libavutil/adler32.h"
27//#include "libavcodec/mpegaudio.h"
28#include "avformat.h"
29#include "riff.h"
30
31#define MAIN_STARTCODE (0x7A561F5F04ADULL + (((uint64_t)('N'<<8) + 'M')<<48))
32#define STREAM_STARTCODE (0x11405BF2F9DBULL + (((uint64_t)('N'<<8) + 'S')<<48))
33#define SYNCPOINT_STARTCODE (0xE4ADEECA4569ULL + (((uint64_t)('N'<<8) + 'K')<<48))
34#define INDEX_STARTCODE (0xDD672F23E64EULL + (((uint64_t)('N'<<8) + 'X')<<48))
35#define INFO_STARTCODE (0xAB68B596BA78ULL + (((uint64_t)('N'<<8) + 'I')<<48))
36
37#define ID_STRING "nut/multimedia container\0"
38
39#define MAX_DISTANCE (1024*32-1)
40
41typedef enum{
42 FLAG_KEY = 1, ///<if set, frame is keyframe
43 FLAG_EOR = 2, ///<if set, stream has no relevance on presentation. (EOR)
44 FLAG_CODED_PTS = 8, ///<if set, coded_pts is in the frame header
45 FLAG_STREAM_ID = 16, ///<if set, stream_id is coded in the frame header
46 FLAG_SIZE_MSB = 32, ///<if set, data_size_msb is at frame header, otherwise data_size_msb is 0
47 FLAG_CHECKSUM = 64, ///<if set, the frame header contains a checksum
48 FLAG_RESERVED = 128, ///<if set, reserved_count is coded in the frame header
49 FLAG_HEADER_IDX =1024, ///<If set, header_idx is coded in the frame header.
50 FLAG_MATCH_TIME =2048, ///<If set, match_time_delta is coded in the frame header
51 FLAG_CODED =4096, ///<if set, coded_flags are stored in the frame header
52 FLAG_INVALID =8192, ///<if set, frame_code is invalid
53}flag_t;
54
55typedef struct {
56 uint64_t pos;
57 uint64_t back_ptr;
58// uint64_t global_key_pts;
59 int64_t ts;
60} syncpoint_t;
61
62typedef struct {
63 uint16_t flags;
64 uint8_t stream_id;
65 uint16_t size_mul;
66 uint16_t size_lsb;
67 int16_t pts_delta;
68 uint8_t reserved_count;
69 uint8_t header_idx;
70} FrameCode; // maybe s/FrameCode/framecode_t/ or change all to Java style but do not mix
71
72typedef struct {
73 int last_flags;
74 int skip_until_key_frame;
75 int64_t last_pts;
76 int time_base_id;
77 AVRational *time_base;
78 int msb_pts_shift;
79 int max_pts_distance;
80 int decode_delay; //FIXME duplicate of has_b_frames
81} StreamContext;// maybe s/StreamContext/streamcontext_t/
82
83typedef struct {
84 AVFormatContext *avf;
85// int written_packet_size;
86// int64_t packet_start;
87 FrameCode frame_code[256];
88 uint8_t header_len[128];
89 const uint8_t *header[128];
90 uint64_t next_startcode; ///< stores the next startcode if it has already been parsed but the stream is not seekable
91 StreamContext *stream;
92 unsigned int max_distance;
93 unsigned int time_base_count;
94 int64_t last_syncpoint_pos;
95 int header_count;
96 AVRational *time_base;
97 struct AVTreeNode *syncpoints;
98} NUTContext;
99
100extern const AVCodecTag ff_nut_subtitle_tags[];
101
102typedef struct {
103 char str[9];
104 int flag;
105} Dispositions;
106
107void ff_nut_reset_ts(NUTContext *nut, AVRational time_base, int64_t val);
108int64_t ff_lsb2full(StreamContext *stream, int64_t lsb);
109int ff_nut_sp_pos_cmp(syncpoint_t *a, syncpoint_t *b);
110int ff_nut_sp_pts_cmp(syncpoint_t *a, syncpoint_t *b);
111void ff_nut_add_sp(NUTContext *nut, int64_t pos, int64_t back_ptr, int64_t ts);
112
113extern const Dispositions ff_nut_dispositions[];
114
115#endif /* FFMPEG_NUT_H */
diff --git a/src/plugins/ffmpeg/libavformat/nutdec.c b/src/plugins/ffmpeg/libavformat/nutdec.c
deleted file mode 100644
index 5dac94c..0000000
--- a/src/plugins/ffmpeg/libavformat/nutdec.c
+++ /dev/null
@@ -1,920 +0,0 @@
1/*
2 * "NUT" Container Format demuxer
3 * Copyright (c) 2004-2006 Michael Niedermayer
4 * Copyright (c) 2003 Alex Beregszaszi
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#include "libavutil/avstring.h"
24#include "libavutil/tree.h"
25#include "nut.h"
26
27#undef NDEBUG
28#include <assert.h>
29
30static int get_str(ByteIOContext *bc, char *string, unsigned int maxlen){
31 unsigned int len= ff_get_v(bc);
32
33 if(len && maxlen)
34 get_buffer(bc, string, FFMIN(len, maxlen));
35 while(len > maxlen){
36 get_byte(bc);
37 len--;
38 }
39
40 if(maxlen)
41 string[FFMIN(len, maxlen-1)]= 0;
42
43 if(maxlen == len)
44 return -1;
45 else
46 return 0;
47}
48
49static int64_t get_s(ByteIOContext *bc){
50 int64_t v = ff_get_v(bc) + 1;
51
52 if (v&1) return -(v>>1);
53 else return (v>>1);
54}
55
56static uint64_t get_fourcc(ByteIOContext *bc){
57 unsigned int len= ff_get_v(bc);
58
59 if (len==2) return get_le16(bc);
60 else if(len==4) return get_le32(bc);
61 else return -1;
62}
63
64#ifdef TRACE
65static inline uint64_t get_v_trace(ByteIOContext *bc, char *file, char *func, int line){
66 uint64_t v= ff_get_v(bc);
67
68 av_log(NULL, AV_LOG_DEBUG, "get_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
69 return v;
70}
71
72static inline int64_t get_s_trace(ByteIOContext *bc, char *file, char *func, int line){
73 int64_t v= get_s(bc);
74
75 av_log(NULL, AV_LOG_DEBUG, "get_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
76 return v;
77}
78
79static inline uint64_t get_vb_trace(ByteIOContext *bc, char *file, char *func, int line){
80 uint64_t v= get_vb(bc);
81
82 av_log(NULL, AV_LOG_DEBUG, "get_vb %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
83 return v;
84}
85#define ff_get_v(bc) get_v_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
86#define get_s(bc) get_s_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
87#define get_vb(bc) get_vb_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
88#endif
89
90static int get_packetheader(NUTContext *nut, ByteIOContext *bc, int calculate_checksum, uint64_t startcode)
91{
92 int64_t size;
93// start= url_ftell(bc) - 8;
94
95 startcode= be2me_64(startcode);
96 startcode= ff_crc04C11DB7_update(0, &startcode, 8);
97
98 init_checksum(bc, ff_crc04C11DB7_update, startcode);
99 size= ff_get_v(bc);
100 if(size > 4096)
101 get_be32(bc);
102 if(get_checksum(bc) && size > 4096)
103 return -1;
104
105 init_checksum(bc, calculate_checksum ? ff_crc04C11DB7_update : NULL, 0);
106
107 return size;
108}
109
110static uint64_t find_any_startcode(ByteIOContext *bc, int64_t pos){
111 uint64_t state=0;
112
113 if(pos >= 0)
114 url_fseek(bc, pos, SEEK_SET); //note, this may fail if the stream is not seekable, but that should not matter, as in this case we simply start where we currently are
115
116 while(!url_feof(bc)){
117 state= (state<<8) | get_byte(bc);
118 if((state>>56) != 'N')
119 continue;
120 switch(state){
121 case MAIN_STARTCODE:
122 case STREAM_STARTCODE:
123 case SYNCPOINT_STARTCODE:
124 case INFO_STARTCODE:
125 case INDEX_STARTCODE:
126 return state;
127 }
128 }
129
130 return 0;
131}
132
133/**
134 * Find the given startcode.
135 * @param code the startcode
136 * @param pos the start position of the search, or -1 if the current position
137 * @returns the position of the startcode or -1 if not found
138 */
139static int64_t find_startcode(ByteIOContext *bc, uint64_t code, int64_t pos){
140 for(;;){
141 uint64_t startcode= find_any_startcode(bc, pos);
142 if(startcode == code)
143 return url_ftell(bc) - 8;
144 else if(startcode == 0)
145 return -1;
146 pos=-1;
147 }
148}
149
150static int nut_probe(AVProbeData *p){
151 int i;
152 uint64_t code= 0;
153
154 for (i = 0; i < p->buf_size; i++) {
155 code = (code << 8) | p->buf[i];
156 if (code == MAIN_STARTCODE)
157 return AVPROBE_SCORE_MAX;
158 }
159 return 0;
160}
161
162#define GET_V(dst, check) \
163 tmp= ff_get_v(bc);\
164 if(!(check)){\
165 av_log(s, AV_LOG_ERROR, "Error " #dst " is (%"PRId64")\n", tmp);\
166 return -1;\
167 }\
168 dst= tmp;
169
170static int skip_reserved(ByteIOContext *bc, int64_t pos){
171 pos -= url_ftell(bc);
172 if(pos<0){
173 url_fseek(bc, pos, SEEK_CUR);
174 return -1;
175 }else{
176 while(pos--)
177 get_byte(bc);
178 return 0;
179 }
180}
181
182static int decode_main_header(NUTContext *nut){
183 AVFormatContext *s= nut->avf;
184 ByteIOContext *bc = s->pb;
185 uint64_t tmp, end;
186 unsigned int stream_count;
187 int i, j, tmp_stream, tmp_mul, tmp_pts, tmp_size, count, tmp_res, tmp_head_idx;
188 int64_t tmp_match;
189
190 end= get_packetheader(nut, bc, 1, MAIN_STARTCODE);
191 end += url_ftell(bc);
192
193 GET_V(tmp , tmp >=2 && tmp <= 3)
194 GET_V(stream_count , tmp > 0 && tmp <=MAX_STREAMS)
195
196 nut->max_distance = ff_get_v(bc);
197 if(nut->max_distance > 65536){
198 av_log(s, AV_LOG_DEBUG, "max_distance %d\n", nut->max_distance);
199 nut->max_distance= 65536;
200 }
201
202 GET_V(nut->time_base_count, tmp>0 && tmp<INT_MAX / sizeof(AVRational))
203 nut->time_base= av_malloc(nut->time_base_count * sizeof(AVRational));
204
205 for(i=0; i<nut->time_base_count; i++){
206 GET_V(nut->time_base[i].num, tmp>0 && tmp<(1ULL<<31))
207 GET_V(nut->time_base[i].den, tmp>0 && tmp<(1ULL<<31))
208 if(ff_gcd(nut->time_base[i].num, nut->time_base[i].den) != 1){
209 av_log(s, AV_LOG_ERROR, "time base invalid\n");
210 return -1;
211 }
212 }
213 tmp_pts=0;
214 tmp_mul=1;
215 tmp_stream=0;
216 tmp_match= 1-(1LL<<62);
217 tmp_head_idx= 0;
218 for(i=0; i<256;){
219 int tmp_flags = ff_get_v(bc);
220 int tmp_fields= ff_get_v(bc);
221 if(tmp_fields>0) tmp_pts = get_s(bc);
222 if(tmp_fields>1) tmp_mul = ff_get_v(bc);
223 if(tmp_fields>2) tmp_stream= ff_get_v(bc);
224 if(tmp_fields>3) tmp_size = ff_get_v(bc);
225 else tmp_size = 0;
226 if(tmp_fields>4) tmp_res = ff_get_v(bc);
227 else tmp_res = 0;
228 if(tmp_fields>5) count = ff_get_v(bc);
229 else count = tmp_mul - tmp_size;
230 if(tmp_fields>6) tmp_match = get_s(bc);
231 if(tmp_fields>7) tmp_head_idx= ff_get_v(bc);
232
233 while(tmp_fields-- > 8)
234 ff_get_v(bc);
235
236 if(count == 0 || i+count > 256){
237 av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
238 return -1;
239 }
240 if(tmp_stream >= stream_count){
241 av_log(s, AV_LOG_ERROR, "illegal stream number\n");
242 return -1;
243 }
244
245 for(j=0; j<count; j++,i++){
246 if (i == 'N') {
247 nut->frame_code[i].flags= FLAG_INVALID;
248 j--;
249 continue;
250 }
251 nut->frame_code[i].flags = tmp_flags ;
252 nut->frame_code[i].pts_delta = tmp_pts ;
253 nut->frame_code[i].stream_id = tmp_stream;
254 nut->frame_code[i].size_mul = tmp_mul ;
255 nut->frame_code[i].size_lsb = tmp_size+j;
256 nut->frame_code[i].reserved_count = tmp_res ;
257 nut->frame_code[i].header_idx = tmp_head_idx;
258 }
259 }
260 assert(nut->frame_code['N'].flags == FLAG_INVALID);
261
262 if(end > url_ftell(bc) + 4){
263 int rem= 1024;
264 GET_V(nut->header_count, tmp<128U)
265 nut->header_count++;
266 for(i=1; i<nut->header_count; i++){
267 GET_V(nut->header_len[i], tmp>0 && tmp<256);
268 rem -= nut->header_len[i];
269 if(rem < 0){
270 av_log(s, AV_LOG_ERROR, "invalid elision header\n");
271 return -1;
272 }
273 nut->header[i]= av_malloc(nut->header_len[i]);
274 get_buffer(bc, nut->header[i], nut->header_len[i]);
275 }
276 assert(nut->header_len[0]==0);
277 }
278
279 if(skip_reserved(bc, end) || get_checksum(bc)){
280 av_log(s, AV_LOG_ERROR, "main header checksum mismatch\n");
281 return -1;
282 }
283
284 nut->stream = av_mallocz(sizeof(StreamContext)*stream_count);
285 for(i=0; i<stream_count; i++){
286 av_new_stream(s, i);
287 }
288
289 return 0;
290}
291
292static int decode_stream_header(NUTContext *nut){
293 AVFormatContext *s= nut->avf;
294 ByteIOContext *bc = s->pb;
295 StreamContext *stc;
296 int class, stream_id;
297 uint64_t tmp, end;
298 AVStream *st;
299
300 end= get_packetheader(nut, bc, 1, STREAM_STARTCODE);
301 end += url_ftell(bc);
302
303 GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base);
304 stc= &nut->stream[stream_id];
305
306 st = s->streams[stream_id];
307 if (!st)
308 return AVERROR(ENOMEM);
309
310 class = ff_get_v(bc);
311 tmp = get_fourcc(bc);
312 st->codec->codec_tag= tmp;
313 switch(class)
314 {
315 case 0:
316 st->codec->codec_type = CODEC_TYPE_VIDEO;
317 st->codec->codec_id = codec_get_id(codec_bmp_tags, tmp);
318 break;
319 case 1:
320 st->codec->codec_type = CODEC_TYPE_AUDIO;
321 st->codec->codec_id = codec_get_id(codec_wav_tags, tmp);
322 break;
323 case 2:
324 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
325 st->codec->codec_id = codec_get_id(ff_nut_subtitle_tags, tmp);
326 break;
327 case 3:
328 st->codec->codec_type = CODEC_TYPE_DATA;
329 break;
330 default:
331 av_log(s, AV_LOG_ERROR, "unknown stream class (%d)\n", class);
332 return -1;
333 }
334 if(class<3 && st->codec->codec_id == CODEC_ID_NONE)
335 av_log(s, AV_LOG_ERROR, "Unknown codec?!\n");
336
337 GET_V(stc->time_base_id , tmp < nut->time_base_count);
338 GET_V(stc->msb_pts_shift , tmp < 16);
339 stc->max_pts_distance= ff_get_v(bc);
340 GET_V(stc->decode_delay , tmp < 1000); //sanity limit, raise this if Moore's law is true
341 st->codec->has_b_frames= stc->decode_delay;
342 ff_get_v(bc); //stream flags
343
344 GET_V(st->codec->extradata_size, tmp < (1<<30));
345 if(st->codec->extradata_size){
346 st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
347 get_buffer(bc, st->codec->extradata, st->codec->extradata_size);
348 }
349
350 if (st->codec->codec_type == CODEC_TYPE_VIDEO){
351 GET_V(st->codec->width , tmp > 0)
352 GET_V(st->codec->height, tmp > 0)
353 st->codec->sample_aspect_ratio.num= ff_get_v(bc);
354 st->codec->sample_aspect_ratio.den= ff_get_v(bc);
355 if((!st->codec->sample_aspect_ratio.num) != (!st->codec->sample_aspect_ratio.den)){
356 av_log(s, AV_LOG_ERROR, "invalid aspect ratio %d/%d\n", st->codec->sample_aspect_ratio.num, st->codec->sample_aspect_ratio.den);
357 return -1;
358 }
359 ff_get_v(bc); /* csp type */
360 }else if (st->codec->codec_type == CODEC_TYPE_AUDIO){
361 GET_V(st->codec->sample_rate , tmp > 0)
362 ff_get_v(bc); // samplerate_den
363 GET_V(st->codec->channels, tmp > 0)
364 }
365 if(skip_reserved(bc, end) || get_checksum(bc)){
366 av_log(s, AV_LOG_ERROR, "stream header %d checksum mismatch\n", stream_id);
367 return -1;
368 }
369 stc->time_base= &nut->time_base[stc->time_base_id];
370 av_set_pts_info(s->streams[stream_id], 63, stc->time_base->num, stc->time_base->den);
371 return 0;
372}
373
374static void set_disposition_bits(AVFormatContext* avf, char* value, int stream_id){
375 int flag = 0, i;
376 for (i=0; ff_nut_dispositions[i].flag; ++i) {
377 if (!strcmp(ff_nut_dispositions[i].str, value))
378 flag = ff_nut_dispositions[i].flag;
379 }
380 if (!flag)
381 av_log(avf, AV_LOG_INFO, "unknown disposition type '%s'\n", value);
382 for (i = 0; i < avf->nb_streams; ++i)
383 if (stream_id == i || stream_id == -1)
384 avf->streams[i]->disposition |= flag;
385}
386
387static int decode_info_header(NUTContext *nut){
388 AVFormatContext *s= nut->avf;
389 ByteIOContext *bc = s->pb;
390 uint64_t tmp;
391 unsigned int stream_id_plus1, chapter_start, chapter_len, count;
392 int chapter_id, i;
393 int64_t value, end;
394 char name[256], str_value[1024], type_str[256];
395 const char *type;
396 AVChapter *chapter= NULL;
397
398 end= get_packetheader(nut, bc, 1, INFO_STARTCODE);
399 end += url_ftell(bc);
400
401 GET_V(stream_id_plus1, tmp <= s->nb_streams)
402 chapter_id = get_s(bc);
403 chapter_start= ff_get_v(bc);
404 chapter_len = ff_get_v(bc);
405 count = ff_get_v(bc);
406
407 if(chapter_id && !stream_id_plus1){
408 int64_t start= chapter_start / nut->time_base_count;
409 chapter= ff_new_chapter(s, chapter_id,
410 nut->time_base[chapter_start % nut->time_base_count],
411 start, start + chapter_len, NULL);
412 }
413
414 for(i=0; i<count; i++){
415 get_str(bc, name, sizeof(name));
416 value= get_s(bc);
417 if(value == -1){
418 type= "UTF-8";
419 get_str(bc, str_value, sizeof(str_value));
420 }else if(value == -2){
421 get_str(bc, type_str, sizeof(type_str));
422 type= type_str;
423 get_str(bc, str_value, sizeof(str_value));
424 }else if(value == -3){
425 type= "s";
426 value= get_s(bc);
427 }else if(value == -4){
428 type= "t";
429 value= ff_get_v(bc);
430 }else if(value < -4){
431 type= "r";
432 get_s(bc);
433 }else{
434 type= "v";
435 }
436
437 if (stream_id_plus1 > s->nb_streams) {
438 av_log(s, AV_LOG_ERROR, "invalid stream id for info packet\n");
439 continue;
440 }
441
442 if(chapter_id==0 && !strcmp(type, "UTF-8")){
443 if (!strcmp(name, "Author"))
444 av_strlcpy(s->author , str_value, sizeof(s->author));
445 else if(!strcmp(name, "Title"))
446 av_strlcpy(s->title , str_value, sizeof(s->title));
447 else if(!strcmp(name, "Copyright"))
448 av_strlcpy(s->copyright, str_value, sizeof(s->copyright));
449 else if(!strcmp(name, "Description"))
450 av_strlcpy(s->comment , str_value, sizeof(s->comment));
451 else if(!strcmp(name, "Disposition"))
452 set_disposition_bits(s, str_value, stream_id_plus1 - 1);
453 }
454 if(chapter && !strcmp(type, "UTF-8")){
455 if(!strcmp(name, "Title"))
456 chapter->title= av_strdup(str_value);
457 }
458 }
459
460 if(skip_reserved(bc, end) || get_checksum(bc)){
461 av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");
462 return -1;
463 }
464 return 0;
465}
466
467static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr){
468 AVFormatContext *s= nut->avf;
469 ByteIOContext *bc = s->pb;
470 int64_t end, tmp;
471
472 nut->last_syncpoint_pos= url_ftell(bc)-8;
473
474 end= get_packetheader(nut, bc, 1, SYNCPOINT_STARTCODE);
475 end += url_ftell(bc);
476
477 tmp= ff_get_v(bc);
478 *back_ptr= nut->last_syncpoint_pos - 16*ff_get_v(bc);
479 if(*back_ptr < 0)
480 return -1;
481
482 ff_nut_reset_ts(nut, nut->time_base[tmp % nut->time_base_count], tmp / nut->time_base_count);
483
484 if(skip_reserved(bc, end) || get_checksum(bc)){
485 av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");
486 return -1;
487 }
488
489 *ts= tmp / s->nb_streams * av_q2d(nut->time_base[tmp % s->nb_streams])*AV_TIME_BASE;
490 ff_nut_add_sp(nut, nut->last_syncpoint_pos, *back_ptr, *ts);
491
492 return 0;
493}
494
495static int find_and_decode_index(NUTContext *nut){
496 AVFormatContext *s= nut->avf;
497 ByteIOContext *bc = s->pb;
498 uint64_t tmp, end;
499 int i, j, syncpoint_count;
500 int64_t filesize= url_fsize(bc);
501 int64_t *syncpoints;
502 int8_t *has_keyframe;
503 int ret= -1;
504
505 url_fseek(bc, filesize-12, SEEK_SET);
506 url_fseek(bc, filesize-get_be64(bc), SEEK_SET);
507 if(get_be64(bc) != INDEX_STARTCODE){
508 av_log(s, AV_LOG_ERROR, "no index at the end\n");
509 return -1;
510 }
511
512 end= get_packetheader(nut, bc, 1, INDEX_STARTCODE);
513 end += url_ftell(bc);
514
515 ff_get_v(bc); //max_pts
516 GET_V(syncpoint_count, tmp < INT_MAX/8 && tmp > 0)
517 syncpoints= av_malloc(sizeof(int64_t)*syncpoint_count);
518 has_keyframe= av_malloc(sizeof(int8_t)*(syncpoint_count+1));
519 for(i=0; i<syncpoint_count; i++){
520 syncpoints[i] = ff_get_v(bc);
521 if(syncpoints[i] <= 0)
522 goto fail;
523 if(i)
524 syncpoints[i] += syncpoints[i-1];
525 }
526
527 for(i=0; i<s->nb_streams; i++){
528 int64_t last_pts= -1;
529 for(j=0; j<syncpoint_count;){
530 uint64_t x= ff_get_v(bc);
531 int type= x&1;
532 int n= j;
533 x>>=1;
534 if(type){
535 int flag= x&1;
536 x>>=1;
537 if(n+x >= syncpoint_count + 1){
538 av_log(s, AV_LOG_ERROR, "index overflow A\n");
539 goto fail;
540 }
541 while(x--)
542 has_keyframe[n++]= flag;
543 has_keyframe[n++]= !flag;
544 }else{
545 while(x != 1){
546 if(n>=syncpoint_count + 1){
547 av_log(s, AV_LOG_ERROR, "index overflow B\n");
548 goto fail;
549 }
550 has_keyframe[n++]= x&1;
551 x>>=1;
552 }
553 }
554 if(has_keyframe[0]){
555 av_log(s, AV_LOG_ERROR, "keyframe before first syncpoint in index\n");
556 goto fail;
557 }
558 assert(n<=syncpoint_count+1);
559 for(; j<n && j<syncpoint_count; j++){
560 if(has_keyframe[j]){
561 uint64_t B, A= ff_get_v(bc);
562 if(!A){
563 A= ff_get_v(bc);
564 B= ff_get_v(bc);
565 //eor_pts[j][i] = last_pts + A + B
566 }else
567 B= 0;
568 av_add_index_entry(
569 s->streams[i],
570 16*syncpoints[j-1],
571 last_pts + A,
572 0,
573 0,
574 AVINDEX_KEYFRAME);
575 last_pts += A + B;
576 }
577 }
578 }
579 }
580
581 if(skip_reserved(bc, end) || get_checksum(bc)){
582 av_log(s, AV_LOG_ERROR, "index checksum mismatch\n");
583 goto fail;
584 }
585 ret= 0;
586fail:
587 av_free(syncpoints);
588 av_free(has_keyframe);
589 return ret;
590}
591
592static int nut_read_header(AVFormatContext *s, AVFormatParameters *ap)
593{
594 NUTContext *nut = s->priv_data;
595 ByteIOContext *bc = s->pb;
596 int64_t pos;
597 int initialized_stream_count;
598
599 nut->avf= s;
600
601 /* main header */
602 pos=0;
603 do{
604 pos= find_startcode(bc, MAIN_STARTCODE, pos)+1;
605 if (pos<0+1){
606 av_log(s, AV_LOG_ERROR, "No main startcode found.\n");
607 return -1;
608 }
609 }while(decode_main_header(nut) < 0);
610
611 /* stream headers */
612 pos=0;
613 for(initialized_stream_count=0; initialized_stream_count < s->nb_streams;){
614 pos= find_startcode(bc, STREAM_STARTCODE, pos)+1;
615 if (pos<0+1){
616 av_log(s, AV_LOG_ERROR, "Not all stream headers found.\n");
617 return -1;
618 }
619 if(decode_stream_header(nut) >= 0)
620 initialized_stream_count++;
621 }
622
623 /* info headers */
624 pos=0;
625 for(;;){
626 uint64_t startcode= find_any_startcode(bc, pos);
627 pos= url_ftell(bc);
628
629 if(startcode==0){
630 av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
631 return -1;
632 }else if(startcode == SYNCPOINT_STARTCODE){
633 nut->next_startcode= startcode;
634 break;
635 }else if(startcode != INFO_STARTCODE){
636 continue;
637 }
638
639 decode_info_header(nut);
640 }
641
642 s->data_offset= pos-8;
643
644 if(!url_is_streamed(bc)){
645 int64_t orig_pos= url_ftell(bc);
646 find_and_decode_index(nut);
647 url_fseek(bc, orig_pos, SEEK_SET);
648 }
649 assert(nut->next_startcode == SYNCPOINT_STARTCODE);
650
651 return 0;
652}
653
654static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id, uint8_t *header_idx, int frame_code){
655 AVFormatContext *s= nut->avf;
656 ByteIOContext *bc = s->pb;
657 StreamContext *stc;
658 int size, flags, size_mul, pts_delta, i, reserved_count;
659 uint64_t tmp;
660
661 if(url_ftell(bc) > nut->last_syncpoint_pos + nut->max_distance){
662 av_log(s, AV_LOG_ERROR, "Last frame must have been damaged %"PRId64" > %"PRId64" + %d\n", url_ftell(bc), nut->last_syncpoint_pos, nut->max_distance);
663 return -1;
664 }
665
666 flags = nut->frame_code[frame_code].flags;
667 size_mul = nut->frame_code[frame_code].size_mul;
668 size = nut->frame_code[frame_code].size_lsb;
669 *stream_id = nut->frame_code[frame_code].stream_id;
670 pts_delta = nut->frame_code[frame_code].pts_delta;
671 reserved_count = nut->frame_code[frame_code].reserved_count;
672 *header_idx = nut->frame_code[frame_code].header_idx;
673
674 if(flags & FLAG_INVALID)
675 return -1;
676 if(flags & FLAG_CODED)
677 flags ^= ff_get_v(bc);
678 if(flags & FLAG_STREAM_ID){
679 GET_V(*stream_id, tmp < s->nb_streams)
680 }
681 stc= &nut->stream[*stream_id];
682 if(flags&FLAG_CODED_PTS){
683 int coded_pts= ff_get_v(bc);
684//FIXME check last_pts validity?
685 if(coded_pts < (1<<stc->msb_pts_shift)){
686 *pts=ff_lsb2full(stc, coded_pts);
687 }else
688 *pts=coded_pts - (1<<stc->msb_pts_shift);
689 }else
690 *pts= stc->last_pts + pts_delta;
691 if(flags&FLAG_SIZE_MSB){
692 size += size_mul*ff_get_v(bc);
693 }
694 if(flags&FLAG_MATCH_TIME)
695 get_s(bc);
696 if(flags&FLAG_HEADER_IDX)
697 *header_idx= ff_get_v(bc);
698 if(flags&FLAG_RESERVED)
699 reserved_count= ff_get_v(bc);
700 for(i=0; i<reserved_count; i++)
701 ff_get_v(bc);
702
703 if(*header_idx >= (unsigned)nut->header_count){
704 av_log(s, AV_LOG_ERROR, "header_idx invalid\n");
705 return -1;
706 }
707 if(size > 4096)
708 *header_idx=0;
709 size -= nut->header_len[*header_idx];
710
711 if(flags&FLAG_CHECKSUM){
712 get_be32(bc); //FIXME check this
713 }else if(size > 2*nut->max_distance || FFABS(stc->last_pts - *pts) > stc->max_pts_distance){
714 av_log(s, AV_LOG_ERROR, "frame size > 2max_distance and no checksum\n");
715 return -1;
716 }
717
718 stc->last_pts= *pts;
719 stc->last_flags= flags;
720
721 return size;
722}
723
724static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code){
725 AVFormatContext *s= nut->avf;
726 ByteIOContext *bc = s->pb;
727 int size, stream_id, discard;
728 int64_t pts, last_IP_pts;
729 StreamContext *stc;
730 uint8_t header_idx;
731
732 size= decode_frame_header(nut, &pts, &stream_id, &header_idx, frame_code);
733 if(size < 0)
734 return -1;
735
736 stc= &nut->stream[stream_id];
737
738 if (stc->last_flags & FLAG_KEY)
739 stc->skip_until_key_frame=0;
740
741 discard= s->streams[ stream_id ]->discard;
742 last_IP_pts= s->streams[ stream_id ]->last_IP_pts;
743 if( (discard >= AVDISCARD_NONKEY && !(stc->last_flags & FLAG_KEY))
744 ||(discard >= AVDISCARD_BIDIR && last_IP_pts != AV_NOPTS_VALUE && last_IP_pts > pts)
745 || discard >= AVDISCARD_ALL
746 || stc->skip_until_key_frame){
747 url_fskip(bc, size);
748 return 1;
749 }
750
751 av_new_packet(pkt, size + nut->header_len[header_idx]);
752 memcpy(pkt->data, nut->header[header_idx], nut->header_len[header_idx]);
753 pkt->pos= url_ftell(bc); //FIXME
754 get_buffer(bc, pkt->data + nut->header_len[header_idx], size);
755
756 pkt->stream_index = stream_id;
757 if (stc->last_flags & FLAG_KEY)
758 pkt->flags |= PKT_FLAG_KEY;
759 pkt->pts = pts;
760
761 return 0;
762}
763
764static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
765{
766 NUTContext *nut = s->priv_data;
767 ByteIOContext *bc = s->pb;
768 int i, frame_code=0, ret, skip;
769 int64_t ts, back_ptr;
770
771 for(;;){
772 int64_t pos= url_ftell(bc);
773 uint64_t tmp= nut->next_startcode;
774 nut->next_startcode=0;
775
776 if(tmp){
777 pos-=8;
778 }else{
779 frame_code = get_byte(bc);
780 if(url_feof(bc))
781 return -1;
782 if(frame_code == 'N'){
783 tmp= frame_code;
784 for(i=1; i<8; i++)
785 tmp = (tmp<<8) + get_byte(bc);
786 }
787 }
788 switch(tmp){
789 case MAIN_STARTCODE:
790 case STREAM_STARTCODE:
791 case INDEX_STARTCODE:
792 skip= get_packetheader(nut, bc, 0, tmp);
793 url_fseek(bc, skip, SEEK_CUR);
794 break;
795 case INFO_STARTCODE:
796 if(decode_info_header(nut)<0)
797 goto resync;
798 break;
799 case SYNCPOINT_STARTCODE:
800 if(decode_syncpoint(nut, &ts, &back_ptr)<0)
801 goto resync;
802 frame_code = get_byte(bc);
803 case 0:
804 ret= decode_frame(nut, pkt, frame_code);
805 if(ret==0)
806 return 0;
807 else if(ret==1) //ok but discard packet
808 break;
809 default:
810resync:
811av_log(s, AV_LOG_DEBUG, "syncing from %"PRId64"\n", pos);
812 tmp= find_any_startcode(bc, nut->last_syncpoint_pos+1);
813 if(tmp==0)
814 return -1;
815av_log(s, AV_LOG_DEBUG, "sync\n");
816 nut->next_startcode= tmp;
817 }
818 }
819}
820
821static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index, int64_t *pos_arg, int64_t pos_limit){
822 NUTContext *nut = s->priv_data;
823 ByteIOContext *bc = s->pb;
824 int64_t pos, pts, back_ptr;
825av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%"PRId64",%"PRId64")\n", stream_index, *pos_arg, pos_limit);
826
827 pos= *pos_arg;
828 do{
829 pos= find_startcode(bc, SYNCPOINT_STARTCODE, pos)+1;
830 if(pos < 1){
831 assert(nut->next_startcode == 0);
832 av_log(s, AV_LOG_ERROR, "read_timestamp failed.\n");
833 return AV_NOPTS_VALUE;
834 }
835 }while(decode_syncpoint(nut, &pts, &back_ptr) < 0);
836 *pos_arg = pos-1;
837 assert(nut->last_syncpoint_pos == *pos_arg);
838
839 av_log(s, AV_LOG_DEBUG, "return %"PRId64" %"PRId64"\n", pts,back_ptr );
840 if (stream_index == -1) return pts;
841 else if(stream_index == -2) return back_ptr;
842
843assert(0);
844}
845
846static int read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags){
847 NUTContext *nut = s->priv_data;
848 AVStream *st= s->streams[stream_index];
849 syncpoint_t dummy={.ts= pts*av_q2d(st->time_base)*AV_TIME_BASE};
850 syncpoint_t nopts_sp= {.ts= AV_NOPTS_VALUE, .back_ptr= AV_NOPTS_VALUE};
851 syncpoint_t *sp, *next_node[2]= {&nopts_sp, &nopts_sp};
852 int64_t pos, pos2, ts;
853 int i;
854
855 if(st->index_entries){
856 int index= av_index_search_timestamp(st, pts, flags);
857 if(index<0)
858 return -1;
859
860 pos2= st->index_entries[index].pos;
861 ts = st->index_entries[index].timestamp;
862 }else{
863 av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pts_cmp, next_node);
864 av_log(s, AV_LOG_DEBUG, "%"PRIu64"-%"PRIu64" %"PRId64"-%"PRId64"\n", next_node[0]->pos, next_node[1]->pos,
865 next_node[0]->ts , next_node[1]->ts);
866 pos= av_gen_search(s, -1, dummy.ts, next_node[0]->pos, next_node[1]->pos, next_node[1]->pos,
867 next_node[0]->ts , next_node[1]->ts, AVSEEK_FLAG_BACKWARD, &ts, nut_read_timestamp);
868
869 if(!(flags & AVSEEK_FLAG_BACKWARD)){
870 dummy.pos= pos+16;
871 next_node[1]= &nopts_sp;
872 av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pos_cmp, next_node);
873 pos2= av_gen_search(s, -2, dummy.pos, next_node[0]->pos , next_node[1]->pos, next_node[1]->pos,
874 next_node[0]->back_ptr, next_node[1]->back_ptr, flags, &ts, nut_read_timestamp);
875 if(pos2>=0)
876 pos= pos2;
877 //FIXME dir but I think it does not matter
878 }
879 dummy.pos= pos;
880 sp= av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pos_cmp, NULL);
881
882 assert(sp);
883 pos2= sp->back_ptr - 15;
884 }
885 av_log(NULL, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos2);
886 pos= find_startcode(s->pb, SYNCPOINT_STARTCODE, pos2);
887 url_fseek(s->pb, pos, SEEK_SET);
888 av_log(NULL, AV_LOG_DEBUG, "SP: %"PRId64"\n", pos);
889 if(pos2 > pos || pos2 + 15 < pos){
890 av_log(NULL, AV_LOG_ERROR, "no syncpoint at backptr pos\n");
891 }
892 for(i=0; i<s->nb_streams; i++)
893 nut->stream[i].skip_until_key_frame=1;
894
895 return 0;
896}
897
898static int nut_read_close(AVFormatContext *s)
899{
900 NUTContext *nut = s->priv_data;
901
902 av_freep(&nut->time_base);
903 av_freep(&nut->stream);
904
905 return 0;
906}
907
908#ifdef CONFIG_NUT_DEMUXER
909AVInputFormat nut_demuxer = {
910 "nut",
911 NULL_IF_CONFIG_SMALL("NUT format"),
912 sizeof(NUTContext),
913 nut_probe,
914 nut_read_header,
915 nut_read_packet,
916 nut_read_close,
917 read_seek,
918 .extensions = "nut",
919};
920#endif
diff --git a/src/plugins/ffmpeg/libavformat/nutenc.c b/src/plugins/ffmpeg/libavformat/nutenc.c
deleted file mode 100644
index 06f5329..0000000
--- a/src/plugins/ffmpeg/libavformat/nutenc.c
+++ /dev/null
@@ -1,825 +0,0 @@
1/*
2 * nut muxer
3 * Copyright (c) 2004-2007 Michael Niedermayer
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/tree.h"
23#include "libavcodec/mpegaudiodata.h"
24#include "nut.h"
25
26static int find_expected_header(AVCodecContext *c, int size, int key_frame, uint8_t out[64]){
27 int sample_rate= c->sample_rate;
28
29 if(size>4096)
30 return 0;
31
32 AV_WB24(out, 1);
33
34 if(c->codec_id == CODEC_ID_MPEG4){
35 if(key_frame){
36 return 3;
37 }else{
38 out[3]= 0xB6;
39 return 4;
40 }
41 }else if(c->codec_id == CODEC_ID_MPEG1VIDEO || c->codec_id == CODEC_ID_MPEG2VIDEO){
42 return 3;
43 }else if(c->codec_id == CODEC_ID_H264){
44 return 3;
45 }else if(c->codec_id == CODEC_ID_MP3 || c->codec_id == CODEC_ID_MP2){
46 int lsf, mpeg25, sample_rate_index, bitrate_index, frame_size;
47 int layer= c->codec_id == CODEC_ID_MP3 ? 3 : 2;
48 unsigned int header= 0xFFF00000;
49
50 lsf = sample_rate < (24000+32000)/2;
51 mpeg25 = sample_rate < (12000+16000)/2;
52 sample_rate <<= lsf + mpeg25;
53 if (sample_rate < (32000 + 44100)/2) sample_rate_index=2;
54 else if(sample_rate < (44100 + 48000)/2) sample_rate_index=0;
55 else sample_rate_index=1;
56
57 sample_rate= ff_mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25);
58
59 for(bitrate_index=2; bitrate_index<30; bitrate_index++){
60 frame_size = ff_mpa_bitrate_tab[lsf][layer-1][bitrate_index>>1];
61 frame_size = (frame_size * 144000) / (sample_rate << lsf) + (bitrate_index&1);
62
63 if(frame_size == size)
64 break;
65 }
66
67 header |= (!lsf)<<19;
68 header |= (4-layer)<<17;
69 header |= 1<<16; //no crc
70 AV_WB32(out, header);
71 if(size <= 0)
72 return 2; //we guess there is no crc, if there is one the user clearly does not care about overhead
73 if(bitrate_index == 30)
74 return -1; //something is wrong ...
75
76 header |= (bitrate_index>>1)<<12;
77 header |= sample_rate_index<<10;
78 header |= (bitrate_index&1)<<9;
79
80 return 2; //FIXME actually put the needed ones in build_elision_headers()
81 return 3; //we guess that the private bit is not set
82//FIXME the above assumptions should be checked, if these turn out false too often something should be done
83 }
84 return 0;
85}
86
87static int find_header_idx(AVFormatContext *s, AVCodecContext *c, int size, int frame_type){
88 NUTContext *nut = s->priv_data;
89 uint8_t out[64];
90 int i;
91 int len= find_expected_header(c, size, frame_type, out);
92
93//av_log(NULL, AV_LOG_ERROR, "expected_h len=%d size=%d codec_id=%d\n", len, size, c->codec_id);
94
95 for(i=1; i<nut->header_count; i++){
96 if( len == nut->header_len[i]
97 && !memcmp(out, nut->header[i], len)){
98// av_log(NULL, AV_LOG_ERROR, "found %d\n", i);
99 return i;
100 }
101 }
102// av_log(NULL, AV_LOG_ERROR, "nothing found\n");
103 return 0;
104}
105
106static void build_elision_headers(AVFormatContext *s){
107 NUTContext *nut = s->priv_data;
108 int i;
109 //FIXME this is lame
110 //FIXME write a 2pass mode to find the maximal headers
111 const static uint8_t headers[][5]={
112 {3, 0x00, 0x00, 0x01},
113 {4, 0x00, 0x00, 0x01, 0xB6},
114 {2, 0xFF, 0xFA}, //mp3+crc
115 {2, 0xFF, 0xFB}, //mp3
116 {2, 0xFF, 0xFC}, //mp2+crc
117 {2, 0xFF, 0xFD}, //mp2
118 };
119
120 nut->header_count= 7;
121 for(i=1; i<nut->header_count; i++){
122 nut->header_len[i]= headers[i-1][0];
123 nut->header [i]= &headers[i-1][1];
124 }
125}
126
127static void build_frame_code(AVFormatContext *s){
128 NUTContext *nut = s->priv_data;
129 int key_frame, index, pred, stream_id;
130 int start=1;
131 int end= 254;
132 int keyframe_0_esc= s->nb_streams > 2;
133 int pred_table[10];
134 FrameCode *ft;
135
136 ft= &nut->frame_code[start];
137 ft->flags= FLAG_CODED;
138 ft->size_mul=1;
139 ft->pts_delta=1;
140 start++;
141
142 if(keyframe_0_esc){
143 /* keyframe = 0 escape */
144 FrameCode *ft= &nut->frame_code[start];
145 ft->flags= FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
146 ft->size_mul=1;
147 start++;
148 }
149
150 for(stream_id= 0; stream_id<s->nb_streams; stream_id++){
151 int start2= start + (end-start)*stream_id / s->nb_streams;
152 int end2 = start + (end-start)*(stream_id+1) / s->nb_streams;
153 AVCodecContext *codec = s->streams[stream_id]->codec;
154 int is_audio= codec->codec_type == CODEC_TYPE_AUDIO;
155 int intra_only= /*codec->intra_only || */is_audio;
156 int pred_count;
157
158 for(key_frame=0; key_frame<2; key_frame++){
159 if(intra_only && keyframe_0_esc && key_frame==0)
160 continue;
161
162 {
163 FrameCode *ft= &nut->frame_code[start2];
164 ft->flags= FLAG_KEY*key_frame;
165 ft->flags|= FLAG_SIZE_MSB | FLAG_CODED_PTS;
166 ft->stream_id= stream_id;
167 ft->size_mul=1;
168 if(is_audio)
169 ft->header_idx= find_header_idx(s, codec, -1, key_frame);
170 start2++;
171 }
172 }
173
174 key_frame= intra_only;
175#if 1
176 if(is_audio){
177 int frame_bytes= codec->frame_size*(int64_t)codec->bit_rate / (8*codec->sample_rate);
178 int pts;
179 for(pts=0; pts<2; pts++){
180 for(pred=0; pred<2; pred++){
181 FrameCode *ft= &nut->frame_code[start2];
182 ft->flags= FLAG_KEY*key_frame;
183 ft->stream_id= stream_id;
184 ft->size_mul=frame_bytes + 2;
185 ft->size_lsb=frame_bytes + pred;
186 ft->pts_delta=pts;
187 ft->header_idx= find_header_idx(s, codec, frame_bytes + pred, key_frame);
188 start2++;
189 }
190 }
191 }else{
192 FrameCode *ft= &nut->frame_code[start2];
193 ft->flags= FLAG_KEY | FLAG_SIZE_MSB;
194 ft->stream_id= stream_id;
195 ft->size_mul=1;
196 ft->pts_delta=1;
197 start2++;
198 }
199#endif
200
201 if(codec->has_b_frames){
202 pred_count=5;
203 pred_table[0]=-2;
204 pred_table[1]=-1;
205 pred_table[2]=1;
206 pred_table[3]=3;
207 pred_table[4]=4;
208 }else if(codec->codec_id == CODEC_ID_VORBIS){
209 pred_count=3;
210 pred_table[0]=2;
211 pred_table[1]=9;
212 pred_table[2]=16;
213 }else{
214 pred_count=1;
215 pred_table[0]=1;
216 }
217
218 for(pred=0; pred<pred_count; pred++){
219 int start3= start2 + (end2-start2)*pred / pred_count;
220 int end3 = start2 + (end2-start2)*(pred+1) / pred_count;
221
222 for(index=start3; index<end3; index++){
223 FrameCode *ft= &nut->frame_code[index];
224 ft->flags= FLAG_KEY*key_frame;
225 ft->flags|= FLAG_SIZE_MSB;
226 ft->stream_id= stream_id;
227//FIXME use single byte size and pred from last
228 ft->size_mul= end3-start3;
229 ft->size_lsb= index - start3;
230 ft->pts_delta= pred_table[pred];
231 if(is_audio)
232 ft->header_idx= find_header_idx(s, codec, -1, key_frame);
233 }
234 }
235 }
236 memmove(&nut->frame_code['N'+1], &nut->frame_code['N'], sizeof(FrameCode)*(255-'N'));
237 nut->frame_code[ 0].flags=
238 nut->frame_code[255].flags=
239 nut->frame_code['N'].flags= FLAG_INVALID;
240}
241
242/**
243 * Gets the length in bytes which is needed to store val as v.
244 */
245static int get_length(uint64_t val){
246 int i=1;
247
248 while(val>>=7)
249 i++;
250
251 return i;
252}
253
254static void put_v(ByteIOContext *bc, uint64_t val){
255 int i= get_length(val);
256
257 while(--i>0)
258 put_byte(bc, 128 | (val>>(7*i)));
259
260 put_byte(bc, val&127);
261}
262
263static void put_t(NUTContext *nut, StreamContext *nus, ByteIOContext *bc, uint64_t val){
264 val *= nut->time_base_count;
265 val += nus->time_base - nut->time_base;
266 put_v(bc, val);
267}
268
269/**
270 * Stores a string as vb.
271 */
272static void put_str(ByteIOContext *bc, const char *string){
273 int len= strlen(string);
274
275 put_v(bc, len);
276 put_buffer(bc, string, len);
277}
278
279static void put_s(ByteIOContext *bc, int64_t val){
280 put_v(bc, 2*FFABS(val) - (val>0));
281}
282
283#ifdef TRACE
284static inline void put_v_trace(ByteIOContext *bc, uint64_t v, char *file, char *func, int line){
285 av_log(NULL, AV_LOG_DEBUG, "put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
286
287 put_v(bc, v);
288}
289
290static inline void put_s_trace(ByteIOContext *bc, int64_t v, char *file, char *func, int line){
291 av_log(NULL, AV_LOG_DEBUG, "put_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
292
293 put_s(bc, v);
294}
295#define put_v(bc, v) put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
296#define put_s(bc, v) put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
297#endif
298
299//FIXME remove calculate_checksum
300static void put_packet(NUTContext *nut, ByteIOContext *bc, ByteIOContext *dyn_bc, int calculate_checksum, uint64_t startcode){
301 uint8_t *dyn_buf=NULL;
302 int dyn_size= url_close_dyn_buf(dyn_bc, &dyn_buf);
303 int forw_ptr= dyn_size + 4*calculate_checksum;
304
305 if(forw_ptr > 4096)
306 init_checksum(bc, ff_crc04C11DB7_update, 0);
307 put_be64(bc, startcode);
308 put_v(bc, forw_ptr);
309 if(forw_ptr > 4096)
310 put_le32(bc, get_checksum(bc));
311
312 if(calculate_checksum)
313 init_checksum(bc, ff_crc04C11DB7_update, 0);
314 put_buffer(bc, dyn_buf, dyn_size);
315 if(calculate_checksum)
316 put_le32(bc, get_checksum(bc));
317
318 av_free(dyn_buf);
319}
320
321static void write_mainheader(NUTContext *nut, ByteIOContext *bc){
322 int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields, tmp_head_idx;
323 int64_t tmp_match;
324
325 put_v(bc, 3); /* version */
326 put_v(bc, nut->avf->nb_streams);
327 put_v(bc, nut->max_distance);
328 put_v(bc, nut->time_base_count);
329
330 for(i=0; i<nut->time_base_count; i++){
331 put_v(bc, nut->time_base[i].num);
332 put_v(bc, nut->time_base[i].den);
333 }
334
335 tmp_pts=0;
336 tmp_mul=1;
337 tmp_stream=0;
338 tmp_match= 1-(1LL<<62);
339 tmp_head_idx= 0;
340 for(i=0; i<256;){
341 tmp_fields=0;
342 tmp_size=0;
343// tmp_res=0;
344 if(tmp_pts != nut->frame_code[i].pts_delta) tmp_fields=1;
345 if(tmp_mul != nut->frame_code[i].size_mul ) tmp_fields=2;
346 if(tmp_stream != nut->frame_code[i].stream_id) tmp_fields=3;
347 if(tmp_size != nut->frame_code[i].size_lsb ) tmp_fields=4;
348// if(tmp_res != nut->frame_code[i].res ) tmp_fields=5;
349 if(tmp_head_idx!=nut->frame_code[i].header_idx)tmp_fields=8;
350
351 tmp_pts = nut->frame_code[i].pts_delta;
352 tmp_flags = nut->frame_code[i].flags;
353 tmp_stream= nut->frame_code[i].stream_id;
354 tmp_mul = nut->frame_code[i].size_mul;
355 tmp_size = nut->frame_code[i].size_lsb;
356// tmp_res = nut->frame_code[i].res;
357 tmp_head_idx= nut->frame_code[i].header_idx;
358
359 for(j=0; i<256; j++,i++){
360 if(i == 'N'){
361 j--;
362 continue;
363 }
364 if(nut->frame_code[i].pts_delta != tmp_pts ) break;
365 if(nut->frame_code[i].flags != tmp_flags ) break;
366 if(nut->frame_code[i].stream_id != tmp_stream) break;
367 if(nut->frame_code[i].size_mul != tmp_mul ) break;
368 if(nut->frame_code[i].size_lsb != tmp_size+j) break;
369// if(nut->frame_code[i].res != tmp_res ) break;
370 if(nut->frame_code[i].header_idx!= tmp_head_idx) break;
371 }
372 if(j != tmp_mul - tmp_size) tmp_fields=6;
373
374 put_v(bc, tmp_flags);
375 put_v(bc, tmp_fields);
376 if(tmp_fields>0) put_s(bc, tmp_pts);
377 if(tmp_fields>1) put_v(bc, tmp_mul);
378 if(tmp_fields>2) put_v(bc, tmp_stream);
379 if(tmp_fields>3) put_v(bc, tmp_size);
380 if(tmp_fields>4) put_v(bc, 0 /*tmp_res*/);
381 if(tmp_fields>5) put_v(bc, j);
382 if(tmp_fields>6) put_v(bc, tmp_match);
383 if(tmp_fields>7) put_v(bc, tmp_head_idx);
384 }
385 put_v(bc, nut->header_count-1);
386 for(i=1; i<nut->header_count; i++){
387 put_v(bc, nut->header_len[i]);
388 put_buffer(bc, nut->header[i], nut->header_len[i]);
389 }
390}
391
392static int write_streamheader(NUTContext *nut, ByteIOContext *bc, AVCodecContext *codec, int i){
393 put_v(bc, i);
394 switch(codec->codec_type){
395 case CODEC_TYPE_VIDEO: put_v(bc, 0); break;
396 case CODEC_TYPE_AUDIO: put_v(bc, 1); break;
397 case CODEC_TYPE_SUBTITLE: put_v(bc, 2); break;
398 default : put_v(bc, 3); break;
399 }
400 put_v(bc, 4);
401 if (codec->codec_tag){
402 put_le32(bc, codec->codec_tag);
403 }else
404 return -1;
405
406 put_v(bc, nut->stream[i].time_base - nut->time_base);
407 put_v(bc, nut->stream[i].msb_pts_shift);
408 put_v(bc, nut->stream[i].max_pts_distance);
409 put_v(bc, codec->has_b_frames);
410 put_byte(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
411
412 put_v(bc, codec->extradata_size);
413 put_buffer(bc, codec->extradata, codec->extradata_size);
414
415 switch(codec->codec_type){
416 case CODEC_TYPE_AUDIO:
417 put_v(bc, codec->sample_rate);
418 put_v(bc, 1);
419 put_v(bc, codec->channels);
420 break;
421 case CODEC_TYPE_VIDEO:
422 put_v(bc, codec->width);
423 put_v(bc, codec->height);
424
425 if(codec->sample_aspect_ratio.num<=0 || codec->sample_aspect_ratio.den<=0){
426 put_v(bc, 0);
427 put_v(bc, 0);
428 }else{
429 put_v(bc, codec->sample_aspect_ratio.num);
430 put_v(bc, codec->sample_aspect_ratio.den);
431 }
432 put_v(bc, 0); /* csp type -- unknown */
433 break;
434 default:
435 break;
436 }
437 return 0;
438}
439
440static int add_info(ByteIOContext *bc, const char *type, const char *value){
441 put_str(bc, type);
442 put_s(bc, -1);
443 put_str(bc, value);
444 return 1;
445}
446
447static int write_globalinfo(NUTContext *nut, ByteIOContext *bc){
448 AVFormatContext *s= nut->avf;
449 ByteIOContext *dyn_bc;
450 uint8_t *dyn_buf=NULL;
451 int count=0, dyn_size;
452 int ret = url_open_dyn_buf(&dyn_bc);
453 if(ret < 0)
454 return ret;
455
456 if(s->title [0]) count+= add_info(dyn_bc, "Title" , s->title);
457 if(s->author [0]) count+= add_info(dyn_bc, "Author" , s->author);
458 if(s->copyright[0]) count+= add_info(dyn_bc, "Copyright", s->copyright);
459 if(!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT))
460 count+= add_info(dyn_bc, "Encoder" , LIBAVFORMAT_IDENT);
461
462 put_v(bc, 0); //stream_if_plus1
463 put_v(bc, 0); //chapter_id
464 put_v(bc, 0); //timestamp_start
465 put_v(bc, 0); //length
466
467 put_v(bc, count);
468
469 dyn_size= url_close_dyn_buf(dyn_bc, &dyn_buf);
470 put_buffer(bc, dyn_buf, dyn_size);
471 av_free(dyn_buf);
472 return 0;
473}
474
475static int write_streaminfo(NUTContext *nut, ByteIOContext *bc, int stream_id){
476 AVFormatContext *s= nut->avf;
477 AVStream* st = s->streams[stream_id];
478 ByteIOContext *dyn_bc;
479 uint8_t *dyn_buf=NULL;
480 int count=0, dyn_size, i;
481 int ret = url_open_dyn_buf(&dyn_bc);
482 if(ret < 0)
483 return ret;
484
485 for (i=0; ff_nut_dispositions[i].flag; ++i) {
486 if (st->disposition & ff_nut_dispositions[i].flag)
487 count += add_info(dyn_bc, "Disposition", ff_nut_dispositions[i].str);
488 }
489 dyn_size = url_close_dyn_buf(dyn_bc, &dyn_buf);
490
491 if (count) {
492 put_v(bc, stream_id + 1); //stream_id_plus1
493 put_v(bc, 0); //chapter_id
494 put_v(bc, 0); //timestamp_start
495 put_v(bc, 0); //length
496
497 put_v(bc, count);
498
499 put_buffer(bc, dyn_buf, dyn_size);
500 }
501
502 av_free(dyn_buf);
503 return count;
504}
505
506static int write_headers(NUTContext *nut, ByteIOContext *bc){
507 ByteIOContext *dyn_bc;
508 int i, ret;
509
510 ret = url_open_dyn_buf(&dyn_bc);
511 if(ret < 0)
512 return ret;
513 write_mainheader(nut, dyn_bc);
514 put_packet(nut, bc, dyn_bc, 1, MAIN_STARTCODE);
515
516 for (i=0; i < nut->avf->nb_streams; i++){
517 AVCodecContext *codec = nut->avf->streams[i]->codec;
518
519 ret = url_open_dyn_buf(&dyn_bc);
520 if(ret < 0)
521 return ret;
522 write_streamheader(nut, dyn_bc, codec, i);
523 put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
524 }
525
526 ret = url_open_dyn_buf(&dyn_bc);
527 if(ret < 0)
528 return ret;
529 write_globalinfo(nut, dyn_bc);
530 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
531
532 for (i = 0; i < nut->avf->nb_streams; i++) {
533 ret = url_open_dyn_buf(&dyn_bc);
534 if(ret < 0)
535 return ret;
536 ret = write_streaminfo(nut, dyn_bc, i);
537 if (ret < 0)
538 return ret;
539 if (ret > 0)
540 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
541 else {
542 uint8_t* buf;
543 url_close_dyn_buf(dyn_bc, &buf);
544 av_free(buf);
545 }
546 }
547
548 nut->last_syncpoint_pos= INT_MIN;
549 nut->header_count++;
550 return 0;
551}
552
553static int write_header(AVFormatContext *s){
554 NUTContext *nut = s->priv_data;
555 ByteIOContext *bc = s->pb;
556 int i, j;
557
558 nut->avf= s;
559
560 nut->stream = av_mallocz(sizeof(StreamContext)*s->nb_streams);
561 nut->time_base= av_mallocz(sizeof(AVRational )*s->nb_streams);
562
563 for(i=0; i<s->nb_streams; i++){
564 AVStream *st= s->streams[i];
565 int ssize;
566 AVRational time_base;
567 ff_parse_specific_params(st->codec, &time_base.den, &ssize, &time_base.num);
568
569 av_set_pts_info(st, 64, time_base.num, time_base.den);
570
571 for(j=0; j<nut->time_base_count; j++){
572 if(!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))){
573 break;
574 }
575 }
576 nut->time_base[j]= time_base;
577 nut->stream[i].time_base= &nut->time_base[j];
578 if(j==nut->time_base_count)
579 nut->time_base_count++;
580
581 if(av_q2d(time_base) >= 0.001)
582 nut->stream[i].msb_pts_shift = 7;
583 else
584 nut->stream[i].msb_pts_shift = 14;
585 nut->stream[i].max_pts_distance= FFMAX(1/av_q2d(time_base), 1);
586 }
587
588 nut->max_distance = MAX_DISTANCE;
589 build_elision_headers(s);
590 build_frame_code(s);
591 assert(nut->frame_code['N'].flags == FLAG_INVALID);
592
593 put_buffer(bc, ID_STRING, strlen(ID_STRING));
594 put_byte(bc, 0);
595
596 write_headers(nut, bc);
597
598 put_flush_packet(bc);
599
600 //FIXME index
601
602 return 0;
603}
604
605static int get_needed_flags(NUTContext *nut, StreamContext *nus, FrameCode *fc, AVPacket *pkt){
606 int flags= 0;
607
608 if(pkt->flags & PKT_FLAG_KEY ) flags |= FLAG_KEY;
609 if(pkt->stream_index != fc->stream_id ) flags |= FLAG_STREAM_ID;
610 if(pkt->size / fc->size_mul ) flags |= FLAG_SIZE_MSB;
611 if(pkt->pts - nus->last_pts != fc->pts_delta) flags |= FLAG_CODED_PTS;
612 if(pkt->size > 2*nut->max_distance ) flags |= FLAG_CHECKSUM;
613 if(FFABS(pkt->pts - nus->last_pts)
614 > nus->max_pts_distance) flags |= FLAG_CHECKSUM;
615 if( pkt->size < nut->header_len[fc->header_idx]
616 || (pkt->size > 4096 && fc->header_idx)
617 || memcmp(pkt->data, nut->header[fc->header_idx], nut->header_len[fc->header_idx]))
618 flags |= FLAG_HEADER_IDX;
619
620 return flags | (fc->flags & FLAG_CODED);
621}
622
623static int find_best_header_idx(NUTContext *nut, AVPacket *pkt){
624 int i;
625 int best_i = 0;
626 int best_len= 0;
627
628 if(pkt->size > 4096)
629 return 0;
630
631 for(i=1; i<nut->header_count; i++){
632 if( pkt->size >= nut->header_len[i]
633 && nut->header_len[i] > best_len
634 && !memcmp(pkt->data, nut->header[i], nut->header_len[i])){
635 best_i= i;
636 best_len= nut->header_len[i];
637 }
638 }
639 return best_i;
640}
641
642static int write_packet(AVFormatContext *s, AVPacket *pkt){
643 NUTContext *nut = s->priv_data;
644 StreamContext *nus= &nut->stream[pkt->stream_index];
645 ByteIOContext *bc = s->pb, *dyn_bc;
646 FrameCode *fc;
647 int64_t coded_pts;
648 int best_length, frame_code, flags, needed_flags, i, header_idx, best_header_idx;
649 int key_frame = !!(pkt->flags & PKT_FLAG_KEY);
650 int store_sp=0;
651 int ret;
652
653 if(pkt->pts < 0)
654 return -1;
655
656 if(1LL<<(20+3*nut->header_count) <= url_ftell(bc))
657 write_headers(nut, bc);
658
659 if(key_frame && !(nus->last_flags & FLAG_KEY))
660 store_sp= 1;
661
662 if(pkt->size + 30/*FIXME check*/ + url_ftell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
663 store_sp= 1;
664
665//FIXME: Ensure store_sp is 1 in the first place.
666
667 if(store_sp){
668 syncpoint_t *sp, dummy= {.pos= INT64_MAX};
669
670 ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
671 for(i=0; i<s->nb_streams; i++){
672 AVStream *st= s->streams[i];
673 int64_t dts_tb = av_rescale_rnd(pkt->dts,
674 nus->time_base->num * (int64_t)nut->stream[i].time_base->den,
675 nus->time_base->den * (int64_t)nut->stream[i].time_base->num,
676 AV_ROUND_DOWN);
677 int index= av_index_search_timestamp(st, dts_tb, AVSEEK_FLAG_BACKWARD);
678 if(index>=0) dummy.pos= FFMIN(dummy.pos, st->index_entries[index].pos);
679 }
680 if(dummy.pos == INT64_MAX)
681 dummy.pos= 0;
682 sp= av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pos_cmp, NULL);
683
684 nut->last_syncpoint_pos= url_ftell(bc);
685 ret = url_open_dyn_buf(&dyn_bc);
686 if(ret < 0)
687 return ret;
688 put_t(nut, nus, dyn_bc, pkt->dts);
689 put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos)>>4 : 0);
690 put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
691
692 ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0/*unused*/, pkt->dts);
693 }
694 assert(nus->last_pts != AV_NOPTS_VALUE);
695
696 coded_pts = pkt->pts & ((1<<nus->msb_pts_shift)-1);
697 if(ff_lsb2full(nus, coded_pts) != pkt->pts)
698 coded_pts= pkt->pts + (1<<nus->msb_pts_shift);
699
700 best_header_idx= find_best_header_idx(nut, pkt);
701
702 best_length=INT_MAX;
703 frame_code= -1;
704 for(i=0; i<256; i++){
705 int length= 0;
706 FrameCode *fc= &nut->frame_code[i];
707 int flags= fc->flags;
708
709 if(flags & FLAG_INVALID)
710 continue;
711 needed_flags= get_needed_flags(nut, nus, fc, pkt);
712
713 if(flags & FLAG_CODED){
714 length++;
715 flags = needed_flags;
716 }
717
718 if((flags & needed_flags) != needed_flags)
719 continue;
720
721 if((flags ^ needed_flags) & FLAG_KEY)
722 continue;
723
724 if(flags & FLAG_STREAM_ID)
725 length+= get_length(pkt->stream_index);
726
727 if(pkt->size % fc->size_mul != fc->size_lsb)
728 continue;
729 if(flags & FLAG_SIZE_MSB)
730 length += get_length(pkt->size / fc->size_mul);
731
732 if(flags & FLAG_CHECKSUM)
733 length+=4;
734
735 if(flags & FLAG_CODED_PTS)
736 length += get_length(coded_pts);
737
738 if( (flags & FLAG_CODED)
739 && nut->header_len[best_header_idx] > nut->header_len[fc->header_idx]+1){
740 flags |= FLAG_HEADER_IDX;
741 }
742
743 if(flags & FLAG_HEADER_IDX){
744 length += 1 - nut->header_len[best_header_idx];
745 }else{
746 length -= nut->header_len[fc->header_idx];
747 }
748
749 length*=4;
750 length+= !(flags & FLAG_CODED_PTS);
751 length+= !(flags & FLAG_CHECKSUM);
752
753 if(length < best_length){
754 best_length= length;
755 frame_code=i;
756 }
757 }
758 assert(frame_code != -1);
759 fc= &nut->frame_code[frame_code];
760 flags= fc->flags;
761 needed_flags= get_needed_flags(nut, nus, fc, pkt);
762 header_idx= fc->header_idx;
763
764 init_checksum(bc, ff_crc04C11DB7_update, 0);
765 put_byte(bc, frame_code);
766 if(flags & FLAG_CODED){
767 put_v(bc, (flags^needed_flags) & ~(FLAG_CODED));
768 flags = needed_flags;
769 }
770 if(flags & FLAG_STREAM_ID) put_v(bc, pkt->stream_index);
771 if(flags & FLAG_CODED_PTS) put_v(bc, coded_pts);
772 if(flags & FLAG_SIZE_MSB) put_v(bc, pkt->size / fc->size_mul);
773 if(flags & FLAG_HEADER_IDX) put_v(bc, header_idx= best_header_idx);
774
775 if(flags & FLAG_CHECKSUM) put_le32(bc, get_checksum(bc));
776 else get_checksum(bc);
777
778 put_buffer(bc, pkt->data + nut->header_len[header_idx], pkt->size - nut->header_len[header_idx]);
779 nus->last_flags= flags;
780 nus->last_pts= pkt->pts;
781
782 //FIXME just store one per syncpoint
783 if(flags & FLAG_KEY)
784 av_add_index_entry(
785 s->streams[pkt->stream_index],
786 nut->last_syncpoint_pos,
787 pkt->pts,
788 0,
789 0,
790 AVINDEX_KEYFRAME);
791
792 return 0;
793}
794
795static int write_trailer(AVFormatContext *s){
796 NUTContext *nut= s->priv_data;
797 ByteIOContext *bc= s->pb;
798
799 while(nut->header_count<3)
800 write_headers(nut, bc);
801 put_flush_packet(bc);
802
803 return 0;
804}
805
806AVOutputFormat nut_muxer = {
807 "nut",
808 NULL_IF_CONFIG_SMALL("NUT format"),
809 "video/x-nut",
810 "nut",
811 sizeof(NUTContext),
812#ifdef CONFIG_LIBVORBIS
813 CODEC_ID_VORBIS,
814#elif defined(CONFIG_LIBMP3LAME)
815 CODEC_ID_MP3,
816#else
817 CODEC_ID_MP2, /* AC3 needs liba52 decoder */
818#endif
819 CODEC_ID_MPEG4,
820 write_header,
821 write_packet,
822 write_trailer,
823 .flags = AVFMT_GLOBALHEADER,
824 .codec_tag= (const AVCodecTag*[]){codec_bmp_tags, codec_wav_tags, ff_nut_subtitle_tags, 0},
825};
diff --git a/src/plugins/ffmpeg/libavformat/nuv.c b/src/plugins/ffmpeg/libavformat/nuv.c
deleted file mode 100644
index 995775d..0000000
--- a/src/plugins/ffmpeg/libavformat/nuv.c
+++ /dev/null
@@ -1,252 +0,0 @@
1/*
2 * NuppelVideo demuxer.
3 * Copyright (c) 2006 Reimar Doeffinger.
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#include "avformat.h"
22#include "riff.h"
23
24typedef struct {
25 int v_id;
26 int a_id;
27 int rtjpg_video;
28} NUVContext;
29
30typedef enum {
31 NUV_VIDEO = 'V',
32 NUV_EXTRADATA = 'D',
33 NUV_AUDIO = 'A',
34 NUV_SEEKP = 'R',
35 NUV_MYTHEXT = 'X'
36} frametype_t;
37
38static int nuv_probe(AVProbeData *p) {
39 if (!memcmp(p->buf, "NuppelVideo", 12))
40 return AVPROBE_SCORE_MAX;
41 if (!memcmp(p->buf, "MythTVVideo", 12))
42 return AVPROBE_SCORE_MAX;
43 return 0;
44}
45
46//! little macro to sanitize packet size
47#define PKTSIZE(s) (s & 0xffffff)
48
49/**
50 * \brief read until we found all data needed for decoding
51 * \param vst video stream of which to change parameters
52 * \param ast video stream of which to change parameters
53 * \param myth set if this is a MythTVVideo format file
54 * \return 1 if all required codec data was found
55 */
56static int get_codec_data(ByteIOContext *pb, AVStream *vst,
57 AVStream *ast, int myth) {
58 frametype_t frametype;
59 if (!vst && !myth)
60 return 1; // no codec data needed
61 while (!url_feof(pb)) {
62 int size, subtype;
63 frametype = get_byte(pb);
64 switch (frametype) {
65 case NUV_EXTRADATA:
66 subtype = get_byte(pb);
67 url_fskip(pb, 6);
68 size = PKTSIZE(get_le32(pb));
69 if (vst && subtype == 'R') {
70 vst->codec->extradata_size = size;
71 vst->codec->extradata = av_malloc(size);
72 get_buffer(pb, vst->codec->extradata, size);
73 size = 0;
74 if (!myth)
75 return 1;
76 }
77 break;
78 case NUV_MYTHEXT:
79 url_fskip(pb, 7);
80 size = PKTSIZE(get_le32(pb));
81 if (size != 128 * 4)
82 break;
83 get_le32(pb); // version
84 if (vst) {
85 vst->codec->codec_tag = get_le32(pb);
86 vst->codec->codec_id =
87 codec_get_id(codec_bmp_tags, vst->codec->codec_tag);
88 if (vst->codec->codec_tag == MKTAG('R', 'J', 'P', 'G'))
89 vst->codec->codec_id = CODEC_ID_NUV;
90 } else
91 url_fskip(pb, 4);
92
93 if (ast) {
94 ast->codec->codec_tag = get_le32(pb);
95 ast->codec->sample_rate = get_le32(pb);
96 ast->codec->bits_per_sample = get_le32(pb);
97 ast->codec->channels = get_le32(pb);
98 ast->codec->codec_id =
99 wav_codec_get_id(ast->codec->codec_tag,
100 ast->codec->bits_per_sample);
101 ast->need_parsing = AVSTREAM_PARSE_FULL;
102 } else
103 url_fskip(pb, 4 * 4);
104
105 size -= 6 * 4;
106 url_fskip(pb, size);
107 return 1;
108 case NUV_SEEKP:
109 size = 11;
110 break;
111 default:
112 url_fskip(pb, 7);
113 size = PKTSIZE(get_le32(pb));
114 break;
115 }
116 url_fskip(pb, size);
117 }
118 return 0;
119}
120
121static int nuv_header(AVFormatContext *s, AVFormatParameters *ap) {
122 NUVContext *ctx = s->priv_data;
123 ByteIOContext *pb = s->pb;
124 char id_string[12], version_string[5];
125 double aspect, fps;
126 int is_mythtv, width, height, v_packs, a_packs;
127 int stream_nr = 0;
128 AVStream *vst = NULL, *ast = NULL;
129 get_buffer(pb, id_string, 12);
130 is_mythtv = !memcmp(id_string, "MythTVVideo", 12);
131 get_buffer(pb, version_string, 5);
132 url_fskip(pb, 3); // padding
133 width = get_le32(pb);
134 height = get_le32(pb);
135 get_le32(pb); // unused, "desiredwidth"
136 get_le32(pb); // unused, "desiredheight"
137 get_byte(pb); // 'P' == progressive, 'I' == interlaced
138 url_fskip(pb, 3); // padding
139 aspect = av_int2dbl(get_le64(pb));
140 fps = av_int2dbl(get_le64(pb));
141
142 // number of packets per stream type, -1 means unknown, e.g. streaming
143 v_packs = get_le32(pb);
144 a_packs = get_le32(pb);
145 get_le32(pb); // text
146
147 get_le32(pb); // keyframe distance (?)
148
149 if (v_packs) {
150 ctx->v_id = stream_nr++;
151 vst = av_new_stream(s, ctx->v_id);
152 if (!vst)
153 return AVERROR(ENOMEM);
154 vst->codec->codec_type = CODEC_TYPE_VIDEO;
155 vst->codec->codec_id = CODEC_ID_NUV;
156 vst->codec->width = width;
157 vst->codec->height = height;
158 vst->codec->bits_per_sample = 10;
159 vst->codec->sample_aspect_ratio = av_d2q(aspect, 10000);
160 vst->r_frame_rate = av_d2q(fps, 60000);
161 av_set_pts_info(vst, 32, 1, 1000);
162 } else
163 ctx->v_id = -1;
164
165 if (a_packs) {
166 ctx->a_id = stream_nr++;
167 ast = av_new_stream(s, ctx->a_id);
168 if (!ast)
169 return AVERROR(ENOMEM);
170 ast->codec->codec_type = CODEC_TYPE_AUDIO;
171 ast->codec->codec_id = CODEC_ID_PCM_S16LE;
172 ast->codec->channels = 2;
173 ast->codec->sample_rate = 44100;
174 ast->codec->bit_rate = 2 * 2 * 44100 * 8;
175 ast->codec->block_align = 2 * 2;
176 ast->codec->bits_per_sample = 16;
177 av_set_pts_info(ast, 32, 1, 1000);
178 } else
179 ctx->a_id = -1;
180
181 get_codec_data(pb, vst, ast, is_mythtv);
182 ctx->rtjpg_video = vst && vst->codec->codec_id == CODEC_ID_NUV;
183 return 0;
184}
185
186#define HDRSIZE 12
187
188static int nuv_packet(AVFormatContext *s, AVPacket *pkt) {
189 NUVContext *ctx = s->priv_data;
190 ByteIOContext *pb = s->pb;
191 uint8_t hdr[HDRSIZE];
192 frametype_t frametype;
193 int ret, size;
194 while (!url_feof(pb)) {
195 int copyhdrsize = ctx->rtjpg_video ? HDRSIZE : 0;
196 ret = get_buffer(pb, hdr, HDRSIZE);
197 if (ret <= 0)
198 return ret ? ret : -1;
199 frametype = hdr[0];
200 size = PKTSIZE(AV_RL32(&hdr[8]));
201 switch (frametype) {
202 case NUV_EXTRADATA:
203 if (!ctx->rtjpg_video) {
204 url_fskip(pb, size);
205 break;
206 }
207 case NUV_VIDEO:
208 if (ctx->v_id < 0) {
209 av_log(s, AV_LOG_ERROR, "Video packet in file without video stream!\n");
210 url_fskip(pb, size);
211 break;
212 }
213 ret = av_new_packet(pkt, copyhdrsize + size);
214 if (ret < 0)
215 return ret;
216 pkt->pos = url_ftell(pb) - copyhdrsize;
217 pkt->pts = AV_RL32(&hdr[4]);
218 pkt->stream_index = ctx->v_id;
219 memcpy(pkt->data, hdr, copyhdrsize);
220 ret = get_buffer(pb, pkt->data + copyhdrsize, size);
221 return ret;
222 case NUV_AUDIO:
223 if (ctx->a_id < 0) {
224 av_log(s, AV_LOG_ERROR, "Audio packet in file without audio stream!\n");
225 url_fskip(pb, size);
226 break;
227 }
228 ret = av_get_packet(pb, pkt, size);
229 pkt->pts = AV_RL32(&hdr[4]);
230 pkt->stream_index = ctx->a_id;
231 return ret;
232 case NUV_SEEKP:
233 // contains no data, size value is invalid
234 break;
235 default:
236 url_fskip(pb, size);
237 break;
238 }
239 }
240 return AVERROR(EIO);
241}
242
243AVInputFormat nuv_demuxer = {
244 "nuv",
245 NULL_IF_CONFIG_SMALL("NuppelVideo format"),
246 sizeof(NUVContext),
247 nuv_probe,
248 nuv_header,
249 nuv_packet,
250 NULL,
251 NULL,
252};
diff --git a/src/plugins/ffmpeg/libavformat/oggdec.c b/src/plugins/ffmpeg/libavformat/oggdec.c
deleted file mode 100644
index 5459e17..0000000
--- a/src/plugins/ffmpeg/libavformat/oggdec.c
+++ /dev/null
@@ -1,586 +0,0 @@
1/*
2 * Ogg bitstream support
3 * Luca Barbato <lu_zero@gentoo.org>
4 * Based on tcvp implementation
5 *
6 */
7
8/**
9 Copyright (C) 2005 Michael Ahlberg, Måns Rullgård
10
11 Permission is hereby granted, free of charge, to any person
12 obtaining a copy of this software and associated documentation
13 files (the "Software"), to deal in the Software without
14 restriction, including without limitation the rights to use, copy,
15 modify, merge, publish, distribute, sublicense, and/or sell copies
16 of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be
20 included in all copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
26 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
27 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
29 DEALINGS IN THE SOFTWARE.
30**/
31
32
33#include <stdio.h>
34#include "oggdec.h"
35#include "avformat.h"
36
37#define MAX_PAGE_SIZE 65307
38#define DECODER_BUFFER_SIZE MAX_PAGE_SIZE
39
40static ogg_codec_t *ogg_codecs[] = {
41 &speex_codec,
42 &vorbis_codec,
43 &theora_codec,
44 &flac_codec,
45 &old_flac_codec,
46 &ogm_video_codec,
47 &ogm_audio_codec,
48 &ogm_text_codec,
49 &ogm_old_codec,
50 NULL
51};
52
53//FIXME We could avoid some structure duplication
54static int
55ogg_save (AVFormatContext * s)
56{
57 ogg_t *ogg = s->priv_data;
58 ogg_state_t *ost =
59 av_malloc(sizeof (*ost) + (ogg->nstreams-1) * sizeof (*ogg->streams));
60 int i;
61 ost->pos = url_ftell (s->pb);
62 ost->curidx = ogg->curidx;
63 ost->next = ogg->state;
64 ost->nstreams = ogg->nstreams;
65 memcpy(ost->streams, ogg->streams, ogg->nstreams * sizeof(*ogg->streams));
66
67 for (i = 0; i < ogg->nstreams; i++){
68 ogg_stream_t *os = ogg->streams + i;
69 os->buf = av_malloc (os->bufsize);
70 memset (os->buf, 0, os->bufsize);
71 memcpy (os->buf, ost->streams[i].buf, os->bufpos);
72 }
73
74 ogg->state = ost;
75
76 return 0;
77}
78
79static int
80ogg_restore (AVFormatContext * s, int discard)
81{
82 ogg_t *ogg = s->priv_data;
83 ByteIOContext *bc = s->pb;
84 ogg_state_t *ost = ogg->state;
85 int i;
86
87 if (!ost)
88 return 0;
89
90 ogg->state = ost->next;
91
92 if (!discard){
93 for (i = 0; i < ogg->nstreams; i++)
94 av_free (ogg->streams[i].buf);
95
96 url_fseek (bc, ost->pos, SEEK_SET);
97 ogg->curidx = ost->curidx;
98 ogg->nstreams = ost->nstreams;
99 memcpy(ogg->streams, ost->streams,
100 ost->nstreams * sizeof(*ogg->streams));
101 }
102
103 av_free (ost);
104
105 return 0;
106}
107
108static int
109ogg_reset (ogg_t * ogg)
110{
111 int i;
112
113 for (i = 0; i < ogg->nstreams; i++){
114 ogg_stream_t *os = ogg->streams + i;
115 os->bufpos = 0;
116 os->pstart = 0;
117 os->psize = 0;
118 os->granule = -1;
119 os->lastgp = -1;
120 os->nsegs = 0;
121 os->segp = 0;
122 }
123
124 ogg->curidx = -1;
125
126 return 0;
127}
128
129static ogg_codec_t *
130ogg_find_codec (uint8_t * buf, int size)
131{
132 int i;
133
134 for (i = 0; ogg_codecs[i]; i++)
135 if (size >= ogg_codecs[i]->magicsize &&
136 !memcmp (buf, ogg_codecs[i]->magic, ogg_codecs[i]->magicsize))
137 return ogg_codecs[i];
138
139 return NULL;
140}
141
142static int
143ogg_find_stream (ogg_t * ogg, int serial)
144{
145 int i;
146
147 for (i = 0; i < ogg->nstreams; i++)
148 if (ogg->streams[i].serial == serial)
149 return i;
150
151 return -1;
152}
153
154static int
155ogg_new_stream (AVFormatContext * s, uint32_t serial)
156{
157
158 ogg_t *ogg = s->priv_data;
159 int idx = ogg->nstreams++;
160 AVStream *st;
161 ogg_stream_t *os;
162
163 ogg->streams = av_realloc (ogg->streams,
164 ogg->nstreams * sizeof (*ogg->streams));
165 memset (ogg->streams + idx, 0, sizeof (*ogg->streams));
166 os = ogg->streams + idx;
167 os->serial = serial;
168 os->bufsize = DECODER_BUFFER_SIZE;
169 os->buf = av_malloc(os->bufsize);
170 os->header = -1;
171
172 st = av_new_stream (s, idx);
173 if (!st)
174 return AVERROR(ENOMEM);
175
176 av_set_pts_info(st, 64, 1, 1000000);
177
178 return idx;
179}
180
181static int
182ogg_new_buf(ogg_t *ogg, int idx)
183{
184 ogg_stream_t *os = ogg->streams + idx;
185 uint8_t *nb = av_malloc(os->bufsize);
186 int size = os->bufpos - os->pstart;
187 if(os->buf){
188 memcpy(nb, os->buf + os->pstart, size);
189 av_free(os->buf);
190 }
191 os->buf = nb;
192 os->bufpos = size;
193 os->pstart = 0;
194
195 return 0;
196}
197
198static int
199ogg_read_page (AVFormatContext * s, int *str)
200{
201 ByteIOContext *bc = s->pb;
202 ogg_t *ogg = s->priv_data;
203 ogg_stream_t *os;
204 int i = 0;
205 int flags, nsegs;
206 uint64_t gp;
207 uint32_t serial;
208 uint32_t seq;
209 uint32_t crc;
210 int size, idx;
211 uint8_t sync[4];
212 int sp = 0;
213
214 if (get_buffer (bc, sync, 4) < 4)
215 return -1;
216
217 do{
218 int c;
219
220 if (sync[sp & 3] == 'O' &&
221 sync[(sp + 1) & 3] == 'g' &&
222 sync[(sp + 2) & 3] == 'g' && sync[(sp + 3) & 3] == 'S')
223 break;
224
225 c = url_fgetc (bc);
226 if (c < 0)
227 return -1;
228 sync[sp++ & 3] = c;
229 }while (i++ < MAX_PAGE_SIZE);
230
231 if (i >= MAX_PAGE_SIZE){
232 av_log (s, AV_LOG_INFO, "ogg, can't find sync word\n");
233 return -1;
234 }
235
236 if (url_fgetc (bc) != 0) /* version */
237 return -1;
238
239 flags = url_fgetc (bc);
240 gp = get_le64 (bc);
241 serial = get_le32 (bc);
242 seq = get_le32 (bc);
243 crc = get_le32 (bc);
244 nsegs = url_fgetc (bc);
245
246 idx = ogg_find_stream (ogg, serial);
247 if (idx < 0){
248 idx = ogg_new_stream (s, serial);
249 if (idx < 0)
250 return -1;
251 }
252
253 os = ogg->streams + idx;
254
255 if(os->psize > 0)
256 ogg_new_buf(ogg, idx);
257
258 if (get_buffer (bc, os->segments, nsegs) < nsegs)
259 return -1;
260
261 os->nsegs = nsegs;
262 os->segp = 0;
263
264 size = 0;
265 for (i = 0; i < nsegs; i++)
266 size += os->segments[i];
267
268 if (flags & OGG_FLAG_CONT){
269 if (!os->psize){
270 while (os->segp < os->nsegs){
271 int seg = os->segments[os->segp++];
272 os->pstart += seg;
273 if (seg < 255)
274 break;
275 }
276 }
277 }else{
278 os->psize = 0;
279 }
280
281 if (os->bufsize - os->bufpos < size){
282 uint8_t *nb = av_malloc (os->bufsize *= 2);
283 memcpy (nb, os->buf, os->bufpos);
284 av_free (os->buf);
285 os->buf = nb;
286 }
287
288 if (get_buffer (bc, os->buf + os->bufpos, size) < size)
289 return -1;
290
291 os->lastgp = os->granule;
292 os->bufpos += size;
293 os->granule = gp;
294 os->flags = flags;
295
296 if (str)
297 *str = idx;
298
299 return 0;
300}
301
302static int
303ogg_packet (AVFormatContext * s, int *str, int *dstart, int *dsize)
304{
305 ogg_t *ogg = s->priv_data;
306 int idx;
307 ogg_stream_t *os;
308 int complete = 0;
309 int segp = 0, psize = 0;
310
311#if 0
312 av_log (s, AV_LOG_DEBUG, "ogg_packet: curidx=%i\n", ogg->curidx);
313#endif
314
315 do{
316 idx = ogg->curidx;
317
318 while (idx < 0){
319 if (ogg_read_page (s, &idx) < 0)
320 return -1;
321 }
322
323 os = ogg->streams + idx;
324
325#if 0
326 av_log (s, AV_LOG_DEBUG,
327 "ogg_packet: idx=%d pstart=%d psize=%d segp=%d nsegs=%d\n",
328 idx, os->pstart, os->psize, os->segp, os->nsegs);
329#endif
330
331 if (!os->codec){
332 if (os->header < 0){
333 os->codec = ogg_find_codec (os->buf, os->bufpos);
334 if (!os->codec){
335 os->header = 0;
336 return 0;
337 }
338 }else{
339 return 0;
340 }
341 }
342
343 segp = os->segp;
344 psize = os->psize;
345
346 while (os->segp < os->nsegs){
347 int ss = os->segments[os->segp++];
348 os->psize += ss;
349 if (ss < 255){
350 complete = 1;
351 break;
352 }
353 }
354
355 if (!complete && os->segp == os->nsegs){
356 ogg->curidx = -1;
357 }
358 }while (!complete);
359
360#if 0
361 av_log (s, AV_LOG_DEBUG,
362 "ogg_packet: idx %i, frame size %i, start %i\n",
363 idx, os->psize, os->pstart);
364#endif
365
366 ogg->curidx = idx;
367
368 if (os->header < 0){
369 int hdr = os->codec->header (s, idx);
370 if (!hdr){
371 os->header = os->seq;
372 os->segp = segp;
373 os->psize = psize;
374 ogg->headers = 1;
375 }else{
376 os->pstart += os->psize;
377 os->psize = 0;
378 }
379 }
380
381 if (os->header > -1 && os->seq > os->header){
382 os->pflags = 0;
383 if (os->codec && os->codec->packet)
384 os->codec->packet (s, idx);
385 if (str)
386 *str = idx;
387 if (dstart)
388 *dstart = os->pstart;
389 if (dsize)
390 *dsize = os->psize;
391 os->pstart += os->psize;
392 os->psize = 0;
393 }
394
395 os->seq++;
396 if (os->segp == os->nsegs)
397 ogg->curidx = -1;
398
399 return 0;
400}
401
402static int
403ogg_get_headers (AVFormatContext * s)
404{
405 ogg_t *ogg = s->priv_data;
406
407 do{
408 if (ogg_packet (s, NULL, NULL, NULL) < 0)
409 return -1;
410 }while (!ogg->headers);
411
412#if 0
413 av_log (s, AV_LOG_DEBUG, "found headers\n");
414#endif
415
416 return 0;
417}
418
419static uint64_t
420ogg_gptopts (AVFormatContext * s, int i, uint64_t gp)
421{
422 ogg_t *ogg = s->priv_data;
423 ogg_stream_t *os = ogg->streams + i;
424 uint64_t pts = AV_NOPTS_VALUE;
425
426 if(os->codec->gptopts){
427 pts = os->codec->gptopts(s, i, gp);
428 } else {
429 pts = gp;
430 }
431
432 return pts;
433}
434
435
436static int
437ogg_get_length (AVFormatContext * s)
438{
439 ogg_t *ogg = s->priv_data;
440 int idx = -1, i;
441 offset_t size, end;
442
443 if(url_is_streamed(s->pb))
444 return 0;
445
446// already set
447 if (s->duration != AV_NOPTS_VALUE)
448 return 0;
449
450 size = url_fsize(s->pb);
451 if(size < 0)
452 return 0;
453 end = size > MAX_PAGE_SIZE? size - MAX_PAGE_SIZE: size;
454
455 ogg_save (s);
456 url_fseek (s->pb, end, SEEK_SET);
457
458 while (!ogg_read_page (s, &i)){
459 if (ogg->streams[i].granule != -1 && ogg->streams[i].granule != 0 &&
460 ogg->streams[i].codec)
461 idx = i;
462 }
463
464 if (idx != -1){
465 s->streams[idx]->duration =
466 ogg_gptopts (s, idx, ogg->streams[idx].granule);
467 }
468
469 ogg->size = size;
470 ogg_restore (s, 0);
471
472 return 0;
473}
474
475
476static int
477ogg_read_header (AVFormatContext * s, AVFormatParameters * ap)
478{
479 ogg_t *ogg = s->priv_data;
480 ogg->curidx = -1;
481 //linear headers seek from start
482 if (ogg_get_headers (s) < 0){
483 return -1;
484 }
485
486 //linear granulepos seek from end
487 ogg_get_length (s);
488
489 //fill the extradata in the per codec callbacks
490 return 0;
491}
492
493
494static int
495ogg_read_packet (AVFormatContext * s, AVPacket * pkt)
496{
497 ogg_t *ogg;
498 ogg_stream_t *os;
499 int idx = -1;
500 int pstart, psize;
501
502 //Get an ogg packet
503 do{
504 if (ogg_packet (s, &idx, &pstart, &psize) < 0)
505 return AVERROR(EIO);
506 }while (idx < 0 || !s->streams[idx]);
507
508 ogg = s->priv_data;
509 os = ogg->streams + idx;
510
511 //Alloc a pkt
512 if (av_new_packet (pkt, psize) < 0)
513 return AVERROR(EIO);
514 pkt->stream_index = idx;
515 memcpy (pkt->data, os->buf + pstart, psize);
516 if (os->lastgp != -1LL){
517 pkt->pts = ogg_gptopts (s, idx, os->lastgp);
518 os->lastgp = -1;
519 }
520
521 pkt->flags = os->pflags;
522
523 return psize;
524}
525
526
527static int
528ogg_read_close (AVFormatContext * s)
529{
530 ogg_t *ogg = s->priv_data;
531 int i;
532
533 for (i = 0; i < ogg->nstreams; i++){
534 av_free (ogg->streams[i].buf);
535 av_free (ogg->streams[i].private);
536 }
537 av_free (ogg->streams);
538 return 0;
539}
540
541
542static int64_t
543ogg_read_timestamp (AVFormatContext * s, int stream_index, int64_t * pos_arg,
544 int64_t pos_limit)
545{
546 ogg_t *ogg = s->priv_data;
547 ByteIOContext *bc = s->pb;
548 int64_t pts = AV_NOPTS_VALUE;
549 int i;
550 url_fseek(bc, *pos_arg, SEEK_SET);
551 while (url_ftell(bc) < pos_limit && !ogg_read_page (s, &i)) {
552 if (ogg->streams[i].granule != -1 && ogg->streams[i].granule != 0 &&
553 ogg->streams[i].codec && i == stream_index) {
554 pts = ogg_gptopts(s, i, ogg->streams[i].granule);
555 // FIXME: this is the position of the packet after the one with above
556 // pts.
557 *pos_arg = url_ftell(bc);
558 break;
559 }
560 }
561 ogg_reset(ogg);
562 return pts;
563}
564
565static int ogg_probe(AVProbeData *p)
566{
567 if (p->buf[0] == 'O' && p->buf[1] == 'g' &&
568 p->buf[2] == 'g' && p->buf[3] == 'S' &&
569 p->buf[4] == 0x0 && p->buf[5] <= 0x7 )
570 return AVPROBE_SCORE_MAX;
571 else
572 return 0;
573}
574
575AVInputFormat ogg_demuxer = {
576 "ogg",
577 NULL_IF_CONFIG_SMALL("Ogg"),
578 sizeof (ogg_t),
579 ogg_probe,
580 ogg_read_header,
581 ogg_read_packet,
582 ogg_read_close,
583 NULL,
584 ogg_read_timestamp,
585 .extensions = "ogg",
586};
diff --git a/src/plugins/ffmpeg/libavformat/oggdec.h b/src/plugins/ffmpeg/libavformat/oggdec.h
deleted file mode 100644
index 4e88d0e..0000000
--- a/src/plugins/ffmpeg/libavformat/oggdec.h
+++ /dev/null
@@ -1,90 +0,0 @@
1/**
2 Copyright (C) 2005 Michael Ahlberg, Måns Rullgård
3
4 Permission is hereby granted, free of charge, to any person
5 obtaining a copy of this software and associated documentation
6 files (the "Software"), to deal in the Software without
7 restriction, including without limitation the rights to use, copy,
8 modify, merge, publish, distribute, sublicense, and/or sell copies
9 of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
11
12 The above copyright notice and this permission notice shall be
13 included in all copies or substantial portions of the Software.
14
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 DEALINGS IN THE SOFTWARE.
23**/
24
25#ifndef FFMPEG_OGGDEC_H
26#define FFMPEG_OGGDEC_H
27
28#include "avformat.h"
29
30typedef struct ogg_codec {
31 const int8_t *magic;
32 uint8_t magicsize;
33 const int8_t *name;
34 int (*header)(AVFormatContext *, int);
35 int (*packet)(AVFormatContext *, int);
36 uint64_t (*gptopts)(AVFormatContext *, int, uint64_t);
37} ogg_codec_t;
38
39typedef struct ogg_stream {
40 uint8_t *buf;
41 unsigned int bufsize;
42 unsigned int bufpos;
43 unsigned int pstart;
44 unsigned int psize;
45 unsigned int pflags;
46 uint32_t serial;
47 uint32_t seq;
48 uint64_t granule, lastgp;
49 int flags;
50 ogg_codec_t *codec;
51 int header;
52 int nsegs, segp;
53 uint8_t segments[255];
54 void *private;
55} ogg_stream_t;
56
57typedef struct ogg_state {
58 uint64_t pos;
59 int curidx;
60 struct ogg_state *next;
61 int nstreams;
62 ogg_stream_t streams[1];
63} ogg_state_t;
64
65typedef struct ogg {
66 ogg_stream_t *streams;
67 int nstreams;
68 int headers;
69 int curidx;
70 uint64_t size;
71 ogg_state_t *state;
72} ogg_t;
73
74#define OGG_FLAG_CONT 1
75#define OGG_FLAG_BOS 2
76#define OGG_FLAG_EOS 4
77
78extern ogg_codec_t flac_codec;
79extern ogg_codec_t ogm_audio_codec;
80extern ogg_codec_t ogm_old_codec;
81extern ogg_codec_t ogm_text_codec;
82extern ogg_codec_t ogm_video_codec;
83extern ogg_codec_t old_flac_codec;
84extern ogg_codec_t speex_codec;
85extern ogg_codec_t theora_codec;
86extern ogg_codec_t vorbis_codec;
87
88extern int vorbis_comment(AVFormatContext *ms, uint8_t *buf, int size);
89
90#endif /* FFMPEG_OGGDEC_H */
diff --git a/src/plugins/ffmpeg/libavformat/oggenc.c b/src/plugins/ffmpeg/libavformat/oggenc.c
deleted file mode 100644
index 9233c72..0000000
--- a/src/plugins/ffmpeg/libavformat/oggenc.c
+++ /dev/null
@@ -1,292 +0,0 @@
1/*
2 * Ogg muxer
3 * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at free dot fr>
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/crc.h"
23#include "libavcodec/xiph.h"
24#include "libavcodec/bytestream.h"
25#include "avformat.h"
26
27typedef struct {
28 int64_t duration;
29 unsigned page_counter;
30 uint8_t *header[3];
31 int header_len[3];
32 /** for theora granule */
33 int kfgshift;
34 int64_t last_kf_pts;
35 int vrev;
36 int eos;
37} OGGStreamContext;
38
39static void ogg_update_checksum(AVFormatContext *s, offset_t crc_offset)
40{
41 offset_t pos = url_ftell(s->pb);
42 uint32_t checksum = get_checksum(s->pb);
43 url_fseek(s->pb, crc_offset, SEEK_SET);
44 put_be32(s->pb, checksum);
45 url_fseek(s->pb, pos, SEEK_SET);
46}
47
48static int ogg_write_page(AVFormatContext *s, const uint8_t *data, int size,
49 int64_t granule, int stream_index, int flags)
50{
51 OGGStreamContext *oggstream = s->streams[stream_index]->priv_data;
52 offset_t crc_offset;
53 int page_segments, i;
54
55 if (size >= 255*255) {
56 granule = -1;
57 size = 255*255;
58 } else if (oggstream->eos)
59 flags |= 4;
60
61 page_segments = FFMIN((size/255)+!!size, 255);
62
63 init_checksum(s->pb, ff_crc04C11DB7_update, 0);
64 put_tag(s->pb, "OggS");
65 put_byte(s->pb, 0);
66 put_byte(s->pb, flags);
67 put_le64(s->pb, granule);
68 put_le32(s->pb, stream_index);
69 put_le32(s->pb, oggstream->page_counter++);
70 crc_offset = url_ftell(s->pb);
71 put_le32(s->pb, 0); // crc
72 put_byte(s->pb, page_segments);
73 for (i = 0; i < page_segments-1; i++)
74 put_byte(s->pb, 255);
75 if (size) {
76 put_byte(s->pb, size - (page_segments-1)*255);
77 put_buffer(s->pb, data, size);
78 }
79 ogg_update_checksum(s, crc_offset);
80 put_flush_packet(s->pb);
81 return size;
82}
83
84static int ogg_build_flac_headers(const uint8_t *extradata, int extradata_size,
85 OGGStreamContext *oggstream, int bitexact)
86{
87 const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
88 uint8_t *p;
89 if (extradata_size != 34)
90 return -1;
91 oggstream->header_len[0] = 51;
92 oggstream->header[0] = av_mallocz(51); // per ogg flac specs
93 p = oggstream->header[0];
94 bytestream_put_byte(&p, 0x7F);
95 bytestream_put_buffer(&p, "FLAC", 4);
96 bytestream_put_byte(&p, 1); // major version
97 bytestream_put_byte(&p, 0); // minor version
98 bytestream_put_be16(&p, 1); // headers packets without this one
99 bytestream_put_buffer(&p, "fLaC", 4);
100 bytestream_put_byte(&p, 0x00); // streaminfo
101 bytestream_put_be24(&p, 34);
102 bytestream_put_buffer(&p, extradata, 34);
103 oggstream->header_len[1] = 1+3+4+strlen(vendor)+4;
104 oggstream->header[1] = av_mallocz(oggstream->header_len[1]);
105 p = oggstream->header[1];
106 bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
107 bytestream_put_be24(&p, oggstream->header_len[1] - 4);
108 bytestream_put_le32(&p, strlen(vendor));
109 bytestream_put_buffer(&p, vendor, strlen(vendor));
110 bytestream_put_le32(&p, 0); // user comment list length
111 return 0;
112}
113
114static int ogg_write_header(AVFormatContext *s)
115{
116 OGGStreamContext *oggstream;
117 int i, j;
118 for (i = 0; i < s->nb_streams; i++) {
119 AVStream *st = s->streams[i];
120 if (st->codec->codec_type == CODEC_TYPE_AUDIO)
121 av_set_pts_info(st, 64, 1, st->codec->sample_rate);
122 else if (st->codec->codec_type == CODEC_TYPE_VIDEO)
123 av_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
124 if (st->codec->codec_id != CODEC_ID_VORBIS &&
125 st->codec->codec_id != CODEC_ID_THEORA &&
126 st->codec->codec_id != CODEC_ID_FLAC) {
127 av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
128 return -1;
129 }
130
131 if (!st->codec->extradata || !st->codec->extradata_size) {
132 av_log(s, AV_LOG_ERROR, "No extradata present\n");
133 return -1;
134 }
135 oggstream = av_mallocz(sizeof(*oggstream));
136 st->priv_data = oggstream;
137 if (st->codec->codec_id == CODEC_ID_FLAC) {
138 if (ogg_build_flac_headers(st->codec->extradata, st->codec->extradata_size,
139 oggstream, st->codec->flags & CODEC_FLAG_BITEXACT) < 0) {
140 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
141 av_freep(&st->priv_data);
142 }
143 } else {
144 if (ff_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
145 st->codec->codec_id == CODEC_ID_VORBIS ? 30 : 42,
146 oggstream->header, oggstream->header_len) < 0) {
147 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
148 av_freep(&st->priv_data);
149 return -1;
150 }
151 if (st->codec->codec_id == CODEC_ID_THEORA) {
152 /** KFGSHIFT is the width of the less significant section of the granule position
153 The less significant section is the frame count since the last keyframe */
154 oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
155 oggstream->vrev = oggstream->header[0][9];
156 av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
157 oggstream->kfgshift, oggstream->vrev);
158 }
159 }
160 }
161 for (i = 0; i < 3; i++) {
162 for (j = 0; j < s->nb_streams; j++) {
163 AVStream *st = s->streams[j];
164 OGGStreamContext *oggstream = st->priv_data;
165 if (oggstream && oggstream->header_len[i]) {
166 ogg_write_page(s, oggstream->header[i], oggstream->header_len[i],
167 0, st->index, i ? 0 : 2); // bos
168 }
169 }
170 }
171 return 0;
172}
173
174static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
175{
176 AVStream *st = s->streams[pkt->stream_index];
177 OGGStreamContext *oggstream = st->priv_data;
178 uint8_t *ptr = pkt->data;
179 int ret, size = pkt->size;
180 int64_t granule;
181
182 if (st->codec->codec_id == CODEC_ID_THEORA) {
183 int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
184 int pframe_count;
185 if (pkt->flags & PKT_FLAG_KEY)
186 oggstream->last_kf_pts = pts;
187 pframe_count = pts - oggstream->last_kf_pts;
188 // prevent frame count from overflow if key frame flag is not set
189 if (pframe_count >= (1<<oggstream->kfgshift)) {
190 oggstream->last_kf_pts += pframe_count;
191 pframe_count = 0;
192 }
193 granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
194 } else
195 granule = pkt->pts + pkt->duration;
196 oggstream->duration = granule;
197 do {
198 ret = ogg_write_page(s, ptr, size, granule, pkt->stream_index, ptr != pkt->data);
199 ptr += ret; size -= ret;
200 } while (size > 0 || ret == 255*255); // need to output a last nil page
201
202 return 0;
203}
204
205int ogg_interleave_per_granule(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
206{
207 AVPacketList *pktl, **next_point, *this_pktl;
208 int stream_count = 0;
209 int streams[MAX_STREAMS] = {0};
210 int interleaved = 0;
211
212 if (pkt) {
213 AVStream *st = s->streams[pkt->stream_index];
214 this_pktl = av_mallocz(sizeof(AVPacketList));
215 this_pktl->pkt = *pkt;
216 if (pkt->destruct == av_destruct_packet)
217 pkt->destruct = NULL; // not shared -> must keep original from being freed
218 else
219 av_dup_packet(&this_pktl->pkt); // shared -> must dup
220 next_point = &s->packet_buffer;
221 while (*next_point) {
222 AVStream *st2 = s->streams[(*next_point)->pkt.stream_index];
223 AVPacket *next_pkt = &(*next_point)->pkt;
224 int64_t cur_granule, next_granule;
225 next_granule = av_rescale_q(next_pkt->pts + next_pkt->duration,
226 st2->time_base, AV_TIME_BASE_Q);
227 cur_granule = av_rescale_q(pkt->pts + pkt->duration,
228 st->time_base, AV_TIME_BASE_Q);
229 if (next_granule > cur_granule)
230 break;
231 next_point= &(*next_point)->next;
232 }
233 this_pktl->next= *next_point;
234 *next_point= this_pktl;
235 }
236
237 pktl = s->packet_buffer;
238 while (pktl) {
239 if (streams[pktl->pkt.stream_index] == 0)
240 stream_count++;
241 streams[pktl->pkt.stream_index]++;
242 // need to buffer at least one packet to set eos flag
243 if (streams[pktl->pkt.stream_index] == 2)
244 interleaved++;
245 pktl = pktl->next;
246 }
247
248 if ((s->nb_streams == stream_count && interleaved == stream_count) ||
249 (flush && stream_count)) {
250 pktl= s->packet_buffer;
251 *out= pktl->pkt;
252 s->packet_buffer = pktl->next;
253 if (flush && streams[out->stream_index] == 1) {
254 OGGStreamContext *ogg = s->streams[out->stream_index]->priv_data;
255 ogg->eos = 1;
256 }
257 av_freep(&pktl);
258 return 1;
259 } else {
260 av_init_packet(out);
261 return 0;
262 }
263}
264
265static int ogg_write_trailer(AVFormatContext *s)
266{
267 int i;
268 for (i = 0; i < s->nb_streams; i++) {
269 AVStream *st = s->streams[i];
270 OGGStreamContext *oggstream = st->priv_data;
271 if (st->codec->codec_id == CODEC_ID_FLAC) {
272 av_free(oggstream->header[0]);
273 av_free(oggstream->header[1]);
274 }
275 av_freep(&st->priv_data);
276 }
277 return 0;
278}
279
280AVOutputFormat ogg_muxer = {
281 "ogg",
282 NULL_IF_CONFIG_SMALL("Ogg"),
283 "application/ogg",
284 "ogg,ogv",
285 0,
286 CODEC_ID_FLAC,
287 CODEC_ID_THEORA,
288 ogg_write_header,
289 ogg_write_packet,
290 ogg_write_trailer,
291 .interleave_packet = ogg_interleave_per_granule,
292};
diff --git a/src/plugins/ffmpeg/libavformat/oggparseflac.c b/src/plugins/ffmpeg/libavformat/oggparseflac.c
deleted file mode 100644
index 386a70e..0000000
--- a/src/plugins/ffmpeg/libavformat/oggparseflac.c
+++ /dev/null
@@ -1,98 +0,0 @@
1/*
2 * Copyright (C) 2005 Matthieu CASTET
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21#include <stdlib.h>
22#include "libavcodec/bitstream.h"
23#include "avformat.h"
24#include "oggdec.h"
25
26#define FLAC_STREAMINFO_SIZE 0x22
27
28static int
29flac_header (AVFormatContext * s, int idx)
30{
31 ogg_t *ogg = s->priv_data;
32 ogg_stream_t *os = ogg->streams + idx;
33 AVStream *st = s->streams[idx];
34 GetBitContext gb;
35 int mdt;
36
37 if (os->buf[os->pstart] == 0xff)
38 return 0;
39
40 init_get_bits(&gb, os->buf + os->pstart, os->psize*8);
41 get_bits(&gb, 1); /* metadata_last */
42 mdt = get_bits(&gb, 7);
43
44 if (mdt == 0x7f) {
45 skip_bits(&gb, 4*8); /* "FLAC" */
46 if(get_bits(&gb, 8) != 1) /* unsupported major version */
47 return -1;
48 skip_bits(&gb, 8 + 16); /* minor version + header count */
49 skip_bits(&gb, 4*8); /* "fLaC" */
50
51 /* METADATA_BLOCK_HEADER */
52 if (get_bits_long(&gb, 32) != FLAC_STREAMINFO_SIZE)
53 return -1;
54
55 skip_bits(&gb, 16*2+24*2);
56
57 st->codec->sample_rate = get_bits_long(&gb, 20);
58 st->codec->channels = get_bits(&gb, 3) + 1;
59
60 st->codec->codec_type = CODEC_TYPE_AUDIO;
61 st->codec->codec_id = CODEC_ID_FLAC;
62
63 st->codec->extradata =
64 av_malloc(FLAC_STREAMINFO_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
65 memcpy (st->codec->extradata, os->buf + os->pstart + 5 + 4 + 4 + 4,
66 FLAC_STREAMINFO_SIZE);
67 st->codec->extradata_size = FLAC_STREAMINFO_SIZE;
68
69 st->time_base.num = 1;
70 st->time_base.den = st->codec->sample_rate;
71 } else if (mdt == 4) {
72 vorbis_comment (s, os->buf + os->pstart + 4, os->psize - 4);
73 }
74
75 return 1;
76}
77
78static int
79old_flac_header (AVFormatContext * s, int idx)
80{
81 AVStream *st = s->streams[idx];
82 st->codec->codec_type = CODEC_TYPE_AUDIO;
83 st->codec->codec_id = CODEC_ID_FLAC;
84
85 return 0;
86}
87
88ogg_codec_t flac_codec = {
89 .magic = "\177FLAC",
90 .magicsize = 5,
91 .header = flac_header
92};
93
94ogg_codec_t old_flac_codec = {
95 .magic = "fLaC",
96 .magicsize = 4,
97 .header = old_flac_header
98};
diff --git a/src/plugins/ffmpeg/libavformat/oggparseogm.c b/src/plugins/ffmpeg/libavformat/oggparseogm.c
deleted file mode 100644
index af1e4cf..0000000
--- a/src/plugins/ffmpeg/libavformat/oggparseogm.c
+++ /dev/null
@@ -1,178 +0,0 @@
1/**
2 Copyright (C) 2005 Michael Ahlberg, Måns Rullgård
3
4 Permission is hereby granted, free of charge, to any person
5 obtaining a copy of this software and associated documentation
6 files (the "Software"), to deal in the Software without
7 restriction, including without limitation the rights to use, copy,
8 modify, merge, publish, distribute, sublicense, and/or sell copies
9 of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
11
12 The above copyright notice and this permission notice shall be
13 included in all copies or substantial portions of the Software.
14
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 DEALINGS IN THE SOFTWARE.
23**/
24
25#include <stdlib.h>
26#include "libavutil/intreadwrite.h"
27#include "libavcodec/bitstream.h"
28#include "libavcodec/bytestream.h"
29#include "avformat.h"
30#include "oggdec.h"
31#include "riff.h"
32
33static int
34ogm_header(AVFormatContext *s, int idx)
35{
36 ogg_t *ogg = s->priv_data;
37 ogg_stream_t *os = ogg->streams + idx;
38 AVStream *st = s->streams[idx];
39 const uint8_t *p = os->buf + os->pstart;
40 uint64_t time_unit;
41 uint64_t spu;
42 uint32_t default_len;
43
44 if(!(*p & 1))
45 return 0;
46 if(*p != 1)
47 return 1;
48
49 p++;
50
51 if(*p == 'v'){
52 int tag;
53 st->codec->codec_type = CODEC_TYPE_VIDEO;
54 p += 8;
55 tag = bytestream_get_le32(&p);
56 st->codec->codec_id = codec_get_id(codec_bmp_tags, tag);
57 st->codec->codec_tag = tag;
58 } else if (*p == 't') {
59 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
60 st->codec->codec_id = CODEC_ID_TEXT;
61 p += 12;
62 } else {
63 uint8_t acid[5];
64 int cid;
65 st->codec->codec_type = CODEC_TYPE_AUDIO;
66 p += 8;
67 bytestream_get_buffer(&p, acid, 4);
68 acid[4] = 0;
69 cid = strtol(acid, NULL, 16);
70 st->codec->codec_id = codec_get_id(codec_wav_tags, cid);
71 st->need_parsing = AVSTREAM_PARSE_FULL;
72 }
73
74 p += 4; /* useless size field */
75
76 time_unit = bytestream_get_le64(&p);
77 spu = bytestream_get_le64(&p);
78 default_len = bytestream_get_le32(&p);
79
80 p += 8; /* buffersize + bits_per_sample */
81
82 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
83 st->codec->width = bytestream_get_le32(&p);
84 st->codec->height = bytestream_get_le32(&p);
85 st->codec->time_base.den = spu * 10000000;
86 st->codec->time_base.num = time_unit;
87 st->time_base = st->codec->time_base;
88 } else {
89 st->codec->channels = bytestream_get_le16(&p);
90 p += 2; /* block_align */
91 st->codec->bit_rate = bytestream_get_le32(&p) * 8;
92 st->codec->sample_rate = spu * 10000000 / time_unit;
93 st->time_base.num = 1;
94 st->time_base.den = st->codec->sample_rate;
95 }
96
97 return 1;
98}
99
100static int
101ogm_dshow_header(AVFormatContext *s, int idx)
102{
103 ogg_t *ogg = s->priv_data;
104 ogg_stream_t *os = ogg->streams + idx;
105 AVStream *st = s->streams[idx];
106 uint8_t *p = os->buf + os->pstart;
107 uint32_t t;
108
109 if(!(*p & 1))
110 return 0;
111 if(*p != 1)
112 return 1;
113
114 t = AV_RL32(p + 96);
115
116 if(t == 0x05589f80){
117 st->codec->codec_type = CODEC_TYPE_VIDEO;
118 st->codec->codec_id = codec_get_id(codec_bmp_tags, AV_RL32(p + 68));
119 st->codec->time_base.den = 10000000;
120 st->codec->time_base.num = AV_RL64(p + 164);
121 st->codec->width = AV_RL32(p + 176);
122 st->codec->height = AV_RL32(p + 180);
123 } else if(t == 0x05589f81){
124 st->codec->codec_type = CODEC_TYPE_AUDIO;
125 st->codec->codec_id = codec_get_id(codec_wav_tags, AV_RL16(p + 124));
126 st->codec->channels = AV_RL16(p + 126);
127 st->codec->sample_rate = AV_RL32(p + 128);
128 st->codec->bit_rate = AV_RL32(p + 132) * 8;
129 }
130
131 return 1;
132}
133
134static int
135ogm_packet(AVFormatContext *s, int idx)
136{
137 ogg_t *ogg = s->priv_data;
138 ogg_stream_t *os = ogg->streams + idx;
139 uint8_t *p = os->buf + os->pstart;
140 int lb;
141
142 if(*p & 8)
143 os->pflags |= PKT_FLAG_KEY;
144
145 lb = ((*p & 2) << 1) | ((*p >> 6) & 3);
146 os->pstart += lb + 1;
147 os->psize -= lb + 1;
148
149 return 0;
150}
151
152ogg_codec_t ogm_video_codec = {
153 .magic = "\001video",
154 .magicsize = 6,
155 .header = ogm_header,
156 .packet = ogm_packet
157};
158
159ogg_codec_t ogm_audio_codec = {
160 .magic = "\001audio",
161 .magicsize = 6,
162 .header = ogm_header,
163 .packet = ogm_packet
164};
165
166ogg_codec_t ogm_text_codec = {
167 .magic = "\001text",
168 .magicsize = 5,
169 .header = ogm_header,
170 .packet = ogm_packet
171};
172
173ogg_codec_t ogm_old_codec = {
174 .magic = "\001Direct Show Samples embedded in Ogg",
175 .magicsize = 35,
176 .header = ogm_dshow_header,
177 .packet = ogm_packet
178};
diff --git a/src/plugins/ffmpeg/libavformat/oggparsespeex.c b/src/plugins/ffmpeg/libavformat/oggparsespeex.c
deleted file mode 100644
index ad2f0b7..0000000
--- a/src/plugins/ffmpeg/libavformat/oggparsespeex.c
+++ /dev/null
@@ -1,61 +0,0 @@
1/*
2 Copyright (C) 2008 Reimar Döffinger
3
4 Permission is hereby granted, free of charge, to any person
5 obtaining a copy of this software and associated documentation
6 files (the "Software"), to deal in the Software without
7 restriction, including without limitation the rights to use, copy,
8 modify, merge, publish, distribute, sublicense, and/or sell copies
9 of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
11
12 The above copyright notice and this permission notice shall be
13 included in all copies or substantial portions of the Software.
14
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 DEALINGS IN THE SOFTWARE.
23**/
24
25#include <stdlib.h>
26#include "libavutil/bswap.h"
27#include "libavutil/avstring.h"
28#include "libavcodec/bitstream.h"
29#include "libavcodec/bytestream.h"
30#include "avformat.h"
31#include "oggdec.h"
32
33static int speex_header(AVFormatContext *s, int idx) {
34 ogg_t *ogg = s->priv_data;
35 ogg_stream_t *os = ogg->streams + idx;
36 AVStream *st = s->streams[idx];
37 uint8_t *p = os->buf + os->pstart;
38
39 if (os->psize < 80)
40 return 1;
41
42 st->codec->codec_type = CODEC_TYPE_AUDIO;
43 st->codec->codec_id = CODEC_ID_SPEEX;
44
45 st->codec->sample_rate = AV_RL32(p + 36);
46 st->codec->channels = AV_RL32(p + 48);
47 st->codec->extradata_size = os->psize;
48 st->codec->extradata = av_malloc(st->codec->extradata_size);
49 memcpy(st->codec->extradata, p, st->codec->extradata_size);
50
51 st->time_base.num = 1;
52 st->time_base.den = st->codec->sample_rate;
53
54 return 0;
55}
56
57ogg_codec_t speex_codec = {
58 .magic = "Speex ",
59 .magicsize = 8,
60 .header = speex_header
61};
diff --git a/src/plugins/ffmpeg/libavformat/oggparsetheora.c b/src/plugins/ffmpeg/libavformat/oggparsetheora.c
deleted file mode 100644
index 36848b1..0000000
--- a/src/plugins/ffmpeg/libavformat/oggparsetheora.c
+++ /dev/null
@@ -1,138 +0,0 @@
1/**
2 Copyright (C) 2005 Matthieu CASTET, Alex Beregszaszi
3
4 Permission is hereby granted, free of charge, to any person
5 obtaining a copy of this software and associated documentation
6 files (the "Software"), to deal in the Software without
7 restriction, including without limitation the rights to use, copy,
8 modify, merge, publish, distribute, sublicense, and/or sell copies
9 of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
11
12 The above copyright notice and this permission notice shall be
13 included in all copies or substantial portions of the Software.
14
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 DEALINGS IN THE SOFTWARE.
23**/
24
25#include <stdlib.h>
26#include "libavutil/bswap.h"
27#include "libavcodec/bitstream.h"
28#include "avformat.h"
29#include "oggdec.h"
30
31typedef struct theora_params {
32 int gpshift;
33 int gpmask;
34} theora_params_t;
35
36static int
37theora_header (AVFormatContext * s, int idx)
38{
39 ogg_t *ogg = s->priv_data;
40 ogg_stream_t *os = ogg->streams + idx;
41 AVStream *st = s->streams[idx];
42 theora_params_t *thp = os->private;
43 int cds = st->codec->extradata_size + os->psize + 2;
44 uint8_t *cdp;
45
46 if(!(os->buf[os->pstart] & 0x80))
47 return 0;
48
49 if(!thp){
50 thp = av_mallocz(sizeof(*thp));
51 os->private = thp;
52 }
53
54 if (os->buf[os->pstart] == 0x80) {
55 GetBitContext gb;
56 int width, height;
57 int version;
58
59 init_get_bits(&gb, os->buf + os->pstart, os->psize*8);
60
61 skip_bits(&gb, 7*8); /* 0x80"theora" */
62
63 version = get_bits_long(&gb, 24);
64 if (version < 0x030100)
65 {
66 av_log(s, AV_LOG_ERROR,
67 "Too old or unsupported Theora (%x)\n", version);
68 return -1;
69 }
70
71 width = get_bits(&gb, 16) << 4;
72 height = get_bits(&gb, 16) << 4;
73 avcodec_set_dimensions(st->codec, width, height);
74
75 if (version >= 0x030400)
76 skip_bits(&gb, 100);
77
78 width = get_bits_long(&gb, 24);
79 height = get_bits_long(&gb, 24);
80 if ( width <= st->codec->width && width > st->codec->width-16
81 && height <= st->codec->height && height > st->codec->height-16)
82 avcodec_set_dimensions(st->codec, width, height);
83
84 if (version >= 0x030200)
85 skip_bits(&gb, 16);
86 st->codec->time_base.den = get_bits_long(&gb, 32);
87 st->codec->time_base.num = get_bits_long(&gb, 32);
88 st->time_base = st->codec->time_base;
89
90 st->codec->sample_aspect_ratio.num = get_bits_long(&gb, 24);
91 st->codec->sample_aspect_ratio.den = get_bits_long(&gb, 24);
92
93 if (version >= 0x030200)
94 skip_bits(&gb, 38);
95 if (version >= 0x304000)
96 skip_bits(&gb, 2);
97
98 thp->gpshift = get_bits(&gb, 5);
99 thp->gpmask = (1 << thp->gpshift) - 1;
100
101 st->codec->codec_type = CODEC_TYPE_VIDEO;
102 st->codec->codec_id = CODEC_ID_THEORA;
103
104 } else if (os->buf[os->pstart] == 0x83) {
105 vorbis_comment (s, os->buf + os->pstart + 7, os->psize - 8);
106 }
107
108 st->codec->extradata = av_realloc (st->codec->extradata, cds);
109 cdp = st->codec->extradata + st->codec->extradata_size;
110 *cdp++ = os->psize >> 8;
111 *cdp++ = os->psize & 0xff;
112 memcpy (cdp, os->buf + os->pstart, os->psize);
113 st->codec->extradata_size = cds;
114
115 return 1;
116}
117
118static uint64_t
119theora_gptopts(AVFormatContext *ctx, int idx, uint64_t gp)
120{
121 ogg_t *ogg = ctx->priv_data;
122 ogg_stream_t *os = ogg->streams + idx;
123 theora_params_t *thp = os->private;
124 uint64_t iframe = gp >> thp->gpshift;
125 uint64_t pframe = gp & thp->gpmask;
126
127 if(!pframe)
128 os->pflags |= PKT_FLAG_KEY;
129
130 return iframe + pframe;
131}
132
133ogg_codec_t theora_codec = {
134 .magic = "\200theora",
135 .magicsize = 7,
136 .header = theora_header,
137 .gptopts = theora_gptopts
138};
diff --git a/src/plugins/ffmpeg/libavformat/oggparsevorbis.c b/src/plugins/ffmpeg/libavformat/oggparsevorbis.c
deleted file mode 100644
index b116273..0000000
--- a/src/plugins/ffmpeg/libavformat/oggparsevorbis.c
+++ /dev/null
@@ -1,226 +0,0 @@
1/**
2 Copyright (C) 2005 Michael Ahlberg, Måns Rullgård
3
4 Permission is hereby granted, free of charge, to any person
5 obtaining a copy of this software and associated documentation
6 files (the "Software"), to deal in the Software without
7 restriction, including without limitation the rights to use, copy,
8 modify, merge, publish, distribute, sublicense, and/or sell copies
9 of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
11
12 The above copyright notice and this permission notice shall be
13 included in all copies or substantial portions of the Software.
14
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 DEALINGS IN THE SOFTWARE.
23**/
24
25#include <stdlib.h>
26#include "libavutil/avstring.h"
27#include "libavutil/bswap.h"
28#include "libavcodec/bitstream.h"
29#include "libavcodec/bytestream.h"
30#include "avformat.h"
31#include "oggdec.h"
32
33extern int
34vorbis_comment(AVFormatContext * as, uint8_t *buf, int size)
35{
36 const uint8_t *p = buf;
37 const uint8_t *end = buf + size;
38 unsigned s, n, j;
39
40 if (size < 8) /* must have vendor_length and user_comment_list_length */
41 return -1;
42
43 s = bytestream_get_le32(&p);
44
45 if (end - p < s)
46 return -1;
47
48 p += s;
49
50 n = bytestream_get_le32(&p);
51
52 while (p < end && n > 0) {
53 const char *t, *v;
54 int tl, vl;
55
56 s = bytestream_get_le32(&p);
57
58 if (end - p < s)
59 break;
60
61 t = p;
62 p += s;
63 n--;
64
65 v = memchr(t, '=', s);
66 if (!v)
67 continue;
68
69 tl = v - t;
70 vl = s - tl - 1;
71 v++;
72
73 if (tl && vl) {
74 char tt[tl + 1];
75 char ct[vl + 1];
76
77 for (j = 0; j < tl; j++)
78 tt[j] = toupper(t[j]);
79 tt[tl] = 0;
80
81 memcpy(ct, v, vl);
82 ct[vl] = 0;
83
84 // took from Vorbis_I_spec
85 if (!strcmp(tt, "AUTHOR") || !strcmp(tt, "ARTIST"))
86 av_strlcpy(as->author, ct, sizeof(as->author));
87 else if (!strcmp(tt, "TITLE"))
88 av_strlcpy(as->title, ct, sizeof(as->title));
89 else if (!strcmp(tt, "COPYRIGHT"))
90 av_strlcpy(as->copyright, ct, sizeof(as->copyright));
91 else if (!strcmp(tt, "DESCRIPTION"))
92 av_strlcpy(as->comment, ct, sizeof(as->comment));
93 else if (!strcmp(tt, "GENRE"))
94 av_strlcpy(as->genre, ct, sizeof(as->genre));
95 else if (!strcmp(tt, "TRACKNUMBER"))
96 as->track = atoi(ct);
97 else if (!strcmp(tt, "ALBUM"))
98 av_strlcpy(as->album, ct, sizeof(as->album));
99 }
100 }
101
102 if (p != end)
103 av_log(as, AV_LOG_INFO, "%ti bytes of comment header remain\n", p-end);
104 if (n > 0)
105 av_log(as, AV_LOG_INFO,
106 "truncated comment header, %i comments not found\n", n);
107
108 return 0;
109}
110
111
112/** Parse the vorbis header
113 * Vorbis Identification header from Vorbis_I_spec.html#vorbis-spec-codec
114 * [vorbis_version] = read 32 bits as unsigned integer | Not used
115 * [audio_channels] = read 8 bit integer as unsigned | Used
116 * [audio_sample_rate] = read 32 bits as unsigned integer | Used
117 * [bitrate_maximum] = read 32 bits as signed integer | Not used yet
118 * [bitrate_nominal] = read 32 bits as signed integer | Not used yet
119 * [bitrate_minimum] = read 32 bits as signed integer | Used as bitrate
120 * [blocksize_0] = read 4 bits as unsigned integer | Not Used
121 * [blocksize_1] = read 4 bits as unsigned integer | Not Used
122 * [framing_flag] = read one bit | Not Used
123 * */
124
125typedef struct {
126 unsigned int len[3];
127 unsigned char *packet[3];
128} oggvorbis_private_t;
129
130
131static unsigned int
132fixup_vorbis_headers(AVFormatContext * as, oggvorbis_private_t *priv,
133 uint8_t **buf)
134{
135 int i,offset, len;
136 unsigned char *ptr;
137
138 len = priv->len[0] + priv->len[1] + priv->len[2];
139 ptr = *buf = av_mallocz(len + len/255 + 64);
140
141 ptr[0] = 2;
142 offset = 1;
143 offset += av_xiphlacing(&ptr[offset], priv->len[0]);
144 offset += av_xiphlacing(&ptr[offset], priv->len[1]);
145 for (i = 0; i < 3; i++) {
146 memcpy(&ptr[offset], priv->packet[i], priv->len[i]);
147 offset += priv->len[i];
148 }
149 *buf = av_realloc(*buf, offset + FF_INPUT_BUFFER_PADDING_SIZE);
150 return offset;
151}
152
153
154static int
155vorbis_header (AVFormatContext * s, int idx)
156{
157 ogg_t *ogg = s->priv_data;
158 ogg_stream_t *os = ogg->streams + idx;
159 AVStream *st = s->streams[idx];
160 oggvorbis_private_t *priv;
161
162 if (os->seq > 2)
163 return 0;
164
165 if (os->seq == 0) {
166 os->private = av_mallocz(sizeof(oggvorbis_private_t));
167 if (!os->private)
168 return 0;
169 }
170
171 if (os->psize < 1)
172 return -1;
173
174 priv = os->private;
175 priv->len[os->seq] = os->psize;
176 priv->packet[os->seq] = av_mallocz(os->psize);
177 memcpy(priv->packet[os->seq], os->buf + os->pstart, os->psize);
178 if (os->buf[os->pstart] == 1) {
179 const uint8_t *p = os->buf + os->pstart + 7; /* skip "\001vorbis" tag */
180 unsigned blocksize, bs0, bs1;
181
182 if (os->psize != 30)
183 return -1;
184
185 if (bytestream_get_le32(&p) != 0) /* vorbis_version */
186 return -1;
187
188 st->codec->channels = bytestream_get_byte(&p);
189 st->codec->sample_rate = bytestream_get_le32(&p);
190 p += 4; // skip maximum bitrate
191 st->codec->bit_rate = bytestream_get_le32(&p); // nominal bitrate
192 p += 4; // skip minimum bitrate
193
194 blocksize = bytestream_get_byte(&p);
195 bs0 = blocksize & 15;
196 bs1 = blocksize >> 4;
197
198 if (bs0 > bs1)
199 return -1;
200 if (bs0 < 6 || bs1 > 13)
201 return -1;
202
203 if (bytestream_get_byte(&p) != 1) /* framing_flag */
204 return -1;
205
206 st->codec->codec_type = CODEC_TYPE_AUDIO;
207 st->codec->codec_id = CODEC_ID_VORBIS;
208
209 st->time_base.num = 1;
210 st->time_base.den = st->codec->sample_rate;
211 } else if (os->buf[os->pstart] == 3) {
212 if (os->psize > 8)
213 vorbis_comment (s, os->buf + os->pstart + 7, os->psize - 8);
214 } else {
215 st->codec->extradata_size =
216 fixup_vorbis_headers(s, priv, &st->codec->extradata);
217 }
218
219 return os->seq < 3;
220}
221
222ogg_codec_t vorbis_codec = {
223 .magic = "\001vorbis",
224 .magicsize = 7,
225 .header = vorbis_header
226};
diff --git a/src/plugins/ffmpeg/libavformat/oma.c b/src/plugins/ffmpeg/libavformat/oma.c
deleted file mode 100644
index 653f413..0000000
--- a/src/plugins/ffmpeg/libavformat/oma.c
+++ /dev/null
@@ -1,200 +0,0 @@
1/*
2 * Sony OpenMG (OMA) demuxer
3 *
4 * Copyright (c) 2008 Maxim Poliakovski
5 * 2008 Benjamin Larsson
6 *
7 * This file is part of FFmpeg.
8 *
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23
24/**
25 * @file oma.c
26 * This is a demuxer for Sony OpenMG Music files
27 *
28 * Known file extensions: ".oma", "aa3"
29 * The format of such files consists of three parts:
30 * - "ea3" header carrying overall info and metadata.
31 * - "EA3" header is a Sony-specific header containing information about
32 * the OpenMG file: codec type (usually ATRAC, can also be MP3 or WMA),
33 * codec specific info (packet size, sample rate, channels and so on)
34 * and DRM related info (file encryption, content id).
35 * - Sound data organized in packets follow the EA3 header
36 * (can be encrypted using the Sony DRM!).
37 *
38 * LIMITATIONS: This version supports only plain (unencrypted) OMA files.
39 * If any DRM-protected (encrypted) file is encountered you will get the
40 * corresponding error message. Try to remove the encryption using any
41 * Sony software (for example SonicStage).
42 * CODEC SUPPORT: Only ATRAC3 codec is currently supported!
43 */
44
45#include "avformat.h"
46#include "libavutil/intreadwrite.h"
47#include "raw.h"
48#include "riff.h"
49
50#define EA3_HEADER_SIZE 96
51
52enum {
53 OMA_CODECID_ATRAC3 = 0,
54 OMA_CODECID_ATRAC3P = 1,
55 OMA_CODECID_MP3 = 3,
56 OMA_CODECID_LPCM = 4,
57 OMA_CODECID_WMA = 5,
58};
59
60static const AVCodecTag codec_oma_tags[] = {
61 { CODEC_ID_ATRAC3, OMA_CODECID_ATRAC3 },
62 { CODEC_ID_ATRAC3P, OMA_CODECID_ATRAC3P },
63 { CODEC_ID_MP3, OMA_CODECID_MP3 },
64};
65
66static int oma_read_header(AVFormatContext *s,
67 AVFormatParameters *ap)
68{
69 static const uint16_t srate_tab[6] = {320,441,480,882,960,0};
70 int ret, ea3_taglen, EA3_pos, framesize, jsflag, samplerate;
71 uint32_t codec_params;
72 int16_t eid;
73 uint8_t buf[EA3_HEADER_SIZE];
74 uint8_t *edata;
75 AVStream *st;
76
77 ret = get_buffer(s->pb, buf, 10);
78 if (ret != 10)
79 return -1;
80
81 ea3_taglen = ((buf[6] & 0x7f) << 21) | ((buf[7] & 0x7f) << 14) | ((buf[8] & 0x7f) << 7) | (buf[9] & 0x7f);
82
83 EA3_pos = ea3_taglen + 10;
84 if (buf[5] & 0x10)
85 EA3_pos += 10;
86
87 url_fseek(s->pb, EA3_pos, SEEK_SET);
88 ret = get_buffer(s->pb, buf, EA3_HEADER_SIZE);
89 if (ret != EA3_HEADER_SIZE)
90 return -1;
91
92 if (memcmp(buf, (uint8_t[]){'E', 'A', '3'},3) || buf[4] != 0 || buf[5] != EA3_HEADER_SIZE) {
93 av_log(s, AV_LOG_ERROR, "Couldn't find the EA3 header !\n");
94 return -1;
95 }
96
97 eid = AV_RB16(&buf[6]);
98 if (eid != -1 && eid != -128) {
99 av_log(s, AV_LOG_ERROR, "Encrypted file! Eid: %d\n", eid);
100 return -1;
101 }
102
103 codec_params = AV_RB24(&buf[33]);
104
105 st = av_new_stream(s, 0);
106 if (!st)
107 return AVERROR(ENOMEM);
108
109 st->start_time = 0;
110 st->codec->codec_type = CODEC_TYPE_AUDIO;
111 st->codec->codec_tag = buf[32];
112 st->codec->codec_id = codec_get_id(codec_oma_tags, st->codec->codec_tag);
113
114 switch (buf[32]) {
115 case OMA_CODECID_ATRAC3:
116 samplerate = srate_tab[(codec_params >> 13) & 7]*100;
117 if (samplerate != 44100)
118 av_log(s, AV_LOG_ERROR, "Unsupported sample rate, send sample file to developers: %d\n", samplerate);
119
120 framesize = (codec_params & 0x3FF) * 8;
121 jsflag = (codec_params >> 17) & 1; /* get stereo coding mode, 1 for joint-stereo */
122 st->codec->channels = 2;
123 st->codec->sample_rate = samplerate;
124 st->codec->bit_rate = st->codec->sample_rate * framesize * 8 / 1024;
125
126 /* fake the atrac3 extradata (wav format, makes stream copy to wav work) */
127 st->codec->extradata_size = 14;
128 edata = av_mallocz(14 + FF_INPUT_BUFFER_PADDING_SIZE);
129 if (!edata)
130 return AVERROR(ENOMEM);
131
132 st->codec->extradata = edata;
133 AV_WL16(&edata[0], 1); // always 1
134 AV_WL32(&edata[2], samplerate); // samples rate
135 AV_WL16(&edata[6], jsflag); // coding mode
136 AV_WL16(&edata[8], jsflag); // coding mode
137 AV_WL16(&edata[10], 1); // always 1
138 // AV_WL16(&edata[12], 0); // always 0
139
140 av_set_pts_info(st, 64, 1, st->codec->sample_rate);
141 break;
142 case OMA_CODECID_ATRAC3P:
143 st->codec->channels = (codec_params >> 10) & 7;
144 framesize = ((codec_params & 0x3FF) * 8) + 8;
145 st->codec->sample_rate = srate_tab[(codec_params >> 13) & 7]*100;
146 st->codec->bit_rate = st->codec->sample_rate * framesize * 8 / 1024;
147 av_set_pts_info(st, 64, 1, st->codec->sample_rate);
148 av_log(s, AV_LOG_ERROR, "Unsupported codec ATRAC3+!\n");
149 break;
150 case OMA_CODECID_MP3:
151 st->need_parsing = AVSTREAM_PARSE_FULL;
152 framesize = 1024;
153 break;
154 default:
155 av_log(s, AV_LOG_ERROR, "Unsupported codec %d!\n",buf[32]);
156 return -1;
157 break;
158 }
159
160 st->codec->block_align = framesize;
161 url_fseek(s->pb, EA3_pos + EA3_HEADER_SIZE, SEEK_SET);
162
163 return 0;
164}
165
166
167static int oma_read_packet(AVFormatContext *s, AVPacket *pkt)
168{
169 int ret = av_get_packet(s->pb, pkt, s->streams[0]->codec->block_align);
170
171 pkt->stream_index = 0;
172 if (ret <= 0)
173 return AVERROR(EIO);
174
175 return ret;
176}
177
178static int oma_read_probe(AVProbeData *p)
179{
180 if (!memcmp(p->buf, (uint8_t[]){'e', 'a', '3', 3, 0},5))
181 return AVPROBE_SCORE_MAX;
182 else
183 return 0;
184}
185
186
187AVInputFormat oma_demuxer = {
188 "oma",
189 NULL_IF_CONFIG_SMALL("Sony OpenMG audio"),
190 0,
191 oma_read_probe,
192 oma_read_header,
193 oma_read_packet,
194 0,
195 pcm_read_seek,
196 .flags= AVFMT_GENERIC_INDEX,
197 .extensions = "oma,aa3",
198 .codec_tag= (const AVCodecTag*[]){codec_oma_tags, 0},
199};
200
diff --git a/src/plugins/ffmpeg/libavformat/os_support.c b/src/plugins/ffmpeg/libavformat/os_support.c
deleted file mode 100644
index cc109d5..0000000
--- a/src/plugins/ffmpeg/libavformat/os_support.c
+++ /dev/null
@@ -1,155 +0,0 @@
1/*
2 * Various utilities for ffmpeg system
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4 * copyright (c) 2002 Francois Revol
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22#include "config.h"
23#include "avformat.h"
24#include <unistd.h>
25#include <fcntl.h>
26#include "os_support.h"
27
28#ifdef CONFIG_NETWORK
29#ifndef HAVE_POLL_H
30#ifdef HAVE_WINSOCK2_H
31#include <winsock2.h>
32#elif defined (HAVE_SYS_SELECT_H)
33#include <sys/select.h>
34#endif
35#endif
36
37#include "network.h"
38
39#if !defined(HAVE_INET_ATON)
40#include <stdlib.h>
41#include <strings.h>
42
43int inet_aton (const char * str, struct in_addr * add)
44{
45 unsigned int add1 = 0, add2 = 0, add3 = 0, add4 = 0;
46
47 if (sscanf(str, "%d.%d.%d.%d", &add1, &add2, &add3, &add4) != 4)
48 return 0;
49
50 if (!add1 || (add1|add2|add3|add4) > 255) return 0;
51
52 add->s_addr=(add4<<24)+(add3<<16)+(add2<<8)+add1;
53
54 return 1;
55}
56#endif /* !defined(HAVE_INET_ATON) */
57
58/* resolve host with also IP address parsing */
59int resolve_host(struct in_addr *sin_addr, const char *hostname)
60{
61 struct hostent *hp;
62
63 if (!inet_aton(hostname, sin_addr)) {
64 hp = gethostbyname(hostname);
65 if (!hp)
66 return -1;
67 memcpy(sin_addr, hp->h_addr, sizeof(struct in_addr));
68 }
69 return 0;
70}
71
72int ff_socket_nonblock(int socket, int enable)
73{
74#ifdef HAVE_WINSOCK2_H
75 return ioctlsocket(socket, FIONBIO, &enable);
76#else
77 if (enable)
78 return fcntl(socket, F_SETFL, fcntl(socket, F_GETFL) | O_NONBLOCK);
79 else
80 return fcntl(socket, F_SETFL, fcntl(socket, F_GETFL) & ~O_NONBLOCK);
81#endif
82}
83#endif /* CONFIG_NETWORK */
84
85#ifdef CONFIG_FFSERVER
86#ifndef HAVE_POLL_H
87int poll(struct pollfd *fds, nfds_t numfds, int timeout)
88{
89 fd_set read_set;
90 fd_set write_set;
91 fd_set exception_set;
92 nfds_t i;
93 int n;
94 int rc;
95
96#ifdef HAVE_WINSOCK2_H
97 if (numfds >= FD_SETSIZE) {
98 errno = EINVAL;
99 return -1;
100 }
101#endif
102
103 FD_ZERO(&read_set);
104 FD_ZERO(&write_set);
105 FD_ZERO(&exception_set);
106
107 n = -1;
108 for(i = 0; i < numfds; i++) {
109 if (fds[i].fd < 0)
110 continue;
111#ifndef HAVE_WINSOCK2_H
112 if (fds[i].fd >= FD_SETSIZE) {
113 errno = EINVAL;
114 return -1;
115 }
116#endif
117
118 if (fds[i].events & POLLIN) FD_SET(fds[i].fd, &read_set);
119 if (fds[i].events & POLLOUT) FD_SET(fds[i].fd, &write_set);
120 if (fds[i].events & POLLERR) FD_SET(fds[i].fd, &exception_set);
121
122 if (fds[i].fd > n)
123 n = fds[i].fd;
124 };
125
126 if (n == -1)
127 /* Hey!? Nothing to poll, in fact!!! */
128 return 0;
129
130 if (timeout < 0)
131 rc = select(n+1, &read_set, &write_set, &exception_set, NULL);
132 else {
133 struct timeval tv;
134
135 tv.tv_sec = timeout / 1000;
136 tv.tv_usec = 1000 * (timeout % 1000);
137 rc = select(n+1, &read_set, &write_set, &exception_set, &tv);
138 };
139
140 if (rc < 0)
141 return rc;
142
143 for(i = 0; i < (nfds_t) n; i++) {
144 fds[i].revents = 0;
145
146 if (FD_ISSET(fds[i].fd, &read_set)) fds[i].revents |= POLLIN;
147 if (FD_ISSET(fds[i].fd, &write_set)) fds[i].revents |= POLLOUT;
148 if (FD_ISSET(fds[i].fd, &exception_set)) fds[i].revents |= POLLERR;
149 };
150
151 return rc;
152}
153#endif /* HAVE_POLL_H */
154#endif /* CONFIG_FFSERVER */
155
diff --git a/src/plugins/ffmpeg/libavformat/os_support.h b/src/plugins/ffmpeg/libavformat/os_support.h
deleted file mode 100644
index 34970e3..0000000
--- a/src/plugins/ffmpeg/libavformat/os_support.h
+++ /dev/null
@@ -1,95 +0,0 @@
1/*
2 * various utilities for ffmpeg system
3 * copyright (c) 2000, 2001, 2002 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#ifndef FFMPEG_OS_SUPPORT_H
23#define FFMPEG_OS_SUPPORT_H
24
25/**
26 * @file os_support.h
27 * miscellaneous OS support macros and functions.
28 */
29
30#ifdef __MINGW32__
31# define WIN32_LEAN_AND_MEAN
32# include <windows.h>
33# define usleep(t) Sleep((t) / 1000)
34# include <fcntl.h>
35# define lseek(f,p,w) _lseeki64((f), (p), (w))
36#endif
37
38#ifdef __BEOS__
39# include <sys/socket.h>
40# include <netinet/in.h>
41 /* not net_server ? */
42# include <BeBuild.h>
43 /* R5 didn't have usleep, fake it. Haiku and Zeta has it now. */
44# if B_BEOS_VERSION <= B_BEOS_VERSION_5
45# include <OS.h>
46 /* doesn't set errno but that's enough */
47# define usleep(t) snooze((bigtime_t)(t))
48# endif
49# ifndef SA_RESTART
50# warning SA_RESTART not implemented; ffserver might misbehave.
51# define SA_RESTART 0
52# endif
53#endif
54
55#ifdef CONFIG_NETWORK
56#ifndef HAVE_SOCKLEN_T
57typedef int socklen_t;
58#endif
59
60/* most of the time closing a socket is just closing an fd */
61#ifndef HAVE_CLOSESOCKET
62#define closesocket close
63#endif
64
65#ifdef CONFIG_FFSERVER
66#ifndef HAVE_POLL_H
67typedef unsigned long nfds_t;
68
69struct pollfd {
70 int fd;
71 short events; /* events to look for */
72 short revents; /* events that occurred */
73};
74
75/* events & revents */
76#define POLLIN 0x0001 /* any readable data available */
77#define POLLOUT 0x0002 /* file descriptor is writeable */
78#define POLLRDNORM POLLIN
79#define POLLWRNORM POLLOUT
80#define POLLRDBAND 0x0008 /* priority readable data */
81#define POLLWRBAND 0x0010 /* priority data can be written */
82#define POLLPRI 0x0020 /* high priority readable data */
83
84/* revents only */
85#define POLLERR 0x0004 /* errors pending */
86#define POLLHUP 0x0080 /* disconnected */
87#define POLLNVAL 0x1000 /* invalid file descriptor */
88
89
90extern int poll(struct pollfd *fds, nfds_t numfds, int timeout);
91#endif /* HAVE_POLL_H */
92#endif /* CONFIG_FFSERVER */
93#endif /* CONFIG_NETWORK */
94
95#endif /* FFMPEG_OS_SUPPORT_H */
diff --git a/src/plugins/ffmpeg/libavformat/psxstr.c b/src/plugins/ffmpeg/libavformat/psxstr.c
deleted file mode 100644
index 469a2c4..0000000
--- a/src/plugins/ffmpeg/libavformat/psxstr.c
+++ /dev/null
@@ -1,268 +0,0 @@
1/*
2 * Sony Playstation (PSX) STR File Demuxer
3 * Copyright (c) 2003 The ffmpeg Project
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/**
23 * @file psxstr.c
24 * PSX STR file demuxer
25 * by Mike Melanson (melanson@pcisys.net)
26 * This module handles streams that have been ripped from Sony Playstation
27 * CD games. This demuxer can handle either raw STR files (which are just
28 * concatenations of raw compact disc sectors) or STR files with 0x2C-byte
29 * RIFF headers, followed by CD sectors.
30 */
31
32#include "avformat.h"
33
34#define RIFF_TAG MKTAG('R', 'I', 'F', 'F')
35#define CDXA_TAG MKTAG('C', 'D', 'X', 'A')
36
37#define RAW_CD_SECTOR_SIZE 2352
38#define RAW_CD_SECTOR_DATA_SIZE 2304
39#define VIDEO_DATA_CHUNK_SIZE 0x7E0
40#define VIDEO_DATA_HEADER_SIZE 0x38
41#define RIFF_HEADER_SIZE 0x2C
42
43#define CDXA_TYPE_MASK 0x0E
44#define CDXA_TYPE_DATA 0x08
45#define CDXA_TYPE_AUDIO 0x04
46#define CDXA_TYPE_VIDEO 0x02
47
48#define STR_MAGIC (0x80010160)
49
50typedef struct StrChannel {
51 /* video parameters */
52 int video_stream_index;
53 AVPacket tmp_pkt;
54
55 /* audio parameters */
56 int audio_stream_index;
57} StrChannel;
58
59typedef struct StrDemuxContext {
60
61 /* a STR file can contain up to 32 channels of data */
62 StrChannel channels[32];
63} StrDemuxContext;
64
65static const char sync_header[12] = {0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00};
66
67static int str_probe(AVProbeData *p)
68{
69 uint8_t *sector= p->buf;
70
71 if (p->buf_size < RAW_CD_SECTOR_SIZE)
72 return 0;
73
74 if ((AV_RL32(&p->buf[0]) == RIFF_TAG) &&
75 (AV_RL32(&p->buf[8]) == CDXA_TAG)) {
76
77 /* RIFF header seen; skip 0x2C bytes */
78 sector += RIFF_HEADER_SIZE;
79 }
80
81 /* look for CD sync header (00, 0xFF x 10, 00) */
82 if (memcmp(sector,sync_header,sizeof(sync_header)))
83 return 0;
84
85 if(sector[0x11] >= 32)
86 return 0;
87 if( (sector[0x12] & CDXA_TYPE_MASK) != CDXA_TYPE_VIDEO
88 && (sector[0x12] & CDXA_TYPE_MASK) != CDXA_TYPE_AUDIO
89 && (sector[0x12] & CDXA_TYPE_MASK) != CDXA_TYPE_DATA)
90 return 0;
91
92 /* MPEG files (like those ripped from VCDs) can also look like this;
93 * only return half certainty */
94 return 50;
95}
96
97static int str_read_header(AVFormatContext *s,
98 AVFormatParameters *ap)
99{
100 ByteIOContext *pb = s->pb;
101 StrDemuxContext *str = s->priv_data;
102 unsigned char sector[RAW_CD_SECTOR_SIZE];
103 int start;
104 int i;
105
106 /* skip over any RIFF header */
107 if (get_buffer(pb, sector, RIFF_HEADER_SIZE) != RIFF_HEADER_SIZE)
108 return AVERROR(EIO);
109 if (AV_RL32(&sector[0]) == RIFF_TAG)
110 start = RIFF_HEADER_SIZE;
111 else
112 start = 0;
113
114 url_fseek(pb, start, SEEK_SET);
115
116 for(i=0; i<32; i++){
117 str->channels[i].video_stream_index=
118 str->channels[i].audio_stream_index= -1;
119 }
120
121 s->ctx_flags |= AVFMTCTX_NOHEADER;
122
123 return 0;
124}
125
126static int str_read_packet(AVFormatContext *s,
127 AVPacket *ret_pkt)
128{
129 ByteIOContext *pb = s->pb;
130 StrDemuxContext *str = s->priv_data;
131 unsigned char sector[RAW_CD_SECTOR_SIZE];
132 int channel;
133 AVPacket *pkt;
134 AVStream *st;
135
136 while (1) {
137
138 if (get_buffer(pb, sector, RAW_CD_SECTOR_SIZE) != RAW_CD_SECTOR_SIZE)
139 return AVERROR(EIO);
140
141 channel = sector[0x11];
142 if (channel >= 32)
143 return AVERROR_INVALIDDATA;
144
145 switch (sector[0x12] & CDXA_TYPE_MASK) {
146
147 case CDXA_TYPE_DATA:
148 case CDXA_TYPE_VIDEO:
149 {
150
151 int current_sector = AV_RL16(&sector[0x1C]);
152 int sector_count = AV_RL16(&sector[0x1E]);
153 int frame_size = AV_RL32(&sector[0x24]);
154
155 if(!( frame_size>=0
156 && current_sector < sector_count
157 && sector_count*VIDEO_DATA_CHUNK_SIZE >=frame_size)){
158 av_log(s, AV_LOG_ERROR, "Invalid parameters %d %d %d\n", current_sector, sector_count, frame_size);
159 break;
160 }
161
162 if(str->channels[channel].video_stream_index < 0){
163 /* allocate a new AVStream */
164 st = av_new_stream(s, 0);
165 if (!st)
166 return AVERROR(ENOMEM);
167 av_set_pts_info(st, 64, 1, 15);
168
169 str->channels[channel].video_stream_index = st->index;
170
171 st->codec->codec_type = CODEC_TYPE_VIDEO;
172 st->codec->codec_id = CODEC_ID_MDEC;
173 st->codec->codec_tag = 0; /* no fourcc */
174 st->codec->width = AV_RL16(&sector[0x28]);
175 st->codec->height = AV_RL16(&sector[0x2A]);
176 }
177
178 /* if this is the first sector of the frame, allocate a pkt */
179 pkt = &str->channels[channel].tmp_pkt;
180
181 if(pkt->size != sector_count*VIDEO_DATA_CHUNK_SIZE){
182 if(pkt->data)
183 av_log(s, AV_LOG_ERROR, "missmatching sector_count\n");
184 av_free_packet(pkt);
185 if (av_new_packet(pkt, sector_count*VIDEO_DATA_CHUNK_SIZE))
186 return AVERROR(EIO);
187
188 pkt->pos= url_ftell(pb) - RAW_CD_SECTOR_SIZE;
189 pkt->stream_index =
190 str->channels[channel].video_stream_index;
191 }
192
193 memcpy(pkt->data + current_sector*VIDEO_DATA_CHUNK_SIZE,
194 sector + VIDEO_DATA_HEADER_SIZE,
195 VIDEO_DATA_CHUNK_SIZE);
196
197 if (current_sector == sector_count-1) {
198 pkt->size= frame_size;
199 *ret_pkt = *pkt;
200 pkt->data= NULL;
201 pkt->size= -1;
202 return 0;
203 }
204
205 }
206 break;
207
208 case CDXA_TYPE_AUDIO:
209 if(str->channels[channel].audio_stream_index < 0){
210 int fmt = sector[0x13];
211 /* allocate a new AVStream */
212 st = av_new_stream(s, 0);
213 if (!st)
214 return AVERROR(ENOMEM);
215
216 str->channels[channel].audio_stream_index = st->index;
217
218 st->codec->codec_type = CODEC_TYPE_AUDIO;
219 st->codec->codec_id = CODEC_ID_ADPCM_XA;
220 st->codec->codec_tag = 0; /* no fourcc */
221 st->codec->channels = (fmt&1)?2:1;
222 st->codec->sample_rate = (fmt&4)?18900:37800;
223 // st->codec->bit_rate = 0; //FIXME;
224 st->codec->block_align = 128;
225
226 av_set_pts_info(st, 64, 128, st->codec->sample_rate);
227 }
228 pkt = ret_pkt;
229 if (av_new_packet(pkt, 2304))
230 return AVERROR(EIO);
231 memcpy(pkt->data,sector+24,2304);
232
233 pkt->stream_index =
234 str->channels[channel].audio_stream_index;
235 return 0;
236 break;
237 default:
238 av_log(s, AV_LOG_WARNING, "Unknown sector type %02X\n", sector[0x12]);
239 /* drop the sector and move on */
240 break;
241 }
242
243 if (url_feof(pb))
244 return AVERROR(EIO);
245 }
246}
247
248static int str_read_close(AVFormatContext *s)
249{
250 StrDemuxContext *str = s->priv_data;
251 int i;
252 for(i=0; i<32; i++){
253 if(str->channels[i].tmp_pkt.data)
254 av_free_packet(&str->channels[i].tmp_pkt);
255 }
256
257 return 0;
258}
259
260AVInputFormat str_demuxer = {
261 "psxstr",
262 NULL_IF_CONFIG_SMALL("Sony Playstation STR format"),
263 sizeof(StrDemuxContext),
264 str_probe,
265 str_read_header,
266 str_read_packet,
267 str_read_close,
268};
diff --git a/src/plugins/ffmpeg/libavformat/pva.c b/src/plugins/ffmpeg/libavformat/pva.c
deleted file mode 100644
index 32827d4..0000000
--- a/src/plugins/ffmpeg/libavformat/pva.c
+++ /dev/null
@@ -1,211 +0,0 @@
1/*
2 * TechnoTrend PVA (.pva) demuxer
3 * Copyright (c) 2007, 2008 Ivo van Poorten
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 "avformat.h"
23#include "mpeg.h"
24
25#define PVA_MAX_PAYLOAD_LENGTH 0x17f8
26#define PVA_VIDEO_PAYLOAD 0x01
27#define PVA_AUDIO_PAYLOAD 0x02
28#define PVA_MAGIC (('A' << 8) + 'V')
29
30typedef struct {
31 int continue_pes;
32} PVAContext;
33
34static int pva_probe(AVProbeData * pd) {
35 unsigned char *buf = pd->buf;
36
37 if (AV_RB16(buf) == PVA_MAGIC && buf[2] && buf[2] < 3 && buf[4] == 0x55)
38 return AVPROBE_SCORE_MAX / 2;
39
40 return 0;
41}
42
43static int pva_read_header(AVFormatContext *s, AVFormatParameters *ap) {
44 AVStream *st;
45
46 if (!(st = av_new_stream(s, 0)))
47 return AVERROR(ENOMEM);
48 st->codec->codec_type = CODEC_TYPE_VIDEO;
49 st->codec->codec_id = CODEC_ID_MPEG2VIDEO;
50 st->need_parsing = AVSTREAM_PARSE_FULL;
51 av_set_pts_info(st, 32, 1, 90000);
52 av_add_index_entry(st, 0, 0, 0, 0, AVINDEX_KEYFRAME);
53
54 if (!(st = av_new_stream(s, 1)))
55 return AVERROR(ENOMEM);
56 st->codec->codec_type = CODEC_TYPE_AUDIO;
57 st->codec->codec_id = CODEC_ID_MP2;
58 st->need_parsing = AVSTREAM_PARSE_HEADERS;
59 av_set_pts_info(st, 33, 1, 90000);
60 av_add_index_entry(st, 0, 0, 0, 0, AVINDEX_KEYFRAME);
61
62 /* the parameters will be extracted from the compressed bitstream */
63 return 0;
64}
65
66#define pva_log if (read_packet) av_log
67
68static int read_part_of_packet(AVFormatContext *s, int64_t *pts,
69 int *len, int *strid, int read_packet) {
70 ByteIOContext *pb = s->pb;
71 PVAContext *pvactx = s->priv_data;
72 int syncword, streamid, reserved, flags, length, pts_flag;
73 int64_t pva_pts = AV_NOPTS_VALUE, startpos;
74
75recover:
76 startpos = url_ftell(pb);
77
78 syncword = get_be16(pb);
79 streamid = get_byte(pb);
80 get_byte(pb); /* counter not used */
81 reserved = get_byte(pb);
82 flags = get_byte(pb);
83 length = get_be16(pb);
84
85 pts_flag = flags & 0x10;
86
87 if (syncword != PVA_MAGIC) {
88 pva_log(s, AV_LOG_ERROR, "invalid syncword\n");
89 return AVERROR(EIO);
90 }
91 if (streamid != PVA_VIDEO_PAYLOAD && streamid != PVA_AUDIO_PAYLOAD) {
92 pva_log(s, AV_LOG_ERROR, "invalid streamid\n");
93 return AVERROR(EIO);
94 }
95 if (reserved != 0x55) {
96 pva_log(s, AV_LOG_WARNING, "expected reserved byte to be 0x55\n");
97 }
98 if (length > PVA_MAX_PAYLOAD_LENGTH) {
99 pva_log(s, AV_LOG_ERROR, "invalid payload length %u\n", length);
100 return AVERROR(EIO);
101 }
102
103 if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) {
104 pva_pts = get_be32(pb);
105 length -= 4;
106 } else if (streamid == PVA_AUDIO_PAYLOAD) {
107 /* PVA Audio Packets either start with a signaled PES packet or
108 * are a continuation of the previous PES packet. New PES packets
109 * always start at the beginning of a PVA Packet, never somewhere in
110 * the middle. */
111 if (!pvactx->continue_pes) {
112 int pes_signal, pes_header_data_length, pes_packet_length,
113 pes_flags;
114 unsigned char pes_header_data[256];
115
116 pes_signal = get_be24(pb);
117 get_byte(pb);
118 pes_packet_length = get_be16(pb);
119 pes_flags = get_be16(pb);
120 pes_header_data_length = get_byte(pb);
121
122 if (pes_signal != 1) {
123 pva_log(s, AV_LOG_WARNING, "expected signaled PES packet, "
124 "trying to recover\n");
125 url_fskip(pb, length - 9);
126 if (!read_packet)
127 return AVERROR(EIO);
128 goto recover;
129 }
130
131 get_buffer(pb, pes_header_data, pes_header_data_length);
132 length -= 9 + pes_header_data_length;
133
134 pes_packet_length -= 3 + pes_header_data_length;
135
136 pvactx->continue_pes = pes_packet_length;
137
138 if (pes_flags & 0x80 && (pes_header_data[0] & 0xf0) == 0x20)
139 pva_pts = ff_parse_pes_pts(pes_header_data);
140 }
141
142 pvactx->continue_pes -= length;
143
144 if (pvactx->continue_pes < 0) {
145 pva_log(s, AV_LOG_WARNING, "audio data corruption\n");
146 pvactx->continue_pes = 0;
147 }
148 }
149
150 if (pva_pts != AV_NOPTS_VALUE)
151 av_add_index_entry(s->streams[streamid-1], startpos, pva_pts, 0, 0, AVINDEX_KEYFRAME);
152
153 *pts = pva_pts;
154 *len = length;
155 *strid = streamid;
156 return 0;
157}
158
159static int pva_read_packet(AVFormatContext *s, AVPacket *pkt) {
160 ByteIOContext *pb = s->pb;
161 int64_t pva_pts;
162 int ret, length, streamid;
163
164 if (read_part_of_packet(s, &pva_pts, &length, &streamid, 1) < 0 ||
165 (ret = av_get_packet(pb, pkt, length)) <= 0)
166 return AVERROR(EIO);
167
168 pkt->stream_index = streamid - 1;
169 pkt->pts = pva_pts;
170
171 return ret;
172}
173
174static int64_t pva_read_timestamp(struct AVFormatContext *s, int stream_index,
175 int64_t *pos, int64_t pos_limit) {
176 ByteIOContext *pb = s->pb;
177 PVAContext *pvactx = s->priv_data;
178 int length, streamid;
179 int64_t res;
180
181 pos_limit = FFMIN(*pos+PVA_MAX_PAYLOAD_LENGTH*8, (uint64_t)*pos+pos_limit);
182
183 while (*pos < pos_limit) {
184 res = AV_NOPTS_VALUE;
185 url_fseek(pb, *pos, SEEK_SET);
186
187 pvactx->continue_pes = 0;
188 if (read_part_of_packet(s, &res, &length, &streamid, 0)) {
189 (*pos)++;
190 continue;
191 }
192 if (streamid - 1 != stream_index || res == AV_NOPTS_VALUE) {
193 *pos = url_ftell(pb) + length;
194 continue;
195 }
196 break;
197 }
198
199 pvactx->continue_pes = 0;
200 return res;
201}
202
203AVInputFormat pva_demuxer = {
204 "pva",
205 NULL_IF_CONFIG_SMALL("TechnoTrend PVA file and stream format"),
206 sizeof(PVAContext),
207 pva_probe,
208 pva_read_header,
209 pva_read_packet,
210 .read_timestamp = pva_read_timestamp
211};
diff --git a/src/plugins/ffmpeg/libavformat/qtpalette.h b/src/plugins/ffmpeg/libavformat/qtpalette.h
deleted file mode 100644
index 0c6c44f..0000000
--- a/src/plugins/ffmpeg/libavformat/qtpalette.h
+++ /dev/null
@@ -1,313 +0,0 @@
1/*
2 * Default Palettes for Quicktime Files
3 * Automatically generated from a utility derived from XAnim:
4 * http://xanim.va.pubnix.com/home.html
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#ifndef FFMPEG_QTPALETTE_H
24#define FFMPEG_QTPALETTE_H
25
26#include <inttypes.h>
27
28static const uint8_t ff_qt_default_palette_4[4 * 4] = {
29 0x93, 0x65, 0x5E, 0x00,
30 0xFF, 0xFF, 0xFF, 0x00,
31 0xDF, 0xD0, 0xAB, 0x00,
32 0x00, 0x00, 0x00, 0x00
33};
34
35static const uint8_t ff_qt_default_palette_16[16 * 4] = {
36 0xFF, 0xFB, 0xFF, 0x00,
37 0xEF, 0xD9, 0xBB, 0x00,
38 0xE8, 0xC9, 0xB1, 0x00,
39 0x93, 0x65, 0x5E, 0x00,
40 0xFC, 0xDE, 0xE8, 0x00,
41 0x9D, 0x88, 0x91, 0x00,
42 0xFF, 0xFF, 0xFF, 0x00,
43 0xFF, 0xFF, 0xFF, 0x00,
44 0xFF, 0xFF, 0xFF, 0x00,
45 0x47, 0x48, 0x37, 0x00,
46 0x7A, 0x5E, 0x55, 0x00,
47 0xDF, 0xD0, 0xAB, 0x00,
48 0xFF, 0xFB, 0xF9, 0x00,
49 0xE8, 0xCA, 0xC5, 0x00,
50 0x8A, 0x7C, 0x77, 0x00,
51 0x00, 0x00, 0x00, 0x00
52};
53
54static const uint8_t ff_qt_default_palette_256[256 * 4] = {
55 /* 0, 0x00 */ 0xFF, 0xFF, 0xFF, 0x00,
56 /* 1, 0x01 */ 0xFF, 0xFF, 0xCC, 0x00,
57 /* 2, 0x02 */ 0xFF, 0xFF, 0x99, 0x00,
58 /* 3, 0x03 */ 0xFF, 0xFF, 0x66, 0x00,
59 /* 4, 0x04 */ 0xFF, 0xFF, 0x33, 0x00,
60 /* 5, 0x05 */ 0xFF, 0xFF, 0x00, 0x00,
61 /* 6, 0x06 */ 0xFF, 0xCC, 0xFF, 0x00,
62 /* 7, 0x07 */ 0xFF, 0xCC, 0xCC, 0x00,
63 /* 8, 0x08 */ 0xFF, 0xCC, 0x99, 0x00,
64 /* 9, 0x09 */ 0xFF, 0xCC, 0x66, 0x00,
65 /* 10, 0x0A */ 0xFF, 0xCC, 0x33, 0x00,
66 /* 11, 0x0B */ 0xFF, 0xCC, 0x00, 0x00,
67 /* 12, 0x0C */ 0xFF, 0x99, 0xFF, 0x00,
68 /* 13, 0x0D */ 0xFF, 0x99, 0xCC, 0x00,
69 /* 14, 0x0E */ 0xFF, 0x99, 0x99, 0x00,
70 /* 15, 0x0F */ 0xFF, 0x99, 0x66, 0x00,
71 /* 16, 0x10 */ 0xFF, 0x99, 0x33, 0x00,
72 /* 17, 0x11 */ 0xFF, 0x99, 0x00, 0x00,
73 /* 18, 0x12 */ 0xFF, 0x66, 0xFF, 0x00,
74 /* 19, 0x13 */ 0xFF, 0x66, 0xCC, 0x00,
75 /* 20, 0x14 */ 0xFF, 0x66, 0x99, 0x00,
76 /* 21, 0x15 */ 0xFF, 0x66, 0x66, 0x00,
77 /* 22, 0x16 */ 0xFF, 0x66, 0x33, 0x00,
78 /* 23, 0x17 */ 0xFF, 0x66, 0x00, 0x00,
79 /* 24, 0x18 */ 0xFF, 0x33, 0xFF, 0x00,
80 /* 25, 0x19 */ 0xFF, 0x33, 0xCC, 0x00,
81 /* 26, 0x1A */ 0xFF, 0x33, 0x99, 0x00,
82 /* 27, 0x1B */ 0xFF, 0x33, 0x66, 0x00,
83 /* 28, 0x1C */ 0xFF, 0x33, 0x33, 0x00,
84 /* 29, 0x1D */ 0xFF, 0x33, 0x00, 0x00,
85 /* 30, 0x1E */ 0xFF, 0x00, 0xFF, 0x00,
86 /* 31, 0x1F */ 0xFF, 0x00, 0xCC, 0x00,
87 /* 32, 0x20 */ 0xFF, 0x00, 0x99, 0x00,
88 /* 33, 0x21 */ 0xFF, 0x00, 0x66, 0x00,
89 /* 34, 0x22 */ 0xFF, 0x00, 0x33, 0x00,
90 /* 35, 0x23 */ 0xFF, 0x00, 0x00, 0x00,
91 /* 36, 0x24 */ 0xCC, 0xFF, 0xFF, 0x00,
92 /* 37, 0x25 */ 0xCC, 0xFF, 0xCC, 0x00,
93 /* 38, 0x26 */ 0xCC, 0xFF, 0x99, 0x00,
94 /* 39, 0x27 */ 0xCC, 0xFF, 0x66, 0x00,
95 /* 40, 0x28 */ 0xCC, 0xFF, 0x33, 0x00,
96 /* 41, 0x29 */ 0xCC, 0xFF, 0x00, 0x00,
97 /* 42, 0x2A */ 0xCC, 0xCC, 0xFF, 0x00,
98 /* 43, 0x2B */ 0xCC, 0xCC, 0xCC, 0x00,
99 /* 44, 0x2C */ 0xCC, 0xCC, 0x99, 0x00,
100 /* 45, 0x2D */ 0xCC, 0xCC, 0x66, 0x00,
101 /* 46, 0x2E */ 0xCC, 0xCC, 0x33, 0x00,
102 /* 47, 0x2F */ 0xCC, 0xCC, 0x00, 0x00,
103 /* 48, 0x30 */ 0xCC, 0x99, 0xFF, 0x00,
104 /* 49, 0x31 */ 0xCC, 0x99, 0xCC, 0x00,
105 /* 50, 0x32 */ 0xCC, 0x99, 0x99, 0x00,
106 /* 51, 0x33 */ 0xCC, 0x99, 0x66, 0x00,
107 /* 52, 0x34 */ 0xCC, 0x99, 0x33, 0x00,
108 /* 53, 0x35 */ 0xCC, 0x99, 0x00, 0x00,
109 /* 54, 0x36 */ 0xCC, 0x66, 0xFF, 0x00,
110 /* 55, 0x37 */ 0xCC, 0x66, 0xCC, 0x00,
111 /* 56, 0x38 */ 0xCC, 0x66, 0x99, 0x00,
112 /* 57, 0x39 */ 0xCC, 0x66, 0x66, 0x00,
113 /* 58, 0x3A */ 0xCC, 0x66, 0x33, 0x00,
114 /* 59, 0x3B */ 0xCC, 0x66, 0x00, 0x00,
115 /* 60, 0x3C */ 0xCC, 0x33, 0xFF, 0x00,
116 /* 61, 0x3D */ 0xCC, 0x33, 0xCC, 0x00,
117 /* 62, 0x3E */ 0xCC, 0x33, 0x99, 0x00,
118 /* 63, 0x3F */ 0xCC, 0x33, 0x66, 0x00,
119 /* 64, 0x40 */ 0xCC, 0x33, 0x33, 0x00,
120 /* 65, 0x41 */ 0xCC, 0x33, 0x00, 0x00,
121 /* 66, 0x42 */ 0xCC, 0x00, 0xFF, 0x00,
122 /* 67, 0x43 */ 0xCC, 0x00, 0xCC, 0x00,
123 /* 68, 0x44 */ 0xCC, 0x00, 0x99, 0x00,
124 /* 69, 0x45 */ 0xCC, 0x00, 0x66, 0x00,
125 /* 70, 0x46 */ 0xCC, 0x00, 0x33, 0x00,
126 /* 71, 0x47 */ 0xCC, 0x00, 0x00, 0x00,
127 /* 72, 0x48 */ 0x99, 0xFF, 0xFF, 0x00,
128 /* 73, 0x49 */ 0x99, 0xFF, 0xCC, 0x00,
129 /* 74, 0x4A */ 0x99, 0xFF, 0x99, 0x00,
130 /* 75, 0x4B */ 0x99, 0xFF, 0x66, 0x00,
131 /* 76, 0x4C */ 0x99, 0xFF, 0x33, 0x00,
132 /* 77, 0x4D */ 0x99, 0xFF, 0x00, 0x00,
133 /* 78, 0x4E */ 0x99, 0xCC, 0xFF, 0x00,
134 /* 79, 0x4F */ 0x99, 0xCC, 0xCC, 0x00,
135 /* 80, 0x50 */ 0x99, 0xCC, 0x99, 0x00,
136 /* 81, 0x51 */ 0x99, 0xCC, 0x66, 0x00,
137 /* 82, 0x52 */ 0x99, 0xCC, 0x33, 0x00,
138 /* 83, 0x53 */ 0x99, 0xCC, 0x00, 0x00,
139 /* 84, 0x54 */ 0x99, 0x99, 0xFF, 0x00,
140 /* 85, 0x55 */ 0x99, 0x99, 0xCC, 0x00,
141 /* 86, 0x56 */ 0x99, 0x99, 0x99, 0x00,
142 /* 87, 0x57 */ 0x99, 0x99, 0x66, 0x00,
143 /* 88, 0x58 */ 0x99, 0x99, 0x33, 0x00,
144 /* 89, 0x59 */ 0x99, 0x99, 0x00, 0x00,
145 /* 90, 0x5A */ 0x99, 0x66, 0xFF, 0x00,
146 /* 91, 0x5B */ 0x99, 0x66, 0xCC, 0x00,
147 /* 92, 0x5C */ 0x99, 0x66, 0x99, 0x00,
148 /* 93, 0x5D */ 0x99, 0x66, 0x66, 0x00,
149 /* 94, 0x5E */ 0x99, 0x66, 0x33, 0x00,
150 /* 95, 0x5F */ 0x99, 0x66, 0x00, 0x00,
151 /* 96, 0x60 */ 0x99, 0x33, 0xFF, 0x00,
152 /* 97, 0x61 */ 0x99, 0x33, 0xCC, 0x00,
153 /* 98, 0x62 */ 0x99, 0x33, 0x99, 0x00,
154 /* 99, 0x63 */ 0x99, 0x33, 0x66, 0x00,
155 /* 100, 0x64 */ 0x99, 0x33, 0x33, 0x00,
156 /* 101, 0x65 */ 0x99, 0x33, 0x00, 0x00,
157 /* 102, 0x66 */ 0x99, 0x00, 0xFF, 0x00,
158 /* 103, 0x67 */ 0x99, 0x00, 0xCC, 0x00,
159 /* 104, 0x68 */ 0x99, 0x00, 0x99, 0x00,
160 /* 105, 0x69 */ 0x99, 0x00, 0x66, 0x00,
161 /* 106, 0x6A */ 0x99, 0x00, 0x33, 0x00,
162 /* 107, 0x6B */ 0x99, 0x00, 0x00, 0x00,
163 /* 108, 0x6C */ 0x66, 0xFF, 0xFF, 0x00,
164 /* 109, 0x6D */ 0x66, 0xFF, 0xCC, 0x00,
165 /* 110, 0x6E */ 0x66, 0xFF, 0x99, 0x00,
166 /* 111, 0x6F */ 0x66, 0xFF, 0x66, 0x00,
167 /* 112, 0x70 */ 0x66, 0xFF, 0x33, 0x00,
168 /* 113, 0x71 */ 0x66, 0xFF, 0x00, 0x00,
169 /* 114, 0x72 */ 0x66, 0xCC, 0xFF, 0x00,
170 /* 115, 0x73 */ 0x66, 0xCC, 0xCC, 0x00,
171 /* 116, 0x74 */ 0x66, 0xCC, 0x99, 0x00,
172 /* 117, 0x75 */ 0x66, 0xCC, 0x66, 0x00,
173 /* 118, 0x76 */ 0x66, 0xCC, 0x33, 0x00,
174 /* 119, 0x77 */ 0x66, 0xCC, 0x00, 0x00,
175 /* 120, 0x78 */ 0x66, 0x99, 0xFF, 0x00,
176 /* 121, 0x79 */ 0x66, 0x99, 0xCC, 0x00,
177 /* 122, 0x7A */ 0x66, 0x99, 0x99, 0x00,
178 /* 123, 0x7B */ 0x66, 0x99, 0x66, 0x00,
179 /* 124, 0x7C */ 0x66, 0x99, 0x33, 0x00,
180 /* 125, 0x7D */ 0x66, 0x99, 0x00, 0x00,
181 /* 126, 0x7E */ 0x66, 0x66, 0xFF, 0x00,
182 /* 127, 0x7F */ 0x66, 0x66, 0xCC, 0x00,
183 /* 128, 0x80 */ 0x66, 0x66, 0x99, 0x00,
184 /* 129, 0x81 */ 0x66, 0x66, 0x66, 0x00,
185 /* 130, 0x82 */ 0x66, 0x66, 0x33, 0x00,
186 /* 131, 0x83 */ 0x66, 0x66, 0x00, 0x00,
187 /* 132, 0x84 */ 0x66, 0x33, 0xFF, 0x00,
188 /* 133, 0x85 */ 0x66, 0x33, 0xCC, 0x00,
189 /* 134, 0x86 */ 0x66, 0x33, 0x99, 0x00,
190 /* 135, 0x87 */ 0x66, 0x33, 0x66, 0x00,
191 /* 136, 0x88 */ 0x66, 0x33, 0x33, 0x00,
192 /* 137, 0x89 */ 0x66, 0x33, 0x00, 0x00,
193 /* 138, 0x8A */ 0x66, 0x00, 0xFF, 0x00,
194 /* 139, 0x8B */ 0x66, 0x00, 0xCC, 0x00,
195 /* 140, 0x8C */ 0x66, 0x00, 0x99, 0x00,
196 /* 141, 0x8D */ 0x66, 0x00, 0x66, 0x00,
197 /* 142, 0x8E */ 0x66, 0x00, 0x33, 0x00,
198 /* 143, 0x8F */ 0x66, 0x00, 0x00, 0x00,
199 /* 144, 0x90 */ 0x33, 0xFF, 0xFF, 0x00,
200 /* 145, 0x91 */ 0x33, 0xFF, 0xCC, 0x00,
201 /* 146, 0x92 */ 0x33, 0xFF, 0x99, 0x00,
202 /* 147, 0x93 */ 0x33, 0xFF, 0x66, 0x00,
203 /* 148, 0x94 */ 0x33, 0xFF, 0x33, 0x00,
204 /* 149, 0x95 */ 0x33, 0xFF, 0x00, 0x00,
205 /* 150, 0x96 */ 0x33, 0xCC, 0xFF, 0x00,
206 /* 151, 0x97 */ 0x33, 0xCC, 0xCC, 0x00,
207 /* 152, 0x98 */ 0x33, 0xCC, 0x99, 0x00,
208 /* 153, 0x99 */ 0x33, 0xCC, 0x66, 0x00,
209 /* 154, 0x9A */ 0x33, 0xCC, 0x33, 0x00,
210 /* 155, 0x9B */ 0x33, 0xCC, 0x00, 0x00,
211 /* 156, 0x9C */ 0x33, 0x99, 0xFF, 0x00,
212 /* 157, 0x9D */ 0x33, 0x99, 0xCC, 0x00,
213 /* 158, 0x9E */ 0x33, 0x99, 0x99, 0x00,
214 /* 159, 0x9F */ 0x33, 0x99, 0x66, 0x00,
215 /* 160, 0xA0 */ 0x33, 0x99, 0x33, 0x00,
216 /* 161, 0xA1 */ 0x33, 0x99, 0x00, 0x00,
217 /* 162, 0xA2 */ 0x33, 0x66, 0xFF, 0x00,
218 /* 163, 0xA3 */ 0x33, 0x66, 0xCC, 0x00,
219 /* 164, 0xA4 */ 0x33, 0x66, 0x99, 0x00,
220 /* 165, 0xA5 */ 0x33, 0x66, 0x66, 0x00,
221 /* 166, 0xA6 */ 0x33, 0x66, 0x33, 0x00,
222 /* 167, 0xA7 */ 0x33, 0x66, 0x00, 0x00,
223 /* 168, 0xA8 */ 0x33, 0x33, 0xFF, 0x00,
224 /* 169, 0xA9 */ 0x33, 0x33, 0xCC, 0x00,
225 /* 170, 0xAA */ 0x33, 0x33, 0x99, 0x00,
226 /* 171, 0xAB */ 0x33, 0x33, 0x66, 0x00,
227 /* 172, 0xAC */ 0x33, 0x33, 0x33, 0x00,
228 /* 173, 0xAD */ 0x33, 0x33, 0x00, 0x00,
229 /* 174, 0xAE */ 0x33, 0x00, 0xFF, 0x00,
230 /* 175, 0xAF */ 0x33, 0x00, 0xCC, 0x00,
231 /* 176, 0xB0 */ 0x33, 0x00, 0x99, 0x00,
232 /* 177, 0xB1 */ 0x33, 0x00, 0x66, 0x00,
233 /* 178, 0xB2 */ 0x33, 0x00, 0x33, 0x00,
234 /* 179, 0xB3 */ 0x33, 0x00, 0x00, 0x00,
235 /* 180, 0xB4 */ 0x00, 0xFF, 0xFF, 0x00,
236 /* 181, 0xB5 */ 0x00, 0xFF, 0xCC, 0x00,
237 /* 182, 0xB6 */ 0x00, 0xFF, 0x99, 0x00,
238 /* 183, 0xB7 */ 0x00, 0xFF, 0x66, 0x00,
239 /* 184, 0xB8 */ 0x00, 0xFF, 0x33, 0x00,
240 /* 185, 0xB9 */ 0x00, 0xFF, 0x00, 0x00,
241 /* 186, 0xBA */ 0x00, 0xCC, 0xFF, 0x00,
242 /* 187, 0xBB */ 0x00, 0xCC, 0xCC, 0x00,
243 /* 188, 0xBC */ 0x00, 0xCC, 0x99, 0x00,
244 /* 189, 0xBD */ 0x00, 0xCC, 0x66, 0x00,
245 /* 190, 0xBE */ 0x00, 0xCC, 0x33, 0x00,
246 /* 191, 0xBF */ 0x00, 0xCC, 0x00, 0x00,
247 /* 192, 0xC0 */ 0x00, 0x99, 0xFF, 0x00,
248 /* 193, 0xC1 */ 0x00, 0x99, 0xCC, 0x00,
249 /* 194, 0xC2 */ 0x00, 0x99, 0x99, 0x00,
250 /* 195, 0xC3 */ 0x00, 0x99, 0x66, 0x00,
251 /* 196, 0xC4 */ 0x00, 0x99, 0x33, 0x00,
252 /* 197, 0xC5 */ 0x00, 0x99, 0x00, 0x00,
253 /* 198, 0xC6 */ 0x00, 0x66, 0xFF, 0x00,
254 /* 199, 0xC7 */ 0x00, 0x66, 0xCC, 0x00,
255 /* 200, 0xC8 */ 0x00, 0x66, 0x99, 0x00,
256 /* 201, 0xC9 */ 0x00, 0x66, 0x66, 0x00,
257 /* 202, 0xCA */ 0x00, 0x66, 0x33, 0x00,
258 /* 203, 0xCB */ 0x00, 0x66, 0x00, 0x00,
259 /* 204, 0xCC */ 0x00, 0x33, 0xFF, 0x00,
260 /* 205, 0xCD */ 0x00, 0x33, 0xCC, 0x00,
261 /* 206, 0xCE */ 0x00, 0x33, 0x99, 0x00,
262 /* 207, 0xCF */ 0x00, 0x33, 0x66, 0x00,
263 /* 208, 0xD0 */ 0x00, 0x33, 0x33, 0x00,
264 /* 209, 0xD1 */ 0x00, 0x33, 0x00, 0x00,
265 /* 210, 0xD2 */ 0x00, 0x00, 0xFF, 0x00,
266 /* 211, 0xD3 */ 0x00, 0x00, 0xCC, 0x00,
267 /* 212, 0xD4 */ 0x00, 0x00, 0x99, 0x00,
268 /* 213, 0xD5 */ 0x00, 0x00, 0x66, 0x00,
269 /* 214, 0xD6 */ 0x00, 0x00, 0x33, 0x00,
270 /* 215, 0xD7 */ 0xEE, 0x00, 0x00, 0x00,
271 /* 216, 0xD8 */ 0xDD, 0x00, 0x00, 0x00,
272 /* 217, 0xD9 */ 0xBB, 0x00, 0x00, 0x00,
273 /* 218, 0xDA */ 0xAA, 0x00, 0x00, 0x00,
274 /* 219, 0xDB */ 0x88, 0x00, 0x00, 0x00,
275 /* 220, 0xDC */ 0x77, 0x00, 0x00, 0x00,
276 /* 221, 0xDD */ 0x55, 0x00, 0x00, 0x00,
277 /* 222, 0xDE */ 0x44, 0x00, 0x00, 0x00,
278 /* 223, 0xDF */ 0x22, 0x00, 0x00, 0x00,
279 /* 224, 0xE0 */ 0x11, 0x00, 0x00, 0x00,
280 /* 225, 0xE1 */ 0x00, 0xEE, 0x00, 0x00,
281 /* 226, 0xE2 */ 0x00, 0xDD, 0x00, 0x00,
282 /* 227, 0xE3 */ 0x00, 0xBB, 0x00, 0x00,
283 /* 228, 0xE4 */ 0x00, 0xAA, 0x00, 0x00,
284 /* 229, 0xE5 */ 0x00, 0x88, 0x00, 0x00,
285 /* 230, 0xE6 */ 0x00, 0x77, 0x00, 0x00,
286 /* 231, 0xE7 */ 0x00, 0x55, 0x00, 0x00,
287 /* 232, 0xE8 */ 0x00, 0x44, 0x00, 0x00,
288 /* 233, 0xE9 */ 0x00, 0x22, 0x00, 0x00,
289 /* 234, 0xEA */ 0x00, 0x11, 0x00, 0x00,
290 /* 235, 0xEB */ 0x00, 0x00, 0xEE, 0x00,
291 /* 236, 0xEC */ 0x00, 0x00, 0xDD, 0x00,
292 /* 237, 0xED */ 0x00, 0x00, 0xBB, 0x00,
293 /* 238, 0xEE */ 0x00, 0x00, 0xAA, 0x00,
294 /* 239, 0xEF */ 0x00, 0x00, 0x88, 0x00,
295 /* 240, 0xF0 */ 0x00, 0x00, 0x77, 0x00,
296 /* 241, 0xF1 */ 0x00, 0x00, 0x55, 0x00,
297 /* 242, 0xF2 */ 0x00, 0x00, 0x44, 0x00,
298 /* 243, 0xF3 */ 0x00, 0x00, 0x22, 0x00,
299 /* 244, 0xF4 */ 0x00, 0x00, 0x11, 0x00,
300 /* 245, 0xF5 */ 0xEE, 0xEE, 0xEE, 0x00,
301 /* 246, 0xF6 */ 0xDD, 0xDD, 0xDD, 0x00,
302 /* 247, 0xF7 */ 0xBB, 0xBB, 0xBB, 0x00,
303 /* 248, 0xF8 */ 0xAA, 0xAA, 0xAA, 0x00,
304 /* 249, 0xF9 */ 0x88, 0x88, 0x88, 0x00,
305 /* 250, 0xFA */ 0x77, 0x77, 0x77, 0x00,
306 /* 251, 0xFB */ 0x55, 0x55, 0x55, 0x00,
307 /* 252, 0xFC */ 0x44, 0x44, 0x44, 0x00,
308 /* 253, 0xFD */ 0x22, 0x22, 0x22, 0x00,
309 /* 254, 0xFE */ 0x11, 0x11, 0x11, 0x00,
310 /* 255, 0xFF */ 0x00, 0x00, 0x00, 0x00
311};
312
313#endif /* FFMPEG_QTPALETTE_H */
diff --git a/src/plugins/ffmpeg/libavformat/raw.c b/src/plugins/ffmpeg/libavformat/raw.c
deleted file mode 100644
index dd4d011..0000000
--- a/src/plugins/ffmpeg/libavformat/raw.c
+++ /dev/null
@@ -1,997 +0,0 @@
1/*
2 * RAW muxer and demuxer
3 * Copyright (c) 2001 Fabrice Bellard.
4 * Copyright (c) 2005 Alex Beregszaszi
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#include "libavutil/crc.h"
24#include "libavcodec/ac3_parser.h"
25#include "libavcodec/bitstream.h"
26#include "libavcodec/bytestream.h"
27#include "avformat.h"
28#include "raw.h"
29
30#ifdef CONFIG_MUXERS
31/* simple formats */
32static int flac_write_header(struct AVFormatContext *s)
33{
34 static const uint8_t header[8] = {
35 0x66, 0x4C, 0x61, 0x43, 0x80, 0x00, 0x00, 0x22
36 };
37 uint8_t *streaminfo = s->streams[0]->codec->extradata;
38 int len = s->streams[0]->codec->extradata_size;
39 if(streaminfo != NULL && len > 0) {
40 put_buffer(s->pb, header, 8);
41 put_buffer(s->pb, streaminfo, len);
42 }
43 return 0;
44}
45
46
47static int roq_write_header(struct AVFormatContext *s)
48{
49 static const uint8_t header[] = {
50 0x84, 0x10, 0xFF, 0xFF, 0xFF, 0xFF, 0x1E, 0x00
51 };
52
53 put_buffer(s->pb, header, 8);
54 put_flush_packet(s->pb);
55
56 return 0;
57}
58
59static int null_write_packet(struct AVFormatContext *s, AVPacket *pkt)
60{
61 return 0;
62}
63
64static int raw_write_packet(struct AVFormatContext *s, AVPacket *pkt)
65{
66 put_buffer(s->pb, pkt->data, pkt->size);
67 put_flush_packet(s->pb);
68 return 0;
69}
70#endif //CONFIG_MUXERS
71
72/* raw input */
73static int raw_read_header(AVFormatContext *s, AVFormatParameters *ap)
74{
75 AVStream *st;
76 int id;
77
78 st = av_new_stream(s, 0);
79 if (!st)
80 return AVERROR(ENOMEM);
81
82 id = s->iformat->value;
83 if (id == CODEC_ID_RAWVIDEO) {
84 st->codec->codec_type = CODEC_TYPE_VIDEO;
85 } else {
86 st->codec->codec_type = CODEC_TYPE_AUDIO;
87 }
88 st->codec->codec_id = id;
89
90 switch(st->codec->codec_type) {
91 case CODEC_TYPE_AUDIO:
92 st->codec->sample_rate = ap->sample_rate;
93 st->codec->channels = ap->channels;
94 av_set_pts_info(st, 64, 1, st->codec->sample_rate);
95 break;
96 case CODEC_TYPE_VIDEO:
97 if(ap->time_base.num)
98 av_set_pts_info(st, 64, ap->time_base.num, ap->time_base.den);
99 else
100 av_set_pts_info(st, 64, 1, 25);
101 st->codec->width = ap->width;
102 st->codec->height = ap->height;
103 st->codec->pix_fmt = ap->pix_fmt;
104 if(st->codec->pix_fmt == PIX_FMT_NONE)
105 st->codec->pix_fmt= PIX_FMT_YUV420P;
106 break;
107 default:
108 return -1;
109 }
110 return 0;
111}
112
113#define RAW_PACKET_SIZE 1024
114
115static int raw_read_packet(AVFormatContext *s, AVPacket *pkt)
116{
117 int ret, size, bps;
118 // AVStream *st = s->streams[0];
119
120 size= RAW_PACKET_SIZE;
121
122 ret= av_get_packet(s->pb, pkt, size);
123
124 pkt->stream_index = 0;
125 if (ret <= 0) {
126 return AVERROR(EIO);
127 }
128 /* note: we need to modify the packet size here to handle the last
129 packet */
130 pkt->size = ret;
131
132 bps= av_get_bits_per_sample(s->streams[0]->codec->codec_id);
133 assert(bps); // if false there IS a bug elsewhere (NOT in this function)
134 pkt->dts=
135 pkt->pts= pkt->pos*8 / (bps * s->streams[0]->codec->channels);
136
137 return ret;
138}
139
140static int raw_read_partial_packet(AVFormatContext *s, AVPacket *pkt)
141{
142 int ret, size;
143
144 size = RAW_PACKET_SIZE;
145
146 if (av_new_packet(pkt, size) < 0)
147 return AVERROR(EIO);
148
149 pkt->pos= url_ftell(s->pb);
150 pkt->stream_index = 0;
151 ret = get_partial_buffer(s->pb, pkt->data, size);
152 if (ret <= 0) {
153 av_free_packet(pkt);
154 return AVERROR(EIO);
155 }
156 pkt->size = ret;
157 return ret;
158}
159
160static int rawvideo_read_packet(AVFormatContext *s, AVPacket *pkt)
161{
162 int packet_size, ret, width, height;
163 AVStream *st = s->streams[0];
164
165 width = st->codec->width;
166 height = st->codec->height;
167
168 packet_size = avpicture_get_size(st->codec->pix_fmt, width, height);
169 if (packet_size < 0)
170 return -1;
171
172 ret= av_get_packet(s->pb, pkt, packet_size);
173 pkt->pts=
174 pkt->dts= pkt->pos / packet_size;
175
176 pkt->stream_index = 0;
177 if (ret != packet_size) {
178 return AVERROR(EIO);
179 } else {
180 return 0;
181 }
182}
183
184// http://www.artificis.hu/files/texts/ingenient.txt
185static int ingenient_read_packet(AVFormatContext *s, AVPacket *pkt)
186{
187 int ret, size, w, h, unk1, unk2;
188
189 if (get_le32(s->pb) != MKTAG('M', 'J', 'P', 'G'))
190 return AVERROR(EIO); // FIXME
191
192 size = get_le32(s->pb);
193
194 w = get_le16(s->pb);
195 h = get_le16(s->pb);
196
197 url_fskip(s->pb, 8); // zero + size (padded?)
198 url_fskip(s->pb, 2);
199 unk1 = get_le16(s->pb);
200 unk2 = get_le16(s->pb);
201 url_fskip(s->pb, 22); // ascii timestamp
202
203 av_log(NULL, AV_LOG_DEBUG, "Ingenient packet: size=%d, width=%d, height=%d, unk1=%d unk2=%d\n",
204 size, w, h, unk1, unk2);
205
206 if (av_new_packet(pkt, size) < 0)
207 return AVERROR(EIO);
208
209 pkt->pos = url_ftell(s->pb);
210 pkt->stream_index = 0;
211 ret = get_buffer(s->pb, pkt->data, size);
212 if (ret <= 0) {
213 av_free_packet(pkt);
214 return AVERROR(EIO);
215 }
216 pkt->size = ret;
217 return ret;
218}
219
220int pcm_read_seek(AVFormatContext *s,
221 int stream_index, int64_t timestamp, int flags)
222{
223 AVStream *st;
224 int block_align, byte_rate;
225 int64_t pos;
226
227 st = s->streams[0];
228
229 block_align = st->codec->block_align ? st->codec->block_align :
230 (av_get_bits_per_sample(st->codec->codec_id) * st->codec->channels) >> 3;
231 byte_rate = st->codec->bit_rate ? st->codec->bit_rate >> 3 :
232 block_align * st->codec->sample_rate;
233
234 if (block_align <= 0 || byte_rate <= 0)
235 return -1;
236
237 /* compute the position by aligning it to block_align */
238 pos = av_rescale_rnd(timestamp * byte_rate,
239 st->time_base.num,
240 st->time_base.den * (int64_t)block_align,
241 (flags & AVSEEK_FLAG_BACKWARD) ? AV_ROUND_DOWN : AV_ROUND_UP);
242 pos *= block_align;
243
244 /* recompute exact position */
245 st->cur_dts = av_rescale(pos, st->time_base.den, byte_rate * (int64_t)st->time_base.num);
246 url_fseek(s->pb, pos + s->data_offset, SEEK_SET);
247 return 0;
248}
249
250static int audio_read_header(AVFormatContext *s,
251 AVFormatParameters *ap)
252{
253 AVStream *st = av_new_stream(s, 0);
254 if (!st)
255 return AVERROR(ENOMEM);
256 st->codec->codec_type = CODEC_TYPE_AUDIO;
257 st->codec->codec_id = s->iformat->value;
258 st->need_parsing = AVSTREAM_PARSE_FULL;
259 /* the parameters will be extracted from the compressed bitstream */
260 return 0;
261}
262
263/* mpeg1/h263 input */
264static int video_read_header(AVFormatContext *s,
265 AVFormatParameters *ap)
266{
267 AVStream *st;
268
269 st = av_new_stream(s, 0);
270 if (!st)
271 return AVERROR(ENOMEM);
272
273 st->codec->codec_type = CODEC_TYPE_VIDEO;
274 st->codec->codec_id = s->iformat->value;
275 st->need_parsing = AVSTREAM_PARSE_FULL;
276
277 /* for mjpeg, specify frame rate */
278 /* for mpeg4 specify it too (most mpeg4 streams do not have the fixed_vop_rate set ...)*/
279 if (ap->time_base.num) {
280 av_set_pts_info(st, 64, ap->time_base.num, ap->time_base.den);
281 } else if ( st->codec->codec_id == CODEC_ID_MJPEG ||
282 st->codec->codec_id == CODEC_ID_MPEG4 ||
283 st->codec->codec_id == CODEC_ID_DIRAC ||
284 st->codec->codec_id == CODEC_ID_H264) {
285 av_set_pts_info(st, 64, 1, 25);
286 }
287
288 return 0;
289}
290
291#define SEQ_START_CODE 0x000001b3
292#define GOP_START_CODE 0x000001b8
293#define PICTURE_START_CODE 0x00000100
294#define SLICE_START_CODE 0x00000101
295#define PACK_START_CODE 0x000001ba
296#define VIDEO_ID 0x000001e0
297#define AUDIO_ID 0x000001c0
298
299static int mpegvideo_probe(AVProbeData *p)
300{
301 uint32_t code= -1;
302 int pic=0, seq=0, slice=0, pspack=0, pes=0;
303 int i;
304
305 for(i=0; i<p->buf_size; i++){
306 code = (code<<8) + p->buf[i];
307 if ((code & 0xffffff00) == 0x100) {
308 switch(code){
309 case SEQ_START_CODE: seq++; break;
310 case PICTURE_START_CODE: pic++; break;
311 case SLICE_START_CODE: slice++; break;
312 case PACK_START_CODE: pspack++; break;
313 }
314 if ((code & 0x1f0) == VIDEO_ID) pes++;
315 else if((code & 0x1e0) == AUDIO_ID) pes++;
316 }
317 }
318 if(seq && seq*9<=pic*10 && pic*9<=slice*10 && !pspack && !pes)
319 return AVPROBE_SCORE_MAX/2+1; // +1 for .mpg
320 return 0;
321}
322
323#define VISUAL_OBJECT_START_CODE 0x000001b5
324#define VOP_START_CODE 0x000001b6
325
326static int mpeg4video_probe(AVProbeData *probe_packet)
327{
328 uint32_t temp_buffer= -1;
329 int VO=0, VOL=0, VOP = 0, VISO = 0, res=0;
330 int i;
331
332 for(i=0; i<probe_packet->buf_size; i++){
333 temp_buffer = (temp_buffer<<8) + probe_packet->buf[i];
334 if ((temp_buffer & 0xffffff00) != 0x100)
335 continue;
336
337 if (temp_buffer == VOP_START_CODE) VOP++;
338 else if (temp_buffer == VISUAL_OBJECT_START_CODE) VISO++;
339 else if (temp_buffer < 0x120) VO++;
340 else if (temp_buffer < 0x130) VOL++;
341 else if ( !(0x1AF < temp_buffer && temp_buffer < 0x1B7)
342 && !(0x1B9 < temp_buffer && temp_buffer < 0x1C4)) res++;
343 }
344
345 if ( VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res==0)
346 return AVPROBE_SCORE_MAX/2;
347 return 0;
348}
349
350static int h264_probe(AVProbeData *p)
351{
352 uint32_t code= -1;
353 int sps=0, pps=0, idr=0, res=0;
354 int i;
355
356 for(i=0; i<p->buf_size; i++){
357 code = (code<<8) + p->buf[i];
358 if ((code & 0xffffff00) == 0x100) {
359 int ref_idc= (code>>5)&3;
360 int type = code & 0x1F;
361 static const int8_t ref_zero[32]={
362 2, 0, 0, 0, 0,-1, 1,-1,
363 -1, 1, 1, 1, 1,-1, 2, 2,
364 2, 2, 2, 0, 2, 2, 2, 2,
365 2, 2, 2, 2, 2, 2, 2, 2
366 };
367
368 if(code & 0x80) //forbidden bit
369 return 0;
370
371 if(ref_zero[type] == 1 && ref_idc)
372 return 0;
373 if(ref_zero[type] ==-1 && !ref_idc)
374 return 0;
375 if(ref_zero[type] == 2)
376 res++;
377
378 switch(type){
379 case 5: idr++; break;
380 case 7:
381 if(p->buf[i+2]&0x0F)
382 return 0;
383 sps++;
384 break;
385 case 8: pps++; break;
386 }
387 }
388 }
389 if(sps && pps && idr && res<(sps+pps+idr))
390 return AVPROBE_SCORE_MAX/2+1; // +1 for .mpg
391 return 0;
392}
393
394static int h263_probe(AVProbeData *p)
395{
396 int code;
397 const uint8_t *d;
398
399 d = p->buf;
400 code = (d[0] << 14) | (d[1] << 6) | (d[2] >> 2);
401 if (code == 0x20) {
402 return 50;
403 }
404 return 0;
405}
406
407static int h261_probe(AVProbeData *p)
408{
409 int code;
410 const uint8_t *d;
411
412 d = p->buf;
413 code = (d[0] << 12) | (d[1] << 4) | (d[2] >> 4);
414 if (code == 0x10) {
415 return 50;
416 }
417 return 0;
418}
419
420#define DCA_MARKER_14B_BE 0x1FFFE800
421#define DCA_MARKER_14B_LE 0xFF1F00E8
422#define DCA_MARKER_RAW_BE 0x7FFE8001
423#define DCA_MARKER_RAW_LE 0xFE7F0180
424static int dts_probe(AVProbeData *p)
425{
426 const uint8_t *buf, *bufp;
427 uint32_t state = -1;
428
429 buf = p->buf;
430
431 for(; buf < (p->buf+p->buf_size)-2; buf+=2) {
432 bufp = buf;
433 state = (state << 16) | bytestream_get_be16(&bufp);
434
435 /* Regular bitstream */
436 if (state == DCA_MARKER_RAW_BE || state == DCA_MARKER_RAW_LE)
437 return AVPROBE_SCORE_MAX/2+1;
438
439 /* 14 bits big endian bitstream */
440 if (state == DCA_MARKER_14B_BE)
441 if ((bytestream_get_be16(&bufp) & 0xFFF0) == 0x07F0)
442 return AVPROBE_SCORE_MAX/2+1;
443
444 /* 14 bits little endian bitstream */
445 if (state == DCA_MARKER_14B_LE)
446 if ((bytestream_get_be16(&bufp) & 0xF0FF) == 0xF007)
447 return AVPROBE_SCORE_MAX/2+1;
448 }
449
450 return 0;
451}
452
453static int dirac_probe(AVProbeData *p)
454{
455 if (AV_RL32(p->buf) == MKTAG('B', 'B', 'C', 'D'))
456 return AVPROBE_SCORE_MAX;
457 else
458 return 0;
459}
460
461static int ac3_probe(AVProbeData *p)
462{
463 int max_frames, first_frames = 0, frames;
464 uint8_t *buf, *buf2, *end;
465 AC3HeaderInfo hdr;
466 GetBitContext gbc;
467
468 max_frames = 0;
469 buf = p->buf;
470 end = buf + p->buf_size;
471
472 for(; buf < end; buf++) {
473 buf2 = buf;
474
475 for(frames = 0; buf2 < end; frames++) {
476 init_get_bits(&gbc, buf2, 54);
477 if(ff_ac3_parse_header(&gbc, &hdr) < 0)
478 break;
479 if(buf2 + hdr.frame_size > end ||
480 av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, buf2 + 2, hdr.frame_size - 2))
481 break;
482 buf2 += hdr.frame_size;
483 }
484 max_frames = FFMAX(max_frames, frames);
485 if(buf == p->buf)
486 first_frames = frames;
487 }
488 if (first_frames>=3) return AVPROBE_SCORE_MAX * 3 / 4;
489 else if(max_frames>=3) return AVPROBE_SCORE_MAX / 2;
490 else if(max_frames>=1) return 1;
491 else return 0;
492}
493
494static int flac_probe(AVProbeData *p)
495{
496 if(memcmp(p->buf, "fLaC", 4)) return 0;
497 else return AVPROBE_SCORE_MAX / 2;
498}
499
500
501/* Note: Do not forget to add new entries to the Makefile as well. */
502
503AVInputFormat aac_demuxer = {
504 "aac",
505 NULL_IF_CONFIG_SMALL("ADTS AAC"),
506 0,
507 NULL,
508 audio_read_header,
509 raw_read_partial_packet,
510 .flags= AVFMT_GENERIC_INDEX,
511 .extensions = "aac",
512 .value = CODEC_ID_AAC,
513};
514
515#ifdef CONFIG_AC3_DEMUXER
516AVInputFormat ac3_demuxer = {
517 "ac3",
518 NULL_IF_CONFIG_SMALL("raw AC-3"),
519 0,
520 ac3_probe,
521 audio_read_header,
522 raw_read_partial_packet,
523 .flags= AVFMT_GENERIC_INDEX,
524 .extensions = "ac3",
525 .value = CODEC_ID_AC3,
526};
527#endif
528
529#ifdef CONFIG_MUXERS
530AVOutputFormat ac3_muxer = {
531 "ac3",
532 NULL_IF_CONFIG_SMALL("raw AC-3"),
533 "audio/x-ac3",
534 "ac3",
535 0,
536 CODEC_ID_AC3,
537 CODEC_ID_NONE,
538 NULL,
539 raw_write_packet,
540 .flags= AVFMT_NOTIMESTAMPS,
541};
542#endif //CONFIG_MUXERS
543
544AVInputFormat dirac_demuxer = {
545 "dirac",
546 NULL_IF_CONFIG_SMALL("raw Dirac"),
547 0,
548 dirac_probe,
549 video_read_header,
550 raw_read_partial_packet,
551 .flags= AVFMT_GENERIC_INDEX,
552 .value = CODEC_ID_DIRAC,
553};
554
555#ifdef CONFIG_MUXERS
556AVOutputFormat dirac_muxer = {
557 "dirac",
558 NULL_IF_CONFIG_SMALL("raw Dirac"),
559 NULL,
560 "drc",
561 0,
562 CODEC_ID_NONE,
563 CODEC_ID_DIRAC,
564 NULL,
565 raw_write_packet,
566 .flags= AVFMT_NOTIMESTAMPS,
567};
568#endif
569
570AVInputFormat dts_demuxer = {
571 "dts",
572 NULL_IF_CONFIG_SMALL("raw DTS"),
573 0,
574 dts_probe,
575 audio_read_header,
576 raw_read_partial_packet,
577 .flags= AVFMT_GENERIC_INDEX,
578 .extensions = "dts",
579 .value = CODEC_ID_DTS,
580};
581
582#ifdef CONFIG_MUXERS
583AVOutputFormat dts_muxer = {
584 "dts",
585 NULL_IF_CONFIG_SMALL("raw DTS"),
586 "audio/x-dca",
587 "dts",
588 0,
589 CODEC_ID_DTS,
590 CODEC_ID_NONE,
591 NULL,
592 raw_write_packet,
593 .flags= AVFMT_NOTIMESTAMPS,
594};
595#endif
596
597AVInputFormat flac_demuxer = {
598 "flac",
599 NULL_IF_CONFIG_SMALL("raw FLAC"),
600 0,
601 flac_probe,
602 audio_read_header,
603 raw_read_partial_packet,
604 .flags= AVFMT_GENERIC_INDEX,
605 .extensions = "flac",
606 .value = CODEC_ID_FLAC,
607};
608
609#ifdef CONFIG_MUXERS
610AVOutputFormat flac_muxer = {
611 "flac",
612 NULL_IF_CONFIG_SMALL("raw FLAC"),
613 "audio/x-flac",
614 "flac",
615 0,
616 CODEC_ID_FLAC,
617 CODEC_ID_NONE,
618 flac_write_header,
619 raw_write_packet,
620 .flags= AVFMT_NOTIMESTAMPS,
621};
622#endif //CONFIG_MUXERS
623
624AVInputFormat gsm_demuxer = {
625 "gsm",
626 NULL_IF_CONFIG_SMALL("GSM"),
627 0,
628 NULL,
629 audio_read_header,
630 raw_read_partial_packet,
631 .flags= AVFMT_GENERIC_INDEX,
632 .extensions = "gsm",
633 .value = CODEC_ID_GSM,
634};
635
636AVInputFormat h261_demuxer = {
637 "h261",
638 NULL_IF_CONFIG_SMALL("raw H.261"),
639 0,
640 h261_probe,
641 video_read_header,
642 raw_read_partial_packet,
643 .flags= AVFMT_GENERIC_INDEX,
644 .extensions = "h261",
645 .value = CODEC_ID_H261,
646};
647
648#ifdef CONFIG_MUXERS
649AVOutputFormat h261_muxer = {
650 "h261",
651 NULL_IF_CONFIG_SMALL("raw H.261"),
652 "video/x-h261",
653 "h261",
654 0,
655 CODEC_ID_NONE,
656 CODEC_ID_H261,
657 NULL,
658 raw_write_packet,
659 .flags= AVFMT_NOTIMESTAMPS,
660};
661#endif //CONFIG_MUXERS
662
663AVInputFormat h263_demuxer = {
664 "h263",
665 NULL_IF_CONFIG_SMALL("raw H.263"),
666 0,
667 h263_probe,
668 video_read_header,
669 raw_read_partial_packet,
670 .flags= AVFMT_GENERIC_INDEX,
671// .extensions = "h263", //FIXME remove after writing mpeg4_probe
672 .value = CODEC_ID_H263,
673};
674
675#ifdef CONFIG_MUXERS
676AVOutputFormat h263_muxer = {
677 "h263",
678 NULL_IF_CONFIG_SMALL("raw H.263"),
679 "video/x-h263",
680 "h263",
681 0,
682 CODEC_ID_NONE,
683 CODEC_ID_H263,
684 NULL,
685 raw_write_packet,
686 .flags= AVFMT_NOTIMESTAMPS,
687};
688#endif //CONFIG_MUXERS
689
690AVInputFormat h264_demuxer = {
691 "h264",
692 NULL_IF_CONFIG_SMALL("raw H.264 video format"),
693 0,
694 h264_probe,
695 video_read_header,
696 raw_read_partial_packet,
697 .flags= AVFMT_GENERIC_INDEX,
698 .extensions = "h26l,h264,264", //FIXME remove after writing mpeg4_probe
699 .value = CODEC_ID_H264,
700};
701
702#ifdef CONFIG_MUXERS
703AVOutputFormat h264_muxer = {
704 "h264",
705 NULL_IF_CONFIG_SMALL("raw H.264 video format"),
706 NULL,
707 "h264",
708 0,
709 CODEC_ID_NONE,
710 CODEC_ID_H264,
711 NULL,
712 raw_write_packet,
713 .flags= AVFMT_NOTIMESTAMPS,
714};
715#endif //CONFIG_MUXERS
716
717AVInputFormat ingenient_demuxer = {
718 "ingenient",
719 NULL_IF_CONFIG_SMALL("Ingenient MJPEG"),
720 0,
721 NULL,
722 video_read_header,
723 ingenient_read_packet,
724 .flags= AVFMT_GENERIC_INDEX,
725 .extensions = "cgi", // FIXME
726 .value = CODEC_ID_MJPEG,
727};
728
729AVInputFormat m4v_demuxer = {
730 "m4v",
731 NULL_IF_CONFIG_SMALL("raw MPEG-4 video format"),
732 0,
733 mpeg4video_probe, /** probing for mpeg4 data */
734 video_read_header,
735 raw_read_partial_packet,
736 .flags= AVFMT_GENERIC_INDEX,
737 .extensions = "m4v", //FIXME remove after writing mpeg4_probe
738 .value = CODEC_ID_MPEG4,
739};
740
741#ifdef CONFIG_MUXERS
742AVOutputFormat m4v_muxer = {
743 "m4v",
744 NULL_IF_CONFIG_SMALL("raw MPEG-4 video format"),
745 NULL,
746 "m4v",
747 0,
748 CODEC_ID_NONE,
749 CODEC_ID_MPEG4,
750 NULL,
751 raw_write_packet,
752 .flags= AVFMT_NOTIMESTAMPS,
753};
754#endif //CONFIG_MUXERS
755
756AVInputFormat mjpeg_demuxer = {
757 "mjpeg",
758 NULL_IF_CONFIG_SMALL("MJPEG video"),
759 0,
760 NULL,
761 video_read_header,
762 raw_read_partial_packet,
763 .flags= AVFMT_GENERIC_INDEX,
764 .extensions = "mjpg,mjpeg",
765 .value = CODEC_ID_MJPEG,
766};
767
768#ifdef CONFIG_MUXERS
769AVOutputFormat mjpeg_muxer = {
770 "mjpeg",
771 NULL_IF_CONFIG_SMALL("MJPEG video"),
772 "video/x-mjpeg",
773 "mjpg,mjpeg",
774 0,
775 CODEC_ID_NONE,
776 CODEC_ID_MJPEG,
777 NULL,
778 raw_write_packet,
779 .flags= AVFMT_NOTIMESTAMPS,
780};
781#endif //CONFIG_MUXERS
782
783AVInputFormat mlp_demuxer = {
784 "mlp",
785 NULL_IF_CONFIG_SMALL("raw MLP"),
786 0,
787 NULL,
788 audio_read_header,
789 raw_read_partial_packet,
790 .flags= AVFMT_GENERIC_INDEX,
791 .extensions = "mlp",
792 .value = CODEC_ID_MLP,
793};
794
795#ifdef CONFIG_MUXERS
796AVOutputFormat mpeg1video_muxer = {
797 "mpeg1video",
798 NULL_IF_CONFIG_SMALL("MPEG video"),
799 "video/x-mpeg",
800 "mpg,mpeg,m1v",
801 0,
802 CODEC_ID_NONE,
803 CODEC_ID_MPEG1VIDEO,
804 NULL,
805 raw_write_packet,
806 .flags= AVFMT_NOTIMESTAMPS,
807};
808#endif //CONFIG_MUXERS
809
810#ifdef CONFIG_MUXERS
811AVOutputFormat mpeg2video_muxer = {
812 "mpeg2video",
813 NULL_IF_CONFIG_SMALL("MPEG-2 video"),
814 NULL,
815 "m2v",
816 0,
817 CODEC_ID_NONE,
818 CODEC_ID_MPEG2VIDEO,
819 NULL,
820 raw_write_packet,
821 .flags= AVFMT_NOTIMESTAMPS,
822};
823#endif //CONFIG_MUXERS
824
825AVInputFormat mpegvideo_demuxer = {
826 "mpegvideo",
827 NULL_IF_CONFIG_SMALL("MPEG video"),
828 0,
829 mpegvideo_probe,
830 video_read_header,
831 raw_read_partial_packet,
832 .flags= AVFMT_GENERIC_INDEX,
833 .value = CODEC_ID_MPEG1VIDEO,
834};
835
836#ifdef CONFIG_MUXERS
837AVOutputFormat null_muxer = {
838 "null",
839 NULL_IF_CONFIG_SMALL("null video format"),
840 NULL,
841 NULL,
842 0,
843#ifdef WORDS_BIGENDIAN
844 CODEC_ID_PCM_S16BE,
845#else
846 CODEC_ID_PCM_S16LE,
847#endif
848 CODEC_ID_RAWVIDEO,
849 NULL,
850 null_write_packet,
851 .flags = AVFMT_NOFILE | AVFMT_RAWPICTURE | AVFMT_NOTIMESTAMPS,
852};
853#endif //CONFIG_MUXERS
854
855AVInputFormat rawvideo_demuxer = {
856 "rawvideo",
857 NULL_IF_CONFIG_SMALL("raw video format"),
858 0,
859 NULL,
860 raw_read_header,
861 rawvideo_read_packet,
862 .flags= AVFMT_GENERIC_INDEX,
863 .extensions = "yuv,cif,qcif,rgb",
864 .value = CODEC_ID_RAWVIDEO,
865};
866
867#ifdef CONFIG_MUXERS
868AVOutputFormat rawvideo_muxer = {
869 "rawvideo",
870 NULL_IF_CONFIG_SMALL("raw video format"),
871 NULL,
872 "yuv,rgb",
873 0,
874 CODEC_ID_NONE,
875 CODEC_ID_RAWVIDEO,
876 NULL,
877 raw_write_packet,
878 .flags= AVFMT_NOTIMESTAMPS,
879};
880#endif //CONFIG_MUXERS
881
882#ifdef CONFIG_ROQ_MUXER
883AVOutputFormat roq_muxer =
884{
885 "RoQ",
886 NULL_IF_CONFIG_SMALL("id RoQ format"),
887 NULL,
888 "roq",
889 0,
890 CODEC_ID_ROQ_DPCM,
891 CODEC_ID_ROQ,
892 roq_write_header,
893 raw_write_packet,
894};
895#endif //CONFIG_ROQ_MUXER
896
897AVInputFormat shorten_demuxer = {
898 "shn",
899 NULL_IF_CONFIG_SMALL("raw Shorten"),
900 0,
901 NULL,
902 audio_read_header,
903 raw_read_partial_packet,
904 .flags= AVFMT_GENERIC_INDEX,
905 .extensions = "shn",
906 .value = CODEC_ID_SHORTEN,
907};
908
909AVInputFormat vc1_demuxer = {
910 "vc1",
911 NULL_IF_CONFIG_SMALL("raw VC-1"),
912 0,
913 NULL /* vc1_probe */,
914 video_read_header,
915 raw_read_partial_packet,
916 .extensions = "vc1",
917 .value = CODEC_ID_VC1,
918};
919
920/* pcm formats */
921
922#define PCMINPUTDEF(name, long_name, ext, codec) \
923AVInputFormat pcm_ ## name ## _demuxer = {\
924 #name,\
925 NULL_IF_CONFIG_SMALL(long_name),\
926 0,\
927 NULL,\
928 raw_read_header,\
929 raw_read_packet,\
930 NULL,\
931 pcm_read_seek,\
932 .flags= AVFMT_GENERIC_INDEX,\
933 .extensions = ext,\
934 .value = codec,\
935};
936
937#define PCMOUTPUTDEF(name, long_name, ext, codec) \
938AVOutputFormat pcm_ ## name ## _muxer = {\
939 #name,\
940 NULL_IF_CONFIG_SMALL(long_name),\
941 NULL,\
942 ext,\
943 0,\
944 codec,\
945 CODEC_ID_NONE,\
946 NULL,\
947 raw_write_packet,\
948 .flags= AVFMT_NOTIMESTAMPS,\
949};
950
951
952#if !defined(CONFIG_MUXERS) && defined(CONFIG_DEMUXERS)
953#define PCMDEF(name, long_name, ext, codec) \
954 PCMINPUTDEF(name, long_name, ext, codec)
955#elif defined(CONFIG_MUXERS) && !defined(CONFIG_DEMUXERS)
956#define PCMDEF(name, long_name, ext, codec) \
957 PCMOUTPUTDEF(name, long_name, ext, codec)
958#elif defined(CONFIG_MUXERS) && defined(CONFIG_DEMUXERS)
959#define PCMDEF(name, long_name, ext, codec) \
960 PCMINPUTDEF(name, long_name, ext, codec)\
961 PCMOUTPUTDEF(name, long_name, ext, codec)
962#else
963#define PCMDEF(name, long_name, ext, codec)
964#endif
965
966#ifdef WORDS_BIGENDIAN
967#define BE_DEF(s) s
968#define LE_DEF(s) NULL
969#else
970#define BE_DEF(s) NULL
971#define LE_DEF(s) s
972#endif
973
974
975PCMDEF(s16be, "PCM signed 16 bit big-endian format",
976 BE_DEF("sw"), CODEC_ID_PCM_S16BE)
977
978PCMDEF(s16le, "PCM signed 16 bit little-endian format",
979 LE_DEF("sw"), CODEC_ID_PCM_S16LE)
980
981PCMDEF(s8, "PCM signed 8 bit format",
982 "sb", CODEC_ID_PCM_S8)
983
984PCMDEF(u16be, "PCM unsigned 16 bit big-endian format",
985 BE_DEF("uw"), CODEC_ID_PCM_U16BE)
986
987PCMDEF(u16le, "PCM unsigned 16 bit little-endian format",
988 LE_DEF("uw"), CODEC_ID_PCM_U16LE)
989
990PCMDEF(u8, "PCM unsigned 8 bit format",
991 "ub", CODEC_ID_PCM_U8)
992
993PCMDEF(alaw, "PCM A-law format",
994 "al", CODEC_ID_PCM_ALAW)
995
996PCMDEF(mulaw, "PCM mu-law format",
997 "ul", CODEC_ID_PCM_MULAW)
diff --git a/src/plugins/ffmpeg/libavformat/raw.h b/src/plugins/ffmpeg/libavformat/raw.h
deleted file mode 100644
index 3d851c8..0000000
--- a/src/plugins/ffmpeg/libavformat/raw.h
+++ /dev/null
@@ -1,30 +0,0 @@
1/*
2 * RAW muxer and demuxer
3 * Copyright (C) 2007 Aurelien Jacobs <aurel@gnuage.org>
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#ifndef FFMPEG_RAW_H
23#define FFMPEG_RAW_H
24
25#include "avformat.h"
26
27int pcm_read_seek(AVFormatContext *s,
28 int stream_index, int64_t timestamp, int flags);
29
30#endif /* FFMPEG_RAW_H */
diff --git a/src/plugins/ffmpeg/libavformat/riff.c b/src/plugins/ffmpeg/libavformat/riff.c
deleted file mode 100644
index 1945b38..0000000
--- a/src/plugins/ffmpeg/libavformat/riff.c
+++ /dev/null
@@ -1,434 +0,0 @@
1/*
2 * RIFF codec tags
3 * Copyright (c) 2000 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 "libavcodec/avcodec.h"
23#include "avformat.h"
24#include "riff.h"
25
26/* Note: when encoding, the first matching tag is used, so order is
27 important if multiple tags possible for a given codec. */
28const AVCodecTag codec_bmp_tags[] = {
29 { CODEC_ID_H264, MKTAG('H', '2', '6', '4') },
30 { CODEC_ID_H264, MKTAG('h', '2', '6', '4') },
31 { CODEC_ID_H264, MKTAG('X', '2', '6', '4') },
32 { CODEC_ID_H264, MKTAG('x', '2', '6', '4') },
33 { CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') },
34 { CODEC_ID_H264, MKTAG('V', 'S', 'S', 'H') },
35 { CODEC_ID_H263, MKTAG('H', '2', '6', '3') },
36 { CODEC_ID_H263P, MKTAG('H', '2', '6', '3') },
37 { CODEC_ID_H263I, MKTAG('I', '2', '6', '3') }, /* intel h263 */
38 { CODEC_ID_H261, MKTAG('H', '2', '6', '1') },
39 { CODEC_ID_H263P, MKTAG('U', '2', '6', '3') },
40 { CODEC_ID_H263P, MKTAG('v', 'i', 'v', '1') },
41 { CODEC_ID_MPEG4, MKTAG('F', 'M', 'P', '4') },
42 { CODEC_ID_MPEG4, MKTAG('D', 'I', 'V', 'X') },
43 { CODEC_ID_MPEG4, MKTAG('D', 'X', '5', '0') },
44 { CODEC_ID_MPEG4, MKTAG('X', 'V', 'I', 'D') },
45 { CODEC_ID_MPEG4, MKTAG('M', 'P', '4', 'S') },
46 { CODEC_ID_MPEG4, MKTAG('M', '4', 'S', '2') },
47 { CODEC_ID_MPEG4, MKTAG( 4 , 0 , 0 , 0 ) }, /* some broken avi use this */
48 { CODEC_ID_MPEG4, MKTAG('D', 'I', 'V', '1') },
49 { CODEC_ID_MPEG4, MKTAG('B', 'L', 'Z', '0') },
50 { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
51 { CODEC_ID_MPEG4, MKTAG('U', 'M', 'P', '4') },
52 { CODEC_ID_MPEG4, MKTAG('W', 'V', '1', 'F') },
53 { CODEC_ID_MPEG4, MKTAG('S', 'E', 'D', 'G') },
54 { CODEC_ID_MPEG4, MKTAG('R', 'M', 'P', '4') },
55 { CODEC_ID_MSMPEG4V3, MKTAG('D', 'I', 'V', '3') }, /* default signature when using MSMPEG4 */
56 { CODEC_ID_MSMPEG4V3, MKTAG('M', 'P', '4', '3') },
57 { CODEC_ID_MSMPEG4V3, MKTAG('M', 'P', 'G', '3') },
58 { CODEC_ID_MSMPEG4V3, MKTAG('D', 'I', 'V', '5') },
59 { CODEC_ID_MSMPEG4V3, MKTAG('D', 'I', 'V', '6') },
60 { CODEC_ID_MSMPEG4V3, MKTAG('D', 'I', 'V', '4') },
61 { CODEC_ID_MSMPEG4V3, MKTAG('A', 'P', '4', '1') },
62 { CODEC_ID_MSMPEG4V3, MKTAG('C', 'O', 'L', '1') },
63 { CODEC_ID_MSMPEG4V3, MKTAG('C', 'O', 'L', '0') },
64 { CODEC_ID_MSMPEG4V2, MKTAG('M', 'P', '4', '2') },
65 { CODEC_ID_MSMPEG4V2, MKTAG('D', 'I', 'V', '2') },
66 { CODEC_ID_MSMPEG4V1, MKTAG('M', 'P', 'G', '4') },
67 { CODEC_ID_WMV1, MKTAG('W', 'M', 'V', '1') },
68 { CODEC_ID_WMV2, MKTAG('W', 'M', 'V', '2') },
69 { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 's', 'd') },
70 { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'h', 'd') },
71 { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 's', 'l') },
72 { CODEC_ID_DVVIDEO, MKTAG('d', 'v', '2', '5') },
73 { CODEC_ID_DVVIDEO, MKTAG('d', 'v', '5', '0') },
74 { CODEC_ID_DVVIDEO, MKTAG('c', 'd', 'v', 'c') }, /* Canopus DV */
75 { CODEC_ID_MPEG1VIDEO, MKTAG('m', 'p', 'g', '1') },
76 { CODEC_ID_MPEG1VIDEO, MKTAG('m', 'p', 'g', '2') },
77 { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'p', 'g', '2') },
78 { CODEC_ID_MPEG2VIDEO, MKTAG('M', 'P', 'E', 'G') },
79 { CODEC_ID_MPEG1VIDEO, MKTAG('P', 'I', 'M', '1') },
80 { CODEC_ID_MPEG1VIDEO, MKTAG('V', 'C', 'R', '2') },
81 { CODEC_ID_MPEG1VIDEO, MKTAG( 1 , 0 , 0 , 16) },
82 { CODEC_ID_MPEG2VIDEO, MKTAG( 2 , 0 , 0 , 16) },
83 { CODEC_ID_MPEG2VIDEO, MKTAG('D', 'V', 'R', ' ') },
84 { CODEC_ID_MPEG2VIDEO, MKTAG('M', 'M', 'E', 'S') },
85 { CODEC_ID_MJPEG, MKTAG('M', 'J', 'P', 'G') },
86 { CODEC_ID_MJPEG, MKTAG('L', 'J', 'P', 'G') },
87 { CODEC_ID_LJPEG, MKTAG('L', 'J', 'P', 'G') },
88 { CODEC_ID_MJPEG, MKTAG('J', 'P', 'G', 'L') }, /* Pegasus lossless JPEG */
89 { CODEC_ID_JPEGLS, MKTAG('M', 'J', 'L', 'S') }, /* JPEG-LS custom FOURCC for avi - encoder */
90 { CODEC_ID_MJPEG, MKTAG('M', 'J', 'L', 'S') }, /* JPEG-LS custom FOURCC for avi - decoder */
91 { CODEC_ID_MJPEG, MKTAG('j', 'p', 'e', 'g') },
92 { CODEC_ID_MJPEG, MKTAG('I', 'J', 'P', 'G') },
93 { CODEC_ID_MJPEG, MKTAG('A', 'V', 'R', 'n') },
94 { CODEC_ID_HUFFYUV, MKTAG('H', 'F', 'Y', 'U') },
95 { CODEC_ID_FFVHUFF, MKTAG('F', 'F', 'V', 'H') },
96 { CODEC_ID_CYUV, MKTAG('C', 'Y', 'U', 'V') },
97 { CODEC_ID_RAWVIDEO, MKTAG( 0 , 0 , 0 , 0 ) },
98 { CODEC_ID_RAWVIDEO, MKTAG('I', '4', '2', '0') },
99 { CODEC_ID_RAWVIDEO, MKTAG('Y', 'U', 'Y', '2') },
100 { CODEC_ID_RAWVIDEO, MKTAG('Y', '4', '2', '2') },
101 { CODEC_ID_RAWVIDEO, MKTAG('Y', 'V', '1', '2') },
102 { CODEC_ID_RAWVIDEO, MKTAG('U', 'Y', 'V', 'Y') },
103 { CODEC_ID_RAWVIDEO, MKTAG('I', 'Y', 'U', 'V') },
104 { CODEC_ID_RAWVIDEO, MKTAG('Y', '8', '0', '0') },
105 { CODEC_ID_RAWVIDEO, MKTAG('H', 'D', 'Y', 'C') },
106 { CODEC_ID_INDEO3, MKTAG('I', 'V', '3', '1') },
107 { CODEC_ID_INDEO3, MKTAG('I', 'V', '3', '2') },
108 { CODEC_ID_INDEO4, MKTAG('I', 'V', '4', '1') },
109 { CODEC_ID_INDEO5, MKTAG('I', 'V', '5', '0') },
110 { CODEC_ID_VP3, MKTAG('V', 'P', '3', '1') },
111 { CODEC_ID_VP3, MKTAG('V', 'P', '3', '0') },
112 { CODEC_ID_VP5, MKTAG('V', 'P', '5', '0') },
113 { CODEC_ID_VP6, MKTAG('V', 'P', '6', '0') },
114 { CODEC_ID_VP6, MKTAG('V', 'P', '6', '1') },
115 { CODEC_ID_VP6, MKTAG('V', 'P', '6', '2') },
116 { CODEC_ID_ASV1, MKTAG('A', 'S', 'V', '1') },
117 { CODEC_ID_ASV2, MKTAG('A', 'S', 'V', '2') },
118 { CODEC_ID_VCR1, MKTAG('V', 'C', 'R', '1') },
119 { CODEC_ID_FFV1, MKTAG('F', 'F', 'V', '1') },
120 { CODEC_ID_XAN_WC4, MKTAG('X', 'x', 'a', 'n') },
121 { CODEC_ID_MSRLE, MKTAG('m', 'r', 'l', 'e') },
122 { CODEC_ID_MSRLE, MKTAG( 1 , 0 , 0 , 0 ) },
123 { CODEC_ID_MSVIDEO1, MKTAG('M', 'S', 'V', 'C') },
124 { CODEC_ID_MSVIDEO1, MKTAG('m', 's', 'v', 'c') },
125 { CODEC_ID_MSVIDEO1, MKTAG('C', 'R', 'A', 'M') },
126 { CODEC_ID_MSVIDEO1, MKTAG('c', 'r', 'a', 'm') },
127 { CODEC_ID_MSVIDEO1, MKTAG('W', 'H', 'A', 'M') },
128 { CODEC_ID_MSVIDEO1, MKTAG('w', 'h', 'a', 'm') },
129 { CODEC_ID_CINEPAK, MKTAG('c', 'v', 'i', 'd') },
130 { CODEC_ID_TRUEMOTION1, MKTAG('D', 'U', 'C', 'K') },
131 { CODEC_ID_MSZH, MKTAG('M', 'S', 'Z', 'H') },
132 { CODEC_ID_ZLIB, MKTAG('Z', 'L', 'I', 'B') },
133 { CODEC_ID_SNOW, MKTAG('S', 'N', 'O', 'W') },
134 { CODEC_ID_4XM, MKTAG('4', 'X', 'M', 'V') },
135 { CODEC_ID_FLV1, MKTAG('F', 'L', 'V', '1') },
136 { CODEC_ID_FLASHSV, MKTAG('F', 'S', 'V', '1') },
137 { CODEC_ID_VP6F, MKTAG('V', 'P', '6', 'F') },
138 { CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', '1') },
139 { CODEC_ID_TSCC, MKTAG('t', 's', 'c', 'c') },
140 { CODEC_ID_ULTI, MKTAG('U', 'L', 'T', 'I') },
141 { CODEC_ID_VIXL, MKTAG('V', 'I', 'X', 'L') },
142 { CODEC_ID_QPEG, MKTAG('Q', 'P', 'E', 'G') },
143 { CODEC_ID_QPEG, MKTAG('Q', '1', '.', '0') },
144 { CODEC_ID_QPEG, MKTAG('Q', '1', '.', '1') },
145 { CODEC_ID_WMV3, MKTAG('W', 'M', 'V', '3') },
146 { CODEC_ID_VC1, MKTAG('W', 'V', 'C', '1') },
147 { CODEC_ID_VC1, MKTAG('W', 'M', 'V', 'A') },
148 { CODEC_ID_LOCO, MKTAG('L', 'O', 'C', 'O') },
149 { CODEC_ID_WNV1, MKTAG('W', 'N', 'V', '1') },
150 { CODEC_ID_AASC, MKTAG('A', 'A', 'S', 'C') },
151 { CODEC_ID_INDEO2, MKTAG('R', 'T', '2', '1') },
152 { CODEC_ID_FRAPS, MKTAG('F', 'P', 'S', '1') },
153 { CODEC_ID_THEORA, MKTAG('t', 'h', 'e', 'o') },
154 { CODEC_ID_TRUEMOTION2, MKTAG('T', 'M', '2', '0') },
155 { CODEC_ID_CSCD, MKTAG('C', 'S', 'C', 'D') },
156 { CODEC_ID_ZMBV, MKTAG('Z', 'M', 'B', 'V') },
157 { CODEC_ID_KMVC, MKTAG('K', 'M', 'V', 'C') },
158 { CODEC_ID_CAVS, MKTAG('C', 'A', 'V', 'S') },
159 { CODEC_ID_JPEG2000, MKTAG('M', 'J', '2', 'C') },
160 { CODEC_ID_VMNC, MKTAG('V', 'M', 'n', 'c') },
161 { CODEC_ID_TARGA, MKTAG('t', 'g', 'a', ' ') },
162 { CODEC_ID_CLJR, MKTAG('c', 'l', 'j', 'r') },
163 { CODEC_ID_DIRAC, MKTAG('d', 'r', 'a', 'c') },
164 { CODEC_ID_NONE, 0 }
165};
166
167const AVCodecTag codec_wav_tags[] = {
168 { CODEC_ID_PCM_S16LE, 0x0001 },
169 { CODEC_ID_PCM_U8, 0x0001 }, /* must come after s16le in this list */
170 { CODEC_ID_PCM_S24LE, 0x0001 },
171 { CODEC_ID_PCM_S32LE, 0x0001 },
172 { CODEC_ID_ADPCM_MS, 0x0002 },
173 { CODEC_ID_PCM_ALAW, 0x0006 },
174 { CODEC_ID_PCM_MULAW, 0x0007 },
175 { CODEC_ID_WMAVOICE, 0x000A },
176 { CODEC_ID_ADPCM_IMA_WAV, 0x0011 },
177 { CODEC_ID_ADPCM_YAMAHA, 0x0020 },
178 { CODEC_ID_TRUESPEECH, 0x0022 },
179 { CODEC_ID_GSM_MS, 0x0031 },
180 { CODEC_ID_ADPCM_G726, 0x0045 },
181 { CODEC_ID_MP2, 0x0050 },
182 { CODEC_ID_MP3, 0x0055 },
183 { CODEC_ID_ADPCM_IMA_DK4, 0x0061 }, /* rogue format number */
184 { CODEC_ID_ADPCM_IMA_DK3, 0x0062 }, /* rogue format number */
185 { CODEC_ID_VOXWARE, 0x0075 },
186 { CODEC_ID_AAC, 0x00ff },
187 { CODEC_ID_WMAV1, 0x0160 },
188 { CODEC_ID_WMAV2, 0x0161 },
189 { CODEC_ID_WMAPRO, 0x0162 },
190 { CODEC_ID_WMALOSSLESS, 0x0163 },
191 { CODEC_ID_ADPCM_CT, 0x0200 },
192 { CODEC_ID_ATRAC3, 0x0270 },
193 { CODEC_ID_IMC, 0x0401 },
194 { CODEC_ID_AC3, 0x2000 },
195 { CODEC_ID_DTS, 0x2001 },
196 { CODEC_ID_SONIC, 0x2048 },
197 { CODEC_ID_SONIC_LS, 0x2048 },
198 { CODEC_ID_AAC, 0x706d },
199 { CODEC_ID_FLAC, 0xF1AC },
200 { CODEC_ID_ADPCM_SWF, ('S'<<8)+'F' },
201 { CODEC_ID_VORBIS, ('V'<<8)+'o' }, //HACK/FIXME, does vorbis in WAV/AVI have an (in)official id?
202
203 /* FIXME: All of the IDs below are not 16 bit and thus illegal. */
204 // for NuppelVideo (nuv.c)
205 { CODEC_ID_PCM_S16LE, MKTAG('R', 'A', 'W', 'A') },
206 { CODEC_ID_MP3, MKTAG('L', 'A', 'M', 'E') },
207 { CODEC_ID_MP3, MKTAG('M', 'P', '3', ' ') },
208 { 0, 0 },
209};
210
211#ifdef CONFIG_MUXERS
212offset_t start_tag(ByteIOContext *pb, const char *tag)
213{
214 put_tag(pb, tag);
215 put_le32(pb, 0);
216 return url_ftell(pb);
217}
218
219void end_tag(ByteIOContext *pb, offset_t start)
220{
221 offset_t pos;
222
223 pos = url_ftell(pb);
224 url_fseek(pb, start - 4, SEEK_SET);
225 put_le32(pb, (uint32_t)(pos - start));
226 url_fseek(pb, pos, SEEK_SET);
227}
228
229/* WAVEFORMATEX header */
230/* returns the size or -1 on error */
231int put_wav_header(ByteIOContext *pb, AVCodecContext *enc)
232{
233 int bps, blkalign, bytespersec;
234 int hdrsize = 18;
235
236 if(!enc->codec_tag || enc->codec_tag > 0xffff)
237 return -1;
238
239 put_le16(pb, enc->codec_tag);
240 put_le16(pb, enc->channels);
241 put_le32(pb, enc->sample_rate);
242 if (enc->codec_id == CODEC_ID_PCM_U8 ||
243 enc->codec_id == CODEC_ID_PCM_ALAW ||
244 enc->codec_id == CODEC_ID_PCM_MULAW) {
245 bps = 8;
246 } else if (enc->codec_id == CODEC_ID_MP2 || enc->codec_id == CODEC_ID_MP3 || enc->codec_id == CODEC_ID_GSM_MS) {
247 bps = 0;
248 } else if (enc->codec_id == CODEC_ID_ADPCM_IMA_WAV || enc->codec_id == CODEC_ID_ADPCM_MS || enc->codec_id == CODEC_ID_ADPCM_G726 || enc->codec_id == CODEC_ID_ADPCM_YAMAHA) { //
249 bps = 4;
250 } else if (enc->codec_id == CODEC_ID_PCM_S24LE) {
251 bps = 24;
252 } else if (enc->codec_id == CODEC_ID_PCM_S32LE) {
253 bps = 32;
254 } else {
255 bps = 16;
256 }
257 if(bps != enc->bits_per_sample && enc->bits_per_sample){
258 av_log(enc, AV_LOG_WARNING, "requested bits_per_sample (%d) and actually stored (%d) differ\n", enc->bits_per_sample, bps);
259 }
260
261 if (enc->codec_id == CODEC_ID_MP2 || enc->codec_id == CODEC_ID_MP3 || enc->codec_id == CODEC_ID_GSM_MS || enc->codec_id == CODEC_ID_AC3) {
262 blkalign = enc->frame_size; //this is wrong, but it seems many demuxers do not work if this is set correctly
263 //blkalign = 144 * enc->bit_rate/enc->sample_rate;
264 } else if (enc->codec_id == CODEC_ID_ADPCM_G726) { //
265 blkalign = 1;
266 } else if (enc->block_align != 0) { /* specified by the codec */
267 blkalign = enc->block_align;
268 } else
269 blkalign = enc->channels*bps >> 3;
270 if (enc->codec_id == CODEC_ID_PCM_U8 ||
271 enc->codec_id == CODEC_ID_PCM_S24LE ||
272 enc->codec_id == CODEC_ID_PCM_S32LE ||
273 enc->codec_id == CODEC_ID_PCM_S16LE) {
274 bytespersec = enc->sample_rate * blkalign;
275 } else {
276 bytespersec = enc->bit_rate / 8;
277 }
278 put_le32(pb, bytespersec); /* bytes per second */
279 put_le16(pb, blkalign); /* block align */
280 put_le16(pb, bps); /* bits per sample */
281 if (enc->codec_id == CODEC_ID_MP3) {
282 put_le16(pb, 12); /* wav_extra_size */
283 hdrsize += 12;
284 put_le16(pb, 1); /* wID */
285 put_le32(pb, 2); /* fdwFlags */
286 put_le16(pb, 1152); /* nBlockSize */
287 put_le16(pb, 1); /* nFramesPerBlock */
288 put_le16(pb, 1393); /* nCodecDelay */
289 } else if (enc->codec_id == CODEC_ID_MP2) {
290 put_le16(pb, 22); /* wav_extra_size */
291 hdrsize += 22;
292 put_le16(pb, 2); /* fwHeadLayer */
293 put_le32(pb, enc->bit_rate); /* dwHeadBitrate */
294 put_le16(pb, enc->channels == 2 ? 1 : 8); /* fwHeadMode */
295 put_le16(pb, 0); /* fwHeadModeExt */
296 put_le16(pb, 1); /* wHeadEmphasis */
297 put_le16(pb, 16); /* fwHeadFlags */
298 put_le32(pb, 0); /* dwPTSLow */
299 put_le32(pb, 0); /* dwPTSHigh */
300 } else if (enc->codec_id == CODEC_ID_GSM_MS) {
301 put_le16(pb, 2); /* wav_extra_size */
302 hdrsize += 2;
303 put_le16(pb, enc->frame_size); /* wSamplesPerBlock */
304 } else if (enc->codec_id == CODEC_ID_ADPCM_IMA_WAV) {
305 put_le16(pb, 2); /* wav_extra_size */
306 hdrsize += 2;
307 put_le16(pb, enc->frame_size); /* wSamplesPerBlock */
308 } else if(enc->extradata_size){
309 put_le16(pb, enc->extradata_size);
310 put_buffer(pb, enc->extradata, enc->extradata_size);
311 hdrsize += enc->extradata_size;
312 if(hdrsize&1){
313 hdrsize++;
314 put_byte(pb, 0);
315 }
316 } else {
317 hdrsize -= 2;
318 }
319
320 return hdrsize;
321}
322
323/* BITMAPINFOHEADER header */
324void put_bmp_header(ByteIOContext *pb, AVCodecContext *enc, const AVCodecTag *tags, int for_asf)
325{
326 put_le32(pb, 40 + enc->extradata_size); /* size */
327 put_le32(pb, enc->width);
328 put_le32(pb, enc->height);
329 put_le16(pb, 1); /* planes */
330
331 put_le16(pb, enc->bits_per_sample ? enc->bits_per_sample : 24); /* depth */
332 /* compression type */
333 put_le32(pb, enc->codec_tag);
334 put_le32(pb, enc->width * enc->height * 3);
335 put_le32(pb, 0);
336 put_le32(pb, 0);
337 put_le32(pb, 0);
338 put_le32(pb, 0);
339
340 put_buffer(pb, enc->extradata, enc->extradata_size);
341
342 if (enc->extradata_size & 1)
343 put_byte(pb, 0);
344}
345#endif //CONFIG_MUXERS
346
347#ifdef CONFIG_DEMUXERS
348/* We could be given one of the three possible structures here:
349 * WAVEFORMAT, PCMWAVEFORMAT or WAVEFORMATEX. Each structure
350 * is an expansion of the previous one with the fields added
351 * at the bottom. PCMWAVEFORMAT adds 'WORD wBitsPerSample' and
352 * WAVEFORMATEX adds 'WORD cbSize' and basically makes itself
353 * an openended structure.
354 */
355void get_wav_header(ByteIOContext *pb, AVCodecContext *codec, int size)
356{
357 int id;
358
359 id = get_le16(pb);
360 codec->codec_type = CODEC_TYPE_AUDIO;
361 codec->codec_tag = id;
362 codec->channels = get_le16(pb);
363 codec->sample_rate = get_le32(pb);
364 codec->bit_rate = get_le32(pb) * 8;
365 codec->block_align = get_le16(pb);
366 if (size == 14) { /* We're dealing with plain vanilla WAVEFORMAT */
367 codec->bits_per_sample = 8;
368 }else
369 codec->bits_per_sample = get_le16(pb);
370 if (size >= 18) { /* We're obviously dealing with WAVEFORMATEX */
371 int cbSize = get_le16(pb); /* cbSize */
372 size -= 18;
373 cbSize = FFMIN(size, cbSize);
374 if (cbSize >= 22 && id == 0xfffe) { /* WAVEFORMATEXTENSIBLE */
375 codec->bits_per_sample = get_le16(pb);
376 get_le32(pb); /* dwChannelMask */
377 id = get_le32(pb); /* 4 first bytes of GUID */
378 url_fskip(pb, 12); /* skip end of GUID */
379 cbSize -= 22;
380 size -= 22;
381 }
382 codec->extradata_size = cbSize;
383 if (cbSize > 0) {
384 codec->extradata = av_mallocz(codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
385 get_buffer(pb, codec->extradata, codec->extradata_size);
386 size -= cbSize;
387 }
388
389 /* It is possible for the chunk to contain garbage at the end */
390 if (size > 0)
391 url_fskip(pb, size);
392 }
393 codec->codec_id = wav_codec_get_id(id, codec->bits_per_sample);
394}
395
396
397int wav_codec_get_id(unsigned int tag, int bps)
398{
399 int id;
400 id = codec_get_id(codec_wav_tags, tag);
401 if (id <= 0)
402 return id;
403 /* handle specific u8 codec */
404 if (id == CODEC_ID_PCM_S16LE && bps == 8)
405 id = CODEC_ID_PCM_U8;
406 if (id == CODEC_ID_PCM_S16LE && bps == 24)
407 id = CODEC_ID_PCM_S24LE;
408 if (id == CODEC_ID_PCM_S16LE && bps == 32)
409 id = CODEC_ID_PCM_S32LE;
410 if (id == CODEC_ID_ADPCM_IMA_WAV && bps == 8)
411 id = CODEC_ID_PCM_ZORK;
412 return id;
413}
414#endif // CONFIG_DEMUXERS
415
416void ff_parse_specific_params(AVCodecContext *stream, int *au_rate, int *au_ssize, int *au_scale)
417{
418 int gcd;
419
420 *au_ssize= stream->block_align;
421 if(stream->frame_size && stream->sample_rate){
422 *au_scale=stream->frame_size;
423 *au_rate= stream->sample_rate;
424 }else if(stream->codec_type == CODEC_TYPE_VIDEO){
425 *au_scale= stream->time_base.num;
426 *au_rate = stream->time_base.den;
427 }else{
428 *au_scale= stream->block_align ? stream->block_align*8 : 8;
429 *au_rate = stream->bit_rate ? stream->bit_rate : 8*stream->sample_rate;
430 }
431 gcd= ff_gcd(*au_scale, *au_rate);
432 *au_scale /= gcd;
433 *au_rate /= gcd;
434}
diff --git a/src/plugins/ffmpeg/libavformat/riff.h b/src/plugins/ffmpeg/libavformat/riff.h
deleted file mode 100644
index 9d36715..0000000
--- a/src/plugins/ffmpeg/libavformat/riff.h
+++ /dev/null
@@ -1,54 +0,0 @@
1/*
2 * RIFF codec tags
3 * copyright (c) 2000 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/**
23 * @file riff.h
24 * internal header for RIFF based (de)muxers
25 * do NOT include this in end user applications
26 */
27
28#ifndef FFMPEG_RIFF_H
29#define FFMPEG_RIFF_H
30
31#include "libavcodec/avcodec.h"
32#include "avio.h"
33
34offset_t start_tag(ByteIOContext *pb, const char *tag);
35void end_tag(ByteIOContext *pb, offset_t start);
36
37typedef struct AVCodecTag {
38 int id;
39 unsigned int tag;
40} AVCodecTag;
41
42void put_bmp_header(ByteIOContext *pb, AVCodecContext *enc, const AVCodecTag *tags, int for_asf);
43int put_wav_header(ByteIOContext *pb, AVCodecContext *enc);
44int wav_codec_get_id(unsigned int tag, int bps);
45void get_wav_header(ByteIOContext *pb, AVCodecContext *codec, int size);
46
47extern const AVCodecTag codec_bmp_tags[];
48extern const AVCodecTag codec_wav_tags[];
49
50unsigned int codec_get_tag(const AVCodecTag *tags, int id);
51enum CodecID codec_get_id(const AVCodecTag *tags, unsigned int tag);
52void ff_parse_specific_params(AVCodecContext *stream, int *au_rate, int *au_ssize, int *au_scale);
53
54#endif /* FFMPEG_RIFF_H */
diff --git a/src/plugins/ffmpeg/libavformat/rl2.c b/src/plugins/ffmpeg/libavformat/rl2.c
deleted file mode 100644
index 407867f..0000000
--- a/src/plugins/ffmpeg/libavformat/rl2.c
+++ /dev/null
@@ -1,299 +0,0 @@
1/*
2 * RL2 Format Demuxer
3 * Copyright (c) 2008 Sascha Sommer (saschasommer@freenet.de)
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/**
23 * RL2 file demuxer
24 * @file rl2.c
25 * @author Sascha Sommer (saschasommer@freenet.de)
26 * For more information regarding the RL2 file format, visit:
27 * http://wiki.multimedia.cx/index.php?title=RL2
28 *
29 * extradata:
30 * 2 byte le initial drawing offset within 320x200 viewport
31 * 4 byte le number of used colors
32 * 256 * 3 bytes rgb palette
33 * optional background_frame
34 */
35
36#include "avformat.h"
37
38#define EXTRADATA1_SIZE (6 + 256 * 3) ///< video base, clr, palette
39
40#define FORM_TAG MKBETAG('F', 'O', 'R', 'M')
41#define RLV2_TAG MKBETAG('R', 'L', 'V', '2')
42#define RLV3_TAG MKBETAG('R', 'L', 'V', '3')
43
44typedef struct Rl2DemuxContext {
45 unsigned int index_pos[2]; ///< indexes in the sample tables
46} Rl2DemuxContext;
47
48
49/**
50 * check if the file is in rl2 format
51 * @param p probe buffer
52 * @return 0 when the probe buffer does not contain rl2 data, > 0 otherwise
53 */
54static int rl2_probe(AVProbeData *p)
55{
56
57 if(AV_RB32(&p->buf[0]) != FORM_TAG)
58 return 0;
59
60 if(AV_RB32(&p->buf[8]) != RLV2_TAG &&
61 AV_RB32(&p->buf[8]) != RLV3_TAG)
62 return 0;
63
64 return AVPROBE_SCORE_MAX;
65}
66
67/**
68 * read rl2 header data and setup the avstreams
69 * @param s demuxer context
70 * @param ap format parameters
71 * @return 0 on success, AVERROR otherwise
72 */
73static av_cold int rl2_read_header(AVFormatContext *s,
74 AVFormatParameters *ap)
75{
76 ByteIOContext *pb = s->pb;
77 AVStream *st;
78 unsigned int frame_count;
79 unsigned int audio_frame_counter = 0;
80 unsigned int video_frame_counter = 0;
81 unsigned int back_size;
82 int data_size;
83 unsigned short encoding_method;
84 unsigned short sound_rate;
85 unsigned short rate;
86 unsigned short channels;
87 unsigned short def_sound_size;
88 unsigned int signature;
89 unsigned int pts_den = 11025; /* video only case */
90 unsigned int pts_num = 1103;
91 unsigned int* chunk_offset = NULL;
92 int* chunk_size = NULL;
93 int* audio_size = NULL;
94 int i;
95 int ret = 0;
96
97 url_fskip(pb,4); /* skip FORM tag */
98 back_size = get_le32(pb); /** get size of the background frame */
99 signature = get_be32(pb);
100 data_size = get_be32(pb);
101 frame_count = get_le32(pb);
102
103 /* disallow back_sizes and frame_counts that may lead to overflows later */
104 if(back_size > INT_MAX/2 || frame_count > INT_MAX / sizeof(uint32_t))
105 return AVERROR_INVALIDDATA;
106
107 encoding_method = get_le16(pb);
108 sound_rate = get_le16(pb);
109 rate = get_le16(pb);
110 channels = get_le16(pb);
111 def_sound_size = get_le16(pb);
112
113 /** setup video stream */
114 st = av_new_stream(s, 0);
115 if(!st)
116 return AVERROR(ENOMEM);
117
118 st->codec->codec_type = CODEC_TYPE_VIDEO;
119 st->codec->codec_id = CODEC_ID_RL2;
120 st->codec->codec_tag = 0; /* no fourcc */
121 st->codec->width = 320;
122 st->codec->height = 200;
123
124 /** allocate and fill extradata */
125 st->codec->extradata_size = EXTRADATA1_SIZE;
126
127 if(signature == RLV3_TAG && back_size > 0)
128 st->codec->extradata_size += back_size;
129
130 st->codec->extradata = av_mallocz(st->codec->extradata_size +
131 FF_INPUT_BUFFER_PADDING_SIZE);
132 if(!st->codec->extradata)
133 return AVERROR(ENOMEM);
134
135 if(get_buffer(pb,st->codec->extradata,st->codec->extradata_size) !=
136 st->codec->extradata_size)
137 return AVERROR(EIO);
138
139 /** setup audio stream if present */
140 if(sound_rate){
141 pts_num = def_sound_size;
142 pts_den = rate;
143
144 st = av_new_stream(s, 0);
145 if (!st)
146 return AVERROR(ENOMEM);
147 st->codec->codec_type = CODEC_TYPE_AUDIO;
148 st->codec->codec_id = CODEC_ID_PCM_U8;
149 st->codec->codec_tag = 1;
150 st->codec->channels = channels;
151 st->codec->bits_per_sample = 8;
152 st->codec->sample_rate = rate;
153 st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *
154 st->codec->bits_per_sample;
155 st->codec->block_align = st->codec->channels *
156 st->codec->bits_per_sample / 8;
157 av_set_pts_info(st,32,1,rate);
158 }
159
160 av_set_pts_info(s->streams[0], 32, pts_num, pts_den);
161
162 chunk_size = av_malloc(frame_count * sizeof(uint32_t));
163 audio_size = av_malloc(frame_count * sizeof(uint32_t));
164 chunk_offset = av_malloc(frame_count * sizeof(uint32_t));
165
166 if(!chunk_size || !audio_size || !chunk_offset){
167 av_free(chunk_size);
168 av_free(audio_size);
169 av_free(chunk_offset);
170 return AVERROR(ENOMEM);
171 }
172
173 /** read offset and size tables */
174 for(i=0; i < frame_count;i++)
175 chunk_size[i] = get_le32(pb);
176 for(i=0; i < frame_count;i++)
177 chunk_offset[i] = get_le32(pb);
178 for(i=0; i < frame_count;i++)
179 audio_size[i] = get_le32(pb) & 0xFFFF;
180
181 /** build the sample index */
182 for(i=0;i<frame_count;i++){
183 if(chunk_size[i] < 0 || audio_size[i] > chunk_size[i]){
184 ret = AVERROR_INVALIDDATA;
185 break;
186 }
187
188 if(sound_rate && audio_size[i]){
189 av_add_index_entry(s->streams[1], chunk_offset[i],
190 audio_frame_counter,audio_size[i], 0, AVINDEX_KEYFRAME);
191 audio_frame_counter += audio_size[i] / channels;
192 }
193 av_add_index_entry(s->streams[0], chunk_offset[i] + audio_size[i],
194 video_frame_counter,chunk_size[i]-audio_size[i],0,AVINDEX_KEYFRAME);
195 ++video_frame_counter;
196 }
197
198
199 av_free(chunk_size);
200 av_free(audio_size);
201 av_free(chunk_offset);
202
203 return ret;
204}
205
206/**
207 * read a single audio or video packet
208 * @param s demuxer context
209 * @param pkt the packet to be filled
210 * @return 0 on success, AVERROR otherwise
211 */
212static int rl2_read_packet(AVFormatContext *s,
213 AVPacket *pkt)
214{
215 Rl2DemuxContext *rl2 = s->priv_data;
216 ByteIOContext *pb = s->pb;
217 AVIndexEntry *sample = NULL;
218 int i;
219 int ret = 0;
220 int stream_id = -1;
221 int64_t pos = INT64_MAX;
222
223 /** check if there is a valid video or audio entry that can be used */
224 for(i=0; i<s->nb_streams; i++){
225 if(rl2->index_pos[i] < s->streams[i]->nb_index_entries
226 && s->streams[i]->index_entries[ rl2->index_pos[i] ].pos < pos){
227 sample = &s->streams[i]->index_entries[ rl2->index_pos[i] ];
228 pos= sample->pos;
229 stream_id= i;
230 }
231 }
232
233 if(stream_id == -1)
234 return AVERROR(EIO);
235
236 ++rl2->index_pos[stream_id];
237
238 /** position the stream (will probably be there anyway) */
239 url_fseek(pb, sample->pos, SEEK_SET);
240
241 /** fill the packet */
242 ret = av_get_packet(pb, pkt, sample->size);
243 if(ret != sample->size){
244 av_free_packet(pkt);
245 return AVERROR(EIO);
246 }
247
248 pkt->stream_index = stream_id;
249 pkt->pts = sample->timestamp;
250
251 return ret;
252}
253
254/**
255 * seek to a new timestamp
256 * @param s demuxer context
257 * @param stream_index index of the stream that should be seeked
258 * @param timestamp wanted timestamp
259 * @param flags direction and seeking mode
260 * @return 0 on success, -1 otherwise
261 */
262static int rl2_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
263{
264 AVStream *st = s->streams[stream_index];
265 Rl2DemuxContext *rl2 = s->priv_data;
266 int i;
267 int index = av_index_search_timestamp(st, timestamp, flags);
268 if(index < 0)
269 return -1;
270
271 rl2->index_pos[stream_index] = index;
272 timestamp = st->index_entries[index].timestamp;
273
274 for(i=0; i < s->nb_streams; i++){
275 AVStream *st2 = s->streams[i];
276 index = av_index_search_timestamp(st2,
277 av_rescale_q(timestamp, st->time_base, st2->time_base),
278 flags | AVSEEK_FLAG_BACKWARD);
279
280 if(index < 0)
281 index = 0;
282
283 rl2->index_pos[i] = index;
284 }
285
286 return 0;
287}
288
289AVInputFormat rl2_demuxer = {
290 "rl2",
291 NULL_IF_CONFIG_SMALL("rl2 format"),
292 sizeof(Rl2DemuxContext),
293 rl2_probe,
294 rl2_read_header,
295 rl2_read_packet,
296 NULL,
297 rl2_read_seek,
298};
299
diff --git a/src/plugins/ffmpeg/libavformat/rm.h b/src/plugins/ffmpeg/libavformat/rm.h
deleted file mode 100644
index 2f7f8df..0000000
--- a/src/plugins/ffmpeg/libavformat/rm.h
+++ /dev/null
@@ -1,108 +0,0 @@
1/*
2 * "Real" compatible muxer and demuxer.
3 * Copyright (c) 2000, 2001 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#ifndef FFMPEG_RM_H
23#define FFMPEG_RM_H
24
25#include "avformat.h"
26
27
28typedef struct {
29 int nb_packets;
30 int packet_total_size;
31 int packet_max_size;
32 /* codec related output */
33 int bit_rate;
34 float frame_rate;
35 int nb_frames; /* current frame number */
36 int total_frames; /* total number of frames */
37 int num;
38 AVCodecContext *enc;
39} StreamInfo;
40
41typedef struct {
42 StreamInfo streams[2];
43 StreamInfo *audio_stream, *video_stream;
44 int data_pos; /* position of the data after the header */
45 int nb_packets;
46 int old_format;
47 int current_stream;
48 int remaining_len;
49 uint8_t *videobuf; ///< place to store merged video frame
50 int videobufsize; ///< current assembled frame size
51 int videobufpos; ///< position for the next slice in the video buffer
52 int curpic_num; ///< picture number of current frame
53 int cur_slice, slices;
54 int64_t pktpos; ///< first slice position in file
55 /// Audio descrambling matrix parameters
56 uint8_t *audiobuf; ///< place to store reordered audio data
57 int64_t audiotimestamp; ///< Audio packet timestamp
58 int sub_packet_cnt; // Subpacket counter, used while reading
59 int sub_packet_size, sub_packet_h, coded_framesize; ///< Descrambling parameters from container
60 int audio_stream_num; ///< Stream number for audio packets
61 int audio_pkt_cnt; ///< Output packet counter
62 int audio_framesize; /// Audio frame size from container
63 int sub_packet_lengths[16]; /// Length of each aac subpacket
64} RMContext;
65
66/**
67 * Read the MDPR chunk, which contains stream-specific codec initialization
68 * parameters.
69 *
70 * @param s context containing RMContext and ByteIOContext for stream reading
71 * @param st the stream that the MDPR chunk belongs to and where to store the
72 * parameters read from the chunk into
73 * @return 0 on success, errno codes on error
74 */
75int ff_rm_read_mdpr_codecdata (AVFormatContext *s, AVStream *st);
76
77/**
78 * Parse one rm-stream packet from the input bytestream.
79 *
80 * @param s context containing RMContext and ByteIOContext for stream reading
81 * @param st stream to which the packet to be read belongs
82 * @param len packet length to read from the input
83 * @param pkt packet location to store the parsed packet data
84 * @param seq pointer to an integer containing the sequence number, may be
85 * updated
86 * @param flags pointer to an integer containing the packet flags, may be
87 updated
88 * @param ts pointer to timestamp, may be updated
89 * @return 0 on success, errno codes on error
90 */
91int ff_rm_parse_packet (AVFormatContext *s, AVStream *st, int len,
92 AVPacket *pkt, int *seq, int *flags, int64_t *ts);
93
94/**
95 * Retrieve one cached packet from the rm-context. The real container can
96 * store several packets (as interpreted by the codec) in a single container
97 * packet, which means the demuxer holds some back when the first container
98 * packet is parsed and returned. The result is that rm->audio_pkt_cnt is
99 * a positive number, the amount of cached packets. Using this function, each
100 * of those packets can be retrieved sequentially.
101 *
102 * @param s context containing RMContext and ByteIOContext for stream reading
103 * @param st stream that this packet belongs to
104 * @param pkt location to store the packet data
105 */
106void ff_rm_retrieve_cache (AVFormatContext *s, AVStream *st, AVPacket *pkt);
107
108#endif /* FFMPEG_RM_H */
diff --git a/src/plugins/ffmpeg/libavformat/rmdec.c b/src/plugins/ffmpeg/libavformat/rmdec.c
deleted file mode 100644
index aa8bda7..0000000
--- a/src/plugins/ffmpeg/libavformat/rmdec.c
+++ /dev/null
@@ -1,798 +0,0 @@
1/*
2 * "Real" compatible demuxer.
3 * Copyright (c) 2000, 2001 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/avstring.h"
23#include "avformat.h"
24#include "rm.h"
25
26static inline void get_strl(ByteIOContext *pb, char *buf, int buf_size, int len)
27{
28 int i;
29 char *q, r;
30
31 q = buf;
32 for(i=0;i<len;i++) {
33 r = get_byte(pb);
34 if (i < buf_size - 1)
35 *q++ = r;
36 }
37 if (buf_size > 0) *q = '\0';
38}
39
40static void get_str16(ByteIOContext *pb, char *buf, int buf_size)
41{
42 get_strl(pb, buf, buf_size, get_be16(pb));
43}
44
45static void get_str8(ByteIOContext *pb, char *buf, int buf_size)
46{
47 get_strl(pb, buf, buf_size, get_byte(pb));
48}
49
50static int rm_read_audio_stream_info(AVFormatContext *s, AVStream *st,
51 int read_all)
52{
53 RMContext *rm = s->priv_data;
54 ByteIOContext *pb = s->pb;
55 char buf[256];
56 uint32_t version;
57 int i;
58
59 /* ra type header */
60 version = get_be32(pb); /* version */
61 if (((version >> 16) & 0xff) == 3) {
62 int64_t startpos = url_ftell(pb);
63 /* very old version */
64 for(i = 0; i < 14; i++)
65 get_byte(pb);
66 get_str8(pb, s->title, sizeof(s->title));
67 get_str8(pb, s->author, sizeof(s->author));
68 get_str8(pb, s->copyright, sizeof(s->copyright));
69 get_str8(pb, s->comment, sizeof(s->comment));
70 if ((startpos + (version & 0xffff)) >= url_ftell(pb) + 2) {
71 // fourcc (should always be "lpcJ")
72 get_byte(pb);
73 get_str8(pb, buf, sizeof(buf));
74 }
75 // Skip extra header crap (this should never happen)
76 if ((startpos + (version & 0xffff)) > url_ftell(pb))
77 url_fskip(pb, (version & 0xffff) + startpos - url_ftell(pb));
78 st->codec->sample_rate = 8000;
79 st->codec->channels = 1;
80 st->codec->codec_type = CODEC_TYPE_AUDIO;
81 st->codec->codec_id = CODEC_ID_RA_144;
82 } else {
83 int flavor, sub_packet_h, coded_framesize, sub_packet_size;
84 /* old version (4) */
85 get_be32(pb); /* .ra4 */
86 get_be32(pb); /* data size */
87 get_be16(pb); /* version2 */
88 get_be32(pb); /* header size */
89 flavor= get_be16(pb); /* add codec info / flavor */
90 rm->coded_framesize = coded_framesize = get_be32(pb); /* coded frame size */
91 get_be32(pb); /* ??? */
92 get_be32(pb); /* ??? */
93 get_be32(pb); /* ??? */
94 rm->sub_packet_h = sub_packet_h = get_be16(pb); /* 1 */
95 st->codec->block_align= get_be16(pb); /* frame size */
96 rm->sub_packet_size = sub_packet_size = get_be16(pb); /* sub packet size */
97 get_be16(pb); /* ??? */
98 if (((version >> 16) & 0xff) == 5) {
99 get_be16(pb); get_be16(pb); get_be16(pb); }
100 st->codec->sample_rate = get_be16(pb);
101 get_be32(pb);
102 st->codec->channels = get_be16(pb);
103 if (((version >> 16) & 0xff) == 5) {
104 get_be32(pb);
105 buf[0] = get_byte(pb);
106 buf[1] = get_byte(pb);
107 buf[2] = get_byte(pb);
108 buf[3] = get_byte(pb);
109 buf[4] = 0;
110 } else {
111 get_str8(pb, buf, sizeof(buf)); /* desc */
112 get_str8(pb, buf, sizeof(buf)); /* desc */
113 }
114 st->codec->codec_type = CODEC_TYPE_AUDIO;
115 if (!strcmp(buf, "dnet")) {
116 st->codec->codec_id = CODEC_ID_AC3;
117 st->need_parsing = AVSTREAM_PARSE_FULL;
118 } else if (!strcmp(buf, "28_8")) {
119 st->codec->codec_id = CODEC_ID_RA_288;
120 st->codec->extradata_size= 0;
121 rm->audio_framesize = st->codec->block_align;
122 st->codec->block_align = coded_framesize;
123
124 if(rm->audio_framesize >= UINT_MAX / sub_packet_h){
125 av_log(s, AV_LOG_ERROR, "rm->audio_framesize * sub_packet_h too large\n");
126 return -1;
127 }
128
129 rm->audiobuf = av_malloc(rm->audio_framesize * sub_packet_h);
130 } else if ((!strcmp(buf, "cook")) || (!strcmp(buf, "atrc"))) {
131 int codecdata_length, i;
132 get_be16(pb); get_byte(pb);
133 if (((version >> 16) & 0xff) == 5)
134 get_byte(pb);
135 codecdata_length = get_be32(pb);
136 if(codecdata_length + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){
137 av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");
138 return -1;
139 }
140
141 if (!strcmp(buf, "cook")) st->codec->codec_id = CODEC_ID_COOK;
142 else st->codec->codec_id = CODEC_ID_ATRAC3;
143 st->codec->extradata_size= codecdata_length;
144 st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
145 for(i = 0; i < codecdata_length; i++)
146 ((uint8_t*)st->codec->extradata)[i] = get_byte(pb);
147 rm->audio_framesize = st->codec->block_align;
148 st->codec->block_align = rm->sub_packet_size;
149
150 if(rm->audio_framesize >= UINT_MAX / sub_packet_h){
151 av_log(s, AV_LOG_ERROR, "rm->audio_framesize * sub_packet_h too large\n");
152 return -1;
153 }
154
155 rm->audiobuf = av_malloc(rm->audio_framesize * sub_packet_h);
156 } else if (!strcmp(buf, "raac") || !strcmp(buf, "racp")) {
157 int codecdata_length, i;
158 get_be16(pb); get_byte(pb);
159 if (((version >> 16) & 0xff) == 5)
160 get_byte(pb);
161 st->codec->codec_id = CODEC_ID_AAC;
162 codecdata_length = get_be32(pb);
163 if(codecdata_length + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){
164 av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");
165 return -1;
166 }
167 if (codecdata_length >= 1) {
168 st->codec->extradata_size = codecdata_length - 1;
169 st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
170 get_byte(pb);
171 for(i = 0; i < st->codec->extradata_size; i++)
172 ((uint8_t*)st->codec->extradata)[i] = get_byte(pb);
173 }
174 } else {
175 st->codec->codec_id = CODEC_ID_NONE;
176 av_strlcpy(st->codec->codec_name, buf, sizeof(st->codec->codec_name));
177 }
178 if (read_all) {
179 get_byte(pb);
180 get_byte(pb);
181 get_byte(pb);
182
183 get_str8(pb, s->title, sizeof(s->title));
184 get_str8(pb, s->author, sizeof(s->author));
185 get_str8(pb, s->copyright, sizeof(s->copyright));
186 get_str8(pb, s->comment, sizeof(s->comment));
187 }
188 }
189 return 0;
190}
191
192int
193ff_rm_read_mdpr_codecdata (AVFormatContext *s, AVStream *st)
194{
195 ByteIOContext *pb = s->pb;
196 unsigned int v;
197 int codec_data_size, size;
198 int64_t codec_pos;
199
200 codec_data_size = get_be32(pb);
201 codec_pos = url_ftell(pb);
202 v = get_be32(pb);
203 if (v == MKTAG(0xfd, 'a', 'r', '.')) {
204 /* ra type header */
205 if (rm_read_audio_stream_info(s, st, 0))
206 return -1;
207 } else {
208 int fps, fps2;
209 if (get_le32(pb) != MKTAG('V', 'I', 'D', 'O')) {
210 fail1:
211 av_log(st->codec, AV_LOG_ERROR, "Unsupported video codec\n");
212 goto skip;
213 }
214 st->codec->codec_tag = get_le32(pb);
215// av_log(NULL, AV_LOG_DEBUG, "%X %X\n", st->codec->codec_tag, MKTAG('R', 'V', '2', '0'));
216 if ( st->codec->codec_tag != MKTAG('R', 'V', '1', '0')
217 && st->codec->codec_tag != MKTAG('R', 'V', '2', '0')
218 && st->codec->codec_tag != MKTAG('R', 'V', '3', '0')
219 && st->codec->codec_tag != MKTAG('R', 'V', '4', '0'))
220 goto fail1;
221 st->codec->width = get_be16(pb);
222 st->codec->height = get_be16(pb);
223 st->codec->time_base.num= 1;
224 fps= get_be16(pb);
225 st->codec->codec_type = CODEC_TYPE_VIDEO;
226 get_be32(pb);
227 fps2= get_be16(pb);
228 get_be16(pb);
229
230 st->codec->extradata_size= codec_data_size - (url_ftell(pb) - codec_pos);
231
232 if(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)st->codec->extradata_size){
233 //check is redundant as get_buffer() will catch this
234 av_log(s, AV_LOG_ERROR, "st->codec->extradata_size too large\n");
235 return -1;
236 }
237 st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
238 if (!st->codec->extradata)
239 return AVERROR(ENOMEM);
240 get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
241
242// av_log(NULL, AV_LOG_DEBUG, "fps= %d fps2= %d\n", fps, fps2);
243 st->codec->time_base.den = fps * st->codec->time_base.num;
244 switch(((uint8_t*)st->codec->extradata)[4]>>4){
245 case 1: st->codec->codec_id = CODEC_ID_RV10; break;
246 case 2: st->codec->codec_id = CODEC_ID_RV20; break;
247 case 3: st->codec->codec_id = CODEC_ID_RV30; break;
248 case 4: st->codec->codec_id = CODEC_ID_RV40; break;
249 default: goto fail1;
250 }
251 }
252
253skip:
254 /* skip codec info */
255 size = url_ftell(pb) - codec_pos;
256 url_fskip(pb, codec_data_size - size);
257
258 return 0;
259}
260
261
262static int rm_read_header_old(AVFormatContext *s, AVFormatParameters *ap)
263{
264 RMContext *rm = s->priv_data;
265 AVStream *st;
266
267 rm->old_format = 1;
268 st = av_new_stream(s, 0);
269 if (!st)
270 return -1;
271 return rm_read_audio_stream_info(s, st, 1);
272}
273
274static int rm_read_header(AVFormatContext *s, AVFormatParameters *ap)
275{
276 RMContext *rm = s->priv_data;
277 AVStream *st;
278 ByteIOContext *pb = s->pb;
279 unsigned int tag;
280 int tag_size;
281 unsigned int start_time, duration;
282 char buf[128];
283 int flags = 0;
284
285 tag = get_le32(pb);
286 if (tag == MKTAG('.', 'r', 'a', 0xfd)) {
287 /* very old .ra format */
288 return rm_read_header_old(s, ap);
289 } else if (tag != MKTAG('.', 'R', 'M', 'F')) {
290 return AVERROR(EIO);
291 }
292
293 get_be32(pb); /* header size */
294 get_be16(pb);
295 get_be32(pb);
296 get_be32(pb); /* number of headers */
297
298 for(;;) {
299 if (url_feof(pb))
300 return -1;
301 tag = get_le32(pb);
302 tag_size = get_be32(pb);
303 get_be16(pb);
304#if 0
305 printf("tag=%c%c%c%c (%08x) size=%d\n",
306 (tag) & 0xff,
307 (tag >> 8) & 0xff,
308 (tag >> 16) & 0xff,
309 (tag >> 24) & 0xff,
310 tag,
311 tag_size);
312#endif
313 if (tag_size < 10 && tag != MKTAG('D', 'A', 'T', 'A'))
314 return -1;
315 switch(tag) {
316 case MKTAG('P', 'R', 'O', 'P'):
317 /* file header */
318 get_be32(pb); /* max bit rate */
319 get_be32(pb); /* avg bit rate */
320 get_be32(pb); /* max packet size */
321 get_be32(pb); /* avg packet size */
322 get_be32(pb); /* nb packets */
323 get_be32(pb); /* duration */
324 get_be32(pb); /* preroll */
325 get_be32(pb); /* index offset */
326 get_be32(pb); /* data offset */
327 get_be16(pb); /* nb streams */
328 flags = get_be16(pb); /* flags */
329 break;
330 case MKTAG('C', 'O', 'N', 'T'):
331 get_str16(pb, s->title, sizeof(s->title));
332 get_str16(pb, s->author, sizeof(s->author));
333 get_str16(pb, s->copyright, sizeof(s->copyright));
334 get_str16(pb, s->comment, sizeof(s->comment));
335 break;
336 case MKTAG('M', 'D', 'P', 'R'):
337 st = av_new_stream(s, 0);
338 if (!st)
339 return AVERROR(ENOMEM);
340 st->id = get_be16(pb);
341 get_be32(pb); /* max bit rate */
342 st->codec->bit_rate = get_be32(pb); /* bit rate */
343 get_be32(pb); /* max packet size */
344 get_be32(pb); /* avg packet size */
345 start_time = get_be32(pb); /* start time */
346 get_be32(pb); /* preroll */
347 duration = get_be32(pb); /* duration */
348 st->start_time = start_time;
349 st->duration = duration;
350 get_str8(pb, buf, sizeof(buf)); /* desc */
351 get_str8(pb, buf, sizeof(buf)); /* mimetype */
352 st->codec->codec_type = CODEC_TYPE_DATA;
353 av_set_pts_info(st, 64, 1, 1000);
354 if (ff_rm_read_mdpr_codecdata(s, st) < 0)
355 return -1;
356 break;
357 case MKTAG('D', 'A', 'T', 'A'):
358 goto header_end;
359 default:
360 /* unknown tag: skip it */
361 url_fskip(pb, tag_size - 10);
362 break;
363 }
364 }
365 header_end:
366 rm->nb_packets = get_be32(pb); /* number of packets */
367 if (!rm->nb_packets && (flags & 4))
368 rm->nb_packets = 3600 * 25;
369 get_be32(pb); /* next data header */
370 rm->curpic_num = -1;
371 return 0;
372}
373
374static int get_num(ByteIOContext *pb, int *len)
375{
376 int n, n1;
377
378 n = get_be16(pb);
379 (*len)-=2;
380 n &= 0x7FFF;
381 if (n >= 0x4000) {
382 return n - 0x4000;
383 } else {
384 n1 = get_be16(pb);
385 (*len)-=2;
386 return (n << 16) | n1;
387 }
388}
389
390/* multiple of 20 bytes for ra144 (ugly) */
391#define RAW_PACKET_SIZE 1000
392
393static int sync(AVFormatContext *s, int64_t *timestamp, int *flags, int *stream_index, int64_t *pos){
394 RMContext *rm = s->priv_data;
395 ByteIOContext *pb = s->pb;
396 int len, num, res, i;
397 AVStream *st;
398 uint32_t state=0xFFFFFFFF;
399
400 while(!url_feof(pb)){
401 *pos= url_ftell(pb) - 3;
402 if(rm->remaining_len > 0){
403 num= rm->current_stream;
404 len= rm->remaining_len;
405 *timestamp = AV_NOPTS_VALUE;
406 *flags= 0;
407 }else{
408 state= (state<<8) + get_byte(pb);
409
410 if(state == MKBETAG('I', 'N', 'D', 'X')){
411 len = get_be16(pb) - 6;
412 if(len<0)
413 continue;
414 goto skip;
415 }
416
417 if(state > (unsigned)0xFFFF || state < 12)
418 continue;
419 len=state;
420 state= 0xFFFFFFFF;
421
422 num = get_be16(pb);
423 *timestamp = get_be32(pb);
424 res= get_byte(pb); /* reserved */
425 *flags = get_byte(pb); /* flags */
426
427
428 len -= 12;
429 }
430 for(i=0;i<s->nb_streams;i++) {
431 st = s->streams[i];
432 if (num == st->id)
433 break;
434 }
435 if (i == s->nb_streams) {
436skip:
437 /* skip packet if unknown number */
438 url_fskip(pb, len);
439 rm->remaining_len -= len;
440 continue;
441 }
442 *stream_index= i;
443
444 return len;
445 }
446 return -1;
447}
448
449static int rm_assemble_video_frame(AVFormatContext *s, RMContext *rm, AVPacket *pkt, int len)
450{
451 ByteIOContext *pb = s->pb;
452 int hdr, seq, pic_num, len2, pos;
453 int type;
454
455 hdr = get_byte(pb); len--;
456 type = hdr >> 6;
457 switch(type){
458 case 0: // slice
459 case 2: // last slice
460 seq = get_byte(pb); len--;
461 len2 = get_num(pb, &len);
462 pos = get_num(pb, &len);
463 pic_num = get_byte(pb); len--;
464 rm->remaining_len = len;
465 break;
466 case 1: //whole frame
467 seq = get_byte(pb); len--;
468 if(av_new_packet(pkt, len + 9) < 0)
469 return AVERROR(EIO);
470 pkt->data[0] = 0;
471 AV_WL32(pkt->data + 1, 1);
472 AV_WL32(pkt->data + 5, 0);
473 get_buffer(pb, pkt->data + 9, len);
474 rm->remaining_len = 0;
475 return 0;
476 case 3: //frame as a part of packet
477 len2 = get_num(pb, &len);
478 pos = get_num(pb, &len);
479 pic_num = get_byte(pb); len--;
480 rm->remaining_len = len - len2;
481 if(av_new_packet(pkt, len2 + 9) < 0)
482 return AVERROR(EIO);
483 pkt->data[0] = 0;
484 AV_WL32(pkt->data + 1, 1);
485 AV_WL32(pkt->data + 5, 0);
486 get_buffer(pb, pkt->data + 9, len2);
487 return 0;
488 }
489 //now we have to deal with single slice
490
491 if((seq & 0x7F) == 1 || rm->curpic_num != pic_num){
492 rm->slices = ((hdr & 0x3F) << 1) + 1;
493 rm->videobufsize = len2 + 8*rm->slices + 1;
494 av_free(rm->videobuf);
495 if(!(rm->videobuf = av_malloc(rm->videobufsize)))
496 return AVERROR(ENOMEM);
497 rm->videobufpos = 8*rm->slices + 1;
498 rm->cur_slice = 0;
499 rm->curpic_num = pic_num;
500 rm->pktpos = url_ftell(pb);
501 }
502 if(type == 2)
503 len = FFMIN(len, pos);
504
505 if(++rm->cur_slice > rm->slices)
506 return 1;
507 AV_WL32(rm->videobuf - 7 + 8*rm->cur_slice, 1);
508 AV_WL32(rm->videobuf - 3 + 8*rm->cur_slice, rm->videobufpos - 8*rm->slices - 1);
509 if(rm->videobufpos + len > rm->videobufsize)
510 return 1;
511 if (get_buffer(pb, rm->videobuf + rm->videobufpos, len) != len)
512 return AVERROR(EIO);
513 rm->videobufpos += len;
514 rm->remaining_len-= len;
515
516 if(type == 2 || (rm->videobufpos) == rm->videobufsize){
517 rm->videobuf[0] = rm->cur_slice-1;
518 if(av_new_packet(pkt, rm->videobufpos - 8*(rm->slices - rm->cur_slice)) < 0)
519 return AVERROR(ENOMEM);
520 memcpy(pkt->data, rm->videobuf, 1 + 8*rm->cur_slice);
521 memcpy(pkt->data + 1 + 8*rm->cur_slice, rm->videobuf + 1 + 8*rm->slices,
522 rm->videobufpos - 1 - 8*rm->slices);
523 pkt->pts = AV_NOPTS_VALUE;
524 pkt->pos = rm->pktpos;
525 return 0;
526 }
527
528 return 1;
529}
530
531static inline void
532rm_ac3_swap_bytes (AVStream *st, AVPacket *pkt)
533{
534 uint8_t *ptr;
535 int j;
536
537 if (st->codec->codec_id == CODEC_ID_AC3) {
538 ptr = pkt->data;
539 for (j=0;j<pkt->size;j+=2) {
540 FFSWAP(int, ptr[0], ptr[1]);
541 ptr += 2;
542 }
543 }
544}
545
546int
547ff_rm_parse_packet (AVFormatContext *s, AVStream *st, int len, AVPacket *pkt,
548 int *seq, int *flags, int64_t *timestamp)
549{
550 ByteIOContext *pb = s->pb;
551 RMContext *rm = s->priv_data;
552
553 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
554 rm->current_stream= st->id;
555 if(rm_assemble_video_frame(s, rm, pkt, len) == 1)
556 return -1; //got partial frame
557 } else if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
558 if ((st->codec->codec_id == CODEC_ID_RA_288) ||
559 (st->codec->codec_id == CODEC_ID_COOK) ||
560 (st->codec->codec_id == CODEC_ID_ATRAC3)) {
561 int x;
562 int sps = rm->sub_packet_size;
563 int cfs = rm->coded_framesize;
564 int h = rm->sub_packet_h;
565 int y = rm->sub_packet_cnt;
566 int w = rm->audio_framesize;
567
568 if (*flags & 2)
569 y = rm->sub_packet_cnt = 0;
570 if (!y)
571 rm->audiotimestamp = *timestamp;
572
573 switch(st->codec->codec_id) {
574 case CODEC_ID_RA_288:
575 for (x = 0; x < h/2; x++)
576 get_buffer(pb, rm->audiobuf+x*2*w+y*cfs, cfs);
577 break;
578 case CODEC_ID_ATRAC3:
579 case CODEC_ID_COOK:
580 for (x = 0; x < w/sps; x++)
581 get_buffer(pb, rm->audiobuf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), sps);
582 break;
583 }
584
585 if (++(rm->sub_packet_cnt) < h)
586 return -1;
587 else {
588 rm->sub_packet_cnt = 0;
589 rm->audio_stream_num = st->index;
590 rm->audio_pkt_cnt = h * w / st->codec->block_align - 1;
591 // Release first audio packet
592 av_new_packet(pkt, st->codec->block_align);
593 memcpy(pkt->data, rm->audiobuf, st->codec->block_align);
594 *timestamp = rm->audiotimestamp;
595 *flags = 2; // Mark first packet as keyframe
596 }
597 } else if (st->codec->codec_id == CODEC_ID_AAC) {
598 int x;
599 rm->audio_stream_num = st->index;
600 rm->sub_packet_cnt = (get_be16(pb) & 0xf0) >> 4;
601 if (rm->sub_packet_cnt) {
602 for (x = 0; x < rm->sub_packet_cnt; x++)
603 rm->sub_packet_lengths[x] = get_be16(pb);
604 // Release first audio packet
605 rm->audio_pkt_cnt = rm->sub_packet_cnt - 1;
606 av_get_packet(pb, pkt, rm->sub_packet_lengths[0]);
607 *flags = 2; // Mark first packet as keyframe
608 }
609 } else {
610 av_get_packet(pb, pkt, len);
611 rm_ac3_swap_bytes(st, pkt);
612 }
613 } else
614 av_get_packet(pb, pkt, len);
615
616 if( (st->discard >= AVDISCARD_NONKEY && !(*flags&2))
617 || st->discard >= AVDISCARD_ALL){
618 av_free_packet(pkt);
619 return -1;
620 }
621
622 pkt->stream_index = st->index;
623
624#if 0
625 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
626 if(st->codec->codec_id == CODEC_ID_RV20){
627 int seq= 128*(pkt->data[2]&0x7F) + (pkt->data[3]>>1);
628 av_log(NULL, AV_LOG_DEBUG, "%d %"PRId64" %d\n", *timestamp, *timestamp*512LL/25, seq);
629
630 seq |= (*timestamp&~0x3FFF);
631 if(seq - *timestamp > 0x2000) seq -= 0x4000;
632 if(seq - *timestamp < -0x2000) seq += 0x4000;
633 }
634 }
635#endif
636
637 pkt->pts= *timestamp;
638 if (*flags & 2)
639 pkt->flags |= PKT_FLAG_KEY;
640
641 return 0;
642}
643
644void
645ff_rm_retrieve_cache (AVFormatContext *s, AVStream *st, AVPacket *pkt)
646{
647 ByteIOContext *pb = s->pb;
648 RMContext *rm = s->priv_data;
649
650 assert (rm->audio_pkt_cnt > 0);
651
652 if (st->codec->codec_id == CODEC_ID_AAC)
653 av_get_packet(pb, pkt, rm->sub_packet_lengths[rm->sub_packet_cnt - rm->audio_pkt_cnt]);
654 else {
655 av_new_packet(pkt, st->codec->block_align);
656 memcpy(pkt->data, rm->audiobuf + st->codec->block_align *
657 (rm->sub_packet_h * rm->audio_framesize / st->codec->block_align - rm->audio_pkt_cnt),
658 st->codec->block_align);
659 }
660 rm->audio_pkt_cnt--;
661 pkt->flags = 0;
662 pkt->stream_index = st->index;
663}
664
665static int rm_read_packet(AVFormatContext *s, AVPacket *pkt)
666{
667 RMContext *rm = s->priv_data;
668 ByteIOContext *pb = s->pb;
669 AVStream *st;
670 int i, len;
671 int64_t timestamp, pos;
672 int flags;
673
674 if (rm->audio_pkt_cnt) {
675 // If there are queued audio packet return them first
676 st = s->streams[rm->audio_stream_num];
677 ff_rm_retrieve_cache(s, st, pkt);
678 } else if (rm->old_format) {
679 st = s->streams[0];
680 if (st->codec->codec_id == CODEC_ID_RA_288) {
681 int x, y;
682
683 for (y = 0; y < rm->sub_packet_h; y++)
684 for (x = 0; x < rm->sub_packet_h/2; x++)
685 if (get_buffer(pb, rm->audiobuf+x*2*rm->audio_framesize+y*rm->coded_framesize, rm->coded_framesize) <= 0)
686 return AVERROR(EIO);
687 rm->audio_stream_num = 0;
688 rm->audio_pkt_cnt = rm->sub_packet_h * rm->audio_framesize / st->codec->block_align - 1;
689 // Release first audio packet
690 av_new_packet(pkt, st->codec->block_align);
691 memcpy(pkt->data, rm->audiobuf, st->codec->block_align);
692 pkt->flags |= PKT_FLAG_KEY; // Mark first packet as keyframe
693 pkt->stream_index = 0;
694 } else {
695 /* just read raw bytes */
696 len = RAW_PACKET_SIZE;
697 len= av_get_packet(pb, pkt, len);
698 pkt->stream_index = 0;
699 if (len <= 0) {
700 return AVERROR(EIO);
701 }
702 pkt->size = len;
703 }
704 rm_ac3_swap_bytes(st, pkt);
705 } else {
706 int seq=1;
707resync:
708 len=sync(s, &timestamp, &flags, &i, &pos);
709 if(len<0)
710 return AVERROR(EIO);
711 st = s->streams[i];
712
713 if (ff_rm_parse_packet (s, st, len, pkt, &seq, &flags, &timestamp) < 0)
714 goto resync;
715
716 if((flags&2) && (seq&0x7F) == 1)
717 av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME);
718 }
719
720 return 0;
721}
722
723static int rm_read_close(AVFormatContext *s)
724{
725 RMContext *rm = s->priv_data;
726
727 av_free(rm->audiobuf);
728 av_free(rm->videobuf);
729 return 0;
730}
731
732static int rm_probe(AVProbeData *p)
733{
734 /* check file header */
735 if ((p->buf[0] == '.' && p->buf[1] == 'R' &&
736 p->buf[2] == 'M' && p->buf[3] == 'F' &&
737 p->buf[4] == 0 && p->buf[5] == 0) ||
738 (p->buf[0] == '.' && p->buf[1] == 'r' &&
739 p->buf[2] == 'a' && p->buf[3] == 0xfd))
740 return AVPROBE_SCORE_MAX;
741 else
742 return 0;
743}
744
745static int64_t rm_read_dts(AVFormatContext *s, int stream_index,
746 int64_t *ppos, int64_t pos_limit)
747{
748 RMContext *rm = s->priv_data;
749 int64_t pos, dts;
750 int stream_index2, flags, len, h;
751
752 pos = *ppos;
753
754 if(rm->old_format)
755 return AV_NOPTS_VALUE;
756
757 url_fseek(s->pb, pos, SEEK_SET);
758 rm->remaining_len=0;
759 for(;;){
760 int seq=1;
761 AVStream *st;
762
763 len=sync(s, &dts, &flags, &stream_index2, &pos);
764 if(len<0)
765 return AV_NOPTS_VALUE;
766
767 st = s->streams[stream_index2];
768 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
769 h= get_byte(s->pb); len--;
770 if(!(h & 0x40)){
771 seq = get_byte(s->pb); len--;
772 }
773 }
774
775 if((flags&2) && (seq&0x7F) == 1){
776// av_log(s, AV_LOG_DEBUG, "%d %d-%d %"PRId64" %d\n", flags, stream_index2, stream_index, dts, seq);
777 av_add_index_entry(st, pos, dts, 0, 0, AVINDEX_KEYFRAME);
778 if(stream_index2 == stream_index)
779 break;
780 }
781
782 url_fskip(s->pb, len);
783 }
784 *ppos = pos;
785 return dts;
786}
787
788AVInputFormat rm_demuxer = {
789 "rm",
790 NULL_IF_CONFIG_SMALL("RM format"),
791 sizeof(RMContext),
792 rm_probe,
793 rm_read_header,
794 rm_read_packet,
795 rm_read_close,
796 NULL,
797 rm_read_dts,
798};
diff --git a/src/plugins/ffmpeg/libavformat/rmenc.c b/src/plugins/ffmpeg/libavformat/rmenc.c
deleted file mode 100644
index 03f629e..0000000
--- a/src/plugins/ffmpeg/libavformat/rmenc.c
+++ /dev/null
@@ -1,444 +0,0 @@
1/*
2 * "Real" compatible muxer.
3 * Copyright (c) 2000, 2001 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#include "avformat.h"
22#include "rm.h"
23
24/* in ms */
25#define BUFFER_DURATION 0
26
27
28static void put_str(ByteIOContext *s, const char *tag)
29{
30 put_be16(s,strlen(tag));
31 while (*tag) {
32 put_byte(s, *tag++);
33 }
34}
35
36static void put_str8(ByteIOContext *s, const char *tag)
37{
38 put_byte(s, strlen(tag));
39 while (*tag) {
40 put_byte(s, *tag++);
41 }
42}
43
44static void rv10_write_header(AVFormatContext *ctx,
45 int data_size, int index_pos)
46{
47 RMContext *rm = ctx->priv_data;
48 ByteIOContext *s = ctx->pb;
49 StreamInfo *stream;
50 unsigned char *data_offset_ptr, *start_ptr;
51 const char *desc, *mimetype;
52 int nb_packets, packet_total_size, packet_max_size, size, packet_avg_size, i;
53 int bit_rate, v, duration, flags, data_pos;
54
55 start_ptr = s->buf_ptr;
56
57 put_tag(s, ".RMF");
58 put_be32(s,18); /* header size */
59 put_be16(s,0);
60 put_be32(s,0);
61 put_be32(s,4 + ctx->nb_streams); /* num headers */
62
63 put_tag(s,"PROP");
64 put_be32(s, 50);
65 put_be16(s, 0);
66 packet_max_size = 0;
67 packet_total_size = 0;
68 nb_packets = 0;
69 bit_rate = 0;
70 duration = 0;
71 for(i=0;i<ctx->nb_streams;i++) {
72 StreamInfo *stream = &rm->streams[i];
73 bit_rate += stream->bit_rate;
74 if (stream->packet_max_size > packet_max_size)
75 packet_max_size = stream->packet_max_size;
76 nb_packets += stream->nb_packets;
77 packet_total_size += stream->packet_total_size;
78 /* select maximum duration */
79 v = (int) (1000.0 * (float)stream->total_frames / stream->frame_rate);
80 if (v > duration)
81 duration = v;
82 }
83 put_be32(s, bit_rate); /* max bit rate */
84 put_be32(s, bit_rate); /* avg bit rate */
85 put_be32(s, packet_max_size); /* max packet size */
86 if (nb_packets > 0)
87 packet_avg_size = packet_total_size / nb_packets;
88 else
89 packet_avg_size = 0;
90 put_be32(s, packet_avg_size); /* avg packet size */
91 put_be32(s, nb_packets); /* num packets */
92 put_be32(s, duration); /* duration */
93 put_be32(s, BUFFER_DURATION); /* preroll */
94 put_be32(s, index_pos); /* index offset */
95 /* computation of data the data offset */
96 data_offset_ptr = s->buf_ptr;
97 put_be32(s, 0); /* data offset : will be patched after */
98 put_be16(s, ctx->nb_streams); /* num streams */
99 flags = 1 | 2; /* save allowed & perfect play */
100 if (url_is_streamed(s))
101 flags |= 4; /* live broadcast */
102 put_be16(s, flags);
103
104 /* comments */
105
106 put_tag(s,"CONT");
107 size = strlen(ctx->title) + strlen(ctx->author) + strlen(ctx->copyright) +
108 strlen(ctx->comment) + 4 * 2 + 10;
109 put_be32(s,size);
110 put_be16(s,0);
111 put_str(s, ctx->title);
112 put_str(s, ctx->author);
113 put_str(s, ctx->copyright);
114 put_str(s, ctx->comment);
115
116 for(i=0;i<ctx->nb_streams;i++) {
117 int codec_data_size;
118
119 stream = &rm->streams[i];
120
121 if (stream->enc->codec_type == CODEC_TYPE_AUDIO) {
122 desc = "The Audio Stream";
123 mimetype = "audio/x-pn-realaudio";
124 codec_data_size = 73;
125 } else {
126 desc = "The Video Stream";
127 mimetype = "video/x-pn-realvideo";
128 codec_data_size = 34;
129 }
130
131 put_tag(s,"MDPR");
132 size = 10 + 9 * 4 + strlen(desc) + strlen(mimetype) + codec_data_size;
133 put_be32(s, size);
134 put_be16(s, 0);
135
136 put_be16(s, i); /* stream number */
137 put_be32(s, stream->bit_rate); /* max bit rate */
138 put_be32(s, stream->bit_rate); /* avg bit rate */
139 put_be32(s, stream->packet_max_size); /* max packet size */
140 if (stream->nb_packets > 0)
141 packet_avg_size = stream->packet_total_size /
142 stream->nb_packets;
143 else
144 packet_avg_size = 0;
145 put_be32(s, packet_avg_size); /* avg packet size */
146 put_be32(s, 0); /* start time */
147 put_be32(s, BUFFER_DURATION); /* preroll */
148 /* duration */
149 if (url_is_streamed(s) || !stream->total_frames)
150 put_be32(s, (int)(3600 * 1000));
151 else
152 put_be32(s, (int)(stream->total_frames * 1000 / stream->frame_rate));
153 put_str8(s, desc);
154 put_str8(s, mimetype);
155 put_be32(s, codec_data_size);
156
157 if (stream->enc->codec_type == CODEC_TYPE_AUDIO) {
158 int coded_frame_size, fscode, sample_rate;
159 sample_rate = stream->enc->sample_rate;
160 coded_frame_size = (stream->enc->bit_rate *
161 stream->enc->frame_size) / (8 * sample_rate);
162 /* audio codec info */
163 put_tag(s, ".ra");
164 put_byte(s, 0xfd);
165 put_be32(s, 0x00040000); /* version */
166 put_tag(s, ".ra4");
167 put_be32(s, 0x01b53530); /* stream length */
168 put_be16(s, 4); /* unknown */
169 put_be32(s, 0x39); /* header size */
170
171 switch(sample_rate) {
172 case 48000:
173 case 24000:
174 case 12000:
175 fscode = 1;
176 break;
177 default:
178 case 44100:
179 case 22050:
180 case 11025:
181 fscode = 2;
182 break;
183 case 32000:
184 case 16000:
185 case 8000:
186 fscode = 3;
187 }
188 put_be16(s, fscode); /* codec additional info, for AC3, seems
189 to be a frequency code */
190 /* special hack to compensate rounding errors... */
191 if (coded_frame_size == 557)
192 coded_frame_size--;
193 put_be32(s, coded_frame_size); /* frame length */
194 put_be32(s, 0x51540); /* unknown */
195 put_be32(s, 0x249f0); /* unknown */
196 put_be32(s, 0x249f0); /* unknown */
197 put_be16(s, 0x01);
198 /* frame length : seems to be very important */
199 put_be16(s, coded_frame_size);
200 put_be32(s, 0); /* unknown */
201 put_be16(s, stream->enc->sample_rate); /* sample rate */
202 put_be32(s, 0x10); /* unknown */
203 put_be16(s, stream->enc->channels);
204 put_str8(s, "Int0"); /* codec name */
205 put_str8(s, "dnet"); /* codec name */
206 put_be16(s, 0); /* title length */
207 put_be16(s, 0); /* author length */
208 put_be16(s, 0); /* copyright length */
209 put_byte(s, 0); /* end of header */
210 } else {
211 /* video codec info */
212 put_be32(s,34); /* size */
213 if(stream->enc->codec_id == CODEC_ID_RV10)
214 put_tag(s,"VIDORV10");
215 else
216 put_tag(s,"VIDORV20");
217 put_be16(s, stream->enc->width);
218 put_be16(s, stream->enc->height);
219 put_be16(s, (int) stream->frame_rate); /* frames per seconds ? */
220 put_be32(s,0); /* unknown meaning */
221 put_be16(s, (int) stream->frame_rate); /* unknown meaning */
222 put_be32(s,0); /* unknown meaning */
223 put_be16(s, 8); /* unknown meaning */
224 /* Seems to be the codec version: only use basic H263. The next
225 versions seems to add a diffential DC coding as in
226 MPEG... nothing new under the sun */
227 if(stream->enc->codec_id == CODEC_ID_RV10)
228 put_be32(s,0x10000000);
229 else
230 put_be32(s,0x20103001);
231 //put_be32(s,0x10003000);
232 }
233 }
234
235 /* patch data offset field */
236 data_pos = s->buf_ptr - start_ptr;
237 rm->data_pos = data_pos;
238 data_offset_ptr[0] = data_pos >> 24;
239 data_offset_ptr[1] = data_pos >> 16;
240 data_offset_ptr[2] = data_pos >> 8;
241 data_offset_ptr[3] = data_pos;
242
243 /* data stream */
244 put_tag(s,"DATA");
245 put_be32(s,data_size + 10 + 8);
246 put_be16(s,0);
247
248 put_be32(s, nb_packets); /* number of packets */
249 put_be32(s,0); /* next data header */
250}
251
252static void write_packet_header(AVFormatContext *ctx, StreamInfo *stream,
253 int length, int key_frame)
254{
255 int timestamp;
256 ByteIOContext *s = ctx->pb;
257
258 stream->nb_packets++;
259 stream->packet_total_size += length;
260 if (length > stream->packet_max_size)
261 stream->packet_max_size = length;
262
263 put_be16(s,0); /* version */
264 put_be16(s,length + 12);
265 put_be16(s, stream->num); /* stream number */
266 timestamp = (1000 * (float)stream->nb_frames) / stream->frame_rate;
267 put_be32(s, timestamp); /* timestamp */
268 put_byte(s, 0); /* reserved */
269 put_byte(s, key_frame ? 2 : 0); /* flags */
270}
271
272static int rm_write_header(AVFormatContext *s)
273{
274 RMContext *rm = s->priv_data;
275 StreamInfo *stream;
276 int n;
277 AVCodecContext *codec;
278
279 for(n=0;n<s->nb_streams;n++) {
280 s->streams[n]->id = n;
281 codec = s->streams[n]->codec;
282 stream = &rm->streams[n];
283 memset(stream, 0, sizeof(StreamInfo));
284 stream->num = n;
285 stream->bit_rate = codec->bit_rate;
286 stream->enc = codec;
287
288 switch(codec->codec_type) {
289 case CODEC_TYPE_AUDIO:
290 rm->audio_stream = stream;
291 stream->frame_rate = (float)codec->sample_rate / (float)codec->frame_size;
292 /* XXX: dummy values */
293 stream->packet_max_size = 1024;
294 stream->nb_packets = 0;
295 stream->total_frames = stream->nb_packets;
296 break;
297 case CODEC_TYPE_VIDEO:
298 rm->video_stream = stream;
299 stream->frame_rate = (float)codec->time_base.den / (float)codec->time_base.num;
300 /* XXX: dummy values */
301 stream->packet_max_size = 4096;
302 stream->nb_packets = 0;
303 stream->total_frames = stream->nb_packets;
304 break;
305 default:
306 return -1;
307 }
308 }
309
310 rv10_write_header(s, 0, 0);
311 put_flush_packet(s->pb);
312 return 0;
313}
314
315static int rm_write_audio(AVFormatContext *s, const uint8_t *buf, int size, int flags)
316{
317 uint8_t *buf1;
318 RMContext *rm = s->priv_data;
319 ByteIOContext *pb = s->pb;
320 StreamInfo *stream = rm->audio_stream;
321 int i;
322
323 /* XXX: suppress this malloc */
324 buf1= (uint8_t*) av_malloc( size * sizeof(uint8_t) );
325
326 write_packet_header(s, stream, size, !!(flags & PKT_FLAG_KEY));
327
328 /* for AC3, the words seems to be reversed */
329 for(i=0;i<size;i+=2) {
330 buf1[i] = buf[i+1];
331 buf1[i+1] = buf[i];
332 }
333 put_buffer(pb, buf1, size);
334 put_flush_packet(pb);
335 stream->nb_frames++;
336 av_free(buf1);
337 return 0;
338}
339
340static int rm_write_video(AVFormatContext *s, const uint8_t *buf, int size, int flags)
341{
342 RMContext *rm = s->priv_data;
343 ByteIOContext *pb = s->pb;
344 StreamInfo *stream = rm->video_stream;
345 int key_frame = !!(flags & PKT_FLAG_KEY);
346
347 /* XXX: this is incorrect: should be a parameter */
348
349 /* Well, I spent some time finding the meaning of these bits. I am
350 not sure I understood everything, but it works !! */
351#if 1
352 write_packet_header(s, stream, size + 7 + (size >= 0x4000)*4, key_frame);
353 /* bit 7: '1' if final packet of a frame converted in several packets */
354 put_byte(pb, 0x81);
355 /* bit 7: '1' if I frame. bits 6..0 : sequence number in current
356 frame starting from 1 */
357 if (key_frame) {
358 put_byte(pb, 0x81);
359 } else {
360 put_byte(pb, 0x01);
361 }
362 if(size >= 0x4000){
363 put_be32(pb, size); /* total frame size */
364 put_be32(pb, size); /* offset from the start or the end */
365 }else{
366 put_be16(pb, 0x4000 | size); /* total frame size */
367 put_be16(pb, 0x4000 | size); /* offset from the start or the end */
368 }
369#else
370 /* full frame */
371 write_packet_header(s, size + 6);
372 put_byte(pb, 0xc0);
373 put_be16(pb, 0x4000 + size); /* total frame size */
374 put_be16(pb, 0x4000 + packet_number * 126); /* position in stream */
375#endif
376 put_byte(pb, stream->nb_frames & 0xff);
377
378 put_buffer(pb, buf, size);
379 put_flush_packet(pb);
380
381 stream->nb_frames++;
382 return 0;
383}
384
385static int rm_write_packet(AVFormatContext *s, AVPacket *pkt)
386{
387 if (s->streams[pkt->stream_index]->codec->codec_type ==
388 CODEC_TYPE_AUDIO)
389 return rm_write_audio(s, pkt->data, pkt->size, pkt->flags);
390 else
391 return rm_write_video(s, pkt->data, pkt->size, pkt->flags);
392}
393
394static int rm_write_trailer(AVFormatContext *s)
395{
396 RMContext *rm = s->priv_data;
397 int data_size, index_pos, i;
398 ByteIOContext *pb = s->pb;
399
400 if (!url_is_streamed(s->pb)) {
401 /* end of file: finish to write header */
402 index_pos = url_fseek(pb, 0, SEEK_CUR);
403 data_size = index_pos - rm->data_pos;
404
405 /* index */
406 put_tag(pb, "INDX");
407 put_be32(pb, 10 + 10 * s->nb_streams);
408 put_be16(pb, 0);
409
410 for(i=0;i<s->nb_streams;i++) {
411 put_be32(pb, 0); /* zero indexes */
412 put_be16(pb, i); /* stream number */
413 put_be32(pb, 0); /* next index */
414 }
415 /* undocumented end header */
416 put_be32(pb, 0);
417 put_be32(pb, 0);
418
419 url_fseek(pb, 0, SEEK_SET);
420 for(i=0;i<s->nb_streams;i++)
421 rm->streams[i].total_frames = rm->streams[i].nb_frames;
422 rv10_write_header(s, data_size, index_pos);
423 } else {
424 /* undocumented end header */
425 put_be32(pb, 0);
426 put_be32(pb, 0);
427 }
428 put_flush_packet(pb);
429 return 0;
430}
431
432
433AVOutputFormat rm_muxer = {
434 "rm",
435 NULL_IF_CONFIG_SMALL("RM format"),
436 "application/vnd.rn-realmedia",
437 "rm,ra",
438 sizeof(RMContext),
439 CODEC_ID_AC3,
440 CODEC_ID_RV10,
441 rm_write_header,
442 rm_write_packet,
443 rm_write_trailer,
444};
diff --git a/src/plugins/ffmpeg/libavformat/rpl.c b/src/plugins/ffmpeg/libavformat/rpl.c
deleted file mode 100644
index 7340e18..0000000
--- a/src/plugins/ffmpeg/libavformat/rpl.c
+++ /dev/null
@@ -1,356 +0,0 @@
1/*
2 * ARMovie/RPL demuxer
3 * Copyright (c) 2007 Christian Ohm, 2008 Eli Friedman
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/avstring.h"
23#include "avformat.h"
24#include <stdlib.h>
25
26#define RPL_SIGNATURE "ARMovie\x0A"
27#define RPL_SIGNATURE_SIZE 8
28
29/** 256 is arbitrary, but should be big enough for any reasonable file. */
30#define RPL_LINE_LENGTH 256
31
32static int rpl_probe(AVProbeData *p)
33{
34 if (memcmp(p->buf, RPL_SIGNATURE, RPL_SIGNATURE_SIZE))
35 return 0;
36
37 return AVPROBE_SCORE_MAX;
38}
39
40typedef struct RPLContext {
41 // RPL header data
42 int32_t frames_per_chunk;
43
44 // Stream position data
45 uint32_t chunk_number;
46 uint32_t chunk_part;
47 uint32_t frame_in_part;
48} RPLContext;
49
50static int read_line(ByteIOContext * pb, char* line, int bufsize)
51{
52 int i;
53 for (i = 0; i < bufsize - 1; i++) {
54 int b = get_byte(pb);
55 if (b == 0)
56 break;
57 if (b == '\n') {
58 line[i] = '\0';
59 return 0;
60 }
61 line[i] = b;
62 }
63 line[i] = '\0';
64 return -1;
65}
66
67static int32_t read_int(const char* line, const char** endptr, int* error)
68{
69 unsigned long result = 0;
70 for (; *line>='0' && *line<='9'; line++) {
71 if (result > (0x7FFFFFFF - 9) / 10)
72 *error = -1;
73 result = 10 * result + *line - '0';
74 }
75 *endptr = line;
76 return result;
77}
78
79static int32_t read_line_and_int(ByteIOContext * pb, int* error)
80{
81 char line[RPL_LINE_LENGTH];
82 const char *endptr;
83 *error |= read_line(pb, line, sizeof(line));
84 return read_int(line, &endptr, error);
85}
86
87/** Parsing for fps, which can be a fraction. Unfortunately,
88 * the spec for the header leaves out a lot of details,
89 * so this is mostly guessing.
90 */
91static AVRational read_fps(const char* line, int* error)
92{
93 int64_t num, den = 1;
94 AVRational result;
95 num = read_int(line, &line, error);
96 if (*line == '.')
97 line++;
98 for (; *line>='0' && *line<='9'; line++) {
99 // Truncate any numerator too large to fit into an int64_t
100 if (num > (INT64_MAX - 9) / 10 || den > INT64_MAX / 10)
101 break;
102 num = 10 * num + *line - '0';
103 den *= 10;
104 }
105 if (!num)
106 *error = -1;
107 av_reduce(&result.num, &result.den, num, den, 0x7FFFFFFF);
108 return result;
109}
110
111static int rpl_read_header(AVFormatContext *s, AVFormatParameters *ap)
112{
113 ByteIOContext *pb = s->pb;
114 RPLContext *rpl = s->priv_data;
115 AVStream *vst = NULL, *ast = NULL;
116 int total_audio_size;
117 int error = 0;
118
119 uint32_t i;
120
121 int32_t audio_format, chunk_catalog_offset, number_of_chunks;
122 AVRational fps;
123
124 char line[RPL_LINE_LENGTH];
125
126 // The header for RPL/ARMovie files is 21 lines of text
127 // containing the various header fields. The fields are always
128 // in the same order, and other text besides the first
129 // number usually isn't important.
130 // (The spec says that there exists some significance
131 // for the text in a few cases; samples needed.)
132 error |= read_line(pb, line , sizeof(line )); // ARMovie
133 error |= read_line(pb, s->title , sizeof(s->title )); // movie name
134 error |= read_line(pb, s->copyright, sizeof(s->copyright)); // date/copyright
135 error |= read_line(pb, s->author , sizeof(s->author )); // author and other
136
137 // video headers
138 vst = av_new_stream(s, 0);
139 if (!vst)
140 return AVERROR(ENOMEM);
141 vst->codec->codec_type = CODEC_TYPE_VIDEO;
142 vst->codec->codec_tag = read_line_and_int(pb, &error); // video format
143 vst->codec->width = read_line_and_int(pb, &error); // video width
144 vst->codec->height = read_line_and_int(pb, &error); // video height
145 vst->codec->bits_per_sample = read_line_and_int(pb, &error); // video bits per sample
146 error |= read_line(pb, line, sizeof(line)); // video frames per second
147 fps = read_fps(line, &error);
148 av_set_pts_info(vst, 32, fps.den, fps.num);
149
150 // Figure out the video codec
151 switch (vst->codec->codec_tag) {
152#if 0
153 case 122:
154 vst->codec->codec_id = CODEC_ID_ESCAPE122;
155 break;
156#endif
157 case 124:
158 vst->codec->codec_id = CODEC_ID_ESCAPE124;
159 // The header is wrong here, at least sometimes
160 vst->codec->bits_per_sample = 16;
161 break;
162#if 0
163 case 130:
164 vst->codec->codec_id = CODEC_ID_ESCAPE130;
165 break;
166#endif
167 default:
168 av_log(s, AV_LOG_WARNING,
169 "RPL video format %i not supported yet!\n",
170 vst->codec->codec_tag);
171 vst->codec->codec_id = CODEC_ID_NONE;
172 }
173
174 // Audio headers
175
176 // ARMovie supports multiple audio tracks; I don't have any
177 // samples, though. This code will ignore additional tracks.
178 audio_format = read_line_and_int(pb, &error); // audio format ID
179 if (audio_format) {
180 ast = av_new_stream(s, 0);
181 if (!ast)
182 return AVERROR(ENOMEM);
183 ast->codec->codec_type = CODEC_TYPE_AUDIO;
184 ast->codec->codec_tag = audio_format;
185 ast->codec->sample_rate = read_line_and_int(pb, &error); // audio bitrate
186 ast->codec->channels = read_line_and_int(pb, &error); // number of audio channels
187 ast->codec->bits_per_sample = read_line_and_int(pb, &error); // audio bits per sample
188 // At least one sample uses 0 for ADPCM, which is really 4 bits
189 // per sample.
190 if (ast->codec->bits_per_sample == 0)
191 ast->codec->bits_per_sample = 4;
192
193 ast->codec->bit_rate = ast->codec->sample_rate *
194 ast->codec->bits_per_sample *
195 ast->codec->channels;
196
197 ast->codec->codec_id = CODEC_ID_NONE;
198 switch (audio_format) {
199 case 1:
200 if (ast->codec->bits_per_sample == 16) {
201 // 16-bit audio is always signed
202 ast->codec->codec_id = CODEC_ID_PCM_S16LE;
203 break;
204 }
205 // There are some other formats listed as legal per the spec;
206 // samples needed.
207 break;
208 case 101:
209 if (ast->codec->bits_per_sample == 8) {
210 // The samples with this kind of audio that I have
211 // are all unsigned.
212 ast->codec->codec_id = CODEC_ID_PCM_U8;
213 break;
214 } else if (ast->codec->bits_per_sample == 4) {
215 ast->codec->codec_id = CODEC_ID_ADPCM_IMA_EA_SEAD;
216 break;
217 }
218 break;
219 }
220 if (ast->codec->codec_id == CODEC_ID_NONE) {
221 av_log(s, AV_LOG_WARNING,
222 "RPL audio format %i not supported yet!\n",
223 audio_format);
224 }
225 av_set_pts_info(ast, 32, 1, ast->codec->bit_rate);
226 } else {
227 for (i = 0; i < 3; i++)
228 error |= read_line(pb, line, sizeof(line));
229 }
230
231 rpl->frames_per_chunk = read_line_and_int(pb, &error); // video frames per chunk
232 if (rpl->frames_per_chunk > 1 && vst->codec->codec_tag != 124)
233 av_log(s, AV_LOG_WARNING,
234 "Don't know how to split frames for video format %i. "
235 "Video stream will be broken!\n", vst->codec->codec_tag);
236
237 number_of_chunks = read_line_and_int(pb, &error); // number of chunks in the file
238 // The number in the header is actually the index of the last chunk.
239 number_of_chunks++;
240
241 error |= read_line(pb, line, sizeof(line)); // "even" chunk size in bytes
242 error |= read_line(pb, line, sizeof(line)); // "odd" chunk size in bytes
243 chunk_catalog_offset = // offset of the "chunk catalog"
244 read_line_and_int(pb, &error); // (file index)
245 error |= read_line(pb, line, sizeof(line)); // offset to "helpful" sprite
246 error |= read_line(pb, line, sizeof(line)); // size of "helpful" sprite
247 error |= read_line(pb, line, sizeof(line)); // offset to key frame list
248
249 // Read the index
250 url_fseek(pb, chunk_catalog_offset, SEEK_SET);
251 total_audio_size = 0;
252 for (i = 0; i < number_of_chunks; i++) {
253 int64_t offset, video_size, audio_size;
254 error |= read_line(pb, line, sizeof(line));
255 if (3 != sscanf(line, "%"PRId64" , %"PRId64" ; %"PRId64,
256 &offset, &video_size, &audio_size))
257 error = -1;
258 av_add_index_entry(vst, offset, i * rpl->frames_per_chunk,
259 video_size, rpl->frames_per_chunk, 0);
260 if (ast)
261 av_add_index_entry(ast, offset + video_size, total_audio_size,
262 audio_size, audio_size * 8, 0);
263 total_audio_size += audio_size * 8;
264 }
265
266 if (error) return AVERROR(EIO);
267
268 return 0;
269}
270
271static int rpl_read_packet(AVFormatContext *s, AVPacket *pkt)
272{
273 RPLContext *rpl = s->priv_data;
274 ByteIOContext *pb = s->pb;
275 AVStream* stream;
276 AVIndexEntry* index_entry;
277 uint32_t ret;
278
279 if (rpl->chunk_part == s->nb_streams) {
280 rpl->chunk_number++;
281 rpl->chunk_part = 0;
282 }
283
284 stream = s->streams[rpl->chunk_part];
285
286 if (rpl->chunk_number >= stream->nb_index_entries)
287 return -1;
288
289 index_entry = &stream->index_entries[rpl->chunk_number];
290
291 if (rpl->frame_in_part == 0)
292 if (url_fseek(pb, index_entry->pos, SEEK_SET) < 0)
293 return AVERROR(EIO);
294
295 if (stream->codec->codec_type == CODEC_TYPE_VIDEO &&
296 stream->codec->codec_tag == 124) {
297 // We have to split Escape 124 frames because there are
298 // multiple frames per chunk in Escape 124 samples.
299 uint32_t frame_size, frame_flags;
300
301 frame_flags = get_le32(pb);
302 frame_size = get_le32(pb);
303 if (url_fseek(pb, -8, SEEK_CUR) < 0)
304 return AVERROR(EIO);
305
306 ret = av_get_packet(pb, pkt, frame_size);
307 if (ret != frame_size) {
308 av_free_packet(pkt);
309 return AVERROR(EIO);
310 }
311 pkt->duration = 1;
312 pkt->pts = index_entry->timestamp + rpl->frame_in_part;
313 pkt->stream_index = rpl->chunk_part;
314
315 rpl->frame_in_part++;
316 if (rpl->frame_in_part == rpl->frames_per_chunk) {
317 rpl->frame_in_part = 0;
318 rpl->chunk_part++;
319 }
320 } else {
321 ret = av_get_packet(pb, pkt, index_entry->size);
322 if (ret != index_entry->size) {
323 av_free_packet(pkt);
324 return AVERROR(EIO);
325 }
326
327 if (stream->codec->codec_type == CODEC_TYPE_VIDEO) {
328 // frames_per_chunk should always be one here; the header
329 // parsing will warn if it isn't.
330 pkt->duration = rpl->frames_per_chunk;
331 } else {
332 // All the audio codecs supported in this container
333 // (at least so far) are constant-bitrate.
334 pkt->duration = ret * 8;
335 }
336 pkt->pts = index_entry->timestamp;
337 pkt->stream_index = rpl->chunk_part;
338 rpl->chunk_part++;
339 }
340
341 // None of the Escape formats have keyframes, and the ADPCM
342 // format used doesn't have keyframes.
343 if (rpl->chunk_number == 0 && rpl->frame_in_part == 0)
344 pkt->flags |= PKT_FLAG_KEY;
345
346 return ret;
347}
348
349AVInputFormat rpl_demuxer = {
350 "rpl",
351 NULL_IF_CONFIG_SMALL("RPL/ARMovie format"),
352 sizeof(RPLContext),
353 rpl_probe,
354 rpl_read_header,
355 rpl_read_packet,
356};
diff --git a/src/plugins/ffmpeg/libavformat/rtp.c b/src/plugins/ffmpeg/libavformat/rtp.c
deleted file mode 100644
index b1501e6..0000000
--- a/src/plugins/ffmpeg/libavformat/rtp.c
+++ /dev/null
@@ -1,133 +0,0 @@
1/*
2 * RTP input/output format
3 * Copyright (c) 2002 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 "libavcodec/bitstream.h"
23#include "avformat.h"
24
25#include <unistd.h>
26#include "network.h"
27
28#include "rtp_internal.h"
29
30//#define DEBUG
31
32/* from http://www.iana.org/assignments/rtp-parameters last updated 05 January 2005 */
33/* payload types >= 96 are dynamic;
34 * payload types between 72 and 76 are reserved for RTCP conflict avoidance;
35 * all the other payload types not present in the table are unassigned or
36 * reserved
37 */
38static const struct
39{
40 int pt;
41 const char enc_name[6];
42 enum CodecType codec_type;
43 enum CodecID codec_id;
44 int clock_rate;
45 int audio_channels;
46} AVRtpPayloadTypes[]=
47{
48 {0, "PCMU", CODEC_TYPE_AUDIO, CODEC_ID_PCM_MULAW, 8000, 1},
49 {3, "GSM", CODEC_TYPE_AUDIO, CODEC_ID_NONE, 8000, 1},
50 {4, "G723", CODEC_TYPE_AUDIO, CODEC_ID_NONE, 8000, 1},
51 {5, "DVI4", CODEC_TYPE_AUDIO, CODEC_ID_NONE, 8000, 1},
52 {6, "DVI4", CODEC_TYPE_AUDIO, CODEC_ID_NONE, 16000, 1},
53 {7, "LPC", CODEC_TYPE_AUDIO, CODEC_ID_NONE, 8000, 1},
54 {8, "PCMA", CODEC_TYPE_AUDIO, CODEC_ID_PCM_ALAW, 8000, 1},
55 {9, "G722", CODEC_TYPE_AUDIO, CODEC_ID_NONE, 8000, 1},
56 {10, "L16", CODEC_TYPE_AUDIO, CODEC_ID_PCM_S16BE, 44100, 2},
57 {11, "L16", CODEC_TYPE_AUDIO, CODEC_ID_PCM_S16BE, 44100, 1},
58 {12, "QCELP", CODEC_TYPE_AUDIO, CODEC_ID_QCELP, 8000, 1},
59 {13, "CN", CODEC_TYPE_AUDIO, CODEC_ID_NONE, 8000, 1},
60 {14, "MPA", CODEC_TYPE_AUDIO, CODEC_ID_MP2, -1, -1},
61 {14, "MPA", CODEC_TYPE_AUDIO, CODEC_ID_MP3, -1, -1},
62 {15, "G728", CODEC_TYPE_AUDIO, CODEC_ID_NONE, 8000, 1},
63 {16, "DVI4", CODEC_TYPE_AUDIO, CODEC_ID_NONE, 11025, 1},
64 {17, "DVI4", CODEC_TYPE_AUDIO, CODEC_ID_NONE, 22050, 1},
65 {18, "G729", CODEC_TYPE_AUDIO, CODEC_ID_NONE, 8000, 1},
66 {25, "CelB", CODEC_TYPE_VIDEO, CODEC_ID_NONE, 90000, -1},
67 {26, "JPEG", CODEC_TYPE_VIDEO, CODEC_ID_MJPEG, 90000, -1},
68 {28, "nv", CODEC_TYPE_VIDEO, CODEC_ID_NONE, 90000, -1},
69 {31, "H261", CODEC_TYPE_VIDEO, CODEC_ID_H261, 90000, -1},
70 {32, "MPV", CODEC_TYPE_VIDEO, CODEC_ID_MPEG1VIDEO, 90000, -1},
71 {32, "MPV", CODEC_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO, 90000, -1},
72 {33, "MP2T", CODEC_TYPE_DATA, CODEC_ID_MPEG2TS, 90000, -1},
73 {34, "H263", CODEC_TYPE_VIDEO, CODEC_ID_H263, 90000, -1},
74 {-1, "", CODEC_TYPE_UNKNOWN, CODEC_ID_NONE, -1, -1}
75};
76
77int rtp_get_codec_info(AVCodecContext *codec, int payload_type)
78{
79 int i = 0;
80
81 for (i = 0; AVRtpPayloadTypes[i].pt >= 0; i++)
82 if (AVRtpPayloadTypes[i].pt == payload_type) {
83 if (AVRtpPayloadTypes[i].codec_id != CODEC_ID_NONE) {
84 codec->codec_type = AVRtpPayloadTypes[i].codec_type;
85 codec->codec_id = AVRtpPayloadTypes[i].codec_id;
86 if (AVRtpPayloadTypes[i].audio_channels > 0)
87 codec->channels = AVRtpPayloadTypes[i].audio_channels;
88 if (AVRtpPayloadTypes[i].clock_rate > 0)
89 codec->sample_rate = AVRtpPayloadTypes[i].clock_rate;
90 return 0;
91 }
92 }
93 return -1;
94}
95
96int rtp_get_payload_type(AVCodecContext *codec)
97{
98 int i, payload_type;
99
100 /* compute the payload type */
101 for (payload_type = -1, i = 0; AVRtpPayloadTypes[i].pt >= 0; ++i)
102 if (AVRtpPayloadTypes[i].codec_id == codec->codec_id) {
103 if (codec->codec_id == CODEC_ID_PCM_S16BE)
104 if (codec->channels != AVRtpPayloadTypes[i].audio_channels)
105 continue;
106 payload_type = AVRtpPayloadTypes[i].pt;
107 }
108 return payload_type;
109}
110
111const char *ff_rtp_enc_name(int payload_type)
112{
113 int i;
114
115 for (i = 0; AVRtpPayloadTypes[i].pt >= 0; i++)
116 if (AVRtpPayloadTypes[i].pt == payload_type) {
117 return AVRtpPayloadTypes[i].enc_name;
118 }
119
120 return "";
121}
122
123enum CodecID ff_rtp_codec_id(const char *buf, enum CodecType codec_type)
124{
125 int i;
126
127 for (i = 0; AVRtpPayloadTypes[i].pt >= 0; i++)
128 if (!strcmp(buf, AVRtpPayloadTypes[i].enc_name) && (codec_type == AVRtpPayloadTypes[i].codec_type)){
129 return AVRtpPayloadTypes[i].codec_id;
130 }
131
132 return CODEC_ID_NONE;
133}
diff --git a/src/plugins/ffmpeg/libavformat/rtp.h b/src/plugins/ffmpeg/libavformat/rtp.h
deleted file mode 100644
index 36affed..0000000
--- a/src/plugins/ffmpeg/libavformat/rtp.h
+++ /dev/null
@@ -1,113 +0,0 @@
1/*
2 * RTP definitions
3 * Copyright (c) 2002 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#ifndef FFMPEG_RTP_H
22#define FFMPEG_RTP_H
23
24#include "libavcodec/avcodec.h"
25#include "avformat.h"
26
27#define RTP_MIN_PACKET_LENGTH 12
28#define RTP_MAX_PACKET_LENGTH 1500 /* XXX: suppress this define */
29
30int rtp_get_codec_info(AVCodecContext *codec, int payload_type);
31
32/** return < 0 if unknown payload type */
33int rtp_get_payload_type(AVCodecContext *codec);
34
35typedef struct RTPDemuxContext RTPDemuxContext;
36typedef struct rtp_payload_data_s rtp_payload_data_s;
37RTPDemuxContext *rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *rtpc, int payload_type, rtp_payload_data_s *rtp_payload_data);
38int rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
39 const uint8_t *buf, int len);
40void rtp_parse_close(RTPDemuxContext *s);
41
42int rtp_get_local_port(URLContext *h);
43int rtp_set_remote_url(URLContext *h, const char *uri);
44void rtp_get_file_handles(URLContext *h, int *prtp_fd, int *prtcp_fd);
45
46/**
47 * some rtp servers assume client is dead if they don't hear from them...
48 * so we send a Receiver Report to the provided ByteIO context
49 * (we don't have access to the rtcp handle from here)
50 */
51int rtp_check_and_send_back_rr(RTPDemuxContext *s, int count);
52
53#define RTP_PT_PRIVATE 96
54#define RTP_VERSION 2
55#define RTP_MAX_SDES 256 /**< maximum text length for SDES */
56
57/* RTCP paquets use 0.5 % of the bandwidth */
58#define RTCP_TX_RATIO_NUM 5
59#define RTCP_TX_RATIO_DEN 1000
60
61/** Structure listing useful vars to parse RTP packet payload*/
62typedef struct rtp_payload_data_s
63{
64 int sizelength;
65 int indexlength;
66 int indexdeltalength;
67 int profile_level_id;
68 int streamtype;
69 int objecttype;
70 char *mode;
71
72 /** mpeg 4 AU headers */
73 struct AUHeaders {
74 int size;
75 int index;
76 int cts_flag;
77 int cts;
78 int dts_flag;
79 int dts;
80 int rap_flag;
81 int streamstate;
82 } *au_headers;
83 int nb_au_headers;
84 int au_headers_length_bytes;
85 int cur_au_index;
86} rtp_payload_data_t;
87
88#if 0
89typedef enum {
90 RTCP_SR = 200,
91 RTCP_RR = 201,
92 RTCP_SDES = 202,
93 RTCP_BYE = 203,
94 RTCP_APP = 204
95} rtcp_type_t;
96
97typedef enum {
98 RTCP_SDES_END = 0,
99 RTCP_SDES_CNAME = 1,
100 RTCP_SDES_NAME = 2,
101 RTCP_SDES_EMAIL = 3,
102 RTCP_SDES_PHONE = 4,
103 RTCP_SDES_LOC = 5,
104 RTCP_SDES_TOOL = 6,
105 RTCP_SDES_NOTE = 7,
106 RTCP_SDES_PRIV = 8,
107 RTCP_SDES_IMG = 9,
108 RTCP_SDES_DOOR = 10,
109 RTCP_SDES_SOURCE = 11
110} rtcp_sdes_type_t;
111#endif
112
113#endif /* FFMPEG_RTP_H */
diff --git a/src/plugins/ffmpeg/libavformat/rtp_aac.c b/src/plugins/ffmpeg/libavformat/rtp_aac.c
deleted file mode 100644
index 4cd8e12..0000000
--- a/src/plugins/ffmpeg/libavformat/rtp_aac.c
+++ /dev/null
@@ -1,88 +0,0 @@
1/*
2 * copyright (c) 2007 Luca Abeni
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21#include "avformat.h"
22#include "rtp_aac.h"
23#include "rtp_internal.h"
24
25#define MAX_FRAMES_PER_PACKET (s->max_frames_per_packet ? s->max_frames_per_packet : 5)
26#define MAX_AU_HEADERS_SIZE (2 + 2 * MAX_FRAMES_PER_PACKET)
27
28void ff_rtp_send_aac(AVFormatContext *s1, const uint8_t *buff, int size)
29{
30 RTPDemuxContext *s = s1->priv_data;
31 int len, max_packet_size;
32 uint8_t *p;
33
34 /* skip ADTS header, if present */
35 if ((s1->streams[0]->codec->extradata_size) == 0) {
36 size -= 7;
37 buff += 7;
38 }
39 max_packet_size = s->max_payload_size - MAX_AU_HEADERS_SIZE;
40
41 /* test if the packet must be sent */
42 len = (s->buf_ptr - s->buf);
43 if ((s->read_buf_index == MAX_FRAMES_PER_PACKET) || (len && (len + size) > max_packet_size)) {
44 int au_size = s->read_buf_index * 2;
45
46 p = s->buf + MAX_AU_HEADERS_SIZE - au_size - 2;
47 if (p != s->buf) {
48 memmove(p + 2, s->buf + 2, au_size);
49 }
50 /* Write the AU header size */
51 p[0] = ((au_size * 8) & 0xFF) >> 8;
52 p[1] = (au_size * 8) & 0xFF;
53
54 ff_rtp_send_data(s1, p, s->buf_ptr - p, 1);
55
56 s->read_buf_index = 0;
57 }
58 if (s->read_buf_index == 0) {
59 s->buf_ptr = s->buf + MAX_AU_HEADERS_SIZE;
60 s->timestamp = s->cur_timestamp;
61 }
62
63 if (size < max_packet_size) {
64 p = s->buf + s->read_buf_index++ * 2 + 2;
65 *p++ = size >> 5;
66 *p = (size & 0x1F) << 3;
67 memcpy(s->buf_ptr, buff, size);
68 s->buf_ptr += size;
69 } else {
70 if (s->buf_ptr != s->buf + MAX_AU_HEADERS_SIZE) {
71 av_log(s1, AV_LOG_ERROR, "Strange...\n");
72 av_abort();
73 }
74 max_packet_size = s->max_payload_size - 4;
75 p = s->buf;
76 p[0] = 0;
77 p[1] = 16;
78 while (size > 0) {
79 len = FFMIN(size, max_packet_size);
80 p[2] = len >> 5;
81 p[3] = (size & 0x1F) << 3;
82 memcpy(p + 4, buff, len);
83 ff_rtp_send_data(s1, p, len + 4, len == size);
84 size -= len;
85 buff += len;
86 }
87 }
88}
diff --git a/src/plugins/ffmpeg/libavformat/rtp_aac.h b/src/plugins/ffmpeg/libavformat/rtp_aac.h
deleted file mode 100644
index 24b41cc..0000000
--- a/src/plugins/ffmpeg/libavformat/rtp_aac.h
+++ /dev/null
@@ -1,27 +0,0 @@
1/*
2 * RTP definitions
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20#ifndef FFMPEG_RTP_AAC_H
21#define FFMPEG_RTP_AAC_H
22
23#include "avformat.h"
24
25void ff_rtp_send_aac(AVFormatContext *s1, const uint8_t *buff, int size);
26
27#endif /* FFMPEG_RTP_AAC_H */
diff --git a/src/plugins/ffmpeg/libavformat/rtp_h264.c b/src/plugins/ffmpeg/libavformat/rtp_h264.c
deleted file mode 100644
index c83b3a7..0000000
--- a/src/plugins/ffmpeg/libavformat/rtp_h264.c
+++ /dev/null
@@ -1,416 +0,0 @@
1/*
2 * RTP H264 Protocol (RFC3984)
3 * Copyright (c) 2006 Ryan Martell.
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/**
23* @file rtp_h264.c
24 * @brief H.264 / RTP Code (RFC3984)
25 * @author Ryan Martell <rdm4@martellventures.com>
26 *
27 * @note Notes:
28 * Notes:
29 * This currently supports packetization mode:
30 * Single Nal Unit Mode (0), or
31 * Non-Interleaved Mode (1). It currently does not support
32 * Interleaved Mode (2). (This requires implementing STAP-B, MTAP16, MTAP24, FU-B packet types)
33 *
34 * @note TODO:
35 * 1) RTCP sender reports for udp streams are required..
36 *
37 */
38
39#include "libavutil/base64.h"
40#include "libavutil/avstring.h"
41#include "libavcodec/bitstream.h"
42#include "avformat.h"
43#include "mpegts.h"
44
45#include <unistd.h>
46#include "network.h"
47#include <assert.h>
48
49#include "rtp_internal.h"
50#include "rtp_h264.h"
51
52/**
53 RTP/H264 specific private data.
54*/
55typedef struct h264_rtp_extra_data {
56 unsigned long cookie; ///< sanity check, to make sure we get the pointer we're expecting.
57
58 //sdp setup parameters
59 uint8_t profile_idc; ///< from the sdp setup parameters.
60 uint8_t profile_iop; ///< from the sdp setup parameters.
61 uint8_t level_idc; ///< from the sdp setup parameters.
62 int packetization_mode; ///< from the sdp setup parameters.
63#ifdef DEBUG
64 int packet_types_received[32];
65#endif
66} h264_rtp_extra_data;
67
68#define MAGIC_COOKIE (0xdeadbeef) ///< Cookie for the extradata; to verify we are what we think we are, and that we haven't been freed.
69#define DEAD_COOKIE (0xdeaddead) ///< Cookie for the extradata; once it is freed.
70
71/* ---------------- private code */
72static void sdp_parse_fmtp_config_h264(AVStream * stream,
73 h264_rtp_extra_data * h264_data,
74 char *attr, char *value)
75{
76 AVCodecContext *codec = stream->codec;
77 assert(codec->codec_id == CODEC_ID_H264);
78 assert(h264_data != NULL);
79
80 if (!strcmp(attr, "packetization-mode")) {
81 av_log(NULL, AV_LOG_DEBUG, "H.264/RTP Packetization Mode: %d\n", atoi(value));
82 h264_data->packetization_mode = atoi(value);
83 /*
84 Packetization Mode:
85 0 or not present: Single NAL mode (Only nals from 1-23 are allowed)
86 1: Non-interleaved Mode: 1-23, 24 (STAP-A), 28 (FU-A) are allowed.
87 2: Interleaved Mode: 25 (STAP-B), 26 (MTAP16), 27 (MTAP24), 28 (FU-A), and 29 (FU-B) are allowed.
88 */
89 if (h264_data->packetization_mode > 1)
90 av_log(stream, AV_LOG_ERROR,
91 "H.264/RTP Interleaved RTP mode is not supported yet.");
92 } else if (!strcmp(attr, "profile-level-id")) {
93 if (strlen(value) == 6) {
94 char buffer[3];
95 // 6 characters=3 bytes, in hex.
96 uint8_t profile_idc;
97 uint8_t profile_iop;
98 uint8_t level_idc;
99
100 buffer[0] = value[0]; buffer[1] = value[1]; buffer[2] = '\0';
101 profile_idc = strtol(buffer, NULL, 16);
102 buffer[0] = value[2]; buffer[1] = value[3];
103 profile_iop = strtol(buffer, NULL, 16);
104 buffer[0] = value[4]; buffer[1] = value[5];
105 level_idc = strtol(buffer, NULL, 16);
106
107 // set the parameters...
108 av_log(NULL, AV_LOG_DEBUG,
109 "H.264/RTP Profile IDC: %x Profile IOP: %x Level: %x\n",
110 profile_idc, profile_iop, level_idc);
111 h264_data->profile_idc = profile_idc;
112 h264_data->profile_iop = profile_iop;
113 h264_data->level_idc = level_idc;
114 }
115 } else if (!strcmp(attr, "sprop-parameter-sets")) {
116 uint8_t start_sequence[]= { 0, 0, 1 };
117 codec->extradata_size= 0;
118 codec->extradata= NULL;
119
120 while (*value) {
121 char base64packet[1024];
122 uint8_t decoded_packet[1024];
123 uint32_t packet_size;
124 char *dst = base64packet;
125
126 while (*value && *value != ','
127 && (dst - base64packet) < sizeof(base64packet) - 1) {
128 *dst++ = *value++;
129 }
130 *dst++ = '\0';
131
132 if (*value == ',')
133 value++;
134
135 packet_size= av_base64_decode(decoded_packet, base64packet, sizeof(decoded_packet));
136 if (packet_size) {
137 uint8_t *dest= av_malloc(packet_size+sizeof(start_sequence)+codec->extradata_size);
138 if(dest)
139 {
140 if(codec->extradata_size)
141 {
142 // av_realloc?
143 memcpy(dest, codec->extradata, codec->extradata_size);
144 av_free(codec->extradata);
145 }
146
147 memcpy(dest+codec->extradata_size, start_sequence, sizeof(start_sequence));
148 memcpy(dest+codec->extradata_size+sizeof(start_sequence), decoded_packet, packet_size);
149
150 codec->extradata= dest;
151 codec->extradata_size+= sizeof(start_sequence)+packet_size;
152 } else {
153 av_log(NULL, AV_LOG_ERROR, "H.264/RTP Unable to allocate memory for extradata!");
154 }
155 }
156 }
157 av_log(NULL, AV_LOG_DEBUG, "H.264/RTP Extradata set to %p (size: %d)!", codec->extradata, codec->extradata_size);
158 }
159}
160
161// return 0 on packet, no more left, 1 on packet, 1 on partial packet...
162static int h264_handle_packet(RTPDemuxContext * s,
163 AVPacket * pkt,
164 uint32_t * timestamp,
165 const uint8_t * buf,
166 int len, int flags)
167{
168#ifdef DEBUG
169 h264_rtp_extra_data *data = s->dynamic_protocol_context;
170#endif
171 uint8_t nal = buf[0];
172 uint8_t type = (nal & 0x1f);
173 int result= 0;
174 uint8_t start_sequence[]= {0, 0, 1};
175
176#ifdef DEBUG
177 assert(data);
178 assert(data->cookie == MAGIC_COOKIE);
179#endif
180 assert(buf);
181
182 if (type >= 1 && type <= 23)
183 type = 1; // simplify the case. (these are all the nal types used internally by the h264 codec)
184 switch (type) {
185 case 0: // undefined;
186 result= -1;
187 break;
188
189 case 1:
190 av_new_packet(pkt, len+sizeof(start_sequence));
191 memcpy(pkt->data, start_sequence, sizeof(start_sequence));
192 memcpy(pkt->data+sizeof(start_sequence), buf, len);
193#ifdef DEBUG
194 data->packet_types_received[nal & 0x1f]++;
195#endif
196 break;
197
198 case 24: // STAP-A (one packet, multiple nals)
199 // consume the STAP-A NAL
200 buf++;
201 len--;
202 // first we are going to figure out the total size....
203 {
204 int pass= 0;
205 int total_length= 0;
206 uint8_t *dst= NULL;
207
208 for(pass= 0; pass<2; pass++) {
209 const uint8_t *src= buf;
210 int src_len= len;
211
212 do {
213 uint16_t nal_size = AV_RB16(src); // this going to be a problem if unaligned (can it be?)
214
215 // consume the length of the aggregate...
216 src += 2;
217 src_len -= 2;
218
219 if (nal_size <= src_len) {
220 if(pass==0) {
221 // counting...
222 total_length+= sizeof(start_sequence)+nal_size;
223 } else {
224 // copying
225 assert(dst);
226 memcpy(dst, start_sequence, sizeof(start_sequence));
227 dst+= sizeof(start_sequence);
228 memcpy(dst, src, nal_size);
229#ifdef DEBUG
230 data->packet_types_received[*src & 0x1f]++;
231#endif
232 dst+= nal_size;
233 }
234 } else {
235 av_log(NULL, AV_LOG_ERROR,
236 "nal size exceeds length: %d %d\n", nal_size, src_len);
237 }
238
239 // eat what we handled...
240 src += nal_size;
241 src_len -= nal_size;
242
243 if (src_len < 0)
244 av_log(NULL, AV_LOG_ERROR,
245 "Consumed more bytes than we got! (%d)\n", src_len);
246 } while (src_len > 2); // because there could be rtp padding..
247
248 if(pass==0) {
249 // now we know the total size of the packet (with the start sequences added)
250 av_new_packet(pkt, total_length);
251 dst= pkt->data;
252 } else {
253 assert(dst-pkt->data==total_length);
254 }
255 }
256 }
257 break;
258
259 case 25: // STAP-B
260 case 26: // MTAP-16
261 case 27: // MTAP-24
262 case 29: // FU-B
263 av_log(NULL, AV_LOG_ERROR,
264 "Unhandled type (%d) (See RFC for implementation details\n",
265 type);
266 result= -1;
267 break;
268
269 case 28: // FU-A (fragmented nal)
270 buf++;
271 len--; // skip the fu_indicator
272 {
273 // these are the same as above, we just redo them here for clarity...
274 uint8_t fu_indicator = nal;
275 uint8_t fu_header = *buf; // read the fu_header.
276 uint8_t start_bit = fu_header >> 7;
277// uint8_t end_bit = (fu_header & 0x40) >> 6;
278 uint8_t nal_type = (fu_header & 0x1f);
279 uint8_t reconstructed_nal;
280
281 // reconstruct this packet's true nal; only the data follows..
282 reconstructed_nal = fu_indicator & (0xe0); // the original nal forbidden bit and NRI are stored in this packet's nal;
283 reconstructed_nal |= nal_type;
284
285 // skip the fu_header...
286 buf++;
287 len--;
288
289#ifdef DEBUG
290 if (start_bit)
291 data->packet_types_received[nal_type]++;
292#endif
293 if(start_bit) {
294 // copy in the start sequence, and the reconstructed nal....
295 av_new_packet(pkt, sizeof(start_sequence)+sizeof(nal)+len);
296 memcpy(pkt->data, start_sequence, sizeof(start_sequence));
297 pkt->data[sizeof(start_sequence)]= reconstructed_nal;
298 memcpy(pkt->data+sizeof(start_sequence)+sizeof(nal), buf, len);
299 } else {
300 av_new_packet(pkt, len);
301 memcpy(pkt->data, buf, len);
302 }
303 }
304 break;
305
306 case 30: // undefined
307 case 31: // undefined
308 default:
309 av_log(NULL, AV_LOG_ERROR, "Undefined type (%d)", type);
310 result= -1;
311 break;
312 }
313
314 return result;
315}
316
317/* ---------------- public code */
318static void *h264_new_extradata(void)
319{
320 h264_rtp_extra_data *data =
321 av_mallocz(sizeof(h264_rtp_extra_data) +
322 FF_INPUT_BUFFER_PADDING_SIZE);
323
324 if (data) {
325 data->cookie = MAGIC_COOKIE;
326 }
327
328 return data;
329}
330
331static void h264_free_extradata(void *d)
332{
333 h264_rtp_extra_data *data = (h264_rtp_extra_data *) d;
334#ifdef DEBUG
335 int ii;
336
337 for (ii = 0; ii < 32; ii++) {
338 if (data->packet_types_received[ii])
339 av_log(NULL, AV_LOG_DEBUG, "Received %d packets of type %d\n",
340 data->packet_types_received[ii], ii);
341 }
342#endif
343
344 assert(data);
345 assert(data->cookie == MAGIC_COOKIE);
346
347 // avoid stale pointers (assert)
348 data->cookie = DEAD_COOKIE;
349
350 // and clear out this...
351 av_free(data);
352}
353
354static int parse_h264_sdp_line(AVStream * stream, void *data,
355 const char *line)
356{
357 AVCodecContext *codec = stream->codec;
358 h264_rtp_extra_data *h264_data = (h264_rtp_extra_data *) data;
359 const char *p = line;
360
361 assert(h264_data->cookie == MAGIC_COOKIE);
362
363 if (av_strstart(p, "framesize:", &p)) {
364 char buf1[50];
365 char *dst = buf1;
366
367 // remove the protocol identifier..
368 while (*p && *p == ' ') p++; // strip spaces.
369 while (*p && *p != ' ') p++; // eat protocol identifier
370 while (*p && *p == ' ') p++; // strip trailing spaces.
371 while (*p && *p != '-' && (buf1 - dst) < sizeof(buf1) - 1) {
372 *dst++ = *p++;
373 }
374 *dst = '\0';
375
376 // a='framesize:96 320-240'
377 // set our parameters..
378 codec->width = atoi(buf1);
379 codec->height = atoi(p + 1); // skip the -
380 codec->pix_fmt = PIX_FMT_YUV420P;
381 } else if (av_strstart(p, "fmtp:", &p)) {
382 char attr[256];
383 char value[4096];
384
385 // remove the protocol identifier..
386 while (*p && *p == ' ') p++; // strip spaces.
387 while (*p && *p != ' ') p++; // eat protocol identifier
388 while (*p && *p == ' ') p++; // strip trailing spaces.
389
390 /* loop on each attribute */
391 while (rtsp_next_attr_and_value
392 (&p, attr, sizeof(attr), value, sizeof(value))) {
393 /* grab the codec extra_data from the config parameter of the fmtp line */
394 sdp_parse_fmtp_config_h264(stream, h264_data, attr, value);
395 }
396 } else if (av_strstart(p, "cliprect:", &p)) {
397 // could use this if we wanted.
398 }
399
400 av_set_pts_info(stream, 33, 1, 90000); // 33 should be right, because the pts is 64 bit? (done elsewhere; this is a one time thing)
401
402 return 0; // keep processing it the normal way...
403}
404
405/**
406This is the structure for expanding on the dynamic rtp protocols (makes everything static. yay!)
407*/
408RTPDynamicProtocolHandler ff_h264_dynamic_handler = {
409 "H264",
410 CODEC_TYPE_VIDEO,
411 CODEC_ID_H264,
412 parse_h264_sdp_line,
413 h264_new_extradata,
414 h264_free_extradata,
415 h264_handle_packet
416};
diff --git a/src/plugins/ffmpeg/libavformat/rtp_h264.h b/src/plugins/ffmpeg/libavformat/rtp_h264.h
deleted file mode 100644
index 0f23e52..0000000
--- a/src/plugins/ffmpeg/libavformat/rtp_h264.h
+++ /dev/null
@@ -1,30 +0,0 @@
1/*
2 * RTP H264 Protocol (RFC3984)
3 * Copyright (c) 2006 Ryan Martell.
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#ifndef FFMPEG_RTP_H264_H
23#define FFMPEG_RTP_H264_H
24
25#include "rtp_internal.h"
26
27extern RTPDynamicProtocolHandler ff_h264_dynamic_handler;
28void ff_rtp_send_h264(AVFormatContext *s1, const uint8_t *buf1, int size);
29
30#endif /* FFMPEG_RTP_H264_H */
diff --git a/src/plugins/ffmpeg/libavformat/rtp_internal.h b/src/plugins/ffmpeg/libavformat/rtp_internal.h
deleted file mode 100644
index c34212d..0000000
--- a/src/plugins/ffmpeg/libavformat/rtp_internal.h
+++ /dev/null
@@ -1,131 +0,0 @@
1/*
2 * RTP definitions
3 * Copyright (c) 2006 Ryan Martell <rdm4@martellventures.com>
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// this is a bit of a misnomer, because rtp & rtsp internal structures and prototypes are in here.
23#ifndef FFMPEG_RTP_INTERNAL_H
24#define FFMPEG_RTP_INTERNAL_H
25
26#include <stdint.h>
27#include "libavcodec/avcodec.h"
28#include "rtp.h"
29
30// these statistics are used for rtcp receiver reports...
31typedef struct {
32 uint16_t max_seq; ///< highest sequence number seen
33 uint32_t cycles; ///< shifted count of sequence number cycles
34 uint32_t base_seq; ///< base sequence number
35 uint32_t bad_seq; ///< last bad sequence number + 1
36 int probation; ///< sequence packets till source is valid
37 int received; ///< packets received
38 int expected_prior; ///< packets expected in last interval
39 int received_prior; ///< packets received in last interval
40 uint32_t transit; ///< relative transit time for previous packet
41 uint32_t jitter; ///< estimated jitter.
42} RTPStatistics;
43
44/**
45 * Packet parsing for "private" payloads in the RTP specs.
46 *
47 * @param s stream context
48 * @param pkt packet in which to write the parsed data
49 * @param timestamp pointer in which to write the timestamp of this RTP packet
50 * @param buf pointer to raw RTP packet data
51 * @param len length of buf
52 * @param flags flags from the RTP packet header (PKT_FLAG_*)
53 */
54typedef int (*DynamicPayloadPacketHandlerProc) (struct RTPDemuxContext * s,
55 AVPacket * pkt,
56 uint32_t *timestamp,
57 const uint8_t * buf,
58 int len, int flags);
59
60typedef struct RTPDynamicProtocolHandler_s {
61 // fields from AVRtpDynamicPayloadType_s
62 const char enc_name[50]; /* XXX: still why 50 ? ;-) */
63 enum CodecType codec_type;
64 enum CodecID codec_id;
65
66 // may be null
67 int (*parse_sdp_a_line) (AVStream * stream,
68 void *protocol_data,
69 const char *line); ///< Parse the a= line from the sdp field
70 void *(*open) (); ///< allocate any data needed by the rtp parsing for this dynamic data.
71 void (*close)(void *protocol_data); ///< free any data needed by the rtp parsing for this dynamic data.
72 DynamicPayloadPacketHandlerProc parse_packet; ///< parse handler for this dynamic packet.
73
74 struct RTPDynamicProtocolHandler_s *next;
75} RTPDynamicProtocolHandler;
76
77// moved out of rtp.c, because the h264 decoder needs to know about this structure..
78struct RTPDemuxContext {
79 AVFormatContext *ic;
80 AVStream *st;
81 int payload_type;
82 uint32_t ssrc;
83 uint16_t seq;
84 uint32_t timestamp;
85 uint32_t base_timestamp;
86 uint32_t cur_timestamp;
87 int max_payload_size;
88 struct MpegTSContext *ts; /* only used for MP2T payloads */
89 int read_buf_index;
90 int read_buf_size;
91 /* used to send back RTCP RR */
92 URLContext *rtp_ctx;
93 char hostname[256];
94
95 RTPStatistics statistics; ///< Statistics for this stream (used by RTCP receiver reports)
96
97 /* rtcp sender statistics receive */
98 int64_t last_rtcp_ntp_time; // TODO: move into statistics
99 int64_t first_rtcp_ntp_time; // TODO: move into statistics
100 uint32_t last_rtcp_timestamp; // TODO: move into statistics
101
102 /* rtcp sender statistics */
103 unsigned int packet_count; // TODO: move into statistics (outgoing)
104 unsigned int octet_count; // TODO: move into statistics (outgoing)
105 unsigned int last_octet_count; // TODO: move into statistics (outgoing)
106 int first_packet;
107 /* buffer for output */
108 uint8_t buf[RTP_MAX_PACKET_LENGTH];
109 uint8_t *buf_ptr;
110
111 /* special infos for au headers parsing */
112 rtp_payload_data_t *rtp_payload_data; // TODO: Move into dynamic payload handlers
113
114 /* dynamic payload stuff */
115 DynamicPayloadPacketHandlerProc parse_packet; ///< This is also copied from the dynamic protocol handler structure
116 void *dynamic_protocol_context; ///< This is a copy from the values setup from the sdp parsing, in rtsp.c don't free me.
117 int max_frames_per_packet;
118};
119
120extern RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler;
121
122int rtsp_next_attr_and_value(const char **p, char *attr, int attr_size, char *value, int value_size); ///< from rtsp.c, but used by rtp dynamic protocol handlers.
123
124void ff_rtp_send_data(AVFormatContext *s1, const uint8_t *buf1, int len, int m);
125const char *ff_rtp_enc_name(int payload_type);
126enum CodecID ff_rtp_codec_id(const char *buf, enum CodecType codec_type);
127
128void av_register_rtp_dynamic_payload_handlers(void);
129
130#endif /* FFMPEG_RTP_INTERNAL_H */
131
diff --git a/src/plugins/ffmpeg/libavformat/rtp_mpv.c b/src/plugins/ffmpeg/libavformat/rtp_mpv.c
deleted file mode 100644
index 2c67f05..0000000
--- a/src/plugins/ffmpeg/libavformat/rtp_mpv.c
+++ /dev/null
@@ -1,118 +0,0 @@
1/*
2 * RTP packetization for MPEG video
3 * Copyright (c) 2002 Fabrice Bellard.
4 * Copyright (c) 2007 Luca Abeni.
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#include "libavcodec/mpegvideo.h"
24#include "avformat.h"
25#include "rtp_internal.h"
26
27/* NOTE: a single frame must be passed with sequence header if
28 needed. XXX: use slices. */
29void ff_rtp_send_mpegvideo(AVFormatContext *s1, const uint8_t *buf1, int size)
30{
31 RTPDemuxContext *s = s1->priv_data;
32 int len, h, max_packet_size;
33 uint8_t *q;
34 int begin_of_slice, end_of_slice, frame_type, temporal_reference;
35
36 max_packet_size = s->max_payload_size;
37 begin_of_slice = 1;
38 end_of_slice = 0;
39 frame_type = 0;
40 temporal_reference = 0;
41
42 while (size > 0) {
43 int begin_of_sequence;
44
45 begin_of_sequence = 0;
46 len = max_packet_size - 4;
47
48 if (len >= size) {
49 len = size;
50 end_of_slice = 1;
51 } else {
52 const uint8_t *r, *r1;
53 int start_code;
54
55 r1 = buf1;
56 while (1) {
57 start_code = -1;
58 r = ff_find_start_code(r1, buf1 + size, &start_code);
59 if((start_code & 0xFFFFFF00) == 0x100) {
60 /* New start code found */
61 if (start_code == 0x100) {
62 frame_type = (r[1] & 0x38) >> 3;
63 temporal_reference = (int)r[0] << 2 | r[1] >> 6;
64 }
65 if (start_code == 0x1B8) {
66 begin_of_sequence = 1;
67 }
68
69 if (r - buf1 - 4 <= len) {
70 /* The current slice fits in the packet */
71 if (begin_of_slice == 0) {
72 /* no slice at the beginning of the packet... */
73 end_of_slice = 1;
74 len = r - buf1 - 4;
75 break;
76 }
77 r1 = r;
78 } else {
79 if ((r1 - buf1 > 4) && (r - r1 < max_packet_size)) {
80 len = r1 - buf1 - 4;
81 end_of_slice = 1;
82 }
83 break;
84 }
85 } else {
86 break;
87 }
88 }
89 }
90
91 h = 0;
92 h |= temporal_reference << 16;
93 h |= begin_of_sequence << 13;
94 h |= begin_of_slice << 12;
95 h |= end_of_slice << 11;
96 h |= frame_type << 8;
97
98 q = s->buf;
99 *q++ = h >> 24;
100 *q++ = h >> 16;
101 *q++ = h >> 8;
102 *q++ = h;
103
104 memcpy(q, buf1, len);
105 q += len;
106
107 /* 90 KHz time stamp */
108 s->timestamp = s->cur_timestamp;
109 ff_rtp_send_data(s1, s->buf, q - s->buf, (len == size));
110
111 buf1 += len;
112 size -= len;
113 begin_of_slice = end_of_slice;
114 end_of_slice = 0;
115 }
116}
117
118
diff --git a/src/plugins/ffmpeg/libavformat/rtp_mpv.h b/src/plugins/ffmpeg/libavformat/rtp_mpv.h
deleted file mode 100644
index 36e649a..0000000
--- a/src/plugins/ffmpeg/libavformat/rtp_mpv.h
+++ /dev/null
@@ -1,27 +0,0 @@
1/*
2 * RTP definitions
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20#ifndef FFMPEG_RTP_MPV_H
21#define FFMPEG_RTP_MPV_H
22
23#include "avformat.h"
24
25void ff_rtp_send_mpegvideo(AVFormatContext *s1, const uint8_t *buf1, int size);
26
27#endif /* FFMPEG_RTP_MPV_H */
diff --git a/src/plugins/ffmpeg/libavformat/rtpdec.c b/src/plugins/ffmpeg/libavformat/rtpdec.c
deleted file mode 100644
index e469a59..0000000
--- a/src/plugins/ffmpeg/libavformat/rtpdec.c
+++ /dev/null
@@ -1,537 +0,0 @@
1/*
2 * RTP input format
3 * Copyright (c) 2002 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 "libavcodec/bitstream.h"
23#include "avformat.h"
24#include "mpegts.h"
25
26#include <unistd.h>
27#include "network.h"
28
29#include "rtp_internal.h"
30#include "rtp_h264.h"
31
32//#define DEBUG
33
34/* TODO: - add RTCP statistics reporting (should be optional).
35
36 - add support for h263/mpeg4 packetized output : IDEA: send a
37 buffer to 'rtp_write_packet' contains all the packets for ONE
38 frame. Each packet should have a four byte header containing
39 the length in big endian format (same trick as
40 'url_open_dyn_packet_buf')
41*/
42
43/* statistics functions */
44RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler= NULL;
45
46static RTPDynamicProtocolHandler mp4v_es_handler= {"MP4V-ES", CODEC_TYPE_VIDEO, CODEC_ID_MPEG4};
47static RTPDynamicProtocolHandler mpeg4_generic_handler= {"mpeg4-generic", CODEC_TYPE_AUDIO, CODEC_ID_AAC};
48
49static void register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
50{
51 handler->next= RTPFirstDynamicPayloadHandler;
52 RTPFirstDynamicPayloadHandler= handler;
53}
54
55void av_register_rtp_dynamic_payload_handlers(void)
56{
57 register_dynamic_payload_handler(&mp4v_es_handler);
58 register_dynamic_payload_handler(&mpeg4_generic_handler);
59 register_dynamic_payload_handler(&ff_h264_dynamic_handler);
60}
61
62static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf, int len)
63{
64 if (buf[1] != 200)
65 return -1;
66 s->last_rtcp_ntp_time = AV_RB64(buf + 8);
67 if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE)
68 s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
69 s->last_rtcp_timestamp = AV_RB32(buf + 16);
70 return 0;
71}
72
73#define RTP_SEQ_MOD (1<<16)
74
75/**
76* called on parse open packet
77*/
78static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence) // called on parse open packet.
79{
80 memset(s, 0, sizeof(RTPStatistics));
81 s->max_seq= base_sequence;
82 s->probation= 1;
83}
84
85/**
86* called whenever there is a large jump in sequence numbers, or when they get out of probation...
87*/
88static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
89{
90 s->max_seq= seq;
91 s->cycles= 0;
92 s->base_seq= seq -1;
93 s->bad_seq= RTP_SEQ_MOD + 1;
94 s->received= 0;
95 s->expected_prior= 0;
96 s->received_prior= 0;
97 s->jitter= 0;
98 s->transit= 0;
99}
100
101/**
102* returns 1 if we should handle this packet.
103*/
104static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
105{
106 uint16_t udelta= seq - s->max_seq;
107 const int MAX_DROPOUT= 3000;
108 const int MAX_MISORDER = 100;
109 const int MIN_SEQUENTIAL = 2;
110
111 /* source not valid until MIN_SEQUENTIAL packets with sequence seq. numbers have been received */
112 if(s->probation)
113 {
114 if(seq==s->max_seq + 1) {
115 s->probation--;
116 s->max_seq= seq;
117 if(s->probation==0) {
118 rtp_init_sequence(s, seq);
119 s->received++;
120 return 1;
121 }
122 } else {
123 s->probation= MIN_SEQUENTIAL - 1;
124 s->max_seq = seq;
125 }
126 } else if (udelta < MAX_DROPOUT) {
127 // in order, with permissible gap
128 if(seq < s->max_seq) {
129 //sequence number wrapped; count antother 64k cycles
130 s->cycles += RTP_SEQ_MOD;
131 }
132 s->max_seq= seq;
133 } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
134 // sequence made a large jump...
135 if(seq==s->bad_seq) {
136 // two sequential packets-- assume that the other side restarted without telling us; just resync.
137 rtp_init_sequence(s, seq);
138 } else {
139 s->bad_seq= (seq + 1) & (RTP_SEQ_MOD-1);
140 return 0;
141 }
142 } else {
143 // duplicate or reordered packet...
144 }
145 s->received++;
146 return 1;
147}
148
149#if 0
150/**
151* This function is currently unused; without a valid local ntp time, I don't see how we could calculate the
152* difference between the arrival and sent timestamp. As a result, the jitter and transit statistics values
153* never change. I left this in in case someone else can see a way. (rdm)
154*/
155static void rtcp_update_jitter(RTPStatistics *s, uint32_t sent_timestamp, uint32_t arrival_timestamp)
156{
157 uint32_t transit= arrival_timestamp - sent_timestamp;
158 int d;
159 s->transit= transit;
160 d= FFABS(transit - s->transit);
161 s->jitter += d - ((s->jitter + 8)>>4);
162}
163#endif
164
165int rtp_check_and_send_back_rr(RTPDemuxContext *s, int count)
166{
167 ByteIOContext *pb;
168 uint8_t *buf;
169 int len;
170 int rtcp_bytes;
171 RTPStatistics *stats= &s->statistics;
172 uint32_t lost;
173 uint32_t extended_max;
174 uint32_t expected_interval;
175 uint32_t received_interval;
176 uint32_t lost_interval;
177 uint32_t expected;
178 uint32_t fraction;
179 uint64_t ntp_time= s->last_rtcp_ntp_time; // TODO: Get local ntp time?
180
181 if (!s->rtp_ctx || (count < 1))
182 return -1;
183
184 /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
185 /* XXX: mpeg pts hardcoded. RTCP send every 0.5 seconds */
186 s->octet_count += count;
187 rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
188 RTCP_TX_RATIO_DEN;
189 rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?
190 if (rtcp_bytes < 28)
191 return -1;
192 s->last_octet_count = s->octet_count;
193
194 if (url_open_dyn_buf(&pb) < 0)
195 return -1;
196
197 // Receiver Report
198 put_byte(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
199 put_byte(pb, 201);
200 put_be16(pb, 7); /* length in words - 1 */
201 put_be32(pb, s->ssrc); // our own SSRC
202 put_be32(pb, s->ssrc); // XXX: should be the server's here!
203 // some placeholders we should really fill...
204 // RFC 1889/p64
205 extended_max= stats->cycles + stats->max_seq;
206 expected= extended_max - stats->base_seq + 1;
207 lost= expected - stats->received;
208 lost= FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
209 expected_interval= expected - stats->expected_prior;
210 stats->expected_prior= expected;
211 received_interval= stats->received - stats->received_prior;
212 stats->received_prior= stats->received;
213 lost_interval= expected_interval - received_interval;
214 if (expected_interval==0 || lost_interval<=0) fraction= 0;
215 else fraction = (lost_interval<<8)/expected_interval;
216
217 fraction= (fraction<<24) | lost;
218
219 put_be32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
220 put_be32(pb, extended_max); /* max sequence received */
221 put_be32(pb, stats->jitter>>4); /* jitter */
222
223 if(s->last_rtcp_ntp_time==AV_NOPTS_VALUE)
224 {
225 put_be32(pb, 0); /* last SR timestamp */
226 put_be32(pb, 0); /* delay since last SR */
227 } else {
228 uint32_t middle_32_bits= s->last_rtcp_ntp_time>>16; // this is valid, right? do we need to handle 64 bit values special?
229 uint32_t delay_since_last= ntp_time - s->last_rtcp_ntp_time;
230
231 put_be32(pb, middle_32_bits); /* last SR timestamp */
232 put_be32(pb, delay_since_last); /* delay since last SR */
233 }
234
235 // CNAME
236 put_byte(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
237 put_byte(pb, 202);
238 len = strlen(s->hostname);
239 put_be16(pb, (6 + len + 3) / 4); /* length in words - 1 */
240 put_be32(pb, s->ssrc);
241 put_byte(pb, 0x01);
242 put_byte(pb, len);
243 put_buffer(pb, s->hostname, len);
244 // padding
245 for (len = (6 + len) % 4; len % 4; len++) {
246 put_byte(pb, 0);
247 }
248
249 put_flush_packet(pb);
250 len = url_close_dyn_buf(pb, &buf);
251 if ((len > 0) && buf) {
252 int result;
253 dprintf(s->ic, "sending %d bytes of RR\n", len);
254 result= url_write(s->rtp_ctx, buf, len);
255 dprintf(s->ic, "result from url_write: %d\n", result);
256 av_free(buf);
257 }
258 return 0;
259}
260
261/**
262 * open a new RTP parse context for stream 'st'. 'st' can be NULL for
263 * MPEG2TS streams to indicate that they should be demuxed inside the
264 * rtp demux (otherwise CODEC_ID_MPEG2TS packets are returned)
265 * TODO: change this to not take rtp_payload data, and use the new dynamic payload system.
266 */
267RTPDemuxContext *rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *rtpc, int payload_type, rtp_payload_data_t *rtp_payload_data)
268{
269 RTPDemuxContext *s;
270
271 s = av_mallocz(sizeof(RTPDemuxContext));
272 if (!s)
273 return NULL;
274 s->payload_type = payload_type;
275 s->last_rtcp_ntp_time = AV_NOPTS_VALUE;
276 s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
277 s->ic = s1;
278 s->st = st;
279 s->rtp_payload_data = rtp_payload_data;
280 rtp_init_statistics(&s->statistics, 0); // do we know the initial sequence from sdp?
281 av_set_pts_info(s->st, 32, 1, 90000);
282 if (!strcmp(ff_rtp_enc_name(payload_type), "MP2T")) {
283 s->ts = mpegts_parse_open(s->ic);
284 if (s->ts == NULL) {
285 av_free(s);
286 return NULL;
287 }
288 } else {
289 switch(st->codec->codec_id) {
290 case CODEC_ID_MPEG1VIDEO:
291 case CODEC_ID_MPEG2VIDEO:
292 case CODEC_ID_MP2:
293 case CODEC_ID_MP3:
294 case CODEC_ID_MPEG4:
295 case CODEC_ID_H264:
296 st->need_parsing = AVSTREAM_PARSE_FULL;
297 break;
298 default:
299 if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
300 av_set_pts_info(st, 32, 1, st->codec->sample_rate);
301 }
302 break;
303 }
304 }
305 // needed to send back RTCP RR in RTSP sessions
306 s->rtp_ctx = rtpc;
307 gethostname(s->hostname, sizeof(s->hostname));
308 return s;
309}
310
311static int rtp_parse_mp4_au(RTPDemuxContext *s, const uint8_t *buf)
312{
313 int au_headers_length, au_header_size, i;
314 GetBitContext getbitcontext;
315 rtp_payload_data_t *infos;
316
317 infos = s->rtp_payload_data;
318
319 if (infos == NULL)
320 return -1;
321
322 /* decode the first 2 bytes where the AUHeader sections are stored
323 length in bits */
324 au_headers_length = AV_RB16(buf);
325
326 if (au_headers_length > RTP_MAX_PACKET_LENGTH)
327 return -1;
328
329 infos->au_headers_length_bytes = (au_headers_length + 7) / 8;
330
331 /* skip AU headers length section (2 bytes) */
332 buf += 2;
333
334 init_get_bits(&getbitcontext, buf, infos->au_headers_length_bytes * 8);
335
336 /* XXX: Wrong if optionnal additional sections are present (cts, dts etc...) */
337 au_header_size = infos->sizelength + infos->indexlength;
338 if (au_header_size <= 0 || (au_headers_length % au_header_size != 0))
339 return -1;
340
341 infos->nb_au_headers = au_headers_length / au_header_size;
342 infos->au_headers = av_malloc(sizeof(struct AUHeaders) * infos->nb_au_headers);
343
344 /* XXX: We handle multiple AU Section as only one (need to fix this for interleaving)
345 In my test, the FAAD decoder does not behave correctly when sending each AU one by one
346 but does when sending the whole as one big packet... */
347 infos->au_headers[0].size = 0;
348 infos->au_headers[0].index = 0;
349 for (i = 0; i < infos->nb_au_headers; ++i) {
350 infos->au_headers[0].size += get_bits_long(&getbitcontext, infos->sizelength);
351 infos->au_headers[0].index = get_bits_long(&getbitcontext, infos->indexlength);
352 }
353
354 infos->nb_au_headers = 1;
355
356 return 0;
357}
358
359/**
360 * This was the second switch in rtp_parse packet. Normalizes time, if required, sets stream_index, etc.
361 */
362static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
363{
364 if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE) {
365 int64_t addend;
366 int delta_timestamp;
367
368 /* compute pts from timestamp with received ntp_time */
369 delta_timestamp = timestamp - s->last_rtcp_timestamp;
370 /* convert to the PTS timebase */
371 addend = av_rescale(s->last_rtcp_ntp_time - s->first_rtcp_ntp_time, s->st->time_base.den, (uint64_t)s->st->time_base.num << 32);
372 pkt->pts = addend + delta_timestamp;
373 }
374 pkt->stream_index = s->st->index;
375}
376
377/**
378 * Parse an RTP or RTCP packet directly sent as a buffer.
379 * @param s RTP parse context.
380 * @param pkt returned packet
381 * @param buf input buffer or NULL to read the next packets
382 * @param len buffer len
383 * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
384 * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
385 */
386int rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
387 const uint8_t *buf, int len)
388{
389 unsigned int ssrc, h;
390 int payload_type, seq, ret, flags = 0;
391 AVStream *st;
392 uint32_t timestamp;
393 int rv= 0;
394
395 if (!buf) {
396 /* return the next packets, if any */
397 if(s->st && s->parse_packet) {
398 timestamp= 0; ///< Should not be used if buf is NULL, but should be set to the timestamp of the packet returned....
399 rv= s->parse_packet(s, pkt, &timestamp, NULL, 0, flags);
400 finalize_packet(s, pkt, timestamp);
401 return rv;
402 } else {
403 // TODO: Move to a dynamic packet handler (like above)
404 if (s->read_buf_index >= s->read_buf_size)
405 return -1;
406 ret = mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
407 s->read_buf_size - s->read_buf_index);
408 if (ret < 0)
409 return -1;
410 s->read_buf_index += ret;
411 if (s->read_buf_index < s->read_buf_size)
412 return 1;
413 else
414 return 0;
415 }
416 }
417
418 if (len < 12)
419 return -1;
420
421 if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
422 return -1;
423 if (buf[1] >= 200 && buf[1] <= 204) {
424 rtcp_parse_packet(s, buf, len);
425 return -1;
426 }
427 payload_type = buf[1] & 0x7f;
428 seq = AV_RB16(buf + 2);
429 timestamp = AV_RB32(buf + 4);
430 ssrc = AV_RB32(buf + 8);
431 /* store the ssrc in the RTPDemuxContext */
432 s->ssrc = ssrc;
433
434 /* NOTE: we can handle only one payload type */
435 if (s->payload_type != payload_type)
436 return -1;
437
438 st = s->st;
439 // only do something with this if all the rtp checks pass...
440 if(!rtp_valid_packet_in_sequence(&s->statistics, seq))
441 {
442 av_log(st?st->codec:NULL, AV_LOG_ERROR, "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
443 payload_type, seq, ((s->seq + 1) & 0xffff));
444 return -1;
445 }
446
447 s->seq = seq;
448 len -= 12;
449 buf += 12;
450
451 if (!st) {
452 /* specific MPEG2TS demux support */
453 ret = mpegts_parse_packet(s->ts, pkt, buf, len);
454 if (ret < 0)
455 return -1;
456 if (ret < len) {
457 s->read_buf_size = len - ret;
458 memcpy(s->buf, buf + ret, s->read_buf_size);
459 s->read_buf_index = 0;
460 return 1;
461 }
462 } else if (s->parse_packet) {
463 rv = s->parse_packet(s, pkt, &timestamp, buf, len, flags);
464 } else {
465 // at this point, the RTP header has been stripped; This is ASSUMING that there is only 1 CSRC, which in't wise.
466 switch(st->codec->codec_id) {
467 case CODEC_ID_MP2:
468 /* better than nothing: skip mpeg audio RTP header */
469 if (len <= 4)
470 return -1;
471 h = AV_RB32(buf);
472 len -= 4;
473 buf += 4;
474 av_new_packet(pkt, len);
475 memcpy(pkt->data, buf, len);
476 break;
477 case CODEC_ID_MPEG1VIDEO:
478 case CODEC_ID_MPEG2VIDEO:
479 /* better than nothing: skip mpeg video RTP header */
480 if (len <= 4)
481 return -1;
482 h = AV_RB32(buf);
483 buf += 4;
484 len -= 4;
485 if (h & (1 << 26)) {
486 /* mpeg2 */
487 if (len <= 4)
488 return -1;
489 buf += 4;
490 len -= 4;
491 }
492 av_new_packet(pkt, len);
493 memcpy(pkt->data, buf, len);
494 break;
495 // moved from below, verbatim. this is because this section handles packets, and the lower switch handles
496 // timestamps.
497 // TODO: Put this into a dynamic packet handler...
498 case CODEC_ID_AAC:
499 if (rtp_parse_mp4_au(s, buf))
500 return -1;
501 {
502 rtp_payload_data_t *infos = s->rtp_payload_data;
503 if (infos == NULL)
504 return -1;
505 buf += infos->au_headers_length_bytes + 2;
506 len -= infos->au_headers_length_bytes + 2;
507
508 /* XXX: Fixme we only handle the case where rtp_parse_mp4_au define
509 one au_header */
510 av_new_packet(pkt, infos->au_headers[0].size);
511 memcpy(pkt->data, buf, infos->au_headers[0].size);
512 buf += infos->au_headers[0].size;
513 len -= infos->au_headers[0].size;
514 }
515 s->read_buf_size = len;
516 rv= 0;
517 break;
518 default:
519 av_new_packet(pkt, len);
520 memcpy(pkt->data, buf, len);
521 break;
522 }
523
524 // now perform timestamp things....
525 finalize_packet(s, pkt, timestamp);
526 }
527 return rv;
528}
529
530void rtp_parse_close(RTPDemuxContext *s)
531{
532 // TODO: fold this into the protocol specific data fields.
533 if (!strcmp(ff_rtp_enc_name(s->payload_type), "MP2T")) {
534 mpegts_parse_close(s->ts);
535 }
536 av_free(s);
537}
diff --git a/src/plugins/ffmpeg/libavformat/rtpenc.c b/src/plugins/ffmpeg/libavformat/rtpenc.c
deleted file mode 100644
index 2317f5c..0000000
--- a/src/plugins/ffmpeg/libavformat/rtpenc.c
+++ /dev/null
@@ -1,360 +0,0 @@
1/*
2 * RTP output format
3 * Copyright (c) 2002 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 "libavcodec/bitstream.h"
23#include "avformat.h"
24#include "mpegts.h"
25
26#include <unistd.h>
27#include "network.h"
28
29#include "rtp_internal.h"
30#include "rtp_mpv.h"
31#include "rtp_aac.h"
32#include "rtp_h264.h"
33
34//#define DEBUG
35
36#define RTCP_SR_SIZE 28
37#define NTP_OFFSET 2208988800ULL
38#define NTP_OFFSET_US (NTP_OFFSET * 1000000ULL)
39
40static uint64_t ntp_time(void)
41{
42 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
43}
44
45static int rtp_write_header(AVFormatContext *s1)
46{
47 RTPDemuxContext *s = s1->priv_data;
48 int payload_type, max_packet_size, n;
49 AVStream *st;
50
51 if (s1->nb_streams != 1)
52 return -1;
53 st = s1->streams[0];
54
55 payload_type = rtp_get_payload_type(st->codec);
56 if (payload_type < 0)
57 payload_type = RTP_PT_PRIVATE; /* private payload type */
58 s->payload_type = payload_type;
59
60// following 2 FIXMEs could be set based on the current time, there is normally no info leak, as RTP will likely be transmitted immediately
61 s->base_timestamp = 0; /* FIXME: was random(), what should this be? */
62 s->timestamp = s->base_timestamp;
63 s->cur_timestamp = 0;
64 s->ssrc = 0; /* FIXME: was random(), what should this be? */
65 s->first_packet = 1;
66 s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
67
68 max_packet_size = url_fget_max_packet_size(s1->pb);
69 if (max_packet_size <= 12)
70 return AVERROR(EIO);
71 s->max_payload_size = max_packet_size - 12;
72
73 s->max_frames_per_packet = 0;
74 if (s1->max_delay) {
75 if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
76 if (st->codec->frame_size == 0) {
77 av_log(s1, AV_LOG_ERROR, "Cannot respect max delay: frame size = 0\n");
78 } else {
79 s->max_frames_per_packet = av_rescale_rnd(s1->max_delay, st->codec->sample_rate, AV_TIME_BASE * st->codec->frame_size, AV_ROUND_DOWN);
80 }
81 }
82 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
83 /* FIXME: We should round down here... */
84 s->max_frames_per_packet = av_rescale_q(s1->max_delay, (AVRational){1, 1000000}, st->codec->time_base);
85 }
86 }
87
88 av_set_pts_info(st, 32, 1, 90000);
89 switch(st->codec->codec_id) {
90 case CODEC_ID_MP2:
91 case CODEC_ID_MP3:
92 s->buf_ptr = s->buf + 4;
93 break;
94 case CODEC_ID_MPEG1VIDEO:
95 case CODEC_ID_MPEG2VIDEO:
96 break;
97 case CODEC_ID_MPEG2TS:
98 n = s->max_payload_size / TS_PACKET_SIZE;
99 if (n < 1)
100 n = 1;
101 s->max_payload_size = n * TS_PACKET_SIZE;
102 s->buf_ptr = s->buf;
103 break;
104 case CODEC_ID_AAC:
105 s->read_buf_index = 0;
106 default:
107 if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
108 av_set_pts_info(st, 32, 1, st->codec->sample_rate);
109 }
110 s->buf_ptr = s->buf;
111 break;
112 }
113
114 return 0;
115}
116
117/* send an rtcp sender report packet */
118static void rtcp_send_sr(AVFormatContext *s1, int64_t ntp_time)
119{
120 RTPDemuxContext *s = s1->priv_data;
121 uint32_t rtp_ts;
122
123 dprintf(s1, "RTCP: %02x %"PRIx64" %x\n", s->payload_type, ntp_time, s->timestamp);
124
125 if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE) s->first_rtcp_ntp_time = ntp_time;
126 s->last_rtcp_ntp_time = ntp_time;
127 rtp_ts = av_rescale_q(ntp_time - s->first_rtcp_ntp_time, (AVRational){1, 1000000},
128 s1->streams[0]->time_base) + s->base_timestamp;
129 put_byte(s1->pb, (RTP_VERSION << 6));
130 put_byte(s1->pb, 200);
131 put_be16(s1->pb, 6); /* length in words - 1 */
132 put_be32(s1->pb, s->ssrc);
133 put_be32(s1->pb, ntp_time / 1000000);
134 put_be32(s1->pb, ((ntp_time % 1000000) << 32) / 1000000);
135 put_be32(s1->pb, rtp_ts);
136 put_be32(s1->pb, s->packet_count);
137 put_be32(s1->pb, s->octet_count);
138 put_flush_packet(s1->pb);
139}
140
141/* send an rtp packet. sequence number is incremented, but the caller
142 must update the timestamp itself */
143void ff_rtp_send_data(AVFormatContext *s1, const uint8_t *buf1, int len, int m)
144{
145 RTPDemuxContext *s = s1->priv_data;
146
147 dprintf(s1, "rtp_send_data size=%d\n", len);
148
149 /* build the RTP header */
150 put_byte(s1->pb, (RTP_VERSION << 6));
151 put_byte(s1->pb, (s->payload_type & 0x7f) | ((m & 0x01) << 7));
152 put_be16(s1->pb, s->seq);
153 put_be32(s1->pb, s->timestamp);
154 put_be32(s1->pb, s->ssrc);
155
156 put_buffer(s1->pb, buf1, len);
157 put_flush_packet(s1->pb);
158
159 s->seq++;
160 s->octet_count += len;
161 s->packet_count++;
162}
163
164/* send an integer number of samples and compute time stamp and fill
165 the rtp send buffer before sending. */
166static void rtp_send_samples(AVFormatContext *s1,
167 const uint8_t *buf1, int size, int sample_size)
168{
169 RTPDemuxContext *s = s1->priv_data;
170 int len, max_packet_size, n;
171
172 max_packet_size = (s->max_payload_size / sample_size) * sample_size;
173 /* not needed, but who nows */
174 if ((size % sample_size) != 0)
175 av_abort();
176 n = 0;
177 while (size > 0) {
178 s->buf_ptr = s->buf;
179 len = FFMIN(max_packet_size, size);
180
181 /* copy data */
182 memcpy(s->buf_ptr, buf1, len);
183 s->buf_ptr += len;
184 buf1 += len;
185 size -= len;
186 s->timestamp = s->cur_timestamp + n / sample_size;
187 ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 0);
188 n += (s->buf_ptr - s->buf);
189 }
190}
191
192/* NOTE: we suppose that exactly one frame is given as argument here */
193/* XXX: test it */
194static void rtp_send_mpegaudio(AVFormatContext *s1,
195 const uint8_t *buf1, int size)
196{
197 RTPDemuxContext *s = s1->priv_data;
198 int len, count, max_packet_size;
199
200 max_packet_size = s->max_payload_size;
201
202 /* test if we must flush because not enough space */
203 len = (s->buf_ptr - s->buf);
204 if ((len + size) > max_packet_size) {
205 if (len > 4) {
206 ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 0);
207 s->buf_ptr = s->buf + 4;
208 }
209 }
210 if (s->buf_ptr == s->buf + 4) {
211 s->timestamp = s->cur_timestamp;
212 }
213
214 /* add the packet */
215 if (size > max_packet_size) {
216 /* big packet: fragment */
217 count = 0;
218 while (size > 0) {
219 len = max_packet_size - 4;
220 if (len > size)
221 len = size;
222 /* build fragmented packet */
223 s->buf[0] = 0;
224 s->buf[1] = 0;
225 s->buf[2] = count >> 8;
226 s->buf[3] = count;
227 memcpy(s->buf + 4, buf1, len);
228 ff_rtp_send_data(s1, s->buf, len + 4, 0);
229 size -= len;
230 buf1 += len;
231 count += len;
232 }
233 } else {
234 if (s->buf_ptr == s->buf + 4) {
235 /* no fragmentation possible */
236 s->buf[0] = 0;
237 s->buf[1] = 0;
238 s->buf[2] = 0;
239 s->buf[3] = 0;
240 }
241 memcpy(s->buf_ptr, buf1, size);
242 s->buf_ptr += size;
243 }
244}
245
246static void rtp_send_raw(AVFormatContext *s1,
247 const uint8_t *buf1, int size)
248{
249 RTPDemuxContext *s = s1->priv_data;
250 int len, max_packet_size;
251
252 max_packet_size = s->max_payload_size;
253
254 while (size > 0) {
255 len = max_packet_size;
256 if (len > size)
257 len = size;
258
259 s->timestamp = s->cur_timestamp;
260 ff_rtp_send_data(s1, buf1, len, (len == size));
261
262 buf1 += len;
263 size -= len;
264 }
265}
266
267/* NOTE: size is assumed to be an integer multiple of TS_PACKET_SIZE */
268static void rtp_send_mpegts_raw(AVFormatContext *s1,
269 const uint8_t *buf1, int size)
270{
271 RTPDemuxContext *s = s1->priv_data;
272 int len, out_len;
273
274 while (size >= TS_PACKET_SIZE) {
275 len = s->max_payload_size - (s->buf_ptr - s->buf);
276 if (len > size)
277 len = size;
278 memcpy(s->buf_ptr, buf1, len);
279 buf1 += len;
280 size -= len;
281 s->buf_ptr += len;
282
283 out_len = s->buf_ptr - s->buf;
284 if (out_len >= s->max_payload_size) {
285 ff_rtp_send_data(s1, s->buf, out_len, 0);
286 s->buf_ptr = s->buf;
287 }
288 }
289}
290
291/* write an RTP packet. 'buf1' must contain a single specific frame. */
292static int rtp_write_packet(AVFormatContext *s1, AVPacket *pkt)
293{
294 RTPDemuxContext *s = s1->priv_data;
295 AVStream *st = s1->streams[0];
296 int rtcp_bytes;
297 int size= pkt->size;
298 uint8_t *buf1= pkt->data;
299
300 dprintf(s1, "%d: write len=%d\n", pkt->stream_index, size);
301
302 rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
303 RTCP_TX_RATIO_DEN;
304 if (s->first_packet || ((rtcp_bytes >= RTCP_SR_SIZE) &&
305 (ntp_time() - s->last_rtcp_ntp_time > 5000000))) {
306 rtcp_send_sr(s1, ntp_time());
307 s->last_octet_count = s->octet_count;
308 s->first_packet = 0;
309 }
310 s->cur_timestamp = s->base_timestamp + pkt->pts;
311
312 switch(st->codec->codec_id) {
313 case CODEC_ID_PCM_MULAW:
314 case CODEC_ID_PCM_ALAW:
315 case CODEC_ID_PCM_U8:
316 case CODEC_ID_PCM_S8:
317 rtp_send_samples(s1, buf1, size, 1 * st->codec->channels);
318 break;
319 case CODEC_ID_PCM_U16BE:
320 case CODEC_ID_PCM_U16LE:
321 case CODEC_ID_PCM_S16BE:
322 case CODEC_ID_PCM_S16LE:
323 rtp_send_samples(s1, buf1, size, 2 * st->codec->channels);
324 break;
325 case CODEC_ID_MP2:
326 case CODEC_ID_MP3:
327 rtp_send_mpegaudio(s1, buf1, size);
328 break;
329 case CODEC_ID_MPEG1VIDEO:
330 case CODEC_ID_MPEG2VIDEO:
331 ff_rtp_send_mpegvideo(s1, buf1, size);
332 break;
333 case CODEC_ID_AAC:
334 ff_rtp_send_aac(s1, buf1, size);
335 break;
336 case CODEC_ID_MPEG2TS:
337 rtp_send_mpegts_raw(s1, buf1, size);
338 break;
339 case CODEC_ID_H264:
340 ff_rtp_send_h264(s1, buf1, size);
341 break;
342 default:
343 /* better than nothing : send the codec raw data */
344 rtp_send_raw(s1, buf1, size);
345 break;
346 }
347 return 0;
348}
349
350AVOutputFormat rtp_muxer = {
351 "rtp",
352 NULL_IF_CONFIG_SMALL("RTP output format"),
353 NULL,
354 NULL,
355 sizeof(RTPDemuxContext),
356 CODEC_ID_PCM_MULAW,
357 CODEC_ID_NONE,
358 rtp_write_header,
359 rtp_write_packet,
360};
diff --git a/src/plugins/ffmpeg/libavformat/rtpenc_h264.c b/src/plugins/ffmpeg/libavformat/rtpenc_h264.c
deleted file mode 100644
index 95d5fff..0000000
--- a/src/plugins/ffmpeg/libavformat/rtpenc_h264.c
+++ /dev/null
@@ -1,78 +0,0 @@
1/*
2 * RTP packetization for H.264 (RFC3984)
3 * Copyright (c) 2008 Luca Abeni.
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/**
23 * @file rtpenc_h264.c
24 * @brief H.264 packetization
25 * @author Luca Abeni <lucabe72@email.it>
26 */
27
28#include "avformat.h"
29#include "avc.h"
30#include "rtp_h264.h"
31
32static void nal_send(AVFormatContext *s1, const uint8_t *buf, int size, int last)
33{
34 RTPDemuxContext *s = s1->priv_data;
35
36 av_log(s1, AV_LOG_DEBUG, "Sending NAL %x of len %d M=%d\n", buf[0] & 0x1F, size, last);
37 if (size <= s->max_payload_size) {
38 ff_rtp_send_data(s1, buf, size, last);
39 } else {
40 uint8_t type = buf[0] & 0x1F;
41 uint8_t nri = buf[0] & 0x60;
42
43 av_log(s1, AV_LOG_DEBUG, "NAL size %d > %d\n", size, s->max_payload_size);
44 s->buf[0] = 28; /* FU Indicator; Type = 28 ---> FU-A */
45 s->buf[0] |= nri;
46 s->buf[1] = type;
47 s->buf[1] |= 1 << 7;
48 buf += 1;
49 size -= 1;
50 while (size + 2 > s->max_payload_size) {
51 memcpy(&s->buf[2], buf, s->max_payload_size - 2);
52 ff_rtp_send_data(s1, s->buf, s->max_payload_size, 0);
53 buf += s->max_payload_size - 2;
54 size -= s->max_payload_size - 2;
55 s->buf[1] &= ~(1 << 7);
56 }
57 s->buf[1] |= 1 << 6;
58 memcpy(&s->buf[2], buf, size);
59 ff_rtp_send_data(s1, s->buf, size + 2, 1);
60 }
61}
62
63void ff_rtp_send_h264(AVFormatContext *s1, const uint8_t *buf1, int size)
64{
65 const uint8_t *r;
66 RTPDemuxContext *s = s1->priv_data;
67
68 s->timestamp = s->cur_timestamp;
69 r = ff_avc_find_startcode(buf1, buf1 + size);
70 while (r < buf1 + size) {
71 const uint8_t *r1;
72
73 while(!*(r++));
74 r1 = ff_avc_find_startcode(r, buf1 + size);
75 nal_send(s1, r, r1 - r, (r1 == buf1 + size));
76 r = r1;
77 }
78}
diff --git a/src/plugins/ffmpeg/libavformat/rtpproto.c b/src/plugins/ffmpeg/libavformat/rtpproto.c
deleted file mode 100644
index 99fae3a..0000000
--- a/src/plugins/ffmpeg/libavformat/rtpproto.c
+++ /dev/null
@@ -1,317 +0,0 @@
1/*
2 * RTP network protocol
3 * Copyright (c) 2002 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/**
23 * @file rtpproto.c
24 * RTP protocol
25 */
26
27#include "libavutil/avstring.h"
28#include "avformat.h"
29
30#include <unistd.h>
31#include <stdarg.h>
32#include "network.h"
33#include "os_support.h"
34#include <fcntl.h>
35
36#define RTP_TX_BUF_SIZE (64 * 1024)
37#define RTP_RX_BUF_SIZE (128 * 1024)
38
39typedef struct RTPContext {
40 URLContext *rtp_hd, *rtcp_hd;
41 int rtp_fd, rtcp_fd;
42} RTPContext;
43
44/**
45 * If no filename is given to av_open_input_file because you want to
46 * get the local port first, then you must call this function to set
47 * the remote server address.
48 *
49 * @param s1 media file context
50 * @param uri of the remote server
51 * @return zero if no error.
52 */
53
54int rtp_set_remote_url(URLContext *h, const char *uri)
55{
56 RTPContext *s = h->priv_data;
57 char hostname[256];
58 int port;
59
60 char buf[1024];
61 char path[1024];
62
63 url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port,
64 path, sizeof(path), uri);
65
66 snprintf(buf, sizeof(buf), "udp://%s:%d%s", hostname, port, path);
67 udp_set_remote_url(s->rtp_hd, buf);
68
69 snprintf(buf, sizeof(buf), "udp://%s:%d%s", hostname, port + 1, path);
70 udp_set_remote_url(s->rtcp_hd, buf);
71 return 0;
72}
73
74
75/**
76 * add option to url of the form:
77 * "http://host:port/path?option1=val1&option2=val2...
78 */
79
80static void url_add_option(char *buf, int buf_size, const char *fmt, ...)
81{
82 char buf1[1024];
83 va_list ap;
84
85 va_start(ap, fmt);
86 if (strchr(buf, '?'))
87 av_strlcat(buf, "&", buf_size);
88 else
89 av_strlcat(buf, "?", buf_size);
90 vsnprintf(buf1, sizeof(buf1), fmt, ap);
91 av_strlcat(buf, buf1, buf_size);
92 va_end(ap);
93}
94
95static void build_udp_url(char *buf, int buf_size,
96 const char *hostname, int port,
97 int local_port, int ttl,
98 int max_packet_size)
99{
100 snprintf(buf, buf_size, "udp://%s:%d", hostname, port);
101 if (local_port >= 0)
102 url_add_option(buf, buf_size, "localport=%d", local_port);
103 if (ttl >= 0)
104 url_add_option(buf, buf_size, "ttl=%d", ttl);
105 if (max_packet_size >=0)
106 url_add_option(buf, buf_size, "pkt_size=%d", max_packet_size);
107}
108
109/**
110 * url syntax: rtp://host:port[?option=val...]
111 * option: 'ttl=n' : set the ttl value (for multicast only)
112 * 'localport=n' : set the local port to n
113 * 'pkt_size=n' : set max packet size
114 *
115 */
116
117static int rtp_open(URLContext *h, const char *uri, int flags)
118{
119 RTPContext *s;
120 int port, is_output, ttl, local_port, max_packet_size;
121 char hostname[256];
122 char buf[1024];
123 char path[1024];
124 const char *p;
125
126 is_output = (flags & URL_WRONLY);
127
128 s = av_mallocz(sizeof(RTPContext));
129 if (!s)
130 return AVERROR(ENOMEM);
131 h->priv_data = s;
132
133 url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port,
134 path, sizeof(path), uri);
135 /* extract parameters */
136 ttl = -1;
137 local_port = -1;
138 max_packet_size = -1;
139
140 p = strchr(uri, '?');
141 if (p) {
142 if (find_info_tag(buf, sizeof(buf), "ttl", p)) {
143 ttl = strtol(buf, NULL, 10);
144 }
145 if (find_info_tag(buf, sizeof(buf), "localport", p)) {
146 local_port = strtol(buf, NULL, 10);
147 }
148 if (find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
149 max_packet_size = strtol(buf, NULL, 10);
150 }
151 }
152
153 build_udp_url(buf, sizeof(buf),
154 hostname, port, local_port, ttl, max_packet_size);
155 if (url_open(&s->rtp_hd, buf, flags) < 0)
156 goto fail;
157 local_port = udp_get_local_port(s->rtp_hd);
158 /* XXX: need to open another connection if the port is not even */
159
160 /* well, should suppress localport in path */
161
162 build_udp_url(buf, sizeof(buf),
163 hostname, port + 1, local_port + 1, ttl, max_packet_size);
164 if (url_open(&s->rtcp_hd, buf, flags) < 0)
165 goto fail;
166
167 /* just to ease handle access. XXX: need to suppress direct handle
168 access */
169 s->rtp_fd = udp_get_file_handle(s->rtp_hd);
170 s->rtcp_fd = udp_get_file_handle(s->rtcp_hd);
171
172 h->max_packet_size = url_get_max_packet_size(s->rtp_hd);
173 h->is_streamed = 1;
174 return 0;
175
176 fail:
177 if (s->rtp_hd)
178 url_close(s->rtp_hd);
179 if (s->rtcp_hd)
180 url_close(s->rtcp_hd);
181 av_free(s);
182 return AVERROR(EIO);
183}
184
185static int rtp_read(URLContext *h, uint8_t *buf, int size)
186{
187 RTPContext *s = h->priv_data;
188 struct sockaddr_in from;
189 socklen_t from_len;
190 int len, fd_max, n;
191 fd_set rfds;
192#if 0
193 for(;;) {
194 from_len = sizeof(from);
195 len = recvfrom (s->rtp_fd, buf, size, 0,
196 (struct sockaddr *)&from, &from_len);
197 if (len < 0) {
198 if (ff_neterrno() == FF_NETERROR(EAGAIN) ||
199 ff_neterrno() == FF_NETERROR(EINTR))
200 continue;
201 return AVERROR(EIO);
202 }
203 break;
204 }
205#else
206 for(;;) {
207 /* build fdset to listen to RTP and RTCP packets */
208 FD_ZERO(&rfds);
209 fd_max = s->rtp_fd;
210 FD_SET(s->rtp_fd, &rfds);
211 if (s->rtcp_fd > fd_max)
212 fd_max = s->rtcp_fd;
213 FD_SET(s->rtcp_fd, &rfds);
214 n = select(fd_max + 1, &rfds, NULL, NULL, NULL);
215 if (n > 0) {
216 /* first try RTCP */
217 if (FD_ISSET(s->rtcp_fd, &rfds)) {
218 from_len = sizeof(from);
219 len = recvfrom (s->rtcp_fd, buf, size, 0,
220 (struct sockaddr *)&from, &from_len);
221 if (len < 0) {
222 if (ff_neterrno() == FF_NETERROR(EAGAIN) ||
223 ff_neterrno() == FF_NETERROR(EINTR))
224 continue;
225 return AVERROR(EIO);
226 }
227 break;
228 }
229 /* then RTP */
230 if (FD_ISSET(s->rtp_fd, &rfds)) {
231 from_len = sizeof(from);
232 len = recvfrom (s->rtp_fd, buf, size, 0,
233 (struct sockaddr *)&from, &from_len);
234 if (len < 0) {
235 if (ff_neterrno() == FF_NETERROR(EAGAIN) ||
236 ff_neterrno() == FF_NETERROR(EINTR))
237 continue;
238 return AVERROR(EIO);
239 }
240 break;
241 }
242 }
243 }
244#endif
245 return len;
246}
247
248static int rtp_write(URLContext *h, uint8_t *buf, int size)
249{
250 RTPContext *s = h->priv_data;
251 int ret;
252 URLContext *hd;
253
254 if (buf[1] >= 200 && buf[1] <= 204) {
255 /* RTCP payload type */
256 hd = s->rtcp_hd;
257 } else {
258 /* RTP payload type */
259 hd = s->rtp_hd;
260 }
261
262 ret = url_write(hd, buf, size);
263#if 0
264 {
265 struct timespec ts;
266 ts.tv_sec = 0;
267 ts.tv_nsec = 10 * 1000000;
268 nanosleep(&ts, NULL);
269 }
270#endif
271 return ret;
272}
273
274static int rtp_close(URLContext *h)
275{
276 RTPContext *s = h->priv_data;
277
278 url_close(s->rtp_hd);
279 url_close(s->rtcp_hd);
280 av_free(s);
281 return 0;
282}
283
284/**
285 * Return the local port used by the RTP connection
286 * @param s1 media file context
287 * @return the local port number
288 */
289
290int rtp_get_local_port(URLContext *h)
291{
292 RTPContext *s = h->priv_data;
293 return udp_get_local_port(s->rtp_hd);
294}
295
296/**
297 * Return the rtp and rtcp file handles for select() usage to wait for
298 * several RTP streams at the same time.
299 * @param h media file context
300 */
301
302void rtp_get_file_handles(URLContext *h, int *prtp_fd, int *prtcp_fd)
303{
304 RTPContext *s = h->priv_data;
305
306 *prtp_fd = s->rtp_fd;
307 *prtcp_fd = s->rtcp_fd;
308}
309
310URLProtocol rtp_protocol = {
311 "rtp",
312 rtp_open,
313 rtp_read,
314 rtp_write,
315 NULL, /* seek */
316 rtp_close,
317};
diff --git a/src/plugins/ffmpeg/libavformat/rtsp.c b/src/plugins/ffmpeg/libavformat/rtsp.c
deleted file mode 100644
index 79fa4e1..0000000
--- a/src/plugins/ffmpeg/libavformat/rtsp.c
+++ /dev/null
@@ -1,1538 +0,0 @@
1/*
2 * RTSP/SDP client
3 * Copyright (c) 2002 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/avstring.h"
23#include "avformat.h"
24
25#include <sys/time.h>
26#include <unistd.h> /* for select() prototype */
27#include "network.h"
28#include "rtsp.h"
29
30#include "rtp_internal.h"
31
32//#define DEBUG
33//#define DEBUG_RTP_TCP
34
35enum RTSPClientState {
36 RTSP_STATE_IDLE,
37 RTSP_STATE_PLAYING,
38 RTSP_STATE_PAUSED,
39};
40
41typedef struct RTSPState {
42 URLContext *rtsp_hd; /* RTSP TCP connexion handle */
43 int nb_rtsp_streams;
44 struct RTSPStream **rtsp_streams;
45
46 enum RTSPClientState state;
47 int64_t seek_timestamp;
48
49 /* XXX: currently we use unbuffered input */
50 // ByteIOContext rtsp_gb;
51 int seq; /* RTSP command sequence number */
52 char session_id[512];
53 enum RTSPProtocol protocol;
54 char last_reply[2048]; /* XXX: allocate ? */
55 RTPDemuxContext *cur_rtp;
56} RTSPState;
57
58typedef struct RTSPStream {
59 URLContext *rtp_handle; /* RTP stream handle */
60 RTPDemuxContext *rtp_ctx; /* RTP parse context */
61
62 int stream_index; /* corresponding stream index, if any. -1 if none (MPEG2TS case) */
63 int interleaved_min, interleaved_max; /* interleave ids, if TCP transport */
64 char control_url[1024]; /* url for this stream (from SDP) */
65
66 int sdp_port; /* port (from SDP content - not used in RTSP) */
67 struct in_addr sdp_ip; /* IP address (from SDP content - not used in RTSP) */
68 int sdp_ttl; /* IP TTL (from SDP content - not used in RTSP) */
69 int sdp_payload_type; /* payload type - only used in SDP */
70 rtp_payload_data_t rtp_payload_data; /* rtp payload parsing infos from SDP */
71
72 RTPDynamicProtocolHandler *dynamic_handler; ///< Only valid if it's a dynamic protocol. (This is the handler structure)
73 void *dynamic_protocol_context; ///< Only valid if it's a dynamic protocol. (This is any private data associated with the dynamic protocol)
74} RTSPStream;
75
76static int rtsp_read_play(AVFormatContext *s);
77
78/* XXX: currently, the only way to change the protocols consists in
79 changing this variable */
80
81#if LIBAVFORMAT_VERSION_INT < (53 << 16)
82int rtsp_default_protocols = (1 << RTSP_PROTOCOL_RTP_UDP);
83#endif
84
85static int rtsp_probe(AVProbeData *p)
86{
87 if (av_strstart(p->filename, "rtsp:", NULL))
88 return AVPROBE_SCORE_MAX;
89 return 0;
90}
91
92static int redir_isspace(int c)
93{
94 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
95}
96
97static void skip_spaces(const char **pp)
98{
99 const char *p;
100 p = *pp;
101 while (redir_isspace(*p))
102 p++;
103 *pp = p;
104}
105
106static void get_word_sep(char *buf, int buf_size, const char *sep,
107 const char **pp)
108{
109 const char *p;
110 char *q;
111
112 p = *pp;
113 if (*p == '/')
114 p++;
115 skip_spaces(&p);
116 q = buf;
117 while (!strchr(sep, *p) && *p != '\0') {
118 if ((q - buf) < buf_size - 1)
119 *q++ = *p;
120 p++;
121 }
122 if (buf_size > 0)
123 *q = '\0';
124 *pp = p;
125}
126
127static void get_word(char *buf, int buf_size, const char **pp)
128{
129 const char *p;
130 char *q;
131
132 p = *pp;
133 skip_spaces(&p);
134 q = buf;
135 while (!redir_isspace(*p) && *p != '\0') {
136 if ((q - buf) < buf_size - 1)
137 *q++ = *p;
138 p++;
139 }
140 if (buf_size > 0)
141 *q = '\0';
142 *pp = p;
143}
144
145/* parse the rtpmap description: <codec_name>/<clock_rate>[/<other
146 params>] */
147static int sdp_parse_rtpmap(AVCodecContext *codec, RTSPStream *rtsp_st, int payload_type, const char *p)
148{
149 char buf[256];
150 int i;
151 AVCodec *c;
152 const char *c_name;
153
154 /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
155 see if we can handle this kind of payload */
156 get_word_sep(buf, sizeof(buf), "/", &p);
157 if (payload_type >= RTP_PT_PRIVATE) {
158 RTPDynamicProtocolHandler *handler= RTPFirstDynamicPayloadHandler;
159 while(handler) {
160 if (!strcmp(buf, handler->enc_name) && (codec->codec_type == handler->codec_type)) {
161 codec->codec_id = handler->codec_id;
162 rtsp_st->dynamic_handler= handler;
163 if(handler->open) {
164 rtsp_st->dynamic_protocol_context= handler->open();
165 }
166 break;
167 }
168 handler= handler->next;
169 }
170 } else {
171 /* We are in a standard case ( from http://www.iana.org/assignments/rtp-parameters) */
172 /* search into AVRtpPayloadTypes[] */
173 codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
174 }
175
176 c = avcodec_find_decoder(codec->codec_id);
177 if (c && c->name)
178 c_name = c->name;
179 else
180 c_name = (char *)NULL;
181
182 if (c_name) {
183 get_word_sep(buf, sizeof(buf), "/", &p);
184 i = atoi(buf);
185 switch (codec->codec_type) {
186 case CODEC_TYPE_AUDIO:
187 av_log(codec, AV_LOG_DEBUG, " audio codec set to : %s\n", c_name);
188 codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
189 codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
190 if (i > 0) {
191 codec->sample_rate = i;
192 get_word_sep(buf, sizeof(buf), "/", &p);
193 i = atoi(buf);
194 if (i > 0)
195 codec->channels = i;
196 // TODO: there is a bug here; if it is a mono stream, and less than 22000Hz, faad upconverts to stereo and twice the
197 // frequency. No problem, but the sample rate is being set here by the sdp line. Upcoming patch forthcoming. (rdm)
198 }
199 av_log(codec, AV_LOG_DEBUG, " audio samplerate set to : %i\n", codec->sample_rate);
200 av_log(codec, AV_LOG_DEBUG, " audio channels set to : %i\n", codec->channels);
201 break;
202 case CODEC_TYPE_VIDEO:
203 av_log(codec, AV_LOG_DEBUG, " video codec set to : %s\n", c_name);
204 break;
205 default:
206 break;
207 }
208 return 0;
209 }
210
211 return -1;
212}
213
214/* return the length and optionnaly the data */
215static int hex_to_data(uint8_t *data, const char *p)
216{
217 int c, len, v;
218
219 len = 0;
220 v = 1;
221 for(;;) {
222 skip_spaces(&p);
223 if (p == '\0')
224 break;
225 c = toupper((unsigned char)*p++);
226 if (c >= '0' && c <= '9')
227 c = c - '0';
228 else if (c >= 'A' && c <= 'F')
229 c = c - 'A' + 10;
230 else
231 break;
232 v = (v << 4) | c;
233 if (v & 0x100) {
234 if (data)
235 data[len] = v;
236 len++;
237 v = 1;
238 }
239 }
240 return len;
241}
242
243static void sdp_parse_fmtp_config(AVCodecContext *codec, char *attr, char *value)
244{
245 switch (codec->codec_id) {
246 case CODEC_ID_MPEG4:
247 case CODEC_ID_AAC:
248 if (!strcmp(attr, "config")) {
249 /* decode the hexa encoded parameter */
250 int len = hex_to_data(NULL, value);
251 codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
252 if (!codec->extradata)
253 return;
254 codec->extradata_size = len;
255 hex_to_data(codec->extradata, value);
256 }
257 break;
258 default:
259 break;
260 }
261 return;
262}
263
264typedef struct attrname_map
265{
266 const char *str;
267 uint16_t type;
268 uint32_t offset;
269} attrname_map_t;
270
271/* All known fmtp parmeters and the corresping RTPAttrTypeEnum */
272#define ATTR_NAME_TYPE_INT 0
273#define ATTR_NAME_TYPE_STR 1
274static attrname_map_t attr_names[]=
275{
276 {"SizeLength", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, sizelength)},
277 {"IndexLength", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, indexlength)},
278 {"IndexDeltaLength", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, indexdeltalength)},
279 {"profile-level-id", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, profile_level_id)},
280 {"StreamType", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, streamtype)},
281 {"mode", ATTR_NAME_TYPE_STR, offsetof(rtp_payload_data_t, mode)},
282 {NULL, -1, -1},
283};
284
285/** parse the attribute line from the fmtp a line of an sdp resonse. This is broken out as a function
286* because it is used in rtp_h264.c, which is forthcoming.
287*/
288int rtsp_next_attr_and_value(const char **p, char *attr, int attr_size, char *value, int value_size)
289{
290 skip_spaces(p);
291 if(**p)
292 {
293 get_word_sep(attr, attr_size, "=", p);
294 if (**p == '=')
295 (*p)++;
296 get_word_sep(value, value_size, ";", p);
297 if (**p == ';')
298 (*p)++;
299 return 1;
300 }
301 return 0;
302}
303
304/* parse a SDP line and save stream attributes */
305static void sdp_parse_fmtp(AVStream *st, const char *p)
306{
307 char attr[256];
308 char value[4096];
309 int i;
310
311 RTSPStream *rtsp_st = st->priv_data;
312 AVCodecContext *codec = st->codec;
313 rtp_payload_data_t *rtp_payload_data = &rtsp_st->rtp_payload_data;
314
315 /* loop on each attribute */
316 while(rtsp_next_attr_and_value(&p, attr, sizeof(attr), value, sizeof(value)))
317 {
318 /* grab the codec extra_data from the config parameter of the fmtp line */
319 sdp_parse_fmtp_config(codec, attr, value);
320 /* Looking for a known attribute */
321 for (i = 0; attr_names[i].str; ++i) {
322 if (!strcasecmp(attr, attr_names[i].str)) {
323 if (attr_names[i].type == ATTR_NAME_TYPE_INT)
324 *(int *)((char *)rtp_payload_data + attr_names[i].offset) = atoi(value);
325 else if (attr_names[i].type == ATTR_NAME_TYPE_STR)
326 *(char **)((char *)rtp_payload_data + attr_names[i].offset) = av_strdup(value);
327 }
328 }
329 }
330}
331
332/** Parse a string \p in the form of Range:npt=xx-xx, and determine the start
333 * and end time.
334 * Used for seeking in the rtp stream.
335 */
336static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
337{
338 char buf[256];
339
340 skip_spaces(&p);
341 if (!av_stristart(p, "npt=", &p))
342 return;
343
344 *start = AV_NOPTS_VALUE;
345 *end = AV_NOPTS_VALUE;
346
347 get_word_sep(buf, sizeof(buf), "-", &p);
348 *start = parse_date(buf, 1);
349 if (*p == '-') {
350 p++;
351 get_word_sep(buf, sizeof(buf), "-", &p);
352 *end = parse_date(buf, 1);
353 }
354// av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
355// av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
356}
357
358typedef struct SDPParseState {
359 /* SDP only */
360 struct in_addr default_ip;
361 int default_ttl;
362} SDPParseState;
363
364static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
365 int letter, const char *buf)
366{
367 RTSPState *rt = s->priv_data;
368 char buf1[64], st_type[64];
369 const char *p;
370 int codec_type, payload_type, i;
371 AVStream *st;
372 RTSPStream *rtsp_st;
373 struct in_addr sdp_ip;
374 int ttl;
375
376#ifdef DEBUG
377 printf("sdp: %c='%s'\n", letter, buf);
378#endif
379
380 p = buf;
381 switch(letter) {
382 case 'c':
383 get_word(buf1, sizeof(buf1), &p);
384 if (strcmp(buf1, "IN") != 0)
385 return;
386 get_word(buf1, sizeof(buf1), &p);
387 if (strcmp(buf1, "IP4") != 0)
388 return;
389 get_word_sep(buf1, sizeof(buf1), "/", &p);
390 if (inet_aton(buf1, &sdp_ip) == 0)
391 return;
392 ttl = 16;
393 if (*p == '/') {
394 p++;
395 get_word_sep(buf1, sizeof(buf1), "/", &p);
396 ttl = atoi(buf1);
397 }
398 if (s->nb_streams == 0) {
399 s1->default_ip = sdp_ip;
400 s1->default_ttl = ttl;
401 } else {
402 st = s->streams[s->nb_streams - 1];
403 rtsp_st = st->priv_data;
404 rtsp_st->sdp_ip = sdp_ip;
405 rtsp_st->sdp_ttl = ttl;
406 }
407 break;
408 case 's':
409 av_strlcpy(s->title, p, sizeof(s->title));
410 break;
411 case 'i':
412 if (s->nb_streams == 0) {
413 av_strlcpy(s->comment, p, sizeof(s->comment));
414 break;
415 }
416 break;
417 case 'm':
418 /* new stream */
419 get_word(st_type, sizeof(st_type), &p);
420 if (!strcmp(st_type, "audio")) {
421 codec_type = CODEC_TYPE_AUDIO;
422 } else if (!strcmp(st_type, "video")) {
423 codec_type = CODEC_TYPE_VIDEO;
424 } else {
425 return;
426 }
427 rtsp_st = av_mallocz(sizeof(RTSPStream));
428 if (!rtsp_st)
429 return;
430 rtsp_st->stream_index = -1;
431 dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
432
433 rtsp_st->sdp_ip = s1->default_ip;
434 rtsp_st->sdp_ttl = s1->default_ttl;
435
436 get_word(buf1, sizeof(buf1), &p); /* port */
437 rtsp_st->sdp_port = atoi(buf1);
438
439 get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
440
441 /* XXX: handle list of formats */
442 get_word(buf1, sizeof(buf1), &p); /* format list */
443 rtsp_st->sdp_payload_type = atoi(buf1);
444
445 if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
446 /* no corresponding stream */
447 } else {
448 st = av_new_stream(s, 0);
449 if (!st)
450 return;
451 st->priv_data = rtsp_st;
452 rtsp_st->stream_index = st->index;
453 st->codec->codec_type = codec_type;
454 if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
455 /* if standard payload type, we can find the codec right now */
456 rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
457 }
458 }
459 /* put a default control url */
460 av_strlcpy(rtsp_st->control_url, s->filename, sizeof(rtsp_st->control_url));
461 break;
462 case 'a':
463 if (av_strstart(p, "control:", &p) && s->nb_streams > 0) {
464 char proto[32];
465 /* get the control url */
466 st = s->streams[s->nb_streams - 1];
467 rtsp_st = st->priv_data;
468
469 /* XXX: may need to add full url resolution */
470 url_split(proto, sizeof(proto), NULL, 0, NULL, 0, NULL, NULL, 0, p);
471 if (proto[0] == '\0') {
472 /* relative control URL */
473 av_strlcat(rtsp_st->control_url, "/", sizeof(rtsp_st->control_url));
474 av_strlcat(rtsp_st->control_url, p, sizeof(rtsp_st->control_url));
475 } else {
476 av_strlcpy(rtsp_st->control_url, p, sizeof(rtsp_st->control_url));
477 }
478 } else if (av_strstart(p, "rtpmap:", &p)) {
479 /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
480 get_word(buf1, sizeof(buf1), &p);
481 payload_type = atoi(buf1);
482 for(i = 0; i < s->nb_streams;i++) {
483 st = s->streams[i];
484 rtsp_st = st->priv_data;
485 if (rtsp_st->sdp_payload_type == payload_type) {
486 sdp_parse_rtpmap(st->codec, rtsp_st, payload_type, p);
487 }
488 }
489 } else if (av_strstart(p, "fmtp:", &p)) {
490 /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
491 get_word(buf1, sizeof(buf1), &p);
492 payload_type = atoi(buf1);
493 for(i = 0; i < s->nb_streams;i++) {
494 st = s->streams[i];
495 rtsp_st = st->priv_data;
496 if (rtsp_st->sdp_payload_type == payload_type) {
497 if(rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->parse_sdp_a_line) {
498 if(!rtsp_st->dynamic_handler->parse_sdp_a_line(st, rtsp_st->dynamic_protocol_context, buf)) {
499 sdp_parse_fmtp(st, p);
500 }
501 } else {
502 sdp_parse_fmtp(st, p);
503 }
504 }
505 }
506 } else if(av_strstart(p, "framesize:", &p)) {
507 // let dynamic protocol handlers have a stab at the line.
508 get_word(buf1, sizeof(buf1), &p);
509 payload_type = atoi(buf1);
510 for(i = 0; i < s->nb_streams;i++) {
511 st = s->streams[i];
512 rtsp_st = st->priv_data;
513 if (rtsp_st->sdp_payload_type == payload_type) {
514 if(rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->parse_sdp_a_line) {
515 rtsp_st->dynamic_handler->parse_sdp_a_line(st, rtsp_st->dynamic_protocol_context, buf);
516 }
517 }
518 }
519 } else if(av_strstart(p, "range:", &p)) {
520 int64_t start, end;
521
522 // this is so that seeking on a streamed file can work.
523 rtsp_parse_range_npt(p, &start, &end);
524 s->start_time= start;
525 s->duration= (end==AV_NOPTS_VALUE)?AV_NOPTS_VALUE:end-start; // AV_NOPTS_VALUE means live broadcast (and can't seek)
526 }
527 break;
528 }
529}
530
531static int sdp_parse(AVFormatContext *s, const char *content)
532{
533 const char *p;
534 int letter;
535 char buf[1024], *q;
536 SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
537
538 memset(s1, 0, sizeof(SDPParseState));
539 p = content;
540 for(;;) {
541 skip_spaces(&p);
542 letter = *p;
543 if (letter == '\0')
544 break;
545 p++;
546 if (*p != '=')
547 goto next_line;
548 p++;
549 /* get the content */
550 q = buf;
551 while (*p != '\n' && *p != '\r' && *p != '\0') {
552 if ((q - buf) < sizeof(buf) - 1)
553 *q++ = *p;
554 p++;
555 }
556 *q = '\0';
557 sdp_parse_line(s, s1, letter, buf);
558 next_line:
559 while (*p != '\n' && *p != '\0')
560 p++;
561 if (*p == '\n')
562 p++;
563 }
564 return 0;
565}
566
567static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
568{
569 const char *p;
570 int v;
571
572 p = *pp;
573 skip_spaces(&p);
574 v = strtol(p, (char **)&p, 10);
575 if (*p == '-') {
576 p++;
577 *min_ptr = v;
578 v = strtol(p, (char **)&p, 10);
579 *max_ptr = v;
580 } else {
581 *min_ptr = v;
582 *max_ptr = v;
583 }
584 *pp = p;
585}
586
587/* XXX: only one transport specification is parsed */
588static void rtsp_parse_transport(RTSPHeader *reply, const char *p)
589{
590 char transport_protocol[16];
591 char profile[16];
592 char lower_transport[16];
593 char parameter[16];
594 RTSPTransportField *th;
595 char buf[256];
596
597 reply->nb_transports = 0;
598
599 for(;;) {
600 skip_spaces(&p);
601 if (*p == '\0')
602 break;
603
604 th = &reply->transports[reply->nb_transports];
605
606 get_word_sep(transport_protocol, sizeof(transport_protocol),
607 "/", &p);
608 if (*p == '/')
609 p++;
610 if (!strcasecmp (transport_protocol, "rtp")) {
611 get_word_sep(profile, sizeof(profile), "/;,", &p);
612 lower_transport[0] = '\0';
613 /* rtp/avp/<protocol> */
614 if (*p == '/') {
615 p++;
616 get_word_sep(lower_transport, sizeof(lower_transport),
617 ";,", &p);
618 }
619 } else if (!strcasecmp (transport_protocol, "x-pn-tng")) {
620 /* x-pn-tng/<protocol> */
621 get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
622 profile[0] = '\0';
623 }
624 if (!strcasecmp(lower_transport, "TCP"))
625 th->protocol = RTSP_PROTOCOL_RTP_TCP;
626 else
627 th->protocol = RTSP_PROTOCOL_RTP_UDP;
628
629 if (*p == ';')
630 p++;
631 /* get each parameter */
632 while (*p != '\0' && *p != ',') {
633 get_word_sep(parameter, sizeof(parameter), "=;,", &p);
634 if (!strcmp(parameter, "port")) {
635 if (*p == '=') {
636 p++;
637 rtsp_parse_range(&th->port_min, &th->port_max, &p);
638 }
639 } else if (!strcmp(parameter, "client_port")) {
640 if (*p == '=') {
641 p++;
642 rtsp_parse_range(&th->client_port_min,
643 &th->client_port_max, &p);
644 }
645 } else if (!strcmp(parameter, "server_port")) {
646 if (*p == '=') {
647 p++;
648 rtsp_parse_range(&th->server_port_min,
649 &th->server_port_max, &p);
650 }
651 } else if (!strcmp(parameter, "interleaved")) {
652 if (*p == '=') {
653 p++;
654 rtsp_parse_range(&th->interleaved_min,
655 &th->interleaved_max, &p);
656 }
657 } else if (!strcmp(parameter, "multicast")) {
658 if (th->protocol == RTSP_PROTOCOL_RTP_UDP)
659 th->protocol = RTSP_PROTOCOL_RTP_UDP_MULTICAST;
660 } else if (!strcmp(parameter, "ttl")) {
661 if (*p == '=') {
662 p++;
663 th->ttl = strtol(p, (char **)&p, 10);
664 }
665 } else if (!strcmp(parameter, "destination")) {
666 struct in_addr ipaddr;
667
668 if (*p == '=') {
669 p++;
670 get_word_sep(buf, sizeof(buf), ";,", &p);
671 if (inet_aton(buf, &ipaddr))
672 th->destination = ntohl(ipaddr.s_addr);
673 }
674 }
675 while (*p != ';' && *p != '\0' && *p != ',')
676 p++;
677 if (*p == ';')
678 p++;
679 }
680 if (*p == ',')
681 p++;
682
683 reply->nb_transports++;
684 }
685}
686
687void rtsp_parse_line(RTSPHeader *reply, const char *buf)
688{
689 const char *p;
690
691 /* NOTE: we do case independent match for broken servers */
692 p = buf;
693 if (av_stristart(p, "Session:", &p)) {
694 get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
695 } else if (av_stristart(p, "Content-Length:", &p)) {
696 reply->content_length = strtol(p, NULL, 10);
697 } else if (av_stristart(p, "Transport:", &p)) {
698 rtsp_parse_transport(reply, p);
699 } else if (av_stristart(p, "CSeq:", &p)) {
700 reply->seq = strtol(p, NULL, 10);
701 } else if (av_stristart(p, "Range:", &p)) {
702 rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
703 }
704}
705
706static int url_readbuf(URLContext *h, unsigned char *buf, int size)
707{
708 int ret, len;
709
710 len = 0;
711 while (len < size) {
712 ret = url_read(h, buf+len, size-len);
713 if (ret < 1)
714 return ret;
715 len += ret;
716 }
717 return len;
718}
719
720/* skip a RTP/TCP interleaved packet */
721static void rtsp_skip_packet(AVFormatContext *s)
722{
723 RTSPState *rt = s->priv_data;
724 int ret, len, len1;
725 uint8_t buf[1024];
726
727 ret = url_readbuf(rt->rtsp_hd, buf, 3);
728 if (ret != 3)
729 return;
730 len = AV_RB16(buf + 1);
731#ifdef DEBUG
732 printf("skipping RTP packet len=%d\n", len);
733#endif
734 /* skip payload */
735 while (len > 0) {
736 len1 = len;
737 if (len1 > sizeof(buf))
738 len1 = sizeof(buf);
739 ret = url_readbuf(rt->rtsp_hd, buf, len1);
740 if (ret != len1)
741 return;
742 len -= len1;
743 }
744}
745
746static void rtsp_send_cmd(AVFormatContext *s,
747 const char *cmd, RTSPHeader *reply,
748 unsigned char **content_ptr)
749{
750 RTSPState *rt = s->priv_data;
751 char buf[4096], buf1[1024], *q;
752 unsigned char ch;
753 const char *p;
754 int content_length, line_count;
755 unsigned char *content = NULL;
756
757 memset(reply, 0, sizeof(RTSPHeader));
758
759 rt->seq++;
760 av_strlcpy(buf, cmd, sizeof(buf));
761 snprintf(buf1, sizeof(buf1), "CSeq: %d\r\n", rt->seq);
762 av_strlcat(buf, buf1, sizeof(buf));
763 if (rt->session_id[0] != '\0' && !strstr(cmd, "\nIf-Match:")) {
764 snprintf(buf1, sizeof(buf1), "Session: %s\r\n", rt->session_id);
765 av_strlcat(buf, buf1, sizeof(buf));
766 }
767 av_strlcat(buf, "\r\n", sizeof(buf));
768#ifdef DEBUG
769 printf("Sending:\n%s--\n", buf);
770#endif
771 url_write(rt->rtsp_hd, buf, strlen(buf));
772
773 /* parse reply (XXX: use buffers) */
774 line_count = 0;
775 rt->last_reply[0] = '\0';
776 for(;;) {
777 q = buf;
778 for(;;) {
779 if (url_readbuf(rt->rtsp_hd, &ch, 1) != 1)
780 break;
781 if (ch == '\n')
782 break;
783 if (ch == '$') {
784 /* XXX: only parse it if first char on line ? */
785 rtsp_skip_packet(s);
786 } else if (ch != '\r') {
787 if ((q - buf) < sizeof(buf) - 1)
788 *q++ = ch;
789 }
790 }
791 *q = '\0';
792#ifdef DEBUG
793 printf("line='%s'\n", buf);
794#endif
795 /* test if last line */
796 if (buf[0] == '\0')
797 break;
798 p = buf;
799 if (line_count == 0) {
800 /* get reply code */
801 get_word(buf1, sizeof(buf1), &p);
802 get_word(buf1, sizeof(buf1), &p);
803 reply->status_code = atoi(buf1);
804 } else {
805 rtsp_parse_line(reply, p);
806 av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
807 av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
808 }
809 line_count++;
810 }
811
812 if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
813 av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
814
815 content_length = reply->content_length;
816 if (content_length > 0) {
817 /* leave some room for a trailing '\0' (useful for simple parsing) */
818 content = av_malloc(content_length + 1);
819 (void)url_readbuf(rt->rtsp_hd, content, content_length);
820 content[content_length] = '\0';
821 }
822 if (content_ptr)
823 *content_ptr = content;
824 else
825 av_free(content);
826}
827
828
829/* close and free RTSP streams */
830static void rtsp_close_streams(RTSPState *rt)
831{
832 int i;
833 RTSPStream *rtsp_st;
834
835 for(i=0;i<rt->nb_rtsp_streams;i++) {
836 rtsp_st = rt->rtsp_streams[i];
837 if (rtsp_st) {
838 if (rtsp_st->rtp_ctx)
839 rtp_parse_close(rtsp_st->rtp_ctx);
840 if (rtsp_st->rtp_handle)
841 url_close(rtsp_st->rtp_handle);
842 if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
843 rtsp_st->dynamic_handler->close(rtsp_st->dynamic_protocol_context);
844 }
845 }
846 av_free(rt->rtsp_streams);
847}
848
849/**
850 * @returns 0 on success, <0 on error, 1 if protocol is unavailable.
851 */
852static int
853make_setup_request (AVFormatContext *s, const char *host, int port, int protocol)
854{
855 RTSPState *rt = s->priv_data;
856 int j, i, err;
857 RTSPStream *rtsp_st;
858 AVStream *st;
859 RTSPHeader reply1, *reply = &reply1;
860 char cmd[2048];
861
862 /* for each stream, make the setup request */
863 /* XXX: we assume the same server is used for the control of each
864 RTSP stream */
865
866 for(j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
867 char transport[2048];
868
869 rtsp_st = rt->rtsp_streams[i];
870
871 /* compute available transports */
872 transport[0] = '\0';
873
874 /* RTP/UDP */
875 if (protocol == RTSP_PROTOCOL_RTP_UDP) {
876 char buf[256];
877
878 /* first try in specified port range */
879 if (RTSP_RTP_PORT_MIN != 0) {
880 while(j <= RTSP_RTP_PORT_MAX) {
881 snprintf(buf, sizeof(buf), "rtp://%s?localport=%d", host, j);
882 j += 2; /* we will use two port by rtp stream (rtp and rtcp) */
883 if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0) {
884 goto rtp_opened;
885 }
886 }
887 }
888
889/* then try on any port
890** if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
891** err = AVERROR_INVALIDDATA;
892** goto fail;
893** }
894*/
895
896 rtp_opened:
897 port = rtp_get_local_port(rtsp_st->rtp_handle);
898 if (transport[0] != '\0')
899 av_strlcat(transport, ",", sizeof(transport));
900 snprintf(transport + strlen(transport), sizeof(transport) - strlen(transport) - 1,
901 "RTP/AVP/UDP;unicast;client_port=%d-%d",
902 port, port + 1);
903 }
904
905 /* RTP/TCP */
906 else if (protocol == RTSP_PROTOCOL_RTP_TCP) {
907 if (transport[0] != '\0')
908 av_strlcat(transport, ",", sizeof(transport));
909 snprintf(transport + strlen(transport), sizeof(transport) - strlen(transport) - 1,
910 "RTP/AVP/TCP");
911 }
912
913 else if (protocol == RTSP_PROTOCOL_RTP_UDP_MULTICAST) {
914 if (transport[0] != '\0')
915 av_strlcat(transport, ",", sizeof(transport));
916 snprintf(transport + strlen(transport),
917 sizeof(transport) - strlen(transport) - 1,
918 "RTP/AVP/UDP;multicast");
919 }
920 snprintf(cmd, sizeof(cmd),
921 "SETUP %s RTSP/1.0\r\n"
922 "Transport: %s\r\n",
923 rtsp_st->control_url, transport);
924 rtsp_send_cmd(s, cmd, reply, NULL);
925 if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
926 err = 1;
927 goto fail;
928 } else if (reply->status_code != RTSP_STATUS_OK ||
929 reply->nb_transports != 1) {
930 err = AVERROR_INVALIDDATA;
931 goto fail;
932 }
933
934 /* XXX: same protocol for all streams is required */
935 if (i > 0) {
936 if (reply->transports[0].protocol != rt->protocol) {
937 err = AVERROR_INVALIDDATA;
938 goto fail;
939 }
940 } else {
941 rt->protocol = reply->transports[0].protocol;
942 }
943
944 /* close RTP connection if not choosen */
945 if (reply->transports[0].protocol != RTSP_PROTOCOL_RTP_UDP &&
946 (protocol == RTSP_PROTOCOL_RTP_UDP)) {
947 url_close(rtsp_st->rtp_handle);
948 rtsp_st->rtp_handle = NULL;
949 }
950
951 switch(reply->transports[0].protocol) {
952 case RTSP_PROTOCOL_RTP_TCP:
953 rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
954 rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
955 break;
956
957 case RTSP_PROTOCOL_RTP_UDP:
958 {
959 char url[1024];
960
961 /* XXX: also use address if specified */
962 snprintf(url, sizeof(url), "rtp://%s:%d",
963 host, reply->transports[0].server_port_min);
964 if (rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
965 err = AVERROR_INVALIDDATA;
966 goto fail;
967 }
968 }
969 break;
970 case RTSP_PROTOCOL_RTP_UDP_MULTICAST:
971 {
972 char url[1024];
973 struct in_addr in;
974
975 in.s_addr = htonl(reply->transports[0].destination);
976 snprintf(url, sizeof(url), "rtp://%s:%d?ttl=%d",
977 inet_ntoa(in),
978 reply->transports[0].port_min,
979 reply->transports[0].ttl);
980 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
981 err = AVERROR_INVALIDDATA;
982 goto fail;
983 }
984 }
985 break;
986 }
987 /* open the RTP context */
988 st = NULL;
989 if (rtsp_st->stream_index >= 0)
990 st = s->streams[rtsp_st->stream_index];
991 if (!st)
992 s->ctx_flags |= AVFMTCTX_NOHEADER;
993 rtsp_st->rtp_ctx = rtp_parse_open(s, st, rtsp_st->rtp_handle, rtsp_st->sdp_payload_type, &rtsp_st->rtp_payload_data);
994
995 if (!rtsp_st->rtp_ctx) {
996 err = AVERROR(ENOMEM);
997 goto fail;
998 } else {
999 if(rtsp_st->dynamic_handler) {
1000 rtsp_st->rtp_ctx->dynamic_protocol_context= rtsp_st->dynamic_protocol_context;
1001 rtsp_st->rtp_ctx->parse_packet= rtsp_st->dynamic_handler->parse_packet;
1002 }
1003 }
1004 }
1005
1006 return 0;
1007
1008fail:
1009 for (i=0; i<rt->nb_rtsp_streams; i++) {
1010 if (rt->rtsp_streams[i]->rtp_handle) {
1011 url_close(rt->rtsp_streams[i]->rtp_handle);
1012 rt->rtsp_streams[i]->rtp_handle = NULL;
1013 }
1014 }
1015 return err;
1016}
1017
1018static int rtsp_read_header(AVFormatContext *s,
1019 AVFormatParameters *ap)
1020{
1021 RTSPState *rt = s->priv_data;
1022 char host[1024], path[1024], tcpname[1024], cmd[2048], *option_list, *option;
1023 URLContext *rtsp_hd;
1024 int port, ret, err;
1025 RTSPHeader reply1, *reply = &reply1;
1026 unsigned char *content = NULL;
1027 int protocol_mask = 0;
1028
1029 /* extract hostname and port */
1030 url_split(NULL, 0, NULL, 0,
1031 host, sizeof(host), &port, path, sizeof(path), s->filename);
1032 if (port < 0)
1033 port = RTSP_DEFAULT_PORT;
1034
1035 /* search for options */
1036 option_list = strchr(path, '?');
1037 if (option_list) {
1038 /* remove the options from the path */
1039 *option_list++ = 0;
1040 while(option_list) {
1041 /* move the option pointer */
1042 option = option_list;
1043 option_list = strchr(option_list, '&');
1044 if (option_list)
1045 *(option_list++) = 0;
1046 /* handle the options */
1047 if (strcmp(option, "udp") == 0)
1048 protocol_mask = (1<< RTSP_PROTOCOL_RTP_UDP);
1049 else if (strcmp(option, "multicast") == 0)
1050 protocol_mask = (1<< RTSP_PROTOCOL_RTP_UDP_MULTICAST);
1051 else if (strcmp(option, "tcp") == 0)
1052 protocol_mask = (1<< RTSP_PROTOCOL_RTP_TCP);
1053 }
1054 }
1055
1056 if (!protocol_mask)
1057 protocol_mask = (1 << RTSP_PROTOCOL_RTP_LAST) - 1;
1058
1059 /* open the tcp connexion */
1060 snprintf(tcpname, sizeof(tcpname), "tcp://%s:%d", host, port);
1061 if (url_open(&rtsp_hd, tcpname, URL_RDWR) < 0)
1062 return AVERROR(EIO);
1063 rt->rtsp_hd = rtsp_hd;
1064 rt->seq = 0;
1065
1066 /* describe the stream */
1067 snprintf(cmd, sizeof(cmd),
1068 "DESCRIBE %s RTSP/1.0\r\n"
1069 "Accept: application/sdp\r\n",
1070 s->filename);
1071 rtsp_send_cmd(s, cmd, reply, &content);
1072 if (!content) {
1073 err = AVERROR_INVALIDDATA;
1074 goto fail;
1075 }
1076 if (reply->status_code != RTSP_STATUS_OK) {
1077 err = AVERROR_INVALIDDATA;
1078 goto fail;
1079 }
1080
1081 /* now we got the SDP description, we parse it */
1082 ret = sdp_parse(s, (const char *)content);
1083 av_freep(&content);
1084 if (ret < 0) {
1085 err = AVERROR_INVALIDDATA;
1086 goto fail;
1087 }
1088
1089 do {
1090 int protocol = ff_log2_tab[protocol_mask & ~(protocol_mask - 1)];
1091
1092 err = make_setup_request(s, host, port, protocol);
1093 if (err < 0)
1094 goto fail;
1095 protocol_mask &= ~(1 << protocol);
1096 if (protocol_mask == 0 && err == 1) {
1097 err = AVERROR(FF_NETERROR(EPROTONOSUPPORT));
1098 goto fail;
1099 }
1100 } while (err);
1101
1102 rt->state = RTSP_STATE_IDLE;
1103 rt->seek_timestamp = 0; /* default is to start stream at position
1104 zero */
1105 if (ap->initial_pause) {
1106 /* do not start immediately */
1107 } else {
1108 if (rtsp_read_play(s) < 0) {
1109 err = AVERROR_INVALIDDATA;
1110 goto fail;
1111 }
1112 }
1113 return 0;
1114 fail:
1115 rtsp_close_streams(rt);
1116 av_freep(&content);
1117 url_close(rt->rtsp_hd);
1118 return err;
1119}
1120
1121static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1122 uint8_t *buf, int buf_size)
1123{
1124 RTSPState *rt = s->priv_data;
1125 int id, len, i, ret;
1126 RTSPStream *rtsp_st;
1127
1128#ifdef DEBUG_RTP_TCP
1129 printf("tcp_read_packet:\n");
1130#endif
1131 redo:
1132 for(;;) {
1133 ret = url_readbuf(rt->rtsp_hd, buf, 1);
1134#ifdef DEBUG_RTP_TCP
1135 printf("ret=%d c=%02x [%c]\n", ret, buf[0], buf[0]);
1136#endif
1137 if (ret != 1)
1138 return -1;
1139 if (buf[0] == '$')
1140 break;
1141 }
1142 ret = url_readbuf(rt->rtsp_hd, buf, 3);
1143 if (ret != 3)
1144 return -1;
1145 id = buf[0];
1146 len = AV_RB16(buf + 1);
1147#ifdef DEBUG_RTP_TCP
1148 printf("id=%d len=%d\n", id, len);
1149#endif
1150 if (len > buf_size || len < 12)
1151 goto redo;
1152 /* get the data */
1153 ret = url_readbuf(rt->rtsp_hd, buf, len);
1154 if (ret != len)
1155 return -1;
1156
1157 /* find the matching stream */
1158 for(i = 0; i < rt->nb_rtsp_streams; i++) {
1159 rtsp_st = rt->rtsp_streams[i];
1160 if (id >= rtsp_st->interleaved_min &&
1161 id <= rtsp_st->interleaved_max)
1162 goto found;
1163 }
1164 goto redo;
1165 found:
1166 *prtsp_st = rtsp_st;
1167 return len;
1168}
1169
1170static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1171 uint8_t *buf, int buf_size)
1172{
1173 RTSPState *rt = s->priv_data;
1174 RTSPStream *rtsp_st;
1175 fd_set rfds;
1176 int fd1, fd2, fd_max, n, i, ret;
1177 struct timeval tv;
1178
1179 for(;;) {
1180 if (url_interrupt_cb())
1181 return AVERROR(EINTR);
1182 FD_ZERO(&rfds);
1183 fd_max = -1;
1184 for(i = 0; i < rt->nb_rtsp_streams; i++) {
1185 rtsp_st = rt->rtsp_streams[i];
1186 /* currently, we cannot probe RTCP handle because of blocking restrictions */
1187 rtp_get_file_handles(rtsp_st->rtp_handle, &fd1, &fd2);
1188 if (fd1 > fd_max)
1189 fd_max = fd1;
1190 FD_SET(fd1, &rfds);
1191 }
1192 tv.tv_sec = 0;
1193 tv.tv_usec = 100 * 1000;
1194 n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
1195 if (n > 0) {
1196 for(i = 0; i < rt->nb_rtsp_streams; i++) {
1197 rtsp_st = rt->rtsp_streams[i];
1198 rtp_get_file_handles(rtsp_st->rtp_handle, &fd1, &fd2);
1199 if (FD_ISSET(fd1, &rfds)) {
1200 ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
1201 if (ret > 0) {
1202 *prtsp_st = rtsp_st;
1203 return ret;
1204 }
1205 }
1206 }
1207 }
1208 }
1209}
1210
1211static int rtsp_read_packet(AVFormatContext *s,
1212 AVPacket *pkt)
1213{
1214 RTSPState *rt = s->priv_data;
1215 RTSPStream *rtsp_st;
1216 int ret, len;
1217 uint8_t buf[RTP_MAX_PACKET_LENGTH];
1218
1219 /* get next frames from the same RTP packet */
1220 if (rt->cur_rtp) {
1221 ret = rtp_parse_packet(rt->cur_rtp, pkt, NULL, 0);
1222 if (ret == 0) {
1223 rt->cur_rtp = NULL;
1224 return 0;
1225 } else if (ret == 1) {
1226 return 0;
1227 } else {
1228 rt->cur_rtp = NULL;
1229 }
1230 }
1231
1232 /* read next RTP packet */
1233 redo:
1234 switch(rt->protocol) {
1235 default:
1236 case RTSP_PROTOCOL_RTP_TCP:
1237 len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
1238 break;
1239 case RTSP_PROTOCOL_RTP_UDP:
1240 case RTSP_PROTOCOL_RTP_UDP_MULTICAST:
1241 len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
1242 if (len >=0 && rtsp_st->rtp_ctx)
1243 rtp_check_and_send_back_rr(rtsp_st->rtp_ctx, len);
1244 break;
1245 }
1246 if (len < 0)
1247 return len;
1248 ret = rtp_parse_packet(rtsp_st->rtp_ctx, pkt, buf, len);
1249 if (ret < 0)
1250 goto redo;
1251 if (ret == 1) {
1252 /* more packets may follow, so we save the RTP context */
1253 rt->cur_rtp = rtsp_st->rtp_ctx;
1254 }
1255 return 0;
1256}
1257
1258static int rtsp_read_play(AVFormatContext *s)
1259{
1260 RTSPState *rt = s->priv_data;
1261 RTSPHeader reply1, *reply = &reply1;
1262 char cmd[1024];
1263
1264 av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
1265
1266 if (rt->state == RTSP_STATE_PAUSED) {
1267 snprintf(cmd, sizeof(cmd),
1268 "PLAY %s RTSP/1.0\r\n",
1269 s->filename);
1270 } else {
1271 snprintf(cmd, sizeof(cmd),
1272 "PLAY %s RTSP/1.0\r\n"
1273 "Range: npt=%0.3f-\r\n",
1274 s->filename,
1275 (double)rt->seek_timestamp / AV_TIME_BASE);
1276 }
1277 rtsp_send_cmd(s, cmd, reply, NULL);
1278 if (reply->status_code != RTSP_STATUS_OK) {
1279 return -1;
1280 } else {
1281 rt->state = RTSP_STATE_PLAYING;
1282 return 0;
1283 }
1284}
1285
1286/* pause the stream */
1287static int rtsp_read_pause(AVFormatContext *s)
1288{
1289 RTSPState *rt = s->priv_data;
1290 RTSPHeader reply1, *reply = &reply1;
1291 char cmd[1024];
1292
1293 rt = s->priv_data;
1294
1295 if (rt->state != RTSP_STATE_PLAYING)
1296 return 0;
1297
1298 snprintf(cmd, sizeof(cmd),
1299 "PAUSE %s RTSP/1.0\r\n",
1300 s->filename);
1301 rtsp_send_cmd(s, cmd, reply, NULL);
1302 if (reply->status_code != RTSP_STATUS_OK) {
1303 return -1;
1304 } else {
1305 rt->state = RTSP_STATE_PAUSED;
1306 return 0;
1307 }
1308}
1309
1310static int rtsp_read_seek(AVFormatContext *s, int stream_index,
1311 int64_t timestamp, int flags)
1312{
1313 RTSPState *rt = s->priv_data;
1314
1315 rt->seek_timestamp = av_rescale_q(timestamp, s->streams[stream_index]->time_base, AV_TIME_BASE_Q);
1316 switch(rt->state) {
1317 default:
1318 case RTSP_STATE_IDLE:
1319 break;
1320 case RTSP_STATE_PLAYING:
1321 if (rtsp_read_play(s) != 0)
1322 return -1;
1323 break;
1324 case RTSP_STATE_PAUSED:
1325 rt->state = RTSP_STATE_IDLE;
1326 break;
1327 }
1328 return 0;
1329}
1330
1331static int rtsp_read_close(AVFormatContext *s)
1332{
1333 RTSPState *rt = s->priv_data;
1334 RTSPHeader reply1, *reply = &reply1;
1335 char cmd[1024];
1336
1337#if 0
1338 /* NOTE: it is valid to flush the buffer here */
1339 if (rt->protocol == RTSP_PROTOCOL_RTP_TCP) {
1340 url_fclose(&rt->rtsp_gb);
1341 }
1342#endif
1343 snprintf(cmd, sizeof(cmd),
1344 "TEARDOWN %s RTSP/1.0\r\n",
1345 s->filename);
1346 rtsp_send_cmd(s, cmd, reply, NULL);
1347
1348 rtsp_close_streams(rt);
1349 url_close(rt->rtsp_hd);
1350 return 0;
1351}
1352
1353#ifdef CONFIG_RTSP_DEMUXER
1354AVInputFormat rtsp_demuxer = {
1355 "rtsp",
1356 NULL_IF_CONFIG_SMALL("RTSP input format"),
1357 sizeof(RTSPState),
1358 rtsp_probe,
1359 rtsp_read_header,
1360 rtsp_read_packet,
1361 rtsp_read_close,
1362 rtsp_read_seek,
1363 .flags = AVFMT_NOFILE,
1364 .read_play = rtsp_read_play,
1365 .read_pause = rtsp_read_pause,
1366};
1367#endif
1368
1369static int sdp_probe(AVProbeData *p1)
1370{
1371 const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
1372
1373 /* we look for a line beginning "c=IN IP4" */
1374 while (p < p_end && *p != '\0') {
1375 if (p + sizeof("c=IN IP4") - 1 < p_end && av_strstart(p, "c=IN IP4", NULL))
1376 return AVPROBE_SCORE_MAX / 2;
1377
1378 while(p < p_end - 1 && *p != '\n') p++;
1379 if (++p >= p_end)
1380 break;
1381 if (*p == '\r')
1382 p++;
1383 }
1384 return 0;
1385}
1386
1387#define SDP_MAX_SIZE 8192
1388
1389static int sdp_read_header(AVFormatContext *s,
1390 AVFormatParameters *ap)
1391{
1392 RTSPState *rt = s->priv_data;
1393 RTSPStream *rtsp_st;
1394 int size, i, err;
1395 char *content;
1396 char url[1024];
1397 AVStream *st;
1398
1399 /* read the whole sdp file */
1400 /* XXX: better loading */
1401 content = av_malloc(SDP_MAX_SIZE);
1402 size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
1403 if (size <= 0) {
1404 av_free(content);
1405 return AVERROR_INVALIDDATA;
1406 }
1407 content[size] ='\0';
1408
1409 sdp_parse(s, content);
1410 av_free(content);
1411
1412 /* open each RTP stream */
1413 for(i=0;i<rt->nb_rtsp_streams;i++) {
1414 rtsp_st = rt->rtsp_streams[i];
1415
1416 snprintf(url, sizeof(url), "rtp://%s:%d?localport=%d&ttl=%d",
1417 inet_ntoa(rtsp_st->sdp_ip),
1418 rtsp_st->sdp_port,
1419 rtsp_st->sdp_port,
1420 rtsp_st->sdp_ttl);
1421 if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
1422 err = AVERROR_INVALIDDATA;
1423 goto fail;
1424 }
1425 /* open the RTP context */
1426 st = NULL;
1427 if (rtsp_st->stream_index >= 0)
1428 st = s->streams[rtsp_st->stream_index];
1429 if (!st)
1430 s->ctx_flags |= AVFMTCTX_NOHEADER;
1431 rtsp_st->rtp_ctx = rtp_parse_open(s, st, rtsp_st->rtp_handle, rtsp_st->sdp_payload_type, &rtsp_st->rtp_payload_data);
1432 if (!rtsp_st->rtp_ctx) {
1433 err = AVERROR(ENOMEM);
1434 goto fail;
1435 } else {
1436 if(rtsp_st->dynamic_handler) {
1437 rtsp_st->rtp_ctx->dynamic_protocol_context= rtsp_st->dynamic_protocol_context;
1438 rtsp_st->rtp_ctx->parse_packet= rtsp_st->dynamic_handler->parse_packet;
1439 }
1440 }
1441 }
1442 return 0;
1443 fail:
1444 rtsp_close_streams(rt);
1445 return err;
1446}
1447
1448static int sdp_read_packet(AVFormatContext *s,
1449 AVPacket *pkt)
1450{
1451 return rtsp_read_packet(s, pkt);
1452}
1453
1454static int sdp_read_close(AVFormatContext *s)
1455{
1456 RTSPState *rt = s->priv_data;
1457 rtsp_close_streams(rt);
1458 return 0;
1459}
1460
1461#ifdef CONFIG_SDP_DEMUXER
1462AVInputFormat sdp_demuxer = {
1463 "sdp",
1464 NULL_IF_CONFIG_SMALL("SDP"),
1465 sizeof(RTSPState),
1466 sdp_probe,
1467 sdp_read_header,
1468 sdp_read_packet,
1469 sdp_read_close,
1470};
1471#endif
1472
1473#ifdef CONFIG_REDIR_DEMUXER
1474/* dummy redirector format (used directly in av_open_input_file now) */
1475static int redir_probe(AVProbeData *pd)
1476{
1477 const char *p;
1478 p = pd->buf;
1479 while (redir_isspace(*p))
1480 p++;
1481 if (av_strstart(p, "http://", NULL) ||
1482 av_strstart(p, "rtsp://", NULL))
1483 return AVPROBE_SCORE_MAX;
1484 return 0;
1485}
1486
1487static int redir_read_header(AVFormatContext *s, AVFormatParameters *ap)
1488{
1489 char buf[4096], *q;
1490 int c;
1491 AVFormatContext *ic = NULL;
1492 ByteIOContext *f = s->pb;
1493
1494 /* parse each URL and try to open it */
1495 c = url_fgetc(f);
1496 while (c != URL_EOF) {
1497 /* skip spaces */
1498 for(;;) {
1499 if (!redir_isspace(c))
1500 break;
1501 c = url_fgetc(f);
1502 }
1503 if (c == URL_EOF)
1504 break;
1505 /* record url */
1506 q = buf;
1507 for(;;) {
1508 if (c == URL_EOF || redir_isspace(c))
1509 break;
1510 if ((q - buf) < sizeof(buf) - 1)
1511 *q++ = c;
1512 c = url_fgetc(f);
1513 }
1514 *q = '\0';
1515 //printf("URL='%s'\n", buf);
1516 /* try to open the media file */
1517 if (av_open_input_file(&ic, buf, NULL, 0, NULL) == 0)
1518 break;
1519 }
1520 if (!ic)
1521 return AVERROR(EIO);
1522
1523 *s = *ic;
1524 url_fclose(f);
1525
1526 return 0;
1527}
1528
1529AVInputFormat redir_demuxer = {
1530 "redir",
1531 NULL_IF_CONFIG_SMALL("Redirector format"),
1532 0,
1533 redir_probe,
1534 redir_read_header,
1535 NULL,
1536 NULL,
1537};
1538#endif
diff --git a/src/plugins/ffmpeg/libavformat/rtsp.h b/src/plugins/ffmpeg/libavformat/rtsp.h
deleted file mode 100644
index 288f697..0000000
--- a/src/plugins/ffmpeg/libavformat/rtsp.h
+++ /dev/null
@@ -1,97 +0,0 @@
1/*
2 * RTSP definitions
3 * Copyright (c) 2002 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#ifndef FFMPEG_RTSP_H
22#define FFMPEG_RTSP_H
23
24#include <stdint.h>
25#include "avformat.h"
26#include "rtspcodes.h"
27
28enum RTSPProtocol {
29 RTSP_PROTOCOL_RTP_UDP = 0,
30 RTSP_PROTOCOL_RTP_TCP = 1,
31 RTSP_PROTOCOL_RTP_UDP_MULTICAST = 2,
32 /**
33 * This is not part of public API and shouldn't be used outside of ffmpeg.
34 */
35 RTSP_PROTOCOL_RTP_LAST
36};
37
38#define RTSP_DEFAULT_PORT 554
39#define RTSP_MAX_TRANSPORTS 8
40#define RTSP_TCP_MAX_PACKET_SIZE 1472
41#define RTSP_DEFAULT_NB_AUDIO_CHANNELS 2
42#define RTSP_DEFAULT_AUDIO_SAMPLERATE 44100
43#define RTSP_RTP_PORT_MIN 5000
44#define RTSP_RTP_PORT_MAX 10000
45
46typedef struct RTSPTransportField {
47 int interleaved_min, interleaved_max; /**< interleave ids, if TCP transport */
48 int port_min, port_max; /**< RTP ports */
49 int client_port_min, client_port_max; /**< RTP ports */
50 int server_port_min, server_port_max; /**< RTP ports */
51 int ttl; /**< ttl value */
52 uint32_t destination; /**< destination IP address */
53 enum RTSPProtocol protocol;
54} RTSPTransportField;
55
56typedef struct RTSPHeader {
57 int content_length;
58 enum RTSPStatusCode status_code; /**< response code from server */
59 int nb_transports;
60 /** in AV_TIME_BASE unit, AV_NOPTS_VALUE if not used */
61 int64_t range_start, range_end;
62 RTSPTransportField transports[RTSP_MAX_TRANSPORTS];
63 int seq; /**< sequence number */
64 char session_id[512];
65} RTSPHeader;
66
67/** the callback can be used to extend the connection setup/teardown step */
68enum RTSPCallbackAction {
69 RTSP_ACTION_SERVER_SETUP,
70 RTSP_ACTION_SERVER_TEARDOWN,
71 RTSP_ACTION_CLIENT_SETUP,
72 RTSP_ACTION_CLIENT_TEARDOWN,
73};
74
75typedef struct RTSPActionServerSetup {
76 uint32_t ipaddr;
77 char transport_option[512];
78} RTSPActionServerSetup;
79
80typedef int FFRTSPCallback(enum RTSPCallbackAction action,
81 const char *session_id,
82 char *buf, int buf_size,
83 void *arg);
84
85int rtsp_init(void);
86void rtsp_parse_line(RTSPHeader *reply, const char *buf);
87
88#if LIBAVFORMAT_VERSION_INT < (53 << 16)
89extern int rtsp_default_protocols;
90#endif
91extern int rtsp_rtp_port_min;
92extern int rtsp_rtp_port_max;
93
94int rtsp_pause(AVFormatContext *s);
95int rtsp_resume(AVFormatContext *s);
96
97#endif /* FFMPEG_RTSP_H */
diff --git a/src/plugins/ffmpeg/libavformat/rtspcodes.h b/src/plugins/ffmpeg/libavformat/rtspcodes.h
deleted file mode 100644
index d4ad25b..0000000
--- a/src/plugins/ffmpeg/libavformat/rtspcodes.h
+++ /dev/null
@@ -1,40 +0,0 @@
1/*
2 * RTSP definitions
3 * copyright (c) 2002 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#ifndef FFMPEG_RTSPCODES_H
23#define FFMPEG_RTSPCODES_H
24
25/** RTSP handling */
26enum RTSPStatusCode {
27RTSP_STATUS_OK =200, /**< OK */
28RTSP_STATUS_METHOD =405, /**< Method Not Allowed */
29RTSP_STATUS_BANDWIDTH =453, /**< Not Enough Bandwidth */
30RTSP_STATUS_SESSION =454, /**< Session Not Found */
31RTSP_STATUS_STATE =455, /**< Method Not Valid in This State */
32RTSP_STATUS_AGGREGATE =459, /**< Aggregate operation not allowed */
33RTSP_STATUS_ONLY_AGGREGATE =460, /**< Only aggregate operation allowed */
34RTSP_STATUS_TRANSPORT =461, /**< Unsupported transport */
35RTSP_STATUS_INTERNAL =500, /**< Internal Server Error */
36RTSP_STATUS_SERVICE =503, /**< Service Unavailable */
37RTSP_STATUS_VERSION =505, /**< RTSP Version not supported */
38};
39
40#endif /* FFMPEG_RTSPCODES_H */
diff --git a/src/plugins/ffmpeg/libavformat/sdp.c b/src/plugins/ffmpeg/libavformat/sdp.c
deleted file mode 100644
index cf83e60..0000000
--- a/src/plugins/ffmpeg/libavformat/sdp.c
+++ /dev/null
@@ -1,323 +0,0 @@
1/*
2 * copyright (c) 2007 Luca Abeni
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21#include "libavutil/avstring.h"
22#include "libavutil/base64.h"
23#include "avformat.h"
24#include "avc.h"
25#include "rtp.h"
26
27#ifdef CONFIG_RTP_MUXER
28#define MAX_EXTRADATA_SIZE ((INT_MAX - 10) / 2)
29
30struct sdp_session_level {
31 int sdp_version; /**< protocol version (currently 0) */
32 int id; /**< session id */
33 int version; /**< session version */
34 int start_time; /**< session start time (NTP time, in seconds),
35 or 0 in case of permanent session */
36 int end_time; /**< session end time (NTP time, in seconds),
37 or 0 if the session is not bounded */
38 int ttl; /**< TTL, in case of multicast stream */
39 const char *user; /**< username of the session's creator */
40 const char *src_addr; /**< IP address of the machine from which the session was created */
41 const char *dst_addr; /**< destination IP address (can be multicast) */
42 const char *name; /**< session name (can be an empty string) */
43};
44
45static void dest_write(char *buff, int size, const char *dest_addr, int ttl)
46{
47 if (dest_addr) {
48 if (ttl > 0) {
49 av_strlcatf(buff, size, "c=IN IP4 %s/%d\r\n", dest_addr, ttl);
50 } else {
51 av_strlcatf(buff, size, "c=IN IP4 %s\r\n", dest_addr);
52 }
53 }
54}
55
56static void sdp_write_header(char *buff, int size, struct sdp_session_level *s)
57{
58 av_strlcatf(buff, size, "v=%d\r\n"
59 "o=- %d %d IN IPV4 %s\r\n"
60 "t=%d %d\r\n"
61 "s=%s\r\n"
62 "a=tool:libavformat " AV_STRINGIFY(LIBAVFORMAT_VERSION) "\r\n",
63 s->sdp_version,
64 s->id, s->version, s->src_addr,
65 s->start_time, s->end_time,
66 s->name[0] ? s->name : "No Name");
67 dest_write(buff, size, s->dst_addr, s->ttl);
68}
69
70static int get_address(char *dest_addr, int size, int *ttl, const char *url)
71{
72 int port;
73 const char *p;
74
75 url_split(NULL, 0, NULL, 0, dest_addr, size, &port, NULL, 0, url);
76
77 *ttl = 0;
78 p = strchr(url, '?');
79 if (p) {
80 char buff[64];
81 int is_multicast = find_info_tag(buff, sizeof(buff), "multicast", p);
82
83 if (is_multicast) {
84 if (find_info_tag(buff, sizeof(buff), "ttl", p)) {
85 *ttl = strtol(buff, NULL, 10);
86 } else {
87 *ttl = 5;
88 }
89 }
90 }
91
92 return port;
93}
94
95#define MAX_PSET_SIZE 1024
96static char *extradata2psets(AVCodecContext *c)
97{
98 char *psets, *p;
99 const uint8_t *r;
100 const char *pset_string = "; sprop-parameter-sets=";
101
102 if (c->extradata_size > MAX_EXTRADATA_SIZE) {
103 av_log(c, AV_LOG_ERROR, "Too many extra data!\n");
104
105 return NULL;
106 }
107
108 psets = av_mallocz(MAX_PSET_SIZE);
109 if (psets == NULL) {
110 av_log(c, AV_LOG_ERROR, "Cannot allocate memory for the parameter sets\n");
111 return NULL;
112 }
113 memcpy(psets, pset_string, strlen(pset_string));
114 p = psets + strlen(pset_string);
115 r = ff_avc_find_startcode(c->extradata, c->extradata + c->extradata_size);
116 while (r < c->extradata + c->extradata_size) {
117 const uint8_t *r1;
118
119 while (!*(r++));
120 r1 = ff_avc_find_startcode(r, c->extradata + c->extradata_size);
121 if (p != (psets + strlen(pset_string))) {
122 *p = ',';
123 p++;
124 }
125 if (av_base64_encode(p, MAX_PSET_SIZE - (p - psets), r, r1 - r) == NULL) {
126 av_log(c, AV_LOG_ERROR, "Cannot BASE64 encode %td %td!\n", MAX_PSET_SIZE - (p - psets), r1 - r);
127 av_free(psets);
128
129 return NULL;
130 }
131 p += strlen(p);
132 r = r1;
133 }
134
135 return psets;
136}
137
138static void digit_to_char(char *dst, uint8_t src)
139{
140 if (src < 10) {
141 *dst = '0' + src;
142 } else {
143 *dst = 'A' + src - 10;
144 }
145}
146
147static char *data_to_hex(char *buff, const uint8_t *src, int s)
148{
149 int i;
150
151 for(i = 0; i < s; i++) {
152 digit_to_char(buff + 2 * i, src[i] >> 4);
153 digit_to_char(buff + 2 * i + 1, src[i] & 0xF);
154 }
155
156 return buff;
157}
158
159static char *extradata2config(AVCodecContext *c)
160{
161 char *config;
162
163 if (c->extradata_size > MAX_EXTRADATA_SIZE) {
164 av_log(c, AV_LOG_ERROR, "Too many extra data!\n");
165
166 return NULL;
167 }
168 config = av_malloc(10 + c->extradata_size * 2);
169 if (config == NULL) {
170 av_log(c, AV_LOG_ERROR, "Cannot allocate memory for the config info\n");
171 return NULL;
172 }
173 memcpy(config, "; config=", 9);
174 data_to_hex(config + 9, c->extradata, c->extradata_size);
175 config[9 + c->extradata_size * 2] = 0;
176
177 return config;
178}
179
180static char *sdp_media_attributes(char *buff, int size, AVCodecContext *c, int payload_type)
181{
182 char *config = NULL;
183
184 switch (c->codec_id) {
185 case CODEC_ID_H264:
186 if (c->extradata_size) {
187 config = extradata2psets(c);
188 }
189 av_strlcatf(buff, size, "a=rtpmap:%d H264/90000\r\n"
190 "a=fmtp:%d packetization-mode=1%s\r\n",
191 payload_type,
192 payload_type, config ? config : "");
193 break;
194 case CODEC_ID_MPEG4:
195 if (c->extradata_size) {
196 config = extradata2config(c);
197 }
198 av_strlcatf(buff, size, "a=rtpmap:%d MP4V-ES/90000\r\n"
199 "a=fmtp:%d profile-level-id=1%s\r\n",
200 payload_type,
201 payload_type, config ? config : "");
202 break;
203 case CODEC_ID_AAC:
204 if (c->extradata_size) {
205 config = extradata2config(c);
206 } else {
207 /* FIXME: maybe we can forge config information based on the
208 * codec parameters...
209 */
210 av_log(c, AV_LOG_ERROR, "AAC with no global headers is currently not supported\n");
211 return NULL;
212 }
213 if (config == NULL) {
214 return NULL;
215 }
216 av_strlcatf(buff, size, "a=rtpmap:%d MPEG4-GENERIC/%d/%d\r\n"
217 "a=fmtp:%d profile-level-id=1;"
218 "mode=AAC-hbr;sizelength=13;indexlength=3;"
219 "indexdeltalength=3%s\r\n",
220 payload_type, c->sample_rate, c->channels,
221 payload_type, config);
222 break;
223 case CODEC_ID_PCM_S16BE:
224 if (payload_type >= 96)
225 av_strlcatf(buff, size, "a=rtpmap:%d L16/%d/%d\r\n",
226 payload_type,
227 c->sample_rate, c->channels);
228 break;
229 case CODEC_ID_PCM_MULAW:
230 if (payload_type >= 96)
231 av_strlcatf(buff, size, "a=rtpmap:%d PCMU/%d/%d\r\n",
232 payload_type,
233 c->sample_rate, c->channels);
234 break;
235 case CODEC_ID_PCM_ALAW:
236 if (payload_type >= 96)
237 av_strlcatf(buff, size, "a=rtpmap:%d PCMA/%d/%d\r\n",
238 payload_type,
239 c->sample_rate, c->channels);
240 break;
241 default:
242 /* Nothing special to do, here... */
243 break;
244 }
245
246 av_free(config);
247
248 return buff;
249}
250
251static void sdp_write_media(char *buff, int size, AVCodecContext *c, const char *dest_addr, int port, int ttl)
252{
253 const char *type;
254 int payload_type;
255
256 payload_type = rtp_get_payload_type(c);
257 if (payload_type < 0) {
258 payload_type = 96; /* FIXME: how to assign a private pt? rtp.c is broken too */
259 }
260
261 switch (c->codec_type) {
262 case CODEC_TYPE_VIDEO : type = "video" ; break;
263 case CODEC_TYPE_AUDIO : type = "audio" ; break;
264 case CODEC_TYPE_SUBTITLE: type = "text" ; break;
265 default : type = "application"; break;
266 }
267
268 av_strlcatf(buff, size, "m=%s %d RTP/AVP %d\r\n", type, port, payload_type);
269 dest_write(buff, size, dest_addr, ttl);
270 if (c->bit_rate) {
271 av_strlcatf(buff, size, "b=AS:%d\r\n", c->bit_rate / 1000);
272 }
273
274 sdp_media_attributes(buff, size, c, payload_type);
275}
276
277int avf_sdp_create(AVFormatContext *ac[], int n_files, char *buff, int size)
278{
279 struct sdp_session_level s;
280 int i, j, port, ttl;
281 char dst[32];
282
283 memset(buff, 0, size);
284 memset(&s, 0, sizeof(struct sdp_session_level));
285 s.user = "-";
286 s.src_addr = "127.0.0.1"; /* FIXME: Properly set this */
287 s.name = ac[0]->title;
288
289 port = 0;
290 ttl = 0;
291 if (n_files == 1) {
292 port = get_address(dst, sizeof(dst), &ttl, ac[0]->filename);
293 if (port > 0) {
294 s.dst_addr = dst;
295 s.ttl = ttl;
296 }
297 }
298 sdp_write_header(buff, size, &s);
299
300 dst[0] = 0;
301 for (i = 0; i < n_files; i++) {
302 if (n_files != 1) {
303 port = get_address(dst, sizeof(dst), &ttl, ac[i]->filename);
304 }
305 for (j = 0; j < ac[i]->nb_streams; j++) {
306 sdp_write_media(buff, size,
307 ac[i]->streams[j]->codec, dst[0] ? dst : NULL,
308 (port > 0) ? port + j * 2 : 0, ttl);
309 if (port <= 0) {
310 av_strlcatf(buff, size,
311 "a=control:streamid=%d\r\n", i + j);
312 }
313 }
314 }
315
316 return 0;
317}
318#else
319int avf_sdp_create(AVFormatContext *ac[], int n_files, char *buff, int size)
320{
321 return AVERROR(ENOSYS);
322}
323#endif
diff --git a/src/plugins/ffmpeg/libavformat/segafilm.c b/src/plugins/ffmpeg/libavformat/segafilm.c
deleted file mode 100644
index 4c6d138..0000000
--- a/src/plugins/ffmpeg/libavformat/segafilm.c
+++ /dev/null
@@ -1,292 +0,0 @@
1/*
2 * Sega FILM Format (CPK) Demuxer
3 * Copyright (c) 2003 The ffmpeg Project
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/**
23 * @file segafilm.c
24 * Sega FILM (.cpk) file demuxer
25 * by Mike Melanson (melanson@pcisys.net)
26 * For more information regarding the Sega FILM file format, visit:
27 * http://www.pcisys.net/~melanson/codecs/
28 */
29
30#include "avformat.h"
31
32#define FILM_TAG MKBETAG('F', 'I', 'L', 'M')
33#define FDSC_TAG MKBETAG('F', 'D', 'S', 'C')
34#define STAB_TAG MKBETAG('S', 'T', 'A', 'B')
35#define CVID_TAG MKBETAG('c', 'v', 'i', 'd')
36
37typedef struct {
38 int stream;
39 offset_t sample_offset;
40 unsigned int sample_size;
41 int64_t pts;
42 int keyframe;
43} film_sample_t;
44
45typedef struct FilmDemuxContext {
46 int video_stream_index;
47 int audio_stream_index;
48
49 unsigned int audio_type;
50 unsigned int audio_samplerate;
51 unsigned int audio_bits;
52 unsigned int audio_channels;
53
54 unsigned int video_type;
55 unsigned int sample_count;
56 film_sample_t *sample_table;
57 unsigned int current_sample;
58
59 unsigned int base_clock;
60 unsigned int version;
61
62 /* buffer used for interleaving stereo PCM data */
63 unsigned char *stereo_buffer;
64 int stereo_buffer_size;
65} FilmDemuxContext;
66
67static int film_probe(AVProbeData *p)
68{
69 if (AV_RB32(&p->buf[0]) != FILM_TAG)
70 return 0;
71
72 return AVPROBE_SCORE_MAX;
73}
74
75static int film_read_header(AVFormatContext *s,
76 AVFormatParameters *ap)
77{
78 FilmDemuxContext *film = s->priv_data;
79 ByteIOContext *pb = s->pb;
80 AVStream *st;
81 unsigned char scratch[256];
82 int i;
83 unsigned int data_offset;
84 unsigned int audio_frame_counter;
85
86 film->sample_table = NULL;
87 film->stereo_buffer = NULL;
88 film->stereo_buffer_size = 0;
89
90 /* load the main FILM header */
91 if (get_buffer(pb, scratch, 16) != 16)
92 return AVERROR(EIO);
93 data_offset = AV_RB32(&scratch[4]);
94 film->version = AV_RB32(&scratch[8]);
95
96 /* load the FDSC chunk */
97 if (film->version == 0) {
98 /* special case for Lemmings .film files; 20-byte header */
99 if (get_buffer(pb, scratch, 20) != 20)
100 return AVERROR(EIO);
101 /* make some assumptions about the audio parameters */
102 film->audio_type = CODEC_ID_PCM_S8;
103 film->audio_samplerate = 22050;
104 film->audio_channels = 1;
105 film->audio_bits = 8;
106 } else {
107 /* normal Saturn .cpk files; 32-byte header */
108 if (get_buffer(pb, scratch, 32) != 32)
109 return AVERROR(EIO);
110 film->audio_samplerate = AV_RB16(&scratch[24]);
111 film->audio_channels = scratch[21];
112 film->audio_bits = scratch[22];
113 if (film->audio_bits == 8)
114 film->audio_type = CODEC_ID_PCM_S8;
115 else if (film->audio_bits == 16)
116 film->audio_type = CODEC_ID_PCM_S16BE;
117 else
118 film->audio_type = 0;
119 }
120
121 if (AV_RB32(&scratch[0]) != FDSC_TAG)
122 return AVERROR_INVALIDDATA;
123
124 if (AV_RB32(&scratch[8]) == CVID_TAG) {
125 film->video_type = CODEC_ID_CINEPAK;
126 } else
127 film->video_type = 0;
128
129 /* initialize the decoder streams */
130 if (film->video_type) {
131 st = av_new_stream(s, 0);
132 if (!st)
133 return AVERROR(ENOMEM);
134 film->video_stream_index = st->index;
135 st->codec->codec_type = CODEC_TYPE_VIDEO;
136 st->codec->codec_id = film->video_type;
137 st->codec->codec_tag = 0; /* no fourcc */
138 st->codec->width = AV_RB32(&scratch[16]);
139 st->codec->height = AV_RB32(&scratch[12]);
140 }
141
142 if (film->audio_type) {
143 st = av_new_stream(s, 0);
144 if (!st)
145 return AVERROR(ENOMEM);
146 film->audio_stream_index = st->index;
147 st->codec->codec_type = CODEC_TYPE_AUDIO;
148 st->codec->codec_id = film->audio_type;
149 st->codec->codec_tag = 1;
150 st->codec->channels = film->audio_channels;
151 st->codec->bits_per_sample = film->audio_bits;
152 st->codec->sample_rate = film->audio_samplerate;
153 st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *
154 st->codec->bits_per_sample;
155 st->codec->block_align = st->codec->channels *
156 st->codec->bits_per_sample / 8;
157 }
158
159 /* load the sample table */
160 if (get_buffer(pb, scratch, 16) != 16)
161 return AVERROR(EIO);
162 if (AV_RB32(&scratch[0]) != STAB_TAG)
163 return AVERROR_INVALIDDATA;
164 film->base_clock = AV_RB32(&scratch[8]);
165 film->sample_count = AV_RB32(&scratch[12]);
166 if(film->sample_count >= UINT_MAX / sizeof(film_sample_t))
167 return -1;
168 film->sample_table = av_malloc(film->sample_count * sizeof(film_sample_t));
169
170 for(i=0; i<s->nb_streams; i++)
171 av_set_pts_info(s->streams[i], 33, 1, film->base_clock);
172
173 audio_frame_counter = 0;
174 for (i = 0; i < film->sample_count; i++) {
175 /* load the next sample record and transfer it to an internal struct */
176 if (get_buffer(pb, scratch, 16) != 16) {
177 av_free(film->sample_table);
178 return AVERROR(EIO);
179 }
180 film->sample_table[i].sample_offset =
181 data_offset + AV_RB32(&scratch[0]);
182 film->sample_table[i].sample_size = AV_RB32(&scratch[4]);
183 if (AV_RB32(&scratch[8]) == 0xFFFFFFFF) {
184 film->sample_table[i].stream = film->audio_stream_index;
185 film->sample_table[i].pts = audio_frame_counter;
186 film->sample_table[i].pts *= film->base_clock;
187 film->sample_table[i].pts /= film->audio_samplerate;
188
189 audio_frame_counter += (film->sample_table[i].sample_size /
190 (film->audio_channels * film->audio_bits / 8));
191 } else {
192 film->sample_table[i].stream = film->video_stream_index;
193 film->sample_table[i].pts = AV_RB32(&scratch[8]) & 0x7FFFFFFF;
194 film->sample_table[i].keyframe = (scratch[8] & 0x80) ? 0 : 1;
195 }
196 }
197
198 film->current_sample = 0;
199
200 return 0;
201}
202
203static int film_read_packet(AVFormatContext *s,
204 AVPacket *pkt)
205{
206 FilmDemuxContext *film = s->priv_data;
207 ByteIOContext *pb = s->pb;
208 film_sample_t *sample;
209 int ret = 0;
210 int i;
211 int left, right;
212
213 if (film->current_sample >= film->sample_count)
214 return AVERROR(EIO);
215
216 sample = &film->sample_table[film->current_sample];
217
218 /* position the stream (will probably be there anyway) */
219 url_fseek(pb, sample->sample_offset, SEEK_SET);
220
221 /* do a special song and dance when loading FILM Cinepak chunks */
222 if ((sample->stream == film->video_stream_index) &&
223 (film->video_type == CODEC_ID_CINEPAK)) {
224 pkt->pos= url_ftell(pb);
225 if (av_new_packet(pkt, sample->sample_size))
226 return AVERROR(ENOMEM);
227 get_buffer(pb, pkt->data, sample->sample_size);
228 } else if ((sample->stream == film->audio_stream_index) &&
229 (film->audio_channels == 2)) {
230 /* stereo PCM needs to be interleaved */
231
232 if (av_new_packet(pkt, sample->sample_size))
233 return AVERROR(ENOMEM);
234
235 /* make sure the interleave buffer is large enough */
236 if (sample->sample_size > film->stereo_buffer_size) {
237 av_free(film->stereo_buffer);
238 film->stereo_buffer_size = sample->sample_size;
239 film->stereo_buffer = av_malloc(film->stereo_buffer_size);
240 }
241
242 pkt->pos= url_ftell(pb);
243 ret = get_buffer(pb, film->stereo_buffer, sample->sample_size);
244 if (ret != sample->sample_size)
245 ret = AVERROR(EIO);
246
247 left = 0;
248 right = sample->sample_size / 2;
249 for (i = 0; i < sample->sample_size; ) {
250 if (film->audio_bits == 8) {
251 pkt->data[i++] = film->stereo_buffer[left++];
252 pkt->data[i++] = film->stereo_buffer[right++];
253 } else {
254 pkt->data[i++] = film->stereo_buffer[left++];
255 pkt->data[i++] = film->stereo_buffer[left++];
256 pkt->data[i++] = film->stereo_buffer[right++];
257 pkt->data[i++] = film->stereo_buffer[right++];
258 }
259 }
260 } else {
261 ret= av_get_packet(pb, pkt, sample->sample_size);
262 if (ret != sample->sample_size)
263 ret = AVERROR(EIO);
264 }
265
266 pkt->stream_index = sample->stream;
267 pkt->pts = sample->pts;
268
269 film->current_sample++;
270
271 return ret;
272}
273
274static int film_read_close(AVFormatContext *s)
275{
276 FilmDemuxContext *film = s->priv_data;
277
278 av_free(film->sample_table);
279 av_free(film->stereo_buffer);
280
281 return 0;
282}
283
284AVInputFormat segafilm_demuxer = {
285 "film_cpk",
286 NULL_IF_CONFIG_SMALL("Sega FILM/CPK format"),
287 sizeof(FilmDemuxContext),
288 film_probe,
289 film_read_header,
290 film_read_packet,
291 film_read_close,
292};
diff --git a/src/plugins/ffmpeg/libavformat/sierravmd.c b/src/plugins/ffmpeg/libavformat/sierravmd.c
deleted file mode 100644
index 7b0e700..0000000
--- a/src/plugins/ffmpeg/libavformat/sierravmd.c
+++ /dev/null
@@ -1,300 +0,0 @@
1/*
2 * Sierra VMD Format Demuxer
3 * Copyright (c) 2004 The ffmpeg Project
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/**
23 * @file sierravmd.c
24 * Sierra VMD file demuxer
25 * by Vladimir "VAG" Gneushev (vagsoft at mail.ru)
26 * for more information on the Sierra VMD file format, visit:
27 * http://www.pcisys.net/~melanson/codecs/
28 */
29
30#include "avformat.h"
31
32#define VMD_HEADER_SIZE 0x0330
33#define BYTES_PER_FRAME_RECORD 16
34
35typedef struct {
36 int stream_index;
37 offset_t frame_offset;
38 unsigned int frame_size;
39 int64_t pts;
40 int keyframe;
41 unsigned char frame_record[BYTES_PER_FRAME_RECORD];
42} vmd_frame_t;
43
44typedef struct VmdDemuxContext {
45 int video_stream_index;
46 int audio_stream_index;
47
48 unsigned int frame_count;
49 unsigned int frames_per_block;
50 vmd_frame_t *frame_table;
51 unsigned int current_frame;
52
53 int sample_rate;
54 int64_t audio_sample_counter;
55 int skiphdr;
56
57 unsigned char vmd_header[VMD_HEADER_SIZE];
58} VmdDemuxContext;
59
60static int vmd_probe(AVProbeData *p)
61{
62 /* check if the first 2 bytes of the file contain the appropriate size
63 * of a VMD header chunk */
64 if (AV_RL16(&p->buf[0]) != VMD_HEADER_SIZE - 2)
65 return 0;
66
67 /* only return half certainty since this check is a bit sketchy */
68 return AVPROBE_SCORE_MAX / 2;
69}
70
71static int vmd_read_header(AVFormatContext *s,
72 AVFormatParameters *ap)
73{
74 VmdDemuxContext *vmd = s->priv_data;
75 ByteIOContext *pb = s->pb;
76 AVStream *st = NULL, *vst;
77 unsigned int toc_offset;
78 unsigned char *raw_frame_table;
79 int raw_frame_table_size;
80 offset_t current_offset;
81 int i, j;
82 unsigned int total_frames;
83 int64_t pts_inc = 1;
84 int64_t current_video_pts = 0, current_audio_pts = 0;
85 unsigned char chunk[BYTES_PER_FRAME_RECORD];
86 int num, den;
87 int sound_buffers;
88
89 /* fetch the main header, including the 2 header length bytes */
90 url_fseek(pb, 0, SEEK_SET);
91 if (get_buffer(pb, vmd->vmd_header, VMD_HEADER_SIZE) != VMD_HEADER_SIZE)
92 return AVERROR(EIO);
93
94 /* start up the decoders */
95 vst = av_new_stream(s, 0);
96 if (!vst)
97 return AVERROR(ENOMEM);
98 av_set_pts_info(vst, 33, 1, 10);
99 vmd->video_stream_index = vst->index;
100 vst->codec->codec_type = CODEC_TYPE_VIDEO;
101 vst->codec->codec_id = CODEC_ID_VMDVIDEO;
102 vst->codec->codec_tag = 0; /* no fourcc */
103 vst->codec->width = AV_RL16(&vmd->vmd_header[12]);
104 vst->codec->height = AV_RL16(&vmd->vmd_header[14]);
105 vst->codec->extradata_size = VMD_HEADER_SIZE;
106 vst->codec->extradata = av_mallocz(VMD_HEADER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
107 memcpy(vst->codec->extradata, vmd->vmd_header, VMD_HEADER_SIZE);
108
109 /* if sample rate is 0, assume no audio */
110 vmd->sample_rate = AV_RL16(&vmd->vmd_header[804]);
111 if (vmd->sample_rate) {
112 st = av_new_stream(s, 0);
113 if (!st)
114 return AVERROR(ENOMEM);
115 vmd->audio_stream_index = st->index;
116 st->codec->codec_type = CODEC_TYPE_AUDIO;
117 st->codec->codec_id = CODEC_ID_VMDAUDIO;
118 st->codec->codec_tag = 0; /* no fourcc */
119 st->codec->channels = (vmd->vmd_header[811] & 0x80) ? 2 : 1;
120 st->codec->sample_rate = vmd->sample_rate;
121 st->codec->block_align = AV_RL16(&vmd->vmd_header[806]);
122 if (st->codec->block_align & 0x8000) {
123 st->codec->bits_per_sample = 16;
124 st->codec->block_align = -(st->codec->block_align - 0x10000);
125 } else {
126 st->codec->bits_per_sample = 8;
127 }
128 st->codec->bit_rate = st->codec->sample_rate *
129 st->codec->bits_per_sample * st->codec->channels;
130
131 /* calculate pts */
132 num = st->codec->block_align;
133 den = st->codec->sample_rate * st->codec->channels;
134 av_reduce(&den, &num, den, num, (1UL<<31)-1);
135 av_set_pts_info(vst, 33, num, den);
136 av_set_pts_info(st, 33, num, den);
137 pts_inc = num;
138 }
139
140 toc_offset = AV_RL32(&vmd->vmd_header[812]);
141 vmd->frame_count = AV_RL16(&vmd->vmd_header[6]);
142 vmd->frames_per_block = AV_RL16(&vmd->vmd_header[18]);
143 url_fseek(pb, toc_offset, SEEK_SET);
144
145 raw_frame_table = NULL;
146 vmd->frame_table = NULL;
147 sound_buffers = AV_RL16(&vmd->vmd_header[808]);
148 raw_frame_table_size = vmd->frame_count * 6;
149 if(vmd->frame_count * vmd->frames_per_block >= UINT_MAX / sizeof(vmd_frame_t)){
150 av_log(s, AV_LOG_ERROR, "vmd->frame_count * vmd->frames_per_block too large\n");
151 return -1;
152 }
153 raw_frame_table = av_malloc(raw_frame_table_size);
154 vmd->frame_table = av_malloc((vmd->frame_count * vmd->frames_per_block + sound_buffers) * sizeof(vmd_frame_t));
155 if (!raw_frame_table || !vmd->frame_table) {
156 av_free(raw_frame_table);
157 av_free(vmd->frame_table);
158 return AVERROR(ENOMEM);
159 }
160 if (get_buffer(pb, raw_frame_table, raw_frame_table_size) !=
161 raw_frame_table_size) {
162 av_free(raw_frame_table);
163 av_free(vmd->frame_table);
164 return AVERROR(EIO);
165 }
166
167 total_frames = 0;
168 for (i = 0; i < vmd->frame_count; i++) {
169
170 current_offset = AV_RL32(&raw_frame_table[6 * i + 2]);
171
172 /* handle each entry in index block */
173 for (j = 0; j < vmd->frames_per_block; j++) {
174 int type;
175 uint32_t size;
176
177 get_buffer(pb, chunk, BYTES_PER_FRAME_RECORD);
178 type = chunk[0];
179 size = AV_RL32(&chunk[2]);
180 if(!size)
181 continue;
182 switch(type) {
183 case 1: /* Audio Chunk */
184 if (!st) break;
185 /* first audio chunk contains several audio buffers */
186 if(current_audio_pts){
187 vmd->frame_table[total_frames].frame_offset = current_offset;
188 vmd->frame_table[total_frames].stream_index = vmd->audio_stream_index;
189 vmd->frame_table[total_frames].frame_size = size;
190 memcpy(vmd->frame_table[total_frames].frame_record, chunk, BYTES_PER_FRAME_RECORD);
191 vmd->frame_table[total_frames].pts = current_audio_pts;
192 total_frames++;
193 current_audio_pts += pts_inc;
194 }else{
195 uint32_t flags;
196 int k;
197 int noff;
198 int64_t pos;
199
200 pos = url_ftell(pb);
201 url_fseek(pb, current_offset, SEEK_SET);
202 flags = get_le32(pb);
203 noff = 4;
204 url_fseek(pb, pos, SEEK_SET);
205 av_log(s, AV_LOG_DEBUG, "Sound mapping = %08X (%i bufs)\n", flags, sound_buffers);
206 for(k = 0; k < sound_buffers - 1; k++){
207 if(flags & 1) { /* silent block */
208 vmd->frame_table[total_frames].frame_size = 0;
209 }else{
210 vmd->frame_table[total_frames].frame_size = st->codec->block_align + (st->codec->block_align & 1);
211 }
212 noff += vmd->frame_table[total_frames].frame_size;
213 vmd->frame_table[total_frames].frame_offset = current_offset + noff;
214 vmd->frame_table[total_frames].stream_index = vmd->audio_stream_index;
215 memcpy(vmd->frame_table[total_frames].frame_record, chunk, BYTES_PER_FRAME_RECORD);
216 vmd->frame_table[total_frames].pts = current_audio_pts;
217 total_frames++;
218 current_audio_pts += pts_inc;
219 flags >>= 1;
220 }
221 }
222 break;
223 case 2: /* Video Chunk */
224 vmd->frame_table[total_frames].frame_offset = current_offset;
225 vmd->frame_table[total_frames].stream_index = vmd->video_stream_index;
226 vmd->frame_table[total_frames].frame_size = size;
227 memcpy(vmd->frame_table[total_frames].frame_record, chunk, BYTES_PER_FRAME_RECORD);
228 vmd->frame_table[total_frames].pts = current_video_pts;
229 total_frames++;
230 break;
231 }
232 current_offset += size;
233 }
234 current_video_pts += pts_inc;
235 }
236
237 av_free(raw_frame_table);
238
239 vmd->current_frame = 0;
240 vmd->frame_count = total_frames;
241
242 return 0;
243}
244
245static int vmd_read_packet(AVFormatContext *s,
246 AVPacket *pkt)
247{
248 VmdDemuxContext *vmd = s->priv_data;
249 ByteIOContext *pb = s->pb;
250 int ret = 0;
251 vmd_frame_t *frame;
252
253 if (vmd->current_frame >= vmd->frame_count)
254 return AVERROR(EIO);
255
256 frame = &vmd->frame_table[vmd->current_frame];
257 /* position the stream (will probably be there already) */
258 url_fseek(pb, frame->frame_offset, SEEK_SET);
259
260 if (av_new_packet(pkt, frame->frame_size + BYTES_PER_FRAME_RECORD))
261 return AVERROR(ENOMEM);
262 pkt->pos= url_ftell(pb);
263 memcpy(pkt->data, frame->frame_record, BYTES_PER_FRAME_RECORD);
264 ret = get_buffer(pb, pkt->data + BYTES_PER_FRAME_RECORD,
265 frame->frame_size);
266
267 if (ret != frame->frame_size) {
268 av_free_packet(pkt);
269 ret = AVERROR(EIO);
270 }
271 pkt->stream_index = frame->stream_index;
272 pkt->pts = frame->pts;
273 av_log(NULL, AV_LOG_DEBUG, " dispatching %s frame with %d bytes and pts %"PRId64"\n",
274 (frame->frame_record[0] == 0x02) ? "video" : "audio",
275 frame->frame_size + BYTES_PER_FRAME_RECORD,
276 pkt->pts);
277
278 vmd->current_frame++;
279
280 return ret;
281}
282
283static int vmd_read_close(AVFormatContext *s)
284{
285 VmdDemuxContext *vmd = s->priv_data;
286
287 av_free(vmd->frame_table);
288
289 return 0;
290}
291
292AVInputFormat vmd_demuxer = {
293 "vmd",
294 NULL_IF_CONFIG_SMALL("Sierra VMD format"),
295 sizeof(VmdDemuxContext),
296 vmd_probe,
297 vmd_read_header,
298 vmd_read_packet,
299 vmd_read_close,
300};
diff --git a/src/plugins/ffmpeg/libavformat/siff.c b/src/plugins/ffmpeg/libavformat/siff.c
deleted file mode 100644
index 30bd307..0000000
--- a/src/plugins/ffmpeg/libavformat/siff.c
+++ /dev/null
@@ -1,236 +0,0 @@
1/*
2 * Beam Software SIFF demuxer
3 * Copyright (c) 2007 Konstantin Shishkov.
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 "avformat.h"
23
24enum SIFFTags{
25 TAG_SIFF = MKTAG('S', 'I', 'F', 'F'),
26 TAG_BODY = MKTAG('B', 'O', 'D', 'Y'),
27 TAG_VBHD = MKTAG('V', 'B', 'H', 'D'),
28 TAG_SHDR = MKTAG('S', 'H', 'D', 'R'),
29 TAG_VBV1 = MKTAG('V', 'B', 'V', '1'),
30 TAG_SOUN = MKTAG('S', 'O', 'U', 'N'),
31};
32
33enum VBFlags{
34 VB_HAS_GMC = 0x01,
35 VB_HAS_AUDIO = 0x04,
36 VB_HAS_VIDEO = 0x08,
37 VB_HAS_PALETTE = 0x10,
38 VB_HAS_LENGTH = 0x20
39};
40
41typedef struct SIFFContext{
42 int frames;
43 int cur_frame;
44 int rate;
45 int bits;
46 int block_align;
47
48 int has_video;
49 int has_audio;
50
51 int curstrm;
52 int pktsize;
53 int gmcsize;
54 int sndsize;
55
56 int flags;
57 uint8_t gmc[4];
58}SIFFContext;
59
60static int siff_probe(AVProbeData *p)
61{
62 /* check file header */
63 if (AV_RL32(p->buf) == TAG_SIFF)
64 return AVPROBE_SCORE_MAX;
65 else
66 return 0;
67}
68
69static int create_audio_stream(AVFormatContext *s, SIFFContext *c)
70{
71 AVStream *ast;
72 ast = av_new_stream(s, 0);
73 if (!ast)
74 return -1;
75 ast->codec->codec_type = CODEC_TYPE_AUDIO;
76 ast->codec->codec_id = CODEC_ID_PCM_U8;
77 ast->codec->channels = 1;
78 ast->codec->bits_per_sample = c->bits;
79 ast->codec->sample_rate = c->rate;
80 ast->codec->frame_size = c->block_align;
81 av_set_pts_info(ast, 16, 1, c->rate);
82 return 0;
83}
84
85static int siff_parse_vbv1(AVFormatContext *s, SIFFContext *c, ByteIOContext *pb)
86{
87 AVStream *st;
88 int width, height;
89
90 if (get_le32(pb) != TAG_VBHD){
91 av_log(s, AV_LOG_ERROR, "Header chunk is missing\n");
92 return -1;
93 }
94 if(get_be32(pb) != 32){
95 av_log(s, AV_LOG_ERROR, "Header chunk size is incorrect\n");
96 return -1;
97 }
98 if(get_le16(pb) != 1){
99 av_log(s, AV_LOG_ERROR, "Incorrect header version\n");
100 return -1;
101 }
102 width = get_le16(pb);
103 height = get_le16(pb);
104 url_fskip(pb, 4);
105 c->frames = get_le16(pb);
106 if(!c->frames){
107 av_log(s, AV_LOG_ERROR, "File contains no frames ???\n");
108 return -1;
109 }
110 c->bits = get_le16(pb);
111 c->rate = get_le16(pb);
112 c->block_align = c->rate * (c->bits >> 3);
113
114 url_fskip(pb, 16); //zeroes
115
116 st = av_new_stream(s, 0);
117 if (!st)
118 return -1;
119 st->codec->codec_type = CODEC_TYPE_VIDEO;
120 st->codec->codec_id = CODEC_ID_VB;
121 st->codec->codec_tag = MKTAG('V', 'B', 'V', '1');
122 st->codec->width = width;
123 st->codec->height = height;
124 st->codec->pix_fmt = PIX_FMT_PAL8;
125 av_set_pts_info(st, 16, 1, 12);
126
127 c->cur_frame = 0;
128 c->has_video = 1;
129 c->has_audio = !!c->rate;
130 c->curstrm = -1;
131 if (c->has_audio && create_audio_stream(s, c) < 0)
132 return -1;
133 return 0;
134}
135
136static int siff_parse_soun(AVFormatContext *s, SIFFContext *c, ByteIOContext *pb)
137{
138 if (get_le32(pb) != TAG_SHDR){
139 av_log(s, AV_LOG_ERROR, "Header chunk is missing\n");
140 return -1;
141 }
142 if(get_be32(pb) != 8){
143 av_log(s, AV_LOG_ERROR, "Header chunk size is incorrect\n");
144 return -1;
145 }
146 url_fskip(pb, 4); //unknown value
147 c->rate = get_le16(pb);
148 c->bits = get_le16(pb);
149 c->block_align = c->rate * (c->bits >> 3);
150 return create_audio_stream(s, c);
151}
152
153static int siff_read_header(AVFormatContext *s, AVFormatParameters *ap)
154{
155 ByteIOContext *pb = s->pb;
156 SIFFContext *c = s->priv_data;
157 uint32_t tag;
158
159 if (get_le32(pb) != TAG_SIFF)
160 return -1;
161 url_fskip(pb, 4); //ignore size
162 tag = get_le32(pb);
163
164 if (tag != TAG_VBV1 && tag != TAG_SOUN){
165 av_log(s, AV_LOG_ERROR, "Not a VBV file\n");
166 return -1;
167 }
168
169 if (tag == TAG_VBV1 && siff_parse_vbv1(s, c, pb) < 0)
170 return -1;
171 if (tag == TAG_SOUN && siff_parse_soun(s, c, pb) < 0)
172 return -1;
173 if (get_le32(pb) != MKTAG('B', 'O', 'D', 'Y')){
174 av_log(s, AV_LOG_ERROR, "'BODY' chunk is missing\n");
175 return -1;
176 }
177 url_fskip(pb, 4); //ignore size
178
179 return 0;
180}
181
182static int siff_read_packet(AVFormatContext *s, AVPacket *pkt)
183{
184 SIFFContext *c = s->priv_data;
185 int size;
186
187 if (c->has_video){
188 if (c->cur_frame >= c->frames)
189 return AVERROR(EIO);
190 if (c->curstrm == -1){
191 c->pktsize = get_le32(s->pb) - 4;
192 c->flags = get_le16(s->pb);
193 c->gmcsize = (c->flags & VB_HAS_GMC) ? 4 : 0;
194 if (c->gmcsize)
195 get_buffer(s->pb, c->gmc, c->gmcsize);
196 c->sndsize = (c->flags & VB_HAS_AUDIO) ? get_le32(s->pb): 0;
197 c->curstrm = !!(c->flags & VB_HAS_AUDIO);
198 }
199
200 if (!c->curstrm){
201 size = c->pktsize - c->sndsize;
202 if (av_new_packet(pkt, size) < 0)
203 return AVERROR(ENOMEM);
204 AV_WL16(pkt->data, c->flags);
205 if (c->gmcsize)
206 memcpy(pkt->data + 2, c->gmc, c->gmcsize);
207 get_buffer(s->pb, pkt->data + 2 + c->gmcsize, size - c->gmcsize - 2);
208 pkt->stream_index = 0;
209 c->curstrm = -1;
210 }else{
211 if (av_get_packet(s->pb, pkt, c->sndsize - 4) < 0)
212 return AVERROR(EIO);
213 pkt->stream_index = 1;
214 c->curstrm = 0;
215 }
216 if(!c->cur_frame || c->curstrm)
217 pkt->flags |= PKT_FLAG_KEY;
218 if (c->curstrm == -1)
219 c->cur_frame++;
220 }else{
221 size = av_get_packet(s->pb, pkt, c->block_align);
222 if(size <= 0)
223 return AVERROR(EIO);
224 }
225 return pkt->size;
226}
227
228AVInputFormat siff_demuxer = {
229 "siff",
230 NULL_IF_CONFIG_SMALL("Beam Software SIFF"),
231 sizeof(SIFFContext),
232 siff_probe,
233 siff_read_header,
234 siff_read_packet,
235 .extensions = "vb,son"
236};
diff --git a/src/plugins/ffmpeg/libavformat/smacker.c b/src/plugins/ffmpeg/libavformat/smacker.c
deleted file mode 100644
index 8d0b742..0000000
--- a/src/plugins/ffmpeg/libavformat/smacker.c
+++ /dev/null
@@ -1,345 +0,0 @@
1/*
2 * Smacker demuxer
3 * Copyright (c) 2006 Konstantin Shishkov.
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/*
23 * Based on http://wiki.multimedia.cx/index.php?title=Smacker
24 */
25
26#include "libavutil/bswap.h"
27#include "avformat.h"
28
29#define SMACKER_PAL 0x01
30#define SMACKER_FLAG_RING_FRAME 0x01
31
32enum SAudFlags {
33 SMK_AUD_PACKED = 0x80000000,
34 SMK_AUD_16BITS = 0x20000000,
35 SMK_AUD_STEREO = 0x10000000,
36 SMK_AUD_BINKAUD = 0x08000000,
37 SMK_AUD_USEDCT = 0x04000000
38};
39
40typedef struct SmackerContext {
41 /* Smacker file header */
42 uint32_t magic;
43 uint32_t width, height;
44 uint32_t frames;
45 int pts_inc;
46 uint32_t flags;
47 uint32_t audio[7];
48 uint32_t treesize;
49 uint32_t mmap_size, mclr_size, full_size, type_size;
50 uint32_t rates[7];
51 uint32_t pad;
52 /* frame info */
53 uint32_t *frm_size;
54 uint8_t *frm_flags;
55 /* internal variables */
56 int cur_frame;
57 int is_ver4;
58 int64_t cur_pts;
59 /* current frame for demuxing */
60 uint8_t pal[768];
61 int indexes[7];
62 int videoindex;
63 uint8_t *bufs[7];
64 int buf_sizes[7];
65 int stream_id[7];
66 int curstream;
67 offset_t nextpos;
68 int64_t aud_pts[7];
69} SmackerContext;
70
71typedef struct SmackerFrame {
72 int64_t pts;
73 int stream;
74} SmackerFrame;
75
76/* palette used in Smacker */
77static const uint8_t smk_pal[64] = {
78 0x00, 0x04, 0x08, 0x0C, 0x10, 0x14, 0x18, 0x1C,
79 0x20, 0x24, 0x28, 0x2C, 0x30, 0x34, 0x38, 0x3C,
80 0x41, 0x45, 0x49, 0x4D, 0x51, 0x55, 0x59, 0x5D,
81 0x61, 0x65, 0x69, 0x6D, 0x71, 0x75, 0x79, 0x7D,
82 0x82, 0x86, 0x8A, 0x8E, 0x92, 0x96, 0x9A, 0x9E,
83 0xA2, 0xA6, 0xAA, 0xAE, 0xB2, 0xB6, 0xBA, 0xBE,
84 0xC3, 0xC7, 0xCB, 0xCF, 0xD3, 0xD7, 0xDB, 0xDF,
85 0xE3, 0xE7, 0xEB, 0xEF, 0xF3, 0xF7, 0xFB, 0xFF
86};
87
88
89static int smacker_probe(AVProbeData *p)
90{
91 if(p->buf[0] == 'S' && p->buf[1] == 'M' && p->buf[2] == 'K'
92 && (p->buf[3] == '2' || p->buf[3] == '4'))
93 return AVPROBE_SCORE_MAX;
94 else
95 return 0;
96}
97
98static int smacker_read_header(AVFormatContext *s, AVFormatParameters *ap)
99{
100 ByteIOContext *pb = s->pb;
101 SmackerContext *smk = s->priv_data;
102 AVStream *st, *ast[7];
103 int i, ret;
104 int tbase;
105
106 /* read and check header */
107 smk->magic = get_le32(pb);
108 if (smk->magic != MKTAG('S', 'M', 'K', '2') && smk->magic != MKTAG('S', 'M', 'K', '4'))
109 return -1;
110 smk->width = get_le32(pb);
111 smk->height = get_le32(pb);
112 smk->frames = get_le32(pb);
113 smk->pts_inc = (int32_t)get_le32(pb);
114 smk->flags = get_le32(pb);
115 if(smk->flags & SMACKER_FLAG_RING_FRAME)
116 smk->frames++;
117 for(i = 0; i < 7; i++)
118 smk->audio[i] = get_le32(pb);
119 smk->treesize = get_le32(pb);
120
121 if(smk->treesize >= UINT_MAX/4){ // smk->treesize + 16 must not overflow (this check is probably redundant)
122 av_log(s, AV_LOG_ERROR, "treesize too large\n");
123 return -1;
124 }
125
126//FIXME remove extradata "rebuilding"
127 smk->mmap_size = get_le32(pb);
128 smk->mclr_size = get_le32(pb);
129 smk->full_size = get_le32(pb);
130 smk->type_size = get_le32(pb);
131 for(i = 0; i < 7; i++)
132 smk->rates[i] = get_le32(pb);
133 smk->pad = get_le32(pb);
134 /* setup data */
135 if(smk->frames > 0xFFFFFF) {
136 av_log(s, AV_LOG_ERROR, "Too many frames: %i\n", smk->frames);
137 return -1;
138 }
139 smk->frm_size = av_malloc(smk->frames * 4);
140 smk->frm_flags = av_malloc(smk->frames);
141
142 smk->is_ver4 = (smk->magic != MKTAG('S', 'M', 'K', '2'));
143
144 /* read frame info */
145 for(i = 0; i < smk->frames; i++) {
146 smk->frm_size[i] = get_le32(pb);
147 }
148 for(i = 0; i < smk->frames; i++) {
149 smk->frm_flags[i] = get_byte(pb);
150 }
151
152 /* init video codec */
153 st = av_new_stream(s, 0);
154 if (!st)
155 return -1;
156 smk->videoindex = st->index;
157 st->codec->width = smk->width;
158 st->codec->height = smk->height;
159 st->codec->pix_fmt = PIX_FMT_PAL8;
160 st->codec->codec_type = CODEC_TYPE_VIDEO;
161 st->codec->codec_id = CODEC_ID_SMACKVIDEO;
162 st->codec->codec_tag = smk->magic;
163 /* Smacker uses 100000 as internal timebase */
164 if(smk->pts_inc < 0)
165 smk->pts_inc = -smk->pts_inc;
166 else
167 smk->pts_inc *= 100;
168 tbase = 100000;
169 av_reduce(&tbase, &smk->pts_inc, tbase, smk->pts_inc, (1UL<<31)-1);
170 av_set_pts_info(st, 33, smk->pts_inc, tbase);
171 /* handle possible audio streams */
172 for(i = 0; i < 7; i++) {
173 smk->indexes[i] = -1;
174 if((smk->rates[i] & 0xFFFFFF) && !(smk->rates[i] & SMK_AUD_BINKAUD)){
175 ast[i] = av_new_stream(s, 0);
176 smk->indexes[i] = ast[i]->index;
177 ast[i]->codec->codec_type = CODEC_TYPE_AUDIO;
178 ast[i]->codec->codec_id = (smk->rates[i] & SMK_AUD_PACKED) ? CODEC_ID_SMACKAUDIO : CODEC_ID_PCM_U8;
179 ast[i]->codec->codec_tag = MKTAG('S', 'M', 'K', 'A');
180 ast[i]->codec->channels = (smk->rates[i] & SMK_AUD_STEREO) ? 2 : 1;
181 ast[i]->codec->sample_rate = smk->rates[i] & 0xFFFFFF;
182 ast[i]->codec->bits_per_sample = (smk->rates[i] & SMK_AUD_16BITS) ? 16 : 8;
183 if(ast[i]->codec->bits_per_sample == 16 && ast[i]->codec->codec_id == CODEC_ID_PCM_U8)
184 ast[i]->codec->codec_id = CODEC_ID_PCM_S16LE;
185 av_set_pts_info(ast[i], 64, 1, ast[i]->codec->sample_rate
186 * ast[i]->codec->channels * ast[i]->codec->bits_per_sample / 8);
187 }
188 }
189
190
191 /* load trees to extradata, they will be unpacked by decoder */
192 st->codec->extradata = av_malloc(smk->treesize + 16);
193 st->codec->extradata_size = smk->treesize + 16;
194 if(!st->codec->extradata){
195 av_log(s, AV_LOG_ERROR, "Cannot allocate %i bytes of extradata\n", smk->treesize + 16);
196 av_free(smk->frm_size);
197 av_free(smk->frm_flags);
198 return -1;
199 }
200 ret = get_buffer(pb, st->codec->extradata + 16, st->codec->extradata_size - 16);
201 if(ret != st->codec->extradata_size - 16){
202 av_free(smk->frm_size);
203 av_free(smk->frm_flags);
204 return AVERROR(EIO);
205 }
206 ((int32_t*)st->codec->extradata)[0] = le2me_32(smk->mmap_size);
207 ((int32_t*)st->codec->extradata)[1] = le2me_32(smk->mclr_size);
208 ((int32_t*)st->codec->extradata)[2] = le2me_32(smk->full_size);
209 ((int32_t*)st->codec->extradata)[3] = le2me_32(smk->type_size);
210
211 smk->curstream = -1;
212 smk->nextpos = url_ftell(pb);
213
214 return 0;
215}
216
217
218static int smacker_read_packet(AVFormatContext *s, AVPacket *pkt)
219{
220 SmackerContext *smk = s->priv_data;
221 int flags;
222 int ret;
223 int i;
224 int frame_size = 0;
225 int palchange = 0;
226 int pos;
227
228 if (url_feof(s->pb) || smk->cur_frame >= smk->frames)
229 return AVERROR(EIO);
230
231 /* if we demuxed all streams, pass another frame */
232 if(smk->curstream < 0) {
233 url_fseek(s->pb, smk->nextpos, 0);
234 frame_size = smk->frm_size[smk->cur_frame] & (~3);
235 flags = smk->frm_flags[smk->cur_frame];
236 /* handle palette change event */
237 pos = url_ftell(s->pb);
238 if(flags & SMACKER_PAL){
239 int size, sz, t, off, j, pos;
240 uint8_t *pal = smk->pal;
241 uint8_t oldpal[768];
242
243 memcpy(oldpal, pal, 768);
244 size = get_byte(s->pb);
245 size = size * 4 - 1;
246 frame_size -= size;
247 frame_size--;
248 sz = 0;
249 pos = url_ftell(s->pb) + size;
250 while(sz < 256){
251 t = get_byte(s->pb);
252 if(t & 0x80){ /* skip palette entries */
253 sz += (t & 0x7F) + 1;
254 pal += ((t & 0x7F) + 1) * 3;
255 } else if(t & 0x40){ /* copy with offset */
256 off = get_byte(s->pb) * 3;
257 j = (t & 0x3F) + 1;
258 while(j-- && sz < 256) {
259 *pal++ = oldpal[off + 0];
260 *pal++ = oldpal[off + 1];
261 *pal++ = oldpal[off + 2];
262 sz++;
263 off += 3;
264 }
265 } else { /* new entries */
266 *pal++ = smk_pal[t];
267 *pal++ = smk_pal[get_byte(s->pb) & 0x3F];
268 *pal++ = smk_pal[get_byte(s->pb) & 0x3F];
269 sz++;
270 }
271 }
272 url_fseek(s->pb, pos, 0);
273 palchange |= 1;
274 }
275 flags >>= 1;
276 smk->curstream = -1;
277 /* if audio chunks are present, put them to stack and retrieve later */
278 for(i = 0; i < 7; i++) {
279 if(flags & 1) {
280 int size;
281 size = get_le32(s->pb) - 4;
282 frame_size -= size;
283 frame_size -= 4;
284 smk->curstream++;
285 smk->bufs[smk->curstream] = av_realloc(smk->bufs[smk->curstream], size);
286 smk->buf_sizes[smk->curstream] = size;
287 ret = get_buffer(s->pb, smk->bufs[smk->curstream], size);
288 if(ret != size)
289 return AVERROR(EIO);
290 smk->stream_id[smk->curstream] = smk->indexes[i];
291 }
292 flags >>= 1;
293 }
294 if (av_new_packet(pkt, frame_size + 768))
295 return AVERROR(ENOMEM);
296 if(smk->frm_size[smk->cur_frame] & 1)
297 palchange |= 2;
298 pkt->data[0] = palchange;
299 memcpy(pkt->data + 1, smk->pal, 768);
300 ret = get_buffer(s->pb, pkt->data + 769, frame_size);
301 if(ret != frame_size)
302 return AVERROR(EIO);
303 pkt->stream_index = smk->videoindex;
304 pkt->size = ret + 769;
305 smk->cur_frame++;
306 smk->nextpos = url_ftell(s->pb);
307 } else {
308 if (av_new_packet(pkt, smk->buf_sizes[smk->curstream]))
309 return AVERROR(ENOMEM);
310 memcpy(pkt->data, smk->bufs[smk->curstream], smk->buf_sizes[smk->curstream]);
311 pkt->size = smk->buf_sizes[smk->curstream];
312 pkt->stream_index = smk->stream_id[smk->curstream];
313 pkt->pts = smk->aud_pts[smk->curstream];
314 smk->aud_pts[smk->curstream] += AV_RL32(pkt->data);
315 smk->curstream--;
316 }
317
318 return 0;
319}
320
321static int smacker_read_close(AVFormatContext *s)
322{
323 SmackerContext *smk = s->priv_data;
324 int i;
325
326 for(i = 0; i < 7; i++)
327 if(smk->bufs[i])
328 av_free(smk->bufs[i]);
329 if(smk->frm_size)
330 av_free(smk->frm_size);
331 if(smk->frm_flags)
332 av_free(smk->frm_flags);
333
334 return 0;
335}
336
337AVInputFormat smacker_demuxer = {
338 "smk",
339 NULL_IF_CONFIG_SMALL("Smacker video"),
340 sizeof(SmackerContext),
341 smacker_probe,
342 smacker_read_header,
343 smacker_read_packet,
344 smacker_read_close,
345};
diff --git a/src/plugins/ffmpeg/libavformat/sol.c b/src/plugins/ffmpeg/libavformat/sol.c
deleted file mode 100644
index 775b4e0..0000000
--- a/src/plugins/ffmpeg/libavformat/sol.c
+++ /dev/null
@@ -1,152 +0,0 @@
1/*
2 * Sierra SOL demuxer
3 * Copyright Konstantin Shishkov.
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/*
23 * Based on documents from Game Audio Player and own research
24 */
25
26#include "libavutil/bswap.h"
27#include "avformat.h"
28#include "raw.h"
29
30/* if we don't know the size in advance */
31#define AU_UNKNOWN_SIZE ((uint32_t)(~0))
32
33static int sol_probe(AVProbeData *p)
34{
35 /* check file header */
36 uint16_t magic;
37 magic=le2me_16(*((uint16_t*)p->buf));
38 if ((magic == 0x0B8D || magic == 0x0C0D || magic == 0x0C8D) &&
39 p->buf[2] == 'S' && p->buf[3] == 'O' &&
40 p->buf[4] == 'L' && p->buf[5] == 0)
41 return AVPROBE_SCORE_MAX;
42 else
43 return 0;
44}
45
46#define SOL_DPCM 1
47#define SOL_16BIT 4
48#define SOL_STEREO 16
49
50static int sol_codec_id(int magic, int type)
51{
52 if (magic == 0x0B8D)
53 {
54 if (type & SOL_DPCM) return CODEC_ID_SOL_DPCM;
55 else return CODEC_ID_PCM_U8;
56 }
57 if (type & SOL_DPCM)
58 {
59 if (type & SOL_16BIT) return CODEC_ID_SOL_DPCM;
60 else if (magic == 0x0C8D) return CODEC_ID_SOL_DPCM;
61 else return CODEC_ID_SOL_DPCM;
62 }
63 if (type & SOL_16BIT) return CODEC_ID_PCM_S16LE;
64 return CODEC_ID_PCM_U8;
65}
66
67static int sol_codec_type(int magic, int type)
68{
69 if (magic == 0x0B8D) return 1;//SOL_DPCM_OLD;
70 if (type & SOL_DPCM)
71 {
72 if (type & SOL_16BIT) return 3;//SOL_DPCM_NEW16;
73 else if (magic == 0x0C8D) return 1;//SOL_DPCM_OLD;
74 else return 2;//SOL_DPCM_NEW8;
75 }
76 return -1;
77}
78
79static int sol_channels(int magic, int type)
80{
81 if (magic == 0x0B8D || !(type & SOL_STEREO)) return 1;
82 return 2;
83}
84
85static int sol_read_header(AVFormatContext *s,
86 AVFormatParameters *ap)
87{
88 int size;
89 unsigned int magic,tag;
90 ByteIOContext *pb = s->pb;
91 unsigned int id, codec, channels, rate, type;
92 AVStream *st;
93
94 /* check ".snd" header */
95 magic = get_le16(pb);
96 tag = get_le32(pb);
97 if (tag != MKTAG('S', 'O', 'L', 0))
98 return -1;
99 rate = get_le16(pb);
100 type = get_byte(pb);
101 size = get_le32(pb);
102 if (magic != 0x0B8D)
103 get_byte(pb); /* newer SOLs contain padding byte */
104
105 codec = sol_codec_id(magic, type);
106 channels = sol_channels(magic, type);
107
108 if (codec == CODEC_ID_SOL_DPCM)
109 id = sol_codec_type(magic, type);
110 else id = 0;
111
112 /* now we are ready: build format streams */
113 st = av_new_stream(s, 0);
114 if (!st)
115 return -1;
116 st->codec->codec_type = CODEC_TYPE_AUDIO;
117 st->codec->codec_tag = id;
118 st->codec->codec_id = codec;
119 st->codec->channels = channels;
120 st->codec->sample_rate = rate;
121 av_set_pts_info(st, 64, 1, rate);
122 return 0;
123}
124
125#define MAX_SIZE 4096
126
127static int sol_read_packet(AVFormatContext *s,
128 AVPacket *pkt)
129{
130 int ret;
131
132 if (url_feof(s->pb))
133 return AVERROR(EIO);
134 ret= av_get_packet(s->pb, pkt, MAX_SIZE);
135 pkt->stream_index = 0;
136
137 /* note: we need to modify the packet size here to handle the last
138 packet */
139 pkt->size = ret;
140 return 0;
141}
142
143AVInputFormat sol_demuxer = {
144 "sol",
145 NULL_IF_CONFIG_SMALL("Sierra SOL format"),
146 0,
147 sol_probe,
148 sol_read_header,
149 sol_read_packet,
150 NULL,
151 pcm_read_seek,
152};
diff --git a/src/plugins/ffmpeg/libavformat/swf.h b/src/plugins/ffmpeg/libavformat/swf.h
deleted file mode 100644
index 8249f7d..0000000
--- a/src/plugins/ffmpeg/libavformat/swf.h
+++ /dev/null
@@ -1,96 +0,0 @@
1/*
2 * Flash Compatible Streaming Format common header.
3 * Copyright (c) 2000 Fabrice Bellard.
4 * Copyright (c) 2003 Tinic Uro.
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#ifndef FFMPEG_SWF_H
24#define FFMPEG_SWF_H
25
26#include "libavutil/fifo.h"
27#include "avformat.h"
28#include "riff.h" /* for CodecTag */
29
30/* should have a generic way to indicate probable size */
31#define DUMMY_FILE_SIZE (100 * 1024 * 1024)
32#define DUMMY_DURATION 600 /* in seconds */
33
34#define TAG_END 0
35#define TAG_SHOWFRAME 1
36#define TAG_DEFINESHAPE 2
37#define TAG_FREECHARACTER 3
38#define TAG_PLACEOBJECT 4
39#define TAG_REMOVEOBJECT 5
40#define TAG_STREAMHEAD 18
41#define TAG_STREAMBLOCK 19
42#define TAG_JPEG2 21
43#define TAG_PLACEOBJECT2 26
44#define TAG_STREAMHEAD2 45
45#define TAG_VIDEOSTREAM 60
46#define TAG_VIDEOFRAME 61
47#define TAG_FILEATTRIBUTES 69
48
49#define TAG_LONG 0x100
50
51/* flags for shape definition */
52#define FLAG_MOVETO 0x01
53#define FLAG_SETFILL0 0x02
54#define FLAG_SETFILL1 0x04
55
56#define AUDIO_FIFO_SIZE 65536
57
58/* character id used */
59#define BITMAP_ID 0
60#define VIDEO_ID 0
61#define SHAPE_ID 1
62
63#undef NDEBUG
64#include <assert.h>
65
66typedef struct {
67 int audio_stream_index;
68 offset_t duration_pos;
69 offset_t tag_pos;
70 offset_t vframes_pos;
71 int samples_per_frame;
72 int sound_samples;
73 int swf_frame_number;
74 int video_frame_number;
75 int frame_rate;
76 int tag;
77 AVFifoBuffer audio_fifo;
78 AVCodecContext *audio_enc, *video_enc;
79} SWFContext;
80
81static const AVCodecTag swf_codec_tags[] = {
82 {CODEC_ID_FLV1, 0x02},
83 {CODEC_ID_VP6F, 0x04},
84 {0, 0},
85};
86
87static const AVCodecTag swf_audio_codec_tags[] = {
88 {CODEC_ID_PCM_S16LE, 0x00},
89 {CODEC_ID_ADPCM_SWF, 0x01},
90 {CODEC_ID_MP3, 0x02},
91 {CODEC_ID_PCM_S16LE, 0x03},
92 //{CODEC_ID_NELLYMOSER, 0x06},
93 {0, 0},
94};
95
96#endif /* FFMPEG_SWF_H */
diff --git a/src/plugins/ffmpeg/libavformat/swfdec.c b/src/plugins/ffmpeg/libavformat/swfdec.c
deleted file mode 100644
index d899b2d..0000000
--- a/src/plugins/ffmpeg/libavformat/swfdec.c
+++ /dev/null
@@ -1,193 +0,0 @@
1/*
2 * Flash Compatible Streaming Format demuxer
3 * Copyright (c) 2000 Fabrice Bellard.
4 * Copyright (c) 2003 Tinic Uro.
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#include "swf.h"
24
25static int get_swf_tag(ByteIOContext *pb, int *len_ptr)
26{
27 int tag, len;
28
29 if (url_feof(pb))
30 return -1;
31
32 tag = get_le16(pb);
33 len = tag & 0x3f;
34 tag = tag >> 6;
35 if (len == 0x3f) {
36 len = get_le32(pb);
37 }
38// av_log(NULL, AV_LOG_DEBUG, "Tag: %d - Len: %d\n", tag, len);
39 *len_ptr = len;
40 return tag;
41}
42
43
44static int swf_probe(AVProbeData *p)
45{
46 /* check file header */
47 if ((p->buf[0] == 'F' || p->buf[0] == 'C') && p->buf[1] == 'W' &&
48 p->buf[2] == 'S')
49 return AVPROBE_SCORE_MAX;
50 else
51 return 0;
52}
53
54static int swf_read_header(AVFormatContext *s, AVFormatParameters *ap)
55{
56 SWFContext *swf = s->priv_data;
57 ByteIOContext *pb = s->pb;
58 int nbits, len, tag;
59
60 tag = get_be32(pb) & 0xffffff00;
61
62 if (tag == MKBETAG('C', 'W', 'S', 0)) {
63 av_log(s, AV_LOG_ERROR, "Compressed SWF format not supported\n");
64 return AVERROR(EIO);
65 }
66 if (tag != MKBETAG('F', 'W', 'S', 0))
67 return AVERROR(EIO);
68 get_le32(pb);
69 /* skip rectangle size */
70 nbits = get_byte(pb) >> 3;
71 len = (4 * nbits - 3 + 7) / 8;
72 url_fskip(pb, len);
73 swf->frame_rate = get_le16(pb); /* 8.8 fixed */
74 get_le16(pb); /* frame count */
75
76 swf->samples_per_frame = 0;
77 s->ctx_flags |= AVFMTCTX_NOHEADER;
78 return 0;
79}
80
81static int swf_read_packet(AVFormatContext *s, AVPacket *pkt)
82{
83 SWFContext *swf = s->priv_data;
84 ByteIOContext *pb = s->pb;
85 AVStream *vst = NULL, *ast = NULL, *st = 0;
86 int tag, len, i, frame, v;
87
88 for(;;) {
89 tag = get_swf_tag(pb, &len);
90 if (tag < 0)
91 return AVERROR(EIO);
92 if (tag == TAG_VIDEOSTREAM && !vst) {
93 int ch_id = get_le16(pb);
94 get_le16(pb);
95 get_le16(pb);
96 get_le16(pb);
97 get_byte(pb);
98 /* Check for FLV1 */
99 vst = av_new_stream(s, ch_id);
100 if (!vst)
101 return -1;
102 vst->codec->codec_type = CODEC_TYPE_VIDEO;
103 vst->codec->codec_id = codec_get_id(swf_codec_tags, get_byte(pb));
104 av_set_pts_info(vst, 64, 256, swf->frame_rate);
105 vst->codec->time_base = (AVRational){ 256, swf->frame_rate };
106 len -= 10;
107 } else if ((tag == TAG_STREAMHEAD || tag == TAG_STREAMHEAD2) && !ast) {
108 /* streaming found */
109 int sample_rate_code;
110 get_byte(pb);
111 v = get_byte(pb);
112 swf->samples_per_frame = get_le16(pb);
113 ast = av_new_stream(s, -1); /* -1 to avoid clash with video stream ch_id */
114 if (!ast)
115 return -1;
116 swf->audio_stream_index = ast->index;
117 ast->codec->channels = 1 + (v&1);
118 ast->codec->codec_type = CODEC_TYPE_AUDIO;
119 ast->codec->codec_id = codec_get_id(swf_audio_codec_tags, (v>>4) & 15);
120 ast->need_parsing = AVSTREAM_PARSE_FULL;
121 sample_rate_code= (v>>2) & 3;
122 if (!sample_rate_code)
123 return AVERROR(EIO);
124 ast->codec->sample_rate = 11025 << (sample_rate_code-1);
125 av_set_pts_info(ast, 64, 1, ast->codec->sample_rate);
126 len -= 4;
127 } else if (tag == TAG_VIDEOFRAME) {
128 int ch_id = get_le16(pb);
129 len -= 2;
130 for(i=0; i<s->nb_streams; i++) {
131 st = s->streams[i];
132 if (st->codec->codec_type == CODEC_TYPE_VIDEO && st->id == ch_id) {
133 frame = get_le16(pb);
134 av_get_packet(pb, pkt, len-2);
135 pkt->pts = frame;
136 pkt->stream_index = st->index;
137 return pkt->size;
138 }
139 }
140 } else if (tag == TAG_STREAMBLOCK) {
141 st = s->streams[swf->audio_stream_index];
142 if (st->codec->codec_id == CODEC_ID_MP3) {
143 url_fskip(pb, 4);
144 av_get_packet(pb, pkt, len-4);
145 } else { // ADPCM, PCM
146 av_get_packet(pb, pkt, len);
147 }
148 pkt->stream_index = st->index;
149 return pkt->size;
150 } else if (tag == TAG_JPEG2) {
151 for (i=0; i<s->nb_streams; i++) {
152 st = s->streams[i];
153 if (st->id == -2)
154 break;
155 }
156 if (i == s->nb_streams) {
157 vst = av_new_stream(s, -2); /* -2 to avoid clash with video stream and audio stream */
158 if (!vst)
159 return -1;
160 vst->codec->codec_type = CODEC_TYPE_VIDEO;
161 vst->codec->codec_id = CODEC_ID_MJPEG;
162 av_set_pts_info(vst, 64, 256, swf->frame_rate);
163 vst->codec->time_base = (AVRational){ 256, swf->frame_rate };
164 st = vst;
165 }
166 get_le16(pb); /* BITMAP_ID */
167 av_new_packet(pkt, len-2);
168 get_buffer(pb, pkt->data, 4);
169 if (AV_RB32(pkt->data) == 0xffd8ffd9 ||
170 AV_RB32(pkt->data) == 0xffd9ffd8) {
171 /* old SWF files containing SOI/EOI as data start */
172 /* files created by swink have reversed tag */
173 pkt->size -= 4;
174 get_buffer(pb, pkt->data, pkt->size);
175 } else {
176 get_buffer(pb, pkt->data + 4, pkt->size - 4);
177 }
178 pkt->stream_index = st->index;
179 return pkt->size;
180 }
181 url_fskip(pb, len);
182 }
183 return 0;
184}
185
186AVInputFormat swf_demuxer = {
187 "swf",
188 NULL_IF_CONFIG_SMALL("Flash format"),
189 sizeof(SWFContext),
190 swf_probe,
191 swf_read_header,
192 swf_read_packet,
193};
diff --git a/src/plugins/ffmpeg/libavformat/swfenc.c b/src/plugins/ffmpeg/libavformat/swfenc.c
deleted file mode 100644
index 2d341dc..0000000
--- a/src/plugins/ffmpeg/libavformat/swfenc.c
+++ /dev/null
@@ -1,533 +0,0 @@
1/*
2 * Flash Compatible Streaming Format muxer
3 * Copyright (c) 2000 Fabrice Bellard.
4 * Copyright (c) 2003 Tinic Uro.
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#include "libavcodec/bitstream.h"
24#include "avformat.h"
25#include "swf.h"
26
27static void put_swf_tag(AVFormatContext *s, int tag)
28{
29 SWFContext *swf = s->priv_data;
30 ByteIOContext *pb = s->pb;
31
32 swf->tag_pos = url_ftell(pb);
33 swf->tag = tag;
34 /* reserve some room for the tag */
35 if (tag & TAG_LONG) {
36 put_le16(pb, 0);
37 put_le32(pb, 0);
38 } else {
39 put_le16(pb, 0);
40 }
41}
42
43static void put_swf_end_tag(AVFormatContext *s)
44{
45 SWFContext *swf = s->priv_data;
46 ByteIOContext *pb = s->pb;
47 offset_t pos;
48 int tag_len, tag;
49
50 pos = url_ftell(pb);
51 tag_len = pos - swf->tag_pos - 2;
52 tag = swf->tag;
53 url_fseek(pb, swf->tag_pos, SEEK_SET);
54 if (tag & TAG_LONG) {
55 tag &= ~TAG_LONG;
56 put_le16(pb, (tag << 6) | 0x3f);
57 put_le32(pb, tag_len - 4);
58 } else {
59 assert(tag_len < 0x3f);
60 put_le16(pb, (tag << 6) | tag_len);
61 }
62 url_fseek(pb, pos, SEEK_SET);
63}
64
65static inline void max_nbits(int *nbits_ptr, int val)
66{
67 int n;
68
69 if (val == 0)
70 return;
71 val = abs(val);
72 n = 1;
73 while (val != 0) {
74 n++;
75 val >>= 1;
76 }
77 if (n > *nbits_ptr)
78 *nbits_ptr = n;
79}
80
81static void put_swf_rect(ByteIOContext *pb,
82 int xmin, int xmax, int ymin, int ymax)
83{
84 PutBitContext p;
85 uint8_t buf[256];
86 int nbits, mask;
87
88 init_put_bits(&p, buf, sizeof(buf));
89
90 nbits = 0;
91 max_nbits(&nbits, xmin);
92 max_nbits(&nbits, xmax);
93 max_nbits(&nbits, ymin);
94 max_nbits(&nbits, ymax);
95 mask = (1 << nbits) - 1;
96
97 /* rectangle info */
98 put_bits(&p, 5, nbits);
99 put_bits(&p, nbits, xmin & mask);
100 put_bits(&p, nbits, xmax & mask);
101 put_bits(&p, nbits, ymin & mask);
102 put_bits(&p, nbits, ymax & mask);
103
104 flush_put_bits(&p);
105 put_buffer(pb, buf, pbBufPtr(&p) - p.buf);
106}
107
108static void put_swf_line_edge(PutBitContext *pb, int dx, int dy)
109{
110 int nbits, mask;
111
112 put_bits(pb, 1, 1); /* edge */
113 put_bits(pb, 1, 1); /* line select */
114 nbits = 2;
115 max_nbits(&nbits, dx);
116 max_nbits(&nbits, dy);
117
118 mask = (1 << nbits) - 1;
119 put_bits(pb, 4, nbits - 2); /* 16 bits precision */
120 if (dx == 0) {
121 put_bits(pb, 1, 0);
122 put_bits(pb, 1, 1);
123 put_bits(pb, nbits, dy & mask);
124 } else if (dy == 0) {
125 put_bits(pb, 1, 0);
126 put_bits(pb, 1, 0);
127 put_bits(pb, nbits, dx & mask);
128 } else {
129 put_bits(pb, 1, 1);
130 put_bits(pb, nbits, dx & mask);
131 put_bits(pb, nbits, dy & mask);
132 }
133}
134
135#define FRAC_BITS 16
136
137static void put_swf_matrix(ByteIOContext *pb,
138 int a, int b, int c, int d, int tx, int ty)
139{
140 PutBitContext p;
141 uint8_t buf[256];
142 int nbits;
143
144 init_put_bits(&p, buf, sizeof(buf));
145
146 put_bits(&p, 1, 1); /* a, d present */
147 nbits = 1;
148 max_nbits(&nbits, a);
149 max_nbits(&nbits, d);
150 put_bits(&p, 5, nbits); /* nb bits */
151 put_bits(&p, nbits, a);
152 put_bits(&p, nbits, d);
153
154 put_bits(&p, 1, 1); /* b, c present */
155 nbits = 1;
156 max_nbits(&nbits, c);
157 max_nbits(&nbits, b);
158 put_bits(&p, 5, nbits); /* nb bits */
159 put_bits(&p, nbits, c);
160 put_bits(&p, nbits, b);
161
162 nbits = 1;
163 max_nbits(&nbits, tx);
164 max_nbits(&nbits, ty);
165 put_bits(&p, 5, nbits); /* nb bits */
166 put_bits(&p, nbits, tx);
167 put_bits(&p, nbits, ty);
168
169 flush_put_bits(&p);
170 put_buffer(pb, buf, pbBufPtr(&p) - p.buf);
171}
172
173static int swf_write_header(AVFormatContext *s)
174{
175 SWFContext *swf = s->priv_data;
176 ByteIOContext *pb = s->pb;
177 PutBitContext p;
178 uint8_t buf1[256];
179 int i, width, height, rate, rate_base;
180 int version;
181
182 swf->sound_samples = 0;
183 swf->swf_frame_number = 0;
184 swf->video_frame_number = 0;
185
186 for(i=0;i<s->nb_streams;i++) {
187 AVCodecContext *enc = s->streams[i]->codec;
188 if (enc->codec_type == CODEC_TYPE_AUDIO) {
189 if (enc->codec_id == CODEC_ID_MP3) {
190 if (!enc->frame_size) {
191 av_log(s, AV_LOG_ERROR, "audio frame size not set\n");
192 return -1;
193 }
194 swf->audio_enc = enc;
195 av_fifo_init(&swf->audio_fifo, AUDIO_FIFO_SIZE);
196 } else {
197 av_log(s, AV_LOG_ERROR, "SWF muxer only supports MP3\n");
198 return -1;
199 }
200 } else {
201 if (enc->codec_id == CODEC_ID_VP6F ||
202 enc->codec_id == CODEC_ID_FLV1 ||
203 enc->codec_id == CODEC_ID_MJPEG) {
204 swf->video_enc = enc;
205 } else {
206 av_log(s, AV_LOG_ERROR, "SWF muxer only supports VP6, FLV1 and MJPEG\n");
207 return -1;
208 }
209 }
210 }
211
212 if (!swf->video_enc) {
213 /* currently, cannot work correctly if audio only */
214 width = 320;
215 height = 200;
216 rate = 10;
217 rate_base= 1;
218 } else {
219 width = swf->video_enc->width;
220 height = swf->video_enc->height;
221 rate = swf->video_enc->time_base.den;
222 rate_base = swf->video_enc->time_base.num;
223 }
224
225 if (!swf->audio_enc)
226 swf->samples_per_frame = (44100. * rate_base) / rate;
227 else
228 swf->samples_per_frame = (swf->audio_enc->sample_rate * rate_base) / rate;
229
230 put_tag(pb, "FWS");
231
232 if (!strcmp("avm2", s->oformat->name))
233 version = 9;
234 else if (swf->video_enc && swf->video_enc->codec_id == CODEC_ID_VP6F)
235 version = 8; /* version 8 and above support VP6 codec */
236 else if (swf->video_enc && swf->video_enc->codec_id == CODEC_ID_FLV1)
237 version = 6; /* version 6 and above support FLV1 codec */
238 else
239 version = 4; /* version 4 for mpeg audio support */
240 put_byte(pb, version);
241
242 put_le32(pb, DUMMY_FILE_SIZE); /* dummy size
243 (will be patched if not streamed) */
244
245 put_swf_rect(pb, 0, width * 20, 0, height * 20);
246 put_le16(pb, (rate * 256) / rate_base); /* frame rate */
247 swf->duration_pos = url_ftell(pb);
248 put_le16(pb, (uint16_t)(DUMMY_DURATION * (int64_t)rate / rate_base)); /* frame count */
249
250 /* avm2/swf v9 (also v8?) files require a file attribute tag */
251 if (version == 9) {
252 put_swf_tag(s, TAG_FILEATTRIBUTES);
253 put_le32(pb, 1<<3); /* set ActionScript v3/AVM2 flag */
254 put_swf_end_tag(s);
255 }
256
257 /* define a shape with the jpeg inside */
258 if (swf->video_enc && swf->video_enc->codec_id == CODEC_ID_MJPEG) {
259 put_swf_tag(s, TAG_DEFINESHAPE);
260
261 put_le16(pb, SHAPE_ID); /* ID of shape */
262 /* bounding rectangle */
263 put_swf_rect(pb, 0, width, 0, height);
264 /* style info */
265 put_byte(pb, 1); /* one fill style */
266 put_byte(pb, 0x41); /* clipped bitmap fill */
267 put_le16(pb, BITMAP_ID); /* bitmap ID */
268 /* position of the bitmap */
269 put_swf_matrix(pb, (int)(1.0 * (1 << FRAC_BITS)), 0,
270 0, (int)(1.0 * (1 << FRAC_BITS)), 0, 0);
271 put_byte(pb, 0); /* no line style */
272
273 /* shape drawing */
274 init_put_bits(&p, buf1, sizeof(buf1));
275 put_bits(&p, 4, 1); /* one fill bit */
276 put_bits(&p, 4, 0); /* zero line bit */
277
278 put_bits(&p, 1, 0); /* not an edge */
279 put_bits(&p, 5, FLAG_MOVETO | FLAG_SETFILL0);
280 put_bits(&p, 5, 1); /* nbits */
281 put_bits(&p, 1, 0); /* X */
282 put_bits(&p, 1, 0); /* Y */
283 put_bits(&p, 1, 1); /* set fill style 1 */
284
285 /* draw the rectangle ! */
286 put_swf_line_edge(&p, width, 0);
287 put_swf_line_edge(&p, 0, height);
288 put_swf_line_edge(&p, -width, 0);
289 put_swf_line_edge(&p, 0, -height);
290
291 /* end of shape */
292 put_bits(&p, 1, 0); /* not an edge */
293 put_bits(&p, 5, 0);
294
295 flush_put_bits(&p);
296 put_buffer(pb, buf1, pbBufPtr(&p) - p.buf);
297
298 put_swf_end_tag(s);
299 }
300
301 if (swf->audio_enc && swf->audio_enc->codec_id == CODEC_ID_MP3) {
302 int v = 0;
303
304 /* start sound */
305 put_swf_tag(s, TAG_STREAMHEAD2);
306 switch(swf->audio_enc->sample_rate) {
307 case 11025: v |= 1 << 2; break;
308 case 22050: v |= 2 << 2; break;
309 case 44100: v |= 3 << 2; break;
310 default:
311 /* not supported */
312 av_log(s, AV_LOG_ERROR, "swf does not support that sample rate, choose from (44100, 22050, 11025).\n");
313 return -1;
314 }
315 v |= 0x02; /* 16 bit playback */
316 if (swf->audio_enc->channels == 2)
317 v |= 0x01; /* stereo playback */
318 put_byte(s->pb, v);
319 v |= 0x20; /* mp3 compressed */
320 put_byte(s->pb, v);
321 put_le16(s->pb, swf->samples_per_frame); /* avg samples per frame */
322 put_le16(s->pb, 0);
323
324 put_swf_end_tag(s);
325 }
326
327 put_flush_packet(s->pb);
328 return 0;
329}
330
331static int swf_write_video(AVFormatContext *s,
332 AVCodecContext *enc, const uint8_t *buf, int size)
333{
334 SWFContext *swf = s->priv_data;
335 ByteIOContext *pb = s->pb;
336
337 /* Flash Player limit */
338 if (swf->swf_frame_number == 16000)
339 av_log(enc, AV_LOG_INFO, "warning: Flash Player limit of 16000 frames reached\n");
340
341 if (enc->codec_id == CODEC_ID_VP6F ||
342 enc->codec_id == CODEC_ID_FLV1) {
343 if (swf->video_frame_number == 0) {
344 /* create a new video object */
345 put_swf_tag(s, TAG_VIDEOSTREAM);
346 put_le16(pb, VIDEO_ID);
347 swf->vframes_pos = url_ftell(pb);
348 put_le16(pb, 15000); /* hard flash player limit */
349 put_le16(pb, enc->width);
350 put_le16(pb, enc->height);
351 put_byte(pb, 0);
352 put_byte(pb,codec_get_tag(swf_codec_tags,enc->codec_id));
353 put_swf_end_tag(s);
354
355 /* place the video object for the first time */
356 put_swf_tag(s, TAG_PLACEOBJECT2);
357 put_byte(pb, 0x36);
358 put_le16(pb, 1);
359 put_le16(pb, VIDEO_ID);
360 put_swf_matrix(pb, 1 << FRAC_BITS, 0, 0, 1 << FRAC_BITS, 0, 0);
361 put_le16(pb, swf->video_frame_number);
362 put_tag(pb, "video");
363 put_byte(pb, 0x00);
364 put_swf_end_tag(s);
365 } else {
366 /* mark the character for update */
367 put_swf_tag(s, TAG_PLACEOBJECT2);
368 put_byte(pb, 0x11);
369 put_le16(pb, 1);
370 put_le16(pb, swf->video_frame_number);
371 put_swf_end_tag(s);
372 }
373
374 /* set video frame data */
375 put_swf_tag(s, TAG_VIDEOFRAME | TAG_LONG);
376 put_le16(pb, VIDEO_ID);
377 put_le16(pb, swf->video_frame_number++);
378 put_buffer(pb, buf, size);
379 put_swf_end_tag(s);
380 } else if (enc->codec_id == CODEC_ID_MJPEG) {
381 if (swf->swf_frame_number > 0) {
382 /* remove the shape */
383 put_swf_tag(s, TAG_REMOVEOBJECT);
384 put_le16(pb, SHAPE_ID); /* shape ID */
385 put_le16(pb, 1); /* depth */
386 put_swf_end_tag(s);
387
388 /* free the bitmap */
389 put_swf_tag(s, TAG_FREECHARACTER);
390 put_le16(pb, BITMAP_ID);
391 put_swf_end_tag(s);
392 }
393
394 put_swf_tag(s, TAG_JPEG2 | TAG_LONG);
395
396 put_le16(pb, BITMAP_ID); /* ID of the image */
397
398 /* a dummy jpeg header seems to be required */
399 put_be32(pb, 0xffd8ffd9);
400 /* write the jpeg image */
401 put_buffer(pb, buf, size);
402
403 put_swf_end_tag(s);
404
405 /* draw the shape */
406
407 put_swf_tag(s, TAG_PLACEOBJECT);
408 put_le16(pb, SHAPE_ID); /* shape ID */
409 put_le16(pb, 1); /* depth */
410 put_swf_matrix(pb, 20 << FRAC_BITS, 0, 0, 20 << FRAC_BITS, 0, 0);
411 put_swf_end_tag(s);
412 }
413
414 swf->swf_frame_number++;
415
416 /* streaming sound always should be placed just before showframe tags */
417 if (swf->audio_enc && av_fifo_size(&swf->audio_fifo)) {
418 int frame_size = av_fifo_size(&swf->audio_fifo);
419 put_swf_tag(s, TAG_STREAMBLOCK | TAG_LONG);
420 put_le16(pb, swf->sound_samples);
421 put_le16(pb, 0); // seek samples
422 av_fifo_generic_read(&swf->audio_fifo, frame_size, &put_buffer, pb);
423 put_swf_end_tag(s);
424
425 /* update FIFO */
426 swf->sound_samples = 0;
427 }
428
429 /* output the frame */
430 put_swf_tag(s, TAG_SHOWFRAME);
431 put_swf_end_tag(s);
432
433 put_flush_packet(s->pb);
434
435 return 0;
436}
437
438static int swf_write_audio(AVFormatContext *s,
439 AVCodecContext *enc, const uint8_t *buf, int size)
440{
441 SWFContext *swf = s->priv_data;
442
443 /* Flash Player limit */
444 if (swf->swf_frame_number == 16000)
445 av_log(enc, AV_LOG_INFO, "warning: Flash Player limit of 16000 frames reached\n");
446
447 if (av_fifo_size(&swf->audio_fifo) + size > AUDIO_FIFO_SIZE) {
448 av_log(s, AV_LOG_ERROR, "audio fifo too small to mux audio essence\n");
449 return -1;
450 }
451
452 av_fifo_generic_write(&swf->audio_fifo, buf, size, NULL);
453 swf->sound_samples += enc->frame_size;
454
455 /* if audio only stream make sure we add swf frames */
456 if (!swf->video_enc)
457 swf_write_video(s, enc, 0, 0);
458
459 return 0;
460}
461
462static int swf_write_packet(AVFormatContext *s, AVPacket *pkt)
463{
464 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
465 if (codec->codec_type == CODEC_TYPE_AUDIO)
466 return swf_write_audio(s, codec, pkt->data, pkt->size);
467 else
468 return swf_write_video(s, codec, pkt->data, pkt->size);
469}
470
471static int swf_write_trailer(AVFormatContext *s)
472{
473 SWFContext *swf = s->priv_data;
474 ByteIOContext *pb = s->pb;
475 AVCodecContext *enc, *video_enc;
476 int file_size, i;
477
478 video_enc = NULL;
479 for(i=0;i<s->nb_streams;i++) {
480 enc = s->streams[i]->codec;
481 if (enc->codec_type == CODEC_TYPE_VIDEO)
482 video_enc = enc;
483 else
484 av_fifo_free(&swf->audio_fifo);
485 }
486
487 put_swf_tag(s, TAG_END);
488 put_swf_end_tag(s);
489
490 put_flush_packet(s->pb);
491
492 /* patch file size and number of frames if not streamed */
493 if (!url_is_streamed(s->pb) && video_enc) {
494 file_size = url_ftell(pb);
495 url_fseek(pb, 4, SEEK_SET);
496 put_le32(pb, file_size);
497 url_fseek(pb, swf->duration_pos, SEEK_SET);
498 put_le16(pb, swf->video_frame_number);
499 url_fseek(pb, swf->vframes_pos, SEEK_SET);
500 put_le16(pb, swf->video_frame_number);
501 url_fseek(pb, file_size, SEEK_SET);
502 }
503 return 0;
504}
505
506#ifdef CONFIG_SWF_MUXER
507AVOutputFormat swf_muxer = {
508 "swf",
509 NULL_IF_CONFIG_SMALL("Flash format"),
510 "application/x-shockwave-flash",
511 "swf",
512 sizeof(SWFContext),
513 CODEC_ID_MP3,
514 CODEC_ID_FLV1,
515 swf_write_header,
516 swf_write_packet,
517 swf_write_trailer,
518};
519#endif
520#ifdef CONFIG_AVM2_MUXER
521AVOutputFormat avm2_muxer = {
522 "avm2",
523 NULL_IF_CONFIG_SMALL("Flash 9 (AVM2) format"),
524 "application/x-shockwave-flash",
525 NULL,
526 sizeof(SWFContext),
527 CODEC_ID_MP3,
528 CODEC_ID_FLV1,
529 swf_write_header,
530 swf_write_packet,
531 swf_write_trailer,
532};
533#endif
diff --git a/src/plugins/ffmpeg/libavformat/tcp.c b/src/plugins/ffmpeg/libavformat/tcp.c
deleted file mode 100644
index 6c25e72..0000000
--- a/src/plugins/ffmpeg/libavformat/tcp.c
+++ /dev/null
@@ -1,194 +0,0 @@
1/*
2 * TCP protocol
3 * Copyright (c) 2002 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#include "avformat.h"
22#include <unistd.h>
23#include "network.h"
24#include "os_support.h"
25#include <sys/time.h>
26
27typedef struct TCPContext {
28 int fd;
29} TCPContext;
30
31/* return non zero if error */
32static int tcp_open(URLContext *h, const char *uri, int flags)
33{
34 struct sockaddr_in dest_addr;
35 char hostname[1024], *q;
36 int port, fd = -1;
37 TCPContext *s = NULL;
38 fd_set wfds;
39 int fd_max, ret;
40 struct timeval tv;
41 socklen_t optlen;
42 char proto[1024],path[1024],tmp[1024]; // PETR: protocol and path strings
43
44 url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname),
45 &port, path, sizeof(path), uri); // PETR: use url_split
46 if (strcmp(proto,"tcp")) goto fail; // PETR: check protocol
47 if ((q = strchr(hostname,'@'))) { strcpy(tmp,q+1); strcpy(hostname,tmp); } // PETR: take only the part after '@' for tcp protocol
48
49 s = av_malloc(sizeof(TCPContext));
50 if (!s)
51 return AVERROR(ENOMEM);
52 h->priv_data = s;
53 h->is_streamed = 1;
54
55 if (port <= 0 || port >= 65536)
56 goto fail;
57
58 if(!ff_network_init())
59 return AVERROR(EIO);
60
61 dest_addr.sin_family = AF_INET;
62 dest_addr.sin_port = htons(port);
63 if (resolve_host(&dest_addr.sin_addr, hostname) < 0)
64 goto fail;
65
66 fd = socket(AF_INET, SOCK_STREAM, 0);
67 if (fd < 0)
68 goto fail;
69 ff_socket_nonblock(fd, 1);
70
71 redo:
72 ret = connect(fd, (struct sockaddr *)&dest_addr,
73 sizeof(dest_addr));
74 if (ret < 0) {
75 if (ff_neterrno() == FF_NETERROR(EINTR))
76 goto redo;
77 if (ff_neterrno() != FF_NETERROR(EINPROGRESS) &&
78 ff_neterrno() != FF_NETERROR(EAGAIN))
79 goto fail;
80
81 /* wait until we are connected or until abort */
82 for(;;) {
83 if (url_interrupt_cb()) {
84 ret = AVERROR(EINTR);
85 goto fail1;
86 }
87 fd_max = fd;
88 FD_ZERO(&wfds);
89 FD_SET(fd, &wfds);
90 tv.tv_sec = 0;
91 tv.tv_usec = 100 * 1000;
92 ret = select(fd_max + 1, NULL, &wfds, NULL, &tv);
93 if (ret > 0 && FD_ISSET(fd, &wfds))
94 break;
95 }
96
97 /* test error */
98 optlen = sizeof(ret);
99 getsockopt (fd, SOL_SOCKET, SO_ERROR, &ret, &optlen);
100 if (ret != 0)
101 goto fail;
102 }
103 s->fd = fd;
104 return 0;
105
106 fail:
107 ret = AVERROR(EIO);
108 fail1:
109 if (fd >= 0)
110 closesocket(fd);
111 av_free(s);
112 return ret;
113}
114
115static int tcp_read(URLContext *h, uint8_t *buf, int size)
116{
117 TCPContext *s = h->priv_data;
118 int len, fd_max, ret;
119 fd_set rfds;
120 struct timeval tv;
121
122 for (;;) {
123 if (url_interrupt_cb())
124 return AVERROR(EINTR);
125 fd_max = s->fd;
126 FD_ZERO(&rfds);
127 FD_SET(s->fd, &rfds);
128 tv.tv_sec = 0;
129 tv.tv_usec = 100 * 1000;
130 ret = select(fd_max + 1, &rfds, NULL, NULL, &tv);
131 if (ret > 0 && FD_ISSET(s->fd, &rfds)) {
132 len = recv(s->fd, buf, size, 0);
133 if (len < 0) {
134 if (ff_neterrno() != FF_NETERROR(EINTR) &&
135 ff_neterrno() != FF_NETERROR(EAGAIN))
136 return AVERROR(errno);
137 } else return len;
138 } else if (ret < 0) {
139 return -1;
140 }
141 }
142}
143
144static int tcp_write(URLContext *h, uint8_t *buf, int size)
145{
146 TCPContext *s = h->priv_data;
147 int ret, size1, fd_max, len;
148 fd_set wfds;
149 struct timeval tv;
150
151 size1 = size;
152 while (size > 0) {
153 if (url_interrupt_cb())
154 return AVERROR(EINTR);
155 fd_max = s->fd;
156 FD_ZERO(&wfds);
157 FD_SET(s->fd, &wfds);
158 tv.tv_sec = 0;
159 tv.tv_usec = 100 * 1000;
160 ret = select(fd_max + 1, NULL, &wfds, NULL, &tv);
161 if (ret > 0 && FD_ISSET(s->fd, &wfds)) {
162 len = send(s->fd, buf, size, 0);
163 if (len < 0) {
164 if (ff_neterrno() != FF_NETERROR(EINTR) &&
165 ff_neterrno() != FF_NETERROR(EAGAIN))
166 return AVERROR(errno);
167 continue;
168 }
169 size -= len;
170 buf += len;
171 } else if (ret < 0) {
172 return -1;
173 }
174 }
175 return size1 - size;
176}
177
178static int tcp_close(URLContext *h)
179{
180 TCPContext *s = h->priv_data;
181 closesocket(s->fd);
182 ff_network_close();
183 av_free(s);
184 return 0;
185}
186
187URLProtocol tcp_protocol = {
188 "tcp",
189 tcp_open,
190 tcp_read,
191 tcp_write,
192 NULL, /* seek */
193 tcp_close,
194};
diff --git a/src/plugins/ffmpeg/libavformat/thp.c b/src/plugins/ffmpeg/libavformat/thp.c
deleted file mode 100644
index 434bc29..0000000
--- a/src/plugins/ffmpeg/libavformat/thp.c
+++ /dev/null
@@ -1,197 +0,0 @@
1/*
2 * THP Demuxer
3 * Copyright (c) 2007 Marco Gerards.
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
23#include "avformat.h"
24
25typedef struct ThpDemuxContext {
26 int version;
27 int first_frame;
28 int first_framesz;
29 int last_frame;
30 int compoff;
31 int framecnt;
32 AVRational fps;
33 int frame;
34 int next_frame;
35 int next_framesz;
36 int video_stream_index;
37 int audio_stream_index;
38 int compcount;
39 unsigned char components[16];
40 AVStream* vst;
41 int has_audio;
42 int audiosize;
43} ThpDemuxContext;
44
45
46static int thp_probe(AVProbeData *p)
47{
48 /* check file header */
49 if (AV_RL32(p->buf) == MKTAG('T', 'H', 'P', '\0'))
50 return AVPROBE_SCORE_MAX;
51 else
52 return 0;
53}
54
55static int thp_read_header(AVFormatContext *s,
56 AVFormatParameters *ap)
57{
58 ThpDemuxContext *thp = s->priv_data;
59 AVStream *st;
60 ByteIOContext *pb = s->pb;
61 int i;
62
63 /* Read the file header. */
64 get_be32(pb); /* Skip Magic. */
65 thp->version = get_be32(pb);
66
67 get_be32(pb); /* Max buf size. */
68 get_be32(pb); /* Max samples. */
69
70 thp->fps = av_d2q(av_int2flt(get_be32(pb)), INT_MAX);
71 thp->framecnt = get_be32(pb);
72 thp->first_framesz = get_be32(pb);
73 get_be32(pb); /* Data size. */
74
75 thp->compoff = get_be32(pb);
76 get_be32(pb); /* offsetDataOffset. */
77 thp->first_frame = get_be32(pb);
78 thp->last_frame = get_be32(pb);
79
80 thp->next_framesz = thp->first_framesz;
81 thp->next_frame = thp->first_frame;
82
83 /* Read the component structure. */
84 url_fseek (pb, thp->compoff, SEEK_SET);
85 thp->compcount = get_be32(pb);
86
87 /* Read the list of component types. */
88 get_buffer(pb, thp->components, 16);
89
90 for (i = 0; i < thp->compcount; i++) {
91 if (thp->components[i] == 0) {
92 if (thp->vst != 0)
93 break;
94
95 /* Video component. */
96 st = av_new_stream(s, 0);
97 if (!st)
98 return AVERROR(ENOMEM);
99
100 /* The denominator and numerator are switched because 1/fps
101 is required. */
102 av_set_pts_info(st, 64, thp->fps.den, thp->fps.num);
103 st->codec->codec_type = CODEC_TYPE_VIDEO;
104 st->codec->codec_id = CODEC_ID_THP;
105 st->codec->codec_tag = 0; /* no fourcc */
106 st->codec->width = get_be32(pb);
107 st->codec->height = get_be32(pb);
108 st->codec->sample_rate = av_q2d(thp->fps);
109 thp->vst = st;
110 thp->video_stream_index = st->index;
111
112 if (thp->version == 0x11000)
113 get_be32(pb); /* Unknown. */
114 } else if (thp->components[i] == 1) {
115 if (thp->has_audio != 0)
116 break;
117
118 /* Audio component. */
119 st = av_new_stream(s, 0);
120 if (!st)
121 return AVERROR(ENOMEM);
122
123 st->codec->codec_type = CODEC_TYPE_AUDIO;
124 st->codec->codec_id = CODEC_ID_ADPCM_THP;
125 st->codec->codec_tag = 0; /* no fourcc */
126 st->codec->channels = get_be32(pb); /* numChannels. */
127 st->codec->sample_rate = get_be32(pb); /* Frequency. */
128
129 av_set_pts_info(st, 64, 1, st->codec->sample_rate);
130
131 thp->audio_stream_index = st->index;
132 thp->has_audio = 1;
133 }
134 }
135
136 return 0;
137}
138
139static int thp_read_packet(AVFormatContext *s,
140 AVPacket *pkt)
141{
142 ThpDemuxContext *thp = s->priv_data;
143 ByteIOContext *pb = s->pb;
144 int size;
145 int ret;
146
147 if (thp->audiosize == 0) {
148 /* Terminate when last frame is reached. */
149 if (thp->frame >= thp->framecnt)
150 return AVERROR(EIO);
151
152 url_fseek(pb, thp->next_frame, SEEK_SET);
153
154 /* Locate the next frame and read out its size. */
155 thp->next_frame += thp->next_framesz;
156 thp->next_framesz = get_be32(pb);
157
158 get_be32(pb); /* Previous total size. */
159 size = get_be32(pb); /* Total size of this frame. */
160
161 /* Store the audiosize so the next time this function is called,
162 the audio can be read. */
163 if (thp->has_audio)
164 thp->audiosize = get_be32(pb); /* Audio size. */
165 else
166 thp->frame++;
167
168 ret = av_get_packet(pb, pkt, size);
169 if (ret != size) {
170 av_free_packet(pkt);
171 return AVERROR(EIO);
172 }
173
174 pkt->stream_index = thp->video_stream_index;
175 } else {
176 ret = av_get_packet(pb, pkt, thp->audiosize);
177 if (ret != thp->audiosize) {
178 av_free_packet(pkt);
179 return AVERROR(EIO);
180 }
181
182 pkt->stream_index = thp->audio_stream_index;
183 thp->audiosize = 0;
184 thp->frame++;
185 }
186
187 return 0;
188}
189
190AVInputFormat thp_demuxer = {
191 "thp",
192 NULL_IF_CONFIG_SMALL("THP"),
193 sizeof(ThpDemuxContext),
194 thp_probe,
195 thp_read_header,
196 thp_read_packet
197};
diff --git a/src/plugins/ffmpeg/libavformat/tiertexseq.c b/src/plugins/ffmpeg/libavformat/tiertexseq.c
deleted file mode 100644
index 00dcb5e..0000000
--- a/src/plugins/ffmpeg/libavformat/tiertexseq.c
+++ /dev/null
@@ -1,313 +0,0 @@
1/*
2 * Tiertex Limited SEQ File Demuxer
3 * Copyright (c) 2006 Gregory Montoir (cyx@users.sourceforge.net)
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/**
23 * @file tiertexseq.c
24 * Tiertex Limited SEQ file demuxer
25 */
26
27#include "avformat.h"
28
29#define SEQ_FRAME_SIZE 6144
30#define SEQ_FRAME_W 256
31#define SEQ_FRAME_H 128
32#define SEQ_NUM_FRAME_BUFFERS 30
33#define SEQ_AUDIO_BUFFER_SIZE 882
34#define SEQ_SAMPLE_RATE 22050
35#define SEQ_FRAME_RATE 25
36
37
38typedef struct TiertexSeqFrameBuffer {
39 int fill_size;
40 int data_size;
41 unsigned char *data;
42} TiertexSeqFrameBuffer;
43
44typedef struct SeqDemuxContext {
45 int audio_stream_index;
46 int video_stream_index;
47 int current_frame_pts;
48 int current_frame_offs;
49 TiertexSeqFrameBuffer frame_buffers[SEQ_NUM_FRAME_BUFFERS];
50 int frame_buffers_count;
51 unsigned int current_audio_data_size;
52 unsigned int current_audio_data_offs;
53 unsigned int current_pal_data_size;
54 unsigned int current_pal_data_offs;
55 unsigned int current_video_data_size;
56 unsigned char *current_video_data_ptr;
57 int audio_buffer_full;
58} SeqDemuxContext;
59
60
61static int seq_probe(AVProbeData *p)
62{
63 int i;
64
65 if (p->buf_size < 258)
66 return 0;
67
68 /* there's no real header in a .seq file, the only thing they have in common */
69 /* is the first 256 bytes of the file which are always filled with 0 */
70 for (i = 0; i < 256; i++)
71 if (p->buf[i])
72 return 0;
73
74 if(p->buf[256]==0 && p->buf[257]==0)
75 return 0;
76
77 /* only one fourth of the score since the previous check is too naive */
78 return AVPROBE_SCORE_MAX / 4;
79}
80
81static int seq_init_frame_buffers(SeqDemuxContext *seq, ByteIOContext *pb)
82{
83 int i, sz;
84 TiertexSeqFrameBuffer *seq_buffer;
85
86 url_fseek(pb, 256, SEEK_SET);
87
88 for (i = 0; i < SEQ_NUM_FRAME_BUFFERS; i++) {
89 sz = get_le16(pb);
90 if (sz == 0)
91 break;
92 else {
93 seq_buffer = &seq->frame_buffers[i];
94 seq_buffer->fill_size = 0;
95 seq_buffer->data_size = sz;
96 seq_buffer->data = av_malloc(sz);
97 if (!seq_buffer->data)
98 return AVERROR(ENOMEM);
99 }
100 }
101 seq->frame_buffers_count = i;
102 return 0;
103}
104
105static int seq_fill_buffer(SeqDemuxContext *seq, ByteIOContext *pb, int buffer_num, unsigned int data_offs, int data_size)
106{
107 TiertexSeqFrameBuffer *seq_buffer;
108
109 if (buffer_num >= SEQ_NUM_FRAME_BUFFERS)
110 return AVERROR_INVALIDDATA;
111
112 seq_buffer = &seq->frame_buffers[buffer_num];
113 if (seq_buffer->fill_size + data_size > seq_buffer->data_size || data_size <= 0)
114 return AVERROR_INVALIDDATA;
115
116 url_fseek(pb, seq->current_frame_offs + data_offs, SEEK_SET);
117 if (get_buffer(pb, seq_buffer->data + seq_buffer->fill_size, data_size) != data_size)
118 return AVERROR(EIO);
119
120 seq_buffer->fill_size += data_size;
121 return 0;
122}
123
124static int seq_parse_frame_data(SeqDemuxContext *seq, ByteIOContext *pb)
125{
126 unsigned int offset_table[4], buffer_num[4];
127 TiertexSeqFrameBuffer *seq_buffer;
128 int i, e, err;
129
130 seq->current_frame_offs += SEQ_FRAME_SIZE;
131 url_fseek(pb, seq->current_frame_offs, SEEK_SET);
132
133 /* sound data */
134 seq->current_audio_data_offs = get_le16(pb);
135 if (seq->current_audio_data_offs) {
136 seq->current_audio_data_size = SEQ_AUDIO_BUFFER_SIZE * 2;
137 } else {
138 seq->current_audio_data_size = 0;
139 }
140
141 /* palette data */
142 seq->current_pal_data_offs = get_le16(pb);
143 if (seq->current_pal_data_offs) {
144 seq->current_pal_data_size = 768;
145 } else {
146 seq->current_pal_data_size = 0;
147 }
148
149 /* video data */
150 for (i = 0; i < 4; i++)
151 buffer_num[i] = get_byte(pb);
152
153 for (i = 0; i < 4; i++)
154 offset_table[i] = get_le16(pb);
155
156 for (i = 0; i < 3; i++) {
157 if (offset_table[i]) {
158 for (e = i + 1; e < 3 && offset_table[e] == 0; e++);
159 err = seq_fill_buffer(seq, pb, buffer_num[1 + i],
160 offset_table[i],
161 offset_table[e] - offset_table[i]);
162 if (err)
163 return err;
164 }
165 }
166
167 if (buffer_num[0] != 255) {
168 if (buffer_num[0] >= SEQ_NUM_FRAME_BUFFERS)
169 return AVERROR_INVALIDDATA;
170
171 seq_buffer = &seq->frame_buffers[buffer_num[0]];
172 seq->current_video_data_size = seq_buffer->fill_size;
173 seq->current_video_data_ptr = seq_buffer->data;
174 seq_buffer->fill_size = 0;
175 } else {
176 seq->current_video_data_size = 0;
177 seq->current_video_data_ptr = 0;
178 }
179
180 return 0;
181}
182
183static int seq_read_header(AVFormatContext *s, AVFormatParameters *ap)
184{
185 int i, rc;
186 SeqDemuxContext *seq = s->priv_data;
187 ByteIOContext *pb = s->pb;
188 AVStream *st;
189
190 /* init internal buffers */
191 rc = seq_init_frame_buffers(seq, pb);
192 if (rc)
193 return rc;
194
195 seq->current_frame_offs = 0;
196
197 /* preload (no audio data, just buffer operations related data) */
198 for (i = 1; i <= 100; i++) {
199 rc = seq_parse_frame_data(seq, pb);
200 if (rc)
201 return rc;
202 }
203
204 seq->current_frame_pts = 0;
205
206 seq->audio_buffer_full = 0;
207
208 /* initialize the video decoder stream */
209 st = av_new_stream(s, 0);
210 if (!st)
211 return AVERROR(ENOMEM);
212
213 av_set_pts_info(st, 32, 1, SEQ_FRAME_RATE);
214 seq->video_stream_index = st->index;
215 st->codec->codec_type = CODEC_TYPE_VIDEO;
216 st->codec->codec_id = CODEC_ID_TIERTEXSEQVIDEO;
217 st->codec->codec_tag = 0; /* no fourcc */
218 st->codec->width = SEQ_FRAME_W;
219 st->codec->height = SEQ_FRAME_H;
220
221 /* initialize the audio decoder stream */
222 st = av_new_stream(s, 0);
223 if (!st)
224 return AVERROR(ENOMEM);
225
226 av_set_pts_info(st, 32, 1, SEQ_SAMPLE_RATE);
227 seq->audio_stream_index = st->index;
228 st->codec->codec_type = CODEC_TYPE_AUDIO;
229 st->codec->codec_id = CODEC_ID_PCM_S16BE;
230 st->codec->codec_tag = 0; /* no tag */
231 st->codec->channels = 1;
232 st->codec->sample_rate = SEQ_SAMPLE_RATE;
233 st->codec->bits_per_sample = 16;
234 st->codec->bit_rate = st->codec->sample_rate * st->codec->bits_per_sample * st->codec->channels;
235 st->codec->block_align = st->codec->channels * st->codec->bits_per_sample;
236
237 return 0;
238}
239
240static int seq_read_packet(AVFormatContext *s, AVPacket *pkt)
241{
242 int rc;
243 SeqDemuxContext *seq = s->priv_data;
244 ByteIOContext *pb = s->pb;
245
246 if (!seq->audio_buffer_full) {
247 rc = seq_parse_frame_data(seq, pb);
248 if (rc)
249 return rc;
250
251 /* video packet */
252 if (seq->current_pal_data_size + seq->current_video_data_size != 0) {
253 if (av_new_packet(pkt, 1 + seq->current_pal_data_size + seq->current_video_data_size))
254 return AVERROR(ENOMEM);
255
256 pkt->data[0] = 0;
257 if (seq->current_pal_data_size) {
258 pkt->data[0] |= 1;
259 url_fseek(pb, seq->current_frame_offs + seq->current_pal_data_offs, SEEK_SET);
260 if (get_buffer(pb, &pkt->data[1], seq->current_pal_data_size) != seq->current_pal_data_size)
261 return AVERROR(EIO);
262 }
263 if (seq->current_video_data_size) {
264 pkt->data[0] |= 2;
265 memcpy(&pkt->data[1 + seq->current_pal_data_size],
266 seq->current_video_data_ptr,
267 seq->current_video_data_size);
268 }
269 pkt->stream_index = seq->video_stream_index;
270 pkt->pts = seq->current_frame_pts;
271
272 /* sound buffer will be processed on next read_packet() call */
273 seq->audio_buffer_full = 1;
274 return 0;
275 }
276 }
277
278 /* audio packet */
279 if (seq->current_audio_data_offs == 0) /* end of data reached */
280 return AVERROR(EIO);
281
282 url_fseek(pb, seq->current_frame_offs + seq->current_audio_data_offs, SEEK_SET);
283 rc = av_get_packet(pb, pkt, seq->current_audio_data_size);
284 if (rc < 0)
285 return rc;
286
287 pkt->stream_index = seq->audio_stream_index;
288 seq->current_frame_pts++;
289
290 seq->audio_buffer_full = 0;
291 return 0;
292}
293
294static int seq_read_close(AVFormatContext *s)
295{
296 int i;
297 SeqDemuxContext *seq = s->priv_data;
298
299 for (i = 0; i < SEQ_NUM_FRAME_BUFFERS; i++)
300 av_free(seq->frame_buffers[i].data);
301
302 return 0;
303}
304
305AVInputFormat tiertexseq_demuxer = {
306 "tiertexseq",
307 NULL_IF_CONFIG_SMALL("Tiertex Limited SEQ format"),
308 sizeof(SeqDemuxContext),
309 seq_probe,
310 seq_read_header,
311 seq_read_packet,
312 seq_read_close,
313};
diff --git a/src/plugins/ffmpeg/libavformat/tta.c b/src/plugins/ffmpeg/libavformat/tta.c
deleted file mode 100644
index 9a30e1f..0000000
--- a/src/plugins/ffmpeg/libavformat/tta.c
+++ /dev/null
@@ -1,150 +0,0 @@
1/*
2 * TTA demuxer
3 * Copyright (c) 2006 Alex Beregszaszi
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 "libavcodec/bitstream.h"
23#include "avformat.h"
24
25typedef struct {
26 int totalframes, currentframe;
27} TTAContext;
28
29static int tta_probe(AVProbeData *p)
30{
31 const uint8_t *d = p->buf;
32 if (d[0] == 'T' && d[1] == 'T' && d[2] == 'A' && d[3] == '1')
33 return 80;
34 return 0;
35}
36
37static int tta_read_header(AVFormatContext *s, AVFormatParameters *ap)
38{
39 TTAContext *c = s->priv_data;
40 AVStream *st;
41 int i, channels, bps, samplerate, datalen, framelen;
42 uint64_t framepos;
43
44 if (get_le32(s->pb) != ff_get_fourcc("TTA1"))
45 return -1; // not tta file
46
47 url_fskip(s->pb, 2); // FIXME: flags
48 channels = get_le16(s->pb);
49 bps = get_le16(s->pb);
50 samplerate = get_le32(s->pb);
51 if(samplerate <= 0 || samplerate > 1000000){
52 av_log(s, AV_LOG_ERROR, "nonsense samplerate\n");
53 return -1;
54 }
55
56 datalen = get_le32(s->pb);
57 if(datalen < 0){
58 av_log(s, AV_LOG_ERROR, "nonsense datalen\n");
59 return -1;
60 }
61
62 url_fskip(s->pb, 4); // header crc
63
64 framelen = samplerate*256/245;
65 c->totalframes = datalen / framelen + ((datalen % framelen) ? 1 : 0);
66 c->currentframe = 0;
67
68 if(c->totalframes >= UINT_MAX/sizeof(uint32_t)){
69 av_log(s, AV_LOG_ERROR, "totalframes too large\n");
70 return -1;
71 }
72
73 st = av_new_stream(s, 0);
74 if (!st)
75 return AVERROR(ENOMEM);
76
77 av_set_pts_info(st, 64, 1, samplerate);
78 st->start_time = 0;
79 st->duration = datalen;
80
81 framepos = url_ftell(s->pb) + 4*c->totalframes + 4;
82
83 for (i = 0; i < c->totalframes; i++) {
84 uint32_t size = get_le32(s->pb);
85 av_add_index_entry(st, framepos, i*framelen, size, 0, AVINDEX_KEYFRAME);
86 framepos += size;
87 }
88 url_fskip(s->pb, 4); // seektable crc
89
90 st->codec->codec_type = CODEC_TYPE_AUDIO;
91 st->codec->codec_id = CODEC_ID_TTA;
92 st->codec->channels = channels;
93 st->codec->sample_rate = samplerate;
94 st->codec->bits_per_sample = bps;
95
96 st->codec->extradata_size = url_ftell(s->pb);
97 if(st->codec->extradata_size+FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)st->codec->extradata_size){
98 //this check is redundant as get_buffer should fail
99 av_log(s, AV_LOG_ERROR, "extradata_size too large\n");
100 return -1;
101 }
102 st->codec->extradata = av_mallocz(st->codec->extradata_size+FF_INPUT_BUFFER_PADDING_SIZE);
103 url_fseek(s->pb, 0, SEEK_SET);
104 get_buffer(s->pb, st->codec->extradata, st->codec->extradata_size);
105
106 return 0;
107}
108
109static int tta_read_packet(AVFormatContext *s, AVPacket *pkt)
110{
111 TTAContext *c = s->priv_data;
112 AVStream *st = s->streams[0];
113 int size, ret;
114
115 // FIXME!
116 if (c->currentframe > c->totalframes)
117 return -1;
118
119 size = st->index_entries[c->currentframe].size;
120
121 ret = av_get_packet(s->pb, pkt, size);
122 pkt->dts = st->index_entries[c->currentframe++].timestamp;
123 return ret;
124}
125
126static int tta_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
127{
128 TTAContext *c = s->priv_data;
129 AVStream *st = s->streams[stream_index];
130 int index = av_index_search_timestamp(st, timestamp, flags);
131 if (index < 0)
132 return -1;
133
134 c->currentframe = index;
135 url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
136
137 return 0;
138}
139
140AVInputFormat tta_demuxer = {
141 "tta",
142 NULL_IF_CONFIG_SMALL("True Audio"),
143 sizeof(TTAContext),
144 tta_probe,
145 tta_read_header,
146 tta_read_packet,
147 NULL,
148 tta_read_seek,
149 .extensions = "tta",
150};
diff --git a/src/plugins/ffmpeg/libavformat/txd.c b/src/plugins/ffmpeg/libavformat/txd.c
deleted file mode 100644
index d2c3996..0000000
--- a/src/plugins/ffmpeg/libavformat/txd.c
+++ /dev/null
@@ -1,98 +0,0 @@
1/*
2 * Renderware TeXture Dictionary (.txd) demuxer
3 * Copyright (c) 2007 Ivo van Poorten
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 "avformat.h"
23
24#define TXD_FILE 0x16
25#define TXD_INFO 0x01
26#define TXD_EXTRA 0x03
27#define TXD_TEXTURE 0x15
28#define TXD_TEXTURE_DATA 0x01
29#define TXD_MARKER 0x1803ffff
30#define TXD_MARKER2 0x1003ffff
31
32static int txd_probe(AVProbeData * pd) {
33 if (AV_RL32(pd->buf ) == TXD_FILE &&
34 (AV_RL32(pd->buf+8) == TXD_MARKER || AV_RL32(pd->buf+8) == TXD_MARKER2))
35 return AVPROBE_SCORE_MAX;
36 return 0;
37}
38
39static int txd_read_header(AVFormatContext *s, AVFormatParameters *ap) {
40 AVStream *st;
41
42 st = av_new_stream(s, 0);
43 if (!st)
44 return AVERROR(ENOMEM);
45 st->codec->codec_type = CODEC_TYPE_VIDEO;
46 st->codec->codec_id = CODEC_ID_TXD;
47 st->codec->time_base.den = 5;
48 st->codec->time_base.num = 1;
49 /* the parameters will be extracted from the compressed bitstream */
50 return 0;
51}
52
53static int txd_read_packet(AVFormatContext *s, AVPacket *pkt) {
54 ByteIOContext *pb = s->pb;
55 unsigned int id, chunk_size, marker;
56 int ret;
57
58next_chunk:
59 id = get_le32(pb);
60 chunk_size = get_le32(pb);
61 marker = get_le32(pb);
62
63 if (url_feof(s->pb))
64 return AVERROR(EIO);
65 if (marker != TXD_MARKER && marker != TXD_MARKER2) {
66 av_log(NULL, AV_LOG_ERROR, "marker does not match\n");
67 return AVERROR(EIO);
68 }
69
70 switch (id) {
71 case TXD_INFO:
72 if (chunk_size > 100)
73 break;
74 case TXD_EXTRA:
75 url_fskip(s->pb, chunk_size);
76 case TXD_FILE:
77 case TXD_TEXTURE:
78 goto next_chunk;
79 default:
80 av_log(NULL, AV_LOG_ERROR, "unknown chunk id %i\n", id);
81 return AVERROR(EIO);
82 }
83
84 ret = av_get_packet(s->pb, pkt, chunk_size);
85 pkt->stream_index = 0;
86
87 return ret <= 0 ? AVERROR(EIO) : ret;
88}
89
90AVInputFormat txd_demuxer =
91{
92 "txd",
93 NULL_IF_CONFIG_SMALL("txd format"),
94 0,
95 txd_probe,
96 txd_read_header,
97 txd_read_packet,
98};
diff --git a/src/plugins/ffmpeg/libavformat/udp.c b/src/plugins/ffmpeg/libavformat/udp.c
deleted file mode 100644
index effe699..0000000
--- a/src/plugins/ffmpeg/libavformat/udp.c
+++ /dev/null
@@ -1,496 +0,0 @@
1/*
2 * UDP prototype streaming system
3 * Copyright (c) 2000, 2001, 2002 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/**
23 * @file udp.c
24 * UDP protocol
25 */
26
27#include "avformat.h"
28#include <unistd.h>
29#include "network.h"
30#include "os_support.h"
31
32#ifndef IPV6_ADD_MEMBERSHIP
33#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
34#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
35#endif
36#ifndef IN_MULTICAST
37#define IN_MULTICAST(a) ((((uint32_t)(a)) & 0xf0000000) == 0xe0000000)
38#endif
39#ifndef IN6_IS_ADDR_MULTICAST
40#define IN6_IS_ADDR_MULTICAST(a) (((uint8_t *) (a))[0] == 0xff)
41#endif
42
43typedef struct {
44 int udp_fd;
45 int ttl;
46 int is_multicast;
47 int local_port;
48 int reuse_socket;
49#ifndef CONFIG_IPV6
50 struct sockaddr_in dest_addr;
51#else
52 struct sockaddr_storage dest_addr;
53#endif
54 int dest_addr_len;
55} UDPContext;
56
57#define UDP_TX_BUF_SIZE 32768
58#define UDP_MAX_PKT_SIZE 65536
59
60static int udp_set_multicast_ttl(int sockfd, int mcastTTL, struct sockaddr *addr) {
61#ifdef IP_MULTICAST_TTL
62 if (addr->sa_family == AF_INET) {
63 if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
64 av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL): %s\n", strerror(errno));
65 return -1;
66 }
67 }
68#endif
69#ifdef CONFIG_IPV6
70 if (addr->sa_family == AF_INET6) {
71 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
72 av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS): %s\n", strerror(errno));
73 return -1;
74 }
75 }
76#endif
77 return 0;
78}
79
80static int udp_join_multicast_group(int sockfd, struct sockaddr *addr) {
81#ifdef IP_ADD_MEMBERSHIP
82 if (addr->sa_family == AF_INET) {
83 struct ip_mreq mreq;
84
85 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
86 mreq.imr_interface.s_addr= INADDR_ANY;
87 if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
88 av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP): %s\n", strerror(errno));
89 return -1;
90 }
91 }
92#endif
93#ifdef CONFIG_IPV6
94 if (addr->sa_family == AF_INET6) {
95 struct ipv6_mreq mreq6;
96
97 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
98 mreq6.ipv6mr_interface= 0;
99 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
100 av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP): %s\n", strerror(errno));
101 return -1;
102 }
103 }
104#endif
105 return 0;
106}
107
108static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr) {
109#ifdef IP_DROP_MEMBERSHIP
110 if (addr->sa_family == AF_INET) {
111 struct ip_mreq mreq;
112
113 mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
114 mreq.imr_interface.s_addr= INADDR_ANY;
115 if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
116 av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP): %s\n", strerror(errno));
117 return -1;
118 }
119 }
120#endif
121#ifdef CONFIG_IPV6
122 if (addr->sa_family == AF_INET6) {
123 struct ipv6_mreq mreq6;
124
125 memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
126 mreq6.ipv6mr_interface= 0;
127 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
128 av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP): %s\n", strerror(errno));
129 return -1;
130 }
131 }
132#endif
133 return 0;
134}
135
136#ifdef CONFIG_IPV6
137static struct addrinfo* udp_ipv6_resolve_host(const char *hostname, int port, int type, int family, int flags) {
138 struct addrinfo hints, *res = 0;
139 int error;
140 char sport[16];
141 const char *node = 0, *service = "0";
142
143 if (port > 0) {
144 snprintf(sport, sizeof(sport), "%d", port);
145 service = sport;
146 }
147 if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
148 node = hostname;
149 }
150 memset(&hints, 0, sizeof(hints));
151 hints.ai_socktype = type;
152 hints.ai_family = family;
153 hints.ai_flags = flags;
154 if ((error = getaddrinfo(node, service, &hints, &res))) {
155 av_log(NULL, AV_LOG_ERROR, "udp_ipv6_resolve_host: %s\n", gai_strerror(error));
156 }
157
158 return res;
159}
160
161static int udp_set_url(struct sockaddr_storage *addr, const char *hostname, int port) {
162 struct addrinfo *res0;
163 int addr_len;
164
165 res0 = udp_ipv6_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
166 if (res0 == 0) return AVERROR(EIO);
167 memcpy(addr, res0->ai_addr, res0->ai_addrlen);
168 addr_len = res0->ai_addrlen;
169 freeaddrinfo(res0);
170
171 return addr_len;
172}
173
174static int is_multicast_address(struct sockaddr_storage *addr)
175{
176 if (addr->ss_family == AF_INET) {
177 return IN_MULTICAST(ntohl(((struct sockaddr_in *)addr)->sin_addr.s_addr));
178 }
179 if (addr->ss_family == AF_INET6) {
180 return IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)addr)->sin6_addr);
181 }
182
183 return 0;
184}
185
186static int udp_socket_create(UDPContext *s, struct sockaddr_storage *addr, int *addr_len)
187{
188 int udp_fd = -1;
189 struct addrinfo *res0 = NULL, *res = NULL;
190 int family = AF_UNSPEC;
191
192 if (((struct sockaddr *) &s->dest_addr)->sa_family)
193 family = ((struct sockaddr *) &s->dest_addr)->sa_family;
194 res0 = udp_ipv6_resolve_host(0, s->local_port, SOCK_DGRAM, family, AI_PASSIVE);
195 if (res0 == 0)
196 goto fail;
197 for (res = res0; res; res=res->ai_next) {
198 udp_fd = socket(res->ai_family, SOCK_DGRAM, 0);
199 if (udp_fd > 0) break;
200 av_log(NULL, AV_LOG_ERROR, "socket: %s\n", strerror(errno));
201 }
202
203 if (udp_fd < 0)
204 goto fail;
205
206 memcpy(addr, res->ai_addr, res->ai_addrlen);
207 *addr_len = res->ai_addrlen;
208
209 freeaddrinfo(res0);
210
211 return udp_fd;
212
213 fail:
214 if (udp_fd >= 0)
215 closesocket(udp_fd);
216 if(res0)
217 freeaddrinfo(res0);
218 return -1;
219}
220
221static int udp_port(struct sockaddr_storage *addr, int addr_len)
222{
223 char sbuf[sizeof(int)*3+1];
224
225 if (getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0, sbuf, sizeof(sbuf), NI_NUMERICSERV) != 0) {
226 av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", strerror(errno));
227 return -1;
228 }
229
230 return strtol(sbuf, NULL, 10);
231}
232
233#else
234
235static int udp_set_url(struct sockaddr_in *addr, const char *hostname, int port)
236{
237 /* set the destination address */
238 if (resolve_host(&addr->sin_addr, hostname) < 0)
239 return AVERROR(EIO);
240 addr->sin_family = AF_INET;
241 addr->sin_port = htons(port);
242
243 return sizeof(struct sockaddr_in);
244}
245
246static int is_multicast_address(struct sockaddr_in *addr)
247{
248 return IN_MULTICAST(ntohl(addr->sin_addr.s_addr));
249}
250
251static int udp_socket_create(UDPContext *s, struct sockaddr_in *addr, int *addr_len)
252{
253 int fd;
254
255 fd = socket(AF_INET, SOCK_DGRAM, 0);
256 if (fd < 0)
257 return -1;
258
259 addr->sin_family = AF_INET;
260 addr->sin_addr.s_addr = htonl (INADDR_ANY);
261 addr->sin_port = htons(s->local_port);
262 *addr_len = sizeof(struct sockaddr_in);
263
264 return fd;
265}
266
267static int udp_port(struct sockaddr_in *addr, int len)
268{
269 return ntohs(addr->sin_port);
270}
271#endif /* CONFIG_IPV6 */
272
273
274/**
275 * If no filename is given to av_open_input_file because you want to
276 * get the local port first, then you must call this function to set
277 * the remote server address.
278 *
279 * url syntax: udp://host:port[?option=val...]
280 * option: 'ttl=n' : set the ttl value (for multicast only)
281 * 'localport=n' : set the local port
282 * 'pkt_size=n' : set max packet size
283 * 'reuse=1' : enable reusing the socket
284 *
285 * @param s1 media file context
286 * @param uri of the remote server
287 * @return zero if no error.
288 */
289int udp_set_remote_url(URLContext *h, const char *uri)
290{
291 UDPContext *s = h->priv_data;
292 char hostname[256];
293 int port;
294
295 url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
296
297 /* set the destination address */
298 s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
299 if (s->dest_addr_len < 0) {
300 return AVERROR(EIO);
301 }
302 s->is_multicast = is_multicast_address(&s->dest_addr);
303
304 return 0;
305}
306
307/**
308 * Return the local port used by the UDP connexion
309 * @param s1 media file context
310 * @return the local port number
311 */
312int udp_get_local_port(URLContext *h)
313{
314 UDPContext *s = h->priv_data;
315 return s->local_port;
316}
317
318/**
319 * Return the udp file handle for select() usage to wait for several RTP
320 * streams at the same time.
321 * @param h media file context
322 */
323int udp_get_file_handle(URLContext *h)
324{
325 UDPContext *s = h->priv_data;
326 return s->udp_fd;
327}
328
329/* put it in UDP context */
330/* return non zero if error */
331static int udp_open(URLContext *h, const char *uri, int flags)
332{
333 char hostname[1024];
334 int port, udp_fd = -1, tmp;
335 UDPContext *s = NULL;
336 int is_output;
337 const char *p;
338 char buf[256];
339#ifndef CONFIG_IPV6
340 struct sockaddr_in my_addr;
341#else
342 struct sockaddr_storage my_addr;
343#endif
344 int len;
345
346 h->is_streamed = 1;
347 h->max_packet_size = 1472;
348
349 is_output = (flags & URL_WRONLY);
350
351 s = av_mallocz(sizeof(UDPContext));
352 if (!s)
353 return AVERROR(ENOMEM);
354
355 h->priv_data = s;
356 s->ttl = 16;
357 p = strchr(uri, '?');
358 if (p) {
359 s->reuse_socket = find_info_tag(buf, sizeof(buf), "reuse", p);
360 if (find_info_tag(buf, sizeof(buf), "ttl", p)) {
361 s->ttl = strtol(buf, NULL, 10);
362 }
363 if (find_info_tag(buf, sizeof(buf), "localport", p)) {
364 s->local_port = strtol(buf, NULL, 10);
365 }
366 if (find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
367 h->max_packet_size = strtol(buf, NULL, 10);
368 }
369 }
370
371 /* fill the dest addr */
372 url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
373
374 /* XXX: fix url_split */
375 if (hostname[0] == '\0' || hostname[0] == '?') {
376 /* only accepts null hostname if input */
377 if (flags & URL_WRONLY)
378 goto fail;
379 } else {
380 udp_set_remote_url(h, uri);
381 }
382
383 if(!ff_network_init())
384 return AVERROR(EIO);
385
386 if (s->is_multicast && !(h->flags & URL_WRONLY))
387 s->local_port = port;
388 udp_fd = udp_socket_create(s, &my_addr, &len);
389 if (udp_fd < 0)
390 goto fail;
391
392 if (s->reuse_socket)
393 if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
394 goto fail;
395
396 /* the bind is needed to give a port to the socket now */
397 if (bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0)
398 goto fail;
399
400 len = sizeof(my_addr);
401 getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
402 s->local_port = udp_port(&my_addr, len);
403
404 if (s->is_multicast) {
405 if (h->flags & URL_WRONLY) {
406 /* output */
407 if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
408 goto fail;
409 } else {
410 /* input */
411 if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
412 goto fail;
413 }
414 }
415
416 if (is_output) {
417 /* limit the tx buf size to limit latency */
418 tmp = UDP_TX_BUF_SIZE;
419 if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
420 av_log(NULL, AV_LOG_ERROR, "setsockopt(SO_SNDBUF): %s\n", strerror(errno));
421 goto fail;
422 }
423 } else {
424 /* set udp recv buffer size to the largest possible udp packet size to
425 * avoid losing data on OSes that set this too low by default. */
426 tmp = UDP_MAX_PKT_SIZE;
427 setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp));
428 }
429
430 s->udp_fd = udp_fd;
431 return 0;
432 fail:
433 if (udp_fd >= 0)
434 closesocket(udp_fd);
435 av_free(s);
436 return AVERROR(EIO);
437}
438
439static int udp_read(URLContext *h, uint8_t *buf, int size)
440{
441 UDPContext *s = h->priv_data;
442 int len;
443
444 for(;;) {
445 len = recv(s->udp_fd, buf, size, 0);
446 if (len < 0) {
447 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
448 ff_neterrno() != FF_NETERROR(EINTR))
449 return AVERROR(EIO);
450 } else {
451 break;
452 }
453 }
454 return len;
455}
456
457static int udp_write(URLContext *h, uint8_t *buf, int size)
458{
459 UDPContext *s = h->priv_data;
460 int ret;
461
462 for(;;) {
463 ret = sendto (s->udp_fd, buf, size, 0,
464 (struct sockaddr *) &s->dest_addr,
465 s->dest_addr_len);
466 if (ret < 0) {
467 if (ff_neterrno() != FF_NETERROR(EINTR) &&
468 ff_neterrno() != FF_NETERROR(EAGAIN))
469 return AVERROR(EIO);
470 } else {
471 break;
472 }
473 }
474 return size;
475}
476
477static int udp_close(URLContext *h)
478{
479 UDPContext *s = h->priv_data;
480
481 if (s->is_multicast && !(h->flags & URL_WRONLY))
482 udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
483 closesocket(s->udp_fd);
484 ff_network_close();
485 av_free(s);
486 return 0;
487}
488
489URLProtocol udp_protocol = {
490 "udp",
491 udp_open,
492 udp_read,
493 udp_write,
494 NULL, /* seek */
495 udp_close,
496};
diff --git a/src/plugins/ffmpeg/libavformat/utils.c b/src/plugins/ffmpeg/libavformat/utils.c
deleted file mode 100644
index 89a5cec..0000000
--- a/src/plugins/ffmpeg/libavformat/utils.c
+++ /dev/null
@@ -1,3216 +0,0 @@
1/*
2 * various utility functions for use within FFmpeg
3 * Copyright (c) 2000, 2001, 2002 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#include "avformat.h"
22#include "libavcodec/opt.h"
23#include "libavutil/avstring.h"
24#include "riff.h"
25#include <sys/time.h>
26#include <time.h>
27
28#undef NDEBUG
29#include <assert.h>
30
31/**
32 * @file libavformat/utils.c
33 * various utility functions for use within FFmpeg
34 */
35
36static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den);
37static void av_frac_add(AVFrac *f, int64_t incr);
38
39/** head of registered input format linked list */
40AVInputFormat *first_iformat = NULL;
41/** head of registered output format linked list */
42AVOutputFormat *first_oformat = NULL;
43
44AVInputFormat *av_iformat_next(AVInputFormat *f)
45{
46 if(f) return f->next;
47 else return first_iformat;
48}
49
50AVOutputFormat *av_oformat_next(AVOutputFormat *f)
51{
52 if(f) return f->next;
53 else return first_oformat;
54}
55
56void av_register_input_format(AVInputFormat *format)
57{
58 AVInputFormat **p;
59 p = &first_iformat;
60 while (*p != NULL) p = &(*p)->next;
61 *p = format;
62 format->next = NULL;
63}
64
65void av_register_output_format(AVOutputFormat *format)
66{
67 AVOutputFormat **p;
68 p = &first_oformat;
69 while (*p != NULL) p = &(*p)->next;
70 *p = format;
71 format->next = NULL;
72}
73
74int match_ext(const char *filename, const char *extensions)
75{
76 const char *ext, *p;
77 char ext1[32], *q;
78
79 if(!filename)
80 return 0;
81
82 ext = strrchr(filename, '.');
83 if (ext) {
84 ext++;
85 p = extensions;
86 for(;;) {
87 q = ext1;
88 while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
89 *q++ = *p++;
90 *q = '\0';
91 if (!strcasecmp(ext1, ext))
92 return 1;
93 if (*p == '\0')
94 break;
95 p++;
96 }
97 }
98 return 0;
99}
100
101AVOutputFormat *guess_format(const char *short_name, const char *filename,
102 const char *mime_type)
103{
104 AVOutputFormat *fmt, *fmt_found;
105 int score_max, score;
106
107 /* specific test for image sequences */
108#ifdef CONFIG_IMAGE2_MUXER
109 if (!short_name && filename &&
110 av_filename_number_test(filename) &&
111 av_guess_image2_codec(filename) != CODEC_ID_NONE) {
112 return guess_format("image2", NULL, NULL);
113 }
114#endif
115 /* Find the proper file type. */
116 fmt_found = NULL;
117 score_max = 0;
118 fmt = first_oformat;
119 while (fmt != NULL) {
120 score = 0;
121 if (fmt->name && short_name && !strcmp(fmt->name, short_name))
122 score += 100;
123 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
124 score += 10;
125 if (filename && fmt->extensions &&
126 match_ext(filename, fmt->extensions)) {
127 score += 5;
128 }
129 if (score > score_max) {
130 score_max = score;
131 fmt_found = fmt;
132 }
133 fmt = fmt->next;
134 }
135 return fmt_found;
136}
137
138AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
139 const char *mime_type)
140{
141 AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
142
143 if (fmt) {
144 AVOutputFormat *stream_fmt;
145 char stream_format_name[64];
146
147 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
148 stream_fmt = guess_format(stream_format_name, NULL, NULL);
149
150 if (stream_fmt)
151 fmt = stream_fmt;
152 }
153
154 return fmt;
155}
156
157enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
158 const char *filename, const char *mime_type, enum CodecType type){
159 if(type == CODEC_TYPE_VIDEO){
160 enum CodecID codec_id= CODEC_ID_NONE;
161
162#ifdef CONFIG_IMAGE2_MUXER
163 if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
164 codec_id= av_guess_image2_codec(filename);
165 }
166#endif
167 if(codec_id == CODEC_ID_NONE)
168 codec_id= fmt->video_codec;
169 return codec_id;
170 }else if(type == CODEC_TYPE_AUDIO)
171 return fmt->audio_codec;
172 else
173 return CODEC_ID_NONE;
174}
175
176AVInputFormat *av_find_input_format(const char *short_name)
177{
178 AVInputFormat *fmt;
179 for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
180 if (!strcmp(fmt->name, short_name))
181 return fmt;
182 }
183 return NULL;
184}
185
186/* memory handling */
187
188void av_destruct_packet(AVPacket *pkt)
189{
190 av_free(pkt->data);
191 pkt->data = NULL; pkt->size = 0;
192}
193
194void av_init_packet(AVPacket *pkt)
195{
196 pkt->pts = AV_NOPTS_VALUE;
197 pkt->dts = AV_NOPTS_VALUE;
198 pkt->pos = -1;
199 pkt->duration = 0;
200 pkt->flags = 0;
201 pkt->stream_index = 0;
202 pkt->destruct= av_destruct_packet_nofree;
203}
204
205int av_new_packet(AVPacket *pkt, int size)
206{
207 uint8_t *data;
208 if((unsigned)size > (unsigned)size + FF_INPUT_BUFFER_PADDING_SIZE)
209 return AVERROR(ENOMEM);
210 data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
211 if (!data)
212 return AVERROR(ENOMEM);
213 memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
214
215 av_init_packet(pkt);
216 pkt->data = data;
217 pkt->size = size;
218 pkt->destruct = av_destruct_packet;
219 return 0;
220}
221
222int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
223{
224 int ret= av_new_packet(pkt, size);
225
226 if(ret<0)
227 return ret;
228
229 pkt->pos= url_ftell(s);
230
231 ret= get_buffer(s, pkt->data, size);
232 if(ret<=0)
233 av_free_packet(pkt);
234 else
235 pkt->size= ret;
236
237 return ret;
238}
239
240int av_dup_packet(AVPacket *pkt)
241{
242 if (pkt->destruct != av_destruct_packet) {
243 uint8_t *data;
244 /* We duplicate the packet and don't forget to add the padding again. */
245 if((unsigned)pkt->size > (unsigned)pkt->size + FF_INPUT_BUFFER_PADDING_SIZE)
246 return AVERROR(ENOMEM);
247 data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
248 if (!data) {
249 return AVERROR(ENOMEM);
250 }
251 memcpy(data, pkt->data, pkt->size);
252 memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
253 pkt->data = data;
254 pkt->destruct = av_destruct_packet;
255 }
256 return 0;
257}
258
259int av_filename_number_test(const char *filename)
260{
261 char buf[1024];
262 return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
263}
264
265static AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
266{
267 AVInputFormat *fmt1, *fmt;
268 int score;
269
270 fmt = NULL;
271 for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
272 if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
273 continue;
274 score = 0;
275 if (fmt1->read_probe) {
276 score = fmt1->read_probe(pd);
277 } else if (fmt1->extensions) {
278 if (match_ext(pd->filename, fmt1->extensions)) {
279 score = 50;
280 }
281 }
282 if (score > *score_max) {
283 *score_max = score;
284 fmt = fmt1;
285 }else if (score == *score_max)
286 fmt = NULL;
287 }
288 return fmt;
289}
290
291AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
292 int score=0;
293 return av_probe_input_format2(pd, is_opened, &score);
294}
295
296static int set_codec_from_probe_data(AVStream *st, AVProbeData *pd, int score)
297{
298 AVInputFormat *fmt;
299 fmt = av_probe_input_format2(pd, 1, &score);
300
301 if (fmt) {
302 if (!strcmp(fmt->name, "mp3"))
303 st->codec->codec_id = CODEC_ID_MP3;
304 else if (!strcmp(fmt->name, "ac3"))
305 st->codec->codec_id = CODEC_ID_AC3;
306 else if (!strcmp(fmt->name, "mpegvideo"))
307 st->codec->codec_id = CODEC_ID_MPEG2VIDEO;
308 else if (!strcmp(fmt->name, "h264"))
309 st->codec->codec_id = CODEC_ID_H264;
310 }
311 return !!fmt;
312}
313
314/************************************************************/
315/* input media file */
316
317/**
318 * Open a media file from an IO stream. 'fmt' must be specified.
319 */
320static const char* format_to_name(void* ptr)
321{
322 AVFormatContext* fc = (AVFormatContext*) ptr;
323 if(fc->iformat) return fc->iformat->name;
324 else if(fc->oformat) return fc->oformat->name;
325 else return "NULL";
326}
327
328#define OFFSET(x) offsetof(AVFormatContext,x)
329#define DEFAULT 0 //should be NAN but it does not work as it is not a constant in glibc as required by ANSI/ISO C
330//these names are too long to be readable
331#define E AV_OPT_FLAG_ENCODING_PARAM
332#define D AV_OPT_FLAG_DECODING_PARAM
333
334static const AVOption options[]={
335{"probesize", NULL, OFFSET(probesize), FF_OPT_TYPE_INT, 32000, 32, INT_MAX, D}, /* 32000 from mpegts.c: 1.0 second at 24Mbit/s */
336{"muxrate", "set mux rate", OFFSET(mux_rate), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
337{"packetsize", "set packet size", OFFSET(packet_size), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
338{"fflags", NULL, OFFSET(flags), FF_OPT_TYPE_FLAGS, DEFAULT, INT_MIN, INT_MAX, D|E, "fflags"},
339{"ignidx", "ignore index", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_IGNIDX, INT_MIN, INT_MAX, D, "fflags"},
340{"genpts", "generate pts", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_GENPTS, INT_MIN, INT_MAX, D, "fflags"},
341{"track", " set the track number", OFFSET(track), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
342{"year", "set the year", OFFSET(year), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, E},
343{"analyzeduration", "how many microseconds are analyzed to estimate duration", OFFSET(max_analyze_duration), FF_OPT_TYPE_INT, 3*AV_TIME_BASE, 0, INT_MAX, D},
344{"cryptokey", "decryption key", OFFSET(key), FF_OPT_TYPE_BINARY, 0, 0, 0, D},
345{"indexmem", "max memory used for timestamp index (per stream)", OFFSET(max_index_size), FF_OPT_TYPE_INT, 1<<20, 0, INT_MAX, D},
346{"rtbufsize", "max memory used for buffering real-time frames", OFFSET(max_picture_buffer), FF_OPT_TYPE_INT, 3041280, 0, INT_MAX, D}, /* defaults to 1s of 15fps 352x288 YUYV422 video */
347{"fdebug", "print specific debug info", OFFSET(debug), FF_OPT_TYPE_FLAGS, DEFAULT, 0, INT_MAX, E|D, "fdebug"},
348{"ts", NULL, 0, FF_OPT_TYPE_CONST, FF_FDEBUG_TS, INT_MIN, INT_MAX, E|D, "fdebug"},
349{NULL},
350};
351
352#undef E
353#undef D
354#undef DEFAULT
355
356static const AVClass av_format_context_class = { "AVFormatContext", format_to_name, options };
357
358static void avformat_get_context_defaults(AVFormatContext *s)
359{
360 memset(s, 0, sizeof(AVFormatContext));
361
362 s->av_class = &av_format_context_class;
363
364 av_opt_set_defaults(s);
365}
366
367AVFormatContext *av_alloc_format_context(void)
368{
369 AVFormatContext *ic;
370 ic = av_malloc(sizeof(AVFormatContext));
371 if (!ic) return ic;
372 avformat_get_context_defaults(ic);
373 ic->av_class = &av_format_context_class;
374 return ic;
375}
376
377int av_open_input_stream(AVFormatContext **ic_ptr,
378 ByteIOContext *pb, const char *filename,
379 AVInputFormat *fmt, AVFormatParameters *ap)
380{
381 int err;
382 AVFormatContext *ic;
383 AVFormatParameters default_ap;
384
385 if(!ap){
386 ap=&default_ap;
387 memset(ap, 0, sizeof(default_ap));
388 }
389
390 if(!ap->prealloced_context)
391 ic = av_alloc_format_context();
392 else
393 ic = *ic_ptr;
394 if (!ic) {
395 err = AVERROR(ENOMEM);
396 goto fail;
397 }
398 ic->iformat = fmt;
399 ic->pb = pb;
400 ic->duration = AV_NOPTS_VALUE;
401 ic->start_time = AV_NOPTS_VALUE;
402 av_strlcpy(ic->filename, filename, sizeof(ic->filename));
403
404 /* allocate private data */
405 if (fmt->priv_data_size > 0) {
406 ic->priv_data = av_mallocz(fmt->priv_data_size);
407 if (!ic->priv_data) {
408 err = AVERROR(ENOMEM);
409 goto fail;
410 }
411 } else {
412 ic->priv_data = NULL;
413 }
414
415 if (ic->iformat->read_header) {
416 err = ic->iformat->read_header(ic, ap);
417 if (err < 0)
418 goto fail;
419 }
420
421 if (pb && !ic->data_offset)
422 ic->data_offset = url_ftell(ic->pb);
423
424 *ic_ptr = ic;
425 return 0;
426 fail:
427 if (ic) {
428 int i;
429 av_freep(&ic->priv_data);
430 for(i=0;i<ic->nb_streams;i++) {
431 AVStream *st = ic->streams[i];
432 if (st) {
433 av_free(st->priv_data);
434 av_free(st->codec->extradata);
435 }
436 av_free(st);
437 }
438 }
439 av_free(ic);
440 *ic_ptr = NULL;
441 return err;
442}
443
444/** size of probe buffer, for guessing file type from file contents */
445#define PROBE_BUF_MIN 2048
446#define PROBE_BUF_MAX (1<<20)
447
448int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
449 AVInputFormat *fmt,
450 int buf_size,
451 AVFormatParameters *ap)
452{
453 int err, probe_size;
454 AVProbeData probe_data, *pd = &probe_data;
455 ByteIOContext *pb = NULL;
456
457 pd->filename = "";
458 if (filename)
459 pd->filename = filename;
460 pd->buf = NULL;
461 pd->buf_size = 0;
462
463 if (!fmt) {
464 /* guess format if no file can be opened */
465 fmt = av_probe_input_format(pd, 0);
466 }
467
468 /* Do not open file if the format does not need it. XXX: specific
469 hack needed to handle RTSP/TCP */
470 if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
471 /* if no file needed do not try to open one */
472 if ((err=url_fopen(&pb, filename, URL_RDONLY)) < 0) {
473 goto fail;
474 }
475 if (buf_size > 0) {
476 url_setbufsize(pb, buf_size);
477 }
478
479 for(probe_size= PROBE_BUF_MIN; probe_size<=PROBE_BUF_MAX && !fmt; probe_size<<=1){
480 int score= probe_size < PROBE_BUF_MAX ? AVPROBE_SCORE_MAX/4 : 0;
481 /* read probe data */
482 pd->buf= av_realloc(pd->buf, probe_size + AVPROBE_PADDING_SIZE);
483 pd->buf_size = get_buffer(pb, pd->buf, probe_size);
484 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
485 if (url_fseek(pb, 0, SEEK_SET) < 0) {
486 url_fclose(pb);
487 if (url_fopen(&pb, filename, URL_RDONLY) < 0) {
488 pb = NULL;
489 err = AVERROR(EIO);
490 goto fail;
491 }
492 }
493 /* guess file format */
494 fmt = av_probe_input_format2(pd, 1, &score);
495 }
496 av_freep(&pd->buf);
497 }
498
499 /* if still no format found, error */
500 if (!fmt) {
501 err = AVERROR_NOFMT;
502 goto fail;
503 }
504
505 /* check filename in case an image number is expected */
506 if (fmt->flags & AVFMT_NEEDNUMBER) {
507 if (!av_filename_number_test(filename)) {
508 err = AVERROR_NUMEXPECTED;
509 goto fail;
510 }
511 }
512 err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
513 if (err)
514 goto fail;
515 return 0;
516 fail:
517 av_freep(&pd->buf);
518 if (pb)
519 url_fclose(pb);
520 *ic_ptr = NULL;
521 return err;
522
523}
524
525/*******************************************************/
526
527static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt){
528 AVPacketList *pktl;
529 AVPacketList **plast_pktl= packet_buffer;
530
531 while(*plast_pktl) plast_pktl= &(*plast_pktl)->next; //FIXME maybe maintain pointer to the last?
532
533 pktl = av_mallocz(sizeof(AVPacketList));
534 if (!pktl)
535 return NULL;
536
537 /* add the packet in the buffered packet list */
538 *plast_pktl = pktl;
539 pktl->pkt= *pkt;
540 return &pktl->pkt;
541}
542
543int av_read_packet(AVFormatContext *s, AVPacket *pkt)
544{
545 int ret;
546 AVStream *st;
547
548 for(;;){
549 AVPacketList *pktl = s->raw_packet_buffer;
550
551 if (pktl) {
552 *pkt = pktl->pkt;
553 if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE){
554 s->raw_packet_buffer = pktl->next;
555 av_free(pktl);
556 return 0;
557 }
558 }
559
560 av_init_packet(pkt);
561 ret= s->iformat->read_packet(s, pkt);
562 if (ret < 0)
563 return ret;
564 st= s->streams[pkt->stream_index];
565
566 switch(st->codec->codec_type){
567 case CODEC_TYPE_VIDEO:
568 if(s->video_codec_id) st->codec->codec_id= s->video_codec_id;
569 break;
570 case CODEC_TYPE_AUDIO:
571 if(s->audio_codec_id) st->codec->codec_id= s->audio_codec_id;
572 break;
573 case CODEC_TYPE_SUBTITLE:
574 if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
575 break;
576 }
577
578 if(!pktl && st->codec->codec_id!=CODEC_ID_PROBE)
579 return ret;
580
581 add_to_pktbuf(&s->raw_packet_buffer, pkt);
582
583 if(st->codec->codec_id == CODEC_ID_PROBE){
584 AVProbeData *pd = &st->probe_data;
585
586 pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
587 memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
588 pd->buf_size += pkt->size;
589 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
590
591 if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
592 set_codec_from_probe_data(st, pd, 1);
593 if(st->codec->codec_id != CODEC_ID_PROBE){
594 pd->buf_size=0;
595 av_freep(&pd->buf);
596 }
597 }
598 }
599 }
600}
601
602/**********************************************************/
603
604/**
605 * Get the number of samples of an audio frame. Return -1 on error.
606 */
607static int get_audio_frame_size(AVCodecContext *enc, int size)
608{
609 int frame_size;
610
611 if(enc->codec_id == CODEC_ID_VORBIS)
612 return -1;
613
614 if (enc->frame_size <= 1) {
615 int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
616
617 if (bits_per_sample) {
618 if (enc->channels == 0)
619 return -1;
620 frame_size = (size << 3) / (bits_per_sample * enc->channels);
621 } else {
622 /* used for example by ADPCM codecs */
623 if (enc->bit_rate == 0)
624 return -1;
625 frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate;
626 }
627 } else {
628 frame_size = enc->frame_size;
629 }
630 return frame_size;
631}
632
633
634/**
635 * Return the frame duration in seconds. Return 0 if not available.
636 */
637static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
638 AVCodecParserContext *pc, AVPacket *pkt)
639{
640 int frame_size;
641
642 *pnum = 0;
643 *pden = 0;
644 switch(st->codec->codec_type) {
645 case CODEC_TYPE_VIDEO:
646 if(st->time_base.num*1000LL > st->time_base.den){
647 *pnum = st->time_base.num;
648 *pden = st->time_base.den;
649 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
650 *pnum = st->codec->time_base.num;
651 *pden = st->codec->time_base.den;
652 if (pc && pc->repeat_pict) {
653 *pden *= 2;
654 *pnum = (*pnum) * (2 + pc->repeat_pict);
655 }
656 }
657 break;
658 case CODEC_TYPE_AUDIO:
659 frame_size = get_audio_frame_size(st->codec, pkt->size);
660 if (frame_size < 0)
661 break;
662 *pnum = frame_size;
663 *pden = st->codec->sample_rate;
664 break;
665 default:
666 break;
667 }
668}
669
670static int is_intra_only(AVCodecContext *enc){
671 if(enc->codec_type == CODEC_TYPE_AUDIO){
672 return 1;
673 }else if(enc->codec_type == CODEC_TYPE_VIDEO){
674 switch(enc->codec_id){
675 case CODEC_ID_MJPEG:
676 case CODEC_ID_MJPEGB:
677 case CODEC_ID_LJPEG:
678 case CODEC_ID_RAWVIDEO:
679 case CODEC_ID_DVVIDEO:
680 case CODEC_ID_HUFFYUV:
681 case CODEC_ID_FFVHUFF:
682 case CODEC_ID_ASV1:
683 case CODEC_ID_ASV2:
684 case CODEC_ID_VCR1:
685 return 1;
686 default: break;
687 }
688 }
689 return 0;
690}
691
692static void update_initial_timestamps(AVFormatContext *s, int stream_index,
693 int64_t dts, int64_t pts)
694{
695 AVStream *st= s->streams[stream_index];
696 AVPacketList *pktl= s->packet_buffer;
697
698 if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
699 return;
700
701 st->first_dts= dts - st->cur_dts;
702 st->cur_dts= dts;
703
704 for(; pktl; pktl= pktl->next){
705 if(pktl->pkt.stream_index != stream_index)
706 continue;
707 //FIXME think more about this check
708 if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
709 pktl->pkt.pts += st->first_dts;
710
711 if(pktl->pkt.dts != AV_NOPTS_VALUE)
712 pktl->pkt.dts += st->first_dts;
713
714 if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
715 st->start_time= pktl->pkt.pts;
716 }
717 if (st->start_time == AV_NOPTS_VALUE)
718 st->start_time = pts;
719}
720
721static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
722{
723 AVPacketList *pktl= s->packet_buffer;
724 int64_t cur_dts= 0;
725
726 if(st->first_dts != AV_NOPTS_VALUE){
727 cur_dts= st->first_dts;
728 for(; pktl; pktl= pktl->next){
729 if(pktl->pkt.stream_index == pkt->stream_index){
730 if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
731 break;
732 cur_dts -= pkt->duration;
733 }
734 }
735 pktl= s->packet_buffer;
736 st->first_dts = cur_dts;
737 }else if(st->cur_dts)
738 return;
739
740 for(; pktl; pktl= pktl->next){
741 if(pktl->pkt.stream_index != pkt->stream_index)
742 continue;
743 if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
744 && !pktl->pkt.duration){
745 pktl->pkt.dts= cur_dts;
746 if(!st->codec->has_b_frames)
747 pktl->pkt.pts= cur_dts;
748 cur_dts += pkt->duration;
749 pktl->pkt.duration= pkt->duration;
750 }else
751 break;
752 }
753 if(st->first_dts == AV_NOPTS_VALUE)
754 st->cur_dts= cur_dts;
755}
756
757static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
758 AVCodecParserContext *pc, AVPacket *pkt)
759{
760 int num, den, presentation_delayed, delay, i;
761 int64_t offset;
762
763 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
764 /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
765 pkt->dts -= 1LL<<st->pts_wrap_bits;
766 }
767
768 if (pkt->duration == 0) {
769 compute_frame_duration(&num, &den, st, pc, pkt);
770 if (den && num) {
771 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
772
773 if(pkt->duration != 0 && s->packet_buffer)
774 update_initial_durations(s, st, pkt);
775 }
776 }
777
778 /* correct timestamps with byte offset if demuxers only have timestamps
779 on packet boundaries */
780 if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
781 /* this will estimate bitrate based on this frame's duration and size */
782 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
783 if(pkt->pts != AV_NOPTS_VALUE)
784 pkt->pts += offset;
785 if(pkt->dts != AV_NOPTS_VALUE)
786 pkt->dts += offset;
787 }
788
789 /* do we have a video B-frame ? */
790 delay= st->codec->has_b_frames;
791 presentation_delayed = 0;
792 /* XXX: need has_b_frame, but cannot get it if the codec is
793 not initialized */
794 if (delay &&
795 pc && pc->pict_type != FF_B_TYPE)
796 presentation_delayed = 1;
797 /* This may be redundant, but it should not hurt. */
798 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
799 presentation_delayed = 1;
800
801// av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);
802 /* interpolate PTS and DTS if they are not present */
803 if(delay==0 || (delay==1 && pc)){
804 if (presentation_delayed) {
805 /* DTS = decompression timestamp */
806 /* PTS = presentation timestamp */
807 if (pkt->dts == AV_NOPTS_VALUE)
808 pkt->dts = st->last_IP_pts;
809 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
810 if (pkt->dts == AV_NOPTS_VALUE)
811 pkt->dts = st->cur_dts;
812
813 /* this is tricky: the dts must be incremented by the duration
814 of the frame we are displaying, i.e. the last I- or P-frame */
815 if (st->last_IP_duration == 0)
816 st->last_IP_duration = pkt->duration;
817 if(pkt->dts != AV_NOPTS_VALUE)
818 st->cur_dts = pkt->dts + st->last_IP_duration;
819 st->last_IP_duration = pkt->duration;
820 st->last_IP_pts= pkt->pts;
821 /* cannot compute PTS if not present (we can compute it only
822 by knowing the future */
823 } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
824 if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
825 int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
826 int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
827 if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
828 pkt->pts += pkt->duration;
829 // av_log(NULL, AV_LOG_DEBUG, "id:%d old:%"PRId64" new:%"PRId64" dur:%d cur:%"PRId64" size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);
830 }
831 }
832
833 /* presentation is not delayed : PTS and DTS are the same */
834 if(pkt->pts == AV_NOPTS_VALUE)
835 pkt->pts = pkt->dts;
836 update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
837 if(pkt->pts == AV_NOPTS_VALUE)
838 pkt->pts = st->cur_dts;
839 pkt->dts = pkt->pts;
840 if(pkt->pts != AV_NOPTS_VALUE)
841 st->cur_dts = pkt->pts + pkt->duration;
842 }
843 }
844
845 if(pkt->pts != AV_NOPTS_VALUE){
846 st->pts_buffer[0]= pkt->pts;
847 for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
848 st->pts_buffer[i]= (i-delay-1) * pkt->duration;
849 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
850 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
851 if(pkt->dts == AV_NOPTS_VALUE)
852 pkt->dts= st->pts_buffer[0];
853 if(delay>1){
854 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
855 }
856 if(pkt->dts > st->cur_dts)
857 st->cur_dts = pkt->dts;
858 }
859
860// av_log(NULL, AV_LOG_ERROR, "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n", presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
861
862 /* update flags */
863 if(is_intra_only(st->codec))
864 pkt->flags |= PKT_FLAG_KEY;
865 else if (pc) {
866 pkt->flags = 0;
867 /* keyframe computation */
868 if (pc->pict_type == FF_I_TYPE)
869 pkt->flags |= PKT_FLAG_KEY;
870 }
871}
872
873void av_destruct_packet_nofree(AVPacket *pkt)
874{
875 pkt->data = NULL; pkt->size = 0;
876}
877
878static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
879{
880 AVStream *st;
881 int len, ret, i;
882
883 av_init_packet(pkt);
884
885 for(;;) {
886 /* select current input stream component */
887 st = s->cur_st;
888 if (st) {
889 if (!st->need_parsing || !st->parser) {
890 /* no parsing needed: we just output the packet as is */
891 /* raw data support */
892 *pkt = s->cur_pkt;
893 compute_pkt_fields(s, st, NULL, pkt);
894 s->cur_st = NULL;
895 break;
896 } else if (s->cur_len > 0 && st->discard < AVDISCARD_ALL) {
897 len = av_parser_parse(st->parser, st->codec, &pkt->data, &pkt->size,
898 s->cur_ptr, s->cur_len,
899 s->cur_pkt.pts, s->cur_pkt.dts);
900 s->cur_pkt.pts = AV_NOPTS_VALUE;
901 s->cur_pkt.dts = AV_NOPTS_VALUE;
902 /* increment read pointer */
903 s->cur_ptr += len;
904 s->cur_len -= len;
905
906 /* return packet if any */
907 if (pkt->size) {
908 got_packet:
909 pkt->pos = s->cur_pkt.pos; // Isn't quite accurate but close.
910 pkt->duration = 0;
911 pkt->stream_index = st->index;
912 pkt->pts = st->parser->pts;
913 pkt->dts = st->parser->dts;
914 pkt->destruct = av_destruct_packet_nofree;
915 compute_pkt_fields(s, st, st->parser, pkt);
916
917 if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & PKT_FLAG_KEY){
918 ff_reduce_index(s, st->index);
919 av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
920 0, 0, AVINDEX_KEYFRAME);
921 }
922
923 break;
924 }
925 } else {
926 /* free packet */
927 av_free_packet(&s->cur_pkt);
928 s->cur_st = NULL;
929 }
930 } else {
931 /* read next packet */
932 ret = av_read_packet(s, &s->cur_pkt);
933 if (ret < 0) {
934 if (ret == AVERROR(EAGAIN))
935 return ret;
936 /* return the last frames, if any */
937 for(i = 0; i < s->nb_streams; i++) {
938 st = s->streams[i];
939 if (st->parser && st->need_parsing) {
940 av_parser_parse(st->parser, st->codec,
941 &pkt->data, &pkt->size,
942 NULL, 0,
943 AV_NOPTS_VALUE, AV_NOPTS_VALUE);
944 if (pkt->size)
945 goto got_packet;
946 }
947 }
948 /* no more packets: really terminate parsing */
949 return ret;
950 }
951
952 if(s->cur_pkt.pts != AV_NOPTS_VALUE &&
953 s->cur_pkt.dts != AV_NOPTS_VALUE &&
954 s->cur_pkt.pts < s->cur_pkt.dts){
955 av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
956 s->cur_pkt.stream_index,
957 s->cur_pkt.pts,
958 s->cur_pkt.dts,
959 s->cur_pkt.size);
960// av_free_packet(&s->cur_pkt);
961// return -1;
962 }
963
964 st = s->streams[s->cur_pkt.stream_index];
965 if(s->debug & FF_FDEBUG_TS)
966 av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, flags=%d\n",
967 s->cur_pkt.stream_index,
968 s->cur_pkt.pts,
969 s->cur_pkt.dts,
970 s->cur_pkt.size,
971 s->cur_pkt.flags);
972
973 s->cur_st = st;
974 s->cur_ptr = s->cur_pkt.data;
975 s->cur_len = s->cur_pkt.size;
976 if (st->need_parsing && !st->parser) {
977 st->parser = av_parser_init(st->codec->codec_id);
978 if (!st->parser) {
979 /* no parser available: just output the raw packets */
980 st->need_parsing = AVSTREAM_PARSE_NONE;
981 }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
982 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
983 }
984 if(st->parser && (s->iformat->flags & AVFMT_GENERIC_INDEX)){
985 st->parser->next_frame_offset=
986 st->parser->cur_offset= s->cur_pkt.pos;
987 }
988 }
989 }
990 }
991 if(s->debug & FF_FDEBUG_TS)
992 av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, flags=%d\n",
993 pkt->stream_index,
994 pkt->pts,
995 pkt->dts,
996 pkt->size,
997 pkt->flags);
998
999 return 0;
1000}
1001
1002int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1003{
1004 AVPacketList *pktl;
1005 int eof=0;
1006 const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1007
1008 for(;;){
1009 pktl = s->packet_buffer;
1010 if (pktl) {
1011 AVPacket *next_pkt= &pktl->pkt;
1012
1013 if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
1014 while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
1015 if( pktl->pkt.stream_index == next_pkt->stream_index
1016 && next_pkt->dts < pktl->pkt.dts
1017 && pktl->pkt.pts != pktl->pkt.dts //not b frame
1018 /*&& pktl->pkt.dts != AV_NOPTS_VALUE*/){
1019 next_pkt->pts= pktl->pkt.dts;
1020 }
1021 pktl= pktl->next;
1022 }
1023 pktl = s->packet_buffer;
1024 }
1025
1026 if( next_pkt->pts != AV_NOPTS_VALUE
1027 || next_pkt->dts == AV_NOPTS_VALUE
1028 || !genpts || eof){
1029 /* read packet from packet buffer, if there is data */
1030 *pkt = *next_pkt;
1031 s->packet_buffer = pktl->next;
1032 av_free(pktl);
1033 return 0;
1034 }
1035 }
1036 if(genpts){
1037 int ret= av_read_frame_internal(s, pkt);
1038 if(ret<0){
1039 if(pktl && ret != AVERROR(EAGAIN)){
1040 eof=1;
1041 continue;
1042 }else
1043 return ret;
1044 }
1045
1046 if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt)) < 0)
1047 return AVERROR(ENOMEM);
1048 }else{
1049 assert(!s->packet_buffer);
1050 return av_read_frame_internal(s, pkt);
1051 }
1052 }
1053}
1054
1055/* XXX: suppress the packet queue */
1056static void flush_packet_queue(AVFormatContext *s)
1057{
1058 AVPacketList *pktl;
1059
1060 for(;;) {
1061 pktl = s->packet_buffer;
1062 if (!pktl)
1063 break;
1064 s->packet_buffer = pktl->next;
1065 av_free_packet(&pktl->pkt);
1066 av_free(pktl);
1067 }
1068}
1069
1070/*******************************************************/
1071/* seek support */
1072
1073int av_find_default_stream_index(AVFormatContext *s)
1074{
1075 int first_audio_index = -1;
1076 int i;
1077 AVStream *st;
1078
1079 if (s->nb_streams <= 0)
1080 return -1;
1081 for(i = 0; i < s->nb_streams; i++) {
1082 st = s->streams[i];
1083 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1084 return i;
1085 }
1086 if (first_audio_index < 0 && st->codec->codec_type == CODEC_TYPE_AUDIO)
1087 first_audio_index = i;
1088 }
1089 return first_audio_index >= 0 ? first_audio_index : 0;
1090}
1091
1092/**
1093 * Flush the frame reader.
1094 */
1095static void av_read_frame_flush(AVFormatContext *s)
1096{
1097 AVStream *st;
1098 int i;
1099
1100 flush_packet_queue(s);
1101
1102 /* free previous packet */
1103 if (s->cur_st) {
1104 if (s->cur_st->parser)
1105 av_free_packet(&s->cur_pkt);
1106 s->cur_st = NULL;
1107 }
1108 /* fail safe */
1109 s->cur_ptr = NULL;
1110 s->cur_len = 0;
1111
1112 /* for each stream, reset read state */
1113 for(i = 0; i < s->nb_streams; i++) {
1114 st = s->streams[i];
1115
1116 if (st->parser) {
1117 av_parser_close(st->parser);
1118 st->parser = NULL;
1119 }
1120 st->last_IP_pts = AV_NOPTS_VALUE;
1121 st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1122 }
1123}
1124
1125void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1126 int i;
1127
1128 for(i = 0; i < s->nb_streams; i++) {
1129 AVStream *st = s->streams[i];
1130
1131 st->cur_dts = av_rescale(timestamp,
1132 st->time_base.den * (int64_t)ref_st->time_base.num,
1133 st->time_base.num * (int64_t)ref_st->time_base.den);
1134 }
1135}
1136
1137void ff_reduce_index(AVFormatContext *s, int stream_index)
1138{
1139 AVStream *st= s->streams[stream_index];
1140 unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1141
1142 if((unsigned)st->nb_index_entries >= max_entries){
1143 int i;
1144 for(i=0; 2*i<st->nb_index_entries; i++)
1145 st->index_entries[i]= st->index_entries[2*i];
1146 st->nb_index_entries= i;
1147 }
1148}
1149
1150int av_add_index_entry(AVStream *st,
1151 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1152{
1153 AVIndexEntry *entries, *ie;
1154 int index;
1155
1156 if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1157 return -1;
1158
1159 entries = av_fast_realloc(st->index_entries,
1160 &st->index_entries_allocated_size,
1161 (st->nb_index_entries + 1) *
1162 sizeof(AVIndexEntry));
1163 if(!entries)
1164 return -1;
1165
1166 st->index_entries= entries;
1167
1168 index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
1169
1170 if(index<0){
1171 index= st->nb_index_entries++;
1172 ie= &entries[index];
1173 assert(index==0 || ie[-1].timestamp < timestamp);
1174 }else{
1175 ie= &entries[index];
1176 if(ie->timestamp != timestamp){
1177 if(ie->timestamp <= timestamp)
1178 return -1;
1179 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
1180 st->nb_index_entries++;
1181 }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1182 distance= ie->min_distance;
1183 }
1184
1185 ie->pos = pos;
1186 ie->timestamp = timestamp;
1187 ie->min_distance= distance;
1188 ie->size= size;
1189 ie->flags = flags;
1190
1191 return index;
1192}
1193
1194int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1195 int flags)
1196{
1197 AVIndexEntry *entries= st->index_entries;
1198 int nb_entries= st->nb_index_entries;
1199 int a, b, m;
1200 int64_t timestamp;
1201
1202 a = - 1;
1203 b = nb_entries;
1204
1205 while (b - a > 1) {
1206 m = (a + b) >> 1;
1207 timestamp = entries[m].timestamp;
1208 if(timestamp >= wanted_timestamp)
1209 b = m;
1210 if(timestamp <= wanted_timestamp)
1211 a = m;
1212 }
1213 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1214
1215 if(!(flags & AVSEEK_FLAG_ANY)){
1216 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1217 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1218 }
1219 }
1220
1221 if(m == nb_entries)
1222 return -1;
1223 return m;
1224}
1225
1226#define DEBUG_SEEK
1227
1228int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1229 AVInputFormat *avif= s->iformat;
1230 int64_t pos_min, pos_max, pos, pos_limit;
1231 int64_t ts_min, ts_max, ts;
1232 int index;
1233 AVStream *st;
1234
1235 if (stream_index < 0)
1236 return -1;
1237
1238#ifdef DEBUG_SEEK
1239 av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1240#endif
1241
1242 ts_max=
1243 ts_min= AV_NOPTS_VALUE;
1244 pos_limit= -1; //gcc falsely says it may be uninitialized
1245
1246 st= s->streams[stream_index];
1247 if(st->index_entries){
1248 AVIndexEntry *e;
1249
1250 index= av_index_search_timestamp(st, target_ts, flags | AVSEEK_FLAG_BACKWARD); //FIXME whole func must be checked for non-keyframe entries in index case, especially read_timestamp()
1251 index= FFMAX(index, 0);
1252 e= &st->index_entries[index];
1253
1254 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1255 pos_min= e->pos;
1256 ts_min= e->timestamp;
1257#ifdef DEBUG_SEEK
1258 av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1259 pos_min,ts_min);
1260#endif
1261 }else{
1262 assert(index==0);
1263 }
1264
1265 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1266 assert(index < st->nb_index_entries);
1267 if(index >= 0){
1268 e= &st->index_entries[index];
1269 assert(e->timestamp >= target_ts);
1270 pos_max= e->pos;
1271 ts_max= e->timestamp;
1272 pos_limit= pos_max - e->min_distance;
1273#ifdef DEBUG_SEEK
1274 av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1275 pos_max,pos_limit, ts_max);
1276#endif
1277 }
1278 }
1279
1280 pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1281 if(pos<0)
1282 return -1;
1283
1284 /* do the seek */
1285 url_fseek(s->pb, pos, SEEK_SET);
1286
1287 av_update_cur_dts(s, st, ts);
1288
1289 return 0;
1290}
1291
1292int64_t av_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts, int64_t pos_min, int64_t pos_max, int64_t pos_limit, int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret, int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t )){
1293 int64_t pos, ts;
1294 int64_t start_pos, filesize;
1295 int no_change;
1296
1297#ifdef DEBUG_SEEK
1298 av_log(s, AV_LOG_DEBUG, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1299#endif
1300
1301 if(ts_min == AV_NOPTS_VALUE){
1302 pos_min = s->data_offset;
1303 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1304 if (ts_min == AV_NOPTS_VALUE)
1305 return -1;
1306 }
1307
1308 if(ts_max == AV_NOPTS_VALUE){
1309 int step= 1024;
1310 filesize = url_fsize(s->pb);
1311 pos_max = filesize - 1;
1312 do{
1313 pos_max -= step;
1314 ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1315 step += step;
1316 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1317 if (ts_max == AV_NOPTS_VALUE)
1318 return -1;
1319
1320 for(;;){
1321 int64_t tmp_pos= pos_max + 1;
1322 int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1323 if(tmp_ts == AV_NOPTS_VALUE)
1324 break;
1325 ts_max= tmp_ts;
1326 pos_max= tmp_pos;
1327 if(tmp_pos >= filesize)
1328 break;
1329 }
1330 pos_limit= pos_max;
1331 }
1332
1333 if(ts_min > ts_max){
1334 return -1;
1335 }else if(ts_min == ts_max){
1336 pos_limit= pos_min;
1337 }
1338
1339 no_change=0;
1340 while (pos_min < pos_limit) {
1341#ifdef DEBUG_SEEK
1342 av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1343 pos_min, pos_max,
1344 ts_min, ts_max);
1345#endif
1346 assert(pos_limit <= pos_max);
1347
1348 if(no_change==0){
1349 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1350 // interpolate position (better than dichotomy)
1351 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1352 + pos_min - approximate_keyframe_distance;
1353 }else if(no_change==1){
1354 // bisection, if interpolation failed to change min or max pos last time
1355 pos = (pos_min + pos_limit)>>1;
1356 }else{
1357 /* linear search if bisection failed, can only happen if there
1358 are very few or no keyframes between min/max */
1359 pos=pos_min;
1360 }
1361 if(pos <= pos_min)
1362 pos= pos_min + 1;
1363 else if(pos > pos_limit)
1364 pos= pos_limit;
1365 start_pos= pos;
1366
1367 ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1368 if(pos == pos_max)
1369 no_change++;
1370 else
1371 no_change=0;
1372#ifdef DEBUG_SEEK
1373av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n", pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit, start_pos, no_change);
1374#endif
1375 if(ts == AV_NOPTS_VALUE){
1376 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1377 return -1;
1378 }
1379 assert(ts != AV_NOPTS_VALUE);
1380 if (target_ts <= ts) {
1381 pos_limit = start_pos - 1;
1382 pos_max = pos;
1383 ts_max = ts;
1384 }
1385 if (target_ts >= ts) {
1386 pos_min = pos;
1387 ts_min = ts;
1388 }
1389 }
1390
1391 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1392 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1393#ifdef DEBUG_SEEK
1394 pos_min = pos;
1395 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1396 pos_min++;
1397 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1398 av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1399 pos, ts_min, target_ts, ts_max);
1400#endif
1401 *ts_ret= ts;
1402 return pos;
1403}
1404
1405static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1406 int64_t pos_min, pos_max;
1407#if 0
1408 AVStream *st;
1409
1410 if (stream_index < 0)
1411 return -1;
1412
1413 st= s->streams[stream_index];
1414#endif
1415
1416 pos_min = s->data_offset;
1417 pos_max = url_fsize(s->pb) - 1;
1418
1419 if (pos < pos_min) pos= pos_min;
1420 else if(pos > pos_max) pos= pos_max;
1421
1422 url_fseek(s->pb, pos, SEEK_SET);
1423
1424#if 0
1425 av_update_cur_dts(s, st, ts);
1426#endif
1427 return 0;
1428}
1429
1430static int av_seek_frame_generic(AVFormatContext *s,
1431 int stream_index, int64_t timestamp, int flags)
1432{
1433 int index;
1434 AVStream *st;
1435 AVIndexEntry *ie;
1436
1437 st = s->streams[stream_index];
1438
1439 index = av_index_search_timestamp(st, timestamp, flags);
1440
1441 if(index < 0 || index==st->nb_index_entries-1){
1442 int i;
1443 AVPacket pkt;
1444
1445 if(st->nb_index_entries){
1446 assert(st->index_entries);
1447 ie= &st->index_entries[st->nb_index_entries-1];
1448 url_fseek(s->pb, ie->pos, SEEK_SET);
1449 av_update_cur_dts(s, st, ie->timestamp);
1450 }else
1451 url_fseek(s->pb, 0, SEEK_SET);
1452
1453 for(i=0;; i++) {
1454 int ret = av_read_frame(s, &pkt);
1455 if(ret<0)
1456 break;
1457 av_free_packet(&pkt);
1458 if(stream_index == pkt.stream_index){
1459 if((pkt.flags & PKT_FLAG_KEY) && pkt.dts > timestamp)
1460 break;
1461 }
1462 }
1463 index = av_index_search_timestamp(st, timestamp, flags);
1464 }
1465 if (index < 0)
1466 return -1;
1467
1468 av_read_frame_flush(s);
1469 if (s->iformat->read_seek){
1470 if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1471 return 0;
1472 }
1473 ie = &st->index_entries[index];
1474 url_fseek(s->pb, ie->pos, SEEK_SET);
1475
1476 av_update_cur_dts(s, st, ie->timestamp);
1477
1478 return 0;
1479}
1480
1481int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1482{
1483 int ret;
1484 AVStream *st;
1485
1486 av_read_frame_flush(s);
1487
1488 if(flags & AVSEEK_FLAG_BYTE)
1489 return av_seek_frame_byte(s, stream_index, timestamp, flags);
1490
1491 if(stream_index < 0){
1492 stream_index= av_find_default_stream_index(s);
1493 if(stream_index < 0)
1494 return -1;
1495
1496 st= s->streams[stream_index];
1497 /* timestamp for default must be expressed in AV_TIME_BASE units */
1498 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1499 }
1500 st= s->streams[stream_index];
1501
1502 /* first, we try the format specific seek */
1503 if (s->iformat->read_seek)
1504 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1505 else
1506 ret = -1;
1507 if (ret >= 0) {
1508 return 0;
1509 }
1510
1511 if(s->iformat->read_timestamp)
1512 return av_seek_frame_binary(s, stream_index, timestamp, flags);
1513 else
1514 return av_seek_frame_generic(s, stream_index, timestamp, flags);
1515}
1516
1517/*******************************************************/
1518
1519/**
1520 * Returns TRUE if the stream has accurate duration in any stream.
1521 *
1522 * @return TRUE if the stream has accurate duration for at least one component.
1523 */
1524static int av_has_duration(AVFormatContext *ic)
1525{
1526 int i;
1527 AVStream *st;
1528
1529 for(i = 0;i < ic->nb_streams; i++) {
1530 st = ic->streams[i];
1531 if (st->duration != AV_NOPTS_VALUE)
1532 return 1;
1533 }
1534 return 0;
1535}
1536
1537/**
1538 * Estimate the stream timings from the one of each components.
1539 *
1540 * Also computes the global bitrate if possible.
1541 */
1542static void av_update_stream_timings(AVFormatContext *ic)
1543{
1544 int64_t start_time, start_time1, end_time, end_time1;
1545 int64_t duration, duration1;
1546 int i;
1547 AVStream *st;
1548
1549 start_time = INT64_MAX;
1550 end_time = INT64_MIN;
1551 duration = INT64_MIN;
1552 for(i = 0;i < ic->nb_streams; i++) {
1553 st = ic->streams[i];
1554 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1555 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1556 if (start_time1 < start_time)
1557 start_time = start_time1;
1558 if (st->duration != AV_NOPTS_VALUE) {
1559 end_time1 = start_time1
1560 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1561 if (end_time1 > end_time)
1562 end_time = end_time1;
1563 }
1564 }
1565 if (st->duration != AV_NOPTS_VALUE) {
1566 duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1567 if (duration1 > duration)
1568 duration = duration1;
1569 }
1570 }
1571 if (start_time != INT64_MAX) {
1572 ic->start_time = start_time;
1573 if (end_time != INT64_MIN) {
1574 if (end_time - start_time > duration)
1575 duration = end_time - start_time;
1576 }
1577 }
1578 if (duration != INT64_MIN) {
1579 ic->duration = duration;
1580 if (ic->file_size > 0) {
1581 /* compute the bitrate */
1582 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1583 (double)ic->duration;
1584 }
1585 }
1586}
1587
1588static void fill_all_stream_timings(AVFormatContext *ic)
1589{
1590 int i;
1591 AVStream *st;
1592
1593 av_update_stream_timings(ic);
1594 for(i = 0;i < ic->nb_streams; i++) {
1595 st = ic->streams[i];
1596 if (st->start_time == AV_NOPTS_VALUE) {
1597 if(ic->start_time != AV_NOPTS_VALUE)
1598 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1599 if(ic->duration != AV_NOPTS_VALUE)
1600 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1601 }
1602 }
1603}
1604
1605static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1606{
1607 int64_t filesize, duration;
1608 int bit_rate, i;
1609 AVStream *st;
1610
1611 /* if bit_rate is already set, we believe it */
1612 if (ic->bit_rate == 0) {
1613 bit_rate = 0;
1614 for(i=0;i<ic->nb_streams;i++) {
1615 st = ic->streams[i];
1616 bit_rate += st->codec->bit_rate;
1617 }
1618 ic->bit_rate = bit_rate;
1619 }
1620
1621 /* if duration is already set, we believe it */
1622 if (ic->duration == AV_NOPTS_VALUE &&
1623 ic->bit_rate != 0 &&
1624 ic->file_size != 0) {
1625 filesize = ic->file_size;
1626 if (filesize > 0) {
1627 for(i = 0; i < ic->nb_streams; i++) {
1628 st = ic->streams[i];
1629 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1630 if (st->duration == AV_NOPTS_VALUE)
1631 st->duration = duration;
1632 }
1633 }
1634 }
1635}
1636
1637#define DURATION_MAX_READ_SIZE 250000
1638
1639/* only usable for MPEG-PS streams */
1640static void av_estimate_timings_from_pts(AVFormatContext *ic, offset_t old_offset)
1641{
1642 AVPacket pkt1, *pkt = &pkt1;
1643 AVStream *st;
1644 int read_size, i, ret;
1645 int64_t end_time;
1646 int64_t filesize, offset, duration;
1647
1648 /* free previous packet */
1649 if (ic->cur_st && ic->cur_st->parser)
1650 av_free_packet(&ic->cur_pkt);
1651 ic->cur_st = NULL;
1652
1653 /* flush packet queue */
1654 flush_packet_queue(ic);
1655
1656 for(i=0;i<ic->nb_streams;i++) {
1657 st = ic->streams[i];
1658 if (st->parser) {
1659 av_parser_close(st->parser);
1660 st->parser= NULL;
1661 }
1662 }
1663
1664 /* we read the first packets to get the first PTS (not fully
1665 accurate, but it is enough now) */
1666 url_fseek(ic->pb, 0, SEEK_SET);
1667 read_size = 0;
1668 for(;;) {
1669 if (read_size >= DURATION_MAX_READ_SIZE)
1670 break;
1671 /* if all info is available, we can stop */
1672 for(i = 0;i < ic->nb_streams; i++) {
1673 st = ic->streams[i];
1674 if (st->start_time == AV_NOPTS_VALUE)
1675 break;
1676 }
1677 if (i == ic->nb_streams)
1678 break;
1679
1680 ret = av_read_packet(ic, pkt);
1681 if (ret != 0)
1682 break;
1683 read_size += pkt->size;
1684 st = ic->streams[pkt->stream_index];
1685 if (pkt->pts != AV_NOPTS_VALUE) {
1686 if (st->start_time == AV_NOPTS_VALUE)
1687 st->start_time = pkt->pts;
1688 }
1689 av_free_packet(pkt);
1690 }
1691
1692 /* estimate the end time (duration) */
1693 /* XXX: may need to support wrapping */
1694 filesize = ic->file_size;
1695 offset = filesize - DURATION_MAX_READ_SIZE;
1696 if (offset < 0)
1697 offset = 0;
1698
1699 url_fseek(ic->pb, offset, SEEK_SET);
1700 read_size = 0;
1701 for(;;) {
1702 if (read_size >= DURATION_MAX_READ_SIZE)
1703 break;
1704
1705 ret = av_read_packet(ic, pkt);
1706 if (ret != 0)
1707 break;
1708 read_size += pkt->size;
1709 st = ic->streams[pkt->stream_index];
1710 if (pkt->pts != AV_NOPTS_VALUE &&
1711 st->start_time != AV_NOPTS_VALUE) {
1712 end_time = pkt->pts;
1713 duration = end_time - st->start_time;
1714 if (duration > 0) {
1715 if (st->duration == AV_NOPTS_VALUE ||
1716 st->duration < duration)
1717 st->duration = duration;
1718 }
1719 }
1720 av_free_packet(pkt);
1721 }
1722
1723 fill_all_stream_timings(ic);
1724
1725 url_fseek(ic->pb, old_offset, SEEK_SET);
1726 for(i=0; i<ic->nb_streams; i++){
1727 st= ic->streams[i];
1728 st->cur_dts= st->first_dts;
1729 st->last_IP_pts = AV_NOPTS_VALUE;
1730 }
1731}
1732
1733static void av_estimate_timings(AVFormatContext *ic, offset_t old_offset)
1734{
1735 int64_t file_size;
1736
1737 /* get the file size, if possible */
1738 if (ic->iformat->flags & AVFMT_NOFILE) {
1739 file_size = 0;
1740 } else {
1741 file_size = url_fsize(ic->pb);
1742 if (file_size < 0)
1743 file_size = 0;
1744 }
1745 ic->file_size = file_size;
1746
1747 if ((!strcmp(ic->iformat->name, "mpeg") ||
1748 !strcmp(ic->iformat->name, "mpegts")) &&
1749 file_size && !url_is_streamed(ic->pb)) {
1750 /* get accurate estimate from the PTSes */
1751 av_estimate_timings_from_pts(ic, old_offset);
1752 } else if (av_has_duration(ic)) {
1753 /* at least one component has timings - we use them for all
1754 the components */
1755 fill_all_stream_timings(ic);
1756 } else {
1757 /* less precise: use bitrate info */
1758 av_estimate_timings_from_bit_rate(ic);
1759 }
1760 av_update_stream_timings(ic);
1761
1762#if 0
1763 {
1764 int i;
1765 AVStream *st;
1766 for(i = 0;i < ic->nb_streams; i++) {
1767 st = ic->streams[i];
1768 printf("%d: start_time: %0.3f duration: %0.3f\n",
1769 i, (double)st->start_time / AV_TIME_BASE,
1770 (double)st->duration / AV_TIME_BASE);
1771 }
1772 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1773 (double)ic->start_time / AV_TIME_BASE,
1774 (double)ic->duration / AV_TIME_BASE,
1775 ic->bit_rate / 1000);
1776 }
1777#endif
1778}
1779
1780static int has_codec_parameters(AVCodecContext *enc)
1781{
1782 int val;
1783 switch(enc->codec_type) {
1784 case CODEC_TYPE_AUDIO:
1785 val = enc->sample_rate && enc->channels;
1786 if(!enc->frame_size &&
1787 (enc->codec_id == CODEC_ID_VORBIS ||
1788 enc->codec_id == CODEC_ID_AAC))
1789 return 0;
1790 break;
1791 case CODEC_TYPE_VIDEO:
1792 val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
1793 break;
1794 default:
1795 val = 1;
1796 break;
1797 }
1798 return enc->codec_id != CODEC_ID_NONE && val != 0;
1799}
1800
1801static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
1802{
1803 int16_t *samples;
1804 AVCodec *codec;
1805 int got_picture, data_size, ret=0;
1806 AVFrame picture;
1807
1808 if(!st->codec->codec){
1809 codec = avcodec_find_decoder(st->codec->codec_id);
1810 if (!codec)
1811 return -1;
1812 ret = avcodec_open(st->codec, codec);
1813 if (ret < 0)
1814 return ret;
1815 }
1816
1817 if(!has_codec_parameters(st->codec)){
1818 switch(st->codec->codec_type) {
1819 case CODEC_TYPE_VIDEO:
1820 ret = avcodec_decode_video(st->codec, &picture,
1821 &got_picture, data, size);
1822 break;
1823 case CODEC_TYPE_AUDIO:
1824 data_size = FFMAX(size, AVCODEC_MAX_AUDIO_FRAME_SIZE);
1825 samples = av_malloc(data_size);
1826 if (!samples)
1827 goto fail;
1828 ret = avcodec_decode_audio2(st->codec, samples,
1829 &data_size, data, size);
1830 av_free(samples);
1831 break;
1832 default:
1833 break;
1834 }
1835 }
1836 fail:
1837 return ret;
1838}
1839
1840unsigned int codec_get_tag(const AVCodecTag *tags, int id)
1841{
1842 while (tags->id != CODEC_ID_NONE) {
1843 if (tags->id == id)
1844 return tags->tag;
1845 tags++;
1846 }
1847 return 0;
1848}
1849
1850enum CodecID codec_get_id(const AVCodecTag *tags, unsigned int tag)
1851{
1852 int i;
1853 for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
1854 if(tag == tags[i].tag)
1855 return tags[i].id;
1856 }
1857 for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
1858 if( toupper((tag >> 0)&0xFF) == toupper((tags[i].tag >> 0)&0xFF)
1859 && toupper((tag >> 8)&0xFF) == toupper((tags[i].tag >> 8)&0xFF)
1860 && toupper((tag >>16)&0xFF) == toupper((tags[i].tag >>16)&0xFF)
1861 && toupper((tag >>24)&0xFF) == toupper((tags[i].tag >>24)&0xFF))
1862 return tags[i].id;
1863 }
1864 return CODEC_ID_NONE;
1865}
1866
1867unsigned int av_codec_get_tag(const AVCodecTag *tags[4], enum CodecID id)
1868{
1869 int i;
1870 for(i=0; tags && tags[i]; i++){
1871 int tag= codec_get_tag(tags[i], id);
1872 if(tag) return tag;
1873 }
1874 return 0;
1875}
1876
1877enum CodecID av_codec_get_id(const AVCodecTag *tags[4], unsigned int tag)
1878{
1879 int i;
1880 for(i=0; tags && tags[i]; i++){
1881 enum CodecID id= codec_get_id(tags[i], tag);
1882 if(id!=CODEC_ID_NONE) return id;
1883 }
1884 return CODEC_ID_NONE;
1885}
1886
1887static void compute_chapters_end(AVFormatContext *s)
1888{
1889 unsigned int i;
1890
1891 for (i=0; i+1<s->nb_chapters; i++)
1892 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
1893 assert(s->chapters[i]->start <= s->chapters[i+1]->start);
1894 assert(!av_cmp_q(s->chapters[i]->time_base, s->chapters[i+1]->time_base));
1895 s->chapters[i]->end = s->chapters[i+1]->start;
1896 }
1897
1898 if (s->nb_chapters && s->chapters[i]->end == AV_NOPTS_VALUE) {
1899 assert(s->start_time != AV_NOPTS_VALUE);
1900 assert(s->duration > 0);
1901 s->chapters[i]->end = av_rescale_q(s->start_time + s->duration,
1902 AV_TIME_BASE_Q,
1903 s->chapters[i]->time_base);
1904 }
1905}
1906
1907/* absolute maximum size we read until we abort */
1908#define MAX_READ_SIZE 5000000
1909
1910#define MAX_STD_TIMEBASES (60*12+5)
1911static int get_std_framerate(int i){
1912 if(i<60*12) return i*1001;
1913 else return ((int[]){24,30,60,12,15})[i-60*12]*1000*12;
1914}
1915
1916/*
1917 * Is the time base unreliable.
1918 * This is a heuristic to balance between quick acceptance of the values in
1919 * the headers vs. some extra checks.
1920 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
1921 * MPEG-2 commonly misuses field repeat flags to store different framerates.
1922 * And there are "variable" fps files this needs to detect as well.
1923 */
1924static int tb_unreliable(AVCodecContext *c){
1925 if( c->time_base.den >= 101L*c->time_base.num
1926 || c->time_base.den < 5L*c->time_base.num
1927/* || c->codec_tag == ff_get_fourcc("DIVX")
1928 || c->codec_tag == ff_get_fourcc("XVID")*/
1929 || c->codec_id == CODEC_ID_MPEG2VIDEO)
1930 return 1;
1931 return 0;
1932}
1933
1934int av_find_stream_info(AVFormatContext *ic)
1935{
1936 int i, count, ret, read_size, j;
1937 AVStream *st;
1938 AVPacket pkt1, *pkt;
1939 int64_t last_dts[MAX_STREAMS];
1940 int duration_count[MAX_STREAMS]={0};
1941 double (*duration_error)[MAX_STD_TIMEBASES];
1942 offset_t old_offset = url_ftell(ic->pb);
1943 int64_t codec_info_duration[MAX_STREAMS]={0};
1944 int codec_info_nb_frames[MAX_STREAMS]={0};
1945
1946 duration_error = av_mallocz(MAX_STREAMS * sizeof(*duration_error));
1947 if (!duration_error) return AVERROR(ENOMEM);
1948
1949 for(i=0;i<ic->nb_streams;i++) {
1950 st = ic->streams[i];
1951 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
1952/* if(!st->time_base.num)
1953 st->time_base= */
1954 if(!st->codec->time_base.num)
1955 st->codec->time_base= st->time_base;
1956 }
1957 //only for the split stuff
1958 if (!st->parser) {
1959 st->parser = av_parser_init(st->codec->codec_id);
1960 if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
1961 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1962 }
1963 }
1964 }
1965
1966 for(i=0;i<MAX_STREAMS;i++){
1967 last_dts[i]= AV_NOPTS_VALUE;
1968 }
1969
1970 count = 0;
1971 read_size = 0;
1972 for(;;) {
1973 /* check if one codec still needs to be handled */
1974 for(i=0;i<ic->nb_streams;i++) {
1975 st = ic->streams[i];
1976 if (!has_codec_parameters(st->codec))
1977 break;
1978 /* variable fps and no guess at the real fps */
1979 if( tb_unreliable(st->codec)
1980 && duration_count[i]<20 && st->codec->codec_type == CODEC_TYPE_VIDEO)
1981 break;
1982 if(st->parser && st->parser->parser->split && !st->codec->extradata)
1983 break;
1984 if(st->first_dts == AV_NOPTS_VALUE)
1985 break;
1986 }
1987 if (i == ic->nb_streams) {
1988 /* NOTE: if the format has no header, then we need to read
1989 some packets to get most of the streams, so we cannot
1990 stop here */
1991 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
1992 /* if we found the info for all the codecs, we can stop */
1993 ret = count;
1994 break;
1995 }
1996 }
1997 /* we did not get all the codec info, but we read too much data */
1998 if (read_size >= MAX_READ_SIZE) {
1999 ret = count;
2000 break;
2001 }
2002
2003 /* NOTE: a new stream can be added there if no header in file
2004 (AVFMTCTX_NOHEADER) */
2005 ret = av_read_frame_internal(ic, &pkt1);
2006 if (ret < 0) {
2007 /* EOF or error */
2008 ret = -1; /* we could not have all the codec parameters before EOF */
2009 for(i=0;i<ic->nb_streams;i++) {
2010 st = ic->streams[i];
2011 if (!has_codec_parameters(st->codec)){
2012 char buf[256];
2013 avcodec_string(buf, sizeof(buf), st->codec, 0);
2014 av_log(ic, AV_LOG_INFO, "Could not find codec parameters (%s)\n", buf);
2015 } else {
2016 ret = 0;
2017 }
2018 }
2019 break;
2020 }
2021
2022 pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1);
2023 if(av_dup_packet(pkt) < 0) {
2024 av_free(duration_error);
2025 return AVERROR(ENOMEM);
2026 }
2027
2028 read_size += pkt->size;
2029
2030 st = ic->streams[pkt->stream_index];
2031 if(codec_info_nb_frames[st->index]>1)
2032 codec_info_duration[st->index] += pkt->duration;
2033 if (pkt->duration != 0)
2034 codec_info_nb_frames[st->index]++;
2035
2036 {
2037 int index= pkt->stream_index;
2038 int64_t last= last_dts[index];
2039 int64_t duration= pkt->dts - last;
2040
2041 if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
2042 double dur= duration * av_q2d(st->time_base);
2043
2044// if(st->codec->codec_type == CODEC_TYPE_VIDEO)
2045// av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
2046 if(duration_count[index] < 2)
2047 memset(duration_error[index], 0, sizeof(*duration_error));
2048 for(i=1; i<MAX_STD_TIMEBASES; i++){
2049 int framerate= get_std_framerate(i);
2050 int ticks= lrintf(dur*framerate/(1001*12));
2051 double error= dur - ticks*1001*12/(double)framerate;
2052 duration_error[index][i] += error*error;
2053 }
2054 duration_count[index]++;
2055 }
2056 if(last == AV_NOPTS_VALUE || duration_count[index]<=1)
2057 last_dts[pkt->stream_index]= pkt->dts;
2058 }
2059 if(st->parser && st->parser->parser->split && !st->codec->extradata){
2060 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2061 if(i){
2062 st->codec->extradata_size= i;
2063 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2064 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2065 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2066 }
2067 }
2068
2069 /* if still no information, we try to open the codec and to
2070 decompress the frame. We try to avoid that in most cases as
2071 it takes longer and uses more memory. For MPEG-4, we need to
2072 decompress for QuickTime. */
2073 if (!has_codec_parameters(st->codec) /*&&
2074 (st->codec->codec_id == CODEC_ID_FLV1 ||
2075 st->codec->codec_id == CODEC_ID_H264 ||
2076 st->codec->codec_id == CODEC_ID_H263 ||
2077 st->codec->codec_id == CODEC_ID_H261 ||
2078 st->codec->codec_id == CODEC_ID_VORBIS ||
2079 st->codec->codec_id == CODEC_ID_MJPEG ||
2080 st->codec->codec_id == CODEC_ID_PNG ||
2081 st->codec->codec_id == CODEC_ID_PAM ||
2082 st->codec->codec_id == CODEC_ID_PGM ||
2083 st->codec->codec_id == CODEC_ID_PGMYUV ||
2084 st->codec->codec_id == CODEC_ID_PBM ||
2085 st->codec->codec_id == CODEC_ID_PPM ||
2086 st->codec->codec_id == CODEC_ID_SHORTEN ||
2087 (st->codec->codec_id == CODEC_ID_MPEG4 && !st->need_parsing))*/)
2088 try_decode_frame(st, pkt->data, pkt->size);
2089
2090 if (st->time_base.den > 0 && av_rescale_q(codec_info_duration[st->index], st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
2091 break;
2092 }
2093 count++;
2094 }
2095
2096 // close codecs which were opened in try_decode_frame()
2097 for(i=0;i<ic->nb_streams;i++) {
2098 st = ic->streams[i];
2099 if(st->codec->codec)
2100 avcodec_close(st->codec);
2101 }
2102 for(i=0;i<ic->nb_streams;i++) {
2103 st = ic->streams[i];
2104 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2105 if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_sample)
2106 st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2107
2108 if(duration_count[i]
2109 && tb_unreliable(st->codec) /*&&
2110 //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
2111 st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den*/){
2112 double best_error= 2*av_q2d(st->time_base);
2113 best_error= best_error*best_error*duration_count[i]*1000*12*30;
2114
2115 for(j=1; j<MAX_STD_TIMEBASES; j++){
2116 double error= duration_error[i][j] * get_std_framerate(j);
2117// if(st->codec->codec_type == CODEC_TYPE_VIDEO)
2118// av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
2119 if(error < best_error){
2120 best_error= error;
2121 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, get_std_framerate(j), 12*1001, INT_MAX);
2122 }
2123 }
2124 }
2125
2126 if (!st->r_frame_rate.num){
2127 if( st->codec->time_base.den * (int64_t)st->time_base.num
2128 <= st->codec->time_base.num * (int64_t)st->time_base.den){
2129 st->r_frame_rate.num = st->codec->time_base.den;
2130 st->r_frame_rate.den = st->codec->time_base.num;
2131 }else{
2132 st->r_frame_rate.num = st->time_base.den;
2133 st->r_frame_rate.den = st->time_base.num;
2134 }
2135 }
2136 }else if(st->codec->codec_type == CODEC_TYPE_AUDIO) {
2137 if(!st->codec->bits_per_sample)
2138 st->codec->bits_per_sample= av_get_bits_per_sample(st->codec->codec_id);
2139 }
2140 }
2141
2142 av_estimate_timings(ic, old_offset);
2143
2144 compute_chapters_end(ic);
2145
2146#if 0
2147 /* correct DTS for B-frame streams with no timestamps */
2148 for(i=0;i<ic->nb_streams;i++) {
2149 st = ic->streams[i];
2150 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2151 if(b-frames){
2152 ppktl = &ic->packet_buffer;
2153 while(ppkt1){
2154 if(ppkt1->stream_index != i)
2155 continue;
2156 if(ppkt1->pkt->dts < 0)
2157 break;
2158 if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2159 break;
2160 ppkt1->pkt->dts -= delta;
2161 ppkt1= ppkt1->next;
2162 }
2163 if(ppkt1)
2164 continue;
2165 st->cur_dts -= delta;
2166 }
2167 }
2168 }
2169#endif
2170
2171 av_free(duration_error);
2172
2173 return ret;
2174}
2175
2176/*******************************************************/
2177
2178int av_read_play(AVFormatContext *s)
2179{
2180 if (s->iformat->read_play)
2181 return s->iformat->read_play(s);
2182 if (s->pb)
2183 return av_url_read_fpause(s->pb, 0);
2184 return AVERROR(ENOSYS);
2185}
2186
2187int av_read_pause(AVFormatContext *s)
2188{
2189 if (s->iformat->read_pause)
2190 return s->iformat->read_pause(s);
2191 if (s->pb)
2192 return av_url_read_fpause(s->pb, 1);
2193 return AVERROR(ENOSYS);
2194}
2195
2196void av_close_input_stream(AVFormatContext *s)
2197{
2198 int i;
2199 AVStream *st;
2200
2201 /* free previous packet */
2202 if (s->cur_st && s->cur_st->parser)
2203 av_free_packet(&s->cur_pkt);
2204
2205 if (s->iformat->read_close)
2206 s->iformat->read_close(s);
2207 for(i=0;i<s->nb_streams;i++) {
2208 /* free all data in a stream component */
2209 st = s->streams[i];
2210 if (st->parser) {
2211 av_parser_close(st->parser);
2212 }
2213 av_free(st->index_entries);
2214 av_free(st->codec->extradata);
2215 av_free(st->codec);
2216 av_free(st->filename);
2217 av_free(st->priv_data);
2218 av_free(st);
2219 }
2220 for(i=s->nb_programs-1; i>=0; i--) {
2221 av_freep(&s->programs[i]->provider_name);
2222 av_freep(&s->programs[i]->name);
2223 av_freep(&s->programs[i]->stream_index);
2224 av_freep(&s->programs[i]);
2225 }
2226 av_freep(&s->programs);
2227 flush_packet_queue(s);
2228 av_freep(&s->priv_data);
2229 while(s->nb_chapters--) {
2230 av_free(s->chapters[s->nb_chapters]->title);
2231 av_free(s->chapters[s->nb_chapters]);
2232 }
2233 av_freep(&s->chapters);
2234 av_free(s);
2235}
2236
2237void av_close_input_file(AVFormatContext *s)
2238{
2239 ByteIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb;
2240 av_close_input_stream(s);
2241 if (pb)
2242 url_fclose(pb);
2243}
2244
2245AVStream *av_new_stream(AVFormatContext *s, int id)
2246{
2247 AVStream *st;
2248 int i;
2249
2250 if (s->nb_streams >= MAX_STREAMS)
2251 return NULL;
2252
2253 st = av_mallocz(sizeof(AVStream));
2254 if (!st)
2255 return NULL;
2256
2257 st->codec= avcodec_alloc_context();
2258 if (s->iformat) {
2259 /* no default bitrate if decoding */
2260 st->codec->bit_rate = 0;
2261 }
2262 st->index = s->nb_streams;
2263 st->id = id;
2264 st->start_time = AV_NOPTS_VALUE;
2265 st->duration = AV_NOPTS_VALUE;
2266 /* we set the current DTS to 0 so that formats without any timestamps
2267 but durations get some timestamps, formats with some unknown
2268 timestamps have their first few packets buffered and the
2269 timestamps corrected before they are returned to the user */
2270 st->cur_dts = 0;
2271 st->first_dts = AV_NOPTS_VALUE;
2272
2273 /* default pts setting is MPEG-like */
2274 av_set_pts_info(st, 33, 1, 90000);
2275 st->last_IP_pts = AV_NOPTS_VALUE;
2276 for(i=0; i<MAX_REORDER_DELAY+1; i++)
2277 st->pts_buffer[i]= AV_NOPTS_VALUE;
2278
2279 s->streams[s->nb_streams++] = st;
2280 return st;
2281}
2282
2283AVProgram *av_new_program(AVFormatContext *ac, int id)
2284{
2285 AVProgram *program=NULL;
2286 int i;
2287
2288#ifdef DEBUG_SI
2289 av_log(ac, AV_LOG_DEBUG, "new_program: id=0x%04x\n", id);
2290#endif
2291
2292 for(i=0; i<ac->nb_programs; i++)
2293 if(ac->programs[i]->id == id)
2294 program = ac->programs[i];
2295
2296 if(!program){
2297 program = av_mallocz(sizeof(AVProgram));
2298 if (!program)
2299 return NULL;
2300 dynarray_add(&ac->programs, &ac->nb_programs, program);
2301 program->discard = AVDISCARD_NONE;
2302 }
2303 program->id = id;
2304
2305 return program;
2306}
2307
2308void av_set_program_name(AVProgram *program, char *provider_name, char *name)
2309{
2310 assert(!provider_name == !name);
2311 if(name){
2312 av_free(program->provider_name);
2313 av_free(program-> name);
2314 program->provider_name = av_strdup(provider_name);
2315 program-> name = av_strdup( name);
2316 }
2317}
2318
2319AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2320{
2321 AVChapter *chapter = NULL;
2322 int i;
2323
2324 for(i=0; i<s->nb_chapters; i++)
2325 if(s->chapters[i]->id == id)
2326 chapter = s->chapters[i];
2327
2328 if(!chapter){
2329 chapter= av_mallocz(sizeof(AVChapter));
2330 if(!chapter)
2331 return NULL;
2332 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2333 }
2334 av_free(chapter->title);
2335 chapter->title = av_strdup(title);
2336 chapter->id = id;
2337 chapter->time_base= time_base;
2338 chapter->start = start;
2339 chapter->end = end;
2340
2341 return chapter;
2342}
2343
2344/************************************************************/
2345/* output media file */
2346
2347int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2348{
2349 int ret;
2350
2351 if (s->oformat->priv_data_size > 0) {
2352 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2353 if (!s->priv_data)
2354 return AVERROR(ENOMEM);
2355 } else
2356 s->priv_data = NULL;
2357
2358 if (s->oformat->set_parameters) {
2359 ret = s->oformat->set_parameters(s, ap);
2360 if (ret < 0)
2361 return ret;
2362 }
2363 return 0;
2364}
2365
2366int av_write_header(AVFormatContext *s)
2367{
2368 int ret, i;
2369 AVStream *st;
2370
2371 // some sanity checks
2372 for(i=0;i<s->nb_streams;i++) {
2373 st = s->streams[i];
2374
2375 switch (st->codec->codec_type) {
2376 case CODEC_TYPE_AUDIO:
2377 if(st->codec->sample_rate<=0){
2378 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2379 return -1;
2380 }
2381 break;
2382 case CODEC_TYPE_VIDEO:
2383 if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2384 av_log(s, AV_LOG_ERROR, "time base not set\n");
2385 return -1;
2386 }
2387 if(st->codec->width<=0 || st->codec->height<=0){
2388 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2389 return -1;
2390 }
2391 break;
2392 }
2393
2394 if(s->oformat->codec_tag){
2395 if(st->codec->codec_tag){
2396 //FIXME
2397 //check that tag + id is in the table
2398 //if neither is in the table -> OK
2399 //if tag is in the table with another id -> FAIL
2400 //if id is in the table with another tag -> FAIL unless strict < ?
2401 }else
2402 st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
2403 }
2404 }
2405
2406 if (!s->priv_data && s->oformat->priv_data_size > 0) {
2407 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2408 if (!s->priv_data)
2409 return AVERROR(ENOMEM);
2410 }
2411
2412 if(s->oformat->write_header){
2413 ret = s->oformat->write_header(s);
2414 if (ret < 0)
2415 return ret;
2416 }
2417
2418 /* init PTS generation */
2419 for(i=0;i<s->nb_streams;i++) {
2420 int64_t den = AV_NOPTS_VALUE;
2421 st = s->streams[i];
2422
2423 switch (st->codec->codec_type) {
2424 case CODEC_TYPE_AUDIO:
2425 den = (int64_t)st->time_base.num * st->codec->sample_rate;
2426 break;
2427 case CODEC_TYPE_VIDEO:
2428 den = (int64_t)st->time_base.num * st->codec->time_base.den;
2429 break;
2430 default:
2431 break;
2432 }
2433 if (den != AV_NOPTS_VALUE) {
2434 if (den <= 0)
2435 return AVERROR_INVALIDDATA;
2436 av_frac_init(&st->pts, 0, 0, den);
2437 }
2438 }
2439 return 0;
2440}
2441
2442//FIXME merge with compute_pkt_fields
2443static int compute_pkt_fields2(AVStream *st, AVPacket *pkt){
2444 int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
2445 int num, den, frame_size, i;
2446
2447// av_log(st->codec, AV_LOG_DEBUG, "av_write_frame: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
2448
2449/* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2450 return -1;*/
2451
2452 /* duration field */
2453 if (pkt->duration == 0) {
2454 compute_frame_duration(&num, &den, st, NULL, pkt);
2455 if (den && num) {
2456 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
2457 }
2458 }
2459
2460 if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
2461 pkt->pts= pkt->dts;
2462
2463 //XXX/FIXME this is a temporary hack until all encoders output pts
2464 if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
2465 pkt->dts=
2466// pkt->pts= st->cur_dts;
2467 pkt->pts= st->pts.val;
2468 }
2469
2470 //calculate dts from pts
2471 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){
2472 st->pts_buffer[0]= pkt->pts;
2473 for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
2474 st->pts_buffer[i]= (i-delay-1) * pkt->duration;
2475 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
2476 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
2477
2478 pkt->dts= st->pts_buffer[0];
2479 }
2480
2481 if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
2482 av_log(st->codec, AV_LOG_ERROR, "error, non monotone timestamps %"PRId64" >= %"PRId64"\n", st->cur_dts, pkt->dts);
2483 return -1;
2484 }
2485 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
2486 av_log(st->codec, AV_LOG_ERROR, "error, pts < dts\n");
2487 return -1;
2488 }
2489
2490// av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
2491 st->cur_dts= pkt->dts;
2492 st->pts.val= pkt->dts;
2493
2494 /* update pts */
2495 switch (st->codec->codec_type) {
2496 case CODEC_TYPE_AUDIO:
2497 frame_size = get_audio_frame_size(st->codec, pkt->size);
2498
2499 /* HACK/FIXME, we skip the initial 0 size packets as they are most
2500 likely equal to the encoder delay, but it would be better if we
2501 had the real timestamps from the encoder */
2502 if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
2503 av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
2504 }
2505 break;
2506 case CODEC_TYPE_VIDEO:
2507 av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
2508 break;
2509 default:
2510 break;
2511 }
2512 return 0;
2513}
2514
2515static void truncate_ts(AVStream *st, AVPacket *pkt){
2516 int64_t pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
2517
2518// if(pkt->dts < 0)
2519// pkt->dts= 0; //this happens for low_delay=0 and B-frames, FIXME, needs further investigation about what we should do here
2520
2521 if (pkt->pts != AV_NOPTS_VALUE)
2522 pkt->pts &= pts_mask;
2523 if (pkt->dts != AV_NOPTS_VALUE)
2524 pkt->dts &= pts_mask;
2525}
2526
2527int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2528{
2529 int ret = compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
2530
2531 if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2532 return ret;
2533
2534 truncate_ts(s->streams[pkt->stream_index], pkt);
2535
2536 ret= s->oformat->write_packet(s, pkt);
2537 if(!ret)
2538 ret= url_ferror(s->pb);
2539 return ret;
2540}
2541
2542int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
2543 AVPacketList *pktl, **next_point, *this_pktl;
2544 int stream_count=0;
2545 int streams[MAX_STREAMS];
2546
2547 if(pkt){
2548 AVStream *st= s->streams[ pkt->stream_index];
2549
2550// assert(pkt->destruct != av_destruct_packet); //FIXME
2551
2552 this_pktl = av_mallocz(sizeof(AVPacketList));
2553 this_pktl->pkt= *pkt;
2554 if(pkt->destruct == av_destruct_packet)
2555 pkt->destruct= NULL; // not shared -> must keep original from being freed
2556 else
2557 av_dup_packet(&this_pktl->pkt); //shared -> must dup
2558
2559 next_point = &s->packet_buffer;
2560 while(*next_point){
2561 AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];
2562 int64_t left= st2->time_base.num * (int64_t)st ->time_base.den;
2563 int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
2564 if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow
2565 break;
2566 next_point= &(*next_point)->next;
2567 }
2568 this_pktl->next= *next_point;
2569 *next_point= this_pktl;
2570 }
2571
2572 memset(streams, 0, sizeof(streams));
2573 pktl= s->packet_buffer;
2574 while(pktl){
2575//av_log(s, AV_LOG_DEBUG, "show st:%d dts:%"PRId64"\n", pktl->pkt.stream_index, pktl->pkt.dts);
2576 if(streams[ pktl->pkt.stream_index ] == 0)
2577 stream_count++;
2578 streams[ pktl->pkt.stream_index ]++;
2579 pktl= pktl->next;
2580 }
2581
2582 if(stream_count && (s->nb_streams == stream_count || flush)){
2583 pktl= s->packet_buffer;
2584 *out= pktl->pkt;
2585
2586 s->packet_buffer= pktl->next;
2587 av_freep(&pktl);
2588 return 1;
2589 }else{
2590 av_init_packet(out);
2591 return 0;
2592 }
2593}
2594
2595/**
2596 * Interleaves an AVPacket correctly so it can be muxed.
2597 * @param out the interleaved packet will be output here
2598 * @param in the input packet
2599 * @param flush 1 if no further packets are available as input and all
2600 * remaining packets should be output
2601 * @return 1 if a packet was output, 0 if no packet could be output,
2602 * < 0 if an error occurred
2603 */
2604static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2605 if(s->oformat->interleave_packet)
2606 return s->oformat->interleave_packet(s, out, in, flush);
2607 else
2608 return av_interleave_packet_per_dts(s, out, in, flush);
2609}
2610
2611int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
2612 AVStream *st= s->streams[ pkt->stream_index];
2613
2614 //FIXME/XXX/HACK drop zero sized packets
2615 if(st->codec->codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
2616 return 0;
2617
2618//av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %"PRId64" %"PRId64"\n", pkt->size, pkt->dts, pkt->pts);
2619 if(compute_pkt_fields2(st, pkt) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2620 return -1;
2621
2622 if(pkt->dts == AV_NOPTS_VALUE)
2623 return -1;
2624
2625 for(;;){
2626 AVPacket opkt;
2627 int ret= av_interleave_packet(s, &opkt, pkt, 0);
2628 if(ret<=0) //FIXME cleanup needed for ret<0 ?
2629 return ret;
2630
2631 truncate_ts(s->streams[opkt.stream_index], &opkt);
2632 ret= s->oformat->write_packet(s, &opkt);
2633
2634 av_free_packet(&opkt);
2635 pkt= NULL;
2636
2637 if(ret<0)
2638 return ret;
2639 if(url_ferror(s->pb))
2640 return url_ferror(s->pb);
2641 }
2642}
2643
2644int av_write_trailer(AVFormatContext *s)
2645{
2646 int ret, i;
2647
2648 for(;;){
2649 AVPacket pkt;
2650 ret= av_interleave_packet(s, &pkt, NULL, 1);
2651 if(ret<0) //FIXME cleanup needed for ret<0 ?
2652 goto fail;
2653 if(!ret)
2654 break;
2655
2656 truncate_ts(s->streams[pkt.stream_index], &pkt);
2657 ret= s->oformat->write_packet(s, &pkt);
2658
2659 av_free_packet(&pkt);
2660
2661 if(ret<0)
2662 goto fail;
2663 if(url_ferror(s->pb))
2664 goto fail;
2665 }
2666
2667 if(s->oformat->write_trailer)
2668 ret = s->oformat->write_trailer(s);
2669fail:
2670 if(ret == 0)
2671 ret=url_ferror(s->pb);
2672 for(i=0;i<s->nb_streams;i++)
2673 av_freep(&s->streams[i]->priv_data);
2674 av_freep(&s->priv_data);
2675 return ret;
2676}
2677
2678void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
2679{
2680 int i, j;
2681 AVProgram *program=NULL;
2682 void *tmp;
2683
2684 for(i=0; i<ac->nb_programs; i++){
2685 if(ac->programs[i]->id != progid)
2686 continue;
2687 program = ac->programs[i];
2688 for(j=0; j<program->nb_stream_indexes; j++)
2689 if(program->stream_index[j] == idx)
2690 return;
2691
2692 tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
2693 if(!tmp)
2694 return;
2695 program->stream_index = tmp;
2696 program->stream_index[program->nb_stream_indexes++] = idx;
2697 return;
2698 }
2699}
2700
2701/* "user interface" functions */
2702static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
2703{
2704 char buf[256];
2705 int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
2706 AVStream *st = ic->streams[i];
2707 int g = ff_gcd(st->time_base.num, st->time_base.den);
2708 avcodec_string(buf, sizeof(buf), st->codec, is_output);
2709 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
2710 /* the pid is an important information, so we display it */
2711 /* XXX: add a generic system */
2712 if (flags & AVFMT_SHOW_IDS)
2713 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2714 if (strlen(st->language) > 0)
2715 av_log(NULL, AV_LOG_INFO, "(%s)", st->language);
2716 av_log(NULL, AV_LOG_DEBUG, ", %d/%d", st->time_base.num/g, st->time_base.den/g);
2717 av_log(NULL, AV_LOG_INFO, ": %s", buf);
2718 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
2719 if(st->r_frame_rate.den && st->r_frame_rate.num)
2720 av_log(NULL, AV_LOG_INFO, ", %5.2f tb(r)", av_q2d(st->r_frame_rate));
2721/* else if(st->time_base.den && st->time_base.num)
2722 av_log(NULL, AV_LOG_INFO, ", %5.2f tb(m)", 1/av_q2d(st->time_base));*/
2723 else
2724 av_log(NULL, AV_LOG_INFO, ", %5.2f tb(c)", 1/av_q2d(st->codec->time_base));
2725 }
2726 av_log(NULL, AV_LOG_INFO, "\n");
2727}
2728
2729void dump_format(AVFormatContext *ic,
2730 int index,
2731 const char *url,
2732 int is_output)
2733{
2734 int i;
2735
2736 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2737 is_output ? "Output" : "Input",
2738 index,
2739 is_output ? ic->oformat->name : ic->iformat->name,
2740 is_output ? "to" : "from", url);
2741 if (!is_output) {
2742 av_log(NULL, AV_LOG_INFO, " Duration: ");
2743 if (ic->duration != AV_NOPTS_VALUE) {
2744 int hours, mins, secs, us;
2745 secs = ic->duration / AV_TIME_BASE;
2746 us = ic->duration % AV_TIME_BASE;
2747 mins = secs / 60;
2748 secs %= 60;
2749 hours = mins / 60;
2750 mins %= 60;
2751 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
2752 (100 * us) / AV_TIME_BASE);
2753 } else {
2754 av_log(NULL, AV_LOG_INFO, "N/A");
2755 }
2756 if (ic->start_time != AV_NOPTS_VALUE) {
2757 int secs, us;
2758 av_log(NULL, AV_LOG_INFO, ", start: ");
2759 secs = ic->start_time / AV_TIME_BASE;
2760 us = ic->start_time % AV_TIME_BASE;
2761 av_log(NULL, AV_LOG_INFO, "%d.%06d",
2762 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2763 }
2764 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2765 if (ic->bit_rate) {
2766 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2767 } else {
2768 av_log(NULL, AV_LOG_INFO, "N/A");
2769 }
2770 av_log(NULL, AV_LOG_INFO, "\n");
2771 }
2772 if(ic->nb_programs) {
2773 int j, k;
2774 for(j=0; j<ic->nb_programs; j++) {
2775 av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
2776 ic->programs[j]->name ? ic->programs[j]->name : "");
2777 for(k=0; k<ic->programs[j]->nb_stream_indexes; k++)
2778 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
2779 }
2780 } else
2781 for(i=0;i<ic->nb_streams;i++)
2782 dump_stream_format(ic, i, index, is_output);
2783}
2784
2785int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2786{
2787 return av_parse_video_frame_size(width_ptr, height_ptr, str);
2788}
2789
2790int parse_frame_rate(int *frame_rate_num, int *frame_rate_den, const char *arg)
2791{
2792 AVRational frame_rate;
2793 int ret = av_parse_video_frame_rate(&frame_rate, arg);
2794 *frame_rate_num= frame_rate.num;
2795 *frame_rate_den= frame_rate.den;
2796 return ret;
2797}
2798
2799/**
2800 * Gets the current time in microseconds.
2801 */
2802int64_t av_gettime(void)
2803{
2804 struct timeval tv;
2805 gettimeofday(&tv,NULL);
2806 return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
2807}
2808
2809int64_t parse_date(const char *datestr, int duration)
2810{
2811 const char *p;
2812 int64_t t;
2813 struct tm dt;
2814 int i;
2815 static const char *date_fmt[] = {
2816 "%Y-%m-%d",
2817 "%Y%m%d",
2818 };
2819 static const char *time_fmt[] = {
2820 "%H:%M:%S",
2821 "%H%M%S",
2822 };
2823 const char *q;
2824 char *qq;
2825 int is_utc, len;
2826 char lastch;
2827 int negative = 0;
2828
2829#undef time
2830 time_t now = time(0);
2831
2832 len = strlen(datestr);
2833 if (len > 0)
2834 lastch = datestr[len - 1];
2835 else
2836 lastch = '\0';
2837 is_utc = (lastch == 'z' || lastch == 'Z');
2838
2839 memset(&dt, 0, sizeof(dt));
2840
2841 p = datestr;
2842 q = NULL;
2843 if (!duration) {
2844 /* parse the year-month-day part */
2845 for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
2846 q = small_strptime(p, date_fmt[i], &dt);
2847 if (q) {
2848 break;
2849 }
2850 }
2851
2852 /* if the year-month-day part is missing, then take the
2853 * current year-month-day time */
2854 if (!q) {
2855 if (is_utc) {
2856 dt = *gmtime(&now);
2857 } else {
2858 dt = *localtime(&now);
2859 }
2860 dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
2861 } else {
2862 p = q;
2863 }
2864
2865 if (*p == 'T' || *p == 't' || *p == ' ')
2866 p++;
2867
2868 /* parse the hour-minute-second part */
2869 for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
2870 q = small_strptime(p, time_fmt[i], &dt);
2871 if (q) {
2872 break;
2873 }
2874 }
2875 } else {
2876 /* parse datestr as a duration */
2877 if (p[0] == '-') {
2878 negative = 1;
2879 ++p;
2880 }
2881 /* parse datestr as HH:MM:SS */
2882 q = small_strptime(p, time_fmt[0], &dt);
2883 if (!q) {
2884 /* parse datestr as S+ */
2885 dt.tm_sec = strtol(p, &qq, 10);
2886 if (qq == p)
2887 /* the parsing didn't succeed */
2888 return INT64_MIN;
2889 q = qq;
2890 dt.tm_min = 0;
2891 dt.tm_hour = 0;
2892 }
2893 }
2894
2895 /* Now we have all the fields that we can get */
2896 if (!q) {
2897 return INT64_MIN;
2898 }
2899
2900 if (duration) {
2901 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2902 } else {
2903 dt.tm_isdst = -1; /* unknown */
2904 if (is_utc) {
2905 t = mktimegm(&dt);
2906 } else {
2907 t = mktime(&dt);
2908 }
2909 }
2910
2911 t *= 1000000;
2912
2913 /* parse the .m... part */
2914 if (*q == '.') {
2915 int val, n;
2916 q++;
2917 for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
2918 if (!isdigit(*q))
2919 break;
2920 val += n * (*q - '0');
2921 }
2922 t += val;
2923 }
2924 return negative ? -t : t;
2925}
2926
2927int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
2928{
2929 const char *p;
2930 char tag[128], *q;
2931
2932 p = info;
2933 if (*p == '?')
2934 p++;
2935 for(;;) {
2936 q = tag;
2937 while (*p != '\0' && *p != '=' && *p != '&') {
2938 if ((q - tag) < sizeof(tag) - 1)
2939 *q++ = *p;
2940 p++;
2941 }
2942 *q = '\0';
2943 q = arg;
2944 if (*p == '=') {
2945 p++;
2946 while (*p != '&' && *p != '\0') {
2947 if ((q - arg) < arg_size - 1) {
2948 if (*p == '+')
2949 *q++ = ' ';
2950 else
2951 *q++ = *p;
2952 }
2953 p++;
2954 }
2955 *q = '\0';
2956 }
2957 if (!strcmp(tag, tag1))
2958 return 1;
2959 if (*p != '&')
2960 break;
2961 p++;
2962 }
2963 return 0;
2964}
2965
2966int av_get_frame_filename(char *buf, int buf_size,
2967 const char *path, int number)
2968{
2969 const char *p;
2970 char *q, buf1[20], c;
2971 int nd, len, percentd_found;
2972
2973 q = buf;
2974 p = path;
2975 percentd_found = 0;
2976 for(;;) {
2977 c = *p++;
2978 if (c == '\0')
2979 break;
2980 if (c == '%') {
2981 do {
2982 nd = 0;
2983 while (isdigit(*p)) {
2984 nd = nd * 10 + *p++ - '0';
2985 }
2986 c = *p++;
2987 } while (isdigit(c));
2988
2989 switch(c) {
2990 case '%':
2991 goto addchar;
2992 case 'd':
2993 if (percentd_found)
2994 goto fail;
2995 percentd_found = 1;
2996 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
2997 len = strlen(buf1);
2998 if ((q - buf + len) > buf_size - 1)
2999 goto fail;
3000 memcpy(q, buf1, len);
3001 q += len;
3002 break;
3003 default:
3004 goto fail;
3005 }
3006 } else {
3007 addchar:
3008 if ((q - buf) < buf_size - 1)
3009 *q++ = c;
3010 }
3011 }
3012 if (!percentd_found)
3013 goto fail;
3014 *q = '\0';
3015 return 0;
3016 fail:
3017 *q = '\0';
3018 return -1;
3019}
3020
3021static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
3022{
3023 int len, i, j, c;
3024#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3025
3026 for(i=0;i<size;i+=16) {
3027 len = size - i;
3028 if (len > 16)
3029 len = 16;
3030 PRINT("%08x ", i);
3031 for(j=0;j<16;j++) {
3032 if (j < len)
3033 PRINT(" %02x", buf[i+j]);
3034 else
3035 PRINT(" ");
3036 }
3037 PRINT(" ");
3038 for(j=0;j<len;j++) {
3039 c = buf[i+j];
3040 if (c < ' ' || c > '~')
3041 c = '.';
3042 PRINT("%c", c);
3043 }
3044 PRINT("\n");
3045 }
3046#undef PRINT
3047}
3048
3049void av_hex_dump(FILE *f, uint8_t *buf, int size)
3050{
3051 hex_dump_internal(NULL, f, 0, buf, size);
3052}
3053
3054void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
3055{
3056 hex_dump_internal(avcl, NULL, level, buf, size);
3057}
3058
3059 //FIXME needs to know the time_base
3060static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload)
3061{
3062#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3063 PRINT("stream #%d:\n", pkt->stream_index);
3064 PRINT(" keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
3065 PRINT(" duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
3066 /* DTS is _always_ valid after av_read_frame() */
3067 PRINT(" dts=");
3068 if (pkt->dts == AV_NOPTS_VALUE)
3069 PRINT("N/A");
3070 else
3071 PRINT("%0.3f", (double)pkt->dts / AV_TIME_BASE);
3072 /* PTS may not be known if B-frames are present. */
3073 PRINT(" pts=");
3074 if (pkt->pts == AV_NOPTS_VALUE)
3075 PRINT("N/A");
3076 else
3077 PRINT("%0.3f", (double)pkt->pts / AV_TIME_BASE);
3078 PRINT("\n");
3079 PRINT(" size=%d\n", pkt->size);
3080#undef PRINT
3081 if (dump_payload)
3082 av_hex_dump(f, pkt->data, pkt->size);
3083}
3084
3085void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3086{
3087 pkt_dump_internal(NULL, f, 0, pkt, dump_payload);
3088}
3089
3090void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
3091{
3092 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload);
3093}
3094
3095void url_split(char *proto, int proto_size,
3096 char *authorization, int authorization_size,
3097 char *hostname, int hostname_size,
3098 int *port_ptr,
3099 char *path, int path_size,
3100 const char *url)
3101{
3102 const char *p, *ls, *at, *col, *brk;
3103
3104 if (port_ptr) *port_ptr = -1;
3105 if (proto_size > 0) proto[0] = 0;
3106 if (authorization_size > 0) authorization[0] = 0;
3107 if (hostname_size > 0) hostname[0] = 0;
3108 if (path_size > 0) path[0] = 0;
3109
3110 /* parse protocol */
3111 if ((p = strchr(url, ':'))) {
3112 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3113 p++; /* skip ':' */
3114 if (*p == '/') p++;
3115 if (*p == '/') p++;
3116 } else {
3117 /* no protocol means plain filename */
3118 av_strlcpy(path, url, path_size);
3119 return;
3120 }
3121
3122 /* separate path from hostname */
3123 ls = strchr(p, '/');
3124 if(!ls)
3125 ls = strchr(p, '?');
3126 if(ls)
3127 av_strlcpy(path, ls, path_size);
3128 else
3129 ls = &p[strlen(p)]; // XXX
3130
3131 /* the rest is hostname, use that to parse auth/port */
3132 if (ls != p) {
3133 /* authorization (user[:pass]@hostname) */
3134 if ((at = strchr(p, '@')) && at < ls) {
3135 av_strlcpy(authorization, p,
3136 FFMIN(authorization_size, at + 1 - p));
3137 p = at + 1; /* skip '@' */
3138 }
3139
3140 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3141 /* [host]:port */
3142 av_strlcpy(hostname, p + 1,
3143 FFMIN(hostname_size, brk - p));
3144 if (brk[1] == ':' && port_ptr)
3145 *port_ptr = atoi(brk + 2);
3146 } else if ((col = strchr(p, ':')) && col < ls) {
3147 av_strlcpy(hostname, p,
3148 FFMIN(col + 1 - p, hostname_size));
3149 if (port_ptr) *port_ptr = atoi(col + 1);
3150 } else
3151 av_strlcpy(hostname, p,
3152 FFMIN(ls + 1 - p, hostname_size));
3153 }
3154}
3155
3156void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3157 int pts_num, int pts_den)
3158{
3159 unsigned int gcd= ff_gcd(pts_num, pts_den);
3160 s->pts_wrap_bits = pts_wrap_bits;
3161 s->time_base.num = pts_num/gcd;
3162 s->time_base.den = pts_den/gcd;
3163
3164 if(gcd>1)
3165 av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, gcd);
3166}
3167
3168/* fraction handling */
3169
3170/**
3171 * f = val + (num / den) + 0.5.
3172 *
3173 * 'num' is normalized so that it is such as 0 <= num < den.
3174 *
3175 * @param f fractional number
3176 * @param val integer value
3177 * @param num must be >= 0
3178 * @param den must be >= 1
3179 */
3180static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
3181{
3182 num += (den >> 1);
3183 if (num >= den) {
3184 val += num / den;
3185 num = num % den;
3186 }
3187 f->val = val;
3188 f->num = num;
3189 f->den = den;
3190}
3191
3192/**
3193 * Fractional addition to f: f = f + (incr / f->den).
3194 *
3195 * @param f fractional number
3196 * @param incr increment, can be positive or negative
3197 */
3198static void av_frac_add(AVFrac *f, int64_t incr)
3199{
3200 int64_t num, den;
3201
3202 num = f->num + incr;
3203 den = f->den;
3204 if (num < 0) {
3205 f->val += num / den;
3206 num = num % den;
3207 if (num < 0) {
3208 num += den;
3209 f->val--;
3210 }
3211 } else if (num >= den) {
3212 f->val += num / den;
3213 num = num % den;
3214 }
3215 f->num = num;
3216}
diff --git a/src/plugins/ffmpeg/libavformat/vc1test.c b/src/plugins/ffmpeg/libavformat/vc1test.c
deleted file mode 100644
index 7601ea9..0000000
--- a/src/plugins/ffmpeg/libavformat/vc1test.c
+++ /dev/null
@@ -1,112 +0,0 @@
1/*
2 * VC1 Test Bitstreams Format Demuxer
3 * Copyright (c) 2006, 2008 Konstantin Shishkov
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/**
23 * @file vc1test.c
24 * VC1 test bitstream file demuxer
25 * by Konstantin Shishkov
26 * Format specified in SMPTE standard 421 Annex L
27 */
28
29#include "avformat.h"
30
31#define VC1_EXTRADATA_SIZE 4
32
33static int vc1t_probe(AVProbeData *p)
34{
35 if (p->buf[3] != 0xC5 && AV_RL32(&p->buf[4]) != 4)
36 return 0;
37
38 return AVPROBE_SCORE_MAX/2;
39}
40
41static int vc1t_read_header(AVFormatContext *s,
42 AVFormatParameters *ap)
43{
44 ByteIOContext *pb = s->pb;
45 AVStream *st;
46 int fps, frames;
47
48 frames = get_le24(pb);
49 if(get_byte(pb) != 0xC5 || get_le32(pb) != 4)
50 return -1;
51
52 /* init video codec */
53 st = av_new_stream(s, 0);
54 if (!st)
55 return -1;
56
57 st->codec->codec_type = CODEC_TYPE_VIDEO;
58 st->codec->codec_id = CODEC_ID_WMV3;
59
60 st->codec->extradata = av_malloc(VC1_EXTRADATA_SIZE);
61 st->codec->extradata_size = VC1_EXTRADATA_SIZE;
62 get_buffer(pb, st->codec->extradata, VC1_EXTRADATA_SIZE);
63 st->codec->height = get_le32(pb);
64 st->codec->width = get_le32(pb);
65 if(get_le32(pb) != 0xC)
66 return -1;
67 url_fskip(pb, 8);
68 fps = get_le32(pb);
69 if(fps == -1)
70 av_set_pts_info(st, 32, 1, 1000);
71 else{
72 av_set_pts_info(st, 24, 1, fps);
73 st->duration = frames;
74 }
75
76 return 0;
77}
78
79static int vc1t_read_packet(AVFormatContext *s,
80 AVPacket *pkt)
81{
82 ByteIOContext *pb = s->pb;
83 int frame_size;
84 int keyframe = 0;
85 uint32_t pts;
86
87 if(url_feof(pb))
88 return AVERROR(EIO);
89
90 frame_size = get_le24(pb);
91 if(get_byte(pb) & 0x80)
92 keyframe = 1;
93 pts = get_le32(pb);
94 if(av_get_packet(pb, pkt, frame_size) < 0)
95 return AVERROR(EIO);
96 if(s->streams[0]->time_base.den == 1000)
97 pkt->pts = pts;
98 pkt->flags |= keyframe ? PKT_FLAG_KEY : 0;
99 pkt->pos -= 8;
100
101 return pkt->size;
102}
103
104AVInputFormat vc1t_demuxer = {
105 "vc1test",
106 NULL_IF_CONFIG_SMALL("VC-1 test bitstream format"),
107 0,
108 vc1t_probe,
109 vc1t_read_header,
110 vc1t_read_packet,
111 .flags = AVFMT_GENERIC_INDEX,
112};
diff --git a/src/plugins/ffmpeg/libavformat/voc.c b/src/plugins/ffmpeg/libavformat/voc.c
deleted file mode 100644
index 750f78d..0000000
--- a/src/plugins/ffmpeg/libavformat/voc.c
+++ /dev/null
@@ -1,36 +0,0 @@
1/*
2 * Creative Voice File common data.
3 * Copyright (c) 2006 Aurelien Jacobs <aurel@gnuage.org>
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 "voc.h"
23
24const unsigned char voc_magic[21] = "Creative Voice File\x1A";
25
26const AVCodecTag voc_codec_tags[] = {
27 {CODEC_ID_PCM_U8, 0x00},
28 {CODEC_ID_ADPCM_SBPRO_4, 0x01},
29 {CODEC_ID_ADPCM_SBPRO_3, 0x02},
30 {CODEC_ID_ADPCM_SBPRO_2, 0x03},
31 {CODEC_ID_PCM_S16LE, 0x04},
32 {CODEC_ID_PCM_ALAW, 0x06},
33 {CODEC_ID_PCM_MULAW, 0x07},
34 {CODEC_ID_ADPCM_CT, 0x0200},
35 {0, 0},
36};
diff --git a/src/plugins/ffmpeg/libavformat/voc.h b/src/plugins/ffmpeg/libavformat/voc.h
deleted file mode 100644
index 606f215..0000000
--- a/src/plugins/ffmpeg/libavformat/voc.h
+++ /dev/null
@@ -1,51 +0,0 @@
1/*
2 * Creative Voice File demuxer.
3 * Copyright (c) 2006 Aurelien Jacobs <aurel@gnuage.org>
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#ifndef FFMPEG_VOC_H
23#define FFMPEG_VOC_H
24
25#include "avformat.h"
26#include "riff.h" /* for CodecTag */
27
28typedef struct voc_dec_context {
29 int remaining_size;
30} voc_dec_context_t;
31
32typedef enum voc_type {
33 VOC_TYPE_EOF = 0x00,
34 VOC_TYPE_VOICE_DATA = 0x01,
35 VOC_TYPE_VOICE_DATA_CONT = 0x02,
36 VOC_TYPE_SILENCE = 0x03,
37 VOC_TYPE_MARKER = 0x04,
38 VOC_TYPE_ASCII = 0x05,
39 VOC_TYPE_REPETITION_START = 0x06,
40 VOC_TYPE_REPETITION_END = 0x07,
41 VOC_TYPE_EXTENDED = 0x08,
42 VOC_TYPE_NEW_VOICE_DATA = 0x09,
43} voc_type_t;
44
45extern const unsigned char voc_magic[21];
46extern const AVCodecTag voc_codec_tags[];
47
48int voc_get_packet(AVFormatContext *s, AVPacket *pkt,
49 AVStream *st, int max_size);
50
51#endif /* FFMPEG_VOC_H */
diff --git a/src/plugins/ffmpeg/libavformat/vocdec.c b/src/plugins/ffmpeg/libavformat/vocdec.c
deleted file mode 100644
index 06ef0c3..0000000
--- a/src/plugins/ffmpeg/libavformat/vocdec.c
+++ /dev/null
@@ -1,145 +0,0 @@
1/*
2 * Creative Voice File demuxer.
3 * Copyright (c) 2006 Aurelien Jacobs <aurel@gnuage.org>
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 "voc.h"
23
24
25static int voc_probe(AVProbeData *p)
26{
27 int version, check;
28
29 if (memcmp(p->buf, voc_magic, sizeof(voc_magic) - 1))
30 return 0;
31 version = AV_RL16(p->buf + 22);
32 check = AV_RL16(p->buf + 24);
33 if (~version + 0x1234 != check)
34 return 10;
35
36 return AVPROBE_SCORE_MAX;
37}
38
39static int voc_read_header(AVFormatContext *s, AVFormatParameters *ap)
40{
41 voc_dec_context_t *voc = s->priv_data;
42 ByteIOContext *pb = s->pb;
43 int header_size;
44 AVStream *st;
45
46 url_fskip(pb, 20);
47 header_size = get_le16(pb) - 22;
48 if (header_size != 4) {
49 av_log(s, AV_LOG_ERROR, "unknown header size: %d\n", header_size);
50 return AVERROR(ENOSYS);
51 }
52 url_fskip(pb, header_size);
53 st = av_new_stream(s, 0);
54 if (!st)
55 return AVERROR(ENOMEM);
56 st->codec->codec_type = CODEC_TYPE_AUDIO;
57
58 voc->remaining_size = 0;
59 return 0;
60}
61
62int
63voc_get_packet(AVFormatContext *s, AVPacket *pkt, AVStream *st, int max_size)
64{
65 voc_dec_context_t *voc = s->priv_data;
66 AVCodecContext *dec = st->codec;
67 ByteIOContext *pb = s->pb;
68 voc_type_t type;
69 int size;
70 int sample_rate = 0;
71 int channels = 1;
72
73 while (!voc->remaining_size) {
74 type = get_byte(pb);
75 if (type == VOC_TYPE_EOF)
76 return AVERROR(EIO);
77 voc->remaining_size = get_le24(pb);
78 max_size -= 4;
79
80 switch (type) {
81 case VOC_TYPE_VOICE_DATA:
82 dec->sample_rate = 1000000 / (256 - get_byte(pb));
83 if (sample_rate)
84 dec->sample_rate = sample_rate;
85 dec->channels = channels;
86 dec->codec_id = codec_get_id(voc_codec_tags, get_byte(pb));
87 dec->bits_per_sample = av_get_bits_per_sample(dec->codec_id);
88 voc->remaining_size -= 2;
89 max_size -= 2;
90 channels = 1;
91 break;
92
93 case VOC_TYPE_VOICE_DATA_CONT:
94 break;
95
96 case VOC_TYPE_EXTENDED:
97 sample_rate = get_le16(pb);
98 get_byte(pb);
99 channels = get_byte(pb) + 1;
100 sample_rate = 256000000 / (channels * (65536 - sample_rate));
101 voc->remaining_size = 0;
102 max_size -= 4;
103 break;
104
105 case VOC_TYPE_NEW_VOICE_DATA:
106 dec->sample_rate = get_le32(pb);
107 dec->bits_per_sample = get_byte(pb);
108 dec->channels = get_byte(pb);
109 dec->codec_id = codec_get_id(voc_codec_tags, get_le16(pb));
110 url_fskip(pb, 4);
111 voc->remaining_size -= 12;
112 max_size -= 12;
113 break;
114
115 default:
116 url_fskip(pb, voc->remaining_size);
117 max_size -= voc->remaining_size;
118 voc->remaining_size = 0;
119 break;
120 }
121 }
122
123 dec->bit_rate = dec->sample_rate * dec->bits_per_sample;
124
125 if (max_size <= 0)
126 max_size = 2048;
127 size = FFMIN(voc->remaining_size, max_size);
128 voc->remaining_size -= size;
129 return av_get_packet(pb, pkt, size);
130}
131
132static int voc_read_packet(AVFormatContext *s, AVPacket *pkt)
133{
134 return voc_get_packet(s, pkt, s->streams[0], 0);
135}
136
137AVInputFormat voc_demuxer = {
138 "voc",
139 NULL_IF_CONFIG_SMALL("Creative Voice file format"),
140 sizeof(voc_dec_context_t),
141 voc_probe,
142 voc_read_header,
143 voc_read_packet,
144 .codec_tag=(const AVCodecTag*[]){voc_codec_tags, 0},
145};
diff --git a/src/plugins/ffmpeg/libavformat/vocenc.c b/src/plugins/ffmpeg/libavformat/vocenc.c
deleted file mode 100644
index a96dfc7..0000000
--- a/src/plugins/ffmpeg/libavformat/vocenc.c
+++ /dev/null
@@ -1,103 +0,0 @@
1/*
2 * Creative Voice File muxer.
3 * Copyright (c) 2006 Aurelien Jacobs <aurel@gnuage.org>
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 "voc.h"
23
24
25typedef struct voc_enc_context {
26 int param_written;
27} voc_enc_context_t;
28
29static int voc_write_header(AVFormatContext *s)
30{
31 ByteIOContext *pb = s->pb;
32 const int header_size = 26;
33 const int version = 0x0114;
34
35 if (s->nb_streams != 1
36 || s->streams[0]->codec->codec_type != CODEC_TYPE_AUDIO)
37 return AVERROR_PATCHWELCOME;
38
39 put_buffer(pb, voc_magic, sizeof(voc_magic) - 1);
40 put_le16(pb, header_size);
41 put_le16(pb, version);
42 put_le16(pb, ~version + 0x1234);
43
44 return 0;
45}
46
47static int voc_write_packet(AVFormatContext *s, AVPacket *pkt)
48{
49 voc_enc_context_t *voc = s->priv_data;
50 AVCodecContext *enc = s->streams[0]->codec;
51 ByteIOContext *pb = s->pb;
52
53 if (!voc->param_written) {
54 if (enc->codec_tag > 0xFF) {
55 put_byte(pb, VOC_TYPE_NEW_VOICE_DATA);
56 put_le24(pb, pkt->size + 12);
57 put_le32(pb, enc->sample_rate);
58 put_byte(pb, enc->bits_per_sample);
59 put_byte(pb, enc->channels);
60 put_le16(pb, enc->codec_tag);
61 put_le32(pb, 0);
62 } else {
63 if (s->streams[0]->codec->channels > 1) {
64 put_byte(pb, VOC_TYPE_EXTENDED);
65 put_le24(pb, 4);
66 put_le16(pb, 65536-256000000/(enc->sample_rate*enc->channels));
67 put_byte(pb, enc->codec_tag);
68 put_byte(pb, enc->channels - 1);
69 }
70 put_byte(pb, VOC_TYPE_VOICE_DATA);
71 put_le24(pb, pkt->size + 2);
72 put_byte(pb, 256 - 1000000 / enc->sample_rate);
73 put_byte(pb, enc->codec_tag);
74 }
75 voc->param_written = 1;
76 } else {
77 put_byte(pb, VOC_TYPE_VOICE_DATA_CONT);
78 put_le24(pb, pkt->size);
79 }
80
81 put_buffer(pb, pkt->data, pkt->size);
82 return 0;
83}
84
85static int voc_write_trailer(AVFormatContext *s)
86{
87 put_byte(s->pb, 0);
88 return 0;
89}
90
91AVOutputFormat voc_muxer = {
92 "voc",
93 NULL_IF_CONFIG_SMALL("Creative Voice file format"),
94 "audio/x-voc",
95 "voc",
96 sizeof(voc_enc_context_t),
97 CODEC_ID_PCM_U8,
98 CODEC_ID_NONE,
99 voc_write_header,
100 voc_write_packet,
101 voc_write_trailer,
102 .codec_tag=(const AVCodecTag*[]){voc_codec_tags, 0},
103};
diff --git a/src/plugins/ffmpeg/libavformat/wav.c b/src/plugins/ffmpeg/libavformat/wav.c
deleted file mode 100644
index 945ee39..0000000
--- a/src/plugins/ffmpeg/libavformat/wav.c
+++ /dev/null
@@ -1,285 +0,0 @@
1/*
2 * WAV muxer and demuxer
3 * Copyright (c) 2001, 2002 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#include "avformat.h"
22#include "raw.h"
23#include "riff.h"
24
25typedef struct {
26 offset_t data;
27 offset_t data_end;
28 int64_t minpts;
29 int64_t maxpts;
30 int last_duration;
31} WAVContext;
32
33#ifdef CONFIG_MUXERS
34static int wav_write_header(AVFormatContext *s)
35{
36 WAVContext *wav = s->priv_data;
37 ByteIOContext *pb = s->pb;
38 offset_t fmt, fact;
39
40 put_tag(pb, "RIFF");
41 put_le32(pb, 0); /* file length */
42 put_tag(pb, "WAVE");
43
44 /* format header */
45 fmt = start_tag(pb, "fmt ");
46 if (put_wav_header(pb, s->streams[0]->codec) < 0) {
47 av_free(wav);
48 return -1;
49 }
50 end_tag(pb, fmt);
51
52 if(s->streams[0]->codec->codec_tag != 0x01 /* hence for all other than PCM */
53 && !url_is_streamed(s->pb)) {
54 fact = start_tag(pb, "fact");
55 put_le32(pb, 0);
56 end_tag(pb, fact);
57 }
58
59 av_set_pts_info(s->streams[0], 64, 1, s->streams[0]->codec->sample_rate);
60 wav->maxpts = wav->last_duration = 0;
61 wav->minpts = INT64_MAX;
62
63 /* data header */
64 wav->data = start_tag(pb, "data");
65
66 put_flush_packet(pb);
67
68 return 0;
69}
70
71static int wav_write_packet(AVFormatContext *s, AVPacket *pkt)
72{
73 ByteIOContext *pb = s->pb;
74 WAVContext *wav = s->priv_data;
75 put_buffer(pb, pkt->data, pkt->size);
76 if(pkt->pts != AV_NOPTS_VALUE) {
77 wav->minpts = FFMIN(wav->minpts, pkt->pts);
78 wav->maxpts = FFMAX(wav->maxpts, pkt->pts);
79 wav->last_duration = pkt->duration;
80 } else
81 av_log(s, AV_LOG_ERROR, "wav_write_packet: NOPTS\n");
82 return 0;
83}
84
85static int wav_write_trailer(AVFormatContext *s)
86{
87 ByteIOContext *pb = s->pb;
88 WAVContext *wav = s->priv_data;
89 offset_t file_size;
90
91 if (!url_is_streamed(s->pb)) {
92 end_tag(pb, wav->data);
93
94 /* update file size */
95 file_size = url_ftell(pb);
96 url_fseek(pb, 4, SEEK_SET);
97 put_le32(pb, (uint32_t)(file_size - 8));
98 url_fseek(pb, file_size, SEEK_SET);
99
100 put_flush_packet(pb);
101
102 if(s->streams[0]->codec->codec_tag != 0x01) {
103 /* Update num_samps in fact chunk */
104 int number_of_samples;
105 number_of_samples = av_rescale(wav->maxpts - wav->minpts + wav->last_duration,
106 s->streams[0]->codec->sample_rate * (int64_t)s->streams[0]->time_base.num,
107 s->streams[0]->time_base.den);
108 url_fseek(pb, wav->data-12, SEEK_SET);
109 put_le32(pb, number_of_samples);
110 url_fseek(pb, file_size, SEEK_SET);
111 put_flush_packet(pb);
112 }
113 }
114 return 0;
115}
116#endif //CONFIG_MUXERS
117
118/* return the size of the found tag */
119/* XXX: > 2GB ? */
120static int find_tag(ByteIOContext *pb, uint32_t tag1)
121{
122 unsigned int tag;
123 int size;
124
125 for(;;) {
126 if (url_feof(pb))
127 return -1;
128 tag = get_le32(pb);
129 size = get_le32(pb);
130 if (tag == tag1)
131 break;
132 url_fseek(pb, size, SEEK_CUR);
133 }
134 if (size < 0)
135 size = 0x7fffffff;
136 return size;
137}
138
139static int wav_probe(AVProbeData *p)
140{
141 /* check file header */
142 if (p->buf_size <= 32)
143 return 0;
144 if (p->buf[0] == 'R' && p->buf[1] == 'I' &&
145 p->buf[2] == 'F' && p->buf[3] == 'F' &&
146 p->buf[8] == 'W' && p->buf[9] == 'A' &&
147 p->buf[10] == 'V' && p->buf[11] == 'E')
148 /*
149 Since ACT demuxer has standard WAV header at top of it's own,
150 returning score is decreased to avoid probe conflict
151 between ACT and WAV.
152 */
153 return AVPROBE_SCORE_MAX - 1;
154 else
155 return 0;
156}
157
158/* wav input */
159static int wav_read_header(AVFormatContext *s,
160 AVFormatParameters *ap)
161{
162 int size;
163 unsigned int tag;
164 ByteIOContext *pb = s->pb;
165 AVStream *st;
166 WAVContext *wav = s->priv_data;
167
168 /* check RIFF header */
169 tag = get_le32(pb);
170
171 if (tag != MKTAG('R', 'I', 'F', 'F'))
172 return -1;
173 get_le32(pb); /* file size */
174 tag = get_le32(pb);
175 if (tag != MKTAG('W', 'A', 'V', 'E'))
176 return -1;
177
178 /* parse fmt header */
179 size = find_tag(pb, MKTAG('f', 'm', 't', ' '));
180 if (size < 0)
181 return -1;
182 st = av_new_stream(s, 0);
183 if (!st)
184 return AVERROR(ENOMEM);
185
186 get_wav_header(pb, st->codec, size);
187 st->need_parsing = AVSTREAM_PARSE_FULL;
188
189 av_set_pts_info(st, 64, 1, st->codec->sample_rate);
190
191 size = find_tag(pb, MKTAG('d', 'a', 't', 'a'));
192 if (size < 0)
193 return -1;
194 wav->data_end= url_ftell(pb) + size;
195 return 0;
196}
197
198#define MAX_SIZE 4096
199
200static int wav_read_packet(AVFormatContext *s,
201 AVPacket *pkt)
202{
203 int ret, size, left;
204 AVStream *st;
205 WAVContext *wav = s->priv_data;
206
207 if (url_feof(s->pb))
208 return AVERROR(EIO);
209 st = s->streams[0];
210
211 left= wav->data_end - url_ftell(s->pb);
212 if(left <= 0){
213 left = find_tag(s->pb, MKTAG('d', 'a', 't', 'a'));
214 if (left < 0) {
215 return AVERROR(EIO);
216 }
217 wav->data_end= url_ftell(s->pb) + left;
218 }
219
220 size = MAX_SIZE;
221 if (st->codec->block_align > 1) {
222 if (size < st->codec->block_align)
223 size = st->codec->block_align;
224 size = (size / st->codec->block_align) * st->codec->block_align;
225 }
226 size= FFMIN(size, left);
227 ret= av_get_packet(s->pb, pkt, size);
228 if (ret <= 0)
229 return AVERROR(EIO);
230 pkt->stream_index = 0;
231
232 /* note: we need to modify the packet size here to handle the last
233 packet */
234 pkt->size = ret;
235 return ret;
236}
237
238static int wav_read_seek(AVFormatContext *s,
239 int stream_index, int64_t timestamp, int flags)
240{
241 AVStream *st;
242
243 st = s->streams[0];
244 switch(st->codec->codec_id) {
245 case CODEC_ID_MP2:
246 case CODEC_ID_MP3:
247 case CODEC_ID_AC3:
248 case CODEC_ID_DTS:
249 /* use generic seeking with dynamically generated indexes */
250 return -1;
251 default:
252 break;
253 }
254 return pcm_read_seek(s, stream_index, timestamp, flags);
255}
256
257#ifdef CONFIG_WAV_DEMUXER
258AVInputFormat wav_demuxer = {
259 "wav",
260 NULL_IF_CONFIG_SMALL("WAV format"),
261 sizeof(WAVContext),
262 wav_probe,
263 wav_read_header,
264 wav_read_packet,
265 NULL,
266 wav_read_seek,
267 .flags= AVFMT_GENERIC_INDEX,
268 .codec_tag= (const AVCodecTag*[]){codec_wav_tags, 0},
269};
270#endif
271#ifdef CONFIG_WAV_MUXER
272AVOutputFormat wav_muxer = {
273 "wav",
274 NULL_IF_CONFIG_SMALL("WAV format"),
275 "audio/x-wav",
276 "wav",
277 sizeof(WAVContext),
278 CODEC_ID_PCM_S16LE,
279 CODEC_ID_NONE,
280 wav_write_header,
281 wav_write_packet,
282 wav_write_trailer,
283 .codec_tag= (const AVCodecTag*[]){codec_wav_tags, 0},
284};
285#endif
diff --git a/src/plugins/ffmpeg/libavformat/wc3movie.c b/src/plugins/ffmpeg/libavformat/wc3movie.c
deleted file mode 100644
index bb9a6e2..0000000
--- a/src/plugins/ffmpeg/libavformat/wc3movie.c
+++ /dev/null
@@ -1,394 +0,0 @@
1/*
2 * Wing Commander III Movie (.mve) File Demuxer
3 * Copyright (c) 2003 The ffmpeg Project
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/**
23 * @file wc3movie.c
24 * Wing Commander III Movie file demuxer
25 * by Mike Melanson (melanson@pcisys.net)
26 * for more information on the WC3 .mve file format, visit:
27 * http://www.pcisys.net/~melanson/codecs/
28 */
29
30#include "avformat.h"
31
32#define WC3_PREAMBLE_SIZE 8
33
34#define FORM_TAG MKTAG('F', 'O', 'R', 'M')
35#define MOVE_TAG MKTAG('M', 'O', 'V', 'E')
36#define PC__TAG MKTAG('_', 'P', 'C', '_')
37#define SOND_TAG MKTAG('S', 'O', 'N', 'D')
38#define BNAM_TAG MKTAG('B', 'N', 'A', 'M')
39#define SIZE_TAG MKTAG('S', 'I', 'Z', 'E')
40#define PALT_TAG MKTAG('P', 'A', 'L', 'T')
41#define INDX_TAG MKTAG('I', 'N', 'D', 'X')
42#define BRCH_TAG MKTAG('B', 'R', 'C', 'H')
43#define SHOT_TAG MKTAG('S', 'H', 'O', 'T')
44#define VGA__TAG MKTAG('V', 'G', 'A', ' ')
45#define TEXT_TAG MKTAG('T', 'E', 'X', 'T')
46#define AUDI_TAG MKTAG('A', 'U', 'D', 'I')
47
48/* video resolution unless otherwise specified */
49#define WC3_DEFAULT_WIDTH 320
50#define WC3_DEFAULT_HEIGHT 165
51
52/* always use the same PCM audio parameters */
53#define WC3_SAMPLE_RATE 22050
54#define WC3_AUDIO_CHANNELS 1
55#define WC3_AUDIO_BITS 16
56
57/* nice, constant framerate */
58#define WC3_FRAME_FPS 15
59
60#define PALETTE_SIZE (256 * 3)
61#define PALETTE_COUNT 256
62
63typedef struct Wc3DemuxContext {
64 int width;
65 int height;
66 unsigned char *palettes;
67 int palette_count;
68 int64_t pts;
69 int video_stream_index;
70 int audio_stream_index;
71
72 AVPaletteControl palette_control;
73
74} Wc3DemuxContext;
75
76/* bizarre palette lookup table */
77static const unsigned char wc3_pal_lookup[] = {
78 0x00, 0x03, 0x05, 0x07, 0x09, 0x0B, 0x0D, 0x0E,
79 0x10, 0x12, 0x13, 0x15, 0x16, 0x18, 0x19, 0x1A,
80 0x1C, 0x1D, 0x1F, 0x20, 0x21, 0x23, 0x24, 0x25,
81 0x27, 0x28, 0x29, 0x2A, 0x2C, 0x2D, 0x2E, 0x2F,
82 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x38, 0x39,
83 0x3A, 0x3B, 0x3C, 0x3D, 0x3F, 0x40, 0x41, 0x42,
84 0x43, 0x44, 0x45, 0x46, 0x48, 0x49, 0x4A, 0x4B,
85 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53,
86 0x54, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C,
87 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, 0x64,
88 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C,
89 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74,
90 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C,
91 0x7D, 0x7D, 0x7E, 0x7F, 0x80, 0x81, 0x82, 0x83,
92 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B,
93 0x8C, 0x8D, 0x8D, 0x8E, 0x8F, 0x90, 0x91, 0x92,
94 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x99,
95 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F, 0xA0, 0xA1,
96 0xA2, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8,
97 0xA9, 0xAA, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF,
98 0xB0, 0xB1, 0xB2, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6,
99 0xB7, 0xB8, 0xB9, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD,
100 0xBE, 0xBF, 0xBF, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4,
101 0xC5, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB,
102 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD0, 0xD1,
103 0xD2, 0xD3, 0xD4, 0xD5, 0xD5, 0xD6, 0xD7, 0xD8,
104 0xD9, 0xDA, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF,
105 0xDF, 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE4, 0xE5,
106 0xE6, 0xE7, 0xE8, 0xE9, 0xE9, 0xEA, 0xEB, 0xEC,
107 0xED, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF1, 0xF2,
108 0xF3, 0xF4, 0xF5, 0xF6, 0xF6, 0xF7, 0xF8, 0xF9,
109 0xFA, 0xFA, 0xFB, 0xFC, 0xFD, 0xFD, 0xFD, 0xFD
110};
111
112
113static int wc3_probe(AVProbeData *p)
114{
115 if (p->buf_size < 12)
116 return 0;
117
118 if ((AV_RL32(&p->buf[0]) != FORM_TAG) ||
119 (AV_RL32(&p->buf[8]) != MOVE_TAG))
120 return 0;
121
122 return AVPROBE_SCORE_MAX;
123}
124
125static int wc3_read_header(AVFormatContext *s,
126 AVFormatParameters *ap)
127{
128 Wc3DemuxContext *wc3 = s->priv_data;
129 ByteIOContext *pb = s->pb;
130 unsigned int fourcc_tag;
131 unsigned int size;
132 AVStream *st;
133 unsigned char preamble[WC3_PREAMBLE_SIZE];
134 int ret = 0;
135 int current_palette = 0;
136 int bytes_to_read;
137 int i;
138 unsigned char rotate;
139
140 /* default context members */
141 wc3->width = WC3_DEFAULT_WIDTH;
142 wc3->height = WC3_DEFAULT_HEIGHT;
143 wc3->palettes = NULL;
144 wc3->palette_count = 0;
145 wc3->pts = 0;
146 wc3->video_stream_index = wc3->audio_stream_index = 0;
147
148 /* skip the first 3 32-bit numbers */
149 url_fseek(pb, 12, SEEK_CUR);
150
151 /* traverse through the chunks and load the header information before
152 * the first BRCH tag */
153 if ((ret = get_buffer(pb, preamble, WC3_PREAMBLE_SIZE)) !=
154 WC3_PREAMBLE_SIZE)
155 return AVERROR(EIO);
156 fourcc_tag = AV_RL32(&preamble[0]);
157 size = (AV_RB32(&preamble[4]) + 1) & (~1);
158
159 do {
160 switch (fourcc_tag) {
161
162 case SOND_TAG:
163 case INDX_TAG:
164 /* SOND unknown, INDX unnecessary; ignore both */
165 url_fseek(pb, size, SEEK_CUR);
166 break;
167
168 case PC__TAG:
169 /* need the number of palettes */
170 url_fseek(pb, 8, SEEK_CUR);
171 if ((ret = get_buffer(pb, preamble, 4)) != 4)
172 return AVERROR(EIO);
173 wc3->palette_count = AV_RL32(&preamble[0]);
174 if((unsigned)wc3->palette_count >= UINT_MAX / PALETTE_SIZE){
175 wc3->palette_count= 0;
176 return -1;
177 }
178 wc3->palettes = av_malloc(wc3->palette_count * PALETTE_SIZE);
179 break;
180
181 case BNAM_TAG:
182 /* load up the name */
183 if ((unsigned)size < 512)
184 bytes_to_read = size;
185 else
186 bytes_to_read = 512;
187 if ((ret = get_buffer(pb, s->title, bytes_to_read)) != bytes_to_read)
188 return AVERROR(EIO);
189 break;
190
191 case SIZE_TAG:
192 /* video resolution override */
193 if ((ret = get_buffer(pb, preamble, WC3_PREAMBLE_SIZE)) !=
194 WC3_PREAMBLE_SIZE)
195 return AVERROR(EIO);
196 wc3->width = AV_RL32(&preamble[0]);
197 wc3->height = AV_RL32(&preamble[4]);
198 break;
199
200 case PALT_TAG:
201 /* one of several palettes */
202 if ((unsigned)current_palette >= wc3->palette_count)
203 return AVERROR_INVALIDDATA;
204 if ((ret = get_buffer(pb,
205 &wc3->palettes[current_palette * PALETTE_SIZE],
206 PALETTE_SIZE)) != PALETTE_SIZE)
207 return AVERROR(EIO);
208
209 /* transform the current palette in place */
210 for (i = current_palette * PALETTE_SIZE;
211 i < (current_palette + 1) * PALETTE_SIZE; i++) {
212 /* rotate each palette component left by 2 and use the result
213 * as an index into the color component table */
214 rotate = ((wc3->palettes[i] << 2) & 0xFF) |
215 ((wc3->palettes[i] >> 6) & 0xFF);
216 wc3->palettes[i] = wc3_pal_lookup[rotate];
217 }
218 current_palette++;
219 break;
220
221 default:
222 av_log(s, AV_LOG_ERROR, " unrecognized WC3 chunk: %c%c%c%c (0x%02X%02X%02X%02X)\n",
223 preamble[0], preamble[1], preamble[2], preamble[3],
224 preamble[0], preamble[1], preamble[2], preamble[3]);
225 return AVERROR_INVALIDDATA;
226 break;
227 }
228
229 if ((ret = get_buffer(pb, preamble, WC3_PREAMBLE_SIZE)) !=
230 WC3_PREAMBLE_SIZE)
231 return AVERROR(EIO);
232 fourcc_tag = AV_RL32(&preamble[0]);
233 /* chunk sizes are 16-bit aligned */
234 size = (AV_RB32(&preamble[4]) + 1) & (~1);
235
236 } while (fourcc_tag != BRCH_TAG);
237
238 /* initialize the decoder streams */
239 st = av_new_stream(s, 0);
240 if (!st)
241 return AVERROR(ENOMEM);
242 av_set_pts_info(st, 33, 1, WC3_FRAME_FPS);
243 wc3->video_stream_index = st->index;
244 st->codec->codec_type = CODEC_TYPE_VIDEO;
245 st->codec->codec_id = CODEC_ID_XAN_WC3;
246 st->codec->codec_tag = 0; /* no fourcc */
247 st->codec->width = wc3->width;
248 st->codec->height = wc3->height;
249
250 /* palette considerations */
251 st->codec->palctrl = &wc3->palette_control;
252
253 st = av_new_stream(s, 0);
254 if (!st)
255 return AVERROR(ENOMEM);
256 av_set_pts_info(st, 33, 1, WC3_FRAME_FPS);
257 wc3->audio_stream_index = st->index;
258 st->codec->codec_type = CODEC_TYPE_AUDIO;
259 st->codec->codec_id = CODEC_ID_PCM_S16LE;
260 st->codec->codec_tag = 1;
261 st->codec->channels = WC3_AUDIO_CHANNELS;
262 st->codec->bits_per_sample = WC3_AUDIO_BITS;
263 st->codec->sample_rate = WC3_SAMPLE_RATE;
264 st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *
265 st->codec->bits_per_sample;
266 st->codec->block_align = WC3_AUDIO_BITS * WC3_AUDIO_CHANNELS;
267
268 return 0;
269}
270
271static int wc3_read_packet(AVFormatContext *s,
272 AVPacket *pkt)
273{
274 Wc3DemuxContext *wc3 = s->priv_data;
275 ByteIOContext *pb = s->pb;
276 unsigned int fourcc_tag;
277 unsigned int size;
278 int packet_read = 0;
279 int ret = 0;
280 unsigned char preamble[WC3_PREAMBLE_SIZE];
281 unsigned char text[1024];
282 unsigned int palette_number;
283 int i;
284 unsigned char r, g, b;
285 int base_palette_index;
286
287 while (!packet_read) {
288
289 /* get the next chunk preamble */
290 if ((ret = get_buffer(pb, preamble, WC3_PREAMBLE_SIZE)) !=
291 WC3_PREAMBLE_SIZE)
292 ret = AVERROR(EIO);
293
294 fourcc_tag = AV_RL32(&preamble[0]);
295 /* chunk sizes are 16-bit aligned */
296 size = (AV_RB32(&preamble[4]) + 1) & (~1);
297
298 switch (fourcc_tag) {
299
300 case BRCH_TAG:
301 /* no-op */
302 break;
303
304 case SHOT_TAG:
305 /* load up new palette */
306 if ((ret = get_buffer(pb, preamble, 4)) != 4)
307 return AVERROR(EIO);
308 palette_number = AV_RL32(&preamble[0]);
309 if (palette_number >= wc3->palette_count)
310 return AVERROR_INVALIDDATA;
311 base_palette_index = palette_number * PALETTE_COUNT * 3;
312 for (i = 0; i < PALETTE_COUNT; i++) {
313 r = wc3->palettes[base_palette_index + i * 3 + 0];
314 g = wc3->palettes[base_palette_index + i * 3 + 1];
315 b = wc3->palettes[base_palette_index + i * 3 + 2];
316 wc3->palette_control.palette[i] = (r << 16) | (g << 8) | (b);
317 }
318 wc3->palette_control.palette_changed = 1;
319 break;
320
321 case VGA__TAG:
322 /* send out video chunk */
323 ret= av_get_packet(pb, pkt, size);
324 pkt->stream_index = wc3->video_stream_index;
325 pkt->pts = wc3->pts;
326 if (ret != size)
327 ret = AVERROR(EIO);
328 packet_read = 1;
329 break;
330
331 case TEXT_TAG:
332 /* subtitle chunk */
333#if 0
334 url_fseek(pb, size, SEEK_CUR);
335#else
336 if ((unsigned)size > sizeof(text) || (ret = get_buffer(pb, text, size)) != size)
337 ret = AVERROR(EIO);
338 else {
339 int i = 0;
340 av_log (s, AV_LOG_DEBUG, "Subtitle time!\n");
341 av_log (s, AV_LOG_DEBUG, " inglish: %s\n", &text[i + 1]);
342 i += text[i] + 1;
343 av_log (s, AV_LOG_DEBUG, " doytsch: %s\n", &text[i + 1]);
344 i += text[i] + 1;
345 av_log (s, AV_LOG_DEBUG, " fronsay: %s\n", &text[i + 1]);
346 }
347#endif
348 break;
349
350 case AUDI_TAG:
351 /* send out audio chunk */
352 ret= av_get_packet(pb, pkt, size);
353 pkt->stream_index = wc3->audio_stream_index;
354 pkt->pts = wc3->pts;
355 if (ret != size)
356 ret = AVERROR(EIO);
357
358 /* time to advance pts */
359 wc3->pts++;
360
361 packet_read = 1;
362 break;
363
364 default:
365 av_log (s, AV_LOG_ERROR, " unrecognized WC3 chunk: %c%c%c%c (0x%02X%02X%02X%02X)\n",
366 preamble[0], preamble[1], preamble[2], preamble[3],
367 preamble[0], preamble[1], preamble[2], preamble[3]);
368 ret = AVERROR_INVALIDDATA;
369 packet_read = 1;
370 break;
371 }
372 }
373
374 return ret;
375}
376
377static int wc3_read_close(AVFormatContext *s)
378{
379 Wc3DemuxContext *wc3 = s->priv_data;
380
381 av_free(wc3->palettes);
382
383 return 0;
384}
385
386AVInputFormat wc3_demuxer = {
387 "wc3movie",
388 NULL_IF_CONFIG_SMALL("Wing Commander III movie format"),
389 sizeof(Wc3DemuxContext),
390 wc3_probe,
391 wc3_read_header,
392 wc3_read_packet,
393 wc3_read_close,
394};
diff --git a/src/plugins/ffmpeg/libavformat/westwood.c b/src/plugins/ffmpeg/libavformat/westwood.c
deleted file mode 100644
index d1ac63c..0000000
--- a/src/plugins/ffmpeg/libavformat/westwood.c
+++ /dev/null
@@ -1,392 +0,0 @@
1/*
2 * Westwood Studios Multimedia Formats Demuxer (VQA, AUD)
3 * Copyright (c) 2003 The ffmpeg Project
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/**
23 * @file westwood.c
24 * Westwood Studios VQA & AUD file demuxers
25 * by Mike Melanson (melanson@pcisys.net)
26 * for more information on the Westwood file formats, visit:
27 * http://www.pcisys.net/~melanson/codecs/
28 * http://www.geocities.com/SiliconValley/8682/aud3.txt
29 *
30 * Implementation note: There is no definite file signature for AUD files.
31 * The demuxer uses a probabilistic strategy for content detection. This
32 * entails performing sanity checks on certain header values in order to
33 * qualify a file. Refer to wsaud_probe() for the precise parameters.
34 */
35
36#include "avformat.h"
37
38#define AUD_HEADER_SIZE 12
39#define AUD_CHUNK_PREAMBLE_SIZE 8
40#define AUD_CHUNK_SIGNATURE 0x0000DEAF
41
42#define FORM_TAG MKBETAG('F', 'O', 'R', 'M')
43#define WVQA_TAG MKBETAG('W', 'V', 'Q', 'A')
44#define VQHD_TAG MKBETAG('V', 'Q', 'H', 'D')
45#define FINF_TAG MKBETAG('F', 'I', 'N', 'F')
46#define SND0_TAG MKBETAG('S', 'N', 'D', '0')
47#define SND1_TAG MKBETAG('S', 'N', 'D', '1')
48#define SND2_TAG MKBETAG('S', 'N', 'D', '2')
49#define VQFR_TAG MKBETAG('V', 'Q', 'F', 'R')
50
51/* don't know what these tags are for, but acknowledge their existence */
52#define CINF_TAG MKBETAG('C', 'I', 'N', 'F')
53#define CINH_TAG MKBETAG('C', 'I', 'N', 'H')
54#define CIND_TAG MKBETAG('C', 'I', 'N', 'D')
55#define PINF_TAG MKBETAG('P', 'I', 'N', 'F')
56#define PINH_TAG MKBETAG('P', 'I', 'N', 'H')
57#define PIND_TAG MKBETAG('P', 'I', 'N', 'D')
58#define CMDS_TAG MKBETAG('C', 'M', 'D', 'S')
59
60#define VQA_HEADER_SIZE 0x2A
61#define VQA_FRAMERATE 15
62#define VQA_VIDEO_PTS_INC (90000 / VQA_FRAMERATE)
63#define VQA_PREAMBLE_SIZE 8
64
65typedef struct WsAudDemuxContext {
66 int audio_samplerate;
67 int audio_channels;
68 int audio_bits;
69 int audio_type;
70 int audio_stream_index;
71 int64_t audio_frame_counter;
72} WsAudDemuxContext;
73
74typedef struct WsVqaDemuxContext {
75 int audio_samplerate;
76 int audio_channels;
77 int audio_bits;
78
79 int audio_stream_index;
80 int video_stream_index;
81
82 int64_t audio_frame_counter;
83 int64_t video_pts;
84} WsVqaDemuxContext;
85
86static int wsaud_probe(AVProbeData *p)
87{
88 int field;
89
90 /* Probabilistic content detection strategy: There is no file signature
91 * so perform sanity checks on various header parameters:
92 * 8000 <= sample rate (16 bits) <= 48000 ==> 40001 acceptable numbers
93 * flags <= 0x03 (2 LSBs are used) ==> 4 acceptable numbers
94 * compression type (8 bits) = 1 or 99 ==> 2 acceptable numbers
95 * first audio chunk signature (32 bits) ==> 1 acceptable number
96 * The number space contains 2^64 numbers. There are 40001 * 4 * 2 * 1 =
97 * 320008 acceptable number combinations.
98 */
99
100 if (p->buf_size < AUD_HEADER_SIZE + AUD_CHUNK_PREAMBLE_SIZE)
101 return 0;
102
103 /* check sample rate */
104 field = AV_RL16(&p->buf[0]);
105 if ((field < 8000) || (field > 48000))
106 return 0;
107
108 /* enforce the rule that the top 6 bits of this flags field are reserved (0);
109 * this might not be true, but enforce it until deemed unnecessary */
110 if (p->buf[10] & 0xFC)
111 return 0;
112
113 /* note: only check for WS IMA (type 99) right now since there is no
114 * support for type 1 */
115 if (p->buf[11] != 99)
116 return 0;
117
118 /* read ahead to the first audio chunk and validate the first header signature */
119 if (AV_RL32(&p->buf[16]) != AUD_CHUNK_SIGNATURE)
120 return 0;
121
122 /* return 1/2 certainty since this file check is a little sketchy */
123 return AVPROBE_SCORE_MAX / 2;
124}
125
126static int wsaud_read_header(AVFormatContext *s,
127 AVFormatParameters *ap)
128{
129 WsAudDemuxContext *wsaud = s->priv_data;
130 ByteIOContext *pb = s->pb;
131 AVStream *st;
132 unsigned char header[AUD_HEADER_SIZE];
133
134 if (get_buffer(pb, header, AUD_HEADER_SIZE) != AUD_HEADER_SIZE)
135 return AVERROR(EIO);
136 wsaud->audio_samplerate = AV_RL16(&header[0]);
137 if (header[11] == 99)
138 wsaud->audio_type = CODEC_ID_ADPCM_IMA_WS;
139 else
140 return AVERROR_INVALIDDATA;
141
142 /* flag 0 indicates stereo */
143 wsaud->audio_channels = (header[10] & 0x1) + 1;
144 /* flag 1 indicates 16 bit audio */
145 wsaud->audio_bits = (((header[10] & 0x2) >> 1) + 1) * 8;
146
147 /* initialize the audio decoder stream */
148 st = av_new_stream(s, 0);
149 if (!st)
150 return AVERROR(ENOMEM);
151 av_set_pts_info(st, 33, 1, wsaud->audio_samplerate);
152 st->codec->codec_type = CODEC_TYPE_AUDIO;
153 st->codec->codec_id = wsaud->audio_type;
154 st->codec->codec_tag = 0; /* no tag */
155 st->codec->channels = wsaud->audio_channels;
156 st->codec->sample_rate = wsaud->audio_samplerate;
157 st->codec->bits_per_sample = wsaud->audio_bits;
158 st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *
159 st->codec->bits_per_sample / 4;
160 st->codec->block_align = st->codec->channels * st->codec->bits_per_sample;
161
162 wsaud->audio_stream_index = st->index;
163 wsaud->audio_frame_counter = 0;
164
165 return 0;
166}
167
168static int wsaud_read_packet(AVFormatContext *s,
169 AVPacket *pkt)
170{
171 WsAudDemuxContext *wsaud = s->priv_data;
172 ByteIOContext *pb = s->pb;
173 unsigned char preamble[AUD_CHUNK_PREAMBLE_SIZE];
174 unsigned int chunk_size;
175 int ret = 0;
176
177 if (get_buffer(pb, preamble, AUD_CHUNK_PREAMBLE_SIZE) !=
178 AUD_CHUNK_PREAMBLE_SIZE)
179 return AVERROR(EIO);
180
181 /* validate the chunk */
182 if (AV_RL32(&preamble[4]) != AUD_CHUNK_SIGNATURE)
183 return AVERROR_INVALIDDATA;
184
185 chunk_size = AV_RL16(&preamble[0]);
186 ret= av_get_packet(pb, pkt, chunk_size);
187 if (ret != chunk_size)
188 return AVERROR(EIO);
189 pkt->stream_index = wsaud->audio_stream_index;
190 pkt->pts = wsaud->audio_frame_counter;
191 pkt->pts /= wsaud->audio_samplerate;
192
193 /* 2 samples/byte, 1 or 2 samples per frame depending on stereo */
194 wsaud->audio_frame_counter += (chunk_size * 2) / wsaud->audio_channels;
195
196 return ret;
197}
198
199static int wsvqa_probe(AVProbeData *p)
200{
201 /* need 12 bytes to qualify */
202 if (p->buf_size < 12)
203 return 0;
204
205 /* check for the VQA signatures */
206 if ((AV_RB32(&p->buf[0]) != FORM_TAG) ||
207 (AV_RB32(&p->buf[8]) != WVQA_TAG))
208 return 0;
209
210 return AVPROBE_SCORE_MAX;
211}
212
213static int wsvqa_read_header(AVFormatContext *s,
214 AVFormatParameters *ap)
215{
216 WsVqaDemuxContext *wsvqa = s->priv_data;
217 ByteIOContext *pb = s->pb;
218 AVStream *st;
219 unsigned char *header;
220 unsigned char scratch[VQA_PREAMBLE_SIZE];
221 unsigned int chunk_tag;
222 unsigned int chunk_size;
223
224 /* initialize the video decoder stream */
225 st = av_new_stream(s, 0);
226 if (!st)
227 return AVERROR(ENOMEM);
228 av_set_pts_info(st, 33, 1, VQA_FRAMERATE);
229 wsvqa->video_stream_index = st->index;
230 st->codec->codec_type = CODEC_TYPE_VIDEO;
231 st->codec->codec_id = CODEC_ID_WS_VQA;
232 st->codec->codec_tag = 0; /* no fourcc */
233
234 /* skip to the start of the VQA header */
235 url_fseek(pb, 20, SEEK_SET);
236
237 /* the VQA header needs to go to the decoder */
238 st->codec->extradata_size = VQA_HEADER_SIZE;
239 st->codec->extradata = av_mallocz(VQA_HEADER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
240 header = (unsigned char *)st->codec->extradata;
241 if (get_buffer(pb, st->codec->extradata, VQA_HEADER_SIZE) !=
242 VQA_HEADER_SIZE) {
243 av_free(st->codec->extradata);
244 return AVERROR(EIO);
245 }
246 st->codec->width = AV_RL16(&header[6]);
247 st->codec->height = AV_RL16(&header[8]);
248
249 /* initialize the audio decoder stream for VQA v1 or nonzero samplerate */
250 if (AV_RL16(&header[24]) || (AV_RL16(&header[0]) == 1 && AV_RL16(&header[2]) == 1)) {
251 st = av_new_stream(s, 0);
252 if (!st)
253 return AVERROR(ENOMEM);
254 av_set_pts_info(st, 33, 1, VQA_FRAMERATE);
255 st->codec->codec_type = CODEC_TYPE_AUDIO;
256 if (AV_RL16(&header[0]) == 1)
257 st->codec->codec_id = CODEC_ID_WESTWOOD_SND1;
258 else
259 st->codec->codec_id = CODEC_ID_ADPCM_IMA_WS;
260 st->codec->codec_tag = 0; /* no tag */
261 st->codec->sample_rate = AV_RL16(&header[24]);
262 if (!st->codec->sample_rate)
263 st->codec->sample_rate = 22050;
264 st->codec->channels = header[26];
265 if (!st->codec->channels)
266 st->codec->channels = 1;
267 st->codec->bits_per_sample = 16;
268 st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *
269 st->codec->bits_per_sample / 4;
270 st->codec->block_align = st->codec->channels * st->codec->bits_per_sample;
271
272 wsvqa->audio_stream_index = st->index;
273 wsvqa->audio_samplerate = st->codec->sample_rate;
274 wsvqa->audio_channels = st->codec->channels;
275 wsvqa->audio_frame_counter = 0;
276 }
277
278 /* there are 0 or more chunks before the FINF chunk; iterate until
279 * FINF has been skipped and the file will be ready to be demuxed */
280 do {
281 if (get_buffer(pb, scratch, VQA_PREAMBLE_SIZE) != VQA_PREAMBLE_SIZE) {
282 av_free(st->codec->extradata);
283 return AVERROR(EIO);
284 }
285 chunk_tag = AV_RB32(&scratch[0]);
286 chunk_size = AV_RB32(&scratch[4]);
287
288 /* catch any unknown header tags, for curiousity */
289 switch (chunk_tag) {
290 case CINF_TAG:
291 case CINH_TAG:
292 case CIND_TAG:
293 case PINF_TAG:
294 case PINH_TAG:
295 case PIND_TAG:
296 case FINF_TAG:
297 case CMDS_TAG:
298 break;
299
300 default:
301 av_log (s, AV_LOG_ERROR, " note: unknown chunk seen (%c%c%c%c)\n",
302 scratch[0], scratch[1],
303 scratch[2], scratch[3]);
304 break;
305 }
306
307 url_fseek(pb, chunk_size, SEEK_CUR);
308 } while (chunk_tag != FINF_TAG);
309
310 wsvqa->video_pts = wsvqa->audio_frame_counter = 0;
311
312 return 0;
313}
314
315static int wsvqa_read_packet(AVFormatContext *s,
316 AVPacket *pkt)
317{
318 WsVqaDemuxContext *wsvqa = s->priv_data;
319 ByteIOContext *pb = s->pb;
320 int ret = -1;
321 unsigned char preamble[VQA_PREAMBLE_SIZE];
322 unsigned int chunk_type;
323 unsigned int chunk_size;
324 int skip_byte;
325
326 while (get_buffer(pb, preamble, VQA_PREAMBLE_SIZE) == VQA_PREAMBLE_SIZE) {
327 chunk_type = AV_RB32(&preamble[0]);
328 chunk_size = AV_RB32(&preamble[4]);
329 skip_byte = chunk_size & 0x01;
330
331 if ((chunk_type == SND1_TAG) || (chunk_type == SND2_TAG) || (chunk_type == VQFR_TAG)) {
332
333 if (av_new_packet(pkt, chunk_size))
334 return AVERROR(EIO);
335 ret = get_buffer(pb, pkt->data, chunk_size);
336 if (ret != chunk_size) {
337 av_free_packet(pkt);
338 return AVERROR(EIO);
339 }
340
341 if (chunk_type == SND2_TAG) {
342 pkt->stream_index = wsvqa->audio_stream_index;
343 /* 2 samples/byte, 1 or 2 samples per frame depending on stereo */
344 wsvqa->audio_frame_counter += (chunk_size * 2) / wsvqa->audio_channels;
345 } else if(chunk_type == SND1_TAG) {
346 pkt->stream_index = wsvqa->audio_stream_index;
347 /* unpacked size is stored in header */
348 wsvqa->audio_frame_counter += AV_RL16(pkt->data) / wsvqa->audio_channels;
349 } else {
350 pkt->stream_index = wsvqa->video_stream_index;
351 wsvqa->video_pts += VQA_VIDEO_PTS_INC;
352 }
353 /* stay on 16-bit alignment */
354 if (skip_byte)
355 url_fseek(pb, 1, SEEK_CUR);
356
357 return ret;
358 } else {
359 switch(chunk_type){
360 case CMDS_TAG:
361 case SND0_TAG:
362 break;
363 default:
364 av_log(s, AV_LOG_INFO, "Skipping unknown chunk 0x%08X\n", chunk_type);
365 }
366 url_fseek(pb, chunk_size + skip_byte, SEEK_CUR);
367 }
368 }
369
370 return ret;
371}
372
373#ifdef CONFIG_WSAUD_DEMUXER
374AVInputFormat wsaud_demuxer = {
375 "wsaud",
376 NULL_IF_CONFIG_SMALL("Westwood Studios audio format"),
377 sizeof(WsAudDemuxContext),
378 wsaud_probe,
379 wsaud_read_header,
380 wsaud_read_packet,
381};
382#endif
383#ifdef CONFIG_WSVQA_DEMUXER
384AVInputFormat wsvqa_demuxer = {
385 "wsvqa",
386 NULL_IF_CONFIG_SMALL("Westwood Studios VQA format"),
387 sizeof(WsVqaDemuxContext),
388 wsvqa_probe,
389 wsvqa_read_header,
390 wsvqa_read_packet,
391};
392#endif
diff --git a/src/plugins/ffmpeg/libavformat/wv.c b/src/plugins/ffmpeg/libavformat/wv.c
deleted file mode 100644
index eddd321..0000000
--- a/src/plugins/ffmpeg/libavformat/wv.c
+++ /dev/null
@@ -1,231 +0,0 @@
1/*
2 * WavPack demuxer
3 * Copyright (c) 2006 Konstantin Shishkov.
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 "avformat.h"
24
25// specs say that maximum block size is 1Mb
26#define WV_BLOCK_LIMIT 1047576
27
28#define WV_EXTRA_SIZE 12
29
30enum WV_FLAGS{
31 WV_MONO = 0x0004,
32 WV_HYBRID = 0x0008,
33 WV_JOINT = 0x0010,
34 WV_CROSSD = 0x0020,
35 WV_HSHAPE = 0x0040,
36 WV_FLOAT = 0x0080,
37 WV_INT32 = 0x0100,
38 WV_HBR = 0x0200,
39 WV_HBAL = 0x0400,
40 WV_MCINIT = 0x0800,
41 WV_MCEND = 0x1000,
42};
43
44static const int wv_rates[16] = {
45 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000,
46 32000, 44100, 48000, 64000, 88200, 96000, 192000, -1
47};
48
49typedef struct{
50 uint32_t blksize, flags;
51 int rate, chan, bpp;
52 uint32_t samples, soff;
53 int block_parsed;
54 uint8_t extra[WV_EXTRA_SIZE];
55 int64_t pos;
56}WVContext;
57
58static int wv_probe(AVProbeData *p)
59{
60 /* check file header */
61 if (p->buf_size <= 32)
62 return 0;
63 if (p->buf[0] == 'w' && p->buf[1] == 'v' &&
64 p->buf[2] == 'p' && p->buf[3] == 'k')
65 return AVPROBE_SCORE_MAX;
66 else
67 return 0;
68}
69
70static int wv_read_block_header(AVFormatContext *ctx, ByteIOContext *pb)
71{
72 WVContext *wc = ctx->priv_data;
73 uint32_t tag, ver;
74 int size;
75 int rate, bpp, chan;
76
77 wc->pos = url_ftell(pb);
78 tag = get_le32(pb);
79 if (tag != MKTAG('w', 'v', 'p', 'k'))
80 return -1;
81 size = get_le32(pb);
82 if(size < 24 || size > WV_BLOCK_LIMIT){
83 av_log(ctx, AV_LOG_ERROR, "Incorrect block size %i\n", size);
84 return -1;
85 }
86 wc->blksize = size;
87 ver = get_le16(pb);
88 if(ver < 0x402 || ver > 0x410){
89 av_log(ctx, AV_LOG_ERROR, "Unsupported version %03X\n", ver);
90 return -1;
91 }
92 get_byte(pb); // track no
93 get_byte(pb); // track sub index
94 wc->samples = get_le32(pb); // total samples in file
95 wc->soff = get_le32(pb); // offset in samples of current block
96 get_buffer(pb, wc->extra, WV_EXTRA_SIZE);
97 wc->flags = AV_RL32(wc->extra + 4);
98 //parse flags
99 if(wc->flags & WV_FLOAT){
100 av_log(ctx, AV_LOG_ERROR, "Floating point data is not supported\n");
101 return -1;
102 }
103 if(wc->flags & WV_HYBRID){
104 av_log(ctx, AV_LOG_ERROR, "Hybrid coding mode is not supported\n");
105 return -1;
106 }
107
108 bpp = ((wc->flags & 3) + 1) << 3;
109 chan = 1 + !(wc->flags & WV_MONO);
110 rate = wv_rates[(wc->flags >> 23) & 0xF];
111 if(rate == -1){
112 av_log(ctx, AV_LOG_ERROR, "Unknown sampling rate\n");
113 return -1;
114 }
115 if(!wc->bpp) wc->bpp = bpp;
116 if(!wc->chan) wc->chan = chan;
117 if(!wc->rate) wc->rate = rate;
118
119 if(wc->flags && bpp != wc->bpp){
120 av_log(ctx, AV_LOG_ERROR, "Bits per sample differ, this block: %i, header block: %i\n", bpp, wc->bpp);
121 return -1;
122 }
123 if(wc->flags && chan != wc->chan){
124 av_log(ctx, AV_LOG_ERROR, "Channels differ, this block: %i, header block: %i\n", chan, wc->chan);
125 return -1;
126 }
127 if(wc->flags && rate != wc->rate){
128 av_log(ctx, AV_LOG_ERROR, "Sampling rate differ, this block: %i, header block: %i\n", rate, wc->rate);
129 return -1;
130 }
131 wc->blksize = size - 24;
132 return 0;
133}
134
135static int wv_read_header(AVFormatContext *s,
136 AVFormatParameters *ap)
137{
138 ByteIOContext *pb = s->pb;
139 WVContext *wc = s->priv_data;
140 AVStream *st;
141
142 if(wv_read_block_header(s, pb) < 0)
143 return -1;
144
145 wc->block_parsed = 0;
146 /* now we are ready: build format streams */
147 st = av_new_stream(s, 0);
148 if (!st)
149 return -1;
150 st->codec->codec_type = CODEC_TYPE_AUDIO;
151 st->codec->codec_id = CODEC_ID_WAVPACK;
152 st->codec->channels = wc->chan;
153 st->codec->sample_rate = wc->rate;
154 st->codec->bits_per_sample = wc->bpp;
155 av_set_pts_info(st, 64, 1, wc->rate);
156 s->start_time = 0;
157 s->duration = (int64_t)wc->samples * AV_TIME_BASE / st->codec->sample_rate;
158 return 0;
159}
160
161static int wv_read_packet(AVFormatContext *s,
162 AVPacket *pkt)
163{
164 WVContext *wc = s->priv_data;
165 int ret;
166
167 if (url_feof(s->pb))
168 return AVERROR(EIO);
169 if(wc->block_parsed){
170 if(wv_read_block_header(s, s->pb) < 0)
171 return -1;
172 }
173
174 if(av_new_packet(pkt, wc->blksize + WV_EXTRA_SIZE) < 0)
175 return AVERROR(ENOMEM);
176 memcpy(pkt->data, wc->extra, WV_EXTRA_SIZE);
177 ret = get_buffer(s->pb, pkt->data + WV_EXTRA_SIZE, wc->blksize);
178 if(ret != wc->blksize){
179 av_free_packet(pkt);
180 return AVERROR(EIO);
181 }
182 pkt->stream_index = 0;
183 wc->block_parsed = 1;
184 pkt->size = ret + WV_EXTRA_SIZE;
185 pkt->pts = wc->soff;
186 av_add_index_entry(s->streams[0], wc->pos, pkt->pts, 0, 0, AVINDEX_KEYFRAME);
187 return 0;
188}
189
190static int wv_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
191{
192 AVStream *st = s->streams[stream_index];
193 WVContext *wc = s->priv_data;
194 AVPacket pkt1, *pkt = &pkt1;
195 int ret;
196 int index = av_index_search_timestamp(st, timestamp, flags);
197 int64_t pos, pts;
198
199 /* if found, seek there */
200 if (index >= 0){
201 wc->block_parsed = 1;
202 url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
203 return 0;
204 }
205 /* if timestamp is out of bounds, return error */
206 if(timestamp < 0 || timestamp >= s->duration)
207 return -1;
208
209 pos = url_ftell(s->pb);
210 do{
211 ret = av_read_frame(s, pkt);
212 if (ret < 0){
213 url_fseek(s->pb, pos, SEEK_SET);
214 return -1;
215 }
216 pts = pkt->pts;
217 av_free_packet(pkt);
218 }while(pts < timestamp);
219 return 0;
220}
221
222AVInputFormat wv_demuxer = {
223 "wv",
224 NULL_IF_CONFIG_SMALL("WavPack"),
225 sizeof(WVContext),
226 wv_probe,
227 wv_read_header,
228 wv_read_packet,
229 NULL,
230 wv_read_seek,
231};
diff --git a/src/plugins/ffmpeg/libavformat/xa.c b/src/plugins/ffmpeg/libavformat/xa.c
deleted file mode 100644
index c79df78..0000000
--- a/src/plugins/ffmpeg/libavformat/xa.c
+++ /dev/null
@@ -1,116 +0,0 @@
1/*
2 * Maxis XA (.xa) File Demuxer
3 * Copyright (c) 2008 Robert Marston
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/**
23 * @file xa.c
24 * Maxis XA File Demuxer
25 * by Robert Marston (rmarston@gmail.com)
26 * for more information on the XA audio format see
27 * http://wiki.multimedia.cx/index.php?title=Maxis_XA
28 */
29
30#include "avformat.h"
31
32#define XA00_TAG MKTAG('X', 'A', 0, 0)
33#define XAI0_TAG MKTAG('X', 'A', 'I', 0)
34#define XAJ0_TAG MKTAG('X', 'A', 'J', 0)
35
36typedef struct MaxisXADemuxContext {
37 uint32_t out_size;
38 uint32_t sent_bytes;
39 uint32_t audio_frame_counter;
40} MaxisXADemuxContext;
41
42static int xa_probe(AVProbeData *p)
43{
44 switch(AV_RL32(p->buf)) {
45 case XA00_TAG:
46 case XAI0_TAG:
47 case XAJ0_TAG:
48 return AVPROBE_SCORE_MAX;
49 }
50 return 0;
51}
52
53static int xa_read_header(AVFormatContext *s,
54 AVFormatParameters *ap)
55{
56 MaxisXADemuxContext *xa = s->priv_data;
57 ByteIOContext *pb = s->pb;
58 AVStream *st;
59
60 /*Set up the XA Audio Decoder*/
61 st = av_new_stream(s, 0);
62 if (!st)
63 return AVERROR(ENOMEM);
64
65 st->codec->codec_type = CODEC_TYPE_AUDIO;
66 st->codec->codec_id = CODEC_ID_ADPCM_EA_MAXIS_XA;
67 url_fskip(pb, 4); /* Skip the XA ID */
68 xa->out_size = get_le32(pb);
69 url_fskip(pb, 2); /* Skip the tag */
70 st->codec->channels = get_le16(pb);
71 st->codec->sample_rate = get_le32(pb);
72 /* Value in file is average byte rate*/
73 st->codec->bit_rate = get_le32(pb) * 8;
74 st->codec->block_align = get_le16(pb);
75 st->codec->bits_per_sample = get_le16(pb);
76
77 av_set_pts_info(st, 64, 1, st->codec->sample_rate);
78
79 return 0;
80}
81
82static int xa_read_packet(AVFormatContext *s,
83 AVPacket *pkt)
84{
85 MaxisXADemuxContext *xa = s->priv_data;
86 AVStream *st = s->streams[0];
87 ByteIOContext *pb = s->pb;
88 unsigned int packet_size;
89 int ret;
90
91 if(xa->sent_bytes > xa->out_size)
92 return AVERROR(EIO);
93 /* 1 byte header and 14 bytes worth of samples * number channels per block */
94 packet_size = 15*st->codec->channels;
95
96 ret = av_get_packet(pb, pkt, packet_size);
97 if(ret != packet_size)
98 return AVERROR(EIO);
99
100 pkt->stream_index = st->index;
101 xa->sent_bytes += packet_size;
102 pkt->pts = xa->audio_frame_counter;
103 /* 14 bytes Samples per channel with 2 samples per byte */
104 xa->audio_frame_counter += 28 * st->codec->channels;
105
106 return ret;
107}
108
109AVInputFormat xa_demuxer = {
110 "xa",
111 NULL_IF_CONFIG_SMALL("Maxis XA File Format"),
112 sizeof(MaxisXADemuxContext),
113 xa_probe,
114 xa_read_header,
115 xa_read_packet,
116};
diff --git a/src/plugins/ffmpeg/libavformat/yuv4mpeg.c b/src/plugins/ffmpeg/libavformat/yuv4mpeg.c
deleted file mode 100644
index 6af7d78..0000000
--- a/src/plugins/ffmpeg/libavformat/yuv4mpeg.c
+++ /dev/null
@@ -1,395 +0,0 @@
1/*
2 * YUV4MPEG format
3 * Copyright (c) 2001, 2002, 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#include "avformat.h"
22
23#define Y4M_MAGIC "YUV4MPEG2"
24#define Y4M_FRAME_MAGIC "FRAME"
25#define Y4M_LINE_MAX 256
26
27struct frame_attributes {
28 int interlaced_frame;
29 int top_field_first;
30};
31
32#ifdef CONFIG_YUV4MPEGPIPE_MUXER
33static int yuv4_generate_header(AVFormatContext *s, char* buf)
34{
35 AVStream *st;
36 int width, height;
37 int raten, rated, aspectn, aspectd, n;
38 char inter;
39 const char *colorspace = "";
40
41 st = s->streams[0];
42 width = st->codec->width;
43 height = st->codec->height;
44
45 av_reduce(&raten, &rated, st->codec->time_base.den, st->codec->time_base.num, (1UL<<31)-1);
46
47 aspectn = st->codec->sample_aspect_ratio.num;
48 aspectd = st->codec->sample_aspect_ratio.den;
49
50 if ( aspectn == 0 && aspectd == 1 ) aspectd = 0; // 0:0 means unknown
51
52 inter = 'p'; /* progressive is the default */
53 if (st->codec->coded_frame && st->codec->coded_frame->interlaced_frame) {
54 inter = st->codec->coded_frame->top_field_first ? 't' : 'b';
55 }
56
57 switch(st->codec->pix_fmt) {
58 case PIX_FMT_GRAY8:
59 colorspace = " Cmono";
60 break;
61 case PIX_FMT_YUV411P:
62 colorspace = " C411 XYSCSS=411";
63 break;
64 case PIX_FMT_YUV420P:
65 colorspace = (st->codec->codec_id == CODEC_ID_DVVIDEO)?" C420paldv XYSCSS=420PALDV":" C420mpeg2 XYSCSS=420MPEG2";
66 break;
67 case PIX_FMT_YUV422P:
68 colorspace = " C422 XYSCSS=422";
69 break;
70 case PIX_FMT_YUV444P:
71 colorspace = " C444 XYSCSS=444";
72 break;
73 }
74
75 /* construct stream header, if this is the first frame */
76 n = snprintf(buf, Y4M_LINE_MAX, "%s W%d H%d F%d:%d I%c A%d:%d%s\n",
77 Y4M_MAGIC,
78 width,
79 height,
80 raten, rated,
81 inter,
82 aspectn, aspectd,
83 colorspace);
84
85 return n;
86}
87
88static int yuv4_write_packet(AVFormatContext *s, AVPacket *pkt)
89{
90 AVStream *st = s->streams[pkt->stream_index];
91 ByteIOContext *pb = s->pb;
92 AVPicture *picture;
93 int* first_pkt = s->priv_data;
94 int width, height, h_chroma_shift, v_chroma_shift;
95 int i, m;
96 char buf2[Y4M_LINE_MAX+1];
97 char buf1[20];
98 uint8_t *ptr, *ptr1, *ptr2;
99
100 picture = (AVPicture *)pkt->data;
101
102 /* for the first packet we have to output the header as well */
103 if (*first_pkt) {
104 *first_pkt = 0;
105 if (yuv4_generate_header(s, buf2) < 0) {
106 av_log(s, AV_LOG_ERROR, "Error. YUV4MPEG stream header write failed.\n");
107 return AVERROR(EIO);
108 } else {
109 put_buffer(pb, buf2, strlen(buf2));
110 }
111 }
112
113 /* construct frame header */
114
115 m = snprintf(buf1, sizeof(buf1), "%s\n", Y4M_FRAME_MAGIC);
116 put_buffer(pb, buf1, strlen(buf1));
117
118 width = st->codec->width;
119 height = st->codec->height;
120
121 ptr = picture->data[0];
122 for(i=0;i<height;i++) {
123 put_buffer(pb, ptr, width);
124 ptr += picture->linesize[0];
125 }
126
127 if (st->codec->pix_fmt != PIX_FMT_GRAY8){
128 // Adjust for smaller Cb and Cr planes
129 avcodec_get_chroma_sub_sample(st->codec->pix_fmt, &h_chroma_shift, &v_chroma_shift);
130 width >>= h_chroma_shift;
131 height >>= v_chroma_shift;
132
133 ptr1 = picture->data[1];
134 ptr2 = picture->data[2];
135 for(i=0;i<height;i++) { /* Cb */
136 put_buffer(pb, ptr1, width);
137 ptr1 += picture->linesize[1];
138 }
139 for(i=0;i<height;i++) { /* Cr */
140 put_buffer(pb, ptr2, width);
141 ptr2 += picture->linesize[2];
142 }
143 }
144 put_flush_packet(pb);
145 return 0;
146}
147
148static int yuv4_write_header(AVFormatContext *s)
149{
150 int* first_pkt = s->priv_data;
151
152 if (s->nb_streams != 1)
153 return AVERROR(EIO);
154
155 if (s->streams[0]->codec->pix_fmt == PIX_FMT_YUV411P) {
156 av_log(s, AV_LOG_ERROR, "Warning: generating rarely used 4:1:1 YUV stream, some mjpegtools might not work.\n");
157 }
158 else if ((s->streams[0]->codec->pix_fmt != PIX_FMT_YUV420P) &&
159 (s->streams[0]->codec->pix_fmt != PIX_FMT_YUV422P) &&
160 (s->streams[0]->codec->pix_fmt != PIX_FMT_GRAY8) &&
161 (s->streams[0]->codec->pix_fmt != PIX_FMT_YUV444P)) {
162 av_log(s, AV_LOG_ERROR, "ERROR: yuv4mpeg only handles yuv444p, yuv422p, yuv420p, yuv411p and gray pixel formats. Use -pix_fmt to select one.\n");
163 return AVERROR(EIO);
164 }
165
166 *first_pkt = 1;
167 return 0;
168}
169
170AVOutputFormat yuv4mpegpipe_muxer = {
171 "yuv4mpegpipe",
172 NULL_IF_CONFIG_SMALL("YUV4MPEG pipe format"),
173 "",
174 "y4m",
175 sizeof(int),
176 CODEC_ID_NONE,
177 CODEC_ID_RAWVIDEO,
178 yuv4_write_header,
179 yuv4_write_packet,
180 .flags = AVFMT_RAWPICTURE,
181};
182#endif
183
184/* Header size increased to allow room for optional flags */
185#define MAX_YUV4_HEADER 80
186#define MAX_FRAME_HEADER 80
187
188static int yuv4_read_header(AVFormatContext *s, AVFormatParameters *ap)
189{
190 char header[MAX_YUV4_HEADER+10]; // Include headroom for the longest option
191 char *tokstart,*tokend,*header_end;
192 int i;
193 ByteIOContext *pb = s->pb;
194 int width=-1, height=-1, raten=0, rated=0, aspectn=0, aspectd=0;
195 enum PixelFormat pix_fmt=PIX_FMT_NONE,alt_pix_fmt=PIX_FMT_NONE;
196 AVStream *st;
197 struct frame_attributes *s1 = s->priv_data;
198
199 for (i=0; i<MAX_YUV4_HEADER; i++) {
200 header[i] = get_byte(pb);
201 if (header[i] == '\n') {
202 header[i+1] = 0x20; // Add a space after last option. Makes parsing "444" vs "444alpha" easier.
203 header[i+2] = 0;
204 break;
205 }
206 }
207 if (i == MAX_YUV4_HEADER) return -1;
208 if (strncmp(header, Y4M_MAGIC, strlen(Y4M_MAGIC))) return -1;
209
210 s1->interlaced_frame = 0;
211 s1->top_field_first = 0;
212 header_end = &header[i+1]; // Include space
213 for(tokstart = &header[strlen(Y4M_MAGIC) + 1]; tokstart < header_end; tokstart++) {
214 if (*tokstart==0x20) continue;
215 switch (*tokstart++) {
216 case 'W': // Width. Required.
217 width = strtol(tokstart, &tokend, 10);
218 tokstart=tokend;
219 break;
220 case 'H': // Height. Required.
221 height = strtol(tokstart, &tokend, 10);
222 tokstart=tokend;
223 break;
224 case 'C': // Color space
225 if (strncmp("420jpeg",tokstart,7)==0)
226 pix_fmt = PIX_FMT_YUV420P;
227 else if (strncmp("420mpeg2",tokstart,8)==0)
228 pix_fmt = PIX_FMT_YUV420P;
229 else if (strncmp("420paldv", tokstart, 8)==0)
230 pix_fmt = PIX_FMT_YUV420P;
231 else if (strncmp("411", tokstart, 3)==0)
232 pix_fmt = PIX_FMT_YUV411P;
233 else if (strncmp("422", tokstart, 3)==0)
234 pix_fmt = PIX_FMT_YUV422P;
235 else if (strncmp("444alpha", tokstart, 8)==0) {
236 av_log(s, AV_LOG_ERROR, "Cannot handle 4:4:4:4 YUV4MPEG stream.\n");
237 return -1;
238 } else if (strncmp("444", tokstart, 3)==0)
239 pix_fmt = PIX_FMT_YUV444P;
240 else if (strncmp("mono",tokstart, 4)==0) {
241 pix_fmt = PIX_FMT_GRAY8;
242 } else {
243 av_log(s, AV_LOG_ERROR, "YUV4MPEG stream contains an unknown pixel format.\n");
244 return -1;
245 }
246 while(tokstart<header_end&&*tokstart!=0x20) tokstart++;
247 break;
248 case 'I': // Interlace type
249 switch (*tokstart++){
250 case '?':
251 break;
252 case 'p':
253 s1->interlaced_frame=0;
254 break;
255 case 't':
256 s1->interlaced_frame=1;
257 s1->top_field_first=1;
258 break;
259 case 'b':
260 s1->interlaced_frame=1;
261 s1->top_field_first=0;
262 break;
263 case 'm':
264 av_log(s, AV_LOG_ERROR, "YUV4MPEG stream contains mixed interlaced and non-interlaced frames.\n");
265 return -1;
266 default:
267 av_log(s, AV_LOG_ERROR, "YUV4MPEG has invalid header.\n");
268 return -1;
269 }
270 break;
271 case 'F': // Frame rate
272 sscanf(tokstart,"%d:%d",&raten,&rated); // 0:0 if unknown
273 while(tokstart<header_end&&*tokstart!=0x20) tokstart++;
274 break;
275 case 'A': // Pixel aspect
276 sscanf(tokstart,"%d:%d",&aspectn,&aspectd); // 0:0 if unknown
277 while(tokstart<header_end&&*tokstart!=0x20) tokstart++;
278 break;
279 case 'X': // Vendor extensions
280 if (strncmp("YSCSS=",tokstart,6)==0) {
281 // Older nonstandard pixel format representation
282 tokstart+=6;
283 if (strncmp("420JPEG",tokstart,7)==0)
284 alt_pix_fmt=PIX_FMT_YUV420P;
285 else if (strncmp("420MPEG2",tokstart,8)==0)
286 alt_pix_fmt=PIX_FMT_YUV420P;
287 else if (strncmp("420PALDV",tokstart,8)==0)
288 alt_pix_fmt=PIX_FMT_YUV420P;
289 else if (strncmp("411",tokstart,3)==0)
290 alt_pix_fmt=PIX_FMT_YUV411P;
291 else if (strncmp("422",tokstart,3)==0)
292 alt_pix_fmt=PIX_FMT_YUV422P;
293 else if (strncmp("444",tokstart,3)==0)
294 alt_pix_fmt=PIX_FMT_YUV444P;
295 }
296 while(tokstart<header_end&&*tokstart!=0x20) tokstart++;
297 break;
298 }
299 }
300
301 if ((width == -1) || (height == -1)) {
302 av_log(s, AV_LOG_ERROR, "YUV4MPEG has invalid header.\n");
303 return -1;
304 }
305
306 if (pix_fmt == PIX_FMT_NONE) {
307 if (alt_pix_fmt == PIX_FMT_NONE)
308 pix_fmt = PIX_FMT_YUV420P;
309 else
310 pix_fmt = alt_pix_fmt;
311 }
312
313 if (raten == 0 && rated == 0) {
314 // Frame rate unknown
315 raten = 25;
316 rated = 1;
317 }
318
319 if (aspectn == 0 && aspectd == 0) {
320 // Pixel aspect unknown
321 aspectd = 1;
322 }
323
324 st = av_new_stream(s, 0);
325 if(!st)
326 return AVERROR(ENOMEM);
327 st->codec->width = width;
328 st->codec->height = height;
329 av_reduce(&raten, &rated, raten, rated, (1UL<<31)-1);
330 av_set_pts_info(st, 64, rated, raten);
331 st->codec->pix_fmt = pix_fmt;
332 st->codec->codec_type = CODEC_TYPE_VIDEO;
333 st->codec->codec_id = CODEC_ID_RAWVIDEO;
334 st->codec->sample_aspect_ratio= (AVRational){aspectn, aspectd};
335
336 return 0;
337}
338
339static int yuv4_read_packet(AVFormatContext *s, AVPacket *pkt)
340{
341 int i;
342 char header[MAX_FRAME_HEADER+1];
343 int packet_size, width, height;
344 AVStream *st = s->streams[0];
345 struct frame_attributes *s1 = s->priv_data;
346
347 for (i=0; i<MAX_FRAME_HEADER; i++) {
348 header[i] = get_byte(s->pb);
349 if (header[i] == '\n') {
350 header[i+1] = 0;
351 break;
352 }
353 }
354 if (i == MAX_FRAME_HEADER) return -1;
355 if (strncmp(header, Y4M_FRAME_MAGIC, strlen(Y4M_FRAME_MAGIC))) return -1;
356
357 width = st->codec->width;
358 height = st->codec->height;
359
360 packet_size = avpicture_get_size(st->codec->pix_fmt, width, height);
361 if (packet_size < 0)
362 return -1;
363
364 if (av_get_packet(s->pb, pkt, packet_size) != packet_size)
365 return AVERROR(EIO);
366
367 if (s->streams[0]->codec->coded_frame) {
368 s->streams[0]->codec->coded_frame->interlaced_frame = s1->interlaced_frame;
369 s->streams[0]->codec->coded_frame->top_field_first = s1->top_field_first;
370 }
371
372 pkt->stream_index = 0;
373 return 0;
374}
375
376static int yuv4_probe(AVProbeData *pd)
377{
378 /* check file header */
379 if (strncmp(pd->buf, Y4M_MAGIC, sizeof(Y4M_MAGIC)-1)==0)
380 return AVPROBE_SCORE_MAX;
381 else
382 return 0;
383}
384
385#ifdef CONFIG_YUV4MPEGPIPE_DEMUXER
386AVInputFormat yuv4mpegpipe_demuxer = {
387 "yuv4mpegpipe",
388 NULL_IF_CONFIG_SMALL("YUV4MPEG pipe format"),
389 sizeof(struct frame_attributes),
390 yuv4_probe,
391 yuv4_read_header,
392 yuv4_read_packet,
393 .extensions = "y4m"
394};
395#endif