OSDN Git Service

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