Fix bugs in previous commit that caused FTBFS in synfig and ETL FTBFS with older...
[synfig.git] / synfig-core / tags / synfig_0_61_03 / synfig-core / src / modules / mod_libavcodec / libavformat / dvcore.c
1 /* 
2  * DV format 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  * This library 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 of the License, or (at your option) any later version.
12  *
13  * This library 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 this library; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22 #include "avformat.h"
23 #include "dvcore.h"
24
25 /*
26  * The reason why the following three big ugly looking tables are
27  * here is my lack of DV spec IEC 61834. The tables were basically 
28  * constructed to make code that places packs in SSYB, VAUX and 
29  * AAUX blocks very simple and table-driven. They conform to the
30  * SMPTE 314M and the output of my personal DV camcorder, neither
31  * of which is sufficient for a reliable DV stream producing. Thus
32  * while code is still in development I'll be gathering input from
33  * people with different DV equipment and modifying the tables to
34  * accommodate all the quirks. Later on, if possible, some of them
35  * will be folded into smaller tables and/or switch-if logic. For 
36  * now, my only excuse is -- they don't eat up that much of a space.
37  */
38
39 static const int dv_ssyb_packs_dist[12][6] = {
40     { 0x13, 0x13, 0x13, 0x13, 0x13, 0x13 },
41     { 0x13, 0x13, 0x13, 0x13, 0x13, 0x13 },
42     { 0x13, 0x13, 0x13, 0x13, 0x13, 0x13 },
43     { 0x13, 0x13, 0x13, 0x13, 0x13, 0x13 },
44     { 0x13, 0x13, 0x13, 0x13, 0x13, 0x13 },
45     { 0x13, 0x13, 0x13, 0x13, 0x13, 0x13 },
46     { 0x13, 0x62, 0x63, 0x13, 0x62, 0x63 },
47     { 0x13, 0x62, 0x63, 0x13, 0x62, 0x63 },
48     { 0x13, 0x62, 0x63, 0x13, 0x62, 0x63 },
49     { 0x13, 0x62, 0x63, 0x13, 0x62, 0x63 },
50     { 0x13, 0x62, 0x63, 0x13, 0x62, 0x63 },
51     { 0x13, 0x62, 0x63, 0x13, 0x62, 0x63 },
52 };
53
54 static const int dv_vaux_packs_dist[12][15] = {
55     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
56       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
57     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
58       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
59     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
60       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
61     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
62       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
63     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
64       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
65     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
66       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
67     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
68       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
69     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
70       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
71     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
72       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
73     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
74       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
75     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
76       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
77     { 0x60, 0x61, 0x62, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 
78       0x60, 0x61, 0x62, 0x63, 0xff, 0xff },
79 };
80
81 static const int dv_aaux_packs_dist[12][9] = {
82     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
83     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
84     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
85     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
86     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
87     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
88     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
89     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
90     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
91     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
92     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
93     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
94 };
95
96 enum dv_section_type {
97      dv_sect_header  = 0x1f,
98      dv_sect_subcode = 0x3f,
99      dv_sect_vaux    = 0x56,
100      dv_sect_audio   = 0x76,
101      dv_sect_video   = 0x96,
102 };
103
104 enum dv_pack_type {
105      dv_header525     = 0x3f, /* see dv_write_pack for important details on */ 
106      dv_header625     = 0xbf, /* these two packs */
107      dv_timecode      = 0x13,
108      dv_audio_source  = 0x50,
109      dv_audio_control = 0x51,
110      dv_audio_recdate = 0x52,
111      dv_audio_rectime = 0x53,
112      dv_video_source  = 0x60,
113      dv_video_control = 0x61,
114      dv_viedo_recdate = 0x62,
115      dv_video_rectime = 0x63,
116      dv_unknown_pack  = 0xff,
117 };
118
119 static const uint16_t dv_audio_shuffle525[10][9] = {
120   {  0, 30, 60, 20, 50, 80, 10, 40, 70 }, /* 1st channel */
121   {  6, 36, 66, 26, 56, 86, 16, 46, 76 },
122   { 12, 42, 72,  2, 32, 62, 22, 52, 82 },
123   { 18, 48, 78,  8, 38, 68, 28, 58, 88 },
124   { 24, 54, 84, 14, 44, 74,  4, 34, 64 },
125   
126   {  1, 31, 61, 21, 51, 81, 11, 41, 71 }, /* 2nd channel */
127   {  7, 37, 67, 27, 57, 87, 17, 47, 77 },
128   { 13, 43, 73,  3, 33, 63, 23, 53, 83 },
129   { 19, 49, 79,  9, 39, 69, 29, 59, 89 },
130   { 25, 55, 85, 15, 45, 75,  5, 35, 65 },
131 };
132
133 static const uint16_t dv_audio_shuffle625[12][9] = {
134   {   0,  36,  72,  26,  62,  98,  16,  52,  88}, /* 1st channel */
135   {   6,  42,  78,  32,  68, 104,  22,  58,  94},
136   {  12,  48,  84,   2,  38,  74,  28,  64, 100},
137   {  18,  54,  90,   8,  44,  80,  34,  70, 106},
138   {  24,  60,  96,  14,  50,  86,   4,  40,  76},  
139   {  30,  66, 102,  20,  56,  92,  10,  46,  82},
140         
141   {   1,  37,  73,  27,  63,  99,  17,  53,  89}, /* 2nd channel */
142   {   7,  43,  79,  33,  69, 105,  23,  59,  95},
143   {  13,  49,  85,   3,  39,  75,  29,  65, 101},
144   {  19,  55,  91,   9,  45,  81,  35,  71, 107},
145   {  25,  61,  97,  15,  51,  87,   5,  41,  77},  
146   {  31,  67, 103,  21,  57,  93,  11,  47,  83},
147 };
148
149 static const int dv_audio_frequency[3] = {
150     48000, 44100, 32000,
151 };
152     
153 const DVprofile dv_profiles[2] = {
154     { .dsf = 0,
155       .frame_size = 120000,        /* 525/60 system (NTSC) */
156       .difseg_size = 10,
157       .frame_rate = 30000,
158       .ltc_divisor = 30,
159       .frame_rate_base = 1001,
160       .height = 480,
161 /*    .video_place = dv_place_411, */
162       .audio_stride = 90,
163       .audio_min_samples = { 1580, 1452, 1053 }, /* for 48, 44.1 and 32Khz */
164       .audio_samples_dist = { 1602, 1601, 1602, 1601, 1602 },
165       .audio_shuffle = dv_audio_shuffle525,
166     }, 
167     { .dsf = 1,
168       .frame_size = 144000,        /* 625/50 system (PAL) */
169       .difseg_size = 12,
170       .frame_rate = 25,
171       .frame_rate_base = 1,
172       .ltc_divisor = 25,
173       .height = 576,
174 /*    .video_place = dv_place_420, */
175       .audio_stride = 108,
176       .audio_min_samples = { 1896, 1742, 1264 }, /* for 48, 44.1 and 32Khz */
177       .audio_samples_dist = { 1920, 1920, 1920, 1920, 1920 },
178       .audio_shuffle = dv_audio_shuffle525,
179      }
180 };
181
182 static inline uint16_t dv_audio_12to16(uint16_t sample)
183 {
184     uint16_t shift, result;
185     
186     sample = (sample < 0x800) ? sample : sample | 0xf000;
187     shift = (sample & 0xf00) >> 8;
188
189     if (shift < 0x2 || shift > 0xd) {
190         result = sample;
191     } else if (shift < 0x8) {
192         shift--;
193         result = (sample - (256 * shift)) << shift;
194     } else {
195         shift = 0xe - shift;
196         result = ((sample + ((256 * shift) + 1)) << shift) - 1;
197     }
198
199     return result;
200 }
201
202 static int dv_write_pack(enum dv_pack_type pack_id, DVMuxContext *c, uint8_t* buf)
203 {
204     struct tm tc;
205     time_t ct;
206     int ltc_frame;
207
208     buf[0] = (uint8_t)pack_id;
209     switch (pack_id) {
210     case dv_header525: /* I can't imagine why these two weren't defined as real */
211     case dv_header625: /* packs in SMPTE314M -- they definitely look like ones */
212           buf[1] = 0xf8 |               /* reserved -- always 1 */
213                    (0 & 0x07);          /* APT: Track application ID */
214           buf[2] = (0 << 7)    | /* TF1: audio data is 0 - valid; 1 - invalid */
215                    (0x0f << 3) | /* reserved -- always 1 */
216                    (0 & 0x07);   /* AP1: Audio application ID */
217           buf[3] = (0 << 7)    | /* TF2: video data is 0 - valid; 1 - invalid */  
218                    (0x0f << 3) | /* reserved -- always 1 */
219                    (0 & 0x07);   /* AP2: Video application ID */
220           buf[4] = (0 << 7)    | /* TF3: subcode(SSYB) is 0 - valid; 1 - invalid */ 
221                    (0x0f << 3) | /* reserved -- always 1 */
222                    (0 & 0x07);   /* AP3: Subcode application ID */
223           break;
224     case dv_timecode:
225           ct = (time_t)(c->frames / ((float)c->sys->frame_rate / 
226                                      (float)c->sys->frame_rate_base));
227           localtime_r(&ct, &tc);
228           /* 
229            * LTC drop-frame frame counter drops two frames (0 and 1) every 
230            * minute, unless it is exactly divisible by 10
231            */
232           ltc_frame = (c->frames + 2*ct/60 - 2*ct/600) % c->sys->ltc_divisor;
233           buf[1] = (0 << 7) | /* Color fame: 0 - unsync; 1 - sync mode */
234                    (1 << 6) | /* Drop frame timecode: 0 - nondrop; 1 - drop */
235                    ((ltc_frame / 10) << 4) | /* Tens of frames */
236                    (ltc_frame % 10);         /* Units of frames */
237           buf[2] = (1 << 7) | /* Biphase mark polarity correction: 0 - even; 1 - odd */
238                    ((tc.tm_sec / 10) << 4) | /* Tens of seconds */
239                    (tc.tm_sec % 10);         /* Units of seconds */
240           buf[3] = (1 << 7) | /* Binary group flag BGF0 */
241                    ((tc.tm_min / 10) << 4) | /* Tens of minutes */
242                    (tc.tm_min % 10);         /* Units of minutes */
243           buf[4] = (1 << 7) | /* Binary group flag BGF2 */
244                    (1 << 6) | /* Binary group flag BGF1 */
245                    ((tc.tm_hour / 10) << 4) | /* Tens of hours */
246                    (tc.tm_hour % 10);         /* Units of hours */
247           break;
248     case dv_audio_source:  /* AAUX source pack */
249           buf[1] = (0 << 7) | /* locked mode       */
250                    (1 << 6) | /* reserved -- always 1 */
251                    (dv_audio_frame_size(c->sys, c->frames) -
252                     c->sys->audio_min_samples[0]);
253                               /* # of samples      */
254           buf[2] = (0 << 7) | /* multi-stereo      */
255                    (0 << 5) | /* #of audio channels per block: 0 -- 1 channel */
256                    (0 << 4) | /* pair bit: 0 -- one pair of channels */
257                     0;        /* audio mode        */
258           buf[3] = (1 << 7) | /* res               */
259                    (1 << 6) | /* multi-language flag */
260                    (c->sys->dsf << 5) | /*  system: 60fields/50fields */
261                     0;        /* definition: 0 -- SD (525/625) */
262           buf[4] = (1 << 7) | /* emphasis: 1 -- off */
263                    (0 << 6) | /* emphasis time constant: 0 -- reserved */
264                    (0 << 3) | /* frequency: 0 -- 48Khz, 1 -- 44,1Khz, 2 -- 32Khz */
265                     0;        /* quantization: 0 -- 16bit linear, 1 -- 12bit nonlinear */                           
266           break;
267     case dv_audio_control:
268           buf[1] = (0 << 6) | /* copy protection: 0 -- unrestricted */
269                    (1 << 4) | /* input source: 1 -- digital input */
270                    (3 << 2) | /* compression: 3 -- no information */
271                     0;        /* misc. info/SMPTE emphasis off */
272           buf[2] = (1 << 7) | /* recording start point: 1 -- no */
273                    (1 << 6) | /* recording end point: 1 -- no */
274                    (1 << 3) | /* recording mode: 1 -- original */
275                     7;         
276           buf[3] = (1 << 7) | /* direction: 1 -- forward */
277                     0x20;     /* speed */
278           buf[4] = (1 << 7) | /* reserved -- always 1 */
279                     0x7f;     /* genre category */
280           break;
281     case dv_audio_recdate:
282     case dv_viedo_recdate:  /* VAUX recording date */
283           ct = c->start_time + (time_t)(c->frames / 
284                ((float)c->sys->frame_rate / (float)c->sys->frame_rate_base));
285           localtime_r(&ct, &tc);
286           buf[1] = 0xff; /* ds, tm, tens of time zone, units of time zone */
287                          /* 0xff is very likely to be "unknown" */
288           buf[2] = (3 << 6) | /* reserved -- always 1 */
289                    ((tc.tm_mday / 10) << 4) | /* Tens of day */
290                    (tc.tm_mday % 10);         /* Units of day */
291           buf[3] = /* we set high 4 bits to 0, shouldn't we set them to week? */
292                    (tc.tm_mon % 10);         /* Units of month */
293           buf[4] = (((tc.tm_year % 100) / 10) << 4) | /* Tens of year */
294                    (tc.tm_year % 10);                 /* Units of year */
295           break;
296     case dv_audio_rectime:  /* AAUX recording time */
297     case dv_video_rectime:  /* VAUX recording time */
298           ct = c->start_time + (time_t)(c->frames / 
299                ((float)c->sys->frame_rate / (float)c->sys->frame_rate_base));
300           localtime_r(&ct, &tc);
301           buf[1] = (3 << 6) | /* reserved -- always 1 */
302                    0x3f; /* tens of frame, units of frame: 0x3f - "unknown" ? */
303           buf[2] = (1 << 7) | /* reserved -- always 1 */ 
304                    ((tc.tm_sec / 10) << 4) | /* Tens of seconds */
305                    (tc.tm_sec % 10);         /* Units of seconds */
306           buf[3] = (1 << 7) | /* reserved -- always 1 */
307                    ((tc.tm_min / 10) << 4) | /* Tens of minutes */
308                    (tc.tm_min % 10);         /* Units of minutes */
309           buf[4] = (3 << 6) | /* reserved -- always 1 */ 
310                    ((tc.tm_hour / 10) << 4) | /* Tens of hours */
311                    (tc.tm_hour % 10);         /* Units of hours */
312           break;
313     case dv_video_source:
314           buf[1] = 0xff; /* reserved -- always 1 */
315           buf[2] = (1 << 7) | /* B/W: 0 - b/w, 1 - color */
316                    (1 << 6) | /* following CLF is valid - 0, invalid - 1 */
317                    (3 << 4) | /* CLF: color frames id (see ITU-R BT.470-4) */
318                    0xf; /* reserved -- always 1 */
319           buf[3] = (3 << 6) | /* reserved -- always 1 */
320                    (c->sys->dsf << 5) | /*  system: 60fields/50fields */
321                    0; /* signal type video compression */
322           buf[4] = 0xff; /* VISC: 0xff -- no information */
323           break;
324     case dv_video_control:
325           buf[1] = (0 << 6) | /* Copy generation management (CGMS) 0 -- free */
326                    0x3f; /* reserved -- always 1 */
327           buf[2] = 0xc8 | /* reserved -- always b11001xxx */
328                    c->aspect;
329           buf[3] = (1 << 7) | /* Frame/field flag 1 -- frame, 0 -- field */
330                    (1 << 6) | /* First/second field flag 0 -- field 2, 1 -- field 1 */
331                    (1 << 5) | /* Frame change flag 0 -- same picture as before, 1 -- different */
332                    (1 << 4) | /* 1 - interlaced, 0 - noninterlaced */
333                    0xc; /* reserved -- always b1100 */
334           buf[4] = 0xff; /* reserved -- always 1 */
335           break;
336     default:
337           buf[1] = buf[2] = buf[3] = buf[4] = 0xff;
338     }
339     return 5;
340 }
341
342 static inline int dv_write_dif_id(enum dv_section_type t, uint8_t seq_num, 
343                                   uint8_t dif_num, uint8_t* buf)
344 {
345     buf[0] = (uint8_t)t;    /* Section type */
346     buf[1] = (seq_num<<4) | /* DIF seq number 0-9 for 525/60; 0-11 for 625/50 */
347              (0 << 3) |     /* FSC: for 50Mb/s 0 - first channel; 1 - second */
348              7;             /* reserved -- always 1 */
349     buf[2] = dif_num;       /* DIF block number Video: 0-134, Audio: 0-8 */
350     return 3;
351 }
352
353 static inline int dv_write_ssyb_id(uint8_t syb_num, uint8_t fr, uint8_t* buf)
354 {
355     if (syb_num == 0 || syb_num == 6) {
356         buf[0] = (fr<<7) | /* FR ID 1 - first half of each channel; 0 - second */
357                  (0<<4)  | /* AP3 (Subcode application ID) */
358                  0x0f;     /* reserved -- always 1 */
359     } 
360     else if (syb_num == 11) {
361         buf[0] = (fr<<7) | /* FR ID 1 - first half of each channel; 0 - second */
362                  0x7f;     /* reserved -- always 1 */
363     }
364     else {
365         buf[0] = (fr<<7) | /* FR ID 1 - first half of each channel; 0 - second */
366                  (0<<4)  | /* APT (Track application ID) */
367                  0x0f;     /* reserved -- always 1 */
368     }
369     buf[1] = 0xf0 |            /* reserved -- always 1 */
370              (syb_num & 0x0f); /* SSYB number 0 - 11   */
371     buf[2] = 0xff;             /* reserved -- always 1 */
372     return 3;
373 }
374
375 void dv_format_frame(DVMuxContext *c, uint8_t* buf)
376 {
377     int i, j, k;
378     
379     for (i = 0; i < c->sys->difseg_size; i++) {
380        memset(buf, 0xff, 80 * 6); /* First 6 DIF blocks are for control data */
381        
382        /* DV header: 1DIF */
383        buf += dv_write_dif_id(dv_sect_header, i, 0, buf);
384        buf += dv_write_pack((c->sys->dsf ? dv_header625 : dv_header525), c, buf);
385        buf += 72; /* unused bytes */
386                                    
387        /* DV subcode: 2DIFs */
388        for (j = 0; j < 2; j++) {
389           buf += dv_write_dif_id( dv_sect_subcode, i, j, buf);
390           for (k = 0; k < 6; k++) {
391              buf += dv_write_ssyb_id(k, (i < c->sys->difseg_size/2), buf);
392              buf += dv_write_pack(dv_ssyb_packs_dist[i][k], c, buf);
393           }
394           buf += 29; /* unused bytes */
395        }
396        
397        /* DV VAUX: 3DIFs */
398        for (j = 0; j < 3; j++) {
399           buf += dv_write_dif_id(dv_sect_vaux, i, j, buf);
400           for (k = 0; k < 15 ; k++)
401              buf += dv_write_pack(dv_vaux_packs_dist[i][k], c, buf);
402           buf += 2; /* unused bytes */
403        } 
404        
405        /* DV Audio/Video: 135 Video DIFs + 9 Audio DIFs */
406        for (j = 0; j < 135; j++) {
407             if (j%15 == 0) {
408                 buf += dv_write_dif_id(dv_sect_audio, i, j/15, buf);
409                 buf += dv_write_pack(dv_aaux_packs_dist[i][j/15], c, buf);
410                 buf += 72; /* shuffled PCM audio */
411             }
412             buf += dv_write_dif_id(dv_sect_video, i, j, buf);
413             buf += 77; /* 1 video macro block: 1 bytes control
414                                                4 * 14 bytes Y 8x8 data
415                                                    10 bytes Cr 8x8 data
416                                                    10 bytes Cb 8x8 data */
417        }
418     }
419 }
420
421 void dv_inject_audio(DVMuxContext *c, const uint8_t* pcm, uint8_t* frame_ptr)
422 {
423     int i, j, d, of;
424     for (i = 0; i < c->sys->difseg_size; i++) {
425        frame_ptr += 6 * 80; /* skip DIF segment header */
426        for (j = 0; j < 9; j++) {
427           for (d = 8; d < 80; d+=2) {
428              of = c->sys->audio_shuffle[i][j] + (d - 8)/2 * c->sys->audio_stride;
429              frame_ptr[d] = pcm[of*2+1]; // FIXME: may be we have to admit
430              frame_ptr[d+1] = pcm[of*2]; //        that DV is a big endian PCM       
431           }
432           frame_ptr += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */
433        }
434     }
435 }
436
437 void dv_inject_video(DVMuxContext *c, const uint8_t* video_data, uint8_t* frame_ptr)
438 {
439     int i, j;
440     int ptr = 0;
441
442     for (i = 0; i < c->sys->difseg_size; i++) {
443        ptr += 6 * 80; /* skip DIF segment header */
444        for (j = 0; j < 135; j++) {
445             if (j%15 == 0)
446                 ptr += 80; /* skip Audio DIF */
447             ptr += 3;
448             memcpy(frame_ptr + ptr, video_data + ptr, 77);
449             ptr += 77;
450        }
451     }
452 }
453
454 int dv_audio_frame_size(const DVprofile* sys, int frame)
455 {
456     return sys->audio_samples_dist[frame % (sizeof(sys->audio_samples_dist)/
457                                             sizeof(sys->audio_samples_dist[0]))];
458 }
459
460 const DVprofile* dv_frame_profile(uint8_t* frame)
461 {
462     return &dv_profiles[!!(frame[3] & 0x80)]; /* Header, DSF flag */
463 }
464
465 /* 
466  * This is the dumbest implementation of all -- it simply looks at
467  * a fixed offset and if pack isn't there -- fails. We might want
468  * to have a fallback mechanism for complete search of missing packs.
469  */
470 const uint8_t* dv_extract_pack(uint8_t* frame, enum dv_pack_type t)
471 {
472     int offs;
473     
474     switch (t) {
475     case dv_audio_source:
476           offs = (80*6 + 80*16*3 + 3);
477           break;
478     case dv_audio_control:
479           offs = (80*6 + 80*16*4 + 3);
480           break;
481     case dv_video_control:
482           offs = (80*5 + 48 + 5);
483           break;
484     default:
485           return NULL;
486     }   
487
488     return (frame[offs] == t ? &frame[offs] : NULL);
489 }
490
491 /* 
492  * There's a couple of assumptions being made here:
493  * 1. By default we silence erroneous (0x8000/16bit 0x800/12bit) audio samples.
494  *    We can pass them upwards when ffmpeg will be ready to deal with them.
495  * 2. We don't do software emphasis.
496  * 3. Audio is always returned as 16bit linear samples: 12bit nonlinear samples
497  *    are converted into 16bit linear ones.
498  */
499 int dv_extract_audio(uint8_t* frame, uint8_t* pcm, AVCodecContext* avctx)
500 {
501     int size, i, j, d, of, smpls, freq, quant;
502     uint16_t lc, rc;
503     const DVprofile* sys;
504     const uint8_t* as_pack;
505     
506     as_pack = dv_extract_pack(frame, dv_audio_source);
507     if (!as_pack)    /* No audio ? */
508         return 0;
509    
510     sys = dv_frame_profile(frame);
511     smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */
512     freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48KHz, 1 - 44,1kHz, 2 - 32 kHz */
513     quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */
514     
515     if (quant > 1)
516         return -1; /* Unsupported quantization */
517
518     avctx->sample_rate = dv_audio_frequency[freq];
519     avctx->channels = 2;
520     avctx->bit_rate = avctx->channels * avctx->sample_rate * 16;
521     // What about:
522     // avctx->frame_size =
523    
524     size = (sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */
525
526     /* for each DIF segment */
527     for (i = 0; i < sys->difseg_size; i++) {
528        frame += 6 * 80; /* skip DIF segment header */
529        for (j = 0; j < 9; j++) {
530           for (d = 8; d < 80; d += 2) {
531              if (quant == 0) {  /* 16bit quantization */
532                  of = sys->audio_shuffle[i][j] + (d - 8)/2 * sys->audio_stride;
533                  pcm[of*2] = frame[d+1]; // FIXME: may be we have to admit
534                  pcm[of*2+1] = frame[d]; //        that DV is a big endian PCM
535                  if (pcm[of*2+1] == 0x80 && pcm[of*2] == 0x00)
536                      pcm[of*2+1] = 0;
537               } else {           /* 12bit quantization */
538                  if (i >= sys->difseg_size/2)
539                      goto out;  /* We're not doing 4ch at this time */
540                        
541                  lc = ((uint16_t)frame[d] << 4) | 
542                       ((uint16_t)frame[d+2] >> 4);
543                  rc = ((uint16_t)frame[d+1] << 4) |
544                       ((uint16_t)frame[d+2] & 0x0f);
545                  lc = (lc == 0x800 ? 0 : dv_audio_12to16(lc));
546                  rc = (rc == 0x800 ? 0 : dv_audio_12to16(rc));
547
548                  of = sys->audio_shuffle[i][j] + (d - 8)/3 * sys->audio_stride;
549                  pcm[of*2] = lc & 0xff; // FIXME: may be we have to admit
550                  pcm[of*2+1] = lc >> 8; //        that DV is a big endian PCM
551                  of = sys->audio_shuffle[i+sys->difseg_size/2][j] + 
552                       (d - 8)/3 * sys->audio_stride;
553                  pcm[of*2] = rc & 0xff; // FIXME: may be we have to admit
554                  pcm[of*2+1] = rc >> 8; //        that DV is a big endian PCM
555                  ++d;
556               }
557           }
558                 
559           frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */
560         }
561     }
562
563 out:
564     return size;
565 }
566
567 /* FIXME: The following three functions could be underengineered ;-) */
568 void dv_assemble_frame(DVMuxContext *c, const uint8_t* video, const uint8_t* audio, int asize)
569 {
570     uint8_t pcm[8192];
571     uint8_t* frame = &c->frame_buf[0];
572     int fsize, reqasize;
573    
574     if (c->has_audio && c->has_video) {  /* must be a stale frame */
575         dv_format_frame(c, frame);
576         c->frames++;
577         c->has_audio = c->has_video = 0;
578     }
579     
580     if (video) {
581         /* FIXME: we have to have more sensible approach than this one */
582         if (c->has_video)
583             fprintf(stderr, "Can't process DV frame #%d. Insufficient audio data or severe sync problem.\n", c->frames);
584             
585         dv_inject_video(c, video, frame);
586         c->has_video = 1;
587     } 
588     if (audio) {
589         reqasize = 4 * dv_audio_frame_size(c->sys, c->frames);
590         fsize = fifo_size(&c->audio_data, c->audio_data.rptr);
591         if (fsize + asize >= reqasize) {
592             if (fsize >= reqasize) {
593                 fifo_read(&c->audio_data, &pcm[0], reqasize, &c->audio_data.rptr);
594             } else {
595                 fifo_read(&c->audio_data, &pcm[0], fsize, &c->audio_data.rptr);
596                 memcpy(&pcm[fsize], &audio[0], reqasize - fsize);
597                 audio += reqasize - fsize;
598                 asize -= reqasize - fsize;
599             }
600             dv_inject_audio(c, &pcm[0], frame);
601             c->has_audio = 1;
602         }
603     
604         /* FIXME: we have to have more sensible approach than this one */
605         if (fifo_size(&c->audio_data, c->audio_data.rptr) + asize >= AVCODEC_MAX_AUDIO_FRAME_SIZE)
606             fprintf(stderr, "Can't process DV frame #%d. Insufficient video data or severe sync problem.\n", c->frames);
607         fifo_write(&c->audio_data, (uint8_t *)audio, asize, &c->audio_data.wptr);
608     }
609 }
610
611 int dv_core_init(DVMuxContext *c, AVStream *streams[])
612 {
613     /* We have to sort out where audio and where video stream is */
614     if (streams[0]->codec.codec_type == CODEC_TYPE_VIDEO &&
615         streams[1]->codec.codec_type == CODEC_TYPE_AUDIO) {
616        c->vst = 0;
617        c->ast = 1;
618     }
619     else if (streams[1]->codec.codec_type == CODEC_TYPE_VIDEO &&
620              streams[0]->codec.codec_type == CODEC_TYPE_AUDIO) {
621             c->vst = 1;
622             c->ast = 0;
623     } else
624         goto bail_out;
625   
626     /* Some checks -- DV format is very picky about its incoming streams */
627     if (streams[c->vst]->codec.codec_id != CODEC_ID_DVVIDEO ||
628         streams[c->ast]->codec.codec_id != CODEC_ID_PCM_S16LE)
629        goto bail_out;
630     if (streams[c->ast]->codec.sample_rate != 48000 ||
631         streams[c->ast]->codec.channels != 2)
632        goto bail_out;
633         
634     if (streams[c->vst]->codec.frame_rate == 25 &&
635         streams[c->vst]->codec.frame_rate_base == 1) {
636         /* May be we have to pick sys for every frame */
637         c->sys = &dv_profiles[1];
638     }
639     else if (streams[c->vst]->codec.frame_rate == 30000 &&
640              streams[c->vst]->codec.frame_rate_base == 1001) {
641         /* May be we have to pick sys for every frame */
642         c->sys = &dv_profiles[0];
643     } else
644         goto bail_out;
645     
646     /* Ok, everything seems to be in working order */
647     c->frames = 0;
648     c->has_audio = c->has_video = 0;
649     c->start_time = time(NULL);
650     c->aspect = 0; /* 4:3 is the default */
651     if (streams[c->vst]->codec.aspect_ratio == 16.0 / 9.0)
652         c->aspect = 0x07;
653
654     if (fifo_init(&c->audio_data, AVCODEC_MAX_AUDIO_FRAME_SIZE) < 0)
655         goto bail_out;
656
657     dv_format_frame(c, &c->frame_buf[0]);
658
659     return 0;
660     
661 bail_out:
662     return -1;
663 }
664
665 void dv_core_delete(DVMuxContext *c)
666 {    
667     fifo_free(&c->audio_data);
668 }