OSDN Git Service

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