OSDN Git Service

fix some audio bitrate limits issues with ca aac
[handbrake-jp/handbrake-jp-git.git] / libhb / common.c
1 /* $Id: common.c,v 1.15 2005/03/17 19:22:47 titer Exp $
2
3    This file is part of the HandBrake source code.
4    Homepage: <http://handbrake.fr/>.
5    It may be used under the terms of the GNU General Public License. */
6
7 #include <stdarg.h>
8 #include <time.h>
9 #include <sys/time.h>
10
11 #include "common.h"
12 #include "lang.h"
13 #include "hb.h"
14
15 /**********************************************************************
16  * Global variables
17  *********************************************************************/
18 hb_rate_t hb_video_rates[] =
19 { { "5",  5400000 }, { "10",     2700000 }, { "12", 2250000 },
20   { "15", 1800000 }, { "23.976", 1126125 }, { "24", 1125000 },
21   { "25", 1080000 }, { "29.97",  900900  } };
22 int hb_video_rates_count = sizeof( hb_video_rates ) /
23                            sizeof( hb_rate_t );
24
25 hb_rate_t hb_audio_rates[] =
26 { { "22.05", 22050 }, { "24", 24000 }, { "32", 32000 },
27   { "44.1",  44100 }, { "48", 48000 } };
28 int hb_audio_rates_count   = sizeof( hb_audio_rates ) /
29                              sizeof( hb_rate_t );
30 int hb_audio_rates_default = 3; /* 44100 Hz */
31
32 hb_rate_t hb_audio_bitrates[] =
33 { {  "32",  32 }, {  "40",  40 }, {  "48",  48 }, {  "56",  56 },
34   {  "64",  64 }, {  "80",  80 }, {  "96",  96 }, { "112", 112 },
35   { "128", 128 }, { "160", 160 }, { "192", 192 }, { "224", 224 },
36   { "256", 256 }, { "320", 320 }, { "384", 384 }, { "448", 448 },
37   { "512", 512 }, { "576", 576 }, { "640", 640 }, { "768", 768 } };
38 int hb_audio_bitrates_count = sizeof( hb_audio_bitrates ) /
39                               sizeof( hb_rate_t );
40 int hb_audio_bitrates_default = 8; /* 128 kbps */
41
42 static hb_error_handler_t *error_handler = NULL;
43
44 hb_mixdown_t hb_audio_mixdowns[] =
45 { { "Mono",               "HB_AMIXDOWN_MONO",      "mono",   HB_AMIXDOWN_MONO      },
46   { "Stereo",             "HB_AMIXDOWN_STEREO",    "stereo", HB_AMIXDOWN_STEREO    },
47   { "Dolby Surround",     "HB_AMIXDOWN_DOLBY",     "dpl1",   HB_AMIXDOWN_DOLBY     },
48   { "Dolby Pro Logic II", "HB_AMIXDOWN_DOLBYPLII", "dpl2",   HB_AMIXDOWN_DOLBYPLII },
49   { "6-channel discrete", "HB_AMIXDOWN_6CH",       "6ch",    HB_AMIXDOWN_6CH       }
50 };
51 int hb_audio_mixdowns_count = sizeof( hb_audio_mixdowns ) /
52                               sizeof( hb_mixdown_t );
53
54 int hb_mixdown_get_mixdown_from_short_name( const char * short_name )
55 {
56     int i;
57     for (i = 0; i < hb_audio_mixdowns_count; i++)
58     {
59         if (strcmp(hb_audio_mixdowns[i].short_name, short_name) == 0)
60         {
61             return hb_audio_mixdowns[i].amixdown;
62         }
63     }
64     return 0;
65 }
66
67 const char * hb_mixdown_get_short_name_from_mixdown( int amixdown )
68 {
69     int i;
70     for (i = 0; i < hb_audio_mixdowns_count; i++)
71     {
72         if (hb_audio_mixdowns[i].amixdown == amixdown)
73         {
74             return hb_audio_mixdowns[i].short_name;
75         }
76     }
77     return "";
78 }
79
80 // Given an input bitrate, find closest match in the set of allowed bitrates
81 int hb_find_closest_audio_bitrate(int bitrate)
82 {
83     int ii;
84     int result;
85
86     // result is highest rate if none found during search.
87     // rate returned will always be <= rate asked for.
88     result = hb_audio_bitrates[0].rate;
89     for (ii = hb_audio_bitrates_count-1; ii >= 0; ii++)
90     {
91         if (bitrate >= hb_audio_bitrates[ii].rate)
92         {
93             result = hb_audio_bitrates[ii].rate;
94             break;
95         }
96     }
97     return result;
98 }
99
100 // Get the bitrate low and high limits for a codec/samplerate/mixdown triplet
101 void hb_get_audio_bitrate_limits(uint32_t codec, int samplerate, int mixdown, int *low, int *high)
102 {
103     int channels;
104
105     channels = HB_AMIXDOWN_GET_DISCRETE_CHANNEL_COUNT(mixdown);
106     switch (codec)
107     {
108         case HB_ACODEC_AC3:
109             *low = 32 * channels;
110             *high = 640;
111             break;
112
113         case HB_ACODEC_CA_AAC:
114             *low = channels * 40;
115             if (samplerate <= 44100)
116                 *low = channels * 32;
117             if (samplerate <= 24000)
118                 *low = channels * 16;
119             *high = hb_audio_bitrates[hb_audio_bitrates_count-1].rate;
120             break;
121
122         case HB_ACODEC_FAAC:
123             *low = 32 * channels;
124             if (channels >= 6)
125                 *high = 768;
126             else if (channels >= 2)
127                 *high = 320;
128             else
129                 *high = 160;
130             break;
131
132         case HB_ACODEC_VORBIS:
133             *low = channels * 16;
134             *high = hb_audio_bitrates[hb_audio_bitrates_count-1].rate;
135             if (samplerate > 24000)
136             {
137                 if (channels > 2)
138                 {
139                     // Vorbis minimum is around 30kbps/ch for 6ch 
140                     // at rates > 24k (32k/44.1k/48k) 
141                     *low = 32 * channels;
142                 }
143                 else
144                 {
145                     // Allow 24kbps mono and 48kbps stereo at rates > 24k 
146                     // (32k/44.1k/48k)
147                     *low = 24 * channels;
148                 }
149             }
150             break;
151
152         default:
153             *low = hb_audio_bitrates[0].rate;
154             *high = hb_audio_bitrates[hb_audio_bitrates_count-1].rate;
155             break;
156     }
157 }
158
159 // Given an input bitrate, sanitize it.  Check low and high limits and
160 // make sure it is in the set of allowed bitrates.
161 int hb_get_best_audio_bitrate( uint32_t codec, int bitrate, int samplerate, int mixdown)
162 {
163     int low, high;
164
165     hb_get_audio_bitrate_limits(codec, samplerate, mixdown, &low, &high);
166     if (bitrate > high)
167         bitrate = high;
168     if (bitrate < low)
169         bitrate = low;
170     bitrate = hb_find_closest_audio_bitrate(bitrate);
171     return bitrate;
172 }
173
174 // Get the default bitrate for a given codec/samplerate/mixdown triplet.
175 int hb_get_default_audio_bitrate( uint32_t codec, int samplerate, int mixdown )
176 {
177     int bitrate, channels;
178     int sr_shift;
179
180     channels = HB_AMIXDOWN_GET_DISCRETE_CHANNEL_COUNT(mixdown);
181
182     // Min bitrate is established such that we get good quality
183     // audio as a minimum.
184     sr_shift = (samplerate <= 24000) ? 1 : 0;
185
186     switch ( codec )
187     {
188         case HB_ACODEC_AC3:
189             if (channels == 1)
190                 bitrate = 96;
191             else if (channels <= 2)
192                 bitrate = 224;
193             else
194                 bitrate = 640;
195             break;
196         default:
197             bitrate = channels * 80;
198     }
199     bitrate >>= sr_shift;
200     bitrate = hb_get_best_audio_bitrate( codec, bitrate, samplerate, mixdown );
201     return bitrate;
202 }
203
204 int hb_get_best_mixdown( uint32_t codec, int layout )
205 {
206     switch (layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK)
207     {
208         // stereo input or something not handled below
209         default:
210         case HB_INPUT_CH_LAYOUT_STEREO:
211             // mono gets mixed up to stereo & more than stereo gets mixed down
212             return HB_AMIXDOWN_STEREO;
213
214         // mono input
215         case HB_INPUT_CH_LAYOUT_MONO:
216             // everything else passes through
217             return HB_AMIXDOWN_MONO;
218
219         // dolby (DPL1 aka Dolby Surround = 4.0 matrix-encoded) input
220         // the A52 flags don't allow for a way to distinguish between DPL1 and
221         // DPL2 on a DVD so we always assume a DPL1 source for A52_DOLBY.
222         case HB_INPUT_CH_LAYOUT_DOLBY:
223             return HB_AMIXDOWN_DOLBY;
224
225         // 4 channel discrete
226         case HB_INPUT_CH_LAYOUT_2F2R:
227         case HB_INPUT_CH_LAYOUT_3F1R:
228             // a52dec and libdca can't upmix to 6ch, 
229             // so we must downmix these.
230             return HB_AMIXDOWN_DOLBYPLII;
231
232         // 5 or 6 channel discrete
233         case HB_INPUT_CH_LAYOUT_3F2R:
234             if ( ! ( layout & HB_INPUT_CH_LAYOUT_HAS_LFE ) )
235             {
236                 // we don't do 5 channel discrete so mixdown to DPLII
237                 // a52dec and libdca can't upmix to 6ch, 
238                 // so we must downmix this.
239                 return HB_AMIXDOWN_DOLBYPLII;
240             }
241             else
242             {
243                 switch (codec)
244                 {
245                     case HB_ACODEC_LAME:
246                         return HB_AMIXDOWN_DOLBYPLII;
247
248                     default:
249                         return HB_AMIXDOWN_6CH;
250                 }
251             }
252     }
253 }
254
255 int hb_get_default_mixdown( uint32_t codec, int layout )
256 {
257     switch (layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK)
258     {
259         // stereo input or something not handled below
260         default:
261         case HB_INPUT_CH_LAYOUT_STEREO:
262             // mono gets mixed up to stereo & more than stereo gets mixed down
263             return HB_AMIXDOWN_STEREO;
264
265         // mono input
266         case HB_INPUT_CH_LAYOUT_MONO:
267             // everything else passes through
268             return HB_AMIXDOWN_MONO;
269
270         // dolby (DPL1 aka Dolby Surround = 4.0 matrix-encoded) input
271         // the A52 flags don't allow for a way to distinguish between DPL1 and
272         // DPL2 on a DVD so we always assume a DPL1 source for A52_DOLBY.
273         case HB_INPUT_CH_LAYOUT_DOLBY:
274             return HB_AMIXDOWN_DOLBY;
275
276         // 4 channel discrete
277         case HB_INPUT_CH_LAYOUT_2F2R:
278         case HB_INPUT_CH_LAYOUT_3F1R:
279             // a52dec and libdca can't upmix to 6ch, 
280             // so we must downmix these.
281             return HB_AMIXDOWN_DOLBYPLII;
282
283         // 5 or 6 channel discrete
284         case HB_INPUT_CH_LAYOUT_3F2R:
285             if ( ! ( layout & HB_INPUT_CH_LAYOUT_HAS_LFE ) )
286             {
287                 // we don't do 5 channel discrete so mixdown to DPLII
288                 // a52dec and libdca can't upmix to 6ch, 
289                 // so we must downmix this.
290                 return HB_AMIXDOWN_DOLBYPLII;
291             }
292             else
293             {
294                 switch (codec)
295                 {
296                     case HB_ACODEC_AC3:
297                         return HB_AMIXDOWN_6CH;
298
299                     default:
300                         return HB_AMIXDOWN_DOLBYPLII;
301                 }
302             }
303     }
304 }
305
306 /**********************************************************************
307  * hb_reduce
308  **********************************************************************
309  * Given a numerator (num) and a denominator (den), reduce them to an
310  * equivalent fraction and store the result in x and y.
311  *********************************************************************/
312 void hb_reduce( int *x, int *y, int num, int den )
313 {
314     // find the greatest common divisor of num & den by Euclid's algorithm
315     int n = num, d = den;
316     while ( d )
317     {
318         int t = d;
319         d = n % d;
320         n = t;
321     }
322
323     // at this point n is the gcd. if it's non-zero remove it from num
324     // and den. Otherwise just return the original values.
325     if ( n )
326     {
327         *x = num / n;
328         *y = den / n;
329     }
330     else
331     {
332         *x = num;
333         *y = den;
334     }
335 }
336
337 /**********************************************************************
338  * hb_fix_aspect
339  **********************************************************************
340  * Given the output width (if HB_KEEP_WIDTH) or height
341  * (HB_KEEP_HEIGHT) and the current crop values, calculates the
342  * correct height or width in order to respect the DVD aspect ratio
343  *********************************************************************/
344 void hb_fix_aspect( hb_job_t * job, int keep )
345 {
346     hb_title_t * title = job->title;
347     int          i;
348     int  min_width;
349     int min_height;
350     int    modulus;
351
352     /* don't do anything unless the title has complete size info */
353     if ( title->height == 0 || title->width == 0 || title->aspect == 0 )
354     {
355         hb_log( "hb_fix_aspect: incomplete info for title %d: "
356                 "height = %d, width = %d, aspect = %.3f",
357                 title->index, title->height, title->width, title->aspect );
358         return;
359     }
360
361     // min_width and min_height should be multiples of modulus
362     min_width    = 32;
363     min_height   = 32;
364     modulus      = job->modulus ? job->modulus : 16;
365
366     for( i = 0; i < 4; i++ )
367     {
368         // Sanity check crop values are zero or positive multiples of 2
369         if( i < 2 )
370         {
371             // Top, bottom
372             job->crop[i] = MIN( EVEN( job->crop[i] ), EVEN( ( title->height / 2 ) - ( min_height / 2 ) ) );
373             job->crop[i] = MAX( 0, job->crop[i] );
374         }
375         else
376         {
377             // Left, right
378             job->crop[i] = MIN( EVEN( job->crop[i] ), EVEN( ( title->width / 2 ) - ( min_width / 2 ) ) );
379             job->crop[i] = MAX( 0, job->crop[i] );
380         }
381     }
382
383     double par = (double)title->width / ( (double)title->height * title->aspect );
384     double cropped_sar = (double)( title->height - job->crop[0] - job->crop[1] ) /
385                          (double)( title->width - job->crop[2] - job->crop[3] );
386     double ar = par * cropped_sar;
387
388     // Dimensions must be greater than minimum and multiple of modulus
389     if( keep == HB_KEEP_WIDTH )
390     {
391         job->width  = MULTIPLE_MOD( job->width, modulus );
392         job->width  = MAX( min_width, job->width );
393         job->height = MULTIPLE_MOD( (uint64_t)( (double)job->width * ar ), modulus );
394         job->height = MAX( min_height, job->height );
395     }
396     else
397     {
398         job->height = MULTIPLE_MOD( job->height, modulus );
399         job->height = MAX( min_height, job->height );
400         job->width  = MULTIPLE_MOD( (uint64_t)( (double)job->height / ar ), modulus );
401         job->width  = MAX( min_width, job->width );
402     }
403 }
404
405 /**********************************************************************
406  * hb_calc_bitrate
407  **********************************************************************
408  * size: in megabytes
409  *********************************************************************/
410 int hb_calc_bitrate( hb_job_t * job, int size )
411 {
412     int64_t avail = (int64_t) size * 1024 * 1024;
413     int64_t length;
414     int     overhead;
415     int     samples_per_frame;
416     int     i;
417
418     hb_title_t   * title = job->title;
419     hb_chapter_t * chapter;
420     hb_audio_t   * audio;
421
422     /* How many overhead bytes are used for each frame
423        (quite guessed) */
424     switch( job->mux )
425     {
426        case HB_MUX_MP4:
427        case HB_MUX_PSP:
428                 case HB_MUX_IPOD:
429                 case HB_MUX_MKV:
430             overhead = 6;
431             break;
432         case HB_MUX_AVI:
433             overhead = 24;
434             break;
435         case HB_MUX_OGM:
436             overhead = 6;
437             break;
438         default:
439             return 0;
440     }
441
442     /* Get the duration in seconds */
443     length = 0;
444     for( i = job->chapter_start; i <= job->chapter_end; i++ )
445     {
446         chapter = hb_list_item( title->list_chapter, i - 1 );
447         length += chapter->duration;
448     }
449     length += 135000;
450     length /= 90000;
451
452     if( size == -1 )
453     {
454         hb_interjob_t * interjob = hb_interjob_get( job->h );
455         avail = job->vbitrate * 125 * length;
456         avail += length * interjob->vrate * overhead / interjob->vrate_base;
457     }
458
459     /* Video overhead */
460     avail -= length * job->vrate * overhead / job->vrate_base;
461
462     if( size == -1 )
463     {
464         goto ret;
465     }
466
467     for( i = 0; i < hb_list_count(job->list_audio); i++ )
468     {
469         /* Audio data */
470         int abitrate;
471         audio = hb_list_item( job->list_audio, i);
472
473         /* How many audio samples we put in each frame */
474         switch( audio->config.out.codec )
475         {
476             case HB_ACODEC_FAAC:
477             case HB_ACODEC_CA_AAC:
478             case HB_ACODEC_VORBIS:
479                 samples_per_frame = 1024;
480                 break;
481             case HB_ACODEC_LAME:
482                 samples_per_frame = 1152;
483                 break;
484             case HB_ACODEC_AC3_PASS:
485             case HB_ACODEC_DCA_PASS:
486             case HB_ACODEC_AC3:
487             case HB_ACODEC_DCA:
488                 samples_per_frame = 1536;
489                 break;
490             default:
491                 return 0;
492         }
493
494         if( audio->config.out.codec == HB_ACODEC_AC3_PASS ||
495             audio->config.out.codec == HB_ACODEC_DCA_PASS)
496         {
497             /*
498              * For pass through we take the bitrate from the input audio
499              * bitrate as we are simply passing it through.
500              */
501             abitrate = audio->config.in.bitrate / 8;
502         }
503         else
504         {
505             /*
506              * Where we are transcoding the audio we use the destination
507              * bitrate.
508              */
509             abitrate = audio->config.out.bitrate * 1000 / 8;
510         }
511         avail -= length * abitrate;
512
513         /* Audio overhead */
514         avail -= length * audio->config.out.samplerate * overhead / samples_per_frame;
515     }
516
517 ret:
518     if( avail < 0 )
519     {
520         return 0;
521     }
522
523     return ( avail / ( 125 * length ) );
524 }
525
526 /**********************************************************************
527  * hb_list implementation
528  **********************************************************************
529  * Basic and slow, but enough for what we need
530  *********************************************************************/
531
532 #define HB_LIST_DEFAULT_SIZE 20
533
534 struct hb_list_s
535 {
536     /* Pointers to items in the list */
537     void ** items;
538
539     /* How many (void *) allocated in 'items' */
540     int     items_alloc;
541
542     /* How many valid pointers in 'items' */
543     int     items_count;
544 };
545
546 /**********************************************************************
547  * hb_list_init
548  **********************************************************************
549  * Allocates an empty list ready for HB_LIST_DEFAULT_SIZE items
550  *********************************************************************/
551 hb_list_t * hb_list_init()
552 {
553     hb_list_t * l;
554
555     l              = calloc( sizeof( hb_list_t ), 1 );
556     l->items       = calloc( HB_LIST_DEFAULT_SIZE * sizeof( void * ), 1 );
557     l->items_alloc = HB_LIST_DEFAULT_SIZE;
558
559     return l;
560 }
561
562 /**********************************************************************
563  * hb_list_count
564  **********************************************************************
565  * Returns the number of items currently in the list
566  *********************************************************************/
567 int hb_list_count( hb_list_t * l )
568 {
569     return l->items_count;
570 }
571
572 /**********************************************************************
573  * hb_list_add
574  **********************************************************************
575  * Adds an item at the end of the list, making it bigger if necessary.
576  * Can safely be called with a NULL pointer to add, it will be ignored.
577  *********************************************************************/
578 void hb_list_add( hb_list_t * l, void * p )
579 {
580     if( !p )
581     {
582         return;
583     }
584
585     if( l->items_count == l->items_alloc )
586     {
587         /* We need a bigger boat */
588         l->items_alloc += HB_LIST_DEFAULT_SIZE;
589         l->items        = realloc( l->items,
590                                    l->items_alloc * sizeof( void * ) );
591     }
592
593     l->items[l->items_count] = p;
594     (l->items_count)++;
595 }
596
597 /**********************************************************************
598  * hb_list_rem
599  **********************************************************************
600  * Remove an item from the list. Bad things will happen if called
601  * with a NULL pointer or if the item is not in the list.
602  *********************************************************************/
603 void hb_list_rem( hb_list_t * l, void * p )
604 {
605     int i;
606
607     /* Find the item in the list */
608     for( i = 0; i < l->items_count; i++ )
609     {
610         if( l->items[i] == p )
611         {
612             break;
613         }
614     }
615
616     /* Shift all items after it sizeof( void * ) bytes earlier */
617     memmove( &l->items[i], &l->items[i+1],
618              ( l->items_count - i - 1 ) * sizeof( void * ) );
619
620     (l->items_count)--;
621 }
622
623 /**********************************************************************
624  * hb_list_item
625  **********************************************************************
626  * Returns item at position i, or NULL if there are not that many
627  * items in the list
628  *********************************************************************/
629 void * hb_list_item( hb_list_t * l, int i )
630 {
631     if( i < 0 || i >= l->items_count )
632     {
633         return NULL;
634     }
635
636     return l->items[i];
637 }
638
639 /**********************************************************************
640  * hb_list_bytes
641  **********************************************************************
642  * Assuming all items are of type hb_buffer_t, returns the total
643  * number of bytes in the list
644  *********************************************************************/
645 int hb_list_bytes( hb_list_t * l )
646 {
647     hb_buffer_t * buf;
648     int           ret;
649     int           i;
650
651     ret = 0;
652     for( i = 0; i < hb_list_count( l ); i++ )
653     {
654         buf  = hb_list_item( l, i );
655         ret += buf->size - buf->cur;
656     }
657
658     return ret;
659 }
660
661 /**********************************************************************
662  * hb_list_seebytes
663  **********************************************************************
664  * Assuming all items are of type hb_buffer_t, copy <size> bytes from
665  * the list to <dst>, keeping the list unmodified.
666  *********************************************************************/
667 void hb_list_seebytes( hb_list_t * l, uint8_t * dst, int size )
668 {
669     hb_buffer_t * buf;
670     int           copied;
671     int           copying;
672     int           i;
673
674     for( i = 0, copied = 0; copied < size; i++ )
675     {
676         buf     = hb_list_item( l, i );
677         copying = MIN( buf->size - buf->cur, size - copied );
678         memcpy( &dst[copied], &buf->data[buf->cur], copying );
679         copied += copying;
680     }
681 }
682
683 /**********************************************************************
684  * hb_list_getbytes
685  **********************************************************************
686  * Assuming all items are of type hb_buffer_t, copy <size> bytes from
687  * the list to <dst>. What's copied is removed from the list.
688  * The variable pointed by <pts> is set to the PTS of the buffer the
689  * first byte has been got from.
690  * The variable pointed by <pos> is set to the position of that byte
691  * in that buffer.
692  *********************************************************************/
693 void hb_list_getbytes( hb_list_t * l, uint8_t * dst, int size,
694                        uint64_t * pts, uint64_t * pos )
695 {
696     hb_buffer_t * buf;
697     int           copied;
698     int           copying;
699     uint8_t       has_pts;
700
701     /* So we won't have to deal with NULL pointers */
702      uint64_t dummy1, dummy2;
703
704     if( !pts ) pts = &dummy1;
705     if( !pos ) pos = &dummy2;
706
707     for( copied = 0, has_pts = 0; copied < size;  )
708     {
709         buf     = hb_list_item( l, 0 );
710         copying = MIN( buf->size - buf->cur, size - copied );
711         memcpy( &dst[copied], &buf->data[buf->cur], copying );
712
713         if( !has_pts )
714         {
715             *pts    = buf->start;
716             *pos    = buf->cur;
717             has_pts = 1;
718         }
719
720         buf->cur += copying;
721         if( buf->cur >= buf->size )
722         {
723             hb_list_rem( l, buf );
724             hb_buffer_close( &buf );
725         }
726
727         copied += copying;
728     }
729 }
730
731 /**********************************************************************
732  * hb_list_empty
733  **********************************************************************
734  * Assuming all items are of type hb_buffer_t, close them all and
735  * close the list.
736  *********************************************************************/
737 void hb_list_empty( hb_list_t ** _l )
738 {
739     hb_list_t * l = *_l;
740     hb_buffer_t * b;
741
742     while( ( b = hb_list_item( l, 0 ) ) )
743     {
744         hb_list_rem( l, b );
745         hb_buffer_close( &b );
746     }
747
748     hb_list_close( _l );
749 }
750
751 /**********************************************************************
752  * hb_list_close
753  **********************************************************************
754  * Free memory allocated by hb_list_init. Does NOT free contents of
755  * items still in the list.
756  *********************************************************************/
757 void hb_list_close( hb_list_t ** _l )
758 {
759     hb_list_t * l = *_l;
760
761     free( l->items );
762     free( l );
763
764     *_l = NULL;
765 }
766
767 /**********************************************************************
768  * hb_log
769  **********************************************************************
770  * If verbose mode is one, print message with timestamp. Messages
771  * longer than 180 characters are stripped ;p
772  *********************************************************************/
773 void hb_log( char * log, ... )
774 {
775     char        string[362]; /* 360 chars + \n + \0 */
776     time_t      _now;
777     struct tm * now;
778     va_list     args;
779
780     if( !getenv( "HB_DEBUG" ) )
781     {
782         /* We don't want to print it */
783         return;
784     }
785
786     /* Get the time */
787     _now = time( NULL );
788     now  = localtime( &_now );
789     sprintf( string, "[%02d:%02d:%02d] ",
790              now->tm_hour, now->tm_min, now->tm_sec );
791
792     /* Convert the message to a string */
793     va_start( args, log );
794     vsnprintf( string + 11, 349, log, args );
795     va_end( args );
796
797     /* Add the end of line */
798     strcat( string, "\n" );
799
800     /* Print it */
801     fprintf( stderr, "%s", string );
802 }
803
804 int global_verbosity_level; //Necessary for hb_deep_log
805 /**********************************************************************
806  * hb_deep_log
807  **********************************************************************
808  * If verbose mode is >= level, print message with timestamp. Messages
809  * longer than 360 characters are stripped ;p
810  *********************************************************************/
811 void hb_deep_log( hb_debug_level_t level, char * log, ... )
812 {
813     char        string[362]; /* 360 chars + \n + \0 */
814     time_t      _now;
815     struct tm * now;
816     va_list     args;
817
818     if( global_verbosity_level < level )
819     {
820         /* Hiding message */
821         return;
822     }
823
824     /* Get the time */
825     _now = time( NULL );
826     now  = localtime( &_now );
827     sprintf( string, "[%02d:%02d:%02d] ",
828              now->tm_hour, now->tm_min, now->tm_sec );
829
830     /* Convert the message to a string */
831     va_start( args, log );
832     vsnprintf( string + 11, 349, log, args );
833     va_end( args );
834
835     /* Add the end of line */
836     strcat( string, "\n" );
837
838     /* Print it */
839     fprintf( stderr, "%s", string );
840 }
841
842 /**********************************************************************
843  * hb_error
844  **********************************************************************
845  * Using whatever output is available display this error.
846  *********************************************************************/
847 void hb_error( char * log, ... )
848 {
849     char        string[181]; /* 180 chars + \0 */
850     char        rep_string[181];
851     static char last_string[181];
852     static int  last_error_count = 0;
853     static uint64_t last_series_error_time = 0;
854     static hb_lock_t *mutex = 0;
855     va_list     args;
856     uint64_t time_now;
857
858     /* Convert the message to a string */
859     va_start( args, log );
860     vsnprintf( string, 180, log, args );
861     va_end( args );
862
863     if( !mutex )
864     {
865         mutex = hb_lock_init();
866     }
867
868     hb_lock( mutex );
869
870     time_now = hb_get_date();
871
872     if( strcmp( string, last_string) == 0 )
873     {
874         /*
875          * The last error and this one are the same, don't log it
876          * just count it instead, unless it was more than one second
877          * ago.
878          */
879         last_error_count++;
880         if( last_series_error_time + ( 1000 * 1 ) > time_now )
881         {
882             hb_unlock( mutex );
883             return;
884         } 
885     }
886     
887     /*
888      * A new error, or the same one more than 10sec since the last one
889      * did we have any of the same counted up?
890      */
891     if( last_error_count > 0 )
892     {
893         /*
894          * Print out the last error to ensure context for the last 
895          * repeated message.
896          */
897         if( error_handler )
898         {
899             error_handler( last_string );
900         } else {
901             hb_log( "%s", last_string );
902         }
903         
904         if( last_error_count > 1 )
905         {
906             /*
907              * Only print out the repeat message for more than 2 of the
908              * same, since we just printed out two of them already.
909              */
910             snprintf( rep_string, 180, "Last error repeated %d times", 
911                       last_error_count - 1 );
912             
913             if( error_handler )
914             {
915                 error_handler( rep_string );
916             } else {
917                 hb_log( "%s", rep_string );
918             }
919         }
920         
921         last_error_count = 0;
922     }
923
924     last_series_error_time = time_now;
925
926     strcpy( last_string, string );
927
928     /*
929      * Got the error in a single string, send it off to be dispatched.
930      */
931     if( error_handler )
932     {
933         error_handler( string );
934     } else {
935         hb_log( "%s", string );
936     }
937
938     hb_unlock( mutex );
939 }
940
941 void hb_register_error_handler( hb_error_handler_t * handler )
942 {
943     error_handler = handler;
944 }
945
946 /**********************************************************************
947  * hb_title_init
948  **********************************************************************
949  *
950  *********************************************************************/
951 hb_title_t * hb_title_init( char * path, int index )
952 {
953     hb_title_t * t;
954
955     t = calloc( sizeof( hb_title_t ), 1 );
956
957     t->index         = index;
958     t->list_audio    = hb_list_init();
959     t->list_chapter  = hb_list_init();
960     t->list_subtitle = hb_list_init();
961     t->list_attachment = hb_list_init();
962     strcat( t->path, path );
963     // default to decoding mpeg2
964     t->video_id      = 0xE0;
965     t->video_codec   = WORK_DECMPEG2;
966
967     return t;
968 }
969
970 /**********************************************************************
971  * hb_title_close
972  **********************************************************************
973  *
974  *********************************************************************/
975 void hb_title_close( hb_title_t ** _t )
976 {
977     hb_title_t * t = *_t;
978     hb_audio_t * audio;
979     hb_chapter_t * chapter;
980     hb_subtitle_t * subtitle;
981     hb_attachment_t * attachment;
982
983     while( ( audio = hb_list_item( t->list_audio, 0 ) ) )
984     {
985         hb_list_rem( t->list_audio, audio );
986         free( audio );
987     }
988     hb_list_close( &t->list_audio );
989
990     while( ( chapter = hb_list_item( t->list_chapter, 0 ) ) )
991     {
992         hb_list_rem( t->list_chapter, chapter );
993         free( chapter );
994     }
995     hb_list_close( &t->list_chapter );
996
997     while( ( subtitle = hb_list_item( t->list_subtitle, 0 ) ) )
998     {
999         hb_list_rem( t->list_subtitle, subtitle );
1000         if ( subtitle->extradata )
1001         {
1002             free( subtitle->extradata );
1003             subtitle->extradata = NULL;
1004         }
1005         free( subtitle );
1006     }
1007     hb_list_close( &t->list_subtitle );
1008     
1009     while( ( attachment = hb_list_item( t->list_attachment, 0 ) ) )
1010     {
1011         hb_list_rem( t->list_attachment, attachment );
1012         if ( attachment->name )
1013         {
1014             free( attachment->name );
1015             attachment->name = NULL;
1016         }
1017         if ( attachment->data )
1018         {
1019             free( attachment->data );
1020             attachment->data = NULL;
1021         }
1022         free( attachment );
1023     }
1024     hb_list_close( &t->list_attachment );
1025
1026     if( t->metadata )
1027     {
1028         if( t->metadata->coverart )
1029         {
1030             free( t->metadata->coverart );
1031         }
1032         free( t->metadata );
1033     }
1034
1035     free( t );
1036     *_t = NULL;
1037 }
1038
1039 /**********************************************************************
1040  * hb_filter_close
1041  **********************************************************************
1042  *
1043  *********************************************************************/
1044 void hb_filter_close( hb_filter_object_t ** _f )
1045 {
1046     hb_filter_object_t * f = *_f;
1047
1048     f->close( f->private_data );
1049
1050     if( f->name )
1051         free( f->name );
1052     if( f->settings )
1053         free( f->settings );
1054
1055     free( f );
1056     *_f = NULL;
1057 }
1058
1059 /**********************************************************************
1060  * hb_audio_copy
1061  **********************************************************************
1062  *
1063  *********************************************************************/
1064 hb_audio_t *hb_audio_copy(const hb_audio_t *src)
1065 {
1066     hb_audio_t *audio = NULL;
1067
1068     if( src )
1069     {
1070         audio = calloc(1, sizeof(*audio));
1071         memcpy(audio, src, sizeof(*audio));
1072     }
1073     return audio;
1074 }
1075
1076 /**********************************************************************
1077  * hb_audio_new
1078  **********************************************************************
1079  *
1080  *********************************************************************/
1081 void hb_audio_config_init(hb_audio_config_t * audiocfg)
1082 {
1083     /* Set read only paramaters to invalid values */
1084     audiocfg->in.codec = 0xDEADBEEF;
1085     audiocfg->in.bitrate = -1;
1086     audiocfg->in.samplerate = -1;
1087     audiocfg->in.channel_layout = 0;
1088     audiocfg->in.version = 0;
1089     audiocfg->in.mode = 0;
1090     audiocfg->flags.ac3 = 0;
1091     audiocfg->lang.description[0] = 0;
1092     audiocfg->lang.simple[0] = 0;
1093     audiocfg->lang.iso639_2[0] = 0;
1094
1095     /* Initalize some sensable defaults */
1096     audiocfg->in.track = audiocfg->out.track = 0;
1097     audiocfg->out.codec = HB_ACODEC_FAAC;
1098     audiocfg->out.bitrate = 128;
1099     audiocfg->out.samplerate = 44100;
1100     audiocfg->out.mixdown = HB_AMIXDOWN_DOLBYPLII;
1101     audiocfg->out.dynamic_range_compression = 0;
1102     audiocfg->out.name = NULL;
1103 }
1104
1105 /**********************************************************************
1106  * hb_audio_add
1107  **********************************************************************
1108  *
1109  *********************************************************************/
1110 int hb_audio_add(const hb_job_t * job, const hb_audio_config_t * audiocfg)
1111 {
1112     hb_title_t *title = job->title;
1113     hb_audio_t *audio;
1114
1115     audio = hb_audio_copy( hb_list_item( title->list_audio, audiocfg->in.track ) );
1116     if( audio == NULL )
1117     {
1118         /* We fail! */
1119         return 0;
1120     }
1121
1122     if( (audiocfg->in.bitrate != -1) && (audiocfg->in.codec != 0xDEADBEEF) )
1123     {
1124         /* This most likely means the client didn't call hb_audio_config_init
1125          * so bail.
1126          */
1127         return 0;
1128     }
1129
1130     /* Really shouldn't ignore the passed out track, but there is currently no
1131      * way to handle duplicates or out-of-order track numbers.
1132      */
1133     audio->config.out.track = hb_list_count(job->list_audio) + 1;
1134     audio->config.out.codec = audiocfg->out.codec;
1135     if( (audiocfg->out.codec & HB_ACODEC_MASK) == audio->config.in.codec &&
1136         (audiocfg->out.codec & HB_ACODEC_PASS_FLAG ) )
1137     {
1138         /* Pass-through, copy from input. */
1139         audio->config.out.samplerate = audio->config.in.samplerate;
1140         audio->config.out.bitrate = audio->config.in.bitrate;
1141         audio->config.out.dynamic_range_compression = 0;
1142         audio->config.out.mixdown = 0;
1143     }
1144     else
1145     {
1146         /* Non pass-through, use what is given. */
1147         audio->config.out.codec &= ~HB_ACODEC_PASS_FLAG;
1148         audio->config.out.samplerate = audiocfg->out.samplerate;
1149         audio->config.out.bitrate = audiocfg->out.bitrate;
1150         audio->config.out.dynamic_range_compression = audiocfg->out.dynamic_range_compression;
1151         audio->config.out.mixdown = audiocfg->out.mixdown;
1152     }
1153
1154     hb_list_add(job->list_audio, audio);
1155     return 1;
1156 }
1157
1158 hb_audio_config_t * hb_list_audio_config_item(hb_list_t * list, int i)
1159 {
1160     hb_audio_t *audio = NULL;
1161
1162     if( (audio = hb_list_item(list, i)) )
1163         return &(audio->config);
1164
1165     return NULL;
1166 }
1167
1168 /**********************************************************************
1169  * hb_subtitle_copy
1170  **********************************************************************
1171  *
1172  *********************************************************************/
1173 hb_subtitle_t *hb_subtitle_copy(const hb_subtitle_t *src)
1174 {
1175     hb_subtitle_t *subtitle = NULL;
1176
1177     if( src )
1178     {
1179         subtitle = calloc(1, sizeof(*subtitle));
1180         memcpy(subtitle, src, sizeof(*subtitle));
1181         if ( src->extradata )
1182         {
1183             subtitle->extradata = malloc( src->extradata_size );
1184             memcpy( subtitle->extradata, src->extradata, src->extradata_size );
1185         }
1186     }
1187     return subtitle;
1188 }
1189
1190 /**********************************************************************
1191  * hb_subtitle_add
1192  **********************************************************************
1193  *
1194  *********************************************************************/
1195 int hb_subtitle_add(const hb_job_t * job, const hb_subtitle_config_t * subtitlecfg, int track)
1196 {
1197     hb_title_t *title = job->title;
1198     hb_subtitle_t *subtitle;
1199
1200     subtitle = hb_subtitle_copy( hb_list_item( title->list_subtitle, track ) );
1201     if( subtitle == NULL )
1202     {
1203         /* We fail! */
1204         return 0;
1205     }
1206     subtitle->config = *subtitlecfg;
1207     hb_list_add(job->list_subtitle, subtitle);
1208     return 1;
1209 }
1210
1211 int hb_srt_add( const hb_job_t * job, 
1212                 const hb_subtitle_config_t * subtitlecfg, 
1213                 const char *lang )
1214 {
1215     hb_subtitle_t *subtitle;
1216     iso639_lang_t *language = NULL;
1217     int retval = 0;
1218
1219     subtitle = calloc( 1, sizeof( *subtitle ) );
1220     
1221     subtitle->id = (hb_list_count(job->list_subtitle) << 8) | 0xFF;
1222     subtitle->format = TEXTSUB;
1223     subtitle->source = SRTSUB;
1224
1225     language = lang_for_code2( lang );
1226
1227     if( language )
1228     {
1229
1230         strcpy( subtitle->lang, language->eng_name );
1231         strncpy( subtitle->iso639_2, lang, 4 );
1232         
1233         subtitle->config = *subtitlecfg;
1234         subtitle->config.dest = PASSTHRUSUB;
1235
1236         hb_list_add(job->list_subtitle, subtitle);
1237         retval = 1;
1238     }
1239     return retval;
1240 }
1241
1242 char * hb_strdup_printf( char * fmt, ... )
1243 {
1244     int       len;
1245     va_list   ap;
1246     int       size = 256;
1247     char    * str;
1248     char    * tmp;
1249
1250     str = malloc( size );
1251     if ( str == NULL )
1252         return NULL;
1253
1254     while (1) 
1255     {
1256         /* Try to print in the allocated space. */
1257         va_start( ap, fmt );
1258         len = vsnprintf( str, size, fmt, ap );
1259         va_end( ap );
1260
1261         /* If that worked, return the string. */
1262         if ( len > -1 && len < size )
1263         {
1264             return str;
1265         }
1266
1267         /* Else try again with more space. */
1268         if ( len > -1 )     /* glibc 2.1 */
1269             size = len + 1; /* precisely what is needed */
1270         else                /* glibc 2.0 */
1271             size *= 2;      /* twice the old size */
1272         tmp = realloc( str, size );
1273         if ( tmp == NULL )
1274         {
1275             free( str );
1276             return NULL;
1277         }
1278         else
1279             str = tmp;
1280     }
1281 }
1282
1283 /**********************************************************************
1284  * hb_attachment_copy
1285  **********************************************************************
1286  *
1287  *********************************************************************/
1288 hb_attachment_t *hb_attachment_copy(const hb_attachment_t *src)
1289 {
1290     hb_attachment_t *attachment = NULL;
1291
1292     if( src )
1293     {
1294         attachment = calloc(1, sizeof(*attachment));
1295         memcpy(attachment, src, sizeof(*attachment));
1296         if ( src->name )
1297         {
1298             attachment->name = strdup( src->name );
1299         }
1300         if ( src->data )
1301         {
1302             attachment->data = malloc( src->size );
1303             memcpy( attachment->data, src->data, src->size );
1304         }
1305     }
1306     return attachment;
1307 }
1308
1309 /**********************************************************************
1310  * hb_yuv2rgb
1311  **********************************************************************
1312  * Converts a YCbCr pixel to an RGB pixel.
1313  * 
1314  * This conversion is lossy (due to rounding and clamping).
1315  * 
1316  * Algorithm:
1317  *   http://en.wikipedia.org/w/index.php?title=YCbCr&oldid=361987695#Technical_details
1318  *********************************************************************/
1319 int hb_yuv2rgb(int yuv)
1320 {
1321     double y, Cr, Cb;
1322     int r, g, b;
1323
1324     y  = (yuv >> 16) & 0xff;
1325     Cb = (yuv >>  8) & 0xff;
1326     Cr = (yuv      ) & 0xff;
1327
1328     r = 1.164 * (y - 16)                      + 2.018 * (Cb - 128);
1329     g = 1.164 * (y - 16) - 0.813 * (Cr - 128) - 0.391 * (Cb - 128);
1330     b = 1.164 * (y - 16) + 1.596 * (Cr - 128);
1331     
1332     r = (r < 0) ? 0 : r;
1333     g = (g < 0) ? 0 : g;
1334     b = (b < 0) ? 0 : b;
1335     
1336     r = (r > 255) ? 255 : r;
1337     g = (g > 255) ? 255 : g;
1338     b = (b > 255) ? 255 : b;
1339     
1340     return (r << 16) | (g << 8) | b;
1341 }
1342
1343 /**********************************************************************
1344  * hb_rgb2yuv
1345  **********************************************************************
1346  * Converts an RGB pixel to a YCbCr pixel.
1347  * 
1348  * This conversion is lossy (due to rounding and clamping).
1349  * 
1350  * Algorithm:
1351  *   http://en.wikipedia.org/w/index.php?title=YCbCr&oldid=361987695#Technical_details
1352  *********************************************************************/
1353 int hb_rgb2yuv(int rgb)
1354 {
1355     double r, g, b;
1356     int y, Cr, Cb;
1357     
1358     r = (rgb >> 16) & 0xff;
1359     g = (rgb >>  8) & 0xff;
1360     b = (rgb      ) & 0xff;
1361
1362     y  =  16. + ( 0.257 * r) + (0.504 * g) + (0.098 * b);
1363     Cb = 128. + (-0.148 * r) - (0.291 * g) + (0.439 * b);
1364     Cr = 128. + ( 0.439 * r) - (0.368 * g) - (0.071 * b);
1365     
1366     y = (y < 0) ? 0 : y;
1367     Cb = (Cb < 0) ? 0 : Cb;
1368     Cr = (Cr < 0) ? 0 : Cr;
1369     
1370     y = (y > 255) ? 255 : y;
1371     Cb = (Cb > 255) ? 255 : Cb;
1372     Cr = (Cr > 255) ? 255 : Cr;
1373     
1374     return (y << 16) | (Cb << 8) | Cr;
1375 }
1376
1377 const char * hb_subsource_name( int source )
1378 {
1379     switch (source)
1380     {
1381         case VOBSUB:
1382             return "VOBSUB";
1383         case SRTSUB:
1384             return "SRT";
1385         case CC608SUB:
1386             return "CC";
1387         case CC708SUB:
1388             return "CC";
1389         case UTF8SUB:
1390             return "UTF-8";
1391         case TX3GSUB:
1392             return "TX3G";
1393         case SSASUB:
1394             return "SSA";
1395         default:
1396             return "Unknown";
1397     }
1398 }
1399