OSDN Git Service

cli: make smarter mixdown decision when doing ac3 encode fallback
[handbrake-jp/handbrake-jp-git.git] / libhb / work.c
1 /* $Id: work.c,v 1.43 2005/03/17 16:38:49 titer Exp $
2
3    This file is part of the HandBrake source code.
4    Homepage: <http://handbrake.fr/>.
5    It may be used under the terms of the GNU General Public License. */
6
7 #include "hb.h"
8 #include "a52dec/a52.h"
9 #include "dca.h"
10 #include "libavformat/avformat.h"
11
12 typedef struct
13 {
14     hb_list_t * jobs;
15     hb_job_t  ** current_job;
16     int         cpu_count;
17     int       * error;
18     volatile int * die;
19
20 } hb_work_t;
21
22 static void work_func();
23 static void do_job( hb_job_t *, int cpu_count );
24 static void work_loop( void * );
25
26 #define FIFO_LARGE 32
27 #define FIFO_LARGE_WAKE 16
28 #define FIFO_SMALL 16
29 #define FIFO_SMALL_WAKE 15
30
31 /**
32  * Allocates work object and launches work thread with work_func.
33  * @param jobs Handle to hb_list_t.
34  * @param cpu_count Humber of CPUs found in system.
35  * @param die Handle to user inititated exit indicator.
36  * @param error Handle to error indicator.
37  */
38 hb_thread_t * hb_work_init( hb_list_t * jobs, int cpu_count,
39                             volatile int * die, int * error, hb_job_t ** job )
40 {
41     hb_work_t * work = calloc( sizeof( hb_work_t ), 1 );
42
43     work->jobs      = jobs;
44     work->current_job = job;
45     work->cpu_count = cpu_count;
46     work->die       = die;
47     work->error     = error;
48
49     return hb_thread_init( "work", work_func, work, HB_LOW_PRIORITY );
50 }
51
52 static void InitWorkState( hb_handle_t * h )
53 {
54     hb_state_t state;
55
56     state.state = HB_STATE_WORKING;
57 #define p state.param.working
58     p.progress  = 0.0;
59     p.rate_cur  = 0.0;
60     p.rate_avg  = 0.0;
61     p.hours     = -1;
62     p.minutes   = -1;
63     p.seconds   = -1; 
64 #undef p
65
66     hb_set_state( h, &state );
67
68 }
69
70 /**
71  * Iterates through job list and calls do_job for each job.
72  * @param _work Handle work object.
73  */
74 static void work_func( void * _work )
75 {
76     hb_work_t  * work = _work;
77     hb_job_t   * job;
78
79     hb_log( "%d job(s) to process", hb_list_count( work->jobs ) );
80
81     while( !*work->die && ( job = hb_list_item( work->jobs, 0 ) ) )
82     {
83         hb_list_rem( work->jobs, job );
84         job->die = work->die;
85         *(work->current_job) = job;
86         InitWorkState( job->h );
87         do_job( job, work->cpu_count );
88         *(work->current_job) = NULL;
89     }
90
91     *(work->error) = HB_ERROR_NONE;
92
93     free( work );
94 }
95
96 hb_work_object_t * hb_get_work( int id )
97 {
98     hb_work_object_t * w;
99     for( w = hb_objects; w; w = w->next )
100     {
101         if( w->id == id )
102         {
103             hb_work_object_t *wc = malloc( sizeof(*w) );
104             *wc = *w;
105             return wc;
106         }
107     }
108     return NULL;
109 }
110
111 hb_work_object_t * hb_codec_decoder( int codec )
112 {
113     switch( codec )
114     {
115         case HB_ACODEC_AC3:  return hb_get_work( WORK_DECA52 );
116         case HB_ACODEC_DCA:  return hb_get_work( WORK_DECDCA );
117         case HB_ACODEC_MPGA: return hb_get_work( WORK_DECAVCODEC );
118         case HB_ACODEC_LPCM: return hb_get_work( WORK_DECLPCM );
119         case HB_ACODEC_FFMPEG: return hb_get_work( WORK_DECAVCODECAI );
120     }
121     return NULL;
122 }
123
124 hb_work_object_t * hb_codec_encoder( int codec )
125 {
126     switch( codec )
127     {
128         case HB_ACODEC_FAAC:   return hb_get_work( WORK_ENCFAAC );
129         case HB_ACODEC_LAME:   return hb_get_work( WORK_ENCLAME );
130         case HB_ACODEC_VORBIS: return hb_get_work( WORK_ENCVORBIS );
131         case HB_ACODEC_CA_AAC: return hb_get_work( WORK_ENC_CA_AAC );
132         case HB_ACODEC_AC3:    return hb_get_work( WORK_ENCAC3 );
133     }
134     return NULL;
135 }
136
137 /**
138  * Displays job parameters in the debug log.
139  * @param job Handle work hb_job_t.
140  */
141 void hb_display_job_info( hb_job_t * job )
142 {
143     hb_title_t * title = job->title;
144     hb_audio_t   * audio;
145     hb_subtitle_t * subtitle;
146     int             i, j;
147     
148     hb_log("job configuration:");
149     hb_log( " * source");
150     
151     hb_log( "   + %s", title->path );
152
153     hb_log( "   + title %d, chapter(s) %d to %d", title->index,
154             job->chapter_start, job->chapter_end );
155
156     if( title->container_name != NULL )
157         hb_log( "   + container: %s", title->container_name);
158
159     if( title->data_rate )
160     {
161         hb_log( "   + data rate: %d kbps", title->data_rate / 1000 );
162     }
163     
164     hb_log( " * destination");
165
166     hb_log( "   + %s", job->file );
167
168     switch( job->mux )
169     {
170         case HB_MUX_MP4:
171             hb_log("   + container: MPEG-4 (.mp4 and .m4v)");
172             
173             if( job->ipod_atom )
174                 hb_log( "     + compatibility atom for iPod 5G");
175
176             if( job->largeFileSize )
177                 hb_log( "     + 64-bit formatting");
178
179             if( job->mp4_optimize )
180                 hb_log( "     + optimized for progressive web downloads");
181             
182             if( job->color_matrix )
183                 hb_log( "     + custom color matrix: %s", job->color_matrix == 1 ? "ITU Bt.601 (SD)" : "ITU Bt.709 (HD)");
184             break;
185
186         case HB_MUX_AVI:
187             hb_log("   + container: AVI");
188             break;
189
190         case HB_MUX_MKV:
191             hb_log("   + container: Matroska (.mkv)");
192             break;
193
194         case HB_MUX_OGM:
195             hb_log("   + conttainer: Ogg Media (.ogm)");
196             break;
197     }
198
199     if( job->chapter_markers )
200     {
201         hb_log( "     + chapter markers" );
202     }
203     
204     hb_log(" * video track");
205     
206     hb_log("   + decoder: %s", title->video_codec_name );
207     
208     if( title->video_bitrate )
209     {
210         hb_log( "     + bitrate %d kbps", title->video_bitrate / 1000 );
211     }
212     
213     if( !job->cfr )
214     {
215         hb_log( "   + frame rate: same as source (around %.3f fps)",
216             (float) title->rate / (float) title->rate_base );
217     }
218     else
219     {
220         static const char *frtypes[] = {
221             "", "constant", "peak rate limited to"
222         };
223         hb_log( "   + frame rate: %.3f fps -> %s %.3f fps",
224             (float) title->rate / (float) title->rate_base, frtypes[job->cfr],
225             (float) job->vrate / (float) job->vrate_base );
226     }
227
228     if( job->anamorphic.mode )
229     {
230         hb_log( "   + %s anamorphic", job->anamorphic.mode == 1 ? "strict" : job->anamorphic.mode == 2? "loose" : "custom" );
231         if( job->anamorphic.mode == 3 && job->anamorphic.keep_display_aspect )
232         {
233             hb_log( "     + keeping source display aspect ratio"); 
234         }
235         hb_log( "     + storage dimensions: %d * %d -> %d * %d, crop %d/%d/%d/%d, mod %i",
236                     title->width, title->height, job->width, job->height,
237                     job->crop[0], job->crop[1], job->crop[2], job->crop[3], job->modulus );
238         if( job->anamorphic.itu_par )
239         {
240             hb_log( "     + using ITU pixel aspect ratio values"); 
241         }
242         hb_log( "     + pixel aspect ratio: %i / %i", job->anamorphic.par_width, job->anamorphic.par_height );
243         hb_log( "     + display dimensions: %.0f * %i",
244             (float)( job->width * job->anamorphic.par_width / job->anamorphic.par_height ), job->height );
245     }
246     else
247     {
248         hb_log( "   + dimensions: %d * %d -> %d * %d, crop %d/%d/%d/%d",
249                 title->width, title->height, job->width, job->height,
250                 job->crop[0], job->crop[1], job->crop[2], job->crop[3] );
251     }
252
253     if ( job->grayscale )
254         hb_log( "   + grayscale mode" );
255
256     if( hb_list_count( job->filters ) )
257     {
258         hb_log("   + %s", hb_list_count( job->filters) > 1 ? "filters" : "filter" );
259         for( i = 0; i < hb_list_count( job->filters ); i++ )
260         {
261             hb_filter_object_t * filter = hb_list_item( job->filters, i );
262             if (filter->settings)
263                 hb_log("     + %s (%s)", filter->name, filter->settings);
264             else
265                 hb_log("     + %s (default settings)", filter->name);
266         }
267     }
268     
269     if( !job->indepth_scan )
270     {
271         /* Video encoder */
272         switch( job->vcodec )
273         {
274             case HB_VCODEC_FFMPEG:
275                 hb_log( "   + encoder: FFmpeg" );
276                 break;
277
278             case HB_VCODEC_X264:
279                 hb_log( "   + encoder: x264" );
280                 if( job->x264opts != NULL && *job->x264opts != '\0' )
281                     hb_log( "     + options: %s", job->x264opts);
282                 break;
283
284             case HB_VCODEC_THEORA:
285                 hb_log( "   + encoder: Theora" );
286                 break;
287         }
288
289         if( job->vquality >= 0.0 && job->vquality <= 1.0 )
290         {
291             hb_log( "     + quality: %.2f", job->vquality );
292         }
293         else if( job->vquality > 1 )
294         {
295             hb_log( "     + quality: %.2f %s", job->vquality, job->vcodec == HB_VCODEC_X264 ? "(RF)" : "(QP)" ); 
296         }
297         else
298         {
299             hb_log( "     + bitrate: %d kbps, pass: %d", job->vbitrate, job->pass );
300         }
301     }
302
303     for( i=0; i < hb_list_count( title->list_subtitle ); i++ )
304     {
305         subtitle =  hb_list_item( title->list_subtitle, i );
306
307         if( subtitle )
308         {
309             if( subtitle->source == SRTSUB )
310             {
311                 /* For SRT, print offset and charset too */
312                 hb_log( " * subtitle track %i, %s (id %x) %s [%s] -> %s%s, offset: %"PRId64", charset: %s",
313                         subtitle->track, subtitle->lang, subtitle->id, "Text", "SRT", "Pass-Through",
314                         subtitle->config.default_track ? ", Default" : "",
315                         subtitle->config.offset, subtitle->config.src_codeset );
316             }
317             else
318             {
319                 hb_log( " * subtitle track %i, %s (id %x) %s [%s] -> %s%s%s", subtitle->track, subtitle->lang, subtitle->id,
320                         subtitle->format == PICTURESUB ? "Picture" : "Text",
321                         hb_subsource_name( subtitle->source ),
322                         job->indepth_scan ? "Foreign Audio Search" :
323                         subtitle->config.dest == RENDERSUB ? "Render/Burn in" : "Pass-Through",
324                         subtitle->config.force ? ", Forced Only" : "",
325                         subtitle->config.default_track ? ", Default" : "" );
326             }
327         }
328     }
329
330     if( !job->indepth_scan )
331     {
332         for( i = 0; i < hb_list_count( title->list_audio ); i++ )
333         {
334             audio = hb_list_item( title->list_audio, i );
335
336             hb_log( " * audio track %d", audio->config.out.track );
337             
338             if( audio->config.out.name )
339                 hb_log( "   + name: %s", audio->config.out.name );
340
341             hb_log( "   + decoder: %s (track %d, id %x)", audio->config.lang.description, audio->config.in.track + 1, audio->id );
342
343             if( ( audio->config.in.codec == HB_ACODEC_AC3 ) || ( audio->config.in.codec == HB_ACODEC_DCA) )
344             {
345                 hb_log( "     + bitrate: %d kbps, samplerate: %d Hz", audio->config.in.bitrate / 1000, audio->config.in.samplerate );
346             }
347
348             if( (audio->config.out.codec != HB_ACODEC_AC3_PASS) && (audio->config.out.codec != HB_ACODEC_DCA_PASS) )
349             {
350                 for (j = 0; j < hb_audio_mixdowns_count; j++)
351                 {
352                     if (hb_audio_mixdowns[j].amixdown == audio->config.out.mixdown) {
353                         hb_log( "   + mixdown: %s", hb_audio_mixdowns[j].human_readable_name );
354                         break;
355                     }
356                 }
357             }
358
359             if ( audio->config.out.dynamic_range_compression && (audio->config.out.codec != HB_ACODEC_AC3_PASS) && (audio->config.out.codec != HB_ACODEC_DCA_PASS))
360             {
361                 hb_log("   + dynamic range compression: %f", audio->config.out.dynamic_range_compression);
362             }
363             
364             if( (audio->config.out.codec == HB_ACODEC_AC3_PASS) || (audio->config.out.codec == HB_ACODEC_DCA_PASS) )
365             {
366                 hb_log( "   + %s passthrough", (audio->config.out.codec == HB_ACODEC_AC3_PASS) ?
367                     "AC3" : "DCA" );
368             }
369             else
370             {
371                 hb_log( "   + encoder: %s", 
372                     ( audio->config.out.codec == HB_ACODEC_FAAC ) ?  "faac" : 
373                     ( ( audio->config.out.codec == HB_ACODEC_LAME ) ?  "lame" : 
374                     ( ( audio->config.out.codec == HB_ACODEC_CA_AAC ) ?  "ca_aac" : 
375                     ( ( audio->config.out.codec == HB_ACODEC_AC3 ) ?  "ffac3" : 
376                     "vorbis"  ) ) ) );
377                 hb_log( "     + bitrate: %d kbps, samplerate: %d Hz", audio->config.out.bitrate, audio->config.out.samplerate );            
378             }
379         }
380     }
381 }
382
383 /* Corrects framerates when actual duration and frame count numbers are known. */
384 void correct_framerate( hb_job_t * job )
385 {
386     int real_frames;
387
388     hb_interjob_t * interjob = hb_interjob_get( job->h );
389
390     if( ( job->sequence_id & 0xFFFFFF ) != ( interjob->last_job & 0xFFFFFF) )
391         return; // Interjob information is for a different encode.
392
393     /* Cache the original framerate before altering it. */
394     interjob->vrate = job->vrate;
395     interjob->vrate_base = job->vrate_base;
396
397     real_frames = interjob->frame_count - interjob->render_dropped;
398
399     job->vrate = job->vrate_base * ( (double)real_frames * 90000 / interjob->total_time );
400 }
401
402 /**
403  * Job initialization rountine.
404  * Initializes fifos.
405  * Creates work objects for synchronizer, video decoder, video renderer, video decoder, audio decoder, audio encoder, reader, muxer.
406  * Launches thread for each work object with work_loop.
407  * Loops while monitoring status of work threads and fifos.
408  * Exits loop when conversion is done and fifos are empty.
409  * Closes threads and frees fifos.
410  * @param job Handle work hb_job_t.
411  * @param cpu_count number of CPUs found in system.
412  */
413 static void do_job( hb_job_t * job, int cpu_count )
414 {
415     hb_title_t    * title;
416     int             i, j;
417     hb_work_object_t * w;
418     hb_work_object_t * sync;
419     hb_work_object_t * muxer;
420     hb_interjob_t * interjob;
421
422     hb_audio_t   * audio;
423     hb_subtitle_t * subtitle;
424     hb_attachment_t * attachment;
425     unsigned int subtitle_highest = 0;
426     unsigned int subtitle_highest_id = 0;
427     unsigned int subtitle_lowest = -1;
428     unsigned int subtitle_lowest_id = 0;
429     unsigned int subtitle_forced_id = 0;
430     unsigned int subtitle_hit = 0;
431
432     title = job->title;
433     interjob = hb_interjob_get( job->h );
434
435     if( job->pass == 2 && !job->cfr )
436     {
437         correct_framerate( job );
438     }
439
440     job->list_work = hb_list_init();
441
442     hb_log( "starting job" );
443
444     if( job->anamorphic.mode )
445     {
446         hb_set_anamorphic_size(job, &job->width, &job->height, &job->anamorphic.par_width, &job->anamorphic.par_height);
447
448         if( job->vcodec == HB_VCODEC_FFMPEG )
449         {
450             /* Just to make working with ffmpeg even more fun,
451                lavc's MPEG-4 encoder can't handle PAR values >= 255,
452                even though AVRational does. Adjusting downwards
453                distorts the display aspect slightly, but such is life. */
454             while ((job->anamorphic.par_width & ~0xFF) ||
455                    (job->anamorphic.par_height & ~0xFF))
456             {
457                 job->anamorphic.par_width >>= 1;
458                 job->anamorphic.par_height >>= 1;
459             }
460         }
461     }
462     
463     /* Keep width and height within these boundaries,
464        but ignore for anamorphic. For "loose" anamorphic encodes,
465        this stuff is covered in the pixel_ratio section above.    */
466     if ( job->maxHeight && ( job->height > job->maxHeight ) && ( !job->anamorphic.mode ) )
467     {
468         job->height = job->maxHeight;
469         hb_fix_aspect( job, HB_KEEP_HEIGHT );
470         hb_log( "Height out of bounds, scaling down to %i", job->maxHeight );
471         hb_log( "New dimensions %i * %i", job->width, job->height );
472     }
473     if ( job->maxWidth && ( job->width > job->maxWidth ) && ( !job->anamorphic.mode ) )
474     {
475         job->width = job->maxWidth;
476         hb_fix_aspect( job, HB_KEEP_WIDTH );
477         hb_log( "Width out of bounds, scaling down to %i", job->maxWidth );
478         hb_log( "New dimensions %i * %i", job->width, job->height );
479     }
480
481     if( job->mux & HB_MUX_AVI )
482     {
483         // The concept of variable frame rate video was a bit too advanced
484         // for Microsoft so AVI doesn't support it. Since almost all dvd
485         // video is VFR we have to convert it to constant frame rate to
486         // put it in an AVI container. So duplicate, drop and
487         // otherwise trash video frames to appease the gods of Redmond.
488         job->cfr = 1;
489     }
490
491     if ( job->cfr == 0 )
492     {
493         /* Ensure we're using "Same as source" FPS */
494         job->vrate_base = title->rate_base;
495     }
496
497     job->fifo_mpeg2  = hb_fifo_init( FIFO_LARGE, FIFO_LARGE_WAKE );
498     job->fifo_raw    = hb_fifo_init( FIFO_SMALL, FIFO_SMALL_WAKE );
499     job->fifo_sync   = hb_fifo_init( FIFO_SMALL, FIFO_SMALL_WAKE );
500     job->fifo_render = hb_fifo_init( FIFO_SMALL, FIFO_SMALL_WAKE );
501     job->fifo_mpeg4  = hb_fifo_init( FIFO_LARGE, FIFO_LARGE_WAKE );
502
503     /*
504      * Audio fifos must be initialized before sync
505      */
506     if( !job->indepth_scan )
507     {
508     // if we are doing passthru, and the input codec is not the same as the output
509     // codec, then remove this audio from the job. If we're not doing passthru and
510     // the input codec is the 'internal' ffmpeg codec, make sure that only one
511     // audio references that audio stream since the codec context is specific to
512     // the audio id & multiple copies of the same stream will garble the audio
513     // or cause aborts.
514     uint8_t aud_id_uses[MAX_STREAMS];
515     memset( aud_id_uses, 0, sizeof(aud_id_uses) );
516     for( i = 0; i < hb_list_count( title->list_audio ); )
517     {
518         audio = hb_list_item( title->list_audio, i );
519         if( ( ( audio->config.out.codec == HB_ACODEC_AC3_PASS ) && ( audio->config.in.codec != HB_ACODEC_AC3 ) ) ||
520             ( ( audio->config.out.codec == HB_ACODEC_DCA_PASS ) && ( audio->config.in.codec != HB_ACODEC_DCA ) ) )
521         {
522             hb_log( "Passthru requested and input codec is not the same as output codec for track %d",
523                     audio->config.out.track );
524             hb_list_rem( title->list_audio, audio );
525             free( audio );
526             continue;
527         }
528         if( audio->config.out.codec != HB_ACODEC_AC3_PASS && 
529             audio->config.out.codec != HB_ACODEC_DCA_PASS &&
530             audio->config.out.samplerate > 48000 )
531         {
532             hb_log( "Sample rate %d not supported.  Down-sampling to 48kHz.",
533                     audio->config.out.samplerate );
534             audio->config.out.samplerate = 48000;
535         }
536         if( audio->config.out.codec == HB_ACODEC_AC3 && 
537             audio->config.out.bitrate > 640 )
538         {
539             hb_log( "Bitrate %d not supported.  Reducing to 640Kbps.",
540                     audio->config.out.bitrate );
541             audio->config.out.bitrate = 640;
542         }
543         if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
544         {
545             if ( aud_id_uses[audio->id] )
546             {
547                 hb_log( "Multiple decodes of audio id %d, removing track %d",
548                         audio->id, audio->config.out.track );
549                 hb_list_rem( title->list_audio, audio );
550                 free( audio );
551                 continue;
552             }
553             ++aud_id_uses[audio->id];
554         }
555         /* Adjust output track number, in case we removed one.
556          * Output tracks sadly still need to be in sequential order.
557          */
558         audio->config.out.track = i++;
559     }
560
561     int requested_mixdown = 0;
562     int best_mixdown = 0;
563     int requested_mixdown_index = 0;
564
565     for( i = 0; i < hb_list_count( title->list_audio ); i++ )
566     {
567         audio = hb_list_item( title->list_audio, i );
568
569         best_mixdown = hb_get_best_mixdown( audio->config.out.codec,
570                                             audio->config.in.channel_layout );
571
572         /* sense-check the current mixdown options */
573
574         /* log the requested mixdown */
575         for (j = 0; j < hb_audio_mixdowns_count; j++) {
576             if (hb_audio_mixdowns[j].amixdown == audio->config.out.mixdown) {
577                 requested_mixdown = audio->config.out.mixdown;
578                 requested_mixdown_index = j;
579             }
580         }
581
582         /* sense-check the requested mixdown */
583         if( audio->config.out.mixdown == 0 &&
584             audio->config.out.codec != HB_ACODEC_AC3_PASS && 
585             audio->config.out.codec != HB_ACODEC_DCA_PASS )
586         {
587             /*
588              * Mixdown wasn't specified and this is not pass-through,
589              * set a default mixdown
590              */
591             audio->config.out.mixdown = best_mixdown;
592         }
593
594         if ( !( audio->config.out.codec & HB_ACODEC_PASS_FLAG ) )
595         {
596             if ( audio->config.out.mixdown > best_mixdown )
597             {
598                 audio->config.out.mixdown = best_mixdown;
599             }
600         }
601
602         if ( audio->config.out.mixdown != requested_mixdown )
603         {
604             /* log the output mixdown */
605             for (j = 0; j < hb_audio_mixdowns_count; j++)
606             {
607                 if (hb_audio_mixdowns[j].amixdown == audio->config.out.mixdown)
608                 {
609                     hb_log("work: sanitizing track %i mixdown %s to %s", i, hb_audio_mixdowns[requested_mixdown_index].human_readable_name, hb_audio_mixdowns[j].human_readable_name);
610                 break;
611                 }
612             }
613         }
614
615         if (audio->config.out.codec == HB_ACODEC_VORBIS)
616             audio->priv.config.vorbis.language = audio->config.lang.simple;
617
618         /* set up the audio work structures */
619         audio->priv.fifo_in   = hb_fifo_init( FIFO_LARGE, FIFO_LARGE_WAKE );
620         audio->priv.fifo_raw  = hb_fifo_init( FIFO_SMALL, FIFO_SMALL_WAKE );
621         audio->priv.fifo_sync = hb_fifo_init( FIFO_SMALL, FIFO_SMALL_WAKE );
622         audio->priv.fifo_out  = hb_fifo_init( FIFO_LARGE, FIFO_LARGE_WAKE );
623     }
624
625     }
626     /* Synchronization */
627     sync = hb_sync_init( job );
628
629     /* Video decoder */
630     int vcodec = title->video_codec? title->video_codec : WORK_DECMPEG2;
631     hb_list_add( job->list_work, ( w = hb_get_work( vcodec ) ) );
632     w->codec_param = title->video_codec_param;
633     w->fifo_in  = job->fifo_mpeg2;
634     w->fifo_out = job->fifo_raw;
635
636     /* Video renderer */
637     hb_list_add( job->list_work, ( w = hb_get_work( WORK_RENDER ) ) );
638     w->fifo_in  = job->fifo_sync;
639     if( !job->indepth_scan )
640         w->fifo_out = job->fifo_render;
641     else
642         w->fifo_out = NULL;
643
644     if( !job->indepth_scan )
645     {
646
647         /* Video encoder */
648         switch( job->vcodec )
649         {
650         case HB_VCODEC_FFMPEG:
651             w = hb_get_work( WORK_ENCAVCODEC );
652             break;
653         case HB_VCODEC_X264:
654             w = hb_get_work( WORK_ENCX264 );
655             break;
656         case HB_VCODEC_THEORA:
657             w = hb_get_work( WORK_ENCTHEORA );
658             break;
659         }
660         w->fifo_in  = job->fifo_render;
661         w->fifo_out = job->fifo_mpeg4;
662         w->config   = &job->config;
663
664         hb_list_add( job->list_work, w );
665     }
666
667     /*
668      * Look for the scanned subtitle in the existing subtitle list
669      * select_subtitle implies that we did a scan.
670      */
671     if ( !job->indepth_scan && interjob->select_subtitle &&
672          ( job->pass == 0 || job->pass == 2 ) )
673     {
674         /*
675          * Disable forced subtitles if we didn't find any in the scan
676          * so that we display normal subtitles instead.
677          */
678         if( interjob->select_subtitle->config.force && 
679             interjob->select_subtitle->forced_hits == 0 )
680         {
681             interjob->select_subtitle->config.force = 0;
682         }
683         for( i=0; i < hb_list_count(title->list_subtitle); i++ )
684         {
685             subtitle =  hb_list_item( title->list_subtitle, i );
686
687             if( subtitle )
688             {
689                 /*
690                 * Remove the scanned subtitle from the subtitle list if
691                 * it would result in an identical duplicate subtitle track
692                 * or an emty track (forced and no forced hits).
693                 */
694                 if( ( interjob->select_subtitle->id == subtitle->id ) &&
695                     ( ( interjob->select_subtitle->forced_hits == 0 &&
696                         subtitle->config.force ) ||
697                     ( subtitle->config.force == interjob->select_subtitle->config.force ) ) )
698                 {
699                     *subtitle = *(interjob->select_subtitle);
700                     free( interjob->select_subtitle );
701                     interjob->select_subtitle = NULL;
702                     break;
703                 }
704             }
705         }
706
707         if( interjob->select_subtitle )
708         {
709             /*
710              * Its not in the existing list
711              *
712              * Must be second pass of a two pass with subtitle scan enabled, so
713              * add the subtitle that we found on the first pass for use in this
714              * pass.
715              */
716             hb_list_add( title->list_subtitle, interjob->select_subtitle );
717             interjob->select_subtitle = NULL;
718         }
719     }
720
721
722     for( i=0; i < hb_list_count(title->list_subtitle); i++ )
723     {
724         subtitle =  hb_list_item( title->list_subtitle, i );
725
726         if( subtitle )
727         {
728             subtitle->fifo_in   = hb_fifo_init( FIFO_SMALL, FIFO_SMALL_WAKE );
729             subtitle->fifo_raw  = hb_fifo_init( FIFO_SMALL, FIFO_SMALL_WAKE );
730             subtitle->fifo_sync = hb_fifo_init( FIFO_SMALL, FIFO_SMALL_WAKE );
731             subtitle->fifo_out  = hb_fifo_init( FIFO_SMALL, FIFO_SMALL_WAKE );
732
733             if( (!job->indepth_scan || job->select_subtitle_config.force) && 
734                 subtitle->source == VOBSUB ) {
735                 /*
736                  * Don't add threads for subtitles when we are scanning, unless
737                  * looking for forced subtitles.
738                  */
739                 w = hb_get_work( WORK_DECVOBSUB );
740                 w->fifo_in  = subtitle->fifo_in;
741                 w->fifo_out = subtitle->fifo_raw;
742                 w->subtitle = subtitle;
743                 hb_list_add( job->list_work, w );
744             }
745
746             if( !job->indepth_scan && subtitle->source == CC608SUB )
747             {
748                 w = hb_get_work( WORK_DECCC608 );
749                 w->fifo_in  = subtitle->fifo_in;
750                 w->fifo_out = subtitle->fifo_raw;
751                 hb_list_add( job->list_work, w );
752             }
753
754             if( !job->indepth_scan && subtitle->source == SRTSUB )
755             {
756                 w = hb_get_work( WORK_DECSRTSUB );
757                 w->fifo_in  = subtitle->fifo_in;
758                 w->fifo_out = subtitle->fifo_raw;
759                 w->subtitle = subtitle;
760                 hb_list_add( job->list_work, w );
761             }
762             
763             if( !job->indepth_scan && subtitle->source == UTF8SUB )
764             {
765                 w = hb_get_work( WORK_DECUTF8SUB );
766                 w->fifo_in  = subtitle->fifo_in;
767                 w->fifo_out = subtitle->fifo_raw;
768                 hb_list_add( job->list_work, w );
769             }
770             
771             if( !job->indepth_scan && subtitle->source == TX3GSUB )
772             {
773                 w = hb_get_work( WORK_DECTX3GSUB );
774                 w->fifo_in  = subtitle->fifo_in;
775                 w->fifo_out = subtitle->fifo_raw;
776                 hb_list_add( job->list_work, w );
777             }
778             
779             if( !job->indepth_scan && subtitle->source == SSASUB )
780             {
781                 w = hb_get_work( WORK_DECSSASUB );
782                 w->fifo_in  = subtitle->fifo_in;
783                 w->fifo_out = subtitle->fifo_raw;
784                 w->subtitle = subtitle;
785                 hb_list_add( job->list_work, w );
786             }
787
788             if( !job->indepth_scan && 
789                 subtitle->format == PICTURESUB
790                 && subtitle->config.dest == PASSTHRUSUB )
791             {
792                 /*
793                  * Passing through a subtitle picture, this will have to
794                  * be rle encoded before muxing.
795                  */
796                 w = hb_get_work( WORK_ENCVOBSUB );
797                 w->fifo_in  = subtitle->fifo_sync;
798                 w->fifo_out = subtitle->fifo_out;
799                 w->subtitle = subtitle;
800                 hb_list_add( job->list_work, w );
801             }
802         }
803     }
804
805     if( !job->indepth_scan )
806     {
807         for( i = 0; i < hb_list_count( title->list_audio ); i++ )
808         {
809             audio = hb_list_item( title->list_audio, i );
810
811             /*
812             * Audio Decoder Thread
813             */
814             if ( ( w = hb_codec_decoder( audio->config.in.codec ) ) == NULL )
815             {
816                 hb_error("Invalid input codec: %d", audio->config.in.codec);
817                 *job->die = 1;
818                 goto cleanup;
819             }
820             w->fifo_in  = audio->priv.fifo_in;
821             w->fifo_out = audio->priv.fifo_raw;
822             w->config   = &audio->priv.config;
823             w->audio    = audio;
824             w->codec_param = audio->config.in.codec_param;
825
826             hb_list_add( job->list_work, w );
827
828             /*
829             * Audio Encoder Thread
830             */
831             if( audio->config.out.codec != HB_ACODEC_AC3_PASS &&
832                 audio->config.out.codec != HB_ACODEC_DCA_PASS )
833             {
834                 /*
835                 * Add the encoder thread if not doing AC-3 pass through
836                 */
837                 if ( ( w = hb_codec_encoder( audio->config.out.codec ) ) == NULL )
838                 {
839                     hb_error("Invalid audio codec: %#x", audio->config.out.codec);
840                     w = NULL;
841                     *job->die = 1;
842                     goto cleanup;
843                 }
844                 w->fifo_in  = audio->priv.fifo_sync;
845                 w->fifo_out = audio->priv.fifo_out;
846                 w->config   = &audio->priv.config;
847                 w->audio    = audio;
848
849                 hb_list_add( job->list_work, w );
850             }
851         }
852     }
853     
854     if( job->chapter_markers && job->chapter_start == job->chapter_end )
855     {
856         job->chapter_markers = 0;
857         hb_log("work: only 1 chapter, disabling chapter markers");
858     }
859
860     /* Display settings */
861     hb_display_job_info( job );
862
863     /* Init read & write threads */
864     job->reader = hb_reader_init( job );
865
866
867     job->done = 0;
868
869     /* Launch processing threads */
870     for( i = 0; i < hb_list_count( job->list_work ); i++ )
871     {
872         w = hb_list_item( job->list_work, i );
873         w->done = &job->done;
874         w->thread_sleep_interval = 10;
875         if( w->init( w, job ) )
876         {
877             hb_error( "Failure to initialise thread '%s'", w->name );
878             *job->die = 1;
879             goto cleanup;
880         }
881         w->thread = hb_thread_init( w->name, work_loop, w,
882                                     HB_LOW_PRIORITY );
883     }
884
885     if ( job->indepth_scan )
886     {
887         muxer = NULL;
888         w = sync;
889         sync->done = &job->done;
890     }
891     else
892     {
893         sync->done = &job->done;
894         sync->thread_sleep_interval = 10;
895         if( sync->init( w, job ) )
896         {
897             hb_error( "Failure to initialise thread '%s'", w->name );
898             *job->die = 1;
899             goto cleanup;
900         }
901         sync->thread = hb_thread_init( sync->name, work_loop, sync,
902                                     HB_LOW_PRIORITY );
903
904         // The muxer requires track information that's set up by the encoder
905         // init routines so we have to init the muxer last.
906         muxer = hb_muxer_init( job );
907         w = muxer;
908     }
909
910     while ( !*job->die && !*w->done && w->status != HB_WORK_DONE )
911     {
912         hb_buffer_t      * buf_in, * buf_out;
913
914         buf_in = hb_fifo_get_wait( w->fifo_in );
915         if ( buf_in == NULL )
916             continue;
917         if ( *job->die )
918         {
919             if( buf_in )
920             {
921                 hb_buffer_close( &buf_in );
922             }
923             break;
924         }
925
926         buf_out = NULL;
927         w->status = w->work( w, &buf_in, &buf_out );
928
929         if( buf_in )
930         {
931             hb_buffer_close( &buf_in );
932         }
933         if ( buf_out && w->fifo_out == NULL )
934         {
935             hb_buffer_close( &buf_out );
936         }
937         if( buf_out )
938         {
939             while ( !*job->die )
940             {
941                 if ( hb_fifo_full_wait( w->fifo_out ) )
942                 {
943                     hb_fifo_push( w->fifo_out, buf_out );
944                     break;
945                 }
946             }
947         }
948     }
949
950     hb_handle_t * h = job->h;
951     hb_state_t state;
952     hb_get_state( h, &state );
953     
954     hb_log("work: average encoding speed for job is %f fps", state.param.working.rate_avg);
955
956     job->done = 1;
957     if( muxer != NULL )
958     {
959         muxer->close( muxer );
960         free( muxer );
961
962         if( sync->thread != NULL )
963         {
964             hb_thread_close( &sync->thread );
965             sync->close( sync );
966         }
967         free( sync );
968     }
969
970 cleanup:
971     /* Stop the write thread (thread_close will block until the muxer finishes) */
972     job->done = 1;
973
974     /* Close work objects */
975     while( ( w = hb_list_item( job->list_work, 0 ) ) )
976     {
977         hb_list_rem( job->list_work, w );
978         if( w->thread != NULL )
979         {
980             hb_thread_close( &w->thread );
981             w->close( w );
982         }
983         free( w );
984     }
985
986     hb_list_close( &job->list_work );
987
988     /* Stop the read thread */
989     if( job->reader != NULL )
990         hb_thread_close( &job->reader );
991
992     /* Close fifos */
993     hb_fifo_close( &job->fifo_mpeg2 );
994     hb_fifo_close( &job->fifo_raw );
995     hb_fifo_close( &job->fifo_sync );
996     hb_fifo_close( &job->fifo_render );
997     hb_fifo_close( &job->fifo_mpeg4 );
998
999     for (i=0; i < hb_list_count(title->list_subtitle); i++) {
1000         subtitle =  hb_list_item( title->list_subtitle, i);
1001         if( subtitle )
1002         {
1003             hb_fifo_close( &subtitle->fifo_in );
1004             hb_fifo_close( &subtitle->fifo_raw );
1005             hb_fifo_close( &subtitle->fifo_sync );
1006             hb_fifo_close( &subtitle->fifo_out );
1007         }
1008     }
1009     for( i = 0; i < hb_list_count( title->list_audio ); i++ )
1010     {
1011         audio = hb_list_item( title->list_audio, i );
1012         if( audio->priv.fifo_in != NULL )
1013             hb_fifo_close( &audio->priv.fifo_in );
1014         if( audio->priv.fifo_raw != NULL )
1015             hb_fifo_close( &audio->priv.fifo_raw );
1016         if( audio->priv.fifo_sync != NULL )
1017             hb_fifo_close( &audio->priv.fifo_sync );
1018         if( audio->priv.fifo_out != NULL )
1019             hb_fifo_close( &audio->priv.fifo_out );
1020     }
1021
1022     if( job->indepth_scan )
1023     {
1024         /*
1025          * Before closing the title print out our subtitle stats if we need to
1026          * Find the highest and lowest.
1027          */
1028         for( i=0; i < hb_list_count( title->list_subtitle ); i++ )
1029         {
1030             subtitle =  hb_list_item( title->list_subtitle, i );
1031
1032             hb_log( "Subtitle stream 0x%x '%s': %d hits (%d forced)",
1033                     subtitle->id, subtitle->lang, subtitle->hits,
1034                     subtitle->forced_hits );
1035
1036             if( subtitle->hits == 0 )
1037                 continue;
1038
1039             if( subtitle->hits > subtitle_highest )
1040             {
1041                 subtitle_highest = subtitle->hits;
1042                 subtitle_highest_id = subtitle->id;
1043             }
1044
1045             if( subtitle->hits < subtitle_lowest )
1046             {
1047                 subtitle_lowest = subtitle->hits;
1048                 subtitle_lowest_id = subtitle->id;
1049             }
1050
1051             if( subtitle->forced_hits > 0 )
1052             {
1053                 if( subtitle_forced_id == 0 )
1054                 {
1055                     subtitle_forced_id = subtitle->id;
1056                 }
1057             }
1058         }
1059
1060         
1061         if( subtitle_forced_id )
1062         {
1063             /*
1064              * If there are any subtitle streams with forced subtitles
1065              * then select it in preference to the lowest.
1066              */
1067             subtitle_hit = subtitle_forced_id;
1068             hb_log("Found a subtitle candidate id 0x%x (contains forced subs)",
1069                    subtitle_hit);
1070         } else if( subtitle_lowest < subtitle_highest )
1071         {
1072             /*
1073              * OK we have more than one, and the lowest is lower,
1074              * but how much lower to qualify for turning it on by
1075              * default?
1076              *
1077              * Let's say 10% as a default.
1078              */
1079             if( subtitle_lowest < ( subtitle_highest * 0.1 ) )
1080             {
1081                 subtitle_hit = subtitle_lowest_id;
1082                 hb_log( "Found a subtitle candidate id 0x%x",
1083                         subtitle_hit );
1084             } else {
1085                 hb_log( "No candidate subtitle detected during subtitle-scan");
1086             }
1087         }
1088     }
1089
1090     if( job->indepth_scan )
1091     {
1092         for( i=0; i < hb_list_count( title->list_subtitle ); i++ )
1093         {
1094             subtitle =  hb_list_item( title->list_subtitle, i );
1095             if( subtitle->id == subtitle_hit )
1096             {
1097                 subtitle->config = job->select_subtitle_config;
1098                 hb_list_rem( title->list_subtitle, subtitle );
1099                 interjob->select_subtitle = subtitle;
1100                 break;
1101             }
1102         }
1103     }
1104
1105     if( job->filters )
1106     {
1107         for( i = 0; i < hb_list_count( job->filters ); i++ )
1108         {
1109             hb_filter_object_t * filter = hb_list_item( job->filters, i );
1110             hb_filter_close( &filter );
1111         }
1112         hb_list_close( &job->filters );
1113     }
1114
1115     hb_buffer_pool_free();
1116
1117     hb_title_close( &job->title );
1118     free( job );
1119 }
1120
1121 /**
1122  * Performs the work object's specific work function.
1123  * Loops calling work function for associated work object. Sleeps when fifo is full.
1124  * Monitors work done indicator.
1125  * Exits loop when work indiactor is set.
1126  * @param _w Handle to work object.
1127  */
1128 static void work_loop( void * _w )
1129 {
1130     hb_work_object_t * w = _w;
1131     hb_buffer_t      * buf_in, * buf_out;
1132
1133     while( !*w->done && w->status != HB_WORK_DONE )
1134     {
1135         buf_in = hb_fifo_get_wait( w->fifo_in );
1136         if ( buf_in == NULL )
1137             continue;
1138         if ( *w->done )
1139         {
1140             if( buf_in )
1141             {
1142                 hb_buffer_close( &buf_in );
1143             }
1144             break;
1145         }
1146
1147         // Invalidate buf_out so that if there is no output
1148         // we don't try to pass along junk.
1149         buf_out = NULL;
1150         w->status = w->work( w, &buf_in, &buf_out );
1151
1152         // Propagate any chapter breaks for the worker if and only if the
1153         // output frame has the same time stamp as the input frame (any
1154         // worker that delays frames has to propagate the chapter marks itself
1155         // and workers that move chapter marks to a different time should set
1156         // 'buf_in' to NULL so that this code won't generate spurious duplicates.)
1157         if( buf_in && buf_out && buf_in->new_chap && buf_in->start == buf_out->start)
1158         {
1159             // restore log below to debug chapter mark propagation problems
1160             //hb_log("work %s: Copying Chapter Break @ %"PRId64, w->name, buf_in->start);
1161             buf_out->new_chap = buf_in->new_chap;
1162         }
1163
1164         if( buf_in )
1165         {
1166             hb_buffer_close( &buf_in );
1167         }
1168         if ( buf_out && w->fifo_out == NULL )
1169         {
1170             hb_buffer_close( &buf_out );
1171         }
1172         if( buf_out )
1173         {
1174             while ( !*w->done )
1175             {
1176                 if ( hb_fifo_full_wait( w->fifo_out ) )
1177                 {
1178                     hb_fifo_push( w->fifo_out, buf_out );
1179                     break;
1180                 }
1181             }
1182         }
1183     }
1184     // Consume data in incoming fifo till job complete so that
1185     // residual data does not stall the pipeline
1186     while( !*w->done )
1187     {
1188         buf_in = hb_fifo_get_wait( w->fifo_in );
1189         if ( buf_in != NULL )
1190             hb_buffer_close( &buf_in );
1191     }
1192 }