OSDN Git Service

Stage 1 Soft Subtitle Support - Allow multiple subtitle tracks to be selected, and...
[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  * Deletes current previews associated with titles
299  * @param h Handle to hb_handle_t
300  */
301 void hb_remove_previews( hb_handle_t * h )
302 {
303     char            filename[1024];
304     char            dirname[1024];
305     hb_title_t    * title;
306     int             i, count, len;
307     DIR           * dir;
308     struct dirent * entry;
309
310     memset( dirname, 0, 1024 );
311     hb_get_tempory_directory( h, dirname );
312     dir = opendir( dirname );
313     if (dir == NULL) return;
314
315     count = hb_list_count( h->list_title );
316     while( ( entry = readdir( dir ) ) )
317     {
318         if( entry->d_name[0] == '.' )
319         {
320             continue;
321         }
322         for( i = 0; i < count; i++ )
323         {
324             title = hb_list_item( h->list_title, i );
325             len = snprintf( filename, 1024, "%" PRIxPTR, (intptr_t) title );
326             if (strncmp(entry->d_name, filename, len) == 0)
327             {
328                 snprintf( filename, 1024, "%s/%s", dirname, entry->d_name );
329                 unlink( filename );
330                 break;
331             }
332         }
333     }
334     closedir( dir );
335 }
336
337 /**
338  * Initializes a scan of the by calling hb_scan_init
339  * @param h Handle to hb_handle_t
340  * @param path location of VIDEO_TS folder.
341  * @param title_index Desired title to scan.  0 for all titles.
342  * @param preview_count Number of preview images to generate.
343  * @param store_previews Whether or not to write previews to disk.
344  */
345 void hb_scan( hb_handle_t * h, const char * path, int title_index,
346               int preview_count, int store_previews )
347 {
348     hb_title_t * title;
349
350     /* Clean up from previous scan */
351     hb_remove_previews( h );
352     while( ( title = hb_list_item( h->list_title, 0 ) ) )
353     {
354         hb_list_rem( h->list_title, title );
355         hb_title_close( &title );
356     }
357
358     hb_log( "hb_scan: path=%s, title_index=%d", path, title_index );
359     h->scan_thread = hb_scan_init( h, path, title_index, h->list_title,
360                                    preview_count, store_previews );
361 }
362
363 /**
364  * Returns the list of titles found.
365  * @param h Handle to hb_handle_t
366  * @return Handle to hb_list_t of the title list.
367  */
368 hb_list_t * hb_get_titles( hb_handle_t * h )
369 {
370     return h->list_title;
371 }
372
373 /**
374  * Create preview image of desired title a index of picture.
375  * @param h Handle to hb_handle_t.
376  * @param title Handle to hb_title_t of desired title.
377  * @param picture Index in title.
378  * @param buffer Handle to buufer were inage will be drawn.
379  */
380 void hb_get_preview( hb_handle_t * h, hb_title_t * title, int picture,
381                      uint8_t * buffer )
382 {
383     hb_job_t           * job = title->job;
384     char                 filename[1024];
385     FILE               * file;
386     uint8_t            * buf1, * buf2, * buf3, * buf4, * pen;
387     uint32_t           * p32, swsflags;
388     AVPicture            pic_in, pic_preview, pic_deint, pic_crop, pic_scale;
389     struct SwsContext  * context;
390     int                  i;
391     int                  rgb_width = ((job->width + 7) >> 3) << 3;
392     int                  preview_size;
393
394     swsflags = SWS_LANCZOS | SWS_ACCURATE_RND;
395
396     buf1 = av_malloc( avpicture_get_size( PIX_FMT_YUV420P, title->width, title->height ) );
397     buf2 = av_malloc( avpicture_get_size( PIX_FMT_YUV420P, title->width, title->height ) );
398     buf3 = av_malloc( avpicture_get_size( PIX_FMT_YUV420P, job->width, job->height ) );
399     buf4 = av_malloc( avpicture_get_size( PIX_FMT_RGBA32, rgb_width, job->height ) );
400     avpicture_fill( &pic_in, buf1, PIX_FMT_YUV420P,
401                     title->width, title->height );
402     avpicture_fill( &pic_deint, buf2, PIX_FMT_YUV420P,
403                     title->width, title->height );
404     avpicture_fill( &pic_scale, buf3, PIX_FMT_YUV420P,
405                     job->width, job->height );
406     avpicture_fill( &pic_preview, buf4, PIX_FMT_RGBA32,
407                     rgb_width, job->height );
408
409     // Allocate the AVPicture frames and fill in
410
411     memset( filename, 0, 1024 );
412
413     hb_get_tempory_filename( h, filename, "%" PRIxPTR "%d",
414                              (intptr_t) title, picture );
415
416     file = fopen( filename, "r" );
417     if( !file )
418     {
419         hb_log( "hb_get_preview: fopen failed" );
420         return;
421     }
422
423     fread( buf1, avpicture_get_size( PIX_FMT_YUV420P, title->width, title->height), 1, file );
424     fclose( file );
425
426     if( job->deinterlace )
427     {
428         // Deinterlace and crop
429         avpicture_deinterlace( &pic_deint, &pic_in, PIX_FMT_YUV420P, title->width, title->height );
430         av_picture_crop( &pic_crop, &pic_deint, PIX_FMT_YUV420P, job->crop[0], job->crop[2] );
431     }
432     else
433     {
434         // Crop
435         av_picture_crop( &pic_crop, &pic_in, PIX_FMT_YUV420P, job->crop[0], job->crop[2] );
436     }
437
438     // Get scaling context
439     context = sws_getContext(title->width  - (job->crop[2] + job->crop[3]),
440                              title->height - (job->crop[0] + job->crop[1]),
441                              PIX_FMT_YUV420P,
442                              job->width, job->height, PIX_FMT_YUV420P,
443                              swsflags, NULL, NULL, NULL);
444
445     // Scale
446     sws_scale(context,
447               pic_crop.data, pic_crop.linesize,
448               0, title->height - (job->crop[0] + job->crop[1]),
449               pic_scale.data, pic_scale.linesize);
450
451     // Free context
452     sws_freeContext( context );
453
454     // Get preview context
455     context = sws_getContext(rgb_width, job->height, PIX_FMT_YUV420P,
456                               rgb_width, job->height, PIX_FMT_RGBA32,
457                               swsflags, NULL, NULL, NULL);
458
459     // Create preview
460     sws_scale(context,
461               pic_scale.data, pic_scale.linesize,
462               0, job->height,
463               pic_preview.data, pic_preview.linesize);
464
465     // Free context
466     sws_freeContext( context );
467
468     if( job->height < title->height || job->width < title->width )
469     {
470         /* Gray background */
471         p32 = (uint32_t *) buffer;
472         for( i = 0; i < ( title->width + 2 ) * ( title->height + 2 ); i++ )
473         {
474             p32[i] = 0xFF808080;
475         }
476
477         /* Draw the picture, centered, and draw the cropping zone */
478         preview_size = pic_preview.linesize[0];
479         pen = buffer + ( title->height - job->height ) *
480             ( title->width + 2 ) * 2 + ( title->width - job->width ) * 2;
481         memset( pen, 0xFF, 4 * ( job->width + 2 ) );
482         pen += 4 * ( title->width + 2 );
483         for( i = 0; i < job->height; i++ )
484         {
485             uint8_t * nextLine;
486             nextLine = pen + 4 * ( title->width + 2 );
487             memset( pen, 0xFF, 4 );
488             pen += 4;
489             memcpy( pen, buf4 + preview_size * i, 4 * job->width );
490             pen += 4 * job->width;
491             memset( pen, 0xFF, 4 );
492             pen = nextLine;
493         }
494         memset( pen, 0xFF, 4 * ( job->width + 2 ) );
495     }
496
497     // Clean up
498     avpicture_free( &pic_preview );
499     avpicture_free( &pic_scale );
500     avpicture_free( &pic_deint );
501     avpicture_free( &pic_in );
502 }
503
504  /**
505  * Analyzes a frame to detect interlacing artifacts
506  * and returns true if interlacing (combing) is found.
507  *
508  * Code taken from Thomas Oestreich's 32detect filter
509  * in the Transcode project, with minor formatting changes.
510  *
511  * @param buf         An hb_buffer structure holding valid frame data
512  * @param width       The frame's width in pixels
513  * @param height      The frame's height in pixels
514  * @param color_equal Sensitivity for detecting similar colors
515  * @param color_diff  Sensitivity for detecting different colors
516  * @param threshold   Sensitivity for flagging planes as combed
517  * @param prog_equal  Sensitivity for detecting similar colors on progressive frames
518  * @param prog_diff   Sensitivity for detecting different colors on progressive frames
519  * @param prog_threshold Sensitivity for flagging progressive frames as combed
520  */
521 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 )
522 {
523     int j, k, n, off, cc_1, cc_2, cc[3];
524         // int flag[3] ; // debugging flag
525     uint16_t s1, s2, s3, s4;
526     cc_1 = 0; cc_2 = 0;
527
528     int offset = 0;
529     
530     if ( buf->flags & 16 )
531     {
532         /* Frame is progressive, be more discerning. */
533         color_diff = prog_diff;
534         color_equal = prog_equal;
535         threshold = prog_threshold;
536     }
537
538     /* One pas for Y, one pass for Cb, one pass for Cr */    
539     for( k = 0; k < 3; k++ )
540     {
541         if( k == 1 )
542         {
543             /* Y has already been checked, now offset by Y's dimensions
544                and divide all the other values by 2, since Cr and Cb
545                are half-size compared to Y.                               */
546             offset = width * height;
547             width >>= 1;
548             height >>= 1;
549         }
550         else if ( k == 2 )
551         {
552             /* Y and Cb are done, so the offset needs to be bumped
553                so it's width*height + (width / 2) * (height / 2)  */
554             offset *= 5/4;
555         }
556
557         for( j = 0; j < width; ++j )
558         {
559             off = 0;
560
561             for( n = 0; n < ( height - 4 ); n = n + 2 )
562             {
563                 /* Look at groups of 4 sequential horizontal lines */
564                 s1 = ( ( buf->data + offset )[ off + j             ] & 0xff );
565                 s2 = ( ( buf->data + offset )[ off + j + width     ] & 0xff );
566                 s3 = ( ( buf->data + offset )[ off + j + 2 * width ] & 0xff );
567                 s4 = ( ( buf->data + offset )[ off + j + 3 * width ] & 0xff );
568
569                 /* Note if the 1st and 2nd lines are more different in
570                    color than the 1st and 3rd lines are similar in color.*/
571                 if ( ( abs( s1 - s3 ) < color_equal ) &&
572                      ( abs( s1 - s2 ) > color_diff ) )
573                         ++cc_1;
574
575                 /* Note if the 2nd and 3rd lines are more different in
576                    color than the 2nd and 4th lines are similar in color.*/
577                 if ( ( abs( s2 - s4 ) < color_equal ) &&
578                      ( abs( s2 - s3 ) > color_diff) )
579                         ++cc_2;
580
581                 /* Now move down 2 horizontal lines before starting over.*/
582                 off += 2 * width;
583             }
584         }
585
586         // compare results
587         /*  The final cc score for a plane is the percentage of combed pixels it contains.
588             Because sensitivity goes down to hundreths of a percent, multiply by 1000
589             so it will be easy to compare against the threhold value which is an integer. */
590         cc[k] = (int)( ( cc_1 + cc_2 ) * 1000.0 / ( width * height ) );
591     }
592
593
594     /* HandBrake is all yuv420, so weight the average percentage of all 3 planes accordingly.*/
595     int average_cc = ( 2 * cc[0] + ( cc[1] / 2 ) + ( cc[2] / 2 ) ) / 3;
596     
597     /* Now see if that average percentage of combed pixels surpasses the threshold percentage given by the user.*/
598     if( average_cc > threshold )
599     {
600 #if 0
601             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" );
602 #endif
603         return 1;
604     }
605
606 #if 0
607     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" );
608 #endif
609
610     /* Reaching this point means no combing detected. */
611     return 0;
612
613 }
614
615 /**
616  * Calculates job width and height for anamorphic content,
617  *
618  * @param job Handle to hb_job_t
619  * @param output_width Pointer to returned storage width
620  * @param output_height Pointer to returned storage height
621  * @param output_par_width Pointer to returned pixel width
622  @ param output_par_height Pointer to returned pixel height
623  */
624 void hb_set_anamorphic_size( hb_job_t * job,
625         int *output_width, int *output_height,
626         int *output_par_width, int *output_par_height )
627 {
628     /* Set up some variables to make the math easier to follow. */
629     hb_title_t * title = job->title;
630     int cropped_width = title->width - job->crop[2] - job->crop[3] ;
631     int cropped_height = title->height - job->crop[0] - job->crop[1] ;
632     double storage_aspect = (double)cropped_width / (double)cropped_height;
633     int mod = job->anamorphic.modulus ? job->anamorphic.modulus : 16;
634     double aspect = title->aspect;
635     
636     int pixel_aspect_width  = job->anamorphic.par_width;
637     int pixel_aspect_height = job->anamorphic.par_height;
638
639     /* If a source was really NTSC or PAL and the user specified ITU PAR
640        values, replace the standard PAR values with the ITU broadcast ones. */
641     if( title->width == 720 && job->anamorphic.itu_par )
642     {
643         // convert aspect to a scaled integer so we can test for 16:9 & 4:3
644         // aspect ratios ignoring insignificant differences in the LSBs of
645         // the floating point representation.
646         int iaspect = aspect * 9.;
647
648         /* Handle ITU PARs */
649         if (title->height == 480)
650         {
651             /* It's NTSC */
652             if (iaspect == 16)
653             {
654                 /* It's widescreen */
655                 pixel_aspect_width = 40;
656                 pixel_aspect_height = 33;
657             }
658             else if (iaspect == 12)
659             {
660                 /* It's 4:3 */
661                 pixel_aspect_width = 10;
662                 pixel_aspect_height = 11;
663             }
664         }
665         else if (title->height == 576)
666         {
667             /* It's PAL */
668             if(iaspect == 16)
669             {
670                 /* It's widescreen */
671                 pixel_aspect_width = 16;
672                 pixel_aspect_height = 11;
673             }
674             else if (iaspect == 12)
675             {
676                 /* It's 4:3 */
677                 pixel_aspect_width = 12;
678                 pixel_aspect_height = 11;
679             }
680         }
681     }
682
683     /* Figure out what width the source would display at. */
684     int source_display_width = cropped_width * (double)pixel_aspect_width /
685                                (double)pixel_aspect_height ;
686
687     /*
688        3 different ways of deciding output dimensions:
689         - 1: Strict anamorphic, preserve source dimensions
690         - 2: Loose anamorphic, round to mod16 and preserve storage aspect ratio
691         - 3: Power user anamorphic, specify everything
692     */
693     int width, height;
694     switch( job->anamorphic.mode )
695     {
696         case 1:
697             /* Strict anamorphic */
698             *output_width = cropped_width;
699             *output_height = cropped_height;
700             *output_par_width = title->pixel_aspect_width;
701             *output_par_height = title->pixel_aspect_height;
702         break;
703
704         case 2:
705             /* "Loose" anamorphic.
706                 - Uses mod16-compliant dimensions,
707                 - Allows users to set the width
708             */
709             width = job->width;
710             // height: Gets set later, ignore user job->height value
711
712             /* Gotta handle bounding dimensions.
713                If the width is too big, just reset it with no rescaling.
714                Instead of using the aspect-scaled job height,
715                we need to see if the job width divided by the storage aspect
716                is bigger than the max. If so, set it to the max (this is sloppy).
717                If not, set job height to job width divided by storage aspect.
718             */
719
720             if ( job->maxWidth && (job->maxWidth < job->width) )
721                 width = job->maxWidth;
722
723             /* Time to get picture width that divide cleanly.*/
724             width  = MULTIPLE_MOD( width, mod);
725
726             /* Verify these new dimensions don't violate max height and width settings */
727             if ( job->maxWidth && (job->maxWidth < job->width) )
728                 width = job->maxWidth;
729
730             height = ((double)width / storage_aspect) + 0.5;
731             
732             if ( job->maxHeight && (job->maxHeight < height) )
733                 height = job->maxHeight;
734
735             /* Time to get picture height that divide cleanly.*/
736             height = MULTIPLE_MOD( height, mod);
737
738             /* Verify these new dimensions don't violate max height and width settings */
739             if ( job->maxHeight && (job->maxHeight < height) )
740                 height = job->maxHeight;
741
742             /* The film AR is the source's display width / cropped source height.
743                The output display width is the output height * film AR.
744                The output PAR is the output display width / output storage width. */
745             pixel_aspect_width = height * source_display_width / cropped_height;
746             pixel_aspect_height = width;
747
748             /* Pass the results back to the caller */
749             *output_width = width;
750             *output_height = height;
751         break;
752             
753         case 3:
754             /* Anamorphic 3: Power User Jamboree
755                - Set everything based on specified values */
756             
757             /* Use specified storage dimensions */
758             width = job->width;
759             height = job->height;
760             
761             /* Bind to max dimensions */
762             if( job->maxWidth && width > job->maxWidth )
763                 width = job->maxWidth;
764             if( job->maxHeight && height > job->maxHeight )
765                 height = job->maxHeight;
766             
767             /* Time to get picture dimensions that divide cleanly.*/
768             width  = MULTIPLE_MOD( width, mod);
769             height = MULTIPLE_MOD( height, mod);
770             
771             /* Verify we're still within max dimensions */
772             if( job->maxWidth && width > job->maxWidth )
773                 width = job->maxWidth - (mod/2);
774             if( job->maxHeight && height > job->maxHeight )
775                 height = job->maxHeight - (mod/2);
776                 
777             /* Re-ensure we have picture dimensions that divide cleanly. */
778             width  = MULTIPLE_MOD( width, mod );
779             height = MULTIPLE_MOD( height, mod );
780             
781             /* That finishes the storage dimensions. On to display. */            
782             if( job->anamorphic.dar_width && job->anamorphic.dar_height )
783             {
784                 /* We need to adjust the PAR to produce this aspect. */
785                 pixel_aspect_width = height * job->anamorphic.dar_width / job->anamorphic.dar_height;
786                 pixel_aspect_height = width;
787             }
788             else
789             {
790                 /* We first need the display ar.
791                    That's the source display width divided by the source height after cropping.
792                    Then we multiple the output height by that to get the pixel aspect width,
793                    and the pixel aspect height is the storage width.*/
794                 pixel_aspect_width = height * source_display_width / cropped_height;
795                 pixel_aspect_height = width;
796             }
797             
798             /* Back to caller */
799             *output_width = width;
800             *output_height = height;
801         break;
802     }
803     
804     /* While x264 is smart enough to reduce fractions on its own, libavcodec
805        needs some help with the math, so lose superfluous factors.            */
806     hb_reduce( output_par_width, output_par_height,
807                pixel_aspect_width, pixel_aspect_height );
808 }
809
810 /**
811  * Calculates job width, height, and cropping parameters.
812  * @param job Handle to hb_job_t.
813  * @param aspect Desired aspect ratio. Value of -1 uses title aspect.
814  * @param pixels Maximum desired pixel count.
815  */
816 void hb_set_size( hb_job_t * job, double aspect, int pixels )
817 {
818     hb_title_t * title = job->title;
819
820     int croppedWidth  = title->width - title->crop[2] - title->crop[3];
821     int croppedHeight = title->height - title->crop[0] - title->crop[1];
822     double croppedAspect = title->aspect * title->height * croppedWidth /
823                            croppedHeight / title->width;
824     int addCrop;
825     int i, w, h;
826
827     if( aspect <= 0 )
828     {
829         /* Keep the best possible aspect ratio */
830         aspect = croppedAspect;
831     }
832
833     /* Crop if necessary to obtain the desired ratio */
834     memcpy( job->crop, title->crop, 4 * sizeof( int ) );
835     if( aspect < croppedAspect )
836     {
837         /* Need to crop on the left and right */
838         addCrop = croppedWidth - aspect * croppedHeight * title->width /
839                     title->aspect / title->height;
840         if( addCrop & 3 )
841         {
842             addCrop = ( addCrop + 1 ) / 2;
843             job->crop[2] += addCrop;
844             job->crop[3] += addCrop;
845         }
846         else if( addCrop & 2 )
847         {
848             addCrop /= 2;
849             job->crop[2] += addCrop - 1;
850             job->crop[3] += addCrop + 1;
851         }
852         else
853         {
854             addCrop /= 2;
855             job->crop[2] += addCrop;
856             job->crop[3] += addCrop;
857         }
858     }
859     else if( aspect > croppedAspect )
860     {
861         /* Need to crop on the top and bottom */
862         addCrop = croppedHeight - croppedWidth * title->aspect *
863             title->height / aspect / title->width;
864         if( addCrop & 3 )
865         {
866             addCrop = ( addCrop + 1 ) / 2;
867             job->crop[0] += addCrop;
868             job->crop[1] += addCrop;
869         }
870         else if( addCrop & 2 )
871         {
872             addCrop /= 2;
873             job->crop[0] += addCrop - 1;
874             job->crop[1] += addCrop + 1;
875         }
876         else
877         {
878             addCrop /= 2;
879             job->crop[0] += addCrop;
880             job->crop[1] += addCrop;
881         }
882     }
883
884     /* Compute a resolution from the number of pixels and aspect */
885     for( i = 0;; i++ )
886     {
887         w = 16 * i;
888         h = MULTIPLE_16( (int)( (double)w / aspect ) );
889         if( w * h > pixels )
890         {
891             break;
892         }
893     }
894     i--;
895     job->width  = 16 * i;
896     job->height = MULTIPLE_16( (int)( (double)job->width / aspect ) );
897 }
898
899 /**
900  * Returns the number of jobs in the queue.
901  * @param h Handle to hb_handle_t.
902  * @return Number of jobs.
903  */
904 int hb_count( hb_handle_t * h )
905 {
906     return hb_list_count( h->jobs );
907 }
908
909 /**
910  * Returns handle to job at index i within the job list.
911  * @param h Handle to hb_handle_t.
912  * @param i Index of job.
913  * @returns Handle to hb_job_t of desired job.
914  */
915 hb_job_t * hb_job( hb_handle_t * h, int i )
916 {
917     return hb_list_item( h->jobs, i );
918 }
919
920 hb_job_t * hb_current_job( hb_handle_t * h )
921 {
922     return( h->current_job );
923 }
924
925 /**
926  * Adds a job to the job list.
927  * @param h Handle to hb_handle_t.
928  * @param job Handle to hb_job_t.
929  */
930 void hb_add( hb_handle_t * h, hb_job_t * job )
931 {
932     hb_job_t      * job_copy;
933     hb_title_t    * title,    * title_copy;
934     hb_chapter_t  * chapter,  * chapter_copy;
935     hb_audio_t    * audio;
936     hb_subtitle_t * subtitle, * subtitle_copy;
937     int             i;
938     char            audio_lang[4];
939
940     /* Copy the title */
941     title      = job->title;
942     title_copy = malloc( sizeof( hb_title_t ) );
943     memcpy( title_copy, title, sizeof( hb_title_t ) );
944
945     title_copy->list_chapter = hb_list_init();
946     for( i = 0; i < hb_list_count( title->list_chapter ); i++ )
947     {
948         chapter      = hb_list_item( title->list_chapter, i );
949         chapter_copy = malloc( sizeof( hb_chapter_t ) );
950         memcpy( chapter_copy, chapter, sizeof( hb_chapter_t ) );
951         hb_list_add( title_copy->list_chapter, chapter_copy );
952     }
953
954     /*
955      * Copy the metadata
956      */
957     if( title->metadata )
958     {
959         title_copy->metadata = malloc( sizeof( hb_metadata_t ) );
960         
961         if( title_copy->metadata ) 
962         {
963             memcpy( title_copy->metadata, title->metadata, sizeof( hb_metadata_t ) );
964
965             /*
966              * Need to copy the artwork seperatly (TODO).
967              */
968             if( title->metadata->coverart )
969             {
970                 title_copy->metadata->coverart = malloc( title->metadata->coverart_size );
971                 if( title_copy->metadata->coverart )
972                 {
973                     memcpy( title_copy->metadata->coverart, title->metadata->coverart,
974                             title->metadata->coverart_size );
975                 } else {
976                     title_copy->metadata->coverart_size = 0; 
977                 }
978             }
979         }
980     }
981
982     /* Copy the audio track(s) we want */
983     title_copy->list_audio = hb_list_init();
984
985     for( i = 0; i < hb_list_count(job->list_audio); i++ )
986     {
987         if( ( audio = hb_list_item( job->list_audio, i ) ) )
988         {
989             hb_list_add( title_copy->list_audio, hb_audio_copy(audio) );
990         }
991     }
992
993     title_copy->list_subtitle = hb_list_init();
994
995     /*
996      * The following code is confusing, there are three ways in which
997      * we select subtitles and it depends on whether this is single or
998      * two pass mode.
999      *
1000      * subtitle_scan may be enabled, in which case the first pass
1001      * scans all subtitles of that language. The second pass does not
1002      * select any because they are set at the end of the first pass.
1003      *
1004      * native_language may have a preferred language, in which case we
1005      * may be switching the language we want for the subtitles in the
1006      * first pass of a single pass, or the second pass of a two pass.
1007      *
1008      * We may have manually selected a subtitle, in which case that is
1009      * selected in the first pass of a single pass, or the second of a
1010      * two pass.
1011      */
1012     memset( audio_lang, 0, sizeof( audio_lang ) );
1013
1014     if ( job->indepth_scan || job->native_language ) {
1015
1016         /*
1017          * Find the first audio language that is being encoded
1018          */
1019         for( i = 0; i < hb_list_count(job->list_audio); i++ )
1020         {
1021             if( ( audio = hb_list_item( job->list_audio, i ) ) )
1022             {
1023                 strncpy(audio_lang, audio->config.lang.iso639_2, sizeof(audio_lang));
1024                 break;
1025             }
1026         }
1027
1028         /*
1029          * In all cases switch the language if we need to to our native
1030          * language.
1031          */
1032         if( job->native_language )
1033         {
1034             if( strncasecmp( job->native_language, audio_lang,
1035                              sizeof( audio_lang ) ) != 0 )
1036             {
1037
1038                 if( job->pass != 2 )
1039                 {
1040                     hb_log( "Enabled subtitles in native language '%s', audio is in '%s'",
1041                             job->native_language, audio_lang);
1042                 }
1043                 /*
1044                  * The main audio track is not in our native language, so switch
1045                  * the subtitles to use our native language instead.
1046                  */
1047                 strncpy( audio_lang, job->native_language, sizeof( audio_lang ) );
1048             } else {
1049                 /*
1050                  * native language is irrelevent, free it.
1051                  */
1052                 free( job->native_language );
1053                 job->native_language = NULL;
1054             }
1055         }
1056     }
1057
1058     /*
1059      * If doing a subtitle scan then add all the matching subtitles for this
1060      * language.
1061      */
1062     if ( job->indepth_scan )
1063     {
1064         for( i=0; i < hb_list_count( title->list_subtitle ); i++ )
1065         {
1066             subtitle = hb_list_item( title->list_subtitle, i );
1067             if( strcmp( subtitle->iso639_2, audio_lang ) == 0 )
1068             {
1069                 /*
1070                  * Matched subtitle language with audio language, so
1071                  * add this to our list to scan.
1072                  *
1073                  * We will update the subtitle list on the second pass
1074                  * later after the first pass has completed.
1075                  */
1076                 subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
1077                 memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
1078                 hb_list_add( title_copy->list_subtitle, subtitle_copy );
1079                 if ( job->native_language ) {
1080                     /*
1081                      * With native language just select the
1082                      * first match in our langiage, not all of
1083                      * them. Subsequent ones are likely to be commentary
1084                      */
1085                     break;
1086                 }
1087             }
1088         }
1089     } else {
1090         /*
1091          * Not doing a subtitle scan in this pass, but maybe we are in the
1092          * first pass?
1093          */
1094         if( job->select_subtitle )
1095         {
1096             /*
1097              * Don't add subtitles here, we'll add them via select_subtitle
1098              * at the end of the subtitle_scan.
1099              */
1100         } else {
1101             /*
1102              * Definitely not doing a subtitle scan.
1103              */
1104             if( job->pass != 1 && job->native_language )
1105             {
1106                 /*
1107                  * We are not doing a subtitle scan but do want the
1108                  * native langauge subtitle selected, so select it
1109                  * for pass 0 or pass 2 of a two pass.
1110                  */
1111                 for( i=0; i < hb_list_count( title->list_subtitle ); i++ )
1112                 {
1113                     subtitle = hb_list_item( title->list_subtitle, i );
1114                     if( strcmp( subtitle->iso639_2, audio_lang ) == 0 )
1115                     {
1116                         /*
1117                          * Matched subtitle language with audio language, so
1118                          * add this to our list to scan.
1119                          */
1120                         subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
1121                         memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
1122                         hb_list_add( title_copy->list_subtitle, subtitle_copy );
1123                         break;
1124                     }
1125                 }
1126             } else {
1127                 /*
1128                  * Manually selected subtitles, in which case only
1129                  * bother adding them for pass 0 or pass 2 of a two
1130                  * pass.
1131                  */
1132                 if( job->pass != 1 )
1133                 {
1134                     /*
1135                      * Copy all of them from the input job, to the title_copy/job_copy.
1136                      */
1137                     for(  i = 0; i < hb_list_count(job->list_subtitle); i++ ) {
1138                         if( ( subtitle = hb_list_item( job->list_subtitle, i ) ) )
1139                         {
1140                             subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
1141                             memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
1142                             hb_list_add( title_copy->list_subtitle, subtitle_copy );
1143                         }
1144                     }
1145                 }
1146             }
1147         }
1148     }
1149
1150     /* Copy the job */
1151     job_copy        = calloc( sizeof( hb_job_t ), 1 );
1152     memcpy( job_copy, job, sizeof( hb_job_t ) );
1153     title_copy->job = job_copy;
1154     job_copy->title = title_copy;
1155     job_copy->list_audio = title_copy->list_audio;
1156     job_copy->list_subtitle = title_copy->list_subtitle;   // sharing list between title and job
1157     job_copy->file  = strdup( job->file );
1158     job_copy->h     = h;
1159     job_copy->pause = h->pause_lock;
1160
1161     /* Copy the job filter list */
1162     if( job->filters )
1163     {
1164         int i;
1165         int filter_count = hb_list_count( job->filters );
1166         job_copy->filters = hb_list_init();
1167         for( i = 0; i < filter_count; i++ )
1168         {
1169             /*
1170              * Copy the filters, since the MacGui reuses the global filter objects
1171              * meaning that queued up jobs overwrite the previous filter settings.
1172              * In reality, settings is probably the only field that needs duplicating
1173              * since it's the only value that is ever changed. But name is duplicated
1174              * as well for completeness. Not copying private_data since it gets
1175              * created for each job in renderInit.
1176              */
1177             hb_filter_object_t * filter = hb_list_item( job->filters, i );
1178             hb_filter_object_t * filter_copy = malloc( sizeof( hb_filter_object_t ) );
1179             memcpy( filter_copy, filter, sizeof( hb_filter_object_t ) );
1180             if( filter->name )
1181                 filter_copy->name = strdup( filter->name );
1182             if( filter->settings )
1183                 filter_copy->settings = strdup( filter->settings );
1184             hb_list_add( job_copy->filters, filter_copy );
1185         }
1186     }
1187
1188     /* Add the job to the list */
1189     hb_list_add( h->jobs, job_copy );
1190     h->job_count = hb_count(h);
1191     h->job_count_permanent++;
1192 }
1193
1194 /**
1195  * Removes a job from the job list.
1196  * @param h Handle to hb_handle_t.
1197  * @param job Handle to hb_job_t.
1198  */
1199 void hb_rem( hb_handle_t * h, hb_job_t * job )
1200 {
1201     hb_list_rem( h->jobs, job );
1202
1203     h->job_count = hb_count(h);
1204     if (h->job_count_permanent)
1205         h->job_count_permanent--;
1206
1207     /* XXX free everything XXX */
1208 }
1209
1210 /**
1211  * Starts the conversion process.
1212  * Sets state to HB_STATE_WORKING.
1213  * calls hb_work_init, to launch work thread. Stores handle to work thread.
1214  * @param h Handle to hb_handle_t.
1215  */
1216 void hb_start( hb_handle_t * h )
1217 {
1218     /* XXX Hack */
1219     h->job_count = hb_list_count( h->jobs );
1220     h->job_count_permanent = h->job_count;
1221
1222     hb_lock( h->state_lock );
1223     h->state.state = HB_STATE_WORKING;
1224 #define p h->state.param.working
1225     p.progress  = 0.0;
1226     p.job_cur   = 1;
1227     p.job_count = h->job_count;
1228     p.rate_cur  = 0.0;
1229     p.rate_avg  = 0.0;
1230     p.hours     = -1;
1231     p.minutes   = -1;
1232     p.seconds   = -1;
1233     p.sequence_id = 0;
1234 #undef p
1235     hb_unlock( h->state_lock );
1236
1237     h->paused = 0;
1238
1239     h->work_die    = 0;
1240     h->work_thread = hb_work_init( h->jobs, h->cpu_count,
1241                                    &h->work_die, &h->work_error, &h->current_job );
1242 }
1243
1244 /**
1245  * Pauses the conversion process.
1246  * @param h Handle to hb_handle_t.
1247  */
1248 void hb_pause( hb_handle_t * h )
1249 {
1250     if( !h->paused )
1251     {
1252         hb_lock( h->pause_lock );
1253         h->paused = 1;
1254
1255         hb_lock( h->state_lock );
1256         h->state.state = HB_STATE_PAUSED;
1257         hb_unlock( h->state_lock );
1258     }
1259 }
1260
1261 /**
1262  * Resumes the conversion process.
1263  * @param h Handle to hb_handle_t.
1264  */
1265 void hb_resume( hb_handle_t * h )
1266 {
1267     if( h->paused )
1268     {
1269         hb_unlock( h->pause_lock );
1270         h->paused = 0;
1271     }
1272 }
1273
1274 /**
1275  * Stops the conversion process.
1276  * @param h Handle to hb_handle_t.
1277  */
1278 void hb_stop( hb_handle_t * h )
1279 {
1280     h->work_die = 1;
1281
1282     h->job_count = hb_count(h);
1283     h->job_count_permanent = 0;
1284
1285     hb_resume( h );
1286 }
1287
1288 /**
1289  * Returns the state of the conversion process.
1290  * @param h Handle to hb_handle_t.
1291  * @param s Handle to hb_state_t which to copy the state data.
1292  */
1293 void hb_get_state( hb_handle_t * h, hb_state_t * s )
1294 {
1295     hb_lock( h->state_lock );
1296
1297     memcpy( s, &h->state, sizeof( hb_state_t ) );
1298     if ( h->state.state == HB_STATE_SCANDONE || h->state.state == HB_STATE_WORKDONE )
1299         h->state.state = HB_STATE_IDLE;
1300
1301     hb_unlock( h->state_lock );
1302 }
1303
1304 void hb_get_state2( hb_handle_t * h, hb_state_t * s )
1305 {
1306     hb_lock( h->state_lock );
1307
1308     memcpy( s, &h->state, sizeof( hb_state_t ) );
1309
1310     hb_unlock( h->state_lock );
1311 }
1312
1313 /**
1314  * Called in MacGui in UpdateUI to check
1315  *  for a new scan being completed to set a new source
1316  */
1317 int hb_get_scancount( hb_handle_t * h)
1318  {
1319      return h->scanCount;
1320  }
1321
1322 /**
1323  * Closes access to libhb by freeing the hb_handle_t handle ontained in hb_init_real.
1324  * @param _h Pointer to handle to hb_handle_t.
1325  */
1326 void hb_close( hb_handle_t ** _h )
1327 {
1328     hb_handle_t * h = *_h;
1329     hb_title_t * title;
1330
1331     h->die = 1;
1332     hb_thread_close( &h->main_thread );
1333
1334     while( ( title = hb_list_item( h->list_title, 0 ) ) )
1335     {
1336         hb_list_rem( h->list_title, title );
1337         if( title->job && title->job->filters )
1338         {
1339             hb_list_close( &title->job->filters );
1340         }
1341         free( title->job );
1342         hb_title_close( &title );
1343     }
1344     hb_list_close( &h->list_title );
1345
1346     hb_list_close( &h->jobs );
1347     hb_lock_close( &h->state_lock );
1348     hb_lock_close( &h->pause_lock );
1349     free( h );
1350     *_h = NULL;
1351
1352 }
1353
1354 /**
1355  * Monitors the state of the update, scan, and work threads.
1356  * Sets scan done state when scan thread exits.
1357  * Sets work done state when work thread exits.
1358  * @param _h Handle to hb_handle_t
1359  */
1360 static void thread_func( void * _h )
1361 {
1362     hb_handle_t * h = (hb_handle_t *) _h;
1363     char dirname[1024];
1364     DIR * dir;
1365     struct dirent * entry;
1366
1367     h->pid = getpid();
1368
1369     /* Create folder for temporary files */
1370     memset( dirname, 0, 1024 );
1371     hb_get_tempory_directory( h, dirname );
1372
1373     hb_mkdir( dirname );
1374
1375     while( !h->die )
1376     {
1377         /* In case the check_update thread hangs, it'll die sooner or
1378            later. Then, we join it here */
1379         if( h->update_thread &&
1380             hb_thread_has_exited( h->update_thread ) )
1381         {
1382             hb_thread_close( &h->update_thread );
1383         }
1384
1385         /* Check if the scan thread is done */
1386         if( h->scan_thread &&
1387             hb_thread_has_exited( h->scan_thread ) )
1388         {
1389             hb_thread_close( &h->scan_thread );
1390
1391             hb_log( "libhb: scan thread found %d valid title(s)",
1392                     hb_list_count( h->list_title ) );
1393             hb_lock( h->state_lock );
1394             h->state.state = HB_STATE_SCANDONE; //originally state.state
1395                         hb_unlock( h->state_lock );
1396                         /*we increment this sessions scan count by one for the MacGui
1397                         to trigger a new source being set */
1398             h->scanCount++;
1399         }
1400
1401         /* Check if the work thread is done */
1402         if( h->work_thread &&
1403             hb_thread_has_exited( h->work_thread ) )
1404         {
1405             hb_thread_close( &h->work_thread );
1406
1407             hb_log( "libhb: work result = %d",
1408                     h->work_error );
1409             hb_lock( h->state_lock );
1410             h->state.state                = HB_STATE_WORKDONE;
1411             h->state.param.workdone.error = h->work_error;
1412
1413             h->job_count = hb_count(h);
1414             if (h->job_count < 1)
1415                 h->job_count_permanent = 0;
1416             hb_unlock( h->state_lock );
1417         }
1418
1419         hb_snooze( 50 );
1420     }
1421
1422     if( h->work_thread )
1423     {
1424         hb_stop( h );
1425         hb_thread_close( &h->work_thread );
1426     }
1427
1428     /* Remove temp folder */
1429     dir = opendir( dirname );
1430     if (dir)
1431     {
1432         while( ( entry = readdir( dir ) ) )
1433         {
1434             char filename[1024];
1435             if( entry->d_name[0] == '.' )
1436             {
1437                 continue;
1438             }
1439             memset( filename, 0, 1024 );
1440             snprintf( filename, 1023, "%s/%s", dirname, entry->d_name );
1441             unlink( filename );
1442         }
1443         closedir( dir );
1444         rmdir( dirname );
1445     }
1446 }
1447
1448 /**
1449  * Returns the PID.
1450  * @param h Handle to hb_handle_t
1451  */
1452 int hb_get_pid( hb_handle_t * h )
1453 {
1454     return h->pid;
1455 }
1456
1457 /**
1458  * Sets the current state.
1459  * @param h Handle to hb_handle_t
1460  * @param s Handle to new hb_state_t
1461  */
1462 void hb_set_state( hb_handle_t * h, hb_state_t * s )
1463 {
1464     hb_lock( h->pause_lock );
1465     hb_lock( h->state_lock );
1466     memcpy( &h->state, s, sizeof( hb_state_t ) );
1467     if( h->state.state == HB_STATE_WORKING )
1468     {
1469         /* XXX Hack */
1470         if (h->job_count < 1)
1471             h->job_count_permanent = 1;
1472
1473         h->state.param.working.job_cur =
1474             h->job_count_permanent - hb_list_count( h->jobs );
1475         h->state.param.working.job_count = h->job_count_permanent;
1476
1477         // Set which job is being worked on
1478         if (h->current_job)
1479             h->state.param.working.sequence_id = h->current_job->sequence_id;
1480         else
1481             h->state.param.working.sequence_id = 0;
1482     }
1483     hb_unlock( h->state_lock );
1484     hb_unlock( h->pause_lock );
1485 }