OSDN Git Service

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