OSDN Git Service

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