OSDN Git Service

initialize title->angle_count to 1
[handbrake-jp/handbrake-jp-git.git] / libhb / common.c
1 /* $Id: common.c,v 1.15 2005/03/17 19:22:47 titer Exp $
2
3    This file is part of the HandBrake source code.
4    Homepage: <http://handbrake.fr/>.
5    It may be used under the terms of the GNU General Public License. */
6
7 #include <stdarg.h>
8 #include <time.h>
9 #include <sys/time.h>
10
11 #include "common.h"
12 #include "lang.h"
13 #include "hb.h"
14
15 /**********************************************************************
16  * Global variables
17  *********************************************************************/
18 hb_rate_t hb_video_rates[] =
19 { { "5",  5400000 }, { "10",     2700000 }, { "12", 2250000 },
20   { "15", 1800000 }, { "23.976", 1126125 }, { "24", 1125000 },
21   { "25", 1080000 }, { "29.97",  900900  } };
22 int hb_video_rates_count = sizeof( hb_video_rates ) /
23                            sizeof( hb_rate_t );
24
25 hb_rate_t hb_audio_rates[] =
26 { { "22.05", 22050 }, { "24", 24000 }, { "32", 32000 },
27   { "44.1",  44100 }, { "48", 48000 } };
28 int hb_audio_rates_count   = sizeof( hb_audio_rates ) /
29                              sizeof( hb_rate_t );
30 int hb_audio_rates_default = 3; /* 44100 Hz */
31
32 hb_rate_t hb_audio_bitrates[] =
33 { {  "32",  32 }, {  "40",  40 }, {  "48",  48 }, {  "56",  56 },
34   {  "64",  64 }, {  "80",  80 }, {  "96",  96 }, { "112", 112 },
35   { "128", 128 }, { "160", 160 }, { "192", 192 }, { "224", 224 },
36   { "256", 256 }, { "320", 320 }, { "384", 384 }, { "448", 448 },
37   { "512", 512 }, { "576", 576 }, { "640", 640 }, { "768", 768 } };
38 int hb_audio_bitrates_count = sizeof( hb_audio_bitrates ) /
39                               sizeof( hb_rate_t );
40
41 static hb_error_handler_t *error_handler = NULL;
42
43 hb_mixdown_t hb_audio_mixdowns[] =
44 { { "Mono",               "HB_AMIXDOWN_MONO",      "mono",   HB_AMIXDOWN_MONO      },
45   { "Stereo",             "HB_AMIXDOWN_STEREO",    "stereo", HB_AMIXDOWN_STEREO    },
46   { "Dolby Surround",     "HB_AMIXDOWN_DOLBY",     "dpl1",   HB_AMIXDOWN_DOLBY     },
47   { "Dolby Pro Logic II", "HB_AMIXDOWN_DOLBYPLII", "dpl2",   HB_AMIXDOWN_DOLBYPLII },
48   { "6-channel discrete", "HB_AMIXDOWN_6CH",       "6ch",    HB_AMIXDOWN_6CH       }
49 };
50 int hb_audio_mixdowns_count = sizeof( hb_audio_mixdowns ) /
51                               sizeof( hb_mixdown_t );
52
53 int hb_mixdown_get_mixdown_from_short_name( const char * short_name )
54 {
55     int i;
56     for (i = 0; i < hb_audio_mixdowns_count; i++)
57     {
58         if (strcmp(hb_audio_mixdowns[i].short_name, short_name) == 0)
59         {
60             return hb_audio_mixdowns[i].amixdown;
61         }
62     }
63     return 0;
64 }
65
66 const char * hb_mixdown_get_short_name_from_mixdown( int amixdown )
67 {
68     int i;
69     for (i = 0; i < hb_audio_mixdowns_count; i++)
70     {
71         if (hb_audio_mixdowns[i].amixdown == amixdown)
72         {
73             return hb_audio_mixdowns[i].short_name;
74         }
75     }
76     return "";
77 }
78
79 // Given an input bitrate, find closest match in the set of allowed bitrates
80 int hb_find_closest_audio_bitrate(int bitrate)
81 {
82     int ii;
83     int result;
84
85     // result is highest rate if none found during search.
86     // rate returned will always be <= rate asked for.
87     result = hb_audio_bitrates[0].rate;
88     for (ii = hb_audio_bitrates_count-1; ii >= 0; ii--)
89     {
90         if (bitrate >= hb_audio_bitrates[ii].rate)
91         {
92             result = hb_audio_bitrates[ii].rate;
93             break;
94         }
95     }
96     return result;
97 }
98
99 // Get the bitrate low and high limits for a codec/samplerate/mixdown triplet
100 // The limits have been empirically determined through testing.  Max bitrates
101 // in table below. Numbers in parenthesis are the target bitrate chosen.
102 /*
103 Encoder     1 channel           2 channels          6 channels
104
105 faac
106 24kHz       86 (128)            173 (256)           460 (768)
107 48kHz       152 (160)           304 (320)           759 (768)
108
109 Vorbis
110 24kHz       97 (80)             177 (160)           527 (512)
111 48kHz       241 (224)           465 (448)           783 (768)
112
113 Lame
114 24kHz       146 (768)           138 (768)
115 48kHz       318 (768)           318 (768)
116
117 ffac3
118 24kHz       318 (320)           318 (320)           318 (320)
119 48kHz       636 (640)           636 (640)           636 (640)
120
121 Core Audio  (core audio api provides range of allowed bitrates)
122 24kHz       16-64               32-128              80-320      
123 44.1kHz                         64-320              160-768      
124 48kHz       32-256              64-320              160-768                 
125
126 Core Audio  (minimum limits found in testing)
127 24kHz       16                  32                  96
128 44.1kHz     32                  64                  160
129 48kHz       40                  80                  240
130 */
131
132 void hb_get_audio_bitrate_limits(uint32_t codec, int samplerate, int mixdown, int *low, int *high)
133 {
134     int channels;
135
136     channels = HB_AMIXDOWN_GET_DISCRETE_CHANNEL_COUNT(mixdown);
137     switch (codec)
138     {
139         case HB_ACODEC_AC3:
140             *low = 32 * channels;
141             if (samplerate > 24000)
142             {
143                 *high = 640;
144             }
145             else
146             {
147                 *high = 320;
148             }
149             break;
150
151         case HB_ACODEC_CA_AAC:
152             if (samplerate > 44100)
153             {
154                 *low = channels * 40;
155                 *high = 256;
156                 if (channels == 2)
157                     *high = 320;
158                 if (channels == 6)
159                 {
160                     *high = 768;
161                 }
162             }
163             else if (samplerate > 24000)
164             {
165                 *low = channels * 32;
166                 *high = 256;
167                 if (channels == 2)
168                     *high = 320;
169                 if (channels == 6)
170                 {
171                     *low = 160;
172                     *high = 768;
173                 }
174             }
175             else
176             {
177                 *low = channels * 16;
178                 *high = channels * 64;
179                 if (channels == 6)
180                 {
181                     *high = 320;
182                 }
183             }
184             break;
185
186         case HB_ACODEC_FAAC:
187             *low = 32 * channels;
188             if (samplerate > 24000)
189             {
190                 *high = 160 * channels;
191                 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     t->angle_count   = 1;
1036
1037     return t;
1038 }
1039
1040 /**********************************************************************
1041  * hb_title_close
1042  **********************************************************************
1043  *
1044  *********************************************************************/
1045 void hb_title_close( hb_title_t ** _t )
1046 {
1047     hb_title_t * t = *_t;
1048     hb_audio_t * audio;
1049     hb_chapter_t * chapter;
1050     hb_subtitle_t * subtitle;
1051     hb_attachment_t * attachment;
1052
1053     while( ( audio = hb_list_item( t->list_audio, 0 ) ) )
1054     {
1055         if ( audio->priv.ff_audio_list != NULL )
1056         {
1057             hb_list_close( &audio->priv.ff_audio_list );
1058         }
1059         hb_list_rem( t->list_audio, audio );
1060         free( audio );
1061     }
1062     hb_list_close( &t->list_audio );
1063
1064     while( ( chapter = hb_list_item( t->list_chapter, 0 ) ) )
1065     {
1066         hb_list_rem( t->list_chapter, chapter );
1067         free( chapter );
1068     }
1069     hb_list_close( &t->list_chapter );
1070
1071     while( ( subtitle = hb_list_item( t->list_subtitle, 0 ) ) )
1072     {
1073         hb_list_rem( t->list_subtitle, subtitle );
1074         if ( subtitle->extradata )
1075         {
1076             free( subtitle->extradata );
1077             subtitle->extradata = NULL;
1078         }
1079         free( subtitle );
1080     }
1081     hb_list_close( &t->list_subtitle );
1082     
1083     while( ( attachment = hb_list_item( t->list_attachment, 0 ) ) )
1084     {
1085         hb_list_rem( t->list_attachment, attachment );
1086         if ( attachment->name )
1087         {
1088             free( attachment->name );
1089             attachment->name = NULL;
1090         }
1091         if ( attachment->data )
1092         {
1093             free( attachment->data );
1094             attachment->data = NULL;
1095         }
1096         free( attachment );
1097     }
1098     hb_list_close( &t->list_attachment );
1099
1100     if( t->metadata )
1101     {
1102         if( t->metadata->coverart )
1103         {
1104             free( t->metadata->coverart );
1105         }
1106         free( t->metadata );
1107     }
1108
1109     free( t );
1110     *_t = NULL;
1111 }
1112
1113 /**********************************************************************
1114  * hb_filter_close
1115  **********************************************************************
1116  *
1117  *********************************************************************/
1118 void hb_filter_close( hb_filter_object_t ** _f )
1119 {
1120     hb_filter_object_t * f = *_f;
1121
1122     f->close( f->private_data );
1123
1124     if( f->name )
1125         free( f->name );
1126     if( f->settings )
1127         free( f->settings );
1128
1129     free( f );
1130     *_f = NULL;
1131 }
1132
1133 /**********************************************************************
1134  * hb_audio_copy
1135  **********************************************************************
1136  *
1137  *********************************************************************/
1138 hb_audio_t *hb_audio_copy(const hb_audio_t *src)
1139 {
1140     hb_audio_t *audio = NULL;
1141
1142     if( src )
1143     {
1144         audio = calloc(1, sizeof(*audio));
1145         memcpy(audio, src, sizeof(*audio));
1146     }
1147     return audio;
1148 }
1149
1150 /**********************************************************************
1151  * hb_audio_new
1152  **********************************************************************
1153  *
1154  *********************************************************************/
1155 void hb_audio_config_init(hb_audio_config_t * audiocfg)
1156 {
1157     /* Set read only paramaters to invalid values */
1158     audiocfg->in.codec = 0xDEADBEEF;
1159     audiocfg->in.bitrate = -1;
1160     audiocfg->in.samplerate = -1;
1161     audiocfg->in.channel_layout = 0;
1162     audiocfg->in.version = 0;
1163     audiocfg->in.mode = 0;
1164     audiocfg->flags.ac3 = 0;
1165     audiocfg->lang.description[0] = 0;
1166     audiocfg->lang.simple[0] = 0;
1167     audiocfg->lang.iso639_2[0] = 0;
1168
1169     /* Initalize some sensable defaults */
1170     audiocfg->in.track = audiocfg->out.track = 0;
1171     audiocfg->out.codec = HB_ACODEC_FAAC;
1172     audiocfg->out.bitrate = 128;
1173     audiocfg->out.samplerate = 44100;
1174     audiocfg->out.mixdown = HB_AMIXDOWN_DOLBYPLII;
1175     audiocfg->out.dynamic_range_compression = 0;
1176     audiocfg->out.name = NULL;
1177 }
1178
1179 /**********************************************************************
1180  * hb_audio_add
1181  **********************************************************************
1182  *
1183  *********************************************************************/
1184 int hb_audio_add(const hb_job_t * job, const hb_audio_config_t * audiocfg)
1185 {
1186     hb_title_t *title = job->title;
1187     hb_audio_t *audio;
1188
1189     audio = hb_audio_copy( hb_list_item( title->list_audio, audiocfg->in.track ) );
1190     if( audio == NULL )
1191     {
1192         /* We fail! */
1193         return 0;
1194     }
1195
1196     if( (audiocfg->in.bitrate != -1) && (audiocfg->in.codec != 0xDEADBEEF) )
1197     {
1198         /* This most likely means the client didn't call hb_audio_config_init
1199          * so bail.
1200          */
1201         return 0;
1202     }
1203
1204     /* Really shouldn't ignore the passed out track, but there is currently no
1205      * way to handle duplicates or out-of-order track numbers.
1206      */
1207     audio->config.out.track = hb_list_count(job->list_audio) + 1;
1208     audio->config.out.codec = audiocfg->out.codec;
1209     if( (audiocfg->out.codec & HB_ACODEC_MASK) == audio->config.in.codec &&
1210         (audiocfg->out.codec & HB_ACODEC_PASS_FLAG ) )
1211     {
1212         /* Pass-through, copy from input. */
1213         audio->config.out.samplerate = audio->config.in.samplerate;
1214         audio->config.out.bitrate = audio->config.in.bitrate;
1215         audio->config.out.dynamic_range_compression = 0;
1216         audio->config.out.mixdown = 0;
1217     }
1218     else
1219     {
1220         /* Non pass-through, use what is given. */
1221         audio->config.out.codec &= ~HB_ACODEC_PASS_FLAG;
1222         audio->config.out.samplerate = audiocfg->out.samplerate;
1223         audio->config.out.bitrate = audiocfg->out.bitrate;
1224         audio->config.out.dynamic_range_compression = audiocfg->out.dynamic_range_compression;
1225         audio->config.out.mixdown = audiocfg->out.mixdown;
1226     }
1227
1228     hb_list_add(job->list_audio, audio);
1229     return 1;
1230 }
1231
1232 hb_audio_config_t * hb_list_audio_config_item(hb_list_t * list, int i)
1233 {
1234     hb_audio_t *audio = NULL;
1235
1236     if( (audio = hb_list_item(list, i)) )
1237         return &(audio->config);
1238
1239     return NULL;
1240 }
1241
1242 /**********************************************************************
1243  * hb_subtitle_copy
1244  **********************************************************************
1245  *
1246  *********************************************************************/
1247 hb_subtitle_t *hb_subtitle_copy(const hb_subtitle_t *src)
1248 {
1249     hb_subtitle_t *subtitle = NULL;
1250
1251     if( src )
1252     {
1253         subtitle = calloc(1, sizeof(*subtitle));
1254         memcpy(subtitle, src, sizeof(*subtitle));
1255         if ( src->extradata )
1256         {
1257             subtitle->extradata = malloc( src->extradata_size );
1258             memcpy( subtitle->extradata, src->extradata, src->extradata_size );
1259         }
1260     }
1261     return subtitle;
1262 }
1263
1264 /**********************************************************************
1265  * hb_subtitle_add
1266  **********************************************************************
1267  *
1268  *********************************************************************/
1269 int hb_subtitle_add(const hb_job_t * job, const hb_subtitle_config_t * subtitlecfg, int track)
1270 {
1271     hb_title_t *title = job->title;
1272     hb_subtitle_t *subtitle;
1273
1274     subtitle = hb_subtitle_copy( hb_list_item( title->list_subtitle, track ) );
1275     if( subtitle == NULL )
1276     {
1277         /* We fail! */
1278         return 0;
1279     }
1280     subtitle->config = *subtitlecfg;
1281     hb_list_add(job->list_subtitle, subtitle);
1282     return 1;
1283 }
1284
1285 int hb_srt_add( const hb_job_t * job, 
1286                 const hb_subtitle_config_t * subtitlecfg, 
1287                 const char *lang )
1288 {
1289     hb_subtitle_t *subtitle;
1290     iso639_lang_t *language = NULL;
1291     int retval = 0;
1292
1293     subtitle = calloc( 1, sizeof( *subtitle ) );
1294     
1295     subtitle->id = (hb_list_count(job->list_subtitle) << 8) | 0xFF;
1296     subtitle->format = TEXTSUB;
1297     subtitle->source = SRTSUB;
1298
1299     language = lang_for_code2( lang );
1300
1301     if( language )
1302     {
1303
1304         strcpy( subtitle->lang, language->eng_name );
1305         strncpy( subtitle->iso639_2, lang, 4 );
1306         
1307         subtitle->config = *subtitlecfg;
1308         subtitle->config.dest = PASSTHRUSUB;
1309
1310         hb_list_add(job->list_subtitle, subtitle);
1311         retval = 1;
1312     }
1313     return retval;
1314 }
1315
1316 char * hb_strdup_printf( char * fmt, ... )
1317 {
1318     int       len;
1319     va_list   ap;
1320     int       size = 256;
1321     char    * str;
1322     char    * tmp;
1323
1324     str = malloc( size );
1325     if ( str == NULL )
1326         return NULL;
1327
1328     while (1) 
1329     {
1330         /* Try to print in the allocated space. */
1331         va_start( ap, fmt );
1332         len = vsnprintf( str, size, fmt, ap );
1333         va_end( ap );
1334
1335         /* If that worked, return the string. */
1336         if ( len > -1 && len < size )
1337         {
1338             return str;
1339         }
1340
1341         /* Else try again with more space. */
1342         if ( len > -1 )     /* glibc 2.1 */
1343             size = len + 1; /* precisely what is needed */
1344         else                /* glibc 2.0 */
1345             size *= 2;      /* twice the old size */
1346         tmp = realloc( str, size );
1347         if ( tmp == NULL )
1348         {
1349             free( str );
1350             return NULL;
1351         }
1352         else
1353             str = tmp;
1354     }
1355 }
1356
1357 /**********************************************************************
1358  * hb_attachment_copy
1359  **********************************************************************
1360  *
1361  *********************************************************************/
1362 hb_attachment_t *hb_attachment_copy(const hb_attachment_t *src)
1363 {
1364     hb_attachment_t *attachment = NULL;
1365
1366     if( src )
1367     {
1368         attachment = calloc(1, sizeof(*attachment));
1369         memcpy(attachment, src, sizeof(*attachment));
1370         if ( src->name )
1371         {
1372             attachment->name = strdup( src->name );
1373         }
1374         if ( src->data )
1375         {
1376             attachment->data = malloc( src->size );
1377             memcpy( attachment->data, src->data, src->size );
1378         }
1379     }
1380     return attachment;
1381 }
1382
1383 /**********************************************************************
1384  * hb_yuv2rgb
1385  **********************************************************************
1386  * Converts a YCbCr pixel to an RGB pixel.
1387  * 
1388  * This conversion is lossy (due to rounding and clamping).
1389  * 
1390  * Algorithm:
1391  *   http://en.wikipedia.org/w/index.php?title=YCbCr&oldid=361987695#Technical_details
1392  *********************************************************************/
1393 int hb_yuv2rgb(int yuv)
1394 {
1395     double y, Cr, Cb;
1396     int r, g, b;
1397
1398     y  = (yuv >> 16) & 0xff;
1399     Cb = (yuv >>  8) & 0xff;
1400     Cr = (yuv      ) & 0xff;
1401
1402     r = 1.164 * (y - 16)                      + 2.018 * (Cb - 128);
1403     g = 1.164 * (y - 16) - 0.813 * (Cr - 128) - 0.391 * (Cb - 128);
1404     b = 1.164 * (y - 16) + 1.596 * (Cr - 128);
1405     
1406     r = (r < 0) ? 0 : r;
1407     g = (g < 0) ? 0 : g;
1408     b = (b < 0) ? 0 : b;
1409     
1410     r = (r > 255) ? 255 : r;
1411     g = (g > 255) ? 255 : g;
1412     b = (b > 255) ? 255 : b;
1413     
1414     return (r << 16) | (g << 8) | b;
1415 }
1416
1417 /**********************************************************************
1418  * hb_rgb2yuv
1419  **********************************************************************
1420  * Converts an RGB pixel to a YCbCr pixel.
1421  * 
1422  * This conversion is lossy (due to rounding and clamping).
1423  * 
1424  * Algorithm:
1425  *   http://en.wikipedia.org/w/index.php?title=YCbCr&oldid=361987695#Technical_details
1426  *********************************************************************/
1427 int hb_rgb2yuv(int rgb)
1428 {
1429     double r, g, b;
1430     int y, Cr, Cb;
1431     
1432     r = (rgb >> 16) & 0xff;
1433     g = (rgb >>  8) & 0xff;
1434     b = (rgb      ) & 0xff;
1435
1436     y  =  16. + ( 0.257 * r) + (0.504 * g) + (0.098 * b);
1437     Cb = 128. + (-0.148 * r) - (0.291 * g) + (0.439 * b);
1438     Cr = 128. + ( 0.439 * r) - (0.368 * g) - (0.071 * b);
1439     
1440     y = (y < 0) ? 0 : y;
1441     Cb = (Cb < 0) ? 0 : Cb;
1442     Cr = (Cr < 0) ? 0 : Cr;
1443     
1444     y = (y > 255) ? 255 : y;
1445     Cb = (Cb > 255) ? 255 : Cb;
1446     Cr = (Cr > 255) ? 255 : Cr;
1447     
1448     return (y << 16) | (Cb << 8) | Cr;
1449 }
1450
1451 const char * hb_subsource_name( int source )
1452 {
1453     switch (source)
1454     {
1455         case VOBSUB:
1456             return "VOBSUB";
1457         case SRTSUB:
1458             return "SRT";
1459         case CC608SUB:
1460             return "CC";
1461         case CC708SUB:
1462             return "CC";
1463         case UTF8SUB:
1464             return "UTF-8";
1465         case TX3GSUB:
1466             return "TX3G";
1467         case SSASUB:
1468             return "SSA";
1469         default:
1470             return "Unknown";
1471     }
1472 }
1473