]> git.sesse.net Git - ffmpeg/blob - libavformat/mlvdec.c
avformat/mlvdec: Don't leak open AVIOContexts on error
[ffmpeg] / libavformat / mlvdec.c
1 /*
2  * Magic Lantern Video (MLV) demuxer
3  * Copyright (c) 2014 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  * Magic Lantern Video (MLV) demuxer
25  */
26
27 #include "libavutil/eval.h"
28 #include "libavutil/imgutils.h"
29 #include "libavutil/intreadwrite.h"
30 #include "libavutil/rational.h"
31 #include "avformat.h"
32 #include "avio_internal.h"
33 #include "internal.h"
34 #include "riff.h"
35
36 #define MLV_VERSION "v2.0"
37
38 #define MLV_VIDEO_CLASS_RAW  1
39 #define MLV_VIDEO_CLASS_YUV  2
40 #define MLV_VIDEO_CLASS_JPEG 3
41 #define MLV_VIDEO_CLASS_H264 4
42
43 #define MLV_AUDIO_CLASS_WAV  1
44
45 #define MLV_CLASS_FLAG_DELTA 0x40
46 #define MLV_CLASS_FLAG_LZMA  0x80
47
48 typedef struct {
49     AVIOContext *pb[101];
50     int class[2];
51     int stream_index;
52     uint64_t pts;
53 } MlvContext;
54
55 static int read_close(AVFormatContext *s);
56
57 static int probe(const AVProbeData *p)
58 {
59     if (AV_RL32(p->buf) == MKTAG('M','L','V','I') &&
60         AV_RL32(p->buf + 4) >= 52 &&
61         !memcmp(p->buf + 8, MLV_VERSION, 5))
62         return AVPROBE_SCORE_MAX;
63     return 0;
64 }
65
66 static int check_file_header(AVIOContext *pb, uint64_t guid)
67 {
68     unsigned int size;
69     uint8_t version[8];
70
71     avio_skip(pb, 4);
72     size = avio_rl32(pb);
73     if (size < 52)
74         return AVERROR_INVALIDDATA;
75     avio_read(pb, version, 8);
76     if (memcmp(version, MLV_VERSION, 5) || avio_rl64(pb) != guid)
77         return AVERROR_INVALIDDATA;
78     avio_skip(pb, size - 24);
79     return 0;
80 }
81
82 static void read_string(AVFormatContext *avctx, AVIOContext *pb, const char *tag, unsigned size)
83 {
84     char * value = av_malloc(size + 1);
85     if (!value) {
86         avio_skip(pb, size);
87         return;
88     }
89
90     avio_read(pb, value, size);
91     if (!value[0]) {
92         av_free(value);
93         return;
94     }
95
96     value[size] = 0;
97     av_dict_set(&avctx->metadata, tag, value, AV_DICT_DONT_STRDUP_VAL);
98 }
99
100 static void read_uint8(AVFormatContext *avctx, AVIOContext *pb, const char *tag, const char *fmt)
101 {
102     av_dict_set_int(&avctx->metadata, tag, avio_r8(pb), 0);
103 }
104
105 static void read_uint16(AVFormatContext *avctx, AVIOContext *pb, const char *tag, const char *fmt)
106 {
107     av_dict_set_int(&avctx->metadata, tag, avio_rl16(pb), 0);
108 }
109
110 static void read_uint32(AVFormatContext *avctx, AVIOContext *pb, const char *tag, const char *fmt)
111 {
112     av_dict_set_int(&avctx->metadata, tag, avio_rl32(pb), 0);
113 }
114
115 static void read_uint64(AVFormatContext *avctx, AVIOContext *pb, const char *tag, const char *fmt)
116 {
117     av_dict_set_int(&avctx->metadata, tag, avio_rl64(pb), 0);
118 }
119
120 static int scan_file(AVFormatContext *avctx, AVStream *vst, AVStream *ast, int file)
121 {
122     MlvContext *mlv = avctx->priv_data;
123     AVIOContext *pb = mlv->pb[file];
124     int ret;
125     while (!avio_feof(pb)) {
126         int type;
127         unsigned int size;
128         type = avio_rl32(pb);
129         size = avio_rl32(pb);
130         avio_skip(pb, 8); //timestamp
131         if (size < 16)
132             break;
133         size -= 16;
134         if (vst && type == MKTAG('R','A','W','I') && size >= 164) {
135             vst->codecpar->width  = avio_rl16(pb);
136             vst->codecpar->height = avio_rl16(pb);
137             ret = av_image_check_size(vst->codecpar->width, vst->codecpar->height, 0, avctx);
138             if (ret < 0)
139                 return ret;
140             if (avio_rl32(pb) != 1)
141                 avpriv_request_sample(avctx, "raw api version");
142             avio_skip(pb, 20); // pointer, width, height, pitch, frame_size
143             vst->codecpar->bits_per_coded_sample = avio_rl32(pb);
144             if (vst->codecpar->bits_per_coded_sample < 0 ||
145                 vst->codecpar->bits_per_coded_sample > (INT_MAX - 7) / (vst->codecpar->width * vst->codecpar->height)) {
146                 av_log(avctx, AV_LOG_ERROR,
147                        "invalid bits_per_coded_sample %d (size: %dx%d)\n",
148                        vst->codecpar->bits_per_coded_sample,
149                        vst->codecpar->width, vst->codecpar->height);
150                 return AVERROR_INVALIDDATA;
151             }
152             avio_skip(pb, 8 + 16 + 24); // black_level, white_level, xywh, active_area, exposure_bias
153             if (avio_rl32(pb) != 0x2010100) /* RGGB */
154                 avpriv_request_sample(avctx, "cfa_pattern");
155             avio_skip(pb, 80); // calibration_illuminant1, color_matrix1, dynamic_range
156             vst->codecpar->format    = AV_PIX_FMT_BAYER_RGGB16LE;
157             vst->codecpar->codec_tag = MKTAG('B', 'I', 'T', 16);
158             size -= 164;
159         } else if (ast && type == MKTAG('W', 'A', 'V', 'I') && size >= 16) {
160             ret = ff_get_wav_header(avctx, pb, ast->codecpar, 16, 0);
161             if (ret < 0)
162                 return ret;
163             size -= 16;
164         } else if (type == MKTAG('I','N','F','O')) {
165             if (size > 0)
166                 read_string(avctx, pb, "info", size);
167             continue;
168         } else if (type == MKTAG('I','D','N','T') && size >= 36) {
169             read_string(avctx, pb, "cameraName", 32);
170             read_uint32(avctx, pb, "cameraModel", "0x%"PRIx32);
171             size -= 36;
172             if (size >= 32) {
173                 read_string(avctx, pb, "cameraSerial", 32);
174                 size -= 32;
175             }
176         } else if (type == MKTAG('L','E','N','S') && size >= 48) {
177             read_uint16(avctx, pb, "focalLength", "%i");
178             read_uint16(avctx, pb, "focalDist", "%i");
179             read_uint16(avctx, pb, "aperture", "%i");
180             read_uint8(avctx, pb, "stabilizerMode", "%i");
181             read_uint8(avctx, pb, "autofocusMode", "%i");
182             read_uint32(avctx, pb, "flags", "0x%"PRIx32);
183             read_uint32(avctx, pb, "lensID", "%"PRIi32);
184             read_string(avctx, pb, "lensName", 32);
185             size -= 48;
186             if (size >= 32) {
187                 read_string(avctx, pb, "lensSerial", 32);
188                 size -= 32;
189             }
190         } else if (vst && type == MKTAG('V', 'I', 'D', 'F') && size >= 4) {
191             uint64_t pts = avio_rl32(pb);
192             ff_add_index_entry(&vst->index_entries, &vst->nb_index_entries, &vst->index_entries_allocated_size,
193                                avio_tell(pb) - 20, pts, file, 0, AVINDEX_KEYFRAME);
194             size -= 4;
195         } else if (ast && type == MKTAG('A', 'U', 'D', 'F') && size >= 4) {
196             uint64_t pts = avio_rl32(pb);
197             ff_add_index_entry(&ast->index_entries, &ast->nb_index_entries, &ast->index_entries_allocated_size,
198                                avio_tell(pb) - 20, pts, file, 0, AVINDEX_KEYFRAME);
199             size -= 4;
200         } else if (vst && type == MKTAG('W','B','A','L') && size >= 28) {
201             read_uint32(avctx, pb, "wb_mode", "%"PRIi32);
202             read_uint32(avctx, pb, "kelvin", "%"PRIi32);
203             read_uint32(avctx, pb, "wbgain_r", "%"PRIi32);
204             read_uint32(avctx, pb, "wbgain_g", "%"PRIi32);
205             read_uint32(avctx, pb, "wbgain_b", "%"PRIi32);
206             read_uint32(avctx, pb, "wbs_gm", "%"PRIi32);
207             read_uint32(avctx, pb, "wbs_ba", "%"PRIi32);
208             size -= 28;
209         } else if (type == MKTAG('R','T','C','I') && size >= 20) {
210             char str[32];
211             struct tm time = { 0 };
212             time.tm_sec    = avio_rl16(pb);
213             time.tm_min    = avio_rl16(pb);
214             time.tm_hour   = avio_rl16(pb);
215             time.tm_mday   = avio_rl16(pb);
216             time.tm_mon    = avio_rl16(pb);
217             time.tm_year   = avio_rl16(pb);
218             time.tm_wday   = avio_rl16(pb);
219             time.tm_yday   = avio_rl16(pb);
220             time.tm_isdst  = avio_rl16(pb);
221             avio_skip(pb, 2);
222             if (strftime(str, sizeof(str), "%Y-%m-%d %H:%M:%S", &time))
223                 av_dict_set(&avctx->metadata, "time", str, 0);
224             size -= 20;
225         } else if (type == MKTAG('E','X','P','O') && size >= 16) {
226             av_dict_set(&avctx->metadata, "isoMode", avio_rl32(pb) ? "auto" : "manual", 0);
227             read_uint32(avctx, pb, "isoValue", "%"PRIi32);
228             read_uint32(avctx, pb, "isoAnalog", "%"PRIi32);
229             read_uint32(avctx, pb, "digitalGain", "%"PRIi32);
230             size -= 16;
231             if (size >= 8) {
232                 read_uint64(avctx, pb, "shutterValue", "%"PRIi64);
233                 size -= 8;
234             }
235         } else if (type == MKTAG('S','T','Y','L') && size >= 36) {
236             read_uint32(avctx, pb, "picStyleId", "%"PRIi32);
237             read_uint32(avctx, pb, "contrast", "%"PRIi32);
238             read_uint32(avctx, pb, "sharpness", "%"PRIi32);
239             read_uint32(avctx, pb, "saturation", "%"PRIi32);
240             read_uint32(avctx, pb, "colortone", "%"PRIi32);
241             read_string(avctx, pb, "picStyleName", 16);
242             size -= 36;
243         } else if (type == MKTAG('M','A','R','K')) {
244         } else if (type == MKTAG('N','U','L','L')) {
245         } else if (type == MKTAG('M','L','V','I')) { /* occurs when MLV and Mnn files are concatenated */
246         } else {
247             av_log(avctx, AV_LOG_INFO, "unsupported tag %s, size %u\n",
248                    av_fourcc2str(type), size);
249         }
250         avio_skip(pb, size);
251     }
252     return 0;
253 }
254
255 static int read_header(AVFormatContext *avctx)
256 {
257     MlvContext *mlv = avctx->priv_data;
258     AVIOContext *pb = avctx->pb;
259     AVStream *vst = NULL, *ast = NULL;
260     int size, ret;
261     unsigned nb_video_frames, nb_audio_frames;
262     uint64_t guid;
263     char guidstr[32];
264
265     avio_skip(pb, 4);
266     size = avio_rl32(pb);
267     if (size < 52)
268         return AVERROR_INVALIDDATA;
269
270     avio_skip(pb, 8);
271
272     guid = avio_rl64(pb);
273     snprintf(guidstr, sizeof(guidstr), "0x%"PRIx64, guid);
274     av_dict_set(&avctx->metadata, "guid", guidstr, 0);
275
276     avio_skip(pb, 8); //fileNum, fileCount, fileFlags
277
278     mlv->class[0] = avio_rl16(pb);
279     mlv->class[1] = avio_rl16(pb);
280
281     nb_video_frames = avio_rl32(pb);
282     nb_audio_frames = avio_rl32(pb);
283
284     if (nb_video_frames && mlv->class[0]) {
285         vst = avformat_new_stream(avctx, NULL);
286         if (!vst)
287             return AVERROR(ENOMEM);
288         vst->id = 0;
289         vst->nb_frames = nb_video_frames;
290         if ((mlv->class[0] & (MLV_CLASS_FLAG_DELTA|MLV_CLASS_FLAG_LZMA)))
291             avpriv_request_sample(avctx, "compression");
292         vst->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
293         switch (mlv->class[0] & ~(MLV_CLASS_FLAG_DELTA|MLV_CLASS_FLAG_LZMA)) {
294         case MLV_VIDEO_CLASS_RAW:
295             vst->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
296             break;
297         case MLV_VIDEO_CLASS_YUV:
298             vst->codecpar->format   = AV_PIX_FMT_YUV420P;
299             vst->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
300             vst->codecpar->codec_tag = 0;
301             break;
302         case MLV_VIDEO_CLASS_JPEG:
303             vst->codecpar->codec_id = AV_CODEC_ID_MJPEG;
304             vst->codecpar->codec_tag = 0;
305             break;
306         case MLV_VIDEO_CLASS_H264:
307             vst->codecpar->codec_id = AV_CODEC_ID_H264;
308             vst->codecpar->codec_tag = 0;
309             break;
310         default:
311             avpriv_request_sample(avctx, "unknown video class");
312         }
313     }
314
315     if (nb_audio_frames && mlv->class[1]) {
316         ast = avformat_new_stream(avctx, NULL);
317         if (!ast)
318             return AVERROR(ENOMEM);
319         ast->id = 1;
320         ast->nb_frames = nb_audio_frames;
321         if ((mlv->class[1] & MLV_CLASS_FLAG_LZMA))
322             avpriv_request_sample(avctx, "compression");
323         if ((mlv->class[1] & ~MLV_CLASS_FLAG_LZMA) != MLV_AUDIO_CLASS_WAV)
324             avpriv_request_sample(avctx, "unknown audio class");
325
326         ast->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
327         avpriv_set_pts_info(ast, 33, 1, ast->codecpar->sample_rate);
328     }
329
330     if (vst) {
331        AVRational framerate;
332        framerate.num = avio_rl32(pb);
333        framerate.den = avio_rl32(pb);
334        avpriv_set_pts_info(vst, 64, framerate.den, framerate.num);
335     } else
336        avio_skip(pb, 8);
337
338     avio_skip(pb, size - 52);
339
340     /* scan primary file */
341     mlv->pb[100] = avctx->pb;
342     ret = scan_file(avctx, vst, ast, 100);
343     if (ret < 0)
344         return ret;
345
346     /* scan secondary files */
347     if (strlen(avctx->url) > 2) {
348         int i;
349         char *filename = av_strdup(avctx->url);
350
351         if (!filename)
352             return AVERROR(ENOMEM);
353
354         for (i = 0; i < 100; i++) {
355             snprintf(filename + strlen(filename) - 2, 3, "%02d", i);
356             if (avctx->io_open(avctx, &mlv->pb[i], filename, AVIO_FLAG_READ, NULL) < 0)
357                 break;
358             if (check_file_header(mlv->pb[i], guid) < 0) {
359                 av_log(avctx, AV_LOG_WARNING, "ignoring %s; bad format or guid mismatch\n", filename);
360                 ff_format_io_close(avctx, &mlv->pb[i]);
361                 continue;
362             }
363             av_log(avctx, AV_LOG_INFO, "scanning %s\n", filename);
364             ret = scan_file(avctx, vst, ast, i);
365             if (ret < 0) {
366                 av_log(avctx, AV_LOG_WARNING, "ignoring %s; %s\n", filename, av_err2str(ret));
367                 ff_format_io_close(avctx, &mlv->pb[i]);
368                 continue;
369             }
370         }
371         av_free(filename);
372     }
373
374     if (vst)
375         vst->duration = vst->nb_index_entries;
376     if (ast)
377         ast->duration = ast->nb_index_entries;
378
379     if ((vst && !vst->nb_index_entries) || (ast && !ast->nb_index_entries)) {
380         av_log(avctx, AV_LOG_ERROR, "no index entries found\n");
381         read_close(avctx);
382         return AVERROR_INVALIDDATA;
383     }
384
385     if (vst && ast)
386         avio_seek(pb, FFMIN(vst->index_entries[0].pos, ast->index_entries[0].pos), SEEK_SET);
387     else if (vst)
388         avio_seek(pb, vst->index_entries[0].pos, SEEK_SET);
389     else if (ast)
390         avio_seek(pb, ast->index_entries[0].pos, SEEK_SET);
391
392     return 0;
393 }
394
395 static int read_packet(AVFormatContext *avctx, AVPacket *pkt)
396 {
397     MlvContext *mlv = avctx->priv_data;
398     AVIOContext *pb;
399     AVStream *st;
400     int index, ret;
401     unsigned int size, space;
402
403     if (!avctx->nb_streams)
404         return AVERROR_EOF;
405
406     st = avctx->streams[mlv->stream_index];
407     if (mlv->pts >= st->duration)
408         return AVERROR_EOF;
409
410     index = av_index_search_timestamp(st, mlv->pts, AVSEEK_FLAG_ANY);
411     if (index < 0) {
412         av_log(avctx, AV_LOG_ERROR, "could not find index entry for frame %"PRId64"\n", mlv->pts);
413         return AVERROR(EIO);
414     }
415
416     pb = mlv->pb[st->index_entries[index].size];
417     if (!pb) {
418         ret = FFERROR_REDO;
419         goto next_packet;
420     }
421     avio_seek(pb, st->index_entries[index].pos, SEEK_SET);
422
423     avio_skip(pb, 4); // blockType
424     size = avio_rl32(pb);
425     if (size < 16)
426         return AVERROR_INVALIDDATA;
427     avio_skip(pb, 12); //timestamp, frameNumber
428     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
429         avio_skip(pb, 8); // cropPosX, cropPosY, panPosX, panPosY
430     space = avio_rl32(pb);
431     avio_skip(pb, space);
432
433     if ((mlv->class[st->id] & (MLV_CLASS_FLAG_DELTA|MLV_CLASS_FLAG_LZMA))) {
434         ret = AVERROR_PATCHWELCOME;
435     } else if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
436         ret = av_get_packet(pb, pkt, (st->codecpar->width * st->codecpar->height * st->codecpar->bits_per_coded_sample + 7) >> 3);
437     } else { // AVMEDIA_TYPE_AUDIO
438         if (space > UINT_MAX - 24 || size < (24 + space))
439             return AVERROR_INVALIDDATA;
440         ret = av_get_packet(pb, pkt, size - (24 + space));
441     }
442
443     if (ret < 0)
444         return ret;
445
446     pkt->stream_index = mlv->stream_index;
447     pkt->pts = mlv->pts;
448
449     ret = 0;
450 next_packet:
451     mlv->stream_index++;
452     if (mlv->stream_index == avctx->nb_streams) {
453         mlv->stream_index = 0;
454         mlv->pts++;
455     }
456     return ret;
457 }
458
459 static int read_seek(AVFormatContext *avctx, int stream_index, int64_t timestamp, int flags)
460 {
461     MlvContext *mlv = avctx->priv_data;
462
463     if ((flags & AVSEEK_FLAG_FRAME) || (flags & AVSEEK_FLAG_BYTE))
464         return AVERROR(ENOSYS);
465
466     if (!(avctx->pb->seekable & AVIO_SEEKABLE_NORMAL))
467         return AVERROR(EIO);
468
469     mlv->pts = timestamp;
470     return 0;
471 }
472
473 static int read_close(AVFormatContext *s)
474 {
475     MlvContext *mlv = s->priv_data;
476     int i;
477     for (i = 0; i < 100; i++)
478         ff_format_io_close(s, &mlv->pb[i]);
479     return 0;
480 }
481
482 AVInputFormat ff_mlv_demuxer = {
483     .name           = "mlv",
484     .long_name      = NULL_IF_CONFIG_SMALL("Magic Lantern Video (MLV)"),
485     .priv_data_size = sizeof(MlvContext),
486     .read_probe     = probe,
487     .read_header    = read_header,
488     .read_packet    = read_packet,
489     .read_close     = read_close,
490     .read_seek      = read_seek,
491 };