OSDN Git Service

Add Bluray support
[handbrake-jp/handbrake-jp-git.git] / libhb / scan.c
1 /* $Id: scan.c,v 1.52 2005/11/25 15:05:25 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 "hb.h"
8 #include "a52dec/a52.h"
9 #include "dca.h"
10
11 #define HB_MAX_PREVIEWS 30 // 30 previews = every 5 minutes of a 2.5 hour video
12
13 typedef struct
14 {
15     hb_handle_t  * h;
16     volatile int * die;
17
18     char         * path;
19     int            title_index;
20     hb_list_t    * list_title;
21
22     hb_bd_t      * bd;
23     hb_dvd_t     * dvd;
24     hb_stream_t  * stream;
25     hb_batch_t   * batch;
26
27     int            preview_count;
28     int            store_previews;
29
30     uint64_t       min_title_duration;
31
32 } hb_scan_t;
33
34 static void ScanFunc( void * );
35 static int  DecodePreviews( hb_scan_t *, hb_title_t * title );
36 static void LookForAudio( hb_title_t * title, hb_buffer_t * b );
37 static int  AllAudioOK( hb_title_t * title );
38
39 static const char *aspect_to_string( double aspect )
40 {
41     switch ( (int)(aspect * 9.) )
42     {
43         case 9 * 4 / 3:    return "4:3";
44         case 9 * 16 / 9:   return "16:9";
45     }
46     static char arstr[32];
47     sprintf( arstr, aspect >= 1.? "%.2f:1" : "1:%.2f", aspect );
48     return arstr;
49 }
50
51 hb_thread_t * hb_scan_init( hb_handle_t * handle, volatile int * die,
52                             const char * path, int title_index, 
53                             hb_list_t * list_title, int preview_count, 
54                             int store_previews, uint64_t min_duration )
55 {
56     hb_scan_t * data = calloc( sizeof( hb_scan_t ), 1 );
57
58     data->h            = handle;
59     data->die          = die;
60     data->path         = strdup( path );
61     data->title_index  = title_index;
62     data->list_title   = list_title;
63     
64     data->preview_count  = preview_count;
65     data->store_previews = store_previews;
66     data->min_title_duration = min_duration;
67     
68     return hb_thread_init( "scan", ScanFunc, data, HB_NORMAL_PRIORITY );
69 }
70
71 static void ScanFunc( void * _data )
72 {
73     hb_scan_t  * data = (hb_scan_t *) _data;
74     hb_title_t * title;
75     int          i;
76     int          feature = 0;
77
78     data->bd = NULL;
79     data->dvd = NULL;
80     data->stream = NULL;
81
82     /* Try to open the path as a DVD. If it fails, try as a file */
83     if( ( data->bd = hb_bd_init( data->path ) ) )
84     {
85         hb_log( "scan: BD has %d title(s)",
86                 hb_bd_title_count( data->bd ) );
87         if( data->title_index )
88         {
89             /* Scan this title only */
90             hb_list_add( data->list_title, hb_bd_title_scan( data->bd,
91                          data->title_index, 0 ) );
92         }
93         else
94         {
95             /* Scan all titles */
96             for( i = 0; i < hb_bd_title_count( data->bd ); i++ )
97             {
98                 hb_list_add( data->list_title, hb_bd_title_scan( data->bd, 
99                              i + 1, data->min_title_duration ) );
100             }
101             feature = hb_bd_main_feature( data->bd, data->list_title );
102         }
103     }
104     else if( ( data->dvd = hb_dvd_init( data->path ) ) )
105     {
106         hb_log( "scan: DVD has %d title(s)",
107                 hb_dvd_title_count( data->dvd ) );
108         if( data->title_index )
109         {
110             /* Scan this title only */
111             hb_list_add( data->list_title, hb_dvd_title_scan( data->dvd,
112                             data->title_index, 0 ) );
113         }
114         else
115         {
116             /* Scan all titles */
117             for( i = 0; i < hb_dvd_title_count( data->dvd ); i++ )
118             {
119                 hb_list_add( data->list_title, hb_dvd_title_scan( data->dvd, 
120                             i + 1, data->min_title_duration ) );
121             }
122             feature = hb_dvd_main_feature( data->dvd, data->list_title );
123         }
124     }
125     else if ( ( data->batch = hb_batch_init( data->path ) ) )
126     {
127         int j = 1;
128
129         /* Scan all titles */
130         for( i = 0; i < hb_batch_title_count( data->batch ); i++ )
131         {
132             hb_title_t * title;
133
134             title = hb_batch_title_scan( data->batch, i );
135             if ( title != NULL )
136             {
137                 title->index = j++;
138                 hb_list_add( data->list_title, title );
139             }
140         }
141     }
142     else if ( (data->stream = hb_stream_open( data->path, 0 ) ) != NULL )
143     {
144         hb_list_add( data->list_title, hb_stream_title_scan( data->stream ) );
145     }
146     else
147     {
148         hb_log( "scan: unrecognized file type" );
149         return;
150     }
151
152     for( i = 0; i < hb_list_count( data->list_title ); )
153     {
154         int j;
155         hb_state_t state;
156         hb_audio_t * audio;
157
158         if ( *data->die )
159         {
160             goto finish;
161         }
162         title = hb_list_item( data->list_title, i );
163
164 #define p state.param.scanning
165         /* Update the UI */
166         state.state   = HB_STATE_SCANNING;
167         p.title_cur   = title->index;
168         p.title_count = data->dvd ? hb_dvd_title_count( data->dvd ) : 
169                         data->bd ? hb_bd_title_count( data->bd ) :
170                                    hb_list_count(data->list_title);
171         hb_set_state( data->h, &state );
172 #undef p
173
174         /* Decode previews */
175         /* this will also detect more AC3 / DTS information */
176         if( !DecodePreviews( data, title ) )
177         {
178             /* TODO: free things */
179             hb_list_rem( data->list_title, title );
180             continue;
181         }
182
183         /* Make sure we found audio rates and bitrates */
184         for( j = 0; j < hb_list_count( title->list_audio ); )
185         {
186             audio = hb_list_item( title->list_audio, j );
187             if( !audio->config.in.bitrate )
188             {
189                 hb_log( "scan: removing audio 0x%x because no bitrate found",
190                         audio->id );
191                 hb_list_rem( title->list_audio, audio );
192                 free( audio );
193                 continue;
194             }
195             if ( audio->priv.scan_cache )
196             {
197                 hb_fifo_flush( audio->priv.scan_cache );
198                 hb_fifo_close( &audio->priv.scan_cache );
199             }
200             j++;
201         }
202
203         if ( data->dvd || data->bd )
204         {
205             // The subtitle width and height needs to be set to the 
206             // title widht and height for DVDs.  title width and
207             // height don't get set until we decode previews, so
208             // we can't set subtitle width/height till we get here.
209             for( j = 0; j < hb_list_count( title->list_subtitle ); j++ )
210             {
211                 hb_subtitle_t *subtitle = hb_list_item( title->list_subtitle, j );
212                 if ( subtitle->source == VOBSUB )
213                 {
214                     subtitle->width = title->width;
215                     subtitle->height = title->height;
216                 }
217             }
218         }
219         i++;
220     }
221
222     /* Init jobs templates */
223     for( i = 0; i < hb_list_count( data->list_title ); i++ )
224     {
225         hb_job_t * job;
226
227         title      = hb_list_item( data->list_title, i );
228         job        = calloc( sizeof( hb_job_t ), 1 );
229         title->job = job;
230
231         job->title = title;
232         job->feature = feature;
233
234         /* Set defaults settings */
235         job->chapter_start = 1;
236         job->chapter_end   = hb_list_count( title->list_chapter );
237
238         /* Autocrop by default. Gnark gnark */
239         memcpy( job->crop, title->crop, 4 * sizeof( int ) );
240
241         /* Preserve a source's pixel aspect, if it's available. */
242         if( title->pixel_aspect_width && title->pixel_aspect_height )
243         {
244             job->anamorphic.par_width  = title->pixel_aspect_width;
245             job->anamorphic.par_height = title->pixel_aspect_height;
246         }
247
248         if( title->aspect != 0 && title->aspect != 1. &&
249             !job->anamorphic.par_width && !job->anamorphic.par_height)
250         {
251             hb_reduce( &job->anamorphic.par_width, &job->anamorphic.par_height,
252                        (int)(title->aspect * title->height + 0.5), title->width );
253         }
254
255         job->width = title->width - job->crop[2] - job->crop[3];
256         hb_fix_aspect( job, HB_KEEP_WIDTH );
257         if( job->height > title->height - job->crop[0] - job->crop[1] )
258         {
259             job->height = title->height - job->crop[0] - job->crop[1];
260             hb_fix_aspect( job, HB_KEEP_HEIGHT );
261         }
262
263         hb_log( "scan: title (%d) job->width:%d, job->height:%d",
264                 i, job->width, job->height );
265
266         job->keep_ratio = 1;
267
268         job->vcodec     = HB_VCODEC_FFMPEG;
269         job->vquality   = -1.0;
270         job->vbitrate   = 1000;
271         job->pass       = 0;
272         job->vrate      = title->rate;
273         job->vrate_base = title->rate_base;
274
275         job->list_audio = hb_list_init();
276         job->list_subtitle = hb_list_init();
277
278         job->mux = HB_MUX_MP4;
279     }
280
281 finish:
282
283     if( data->bd )
284     {
285         hb_bd_close( &data->bd );
286     }
287     if( data->dvd )
288     {
289         hb_dvd_close( &data->dvd );
290     }
291     if (data->stream)
292     {
293         hb_stream_close(&data->stream);
294     }
295     if( data->batch )
296     {
297         hb_batch_close( &data->batch );
298     }
299     free( data->path );
300     free( data );
301     _data = NULL;
302 }
303
304 // -----------------------------------------------
305 // stuff related to cropping
306
307 #define DARK 32
308
309 static inline int absdiff( int x, int y )
310 {
311     return x < y ? y - x : x - y;
312 }
313
314 static inline int clampBlack( int x ) 
315 {
316     // luma 'black' is 16 and anything less should be clamped at 16
317     return x < 16 ? 16 : x;
318 }
319
320 static int row_all_dark( hb_title_t *title, uint8_t* luma, int row )
321 {
322     luma += title->width * row;
323
324     // compute the average luma value of the row
325     int i, avg = 0;
326     for ( i = 0; i < title->width; ++i )
327     {
328         avg += clampBlack( luma[i] );
329     }
330     avg /= title->width;
331     if ( avg >= DARK )
332         return 0;
333
334     // since we're trying to detect smooth borders, only take the row if
335     // all pixels are within +-16 of the average (this range is fairly coarse
336     // but there's a lot of quantization noise for luma values near black
337     // so anything less will fail to crop because of the noise).
338     for ( i = 0; i < title->width; ++i )
339     {
340         if ( absdiff( avg, clampBlack( luma[i] ) ) > 16 )
341             return 0;
342     }
343     return 1;
344 }
345
346 static int column_all_dark( hb_title_t *title, uint8_t* luma, int top, int bottom,
347                             int col )
348 {
349     int stride = title->width;
350     int height = title->height - top - bottom;
351     luma += stride * top + col;
352
353     // compute the average value of the column
354     int i = height, avg = 0, row = 0;
355     for ( ; --i >= 0; row += stride )
356     {
357         avg += clampBlack( luma[row] );
358     }
359     avg /= height;
360     if ( avg >= DARK )
361         return 0;
362
363     // since we're trying to detect smooth borders, only take the column if
364     // all pixels are within +-16 of the average.
365     i = height, row = 0;
366     for ( ; --i >= 0; row += stride )
367     {
368         if ( absdiff( avg, clampBlack( luma[row] ) ) > 16 )
369             return 0;
370     }
371     return 1;
372 }
373 #undef DARK
374
375 typedef struct {
376     int n;
377     int t[HB_MAX_PREVIEWS];
378     int b[HB_MAX_PREVIEWS];
379     int l[HB_MAX_PREVIEWS];
380     int r[HB_MAX_PREVIEWS];
381 } crop_record_t;
382
383 static void record_crop( crop_record_t *crops, int t, int b, int l, int r )
384 {
385     crops->t[crops->n] = t;
386     crops->b[crops->n] = b;
387     crops->l[crops->n] = l;
388     crops->r[crops->n] = r;
389     ++crops->n;
390 }
391
392 static int compare_int( const void *a, const void *b )
393 {
394     return *(const int *)a - *(const int *)b;
395 }
396
397 static void sort_crops( crop_record_t *crops )
398 {
399     qsort( crops->t, crops->n, sizeof(crops->t[0]), compare_int );
400     qsort( crops->b, crops->n, sizeof(crops->t[0]), compare_int );
401     qsort( crops->l, crops->n, sizeof(crops->t[0]), compare_int );
402     qsort( crops->r, crops->n, sizeof(crops->t[0]), compare_int );
403 }
404
405 // -----------------------------------------------
406 // stuff related to title width/height/aspect info
407
408 typedef struct {
409     int count;              /* number of times we've seen this info entry */
410     hb_work_info_t info;    /* copy of info entry */
411 } info_list_t;
412
413 static void remember_info( info_list_t *info_list, hb_work_info_t *info )
414 {
415     for ( ; info_list->count; ++info_list )
416     {
417         if ( memcmp( &info_list->info, info, sizeof(*info) ) == 0 )
418         {
419             // we found a match - bump its count
420             ++info_list->count;
421             return;
422         }
423     }
424     // no match found - add new entry to list (info_list points to
425     // the first free slot). NB - we assume that info_list was allocated
426     // so that it's big enough even if there are no dups. I.e., 10 slots
427     // allocated if there are 10 previews.
428     info_list->count = 1;
429     info_list->info = *info;
430 }
431
432 static void most_common_info( info_list_t *info_list, hb_work_info_t *info )
433 {
434     int i, biggest = 0;
435     for ( i = 1; info_list[i].count; ++i )
436     {
437         if ( info_list[i].count > info_list[biggest].count )
438             biggest = i;
439     }
440     *info = info_list[biggest].info;
441     free( info_list );
442 }
443
444 /***********************************************************************
445  * DecodePreviews
446  ***********************************************************************
447  * Decode 10 pictures for the given title.
448  * It assumes that data->reader and data->vts have successfully been
449  * DVDOpen()ed and ifoOpen()ed.
450  **********************************************************************/
451 static int DecodePreviews( hb_scan_t * data, hb_title_t * title )
452 {
453     int             i, npreviews = 0;
454     hb_buffer_t   * buf_ps, * buf_es;
455     hb_list_t     * list_es;
456     int progressive_count = 0;
457     int interlaced_preview_count = 0;
458     info_list_t * info_list = calloc( data->preview_count+1, sizeof(*info_list) );
459     crop_record_t *crops = calloc( 1, sizeof(*crops) );
460
461     buf_ps   = hb_buffer_init( HB_DVD_READ_BUFFER_SIZE );
462     list_es  = hb_list_init();
463
464     hb_log( "scan: decoding previews for title %d", title->index );
465
466     if (data->bd)
467     {
468         hb_bd_start( data->bd, title );
469         hb_log( "scan: title angle(s) %d", title->angle_count );
470     }
471     else if (data->dvd)
472     {
473         hb_dvd_start( data->dvd, title, 1 );
474         title->angle_count = hb_dvd_angle_count( data->dvd );
475         hb_log( "scan: title angle(s) %d", title->angle_count );
476     }
477     else if (data->batch)
478     {
479         data->stream = hb_stream_open( title->path, title );
480     }
481
482     for( i = 0; i < data->preview_count; i++ )
483     {
484         int j;
485         FILE * file_preview;
486         char   filename[1024];
487
488         if ( *data->die )
489         {
490             return 0;
491         }
492         if (data->bd)
493         {
494             if( !hb_bd_seek( data->bd, (float) ( i + 1 ) / ( data->preview_count + 1.0 ) ) )
495           {
496               continue;
497           }
498         }
499         if (data->dvd)
500         {
501             if( !hb_dvd_seek( data->dvd, (float) ( i + 1 ) / ( data->preview_count + 1.0 ) ) )
502           {
503               continue;
504           }
505         }
506         else if (data->stream)
507         {
508           /* we start reading streams at zero rather than 1/11 because
509            * short streams may have only one sequence header in the entire
510            * file and we need it to decode any previews. */
511           if (!hb_stream_seek(data->stream, (float) i / ( data->preview_count + 1.0 ) ) )
512           {
513               continue;
514           }
515         }
516
517         hb_deep_log( 2, "scan: preview %d", i + 1 );
518
519         int vcodec = title->video_codec? title->video_codec : WORK_DECMPEG2;
520         hb_work_object_t *vid_decoder = hb_get_work( vcodec );
521         vid_decoder->codec_param = title->video_codec_param;
522         vid_decoder->title = title;
523         vid_decoder->init( vid_decoder, NULL );
524         hb_buffer_t * vid_buf = NULL;
525         int vidskip = 0;
526
527         if ( title->flags & HBTF_NO_IDR )
528         {
529             // title doesn't have IDR frames so we decode but drop one second's
530             // worth of frames to allow the decoder to converge.
531             if ( ! title->rate_base )
532             {
533                 vidskip = 30;
534             }
535             else
536             {
537                 vidskip = (double)title->rate / (double)title->rate_base + 0.5;
538             }
539             // If it's a BD, we can relax this a bit. Since seeks will
540             // at least get us to a recovery point.
541             if (data->bd)
542                 vidskip = 4;
543         }
544
545         for( j = 0; j < 10240 ; j++ )
546         {
547             if (data->bd)
548             {
549               if( !hb_bd_read( data->bd, buf_ps ) )
550               {
551                   if ( vid_buf )
552                   {
553                     break;
554                   }
555                   hb_log( "Warning: Could not read data for preview %d, skipped", i + 1 );
556                   goto skip_preview;
557               }
558             }
559             if (data->dvd)
560             {
561               if( !hb_dvd_read( data->dvd, buf_ps ) )
562               {
563                   if ( vid_buf )
564                   {
565                     break;
566                   }
567                   hb_log( "Warning: Could not read data for preview %d, skipped", i + 1 );
568                   goto skip_preview;
569               }
570             }
571             else if (data->stream)
572             {
573               if ( !hb_stream_read(data->stream,buf_ps) )
574               {
575                   if ( vid_buf )
576                   {
577                     break;
578                   }
579                   hb_log( "Warning: Could not read data for preview %d, skipped", i + 1 );
580                   goto skip_preview;
581               }
582             }
583             (hb_demux[title->demuxer])(buf_ps, list_es, 0 );
584
585             while( ( buf_es = hb_list_item( list_es, 0 ) ) )
586             {
587                 hb_list_rem( list_es, buf_es );
588                 if( buf_es->id == title->video_id && vid_buf == NULL )
589                 {
590                     vid_decoder->work( vid_decoder, &buf_es, &vid_buf );
591                     if ( vid_buf && vidskip && --vidskip > 0 )
592                     {
593                         // we're dropping frames to get the video decoder in sync
594                         // when the video stream doesn't contain IDR frames
595                         while (vid_buf && --vidskip >= 0)
596                         {
597                             hb_buffer_t * next = vid_buf->next;
598                             vid_buf->next = NULL;
599                             hb_buffer_close( &vid_buf );
600                             vid_buf = next;
601                         }
602                     }
603                 }
604                 else if( ! AllAudioOK( title ) ) 
605                 {
606                     LookForAudio( title, buf_es );
607                     buf_es = NULL;
608                 }
609                 if ( buf_es )
610                     hb_buffer_close( &buf_es );
611             }
612
613             if( vid_buf && AllAudioOK( title ) )
614                 break;
615         }
616
617         if( ! vid_buf )
618         {
619             hb_log( "scan: could not get a decoded picture" );
620             continue;
621         }
622
623         /* Get size and rate infos */
624
625         hb_work_info_t vid_info;
626         if( !vid_decoder->info( vid_decoder, &vid_info ) )
627         {
628             /*
629              * Could not fill vid_info, don't continue and try to use vid_info
630              * in this case.
631              */
632             if (vid_buf)
633             {
634                 hb_buffer_close( &vid_buf );
635             }
636             vid_decoder->close( vid_decoder );
637             free( vid_decoder );
638             continue;
639         }
640         vid_decoder->close( vid_decoder );
641         free( vid_decoder );
642
643         remember_info( info_list, &vid_info );
644
645         title->video_codec_name = strdup( vid_info.name );
646         title->width = vid_info.width;
647         title->height = vid_info.height;
648         title->rate = vid_info.rate;
649         title->rate_base = vid_info.rate_base;
650         title->video_bitrate = vid_info.bitrate;
651
652         if( title->rate_base == 1126125 )
653         {
654             /* Frame FPS is 23.976 (meaning it's progressive), so
655                start keeping track of how many are reporting at
656                that speed. When enough show up that way, we want
657                to make that the overall title FPS.
658             */
659             progressive_count++;
660
661             if( progressive_count < 6 )
662             {
663                 /* Not enough frames are reporting as progressive,
664                    which means we should be conservative and use
665                    29.97 as the title's FPS for now.
666                 */
667                 title->rate_base = 900900;
668             }
669             else
670             {
671                 /* A majority of the scan frames are progressive. Make that
672                     the title's FPS, and announce it once to the log.
673                 */
674                 if( progressive_count == 6 )
675                 {
676                     hb_deep_log( 2, "Title's mostly NTSC Film, setting fps to 23.976");
677                 }
678                 title->rate_base = 1126125;
679             }
680         }
681         else if( title->rate_base == 900900 && progressive_count >= 6 )
682         {
683             /*
684              * We've already deduced that the frame rate is 23.976, so set it
685              * back again.
686              */
687             title->rate_base = 1126125;
688         }
689
690         while( ( buf_es = hb_list_item( list_es, 0 ) ) )
691         {
692             hb_list_rem( list_es, buf_es );
693             hb_buffer_close( &buf_es );
694         }
695
696         /* Check preview for interlacing artifacts */
697         if( hb_detect_comb( vid_buf, title->width, title->height, 10, 30, 9, 10, 30, 9 ) )
698         {
699             hb_deep_log( 2, "Interlacing detected in preview frame %i", i+1);
700             interlaced_preview_count++;
701         }
702         
703         if( data->store_previews )
704         {
705             hb_get_tempory_filename( data->h, filename, "%d_%d_%d",
706                                      hb_get_instance_id(data->h), title->index, i );
707
708             file_preview = fopen( filename, "wb" );
709             if( file_preview )
710             {
711                 fwrite( vid_buf->data, title->width * title->height * 3 / 2,
712                         1, file_preview );
713                 fclose( file_preview );
714             }
715             else
716             {
717                 hb_log( "scan: fopen failed (%s)", filename );
718             }
719         }
720
721         /* Detect black borders */
722
723 #define Y    vid_buf->data
724         int top, bottom, left, right;
725         int h4 = title->height / 4, w4 = title->width / 4;
726
727         // When widescreen content is matted to 16:9 or 4:3 there's sometimes
728         // a thin border on the outer edge of the matte. On TV content it can be
729         // "line 21" VBI data that's normally hidden in the overscan. For HD
730         // content it can just be a diagnostic added in post production so that
731         // the frame borders are visible. We try to ignore these borders so
732         // we can crop the matte. The border width depends on the resolution
733         // (12 pixels on 1080i looks visually the same as 4 pixels on 480i)
734         // so we allow the border to be up to 1% of the frame height.
735         const int border = title->height / 100;
736
737         for ( top = border; top < h4; ++top )
738         {
739             if ( ! row_all_dark( title, Y, top ) )
740                 break;
741         }
742         if ( top <= border )
743         {
744             // we never made it past the border region - see if the rows we
745             // didn't check are dark or if we shouldn't crop at all.
746             for ( top = 0; top < border; ++top )
747             {
748                 if ( ! row_all_dark( title, Y, top ) )
749                     break;
750             }
751             if ( top >= border )
752             {
753                 top = 0;
754             }
755         }
756         for ( bottom = border; bottom < h4; ++bottom )
757         {
758             if ( ! row_all_dark( title, Y, title->height - 1 - bottom ) )
759                 break;
760         }
761         if ( bottom <= border )
762         {
763             for ( bottom = 0; bottom < border; ++bottom )
764             {
765                 if ( ! row_all_dark( title, Y, title->height - 1 - bottom ) )
766                     break;
767             }
768             if ( bottom >= border )
769             {
770                 bottom = 0;
771             }
772         }
773         for ( left = 0; left < w4; ++left )
774         {
775             if ( ! column_all_dark( title, Y, top, bottom, left ) )
776                 break;
777         }
778         for ( right = 0; right < w4; ++right )
779         {
780             if ( ! column_all_dark( title, Y, top, bottom, title->width - 1 - right ) )
781                 break;
782         }
783
784         // only record the result if all the crops are less than a quarter of
785         // the frame otherwise we can get fooled by frames with a lot of black
786         // like titles, credits & fade-thru-black transitions.
787         if ( top < h4 && bottom < h4 && left < w4 && right < w4 )
788         {
789             record_crop( crops, top, bottom, left, right );
790         }
791         ++npreviews;
792
793 skip_preview:
794         /* Make sure we found audio rates and bitrates */
795         for( j = 0; j < hb_list_count( title->list_audio ); j++ )
796         {
797             hb_audio_t * audio = hb_list_item( title->list_audio, j );
798             if ( audio->priv.scan_cache )
799             {
800                 hb_fifo_flush( audio->priv.scan_cache );
801             }
802         }
803         if (vid_buf)
804         {
805             hb_buffer_close( &vid_buf );
806         }
807     }
808
809     if ( data->batch && data->stream )
810     {
811         hb_stream_close( &data->stream );
812     }
813
814     if ( npreviews )
815     {
816         // use the most common frame info for our final title dimensions
817         hb_work_info_t vid_info;
818         most_common_info( info_list, &vid_info );
819
820         title->width = vid_info.width;
821         title->height = vid_info.height;
822         title->pixel_aspect_width = vid_info.pixel_aspect_width;
823         title->pixel_aspect_height = vid_info.pixel_aspect_height;
824
825         // compute the aspect ratio based on the storage dimensions and the
826         // pixel aspect ratio (if supplied) or just storage dimensions if no PAR.
827         title->aspect = (double)title->width / (double)title->height;
828         if( title->pixel_aspect_width && title->pixel_aspect_height )
829         {
830             title->aspect *= (double)title->pixel_aspect_width /
831                              (double)title->pixel_aspect_height;
832
833             // For unknown reasons some French PAL DVDs put the original
834             // content's aspect ratio into the mpeg PAR even though it's
835             // the wrong PAR for the DVD. Apparently they rely on the fact
836             // that DVD players ignore the content PAR and just use the
837             // aspect ratio from the DVD metadata. So, if the aspect computed
838             // from the PAR is different from the container's aspect we use
839             // the container's aspect & recompute the PAR from it.
840             if( title->container_aspect && (int)(title->aspect * 9) != (int)(title->container_aspect * 9) )
841             {
842                 hb_log("scan: content PAR gives wrong aspect %.2f; "
843                        "using container aspect %.2f", title->aspect,
844                        title->container_aspect );
845                 title->aspect = title->container_aspect;
846                 hb_reduce( &title->pixel_aspect_width, &title->pixel_aspect_height,
847                            (int)(title->aspect * title->height + 0.5), title->width );
848             }
849         }
850
851         // don't try to crop unless we got at least 3 previews
852         if ( crops->n > 2 )
853         {
854             sort_crops( crops );
855             // The next line selects median cropping - at least
856             // 50% of the frames will have their borders removed.
857             // Other possible choices are loose cropping (i = 0) where 
858             // no non-black pixels will be cropped from any frame and a
859             // tight cropping (i = crops->n - (crops->n >> 2)) where at
860             // least 75% of the frames will have their borders removed.
861             i = crops->n >> 1;
862             title->crop[0] = EVEN( crops->t[i] );
863             title->crop[1] = EVEN( crops->b[i] );
864             title->crop[2] = EVEN( crops->l[i] );
865             title->crop[3] = EVEN( crops->r[i] );
866         }
867         free( crops );
868
869         hb_log( "scan: %d previews, %dx%d, %.3f fps, autocrop = %d/%d/%d/%d, "
870                 "aspect %s, PAR %d:%d",
871                 npreviews, title->width, title->height, (float) title->rate /
872                 (float) title->rate_base,
873                 title->crop[0], title->crop[1], title->crop[2], title->crop[3],
874                 aspect_to_string( title->aspect ), title->pixel_aspect_width,
875                 title->pixel_aspect_height );
876
877         if( interlaced_preview_count >= ( npreviews / 2 ) )
878         {
879             hb_log("Title is likely interlaced or telecined (%i out of %i previews). You should do something about that.",
880                    interlaced_preview_count, npreviews);
881             title->detected_interlacing = 1;
882         }
883         else
884         {
885             title->detected_interlacing = 0;
886         }
887     }
888
889     hb_buffer_close( &buf_ps );
890     while( ( buf_es = hb_list_item( list_es, 0 ) ) )
891     {
892         hb_list_rem( list_es, buf_es );
893         hb_buffer_close( &buf_es );
894     }
895     hb_list_close( &list_es );
896     if (data->bd)
897       hb_bd_stop( data->bd );
898     if (data->dvd)
899       hb_dvd_stop( data->dvd );
900
901     return npreviews;
902 }
903
904 /*
905  * This routine is called for every frame from a non-video elementary stream.
906  * These are a mix of audio & subtitle streams, some of which we want & some
907  * we're ignoring. This routine checks the frame against all our audio streams
908  * to see if it's one we want and haven't identified yet. If yes, it passes the
909  * frame to a codec-specific id routine which is responsible for filling in
910  * the sample rate, bit rate, channels & other audio parameters.
911  *
912  * Since a sample rate is essential for further audio processing, any audio
913  * stream which isn't successfully id'd by is deleted at the end of the scan.
914  * This is necessary to avoid ambiguities where things that might be audio
915  * aren't (e.g., some European DVD Teletext streams use the same IDs as US ATSC
916  * AC-3 audio).
917  */
918 static void LookForAudio( hb_title_t * title, hb_buffer_t * b )
919 {
920     int i;
921
922     hb_audio_t * audio = NULL;
923     for( i = 0; i < hb_list_count( title->list_audio ); i++ )
924     {
925         audio = hb_list_item( title->list_audio, i );
926         /* check if this elementary stream is one we want */
927         if ( audio->id == b->id )
928         {
929             break;
930         }
931         else
932         {
933             audio = NULL;
934         }
935     }
936     if( !audio || audio->config.in.bitrate != 0 )
937     {
938         /* not found or already done */
939         hb_buffer_close( &b );
940         return;
941     }
942
943     if ( audio->priv.scan_cache == NULL )
944         audio->priv.scan_cache = hb_fifo_init( 16, 16 );
945
946     if ( hb_fifo_size_bytes( audio->priv.scan_cache ) >= 4096 )
947     {
948         hb_buffer_t * tmp;
949         tmp = hb_fifo_get( audio->priv.scan_cache );
950         hb_buffer_close( &tmp );
951     }
952     hb_fifo_push( audio->priv.scan_cache, b );
953
954     hb_work_object_t *w = hb_codec_decoder( audio->config.in.codec );
955
956     if ( w == NULL || w->bsinfo == NULL )
957     {
958         hb_log( "Internal error in scan: unhandled audio type %d for id 0x%x",
959                 audio->config.in.codec, audio->id );
960         goto drop_audio;
961     }
962
963     hb_work_info_t info;
964     w->audio = audio;
965     w->codec_param = audio->config.in.codec_param;
966     b = hb_fifo_see( audio->priv.scan_cache );
967     int ret = w->bsinfo( w, b, &info );
968     if ( ret < 0 )
969     {
970         hb_log( "no info on audio type %d/0x%x for id 0x%x",
971                 audio->config.in.codec, audio->config.in.codec_param,
972                 audio->id );
973         goto drop_audio;
974     }
975     if ( !info.bitrate )
976     {
977         /* didn't find any info */
978         return;
979     }
980     hb_fifo_flush( audio->priv.scan_cache );
981     hb_fifo_close( &audio->priv.scan_cache );
982
983     audio->config.in.samplerate = info.rate;
984     audio->config.in.bitrate = info.bitrate;
985     audio->config.in.channel_layout = info.channel_layout;
986     audio->config.in.version = info.version;
987     audio->config.in.mode = info.mode;
988     audio->config.flags.ac3 = info.flags;
989
990     // update the audio description string based on the info we found
991     if ( audio->config.flags.ac3 & AUDIO_F_DOLBY )
992     {
993         strcat( audio->config.lang.description, " (Dolby Surround)" );
994     }
995     else
996     {
997         int layout = audio->config.in.channel_layout;
998         char *desc = audio->config.lang.description +
999                         strlen( audio->config.lang.description );
1000         sprintf( desc, " (%d.%d ch)",
1001                  HB_INPUT_CH_LAYOUT_GET_DISCRETE_FRONT_COUNT(layout) +
1002                      HB_INPUT_CH_LAYOUT_GET_DISCRETE_REAR_COUNT(layout),
1003                  HB_INPUT_CH_LAYOUT_GET_DISCRETE_LFE_COUNT(layout) );
1004     }
1005
1006     hb_log( "scan: audio 0x%x: %s, rate=%dHz, bitrate=%d %s", audio->id,
1007             info.name, audio->config.in.samplerate, audio->config.in.bitrate,
1008             audio->config.lang.description );
1009  
1010     free( w );
1011     return;
1012
1013     // We get here if there's no hope of finding info on an audio bitstream,
1014     // either because we don't have a decoder (or a decoder with a bitstream
1015     // info proc) or because the decoder's info proc said that the stream
1016     // wasn't something it could handle. Delete the item from the title's
1017     // audio list so we won't keep reading packets while trying to get its
1018     // bitstream info.
1019  drop_audio:
1020     if ( w )
1021         free( w );
1022
1023     hb_fifo_flush( audio->priv.scan_cache );
1024     hb_fifo_close( &audio->priv.scan_cache );
1025     hb_list_rem( title->list_audio, audio );
1026     return;
1027 }
1028
1029 /*
1030  * This routine checks to see if we've ID'd all the audio streams associated
1031  * with a title. It returns 0 if there are more to ID & 1 if all are done.
1032  */
1033 static int  AllAudioOK( hb_title_t * title )
1034 {
1035     int i;
1036     hb_audio_t * audio;
1037
1038     for( i = 0; i < hb_list_count( title->list_audio ); i++ )
1039     {
1040         audio = hb_list_item( title->list_audio, i );
1041         if( audio->config.in.bitrate == 0 )
1042         {
1043             return 0;
1044         }
1045     }
1046     return 1;
1047 }