OSDN Git Service

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