OSDN Git Service

Remove the set cpu count option as it doesn't do anything now
[handbrake-jp/handbrake-jp-git.git] / libhb / deca52.c
1 /* $Id: deca52.c,v 1.14 2005/03/03 17:21:57 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 #include "a52dec/a52.h"
10 #include "libavutil/crc.h"
11
12 struct hb_work_private_s
13 {
14     hb_job_t    * job;
15
16     /* liba52 handle */
17     a52_state_t * state;
18
19     int           flags_in;
20     int           flags_out;
21     int           rate;
22     int           bitrate;
23     int           out_discrete_channels;
24     int           error;
25     int           frames;                   // number of good frames decoded
26     int           crc_errors;               // number of frames with crc errors
27     int           bytes_dropped;            // total bytes dropped while resyncing
28     float         level;
29     float         dynamic_range_compression;
30     double        next_expected_pts;
31     int64_t       last_buf_pts;
32     hb_list_t    *list;
33     const AVCRC  *crc_table;
34     uint8_t       frame[3840];
35 };
36
37 static int  deca52Init( hb_work_object_t *, hb_job_t * );
38 static int  deca52Work( hb_work_object_t *, hb_buffer_t **, hb_buffer_t ** );
39 static void deca52Close( hb_work_object_t * );
40 static int deca52BSInfo( hb_work_object_t * , const hb_buffer_t *,
41                          hb_work_info_t * );
42
43 hb_work_object_t hb_deca52 =
44 {
45     WORK_DECA52,
46     "AC3 decoder",
47     deca52Init,
48     deca52Work,
49     deca52Close,
50     0,
51     deca52BSInfo
52 };
53
54 /***********************************************************************
55  * Local prototypes
56  **********************************************************************/
57 static hb_buffer_t * Decode( hb_work_object_t * w );
58
59 /***********************************************************************
60  * dynrng_call
61  ***********************************************************************
62  * Boosts soft audio -- taken from gbooker's work in A52Decoder, comment and all..
63  * Two cases
64  * 1) The user requested a compression of 1 or less, return the typical power rule
65  * 2) The user requested a compression of more than 1 (decompression):
66  *    If the stream's requested compression is less than 1.0 (loud sound), return the normal compression
67  *    If the stream's requested compression is more than 1.0 (soft sound), use power rule (which will make
68  *   it louder in this case).
69  *
70  **********************************************************************/
71 static sample_t dynrng_call (sample_t c, void *data)
72 {
73         float *level = (float *)data;
74         float levelToUse = (float)*level;
75         if(c > 1.0 || levelToUse <= 1.0)
76         {
77             return powf(c, levelToUse);
78         }
79         else
80                 return c;
81 }
82
83 /***********************************************************************
84  * hb_work_deca52_init
85  ***********************************************************************
86  * Allocate the work object, initialize liba52
87  **********************************************************************/
88 static int deca52Init( hb_work_object_t * w, hb_job_t * job )
89 {
90     hb_work_private_t * pv = calloc( 1, sizeof( hb_work_private_t ) );
91     hb_audio_t * audio = w->audio;
92     w->private_data = pv;
93
94     pv->job   = job;
95
96     pv->crc_table = av_crc_get_table( AV_CRC_16_ANSI );
97     pv->list      = hb_list_init();
98     pv->state     = a52_init( 0 );
99
100     /* Decide what format we want out of a52dec
101     work.c has already done some of this deduction for us in do_job() */
102
103     pv->flags_out = HB_AMIXDOWN_GET_A52_FORMAT(audio->config.out.mixdown);
104
105     /* pass the number of channels used into the private work data */
106     /* will only be actually used if we're not doing AC3 passthru */
107     pv->out_discrete_channels = HB_AMIXDOWN_GET_DISCRETE_CHANNEL_COUNT(audio->config.out.mixdown);
108
109     pv->level     = 32768.0;
110     pv->dynamic_range_compression = audio->config.out.dynamic_range_compression;
111
112     return 0;
113 }
114
115 /***********************************************************************
116  * Close
117  ***********************************************************************
118  * Free memory
119  **********************************************************************/
120 static void deca52Close( hb_work_object_t * w )
121 {
122     hb_work_private_t * pv = w->private_data;
123
124     if ( pv->crc_errors )
125     {
126         hb_log( "deca52: %d frames decoded, %d crc errors, %d bytes dropped",
127                 pv->frames, pv->crc_errors, pv->bytes_dropped );
128     }
129     a52_free( pv->state );
130     hb_list_empty( &pv->list );
131     free( pv );
132     w->private_data = NULL;
133 }
134
135 /***********************************************************************
136  * Work
137  ***********************************************************************
138  * Add the given buffer to the data we already have, and decode as much
139  * as we can
140  **********************************************************************/
141 static int deca52Work( hb_work_object_t * w, hb_buffer_t ** buf_in,
142                 hb_buffer_t ** buf_out )
143 {
144     hb_work_private_t * pv = w->private_data;
145     hb_buffer_t * buf;
146
147     if ( (*buf_in)->size <= 0 )
148     {
149         /* EOF on input stream - send it downstream & say that we're done */
150         *buf_out = *buf_in;
151         *buf_in = NULL;
152         return HB_WORK_DONE;
153     }
154
155     if ( (*buf_in)->start < -1 && pv->next_expected_pts == 0 )
156     {
157         // discard buffers that start before video time 0
158         *buf_out = NULL;
159         return HB_WORK_OK;
160     }
161
162     hb_list_add( pv->list, *buf_in );
163     *buf_in = NULL;
164
165     /* If we got more than a frame, chain raw buffers */
166     *buf_out = buf = Decode( w );
167     while( buf )
168     {
169         buf->next = Decode( w );
170         buf       = buf->next;
171     }
172
173     return HB_WORK_OK;
174 }
175
176 /***********************************************************************
177  * Decode
178  ***********************************************************************
179  *
180  **********************************************************************/
181 static hb_buffer_t * Decode( hb_work_object_t * w )
182 {
183     hb_work_private_t * pv = w->private_data;
184     hb_buffer_t * buf;
185     hb_audio_t  * audio = w->audio;
186     int           i, j, k;
187     int           size = 0;
188
189     // check that we're at the start of a valid frame and align to the
190     // start of a valid frame if we're not.
191     // we have to check the header & crc so we need at least
192     // 7 (the header size) + 128 (the minimum frame size) bytes
193     while( hb_list_bytes( pv->list ) >= 7+128 )
194     {
195         /* check if this is a valid header */
196         hb_list_seebytes( pv->list, pv->frame, 7 );
197         size = a52_syncinfo( pv->frame, &pv->flags_in, &pv->rate, &pv->bitrate );
198         if ( size > 0 )
199         {
200             // header looks valid - check the crc1
201             if( size > hb_list_bytes( pv->list ) )
202             {
203                 // don't have all the frame's data yet
204                 return NULL;
205             }
206             int crc1size = (size >> 1) + (size >> 3);
207             hb_list_seebytes( pv->list, pv->frame, crc1size );
208             if ( av_crc( pv->crc_table, 0, pv->frame + 2, crc1size - 2 ) == 0 )
209             {
210                 // crc1 is ok - say we have valid frame sync
211                 if( pv->error )
212                 {
213                     hb_log( "output track %d: ac3 in sync after skipping %d bytes",
214                             audio->config.out.track, pv->error );
215                     pv->bytes_dropped += pv->error;
216                     pv->error = 0;
217                 }
218                 break;
219             }
220         }
221         // no sync - discard one byte then try again
222         hb_list_getbytes( pv->list, pv->frame, 1, NULL, NULL );
223         ++pv->error;
224     }
225
226     // we exit the above loop either in error state (we didn't find sync
227     // or don't have enough data yet to validate sync) or in sync. If we're
228     // not in sync we need more data so just return.
229     if( pv->error || size <= 0 || hb_list_bytes( pv->list ) < size )
230     {
231         /* Need more data */
232         return NULL;
233     }
234
235     // Get the whole frame and check its CRC. If the CRC is wrong
236     // discard the frame - we'll resync on the next call.
237
238     uint64_t ipts;
239     hb_list_getbytes( pv->list, pv->frame, size, &ipts, NULL );
240     if ( av_crc( pv->crc_table, 0, pv->frame + 2, size - 2 ) != 0 )
241     {
242         ++pv->crc_errors;
243         return NULL;
244     }
245     ++pv->frames;
246     if ( ipts != pv->last_buf_pts )
247     {
248         pv->last_buf_pts = ipts;
249     }
250     else
251     {
252         // spec says that the PTS is the start time of the first frame
253         // that starts in the PES frame so we only use the PTS once then
254         // get the following frames' PTS from the frame length.
255         ipts = -1;
256     }
257
258     double pts = ( ipts != -1 ) ? ipts : pv->next_expected_pts;
259     double frame_dur = (6. * 256. * 90000.) / pv->rate;
260
261     /* AC3 passthrough: don't decode the AC3 frame */
262     if( audio->config.out.codec == HB_ACODEC_AC3_PASS )
263     {
264         buf = hb_buffer_init( size );
265         memcpy( buf->data, pv->frame, size );
266         buf->start = pts;
267         pts += frame_dur;
268         buf->stop  = pts;
269         pv->next_expected_pts = pts;
270         return buf;
271     }
272
273     /* Feed liba52 */
274     a52_frame( pv->state, pv->frame, &pv->flags_out, &pv->level, 0 );
275
276     /* If a user specifies strong dynamic range compression (>1), adjust it.
277        If a user specifies default dynamic range compression (1), leave it alone.
278        If a user specifies no dynamic range compression (0), call a null function. */
279     if( pv->dynamic_range_compression > 1.0 )
280     {
281         a52_dynrng( pv->state, dynrng_call, &pv->dynamic_range_compression );
282     }
283     else if( !pv->dynamic_range_compression )
284     {
285         a52_dynrng( pv->state, NULL, NULL );
286     }
287
288     /* 6 blocks per frame, 256 samples per block, channelsused channels */
289     buf        = hb_buffer_init( 6 * 256 * pv->out_discrete_channels * sizeof( float ) );
290     buf->start = pts;
291     pts += frame_dur;
292     buf->stop  = pts;
293     pv->next_expected_pts = pts;
294
295     for( i = 0; i < 6; i++ )
296     {
297         sample_t * samples_in;
298         float    * samples_out;
299
300         a52_block( pv->state );
301         samples_in  = a52_samples( pv->state );
302         samples_out = ((float *) buf->data) + 256 * pv->out_discrete_channels * i;
303
304         /* Interleave */
305         for( j = 0; j < 256; j++ )
306         {
307             for ( k = 0; k < pv->out_discrete_channels; k++ )
308             {
309                 samples_out[(pv->out_discrete_channels*j)+k]   = samples_in[(256*k)+j];
310             }
311         }
312
313     }
314     return buf;
315 }
316
317 static int find_sync( const uint8_t *buf, int len )
318 {
319     int i;
320
321     // since AC3 frames don't line up with MPEG ES frames scan the
322     // frame for an AC3 sync pattern.
323     for ( i = 0; i < len - 16; ++i )
324     {
325         int rate, bitrate, flags;
326         int size = a52_syncinfo( (uint8_t *)buf + i, &flags, &rate, &bitrate );
327         if( size > 0 )
328         {
329             // we have a plausible sync header - see if crc1 checks
330             int crc1size = (size >> 1) + (size >> 3); 
331             if ( i + crc1size > len )
332             {
333                 // don't have enough data to check crc1
334                 break;
335             }
336             if ( av_crc( av_crc_get_table( AV_CRC_16_ANSI ), 0,
337                          buf + i + 2, crc1size - 2 ) == 0 )
338             {
339                 // crc checks - we've got sync
340                 return i;
341             }
342         }
343     }
344     return -1;
345 }
346
347 static int deca52BSInfo( hb_work_object_t *w, const hb_buffer_t *b,
348                          hb_work_info_t *info )
349 {
350     memset( info, 0, sizeof(*info) );
351
352     // We don't know if the way that AC3 frames are fragmented into whatever
353     // packetization the container uses will give us enough bytes per fragment
354     // to check the CRC (we need at least 5/8 of the the frame). So we
355     // copy the fragment we got into an accumulation buffer in the audio object
356     // then look for sync over all the frags we've accumulated so far.
357     uint8_t *buf = w->audio->priv.config.a52.buf;
358     int len = w->audio->priv.config.a52.len, blen = b->size;
359     if ( len + blen > sizeof(w->audio->priv.config.a52.buf) )
360     {
361         // we don't have enough empty space in the accumulation buffer to
362         // hold the new frag - make room for it by discarding the oldest data.
363         if ( blen >= sizeof(w->audio->priv.config.a52.buf) )
364         {
365             // the frag is bigger than our accumulation buffer - copy all
366             // that will fit (the excess doesn't matter since the buffer
367             // is many times the size of a max length ac3 frame).
368             blen = sizeof(w->audio->priv.config.a52.buf);
369             len = 0;
370         }
371         else
372         {
373             // discard enough bytes from the front of the buffer to make
374             // room for the new stuff
375             int newlen = sizeof(w->audio->priv.config.a52.buf) - blen;
376             memcpy( buf, buf + len - newlen, newlen );
377             len = newlen;
378         }
379     }
380     // add the new frag to the buffer
381     memcpy( buf+len, b->data, blen );
382     len += blen;
383
384     int i;
385     if ( ( i = find_sync( buf, len ) ) < 0 )
386     {
387         // didn't find sync - wait for more data
388         w->audio->priv.config.a52.len = len;
389         return 0;
390     }
391
392     // got sync - extract and canoncalize the bitstream parameters
393     int rate = 0, bitrate = 0, flags = 0;
394     uint8_t raw = buf[i + 5];
395     a52_syncinfo( buf + i, &flags, &rate, &bitrate );
396
397     if ( rate == 0 || bitrate == 0 )
398     {
399         // invalid AC-3 parameters - toss what we have so we'll start over
400         // with the next buf otherwise we'll keep syncing on this junk.
401         w->audio->priv.config.a52.len = 0;
402         return 0;
403     }
404
405     // bsid | bsmod | acmod | cmixlv | surmixlv | dsurmod | lfeon | dialnorm | compre
406     //   5       3      3        2         2         2        1          5        1
407     //      byte1   |          byte2                 |    byte3  
408
409     info->name = "AC-3";
410     info->rate = rate;
411     info->rate_base = 1;
412     info->bitrate = bitrate;
413     info->flags = flags;
414     info->version = raw >> 3;    /* bsid is the first 5 bits */
415     info->mode = raw & 0x7;      /* bsmod is the following 3 bits */
416
417     if ( (flags & A52_CHANNEL_MASK) == A52_DOLBY )
418     {
419         info->flags |= AUDIO_F_DOLBY;
420     }
421
422     switch( flags & A52_CHANNEL_MASK )
423     {
424         /* mono sources */
425         case A52_MONO:
426         case A52_CHANNEL1:
427         case A52_CHANNEL2:
428             info->channel_layout = HB_INPUT_CH_LAYOUT_MONO;
429             break;
430         /* stereo input */
431         case A52_CHANNEL:
432         case A52_STEREO:
433             info->channel_layout = HB_INPUT_CH_LAYOUT_STEREO;
434             break;
435         /* dolby (DPL1 aka Dolby Surround = 4.0 matrix-encoded) input */
436         case A52_DOLBY:
437             info->channel_layout = HB_INPUT_CH_LAYOUT_DOLBY;
438             break;
439         /* 3F/2R input */
440         case A52_3F2R:
441             info->channel_layout = HB_INPUT_CH_LAYOUT_3F2R;
442             break;
443         /* 3F/1R input */
444         case A52_3F1R:
445             info->channel_layout = HB_INPUT_CH_LAYOUT_3F1R;
446             break;
447         /* other inputs */
448         case A52_3F:
449             info->channel_layout = HB_INPUT_CH_LAYOUT_3F;
450             break;
451         case A52_2F1R:
452             info->channel_layout = HB_INPUT_CH_LAYOUT_2F1R;
453             break;
454         case A52_2F2R:
455             info->channel_layout = HB_INPUT_CH_LAYOUT_2F2R;
456             break;
457         /* unknown */
458         default:
459             info->channel_layout = HB_INPUT_CH_LAYOUT_STEREO;
460     }
461
462     if (flags & A52_LFE)
463     {
464         info->channel_layout |= HB_INPUT_CH_LAYOUT_HAS_LFE;
465     }
466
467     return 1;
468 }