OSDN Git Service

7ea3c79330efbcec87084d615d904afd1ce63050
[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 void mf_push( hb_track_t *track, hb_buffer_t *buf )
107 {
108     uint32_t mask = track->mf.flen - 1;
109     uint32_t in = track->mf.in;
110     if ( ( ( in + 1 ) & mask ) == ( track->mf.out & mask ) )
111     {
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..
123         track->mf.flen *= 2;
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 )
128         {
129             nfifo[indx & nmask] = track->mf.fifo[indx & mask];
130             ++indx;
131         }
132         free( track->mf.fifo );
133         track->mf.fifo = nfifo;
134         mask = nmask;
135     }
136     track->mf.fifo[in & mask] = buf;
137     track->mf.in = in + 1;
138 }
139
140 static hb_buffer_t *mf_pull( hb_track_t *track )
141 {
142     hb_buffer_t *b = NULL;
143     if ( track->mf.out != track->mf.in )
144     {
145         // the fifo isn't empty
146         b = track->mf.fifo[track->mf.out & (track->mf.flen - 1)];
147         ++track->mf.out;
148     }
149     return b;
150 }
151
152 static hb_buffer_t *mf_peek( hb_track_t *track )
153 {
154     return track->mf.out == track->mf.in ?
155                 NULL : track->mf.fifo[track->mf.out & (track->mf.flen - 1)];
156 }
157
158 static void MoveToInternalFifos( int tk, hb_mux_t *mux, hb_buffer_t * buf )
159 {
160     hb_track_t *track = mux->track[tk];
161
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 )
168     {
169         // buffer is past our next interleave point so
170         // note that this track is ready to be output.
171         mux->rdy |= ( 1 << tk );
172     }
173 }
174
175 static void OutputTrackChunk( hb_mux_t *mux, hb_track_t *track, hb_mux_object_t *m )
176 {
177     hb_buffer_t *buf;
178
179     while ( ( buf = mf_peek( track ) ) != NULL && buf->start < mux->pts )
180     {
181         m->mux( m, track->mux_data, mf_pull( track ) );
182         track->frames += 1;
183         track->bytes  += buf->size;
184         hb_buffer_close( &buf );
185     }
186 }
187
188 static int muxWork( hb_work_object_t * w, hb_buffer_t ** buf_in,
189                      hb_buffer_t ** buf_out )
190 {
191     hb_work_private_t * pv = w->private_data;
192     hb_job_t    * job = pv->job;
193     hb_mux_t    * mux = pv->mux;
194     hb_track_t  * track;
195     int           i;
196     hb_buffer_t * buf = *buf_in;
197
198     hb_lock( mux->mutex );
199     if ( mux->done )
200     {
201         hb_unlock( mux->mutex );
202         return HB_WORK_DONE;
203     }
204
205     if ( buf->size <= 0 )
206     {
207         // EOF - mark this track as done
208         hb_buffer_close( &buf );
209         mux->eof |= ( 1 << pv->track );
210         mux->rdy |= ( 1 << pv->track );
211     }
212     else if ( ( job->pass != 0 && job->pass != 2 ) ||
213               ( mux->eof & (1 << pv->track) ) )
214     {
215         hb_buffer_close( &buf );
216     }
217     else
218     {
219         MoveToInternalFifos( pv->track, mux, buf );
220     }
221     *buf_in = NULL;
222
223     if ( ( mux->rdy & mux->allRdy ) != mux->allRdy )
224     {
225         hb_unlock( mux->mutex );
226         return HB_WORK_OK;
227     }
228
229     // all tracks have at least 'interleave' ticks of data. Output
230     // all that we can in 'interleave' size chunks.
231     while ( ( mux->rdy & mux->allRdy ) == mux->allRdy )
232     {
233         for ( i = 0; i < mux->ntracks; ++i )
234         {
235             track = mux->track[i];
236             OutputTrackChunk( mux, track, mux->m );
237
238             // if the track is at eof or still has data that's past
239             // our next interleave point then leave it marked as rdy.
240             // Otherwise clear rdy.
241             if ( ( mux->eof & (1 << i) ) == 0 &&
242                  ( track->mf.out == track->mf.in ||
243                    track->mf.fifo[(track->mf.in-1) & (track->mf.flen-1)]->stop
244                      < mux->pts + mux->interleave ) )
245             {
246                 mux->rdy &=~ ( 1 << i );
247             }
248         }
249
250         // if all the tracks are at eof we're just purging their
251         // remaining data -- keep going until all internal fifos are empty.
252         if ( mux->eof == mux->allEof )
253         {
254             for ( i = 0; i < mux->ntracks; ++i )
255             {
256                 if ( mux->track[i]->mf.out != mux->track[i]->mf.in )
257                 {
258                     break;
259                 }
260             }
261             if ( i >= mux->ntracks )
262             {
263                 mux->done = 1;
264                 hb_unlock( mux->mutex );
265                 return HB_WORK_DONE;
266             }
267         }
268         mux->pts += mux->interleave;
269     }
270     hb_unlock( mux->mutex );
271     return HB_WORK_OK;
272 }
273
274 void muxClose( hb_work_object_t * w )
275 {
276     hb_work_private_t * pv = w->private_data;
277     hb_mux_t    * mux = pv->mux;
278     hb_job_t    * job = pv->job;
279     hb_track_t  * track;
280     int           i;
281
282     // we're all done muxing -- print final stats and cleanup.
283     if( job->pass == 0 || job->pass == 2 )
284     {
285         struct stat sb;
286         uint64_t bytes_total, frames_total;
287
288         /* Update the UI */
289         hb_state_t state;
290         state.state = HB_STATE_MUXING;
291         state.param.muxing.progress = 0;
292         hb_set_state( job->h, &state );
293
294         if( !stat( job->file, &sb ) )
295         {
296             hb_deep_log( 2, "mux: file size, %"PRId64" bytes", (uint64_t) sb.st_size );
297
298             bytes_total  = 0;
299             frames_total = 0;
300             for( i = 0; i < mux->ntracks; ++i )
301             {
302                 track = mux->track[i];
303                 hb_log( "mux: track %d, %"PRId64" frames, %"PRId64" bytes, %.2f kbps, fifo %d",
304                         i, track->frames, track->bytes,
305                         90000.0 * track->bytes / mux->pts / 125,
306                         track->mf.flen );
307                 if( !i && ( job->vquality < 0.0 || job->vquality > 1.0 ) )
308                 {
309                     /* Video */
310                     hb_deep_log( 2, "mux: video bitrate error, %+"PRId64" bytes",
311                             (int64_t)(track->bytes - mux->pts * job->vbitrate * 125 / 90000) );
312                 }
313                 bytes_total  += track->bytes;
314                 frames_total += track->frames;
315             }
316
317             if( bytes_total && frames_total )
318             {
319                 hb_deep_log( 2, "mux: overhead, %.2f bytes per frame",
320                         (float) ( sb.st_size - bytes_total ) /
321                         frames_total );
322             }
323         }
324     }
325     
326     hb_lock( mux->mutex );
327     if ( --mux->ref == 0 )
328     {
329         if( mux->m )
330         {
331             mux->m->end( mux->m );
332             free( mux->m );
333         }
334
335         for( i = 0; i < mux->ntracks; ++i )
336         {
337             track = mux->track[i];
338             if( track->mux_data )
339             {
340                 free( track->mux_data );
341                 free( track->mf.fifo );
342             }
343             free( track );
344         }
345         hb_unlock( mux->mutex );
346         hb_lock_close( &mux->mutex );
347         free( mux );
348     }
349     else
350     {
351         hb_unlock( mux->mutex );
352     }
353     free( pv );
354     w->private_data = NULL;
355 }
356
357 static void mux_loop( void * _w )
358 {
359     hb_work_object_t  * w = _w;
360     hb_work_private_t * pv = w->private_data;
361     hb_job_t          * job = pv->job;
362     hb_buffer_t       * buf_in;
363
364     while ( !*job->die && w->status != HB_WORK_DONE )
365     {
366         buf_in = hb_fifo_get_wait( w->fifo_in );
367         if ( pv->mux->done )
368             break;
369         if ( buf_in == NULL )
370             continue;
371         if ( *job->die )
372         {
373             if( buf_in )
374             {
375                 hb_buffer_close( &buf_in );
376             }
377             break;
378         }
379
380         w->status = w->work( w, &buf_in, NULL );
381     }
382 }
383
384 hb_work_object_t * hb_muxer_init( hb_job_t * job )
385 {
386     hb_title_t  * title = job->title;
387     int           i;
388     hb_mux_t    * mux = calloc( sizeof( hb_mux_t ), 1 );
389     hb_work_object_t  * w;
390     hb_work_object_t  * muxer;
391
392     mux->mutex = hb_lock_init();
393
394     // set up to interleave track data in blocks of 1 video frame time.
395     // (the best case for buffering and playout latency). The container-
396     // specific muxers can reblock this into bigger chunks if necessary.
397     mux->interleave = 90000. * (double)job->vrate_base / (double)job->vrate;
398     mux->pts = mux->interleave;
399
400     /* Get a real muxer */
401     if( job->pass == 0 || job->pass == 2)
402     {
403         switch( job->mux )
404         {
405         case HB_MUX_MP4:
406         case HB_MUX_PSP:
407         case HB_MUX_IPOD:
408             mux->m = hb_mux_mp4_init( job );
409             break;
410         case HB_MUX_AVI:
411             mux->m = hb_mux_avi_init( job );
412             break;
413         case HB_MUX_OGM:
414             mux->m = hb_mux_ogm_init( job );
415             break;
416         case HB_MUX_MKV:
417             mux->m = hb_mux_mkv_init( job );
418             break;
419         default:
420             hb_error( "No muxer selected, exiting" );
421             *job->die = 1;
422             return NULL;
423         }
424         /* Create file, write headers */
425         if( mux->m )
426         {
427             mux->m->init( mux->m );
428         }
429     }
430
431     /* Initialize the work objects that will receive fifo data */
432
433     muxer = hb_get_work( WORK_MUX );
434     muxer->private_data = calloc( sizeof( hb_work_private_t ), 1 );
435     muxer->private_data->job = job;
436     muxer->private_data->mux = mux;
437     mux->ref++;
438     muxer->private_data->track = mux->ntracks;
439     muxer->fifo_in = job->fifo_mpeg4;
440     add_mux_track( mux, job->mux_data, 1 );
441     muxer->done = &job->done;
442     muxer->thread = hb_thread_init( muxer->name, mux_loop, muxer, HB_NORMAL_PRIORITY );
443
444     for( i = 0; i < hb_list_count( title->list_audio ); i++ )
445     {
446         hb_audio_t  *audio = hb_list_item( title->list_audio, i );
447
448         w = hb_get_work( WORK_MUX );
449         w->private_data = calloc( sizeof( hb_work_private_t ), 1 );
450         w->private_data->job = job;
451         w->private_data->mux = mux;
452         mux->ref++;
453         w->private_data->track = mux->ntracks;
454         w->fifo_in = audio->priv.fifo_out;
455         add_mux_track( mux, audio->priv.mux_data, 1 );
456         w->done = &job->done;
457         hb_list_add( job->list_work, w );
458         w->thread = hb_thread_init( w->name, mux_loop, w, HB_NORMAL_PRIORITY );
459     }
460
461     for( i = 0; i < hb_list_count( title->list_subtitle ); i++ )
462     {
463         hb_subtitle_t  *subtitle = hb_list_item( title->list_subtitle, i );
464
465         if (subtitle->config.dest != PASSTHRUSUB)
466             continue;
467
468         w = hb_get_work( WORK_MUX );
469         w->private_data = calloc( sizeof( hb_work_private_t ), 1 );
470         w->private_data->job = job;
471         w->private_data->mux = mux;
472         mux->ref++;
473         w->private_data->track = mux->ntracks;
474         w->fifo_in = subtitle->fifo_out;
475         add_mux_track( mux, subtitle->mux_data, 0 );
476         w->done = &job->done;
477         hb_list_add( job->list_work, w );
478         w->thread = hb_thread_init( w->name, mux_loop, w, HB_NORMAL_PRIORITY );
479     }
480     return muxer;
481 }
482
483 // muxInit does nothing because the muxer has a special initializer
484 // that takes care of initializing all muxer work objects
485 static int muxInit( hb_work_object_t * w, hb_job_t * job )
486 {
487     return 0;
488 }
489
490 hb_work_object_t hb_muxer =
491 {
492     WORK_MUX,
493     "Muxer",
494     muxInit,
495     muxWork,
496     muxClose
497 };
498