OSDN Git Service

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