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