OSDN Git Service

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