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