]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavformat/dv.c
* Fixing seeking with DV-AVI (by Jeff Downs <heydowns at borg dot com>)
[frescor/ffmpeg.git] / libavformat / dv.c
1 /*
2  * General DV muxer/demuxer
3  * Copyright (c) 2003 Roman Shaposhnik
4  *
5  * Many thanks to Dan Dennedy <dan@dennedy.org> for providing wealth
6  * of DV technical info.
7  *
8  * Raw DV format
9  * Copyright (c) 2002 Fabrice Bellard.
10  *
11  * 50 Mbps (DVCPRO50) support
12  * Copyright (c) 2006 Daniel Maas <dmaas@maasdigital.com>
13  *
14  * This file is part of FFmpeg.
15  *
16  * FFmpeg is free software; you can redistribute it and/or
17  * modify it under the terms of the GNU Lesser General Public
18  * License as published by the Free Software Foundation; either
19  * version 2.1 of the License, or (at your option) any later version.
20  *
21  * FFmpeg is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
24  * Lesser General Public License for more details.
25  *
26  * You should have received a copy of the GNU Lesser General Public
27  * License along with FFmpeg; if not, write to the Free Software
28  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29  */
30 #include <time.h>
31 #include "avformat.h"
32 #include "dvdata.h"
33 #include "dv.h"
34
35 struct DVDemuxContext {
36     const DVprofile*  sys;    /* Current DV profile. E.g.: 525/60, 625/50 */
37     AVFormatContext* fctx;
38     AVStream*        vst;
39     AVStream*        ast[2];
40     AVPacket         audio_pkt[2];
41     uint8_t          audio_buf[2][8192];
42     int              ach;
43     int              frames;
44     uint64_t         abytes;
45 };
46
47 static inline uint16_t dv_audio_12to16(uint16_t sample)
48 {
49     uint16_t shift, result;
50
51     sample = (sample < 0x800) ? sample : sample | 0xf000;
52     shift = (sample & 0xf00) >> 8;
53
54     if (shift < 0x2 || shift > 0xd) {
55         result = sample;
56     } else if (shift < 0x8) {
57         shift--;
58         result = (sample - (256 * shift)) << shift;
59     } else {
60         shift = 0xe - shift;
61         result = ((sample + ((256 * shift) + 1)) << shift) - 1;
62     }
63
64     return result;
65 }
66
67 /*
68  * This is the dumbest implementation of all -- it simply looks at
69  * a fixed offset and if pack isn't there -- fails. We might want
70  * to have a fallback mechanism for complete search of missing packs.
71  */
72 static const uint8_t* dv_extract_pack(uint8_t* frame, enum dv_pack_type t)
73 {
74     int offs;
75
76     switch (t) {
77     case dv_audio_source:
78           offs = (80*6 + 80*16*3 + 3);
79           break;
80     case dv_audio_control:
81           offs = (80*6 + 80*16*4 + 3);
82           break;
83     case dv_video_control:
84           offs = (80*5 + 48 + 5);
85           break;
86     default:
87           return NULL;
88     }
89
90     return (frame[offs] == t ? &frame[offs] : NULL);
91 }
92
93 /*
94  * There's a couple of assumptions being made here:
95  * 1. By default we silence erroneous (0x8000/16bit 0x800/12bit) audio samples.
96  *    We can pass them upwards when ffmpeg will be ready to deal with them.
97  * 2. We don't do software emphasis.
98  * 3. Audio is always returned as 16bit linear samples: 12bit nonlinear samples
99  *    are converted into 16bit linear ones.
100  */
101 static int dv_extract_audio(uint8_t* frame, uint8_t* pcm, uint8_t* pcm2,
102                             const DVprofile *sys)
103 {
104     int size, chan, i, j, d, of, smpls, freq, quant, half_ch;
105     uint16_t lc, rc;
106     const uint8_t* as_pack;
107
108     as_pack = dv_extract_pack(frame, dv_audio_source);
109     if (!as_pack)    /* No audio ? */
110         return 0;
111
112     smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */
113     freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48KHz, 1 - 44,1kHz, 2 - 32 kHz */
114     quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */
115
116     if (quant > 1)
117         return -1; /* Unsupported quantization */
118
119     size = (sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */
120     half_ch = sys->difseg_size/2;
121
122     /* for each DIF channel */
123     for (chan = 0; chan < sys->n_difchan; chan++) {
124         /* for each DIF segment */
125         for (i = 0; i < sys->difseg_size; i++) {
126             frame += 6 * 80; /* skip DIF segment header */
127             if (quant == 1 && i == half_ch) {
128                 /* next stereo channel (12bit mode only) */
129                 if (!pcm2)
130                     break;
131                 else
132                     pcm = pcm2;
133             }
134
135             /* for each AV sequence */
136             for (j = 0; j < 9; j++) {
137                 for (d = 8; d < 80; d += 2) {
138                     if (quant == 0) {  /* 16bit quantization */
139                         of = sys->audio_shuffle[i][j] + (d - 8)/2 * sys->audio_stride;
140                         if (of*2 >= size)
141                             continue;
142
143                         pcm[of*2] = frame[d+1]; // FIXME: may be we have to admit
144                         pcm[of*2+1] = frame[d]; //        that DV is a big endian PCM
145                         if (pcm[of*2+1] == 0x80 && pcm[of*2] == 0x00)
146                             pcm[of*2+1] = 0;
147                     } else {           /* 12bit quantization */
148                         lc = ((uint16_t)frame[d] << 4) |
149                              ((uint16_t)frame[d+2] >> 4);
150                         rc = ((uint16_t)frame[d+1] << 4) |
151                              ((uint16_t)frame[d+2] & 0x0f);
152                         lc = (lc == 0x800 ? 0 : dv_audio_12to16(lc));
153                         rc = (rc == 0x800 ? 0 : dv_audio_12to16(rc));
154
155                         of = sys->audio_shuffle[i%half_ch][j] + (d - 8)/3 * sys->audio_stride;
156                         if (of*2 >= size)
157                             continue;
158
159                         pcm[of*2] = lc & 0xff; // FIXME: may be we have to admit
160                         pcm[of*2+1] = lc >> 8; //        that DV is a big endian PCM
161                         of = sys->audio_shuffle[i%half_ch+half_ch][j] +
162                             (d - 8)/3 * sys->audio_stride;
163                         pcm[of*2] = rc & 0xff; // FIXME: may be we have to admit
164                         pcm[of*2+1] = rc >> 8; //        that DV is a big endian PCM
165                         ++d;
166                     }
167                 }
168
169                 frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */
170             }
171         }
172
173         /* next stereo channel (50Mbps only) */
174         if(!pcm2)
175             break;
176         pcm = pcm2;
177     }
178
179     return size;
180 }
181
182 static int dv_extract_audio_info(DVDemuxContext* c, uint8_t* frame)
183 {
184     const uint8_t* as_pack;
185     int freq, stype, smpls, quant, i, ach;
186
187     as_pack = dv_extract_pack(frame, dv_audio_source);
188     if (!as_pack || !c->sys) {    /* No audio ? */
189         c->ach = 0;
190         return 0;
191     }
192
193     smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */
194     freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48KHz, 1 - 44,1kHz, 2 - 32 kHz */
195     stype = (as_pack[3] & 0x1f); /* 0 - 2CH, 2 - 4CH */
196     quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */
197
198     /* note: ach counts PAIRS of channels (i.e. stereo channels) */
199     ach = (stype == 2 || (quant && (freq == 2))) ? 2 : 1;
200
201     /* Dynamic handling of the audio streams in DV */
202     for (i=0; i<ach; i++) {
203        if (!c->ast[i]) {
204            c->ast[i] = av_new_stream(c->fctx, 0);
205            if (!c->ast[i])
206                break;
207            av_set_pts_info(c->ast[i], 64, 1, 30000);
208            c->ast[i]->codec->codec_type = CODEC_TYPE_AUDIO;
209            c->ast[i]->codec->codec_id = CODEC_ID_PCM_S16LE;
210
211            av_init_packet(&c->audio_pkt[i]);
212            c->audio_pkt[i].size     = 0;
213            c->audio_pkt[i].data     = c->audio_buf[i];
214            c->audio_pkt[i].stream_index = c->ast[i]->index;
215            c->audio_pkt[i].flags |= PKT_FLAG_KEY;
216        }
217        c->ast[i]->codec->sample_rate = dv_audio_frequency[freq];
218        c->ast[i]->codec->channels = 2;
219        c->ast[i]->codec->bit_rate = 2 * dv_audio_frequency[freq] * 16;
220        c->ast[i]->start_time = 0;
221     }
222     c->ach = i;
223
224     return (c->sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */;
225 }
226
227 static int dv_extract_video_info(DVDemuxContext *c, uint8_t* frame)
228 {
229     const uint8_t* vsc_pack;
230     AVCodecContext* avctx;
231     int apt, is16_9;
232     int size = 0;
233
234     if (c->sys) {
235         avctx = c->vst->codec;
236
237         av_set_pts_info(c->vst, 64, c->sys->frame_rate_base, c->sys->frame_rate);
238         avctx->time_base= (AVRational){c->sys->frame_rate_base, c->sys->frame_rate};
239         if(!avctx->width){
240             avctx->width = c->sys->width;
241             avctx->height = c->sys->height;
242         }
243         avctx->pix_fmt = c->sys->pix_fmt;
244
245         /* finding out SAR is a little bit messy */
246         vsc_pack = dv_extract_pack(frame, dv_video_control);
247         apt = frame[4] & 0x07;
248         is16_9 = (vsc_pack && ((vsc_pack[2] & 0x07) == 0x02 ||
249                                (!apt && (vsc_pack[2] & 0x07) == 0x07)));
250         avctx->sample_aspect_ratio = c->sys->sar[is16_9];
251         avctx->bit_rate = av_rescale(c->sys->frame_size * 8,
252                                      c->sys->frame_rate,
253                                      c->sys->frame_rate_base);
254         size = c->sys->frame_size;
255     }
256     return size;
257 }
258
259 /*
260  * The following 3 functions constitute our interface to the world
261  */
262
263 DVDemuxContext* dv_init_demux(AVFormatContext *s)
264 {
265     DVDemuxContext *c;
266
267     c = av_mallocz(sizeof(DVDemuxContext));
268     if (!c)
269         return NULL;
270
271     c->vst = av_new_stream(s, 0);
272     if (!c->vst) {
273         av_free(c);
274         return NULL;
275     }
276
277     c->sys = NULL;
278     c->fctx = s;
279     c->ast[0] = c->ast[1] = NULL;
280     c->ach = 0;
281     c->frames = 0;
282     c->abytes = 0;
283
284     c->vst->codec->codec_type = CODEC_TYPE_VIDEO;
285     c->vst->codec->codec_id = CODEC_ID_DVVIDEO;
286     c->vst->codec->bit_rate = 25000000;
287     c->vst->start_time = 0;
288
289     return c;
290 }
291
292 int dv_get_packet(DVDemuxContext *c, AVPacket *pkt)
293 {
294     int size = -1;
295     int i;
296
297     for (i=0; i<c->ach; i++) {
298        if (c->ast[i] && c->audio_pkt[i].size) {
299            *pkt = c->audio_pkt[i];
300            c->audio_pkt[i].size = 0;
301            size = pkt->size;
302            break;
303        }
304     }
305
306     return size;
307 }
308
309 int dv_produce_packet(DVDemuxContext *c, AVPacket *pkt,
310                       uint8_t* buf, int buf_size)
311 {
312     int size, i;
313
314     if (buf_size < DV_PROFILE_BYTES ||
315         !(c->sys = dv_frame_profile(buf)) ||
316         buf_size < c->sys->frame_size) {
317           return -1;   /* Broken frame, or not enough data */
318     }
319
320     /* Queueing audio packet */
321     /* FIXME: in case of no audio/bad audio we have to do something */
322     size = dv_extract_audio_info(c, buf);
323     for (i=0; i<c->ach; i++) {
324        c->audio_pkt[i].size = size;
325        c->audio_pkt[i].pts  = c->abytes * 30000*8 / c->ast[i]->codec->bit_rate;
326     }
327     dv_extract_audio(buf, c->audio_buf[0], c->audio_buf[1], c->sys);
328     c->abytes += size;
329
330     /* Now it's time to return video packet */
331     size = dv_extract_video_info(c, buf);
332     av_init_packet(pkt);
333     pkt->data     = buf;
334     pkt->size     = size;
335     pkt->flags   |= PKT_FLAG_KEY;
336     pkt->stream_index = c->vst->id;
337     pkt->pts      = c->frames;
338
339     c->frames++;
340
341     return size;
342 }
343
344 static int64_t dv_frame_offset(AVFormatContext *s, DVDemuxContext *c,
345                               int64_t timestamp, int flags)
346 {
347     // FIXME: sys may be wrong if last dv_read_packet() failed (buffer is junk)
348     const DVprofile* sys = dv_codec_profile(c->vst->codec);
349     int64_t offset;
350     int64_t size = url_fsize(&s->pb);
351     int64_t max_offset = ((size-1) / sys->frame_size) * sys->frame_size;
352
353     offset = sys->frame_size * timestamp;
354
355     if (offset > max_offset) offset = max_offset;
356     else if (offset < 0) offset = 0;
357
358     return offset;
359 }
360
361 void dv_offset_reset(DVDemuxContext *c, int64_t frame_offset)
362 {
363     c->frames= frame_offset;
364     if (c->ach)
365         c->abytes= av_rescale(c->frames,
366                           c->ast[0]->codec->bit_rate * (int64_t)c->sys->frame_rate_base,
367                           8*c->sys->frame_rate);
368     c->audio_pkt[0].size = c->audio_pkt[1].size = 0;
369 }
370
371 /************************************************************
372  * Implementation of the easiest DV storage of all -- raw DV.
373  ************************************************************/
374
375 typedef struct RawDVContext {
376     DVDemuxContext* dv_demux;
377     uint8_t         buf[DV_MAX_FRAME_SIZE];
378 } RawDVContext;
379
380 static int dv_read_header(AVFormatContext *s,
381                           AVFormatParameters *ap)
382 {
383     RawDVContext *c = s->priv_data;
384
385     c->dv_demux = dv_init_demux(s);
386     if (!c->dv_demux)
387         return -1;
388
389     if (get_buffer(&s->pb, c->buf, DV_PROFILE_BYTES) <= 0 ||
390         url_fseek(&s->pb, -DV_PROFILE_BYTES, SEEK_CUR) < 0)
391         return AVERROR_IO;
392
393     c->dv_demux->sys = dv_frame_profile(c->buf);
394     s->bit_rate = av_rescale(c->dv_demux->sys->frame_size * 8,
395                              c->dv_demux->sys->frame_rate,
396                              c->dv_demux->sys->frame_rate_base);
397
398     return 0;
399 }
400
401
402 static int dv_read_packet(AVFormatContext *s, AVPacket *pkt)
403 {
404     int size;
405     RawDVContext *c = s->priv_data;
406
407     size = dv_get_packet(c->dv_demux, pkt);
408
409     if (size < 0) {
410         size = c->dv_demux->sys->frame_size;
411         if (get_buffer(&s->pb, c->buf, size) <= 0)
412             return AVERROR_IO;
413
414         size = dv_produce_packet(c->dv_demux, pkt, c->buf, size);
415     }
416
417     return size;
418 }
419
420 static int dv_read_seek(AVFormatContext *s, int stream_index,
421                        int64_t timestamp, int flags)
422 {
423     RawDVContext *r = s->priv_data;
424     DVDemuxContext *c = r->dv_demux;
425     int64_t offset= dv_frame_offset(s, c, timestamp, flags);
426
427     dv_offset_reset(c, offset / c->sys->frame_size);
428
429     return url_fseek(&s->pb, offset, SEEK_SET);
430 }
431
432 static int dv_read_close(AVFormatContext *s)
433 {
434     RawDVContext *c = s->priv_data;
435     av_free(c->dv_demux);
436     return 0;
437 }
438
439 #ifdef CONFIG_DV_DEMUXER
440 AVInputFormat dv_demuxer = {
441     "dv",
442     "DV video format",
443     sizeof(RawDVContext),
444     NULL,
445     dv_read_header,
446     dv_read_packet,
447     dv_read_close,
448     dv_read_seek,
449     .extensions = "dv,dif",
450 };
451 #endif