OSDN Git Service

57afabfbcee20cd799fd7ce10a3fde4f1da6aeb7
[handbrake-jp/handbrake-jp-git.git] / libhb / hb.c
1 #include "hb.h"
2
3 #include "ffmpeg/avcodec.h"
4 #include "ffmpeg/swscale.h"
5
6 struct hb_handle_s
7 {
8     /* The "Check for update" thread */
9     int            build;
10     char           version[16];
11     hb_thread_t  * update_thread;
12
13     /* This thread's only purpose is to check other threads'
14        states */
15     volatile int   die;
16     hb_thread_t  * main_thread;
17     int            pid;
18
19     /* DVD/file scan thread */
20     hb_list_t    * list_title;
21     hb_thread_t  * scan_thread;
22
23     /* The thread which processes the jobs. Others threads are launched
24        from this one (see work.c) */
25     hb_list_t    * jobs;
26     hb_job_t     * current_job;
27     int            job_count;
28     int            job_count_permanent;
29     volatile int   work_die;
30     int            work_error;
31     hb_thread_t  * work_thread;
32
33     int            cpu_count;
34
35     hb_lock_t    * state_lock;
36     hb_state_t     state;
37     
38     int            paused;
39     hb_lock_t    * pause_lock;
40     /* For MacGui active queue
41        increments each time the scan thread completes*/
42     int            scanCount;
43     
44 };
45
46 hb_work_object_t * hb_objects = NULL;
47
48 static void thread_func( void * );
49
50 /**
51  * Registers work objects, by adding the work object to a liked list.
52  * @param w Handle to hb_work_object_t to register.
53  */
54 void hb_register( hb_work_object_t * w )
55 {
56     w->next    = hb_objects;
57     hb_objects = w;
58 }
59
60 /**
61  * libhb initialization routine.
62  * @param verbose HB_DEBUG_NONE or HB_DEBUG_ALL.
63  * @param update_check signals libhb to check for updated version from HandBrake website.
64  * @return Handle to hb_handle_t for use on all subsequent calls to libhb.
65  */
66 hb_handle_t * hb_init_real( int verbose, int update_check )
67 {
68     hb_handle_t * h = calloc( sizeof( hb_handle_t ), 1 );
69     uint64_t      date;
70
71     /* See hb_log() in common.c */
72     if( verbose > HB_DEBUG_NONE )
73     {
74         putenv( "HB_DEBUG=1" );
75                 av_log_set_level(AV_LOG_DEBUG);
76     }
77
78     /* Check for an update on the website if asked to */
79     h->build = -1;
80
81     if( update_check )
82     {
83         hb_log( "hb_init: checking for updates" );
84         date             = hb_get_date();
85         h->update_thread = hb_update_init( &h->build, h->version );
86
87         for( ;; )
88         {
89             if( hb_thread_has_exited( h->update_thread ) )
90             {
91                 /* Immediate success or failure */
92                 hb_thread_close( &h->update_thread );
93                 break;
94             }
95             if( hb_get_date() > date + 1000 )
96             {
97                 /* Still nothing after one second. Connection problem,
98                    let the thread die */
99                 hb_log( "hb_init: connection problem, not waiting for "
100                         "update_thread" );
101                 break;
102             }
103             hb_snooze( 500 );
104         }
105     }
106
107     /* CPU count detection */
108     hb_log( "hb_init: checking cpu count" );
109     h->cpu_count = hb_get_cpu_count();
110
111     h->list_title = hb_list_init();
112     h->jobs       = hb_list_init();
113
114     h->state_lock  = hb_lock_init();
115     h->state.state = HB_STATE_IDLE;
116
117     h->pause_lock = hb_lock_init();
118
119     /* libavcodec */
120     avcodec_init();
121     avcodec_register_all();
122     av_register_codec_parser( &mpegaudio_parser);
123     
124     /* Start library thread */
125     hb_log( "hb_init: starting libhb thread" );
126     h->die         = 0;
127     h->main_thread = hb_thread_init( "libhb", thread_func, h,
128                                      HB_NORMAL_PRIORITY );
129
130     return h;
131         
132         /* Set the scan count to start at 0 */
133         //scan_count = 0;
134 }
135
136 /**
137  * libhb initialization routine.
138  * This version is to use when calling the dylib, the macro hb_init isn't available from a dylib call!
139  * @param verbose HB_DEBUG_NONE or HB_DEBUG_ALL.
140  * @param update_check signals libhb to check for updated version from HandBrake website.
141  * @return Handle to hb_handle_t for use on all subsequent calls to libhb.
142  */
143 hb_handle_t * hb_init_dl( int verbose, int update_check )
144 {
145     hb_handle_t * h = calloc( sizeof( hb_handle_t ), 1 );
146     uint64_t      date;
147
148     /* See hb_log() in common.c */
149     if( verbose > HB_DEBUG_NONE )
150     {
151         putenv( "HB_DEBUG=1" );
152                 av_log_set_level(AV_LOG_DEBUG);
153     }
154
155     /* Check for an update on the website if asked to */
156     h->build = -1;
157
158     if( update_check )
159     {
160         hb_log( "hb_init: checking for updates" );
161         date             = hb_get_date();
162         h->update_thread = hb_update_init( &h->build, h->version );
163
164         for( ;; )
165         {
166             if( hb_thread_has_exited( h->update_thread ) )
167             {
168                 /* Immediate success or failure */
169                 hb_thread_close( &h->update_thread );
170                 break;
171             }
172             if( hb_get_date() > date + 1000 )
173             {
174                 /* Still nothing after one second. Connection problem,
175                    let the thread die */
176                 hb_log( "hb_init: connection problem, not waiting for "
177                         "update_thread" );
178                 break;
179             }
180             hb_snooze( 500 );
181         }
182     }
183
184     /* CPU count detection */
185     hb_log( "hb_init: checking cpu count" );
186     h->cpu_count = hb_get_cpu_count();
187
188     h->list_title = hb_list_init();
189     h->jobs       = hb_list_init();
190     h->current_job = NULL;
191
192     h->state_lock  = hb_lock_init();
193     h->state.state = HB_STATE_IDLE;
194
195     h->pause_lock = hb_lock_init();
196
197     /* libavcodec */
198     avcodec_init();
199     avcodec_register_all();
200
201     /* Start library thread */
202     hb_log( "hb_init: starting libhb thread" );
203     h->die         = 0;
204     h->main_thread = hb_thread_init( "libhb", thread_func, h,
205                                      HB_NORMAL_PRIORITY );
206
207     hb_register( &hb_sync ); 
208         hb_register( &hb_decmpeg2 ); 
209         hb_register( &hb_decsub ); 
210         hb_register( &hb_render ); 
211         hb_register( &hb_encavcodec ); 
212         hb_register( &hb_encxvid ); 
213         hb_register( &hb_encx264 ); 
214         hb_register( &hb_deca52 ); 
215         hb_register( &hb_decdca ); 
216         hb_register( &hb_decavcodec ); 
217         hb_register( &hb_declpcm ); 
218         hb_register( &hb_encfaac ); 
219         hb_register( &hb_enclame ); 
220         hb_register( &hb_encvorbis ); 
221         
222         return h;
223 }
224
225
226 /**
227  * Returns current version of libhb.
228  * @param h Handle to hb_handle_t.
229  * @return character array of version number.
230  */
231 char * hb_get_version( hb_handle_t * h )
232 {
233     return HB_VERSION;
234 }
235
236 /**
237  * Returns current build of libhb.
238  * @param h Handle to hb_handle_t.
239  * @return character array of build number.
240  */
241 int hb_get_build( hb_handle_t * h )
242 {
243     return HB_BUILD;
244 }
245
246 /**
247  * Checks for needed update.
248  * @param h Handle to hb_handle_t.
249  * @param version Pointer to handle where version will be copied.
250  * @return update indicator.
251  */
252 int hb_check_update( hb_handle_t * h, char ** version )
253 {
254     *version = ( h->build < 0 ) ? NULL : h->version;
255     return h->build;
256 }
257
258 /**
259  * Sets the cpu count to the desired value.
260  * @param h Handle to hb_handle_t
261  * @param cpu_count Number of CPUs to use.
262  */
263 void hb_set_cpu_count( hb_handle_t * h, int cpu_count )
264 {
265     cpu_count    = MAX( 1, cpu_count );
266     cpu_count    = MIN( cpu_count, 8 );
267     h->cpu_count = cpu_count;
268 }
269
270 /**
271  * Initializes a scan of the by calling hb_scan_init
272  * @param h Handle to hb_handle_t
273  * @param path location of VIDEO_TS folder.
274  * @param title_index Desired title to scan.  0 for all titles.
275  */
276 void hb_scan( hb_handle_t * h, const char * path, int title_index )
277 {
278     hb_title_t * title;
279
280     /* Clean up from previous scan */
281     while( ( title = hb_list_item( h->list_title, 0 ) ) )
282     {
283         hb_list_rem( h->list_title, title );
284         hb_title_close( &title );
285     }
286     
287     hb_log( "hb_scan: path=%s, title_index=%d", path, title_index );
288     h->scan_thread = hb_scan_init( h, path, title_index, h->list_title );
289 }
290
291 /**
292  * Returns the list of titles found.
293  * @param h Handle to hb_handle_t
294  * @return Handle to hb_list_t of the title list.
295  */
296 hb_list_t * hb_get_titles( hb_handle_t * h )
297 {
298     return h->list_title;
299 }
300
301 /**
302  * Create preview image of desired title a index of picture.
303  * @param h Handle to hb_handle_t.
304  * @param title Handle to hb_title_t of desired title.
305  * @param picture Index in title.
306  * @param buffer Handle to buufer were inage will be drawn.
307  */
308 void hb_get_preview( hb_handle_t * h, hb_title_t * title, int picture,
309                      uint8_t * buffer )
310 {
311     hb_job_t           * job = title->job;
312     char                 filename[1024];
313     FILE               * file;
314     uint8_t            * pen;
315     uint32_t           * p32;
316     AVPicture            pic_in, pic_preview, pic_deint, pic_crop, pic_scale;
317     struct SwsContext  * context;
318     int                  i;
319
320     // Allocate the AVPicture frames and fill in
321     avpicture_alloc( &pic_in, PIX_FMT_YUV420P, title->width, title->height );
322
323     memset( filename, 0, 1024 );
324
325     hb_get_tempory_filename( h, filename, "%x%d",
326                              (intptr_t) title, picture );
327
328     file = fopen( filename, "r" );
329     if( !file )
330     {
331         hb_log( "hb_get_preview: fopen failed" );
332         return;
333     }
334
335     fread( pic_in.data[0], title->width * title->height * 3 / 2, 1, file );
336     fclose( file );
337
338     if( job->deinterlace )
339     {
340         // Allocate picture to deinterlace into and deinterlace
341         avpicture_alloc( &pic_deint, PIX_FMT_YUV420P, title->width, title->height );
342         avpicture_deinterlace( &pic_deint, &pic_in, PIX_FMT_YUV420P, title->width, title->height );
343
344         av_picture_crop( &pic_crop, &pic_deint, PIX_FMT_YUV420P, job->crop[0], job->crop[2] );
345     }
346     else
347     {
348         av_picture_crop( &pic_crop, &pic_in, PIX_FMT_YUV420P, job->crop[0], job->crop[2] );
349     }
350
351     // Allocate picture to scale into, get scaling context and scale
352     avpicture_alloc( &pic_scale, PIX_FMT_YUV420P, job->width, job->height );
353     context = sws_getContext(title->width  - (job->crop[2] + job->crop[3]),
354                              title->height - (job->crop[0] + job->crop[1]),
355                              PIX_FMT_YUV420P,
356                              job->width, job->height, PIX_FMT_YUV420P,
357                              SWS_LANCZOS, NULL, NULL, NULL);
358     sws_scale(context,
359               pic_crop.data, pic_crop.linesize,
360               0, title->height - (job->crop[0] + job->crop[1]),
361               pic_scale.data, pic_scale.linesize);
362
363     // Allocate RGBA32 preview picture and create preview
364     avpicture_alloc( &pic_preview, PIX_FMT_RGBA32, job->width, job->height );
365     context = sws_getContext(job->width, job->height, PIX_FMT_YUV420P,
366                              job->width, job->height, PIX_FMT_RGBA32,
367                              SWS_LANCZOS, NULL, NULL, NULL);
368     sws_scale(context,
369               pic_scale.data, pic_scale.linesize,
370               0, job->height,
371               pic_preview.data, pic_preview.linesize);
372
373     /* Gray background */
374     p32 = (uint32_t *) buffer;
375     for( i = 0; i < ( title->width + 2 ) * ( title->height + 2 ); i++ )
376     {
377         p32[i] = 0xFF808080;
378     }
379
380     /* Draw the picture, centered, and draw the cropping zone */
381     pen = buffer + ( title->height - job->height ) *
382         ( title->width + 2 ) * 2 + ( title->width - job->width ) * 2;
383     memset( pen, 0xFF, 4 * ( job->width + 2 ) );
384     pen += 4 * ( title->width + 2 );
385     for( i = 0; i < job->height; i++ )
386     {
387         uint8_t * nextLine;
388         nextLine = pen + 4 * ( title->width + 2 );
389         memset( pen, 0xFF, 4 );
390         pen += 4;
391         memcpy( pen, pic_preview.data[0] + 4 * job->width * i, 4 * job->width );
392         pen += 4 * job->width;
393         memset( pen, 0xFF, 4 );
394         pen = nextLine;
395     }
396     memset( pen, 0xFF, 4 * ( job->width + 2 ) );
397
398     avpicture_free( &pic_preview );
399     avpicture_free( &pic_scale );
400     if( job->deinterlace ) avpicture_free( &pic_deint );
401     avpicture_free( &pic_in );
402 }
403
404 /**
405  * Calculates job width, height, and cropping parameters.
406  * @param job Handle to hb_job_t.
407  * @param aspect Desired aspect ratio. Value of -1 uses title aspect.
408  * @param pixels Maximum desired pixel count.
409  */
410 void hb_set_size( hb_job_t * job, int aspect, int pixels )
411 {
412     hb_title_t * title = job->title;
413
414     int croppedWidth  = title->width - title->crop[2] - title->crop[3];
415     int croppedHeight = title->height - title->crop[0] - title->crop[1];
416     int croppedAspect = title->aspect * title->height * croppedWidth /
417                             croppedHeight / title->width;
418     int addCrop;
419     int i, w, h;
420
421     if( aspect <= 0 )
422     {
423         /* Keep the best possible aspect ratio */
424         aspect = croppedAspect;
425     }
426
427     /* Crop if necessary to obtain the desired ratio */
428     memcpy( job->crop, title->crop, 4 * sizeof( int ) );
429     if( aspect < croppedAspect )
430     {
431         /* Need to crop on the left and right */
432         addCrop = croppedWidth - aspect * croppedHeight * title->width /
433                     title->aspect / title->height;
434         if( addCrop & 3 )
435         {
436             addCrop = ( addCrop + 1 ) / 2;
437             job->crop[2] += addCrop;
438             job->crop[3] += addCrop;
439         }
440         else if( addCrop & 2 )
441         {
442             addCrop /= 2;
443             job->crop[2] += addCrop - 1;
444             job->crop[3] += addCrop + 1;
445         }
446         else
447         {
448             addCrop /= 2;
449             job->crop[2] += addCrop;
450             job->crop[3] += addCrop;
451         }
452     }
453     else if( aspect > croppedAspect )
454     {
455         /* Need to crop on the top and bottom */
456         addCrop = croppedHeight - croppedWidth * title->aspect *
457             title->height / aspect / title->width;
458         if( addCrop & 3 )
459         {
460             addCrop = ( addCrop + 1 ) / 2;
461             job->crop[0] += addCrop;
462             job->crop[1] += addCrop;
463         }
464         else if( addCrop & 2 )
465         {
466             addCrop /= 2;
467             job->crop[0] += addCrop - 1;
468             job->crop[1] += addCrop + 1;
469         }
470         else
471         {
472             addCrop /= 2;
473             job->crop[0] += addCrop;
474             job->crop[1] += addCrop;
475         }
476     }
477
478     /* Compute a resolution from the number of pixels and aspect */
479     for( i = 0;; i++ )
480     {
481         w = 16 * i;
482         h = MULTIPLE_16( w * HB_ASPECT_BASE / aspect );
483         if( w * h > pixels )
484         {
485             break;
486         }
487     }
488     i--;
489     job->width  = 16 * i;
490     job->height = MULTIPLE_16( 16 * i * HB_ASPECT_BASE / aspect );
491 }
492
493 /**
494  * Returns the number of jobs in the queue.
495  * @param h Handle to hb_handle_t.
496  * @return Number of jobs.
497  */
498 int hb_count( hb_handle_t * h )
499 {
500     return hb_list_count( h->jobs );
501 }
502
503 /**
504  * Returns handle to job at index i within the job list.
505  * @param h Handle to hb_handle_t.
506  * @param i Index of job.
507  * @returns Handle to hb_job_t of desired job.
508  */
509 hb_job_t * hb_job( hb_handle_t * h, int i )
510 {
511     return hb_list_item( h->jobs, i );
512 }
513
514 hb_job_t * hb_current_job( hb_handle_t * h )
515 {
516     return( h->current_job );
517 }
518
519 /**
520  * Adds a job to the job list.
521  * @param h Handle to hb_handle_t.
522  * @param job Handle to hb_job_t.
523  */
524 void hb_add( hb_handle_t * h, hb_job_t * job )
525 {
526     hb_job_t      * job_copy;
527     hb_title_t    * title,    * title_copy;
528     hb_chapter_t  * chapter,  * chapter_copy;
529     hb_audio_t    * audio,    * audio_copy;
530     hb_subtitle_t * subtitle, * subtitle_copy;
531     int             i;
532     char            audio_lang[4];
533
534     /* Copy the title */
535     title      = job->title;
536     title_copy = malloc( sizeof( hb_title_t ) );
537     memcpy( title_copy, title, sizeof( hb_title_t ) );
538
539     title_copy->list_chapter = hb_list_init();
540     for( i = 0; i < hb_list_count( title->list_chapter ); i++ )
541     {
542         chapter      = hb_list_item( title->list_chapter, i );
543         chapter_copy = malloc( sizeof( hb_chapter_t ) );
544         memcpy( chapter_copy, chapter, sizeof( hb_chapter_t ) );
545         hb_list_add( title_copy->list_chapter, chapter_copy );
546     }
547
548     /* Copy the audio track(s) we want */
549     title_copy->list_audio = hb_list_init();
550
551     /* Do nothing about audio during first pass */
552     if( job->pass == 0 || job->pass == 2 )
553     {
554         for( i = 0; i < 8; i++ )
555         {
556             if( job->audios[i] < 0 )
557             {
558                 break;
559             }
560             if( ( audio = hb_list_item( title->list_audio, job->audios[i] ) ) )
561             {
562                 audio_copy = malloc( sizeof( hb_audio_t ) );
563                 memcpy( audio_copy, audio, sizeof( hb_audio_t ) );
564                 hb_list_add( title_copy->list_audio, audio_copy );
565             }
566         }
567     }
568
569     title_copy->list_subtitle = hb_list_init();
570
571     /*
572      * The following code is confusing, there are three ways in which
573      * we select subtitles and it depends on whether this is single or
574      * two pass mode.
575      *
576      * subtitle_scan may be enabled, in which case the first pass
577      * scans all subtitles of that language. The second pass does not
578      * select any because they are set at the end of the first pass.
579      *
580      * native_language may have a preferred language, in which case we
581      * may be switching the language we want for the subtitles in the
582      * first pass of a single pass, or the second pass of a two pass.
583      *
584      * We may have manually selected a subtitle, in which case that is
585      * selected in the first pass of a single pass, or the second of a
586      * two pass.
587      */
588     memset( audio_lang, 0, sizeof( audio_lang ) );
589
590     if ( job->subtitle_scan || job->native_language ) {
591       
592         /*
593          * Find the first audio language that is being encoded
594          */
595         for( i = 0; i < 8; i++ )
596         {
597             if( job->audios[i] < 0 )
598             {
599                 break;
600             }
601             if( ( audio = hb_list_item( title->list_audio, job->audios[i] ) ) )
602             {
603                 strncpy(audio_lang, audio->iso639_2, sizeof(audio_lang));
604                 break;
605             }
606         }
607
608         /*
609          * In all cases switch the language if we need to to our native
610          * language.
611          */
612         if( job->native_language ) 
613         {
614             if( strncasecmp( job->native_language, audio_lang, 
615                              sizeof( audio_lang ) ) != 0 )
616             {             
617                 
618                 if( job->pass != 2 )
619                 {
620                     hb_log( "Enabled subtitles in native language '%s', audio is in '%s'",
621                             job->native_language, audio_lang);
622                 }
623                 /*
624                  * The main audio track is not in our native language, so switch
625                  * the subtitles to use our native language instead.
626                  */
627                 strncpy( audio_lang, job->native_language, sizeof( audio_lang ) );
628             } else {
629                 /*
630                  * native language is irrelevent, free it.
631                  */
632                 free( job->native_language );
633                 job->native_language = NULL;
634             }
635         }
636     }
637
638     /*
639      * If doing a subtitle scan then add all the matching subtitles for this
640      * language.
641      */
642     if ( job->subtitle_scan ) 
643     {
644         for( i=0; i < hb_list_count( title->list_subtitle ); i++ ) 
645         {
646             subtitle = hb_list_item( title->list_subtitle, i );
647             if( strcmp( subtitle->iso639_2, audio_lang ) == 0 ) 
648             {
649                 /*
650                  * Matched subtitle language with audio language, so
651                  * add this to our list to scan.
652                  *
653                  * We will update the subtitle list on the second pass
654                  * later after the first pass has completed.
655                  */
656                 subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
657                 memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
658                 hb_list_add( title_copy->list_subtitle, subtitle_copy );
659                 if ( job->native_language ) {
660                     /*
661                      * With native language just select the
662                      * first match in our langiage, not all of
663                      * them. Subsequent ones are likely to be commentary
664                      */
665                     break;
666                 }
667             }
668         }
669     } else {
670         /*
671          * Not doing a subtitle scan in this pass, but maybe we are in the
672          * first pass?
673          */
674         if( job->select_subtitle )
675         {
676             /*
677              * Don't add subtitles here, we'll add them via select_subtitle
678              * at the end of the subtitle_scan.
679              */
680         } else {
681             /*
682              * Definitely not doing a subtitle scan.
683              */
684             if( job->pass != 1 && job->native_language ) 
685             {
686                 /*
687                  * We are not doing a subtitle scan but do want the
688                  * native langauge subtitle selected, so select it 
689                  * for pass 0 or pass 2 of a two pass.
690                  */
691                 for( i=0; i < hb_list_count( title->list_subtitle ); i++ ) 
692                 {
693                     subtitle = hb_list_item( title->list_subtitle, i );
694                     if( strcmp( subtitle->iso639_2, audio_lang ) == 0 ) 
695                     {
696                         /*
697                          * Matched subtitle language with audio language, so
698                          * add this to our list to scan.
699                          */
700                         subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
701                         memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
702                         hb_list_add( title_copy->list_subtitle, subtitle_copy );
703                         break;
704                     }
705                 }
706             } else {
707                 /*
708                  * Manually selected subtitle, in which case only
709                  * bother adding them for pass 0 or pass 2 of a two
710                  * pass.
711                  */
712                 if( job->pass != 1 ) 
713                 {
714                     if( ( subtitle = hb_list_item( title->list_subtitle, job->subtitle ) ) )
715                     {
716                         subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
717                         memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
718                         hb_list_add( title_copy->list_subtitle, subtitle_copy );
719                     }
720                 }
721             }
722         }
723     }
724
725     /* Copy the job */
726     job_copy        = calloc( sizeof( hb_job_t ), 1 );
727     memcpy( job_copy, job, sizeof( hb_job_t ) );
728     title_copy->job = job_copy;
729     job_copy->title = title_copy;
730     job_copy->file  = strdup( job->file );
731     job_copy->h     = h;
732     job_copy->pause = h->pause_lock;
733
734     /* Copy the job filter list */
735     if( job->filters )
736     {
737         int i;
738         int filter_count = hb_list_count( job->filters );
739         job_copy->filters = hb_list_init();        
740         for( i = 0; i < filter_count; i++ )
741         {
742             hb_filter_object_t * filter = hb_list_item( job->filters, i );
743             hb_list_add( job_copy->filters, filter );
744         }        
745     }
746     
747     /* Add the job to the list */
748     hb_list_add( h->jobs, job_copy );
749     h->job_count = hb_count(h);
750     h->job_count_permanent++;
751 }
752
753 /**
754  * Removes a job from the job list.
755  * @param h Handle to hb_handle_t.
756  * @param job Handle to hb_job_t.
757  */
758 void hb_rem( hb_handle_t * h, hb_job_t * job )
759 {
760     hb_list_rem( h->jobs, job );
761     
762     h->job_count = hb_count(h);
763     if (h->job_count_permanent)
764         h->job_count_permanent--;
765
766     /* XXX free everything XXX */
767 }
768
769 /**
770  * Starts the conversion process.
771  * Sets state to HB_STATE_WORKING.
772  * calls hb_work_init, to launch work thread. Stores handle to work thread.
773  * @param h Handle to hb_handle_t.
774  */
775 void hb_start( hb_handle_t * h )
776 {
777     /* XXX Hack */
778     h->job_count = hb_list_count( h->jobs );
779
780     hb_lock( h->state_lock );
781     h->state.state = HB_STATE_WORKING;
782 #define p h->state.param.working
783     p.progress  = 0.0;
784     p.job_cur   = 1;
785     p.job_count = h->job_count;
786     p.rate_cur  = 0.0;
787     p.rate_avg  = 0.0;
788     p.hours     = -1;
789     p.minutes   = -1;
790     p.seconds   = -1;
791 #undef p
792     hb_unlock( h->state_lock );
793
794     h->paused = 0;
795
796     h->work_die    = 0;
797     h->work_thread = hb_work_init( h->jobs, h->cpu_count,
798                                    &h->work_die, &h->work_error, &h->current_job );
799 }
800
801 /**
802  * Pauses the conversion process.
803  * @param h Handle to hb_handle_t.
804  */
805 void hb_pause( hb_handle_t * h )
806 {
807     if( !h->paused )
808     {
809         hb_lock( h->pause_lock );
810         h->paused = 1;
811
812         hb_lock( h->state_lock );
813         h->state.state = HB_STATE_PAUSED;
814         hb_unlock( h->state_lock );
815     }
816 }
817
818 /**
819  * Resumes the conversion process.
820  * @param h Handle to hb_handle_t.
821  */
822 void hb_resume( hb_handle_t * h )
823 {
824     if( h->paused )
825     {
826         hb_unlock( h->pause_lock );
827         h->paused = 0;
828     }
829 }
830
831 /**
832  * Stops the conversion process.
833  * @param h Handle to hb_handle_t.
834  */
835 void hb_stop( hb_handle_t * h )
836 {
837     h->work_die = 1;
838
839     h->job_count = hb_count(h);
840     h->job_count_permanent = 0;
841
842     hb_resume( h );
843 }
844
845 /**
846  * Returns the state of the conversion process.
847  * @param h Handle to hb_handle_t.
848  * @param s Handle to hb_state_t which to copy the state data.
849  */
850 void hb_get_state( hb_handle_t * h, hb_state_t * s )
851 {
852     hb_lock( h->state_lock );
853
854     memcpy( s, &h->state, sizeof( hb_state_t ) );
855     if ( h->state.state == HB_STATE_SCANDONE || h->state.state == HB_STATE_WORKDONE )
856         h->state.state = HB_STATE_IDLE;
857
858     hb_unlock( h->state_lock );
859 }
860
861 void hb_get_state2( hb_handle_t * h, hb_state_t * s )
862 {
863     hb_lock( h->state_lock );
864
865     memcpy( s, &h->state, sizeof( hb_state_t ) );
866
867     hb_unlock( h->state_lock );
868 }
869
870 /**
871  * Called in MacGui in UpdateUI to check
872  *  for a new scan being completed to set a new source
873  */
874 int hb_get_scancount( hb_handle_t * h)
875  {
876      return h->scanCount;
877  }
878
879 /**
880  * Closes access to libhb by freeing the hb_handle_t handle ontained in hb_init_real.
881  * @param _h Pointer to handle to hb_handle_t.
882  */
883 void hb_close( hb_handle_t ** _h )
884 {
885     hb_handle_t * h = *_h;
886     hb_title_t * title;
887
888     h->die = 1;
889     hb_thread_close( &h->main_thread );
890
891     while( ( title = hb_list_item( h->list_title, 0 ) ) )
892     {
893         hb_list_rem( h->list_title, title );
894         if( title->job && title->job->filters )
895         {
896             hb_list_close( &title->job->filters );
897         }
898         free( title->job );
899         hb_title_close( &title );
900     }
901     hb_list_close( &h->list_title );
902
903     hb_list_close( &h->jobs );
904     hb_lock_close( &h->state_lock );
905     hb_lock_close( &h->pause_lock );
906     free( h );
907     *_h = NULL;
908 }
909
910 /**
911  * Monitors the state of the update, scan, and work threads.
912  * Sets scan done state when scan thread exits.
913  * Sets work done state when work thread exits.
914  * @param _h Handle to hb_handle_t
915  */
916 static void thread_func( void * _h )
917 {
918     hb_handle_t * h = (hb_handle_t *) _h;
919     char dirname[1024];
920     DIR * dir;
921     struct dirent * entry;
922
923     h->pid = getpid();
924
925     /* Create folder for temporary files */
926     memset( dirname, 0, 1024 );
927     hb_get_tempory_directory( h, dirname );
928
929     hb_mkdir( dirname );
930
931     while( !h->die )
932     {
933         /* In case the check_update thread hangs, it'll die sooner or
934            later. Then, we join it here */
935         if( h->update_thread &&
936             hb_thread_has_exited( h->update_thread ) )
937         {
938             hb_thread_close( &h->update_thread );
939         }
940
941         /* Check if the scan thread is done */
942         if( h->scan_thread &&
943             hb_thread_has_exited( h->scan_thread ) )
944         {
945             hb_thread_close( &h->scan_thread );
946
947             hb_log( "libhb: scan thread found %d valid title(s)",
948                     hb_list_count( h->list_title ) );
949             hb_lock( h->state_lock );
950             h->state.state = HB_STATE_SCANDONE; //originally state.state
951                         hb_unlock( h->state_lock );
952                         /*we increment this sessions scan count by one for the MacGui
953                         to trigger a new source being set */
954             h->scanCount++;
955         }
956
957         /* Check if the work thread is done */
958         if( h->work_thread &&
959             hb_thread_has_exited( h->work_thread ) )
960         {
961             hb_thread_close( &h->work_thread );
962
963             hb_log( "libhb: work result = %d",
964                     h->work_error );
965             hb_lock( h->state_lock );
966             h->state.state                = HB_STATE_WORKDONE;
967             h->state.param.workdone.error = h->work_error;
968             
969             h->job_count = hb_count(h);
970             if (h->job_count < 1)
971                 h->job_count_permanent = 0;
972             hb_unlock( h->state_lock );
973         }
974
975         hb_snooze( 50 );
976     }
977
978     if( h->work_thread )
979     {
980         hb_stop( h );
981         hb_thread_close( &h->work_thread );
982     }
983
984     /* Remove temp folder */
985     dir = opendir( dirname );
986     while( ( entry = readdir( dir ) ) )
987     {
988         char filename[1024];
989         if( entry->d_name[0] == '.' )
990         {
991             continue;
992         }
993         memset( filename, 0, 1024 );
994         snprintf( filename, 1023, "%s/%s", dirname, entry->d_name );
995         unlink( filename );
996     }
997     closedir( dir );
998     rmdir( dirname );
999 }
1000
1001 /**
1002  * Returns the PID.
1003  * @param h Handle to hb_handle_t
1004  */
1005 int hb_get_pid( hb_handle_t * h )
1006 {
1007     return h->pid;
1008 }
1009
1010 /**
1011  * Sets the current state.
1012  * @param h Handle to hb_handle_t
1013  * @param s Handle to new hb_state_t
1014  */
1015 void hb_set_state( hb_handle_t * h, hb_state_t * s )
1016 {
1017     hb_lock( h->pause_lock );
1018     hb_lock( h->state_lock );
1019     memcpy( &h->state, s, sizeof( hb_state_t ) );
1020     if( h->state.state == HB_STATE_WORKING )
1021     {
1022         /* XXX Hack */
1023         if (h->job_count < 1)
1024             h->job_count_permanent = 1;
1025         
1026         h->state.param.working.job_cur =
1027             h->job_count_permanent - hb_list_count( h->jobs );
1028         h->state.param.working.job_count = h->job_count_permanent;
1029     }
1030     hb_unlock( h->state_lock );
1031     hb_unlock( h->pause_lock );
1032 }