OSDN Git Service

Bump libmkv to 0.6.4.1
[handbrake-jp/handbrake-jp-git.git] / libhb / muxcommon.c
1 /* $Id: muxcommon.c,v 1.23 2005/03/30 17:27:19 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
9 struct hb_mux_object_s
10 {
11     HB_MUX_COMMON;
12 };
13
14 typedef struct
15 {
16     hb_buffer_t **fifo;
17     uint32_t    in;     // number of bufs put into fifo
18     uint32_t    out;    // number of bufs taken out of fifo
19     uint32_t    flen;   // fifo length (must be power of two)
20 } mux_fifo_t;
21
22 typedef struct
23 {
24     hb_mux_data_t * mux_data;
25     uint64_t        frames;
26     uint64_t        bytes;
27     mux_fifo_t      mf;
28 } hb_track_t;
29
30 typedef struct
31 {
32     hb_lock_t       * mutex;
33     int               ref;
34     int               done;
35     hb_mux_object_t * m;
36     double            pts;        // end time of next muxing chunk
37     double            interleave; // size in 90KHz ticks of media chunks we mux
38     uint32_t          ntracks;    // total number of tracks we're muxing
39     uint32_t          eof;        // bitmask of track with eof
40     uint32_t          rdy;        // bitmask of tracks ready to output
41     uint32_t          allEof;     // valid bits in eof (all tracks)
42     uint32_t          allRdy;     // valid bits in rdy (audio & video tracks)
43     hb_track_t      * track[32];  // array of tracks to mux ('ntrack' elements)
44                                   // NOTE- this array could be dynamically 
45                                   // allocated but the eof & rdy logic has to 
46                                   // be changed to handle more than 32 tracks 
47                                   // anyway so we keep it simple and fast.
48 } hb_mux_t;
49
50 struct hb_work_private_s
51 {
52     hb_job_t * job;
53     int        track;
54     hb_mux_t * mux;
55 };
56
57 // The muxer handles two different kinds of media: Video and audio tracks
58 // are continuous: once they start they generate continuous, consecutive
59 // sequence of bufs until they end. The muxer will time align all continuous
60 // media tracks so that their data will be well interleaved in the output file.
61 // (Smooth, low latency playback with minimal player buffering requires that
62 // data that's going to be presented close together in time also be close
63 // together in the output file). Since HB's audio and video encoders run at
64 // different speeds, the time-aligning involves buffering *all* the continuous
65 // media tracks until a frame with a timestamp beyond the current alignment
66 // point arrives on the slowest fifo (usually the video encoder).
67 //
68 // The other kind of media, subtitles, close-captions, vobsubs and
69 // similar tracks, are intermittent. They generate frames sporadically or on
70 // human time scales (seconds) rather than near the video frame rate (milliseconds).
71 // If intermittent sources were treated like continuous sources huge sections of
72 // audio and video would get buffered waiting for the next subtitle to show up.
73 // To keep this from happening the muxer doesn't wait for intermittent tracks
74 // (essentially it assumes that they will always go through the HB processing
75 // pipeline faster than the associated video). They are still time aligned and
76 // interleaved at the appropriate point in the output file.
77
78 // This routine adds another track for the muxer to process. The media input
79 // stream will be read from HandBrake fifo 'fifo'. Buffers read from that
80 // stream will be time-aligned with all the other media streams then passed
81 // to the container-specific 'mux' routine with argument 'mux_data' (see
82 // routine OutputTrackChunk). 'is_continuous' must be 1 for an audio or video
83 // track and 0 otherwise (see above).
84
85 static void add_mux_track( hb_mux_t *mux, hb_mux_data_t *mux_data,
86                            int is_continuous )
87 {
88     int max_tracks = sizeof(mux->track) / sizeof(*(mux->track));
89     if ( mux->ntracks >= max_tracks )
90     {
91         hb_error( "add_mux_track: too many tracks (>%d)", max_tracks );
92         return;
93     }
94
95     hb_track_t *track = calloc( sizeof( hb_track_t ), 1 );
96     track->mux_data = mux_data;
97     track->mf.flen = 8;
98     track->mf.fifo = calloc( sizeof(track->mf.fifo[0]), track->mf.flen );
99
100     int t = mux->ntracks++;
101     mux->track[t] = track;
102     mux->allEof |= 1 << t;
103     mux->allRdy |= is_continuous << t;
104 }
105
106 static int mf_full( hb_track_t * track )
107 {
108     uint32_t mask = track->mf.flen - 1;
109     uint32_t in = track->mf.in;
110
111     if ( ( ( in + 1 ) & mask ) == ( track->mf.out & mask ) )
112     {
113         if ( track->mf.flen >= 256 )
114         {
115             return 1;
116         }
117     }
118     return 0;
119 }
120
121 static void mf_push( hb_mux_t * mux, int tk, hb_buffer_t *buf )
122 {
123     hb_track_t * track = mux->track[tk];
124     uint32_t mask = track->mf.flen - 1;
125     uint32_t in = track->mf.in;
126
127     if ( ( ( in + 2 ) & mask ) == ( track->mf.out & mask ) )
128     {
129         if ( track->mf.flen >= 256 )
130         {
131             mux->rdy = mux->allRdy;
132         }
133     }
134     if ( ( ( in + 1 ) & mask ) == ( track->mf.out & mask ) )
135     {
136         // fifo is full - expand it to double the current size.
137         // This is a bit tricky because when we change the size
138         // it changes the modulus (mask) used to convert the in
139         // and out counters to fifo indices. Since existing items
140         // will be referenced at a new location after the expand
141         // we can't just realloc the fifo. If there were
142         // hundreds of fifo entries it would be worth it to have code
143         // for each of the four possible before/after configurations
144         // but these fifos are small so we just allocate a new chunk
145         // of memory then do element by element copies using the old &
146         // new masks then free the old fifo's memory..
147         track->mf.flen *= 2;
148         uint32_t nmask = track->mf.flen - 1;
149         hb_buffer_t **nfifo = malloc( track->mf.flen * sizeof(*nfifo) );
150         int indx = track->mf.out;
151         while ( indx != track->mf.in )
152         {
153             nfifo[indx & nmask] = track->mf.fifo[indx & mask];
154             ++indx;
155         }
156         free( track->mf.fifo );
157         track->mf.fifo = nfifo;
158         mask = nmask;
159     }
160     track->mf.fifo[in & mask] = buf;
161     track->mf.in = in + 1;
162 }
163
164 static hb_buffer_t *mf_pull( hb_track_t *track )
165 {
166     hb_buffer_t *b = NULL;
167     if ( track->mf.out != track->mf.in )
168     {
169         // the fifo isn't empty
170         b = track->mf.fifo[track->mf.out & (track->mf.flen - 1)];
171         ++track->mf.out;
172     }
173     return b;
174 }
175
176 static hb_buffer_t *mf_peek( hb_track_t *track )
177 {
178     return track->mf.out == track->mf.in ?
179                 NULL : track->mf.fifo[track->mf.out & (track->mf.flen - 1)];
180 }
181
182 static void MoveToInternalFifos( int tk, hb_mux_t *mux, hb_buffer_t * buf )
183 {
184     // move all the buffers on the track's fifo to our internal
185     // fifo so that (a) we don't deadlock in the reader and
186     // (b) we can control how data from multiple tracks is
187     // interleaved in the output file.
188     mf_push( mux, tk, buf );
189     if ( buf->stop >= mux->pts )
190     {
191         // buffer is past our next interleave point so
192         // note that this track is ready to be output.
193         mux->rdy |= ( 1 << tk );
194     }
195 }
196
197 static void OutputTrackChunk( hb_mux_t *mux, hb_track_t *track, hb_mux_object_t *m )
198 {
199     hb_buffer_t *buf;
200
201     while ( ( buf = mf_peek( track ) ) != NULL && buf->start < mux->pts )
202     {
203         buf = mf_pull( track );
204         track->frames += 1;
205         track->bytes  += buf->size;
206         m->mux( m, track->mux_data, buf );
207     }
208 }
209
210 static int muxWork( hb_work_object_t * w, hb_buffer_t ** buf_in,
211                      hb_buffer_t ** buf_out )
212 {
213     hb_work_private_t * pv = w->private_data;
214     hb_job_t    * job = pv->job;
215     hb_mux_t    * mux = pv->mux;
216     hb_track_t  * track;
217     int           i;
218     hb_buffer_t * buf = *buf_in;
219
220     hb_lock( mux->mutex );
221     if ( mux->done )
222     {
223         hb_unlock( mux->mutex );
224         return HB_WORK_DONE;
225     }
226
227     if ( buf->size <= 0 )
228     {
229         // EOF - mark this track as done
230         hb_buffer_close( &buf );
231         mux->eof |= ( 1 << pv->track );
232         mux->rdy |= ( 1 << pv->track );
233     }
234     else if ( ( job->pass != 0 && job->pass != 2 ) ||
235               ( mux->eof & (1 << pv->track) ) )
236     {
237         hb_buffer_close( &buf );
238     }
239     else
240     {
241         MoveToInternalFifos( pv->track, mux, buf );
242     }
243     *buf_in = NULL;
244
245     if ( ( mux->rdy & mux->allRdy ) != mux->allRdy )
246     {
247         hb_unlock( mux->mutex );
248         return HB_WORK_OK;
249     }
250
251     // all tracks have at least 'interleave' ticks of data. Output
252     // all that we can in 'interleave' size chunks.
253     while ( ( mux->rdy & mux->allRdy ) == mux->allRdy )
254     {
255         for ( i = 0; i < mux->ntracks; ++i )
256         {
257             track = mux->track[i];
258             OutputTrackChunk( mux, track, mux->m );
259             if ( mf_full( track ) )
260             {
261                 // If the track's fifo is still full, advance
262                 // the currint interleave point and try again.
263                 mux->rdy = mux->allRdy;
264                 break;
265             }
266
267             // if the track is at eof or still has data that's past
268             // our next interleave point then leave it marked as rdy.
269             // Otherwise clear rdy.
270             if ( ( mux->eof & (1 << i) ) == 0 &&
271                  ( track->mf.out == track->mf.in ||
272                    track->mf.fifo[(track->mf.in-1) & (track->mf.flen-1)]->stop
273                      < mux->pts + mux->interleave ) )
274             {
275                 mux->rdy &=~ ( 1 << i );
276             }
277         }
278
279         // if all the tracks are at eof we're just purging their
280         // remaining data -- keep going until all internal fifos are empty.
281         if ( mux->eof == mux->allEof )
282         {
283             for ( i = 0; i < mux->ntracks; ++i )
284             {
285                 if ( mux->track[i]->mf.out != mux->track[i]->mf.in )
286                 {
287                     break;
288                 }
289             }
290             if ( i >= mux->ntracks )
291             {
292                 mux->done = 1;
293                 hb_unlock( mux->mutex );
294                 return HB_WORK_DONE;
295             }
296         }
297         mux->pts += mux->interleave;
298     }
299     hb_unlock( mux->mutex );
300     return HB_WORK_OK;
301 }
302
303 void muxClose( hb_work_object_t * w )
304 {
305     hb_work_private_t * pv = w->private_data;
306     hb_mux_t    * mux = pv->mux;
307     hb_job_t    * job = pv->job;
308     hb_track_t  * track;
309     int           i;
310
311     hb_lock( mux->mutex );
312     if ( --mux->ref == 0 )
313     {
314         // Update state before closing muxer.  Closing the muxer
315         // may initiate optimization which can take a while and
316         // we want the muxing state to be visible while this is
317         // happening.
318         if( job->pass == 0 || job->pass == 2 )
319         {
320             /* Update the UI */
321             hb_state_t state;
322             state.state = HB_STATE_MUXING;
323             state.param.muxing.progress = 0;
324             hb_set_state( job->h, &state );
325         }
326
327         if( mux->m )
328         {
329             mux->m->end( mux->m );
330             free( mux->m );
331         }
332
333         // we're all done muxing -- print final stats and cleanup.
334         if( job->pass == 0 || job->pass == 2 )
335         {
336             struct stat sb;
337             uint64_t bytes_total, frames_total;
338
339             if( !stat( job->file, &sb ) )
340             {
341                 hb_deep_log( 2, "mux: file size, %"PRId64" bytes", (uint64_t) sb.st_size );
342
343                 bytes_total  = 0;
344                 frames_total = 0;
345                 for( i = 0; i < mux->ntracks; ++i )
346                 {
347                     track = mux->track[i];
348                     hb_log( "mux: track %d, %"PRId64" frames, %"PRId64" bytes, %.2f kbps, fifo %d",
349                             i, track->frames, track->bytes,
350                             90000.0 * track->bytes / mux->pts / 125,
351                             track->mf.flen );
352                     if( !i && ( job->vquality < 0.0 || job->vquality > 1.0 ) )
353                     {
354                         /* Video */
355                         hb_deep_log( 2, "mux: video bitrate error, %+"PRId64" bytes",
356                                 (int64_t)(track->bytes - mux->pts * job->vbitrate * 125 / 90000) );
357                     }
358                     bytes_total  += track->bytes;
359                     frames_total += track->frames;
360                 }
361
362                 if( bytes_total && frames_total )
363                 {
364                     hb_deep_log( 2, "mux: overhead, %.2f bytes per frame",
365                             (float) ( sb.st_size - bytes_total ) /
366                             frames_total );
367                 }
368             }
369         }
370     
371         for( i = 0; i < mux->ntracks; ++i )
372         {
373             track = mux->track[i];
374             if( track->mux_data )
375             {
376                 free( track->mux_data );
377                 free( track->mf.fifo );
378             }
379             free( track );
380         }
381         hb_unlock( mux->mutex );
382         hb_lock_close( &mux->mutex );
383         free( mux );
384     }
385     else
386     {
387         hb_unlock( mux->mutex );
388     }
389     free( pv );
390     w->private_data = NULL;
391 }
392
393 static void mux_loop( void * _w )
394 {
395     hb_work_object_t  * w = _w;
396     hb_work_private_t * pv = w->private_data;
397     hb_job_t          * job = pv->job;
398     hb_buffer_t       * buf_in;
399
400     while ( !*job->die && w->status != HB_WORK_DONE )
401     {
402         buf_in = hb_fifo_get_wait( w->fifo_in );
403         if ( pv->mux->done )
404             break;
405         if ( buf_in == NULL )
406             continue;
407         if ( *job->die )
408         {
409             if( buf_in )
410             {
411                 hb_buffer_close( &buf_in );
412             }
413             break;
414         }
415
416         w->status = w->work( w, &buf_in, NULL );
417         if( buf_in )
418         {
419             hb_buffer_close( &buf_in );
420         }
421     }
422 }
423
424 hb_work_object_t * hb_muxer_init( hb_job_t * job )
425 {
426     hb_title_t  * title = job->title;
427     int           i;
428     hb_mux_t    * mux = calloc( sizeof( hb_mux_t ), 1 );
429     hb_work_object_t  * w;
430     hb_work_object_t  * muxer;
431
432     mux->mutex = hb_lock_init();
433
434     // set up to interleave track data in blocks of 1 video frame time.
435     // (the best case for buffering and playout latency). The container-
436     // specific muxers can reblock this into bigger chunks if necessary.
437     mux->interleave = 90000. * (double)job->vrate_base / (double)job->vrate;
438     mux->pts = mux->interleave;
439
440     /* Get a real muxer */
441     if( job->pass == 0 || job->pass == 2)
442     {
443         switch( job->mux )
444         {
445         case HB_MUX_MP4:
446         case HB_MUX_PSP:
447         case HB_MUX_IPOD:
448             mux->m = hb_mux_mp4_init( job );
449             break;
450         case HB_MUX_AVI:
451             mux->m = hb_mux_avi_init( job );
452             break;
453         case HB_MUX_OGM:
454             mux->m = hb_mux_ogm_init( job );
455             break;
456         case HB_MUX_MKV:
457             mux->m = hb_mux_mkv_init( job );
458             break;
459         default:
460             hb_error( "No muxer selected, exiting" );
461             *job->die = 1;
462             return NULL;
463         }
464         /* Create file, write headers */
465         if( mux->m )
466         {
467             mux->m->init( mux->m );
468         }
469     }
470
471     /* Initialize the work objects that will receive fifo data */
472
473     muxer = hb_get_work( WORK_MUX );
474     muxer->private_data = calloc( sizeof( hb_work_private_t ), 1 );
475     muxer->private_data->job = job;
476     muxer->private_data->mux = mux;
477     mux->ref++;
478     muxer->private_data->track = mux->ntracks;
479     muxer->fifo_in = job->fifo_mpeg4;
480     add_mux_track( mux, job->mux_data, 1 );
481     muxer->done = &muxer->private_data->mux->done;
482
483     for( i = 0; i < hb_list_count( title->list_audio ); i++ )
484     {
485         hb_audio_t  *audio = hb_list_item( title->list_audio, i );
486
487         w = hb_get_work( WORK_MUX );
488         w->private_data = calloc( sizeof( hb_work_private_t ), 1 );
489         w->private_data->job = job;
490         w->private_data->mux = mux;
491         mux->ref++;
492         w->private_data->track = mux->ntracks;
493         w->fifo_in = audio->priv.fifo_out;
494         add_mux_track( mux, audio->priv.mux_data, 1 );
495         w->done = &job->done;
496         hb_list_add( job->list_work, w );
497         w->thread = hb_thread_init( w->name, mux_loop, w, HB_NORMAL_PRIORITY );
498     }
499
500     for( i = 0; i < hb_list_count( title->list_subtitle ); i++ )
501     {
502         hb_subtitle_t  *subtitle = hb_list_item( title->list_subtitle, i );
503
504         if (subtitle->config.dest != PASSTHRUSUB)
505             continue;
506
507         w = hb_get_work( WORK_MUX );
508         w->private_data = calloc( sizeof( hb_work_private_t ), 1 );
509         w->private_data->job = job;
510         w->private_data->mux = mux;
511         mux->ref++;
512         w->private_data->track = mux->ntracks;
513         w->fifo_in = subtitle->fifo_out;
514         add_mux_track( mux, subtitle->mux_data, 0 );
515         w->done = &job->done;
516         hb_list_add( job->list_work, w );
517         w->thread = hb_thread_init( w->name, mux_loop, w, HB_NORMAL_PRIORITY );
518     }
519     return muxer;
520 }
521
522 // muxInit does nothing because the muxer has a special initializer
523 // that takes care of initializing all muxer work objects
524 static int muxInit( hb_work_object_t * w, hb_job_t * job )
525 {
526     return 0;
527 }
528
529 hb_work_object_t hb_muxer =
530 {
531     WORK_MUX,
532     "Muxer",
533     muxInit,
534     muxWork,
535     muxClose
536 };
537