OSDN Git Service

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