OSDN Git Service

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