OSDN Git Service

Revert changes to threading sleep intervals.
[handbrake-jp/handbrake-jp-git.git] / libhb / hb.c
1 /* $Id: hb.c,v 1.43 2005/04/27 21:05:24 titer Exp $
2
3    This file is part of the HandBrake source code.
4    Homepage: <http://handbrake.m0k.org/>.
5    It may be used under the terms of the GNU General Public License. */
6
7 #include "hb.h"
8
9 #include "ffmpeg/avcodec.h"
10
11 struct hb_handle_s
12 {
13     /* The "Check for update" thread */
14     int            build;
15     char           version[16];
16     hb_thread_t  * update_thread;
17
18     /* This thread's only purpose is to check other threads'
19        states */
20     volatile int   die;
21     hb_thread_t  * main_thread;
22     int            pid;
23
24     /* DVD/file scan thread */
25     hb_list_t    * list_title;
26     hb_thread_t  * scan_thread;
27
28     /* The thread which processes the jobs. Others threads are launched
29        from this one (see work.c) */
30     hb_list_t    * jobs;
31     int            job_count;
32     volatile int   work_die;
33     int            work_error;
34     hb_thread_t  * work_thread;
35
36     int            cpu_count;
37
38     hb_lock_t    * state_lock;
39     hb_state_t     state;
40
41     int            paused;
42     hb_lock_t    * pause_lock;
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     }
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
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
132 /**
133  * Returns current version of libhb.
134  * @param h Handle to hb_handle_t.
135  * @return character array of version number.
136  */
137 char * hb_get_version( hb_handle_t * h )
138 {
139     return HB_VERSION;
140 }
141
142 /**
143  * Returns current build of libhb.
144  * @param h Handle to hb_handle_t.
145  * @return character array of build number.
146  */
147 int hb_get_build( hb_handle_t * h )
148 {
149     return HB_BUILD;
150 }
151
152 /**
153  * Checks for needed update.
154  * @param h Handle to hb_handle_t.
155  * @param version Pointer to handle where version will be copied.
156  * @return update indicator.
157  */
158 int hb_check_update( hb_handle_t * h, char ** version )
159 {
160     *version = ( h->build < 0 ) ? NULL : h->version;
161     return h->build;
162 }
163
164 /**
165  * Sets the cpu count to the desired value.
166  * @param h Handle to hb_handle_t
167  * @param cpu_count Number of CPUs to use.
168  */
169 void hb_set_cpu_count( hb_handle_t * h, int cpu_count )
170 {
171     cpu_count    = MAX( 1, cpu_count );
172     cpu_count    = MIN( cpu_count, 8 );
173     h->cpu_count = cpu_count;
174 }
175
176 /**
177  * Initializes a scan of the by calling hb_scan_init
178  * @param h Handle to hb_handle_t
179  * @param path location of VIDEO_TS folder.
180  * @param title_index Desired title to scan.  0 for all titles.
181  */
182 void hb_scan( hb_handle_t * h, const char * path, int title_index )
183 {
184     hb_title_t * title;
185
186     /* Clean up from previous scan */
187     while( ( title = hb_list_item( h->list_title, 0 ) ) )
188     {
189         hb_list_rem( h->list_title, title );
190         hb_title_close( &title );
191     }
192     
193     hb_log( "hb_scan: path=%s, title_index=%d", path, title_index );
194     h->scan_thread = hb_scan_init( h, path, title_index, h->list_title );
195 }
196
197 /**
198  * Returns the list of titles found.
199  * @param h Handle to hb_handle_t
200  * @return Handle to hb_list_t of the title list.
201  */
202 hb_list_t * hb_get_titles( hb_handle_t * h )
203 {
204     return h->list_title;
205 }
206
207 /**
208  * Create preview image of desired title a index of picture.
209  * @param h Handle to hb_handle_t.
210  * @param title Handle to hb_title_t of desired title.
211  * @param picture Index in title.
212  * @param buffer Handle to buufer were inage will be drawn.
213  */
214 void hb_get_preview( hb_handle_t * h, hb_title_t * title, int picture,
215                      uint8_t * buffer )
216 {
217     hb_job_t           * job = title->job;
218     char                 filename[1024];
219     FILE               * file;
220     uint8_t            * buf1, * buf2, * buf3, * buf4, * pen;
221     uint32_t           * p32;
222     AVPicture            pic1, pic2, pic3, pic4;
223     ImgReSampleContext * context;
224     int                  i;
225
226     buf1 = malloc( title->width * title->height * 3 / 2 );
227     buf2 = malloc( title->width * title->height * 3 / 2 );
228     buf3 = malloc( title->width * title->height * 3 / 2 );
229     buf4 = malloc( title->width * title->height * 4 );
230     avpicture_fill( &pic1, buf1, PIX_FMT_YUV420P,
231                     title->width, title->height );
232     avpicture_fill( &pic2, buf2, PIX_FMT_YUV420P,
233                     title->width, title->height );
234     avpicture_fill( &pic3, buf3, PIX_FMT_YUV420P,
235                     job->width, job->height );
236     avpicture_fill( &pic4, buf4, PIX_FMT_RGBA32,
237                     job->width, job->height );
238     
239     memset( filename, 0, 1024 );
240
241     hb_get_tempory_filename( h, filename, "%x%d",
242                              (int) title, picture );
243
244     file = fopen( filename, "r" );
245     if( !file )
246     {
247         hb_log( "hb_get_preview: fopen failed" );
248         return;
249     }
250
251     fread( buf1, title->width * title->height * 3 / 2, 1, file );
252     fclose( file );
253
254     context = img_resample_full_init(
255             job->width, job->height, title->width, title->height,
256             job->crop[0], job->crop[1], job->crop[2], job->crop[3],
257             0, 0, 0, 0 );
258
259     if( job->deinterlace )
260     {
261         avpicture_deinterlace( &pic2, &pic1, PIX_FMT_YUV420P,
262                                title->width, title->height );
263         img_resample( context, &pic3, &pic2 );
264     }
265     else
266     {
267         img_resample( context, &pic3, &pic1 );
268     }
269     img_convert( &pic4, PIX_FMT_RGBA32, &pic3, PIX_FMT_YUV420P,
270                  job->width, job->height );
271
272     /* Gray background */
273     p32 = (uint32_t *) buffer;
274     for( i = 0; i < ( title->width + 2 ) * ( title->height + 2 ); i++ )
275     {
276         p32[i] = 0xFF808080;
277     }
278
279     /* Draw the picture, centered, and draw the cropping zone */
280     pen = buffer + ( title->height - job->height ) *
281         ( title->width + 2 ) * 2 + ( title->width - job->width ) * 2;
282     memset( pen, 0xFF, 4 * ( job->width + 2 ) );
283     pen += 4 * ( title->width + 2 );
284     for( i = 0; i < job->height; i++ )
285     {
286         uint8_t * nextLine;
287         nextLine = pen + 4 * ( title->width + 2 );
288         memset( pen, 0xFF, 4 );
289         pen += 4;
290         memcpy( pen, buf4 + 4 * job->width * i, 4 * job->width );
291         pen += 4 * job->width;
292         memset( pen, 0xFF, 4 );
293         pen = nextLine;
294     }
295     memset( pen, 0xFF, 4 * ( job->width + 2 ) );
296
297     free( buf1 );
298     free( buf2 );
299     free( buf3 );
300     free( buf4 );
301 }
302
303 /**
304  * Calculates job width, height, and cropping parameters.
305  * @param job Handle to hb_job_t.
306  * @param aspect Desired aspect ratio. Value of -1 uses title aspect.
307  * @param pixels Maximum desired pixel count.
308  */
309 void hb_set_size( hb_job_t * job, int aspect, int pixels )
310 {
311     hb_title_t * title = job->title;
312
313     int croppedWidth  = title->width - title->crop[2] - title->crop[3];
314     int croppedHeight = title->height - title->crop[0] - title->crop[1];
315     int croppedAspect = title->aspect * title->height * croppedWidth /
316                             croppedHeight / title->width;
317     int addCrop;
318     int i, w, h;
319
320     if( aspect <= 0 )
321     {
322         /* Keep the best possible aspect ratio */
323         aspect = croppedAspect;
324     }
325
326     /* Crop if necessary to obtain the desired ratio */
327     memcpy( job->crop, title->crop, 4 * sizeof( int ) );
328     if( aspect < croppedAspect )
329     {
330         /* Need to crop on the left and right */
331         addCrop = croppedWidth - aspect * croppedHeight * title->width /
332                     title->aspect / title->height;
333         if( addCrop & 3 )
334         {
335             addCrop = ( addCrop + 1 ) / 2;
336             job->crop[2] += addCrop;
337             job->crop[3] += addCrop;
338         }
339         else if( addCrop & 2 )
340         {
341             addCrop /= 2;
342             job->crop[2] += addCrop - 1;
343             job->crop[3] += addCrop + 1;
344         }
345         else
346         {
347             addCrop /= 2;
348             job->crop[2] += addCrop;
349             job->crop[3] += addCrop;
350         }
351     }
352     else if( aspect > croppedAspect )
353     {
354         /* Need to crop on the top and bottom */
355         addCrop = croppedHeight - croppedWidth * title->aspect *
356             title->height / aspect / title->width;
357         if( addCrop & 3 )
358         {
359             addCrop = ( addCrop + 1 ) / 2;
360             job->crop[0] += addCrop;
361             job->crop[1] += addCrop;
362         }
363         else if( addCrop & 2 )
364         {
365             addCrop /= 2;
366             job->crop[0] += addCrop - 1;
367             job->crop[1] += addCrop + 1;
368         }
369         else
370         {
371             addCrop /= 2;
372             job->crop[0] += addCrop;
373             job->crop[1] += addCrop;
374         }
375     }
376
377     /* Compute a resolution from the number of pixels and aspect */
378     for( i = 0;; i++ )
379     {
380         w = 16 * i;
381         h = MULTIPLE_16( w * HB_ASPECT_BASE / aspect );
382         if( w * h > pixels )
383         {
384             break;
385         }
386     }
387     i--;
388     job->width  = 16 * i;
389     job->height = MULTIPLE_16( 16 * i * HB_ASPECT_BASE / aspect );
390 }
391
392 /**
393  * Returns the number of jobs in the queue.
394  * @param h Handle to hb_handle_t.
395  * @return Number of jobs.
396  */
397 int hb_count( hb_handle_t * h )
398 {
399     return hb_list_count( h->jobs );
400 }
401
402 /**
403  * Returns handle to job at index i within the job list.
404  * @param h Handle to hb_handle_t.
405  * @param i Index of job.
406  * @returns Handle to hb_job_t of desired job.
407  */
408 hb_job_t * hb_job( hb_handle_t * h, int i )
409 {
410     return hb_list_item( h->jobs, i );
411 }
412
413 /**
414  * Adds a job to the job list.
415  * @param h Handle to hb_handle_t.
416  * @param job Handle to hb_job_t.
417  */
418 void hb_add( hb_handle_t * h, hb_job_t * job )
419 {
420     hb_job_t      * job_copy;
421     hb_title_t    * title,    * title_copy;
422     hb_chapter_t  * chapter,  * chapter_copy;
423     hb_audio_t    * audio,    * audio_copy;
424     hb_subtitle_t * subtitle, * subtitle_copy;
425     int             i;
426
427     /* Copy the title */
428     title      = job->title;
429     title_copy = malloc( sizeof( hb_title_t ) );
430     memcpy( title_copy, title, sizeof( hb_title_t ) );
431
432     title_copy->list_chapter = hb_list_init();
433     for( i = 0; i < hb_list_count( title->list_chapter ); i++ )
434     {
435         chapter      = hb_list_item( title->list_chapter, i );
436         chapter_copy = malloc( sizeof( hb_chapter_t ) );
437         memcpy( chapter_copy, chapter, sizeof( hb_chapter_t ) );
438         hb_list_add( title_copy->list_chapter, chapter_copy );
439     }
440
441     /* Copy the audio track(s) we want */
442     title_copy->list_audio = hb_list_init();
443
444     /* Do nothing about audio during first pass */
445     if( job->pass != 1 )
446     {
447         for( i = 0; i < 8; i++ )
448         {
449             if( job->audios[i] < 0 )
450             {
451                 break;
452             }
453             if( ( audio = hb_list_item( title->list_audio, job->audios[i] ) ) )
454             {
455                 audio_copy = malloc( sizeof( hb_audio_t ) );
456                 memcpy( audio_copy, audio, sizeof( hb_audio_t ) );
457                 hb_list_add( title_copy->list_audio, audio_copy );
458             }
459         }
460     }
461
462     /* Copy the subtitle we want (or not) */
463     title_copy->list_subtitle = hb_list_init();
464     if( ( subtitle = hb_list_item( title->list_subtitle, job->subtitle ) ) )
465     {
466         subtitle_copy = malloc( sizeof( hb_subtitle_t ) );
467         memcpy( subtitle_copy, subtitle, sizeof( hb_subtitle_t ) );
468         hb_list_add( title_copy->list_subtitle, subtitle_copy );
469     }
470
471     /* Copy the job */
472     job_copy        = calloc( sizeof( hb_job_t ), 1 );
473     memcpy( job_copy, job, sizeof( hb_job_t ) );
474     job_copy->title = title_copy;
475     job_copy->file  = strdup( job->file );
476     job_copy->h     = h;
477     job_copy->pause = h->pause_lock;
478
479     /* Add the job to the list */
480     hb_list_add( h->jobs, job_copy );
481 }
482
483 /**
484  * Removes a job from the job list.
485  * @param h Handle to hb_handle_t.
486  * @param job Handle to hb_job_t.
487  */
488 void hb_rem( hb_handle_t * h, hb_job_t * job )
489 {
490     hb_list_rem( h->jobs, job );
491
492     /* XXX free everything XXX */
493 }
494
495 /**
496  * Starts the conversion process.
497  * Sets state to HB_STATE_WORKING.
498  * calls hb_work_init, to launch work thread. Stores handle to work thread.
499  * @param h Handle to hb_handle_t.
500  */
501 void hb_start( hb_handle_t * h )
502 {
503     /* XXX Hack */
504     h->job_count = hb_list_count( h->jobs );
505
506     hb_lock( h->state_lock );
507     h->state.state = HB_STATE_WORKING;
508 #define p h->state.param.working
509     p.progress  = 0.0;
510     p.job_cur   = 1;
511     p.job_count = h->job_count;
512     p.rate_cur  = 0.0;
513     p.rate_avg  = 0.0;
514     p.hours     = -1;
515     p.minutes   = -1;
516     p.seconds   = -1;
517 #undef p
518     hb_unlock( h->state_lock );
519
520     h->paused = 0;
521
522     h->work_die    = 0;
523     h->work_thread = hb_work_init( h->jobs, h->cpu_count,
524                                    &h->work_die, &h->work_error );
525 }
526
527 /**
528  * Pauses the conversion process.
529  * @param h Handle to hb_handle_t.
530  */
531 void hb_pause( hb_handle_t * h )
532 {
533     if( !h->paused )
534     {
535         hb_lock( h->pause_lock );
536         h->paused = 1;
537
538         hb_lock( h->state_lock );
539         h->state.state = HB_STATE_PAUSED;
540         hb_unlock( h->state_lock );
541     }
542 }
543
544 /**
545  * Resumes the conversion process.
546  * @param h Handle to hb_handle_t.
547  */
548 void hb_resume( hb_handle_t * h )
549 {
550     if( h->paused )
551     {
552         hb_unlock( h->pause_lock );
553         h->paused = 0;
554     }
555 }
556
557 /**
558  * Stops the conversion process.
559  * @param h Handle to hb_handle_t.
560  */
561 void hb_stop( hb_handle_t * h )
562 {
563     h->work_die = 1;
564
565     hb_resume( h );
566 }
567
568 /**
569  * Returns the state of the conversion process.
570  * @param h Handle to hb_handle_t.
571  * @param s Handle to hb_state_t which to copy the state data.
572  */
573 void hb_get_state( hb_handle_t * h, hb_state_t * s )
574 {
575     hb_lock( h->state_lock );
576
577     memcpy( s, &h->state, sizeof( hb_state_t ) );
578     h->state.state = HB_STATE_IDLE;
579
580     hb_unlock( h->state_lock );
581 }
582
583 /**
584  * Closes access to libhb by freeing the hb_handle_t handle ontained in hb_init_real.
585  * @param _h Pointer to handle to hb_handle_t.
586  */
587 void hb_close( hb_handle_t ** _h )
588 {
589     hb_handle_t * h = *_h;
590     hb_title_t * title;
591
592     h->die = 1;
593     hb_thread_close( &h->main_thread );
594
595     while( ( title = hb_list_item( h->list_title, 0 ) ) )
596     {
597         hb_list_rem( h->list_title, title );
598         hb_title_close( &title );
599     }
600     hb_list_close( &h->list_title );
601
602     hb_list_close( &h->jobs );
603     hb_lock_close( &h->state_lock );
604     hb_lock_close( &h->pause_lock );
605     free( h );
606     *_h = NULL;
607 }
608
609 /**
610  * Monitors the state of the update, scan, and work threads.
611  * Sets scan done state when scan thread exits.
612  * Sets work done state when work thread exits.
613  * @param _h Handle to hb_handle_t
614  */
615 static void thread_func( void * _h )
616 {
617     hb_handle_t * h = (hb_handle_t *) _h;
618     char dirname[1024];
619     DIR * dir;
620     struct dirent * entry;
621
622     h->pid = getpid();
623
624     /* Create folder for temporary files */
625     memset( dirname, 0, 1024 );
626     hb_get_tempory_directory( h, dirname );
627
628     hb_mkdir( dirname );
629
630     while( !h->die )
631     {
632         /* In case the check_update thread hangs, it'll die sooner or
633            later. Then, we join it here */
634         if( h->update_thread &&
635             hb_thread_has_exited( h->update_thread ) )
636         {
637             hb_thread_close( &h->update_thread );
638         }
639
640         /* Check if the scan thread is done */
641         if( h->scan_thread &&
642             hb_thread_has_exited( h->scan_thread ) )
643         {
644             hb_thread_close( &h->scan_thread );
645
646             hb_log( "libhb: scan thread found %d valid title(s)",
647                     hb_list_count( h->list_title ) );
648             hb_lock( h->state_lock );
649             h->state.state = HB_STATE_SCANDONE;
650             hb_unlock( h->state_lock );
651         }
652
653         /* Check if the work thread is done */
654         if( h->work_thread &&
655             hb_thread_has_exited( h->work_thread ) )
656         {
657             hb_thread_close( &h->work_thread );
658
659             hb_log( "libhb: work result = %d",
660                     h->work_error );
661             hb_lock( h->state_lock );
662             h->state.state                = HB_STATE_WORKDONE;
663             h->state.param.workdone.error = h->work_error;
664             hb_unlock( h->state_lock );
665         }
666
667         hb_snooze( 50 );
668     }
669
670     if( h->work_thread )
671     {
672         hb_stop( h );
673         hb_thread_close( &h->work_thread );
674     }
675
676     /* Remove temp folder */
677     dir = opendir( dirname );
678     while( ( entry = readdir( dir ) ) )
679     {
680         char filename[1024];
681         if( entry->d_name[0] == '.' )
682         {
683             continue;
684         }
685         memset( filename, 0, 1024 );
686         snprintf( filename, 1023, "%s/%s", dirname, entry->d_name );
687         unlink( filename );
688     }
689     closedir( dir );
690     rmdir( dirname );
691 }
692
693 /**
694  * Returns the PID.
695  * @param h Handle to hb_handle_t
696  */
697 int hb_get_pid( hb_handle_t * h )
698 {
699     return h->pid;
700 }
701
702 /**
703  * Sets the current state.
704  * @param h Handle to hb_handle_t
705  * @param s Handle to new hb_state_t
706  */
707 void hb_set_state( hb_handle_t * h, hb_state_t * s )
708 {
709     hb_lock( h->pause_lock );
710     hb_lock( h->state_lock );
711     memcpy( &h->state, s, sizeof( hb_state_t ) );
712     if( h->state.state == HB_STATE_WORKING )
713     {
714         /* XXX Hack */
715         h->state.param.working.job_cur =
716             h->job_count - hb_list_count( h->jobs );
717         h->state.param.working.job_count = h->job_count;
718     }
719     hb_unlock( h->state_lock );
720     hb_unlock( h->pause_lock );
721 }