OSDN Git Service

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