1 /*
2  *  aud_aux.c
3  *
4  *  Copyright (C) Thomas Oestreich - June 2001
5  *  Copyright (C) Nicolas LAURENT - August 2003
6  *
7  *  This file is part of transcode, a video stream processing tool
8  *
9  *  transcode is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 2, or (at your option)
12  *  any later version.
13  *
14  *  transcode is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with GNU Make; see the file COPYING.  If not, write to
21  *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
22  *
23  */
24 
25 #include "transcode.h"
26 #include "aud_aux.h"
27 
28 #include "libtc/libtc.h"
29 
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <sys/stat.h>
34 #include <unistd.h>
35 #include <fcntl.h>
36 #include <stdint.h>
37 #include <assert.h>
38 
39 #ifdef HAVE_LAME
40 #ifdef HAVE_LAME_INC
41 #include <lame/lame.h>
42 #else
43 #include <lame.h>
44 #endif
45 #endif
46 
47 #ifdef HAVE_FFMPEG
48 #include "libtc/tcavcodec.h"
49 
50 
51 static AVCodec        *mpa_codec = NULL;
52 static AVCodecContext mpa_ctx;
53 static char           *mpa_buf     = NULL;
54 static int            mpa_buf_ptr  = 0;
55 static int            mpa_bytes_ps, mpa_bytes_pf;
56 
57 #endif
58 
59 /*
60  * Capabilities:
61  *
62  *             +-------------------------------+
63  *             |             Output            |
64  *             +-------------------------------+
65  *             |  PCM  |  MP2  |  MP3  |  AC3  |
66  * +---+-------+-------+-------+-------+-------+
67  * | I |  PCM  |   X   |   X   |   X   |   X   |
68  * | n +-------+-------+-------+-------+-------+
69  * | p |  MP2  |       |   X   |       |       |
70  * | u +-------+-------+-------+-------+-------+
71  * | t |  MP3  |       |       |   X   |       |
72  * |   +-------+-------+-------+-------+-------+
73  * |   |  AC3  |       |       |       |   X   |
74  * +---+---------------------------------------+
75  *
76  */
77 
78 
79 /*-----------------------------------------------------------------------------
80                        G L O B A L   V A R I A B L E S
81 -----------------------------------------------------------------------------*/
82 
83 #define MP3_CHUNK_SZ (2*1152)
84 
85 static int verbose_flag=TC_DEBUG;
86 #define IS_AUDIO_MONO   (avi_aud_chan == 1)
87 #ifdef HAVE_LAME
88 #define IS_VBR      (lame_get_VBR(lgf) != vbr_off)
89 #endif
90 
91 /* Output buffer */
92 #define OUTPUT_SIZE SIZE_PCM_FRAME
93 static char *output   = NULL;
94 #ifdef HAVE_LAME
95 static int output_len = 0;
96 #endif
97 
98 /* Input buffer */
99 #define INPUT_SIZE  SIZE_PCM_FRAME
100 static char *input   = NULL;
101 #ifdef HAVE_LAME
102 static int input_len = 0;
103 #endif
104 
105 /* encoder */
106 static int (*tc_audio_encode_function)(char *, int, avi_t *)=NULL;
107 #ifdef HAVE_LAME
108 static lame_global_flags *lgf;
109 #endif
110 static int lame_flush=0;
111 static int bitrate=0;
112 
113 /* output stream */
114 static avi_t *avifile2=NULL;
115 static FILE *fd=NULL;
116 static int is_pipe = 0;
117 
118 // AVI file information for subsequent calls of open routine:
119 static int avi_aud_codec, avi_aud_bitrate;
120 static long avi_aud_rate;
121 static int avi_aud_chan, avi_aud_bits;
122 
123 /*-----------------------------------------------------------------------------
124                              P R O T O T Y P E S
125 -----------------------------------------------------------------------------*/
126 
127 static int tc_audio_init_ffmpeg(vob_t *vob, int o_codec);
128 static int tc_audio_init_lame(vob_t *vob, int o_codec);
129 static int tc_audio_init_raw(vob_t *vob);
130 static int tc_audio_write(char *buffer, size_t size, avi_t *avifile);
131 static int tc_audio_encode_ffmpeg(char *aud_buffer, int aud_size, avi_t *avifile);
132 static int tc_audio_encode_mp3(char *aud_buffer, int aud_size, avi_t *avifile);
133 static int tc_audio_pass_through(char *aud_buffer, int aud_size, avi_t *avifile);
134 static int tc_audio_pass_through_ac3(char *aud_buffer, int aud_size, avi_t *avifile);
135 static int tc_audio_pass_through_pcm(char *aud_buffer, int aud_size, avi_t *avifile);
136 static int tc_audio_mute(char *aud_buffer, int aud_size, avi_t *avifile);
137 #ifdef HAVE_LAME
138 static char * lame_error2str(int error);
no_debug(const char * format,va_list ap)139 static void no_debug(const char *format, va_list ap) {return;}
140 static int tc_get_mp3_header(unsigned char* hbuf, int* chans, int* srate);
141 #endif
142 
143 /**
144  * Init Lame Encoder
145  *
146  * @param vob
147  *
148  * @return TC_EXPORT_OK or TC_EXPORT_ERROR
149  */
tc_audio_init_lame(vob_t * vob,int o_codec)150 static int tc_audio_init_lame(vob_t *vob, int o_codec)
151 {
152     static int initialized=0;
153     int res = TC_EXPORT_ERROR;
154 
155     if (!initialized)
156         if (verbose_flag & TC_DEBUG)
157             tc_info("Audio: using new version");
158 
159     if(initialized==0)
160     {
161 #ifdef HAVE_LAME
162         int preset = 0;
163         lgf=lame_init();
164         if(lgf<0)
165         {
166             tc_warn("Lame encoder init failed.");
167             return(TC_EXPORT_ERROR);
168         }
169 
170         if(!(verbose_flag & TC_DEBUG)) lame_set_msgf  (lgf, no_debug);
171         if(!(verbose_flag & TC_DEBUG)) lame_set_debugf(lgf, no_debug);
172         if(!(verbose_flag & TC_DEBUG)) lame_set_errorf(lgf, no_debug);
173 
174         lame_set_bWriteVbrTag(lgf, 0);
175         lame_set_quality(lgf, vob->mp3quality);
176 
177         /* Setting bitrate */
178         if(vob->a_vbr)
179         { /* VBR */
180             lame_set_VBR(lgf, vob->a_vbr);
181             /*  1 = best vbr q  6=~128k */
182             lame_set_VBR_q(lgf, vob->mp3quality);
183             /*
184              * if(vob->mp3bitrate>0)
185              *  lame_set_VBR_mean_bitrate_kbps(
186              *      lgf,
187              *      vob->mp3bitrate);
188              */
189         } else {
190             lame_set_VBR(lgf, 0);
191             lame_set_brate(lgf, vob->mp3bitrate);
192         }
193 
194         /* Playing with bitreservoir */
195         if(vob->bitreservoir == TC_FALSE)
196             lame_set_disable_reservoir(lgf, 1);
197 
198         /* Mono / Sterero ? */
199         if (IS_AUDIO_MONO)
200         {
201             lame_set_num_channels(lgf, avi_aud_chan);
202             lame_set_mode(lgf, MONO);
203         } else {
204             lame_set_num_channels(lgf, 2);
205             lame_set_mode(lgf, JOINT_STEREO);
206         }
207         /* Overide defaults */
208         if (vob->mp3mode==1)
209             lame_set_mode(lgf, STEREO);
210         if (vob->mp3mode==2)
211             lame_set_mode(lgf, MONO);
212 
213         /* sample rate */
214         lame_set_in_samplerate(lgf, vob->a_rate);
215         lame_set_out_samplerate(lgf, avi_aud_rate);
216 
217         /* Optimisations */
218         if(tc_accel & AC_MMX)
219             lame_set_asm_optimizations(lgf, MMX, 1);
220 
221         if(tc_accel & AC_3DNOW)
222             lame_set_asm_optimizations(lgf, AMD_3DNOW, 1);
223 
224         if(tc_accel & AC_SSE)
225             lame_set_asm_optimizations(lgf, SSE, 1);
226 
227 
228         /* Preset stuff */
229         if (vob->lame_preset && strlen (vob->lame_preset))
230         {
231             char *c = strchr (vob->lame_preset, ',');
232             int fast = 0;
233 
234             if (c && *c && *(c+1)) {
235                 if (strcmp(c+1, "fast"))
236                 {
237                     *c = '\0';
238                     fast = 1;
239                 }
240             }
241 
242             if (strcmp (vob->lame_preset, "standard") == 0)
243             {
244                 preset = fast?STANDARD_FAST:STANDARD;
245                 vob->a_vbr = 1;
246             }
247             else if (strcmp (vob->lame_preset, "medium") == 0)
248             {
249                 preset = fast?MEDIUM_FAST:MEDIUM;
250                 vob->a_vbr = 1;
251             }
252             else if (strcmp (vob->lame_preset, "extreme") == 0)
253             {
254                 preset = fast?EXTREME_FAST:EXTREME;
255                 vob->a_vbr = 1;
256             }
257             else if (strcmp (vob->lame_preset, "insane") == 0) {
258                 preset = INSANE;
259                 vob->a_vbr = 1;
260             }
261             else if ( atoi(vob->lame_preset) != 0)
262             {
263                 vob->a_vbr = 1;
264                 preset = atoi(vob->lame_preset);
265                 avi_aud_bitrate = preset;
266             }
267             else
268                 tc_warn("Lame preset `%s' not supported. "
269                         "Falling back defaults.",
270                         vob->lame_preset);
271 
272             if (fast == 1)
273                 *c = ',';
274 
275             if (preset)
276             {
277                 if (verbose_flag & TC_DEBUG)
278                     tc_info("Using Lame preset `%s'.",
279                             vob->lame_preset);
280                 lame_set_preset(lgf, preset);
281             }
282         }
283 
284         /* Init Lame ! */
285         lame_init_params(lgf);
286         if(verbose_flag)
287             tc_info("Audio: using lame-%s",
288                 get_lame_version());
289         if (verbose_flag & TC_DEBUG) {
290             tc_info("Lame config: PCM -> %s",
291                     (o_codec==CODEC_MP3)?"MP3":"MP2");
292             tc_info("             bitrate         : %d kbit/s",
293                     vob->mp3bitrate);
294             tc_info("             ouput samplerate: %d Hz",
295                     (vob->mp3frequency>0)?vob->mp3frequency:vob->a_rate);
296         }
297         /* init lame encoder only on first call */
298         initialized = 1;
299         res = TC_EXPORT_OK;
300 
301 #else  /* HAVE_LAME */
302         tc_warn("No Lame support available!");
303 #endif /* HAVE_LAME */
304     }
305 
306     return res;
307 }
308 
309 
310 
311 /**
312  * Init FFMPEG AUDIO Encoder
313  *
314  * @param vob
315  *
316  * @return TC_EXPORT_OK or TC_EXPORT_ERROR
317  */
tc_audio_init_ffmpeg(vob_t * vob,int o_codec)318 static int tc_audio_init_ffmpeg(vob_t *vob, int o_codec)
319 {
320     int init_ret = TC_EXPORT_ERROR;
321 #ifdef HAVE_FFMPEG
322     unsigned long codeid = 0;
323     int ret = 0;
324 
325     TC_INIT_LIBAVCODEC;
326 
327     switch (o_codec) {
328       case   0x50:
329         codeid = AV_CODEC_ID_MP2;
330         break;
331       case 0x2000:
332         codeid = AV_CODEC_ID_AC3;
333         break;
334       default:
335         tc_warn("cannot init ffmpeg with %x", o_codec);
336     }
337 
338     //-- get it --
339     mpa_codec = avcodec_find_encoder(codeid);
340     if (!mpa_codec) {
341       tc_log_warn("encode_ffmpeg", "mpa codec not found !");
342       return(TC_EXPORT_ERROR);
343     }
344 
345     // OPEN
346 
347     //-- set parameters (bitrate, channels and sample-rate) --
348     //--------------------------------------------------------
349     avcodec_get_context_defaults3(&mpa_ctx, mpa_codec);
350 #if LIBAVCODEC_VERSION_MAJOR < 53
351     mpa_ctx.codec_type  = CODEC_TYPE_AUDIO;
352 #else
353     mpa_ctx.codec_type  = AVMEDIA_TYPE_AUDIO;
354 #endif
355     mpa_ctx.bit_rate    = vob->mp3bitrate * 1000;  // bitrate dest.
356     mpa_ctx.channels    = vob->dm_chan;            // channels
357     mpa_ctx.sample_rate = vob->a_rate;
358 
359     //-- open codec --
360     //----------------
361     TC_LOCK_LIBAVCODEC;
362     ret = avcodec_open2(&mpa_ctx, mpa_codec, NULL);
363     TC_UNLOCK_LIBAVCODEC;
364     if (ret < 0) {
365         tc_warn("tc_audio_init_ffmpeg: could not open %s codec !",
366                 (codeid == AV_CODEC_ID_MP2) ?"mpa" :"ac3");
367         return(TC_EXPORT_ERROR);
368     }
369 
370     //-- bytes per sample and bytes per frame --
371     mpa_bytes_ps = mpa_ctx.channels * vob->dm_bits/8;
372     mpa_bytes_pf = mpa_ctx.frame_size * mpa_bytes_ps;
373 
374     //-- create buffer to hold 1 frame --
375     mpa_buf     = malloc(mpa_bytes_pf);
376     mpa_buf_ptr = 0;
377     init_ret    = TC_EXPORT_OK;
378 
379 #else  /* HAVE_FFMPEG */
380     tc_warn("No FFmpeg support available!");
381 #endif /* HAVE_FFMPEG */
382 
383     return init_ret;
384 
385 }
386 
387 
388 /**
389  * Init audio encoder RAW -> *
390  *
391  * @param vob
392  *
393  * @return TC_EXPORT_OK or TC_EXPORT_ERROR
394  */
tc_audio_init_raw(vob_t * vob)395 static int tc_audio_init_raw(vob_t *vob)
396 {
397     if(vob->pass_flag & TC_AUDIO)
398     {
399         avi_t *avifile;
400 
401         avifile = AVI_open_input_file(vob->audio_in_file, 1);
402         if(avifile != NULL)
403         {
404             /* set correct pass-through track: */
405             AVI_set_audio_track(avifile, vob->a_track);
406 
407             /*
408              * small hack to fix incorrect samplerates caused by
409              * transcode < 0.5.0-20011109
410              */
411             if (vob->mp3frequency==0)
412                 vob->mp3frequency=AVI_audio_rate(avifile);
413 
414             avi_aud_rate    =  vob->mp3frequency;
415             avi_aud_chan    =  AVI_audio_channels(avifile);
416             avi_aud_bits    =  AVI_audio_bits(avifile);
417             avi_aud_codec   =  AVI_audio_format(avifile);
418             avi_aud_bitrate =  AVI_audio_mp3rate(avifile);
419 
420             AVI_close(avifile);
421         } else {
422             AVI_print_error("avi open error");
423             return(TC_EXPORT_ERROR);
424         }
425     } else
426         tc_audio_encode_function=tc_audio_mute;
427 
428     return(TC_EXPORT_OK);
429 }
430 
431 
432 /**
433  * init audio encoder
434  *
435  * @param vob
436  * @param v is TC_DEBUG for verbose output or 0
437  *
438  * @return  TC_EXPORT_OK or TC_EXPORT_ERROR
439  */
440 
tc_audio_init(vob_t * vob,int v)441 int tc_audio_init(vob_t *vob, int v)
442 {
443     int ret=TC_EXPORT_OK;
444     int sample_size;
445     verbose_flag=v;
446 
447     /* Default */
448     avi_aud_bitrate = vob->mp3bitrate;
449     avi_aud_codec = vob->ex_a_codec;
450 
451     avi_aud_bits=vob->dm_bits;
452     avi_aud_chan=vob->dm_chan;
453     avi_aud_rate=(vob->mp3frequency != 0)?vob->mp3frequency:vob->a_rate;
454 
455     lame_flush=vob->encoder_flush;
456 
457     /* For encoding */
458     sample_size = avi_aud_bits * 8 * avi_aud_chan;
459 
460     /*
461      * Sanity checks
462      */
463     if((sample_size == 0) &&
464        (vob->im_a_codec != CODEC_NULL))
465     {
466         tc_warn("Zero sample size detected for audio format `0x%x'. "
467               "Muting.", vob->im_a_codec);
468         tc_audio_encode_function=tc_audio_mute;
469         return(TC_EXPORT_OK);
470     }
471 
472     output = malloc (OUTPUT_SIZE);
473     input  = malloc (INPUT_SIZE);
474     if (!output || !input) {
475         tc_log_error(__FILE__, "(%s:%d) Out of memory", __FILE__, __LINE__);
476         return (TC_EXPORT_ERROR);
477     }
478 
479 
480     /* paranoia... */
481     memset (output, 0, OUTPUT_SIZE);
482     memset (input, 0, INPUT_SIZE);
483 
484     if (verbose_flag & TC_DEBUG)
485         tc_info("Audio submodule in=0x%x out=0x%x", vob->im_a_codec, vob->ex_a_codec);
486 
487     switch(vob->im_a_codec)
488     {
489     case CODEC_PCM:
490         switch(vob->ex_a_codec)
491         {
492         case CODEC_NULL:
493             tc_audio_encode_function = tc_audio_mute;
494             break;
495 
496         case CODEC_MP3:
497             ret=tc_audio_init_lame(vob, vob->ex_a_codec);
498             tc_audio_encode_function = tc_audio_encode_mp3;
499             break;
500 
501         case CODEC_PCM:
502             tc_info("PCM -> PCM");
503             /* adjust bitrate with magic ! */
504             avi_aud_bitrate=(vob->a_rate*4)/1000*8;
505             tc_audio_encode_function = tc_audio_pass_through_pcm;
506             break;
507 
508         case CODEC_MP2:
509             tc_info("PCM -> MP2");
510             ret=tc_audio_init_ffmpeg(vob, vob->ex_a_codec);
511             tc_audio_encode_function = tc_audio_encode_ffmpeg;
512             break;
513 
514         case CODEC_AC3:
515             tc_info("PCM -> AC3");
516             ret=tc_audio_init_ffmpeg(vob, vob->ex_a_codec);
517             tc_audio_encode_function = tc_audio_encode_ffmpeg;
518             break;
519 
520         default:
521             tc_warn("Conversion not supported (in=0x%x out=0x%x)",
522                     vob->im_a_codec, vob->ex_a_codec);
523             ret=TC_EXPORT_ERROR;
524             break;
525         }
526         break;
527 
528     case CODEC_MP2:
529     case CODEC_MP3: /* only pass through supported */
530         switch(vob->ex_a_codec)
531         {
532         case CODEC_NULL:
533             tc_audio_encode_function = tc_audio_mute;
534             break;
535 
536         case CODEC_MP2:
537         case CODEC_MP3:
538             tc_audio_encode_function = tc_audio_pass_through;
539             break;
540 
541         default:
542             tc_warn("Conversion not supported (in=x0%x out=x0%x)",
543                     vob->im_a_codec, vob->ex_a_codec);
544             ret=TC_EXPORT_ERROR;
545             break;
546         }
547         break;
548 
549     case CODEC_AC3: /* only pass through supported */
550         switch(vob->ex_a_codec)
551         {
552         case CODEC_NULL:
553             tc_audio_encode_function = tc_audio_mute;
554             break;
555 
556         case CODEC_AC3:
557             tc_info("AC3->AC3");
558             if (vob->audio_file_flag) {
559                 tc_audio_encode_function = tc_audio_pass_through;
560             } else {
561                 tc_audio_encode_function = tc_audio_pass_through_ac3;
562             }
563             /*
564              *the bitrate can only be determined in the encoder
565              * section. `bitrate_flags' will be set to 1 after
566              * bitrate is determined.
567              */
568             break;
569         default:
570             tc_warn("Conversion not supported (in=0x%x out=0x%x)",
571                     vob->im_a_codec, vob->ex_a_codec);
572             ret=TC_EXPORT_ERROR;
573             break;
574         }
575         break;
576 
577     case CODEC_NULL: /* no audio requested */
578         tc_audio_encode_function = tc_audio_mute;
579         break;
580 
581     case CODEC_RAW: /* pass-through mode */
582         tc_audio_encode_function = tc_audio_pass_through;
583         ret=tc_audio_init_raw(vob);
584         break;
585 
586     default:
587         tc_warn("Conversion not supported (in=x0%x out=x0%x)",
588               vob->im_a_codec, vob->ex_a_codec);
589         ret=TC_EXPORT_ERROR;
590         break;
591     }
592 
593     return(ret);
594 }
595 
596 
597 /**
598  * open audio output file
599  *
600  * @param vob
601  * @param avifile
602  *
603  * @return TC_EXPORT_OK or TC_EXPORT_ERROR
604  */
tc_audio_open(vob_t * vob,avi_t * avifile)605 int tc_audio_open(vob_t *vob, avi_t *avifile)
606 {
607     if (tc_audio_encode_function != tc_audio_mute)
608     {
609         if(vob->audio_file_flag)
610         {
611             if(! fd)
612             {
613                 if (vob->audio_out_file[0] == '|')
614                 {
615                     fd = popen(vob->audio_out_file+1, "w");
616                     if (! fd)
617                     {
618                         tc_warn("Cannot popen() audio "
619                                 "file `%s'",
620                                 vob->audio_out_file+1);
621                         return(TC_EXPORT_ERROR);
622                     }
623                     is_pipe = 1;
624                 } else {
625                     fd = fopen(vob->audio_out_file, "w");
626                     if (! fd)
627                     {
628                         tc_warn("Cannot open() audio "
629                               "file `%s'",
630                               vob->audio_out_file);
631                         return(TC_EXPORT_ERROR);
632                     }
633                 }
634             }
635 
636             if (verbose_flag & TC_DEBUG)
637                 tc_info("Sending audio output to %s",
638                         vob->audio_out_file);
639         } else {
640 
641             if(avifile==NULL)
642             {
643                 tc_audio_encode_function = tc_audio_mute;
644                 tc_info("No option `-m' found. Muting sound.");
645                 return(TC_EXPORT_OK);
646             }
647 
648             AVI_set_audio(avifile,
649                       avi_aud_chan,
650                       avi_aud_rate,
651                       avi_aud_bits,
652                       avi_aud_codec,
653                       avi_aud_bitrate);
654             AVI_set_audio_vbr(avifile, vob->a_vbr);
655 
656             if (vob->avi_comment_fd > 0)
657                 AVI_set_comment_fd(avifile,
658                            vob->avi_comment_fd);
659 
660             if(avifile2 == NULL)
661                 avifile2 = avifile; /* save for close */
662 
663             if (verbose_flag & TC_DEBUG)
664                 tc_info("AVI stream: format=0x%x, rate=%ld Hz, "
665                         "bits=%d, channels=%d, bitrate=%d",
666                         avi_aud_codec,
667                         avi_aud_rate,
668                         avi_aud_bits,
669                         avi_aud_chan,
670                         avi_aud_bitrate);
671         }
672     }
673 
674     return(TC_EXPORT_OK);
675 }
676 
677 
678 /**
679  * Write audio data to output stream
680  */
tc_audio_write(char * buffer,size_t size,avi_t * avifile)681 static int tc_audio_write(char *buffer, size_t size, avi_t *avifile)
682 {
683     if (fd != NULL) {
684         if (fwrite(buffer, size, 1, fd) != 1) {
685             tc_warn("Audio file write error (errno=%d) [%s].", errno, strerror(errno));
686             return(TC_EXPORT_ERROR);
687         }
688     } else {
689         if (AVI_write_audio(avifile, buffer, size) < 0) {
690             AVI_print_error("AVI file audio write error");
691             return(TC_EXPORT_ERROR);
692         }
693     }
694 
695     return(TC_EXPORT_OK);
696 }
697 
698 
699 /**
700  * encode audio frame in MP3 format
701  *
702  * @param aud_buffer is the input buffer ?
703  * @param aud_size is the input buffer length
704  * @param avifile is the output stream
705  *
706  * @return
707  *
708  * How this code works:
709  *
710  * We always encode raw audio chunks which are MP3_CHUNK_SZ (==2304)
711  * bytes large. `input' contains the raw audio buffer contains
712  * the encoded audio
713  *
714  * It is possible (very likely) that lame cannot produce a valid mp3
715  * chunk per "audio frame" so we do not write out any compressed audio.
716  * We need to buffer the not consumed input audio where another 2304
717  * bytes chunk won't fit in AND we need to buffer the already encoded
718  * but not enough audio.
719  *
720  * To find out how much we actually need to encode we decode the mp3
721  * header of the recently encoded audio chunk and read out the actual
722  * length.
723  *
724  * Then we write the audio. There can either be more than one valid mp3
725  * frame in buffer and/or still enough raw data left to encode one.
726  *
727  * Easy, eh? -- tibit.
728  */
tc_audio_encode_mp3(char * aud_buffer,int aud_size,avi_t * avifile)729 static int tc_audio_encode_mp3(char *aud_buffer, int aud_size, avi_t *avifile)
730 {
731 #ifdef HAVE_LAME
732     int outsize=0;
733     int count=0;
734 
735     /*
736      * Apend the new incoming audio to the already available but not yet
737      * consumed.
738      */
739         ac_memcpy (input+input_len, aud_buffer, aud_size);
740     input_len += aud_size;
741     if (verbose_flag & TC_DEBUG)
742         tc_info("audio_encode_mp3: input buffer size=%d", input_len);
743 
744     /*
745      * As long as lame doesn't return encoded data (lame needs to fill its
746      * internal buffers) AND as long as there is enough input data left.
747      */
748     while(input_len >= MP3_CHUNK_SZ)
749     {
750         if(IS_AUDIO_MONO)
751         {
752             outsize = lame_encode_buffer(
753                 lgf,
754                 (short int *)(input+count*MP3_CHUNK_SZ),
755                 (short int *)(input+count*MP3_CHUNK_SZ),
756                 MP3_CHUNK_SZ/2,
757                 output+output_len,
758                 OUTPUT_SIZE - output_len);
759         } else {
760             outsize = lame_encode_buffer_interleaved(
761                 lgf,
762                 (short int *) (input+count*MP3_CHUNK_SZ),
763                 MP3_CHUNK_SZ/4,
764                 output + output_len,
765                 OUTPUT_SIZE - output_len);
766         }
767 
768         if(outsize < 0)
769         {
770             tc_warn("Lame encoding error: (%s)",
771                     lame_error2str(outsize));
772             return(TC_EXPORT_ERROR);
773         }
774 
775         output_len += outsize;
776         input_len  -= MP3_CHUNK_SZ;
777 
778         ++count;
779 
780         if (verbose_flag & TC_DEBUG)
781             tc_info("Encoding: count=%d outsize=%d output_len=%d "
782                 "consumed=%d",
783                 count, outsize, output_len, count*MP3_CHUNK_SZ);
784     }
785     /* Update input */
786     memmove(input, input+count*MP3_CHUNK_SZ, input_len);
787 
788 
789     if (verbose_flag & TC_DEBUG)
790         tc_info("output_len=%d input_len=%d count=%d",
791             output_len, input_len, count);
792 
793     /* If we don't have any output data, there's nothing to do */
794     if (output_len == 0) {
795         return(TC_EXPORT_OK);
796     }
797 
798     /*
799      * Now, it's time to write mp3 data to output stream...
800      */
801     if (IS_VBR)
802     {
803         int offset=0;
804         int size;
805 
806         /*
807          * In VBR mode, we should write _complete_ chunk. And their
808          * size may change from one to other... So we should analyse
809          * each one and write it if enough data is avaible.
810          */
811 
812         if (verbose_flag & TC_DEBUG)
813             tc_info("Writing... (output_len=%d)\n", output_len);
814         while((size=tc_get_mp3_header(output+offset, NULL, NULL)) > 0)
815         {
816             if (size > output_len)
817                 break;
818 
819             if (verbose_flag & TC_DEBUG)
820                 tc_info("Writing chunk of size=%d", size);
821             tc_audio_write(output+offset, size, avifile);
822             offset += size;
823             output_len -= size;
824         }
825         memmove(output, output+offset, output_len);
826         if (verbose_flag & TC_DEBUG)
827             tc_info("Writing OK (output_len=%d)", output_len);
828     } else {
829         /*
830          * in CBR mode, write our data in simplest way.
831          * Thinking too much about chunk will break audio playback
832          * on archos Jukebox Multimedia...
833          */
834         tc_audio_write(output, output_len, avifile);
835         output_len=0;
836     }
837     return(TC_EXPORT_OK);
838 #else   // HAVE_LAME
839     tc_warn("No Lame support available!");
840     return(TC_EXPORT_ERROR);
841 #endif
842 }
843 
tc_audio_encode_ffmpeg(char * aud_buffer,int aud_size,avi_t * avifile)844 static int tc_audio_encode_ffmpeg(char *aud_buffer, int aud_size, avi_t *avifile)
845 {
846 #ifdef HAVE_FFMPEG
847     int  in_size, out_size;
848     char *in_buf;
849 
850     //-- input buffer and amount of bytes --
851     in_size = aud_size;
852     in_buf  = aud_buffer;
853 
854     //-- any byte in mpa-buffer left from past call ? --
855     //--------------------------------------------------
856     if (mpa_buf_ptr > 0) {
857 
858       int bytes_needed, bytes_avail;
859 
860       bytes_needed = mpa_bytes_pf - mpa_buf_ptr;
861       bytes_avail  = in_size;
862 
863       //-- complete frame -> encode --
864       //------------------------------
865       if ( bytes_avail >= bytes_needed ) {
866 
867     ac_memcpy(&mpa_buf[mpa_buf_ptr], in_buf, bytes_needed);
868 
869     TC_LOCK_LIBAVCODEC;
870     out_size = avcodec_encode_audio(&mpa_ctx, (unsigned char *)output,
871                     OUTPUT_SIZE, (short *)mpa_buf);
872     TC_UNLOCK_LIBAVCODEC;
873     tc_audio_write(output, out_size, avifile);
874 
875         in_size -= bytes_needed;
876         in_buf  += bytes_needed;
877 
878         mpa_buf_ptr = 0;
879       }
880 
881       //-- incomplete frame -> append bytes to mpa-buffer and return --
882       //---------------------------------------------------------------
883       else {
884 
885     ac_memcpy(&mpa_buf[mpa_buf_ptr], aud_buffer, bytes_avail);
886         mpa_buf_ptr += bytes_avail;
887         return (0);
888       }
889     } //bytes availabe from last call?
890 
891 
892     //-- encode only as much "full" frames as available --
893     //----------------------------------------------------
894 
895     while (in_size >= mpa_bytes_pf) {
896       TC_LOCK_LIBAVCODEC;
897       out_size = avcodec_encode_audio(&mpa_ctx, (unsigned char *)output,
898                       OUTPUT_SIZE, (short *)in_buf);
899       TC_UNLOCK_LIBAVCODEC;
900 
901       tc_audio_write(output, out_size, avifile);
902 
903       in_size -= mpa_bytes_pf;
904       in_buf  += mpa_bytes_pf;
905     }
906 
907     //-- hold rest of bytes in mpa-buffer --
908     //--------------------------------------
909     if (in_size > 0) {
910       mpa_buf_ptr = in_size;
911       ac_memcpy(mpa_buf, in_buf, mpa_buf_ptr);
912     }
913 
914     return(TC_EXPORT_OK);
915 #else   // HAVE_FFMPEG
916     tc_warn("No FFMPEG support available!");
917     return(TC_EXPORT_ERROR);
918 #endif
919 }
920 
tc_audio_pass_through_ac3(char * aud_buffer,int aud_size,avi_t * avifile)921 static int tc_audio_pass_through_ac3(char *aud_buffer, int aud_size, avi_t *avifile)
922 {
923     if(bitrate == 0)
924     {
925         int i;
926         uint16_t sync_word = 0;
927 
928         /* try to determine bitrate from audio frame: */
929         for(i=0;i<aud_size-3;++i)
930         {
931             sync_word = (sync_word << 8) + (uint8_t) aud_buffer[i];
932             if(sync_word == 0x0b77)
933             {
934                 /* from import/ac3scan.c */
935                 static const int bitrates[] = {
936                     32, 40, 48, 56,
937                     64, 80, 96, 112,
938                     128, 160, 192, 224,
939                     256, 320, 384, 448,
940                     512, 576, 640
941                 };
942                 int ratecode = (aud_buffer[i+3] & 0x3E) >> 1;
943                 if (ratecode < sizeof(bitrates)/sizeof(*bitrates))
944                     bitrate = bitrates[ratecode];
945                 break;
946             }
947         }
948 
949         /* assume bitrate > 0 is OK. */
950         if (bitrate > 0)
951         {
952             AVI_set_audio_bitrate(avifile, bitrate);
953             if (verbose_flag & TC_DEBUG)
954                 tc_info("bitrate %d kBits/s", bitrate);
955         }
956     }
957 
958     return(tc_audio_write(aud_buffer, aud_size, avifile));
959 }
960 
961 
962 /**
963  *
964  */
tc_audio_pass_through_pcm(char * aud_buffer,int aud_size,avi_t * avifile)965 static int tc_audio_pass_through_pcm(char *aud_buffer, int aud_size, avi_t *avifile)
966 {
967 #ifdef WORDS_BIGENDIAN
968     int i;
969     char tmp;
970 
971     for(i=0; i<aud_size; i+=2)
972     {
973         tmp = aud_buffer[i+1];
974         aud_buffer[i+1] = aud_buffer[i];
975         aud_buffer[i] = tmp;
976     }
977 #endif
978     return(tc_audio_write(aud_buffer, aud_size, avifile));
979 
980 }
981 
982 /**
983  *
984  */
tc_audio_pass_through(char * aud_buffer,int aud_size,avi_t * avifile)985 static int tc_audio_pass_through(char *aud_buffer, int aud_size, avi_t *avifile)
986 {
987     return(tc_audio_write(aud_buffer, aud_size, avifile));
988 
989 }
990 
991 /**
992  *
993  */
tc_audio_mute(char * aud_buffer,int aud_size,avi_t * avifile)994 static int tc_audio_mute(char *aud_buffer, int aud_size, avi_t *avifile)
995 {
996     /*
997      * Avoid Gcc to complain
998      */
999     (void)aud_buffer;
1000     (void)aud_size;
1001     (void)avifile;
1002 
1003     return(TC_EXPORT_OK);
1004 }
1005 
1006 
1007 /**
1008  * encode audio frame
1009  *
1010  * @param aud_buffer is the input buffer ?
1011  * @param aud_size is the input buffer length ?
1012  * @param avifile is the output stream ?
1013  *
1014  * @return
1015  */
tc_audio_encode(char * aud_buffer,int aud_size,avi_t * avifile)1016 int tc_audio_encode(char *aud_buffer, int aud_size, avi_t *avifile)
1017 {
1018     assert(tc_audio_encode_function != NULL);
1019     return(tc_audio_encode_function(aud_buffer, aud_size, avifile));
1020  }
1021 
1022 
1023 /**
1024  * Close audio stream
1025  */
tc_audio_close()1026 int tc_audio_close()
1027 {
1028     /* reset bitrate flag for AC3 pass-through */
1029     bitrate = 0;
1030 
1031     if (tc_audio_encode_function == tc_audio_encode_mp3)
1032     {
1033 #ifdef HAVE_LAME
1034         if(lame_flush) {
1035 
1036             int outsize=0;
1037 
1038             outsize = lame_encode_flush(lgf, output, 0);
1039 
1040             if (verbose_flag & TC_DEBUG)
1041                 tc_info("flushing %d audio bytes", outsize);
1042 
1043             if (output && outsize > 0) {
1044                 tc_audio_write(output, outsize, avifile2);
1045             }
1046         }
1047 #endif
1048     }
1049 
1050     if(fd)
1051     {
1052         if (is_pipe)
1053             pclose(fd);
1054         else
1055             fclose(fd);
1056         fd=NULL;
1057     }
1058 
1059     avifile2 = NULL;
1060     return(TC_EXPORT_OK);
1061 }
1062 
1063 
1064 
tc_audio_stop()1065 int tc_audio_stop()
1066 {
1067         if (input) {
1068             free(input);
1069             input = NULL;
1070         }
1071         if (output) {
1072             free(output);
1073             output = NULL;
1074         }
1075 #ifdef HAVE_LAME
1076     if (tc_audio_encode_function == tc_audio_encode_mp3)
1077         lame_close(lgf);
1078 #endif
1079 
1080 #ifdef HAVE_FFMPEG
1081     if (tc_audio_encode_function == tc_audio_encode_ffmpeg)
1082     {
1083         //-- release encoder --
1084         if (mpa_codec) avcodec_close(&mpa_ctx);
1085 
1086         //-- cleanup buffer resources --
1087         if (mpa_buf) free(mpa_buf);
1088         mpa_buf     = NULL;
1089         mpa_buf_ptr = 0;
1090 
1091     }
1092 #endif
1093 
1094     return(0);
1095 }
1096 
1097 
1098 #ifdef HAVE_LAME
1099 
1100 /**
1101  *
1102  */
lame_error2str(int error)1103 static char * lame_error2str(int error)
1104 {
1105     switch (error)
1106     {
1107     case -1: return "-1:  mp3buf was too small";
1108     case -2: return "-2:  malloc() problem";
1109     case -3: return "-3:  lame_init_params() not called";
1110     case -4: return "-4:  psycho acoustic problems";
1111     case -5: return "-5:  ogg cleanup encoding error";
1112     case -6: return "-6:  ogg frame encoding error";
1113     default: return "Unknown lame error";
1114     }
1115 }
1116 
1117 // from mencoder
1118 //----------------------- mp3 audio frame header parser -----------------------
1119 
1120 static int tabsel_123[2][3][16] = {
1121    { {0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,0},
1122      {0,32,48,56, 64, 80, 96,112,128,160,192,224,256,320,384,0},
1123      {0,32,40,48, 56, 64, 80, 96,112,128,160,192,224,256,320,0} },
1124 
1125    { {0,32,48,56,64,80,96,112,128,144,160,176,192,224,256,0},
1126      {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0},
1127      {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0} }
1128 };
1129 static long freqs[9] = { 44100, 48000, 32000, 22050, 24000, 16000 , 11025 , 12000 , 8000 };
1130 
1131 /*
1132  * return frame size or -1 (bad frame)
1133  */
tc_get_mp3_header(unsigned char * hbuf,int * chans,int * srate)1134 static int tc_get_mp3_header(unsigned char* hbuf, int* chans, int* srate){
1135     int stereo, ssize, crc, lsf, mpeg25, framesize;
1136     int padding, bitrate_index, sampling_frequency;
1137     unsigned long newhead =
1138       hbuf[0] << 24 |
1139       hbuf[1] << 16 |
1140       hbuf[2] <<  8 |
1141       hbuf[3];
1142 
1143 
1144     // head_check:
1145     if( (newhead & 0xffe00000) != 0xffe00000 ||
1146         (newhead & 0x0000fc00) == 0x0000fc00){
1147     //tc_log_warn(__FILE__, "head_check failed");
1148     return -1;
1149     }
1150 
1151     if((4-((newhead>>17)&3))!=3){
1152       tc_warn("not layer-3");
1153       return -1;
1154     }
1155 
1156     if( newhead & ((long)1<<20) ) {
1157       lsf = (newhead & ((long)1<<19)) ? 0x0 : 0x1;
1158       mpeg25 = 0;
1159     } else {
1160       lsf = 1;
1161       mpeg25 = 1;
1162     }
1163 
1164     if(mpeg25)
1165       sampling_frequency = 6 + ((newhead>>10)&0x3);
1166     else
1167       sampling_frequency = ((newhead>>10)&0x3) + (lsf*3);
1168 
1169     if(sampling_frequency>8){
1170     tc_warn("invalid sampling_frequency");
1171     return -1;  // valid: 0..8
1172     }
1173 
1174     crc = ((newhead>>16)&0x1)^0x1;
1175     bitrate_index = ((newhead>>12)&0xf);
1176     padding   = ((newhead>>9)&0x1);
1177 //    fr->extension = ((newhead>>8)&0x1);
1178 //    fr->mode      = ((newhead>>6)&0x3);
1179 //    fr->mode_ext  = ((newhead>>4)&0x3);
1180 //    fr->copyright = ((newhead>>3)&0x1);
1181 //    fr->original  = ((newhead>>2)&0x1);
1182 //    fr->emphasis  = newhead & 0x3;
1183 
1184     stereo    = ( (((newhead>>6)&0x3)) == 3) ? 1 : 2;
1185 
1186     if(!bitrate_index){
1187       tc_warn("Free format not supported.");
1188       return -1;
1189     }
1190 
1191     if(lsf)
1192       ssize = (stereo == 1) ? 9 : 17;
1193     else
1194       ssize = (stereo == 1) ? 17 : 32;
1195     if(crc) ssize += 2;
1196 
1197     framesize = tabsel_123[lsf][2][bitrate_index] * 144000;
1198 
1199     if(!framesize){
1200     tc_warn("invalid framesize/bitrate_index");
1201     return -1;  // valid: 1..14
1202     }
1203 
1204     framesize /= freqs[sampling_frequency]<<lsf;
1205     framesize += padding;
1206 
1207 //    if(framesize<=0 || framesize>MAXFRAMESIZE) return FALSE;
1208     if(srate) *srate = freqs[sampling_frequency];
1209     if(chans) *chans = stereo;
1210 
1211     return framesize;
1212 }
1213 
1214 #endif  // HAVE_LAME
1215 
1216