OSDN Git Service

Saearch & Replace domain names to move from .m0k.org to handbrake.fr. Only covers...
[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 #include <assert.h>
11
12 #include "common.h"
13
14 /**********************************************************************
15  * Global variables
16  *********************************************************************/
17 hb_rate_t hb_video_rates[] =
18 { { "5",  5400000 }, { "10",     2700000 }, { "12", 2250000 },
19   { "15", 1800000 }, { "23.976", 1126125 }, { "24", 1125000 },
20   { "25", 1080000 }, { "29.97",  900900  } };
21 int hb_video_rates_count = sizeof( hb_video_rates ) /
22                            sizeof( hb_rate_t );
23
24 hb_rate_t hb_audio_rates[] =
25 { { "22.05", 22050 }, { "24", 24000 }, { "32", 32000 },
26   { "44.1",  44100 }, { "48", 48000 } };
27 int hb_audio_rates_count   = sizeof( hb_audio_rates ) /
28                              sizeof( hb_rate_t );
29 int hb_audio_rates_default = 3; /* 44100 Hz */
30
31 hb_rate_t hb_audio_bitrates[] =
32 { {  "32",  32 }, {  "40",  40 }, {  "48",  48 }, {  "56",  56 },
33   {  "64",  64 }, {  "80",  80 }, {  "96",  96 }, { "112", 112 },
34   { "128", 128 }, { "160", 160 }, { "192", 192 }, { "224", 224 },
35   { "256", 256 }, { "320", 320 }, { "384", 384 } };
36 int hb_audio_bitrates_count = sizeof( hb_audio_bitrates ) /
37                               sizeof( hb_rate_t );
38 int hb_audio_bitrates_default = 8; /* 128 kbps */
39
40 static hb_error_handler_t *error_handler = NULL;
41
42 hb_mixdown_t hb_audio_mixdowns[] =
43 { { "Mono",               "HB_AMIXDOWN_MONO",      "mono",   HB_AMIXDOWN_MONO      },
44   { "Stereo",             "HB_AMIXDOWN_STEREO",    "stereo", HB_AMIXDOWN_STEREO    },
45   { "Dolby Surround",     "HB_AMIXDOWN_DOLBY",     "dpl1",   HB_AMIXDOWN_DOLBY     },
46   { "Dolby Pro Logic II", "HB_AMIXDOWN_DOLBYPLII", "dpl2",   HB_AMIXDOWN_DOLBYPLII },
47   { "6-channel discrete", "HB_AMIXDOWN_6CH",       "6ch",    HB_AMIXDOWN_6CH       }
48 };
49 int hb_audio_mixdowns_count = sizeof( hb_audio_mixdowns ) /
50                               sizeof( hb_mixdown_t );
51
52 int hb_mixdown_get_mixdown_from_short_name( const char * short_name )
53 {
54     int i;
55     for (i = 0; i < hb_audio_mixdowns_count; i++)
56     {
57         if (strcmp(hb_audio_mixdowns[i].short_name, short_name) == 0)
58         {
59             return hb_audio_mixdowns[i].amixdown;
60         }
61     }
62     return 0;
63 }
64
65 const char * hb_mixdown_get_short_name_from_mixdown( int amixdown )
66 {
67     int i;
68     for (i = 0; i < hb_audio_mixdowns_count; i++)
69     {
70         if (hb_audio_mixdowns[i].amixdown == amixdown)
71         {
72             return hb_audio_mixdowns[i].short_name;
73         }
74     }
75     return "";
76 }
77
78 /**********************************************************************
79  * hb_reduce
80  **********************************************************************
81  * Given a numerator (num) and a denominator (den), reduce them to an
82  * equivalent fraction and store the result in x and y.
83  *********************************************************************/
84 void hb_reduce( int *x, int *y, int num, int den )
85 {
86     int lower = MIN( num, den );
87     int i;
88     *x = num;
89     *y = den;
90     for( i = lower - 1; i > 1; --i )
91     {
92         if( ( num % i == 0 ) && ( den % i == 0 ) )
93         {
94             *x = num / i;
95             *y = den / i;
96             break;
97         }
98     }
99 }
100
101 /**********************************************************************
102  * hb_fix_aspect
103  **********************************************************************
104  * Given the output width (if HB_KEEP_WIDTH) or height
105  * (HB_KEEP_HEIGHT) and the current crop values, calculates the
106  * correct height or width in order to respect the DVD aspect ratio
107  *********************************************************************/
108 void hb_fix_aspect( hb_job_t * job, int keep )
109 {
110     hb_title_t * title = job->title;
111     int          i;
112
113     /* don't do anything unless the title has complete size info */
114     if ( title->height == 0 || title->width == 0 || title->aspect == 0 )
115     {
116         hb_log( "hb_fix_aspect: incomplete info for title %d: "
117                 "height = %d, width = %d, aspect = %d",
118                 title->height, title->width, title->aspect );
119         return;
120     }
121
122     /* Sanity checks:
123        Widths and heights must be multiples of 16 and greater than or
124        equal to 16
125        Crop values must be multiples of 2, greater than or equal to 0
126        and less than half of the dimension */
127     job->width   = MULTIPLE_16( job->width );
128     job->height  = MULTIPLE_16( job->height );
129     job->width   = MAX( 16, job->width );
130     job->height  = MAX( 16, job->height );
131     for( i = 0; i < 4; i++ )
132     {
133         job->crop[i] = EVEN( job->crop[i] );
134         job->crop[i] = MAX( 0, job->crop[i] );
135         if( i < 2 )
136         {
137             /* Top, bottom */
138             job->crop[i] = MIN( job->crop[i], ( title->height / 2 ) - 2 );
139         }
140         else
141         {
142             /* Left, right */
143             job->crop[i] = MIN( job->crop[i], ( title->width / 2 ) - 2 );
144         }
145     }
146
147     if( keep == HB_KEEP_WIDTH )
148     {
149         job->height = MULTIPLE_16(
150             (uint64_t) job->width * title->width * HB_ASPECT_BASE *
151               ( title->height - job->crop[0] - job->crop[1] ) /
152             ( (uint64_t) title->height * title->aspect *
153               ( title->width - job->crop[2] - job->crop[3] ) ) );
154         job->height = MAX( 16, job->height );
155     }
156     else
157     {
158         job->width = MULTIPLE_16(
159             (uint64_t) job->height * title->height * title->aspect *
160               ( title->width - job->crop[2] - job->crop[3] ) /
161             ( (uint64_t) title->width * HB_ASPECT_BASE *
162               ( title->height - job->crop[0] - job->crop[1] ) ) );
163         job->width = MAX( 16, job->width );
164     }
165 }
166
167 /**********************************************************************
168  * hb_calc_bitrate
169  **********************************************************************
170  * size: in megabytes
171  *********************************************************************/
172 int hb_calc_bitrate( hb_job_t * job, int size )
173 {
174     int64_t avail = (int64_t) size * 1024 * 1024;
175     int64_t length;
176     int     overhead;
177     int     samples_per_frame;
178     int     i;
179
180     hb_title_t   * title = job->title;
181     hb_chapter_t * chapter;
182     hb_audio_t   * audio;
183
184     /* How many overhead bytes are used for each frame
185        (quite guessed) */
186     switch( job->mux )
187     {
188        case HB_MUX_MP4:
189        case HB_MUX_PSP:
190                 case HB_MUX_IPOD:
191                 case HB_MUX_MKV:
192             overhead = 6;
193             break;
194         case HB_MUX_AVI:
195             overhead = 24;
196             break;
197         case HB_MUX_OGM:
198             overhead = 6;
199             break;
200         default:
201             return 0;
202     }
203
204     /* Get the duration in seconds */
205     length = 0;
206     for( i = job->chapter_start; i <= job->chapter_end; i++ )
207     {
208         chapter = hb_list_item( title->list_chapter, i - 1 );
209         length += chapter->duration;
210     }
211     length += 135000;
212     length /= 90000;
213
214     /* Video overhead */
215     avail -= length * job->vrate * overhead / job->vrate_base;
216
217     for( i = 0; i < hb_list_count(job->list_audio); i++ )
218     {
219         /* Audio data */
220         int abitrate;
221         audio = hb_list_item( job->list_audio, i);
222
223         /* How many audio samples we put in each frame */
224         switch( audio->config.out.codec )
225         {
226             case HB_ACODEC_FAAC:
227             case HB_ACODEC_VORBIS:
228                 samples_per_frame = 1024;
229                 break;
230             case HB_ACODEC_LAME:
231                 samples_per_frame = 1152;
232                 break;
233             case HB_ACODEC_AC3:
234                 samples_per_frame = 1536;
235                 break;
236             default:
237                 return 0;
238         }
239
240         if( audio->config.out.codec == HB_ACODEC_AC3 ||
241             audio->config.out.codec == HB_ACODEC_DCA)
242         {
243             /*
244              * For pass through we take the bitrate from the input audio
245              * bitrate as we are simply passing it through.
246              */
247             abitrate = audio->config.in.bitrate / 8;
248         }
249         else
250         {
251             /*
252              * Where we are transcoding the audio we use the destination
253              * bitrate.
254              */
255             abitrate = audio->config.out.bitrate * 1000 / 8;
256         }
257         avail -= length * abitrate;
258
259         /* Audio overhead */
260         avail -= length * audio->config.out.samplerate * overhead / samples_per_frame;
261     }
262
263     if( avail < 0 )
264     {
265         return 0;
266     }
267
268     return ( avail / ( 125 * length ) );
269 }
270
271 /**********************************************************************
272  * hb_list implementation
273  **********************************************************************
274  * Basic and slow, but enough for what we need
275  *********************************************************************/
276
277 #define HB_LIST_DEFAULT_SIZE 20
278
279 struct hb_list_s
280 {
281     /* Pointers to items in the list */
282     void ** items;
283
284     /* How many (void *) allocated in 'items' */
285     int     items_alloc;
286
287     /* How many valid pointers in 'items' */
288     int     items_count;
289 };
290
291 /**********************************************************************
292  * hb_list_init
293  **********************************************************************
294  * Allocates an empty list ready for HB_LIST_DEFAULT_SIZE items
295  *********************************************************************/
296 hb_list_t * hb_list_init()
297 {
298     hb_list_t * l;
299
300     l              = calloc( sizeof( hb_list_t ), 1 );
301     l->items       = calloc( HB_LIST_DEFAULT_SIZE * sizeof( void * ), 1 );
302     l->items_alloc = HB_LIST_DEFAULT_SIZE;
303
304     return l;
305 }
306
307 /**********************************************************************
308  * hb_list_count
309  **********************************************************************
310  * Returns the number of items currently in the list
311  *********************************************************************/
312 int hb_list_count( hb_list_t * l )
313 {
314     return l->items_count;
315 }
316
317 /**********************************************************************
318  * hb_list_add
319  **********************************************************************
320  * Adds an item at the end of the list, making it bigger if necessary.
321  * Can safely be called with a NULL pointer to add, it will be ignored.
322  *********************************************************************/
323 void hb_list_add( hb_list_t * l, void * p )
324 {
325     if( !p )
326     {
327         return;
328     }
329
330     if( l->items_count == l->items_alloc )
331     {
332         /* We need a bigger boat */
333         l->items_alloc += HB_LIST_DEFAULT_SIZE;
334         l->items        = realloc( l->items,
335                                    l->items_alloc * sizeof( void * ) );
336     }
337
338     l->items[l->items_count] = p;
339     (l->items_count)++;
340 }
341
342 /**********************************************************************
343  * hb_list_rem
344  **********************************************************************
345  * Remove an item from the list. Bad things will happen if called
346  * with a NULL pointer or if the item is not in the list.
347  *********************************************************************/
348 void hb_list_rem( hb_list_t * l, void * p )
349 {
350     int i;
351
352     /* Find the item in the list */
353     for( i = 0; i < l->items_count; i++ )
354     {
355         if( l->items[i] == p )
356         {
357             break;
358         }
359     }
360
361     /* Shift all items after it sizeof( void * ) bytes earlier */
362     memmove( &l->items[i], &l->items[i+1],
363              ( l->items_count - i - 1 ) * sizeof( void * ) );
364
365     (l->items_count)--;
366 }
367
368 /**********************************************************************
369  * hb_list_item
370  **********************************************************************
371  * Returns item at position i, or NULL if there are not that many
372  * items in the list
373  *********************************************************************/
374 void * hb_list_item( hb_list_t * l, int i )
375 {
376     if( i < 0 || i >= l->items_count )
377     {
378         return NULL;
379     }
380
381     return l->items[i];
382 }
383
384 /**********************************************************************
385  * hb_list_bytes
386  **********************************************************************
387  * Assuming all items are of type hb_buffer_t, returns the total
388  * number of bytes in the list
389  *********************************************************************/
390 int hb_list_bytes( hb_list_t * l )
391 {
392     hb_buffer_t * buf;
393     int           ret;
394     int           i;
395
396     ret = 0;
397     for( i = 0; i < hb_list_count( l ); i++ )
398     {
399         buf  = hb_list_item( l, i );
400         ret += buf->size - buf->cur;
401     }
402
403     return ret;
404 }
405
406 /**********************************************************************
407  * hb_list_seebytes
408  **********************************************************************
409  * Assuming all items are of type hb_buffer_t, copy <size> bytes from
410  * the list to <dst>, keeping the list unmodified.
411  *********************************************************************/
412 void hb_list_seebytes( hb_list_t * l, uint8_t * dst, int size )
413 {
414     hb_buffer_t * buf;
415     int           copied;
416     int           copying;
417     int           i;
418
419     for( i = 0, copied = 0; copied < size; i++ )
420     {
421         buf     = hb_list_item( l, i );
422         copying = MIN( buf->size - buf->cur, size - copied );
423         memcpy( &dst[copied], &buf->data[buf->cur], copying );
424         copied += copying;
425     }
426 }
427
428 /**********************************************************************
429  * hb_list_getbytes
430  **********************************************************************
431  * Assuming all items are of type hb_buffer_t, copy <size> bytes from
432  * the list to <dst>. What's copied is removed from the list.
433  * The variable pointed by <pts> is set to the PTS of the buffer the
434  * first byte has been got from.
435  * The variable pointed by <pos> is set to the position of that byte
436  * in that buffer.
437  *********************************************************************/
438 void hb_list_getbytes( hb_list_t * l, uint8_t * dst, int size,
439                        uint64_t * pts, uint64_t * pos )
440 {
441     hb_buffer_t * buf;
442     int           copied;
443     int           copying;
444     uint8_t       has_pts;
445
446     /* So we won't have to deal with NULL pointers */
447      uint64_t dummy1, dummy2;
448
449     if( !pts ) pts = &dummy1;
450     if( !pos ) pos = &dummy2;
451
452     for( copied = 0, has_pts = 0; copied < size;  )
453     {
454         buf     = hb_list_item( l, 0 );
455         copying = MIN( buf->size - buf->cur, size - copied );
456         memcpy( &dst[copied], &buf->data[buf->cur], copying );
457
458         if( !has_pts )
459         {
460             *pts    = buf->start;
461             *pos    = buf->cur;
462             has_pts = 1;
463         }
464
465         buf->cur += copying;
466         if( buf->cur >= buf->size )
467         {
468             hb_list_rem( l, buf );
469             hb_buffer_close( &buf );
470         }
471
472         copied += copying;
473     }
474 }
475
476 /**********************************************************************
477  * hb_list_empty
478  **********************************************************************
479  * Assuming all items are of type hb_buffer_t, close them all and
480  * close the list.
481  *********************************************************************/
482 void hb_list_empty( hb_list_t ** _l )
483 {
484     hb_list_t * l = *_l;
485     hb_buffer_t * b;
486
487     while( ( b = hb_list_item( l, 0 ) ) )
488     {
489         hb_list_rem( l, b );
490         hb_buffer_close( &b );
491     }
492
493     hb_list_close( _l );
494 }
495
496 /**********************************************************************
497  * hb_list_close
498  **********************************************************************
499  * Free memory allocated by hb_list_init. Does NOT free contents of
500  * items still in the list.
501  *********************************************************************/
502 void hb_list_close( hb_list_t ** _l )
503 {
504     hb_list_t * l = *_l;
505
506     free( l->items );
507     free( l );
508
509     *_l = NULL;
510 }
511
512 /**********************************************************************
513  * hb_log
514  **********************************************************************
515  * If verbose mode is one, print message with timestamp. Messages
516  * longer than 180 characters are stripped ;p
517  *********************************************************************/
518 void hb_log( char * log, ... )
519 {
520     char        string[362]; /* 360 chars + \n + \0 */
521     time_t      _now;
522     struct tm * now;
523     va_list     args;
524
525     if( !getenv( "HB_DEBUG" ) )
526     {
527         /* We don't want to print it */
528         return;
529     }
530
531     /* Get the time */
532     _now = time( NULL );
533     now  = localtime( &_now );
534     sprintf( string, "[%02d:%02d:%02d] ",
535              now->tm_hour, now->tm_min, now->tm_sec );
536
537     /* Convert the message to a string */
538     va_start( args, log );
539     vsnprintf( string + 11, 349, log, args );
540     va_end( args );
541
542     /* Add the end of line */
543     strcat( string, "\n" );
544
545     /* Print it */
546     fprintf( stderr, "%s", string );
547 }
548
549 /**********************************************************************
550  * hb_error
551  **********************************************************************
552  * Using whatever output is available display this error.
553  *********************************************************************/
554 void hb_error( char * log, ... )
555 {
556     char        string[181]; /* 180 chars + \0 */
557     va_list     args;
558
559     /* Convert the message to a string */
560     va_start( args, log );
561     vsnprintf( string, 180, log, args );
562     va_end( args );
563
564     /*
565      * Got the error in a single string, send it off to be dispatched.
566      */
567     if( error_handler )
568     {
569         error_handler( string );
570     } else {
571         hb_log( string );
572     }
573 }
574
575 void hb_register_error_handler( hb_error_handler_t * handler )
576 {
577     error_handler = handler;
578 }
579
580 /**********************************************************************
581  * hb_title_init
582  **********************************************************************
583  *
584  *********************************************************************/
585 hb_title_t * hb_title_init( char * dvd, int index )
586 {
587     hb_title_t * t;
588
589     t = calloc( sizeof( hb_title_t ), 1 );
590
591     t->index         = index;
592     t->list_audio    = hb_list_init();
593     t->list_chapter  = hb_list_init();
594     t->list_subtitle = hb_list_init();
595     strcat( t->dvd, dvd );
596
597     return t;
598 }
599
600 /**********************************************************************
601  * hb_title_close
602  **********************************************************************
603  *
604  *********************************************************************/
605 void hb_title_close( hb_title_t ** _t )
606 {
607     hb_title_t * t = *_t;
608     hb_audio_t * audio;
609     hb_chapter_t * chapter;
610     hb_subtitle_t * subtitle;
611
612     while( ( audio = hb_list_item( t->list_audio, 0 ) ) )
613     {
614         hb_list_rem( t->list_audio, audio );
615         free( audio );
616     }
617     hb_list_close( &t->list_audio );
618
619     while( ( chapter = hb_list_item( t->list_chapter, 0 ) ) )
620     {
621         hb_list_rem( t->list_chapter, chapter );
622         free( chapter );
623     }
624     hb_list_close( &t->list_chapter );
625
626     while( ( subtitle = hb_list_item( t->list_subtitle, 0 ) ) )
627     {
628         hb_list_rem( t->list_subtitle, subtitle );
629         free( subtitle );
630     }
631     hb_list_close( &t->list_subtitle );
632
633     free( t );
634     *_t = NULL;
635 }
636
637 /**********************************************************************
638  * hb_filter_close
639  **********************************************************************
640  *
641  *********************************************************************/
642 void hb_filter_close( hb_filter_object_t ** _f )
643 {
644     hb_filter_object_t * f = *_f;
645
646     f->close( f->private_data );
647
648     if( f->name )
649         free( f->name );
650     if( f->settings )
651         free( f->settings );
652
653     free( f );
654     *_f = NULL;
655 }
656
657 /**********************************************************************
658  * hb_audio_copy
659  **********************************************************************
660  *
661  *********************************************************************/
662 hb_audio_t *hb_audio_copy(const hb_audio_t *src)
663 {
664     hb_audio_t *audio = calloc(1, sizeof(*audio));
665     memcpy(audio, src, sizeof(*audio));
666     return audio;
667 }
668
669 /**********************************************************************
670  * hb_audio_new
671  **********************************************************************
672  *
673  *********************************************************************/
674 void hb_audio_config_init(hb_audio_config_t * audiocfg)
675 {
676     assert(audiocfg != NULL);
677
678     /* Set read only paramaters to invalid values */
679     audiocfg->in.codec = 0xDEADBEEF;
680     audiocfg->in.bitrate = -1;
681     audiocfg->in.samplerate = -1;
682     audiocfg->in.channel_layout = 0;
683     audiocfg->flags.ac3 = 0;
684     audiocfg->lang.description[0] = 0;
685     audiocfg->lang.simple[0] = 0;
686     audiocfg->lang.iso639_2[0] = 0;
687
688     /* Initalize some sensable defaults */
689     audiocfg->in.track = audiocfg->out.track = 0;
690     audiocfg->out.codec = HB_ACODEC_FAAC;
691     audiocfg->out.bitrate = 128;
692     audiocfg->out.samplerate = 44100;
693     audiocfg->out.mixdown = HB_AMIXDOWN_DOLBYPLII;
694     audiocfg->out.dynamic_range_compression = 0;
695 }
696
697 /**********************************************************************
698  * hb_audio_add
699  **********************************************************************
700  *
701  *********************************************************************/
702 int hb_audio_add(const hb_job_t * job, const hb_audio_config_t * audiocfg)
703 {
704     assert(job != NULL);
705     assert(audiocfg != NULL);
706
707     hb_title_t *title = job->title;
708     hb_audio_t *audio;
709
710     audio = hb_audio_copy( hb_list_item( title->list_audio, audiocfg->in.track ) );
711     if( audio == NULL )
712     {
713         /* We fail! */
714         return 0;
715     }
716
717     if( (audiocfg->in.bitrate != -1) && (audiocfg->in.codec != 0xDEADBEEF) )
718     {
719         /* This most likely means the client didn't call hb_audio_config_init
720          * so bail.
721          */
722         return 0;
723     }
724
725     /* Really shouldn't ignore the passed out track, but there is currently no
726      * way to handle duplicates or out-of-order track numbers.
727      */
728     audio->config.out.track = hb_list_count(job->list_audio) + 1;
729     audio->config.out.codec = audiocfg->out.codec;
730     audio->config.out.samplerate = audiocfg->out.samplerate;
731     audio->config.out.bitrate = audiocfg->out.bitrate;
732     audio->config.out.mixdown = audiocfg->out.mixdown;
733     audio->config.out.dynamic_range_compression = audiocfg->out.dynamic_range_compression;
734
735     hb_list_add(job->list_audio, audio);
736     return 1;
737 }
738
739 hb_audio_config_t * hb_list_audio_config_item(hb_list_t * list, int i)
740 {
741     assert(list != NULL);
742
743     hb_audio_t *audio = hb_list_item(list, i);
744
745     return &(audio->config);
746 }