OSDN Git Service

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