1 /* $Id: common.c,v 1.15 2005/03/17 19:22:47 titer Exp $
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. */
15 /**********************************************************************
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 ) /
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 ) /
30 int hb_audio_rates_default = 3; /* 44100 Hz */
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 },
38 int hb_audio_bitrates_count = sizeof( hb_audio_bitrates ) /
40 int hb_audio_bitrates_default = 8; /* 128 kbps */
42 static hb_error_handler_t *error_handler = NULL;
44 hb_mixdown_t hb_audio_mixdowns[] =
45 { { "Mono", "HB_AMIXDOWN_MONO", "mono", HB_AMIXDOWN_MONO },
46 { "Stereo", "HB_AMIXDOWN_STEREO", "stereo", HB_AMIXDOWN_STEREO },
47 { "Dolby Surround", "HB_AMIXDOWN_DOLBY", "dpl1", HB_AMIXDOWN_DOLBY },
48 { "Dolby Pro Logic II", "HB_AMIXDOWN_DOLBYPLII", "dpl2", HB_AMIXDOWN_DOLBYPLII },
49 { "6-channel discrete", "HB_AMIXDOWN_6CH", "6ch", HB_AMIXDOWN_6CH }
51 int hb_audio_mixdowns_count = sizeof( hb_audio_mixdowns ) /
52 sizeof( hb_mixdown_t );
54 int hb_mixdown_get_mixdown_from_short_name( const char * short_name )
57 for (i = 0; i < hb_audio_mixdowns_count; i++)
59 if (strcmp(hb_audio_mixdowns[i].short_name, short_name) == 0)
61 return hb_audio_mixdowns[i].amixdown;
67 const char * hb_mixdown_get_short_name_from_mixdown( int amixdown )
70 for (i = 0; i < hb_audio_mixdowns_count; i++)
72 if (hb_audio_mixdowns[i].amixdown == amixdown)
74 return hb_audio_mixdowns[i].short_name;
80 /**********************************************************************
82 **********************************************************************
83 * Given a numerator (num) and a denominator (den), reduce them to an
84 * equivalent fraction and store the result in x and y.
85 *********************************************************************/
86 void hb_reduce( int *x, int *y, int num, int den )
88 // find the greatest common divisor of num & den by Euclid's algorithm
97 // at this point n is the gcd. if it's non-zero remove it from num
98 // and den. Otherwise just return the original values.
111 /**********************************************************************
113 **********************************************************************
114 * Given the output width (if HB_KEEP_WIDTH) or height
115 * (HB_KEEP_HEIGHT) and the current crop values, calculates the
116 * correct height or width in order to respect the DVD aspect ratio
117 *********************************************************************/
118 void hb_fix_aspect( hb_job_t * job, int keep )
120 hb_title_t * title = job->title;
126 /* don't do anything unless the title has complete size info */
127 if ( title->height == 0 || title->width == 0 || title->aspect == 0 )
129 hb_log( "hb_fix_aspect: incomplete info for title %d: "
130 "height = %d, width = %d, aspect = %.3f",
131 title->index, title->height, title->width, title->aspect );
135 // min_width and min_height should be multiples of modulus
138 modulus = job->modulus ? job->modulus : 16;
140 for( i = 0; i < 4; i++ )
142 // Sanity check crop values are zero or positive multiples of 2
146 job->crop[i] = MIN( EVEN( job->crop[i] ), EVEN( ( title->height / 2 ) - ( min_height / 2 ) ) );
147 job->crop[i] = MAX( 0, job->crop[i] );
152 job->crop[i] = MIN( EVEN( job->crop[i] ), EVEN( ( title->width / 2 ) - ( min_width / 2 ) ) );
153 job->crop[i] = MAX( 0, job->crop[i] );
157 double par = (double)title->width / ( (double)title->height * title->aspect );
158 double cropped_sar = (double)( title->height - job->crop[0] - job->crop[1] ) /
159 (double)( title->width - job->crop[2] - job->crop[3] );
160 double ar = par * cropped_sar;
162 // Dimensions must be greater than minimum and multiple of modulus
163 if( keep == HB_KEEP_WIDTH )
165 job->width = MULTIPLE_MOD( job->width, modulus );
166 job->width = MAX( min_width, job->width );
167 job->height = MULTIPLE_MOD( (uint64_t)( (double)job->width * ar ), modulus );
168 job->height = MAX( min_height, job->height );
172 job->height = MULTIPLE_MOD( job->height, modulus );
173 job->height = MAX( min_height, job->height );
174 job->width = MULTIPLE_MOD( (uint64_t)( (double)job->height / ar ), modulus );
175 job->width = MAX( min_width, job->width );
179 /**********************************************************************
181 **********************************************************************
183 *********************************************************************/
184 int hb_calc_bitrate( hb_job_t * job, int size )
186 int64_t avail = (int64_t) size * 1024 * 1024;
189 int samples_per_frame;
192 hb_title_t * title = job->title;
193 hb_chapter_t * chapter;
196 /* How many overhead bytes are used for each frame
216 /* Get the duration in seconds */
218 for( i = job->chapter_start; i <= job->chapter_end; i++ )
220 chapter = hb_list_item( title->list_chapter, i - 1 );
221 length += chapter->duration;
228 hb_interjob_t * interjob = hb_interjob_get( job->h );
229 avail = job->vbitrate * 125 * length;
230 avail += length * interjob->vrate * overhead / interjob->vrate_base;
234 avail -= length * job->vrate * overhead / job->vrate_base;
241 for( i = 0; i < hb_list_count(job->list_audio); i++ )
245 audio = hb_list_item( job->list_audio, i);
247 /* How many audio samples we put in each frame */
248 switch( audio->config.out.codec )
251 case HB_ACODEC_CA_AAC:
252 case HB_ACODEC_VORBIS:
253 samples_per_frame = 1024;
256 samples_per_frame = 1152;
260 samples_per_frame = 1536;
266 if( audio->config.out.codec == HB_ACODEC_AC3 ||
267 audio->config.out.codec == HB_ACODEC_DCA)
270 * For pass through we take the bitrate from the input audio
271 * bitrate as we are simply passing it through.
273 abitrate = audio->config.in.bitrate / 8;
278 * Where we are transcoding the audio we use the destination
281 abitrate = audio->config.out.bitrate * 1000 / 8;
283 avail -= length * abitrate;
286 avail -= length * audio->config.out.samplerate * overhead / samples_per_frame;
295 return ( avail / ( 125 * length ) );
298 /**********************************************************************
299 * hb_list implementation
300 **********************************************************************
301 * Basic and slow, but enough for what we need
302 *********************************************************************/
304 #define HB_LIST_DEFAULT_SIZE 20
308 /* Pointers to items in the list */
311 /* How many (void *) allocated in 'items' */
314 /* How many valid pointers in 'items' */
318 /**********************************************************************
320 **********************************************************************
321 * Allocates an empty list ready for HB_LIST_DEFAULT_SIZE items
322 *********************************************************************/
323 hb_list_t * hb_list_init()
327 l = calloc( sizeof( hb_list_t ), 1 );
328 l->items = calloc( HB_LIST_DEFAULT_SIZE * sizeof( void * ), 1 );
329 l->items_alloc = HB_LIST_DEFAULT_SIZE;
334 /**********************************************************************
336 **********************************************************************
337 * Returns the number of items currently in the list
338 *********************************************************************/
339 int hb_list_count( hb_list_t * l )
341 return l->items_count;
344 /**********************************************************************
346 **********************************************************************
347 * Adds an item at the end of the list, making it bigger if necessary.
348 * Can safely be called with a NULL pointer to add, it will be ignored.
349 *********************************************************************/
350 void hb_list_add( hb_list_t * l, void * p )
357 if( l->items_count == l->items_alloc )
359 /* We need a bigger boat */
360 l->items_alloc += HB_LIST_DEFAULT_SIZE;
361 l->items = realloc( l->items,
362 l->items_alloc * sizeof( void * ) );
365 l->items[l->items_count] = p;
369 /**********************************************************************
371 **********************************************************************
372 * Remove an item from the list. Bad things will happen if called
373 * with a NULL pointer or if the item is not in the list.
374 *********************************************************************/
375 void hb_list_rem( hb_list_t * l, void * p )
379 /* Find the item in the list */
380 for( i = 0; i < l->items_count; i++ )
382 if( l->items[i] == p )
388 /* Shift all items after it sizeof( void * ) bytes earlier */
389 memmove( &l->items[i], &l->items[i+1],
390 ( l->items_count - i - 1 ) * sizeof( void * ) );
395 /**********************************************************************
397 **********************************************************************
398 * Returns item at position i, or NULL if there are not that many
400 *********************************************************************/
401 void * hb_list_item( hb_list_t * l, int i )
403 if( i < 0 || i >= l->items_count )
411 /**********************************************************************
413 **********************************************************************
414 * Assuming all items are of type hb_buffer_t, returns the total
415 * number of bytes in the list
416 *********************************************************************/
417 int hb_list_bytes( hb_list_t * l )
424 for( i = 0; i < hb_list_count( l ); i++ )
426 buf = hb_list_item( l, i );
427 ret += buf->size - buf->cur;
433 /**********************************************************************
435 **********************************************************************
436 * Assuming all items are of type hb_buffer_t, copy <size> bytes from
437 * the list to <dst>, keeping the list unmodified.
438 *********************************************************************/
439 void hb_list_seebytes( hb_list_t * l, uint8_t * dst, int size )
446 for( i = 0, copied = 0; copied < size; i++ )
448 buf = hb_list_item( l, i );
449 copying = MIN( buf->size - buf->cur, size - copied );
450 memcpy( &dst[copied], &buf->data[buf->cur], copying );
455 /**********************************************************************
457 **********************************************************************
458 * Assuming all items are of type hb_buffer_t, copy <size> bytes from
459 * the list to <dst>. What's copied is removed from the list.
460 * The variable pointed by <pts> is set to the PTS of the buffer the
461 * first byte has been got from.
462 * The variable pointed by <pos> is set to the position of that byte
464 *********************************************************************/
465 void hb_list_getbytes( hb_list_t * l, uint8_t * dst, int size,
466 uint64_t * pts, uint64_t * pos )
473 /* So we won't have to deal with NULL pointers */
474 uint64_t dummy1, dummy2;
476 if( !pts ) pts = &dummy1;
477 if( !pos ) pos = &dummy2;
479 for( copied = 0, has_pts = 0; copied < size; )
481 buf = hb_list_item( l, 0 );
482 copying = MIN( buf->size - buf->cur, size - copied );
483 memcpy( &dst[copied], &buf->data[buf->cur], copying );
493 if( buf->cur >= buf->size )
495 hb_list_rem( l, buf );
496 hb_buffer_close( &buf );
503 /**********************************************************************
505 **********************************************************************
506 * Assuming all items are of type hb_buffer_t, close them all and
508 *********************************************************************/
509 void hb_list_empty( hb_list_t ** _l )
514 while( ( b = hb_list_item( l, 0 ) ) )
517 hb_buffer_close( &b );
523 /**********************************************************************
525 **********************************************************************
526 * Free memory allocated by hb_list_init. Does NOT free contents of
527 * items still in the list.
528 *********************************************************************/
529 void hb_list_close( hb_list_t ** _l )
539 /**********************************************************************
541 **********************************************************************
542 * If verbose mode is one, print message with timestamp. Messages
543 * longer than 180 characters are stripped ;p
544 *********************************************************************/
545 void hb_log( char * log, ... )
547 char string[362]; /* 360 chars + \n + \0 */
552 if( !getenv( "HB_DEBUG" ) )
554 /* We don't want to print it */
560 now = localtime( &_now );
561 sprintf( string, "[%02d:%02d:%02d] ",
562 now->tm_hour, now->tm_min, now->tm_sec );
564 /* Convert the message to a string */
565 va_start( args, log );
566 vsnprintf( string + 11, 349, log, args );
569 /* Add the end of line */
570 strcat( string, "\n" );
573 fprintf( stderr, "%s", string );
576 int global_verbosity_level; //Necessary for hb_deep_log
577 /**********************************************************************
579 **********************************************************************
580 * If verbose mode is >= level, print message with timestamp. Messages
581 * longer than 360 characters are stripped ;p
582 *********************************************************************/
583 void hb_deep_log( hb_debug_level_t level, char * log, ... )
585 char string[362]; /* 360 chars + \n + \0 */
590 if( global_verbosity_level < level )
598 now = localtime( &_now );
599 sprintf( string, "[%02d:%02d:%02d] ",
600 now->tm_hour, now->tm_min, now->tm_sec );
602 /* Convert the message to a string */
603 va_start( args, log );
604 vsnprintf( string + 11, 349, log, args );
607 /* Add the end of line */
608 strcat( string, "\n" );
611 fprintf( stderr, "%s", string );
614 /**********************************************************************
616 **********************************************************************
617 * Using whatever output is available display this error.
618 *********************************************************************/
619 void hb_error( char * log, ... )
621 char string[181]; /* 180 chars + \0 */
622 char rep_string[181];
623 static char last_string[181];
624 static int last_error_count = 0;
625 static uint64_t last_series_error_time = 0;
626 static hb_lock_t *mutex = 0;
630 /* Convert the message to a string */
631 va_start( args, log );
632 vsnprintf( string, 180, log, args );
637 mutex = hb_lock_init();
642 time_now = hb_get_date();
644 if( strcmp( string, last_string) == 0 )
647 * The last error and this one are the same, don't log it
648 * just count it instead, unless it was more than one second
652 if( last_series_error_time + ( 1000 * 1 ) > time_now )
660 * A new error, or the same one more than 10sec since the last one
661 * did we have any of the same counted up?
663 if( last_error_count > 0 )
666 * Print out the last error to ensure context for the last
671 error_handler( last_string );
673 hb_log( "%s", last_string );
676 if( last_error_count > 1 )
679 * Only print out the repeat message for more than 2 of the
680 * same, since we just printed out two of them already.
682 snprintf( rep_string, 180, "Last error repeated %d times",
683 last_error_count - 1 );
687 error_handler( rep_string );
689 hb_log( "%s", rep_string );
693 last_error_count = 0;
696 last_series_error_time = time_now;
698 strcpy( last_string, string );
701 * Got the error in a single string, send it off to be dispatched.
705 error_handler( string );
707 hb_log( "%s", string );
713 void hb_register_error_handler( hb_error_handler_t * handler )
715 error_handler = handler;
718 /**********************************************************************
720 **********************************************************************
722 *********************************************************************/
723 hb_title_t * hb_title_init( char * path, int index )
727 t = calloc( sizeof( hb_title_t ), 1 );
730 t->list_audio = hb_list_init();
731 t->list_chapter = hb_list_init();
732 t->list_subtitle = hb_list_init();
733 strcat( t->path, path );
734 // default to decoding mpeg2
736 t->video_codec = WORK_DECMPEG2;
741 /**********************************************************************
743 **********************************************************************
745 *********************************************************************/
746 void hb_title_close( hb_title_t ** _t )
748 hb_title_t * t = *_t;
750 hb_chapter_t * chapter;
751 hb_subtitle_t * subtitle;
753 while( ( audio = hb_list_item( t->list_audio, 0 ) ) )
755 hb_list_rem( t->list_audio, audio );
758 hb_list_close( &t->list_audio );
760 while( ( chapter = hb_list_item( t->list_chapter, 0 ) ) )
762 hb_list_rem( t->list_chapter, chapter );
765 hb_list_close( &t->list_chapter );
767 while( ( subtitle = hb_list_item( t->list_subtitle, 0 ) ) )
769 hb_list_rem( t->list_subtitle, subtitle );
772 hb_list_close( &t->list_subtitle );
776 if( t->metadata->coverart )
778 free( t->metadata->coverart );
787 /**********************************************************************
789 **********************************************************************
791 *********************************************************************/
792 void hb_filter_close( hb_filter_object_t ** _f )
794 hb_filter_object_t * f = *_f;
796 f->close( f->private_data );
807 /**********************************************************************
809 **********************************************************************
811 *********************************************************************/
812 hb_audio_t *hb_audio_copy(const hb_audio_t *src)
814 hb_audio_t *audio = NULL;
818 audio = calloc(1, sizeof(*audio));
819 memcpy(audio, src, sizeof(*audio));
824 /**********************************************************************
826 **********************************************************************
828 *********************************************************************/
829 void hb_audio_config_init(hb_audio_config_t * audiocfg)
831 /* Set read only paramaters to invalid values */
832 audiocfg->in.codec = 0xDEADBEEF;
833 audiocfg->in.bitrate = -1;
834 audiocfg->in.samplerate = -1;
835 audiocfg->in.channel_layout = 0;
836 audiocfg->in.version = 0;
837 audiocfg->in.mode = 0;
838 audiocfg->flags.ac3 = 0;
839 audiocfg->lang.description[0] = 0;
840 audiocfg->lang.simple[0] = 0;
841 audiocfg->lang.iso639_2[0] = 0;
843 /* Initalize some sensable defaults */
844 audiocfg->in.track = audiocfg->out.track = 0;
845 audiocfg->out.codec = HB_ACODEC_FAAC;
846 audiocfg->out.bitrate = 128;
847 audiocfg->out.samplerate = 44100;
848 audiocfg->out.mixdown = HB_AMIXDOWN_DOLBYPLII;
849 audiocfg->out.dynamic_range_compression = 0;
850 audiocfg->out.name = NULL;
853 /**********************************************************************
855 **********************************************************************
857 *********************************************************************/
858 int hb_audio_add(const hb_job_t * job, const hb_audio_config_t * audiocfg)
860 hb_title_t *title = job->title;
863 audio = hb_audio_copy( hb_list_item( title->list_audio, audiocfg->in.track ) );
870 if( (audiocfg->in.bitrate != -1) && (audiocfg->in.codec != 0xDEADBEEF) )
872 /* This most likely means the client didn't call hb_audio_config_init
878 /* Really shouldn't ignore the passed out track, but there is currently no
879 * way to handle duplicates or out-of-order track numbers.
881 audio->config.out.track = hb_list_count(job->list_audio) + 1;
882 audio->config.out.codec = audiocfg->out.codec;
883 if( audiocfg->out.codec == audio->config.in.codec )
885 /* Pass-through, copy from input. */
886 audio->config.out.samplerate = audio->config.in.samplerate;
887 audio->config.out.bitrate = audio->config.in.bitrate;
888 audio->config.out.dynamic_range_compression = 0;
889 audio->config.out.mixdown = 0;
893 /* Non pass-through, use what is given. */
894 audio->config.out.samplerate = audiocfg->out.samplerate;
895 audio->config.out.bitrate = audiocfg->out.bitrate;
896 audio->config.out.dynamic_range_compression = audiocfg->out.dynamic_range_compression;
897 audio->config.out.mixdown = audiocfg->out.mixdown;
900 hb_list_add(job->list_audio, audio);
904 hb_audio_config_t * hb_list_audio_config_item(hb_list_t * list, int i)
906 hb_audio_t *audio = NULL;
908 if( (audio = hb_list_item(list, i)) )
909 return &(audio->config);
914 /**********************************************************************
916 **********************************************************************
918 *********************************************************************/
919 hb_subtitle_t *hb_subtitle_copy(const hb_subtitle_t *src)
921 hb_subtitle_t *subtitle = NULL;
925 subtitle = calloc(1, sizeof(*subtitle));
926 memcpy(subtitle, src, sizeof(*subtitle));
931 /**********************************************************************
933 **********************************************************************
935 *********************************************************************/
936 int hb_subtitle_add(const hb_job_t * job, const hb_subtitle_config_t * subtitlecfg, int track)
938 hb_title_t *title = job->title;
939 hb_subtitle_t *subtitle;
941 subtitle = hb_subtitle_copy( hb_list_item( title->list_subtitle, track ) );
942 if( subtitle == NULL )
947 subtitle->config = *subtitlecfg;
948 hb_list_add(job->list_subtitle, subtitle);
952 int hb_srt_add( const hb_job_t * job,
953 const hb_subtitle_config_t * subtitlecfg,
956 hb_subtitle_t *subtitle;
957 iso639_lang_t *language = NULL;
960 subtitle = calloc( 1, sizeof( *subtitle ) );
962 subtitle->id = (hb_list_count(job->list_subtitle) << 8) | 0xFF;
963 subtitle->format = TEXTSUB;
964 subtitle->source = SRTSUB;
966 language = lang_for_code2( lang );
971 strcpy( subtitle->lang, language->eng_name );
972 strncpy( subtitle->iso639_2, lang, 4 );
974 subtitle->config = *subtitlecfg;
975 subtitle->config.dest = PASSTHRUSUB;
977 hb_list_add(job->list_subtitle, subtitle);
983 char * hb_strdup_printf( char * fmt, ... )
991 str = malloc( size );
997 /* Try to print in the allocated space. */
999 len = vsnprintf( str, size, fmt, ap );
1002 /* If that worked, return the string. */
1003 if ( len > -1 && len < size )
1008 /* Else try again with more space. */
1009 if ( len > -1 ) /* glibc 2.1 */
1010 size = len + 1; /* precisely what is needed */
1011 else /* glibc 2.0 */
1012 size *= 2; /* twice the old size */
1013 tmp = realloc( str, size );