OSDN Git Service

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