OSDN Git Service

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