OSDN Git Service

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