1 /* $Id: muxcommon.c,v 1.23 2005/03/30 17:27:19 titer Exp $
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. */
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)
24 hb_mux_data_t * mux_data;
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.
50 struct hb_work_private_s
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).
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.
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).
85 static void add_mux_track( hb_mux_t *mux, hb_mux_data_t *mux_data,
88 int max_tracks = sizeof(mux->track) / sizeof(*(mux->track));
89 if ( mux->ntracks >= max_tracks )
91 hb_error( "add_mux_track: too many tracks (>%d)", max_tracks );
95 hb_track_t *track = calloc( sizeof( hb_track_t ), 1 );
96 track->mux_data = mux_data;
98 track->mf.fifo = calloc( sizeof(track->mf.fifo[0]), track->mf.flen );
100 int t = mux->ntracks++;
101 mux->track[t] = track;
102 mux->allEof |= 1 << t;
103 mux->allRdy |= is_continuous << t;
106 static void mf_push( hb_track_t *track, hb_buffer_t *buf )
108 uint32_t mask = track->mf.flen - 1;
109 uint32_t in = track->mf.in;
110 if ( ( ( in + 1 ) & mask ) == ( track->mf.out & mask ) )
112 // fifo is full - expand it to double the current size.
113 // This is a bit tricky because when we change the size
114 // it changes the modulus (mask) used to convert the in
115 // and out counters to fifo indices. Since existing items
116 // will be referenced at a new location after the expand
117 // we can't just realloc the fifo. If there were
118 // hundreds of fifo entries it would be worth it to have code
119 // for each of the four possible before/after configurations
120 // but these fifos are small so we just allocate a new chunk
121 // of memory then do element by element copies using the old &
122 // new masks then free the old fifo's memory..
124 uint32_t nmask = track->mf.flen - 1;
125 hb_buffer_t **nfifo = malloc( track->mf.flen * sizeof(*nfifo) );
126 int indx = track->mf.out;
127 while ( indx != track->mf.in )
129 nfifo[indx & nmask] = track->mf.fifo[indx & mask];
132 free( track->mf.fifo );
133 track->mf.fifo = nfifo;
136 track->mf.fifo[in & mask] = buf;
137 track->mf.in = in + 1;
140 static hb_buffer_t *mf_pull( hb_track_t *track )
142 hb_buffer_t *b = NULL;
143 if ( track->mf.out != track->mf.in )
145 // the fifo isn't empty
146 b = track->mf.fifo[track->mf.out & (track->mf.flen - 1)];
152 static hb_buffer_t *mf_peek( hb_track_t *track )
154 return track->mf.out == track->mf.in ?
155 NULL : track->mf.fifo[track->mf.out & (track->mf.flen - 1)];
158 static void MoveToInternalFifos( int tk, hb_mux_t *mux, hb_buffer_t * buf )
160 hb_track_t *track = mux->track[tk];
162 // move all the buffers on the track's fifo to our internal
163 // fifo so that (a) we don't deadlock in the reader and
164 // (b) we can control how data from multiple tracks is
165 // interleaved in the output file.
166 mf_push( track, buf );
167 if ( buf->stop >= mux->pts )
169 // buffer is past our next interleave point so
170 // note that this track is ready to be output.
171 mux->rdy |= ( 1 << tk );
175 static void OutputTrackChunk( hb_mux_t *mux, hb_track_t *track, hb_mux_object_t *m )
179 while ( ( buf = mf_peek( track ) ) != NULL && buf->start < mux->pts )
181 m->mux( m, track->mux_data, mf_pull( track ) );
183 track->bytes += buf->size;
187 static int muxWork( hb_work_object_t * w, hb_buffer_t ** buf_in,
188 hb_buffer_t ** buf_out )
190 hb_work_private_t * pv = w->private_data;
191 hb_job_t * job = pv->job;
192 hb_mux_t * mux = pv->mux;
195 hb_buffer_t * buf = *buf_in;
197 hb_lock( mux->mutex );
200 hb_unlock( mux->mutex );
204 if ( buf->size <= 0 )
206 // EOF - mark this track as done
207 hb_buffer_close( &buf );
208 mux->eof |= ( 1 << pv->track );
209 mux->rdy |= ( 1 << pv->track );
211 else if ( ( job->pass != 0 && job->pass != 2 ) ||
212 ( mux->eof & (1 << pv->track) ) )
214 hb_buffer_close( &buf );
218 MoveToInternalFifos( pv->track, mux, buf );
222 if ( ( mux->rdy & mux->allRdy ) != mux->allRdy )
224 hb_unlock( mux->mutex );
228 // all tracks have at least 'interleave' ticks of data. Output
229 // all that we can in 'interleave' size chunks.
230 while ( ( mux->rdy & mux->allRdy ) == mux->allRdy )
232 for ( i = 0; i < mux->ntracks; ++i )
234 track = mux->track[i];
235 OutputTrackChunk( mux, track, mux->m );
237 // if the track is at eof or still has data that's past
238 // our next interleave point then leave it marked as rdy.
239 // Otherwise clear rdy.
240 if ( ( mux->eof & (1 << i) ) == 0 &&
241 ( track->mf.out == track->mf.in ||
242 track->mf.fifo[(track->mf.in-1) & (track->mf.flen-1)]->stop
243 < mux->pts + mux->interleave ) )
245 mux->rdy &=~ ( 1 << i );
249 // if all the tracks are at eof we're just purging their
250 // remaining data -- keep going until all internal fifos are empty.
251 if ( mux->eof == mux->allEof )
253 for ( i = 0; i < mux->ntracks; ++i )
255 if ( mux->track[i]->mf.out != mux->track[i]->mf.in )
260 if ( i >= mux->ntracks )
263 hb_unlock( mux->mutex );
267 mux->pts += mux->interleave;
269 hb_unlock( mux->mutex );
273 void muxClose( hb_work_object_t * w )
275 hb_work_private_t * pv = w->private_data;
276 hb_mux_t * mux = pv->mux;
277 hb_job_t * job = pv->job;
281 hb_lock( mux->mutex );
282 if ( --mux->ref == 0 )
286 mux->m->end( mux->m );
290 // we're all done muxing -- print final stats and cleanup.
291 if( job->pass == 0 || job->pass == 2 )
294 uint64_t bytes_total, frames_total;
298 state.state = HB_STATE_MUXING;
299 state.param.muxing.progress = 0;
300 hb_set_state( job->h, &state );
302 if( !stat( job->file, &sb ) )
304 hb_deep_log( 2, "mux: file size, %"PRId64" bytes", (uint64_t) sb.st_size );
308 for( i = 0; i < mux->ntracks; ++i )
310 track = mux->track[i];
311 hb_log( "mux: track %d, %"PRId64" frames, %"PRId64" bytes, %.2f kbps, fifo %d",
312 i, track->frames, track->bytes,
313 90000.0 * track->bytes / mux->pts / 125,
315 if( !i && ( job->vquality < 0.0 || job->vquality > 1.0 ) )
318 hb_deep_log( 2, "mux: video bitrate error, %+"PRId64" bytes",
319 (int64_t)(track->bytes - mux->pts * job->vbitrate * 125 / 90000) );
321 bytes_total += track->bytes;
322 frames_total += track->frames;
325 if( bytes_total && frames_total )
327 hb_deep_log( 2, "mux: overhead, %.2f bytes per frame",
328 (float) ( sb.st_size - bytes_total ) /
334 for( i = 0; i < mux->ntracks; ++i )
336 track = mux->track[i];
337 if( track->mux_data )
339 free( track->mux_data );
340 free( track->mf.fifo );
344 hb_unlock( mux->mutex );
345 hb_lock_close( &mux->mutex );
350 hb_unlock( mux->mutex );
353 w->private_data = NULL;
356 static void mux_loop( void * _w )
358 hb_work_object_t * w = _w;
359 hb_work_private_t * pv = w->private_data;
360 hb_job_t * job = pv->job;
361 hb_buffer_t * buf_in;
363 while ( !*job->die && w->status != HB_WORK_DONE )
365 buf_in = hb_fifo_get_wait( w->fifo_in );
368 if ( buf_in == NULL )
374 hb_buffer_close( &buf_in );
379 w->status = w->work( w, &buf_in, NULL );
383 hb_work_object_t * hb_muxer_init( hb_job_t * job )
385 hb_title_t * title = job->title;
387 hb_mux_t * mux = calloc( sizeof( hb_mux_t ), 1 );
388 hb_work_object_t * w;
389 hb_work_object_t * muxer;
391 mux->mutex = hb_lock_init();
393 // set up to interleave track data in blocks of 1 video frame time.
394 // (the best case for buffering and playout latency). The container-
395 // specific muxers can reblock this into bigger chunks if necessary.
396 mux->interleave = 90000. * (double)job->vrate_base / (double)job->vrate;
397 mux->pts = mux->interleave;
399 /* Get a real muxer */
400 if( job->pass == 0 || job->pass == 2)
407 mux->m = hb_mux_mp4_init( job );
410 mux->m = hb_mux_avi_init( job );
413 mux->m = hb_mux_ogm_init( job );
416 mux->m = hb_mux_mkv_init( job );
419 hb_error( "No muxer selected, exiting" );
423 /* Create file, write headers */
426 mux->m->init( mux->m );
430 /* Initialize the work objects that will receive fifo data */
432 muxer = hb_get_work( WORK_MUX );
433 muxer->private_data = calloc( sizeof( hb_work_private_t ), 1 );
434 muxer->private_data->job = job;
435 muxer->private_data->mux = mux;
437 muxer->private_data->track = mux->ntracks;
438 muxer->fifo_in = job->fifo_mpeg4;
439 add_mux_track( mux, job->mux_data, 1 );
440 muxer->done = &job->done;
441 muxer->thread = hb_thread_init( muxer->name, mux_loop, muxer, HB_NORMAL_PRIORITY );
443 for( i = 0; i < hb_list_count( title->list_audio ); i++ )
445 hb_audio_t *audio = hb_list_item( title->list_audio, i );
447 w = hb_get_work( WORK_MUX );
448 w->private_data = calloc( sizeof( hb_work_private_t ), 1 );
449 w->private_data->job = job;
450 w->private_data->mux = mux;
452 w->private_data->track = mux->ntracks;
453 w->fifo_in = audio->priv.fifo_out;
454 add_mux_track( mux, audio->priv.mux_data, 1 );
455 w->done = &job->done;
456 hb_list_add( job->list_work, w );
457 w->thread = hb_thread_init( w->name, mux_loop, w, HB_NORMAL_PRIORITY );
460 for( i = 0; i < hb_list_count( title->list_subtitle ); i++ )
462 hb_subtitle_t *subtitle = hb_list_item( title->list_subtitle, i );
464 if (subtitle->config.dest != PASSTHRUSUB)
467 w = hb_get_work( WORK_MUX );
468 w->private_data = calloc( sizeof( hb_work_private_t ), 1 );
469 w->private_data->job = job;
470 w->private_data->mux = mux;
472 w->private_data->track = mux->ntracks;
473 w->fifo_in = subtitle->fifo_out;
474 add_mux_track( mux, subtitle->mux_data, 0 );
475 w->done = &job->done;
476 hb_list_add( job->list_work, w );
477 w->thread = hb_thread_init( w->name, mux_loop, w, HB_NORMAL_PRIORITY );
482 // muxInit does nothing because the muxer has a special initializer
483 // that takes care of initializing all muxer work objects
484 static int muxInit( hb_work_object_t * w, hb_job_t * job )
489 hb_work_object_t hb_muxer =