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