WinGui: Fix another instance of the Caliburn vs Json.net sillyness where objects...
[HandBrake.git] / libhb / scan.c
blob56a256f8b3f5d1f88d1eaf58851a907d611a35fe
1 /* scan.c
3 Copyright (c) 2003-2015 HandBrake Team
4 This file is part of the HandBrake source code
5 Homepage: <http://handbrake.fr/>.
6 It may be used under the terms of the GNU General Public License v2.
7 For full terms see the file COPYING file or visit http://www.gnu.org/licenses/gpl-2.0.html
8 */
10 #include "hb.h"
11 #include "opencl.h"
12 #include "hbffmpeg.h"
14 typedef struct
16 hb_handle_t * h;
17 volatile int * die;
19 char * path;
20 int title_index;
21 hb_title_set_t * title_set;
23 hb_bd_t * bd;
24 hb_dvd_t * dvd;
25 hb_stream_t * stream;
26 hb_batch_t * batch;
28 int preview_count;
29 int store_previews;
31 uint64_t min_title_duration;
32 } hb_scan_t;
34 #define PREVIEW_READ_THRESH (1024 * 1024 * 300)
36 static void ScanFunc( void * );
37 static int DecodePreviews( hb_scan_t *, hb_title_t * title, int flush );
38 static void LookForAudio(hb_scan_t *scan, hb_title_t *title, hb_buffer_t *b);
39 static int AllAudioOK( hb_title_t * title );
40 static void UpdateState1(hb_scan_t *scan, int title);
41 static void UpdateState2(hb_scan_t *scan, int title);
42 static void UpdateState3(hb_scan_t *scan, int preview);
44 static const char *aspect_to_string(hb_rational_t *dar)
46 double aspect = (double)dar->num / dar->den;
47 switch ( (int)(aspect * 9.) )
49 case 9 * 4 / 3: return "4:3";
50 case 9 * 16 / 9: return "16:9";
52 static char arstr[32];
53 if (aspect >= 1)
54 sprintf(arstr, "%.2f:1", aspect);
55 else
56 sprintf(arstr, "1:%.2f", 1. / aspect );
57 return arstr;
60 hb_thread_t * hb_scan_init( hb_handle_t * handle, volatile int * die,
61 const char * path, int title_index,
62 hb_title_set_t * title_set, int preview_count,
63 int store_previews, uint64_t min_duration )
65 hb_scan_t * data = calloc( sizeof( hb_scan_t ), 1 );
67 data->h = handle;
68 data->die = die;
69 data->path = strdup( path );
70 data->title_index = title_index;
71 data->title_set = title_set;
73 data->preview_count = preview_count;
74 data->store_previews = store_previews;
75 data->min_title_duration = min_duration;
77 // Initialize scan state
78 hb_state_t state;
79 #define p state.param.scanning
80 state.state = HB_STATE_SCANNING;
81 p.title_cur = 1;
82 p.title_count = 1;
83 p.preview_cur = 0;
84 p.preview_count = 1;
85 p.progress = 0.0;
86 #undef p
87 hb_set_state(handle, &state);
89 return hb_thread_init( "scan", ScanFunc, data, HB_NORMAL_PRIORITY );
92 static void ScanFunc( void * _data )
94 hb_scan_t * data = (hb_scan_t *) _data;
95 hb_title_t * title;
96 int i;
97 int feature = 0;
99 data->bd = NULL;
100 data->dvd = NULL;
101 data->stream = NULL;
103 /* Try to open the path as a DVD. If it fails, try as a file */
104 if( ( data->bd = hb_bd_init( data->h, data->path ) ) )
106 hb_log( "scan: BD has %d title(s)",
107 hb_bd_title_count( data->bd ) );
108 if( data->title_index )
110 /* Scan this title only */
111 hb_list_add( data->title_set->list_title,
112 hb_bd_title_scan( data->bd,
113 data->title_index, 0 ) );
115 else
117 /* Scan all titles */
118 for( i = 0; i < hb_bd_title_count( data->bd ); i++ )
120 UpdateState1(data, i + 1);
121 hb_list_add( data->title_set->list_title,
122 hb_bd_title_scan( data->bd,
123 i + 1, data->min_title_duration ) );
125 feature = hb_bd_main_feature( data->bd,
126 data->title_set->list_title );
129 else if( ( data->dvd = hb_dvd_init( data->h, data->path ) ) )
131 hb_log( "scan: DVD has %d title(s)",
132 hb_dvd_title_count( data->dvd ) );
133 if( data->title_index )
135 /* Scan this title only */
136 hb_list_add( data->title_set->list_title,
137 hb_dvd_title_scan( data->dvd,
138 data->title_index, 0 ) );
140 else
142 /* Scan all titles */
143 for( i = 0; i < hb_dvd_title_count( data->dvd ); i++ )
145 UpdateState1(data, i + 1);
146 hb_list_add( data->title_set->list_title,
147 hb_dvd_title_scan( data->dvd,
148 i + 1, data->min_title_duration ) );
150 feature = hb_dvd_main_feature( data->dvd,
151 data->title_set->list_title );
154 else if ( ( data->batch = hb_batch_init( data->h, data->path ) ) )
156 if( data->title_index )
158 /* Scan this title only */
159 title = hb_batch_title_scan(data->batch, data->title_index);
160 if ( title )
162 hb_list_add( data->title_set->list_title, title );
165 else
167 /* Scan all titles */
168 for( i = 0; i < hb_batch_title_count( data->batch ); i++ )
170 hb_title_t * title;
172 UpdateState1(data, i + 1);
173 title = hb_batch_title_scan(data->batch, i + 1);
174 if ( title != NULL )
176 hb_list_add( data->title_set->list_title, title );
181 else
183 // Title index 0 is not a valid title number and means scan all titles.
184 // So set title index to 1 in this scenario.
186 // Otherwise, set title index in new title to the index that was
187 // requested. This preserves the original index created in batch
188 // mode.
189 if (data->title_index == 0)
190 data->title_index = 1;
191 hb_title_t * title = hb_title_init( data->path, data->title_index );
192 data->stream = hb_stream_open(data->h, data->path, title, 1);
193 if (data->stream != NULL)
195 title = hb_stream_title_scan( data->stream, title );
196 if ( title )
197 hb_list_add( data->title_set->list_title, title );
199 else
201 hb_title_close( &title );
202 hb_log( "scan: unrecognized file type" );
203 return;
207 for( i = 0; i < hb_list_count( data->title_set->list_title ); )
209 int j, npreviews;
210 hb_audio_t * audio;
212 if ( *data->die )
214 goto finish;
216 title = hb_list_item( data->title_set->list_title, i );
218 UpdateState2(data, i + 1);
220 /* Decode previews */
221 /* this will also detect more AC3 / DTS information */
222 npreviews = DecodePreviews( data, title, 1 );
223 if (npreviews < 2)
225 npreviews = DecodePreviews( data, title, 0 );
227 if (npreviews == 0)
229 /* TODO: free things */
230 hb_list_rem( data->title_set->list_title, title );
231 for( j = 0; j < hb_list_count( title->list_audio ); j++)
233 audio = hb_list_item( title->list_audio, j );
234 if ( audio->priv.scan_cache )
236 hb_fifo_flush( audio->priv.scan_cache );
237 hb_fifo_close( &audio->priv.scan_cache );
240 hb_title_close( &title );
241 continue;
244 /* Make sure we found audio rates and bitrates */
245 for( j = 0; j < hb_list_count( title->list_audio ); )
247 audio = hb_list_item( title->list_audio, j );
248 if ( audio->priv.scan_cache )
250 hb_fifo_flush( audio->priv.scan_cache );
251 hb_fifo_close( &audio->priv.scan_cache );
253 if( !audio->config.in.bitrate )
255 hb_log( "scan: removing audio 0x%x because no bitrate found",
256 audio->id );
257 hb_list_rem( title->list_audio, audio );
258 free( audio );
259 continue;
261 j++;
264 if ( data->dvd || data->bd )
266 // The subtitle width and height needs to be set to the
267 // title widht and height for DVDs. title width and
268 // height don't get set until we decode previews, so
269 // we can't set subtitle width/height till we get here.
270 for( j = 0; j < hb_list_count( title->list_subtitle ); j++ )
272 hb_subtitle_t *subtitle = hb_list_item( title->list_subtitle, j );
273 if ( subtitle->source == VOBSUB || subtitle->source == PGSSUB )
275 subtitle->width = title->geometry.width;
276 subtitle->height = title->geometry.height;
280 i++;
283 data->title_set->feature = feature;
285 /* Mark title scan complete and init jobs */
286 for( i = 0; i < hb_list_count( data->title_set->list_title ); i++ )
288 title = hb_list_item( data->title_set->list_title, i );
289 title->flags |= HBTF_SCAN_COMPLETE;
291 if (hb_list_count(data->title_set->list_title) > 0)
293 strncpy(data->title_set->path, data->path, 1024);
294 data->title_set->path[1023] = 0;
296 else
298 data->title_set->path[0] = 0;
301 finish:
303 if( data->bd )
305 hb_bd_close( &data->bd );
307 if( data->dvd )
309 hb_dvd_close( &data->dvd );
311 if (data->stream)
313 hb_stream_close(&data->stream);
315 if( data->batch )
317 hb_batch_close( &data->batch );
319 free( data->path );
320 free( data );
321 _data = NULL;
322 hb_buffer_pool_free();
325 // -----------------------------------------------
326 // stuff related to cropping
328 #define DARK 32
330 static inline int absdiff( int x, int y )
332 return x < y ? y - x : x - y;
335 static inline int clampBlack( int x )
337 // luma 'black' is 16 and anything less should be clamped at 16
338 return x < 16 ? 16 : x;
341 static int row_all_dark( hb_buffer_t* buf, int row )
343 int width = buf->plane[0].width;
344 int stride = buf->plane[0].stride;
345 uint8_t *luma = buf->plane[0].data + stride * row;
347 // compute the average luma value of the row
348 int i, avg = 0;
349 for ( i = 0; i < width; ++i )
351 avg += clampBlack( luma[i] );
353 avg /= width;
354 if ( avg >= DARK )
355 return 0;
357 // since we're trying to detect smooth borders, only take the row if
358 // all pixels are within +-16 of the average (this range is fairly coarse
359 // but there's a lot of quantization noise for luma values near black
360 // so anything less will fail to crop because of the noise).
361 for ( i = 0; i < width; ++i )
363 if ( absdiff( avg, clampBlack( luma[i] ) ) > 16 )
364 return 0;
366 return 1;
369 static int column_all_dark( hb_buffer_t* buf, int top, int bottom, int col )
371 int stride = buf->plane[0].stride;
372 int height = buf->plane[0].height - top - bottom;
373 uint8_t *luma = buf->plane[0].data + stride * top + col;
375 // compute the average value of the column
376 int i = height, avg = 0, row = 0;
377 for ( ; --i >= 0; row += stride )
379 avg += clampBlack( luma[row] );
381 avg /= height;
382 if ( avg >= DARK )
383 return 0;
385 // since we're trying to detect smooth borders, only take the column if
386 // all pixels are within +-16 of the average.
387 i = height, row = 0;
388 for ( ; --i >= 0; row += stride )
390 if ( absdiff( avg, clampBlack( luma[row] ) ) > 16 )
391 return 0;
393 return 1;
395 #undef DARK
397 typedef struct {
398 int n;
399 int *t;
400 int *b;
401 int *l;
402 int *r;
403 } crop_record_t;
405 static crop_record_t * crop_record_init( int max_previews )
407 crop_record_t *crops = calloc( 1, sizeof(*crops) );
409 crops->t = calloc( max_previews, sizeof(int) );
410 crops->b = calloc( max_previews, sizeof(int) );
411 crops->l = calloc( max_previews, sizeof(int) );
412 crops->r = calloc( max_previews, sizeof(int) );
414 return crops;
417 static void crop_record_free( crop_record_t *crops )
419 free( crops->t );
420 free( crops->b );
421 free( crops->l );
422 free( crops->r );
423 free( crops );
426 static void record_crop( crop_record_t *crops, int t, int b, int l, int r )
428 crops->t[crops->n] = t;
429 crops->b[crops->n] = b;
430 crops->l[crops->n] = l;
431 crops->r[crops->n] = r;
432 ++crops->n;
435 static int compare_int( const void *a, const void *b )
437 return *(const int *)a - *(const int *)b;
440 static void sort_crops( crop_record_t *crops )
442 qsort( crops->t, crops->n, sizeof(crops->t[0]), compare_int );
443 qsort( crops->b, crops->n, sizeof(crops->t[0]), compare_int );
444 qsort( crops->l, crops->n, sizeof(crops->t[0]), compare_int );
445 qsort( crops->r, crops->n, sizeof(crops->t[0]), compare_int );
448 // -----------------------------------------------
449 // stuff related to title width/height/aspect info
451 typedef struct {
452 int count; /* number of times we've seen this info entry */
453 hb_work_info_t info; /* copy of info entry */
454 } info_list_t;
456 static void remember_info( info_list_t *info_list, hb_work_info_t *info )
458 for ( ; info_list->count; ++info_list )
460 if ( memcmp( &info_list->info, info, sizeof(*info) ) == 0 )
462 // we found a match - bump its count
463 ++info_list->count;
464 return;
467 // no match found - add new entry to list (info_list points to
468 // the first free slot). NB - we assume that info_list was allocated
469 // so that it's big enough even if there are no dups. I.e., 10 slots
470 // allocated if there are 10 previews.
471 info_list->count = 1;
472 info_list->info = *info;
475 static void most_common_info( info_list_t *info_list, hb_work_info_t *info )
477 int i, biggest = 0;
478 for ( i = 1; info_list[i].count; ++i )
480 if ( info_list[i].count > info_list[biggest].count )
481 biggest = i;
483 *info = info_list[biggest].info;
486 static int has_resolution_change( info_list_t *info_list )
488 int w, h, i;
490 if( !info_list[0].count )
491 return 0;
492 w = info_list[0].info.geometry.width;
493 h = info_list[0].info.geometry.height;
494 for ( i = 1; info_list[i].count; ++i )
496 if (w != info_list[i].info.geometry.width ||
497 h != info_list[i].info.geometry.height)
498 return 1;
500 return 0;
503 static int is_close_to( int val, int target, int thresh )
505 int diff = val - target;
506 diff = diff < 0 ? -diff : diff;
507 return diff < thresh;
510 /***********************************************************************
511 * DecodePreviews
512 ***********************************************************************
513 * Decode 10 pictures for the given title.
514 * It assumes that data->reader and data->vts have successfully been
515 * DVDOpen()ed and ifoOpen()ed.
516 **********************************************************************/
517 static int DecodePreviews( hb_scan_t * data, hb_title_t * title, int flush )
519 int i, npreviews = 0, abort = 0;
520 hb_buffer_t * buf, * buf_es;
521 hb_list_t * list_es;
522 int progressive_count = 0;
523 int pulldown_count = 0;
524 int doubled_frame_count = 0;
525 int interlaced_preview_count = 0;
526 int frame_wait = 0;
527 int cc_wait = 10;
528 int frames;
529 hb_stream_t * stream = NULL;
530 info_list_t * info_list = calloc( data->preview_count+1, sizeof(*info_list) );
531 crop_record_t *crops = crop_record_init( data->preview_count );
533 list_es = hb_list_init();
535 if( data->batch )
537 hb_log( "scan: decoding previews for title %d (%s)", title->index, title->path );
539 else
541 hb_log( "scan: decoding previews for title %d", title->index );
544 if (data->bd)
546 hb_bd_start( data->bd, title );
547 hb_log( "scan: title angle(s) %d", title->angle_count );
549 else if (data->dvd)
551 hb_dvd_start( data->dvd, title, 1 );
552 title->angle_count = hb_dvd_angle_count( data->dvd );
553 hb_log( "scan: title angle(s) %d", title->angle_count );
555 else if (data->batch)
557 stream = hb_stream_open(data->h, title->path, title, 0);
559 else if (data->stream)
561 stream = hb_stream_open(data->h, data->path, title, 0);
564 if (title->video_codec == WORK_NONE)
566 hb_error("No video decoder set!");
567 return 0;
569 hb_work_object_t *vid_decoder = hb_get_work(data->h, title->video_codec);
570 vid_decoder->codec_param = title->video_codec_param;
571 vid_decoder->title = title;
572 vid_decoder->init( vid_decoder, NULL );
574 for( i = 0; i < data->preview_count; i++ )
576 int j;
578 UpdateState3(data, i + 1);
580 if ( *data->die )
582 free( info_list );
583 crop_record_free( crops );
584 return 0;
586 if (data->bd)
588 if( !hb_bd_seek( data->bd, (float) ( i + 1 ) / ( data->preview_count + 1.0 ) ) )
590 continue;
593 if (data->dvd)
595 if( !hb_dvd_seek( data->dvd, (float) ( i + 1 ) / ( data->preview_count + 1.0 ) ) )
597 continue;
600 else if (stream)
602 /* we start reading streams at zero rather than 1/11 because
603 * short streams may have only one sequence header in the entire
604 * file and we need it to decode any previews.
606 * Also, seeking to position 0 loses the palette of avi files
607 * so skip initial seek */
608 if (i != 0)
610 if (!hb_stream_seek(stream,
611 (float)i / (data->preview_count + 1.0)))
613 continue;
616 else
618 hb_stream_set_need_keyframe(stream, 1);
622 hb_deep_log( 2, "scan: preview %d", i + 1 );
624 if (flush && vid_decoder->flush)
625 vid_decoder->flush( vid_decoder );
626 if (title->flags & HBTF_NO_IDR)
628 if (!flush)
630 // If we are doing the first previews decode attempt,
631 // set this threshold high so that we get the best
632 // quality frames possible.
633 frame_wait = 100;
635 else
637 // If we failed to get enough valid frames in the first
638 // previews decode attempt, lower the threshold to improve
639 // our chances of getting something to work with.
640 frame_wait = 10;
643 else
645 // For certain mpeg-2 streams, libav is delivering a
646 // dummy first frame that is all black. So always skip
647 // one frame
648 frame_wait = 1;
650 frames = 0;
652 hb_buffer_t * vid_buf = NULL;
654 int total_read = 0, packets = 0;
655 while (total_read < PREVIEW_READ_THRESH ||
656 (!AllAudioOK(title) && packets < 10000))
658 if (data->bd)
660 if( (buf = hb_bd_read( data->bd )) == NULL )
662 if ( vid_buf )
664 break;
666 hb_log( "Warning: Could not read data for preview %d, skipped", i + 1 );
667 abort = 1;
668 goto skip_preview;
671 else if (data->dvd)
673 if( (buf = hb_dvd_read( data->dvd )) == NULL )
675 if ( vid_buf )
677 break;
679 hb_log( "Warning: Could not read data for preview %d, skipped", i + 1 );
680 abort = 1;
681 goto skip_preview;
684 else if (stream)
686 if ( (buf = hb_stream_read(stream)) == NULL )
688 if ( vid_buf )
690 break;
692 hb_log( "Warning: Could not read data for preview %d, skipped", i + 1 );
693 abort = 1;
694 goto skip_preview;
697 else
699 // Silence compiler warning
700 buf = NULL;
701 hb_error( "Error: This can't happen!" );
702 abort = 1;
703 goto skip_preview;
706 if (buf->size <= 0)
708 hb_log( "Warning: Could not read data for preview %d, skipped", i + 1 );
709 abort = 1;
710 goto skip_preview;
712 total_read += buf->size;
713 packets++;
715 (hb_demux[title->demuxer])(buf, list_es, 0 );
717 while( ( buf_es = hb_list_item( list_es, 0 ) ) )
719 hb_list_rem( list_es, buf_es );
720 if( buf_es->s.id == title->video_id && vid_buf == NULL )
722 vid_decoder->work( vid_decoder, &buf_es, &vid_buf );
723 // There are 2 conditions we decode additional
724 // video frames for during scan.
725 // 1. We did not detect IDR frames, so the initial video
726 // frames may be corrupt. We docode extra frames to
727 // increase the probability of a complete preview frame
728 // 2. Some frames do not contain CC data, even though
729 // CCs are present in the stream. So we need to decode
730 // additional frames to find the CCs.
731 if (vid_buf != NULL && (frame_wait || cc_wait))
733 if (frames > 0 && vid_buf->s.frametype == HB_FRAME_I)
734 frame_wait = 0;
735 if (frame_wait || cc_wait)
737 hb_buffer_close(&vid_buf);
738 if (frame_wait) frame_wait--;
739 if (cc_wait) cc_wait--;
741 frames++;
744 else if( ! AllAudioOK( title ) )
746 LookForAudio( data, title, buf_es );
747 buf_es = NULL;
749 if ( buf_es )
750 hb_buffer_close( &buf_es );
753 if( vid_buf && AllAudioOK( title ) )
754 break;
757 if( ! vid_buf )
759 hb_log( "scan: could not get a decoded picture" );
760 continue;
763 /* Get size and rate infos */
765 hb_work_info_t vid_info;
766 if( !vid_decoder->info( vid_decoder, &vid_info ) )
769 * Could not fill vid_info, don't continue and try to use vid_info
770 * in this case.
772 if (vid_buf)
774 hb_buffer_close( &vid_buf );
776 hb_log( "scan: could not get a video information" );
777 continue;
780 remember_info( info_list, &vid_info );
782 if( is_close_to( vid_info.rate.den, 900900, 100 ) &&
783 ( vid_buf->s.flags & PIC_FLAG_REPEAT_FIRST_FIELD ) )
785 /* Potentially soft telecine material */
786 pulldown_count++;
789 if( vid_buf->s.flags & PIC_FLAG_REPEAT_FRAME )
791 // AVCHD-Lite specifies that all streams are
792 // 50 or 60 fps. To produce 25 or 30 fps, camera
793 // makers are repeating all frames.
794 doubled_frame_count++;
797 if( is_close_to( vid_info.rate.den, 1126125, 100 ) )
799 // Frame FPS is 23.976 (meaning it's progressive), so start keeping
800 // track of how many are reporting at that speed. When enough
801 // show up that way, we want to make that the overall title FPS.
802 progressive_count++;
805 while( ( buf_es = hb_list_item( list_es, 0 ) ) )
807 hb_list_rem( list_es, buf_es );
808 hb_buffer_close( &buf_es );
811 /* Check preview for interlacing artifacts */
812 if( hb_detect_comb( vid_buf, 10, 30, 9, 10, 30, 9 ) )
814 hb_deep_log( 2, "Interlacing detected in preview frame %i", i+1);
815 interlaced_preview_count++;
818 if( data->store_previews )
820 hb_save_preview( data->h, title->index, i, vid_buf );
823 /* Detect black borders */
825 int top, bottom, left, right;
826 int h4 = vid_info.geometry.height / 4, w4 = vid_info.geometry.width / 4;
828 // When widescreen content is matted to 16:9 or 4:3 there's sometimes
829 // a thin border on the outer edge of the matte. On TV content it can be
830 // "line 21" VBI data that's normally hidden in the overscan. For HD
831 // content it can just be a diagnostic added in post production so that
832 // the frame borders are visible. We try to ignore these borders so
833 // we can crop the matte. The border width depends on the resolution
834 // (12 pixels on 1080i looks visually the same as 4 pixels on 480i)
835 // so we allow the border to be up to 1% of the frame height.
836 const int border = vid_info.geometry.height / 100;
838 for ( top = border; top < h4; ++top )
840 if ( ! row_all_dark( vid_buf, top ) )
841 break;
843 if ( top <= border )
845 // we never made it past the border region - see if the rows we
846 // didn't check are dark or if we shouldn't crop at all.
847 for ( top = 0; top < border; ++top )
849 if ( ! row_all_dark( vid_buf, top ) )
850 break;
852 if ( top >= border )
854 top = 0;
857 for ( bottom = border; bottom < h4; ++bottom )
859 if ( ! row_all_dark( vid_buf, vid_info.geometry.height - 1 - bottom ) )
860 break;
862 if ( bottom <= border )
864 for ( bottom = 0; bottom < border; ++bottom )
866 if ( ! row_all_dark( vid_buf, vid_info.geometry.height - 1 - bottom ) )
867 break;
869 if ( bottom >= border )
871 bottom = 0;
874 for ( left = 0; left < w4; ++left )
876 if ( ! column_all_dark( vid_buf, top, bottom, left ) )
877 break;
879 for ( right = 0; right < w4; ++right )
881 if ( ! column_all_dark( vid_buf, top, bottom, vid_info.geometry.width - 1 - right ) )
882 break;
885 // only record the result if all the crops are less than a quarter of
886 // the frame otherwise we can get fooled by frames with a lot of black
887 // like titles, credits & fade-thru-black transitions.
888 if ( top < h4 && bottom < h4 && left < w4 && right < w4 )
890 record_crop( crops, top, bottom, left, right );
892 ++npreviews;
894 skip_preview:
895 /* Make sure we found audio rates and bitrates */
896 for( j = 0; j < hb_list_count( title->list_audio ); j++ )
898 hb_audio_t * audio = hb_list_item( title->list_audio, j );
899 if ( audio->priv.scan_cache )
901 hb_fifo_flush( audio->priv.scan_cache );
904 if (vid_buf)
906 hb_buffer_close( &vid_buf );
908 if (abort)
910 break;
913 UpdateState3(data, i);
915 vid_decoder->close( vid_decoder );
916 free( vid_decoder );
918 if (stream != NULL)
920 hb_stream_close(&stream);
923 if ( npreviews )
925 // use the most common frame info for our final title dimensions
926 hb_work_info_t vid_info;
927 most_common_info( info_list, &vid_info );
929 title->has_resolution_change = has_resolution_change( info_list );
930 if ( title->video_codec_name == NULL )
932 title->video_codec_name = strdup( vid_info.name );
934 title->geometry.width = vid_info.geometry.width;
935 title->geometry.height = vid_info.geometry.height;
936 if (vid_info.rate.num && vid_info.rate.den)
938 // if the frame rate is very close to one of our "common"
939 // framerates, assume it actually is said frame rate;
940 // e.g. some 24000/1001 sources may have a rate.den of 1126124
941 // instead of 1126125
942 const hb_rate_t *video_framerate = NULL;
943 while ((video_framerate = hb_video_framerate_get_next(video_framerate)) != NULL)
945 if (is_close_to(vid_info.rate.den, video_framerate->rate, 100))
947 vid_info.rate.den = video_framerate->rate;
948 break;
951 title->vrate = vid_info.rate;
952 if( vid_info.rate.den == 900900 )
954 if( npreviews >= 4 && pulldown_count >= npreviews / 4 )
956 title->vrate.den = 1126125;
957 hb_deep_log( 2, "Pulldown detected, setting fps to 23.976" );
959 if( npreviews >= 2 && progressive_count >= npreviews / 2 )
961 // We've already deduced that the frame rate is 23.976,
962 // so set it back again.
963 title->vrate.den = 1126125;
964 hb_deep_log( 2, "Title's mostly NTSC Film, setting fps to 23.976" );
967 if( npreviews >= 2 && doubled_frame_count >= 3 * npreviews / 4 )
969 // We've detected that a significant number of the frames
970 // have been doubled in duration by repeat flags.
971 title->vrate.den = 2 * vid_info.rate.den;
972 hb_deep_log(2, "Repeat frames detected, setting fps to %.3f",
973 (float)title->vrate.num / title->vrate.den );
976 title->video_bitrate = vid_info.bitrate;
978 if( vid_info.geometry.par.num && vid_info.geometry.par.den )
980 title->geometry.par = vid_info.geometry.par;
982 title->color_prim = vid_info.color_prim;
983 title->color_transfer = vid_info.color_transfer;
984 title->color_matrix = vid_info.color_matrix;
986 title->video_decode_support = vid_info.video_decode_support;
988 // TODO: check video dimensions
989 title->opencl_support = !!hb_opencl_available();
991 // compute the aspect ratio based on the storage dimensions and PAR.
992 hb_reduce(&title->dar.num, &title->dar.den,
993 title->geometry.par.num * title->geometry.width,
994 title->geometry.height * title->geometry.par.den);
996 // For unknown reasons some French PAL DVDs put the original
997 // content's aspect ratio into the mpeg PAR even though it's
998 // the wrong PAR for the DVD. Apparently they rely on the fact
999 // that DVD players ignore the content PAR and just use the
1000 // aspect ratio from the DVD metadata. So, if the aspect computed
1001 // from the PAR is different from the container's aspect we use
1002 // the container's aspect & recompute the PAR from it.
1003 if (data->dvd &&
1004 (title->dar.num != title->container_dar.num ||
1005 title->dar.den != title->container_dar.den))
1007 hb_log("scan: content PAR gives wrong aspect %d:%d; "
1008 "using container aspect %d:%d",
1009 title->dar.num, title->dar.den,
1010 title->container_dar.num, title->container_dar.den);
1011 title->dar = title->container_dar;
1012 hb_reduce(&title->geometry.par.num, &title->geometry.par.den,
1013 title->geometry.height * title->dar.num,
1014 title->geometry.width * title->dar.den);
1017 // don't try to crop unless we got at least 3 previews
1018 if ( crops->n > 2 )
1020 sort_crops( crops );
1021 // The next line selects median cropping - at least
1022 // 50% of the frames will have their borders removed.
1023 // Other possible choices are loose cropping (i = 0) where
1024 // no non-black pixels will be cropped from any frame and a
1025 // tight cropping (i = crops->n - (crops->n >> 2)) where at
1026 // least 75% of the frames will have their borders removed.
1027 i = crops->n >> 1;
1028 title->crop[0] = EVEN( crops->t[i] );
1029 title->crop[1] = EVEN( crops->b[i] );
1030 title->crop[2] = EVEN( crops->l[i] );
1031 title->crop[3] = EVEN( crops->r[i] );
1034 hb_log( "scan: %d previews, %dx%d, %.3f fps, autocrop = %d/%d/%d/%d, "
1035 "aspect %s, PAR %d:%d",
1036 npreviews, title->geometry.width, title->geometry.height,
1037 (float)title->vrate.num / title->vrate.den,
1038 title->crop[0], title->crop[1], title->crop[2], title->crop[3],
1039 aspect_to_string(&title->dar),
1040 title->geometry.par.num, title->geometry.par.den);
1042 if (title->video_decode_support != HB_DECODE_SUPPORT_SW)
1044 hb_log("scan: supported video decoders:%s%s%s",
1045 !(title->video_decode_support & HB_DECODE_SUPPORT_SW) ? "" : " avcodec",
1046 !(title->video_decode_support & HB_DECODE_SUPPORT_QSV) ? "" : " qsv",
1047 !(title->video_decode_support & HB_DECODE_SUPPORT_DXVA2) ? "" : " dxva2");
1050 if( interlaced_preview_count >= ( npreviews / 2 ) )
1052 hb_log("Title is likely interlaced or telecined (%i out of %i previews). You should do something about that.",
1053 interlaced_preview_count, npreviews);
1054 title->detected_interlacing = 1;
1056 else
1058 title->detected_interlacing = 0;
1061 crop_record_free( crops );
1062 free( info_list );
1064 while( ( buf_es = hb_list_item( list_es, 0 ) ) )
1066 hb_list_rem( list_es, buf_es );
1067 hb_buffer_close( &buf_es );
1069 hb_list_close( &list_es );
1070 if (data->bd)
1071 hb_bd_stop( data->bd );
1072 if (data->dvd)
1073 hb_dvd_stop( data->dvd );
1075 return npreviews;
1079 * This routine is called for every frame from a non-video elementary stream.
1080 * These are a mix of audio & subtitle streams, some of which we want & some
1081 * we're ignoring. This routine checks the frame against all our audio streams
1082 * to see if it's one we want and haven't identified yet. If yes, it passes the
1083 * frame to a codec-specific id routine which is responsible for filling in
1084 * the sample rate, bit rate, channels & other audio parameters.
1086 * Since a sample rate is essential for further audio processing, any audio
1087 * stream which isn't successfully id'd by is deleted at the end of the scan.
1088 * This is necessary to avoid ambiguities where things that might be audio
1089 * aren't (e.g., some European DVD Teletext streams use the same IDs as US ATSC
1090 * AC-3 audio).
1092 static void LookForAudio(hb_scan_t *scan, hb_title_t * title, hb_buffer_t * b)
1094 int i;
1096 hb_audio_t * audio = NULL;
1097 for( i = 0; i < hb_list_count( title->list_audio ); i++ )
1099 audio = hb_list_item( title->list_audio, i );
1100 /* check if this elementary stream is one we want */
1101 if ( audio->id == b->s.id )
1103 break;
1105 else
1107 audio = NULL;
1110 if( !audio || audio->config.in.bitrate != 0 )
1112 /* not found or already done */
1113 hb_buffer_close( &b );
1114 return;
1117 if ( audio->priv.scan_cache == NULL )
1118 audio->priv.scan_cache = hb_fifo_init( 16, 16 );
1120 if ( hb_fifo_size_bytes( audio->priv.scan_cache ) >= 16384 )
1122 hb_buffer_t * tmp;
1123 tmp = hb_fifo_get( audio->priv.scan_cache );
1124 hb_buffer_close( &tmp );
1126 hb_fifo_push( audio->priv.scan_cache, b );
1128 hb_work_object_t *w = hb_codec_decoder(scan->h, audio->config.in.codec);
1130 if ( w == NULL || w->bsinfo == NULL )
1132 hb_log( "Internal error in scan: unhandled audio type %d for id 0x%x",
1133 audio->config.in.codec, audio->id );
1134 goto drop_audio;
1137 hb_work_info_t info;
1138 w->title = title;
1139 w->audio = audio;
1140 w->codec_param = audio->config.in.codec_param;
1141 b = hb_fifo_see( audio->priv.scan_cache );
1142 int ret = w->bsinfo( w, b, &info );
1143 if ( ret < 0 )
1145 hb_log( "no info on audio type %d/0x%x for id 0x%x",
1146 audio->config.in.codec, audio->config.in.codec_param,
1147 audio->id );
1148 goto drop_audio;
1150 if ( !info.bitrate )
1152 /* didn't find any info */
1153 free( w );
1154 return;
1156 hb_fifo_flush( audio->priv.scan_cache );
1157 hb_fifo_close( &audio->priv.scan_cache );
1159 audio->config.in.samplerate = info.rate.num;
1160 audio->config.in.sample_bit_depth = info.sample_bit_depth;
1161 audio->config.in.samples_per_frame = info.samples_per_frame;
1162 audio->config.in.bitrate = info.bitrate;
1163 audio->config.in.matrix_encoding = info.matrix_encoding;
1164 audio->config.in.channel_layout = info.channel_layout;
1165 audio->config.in.channel_map = info.channel_map;
1166 audio->config.in.version = info.version;
1167 audio->config.in.flags = info.flags;
1168 audio->config.in.mode = info.mode;
1170 // now that we have all the info, set the audio description
1171 const char *codec_name = NULL;
1172 if (audio->config.in.codec & HB_ACODEC_FF_MASK)
1174 AVCodec *codec = avcodec_find_decoder(audio->config.in.codec_param);
1175 if (codec != NULL)
1177 if (info.profile != FF_PROFILE_UNKNOWN)
1179 codec_name = av_get_profile_name(codec, info.profile);
1181 if (codec_name == NULL)
1183 // use our own capitalization for the most common codecs
1184 switch (audio->config.in.codec_param)
1186 case AV_CODEC_ID_AAC:
1187 codec_name = "AAC";
1188 break;
1189 case AV_CODEC_ID_AC3:
1190 codec_name = "AC3";
1191 break;
1192 case AV_CODEC_ID_EAC3:
1193 codec_name = "E-AC3";
1194 break;
1195 case AV_CODEC_ID_TRUEHD:
1196 codec_name = "TrueHD";
1197 break;
1198 case AV_CODEC_ID_DTS:
1199 codec_name = audio->config.in.codec == HB_ACODEC_DCA_HD ? "DTS-HD" : "DTS";
1200 break;
1201 case AV_CODEC_ID_FLAC:
1202 codec_name = "FLAC";
1203 break;
1204 case AV_CODEC_ID_MP2:
1205 codec_name = "MPEG";
1206 break;
1207 case AV_CODEC_ID_MP3:
1208 codec_name = "MP3";
1209 break;
1210 case AV_CODEC_ID_PCM_BLURAY:
1211 codec_name = "BD LPCM";
1212 break;
1213 case AV_CODEC_ID_OPUS:
1214 codec_name = "Opus";
1215 break;
1216 case AV_CODEC_ID_VORBIS:
1217 codec_name = "Vorbis";
1218 break;
1219 default:
1220 codec_name = codec->name;
1221 break;
1225 else
1227 switch (audio->config.in.codec)
1229 case HB_ACODEC_AC3:
1230 codec_name = "AC3";
1231 break;
1232 case HB_ACODEC_FFEAC3:
1233 codec_name = "E-AC3";
1234 break;
1235 case HB_ACODEC_FFTRUEHD:
1236 codec_name = "TrueHD";
1237 break;
1238 case HB_ACODEC_DCA:
1239 codec_name = "DTS";
1240 break;
1241 case HB_ACODEC_DCA_HD:
1242 codec_name = "DTS-HD";
1243 break;
1244 case HB_ACODEC_FFAAC:
1245 codec_name = "AAC";
1246 break;
1247 case HB_ACODEC_FFFLAC:
1248 codec_name = "FLAC";
1249 break;
1250 case HB_ACODEC_MP3:
1251 codec_name = "MP3";
1252 break;
1253 default:
1254 codec_name = "Unknown (libav)";
1255 break;
1259 else
1261 switch (audio->config.in.codec)
1263 case HB_ACODEC_AC3:
1264 codec_name = "AC3";
1265 break;
1266 case HB_ACODEC_LPCM:
1267 codec_name = "LPCM";
1268 break;
1269 default:
1270 codec_name = "Unknown";
1271 break;
1274 sprintf(audio->config.lang.description, "%s (%s)",
1275 audio->config.lang.simple, codec_name);
1277 switch (audio->config.lang.type)
1279 case 2:
1280 strcat(audio->config.lang.description, " (Visually Impaired)");
1281 break;
1282 case 3:
1283 strcat(audio->config.lang.description, " (Director's Commentary 1)");
1284 break;
1285 case 4:
1286 strcat(audio->config.lang.description, " (Director's Commentary 2)");
1287 break;
1288 default:
1289 break;
1292 if (audio->config.in.channel_layout)
1294 int lfes = (!!(audio->config.in.channel_layout & AV_CH_LOW_FREQUENCY) +
1295 !!(audio->config.in.channel_layout & AV_CH_LOW_FREQUENCY_2));
1296 int channels = av_get_channel_layout_nb_channels(audio->config.in.channel_layout);
1297 char *desc = audio->config.lang.description +
1298 strlen(audio->config.lang.description);
1299 sprintf(desc, " (%d.%d ch)", channels - lfes, lfes);
1301 // describe the matrix encoding mode, if any
1302 switch (audio->config.in.matrix_encoding)
1304 case AV_MATRIX_ENCODING_DOLBY:
1305 if (audio->config.in.codec == HB_ACODEC_AC3 ||
1306 audio->config.in.codec_param == AV_CODEC_ID_AC3 ||
1307 audio->config.in.codec_param == AV_CODEC_ID_EAC3 ||
1308 audio->config.in.codec_param == AV_CODEC_ID_TRUEHD)
1310 strcat(audio->config.lang.description, " (Dolby Surround)");
1311 break;
1313 strcat(audio->config.lang.description, " (Lt/Rt)");
1314 break;
1315 case AV_MATRIX_ENCODING_DPLII:
1316 strcat(audio->config.lang.description, " (Dolby Pro Logic II)");
1317 break;
1318 case AV_MATRIX_ENCODING_DPLIIX:
1319 strcat(audio->config.lang.description, " (Dolby Pro Logic IIx)");
1320 break;
1321 case AV_MATRIX_ENCODING_DPLIIZ:
1322 strcat(audio->config.lang.description, " (Dolby Pro Logic IIz)");
1323 break;
1324 case AV_MATRIX_ENCODING_DOLBYEX:
1325 strcat(audio->config.lang.description, " (Dolby Digital EX)");
1326 break;
1327 case AV_MATRIX_ENCODING_DOLBYHEADPHONE:
1328 strcat(audio->config.lang.description, " (Dolby Headphone)");
1329 break;
1330 default:
1331 break;
1335 hb_log( "scan: audio 0x%x: %s, rate=%dHz, bitrate=%d %s", audio->id,
1336 info.name, audio->config.in.samplerate, audio->config.in.bitrate,
1337 audio->config.lang.description );
1339 free( w );
1340 return;
1342 // We get here if there's no hope of finding info on an audio bitstream,
1343 // either because we don't have a decoder (or a decoder with a bitstream
1344 // info proc) or because the decoder's info proc said that the stream
1345 // wasn't something it could handle. Delete the item from the title's
1346 // audio list so we won't keep reading packets while trying to get its
1347 // bitstream info.
1348 drop_audio:
1349 if ( w )
1350 free( w );
1352 hb_fifo_flush( audio->priv.scan_cache );
1353 hb_fifo_close( &audio->priv.scan_cache );
1354 hb_list_rem( title->list_audio, audio );
1355 return;
1359 * This routine checks to see if we've ID'd all the audio streams associated
1360 * with a title. It returns 0 if there are more to ID & 1 if all are done.
1362 static int AllAudioOK( hb_title_t * title )
1364 int i;
1365 hb_audio_t * audio;
1367 for( i = 0; i < hb_list_count( title->list_audio ); i++ )
1369 audio = hb_list_item( title->list_audio, i );
1370 if( audio->config.in.bitrate == 0 )
1372 return 0;
1375 return 1;
1378 static void UpdateState1(hb_scan_t *scan, int title)
1380 hb_state_t state;
1382 #define p state.param.scanning
1383 /* Update the UI */
1384 state.state = HB_STATE_SCANNING;
1385 p.title_cur = title;
1386 p.title_count = scan->dvd ? hb_dvd_title_count( scan->dvd ) :
1387 scan->bd ? hb_bd_title_count( scan->bd ) :
1388 scan->batch ? hb_batch_title_count( scan->batch ) :
1389 hb_list_count(scan->title_set->list_title);
1390 p.preview_cur = 0;
1391 p.preview_count = 1;
1392 p.progress = 0.5 * ((float)p.title_cur + ((float)p.preview_cur / p.preview_count)) / p.title_count;
1393 #undef p
1395 hb_set_state(scan->h, &state);
1398 static void UpdateState2(hb_scan_t *scan, int title)
1400 hb_state_t state;
1402 #define p state.param.scanning
1403 /* Update the UI */
1404 state.state = HB_STATE_SCANNING;
1405 p.title_cur = title;
1406 p.title_count = hb_list_count( scan->title_set->list_title );
1407 p.preview_cur = 1;
1408 p.preview_count = scan->preview_count;
1409 if (scan->title_index)
1410 p.progress = (float)(p.title_cur - 1) / p.title_count;
1411 else
1412 p.progress = 0.5 + 0.5 * (float)(p.title_cur - 1) / p.title_count;
1413 #undef p
1415 hb_set_state(scan->h, &state);
1418 static void UpdateState3(hb_scan_t *scan, int preview)
1420 hb_state_t state;
1422 hb_get_state2(scan->h, &state);
1423 #define p state.param.scanning
1424 p.preview_cur = preview;
1425 p.preview_count = scan->preview_count;
1426 if (scan->title_index)
1427 p.progress = ((float)p.title_cur - 1 + ((float)p.preview_cur / p.preview_count)) / p.title_count;
1428 else
1429 p.progress = 0.5 + 0.5 * ((float)p.title_cur - 1 + ((float)p.preview_cur / p.preview_count)) / p.title_count;
1430 #undef p
1432 hb_set_state(scan->h, &state);