OSDN Git Service

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