OSDN Git Service

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