OSDN Git Service

- patch a reference picture leak in ffmpeg/libavcodec/mpegvideo.c that caused aborts...
[handbrake-jp/handbrake-jp-git.git] / libhb / hb.c
1 #include "hb.h"
2
3 #include "libavcodec/avcodec.h"
4 #include "libavformat/avformat.h"
5 #include "libswscale/swscale.h"
6
7 struct hb_handle_s
8 {
9     /* The "Check for update" thread */
10     int            build;
11     char           version[16];
12     hb_thread_t  * update_thread;
13
14     /* This thread's only purpose is to check other threads'
15        states */
16     volatile int   die;
17     hb_thread_t  * main_thread;
18     int            pid;
19
20     /* DVD/file scan thread */
21     hb_list_t    * list_title;
22     hb_thread_t  * scan_thread;
23
24     /* The thread which processes the jobs. Others threads are launched
25        from this one (see work.c) */
26     hb_list_t    * jobs;
27     hb_job_t     * current_job;
28     int            job_count;
29     int            job_count_permanent;
30     volatile int   work_die;
31     int            work_error;
32     hb_thread_t  * work_thread;
33
34     int            cpu_count;
35
36     hb_lock_t    * state_lock;
37     hb_state_t     state;
38
39     int            paused;
40     hb_lock_t    * pause_lock;
41     /* For MacGui active queue
42        increments each time the scan thread completes*/
43     int            scanCount;
44
45 };
46
47 hb_work_object_t * hb_objects = NULL;
48
49 static void thread_func( void * );
50
51 /**
52  * Registers work objects, by adding the work object to a liked list.
53  * @param w Handle to hb_work_object_t to register.
54  */
55 void hb_register( hb_work_object_t * w )
56 {
57     w->next    = hb_objects;
58     hb_objects = w;
59 }
60
61 /**
62  * libhb initialization routine.
63  * @param verbose HB_DEBUG_NONE or HB_DEBUG_ALL.
64  * @param update_check signals libhb to check for updated version from HandBrake website.
65  * @return Handle to hb_handle_t for use on all subsequent calls to libhb.
66  */
67 hb_handle_t * hb_init_real( int verbose, int update_check )
68 {
69     hb_handle_t * h = calloc( sizeof( hb_handle_t ), 1 );
70     uint64_t      date;
71
72     /* See hb_log() in common.c */
73     if( verbose > HB_DEBUG_NONE )
74     {
75         putenv( "HB_DEBUG=1" );
76     }
77
78     /* Check for an update on the website if asked to */
79     h->build = -1;
80
81     if( update_check )
82     {
83         hb_log( "hb_init: checking for updates" );
84         date             = hb_get_date();
85         h->update_thread = hb_update_init( &h->build, h->version );
86
87         for( ;; )
88         {
89             if( hb_thread_has_exited( h->update_thread ) )
90             {
91                 /* Immediate success or failure */
92                 hb_thread_close( &h->update_thread );
93                 break;
94             }
95             if( hb_get_date() > date + 1000 )
96             {
97                 /* Still nothing after one second. Connection problem,
98                    let the thread die */
99                 hb_log( "hb_init: connection problem, not waiting for "
100                         "update_thread" );
101                 break;
102             }
103             hb_snooze( 500 );
104         }
105     }
106
107     /*
108      * Initialise buffer pool
109      */
110     hb_buffer_pool_init();
111
112     /* CPU count detection */
113     hb_log( "hb_init: checking cpu count" );
114     h->cpu_count = hb_get_cpu_count();
115
116     h->list_title = hb_list_init();
117     h->jobs       = hb_list_init();
118
119     h->state_lock  = hb_lock_init();
120     h->state.state = HB_STATE_IDLE;
121
122     h->pause_lock = hb_lock_init();
123
124     /* libavcodec */
125     av_register_all();
126
127     /* Start library thread */
128     hb_log( "hb_init: starting libhb thread" );
129     h->die         = 0;
130     h->main_thread = hb_thread_init( "libhb", thread_func, h,
131                                      HB_NORMAL_PRIORITY );
132
133     return h;
134
135         /* Set the scan count to start at 0 */
136         //scan_count = 0;
137 }
138
139 /**
140  * libhb initialization routine.
141  * This version is to use when calling the dylib, the macro hb_init isn't available from a dylib call!
142  * @param verbose HB_DEBUG_NONE or HB_DEBUG_ALL.
143  * @param update_check signals libhb to check for updated version from HandBrake website.
144  * @return Handle to hb_handle_t for use on all subsequent calls to libhb.
145  */
146 hb_handle_t * hb_init_dl( int verbose, int update_check )
147 {
148     hb_handle_t * h = calloc( sizeof( hb_handle_t ), 1 );
149     uint64_t      date;
150
151     /* See hb_log() in common.c */
152     if( verbose > HB_DEBUG_NONE )
153     {
154         putenv( "HB_DEBUG=1" );
155     }
156
157     /* Check for an update on the website if asked to */
158     h->build = -1;
159
160     if( update_check )
161     {
162         hb_log( "hb_init: checking for updates" );
163         date             = hb_get_date();
164         h->update_thread = hb_update_init( &h->build, h->version );
165
166         for( ;; )
167         {
168             if( hb_thread_has_exited( h->update_thread ) )
169             {
170                 /* Immediate success or failure */
171                 hb_thread_close( &h->update_thread );
172                 break;
173             }
174             if( hb_get_date() > date + 1000 )
175             {
176                 /* Still nothing after one second. Connection problem,
177                    let the thread die */
178                 hb_log( "hb_init: connection problem, not waiting for "
179                         "update_thread" );
180                 break;
181             }
182             hb_snooze( 500 );
183         }
184     }
185
186     /* CPU count detection */
187     hb_log( "hb_init: checking cpu count" );
188     h->cpu_count = hb_get_cpu_count();
189
190     h->list_title = hb_list_init();
191     h->jobs       = hb_list_init();
192     h->current_job = NULL;
193
194     h->state_lock  = hb_lock_init();
195     h->state.state = HB_STATE_IDLE;
196
197     h->pause_lock = hb_lock_init();
198
199     /* libavcodec */
200     avcodec_init();
201     avcodec_register_all();
202
203     /* Start library thread */
204     hb_log( "hb_init: starting libhb thread" );
205     h->die         = 0;
206     h->main_thread = hb_thread_init( "libhb", thread_func, h,
207                                      HB_NORMAL_PRIORITY );
208
209     hb_register( &hb_sync );
210         hb_register( &hb_decmpeg2 );
211         hb_register( &hb_decsub );
212         hb_register( &hb_render );
213         hb_register( &hb_encavcodec );
214         hb_register( &hb_encxvid );
215         hb_register( &hb_encx264 );
216     hb_register( &hb_enctheora );
217         hb_register( &hb_deca52 );
218         hb_register( &hb_decdca );
219         hb_register( &hb_decavcodec );
220         hb_register( &hb_decavcodecv );
221         hb_register( &hb_decavcodecvi );
222         hb_register( &hb_decavcodecai );
223         hb_register( &hb_declpcm );
224         hb_register( &hb_encfaac );
225         hb_register( &hb_enclame );
226         hb_register( &hb_encvorbis );
227
228         return h;
229 }
230
231
232 /**
233  * Returns current version of libhb.
234  * @param h Handle to hb_handle_t.
235  * @return character array of version number.
236  */
237 char * hb_get_version( hb_handle_t * h )
238 {
239     return HB_VERSION;
240 }
241
242 /**
243  * Returns current build of libhb.
244  * @param h Handle to hb_handle_t.
245  * @return character array of build number.
246  */
247 int hb_get_build( hb_handle_t * h )
248 {
249     return HB_BUILD;
250 }
251
252 /**
253  * Checks for needed update.
254  * @param h Handle to hb_handle_t.
255  * @param version Pointer to handle where version will be copied.
256  * @return update indicator.
257  */
258 int hb_check_update( hb_handle_t * h, char ** version )
259 {
260     *version = ( h->build < 0 ) ? NULL : h->version;
261     return h->build;
262 }
263
264 /**
265  * Sets the cpu count to the desired value.
266  * @param h Handle to hb_handle_t
267  * @param cpu_count Number of CPUs to use.
268  */
269 void hb_set_cpu_count( hb_handle_t * h, int cpu_count )
270 {
271     cpu_count    = MAX( 1, cpu_count );
272     cpu_count    = MIN( cpu_count, 8 );
273     h->cpu_count = cpu_count;
274 }
275
276 /**
277  * Initializes a scan of the by calling hb_scan_init
278  * @param h Handle to hb_handle_t
279  * @param path location of VIDEO_TS folder.
280  * @param title_index Desired title to scan.  0 for all titles.
281  */
282 void hb_scan( hb_handle_t * h, const char * path, int title_index )
283 {
284     hb_title_t * title;
285
286     /* Clean up from previous scan */
287     while( ( title = hb_list_item( h->list_title, 0 ) ) )
288     {
289         hb_list_rem( h->list_title, title );
290         hb_title_close( &title );
291     }
292
293     hb_log( "hb_scan: path=%s, title_index=%d", path, title_index );
294     h->scan_thread = hb_scan_init( h, path, title_index, h->list_title );
295 }
296
297 /**
298  * Returns the list of titles found.
299  * @param h Handle to hb_handle_t
300  * @return Handle to hb_list_t of the title list.
301  */
302 hb_list_t * hb_get_titles( hb_handle_t * h )
303 {
304     return h->list_title;
305 }
306
307 /**
308  * Create preview image of desired title a index of picture.
309  * @param h Handle to hb_handle_t.
310  * @param title Handle to hb_title_t of desired title.
311  * @param picture Index in title.
312  * @param buffer Handle to buufer were inage will be drawn.
313  */
314 void hb_get_preview( hb_handle_t * h, hb_title_t * title, int picture,
315                      uint8_t * buffer )
316 {
317     hb_job_t           * job = title->job;
318     char                 filename[1024];
319     FILE               * file;
320     uint8_t            * buf1, * buf2, * buf3, * buf4, * pen;
321     uint32_t           * p32, swsflags;
322     AVPicture            pic_in, pic_preview, pic_deint, pic_crop, pic_scale;
323     struct SwsContext  * context;
324     int                  i;
325
326     swsflags = SWS_LANCZOS;
327 #ifndef __x86_64__
328     swsflags |= SWS_ACCURATE_RND;
329 #endif  /* __x86_64__ */
330
331     buf1 = malloc( title->width * title->height * 3 / 2 );
332     buf2 = malloc( title->width * title->height * 3 / 2 );
333     buf3 = malloc( title->width * title->height * 3 / 2 );
334     buf4 = malloc( title->width * title->height * 4 );
335     avpicture_fill( &pic_in, buf1, PIX_FMT_YUV420P,
336                     title->width, title->height );
337     avpicture_fill( &pic_deint, buf2, PIX_FMT_YUV420P,
338                     title->width, title->height );
339     avpicture_fill( &pic_scale, buf3, PIX_FMT_YUV420P,
340                     job->width, job->height );
341     avpicture_fill( &pic_preview, buf4, PIX_FMT_RGBA32,
342                     job->width, job->height );
343
344     // Allocate the AVPicture frames and fill in
345
346     memset( filename, 0, 1024 );
347
348     hb_get_tempory_filename( h, filename, "%x%d",
349                              (intptr_t) title, picture );
350
351     file = fopen( filename, "r" );
352     if( !file )
353     {
354         hb_log( "hb_get_preview: fopen failed" );
355         return;
356     }
357
358     fread( buf1, title->width * title->height * 3 / 2, 1, file );
359     fclose( file );
360
361     if( job->deinterlace )
362     {
363         // Deinterlace and crop
364         avpicture_deinterlace( &pic_deint, &pic_in, PIX_FMT_YUV420P, title->width, title->height );
365         av_picture_crop( &pic_crop, &pic_deint, PIX_FMT_YUV420P, job->crop[0], job->crop[2] );
366     }
367     else
368     {
369         // Crop
370         av_picture_crop( &pic_crop, &pic_in, PIX_FMT_YUV420P, job->crop[0], job->crop[2] );
371     }
372
373     // Get scaling context
374     context = sws_getContext(title->width  - (job->crop[2] + job->crop[3]),
375                              title->height - (job->crop[0] + job->crop[1]),
376                              PIX_FMT_YUV420P,
377                              job->width, job->height, PIX_FMT_YUV420P,
378                              swsflags, NULL, NULL, NULL);
379
380     // Scale
381     sws_scale(context,
382               pic_crop.data, pic_crop.linesize,
383               0, title->height - (job->crop[0] + job->crop[1]),
384               pic_scale.data, pic_scale.linesize);
385
386     // Free context
387     sws_freeContext( context );
388
389     // Get preview context
390     context = sws_getContext(job->width, job->height, PIX_FMT_YUV420P,
391                               job->width, job->height, PIX_FMT_RGBA32,
392                               swsflags, NULL, NULL, NULL);
393
394     // Create preview
395     sws_scale(context,
396               pic_scale.data, pic_scale.linesize,
397               0, job->height,
398               pic_preview.data, pic_preview.linesize);
399
400     // Free context
401     sws_freeContext( context );
402
403     /* Gray background */
404     p32 = (uint32_t *) buffer;
405     for( i = 0; i < ( title->width + 2 ) * ( title->height + 2 ); i++ )
406     {
407         p32[i] = 0xFF808080;
408     }
409
410     /* Draw the picture, centered, and draw the cropping zone */
411     pen = buffer + ( title->height - job->height ) *
412         ( title->width + 2 ) * 2 + ( title->width - job->width ) * 2;
413     memset( pen, 0xFF, 4 * ( job->width + 2 ) );
414     pen += 4 * ( title->width + 2 );
415     for( i = 0; i < job->height; i++ )
416     {
417         uint8_t * nextLine;
418         nextLine = pen + 4 * ( title->width + 2 );
419         memset( pen, 0xFF, 4 );
420         pen += 4;
421         memcpy( pen, buf4 + 4 * job->width * i, 4 * job->width );
422         pen += 4 * job->width;
423         memset( pen, 0xFF, 4 );
424         pen = nextLine;
425     }
426     memset( pen, 0xFF, 4 * ( job->width + 2 ) );
427
428     // Clean up
429     avpicture_free( &pic_preview );
430     avpicture_free( &pic_scale );
431     avpicture_free( &pic_deint );
432     avpicture_free( &pic_in );
433 }
434
435  /**
436  * Analyzes a frame to detect interlacing artifacts
437  * and returns true if interlacing (combing) is found.
438  *
439  * Code taken from Thomas Oestreich's 32detect filter
440  * in the Transcode project, with minor formatting changes.
441  *
442  * @param buf         An hb_buffer structure holding valid frame data
443  * @param width       The frame's width in pixels
444  * @param height      The frame's height in pixels
445  * @param color_equal Sensitivity for detecting similar colors
446  * @param color_diff  Sensitivity for detecting different colors
447  * @param threshold   Sensitivity for flagging planes as combed
448  * @param prog_equal  Sensitivity for detecting similar colors on progressive frames
449  * @param prog_diff   Sensitivity for detecting different colors on progressive frames
450  * @param prog_threshold Sensitivity for flagging progressive frames as combed
451  */
452 int hb_detect_comb( hb_buffer_t * buf, int width, int height, int color_equal, int color_diff, int threshold, int prog_equal, int prog_diff, int prog_threshold )
453 {
454     int j, k, n, off, cc_1, cc_2, cc[3], flag[3] ;
455     uint16_t s1, s2, s3, s4;
456     cc_1 = 0; cc_2 = 0;
457
458     int offset = 0;
459     
460     if ( buf->flags & 16 )
461     {
462         /* Frame is progressive, be more discerning. */
463         color_diff = prog_diff;
464         color_equal = prog_equal;
465         threshold = prog_threshold;
466     }
467
468     /* One pas for Y, one pass for Cb, one pass for Cr */    
469     for( k = 0; k < 3; k++ )
470     {
471         if( k == 1 )
472         {
473             /* Y has already been checked, now offset by Y's dimensions
474                and divide all the other values by 2, since Cr and Cb
475                are half-size compared to Y.                               */
476             offset = width * height;
477             width >>= 1;
478             height >>= 1;
479         }
480         else if ( k == 2 )
481         {
482             /* Y and Cb are done, so the offset needs to be bumped
483                so it's width*height + (width / 2) * (height / 2)  */
484             offset *= 5/4;
485         }
486
487         for( j = 0; j < width; ++j )
488         {
489             off = 0;
490
491             for( n = 0; n < ( height - 4 ); n = n + 2 )
492             {
493                 /* Look at groups of 4 sequential horizontal lines */
494                 s1 = ( ( buf->data + offset )[ off + j             ] & 0xff );
495                 s2 = ( ( buf->data + offset )[ off + j + width     ] & 0xff );
496                 s3 = ( ( buf->data + offset )[ off + j + 2 * width ] & 0xff );
497                 s4 = ( ( buf->data + offset )[ off + j + 3 * width ] & 0xff );
498
499                 /* Note if the 1st and 2nd lines are more different in
500                    color than the 1st and 3rd lines are similar in color.*/
501                 if ( ( abs( s1 - s3 ) < color_equal ) &&
502                      ( abs( s1 - s2 ) > color_diff ) )
503                         ++cc_1;
504
505                 /* Note if the 2nd and 3rd lines are more different in
506                    color than the 2nd and 4th lines are similar in color.*/
507                 if ( ( abs( s2 - s4 ) < color_equal ) &&
508                      ( abs( s2 - s3 ) > color_diff) )
509                         ++cc_2;
510
511                 /* Now move down 2 horizontal lines before starting over.*/
512                 off += 2 * width;
513             }
514         }
515
516         // compare results
517         /*  The final cc score for a plane is the percentage of combed pixels it contains.
518             Because sensitivity goes down to hundreths of a percent, multiply by 1000
519             so it will be easy to compare against the threhold value which is an integer. */
520         cc[k] = (int)( ( cc_1 + cc_2 ) * 1000.0 / ( width * height ) );
521     }
522
523
524     /* HandBrake is all yuv420, so weight the average percentage of all 3 planes accordingly.*/
525     int average_cc = ( 2 * cc[0] + ( cc[1] / 2 ) + ( cc[2] / 2 ) ) / 3;
526     
527     /* Now see if that average percentage of combed pixels surpasses the threshold percentage given by the user.*/
528     if( average_cc > threshold )
529     {
530 #if 0
531             hb_log("Average %i combed (Threshold %i) %i/%i/%i | PTS: %lld (%fs) %s", average_cc, threshold, cc[0], cc[1], cc[2], buf->start, (float)buf->start / 90000, (buf->flags & 16) ? "Film" : "Video" );
532 #endif
533         return 1;
534     }
535
536 #if 0
537     hb_log("SKIPPED Average %i combed (Threshold %i) %i/%i/%i | PTS: %lld (%fs) %s", average_cc, threshold, cc[0], cc[1], cc[2], buf->start, (float)buf->start / 90000, (buf->flags & 16) ? "Film" : "Video" );
538 #endif
539
540     /* Reaching this point means no combing detected. */
541     return 0;
542
543 }
544
545 /**
546  * Calculates job width and height for anamorphic content,
547  *
548  * @param job Handle to hb_job_t
549  * @param output_width Pointer to returned storage width
550  * @param output_height Pointer to returned storage height
551  * @param output_par_width Pointer to returned pixel width
552  @ param output_par_height Pointer to returned pixel height
553  */
554 void hb_set_anamorphic_size( hb_job_t * job,
555         int *output_width, int *output_height,
556         int *output_par_width, int *output_par_height )
557 {
558     /* "Loose" anamorphic.
559         - Uses mod16-compliant dimensions,
560         - Allows users to set the width
561         - Handles ITU pixel aspects
562     */
563
564     /* Set up some variables to make the math easier to follow. */
565     hb_title_t * title = job->title;
566     int cropped_width = title->width - job->crop[2] - job->crop[3] ;
567     int cropped_height = title->height - job->crop[0] - job->crop[1] ;
568     double storage_aspect = (double)cropped_width / (double)cropped_height;
569     int width = job->width;
570     int height; // Gets set later, ignore user value
571     int mod = job->modulus;
572     double aspect = title->aspect;
573
574     /* Gotta handle bounding dimensions differently
575        than for non-anamorphic encodes:
576        If the width is too big, just reset it with no rescaling.
577        Instead of using the aspect-scaled job height,
578        we need to see if the job width divided by the storage aspect
579        is bigger than the max. If so, set it to the max (this is sloppy).
580        If not, set job height to job width divided by storage aspect.
581     */
582
583     if ( job->maxWidth && (job->maxWidth < job->width) )
584             width = job->maxWidth;
585
586     height = (double)width / storage_aspect;
587     if ( job->maxHeight && (job->maxHeight < height) )
588     {
589         height = job->maxHeight;
590     }
591     else
592     {
593         height = (double)width / storage_aspect;
594     }
595
596
597     /* Time to get picture dimensions that divide cleanly.
598        These variables will store temporary dimensions as we iterate. */
599     int i, w, h;
600
601     /* In case the user specified a modulus, use it */
602     if (job->modulus)
603         mod = job->modulus;
604     else
605         mod = 16;
606
607     /* Iterate through multiples of mod to find one close to job->width. */
608     for( i = 1;; i++ )
609     {
610         w = mod * i;
611
612         if (w < width)
613         {
614             if ( ( width - w ) <= ( mod / 2 ) )
615                 /* We'll take a width that's
616                    smaller, but close enough. */
617                 break;
618         }
619         if (w == width)
620             /* Mod 16 dimensions, how nice! */
621             break;
622         if( w > width )
623         {
624             if ( ( w - width ) < (mod/2) )
625                 /* We'll take a width that's bigger, if we have to. */
626                 break;
627         }
628     }
629     width  = mod * (i);
630
631     /* Now do the same for a mod-friendly value near job->height. */
632     for( i = 1;; i++)
633     {
634         h = i * mod;
635
636         if (h < height)
637             {
638                 if ( ( height - h ) <= ( mod / 2 ))
639                     /* Go with a smaller height,
640                        if it's close enough.    */
641                     break;
642             }
643         if (h == height)
644             /* Mod 16 dimensions, how nice! */
645             break;
646
647         if ( h > height)
648         {
649             if ( ( h - height ) < ( mod / 2 ))
650                 /* Use a taller height if necessary */
651                 break;
652         }
653     }
654     height = mod  * (i);
655
656     int pixel_aspect_width = job->pixel_aspect_width;
657     int pixel_aspect_height = job->pixel_aspect_height;
658     
659     /* If a source was really 704*480 and hard matted with cropping
660        to 720*480, replace the PAR values with the ITU broadcast ones. */
661     if (title->width == 720 && cropped_width <= 706)
662     {
663         // convert aspect to a scaled integer so we can test for 16:9 & 4:3
664         // aspect ratios ignoring insignificant differences in the LSBs of
665         // the floating point representation.
666         int iaspect = aspect * 9.;
667
668         /* Handle ITU PARs */
669         if (title->height == 480)
670         {
671             /* It's NTSC */
672             if (iaspect == 16)
673             {
674                 /* It's widescreen */
675                 pixel_aspect_width = 40;
676                 pixel_aspect_height = 33;
677             }
678             else if (iaspect == 12)
679             {
680                 /* It's 4:3 */
681                 pixel_aspect_width = 10;
682                 pixel_aspect_height = 11;
683             }
684         }
685         else if (title->height == 576)
686         {
687             /* It's PAL */
688             if(iaspect == 16)
689             {
690                 /* It's widescreen */
691                 pixel_aspect_width = 16;
692                 pixel_aspect_height = 11;
693             }
694             else if (iaspect == 12)
695             {
696                 /* It's 4:3 */
697                 pixel_aspect_width = 12;
698                 pixel_aspect_height = 11;
699             }
700         }
701     }
702
703     /* Figure out what dimensions the source would display at. */
704     int source_display_width = cropped_width * (double)pixel_aspect_width /
705                                (double)pixel_aspect_height ;
706
707     /* The film AR is the source's display width / cropped source height.
708        The output display width is the output height * film AR.
709        The output PAR is the output display width / output storage width. */
710     pixel_aspect_width = height * source_display_width / cropped_height;
711     pixel_aspect_height = width;
712
713     /* Pass the results back to the caller */
714     *output_width = width;
715     *output_height = height;
716
717     /* While x264 is smart enough to reduce fractions on its own, libavcodec
718        needs some help with the math, so lose superfluous factors.            */
719     hb_reduce( output_par_width, output_par_height,
720                pixel_aspect_width, pixel_aspect_height );
721 }
722
723 /**
724  * Calculates job width, height, and cropping parameters.
725  * @param job Handle to hb_job_t.
726  * @param aspect Desired aspect ratio. Value of -1 uses title aspect.
727  * @param pixels Maximum desired pixel count.
728  */
729 void hb_set_size( hb_job_t * job, double aspect, int pixels )
730 {
731     hb_title_t * title = job->title;
732
733     int croppedWidth  = title->width - title->crop[2] - title->crop[3];
734     int croppedHeight = title->height - title->crop[0] - title->crop[1];
735     double croppedAspect = title->aspect * title->height * croppedWidth /
736                            croppedHeight / title->width;
737     int addCrop;
738     int i, w, h;
739
740     if( aspect <= 0 )
741     {
742         /* Keep the best possible aspect ratio */
743         aspect = croppedAspect;
744     }
745
746     /* Crop if necessary to obtain the desired ratio */
747     memcpy( job->crop, title->crop, 4 * sizeof( int ) );
748     if( aspect < croppedAspect )
749     {
750         /* Need to crop on the left and right */
751         addCrop = croppedWidth - aspect * croppedHeight * title->width /
752                     title->aspect / title->height;
753         if( addCrop & 3 )
754         {
755             addCrop = ( addCrop + 1 ) / 2;
756             job->crop[2] += addCrop;
757             job->crop[3] += addCrop;
758         }
759         else if( addCrop & 2 )
760         {
761             addCrop /= 2;
762             job->crop[2] += addCrop - 1;
763             job->crop[3] += addCrop + 1;
764         }
765         else
766         {
767             addCrop /= 2;
768             job->crop[2] += addCrop;
769             job->crop[3] += addCrop;
770         }
771     }
772     else if( aspect > croppedAspect )
773     {
774         /* Need to crop on the top and bottom */
775         addCrop = croppedHeight - croppedWidth * title->aspect *
776             title->height / aspect / title->width;
777         if( addCrop & 3 )
778         {
779             addCrop = ( addCrop + 1 ) / 2;
780             job->crop[0] += addCrop;
781             job->crop[1] += addCrop;
782         }
783         else if( addCrop & 2 )
784         {
785             addCrop /= 2;
786             job->crop[0] += addCrop - 1;
787             job->crop[1] += addCrop + 1;
788         }
789         else
790         {
791             addCrop /= 2;
792             job->crop[0] += addCrop;
793             job->crop[1] += addCrop;
794         }
795     }
796
797     /* Compute a resolution from the number of pixels and aspect */
798     for( i = 0;; i++ )
799     {
800         w = 16 * i;
801         h = MULTIPLE_16( (int)( (double)w / aspect ) );
802         if( w * h > pixels )
803         {
804             break;
805         }
806     }
807     i--;
808     job->width  = 16 * i;
809     job->height = MULTIPLE_16( (int)( (double)job->width / aspect ) );
810 }
811
812 /**
813  * Returns the number of jobs in the queue.
814  * @param h Handle to hb_handle_t.
815  * @return Number of jobs.
816  */
817 int hb_count( hb_handle_t * h )
818 {
819     return hb_list_count( h->jobs );
820 }
821
822 /**
823  * Returns handle to job at index i within the job list.
824  * @param h Handle to hb_handle_t.
825  * @param i Index of job.
826  * @returns Handle to hb_job_t of desired job.
827  */
828 hb_job_t * hb_job( hb_handle_t * h, int i )
829 {
830     return hb_list_item( h->jobs, i );
831 }
832
833 hb_job_t * hb_current_job( hb_handle_t * h )
834 {
835     return( h->current_job );
836 }
837
838 /**
839  * Adds a job to the job list.
840  * @param h Handle to hb_handle_t.
841  * @param job Handle to hb_job_t.
842  */
843 void hb_add( hb_handle_t * h, hb_job_t * job )
844 {
845     hb_job_t      * job_copy;
846     hb_title_t    * title,    * title_copy;
847     hb_chapter_t  * chapter,  * chapter_copy;
848     hb_audio_t    * audio;
849     hb_subtitle_t * subtitle, * subtitle_copy;
850     int             i;
851     char            audio_lang[4];
852
853     /* Copy the title */
854     title      = job->title;
855     title_copy = malloc( sizeof( hb_title_t ) );
856     memcpy( title_copy, title, sizeof( hb_title_t ) );
857
858     title_copy->list_chapter = hb_list_init();
859     for( i = 0; i < hb_list_count( title->list_chapter ); i++ )
860     {
861         chapter      = hb_list_item( title->list_chapter, i );
862         chapter_copy = malloc( sizeof( hb_chapter_t ) );
863         memcpy( chapter_copy, chapter, sizeof( hb_chapter_t ) );
864         hb_list_add( title_copy->list_chapter, chapter_copy );
865     }
866
867     /* Copy the audio track(s) we want */
868     title_copy->list_audio = hb_list_init();
869
870     /* Do nothing about audio during first pass */
871     if( job->pass == 0 || job->pass == 2 )
872     {
873         for( i = 0; i < hb_list_count(job->list_audio); i++ )
874         {
875             if( ( audio = hb_list_item( job->list_audio, i ) ) )
876             {
877                 hb_list_add( title_copy->list_audio, hb_audio_copy(audio) );
878             }
879         }
880     }
881
882     title_copy->list_subtitle = hb_list_init();
883
884     /*
885      * The following code is confusing, there are three ways in which
886      * we select subtitles and it depends on whether this is single or
887      * two pass mode.
888      *
889      * subtitle_scan may be enabled, in which case the first pass
890      * scans all subtitles of that language. The second pass does not
891      * select any because they are set at the end of the first pass.
892      *
893      * native_language may have a preferred language, in which case we
894      * may be switching the language we want for the subtitles in the
895      * first pass of a single pass, or the second pass of a two pass.
896      *
897      * We may have manually selected a subtitle, in which case that is
898      * selected in the first pass of a single pass, or the second of a
899      * two pass.
900      */
901     memset( audio_lang, 0, sizeof( audio_lang ) );
902
903     if ( job->indepth_scan || job->native_language ) {
904
905         /*
906          * Find the first audio language that is being encoded
907          */
908         for( i = 0; i < hb_list_count(job->list_audio); i++ )
909         {
910             if( ( audio = hb_list_item( job->list_audio, i ) ) )
911             {
912                 strncpy(audio_lang, audio->config.lang.iso639_2, sizeof(audio_lang));
913                 break;
914             }
915         }
916
917         /*
918          * In all cases switch the language if we need to to our native
919          * language.
920          */
921         if( job->native_language )
922         {
923             if( strncasecmp( job->native_language, audio_lang,
924                              sizeof( audio_lang ) ) != 0 )
925             {
926
927                 if( job->pass != 2 )
928                 {
929                     hb_log( "Enabled subtitles in native language '%s', audio is in '%s'",
930                             job->native_language, audio_lang);
931                 }
932                 /*
933                  * The main audio track is not in our native language, so switch
934                  * the subtitles to use our native language instead.
935                  */
936                 strncpy( audio_lang, job->native_language, sizeof( audio_lang ) );
937             } else {
938                 /*
939                  * native language is irrelevent, free it.
940                  */
941                 free( job->native_language );
942                 job->native_language = NULL;
943             }
944         }
945     }
946
947     /*
948      * If doing a subtitle scan then add all the matching subtitles for this
949      * language.
950      */
951     if ( job->indepth_scan )
952     {
953         for( i=0; i < hb_list_count( title->list_subtitle ); i++ )
954         {
955             subtitle = hb_list_item( title->list_subtitle, i );
956             if( strcmp( subtitle->iso639_2, audio_lang ) == 0 )
957             {
958                 /*
959                  * Matched subtitle language with audio language, so
960                  * add this to our list to scan.
961                  *
962                  * We will update the subtitle list on the second pass
963                  * later after the first pass has completed.
964                  */
965                 subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
966                 memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
967                 hb_list_add( title_copy->list_subtitle, subtitle_copy );
968                 if ( job->native_language ) {
969                     /*
970                      * With native language just select the
971                      * first match in our langiage, not all of
972                      * them. Subsequent ones are likely to be commentary
973                      */
974                     break;
975                 }
976             }
977         }
978     } else {
979         /*
980          * Not doing a subtitle scan in this pass, but maybe we are in the
981          * first pass?
982          */
983         if( job->select_subtitle )
984         {
985             /*
986              * Don't add subtitles here, we'll add them via select_subtitle
987              * at the end of the subtitle_scan.
988              */
989         } else {
990             /*
991              * Definitely not doing a subtitle scan.
992              */
993             if( job->pass != 1 && job->native_language )
994             {
995                 /*
996                  * We are not doing a subtitle scan but do want the
997                  * native langauge subtitle selected, so select it
998                  * for pass 0 or pass 2 of a two pass.
999                  */
1000                 for( i=0; i < hb_list_count( title->list_subtitle ); i++ )
1001                 {
1002                     subtitle = hb_list_item( title->list_subtitle, i );
1003                     if( strcmp( subtitle->iso639_2, audio_lang ) == 0 )
1004                     {
1005                         /*
1006                          * Matched subtitle language with audio language, so
1007                          * add this to our list to scan.
1008                          */
1009                         subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
1010                         memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
1011                         hb_list_add( title_copy->list_subtitle, subtitle_copy );
1012                         break;
1013                     }
1014                 }
1015             } else {
1016                 /*
1017                  * Manually selected subtitle, in which case only
1018                  * bother adding them for pass 0 or pass 2 of a two
1019                  * pass.
1020                  */
1021                 if( job->pass != 1 )
1022                 {
1023                     if( ( subtitle = hb_list_item( title->list_subtitle, job->subtitle ) ) )
1024                     {
1025                         subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
1026                         memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
1027                         hb_list_add( title_copy->list_subtitle, subtitle_copy );
1028                     }
1029                 }
1030             }
1031         }
1032     }
1033
1034     /* Copy the job */
1035     job_copy        = calloc( sizeof( hb_job_t ), 1 );
1036     memcpy( job_copy, job, sizeof( hb_job_t ) );
1037     title_copy->job = job_copy;
1038     job_copy->title = title_copy;
1039     job_copy->list_audio = title_copy->list_audio;
1040     job_copy->file  = strdup( job->file );
1041     job_copy->h     = h;
1042     job_copy->pause = h->pause_lock;
1043
1044     /* Copy the job filter list */
1045     if( job->filters )
1046     {
1047         int i;
1048         int filter_count = hb_list_count( job->filters );
1049         job_copy->filters = hb_list_init();
1050         for( i = 0; i < filter_count; i++ )
1051         {
1052             /*
1053              * Copy the filters, since the MacGui reuses the global filter objects
1054              * meaning that queued up jobs overwrite the previous filter settings.
1055              * In reality, settings is probably the only field that needs duplicating
1056              * since it's the only value that is ever changed. But name is duplicated
1057              * as well for completeness. Not copying private_data since it gets
1058              * created for each job in renderInit.
1059              */
1060             hb_filter_object_t * filter = hb_list_item( job->filters, i );
1061             hb_filter_object_t * filter_copy = malloc( sizeof( hb_filter_object_t ) );
1062             memcpy( filter_copy, filter, sizeof( hb_filter_object_t ) );
1063             if( filter->name )
1064                 filter_copy->name = strdup( filter->name );
1065             if( filter->settings )
1066                 filter_copy->settings = strdup( filter->settings );
1067             hb_list_add( job_copy->filters, filter_copy );
1068         }
1069     }
1070
1071     /* Add the job to the list */
1072     hb_list_add( h->jobs, job_copy );
1073     h->job_count = hb_count(h);
1074     h->job_count_permanent++;
1075 }
1076
1077 /**
1078  * Removes a job from the job list.
1079  * @param h Handle to hb_handle_t.
1080  * @param job Handle to hb_job_t.
1081  */
1082 void hb_rem( hb_handle_t * h, hb_job_t * job )
1083 {
1084     hb_list_rem( h->jobs, job );
1085
1086     h->job_count = hb_count(h);
1087     if (h->job_count_permanent)
1088         h->job_count_permanent--;
1089
1090     /* XXX free everything XXX */
1091 }
1092
1093 /**
1094  * Starts the conversion process.
1095  * Sets state to HB_STATE_WORKING.
1096  * calls hb_work_init, to launch work thread. Stores handle to work thread.
1097  * @param h Handle to hb_handle_t.
1098  */
1099 void hb_start( hb_handle_t * h )
1100 {
1101     /* XXX Hack */
1102     h->job_count = hb_list_count( h->jobs );
1103     h->job_count_permanent = h->job_count;
1104
1105     hb_lock( h->state_lock );
1106     h->state.state = HB_STATE_WORKING;
1107 #define p h->state.param.working
1108     p.progress  = 0.0;
1109     p.job_cur   = 1;
1110     p.job_count = h->job_count;
1111     p.rate_cur  = 0.0;
1112     p.rate_avg  = 0.0;
1113     p.hours     = -1;
1114     p.minutes   = -1;
1115     p.seconds   = -1;
1116     p.sequence_id = 0;
1117 #undef p
1118     hb_unlock( h->state_lock );
1119
1120     h->paused = 0;
1121
1122     h->work_die    = 0;
1123     h->work_thread = hb_work_init( h->jobs, h->cpu_count,
1124                                    &h->work_die, &h->work_error, &h->current_job );
1125 }
1126
1127 /**
1128  * Pauses the conversion process.
1129  * @param h Handle to hb_handle_t.
1130  */
1131 void hb_pause( hb_handle_t * h )
1132 {
1133     if( !h->paused )
1134     {
1135         hb_lock( h->pause_lock );
1136         h->paused = 1;
1137
1138         hb_lock( h->state_lock );
1139         h->state.state = HB_STATE_PAUSED;
1140         hb_unlock( h->state_lock );
1141     }
1142 }
1143
1144 /**
1145  * Resumes the conversion process.
1146  * @param h Handle to hb_handle_t.
1147  */
1148 void hb_resume( hb_handle_t * h )
1149 {
1150     if( h->paused )
1151     {
1152         hb_unlock( h->pause_lock );
1153         h->paused = 0;
1154     }
1155 }
1156
1157 /**
1158  * Stops the conversion process.
1159  * @param h Handle to hb_handle_t.
1160  */
1161 void hb_stop( hb_handle_t * h )
1162 {
1163     h->work_die = 1;
1164
1165     h->job_count = hb_count(h);
1166     h->job_count_permanent = 0;
1167
1168     hb_resume( h );
1169 }
1170
1171 /**
1172  * Returns the state of the conversion process.
1173  * @param h Handle to hb_handle_t.
1174  * @param s Handle to hb_state_t which to copy the state data.
1175  */
1176 void hb_get_state( hb_handle_t * h, hb_state_t * s )
1177 {
1178     hb_lock( h->state_lock );
1179
1180     memcpy( s, &h->state, sizeof( hb_state_t ) );
1181     if ( h->state.state == HB_STATE_SCANDONE || h->state.state == HB_STATE_WORKDONE )
1182         h->state.state = HB_STATE_IDLE;
1183
1184     hb_unlock( h->state_lock );
1185 }
1186
1187 void hb_get_state2( hb_handle_t * h, hb_state_t * s )
1188 {
1189     hb_lock( h->state_lock );
1190
1191     memcpy( s, &h->state, sizeof( hb_state_t ) );
1192
1193     hb_unlock( h->state_lock );
1194 }
1195
1196 /**
1197  * Called in MacGui in UpdateUI to check
1198  *  for a new scan being completed to set a new source
1199  */
1200 int hb_get_scancount( hb_handle_t * h)
1201  {
1202      return h->scanCount;
1203  }
1204
1205 /**
1206  * Closes access to libhb by freeing the hb_handle_t handle ontained in hb_init_real.
1207  * @param _h Pointer to handle to hb_handle_t.
1208  */
1209 void hb_close( hb_handle_t ** _h )
1210 {
1211     hb_handle_t * h = *_h;
1212     hb_title_t * title;
1213
1214     h->die = 1;
1215     hb_thread_close( &h->main_thread );
1216
1217     while( ( title = hb_list_item( h->list_title, 0 ) ) )
1218     {
1219         hb_list_rem( h->list_title, title );
1220         if( title->job && title->job->filters )
1221         {
1222             hb_list_close( &title->job->filters );
1223         }
1224         free( title->job );
1225         hb_title_close( &title );
1226     }
1227     hb_list_close( &h->list_title );
1228
1229     hb_list_close( &h->jobs );
1230     hb_lock_close( &h->state_lock );
1231     hb_lock_close( &h->pause_lock );
1232     free( h );
1233     *_h = NULL;
1234
1235 }
1236
1237 /**
1238  * Monitors the state of the update, scan, and work threads.
1239  * Sets scan done state when scan thread exits.
1240  * Sets work done state when work thread exits.
1241  * @param _h Handle to hb_handle_t
1242  */
1243 static void thread_func( void * _h )
1244 {
1245     hb_handle_t * h = (hb_handle_t *) _h;
1246     char dirname[1024];
1247     DIR * dir;
1248     struct dirent * entry;
1249
1250     h->pid = getpid();
1251
1252     /* Create folder for temporary files */
1253     memset( dirname, 0, 1024 );
1254     hb_get_tempory_directory( h, dirname );
1255
1256     hb_mkdir( dirname );
1257
1258     while( !h->die )
1259     {
1260         /* In case the check_update thread hangs, it'll die sooner or
1261            later. Then, we join it here */
1262         if( h->update_thread &&
1263             hb_thread_has_exited( h->update_thread ) )
1264         {
1265             hb_thread_close( &h->update_thread );
1266         }
1267
1268         /* Check if the scan thread is done */
1269         if( h->scan_thread &&
1270             hb_thread_has_exited( h->scan_thread ) )
1271         {
1272             hb_thread_close( &h->scan_thread );
1273
1274             hb_log( "libhb: scan thread found %d valid title(s)",
1275                     hb_list_count( h->list_title ) );
1276             hb_lock( h->state_lock );
1277             h->state.state = HB_STATE_SCANDONE; //originally state.state
1278                         hb_unlock( h->state_lock );
1279                         /*we increment this sessions scan count by one for the MacGui
1280                         to trigger a new source being set */
1281             h->scanCount++;
1282         }
1283
1284         /* Check if the work thread is done */
1285         if( h->work_thread &&
1286             hb_thread_has_exited( h->work_thread ) )
1287         {
1288             hb_thread_close( &h->work_thread );
1289
1290             hb_log( "libhb: work result = %d",
1291                     h->work_error );
1292             hb_lock( h->state_lock );
1293             h->state.state                = HB_STATE_WORKDONE;
1294             h->state.param.workdone.error = h->work_error;
1295
1296             h->job_count = hb_count(h);
1297             if (h->job_count < 1)
1298                 h->job_count_permanent = 0;
1299             hb_unlock( h->state_lock );
1300         }
1301
1302         hb_snooze( 50 );
1303     }
1304
1305     if( h->work_thread )
1306     {
1307         hb_stop( h );
1308         hb_thread_close( &h->work_thread );
1309     }
1310
1311     /* Remove temp folder */
1312     dir = opendir( dirname );
1313     while( ( entry = readdir( dir ) ) )
1314     {
1315         char filename[1024];
1316         if( entry->d_name[0] == '.' )
1317         {
1318             continue;
1319         }
1320         memset( filename, 0, 1024 );
1321         snprintf( filename, 1023, "%s/%s", dirname, entry->d_name );
1322         unlink( filename );
1323     }
1324     closedir( dir );
1325     rmdir( dirname );
1326 }
1327
1328 /**
1329  * Returns the PID.
1330  * @param h Handle to hb_handle_t
1331  */
1332 int hb_get_pid( hb_handle_t * h )
1333 {
1334     return h->pid;
1335 }
1336
1337 /**
1338  * Sets the current state.
1339  * @param h Handle to hb_handle_t
1340  * @param s Handle to new hb_state_t
1341  */
1342 void hb_set_state( hb_handle_t * h, hb_state_t * s )
1343 {
1344     hb_lock( h->pause_lock );
1345     hb_lock( h->state_lock );
1346     memcpy( &h->state, s, sizeof( hb_state_t ) );
1347     if( h->state.state == HB_STATE_WORKING )
1348     {
1349         /* XXX Hack */
1350         if (h->job_count < 1)
1351             h->job_count_permanent = 1;
1352
1353         h->state.param.working.job_cur =
1354             h->job_count_permanent - hb_list_count( h->jobs );
1355         h->state.param.working.job_count = h->job_count_permanent;
1356
1357         // Set which job is being worked on
1358         if (h->current_job)
1359             h->state.param.working.sequence_id = h->current_job->sequence_id;
1360         else
1361             h->state.param.working.sequence_id = 0;
1362     }
1363     hb_unlock( h->state_lock );
1364     hb_unlock( h->pause_lock );
1365 }