OSDN Git Service

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