OSDN Git Service

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