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 / libavcodec / dv.c
1 /*
2  * DV decoder
3  * Copyright (c) 2002 Fabrice Bellard.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19
20 /**
21  * @file dv.c
22  * DV decoder.
23  */
24 #include "avcodec.h"
25 #include "dsputil.h"
26 #include "mpegvideo.h"
27 #include "simple_idct.h"
28
29 #define NTSC_FRAME_SIZE 120000
30 #define PAL_FRAME_SIZE  144000
31
32 #define TEX_VLC_BITS 9
33
34 typedef struct DVVideoDecodeContext {
35     AVCodecContext *avctx;
36     GetBitContext gb;
37     VLC *vlc;
38     int sampling_411; /* 0 = 420, 1 = 411 */
39     int width, height;
40     uint8_t *current_picture[3]; /* picture structure */
41     AVFrame picture;
42     int linesize[3];
43     DCTELEM block[5*6][64] __align8;
44     uint8_t dv_zigzag[2][64];
45     uint8_t idct_permutation[64];
46     /* XXX: move it to static storage ? */
47     uint8_t dv_shift[2][22][64];
48     void (*idct_put[2])(uint8_t *dest, int line_size, DCTELEM *block);
49 } DVVideoDecodeContext;
50
51 #include "dvdata.h"
52
53 static VLC dv_vlc;
54 /* XXX: also include quantization */
55 static RL_VLC_ELEM *dv_rl_vlc[1];
56
57 static void dv_build_unquantize_tables(DVVideoDecodeContext *s)
58 {
59     int i, q, j;
60
61     /* NOTE: max left shift is 6 */
62     for(q = 0; q < 22; q++) {
63         /* 88 unquant */
64         for(i = 1; i < 64; i++) {
65             /* 88 table */
66             j = s->idct_permutation[i];
67             s->dv_shift[0][q][j] =
68                 dv_quant_shifts[q][dv_88_areas[i]] + 1;
69         }
70         
71         /* 248 unquant */
72         for(i = 1; i < 64; i++) {
73             /* 248 table */
74             s->dv_shift[1][q][i] =  
75                     dv_quant_shifts[q][dv_248_areas[i]] + 1;
76         }
77     }
78 }
79
80 static int dvvideo_decode_init(AVCodecContext *avctx)
81 {
82     DVVideoDecodeContext *s = avctx->priv_data;
83     MpegEncContext s2;
84     static int done=0;
85
86     if (!done) {
87         int i;
88
89         done = 1;
90
91         /* NOTE: as a trick, we use the fact the no codes are unused
92            to accelerate the parsing of partial codes */
93         init_vlc(&dv_vlc, TEX_VLC_BITS, NB_DV_VLC, 
94                  dv_vlc_len, 1, 1, dv_vlc_bits, 2, 2);
95
96         dv_rl_vlc[0] = av_malloc(dv_vlc.table_size * sizeof(RL_VLC_ELEM));
97         for(i = 0; i < dv_vlc.table_size; i++){
98             int code= dv_vlc.table[i][0];
99             int len = dv_vlc.table[i][1];
100             int level, run;
101         
102             if(len<0){ //more bits needed
103                 run= 0;
104                 level= code;
105             } else if (code == (NB_DV_VLC - 1)) {
106                 /* EOB */
107                 run = 0;
108                 level = 256;
109             } else {
110                 run=   dv_vlc_run[code] + 1;
111                 level= dv_vlc_level[code];
112             }
113             dv_rl_vlc[0][i].len = len;
114             dv_rl_vlc[0][i].level = level;
115             dv_rl_vlc[0][i].run = run;
116         }
117     }
118
119     /* ugly way to get the idct & scantable */
120     /* XXX: fix it */
121     memset(&s2, 0, sizeof(MpegEncContext));
122     s2.avctx = avctx;
123     dsputil_init(&s2.dsp, avctx);
124     if (DCT_common_init(&s2) < 0)
125        return -1;
126
127     s->idct_put[0] = s2.dsp.idct_put;
128     memcpy(s->idct_permutation, s2.dsp.idct_permutation, 64);
129     memcpy(s->dv_zigzag[0], s2.intra_scantable.permutated, 64);
130
131     /* XXX: use MMX also for idct248 */
132     s->idct_put[1] = simple_idct248_put;
133     memcpy(s->dv_zigzag[1], dv_248_zigzag, 64);
134
135     /* XXX: do it only for constant case */
136     dv_build_unquantize_tables(s);
137     
138     return 0;
139 }
140
141 //#define VLC_DEBUG
142
143 typedef struct BlockInfo {
144     const uint8_t *shift_table;
145     const uint8_t *scan_table;
146     uint8_t pos; /* position in block */
147     uint8_t eob_reached; /* true if EOB has been reached */
148     uint8_t dct_mode;
149     uint8_t partial_bit_count;
150     uint16_t partial_bit_buffer;
151     int shift_offset;
152 } BlockInfo;
153
154 /* block size in bits */
155 static const uint16_t block_sizes[6] = {
156     112, 112, 112, 112, 80, 80
157 };
158
159 #ifndef ALT_BITSTREAM_READER
160 #warning only works with ALT_BITSTREAM_READER
161 #endif
162
163 /* decode ac coefs */
164 static void dv_decode_ac(DVVideoDecodeContext *s, 
165                          BlockInfo *mb, DCTELEM *block, int last_index)
166 {
167     int last_re_index;
168     int shift_offset = mb->shift_offset;
169     const uint8_t *scan_table = mb->scan_table;
170     const uint8_t *shift_table = mb->shift_table;
171     int pos = mb->pos;
172     int level, pos1, sign, run;
173     int partial_bit_count;
174 #ifndef ALT_BITSTREAM_READER //FIXME
175     int re_index=0; 
176     int re1_index=0;
177 #endif
178     OPEN_READER(re, &s->gb);
179     
180 #ifdef VLC_DEBUG
181     printf("start\n");
182 #endif
183
184     /* if we must parse a partial vlc, we do it here */
185     partial_bit_count = mb->partial_bit_count;
186     if (partial_bit_count > 0) {
187         uint8_t buf[4];
188         uint32_t v;
189         int l, l1;
190         GetBitContext gb1;
191
192         /* build the dummy bit buffer */
193         l = 16 - partial_bit_count;
194         UPDATE_CACHE(re, &s->gb);
195 #ifdef VLC_DEBUG
196         printf("show=%04x\n", SHOW_UBITS(re, &s->gb, 16));
197 #endif
198         v = (mb->partial_bit_buffer << l) | SHOW_UBITS(re, &s->gb, l);
199         buf[0] = v >> 8;
200         buf[1] = v;
201 #ifdef VLC_DEBUG
202         printf("v=%04x cnt=%d %04x\n", 
203                v, partial_bit_count, (mb->partial_bit_buffer << l));
204 #endif
205         /* try to read the codeword */
206         init_get_bits(&gb1, buf, 4*8);
207         {
208             OPEN_READER(re1, &gb1);
209             UPDATE_CACHE(re1, &gb1);
210             GET_RL_VLC(level, run, re1, &gb1, dv_rl_vlc[0], 
211                        TEX_VLC_BITS, 2);
212             l = re1_index;
213             CLOSE_READER(re1, &gb1);
214         }
215 #ifdef VLC_DEBUG
216         printf("****run=%d level=%d size=%d\n", run, level, l);
217 #endif
218         /* compute codeword length */
219         l1 = (level != 256 && level != 0);
220         /* if too long, we cannot parse */
221         l -= partial_bit_count;
222         if ((re_index + l + l1) > last_index)
223             return;
224         /* skip read bits */
225         last_re_index = 0; /* avoid warning */
226         re_index += l;
227         /* by definition, if we can read the vlc, all partial bits
228            will be read (otherwise we could have read the vlc before) */
229         mb->partial_bit_count = 0;
230         UPDATE_CACHE(re, &s->gb);
231         goto handle_vlc;
232     }
233
234     /* get the AC coefficients until last_index is reached */
235     for(;;) {
236         UPDATE_CACHE(re, &s->gb);
237 #ifdef VLC_DEBUG
238         printf("%2d: bits=%04x index=%d\n", 
239                pos, SHOW_UBITS(re, &s->gb, 16), re_index);
240 #endif
241         last_re_index = re_index;
242         GET_RL_VLC(level, run, re, &s->gb, dv_rl_vlc[0], 
243                    TEX_VLC_BITS, 2);
244     handle_vlc:
245 #ifdef VLC_DEBUG
246         printf("run=%d level=%d\n", run, level);
247 #endif
248         if (level == 256) {
249             if (re_index > last_index) {
250             cannot_read:
251                 /* put position before read code */
252                 re_index = last_re_index;
253                 mb->eob_reached = 0;
254                 break;
255             }
256             /* EOB */
257             mb->eob_reached = 1;
258             break;
259         } else if (level != 0) {
260             if ((re_index + 1) > last_index)
261                 goto cannot_read;
262             sign = SHOW_SBITS(re, &s->gb, 1);
263             level = (level ^ sign) - sign;
264             LAST_SKIP_BITS(re, &s->gb, 1);
265             pos += run;
266             /* error */
267             if (pos >= 64) {
268                 goto read_error;
269             }
270             pos1 = scan_table[pos];
271             level = level << (shift_table[pos1] + shift_offset);
272             block[pos1] = level;
273             //            printf("run=%d level=%d shift=%d\n", run, level, shift_table[pos1]);
274         } else {
275             if (re_index > last_index)
276                 goto cannot_read;
277             /* level is zero: means run without coding. No
278                sign is coded */
279             pos += run;
280             /* error */
281             if (pos >= 64) {
282             read_error:
283 #if defined(VLC_DEBUG) || 1
284                 fprintf(stderr, "error pos=%d\n", pos);
285 #endif
286                 /* for errors, we consider the eob is reached */
287                 mb->eob_reached = 1;
288                 break;
289             }
290         }
291     }
292     CLOSE_READER(re, &s->gb);
293     mb->pos = pos;
294 }
295
296 static inline void bit_copy(PutBitContext *pb, GetBitContext *gb, int bits_left)
297 {
298     while (bits_left >= 16) {
299         put_bits(pb, 16, get_bits(gb, 16));
300         bits_left -= 16;
301     }
302     if (bits_left > 0) {
303         put_bits(pb, bits_left, get_bits(gb, bits_left));
304     }
305 }
306
307 /* mb_x and mb_y are in units of 8 pixels */
308 static inline void dv_decode_video_segment(DVVideoDecodeContext *s, 
309                                            uint8_t *buf_ptr1, 
310                                            const uint16_t *mb_pos_ptr)
311 {
312     int quant, dc, dct_mode, class1, j;
313     int mb_index, mb_x, mb_y, v, last_index;
314     DCTELEM *block, *block1;
315     int c_offset, bits_left;
316     uint8_t *y_ptr;
317     BlockInfo mb_data[5 * 6], *mb, *mb1;
318     void (*idct_put)(uint8_t *dest, int line_size, DCTELEM *block);
319     uint8_t *buf_ptr;
320     PutBitContext pb, vs_pb;
321     uint8_t mb_bit_buffer[80 + 4]; /* allow some slack */
322     int mb_bit_count;
323     uint8_t vs_bit_buffer[5 * 80 + 4]; /* allow some slack */
324     int vs_bit_count;
325     
326     memset(s->block, 0, sizeof(s->block));
327
328     /* pass 1 : read DC and AC coefficients in blocks */
329     buf_ptr = buf_ptr1;
330     block1 = &s->block[0][0];
331     mb1 = mb_data;
332     init_put_bits(&vs_pb, vs_bit_buffer, 5 * 80, NULL, NULL);
333     vs_bit_count = 0;
334     for(mb_index = 0; mb_index < 5; mb_index++) {
335         /* skip header */
336         quant = buf_ptr[3] & 0x0f;
337         buf_ptr += 4;
338         init_put_bits(&pb, mb_bit_buffer, 80, NULL, NULL);
339         mb_bit_count = 0;
340         mb = mb1;
341         block = block1;
342         for(j = 0;j < 6; j++) {
343             /* NOTE: size is not important here */
344             init_get_bits(&s->gb, buf_ptr, 14*8);
345             
346             /* get the dc */
347             dc = get_bits(&s->gb, 9);
348             dc = (dc << (32 - 9)) >> (32 - 9);
349             dct_mode = get_bits1(&s->gb);
350             mb->dct_mode = dct_mode;
351             mb->scan_table = s->dv_zigzag[dct_mode];
352             class1 = get_bits(&s->gb, 2);
353             mb->shift_offset = (class1 == 3);
354             mb->shift_table = s->dv_shift[dct_mode]
355                 [quant + dv_quant_offset[class1]];
356             dc = dc << 2;
357             /* convert to unsigned because 128 is not added in the
358                standard IDCT */
359             dc += 1024;
360             block[0] = dc;
361             last_index = block_sizes[j];
362             buf_ptr += last_index >> 3;
363             mb->pos = 0;
364             mb->partial_bit_count = 0;
365
366             dv_decode_ac(s, mb, block, last_index);
367
368             /* write the remaining bits  in a new buffer only if the
369                block is finished */
370             bits_left = last_index - get_bits_count(&s->gb);
371             if (mb->eob_reached) {
372                 mb->partial_bit_count = 0;
373                 mb_bit_count += bits_left;
374                 bit_copy(&pb, &s->gb, bits_left);
375             } else {
376                 /* should be < 16 bits otherwise a codeword could have
377                    been parsed */
378                 mb->partial_bit_count = bits_left;
379                 mb->partial_bit_buffer = get_bits(&s->gb, bits_left);
380             }
381             block += 64;
382             mb++;
383         }
384         
385         flush_put_bits(&pb);
386
387         /* pass 2 : we can do it just after */
388 #ifdef VLC_DEBUG
389         printf("***pass 2 size=%d\n", mb_bit_count);
390 #endif
391         block = block1;
392         mb = mb1;
393         init_get_bits(&s->gb, mb_bit_buffer, 80*8);
394         for(j = 0;j < 6; j++) {
395             if (!mb->eob_reached && get_bits_count(&s->gb) < mb_bit_count) {
396                 dv_decode_ac(s, mb, block, mb_bit_count);
397                 /* if still not finished, no need to parse other blocks */
398                 if (!mb->eob_reached) {
399                     /* we could not parse the current AC coefficient,
400                        so we add the remaining bytes */
401                     bits_left = mb_bit_count - get_bits_count(&s->gb);
402                     if (bits_left > 0) {
403                         mb->partial_bit_count += bits_left;
404                         mb->partial_bit_buffer = 
405                             (mb->partial_bit_buffer << bits_left) | 
406                             get_bits(&s->gb, bits_left);
407                     }
408                     goto next_mb;
409                 }
410             }
411             block += 64;
412             mb++;
413         }
414         /* all blocks are finished, so the extra bytes can be used at
415            the video segment level */
416         bits_left = mb_bit_count - get_bits_count(&s->gb);
417         vs_bit_count += bits_left;
418         bit_copy(&vs_pb, &s->gb, bits_left);
419     next_mb:
420         mb1 += 6;
421         block1 += 6 * 64;
422     }
423
424     /* we need a pass other the whole video segment */
425     flush_put_bits(&vs_pb);
426         
427 #ifdef VLC_DEBUG
428     printf("***pass 3 size=%d\n", vs_bit_count);
429 #endif
430     block = &s->block[0][0];
431     mb = mb_data;
432     init_get_bits(&s->gb, vs_bit_buffer, 5 * 80*8);
433     for(mb_index = 0; mb_index < 5; mb_index++) {
434         for(j = 0;j < 6; j++) {
435             if (!mb->eob_reached) {
436 #ifdef VLC_DEBUG
437                 printf("start %d:%d\n", mb_index, j);
438 #endif
439                 dv_decode_ac(s, mb, block, vs_bit_count);
440             }
441             block += 64;
442             mb++;
443         }
444     }
445     
446     /* compute idct and place blocks */
447     block = &s->block[0][0];
448     mb = mb_data;
449     for(mb_index = 0; mb_index < 5; mb_index++) {
450         v = *mb_pos_ptr++;
451         mb_x = v & 0xff;
452         mb_y = v >> 8;
453         y_ptr = s->current_picture[0] + (mb_y * s->linesize[0] * 8) + (mb_x * 8);
454         if (s->sampling_411)
455             c_offset = (mb_y * s->linesize[1] * 8) + ((mb_x >> 2) * 8);
456         else
457             c_offset = ((mb_y >> 1) * s->linesize[1] * 8) + ((mb_x >> 1) * 8);
458         for(j = 0;j < 6; j++) {
459             idct_put = s->idct_put[mb->dct_mode];
460             if (j < 4) {
461                 if (s->sampling_411 && mb_x < (704 / 8)) {
462                     /* NOTE: at end of line, the macroblock is handled as 420 */
463                     idct_put(y_ptr + (j * 8), s->linesize[0], block);
464                 } else {
465                     idct_put(y_ptr + ((j & 1) * 8) + ((j >> 1) * 8 * s->linesize[0]),
466                              s->linesize[0], block);
467                 }
468             } else {
469                 if (s->sampling_411 && mb_x >= (704 / 8)) {
470                     uint8_t pixels[64], *c_ptr, *c_ptr1, *ptr;
471                     int y, linesize;
472                     /* NOTE: at end of line, the macroblock is handled as 420 */
473                     idct_put(pixels, 8, block);
474                     linesize = s->linesize[6 - j];
475                     c_ptr = s->current_picture[6 - j] + c_offset;
476                     ptr = pixels;
477                     for(y = 0;y < 8; y++) {
478                         /* convert to 411P */
479                         c_ptr1 = c_ptr + 8*linesize;
480                         c_ptr[0]= ptr[0]; c_ptr1[0]= ptr[4];
481                         c_ptr[1]= ptr[1]; c_ptr1[1]= ptr[5];
482                         c_ptr[2]= ptr[2]; c_ptr1[2]= ptr[6];
483                         c_ptr[3]= ptr[3]; c_ptr1[3]= ptr[7];
484                         c_ptr += linesize;
485                         ptr += 8;
486                     }
487                 } else {
488                     /* don't ask me why they inverted Cb and Cr ! */
489                     idct_put(s->current_picture[6 - j] + c_offset, 
490                              s->linesize[6 - j], block);
491                 }
492             }
493             block += 64;
494             mb++;
495         }
496     }
497 }
498
499
500 /* NOTE: exactly one frame must be given (120000 bytes for NTSC,
501    144000 bytes for PAL) */
502 static int dvvideo_decode_frame(AVCodecContext *avctx, 
503                                  void *data, int *data_size,
504                                  uint8_t *buf, int buf_size)
505 {
506     DVVideoDecodeContext *s = avctx->priv_data;
507     int sct, dsf, apt, ds, nb_dif_segs, vs, width, height, i, packet_size;
508     uint8_t *buf_ptr;
509     const uint16_t *mb_pos_ptr;
510     
511     /* parse id */
512     init_get_bits(&s->gb, buf, buf_size*8);
513     sct = get_bits(&s->gb, 3);
514     if (sct != 0)
515         return -1;
516     skip_bits(&s->gb, 5);
517     get_bits(&s->gb, 4); /* dsn (sequence number */
518     get_bits(&s->gb, 1); /* fsc (channel number) */
519     skip_bits(&s->gb, 3);
520     get_bits(&s->gb, 8); /* dbn (diff block number 0-134) */
521
522     dsf = get_bits(&s->gb, 1); /* 0 = NTSC 1 = PAL */
523     if (get_bits(&s->gb, 1) != 0)
524         return -1;
525     skip_bits(&s->gb, 11);
526     apt = get_bits(&s->gb, 3); /* apt */
527
528     get_bits(&s->gb, 1); /* tf1 */
529     skip_bits(&s->gb, 4);
530     get_bits(&s->gb, 3); /* ap1 */
531
532     get_bits(&s->gb, 1); /* tf2 */
533     skip_bits(&s->gb, 4);
534     get_bits(&s->gb, 3); /* ap2 */
535
536     get_bits(&s->gb, 1); /* tf3 */
537     skip_bits(&s->gb, 4);
538     get_bits(&s->gb, 3); /* ap3 */
539     
540     /* init size */
541     width = 720;
542     if (dsf) {
543         avctx->frame_rate = 25;
544         avctx->frame_rate_base = 1;
545         packet_size = PAL_FRAME_SIZE;
546         height = 576;
547         nb_dif_segs = 12;
548     } else {
549         avctx->frame_rate = 30000;
550         avctx->frame_rate_base = 1001;
551         packet_size = NTSC_FRAME_SIZE;
552         height = 480;
553         nb_dif_segs = 10;
554     }
555     /* NOTE: we only accept several full frames */
556     if (buf_size < packet_size)
557         return -1;
558     
559     /* NTSC[dsf == 0] is always 720x480, 4:1:1
560      *  PAL[dsf == 1] is always 720x576, 4:2:0 for IEC 68134[apt == 0]
561      *  but for the SMPTE 314M[apt == 1] it is 720x576, 4:1:1
562      */
563     s->sampling_411 = !dsf || apt;
564     if (s->sampling_411) {
565         mb_pos_ptr = dsf ? dv_place_411P : dv_place_411;
566         avctx->pix_fmt = PIX_FMT_YUV411P;
567     } else {
568         mb_pos_ptr = dv_place_420;
569         avctx->pix_fmt = PIX_FMT_YUV420P;
570     }
571
572     avctx->width = width;
573     avctx->height = height;
574     
575     /* Once again, this is pretty complicated by the fact that the same
576      * field is used differently by IEC 68134[apt == 0] and 
577      * SMPTE 314M[apt == 1].
578      */
579     if (buf[VAUX_TC61_OFFSET] == 0x61 &&
580         ((apt == 0 && (buf[VAUX_TC61_OFFSET + 2] & 0x07) == 0x07) ||
581          (apt == 1 && (buf[VAUX_TC61_OFFSET + 2] & 0x07) == 0x02)))
582         avctx->aspect_ratio = 16.0 / 9.0;
583     else
584         avctx->aspect_ratio = 4.0 / 3.0;
585
586     if(s->picture.data[0])
587         avctx->release_buffer(avctx, &s->picture);
588     
589     s->picture.reference= 0;
590     if(avctx->get_buffer(avctx, &s->picture) < 0) {
591         fprintf(stderr, "get_buffer() failed\n");
592         return -1;
593     }
594
595     for(i=0;i<3;i++) {
596         s->current_picture[i] = s->picture.data[i];
597         s->linesize[i] = s->picture.linesize[i];
598         if (!s->current_picture[i])
599             return -1;
600     }
601     s->width = width;
602     s->height = height;
603
604     /* for each DIF segment */
605     buf_ptr = buf;
606     for (ds = 0; ds < nb_dif_segs; ds++) {
607         buf_ptr += 6 * 80; /* skip DIF segment header */
608         
609         for(vs = 0; vs < 27; vs++) {
610             if ((vs % 3) == 0) {
611                 /* skip audio block */
612                 buf_ptr += 80;
613             }
614             dv_decode_video_segment(s, buf_ptr, mb_pos_ptr);
615             buf_ptr += 5 * 80;
616             mb_pos_ptr += 5;
617         }
618     }
619
620     emms_c();
621
622     /* return image */
623     *data_size = sizeof(AVFrame);
624     *(AVFrame*)data= s->picture;
625     
626     return packet_size;
627 }
628
629 static int dvvideo_decode_end(AVCodecContext *avctx)
630 {
631     avcodec_default_free_buffers(avctx);    
632
633     return 0;
634 }
635
636 AVCodec dvvideo_decoder = {
637     "dvvideo",
638     CODEC_TYPE_VIDEO,
639     CODEC_ID_DVVIDEO,
640     sizeof(DVVideoDecodeContext),
641     dvvideo_decode_init,
642     NULL,
643     dvvideo_decode_end,
644     dvvideo_decode_frame,
645     CODEC_CAP_DR1,
646     NULL
647 };
648
649 typedef struct DVAudioDecodeContext {
650     AVCodecContext *avctx;
651     GetBitContext gb;
652 } DVAudioDecodeContext;
653
654 static int dvaudio_decode_init(AVCodecContext *avctx)
655 {
656     //    DVAudioDecodeContext *s = avctx->priv_data;
657     return 0;
658 }
659
660 static uint16_t dv_audio_12to16(uint16_t sample)
661 {
662     uint16_t shift, result;
663     
664     sample = (sample < 0x800) ? sample : sample | 0xf000;
665     shift = (sample & 0xf00) >> 8;
666
667     if (shift < 0x2 || shift > 0xd) {
668         result = sample;
669     } else if (shift < 0x8) {
670         shift--;
671         result = (sample - (256 * shift)) << shift;
672     } else {
673         shift = 0xe - shift;
674         result = ((sample + ((256 * shift) + 1)) << shift) - 1;
675     }
676
677     return result;
678 }
679
680 /* NOTE: exactly one frame must be given (120000 bytes for NTSC,
681    144000 bytes for PAL) 
682
683    There's a couple of assumptions being made here:
684          1. By default we silence erroneous (0x8000/16bit 0x800/12bit) 
685             audio samples. We can pass them upwards when ffmpeg will be ready
686             to deal with them.
687          2. We don't do software emphasis.
688          3. Audio is always returned as 16bit linear samples: 12bit
689             nonlinear samples are converted into 16bit linear ones.
690 */
691 static int dvaudio_decode_frame(AVCodecContext *avctx, 
692                                  void *data, int *data_size,
693                                  uint8_t *buf, int buf_size)
694 {
695     DVVideoDecodeContext *s = avctx->priv_data;
696     const uint16_t (*unshuffle)[9];
697     int smpls, freq, quant, sys, stride, difseg, ad, dp, nb_dif_segs, i;
698     uint16_t lc, rc;
699     uint8_t *buf_ptr;
700     
701     /* parse id */
702     init_get_bits(&s->gb, &buf[AAUX_AS_OFFSET], 5*8);
703     i = get_bits(&s->gb, 8);
704     if (i != 0x50) { /* No audio ? */
705         *data_size = 0;
706         return buf_size;
707     }
708     
709     get_bits(&s->gb, 1); /* 0 - locked audio, 1 - unlocked audio */
710     skip_bits(&s->gb, 1);
711     smpls = get_bits(&s->gb, 6); /* samples in this frame - min. samples */
712
713     skip_bits(&s->gb, 8);
714
715     skip_bits(&s->gb, 2);
716     sys = get_bits(&s->gb, 1); /* 0 - 60 fields, 1 = 50 fields */
717     skip_bits(&s->gb, 5);
718
719     get_bits(&s->gb, 1); /* 0 - emphasis on, 1 - emphasis off */
720     get_bits(&s->gb, 1); /* 0 - reserved, 1 - emphasis time constant 50/15us */
721     freq = get_bits(&s->gb, 3); /* 0 - 48KHz, 1 - 44,1kHz, 2 - 32 kHz */
722     quant = get_bits(&s->gb, 3); /* 0 - 16bit linear, 1 - 12bit nonlinear */
723
724     if (quant > 1)
725         return -1; /* Unsupported quantization */
726
727     avctx->sample_rate = dv_audio_frequency[freq];
728     avctx->channels = 2;
729     avctx->bit_rate = avctx->channels * avctx->sample_rate * 16;
730     // What about:
731     // avctx->frame_size =
732    
733     *data_size = (dv_audio_min_samples[sys][freq] + smpls) * 
734                  avctx->channels * 2;
735
736     if (sys) {
737         nb_dif_segs = 12;
738         stride = 108;
739         unshuffle = dv_place_audio50;
740     } else {
741         nb_dif_segs = 10;
742         stride = 90;
743         unshuffle = dv_place_audio60;
744     }
745     
746     /* for each DIF segment */
747     buf_ptr = buf;
748     for (difseg = 0; difseg < nb_dif_segs; difseg++) {
749          buf_ptr += 6 * 80; /* skip DIF segment header */
750          for (ad = 0; ad < 9; ad++) {
751               
752               for (dp = 8; dp < 80; dp+=2) {
753                    if (quant == 0) {  /* 16bit quantization */
754                        i = unshuffle[difseg][ad] + (dp - 8)/2 * stride;
755                        ((short *)data)[i] = (buf_ptr[dp] << 8) | buf_ptr[dp+1]; 
756                        if (((unsigned short *)data)[i] == 0x8000)
757                            ((short *)data)[i] = 0;
758                    } else {           /* 12bit quantization */
759                        if (difseg >= nb_dif_segs/2)
760                            goto out;  /* We're not doing 4ch at this time */
761                        
762                        lc = ((uint16_t)buf_ptr[dp] << 4) | 
763                             ((uint16_t)buf_ptr[dp+2] >> 4);
764                        rc = ((uint16_t)buf_ptr[dp+1] << 4) |
765                             ((uint16_t)buf_ptr[dp+2] & 0x0f);
766                        lc = (lc == 0x800 ? 0 : dv_audio_12to16(lc));
767                        rc = (rc == 0x800 ? 0 : dv_audio_12to16(rc));
768
769                        i = unshuffle[difseg][ad] + (dp - 8)/3 * stride;
770                        ((short *)data)[i] = lc;
771                        i = unshuffle[difseg+nb_dif_segs/2][ad] + (dp - 8)/3 * stride;
772                        ((short *)data)[i] = rc;
773                        ++dp;
774                    }
775               }
776                 
777             buf_ptr += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */
778         }
779     }
780
781 out:
782     return buf_size;
783 }
784
785 static int dvaudio_decode_end(AVCodecContext *avctx)
786 {
787     //    DVAudioDecodeContext *s = avctx->priv_data;
788     return 0;
789 }
790
791 AVCodec dvaudio_decoder = {
792     "dvaudio",
793     CODEC_TYPE_AUDIO,
794     CODEC_ID_DVAUDIO,
795     sizeof(DVAudioDecodeContext),
796     dvaudio_decode_init,
797     NULL,
798     dvaudio_decode_end,
799     dvaudio_decode_frame,
800     0,
801     NULL
802 };