]> git.sesse.net Git - ffmpeg/blob - libavformat/dv.c
* fixing a small quirk with DV audio muxing
[ffmpeg] / libavformat / dv.c
1 /* 
2  * General DV muxer/demuxer 
3  * Copyright (c) 2003 Roman Shaposhnick
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  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24  */
25 #include <time.h>
26 #include "avformat.h"
27 #include "dvdata.h"
28 #include "dv.h"
29
30 struct DVDemuxContext {
31     AVFormatContext* fctx;
32     AVStream*        vst;
33     AVStream*        ast[2];       
34     AVPacket         audio_pkt[2];
35     int              ach;
36     int              frames;
37     uint64_t         abytes;
38 };
39
40 struct DVMuxContext {
41     const DVprofile*  sys;    /* Current DV profile. E.g.: 525/60, 625/50 */
42     uint8_t     frame_buf[144000]; /* frame under contruction */
43     FifoBuffer  audio_data;   /* Fifo for storing excessive amounts of PCM */
44     int         frames;       /* Number of a current frame */
45     time_t      start_time;   /* Start time of recording */
46     uint8_t     aspect;       /* Aspect ID 0 - 4:3, 7 - 16:9 */
47     int         has_audio;    /* frame under contruction has audio */
48     int         has_video;    /* frame under contruction has video */
49 };
50
51 enum dv_section_type {
52      dv_sect_header  = 0x1f,
53      dv_sect_subcode = 0x3f,
54      dv_sect_vaux    = 0x56,
55      dv_sect_audio   = 0x76,
56      dv_sect_video   = 0x96,
57 };
58
59 enum dv_pack_type {
60      dv_header525     = 0x3f, /* see dv_write_pack for important details on */ 
61      dv_header625     = 0xbf, /* these two packs */
62      dv_timecode      = 0x13,
63      dv_audio_source  = 0x50,
64      dv_audio_control = 0x51,
65      dv_audio_recdate = 0x52,
66      dv_audio_rectime = 0x53,
67      dv_video_source  = 0x60,
68      dv_video_control = 0x61,
69      dv_viedo_recdate = 0x62,
70      dv_video_rectime = 0x63,
71      dv_unknown_pack  = 0xff,
72 };
73
74
75
76 /*
77  * The reason why the following three big ugly looking tables are
78  * here is my lack of DV spec IEC 61834. The tables were basically 
79  * constructed to make code that places packs in SSYB, VAUX and 
80  * AAUX blocks very simple and table-driven. They conform to the
81  * SMPTE 314M and the output of my personal DV camcorder, neither
82  * of which is sufficient for a reliable DV stream producing. Thus
83  * while code is still in development I'll be gathering input from
84  * people with different DV equipment and modifying the tables to
85  * accommodate all the quirks. Later on, if possible, some of them
86  * will be folded into smaller tables and/or switch-if logic. For 
87  * now, my only excuse is -- they don't eat up that much of a space.
88  */
89
90 static const int dv_ssyb_packs_dist[12][6] = {
91     { 0x13, 0x13, 0x13, 0x13, 0x13, 0x13 },
92     { 0x13, 0x13, 0x13, 0x13, 0x13, 0x13 },
93     { 0x13, 0x13, 0x13, 0x13, 0x13, 0x13 },
94     { 0x13, 0x13, 0x13, 0x13, 0x13, 0x13 },
95     { 0x13, 0x13, 0x13, 0x13, 0x13, 0x13 },
96     { 0x13, 0x13, 0x13, 0x13, 0x13, 0x13 },
97     { 0x13, 0x62, 0x63, 0x13, 0x62, 0x63 },
98     { 0x13, 0x62, 0x63, 0x13, 0x62, 0x63 },
99     { 0x13, 0x62, 0x63, 0x13, 0x62, 0x63 },
100     { 0x13, 0x62, 0x63, 0x13, 0x62, 0x63 },
101     { 0x13, 0x62, 0x63, 0x13, 0x62, 0x63 },
102     { 0x13, 0x62, 0x63, 0x13, 0x62, 0x63 },
103 };
104
105 static const int dv_vaux_packs_dist[12][15] = {
106     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
107       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
108     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
109       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
110     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
111       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
112     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
113       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
114     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
115       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
116     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
117       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
118     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
119       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
120     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
121       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
122     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
123       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
124     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
125       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
126     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
127       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
128     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
129       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
130 };
131
132 static const int dv_aaux_packs_dist[12][9] = {
133     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
134     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
135     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
136     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
137     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
138     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
139     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
140     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
141     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
142     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
143     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
144     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
145 };
146
147 static inline uint16_t dv_audio_12to16(uint16_t sample)
148 {
149     uint16_t shift, result;
150     
151     sample = (sample < 0x800) ? sample : sample | 0xf000;
152     shift = (sample & 0xf00) >> 8;
153
154     if (shift < 0x2 || shift > 0xd) {
155         result = sample;
156     } else if (shift < 0x8) {
157         shift--;
158         result = (sample - (256 * shift)) << shift;
159     } else {
160         shift = 0xe - shift;
161         result = ((sample + ((256 * shift) + 1)) << shift) - 1;
162     }
163
164     return result;
165 }
166
167 static int dv_audio_frame_size(const DVprofile* sys, int frame)
168 {
169     return sys->audio_samples_dist[frame % (sizeof(sys->audio_samples_dist)/
170                                             sizeof(sys->audio_samples_dist[0]))];
171 }
172
173 static int dv_write_pack(enum dv_pack_type pack_id, DVMuxContext *c, uint8_t* buf)
174 {
175     struct tm tc;
176     time_t ct;
177     int ltc_frame;
178
179     buf[0] = (uint8_t)pack_id;
180     switch (pack_id) {
181     case dv_header525: /* I can't imagine why these two weren't defined as real */
182     case dv_header625: /* packs in SMPTE314M -- they definitely look like ones */
183           buf[1] = 0xf8 |               /* reserved -- always 1 */
184                    (0 & 0x07);          /* APT: Track application ID */
185           buf[2] = (0 << 7)    | /* TF1: audio data is 0 - valid; 1 - invalid */
186                    (0x0f << 3) | /* reserved -- always 1 */
187                    (0 & 0x07);   /* AP1: Audio application ID */
188           buf[3] = (0 << 7)    | /* TF2: video data is 0 - valid; 1 - invalid */  
189                    (0x0f << 3) | /* reserved -- always 1 */
190                    (0 & 0x07);   /* AP2: Video application ID */
191           buf[4] = (0 << 7)    | /* TF3: subcode(SSYB) is 0 - valid; 1 - invalid */ 
192                    (0x0f << 3) | /* reserved -- always 1 */
193                    (0 & 0x07);   /* AP3: Subcode application ID */
194           break;
195     case dv_timecode:
196           ct = (time_t)(c->frames / ((float)c->sys->frame_rate / 
197                                      (float)c->sys->frame_rate_base));
198           localtime_r(&ct, &tc);
199           /* 
200            * LTC drop-frame frame counter drops two frames (0 and 1) every 
201            * minute, unless it is exactly divisible by 10
202            */
203           ltc_frame = (c->frames + 2*ct/60 - 2*ct/600) % c->sys->ltc_divisor;
204           buf[1] = (0 << 7) | /* Color fame: 0 - unsync; 1 - sync mode */
205                    (1 << 6) | /* Drop frame timecode: 0 - nondrop; 1 - drop */
206                    ((ltc_frame / 10) << 4) | /* Tens of frames */
207                    (ltc_frame % 10);         /* Units of frames */
208           buf[2] = (1 << 7) | /* Biphase mark polarity correction: 0 - even; 1 - odd */
209                    ((tc.tm_sec / 10) << 4) | /* Tens of seconds */
210                    (tc.tm_sec % 10);         /* Units of seconds */
211           buf[3] = (1 << 7) | /* Binary group flag BGF0 */
212                    ((tc.tm_min / 10) << 4) | /* Tens of minutes */
213                    (tc.tm_min % 10);         /* Units of minutes */
214           buf[4] = (1 << 7) | /* Binary group flag BGF2 */
215                    (1 << 6) | /* Binary group flag BGF1 */
216                    ((tc.tm_hour / 10) << 4) | /* Tens of hours */
217                    (tc.tm_hour % 10);         /* Units of hours */
218           break;
219     case dv_audio_source:  /* AAUX source pack */
220           buf[1] = (0 << 7) | /* locked mode       */
221                    (1 << 6) | /* reserved -- always 1 */
222                    (dv_audio_frame_size(c->sys, c->frames) -
223                     c->sys->audio_min_samples[0]);
224                               /* # of samples      */
225           buf[2] = (0 << 7) | /* multi-stereo      */
226                    (0 << 5) | /* #of audio channels per block: 0 -- 1 channel */
227                    (0 << 4) | /* pair bit: 0 -- one pair of channels */
228                     0;        /* audio mode        */
229           buf[3] = (1 << 7) | /* res               */
230                    (1 << 6) | /* multi-language flag */
231                    (c->sys->dsf << 5) | /*  system: 60fields/50fields */
232                     0;        /* definition: 0 -- SD (525/625) */
233           buf[4] = (1 << 7) | /* emphasis: 1 -- off */
234                    (0 << 6) | /* emphasis time constant: 0 -- reserved */
235                    (0 << 3) | /* frequency: 0 -- 48Khz, 1 -- 44,1Khz, 2 -- 32Khz */
236                     0;        /* quantization: 0 -- 16bit linear, 1 -- 12bit nonlinear */                           
237           break;
238     case dv_audio_control:
239           buf[1] = (0 << 6) | /* copy protection: 0 -- unrestricted */
240                    (1 << 4) | /* input source: 1 -- digital input */
241                    (3 << 2) | /* compression: 3 -- no information */
242                     0;        /* misc. info/SMPTE emphasis off */
243           buf[2] = (1 << 7) | /* recording start point: 1 -- no */
244                    (1 << 6) | /* recording end point: 1 -- no */
245                    (1 << 3) | /* recording mode: 1 -- original */
246                     7;         
247           buf[3] = (1 << 7) | /* direction: 1 -- forward */
248                     0x20;     /* speed */
249           buf[4] = (1 << 7) | /* reserved -- always 1 */
250                     0x7f;     /* genre category */
251           break;
252     case dv_audio_recdate:
253     case dv_viedo_recdate:  /* VAUX recording date */
254           ct = c->start_time + (time_t)(c->frames / 
255                ((float)c->sys->frame_rate / (float)c->sys->frame_rate_base));
256           localtime_r(&ct, &tc);
257           buf[1] = 0xff; /* ds, tm, tens of time zone, units of time zone */
258                          /* 0xff is very likely to be "unknown" */
259           buf[2] = (3 << 6) | /* reserved -- always 1 */
260                    ((tc.tm_mday / 10) << 4) | /* Tens of day */
261                    (tc.tm_mday % 10);         /* Units of day */
262           buf[3] = /* we set high 4 bits to 0, shouldn't we set them to week? */
263                    (tc.tm_mon % 10);         /* Units of month */
264           buf[4] = (((tc.tm_year % 100) / 10) << 4) | /* Tens of year */
265                    (tc.tm_year % 10);                 /* Units of year */
266           break;
267     case dv_audio_rectime:  /* AAUX recording time */
268     case dv_video_rectime:  /* VAUX recording time */
269           ct = c->start_time + (time_t)(c->frames / 
270                ((float)c->sys->frame_rate / (float)c->sys->frame_rate_base));
271           localtime_r(&ct, &tc);
272           buf[1] = (3 << 6) | /* reserved -- always 1 */
273                    0x3f; /* tens of frame, units of frame: 0x3f - "unknown" ? */
274           buf[2] = (1 << 7) | /* reserved -- always 1 */ 
275                    ((tc.tm_sec / 10) << 4) | /* Tens of seconds */
276                    (tc.tm_sec % 10);         /* Units of seconds */
277           buf[3] = (1 << 7) | /* reserved -- always 1 */
278                    ((tc.tm_min / 10) << 4) | /* Tens of minutes */
279                    (tc.tm_min % 10);         /* Units of minutes */
280           buf[4] = (3 << 6) | /* reserved -- always 1 */ 
281                    ((tc.tm_hour / 10) << 4) | /* Tens of hours */
282                    (tc.tm_hour % 10);         /* Units of hours */
283           break;
284     case dv_video_source:
285           buf[1] = 0xff; /* reserved -- always 1 */
286           buf[2] = (1 << 7) | /* B/W: 0 - b/w, 1 - color */
287                    (1 << 6) | /* following CLF is valid - 0, invalid - 1 */
288                    (3 << 4) | /* CLF: color frames id (see ITU-R BT.470-4) */
289                    0xf; /* reserved -- always 1 */
290           buf[3] = (3 << 6) | /* reserved -- always 1 */
291                    (c->sys->dsf << 5) | /*  system: 60fields/50fields */
292                    0; /* signal type video compression */
293           buf[4] = 0xff; /* VISC: 0xff -- no information */
294           break;
295     case dv_video_control:
296           buf[1] = (0 << 6) | /* Copy generation management (CGMS) 0 -- free */
297                    0x3f; /* reserved -- always 1 */
298           buf[2] = 0xc8 | /* reserved -- always b11001xxx */
299                    c->aspect;
300           buf[3] = (1 << 7) | /* Frame/field flag 1 -- frame, 0 -- field */
301                    (1 << 6) | /* First/second field flag 0 -- field 2, 1 -- field 1 */
302                    (1 << 5) | /* Frame change flag 0 -- same picture as before, 1 -- different */
303                    (1 << 4) | /* 1 - interlaced, 0 - noninterlaced */
304                    0xc; /* reserved -- always b1100 */
305           buf[4] = 0xff; /* reserved -- always 1 */
306           break;
307     default:
308           buf[1] = buf[2] = buf[3] = buf[4] = 0xff;
309     }
310     return 5;
311 }
312
313 static inline int dv_write_dif_id(enum dv_section_type t, uint8_t seq_num, 
314                                   uint8_t dif_num, uint8_t* buf)
315 {
316     buf[0] = (uint8_t)t;    /* Section type */
317     buf[1] = (seq_num<<4) | /* DIF seq number 0-9 for 525/60; 0-11 for 625/50 */
318              (0 << 3) |     /* FSC: for 50Mb/s 0 - first channel; 1 - second */
319              7;             /* reserved -- always 1 */
320     buf[2] = dif_num;       /* DIF block number Video: 0-134, Audio: 0-8 */
321     return 3;
322 }
323
324 static inline int dv_write_ssyb_id(uint8_t syb_num, uint8_t fr, uint8_t* buf)
325 {
326     if (syb_num == 0 || syb_num == 6) {
327         buf[0] = (fr<<7) | /* FR ID 1 - first half of each channel; 0 - second */
328                  (0<<4)  | /* AP3 (Subcode application ID) */
329                  0x0f;     /* reserved -- always 1 */
330     } 
331     else if (syb_num == 11) {
332         buf[0] = (fr<<7) | /* FR ID 1 - first half of each channel; 0 - second */
333                  0x7f;     /* reserved -- always 1 */
334     }
335     else {
336         buf[0] = (fr<<7) | /* FR ID 1 - first half of each channel; 0 - second */
337                  (0<<4)  | /* APT (Track application ID) */
338                  0x0f;     /* reserved -- always 1 */
339     }
340     buf[1] = 0xf0 |            /* reserved -- always 1 */
341              (syb_num & 0x0f); /* SSYB number 0 - 11   */
342     buf[2] = 0xff;             /* reserved -- always 1 */
343     return 3;
344 }
345
346 static void dv_format_frame(DVMuxContext *c, uint8_t* buf)
347 {
348     int i, j, k;
349     
350     for (i = 0; i < c->sys->difseg_size; i++) {
351        memset(buf, 0xff, 80 * 6); /* First 6 DIF blocks are for control data */
352        
353        /* DV header: 1DIF */
354        buf += dv_write_dif_id(dv_sect_header, i, 0, buf);
355        buf += dv_write_pack((c->sys->dsf ? dv_header625 : dv_header525), c, buf);
356        buf += 72; /* unused bytes */
357                                    
358        /* DV subcode: 2DIFs */
359        for (j = 0; j < 2; j++) {
360           buf += dv_write_dif_id( dv_sect_subcode, i, j, buf);
361           for (k = 0; k < 6; k++) {
362              buf += dv_write_ssyb_id(k, (i < c->sys->difseg_size/2), buf);
363              buf += dv_write_pack(dv_ssyb_packs_dist[i][k], c, buf);
364           }
365           buf += 29; /* unused bytes */
366        }
367        
368        /* DV VAUX: 3DIFs */
369        for (j = 0; j < 3; j++) {
370           buf += dv_write_dif_id(dv_sect_vaux, i, j, buf);
371           for (k = 0; k < 15 ; k++)
372              buf += dv_write_pack(dv_vaux_packs_dist[i][k], c, buf);
373           buf += 2; /* unused bytes */
374        } 
375        
376        /* DV Audio/Video: 135 Video DIFs + 9 Audio DIFs */
377        for (j = 0; j < 135; j++) {
378             if (j%15 == 0) {
379                 buf += dv_write_dif_id(dv_sect_audio, i, j/15, buf);
380                 buf += dv_write_pack(dv_aaux_packs_dist[i][j/15], c, buf);
381                 buf += 72; /* shuffled PCM audio */
382             }
383             buf += dv_write_dif_id(dv_sect_video, i, j, buf);
384             buf += 77; /* 1 video macro block: 1 bytes control
385                                                4 * 14 bytes Y 8x8 data
386                                                    10 bytes Cr 8x8 data
387                                                    10 bytes Cb 8x8 data */
388        }
389     }
390 }
391
392 static void dv_inject_audio(DVMuxContext *c, const uint8_t* pcm, uint8_t* frame_ptr)
393 {
394     int i, j, d, of, size;
395     size = 4 * dv_audio_frame_size(c->sys, c->frames);
396     for (i = 0; i < c->sys->difseg_size; i++) {
397        frame_ptr += 6 * 80; /* skip DIF segment header */
398        for (j = 0; j < 9; j++) {
399           for (d = 8; d < 80; d+=2) {
400              of = c->sys->audio_shuffle[i][j] + (d - 8)/2 * c->sys->audio_stride;
401              if (of*2 >= size)
402                  continue;
403              
404              frame_ptr[d] = pcm[of*2+1]; // FIXME: may be we have to admit
405              frame_ptr[d+1] = pcm[of*2]; //        that DV is a big endian PCM       
406           }
407           frame_ptr += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */
408        }
409     }
410 }
411
412 static void dv_inject_video(DVMuxContext *c, const uint8_t* video_data, uint8_t* frame_ptr)
413 {
414     int i, j;
415     int ptr = 0;
416
417     for (i = 0; i < c->sys->difseg_size; i++) {
418        ptr += 6 * 80; /* skip DIF segment header */
419        for (j = 0; j < 135; j++) {
420             if (j%15 == 0)
421                 ptr += 80; /* skip Audio DIF */
422             ptr += 3;
423             memcpy(frame_ptr + ptr, video_data + ptr, 77);
424             ptr += 77;
425        }
426     }
427 }
428
429 /* 
430  * This is the dumbest implementation of all -- it simply looks at
431  * a fixed offset and if pack isn't there -- fails. We might want
432  * to have a fallback mechanism for complete search of missing packs.
433  */
434 static const uint8_t* dv_extract_pack(uint8_t* frame, enum dv_pack_type t)
435 {
436     int offs;
437     
438     switch (t) {
439     case dv_audio_source:
440           offs = (80*6 + 80*16*3 + 3);
441           break;
442     case dv_audio_control:
443           offs = (80*6 + 80*16*4 + 3);
444           break;
445     case dv_video_control:
446           offs = (80*5 + 48 + 5);
447           break;
448     default:
449           return NULL;
450     }   
451
452     return (frame[offs] == t ? &frame[offs] : NULL);
453 }
454
455 /* 
456  * There's a couple of assumptions being made here:
457  * 1. By default we silence erroneous (0x8000/16bit 0x800/12bit) audio samples.
458  *    We can pass them upwards when ffmpeg will be ready to deal with them.
459  * 2. We don't do software emphasis.
460  * 3. Audio is always returned as 16bit linear samples: 12bit nonlinear samples
461  *    are converted into 16bit linear ones.
462  */
463 static int dv_extract_audio(uint8_t* frame, uint8_t* pcm, uint8_t* pcm2)
464 {
465     int size, i, j, d, of, smpls, freq, quant, half_ch;
466     uint16_t lc, rc;
467     const DVprofile* sys;
468     const uint8_t* as_pack;
469     
470     as_pack = dv_extract_pack(frame, dv_audio_source);
471     if (!as_pack)    /* No audio ? */
472         return 0;
473    
474     sys = dv_frame_profile(frame);
475     smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */
476     freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48KHz, 1 - 44,1kHz, 2 - 32 kHz */
477     quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */
478     
479     if (quant > 1)
480         return -1; /* Unsupported quantization */
481
482     size = (sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */
483     half_ch = sys->difseg_size/2;
484
485     /* for each DIF segment */
486     for (i = 0; i < sys->difseg_size; i++) {
487        frame += 6 * 80; /* skip DIF segment header */
488        if (quant == 1 && i == half_ch) {
489            if (!pcm2)
490                break;
491            else
492                pcm = pcm2;
493        }
494
495        for (j = 0; j < 9; j++) {
496           for (d = 8; d < 80; d += 2) {
497              if (quant == 0) {  /* 16bit quantization */
498                  of = sys->audio_shuffle[i][j] + (d - 8)/2 * sys->audio_stride;
499                  if (of*2 >= size)
500                      continue;
501                  
502                  pcm[of*2] = frame[d+1]; // FIXME: may be we have to admit
503                  pcm[of*2+1] = frame[d]; //        that DV is a big endian PCM
504                  if (pcm[of*2+1] == 0x80 && pcm[of*2] == 0x00)
505                      pcm[of*2+1] = 0;
506               } else {           /* 12bit quantization */
507                  lc = ((uint16_t)frame[d] << 4) | 
508                       ((uint16_t)frame[d+2] >> 4);
509                  rc = ((uint16_t)frame[d+1] << 4) |
510                       ((uint16_t)frame[d+2] & 0x0f);
511                  lc = (lc == 0x800 ? 0 : dv_audio_12to16(lc));
512                  rc = (rc == 0x800 ? 0 : dv_audio_12to16(rc));
513
514                  of = sys->audio_shuffle[i%half_ch][j] + (d - 8)/3 * sys->audio_stride;
515                  if (of*2 >= size)
516                      continue;
517
518                  pcm[of*2] = lc & 0xff; // FIXME: may be we have to admit
519                  pcm[of*2+1] = lc >> 8; //        that DV is a big endian PCM
520                  of = sys->audio_shuffle[i%half_ch+half_ch][j] + 
521                       (d - 8)/3 * sys->audio_stride;
522                  pcm[of*2] = rc & 0xff; // FIXME: may be we have to admit
523                  pcm[of*2+1] = rc >> 8; //        that DV is a big endian PCM
524                  ++d;
525               }
526           }
527                 
528           frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */
529         }
530     }
531
532     return size;
533 }
534
535 static int dv_extract_audio_info(DVDemuxContext* c, uint8_t* frame)
536 {
537     const uint8_t* as_pack;
538     const DVprofile* sys;
539     int freq, smpls, quant, i;
540
541     sys = dv_frame_profile(frame);
542     as_pack = dv_extract_pack(frame, dv_audio_source);
543     if (!as_pack || !sys) {    /* No audio ? */
544         c->ach = 0;
545         return -1;
546     }
547     
548     smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */
549     freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48KHz, 1 - 44,1kHz, 2 - 32 kHz */
550     quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */
551     c->ach = (quant && freq == 2) ? 2 : 1;
552
553     /* The second stereo channel could appear in IEC 61834 stream only */
554     if (c->ach == 2 && !c->ast[1]) {
555         c->ast[1] = av_new_stream(c->fctx, 0);
556         if (c->ast[1]) {
557             av_set_pts_info(c->ast[1], 64, 1, 30000);
558             c->ast[1]->codec.codec_type = CODEC_TYPE_AUDIO;
559             c->ast[1]->codec.codec_id = CODEC_ID_PCM_S16LE;
560         } else
561             c->ach = 1;
562     }
563     for (i=0; i<c->ach; i++) {
564        c->ast[i]->codec.sample_rate = dv_audio_frequency[freq];
565        c->ast[i]->codec.channels = 2;
566        c->ast[i]->codec.bit_rate = 2 * dv_audio_frequency[freq] * 16;
567     }
568     
569     return (sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */;
570 }
571
572 static int dv_extract_video_info(DVDemuxContext *c, uint8_t* frame)
573 {
574     const DVprofile* sys; 
575     const uint8_t* vsc_pack;
576     AVCodecContext* avctx;
577     int apt, is16_9;
578     int size = 0;
579     
580     sys = dv_frame_profile(frame);
581     if (sys) {
582         avctx = &c->vst->codec;
583         
584         avctx->frame_rate = sys->frame_rate;
585         avctx->frame_rate_base = sys->frame_rate_base;
586         avctx->width = sys->width;
587         avctx->height = sys->height;
588         avctx->pix_fmt = sys->pix_fmt;
589         
590         /* finding out SAR is a little bit messy */
591         vsc_pack = dv_extract_pack(frame, dv_video_control);
592         apt = frame[4] & 0x07;
593         is16_9 = (vsc_pack && ((vsc_pack[2] & 0x07) == 0x02 ||
594                                (!apt && (vsc_pack[2] & 0x07) == 0x07)));
595         avctx->sample_aspect_ratio = sys->sar[is16_9];
596         
597         size = sys->frame_size;
598     }
599     return size;
600 }
601
602 /* 
603  * The following 6 functions constitute our interface to the world
604  */
605
606 int dv_assemble_frame(DVMuxContext *c, AVStream* st,
607                       const uint8_t* data, int data_size, uint8_t** frame)
608 {
609     uint8_t pcm[8192];
610     int fsize, reqasize;
611    
612     *frame = &c->frame_buf[0];
613     if (c->has_audio && c->has_video) {  /* must be a stale frame */
614         dv_format_frame(c, *frame);
615         c->frames++;
616         c->has_audio = c->has_video = 0;
617     }
618     
619     if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
620         /* FIXME: we have to have more sensible approach than this one */
621         if (c->has_video)
622             av_log(&st->codec, AV_LOG_ERROR, "Can't process DV frame #%d. Insufficient audio data or severe sync problem.\n", c->frames);
623             
624         dv_inject_video(c, data, *frame);
625         c->has_video = 1;
626         data_size = 0;
627     } 
628     
629     reqasize = 4 * dv_audio_frame_size(c->sys, c->frames);
630     fsize = fifo_size(&c->audio_data, c->audio_data.rptr);
631     if (st->codec.codec_type == CODEC_TYPE_AUDIO || (c->has_video && fsize >= reqasize)) { 
632         if (fsize + data_size >= reqasize && !c->has_audio) {
633             if (fsize >= reqasize) {
634                 fifo_read(&c->audio_data, &pcm[0], reqasize, &c->audio_data.rptr);
635             } else {
636                 fifo_read(&c->audio_data, &pcm[0], fsize, &c->audio_data.rptr);
637                 memcpy(&pcm[fsize], &data[0], reqasize - fsize);
638                 data += reqasize - fsize;
639                 data_size -= reqasize - fsize;
640             }
641             dv_inject_audio(c, &pcm[0], *frame);
642             c->has_audio = 1;
643         }
644     
645         /* FIXME: we have to have more sensible approach than this one */
646         if (fifo_size(&c->audio_data, c->audio_data.rptr) + data_size >= 100*AVCODEC_MAX_AUDIO_FRAME_SIZE)
647             av_log(&st->codec, AV_LOG_ERROR, "Can't process DV frame #%d. Insufficient video data or severe sync problem.\n", c->frames);
648         fifo_write(&c->audio_data, (uint8_t *)data, data_size, &c->audio_data.wptr);
649     }
650
651     return (c->has_audio && c->has_video) ? c->sys->frame_size : 0;
652 }
653
654 DVMuxContext* dv_init_mux(AVFormatContext* s)
655 {
656     DVMuxContext *c;
657     AVStream *vst;
658     AVStream *ast;
659
660     c = av_mallocz(sizeof(DVMuxContext));
661     if (!c)
662         return NULL;
663
664     if (s->nb_streams != 2)
665         goto bail_out;
666
667     /* We have to sort out where audio and where video stream is */
668     if (s->streams[0]->codec.codec_type == CODEC_TYPE_VIDEO &&
669         s->streams[1]->codec.codec_type == CODEC_TYPE_AUDIO) {
670        vst = s->streams[0];
671        ast = s->streams[1];
672     }
673     else if (s->streams[1]->codec.codec_type == CODEC_TYPE_VIDEO &&
674              s->streams[0]->codec.codec_type == CODEC_TYPE_AUDIO) {
675            vst = s->streams[1];
676            ast = s->streams[0];
677     } else
678         goto bail_out;
679   
680     /* Some checks -- DV format is very picky about its incoming streams */
681     if (vst->codec.codec_id != CODEC_ID_DVVIDEO ||
682         ast->codec.codec_id != CODEC_ID_PCM_S16LE)
683        goto bail_out;
684     if (ast->codec.sample_rate != 48000 ||
685         ast->codec.channels != 2)
686        goto bail_out;
687
688     c->sys = dv_codec_profile(&vst->codec);
689     if (!c->sys)
690         goto bail_out;
691     
692     /* Ok, everything seems to be in working order */
693     c->frames = 0;
694     c->has_audio = c->has_video = 0;
695     c->start_time = (time_t)s->timestamp;
696     c->aspect = 0; /* 4:3 is the default */
697     if ((int)(av_q2d(vst->codec.sample_aspect_ratio) * vst->codec.width / vst->codec.height * 10) == 17) /* 16:9 */ 
698         c->aspect = 0x07;
699
700     if (fifo_init(&c->audio_data, 100*AVCODEC_MAX_AUDIO_FRAME_SIZE) < 0)
701         goto bail_out;
702
703     dv_format_frame(c, &c->frame_buf[0]);
704
705     return c;
706     
707 bail_out:
708     av_free(c);
709     return NULL;
710 }
711
712 void dv_delete_mux(DVMuxContext *c)
713 {    
714     fifo_free(&c->audio_data);
715 }
716
717 DVDemuxContext* dv_init_demux(AVFormatContext *s)
718 {
719     DVDemuxContext *c;
720
721     c = av_mallocz(sizeof(DVDemuxContext));
722     if (!c)
723         return NULL;
724
725     c->vst = av_new_stream(s, 0);
726     c->ast[0] = av_new_stream(s, 0);
727     if (!c->vst || !c->ast[0])
728         goto fail;
729     av_set_pts_info(c->vst, 64, 1, 30000);
730     av_set_pts_info(c->ast[0], 64, 1, 30000);
731
732     c->fctx = s;
733     c->ast[1] = NULL;
734     c->ach = 0;
735     c->frames = 0;
736     c->abytes = 0;
737     c->audio_pkt[0].size = 0;
738     c->audio_pkt[1].size = 0;
739     
740     c->vst->codec.codec_type = CODEC_TYPE_VIDEO;
741     c->vst->codec.codec_id = CODEC_ID_DVVIDEO;
742     c->vst->codec.bit_rate = 25000000;
743     
744     c->ast[0]->codec.codec_type = CODEC_TYPE_AUDIO;
745     c->ast[0]->codec.codec_id = CODEC_ID_PCM_S16LE;
746    
747     s->ctx_flags |= AVFMTCTX_NOHEADER; 
748     
749     return c;
750     
751 fail:
752     if (c->vst)
753         av_free(c->vst);
754     if (c->ast[0])
755         av_free(c->ast[0]);
756     av_free(c);
757     return NULL;
758 }
759
760 static void __destruct_pkt(struct AVPacket *pkt)
761 {
762     pkt->data = NULL; pkt->size = 0;
763     return;
764 }
765
766 int dv_get_packet(DVDemuxContext *c, AVPacket *pkt)
767 {
768     int size = -1;
769     int i;
770
771     for (i=0; i<c->ach; i++) {
772        if (c->ast[i] && c->audio_pkt[i].size) {
773            *pkt = c->audio_pkt[i];
774            c->audio_pkt[i].size = 0;
775            size = pkt->size;
776            break;
777        }
778     }
779
780     return size;
781 }
782
783 int dv_produce_packet(DVDemuxContext *c, AVPacket *pkt, 
784                       uint8_t* buf, int buf_size)
785 {
786     int size, i;
787     const DVprofile* sys = dv_frame_profile(buf);
788    
789     if (buf_size < 4 || buf_size < sys->frame_size)
790         return -1;   /* Broken frame, or not enough data */
791
792     /* Queueing audio packet */
793     /* FIXME: in case of no audio/bad audio we have to do something */
794     size = dv_extract_audio_info(c, buf);
795     c->audio_pkt[0].data = c->audio_pkt[1].data = NULL;
796     for (i=0; i<c->ach; i++) {
797        if (av_new_packet(&c->audio_pkt[i], size) < 0)
798            return AVERROR_NOMEM;
799        c->audio_pkt[i].stream_index = c->ast[i]->index;
800        c->audio_pkt[i].pts = c->abytes * 30000*8 / c->ast[i]->codec.bit_rate;
801        c->audio_pkt[i].flags |= PKT_FLAG_KEY;
802     }
803     dv_extract_audio(buf, c->audio_pkt[0].data, c->audio_pkt[1].data);
804     c->abytes += size;
805     
806     /* Now it's time to return video packet */
807     size = dv_extract_video_info(c, buf);
808     av_init_packet(pkt);
809     pkt->destruct = __destruct_pkt;
810     pkt->data     = buf;
811     pkt->size     = size; 
812     pkt->flags   |= PKT_FLAG_KEY;
813     pkt->stream_index = c->vst->id;
814     pkt->pts      = c->frames * sys->frame_rate_base * (30000/sys->frame_rate);
815     
816     c->frames++;
817
818     return size;
819 }
820                            
821 int64_t dv_frame_offset(DVDemuxContext *c, int64_t timestamp)
822 {
823     const DVprofile* sys = dv_codec_profile(&c->vst->codec);
824
825     return sys->frame_size * ((timestamp * sys->frame_rate) / 
826                               (AV_TIME_BASE * sys->frame_rate_base));
827 }
828
829 /************************************************************
830  * Implementation of the easiest DV storage of all -- raw DV.
831  ************************************************************/
832  
833 typedef struct RawDVContext {
834     uint8_t         buf[144000];
835     DVDemuxContext* dv_demux;
836 } RawDVContext;
837
838 static int dv_read_header(AVFormatContext *s,
839                           AVFormatParameters *ap)
840 {
841     RawDVContext *c = s->priv_data;
842     c->dv_demux = dv_init_demux(s);
843    
844     return c->dv_demux ? 0 : -1;
845 }
846
847
848 static int dv_read_packet(AVFormatContext *s, AVPacket *pkt)
849 {
850     int size;
851     RawDVContext *c = s->priv_data; 
852   
853     size = dv_get_packet(c->dv_demux, pkt);
854     
855     if (size < 0) {
856         if (get_buffer(&s->pb, c->buf, 4) <= 0) 
857             return AVERROR_IO;
858     
859         size = dv_frame_profile(c->buf)->frame_size;
860         if (get_buffer(&s->pb, c->buf + 4, size - 4) <= 0)
861             return AVERROR_IO;
862
863         size = dv_produce_packet(c->dv_demux, pkt, c->buf, size);
864     } 
865     
866     return size;
867 }
868
869 static int dv_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp)
870 {
871     RawDVContext *c = s->priv_data;
872
873     return url_fseek(&s->pb, dv_frame_offset(c->dv_demux, timestamp), SEEK_SET);
874 }
875
876 static int dv_read_close(AVFormatContext *s)
877 {
878     RawDVContext *c = s->priv_data;
879     av_free(c->dv_demux);
880     return 0;
881 }
882
883 static int dv_write_header(AVFormatContext *s)
884 {
885     s->priv_data = dv_init_mux(s);
886     if (!s->priv_data) {
887         av_log(s, AV_LOG_ERROR, "Can't initialize DV format!\n"
888                     "Make sure that you supply exactly two streams:\n"
889                     "     video: 25fps or 29.97fps, audio: 2ch/48Khz/PCM\n");
890         return -1;
891     }
892     return 0;
893 }
894
895 static int dv_write_packet(struct AVFormatContext *s, AVPacket *pkt)
896 {
897     uint8_t* frame;
898     int fsize;
899    
900     fsize = dv_assemble_frame((DVMuxContext *)s->priv_data, s->streams[pkt->stream_index],
901                               pkt->data, pkt->size, &frame);
902     if (fsize > 0) {
903         put_buffer(&s->pb, frame, fsize); 
904         put_flush_packet(&s->pb);
905     } 
906     return 0;
907 }
908
909 /* 
910  * We might end up with some extra A/V data without matching counterpart.
911  * E.g. video data without enough audio to write the complete frame.
912  * Currently we simply drop the last frame. I don't know whether this 
913  * is the best strategy of all
914  */
915 static int dv_write_trailer(struct AVFormatContext *s)
916 {
917     dv_delete_mux((DVMuxContext *)s->priv_data);
918     return 0;
919 }
920
921 static AVInputFormat dv_iformat = {
922     "dv",
923     "DV video format",
924     sizeof(RawDVContext),
925     NULL,
926     dv_read_header,
927     dv_read_packet,
928     dv_read_close,
929     dv_read_seek,
930     .extensions = "dv,dif",
931 };
932
933 static AVOutputFormat dv_oformat = {
934     "dv",
935     "DV video format",
936     NULL,
937     "dv",
938     sizeof(DVMuxContext),
939     CODEC_ID_PCM_S16LE,
940     CODEC_ID_DVVIDEO,
941     dv_write_header,
942     dv_write_packet,
943     dv_write_trailer,
944 };
945
946 int ff_dv_init(void)
947 {
948     av_register_input_format(&dv_iformat);
949     av_register_output_format(&dv_oformat);
950     return 0;
951 }