]> git.sesse.net Git - ffmpeg/blob - libavformat/mvdec.c
2aef93a735dd1d0c4fb4d32268e8788a7637be66
[ffmpeg] / libavformat / mvdec.c
1 /*
2  * Silicon Graphics Movie demuxer
3  * Copyright (c) 2012 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
24  * Silicon Graphics Movie demuxer
25  */
26
27 #include "libavutil/channel_layout.h"
28 #include "libavutil/eval.h"
29 #include "libavutil/intreadwrite.h"
30 #include "libavutil/rational.h"
31
32 #include "avformat.h"
33 #include "internal.h"
34
35 typedef struct MvContext {
36     int nb_video_tracks;
37     int nb_audio_tracks;
38
39     int eof_count;        ///< number of streams that have finished
40     int stream_index;     ///< current stream index
41     int frame[2];         ///< frame nb for current stream
42
43     int acompression;     ///< compression level for audio stream
44     int aformat;          ///< audio format
45 } MvContext;
46
47 #define AUDIO_FORMAT_SIGNED 401
48
49 static int mv_probe(const AVProbeData *p)
50 {
51     if (AV_RB32(p->buf) == MKBETAG('M', 'O', 'V', 'I') &&
52         AV_RB16(p->buf + 4) < 3)
53         return AVPROBE_SCORE_MAX;
54     return 0;
55 }
56
57 static char *var_read_string(AVIOContext *pb, int size)
58 {
59     int n;
60     char *str;
61
62     if (size < 0 || size == INT_MAX)
63         return NULL;
64
65     str = av_malloc(size + 1);
66     if (!str)
67         return NULL;
68     n = avio_get_str(pb, size, str, size + 1);
69     if (n < size)
70         avio_skip(pb, size - n);
71     return str;
72 }
73
74 static int var_read_int(AVIOContext *pb, int size)
75 {
76     int v;
77     char *s = var_read_string(pb, size);
78     if (!s)
79         return 0;
80     v = strtol(s, NULL, 10);
81     av_free(s);
82     return v;
83 }
84
85 static AVRational var_read_float(AVIOContext *pb, int size)
86 {
87     AVRational v;
88     char *s = var_read_string(pb, size);
89     if (!s)
90         return (AVRational) { 0, 0 };
91     v = av_d2q(av_strtod(s, NULL), INT_MAX);
92     av_free(s);
93     return v;
94 }
95
96 static void var_read_metadata(AVFormatContext *avctx, const char *tag, int size)
97 {
98     char *value = var_read_string(avctx->pb, size);
99     if (value)
100         av_dict_set(&avctx->metadata, tag, value, AV_DICT_DONT_STRDUP_VAL);
101 }
102
103 static int set_channels(AVFormatContext *avctx, AVStream *st, int channels)
104 {
105     if (channels <= 0) {
106         av_log(avctx, AV_LOG_ERROR, "Channel count %d invalid.\n", channels);
107         return AVERROR_INVALIDDATA;
108     }
109     st->codecpar->channels       = channels;
110     st->codecpar->channel_layout = (st->codecpar->channels == 1) ? AV_CH_LAYOUT_MONO
111                                                                  : AV_CH_LAYOUT_STEREO;
112     return 0;
113 }
114
115 /**
116  * Parse global variable
117  * @return < 0 if unknown
118  */
119 static int parse_global_var(AVFormatContext *avctx, AVStream *st,
120                             const char *name, int size)
121 {
122     MvContext *mv = avctx->priv_data;
123     AVIOContext *pb = avctx->pb;
124     if (!strcmp(name, "__NUM_I_TRACKS")) {
125         mv->nb_video_tracks = var_read_int(pb, size);
126     } else if (!strcmp(name, "__NUM_A_TRACKS")) {
127         mv->nb_audio_tracks = var_read_int(pb, size);
128     } else if (!strcmp(name, "COMMENT") || !strcmp(name, "TITLE")) {
129         var_read_metadata(avctx, name, size);
130     } else if (!strcmp(name, "LOOP_MODE") || !strcmp(name, "NUM_LOOPS") ||
131                !strcmp(name, "OPTIMIZED")) {
132         avio_skip(pb, size); // ignore
133     } else
134         return AVERROR_INVALIDDATA;
135
136     return 0;
137 }
138
139 /**
140  * Parse audio variable
141  * @return < 0 if unknown
142  */
143 static int parse_audio_var(AVFormatContext *avctx, AVStream *st,
144                            const char *name, int size)
145 {
146     MvContext *mv = avctx->priv_data;
147     AVIOContext *pb = avctx->pb;
148     if (!strcmp(name, "__DIR_COUNT")) {
149         st->nb_frames = var_read_int(pb, size);
150     } else if (!strcmp(name, "AUDIO_FORMAT")) {
151         mv->aformat = var_read_int(pb, size);
152     } else if (!strcmp(name, "COMPRESSION")) {
153         mv->acompression = var_read_int(pb, size);
154     } else if (!strcmp(name, "DEFAULT_VOL")) {
155         var_read_metadata(avctx, name, size);
156     } else if (!strcmp(name, "NUM_CHANNELS")) {
157         return set_channels(avctx, st, var_read_int(pb, size));
158     } else if (!strcmp(name, "SAMPLE_RATE")) {
159         st->codecpar->sample_rate = var_read_int(pb, size);
160         avpriv_set_pts_info(st, 33, 1, st->codecpar->sample_rate);
161     } else if (!strcmp(name, "SAMPLE_WIDTH")) {
162         uint64_t bpc = var_read_int(pb, size) * (uint64_t)8;
163         if (bpc > 16)
164             return AVERROR_INVALIDDATA;
165         st->codecpar->bits_per_coded_sample = bpc;
166     } else
167         return AVERROR_INVALIDDATA;
168
169     return 0;
170 }
171
172 /**
173  * Parse video variable
174  * @return < 0 if unknown
175  */
176 static int parse_video_var(AVFormatContext *avctx, AVStream *st,
177                            const char *name, int size)
178 {
179     AVIOContext *pb = avctx->pb;
180     if (!strcmp(name, "__DIR_COUNT")) {
181         st->nb_frames = st->duration = var_read_int(pb, size);
182     } else if (!strcmp(name, "COMPRESSION")) {
183         char *str = var_read_string(pb, size);
184         if (!str)
185             return AVERROR_INVALIDDATA;
186         if (!strcmp(str, "1")) {
187             st->codecpar->codec_id = AV_CODEC_ID_MVC1;
188         } else if (!strcmp(str, "2")) {
189             st->codecpar->format = AV_PIX_FMT_ABGR;
190             st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
191         } else if (!strcmp(str, "3")) {
192             st->codecpar->codec_id = AV_CODEC_ID_SGIRLE;
193         } else if (!strcmp(str, "10")) {
194             st->codecpar->codec_id = AV_CODEC_ID_MJPEG;
195         } else if (!strcmp(str, "MVC2")) {
196             st->codecpar->codec_id = AV_CODEC_ID_MVC2;
197         } else {
198             avpriv_request_sample(avctx, "Video compression %s", str);
199         }
200         av_free(str);
201     } else if (!strcmp(name, "FPS")) {
202         AVRational fps = var_read_float(pb, size);
203         avpriv_set_pts_info(st, 64, fps.den, fps.num);
204         st->avg_frame_rate = fps;
205     } else if (!strcmp(name, "HEIGHT")) {
206         st->codecpar->height = var_read_int(pb, size);
207     } else if (!strcmp(name, "PIXEL_ASPECT")) {
208         st->sample_aspect_ratio = var_read_float(pb, size);
209         av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
210                   st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
211                   INT_MAX);
212     } else if (!strcmp(name, "WIDTH")) {
213         st->codecpar->width = var_read_int(pb, size);
214     } else if (!strcmp(name, "ORIENTATION")) {
215         if (var_read_int(pb, size) == 1101) {
216             if (!st->codecpar->extradata) {
217                 st->codecpar->extradata = av_strdup("BottomUp");
218                 if (!st->codecpar->extradata)
219                     return AVERROR(ENOMEM);
220                 st->codecpar->extradata_size = 9;
221             }
222         }
223     } else if (!strcmp(name, "Q_SPATIAL") || !strcmp(name, "Q_TEMPORAL")) {
224         var_read_metadata(avctx, name, size);
225     } else if (!strcmp(name, "INTERLACING") || !strcmp(name, "PACKING")) {
226         avio_skip(pb, size); // ignore
227     } else
228         return AVERROR_INVALIDDATA;
229
230     return 0;
231 }
232
233 static int read_table(AVFormatContext *avctx, AVStream *st,
234                        int (*parse)(AVFormatContext *avctx, AVStream *st,
235                                     const char *name, int size))
236 {
237     unsigned count;
238     int i;
239
240     AVIOContext *pb = avctx->pb;
241     avio_skip(pb, 4);
242     count = avio_rb32(pb);
243     avio_skip(pb, 4);
244     for (i = 0; i < count; i++) {
245         char name[17];
246         int size;
247
248         if (avio_feof(pb))
249             return AVERROR_EOF;
250
251         avio_read(pb, name, 16);
252         name[sizeof(name) - 1] = 0;
253         size = avio_rb32(pb);
254         if (size < 0) {
255             av_log(avctx, AV_LOG_ERROR, "entry size %d is invalid\n", size);
256             return AVERROR_INVALIDDATA;
257         }
258         if (parse(avctx, st, name, size) < 0) {
259             avpriv_request_sample(avctx, "Variable %s", name);
260             avio_skip(pb, size);
261         }
262     }
263     return 0;
264 }
265
266 static void read_index(AVIOContext *pb, AVStream *st)
267 {
268     uint64_t timestamp = 0;
269     int i;
270     for (i = 0; i < st->nb_frames; i++) {
271         uint32_t pos  = avio_rb32(pb);
272         uint32_t size = avio_rb32(pb);
273         avio_skip(pb, 8);
274         if (avio_feof(pb))
275             return ;
276         av_add_index_entry(st, pos, timestamp, size, 0, AVINDEX_KEYFRAME);
277         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
278             timestamp += size / (st->codecpar->channels * 2LL);
279         } else {
280             timestamp++;
281         }
282     }
283 }
284
285 static int mv_read_header(AVFormatContext *avctx)
286 {
287     MvContext *mv = avctx->priv_data;
288     AVIOContext *pb = avctx->pb;
289     AVStream *ast = NULL, *vst = NULL; //initialization to suppress warning
290     int version, i;
291     int ret;
292
293     avio_skip(pb, 4);
294
295     version = avio_rb16(pb);
296     if (version == 2) {
297         uint64_t timestamp;
298         int v;
299         avio_skip(pb, 22);
300
301         /* allocate audio track first to prevent unnecessary seeking
302          * (audio packet always precede video packet for a given frame) */
303         ast = avformat_new_stream(avctx, NULL);
304         if (!ast)
305             return AVERROR(ENOMEM);
306
307         vst = avformat_new_stream(avctx, NULL);
308         if (!vst)
309             return AVERROR(ENOMEM);
310         avpriv_set_pts_info(vst, 64, 1, 15);
311         vst->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
312         vst->avg_frame_rate    = av_inv_q(vst->time_base);
313         vst->nb_frames         = avio_rb32(pb);
314         v = avio_rb32(pb);
315         switch (v) {
316         case 1:
317             vst->codecpar->codec_id = AV_CODEC_ID_MVC1;
318             break;
319         case 2:
320             vst->codecpar->format = AV_PIX_FMT_ARGB;
321             vst->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
322             break;
323         default:
324             avpriv_request_sample(avctx, "Video compression %i", v);
325             break;
326         }
327         vst->codecpar->codec_tag = 0;
328         vst->codecpar->width     = avio_rb32(pb);
329         vst->codecpar->height    = avio_rb32(pb);
330         avio_skip(pb, 12);
331
332         ast->codecpar->codec_type  = AVMEDIA_TYPE_AUDIO;
333         ast->nb_frames          = vst->nb_frames;
334         ast->codecpar->sample_rate = avio_rb32(pb);
335         if (ast->codecpar->sample_rate <= 0) {
336             av_log(avctx, AV_LOG_ERROR, "Invalid sample rate %d\n", ast->codecpar->sample_rate);
337             return AVERROR_INVALIDDATA;
338         }
339         avpriv_set_pts_info(ast, 33, 1, ast->codecpar->sample_rate);
340         if (set_channels(avctx, ast, avio_rb32(pb)) < 0)
341             return AVERROR_INVALIDDATA;
342
343         v = avio_rb32(pb);
344         if (v == AUDIO_FORMAT_SIGNED) {
345             ast->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
346         } else {
347             avpriv_request_sample(avctx, "Audio compression (format %i)", v);
348         }
349
350         avio_skip(pb, 12);
351         var_read_metadata(avctx, "title", 0x80);
352         var_read_metadata(avctx, "comment", 0x100);
353         avio_skip(pb, 0x80);
354
355         timestamp = 0;
356         for (i = 0; i < vst->nb_frames; i++) {
357             uint32_t pos   = avio_rb32(pb);
358             uint32_t asize = avio_rb32(pb);
359             uint32_t vsize = avio_rb32(pb);
360             if (avio_feof(pb))
361                 return AVERROR_INVALIDDATA;
362             avio_skip(pb, 8);
363             av_add_index_entry(ast, pos, timestamp, asize, 0, AVINDEX_KEYFRAME);
364             av_add_index_entry(vst, pos + asize, i, vsize, 0, AVINDEX_KEYFRAME);
365             timestamp += asize / (ast->codecpar->channels * 2LL);
366         }
367     } else if (!version && avio_rb16(pb) == 3) {
368         avio_skip(pb, 4);
369
370         if ((ret = read_table(avctx, NULL, parse_global_var)) < 0)
371             return ret;
372
373         if (mv->nb_audio_tracks < 0  || mv->nb_video_tracks < 0 ||
374            (mv->nb_audio_tracks == 0 && mv->nb_video_tracks == 0)) {
375             av_log(avctx, AV_LOG_ERROR, "Stream count is invalid.\n");
376             return AVERROR_INVALIDDATA;
377         }
378
379         if (mv->nb_audio_tracks > 1) {
380             avpriv_request_sample(avctx, "Multiple audio streams support");
381             return AVERROR_PATCHWELCOME;
382         } else if (mv->nb_audio_tracks) {
383             ast = avformat_new_stream(avctx, NULL);
384             if (!ast)
385                 return AVERROR(ENOMEM);
386             ast->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
387             if ((read_table(avctx, ast, parse_audio_var)) < 0)
388                 return ret;
389             if (mv->acompression == 100 &&
390                 mv->aformat == AUDIO_FORMAT_SIGNED &&
391                 ast->codecpar->bits_per_coded_sample == 16) {
392                 ast->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
393             } else {
394                 avpriv_request_sample(avctx,
395                                       "Audio compression %i (format %i, sr %i)",
396                                       mv->acompression, mv->aformat,
397                                       ast->codecpar->bits_per_coded_sample);
398                 ast->codecpar->codec_id = AV_CODEC_ID_NONE;
399             }
400             if (ast->codecpar->channels <= 0) {
401                 av_log(avctx, AV_LOG_ERROR, "No valid channel count found.\n");
402                 return AVERROR_INVALIDDATA;
403             }
404         }
405
406         if (mv->nb_video_tracks > 1) {
407             avpriv_request_sample(avctx, "Multiple video streams support");
408             return AVERROR_PATCHWELCOME;
409         } else if (mv->nb_video_tracks) {
410             vst = avformat_new_stream(avctx, NULL);
411             if (!vst)
412                 return AVERROR(ENOMEM);
413             vst->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
414             if ((ret = read_table(avctx, vst, parse_video_var))<0)
415                 return ret;
416         }
417
418         if (mv->nb_audio_tracks)
419             read_index(pb, ast);
420
421         if (mv->nb_video_tracks)
422             read_index(pb, vst);
423     } else {
424         avpriv_request_sample(avctx, "Version %i", version);
425         return AVERROR_PATCHWELCOME;
426     }
427
428     return 0;
429 }
430
431 static int mv_read_packet(AVFormatContext *avctx, AVPacket *pkt)
432 {
433     MvContext *mv = avctx->priv_data;
434     AVIOContext *pb = avctx->pb;
435     AVStream *st = avctx->streams[mv->stream_index];
436     const AVIndexEntry *index;
437     int frame = mv->frame[mv->stream_index];
438     int64_t ret;
439     uint64_t pos;
440
441     if (frame < st->internal->nb_index_entries) {
442         index = &st->internal->index_entries[frame];
443         pos   = avio_tell(pb);
444         if (index->pos > pos)
445             avio_skip(pb, index->pos - pos);
446         else if (index->pos < pos) {
447             if (!(pb->seekable & AVIO_SEEKABLE_NORMAL))
448                 return AVERROR(EIO);
449             ret = avio_seek(pb, index->pos, SEEK_SET);
450             if (ret < 0)
451                 return ret;
452         }
453         ret = av_get_packet(pb, pkt, index->size);
454         if (ret < 0)
455             return ret;
456
457         pkt->stream_index = mv->stream_index;
458         pkt->pts          = index->timestamp;
459         pkt->flags       |= AV_PKT_FLAG_KEY;
460
461         mv->frame[mv->stream_index]++;
462         mv->eof_count = 0;
463     } else {
464         mv->eof_count++;
465         if (mv->eof_count >= avctx->nb_streams)
466             return AVERROR_EOF;
467
468         // avoid returning 0 without a packet
469         return AVERROR(EAGAIN);
470     }
471
472     mv->stream_index++;
473     if (mv->stream_index >= avctx->nb_streams)
474         mv->stream_index = 0;
475
476     return 0;
477 }
478
479 static int mv_read_seek(AVFormatContext *avctx, int stream_index,
480                         int64_t timestamp, int flags)
481 {
482     MvContext *mv = avctx->priv_data;
483     AVStream *st = avctx->streams[stream_index];
484     int frame, i;
485
486     if ((flags & AVSEEK_FLAG_FRAME) || (flags & AVSEEK_FLAG_BYTE))
487         return AVERROR(ENOSYS);
488
489     if (!(avctx->pb->seekable & AVIO_SEEKABLE_NORMAL))
490         return AVERROR(EIO);
491
492     frame = av_index_search_timestamp(st, timestamp, flags);
493     if (frame < 0)
494         return AVERROR_INVALIDDATA;
495
496     for (i = 0; i < avctx->nb_streams; i++)
497         mv->frame[i] = frame;
498     return 0;
499 }
500
501 AVInputFormat ff_mv_demuxer = {
502     .name           = "mv",
503     .long_name      = NULL_IF_CONFIG_SMALL("Silicon Graphics Movie"),
504     .priv_data_size = sizeof(MvContext),
505     .read_probe     = mv_probe,
506     .read_header    = mv_read_header,
507     .read_packet    = mv_read_packet,
508     .read_seek      = mv_read_seek,
509 };