File: audio.c

package info (click to toggle)
libquicktime 2%3A1.0.2%2Bdebian-2
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 6,496 kB
  • ctags: 6,233
  • sloc: ansic: 48,217; sh: 10,075; makefile: 425; sed: 16
file content (937 lines) | stat: -rw-r--r-- 28,613 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
/*******************************************************************************
 audio.c

 libquicktime - A library for reading and writing quicktime/avi/mp4 files.
 http://libquicktime.sourceforge.net

 Copyright (C) 2002 Heroine Virtual Ltd.
 Copyright (C) 2002-2007 Members of the libquicktime project.

 This library is free software; you can redistribute it and/or modify it under
 the terms of the GNU Lesser General Public License as published by the Free
 Software Foundation; either version 2.1 of the License, or (at your option)
 any later version.

 This library is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 details.

 You should have received a copy of the GNU Lesser General Public License along
 with this library; if not, write to the Free Software Foundation, Inc., 51
 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*******************************************************************************/ 

#include "lqt_private.h"
#include "ffmpeg.h"
#define LQT_LIBQUICKTIME
#include <quicktime/lqt_codecapi.h>
#include <stdlib.h>
#include <string.h>

#define LOG_DOMAIN "ffmpeg_audio"

/* Different decoding functions */

#if LIBAVCODEC_BUILD >= 3349760
#define DECODE_FUNC avcodec_decode_audio2
#else
#define DECODE_FUNC avcodec_decode_audio
#endif

/* The following code was ported from gmerlin_avdecoder (http://gmerlin.sourceforge.net) */

/* MPEG Audio header parsing code */

static int mpeg_bitrates[5][16] = {
  /* MPEG-1 */
  { 0,  32000,  64000,  96000, 128000, 160000, 192000, 224000,    // I
       256000, 288000, 320000, 352000, 384000, 416000, 448000, 0},
  { 0,  32000,  48000,  56000,  64000,  80000,  96000, 112000,    // II
       128000, 160000, 192000, 224000, 256000, 320000, 384000, 0 },
  { 0,  32000,  40000,  48000,  56000,  64000,  80000,  96000,    // III
       112000, 128000, 160000, 192000, 224000, 256000, 320000, 0 },

  /* MPEG-2 LSF */
  { 0,  32000,  48000,  56000,  64000,  80000,  96000, 112000,    // I
       128000, 144000, 160000, 176000, 192000, 224000, 256000, 0 },
  { 0,   8000,  16000,  24000,  32000,  40000,  48000,  56000,
        64000,  80000,  96000, 112000, 128000, 144000, 160000, 0 } // II & III
};

static int mpeg_samplerates[3][3] = {
  { 44100, 48000, 32000 }, // MPEG1
  { 22050, 24000, 16000 }, // MPEG2
  { 11025, 12000, 8000 }   // MPEG2.5
  };

#define MPEG_ID_MASK        0x00180000
#define MPEG_MPEG1          0x00180000
#define MPEG_MPEG2          0x00100000
#define MPEG_MPEG2_5        0x00000000

#define MPEG_LAYER_MASK     0x00060000
#define MPEG_LAYER_III      0x00020000
#define MPEG_LAYER_II       0x00040000
#define MPEG_LAYER_I        0x00060000
#define MPEG_PROTECTION     0x00010000
#define MPEG_BITRATE_MASK   0x0000F000
#define MPEG_FREQUENCY_MASK 0x00000C00
#define MPEG_PAD_MASK       0x00000200
#define MPEG_PRIVATE_MASK   0x00000100
#define MPEG_MODE_MASK      0x000000C0
#define MPEG_MODE_EXT_MASK  0x00000030
#define MPEG_COPYRIGHT_MASK 0x00000008
#define MPEG_HOME_MASK      0x00000004
#define MPEG_EMPHASIS_MASK  0x00000003
#define LAYER_I_SAMPLES       384
#define LAYER_II_III_SAMPLES 1152

/* Header detection stolen from the mpg123 plugin of xmms */

static int header_check(uint32_t head)
{
        if ((head & 0xffe00000) != 0xffe00000)
                return 0;
        if (!((head >> 17) & 3))
                return 0;
        if (((head >> 12) & 0xf) == 0xf)
                return 0;
        if (!((head >> 12) & 0xf))
                return 0;
        if (((head >> 10) & 0x3) == 0x3)
                return 0;
        if (((head >> 19) & 1) == 1 &&
            ((head >> 17) & 3) == 3 &&
            ((head >> 16) & 1) == 1)
                return 0;
        if ((head & 0xffff0000) == 0xfffe0000)
                return 0;
        return 1;
}

typedef enum
  {
    MPEG_VERSION_NONE = 0,
    MPEG_VERSION_1 = 1,
    MPEG_VERSION_2 = 2,
    MPEG_VERSION_2_5
  } mpeg_version_t;

#define CHANNEL_STEREO   0
#define CHANNEL_JSTEREO  1
#define CHANNEL_DUAL     2
#define CHANNEL_MONO     3

typedef struct
  {
  mpeg_version_t version;
  int layer;
  int bitrate;    /* -1: VBR */
  int samplerate;
  int frame_bytes;
  int channel_mode;
  int mode;
  int samples_per_frame;
  } mpeg_header;

static int header_equal(const mpeg_header * h1, const mpeg_header * h2)
  {
  return ((h1->layer == h2->layer) && (h1->version == h2->version) &&
          (h1->samplerate == h2->samplerate));
  }

static int decode_header(mpeg_header * h, uint8_t * ptr, const mpeg_header * ref)
  {
  uint32_t header;
  int index;
  /* For calculation of the byte length of a frame */
  int pad;
  int slots_per_frame;
  h->frame_bytes = 0;
  header =
    ptr[3] | (ptr[2] << 8) | (ptr[1] << 16) | (ptr[0] << 24);
  if(!header_check(header))
    return 0;
  index = (header & MPEG_MODE_MASK) >> 6;
  switch(index)
    {
    case 0:
      h->channel_mode = CHANNEL_STEREO;
      break;
    case 1:
      h->channel_mode = CHANNEL_JSTEREO;
      break;
    case 2:
      h->channel_mode = CHANNEL_DUAL;
      break;
    case 3:
      h->channel_mode = CHANNEL_MONO;
      break;
    }
  /* Get Version */
  switch(header & MPEG_ID_MASK)
    {
    case MPEG_MPEG1:
      h->version = MPEG_VERSION_1;
        break;
    case MPEG_MPEG2:
      h->version = MPEG_VERSION_2;
      break;
    case MPEG_MPEG2_5:
      h->version = MPEG_VERSION_2_5;
      break;
    default:
      return 0;
    }
  /* Get Layer */
  switch(header & MPEG_LAYER_MASK)
    {
    case MPEG_LAYER_I:
      h->layer = 1;
      break;
    case MPEG_LAYER_II:
      h->layer = 2;
      break;
    case MPEG_LAYER_III:
      h->layer = 3;
      break;
    }
  index = (header & MPEG_BITRATE_MASK) >> 12;
  switch(h->version)
    {
    case MPEG_VERSION_1:
      switch(h->layer)
        {
        case 1:
          h->bitrate = mpeg_bitrates[0][index];
          break;
        case 2:
          h->bitrate = mpeg_bitrates[1][index];
          break;
        case 3:
          h->bitrate = mpeg_bitrates[2][index];
          break;
        }
      break;
    case MPEG_VERSION_2:
    case MPEG_VERSION_2_5:
      switch(h->layer)
        {
        case 1:
          h->bitrate = mpeg_bitrates[3][index];
          break;
        case 2:
        case 3:
          h->bitrate = mpeg_bitrates[4][index];
          break;
        }
      break;
    default: // This won't happen, but keeps gcc quiet
      return 0;
    }
  index = (header & MPEG_FREQUENCY_MASK) >> 10;
  switch(h->version)
    {
    case MPEG_VERSION_1:
      h->samplerate = mpeg_samplerates[0][index];
      break;
    case MPEG_VERSION_2:
      h->samplerate = mpeg_samplerates[1][index];
      break;
    case MPEG_VERSION_2_5:
      h->samplerate = mpeg_samplerates[2][index];
      break;
    default: // This won't happen, but keeps gcc quiet
      return 0;
    }
  pad = (header & MPEG_PAD_MASK) ? 1 : 0;
  if(h->layer == 1)
    {
    h->frame_bytes = ((12 * h->bitrate / h->samplerate) + pad) * 4;
    }
  else
    {
    slots_per_frame = ((h->layer == 3) &&
      ((h->version == MPEG_VERSION_2) ||
       (h->version == MPEG_VERSION_2_5))) ? 72 : 144;
    h->frame_bytes = (slots_per_frame * h->bitrate) / h->samplerate + pad;
    }
  // h->mode = (ptr[3] >> 6) & 3;
  h->samples_per_frame =
    (h->layer == 1) ? LAYER_I_SAMPLES : LAYER_II_III_SAMPLES;
  if(h->version != MPEG_VERSION_1)
    h->samples_per_frame /= 2;
  //  dump_header(h);

  /* Check against reference header */

  if(ref && !header_equal(ref, h))
    return 0;
  return 1;
  }

typedef struct
  {
  AVCodecContext * avctx;
  AVCodec * encoder;
  AVCodec * decoder;

  int initialized;
  
  /* Interleaved samples as avcodec needs them */
    
  int16_t * sample_buffer;
  int sample_buffer_alloc; 
  int samples_in_buffer;
  
  /* Buffer for the entire chunk */

  uint8_t * chunk_buffer;
  int chunk_buffer_alloc;
  int bytes_in_chunk_buffer;

  /* Start and end positions of the sample buffer */
    
  int64_t sample_buffer_start;
  int64_t sample_buffer_end;

  mpeg_header mph;
  int have_mpeg_header;

  uint8_t * extradata;
    
  } quicktime_ffmpeg_audio_codec_t;


static int lqt_ffmpeg_delete_audio(quicktime_audio_map_t *vtrack)
  {
  quicktime_ffmpeg_audio_codec_t *codec = ((quicktime_codec_t*)vtrack->codec)->priv;
  
  if(codec->avctx)
    {
    if(codec->initialized)
      avcodec_close(codec->avctx);
    av_free(codec->avctx);
    }
  if(codec->sample_buffer) free(codec->sample_buffer);
  if(codec->chunk_buffer)  free(codec->chunk_buffer);
  if(codec->extradata) free(codec->extradata); 
  free(codec);
  return 0;
  }

static int set_parameter(quicktime_t *file, 
                  int track, 
                  const char *key, 
                  const void *value)
  {
  quicktime_ffmpeg_audio_codec_t *codec = ((quicktime_codec_t*)file->atracks[track].codec)->priv;
  lqt_ffmpeg_set_parameter(codec->avctx, key, value);
  return 0;
  }


/* Decode VBR chunk into the sample buffer */

static int decode_chunk_vbr(quicktime_t * file, int track)
  {
  int chunk_packets, i, num_samples, bytes_decoded;
  int packet_size, packet_samples;
  int frame_bytes;
  int new_samples;
  quicktime_audio_map_t *track_map = &(file->atracks[track]);
  quicktime_ffmpeg_audio_codec_t *codec = ((quicktime_codec_t*)track_map->codec)->priv;

  chunk_packets = lqt_audio_num_vbr_packets(file, track, track_map->current_chunk, &num_samples);

  if(!chunk_packets)
    return 0;

  new_samples = num_samples + AVCODEC_MAX_AUDIO_FRAME_SIZE / (2 * track_map->channels);
  
  if(codec->sample_buffer_alloc <
     codec->sample_buffer_end - codec->sample_buffer_start + new_samples)
    {
    
    codec->sample_buffer_alloc = codec->sample_buffer_end - codec->sample_buffer_start + new_samples;
    codec->sample_buffer = realloc(codec->sample_buffer, 2 * codec->sample_buffer_alloc *
                                   track_map->channels);
    }

  for(i = 0; i < chunk_packets; i++)
    {
    packet_size = lqt_audio_read_vbr_packet(file, track, track_map->current_chunk, i,
                                            &(codec->chunk_buffer), &(codec->chunk_buffer_alloc),
                                            &packet_samples);
    if(!packet_size)
      return 0;

#if LIBAVCODEC_BUILD >= 3349760
    bytes_decoded = codec->sample_buffer_alloc -
      (codec->sample_buffer_end - codec->sample_buffer_start);
    bytes_decoded *= 2 * track_map->channels;
#else
    bytes_decoded = 0;
#endif

    
    frame_bytes =
      DECODE_FUNC(codec->avctx,
                  &(codec->sample_buffer[track_map->channels *
                                         (codec->sample_buffer_end - codec->sample_buffer_start)]),
                  &bytes_decoded,
                  codec->chunk_buffer,
                  packet_size + FF_INPUT_BUFFER_PADDING_SIZE);
    if(frame_bytes < 0)
      {
      lqt_log(file, LQT_LOG_ERROR, LOG_DOMAIN, "avcodec_decode_audio error");
      break;
      }
    codec->sample_buffer_end += (bytes_decoded / (track_map->channels * 2));
    }
  track_map->current_chunk++;
  return num_samples;
  }


/* Decode the current chunk into the sample buffer */

static int decode_chunk(quicktime_t * file, int track)
  {
  mpeg_header mph;
    
  int frame_bytes;
  int num_samples;
  int new_samples;
  int samples_decoded = 0;
  int bytes_decoded;
  int bytes_used, bytes_skipped;
  int64_t chunk_size;
  quicktime_audio_map_t *track_map = &(file->atracks[track]);
  quicktime_ffmpeg_audio_codec_t *codec = ((quicktime_codec_t*)track_map->codec)->priv;

  /* Read chunk */
  
  chunk_size = lqt_append_audio_chunk(file,
                                      track, track_map->current_chunk,
                                      &(codec->chunk_buffer),
                                      &(codec->chunk_buffer_alloc),
                                      codec->bytes_in_chunk_buffer);

  
  if(!chunk_size)
    {
    /* If the codec is mp3, make sure to decode the very last frame */

    if((codec->avctx->codec_id == CODEC_ID_MP3) &&
       (codec->bytes_in_chunk_buffer >= 4))
      {
      if(!decode_header(&mph, codec->chunk_buffer, (const mpeg_header*)0))
        {
        lqt_log(file, LQT_LOG_ERROR, LOG_DOMAIN, "Decode header failed");
        return 0;
        }
      if(mph.frame_bytes <= codec->bytes_in_chunk_buffer)
        {
        lqt_log(file, LQT_LOG_ERROR, LOG_DOMAIN, "Huh, frame not decoded?");
        return 0;
        }

      if(codec->chunk_buffer_alloc < mph.frame_bytes + FF_INPUT_BUFFER_PADDING_SIZE)
        {
        codec->chunk_buffer_alloc = mph.frame_bytes + FF_INPUT_BUFFER_PADDING_SIZE;
        codec->chunk_buffer = realloc(codec->chunk_buffer, codec->chunk_buffer_alloc);
        }
      memset(codec->chunk_buffer + codec->bytes_in_chunk_buffer, 0,
             mph.frame_bytes - codec->bytes_in_chunk_buffer + FF_INPUT_BUFFER_PADDING_SIZE);
      num_samples = mph.samples_per_frame;
      codec->bytes_in_chunk_buffer = mph.frame_bytes;
      }
    else
      return 0;
    }
  else
    {
    num_samples = quicktime_chunk_samples(track_map->track, track_map->current_chunk);
    track_map->current_chunk++;
    codec->bytes_in_chunk_buffer += chunk_size;
    }
  

  if(!num_samples)
    {
    return 0;
    }
  /*
   *  For AVIs, chunk samples are not always 100% correct.
   *  Furthermore, there can be a complete mp3 frame from the last chunk!
   */

  num_samples += 8192;
  new_samples = num_samples + AVCODEC_MAX_AUDIO_FRAME_SIZE / (2 * track_map->channels);
  
  /* Reallocate sample buffer */
  
  if(codec->sample_buffer_alloc < codec->sample_buffer_end - codec->sample_buffer_start + new_samples)
    {
    
    codec->sample_buffer_alloc = codec->sample_buffer_end - codec->sample_buffer_start + new_samples;
    codec->sample_buffer = realloc(codec->sample_buffer, 2 * codec->sample_buffer_alloc *
                                   track_map->channels);
    }
  
  /* Decode this */

  bytes_used = 0;
  while(1)
    {

        
    /* BIG NOTE: We pass extra FF_INPUT_BUFFER_PADDING_SIZE for the buffer size
       because we know, that lqt_read_audio_chunk allocates 16 extra bytes for us */
    
    /* Some really broken mp3 files have the header bytes split across 2 chunks */

    if(codec->avctx->codec_id == CODEC_ID_MP3)
      {
      if(codec->bytes_in_chunk_buffer < 4)
        {
        
        if(codec->bytes_in_chunk_buffer > 0)
          memmove(codec->chunk_buffer,
                  codec->chunk_buffer + bytes_used, codec->bytes_in_chunk_buffer);
        return 1;
        }

      bytes_skipped = 0;
      while(1)
        {
        if(!codec->have_mpeg_header)
          {
          if(decode_header(&mph, &(codec->chunk_buffer[bytes_used]), NULL))
            {
            memcpy(&(codec->mph), &mph, sizeof(mph));
            codec->have_mpeg_header = 1;
            break;
            }
          }
        else if(decode_header(&mph, &(codec->chunk_buffer[bytes_used]), &(codec->mph)))
          break;
        
        bytes_used++;
        codec->bytes_in_chunk_buffer--;
        bytes_skipped++;
        if(codec->bytes_in_chunk_buffer <= 4)
          {

          if(codec->bytes_in_chunk_buffer > 0)
            memmove(codec->chunk_buffer,
                    codec->chunk_buffer + bytes_used, codec->bytes_in_chunk_buffer);
          return 1;
          }
        }
      if(codec->bytes_in_chunk_buffer < mph.frame_bytes)
        {
        
        if(codec->bytes_in_chunk_buffer > 0)
          memmove(codec->chunk_buffer,
                  codec->chunk_buffer + bytes_used, codec->bytes_in_chunk_buffer);
        return 1;
        }
      
      
      }

    /*
     *  decode an audio frame. return -1 if error, otherwise return the
     *  number of bytes used. If no frame could be decompressed,
     *  frame_size_ptr is zero. Otherwise, it is the decompressed frame
     *  size in BYTES.
     */

#if LIBAVCODEC_BUILD >= 3349760
    bytes_decoded = codec->sample_buffer_alloc -
      (codec->sample_buffer_end - codec->sample_buffer_start);
    bytes_decoded *= 2 * track_map->channels;
#else
    bytes_decoded = 0;
#endif

    
    frame_bytes =
      DECODE_FUNC(codec->avctx,
                           &(codec->sample_buffer[track_map->channels *
                                                  (codec->sample_buffer_end - codec->sample_buffer_start)]),
                           &bytes_decoded,
                           &(codec->chunk_buffer[bytes_used]),
                           codec->bytes_in_chunk_buffer + FF_INPUT_BUFFER_PADDING_SIZE);
    if(frame_bytes < 0)
      {
      lqt_log(file, LQT_LOG_ERROR, LOG_DOMAIN, "avcodec_decode_audio error");
      break;
      }

    bytes_used                   += frame_bytes;
    codec->bytes_in_chunk_buffer -= frame_bytes;
    
    if(bytes_decoded < 0)
      {
      if(codec->avctx->codec_id == CODEC_ID_MP3)
        {
        /* For mp3, bytes_decoded < 0 means, that the frame should be muted */
        memset(&(codec->sample_buffer[track_map->channels * (codec->sample_buffer_end - codec->sample_buffer_start)]),
               0, 2 * mph.samples_per_frame * track_map->channels);
        
        codec->sample_buffer_end += mph.samples_per_frame * track_map->channels;

        if(codec->bytes_in_chunk_buffer < 0)
          codec->bytes_in_chunk_buffer = 0;

        if(!codec->bytes_in_chunk_buffer)
          break;

        continue;
        }
      else
        {
        /* Incomplete frame, save the data for later use and exit here */
        if(codec->bytes_in_chunk_buffer > 0)
          memmove(codec->chunk_buffer,
                  codec->chunk_buffer + bytes_used, codec->bytes_in_chunk_buffer);
        return 1;
        }
      }
    
    /* This happens because ffmpeg adds FF_INPUT_BUFFER_PADDING_SIZE to the bytes returned */
    
    if(codec->bytes_in_chunk_buffer < 0)
      codec->bytes_in_chunk_buffer = 0;

    if(bytes_decoded < 0)
      {
      if(codec->bytes_in_chunk_buffer > 0)
        codec->bytes_in_chunk_buffer = 0;
      break;
      }
    
    samples_decoded += (bytes_decoded / (track_map->channels * 2));
    codec->sample_buffer_end += (bytes_decoded / (track_map->channels * 2));

    if((int)(codec->sample_buffer_end - codec->sample_buffer_start) > codec->sample_buffer_alloc)
      lqt_log(file, LQT_LOG_ERROR, LOG_DOMAIN, "BUUUUG, buffer overflow, %d %d",
              (int)(codec->sample_buffer_end - codec->sample_buffer_start),
              codec->sample_buffer_alloc);
    
    if(!codec->bytes_in_chunk_buffer)
      break;

    }
  //  track_map->current_chunk++;
  return samples_decoded;
  }

static int lqt_ffmpeg_decode_audio(quicktime_t *file, void * output, long samples, int track)
  {
  uint8_t * header;
  uint32_t header_len;
  
  int samples_decoded;
  //  int result = 0;
  int64_t chunk_sample; /* For seeking only */
  quicktime_audio_map_t *track_map = &(file->atracks[track]);
  quicktime_ffmpeg_audio_codec_t *codec = ((quicktime_codec_t*)track_map->codec)->priv;
  int channels = file->atracks[track].channels;
  //  int64_t total_samples;

  int samples_to_skip;
  int samples_to_move;


  if(!output) /* Global initialization */
    {
    return 0;
    }
  
  /* Initialize codec */
  if(!codec->initialized)
    {

    /* Set some mandatory variables */
    codec->avctx->channels        = quicktime_track_channels(file, track);
    codec->avctx->sample_rate     = quicktime_sample_rate(file, track);

    if(track_map->track->mdia.minf.stbl.stsd.table[0].version == 1)
      {
      if(track_map->track->mdia.minf.stbl.stsd.table[0].audio_bytes_per_frame)
        codec->avctx->block_align =
          track_map->track->mdia.minf.stbl.stsd.table[0].audio_bytes_per_frame;
      }
    
    //  priv->ctx->block_align     = s->data.audio.block_align;
    //  priv->ctx->bit_rate        = s->codec_bitrate;

    codec->avctx->bits_per_sample = quicktime_audio_bits(file, track);

    /* Some codecs need extra stuff */

    if(codec->decoder->id == CODEC_ID_ALAC)
      {
      header = quicktime_wave_get_user_atom(track_map->track, "alac", &header_len);
      if(header)
        {
        codec->avctx->extradata = header;
        codec->avctx->extradata_size = header_len;
        }
      }
    if(codec->decoder->id == CODEC_ID_QDM2)
      {
      header = quicktime_wave_get_user_atom(track_map->track, "QDCA", &header_len);
      if(header)
        {
        codec->extradata = malloc(header_len + 12);
        /* frma atom */
        codec->extradata[0] = 0x00;
        codec->extradata[1] = 0x00;
        codec->extradata[2] = 0x00;
        codec->extradata[3] = 0x0C;
        memcpy(codec->extradata + 4, "frmaQDM2", 8);
        /* QDCA atom */
        memcpy(codec->extradata + 12, header, header_len);
        codec->avctx->extradata = codec->extradata;
        codec->avctx->extradata_size = header_len + 12;
        }

      }

    
    //    memcpy(&(codec->com.ffcodec_enc), &(codec->com.params), sizeof(AVCodecContext));
    
    if(avcodec_open(codec->avctx, codec->decoder) != 0)
      {
      lqt_log(file, LQT_LOG_ERROR, LOG_DOMAIN, "Avcodec open failed");
      return 0;
      }
    
    //    codec->sample_buffer_offset = 0;
    codec->initialized = 1;
    }

  /* Check if we have to reposition the stream */
  
  if(track_map->last_position != track_map->current_position)
    {

    if((track_map->current_position < codec->sample_buffer_start) || 
       (track_map->current_position + samples >= codec->sample_buffer_end))
      {
      if(lqt_audio_is_vbr(file, track))
        lqt_chunk_of_sample_vbr(&chunk_sample,
                                &(track_map->current_chunk),
                                track_map->track,
                                track_map->current_position);
      else
        quicktime_chunk_of_sample(&chunk_sample,
                                  &(track_map->current_chunk),
                                  track_map->track,
                                  track_map->current_position);
      codec->sample_buffer_start = chunk_sample;
      codec->sample_buffer_end   = chunk_sample;
      codec->bytes_in_chunk_buffer = 0;

      if(lqt_audio_is_vbr(file, track))
        decode_chunk_vbr(file, track);
      else
        decode_chunk(file, track);
      }
    }
  
  /* Flush unneeded samples */
  samples_to_skip = 0;
  if(track_map->current_position > codec->sample_buffer_start)
    {
    samples_to_skip = track_map->current_position - codec->sample_buffer_start;
    if(samples_to_skip > (int)(codec->sample_buffer_end - codec->sample_buffer_start))
      samples_to_skip = (int)(codec->sample_buffer_end - codec->sample_buffer_start);
    
    if(codec->sample_buffer_end > track_map->current_position)
      {
      samples_to_move = codec->sample_buffer_end - track_map->current_position;

      memmove(codec->sample_buffer,
              &(codec->sample_buffer[samples_to_skip * channels]),
              samples_to_move * channels * sizeof(int16_t));
      }
    codec->sample_buffer_start += samples_to_skip;
    

    }
  samples_to_skip = track_map->current_position - codec->sample_buffer_start;
  
  /* Read new chunks until we have enough samples */
  while(codec->sample_buffer_end - codec->sample_buffer_start < samples + samples_to_skip)
    {
    
    //    if(track_map->current_chunk >= track_map->track->mdia.minf.stbl.stco.total_entries)
    //      return 0;

    if(lqt_audio_is_vbr(file, track))
      {
      if(!decode_chunk_vbr(file, track))
        break;
      }
    else
      {
      if(!decode_chunk(file, track))
        break;
      }
    }
  samples_decoded = codec->sample_buffer_end - codec->sample_buffer_start - samples_to_skip;

  
  if(samples_decoded <= 0)
    {
    track_map->last_position = track_map->current_position;
    return 0;
    }
  if(samples_decoded > samples)
    samples_decoded = samples;
  
  /* Deinterleave into the buffer */
  
  
  //  deinterleave(output_i, output_f, codec->sample_buffer + (track_map->channels * samples_to_skip),
  //               channels, samples_decoded);

  memcpy(output, codec->sample_buffer + (channels * samples_to_skip),
         channels * samples_decoded * 2);
  
  track_map->last_position = track_map->current_position + samples_decoded;

  return samples_decoded;
  // #endif
  }

/*
 *   Encoding part
 */

static int lqt_ffmpeg_encode_audio(quicktime_t *file, void * input,
                            long samples, int track)
  {
  int result = -1;
  quicktime_audio_map_t *track_map = &(file->atracks[track]);
  quicktime_ffmpeg_audio_codec_t *codec = ((quicktime_codec_t*)track_map->codec)->priv;
  quicktime_trak_t *trak = track_map->track;
  int channels = file->atracks[track].channels;
  quicktime_atom_t chunk_atom;
  int frame_bytes;
  int samples_done = 0;
  int samples_encoded;
  /* Initialize encoder */
    
  if(!codec->initialized)
    {
    codec->avctx->sample_rate = track_map->samplerate;
    codec->avctx->channels = channels;

    if(avcodec_open(codec->avctx, codec->encoder) != 0)
      {
      lqt_log(file, LQT_LOG_ERROR, LOG_DOMAIN, "Avcodec open failed");
      return -1;
      }
    
    codec->initialized = 1;

    /* One frame is: bitrate * frame_samples / (samplerate * 8) + 1024 */
#if 0		// PATCH 1
    codec->chunk_buffer_alloc = (codec->avctx->bit_rate * codec->avctx->frame_size /
                                (codec->avctx->sample_rate * 8)) + 1024;
#else
    codec->chunk_buffer_alloc = ( codec->avctx->frame_size
									* sizeof( int16_t )
									* codec->avctx->channels
								);
#endif
    codec->chunk_buffer = malloc(codec->chunk_buffer_alloc);
    }

  /* Allocate sample buffer if necessary */

//         PATCH 2 
  if(codec->sample_buffer_alloc < (codec->samples_in_buffer + samples))
    {
    codec->sample_buffer_alloc = codec->samples_in_buffer + samples + 16;
    codec->sample_buffer = realloc(codec->sample_buffer,
                                   codec->sample_buffer_alloc * channels * sizeof(int16_t));
    }

  /* Interleave */

  //  interleave(&(codec->sample_buffer[codec->samples_in_buffer * channels]),
  //             input_i, input_f, samples, channels);

  memcpy(codec->sample_buffer + codec->samples_in_buffer * channels,
         input, samples * channels * 2);
  
  codec->samples_in_buffer += samples;
  
  /* Encode */
  
  while(codec->samples_in_buffer >= codec->avctx->frame_size)
    {
    
    frame_bytes = avcodec_encode_audio(codec->avctx, codec->chunk_buffer,
                                       codec->chunk_buffer_alloc,
                                       &(codec->sample_buffer[samples_done*channels]));
    if(frame_bytes > 0)
      {
      quicktime_write_chunk_header(file, trak, &chunk_atom);
#if 0    // PATCH 3  
      if(codec->avctx->frame_size == 1)
        samples_encoded = codec->samples_in_buffer;
      else
#endif
        samples_encoded = codec->avctx->frame_size;


      samples_done              += samples_encoded;
      codec->samples_in_buffer  -= samples_encoded;
      
      result = !quicktime_write_data(file, codec->chunk_buffer, frame_bytes);
      quicktime_write_chunk_footer(file,
                                   trak, 
                                   file->atracks[track].current_chunk,
                                   &chunk_atom, 
                                   samples_encoded);
      file->atracks[track].current_chunk++;
      }
    }
  if(codec->samples_in_buffer && samples_done)
    memmove(codec->sample_buffer, &(codec->sample_buffer[samples_done*channels]),
            codec->samples_in_buffer * sizeof(int16_t) * channels);
  return result;
  }

void quicktime_init_audio_codec_ffmpeg(quicktime_audio_map_t *atrack, AVCodec *encoder,
                                       AVCodec *decoder)
{
	quicktime_ffmpeg_audio_codec_t *codec;

	avcodec_init();
	codec = calloc(1, sizeof(quicktime_ffmpeg_audio_codec_t));
	if(!codec)
          return;

	codec->encoder = encoder;
	codec->decoder = decoder;
	codec-> avctx = avcodec_alloc_context();
	((quicktime_codec_t*)atrack->codec)->priv = (void *)codec;
	((quicktime_codec_t*)atrack->codec)->delete_acodec = lqt_ffmpeg_delete_audio;
	if(encoder)
          ((quicktime_codec_t*)atrack->codec)->encode_audio = lqt_ffmpeg_encode_audio;
	if(decoder)
          ((quicktime_codec_t*)atrack->codec)->decode_audio = lqt_ffmpeg_decode_audio;
	((quicktime_codec_t*)atrack->codec)->set_parameter = set_parameter;
        atrack->sample_format = LQT_SAMPLE_INT16;
}