]> git.sesse.net Git - ffmpeg/blob - libavformat/xmv.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavformat / xmv.c
1 /*
2  * Microsoft XMV demuxer
3  * Copyright (c) 2011 Sven Hesse <drmccoy@drmccoy.de>
4  * Copyright (c) 2011 Matthew Hoops <clone2727@gmail.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 /**
24  * @file
25  * Microsoft XMV demuxer
26  */
27
28 #include <stdint.h>
29
30 #include "libavutil/intreadwrite.h"
31
32 #include "avformat.h"
33 #include "internal.h"
34 #include "riff.h"
35
36 /** The min size of an XMV header. */
37 #define XMV_MIN_HEADER_SIZE 36
38
39 /** Audio flag: ADPCM'd 5.1 stream, front left / right channels */
40 #define XMV_AUDIO_ADPCM51_FRONTLEFTRIGHT 1
41 /** Audio flag: ADPCM'd 5.1 stream, front center / low frequency channels */
42 #define XMV_AUDIO_ADPCM51_FRONTCENTERLOW 2
43 /** Audio flag: ADPCM'd 5.1 stream, rear left / right channels */
44 #define XMV_AUDIO_ADPCM51_REARLEFTRIGHT  4
45
46 /** Audio flag: Any of the ADPCM'd 5.1 stream flags. */
47 #define XMV_AUDIO_ADPCM51 (XMV_AUDIO_ADPCM51_FRONTLEFTRIGHT | \
48                            XMV_AUDIO_ADPCM51_FRONTCENTERLOW | \
49                            XMV_AUDIO_ADPCM51_REARLEFTRIGHT)
50
51 /** A video packet with an XMV file. */
52 typedef struct XMVVideoPacket {
53     int stream_index; ///< The decoder stream index for this video packet.
54
55     uint32_t data_size;   ///< The size of the remaining video data.
56     uint64_t data_offset; ///< The offset of the video data within the file.
57
58     uint32_t current_frame; ///< The current frame within this video packet.
59     uint32_t frame_count;   ///< The amount of frames within this video packet.
60
61     int     has_extradata; ///< Does the video packet contain extra data?
62     uint8_t extradata[4];  ///< The extra data
63
64     int64_t last_pts; ///< PTS of the last video frame.
65     int64_t pts;      ///< PTS of the most current video frame.
66 } XMVVideoPacket;
67
68 /** An audio packet with an XMV file. */
69 typedef struct XMVAudioPacket {
70     int stream_index; ///< The decoder stream index for this audio packet.
71
72     /* Stream format properties. */
73     uint16_t compression;     ///< The type of compression.
74     uint16_t channels;        ///< Number of channels.
75     uint32_t sample_rate;     ///< Sampling rate.
76     uint16_t bits_per_sample; ///< Bits per compressed sample.
77     uint32_t bit_rate;        ///< Bits of compressed data per second.
78     uint16_t flags;           ///< Flags
79     uint16_t block_align;     ///< Bytes per compressed block.
80     uint16_t block_samples;   ///< Decompressed samples per compressed block.
81
82     enum CodecID codec_id; ///< The codec ID of the compression scheme.
83
84     uint32_t data_size;   ///< The size of the remaining audio data.
85     uint64_t data_offset; ///< The offset of the audio data within the file.
86
87     uint32_t frame_size; ///< Number of bytes to put into an audio frame.
88
89     uint64_t block_count; ///< Running counter of decompressed audio block.
90 } XMVAudioPacket;
91
92 /** Context for demuxing an XMV file. */
93 typedef struct XMVDemuxContext {
94     uint16_t audio_track_count; ///< Number of audio track in this file.
95
96     uint32_t this_packet_size; ///< Size of the current packet.
97     uint32_t next_packet_size; ///< Size of the next packet.
98
99     uint64_t this_packet_offset; ///< Offset of the current packet.
100     uint64_t next_packet_offset; ///< Offset of the next packet.
101
102     uint16_t current_stream; ///< The index of the stream currently handling.
103     uint16_t stream_count;   ///< The number of streams in this file.
104
105     XMVVideoPacket  video; ///< The video packet contained in each packet.
106     XMVAudioPacket *audio; ///< The audio packets contained in each packet.
107 } XMVDemuxContext;
108
109 static int xmv_probe(AVProbeData *p)
110 {
111     uint32_t file_version;
112
113     if (p->buf_size < XMV_MIN_HEADER_SIZE)
114         return 0;
115
116     file_version = AV_RL32(p->buf + 16);
117     if ((file_version == 0) || (file_version > 4))
118         return 0;
119
120     if (!memcmp(p->buf + 12, "xobX", 4))
121         return AVPROBE_SCORE_MAX;
122
123     return 0;
124 }
125
126 static int xmv_read_header(AVFormatContext *s)
127 {
128     XMVDemuxContext *xmv = s->priv_data;
129     AVIOContext     *pb  = s->pb;
130     AVStream        *vst = NULL;
131
132     uint32_t file_version;
133     uint32_t this_packet_size;
134     uint16_t audio_track;
135
136     avio_skip(pb, 4); /* Next packet size */
137
138     this_packet_size = avio_rl32(pb);
139
140     avio_skip(pb, 4); /* Max packet size */
141     avio_skip(pb, 4); /* "xobX" */
142
143     file_version = avio_rl32(pb);
144     if ((file_version != 4) && (file_version != 2))
145         av_log_ask_for_sample(s, "Found uncommon version %d\n", file_version);
146
147
148     /* Video track */
149
150     vst = avformat_new_stream(s, NULL);
151     if (!vst)
152         return AVERROR(ENOMEM);
153
154     avpriv_set_pts_info(vst, 32, 1, 1000);
155
156     vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
157     vst->codec->codec_id   = CODEC_ID_WMV2;
158     vst->codec->codec_tag  = MKBETAG('W', 'M', 'V', '2');
159     vst->codec->width      = avio_rl32(pb);
160     vst->codec->height     = avio_rl32(pb);
161
162     vst->duration          = avio_rl32(pb);
163
164     xmv->video.stream_index = vst->index;
165
166     /* Audio tracks */
167
168     xmv->audio_track_count = avio_rl16(pb);
169
170     avio_skip(pb, 2); /* Unknown (padding?) */
171
172     xmv->audio = av_malloc(xmv->audio_track_count * sizeof(XMVAudioPacket));
173     if (!xmv->audio)
174         return AVERROR(ENOMEM);
175
176     for (audio_track = 0; audio_track < xmv->audio_track_count; audio_track++) {
177         XMVAudioPacket *packet = &xmv->audio[audio_track];
178         AVStream *ast = NULL;
179
180         packet->compression     = avio_rl16(pb);
181         packet->channels        = avio_rl16(pb);
182         packet->sample_rate     = avio_rl32(pb);
183         packet->bits_per_sample = avio_rl16(pb);
184         packet->flags           = avio_rl16(pb);
185
186         packet->bit_rate      = packet->bits_per_sample *
187                                 packet->sample_rate *
188                                 packet->channels;
189         packet->block_align   = 36 * packet->channels;
190         packet->block_samples = 64;
191         packet->codec_id      = ff_wav_codec_get_id(packet->compression,
192                                                     packet->bits_per_sample);
193
194         packet->stream_index = -1;
195
196         packet->frame_size  = 0;
197         packet->block_count = 0;
198
199         /* TODO: ADPCM'd 5.1 sound is encoded in three separate streams.
200          *       Those need to be interleaved to a proper 5.1 stream. */
201         if (packet->flags & XMV_AUDIO_ADPCM51)
202             av_log(s, AV_LOG_WARNING, "Unsupported 5.1 ADPCM audio stream "
203                                       "(0x%04X)\n", packet->flags);
204
205         ast = avformat_new_stream(s, NULL);
206         if (!ast)
207             return AVERROR(ENOMEM);
208
209         ast->codec->codec_type            = AVMEDIA_TYPE_AUDIO;
210         ast->codec->codec_id              = packet->codec_id;
211         ast->codec->codec_tag             = packet->compression;
212         ast->codec->channels              = packet->channels;
213         ast->codec->sample_rate           = packet->sample_rate;
214         ast->codec->bits_per_coded_sample = packet->bits_per_sample;
215         ast->codec->bit_rate              = packet->bit_rate;
216         ast->codec->block_align           = 36 * packet->channels;
217
218         avpriv_set_pts_info(ast, 32, packet->block_samples, packet->sample_rate);
219
220         packet->stream_index = ast->index;
221
222         ast->duration = vst->duration;
223     }
224
225
226     /* Initialize the packet context */
227
228     xmv->next_packet_offset = avio_tell(pb);
229     xmv->next_packet_size   = this_packet_size - xmv->next_packet_offset;
230     xmv->stream_count       = xmv->audio_track_count + 1;
231
232     return 0;
233 }
234
235 static void xmv_read_extradata(uint8_t *extradata, AVIOContext *pb)
236 {
237     /* Read the XMV extradata */
238
239     uint32_t data = avio_rl32(pb);
240
241     int mspel_bit        = !!(data & 0x01);
242     int loop_filter      = !!(data & 0x02);
243     int abt_flag         = !!(data & 0x04);
244     int j_type_bit       = !!(data & 0x08);
245     int top_left_mv_flag = !!(data & 0x10);
246     int per_mb_rl_bit    = !!(data & 0x20);
247     int slice_count      = (data >> 6) & 7;
248
249     /* Write it back as standard WMV2 extradata */
250
251     data = 0;
252
253     data |= mspel_bit        << 15;
254     data |= loop_filter      << 14;
255     data |= abt_flag         << 13;
256     data |= j_type_bit       << 12;
257     data |= top_left_mv_flag << 11;
258     data |= per_mb_rl_bit    << 10;
259     data |= slice_count      <<  7;
260
261     AV_WB32(extradata, data);
262 }
263
264 static int xmv_process_packet_header(AVFormatContext *s)
265 {
266     XMVDemuxContext *xmv = s->priv_data;
267     AVIOContext     *pb  = s->pb;
268
269     uint8_t  data[8];
270     uint16_t audio_track;
271     uint64_t data_offset;
272
273     /* Next packet size */
274     xmv->next_packet_size = avio_rl32(pb);
275
276     /* Packet video header */
277
278     if (avio_read(pb, data, 8) != 8)
279         return AVERROR(EIO);
280
281     xmv->video.data_size     = AV_RL32(data) & 0x007FFFFF;
282
283     xmv->video.current_frame = 0;
284     xmv->video.frame_count   = (AV_RL32(data) >> 23) & 0xFF;
285
286     xmv->video.has_extradata = (data[3] & 0x80) != 0;
287
288     /* Adding the audio data sizes and the video data size keeps you 4 bytes
289      * short for every audio track. But as playing around with XMV files with
290      * ADPCM audio showed, taking the extra 4 bytes from the audio data gives
291      * you either completely distorted audio or click (when skipping the
292      * remaining 68 bytes of the ADPCM block). Substracting 4 bytes for every
293      * audio track from the video data works at least for the audio. Probably
294      * some alignment thing?
295      * The video data has (always?) lots of padding, so it should work out...
296      */
297     xmv->video.data_size -= xmv->audio_track_count * 4;
298
299     xmv->current_stream = 0;
300     if (!xmv->video.frame_count) {
301         xmv->video.frame_count = 1;
302         xmv->current_stream    = 1;
303     }
304
305     /* Packet audio header */
306
307     for (audio_track = 0; audio_track < xmv->audio_track_count; audio_track++) {
308         XMVAudioPacket *packet = &xmv->audio[audio_track];
309
310         if (avio_read(pb, data, 4) != 4)
311             return AVERROR(EIO);
312
313         packet->data_size = AV_RL32(data) & 0x007FFFFF;
314         if ((packet->data_size == 0) && (audio_track != 0))
315             /* This happens when I create an XMV with several identical audio
316              * streams. From the size calculations, duplicating the previous
317              * stream's size works out, but the track data itself is silent.
318              * Maybe this should also redirect the offset to the previous track?
319              */
320             packet->data_size = xmv->audio[audio_track - 1].data_size;
321
322         /* Carve up the audio data in frame_count slices */
323         packet->frame_size  = packet->data_size  / xmv->video.frame_count;
324         packet->frame_size -= packet->frame_size % packet->block_align;
325     }
326
327     /* Packet data offsets */
328
329     data_offset = avio_tell(pb);
330
331     xmv->video.data_offset = data_offset;
332     data_offset += xmv->video.data_size;
333
334     for (audio_track = 0; audio_track < xmv->audio_track_count; audio_track++) {
335         xmv->audio[audio_track].data_offset = data_offset;
336         data_offset += xmv->audio[audio_track].data_size;
337     }
338
339     /* Video frames header */
340
341     /* Read new video extra data */
342     if (xmv->video.data_size > 0) {
343         if (xmv->video.has_extradata) {
344             xmv_read_extradata(xmv->video.extradata, pb);
345
346             xmv->video.data_size   -= 4;
347             xmv->video.data_offset += 4;
348
349             if (xmv->video.stream_index >= 0) {
350                 AVStream *vst = s->streams[xmv->video.stream_index];
351
352                 assert(xmv->video.stream_index < s->nb_streams);
353
354                 if (vst->codec->extradata_size < 4) {
355                     av_free(vst->codec->extradata);
356
357                     vst->codec->extradata =
358                         av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
359                     vst->codec->extradata_size = 4;
360                 }
361
362                 memcpy(vst->codec->extradata, xmv->video.extradata, 4);
363             }
364         }
365     }
366
367     return 0;
368 }
369
370 static int xmv_fetch_new_packet(AVFormatContext *s)
371 {
372     XMVDemuxContext *xmv = s->priv_data;
373     AVIOContext     *pb  = s->pb;
374     int result;
375
376     /* Seek to it */
377     xmv->this_packet_offset = xmv->next_packet_offset;
378     if (avio_seek(pb, xmv->this_packet_offset, SEEK_SET) != xmv->this_packet_offset)
379         return AVERROR(EIO);
380
381     /* Update the size */
382     xmv->this_packet_size = xmv->next_packet_size;
383     if (xmv->this_packet_size < (12 + xmv->audio_track_count * 4))
384         return AVERROR(EIO);
385
386     /* Process the header */
387     result = xmv_process_packet_header(s);
388     if (result)
389         return result;
390
391     /* Update the offset */
392     xmv->next_packet_offset = xmv->this_packet_offset + xmv->this_packet_size;
393
394     return 0;
395 }
396
397 static int xmv_fetch_audio_packet(AVFormatContext *s,
398                                   AVPacket *pkt, uint32_t stream)
399 {
400     XMVDemuxContext *xmv   = s->priv_data;
401     AVIOContext     *pb    = s->pb;
402     XMVAudioPacket  *audio = &xmv->audio[stream];
403
404     uint32_t data_size;
405     uint32_t block_count;
406     int result;
407
408     /* Seek to it */
409     if (avio_seek(pb, audio->data_offset, SEEK_SET) != audio->data_offset)
410         return AVERROR(EIO);
411
412     if ((xmv->video.current_frame + 1) < xmv->video.frame_count)
413         /* Not the last frame, get at most frame_size bytes. */
414         data_size = FFMIN(audio->frame_size, audio->data_size);
415     else
416         /* Last frame, get the rest. */
417         data_size = audio->data_size;
418
419     /* Read the packet */
420     result = av_get_packet(pb, pkt, data_size);
421     if (result <= 0)
422         return result;
423
424     pkt->stream_index = audio->stream_index;
425
426     /* Calculate the PTS */
427
428     block_count = data_size / audio->block_align;
429
430     pkt->duration = block_count;
431     pkt->pts      = audio->block_count;
432     pkt->dts      = AV_NOPTS_VALUE;
433
434     audio->block_count += block_count;
435
436     /* Advance offset */
437     audio->data_size   -= data_size;
438     audio->data_offset += data_size;
439
440     return 0;
441 }
442
443 static int xmv_fetch_video_packet(AVFormatContext *s,
444                                   AVPacket *pkt)
445 {
446     XMVDemuxContext *xmv   = s->priv_data;
447     AVIOContext     *pb    = s->pb;
448     XMVVideoPacket  *video = &xmv->video;
449
450     int result;
451     uint32_t frame_header;
452     uint32_t frame_size, frame_timestamp;
453     uint8_t *data, *end;
454
455     /* Seek to it */
456     if (avio_seek(pb, video->data_offset, SEEK_SET) != video->data_offset)
457         return AVERROR(EIO);
458
459     /* Read the frame header */
460     frame_header = avio_rl32(pb);
461
462     frame_size      = (frame_header & 0x1FFFF) * 4 + 4;
463     frame_timestamp = (frame_header >> 17);
464
465     if ((frame_size + 4) > video->data_size)
466         return AVERROR(EIO);
467
468     /* Get the packet data */
469     result = av_get_packet(pb, pkt, frame_size);
470     if (result != frame_size)
471         return result;
472
473     /* Contrary to normal WMV2 video, the bit stream in XMV's
474      * WMV2 is little-endian.
475      * TODO: This manual swap is of course suboptimal.
476      */
477     for (data = pkt->data, end = pkt->data + frame_size; data < end; data += 4)
478         AV_WB32(data, AV_RL32(data));
479
480     pkt->stream_index = video->stream_index;
481
482     /* Calculate the PTS */
483
484     video->last_pts = frame_timestamp + video->pts;
485
486     pkt->duration = 0;
487     pkt->pts      = video->last_pts;
488     pkt->dts      = AV_NOPTS_VALUE;
489
490     video->pts += frame_timestamp;
491
492     /* Keyframe? */
493     pkt->flags = (pkt->data[0] & 0x80) ? 0 : AV_PKT_FLAG_KEY;
494
495     /* Advance offset */
496     video->data_size   -= frame_size + 4;
497     video->data_offset += frame_size + 4;
498
499     return 0;
500 }
501
502 static int xmv_read_packet(AVFormatContext *s,
503                            AVPacket *pkt)
504 {
505     XMVDemuxContext *xmv = s->priv_data;
506     int result;
507
508     if (xmv->video.current_frame == xmv->video.frame_count) {
509         /* No frames left in this packet, so we fetch a new one */
510
511         result = xmv_fetch_new_packet(s);
512         if (result)
513             return result;
514     }
515
516     if (xmv->current_stream == 0) {
517         /* Fetch a video frame */
518
519         result = xmv_fetch_video_packet(s, pkt);
520         if (result)
521             return result;
522
523     } else {
524         /* Fetch an audio frame */
525
526         result = xmv_fetch_audio_packet(s, pkt, xmv->current_stream - 1);
527         if (result)
528             return result;
529     }
530
531     /* Increase our counters */
532     if (++xmv->current_stream >= xmv->stream_count) {
533         xmv->current_stream       = 0;
534         xmv->video.current_frame += 1;
535     }
536
537     return 0;
538 }
539
540 static int xmv_read_close(AVFormatContext *s)
541 {
542     XMVDemuxContext *xmv = s->priv_data;
543
544     av_free(xmv->audio);
545
546     return 0;
547 }
548
549 AVInputFormat ff_xmv_demuxer = {
550     .name           = "xmv",
551     .long_name      = NULL_IF_CONFIG_SMALL("Microsoft XMV"),
552     .priv_data_size = sizeof(XMVDemuxContext),
553     .read_probe     = xmv_probe,
554     .read_header    = xmv_read_header,
555     .read_packet    = xmv_read_packet,
556     .read_close     = xmv_read_close,
557 };