Source

pyMP3 / pyMP3.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
#!/usr/bin/env python
'''
pyMP3

MP3 decoder

Created on Aug 18, 2010
 
@author: portalfire
'''

from bitbfr import BitBfr
from numpy import *
from pyMP3_tables import *

dbg_output = False

PI = 3.1415

class mp3_frame_hdr:
    def __init__(self):
        self.mpeg_version = 0        
        self.layer = 0
        self.has_CRC = False
        self.bitrate = 0
        self.smpl_rate = 0
        self.padding = False
        self.channel_mode = "unknown"
        self.mode_extention = "unknown"
        self.copyrighted = False
        self.original = False
        self.emphasis = "unknown"
        self.n_channels = 0

class mp3_frame_side_info:
    def __init__(self):
        self.main_data_begin        = 0
        self.private_bits           = 0
        self.scfsi                  = zeros( (2,4), dtype=int32)
        self.part2_3_length         = zeros( (2,2), dtype=int32)
        self.big_values             = zeros( (2,2), dtype=int32)
        self.global_gain            = zeros( (2,2), dtype=int32)
        self.scalefac_compress      = zeros( (2,2), dtype=int32)
        self.window_switching_flag  = zeros( (2,2), dtype=int32)
        self.block_type             = zeros( (2,2), dtype=int32)
        self.mixed_block_flag       = zeros( (2,2), dtype=int32)
        self.table_select           = zeros( (2,2,3), dtype=int32)
        self.subblock_gain          = zeros( (2,2,3), dtype=int32)
        self.region0_count          = zeros( (2,2), dtype=int32)
        self.region1_count          = zeros( (2,2), dtype=int32)
        self.preflag                = zeros( (2,2), dtype=int32)
        self.scalefac_scale         = zeros( (2,2), dtype=int32)
        self.count1table_select     = zeros( (2,2), dtype=int32)

class mp3_frame_main_data:
    def __init__(self):
        self.scalefac_s    = zeros( (2,3,13), dtype=int32)
        self.scalefac_l    = zeros( (2,23), dtype=int32)
        self.q_vals        = zeros( (2,2,32,18), dtype=int32)

class mp3_frame_decoded_data:
    def __init__(self):
        self.dq_vals       = zeros( (2,2,32,18), dtype=float)
        self.lr            = zeros( (2,2,32,18), dtype=float)

class mp3_frame:
    def __init__(self):
        self.hdr          = mp3_frame_hdr()
        self.side_info    = mp3_frame_side_info()
        self.main_data    = mp3_frame_main_data()
        self.decoded_data = mp3_frame_decoded_data()

class pyMP3:
    def __init__(self, filename):
        f = open(filename, "rb")
        file_data = f.read()
        f.close()      
        self.bitbfr = BitBfr(file_data)
        self.cur_frame = mp3_frame()
    
    def decode(self):
        if(dbg_output):
            print "Starting Decode"        
        frame_cnt = 0
        while( self.bitbfr.bits_left() > 0):        
            print "frame #%d" % (frame_cnt+1)

            #Decode the data            
            self.find_next_syncword()
            self.decode_frame_header()
            self.decode_CRC()
            self.decode_side_info()           
            self.decode_main_info()
            
            #Process the Data
            self.dequantize_samples()
            self.process_stereo()
            self.reorder_samples()
            self.antialias_samples()
            self.hybrid_synthesis()
            self.polyphase_synthesis()
            
            frame_cnt+=1

            if(frame_cnt == 2 ):
                break

    def dequantize_samples(self):
        for gr in xrange(2):        
            for ch in xrange(self.cur_frame.hdr.n_channels):        
                cb = 0                 
                #get initial boundary        
                if (self.cur_frame.side_info.window_switching_flag[ch][gr] and (self.cur_frame.side_info.block_type[ch][gr] == 2) ):
                    if (self.cur_frame.side_info.mixed_block_flag[ch][gr]): 
                        #mixed (long first)                
                        next_cb_boundary = sfBandIndex_[self.cur_frame.hdr.smpl_rate][1]
                    else: 
                        #pure short                
                        next_cb_boundary = sfBandIndex_s[self.cur_frame.hdr.smpl_rate][1]*3
                        cb_width         = sfBandIndex_s[self.cur_frame.hdr.smpl_rate][1]
                        cb_begin         = 0;
                else: 
                    #long blocks             
                    next_cb_boundary = sfBandIndex_l[self.cur_frame.hdr.smpl_rate][1]

                #apply formula per block type */    
                for sb in xrange(SBLIMIT):
                    for ss in xrange(SSLIMIT): 
                        if ( (sb*18)+ss == next_cb_boundary):  
                            if (self.cur_frame.side_info.window_switching_flag[ch][gr] and (self.cur_frame.side_info.block_type[ch][gr] == 2)): 
                                if (self.cur_frame.side_info.mixed_block_flag[ch][gr]):  
                                    if (((sb*18)+ss) == sfBandIndex_l[self.cur_frame.hdr.smpl_rate][8]):  
                                        next_cb_boundary = sfBandIndex_s[self.cur_frame.hdr.smpl_rate][4]*3 
                                        cb               = 3
                                        cb_width         = sfBandIndex_s[self.cur_frame.hdr.smpl_rate][cb+1] - sfBandIndex_s[self.cur_frame.hdr.smpl_rate][cb]
                                        cb_begin         = sfBandIndex_s[self.cur_frame.hdr.smpl_rate][cb]*3      
                                    elif (((sb*18)+ss) < sfBandIndex_l[self.cur_frame.hdr.smpl_rate][8]):
                                        cb += 1 
                                        next_cb_boundary = sfBandIndex_l[self.cur_frame.hdr.smpl_rate][cb+1]
                                    else: 
                                        cb += 1 
                                        next_cb_boundary = sfBandIndex_s[self.cur_frame.hdr.smpl_rate][cb+1]*3
                                        cb_width         = sfBandIndex_s[self.cur_frame.hdr.smpl_rate][cb+1] - sfBandIndex_s[self.cur_frame.hdr.smpl_rate][cb]
                                        cb_begin         = sfBandIndex_s[self.cur_frame.hdr.smpl_rate][cb]*3                                       
                                else:  
                                    cb += 1
                                    next_cb_boundary = sfBandIndex_s[self.cur_frame.hdr.smpl_rate][cb+1]*3
                                    cb_width = sfBandIndex_s[self.cur_frame.hdr.smpl_rate][cb+1] -sfBandIndex_s[self.cur_frame.hdr.smpl_rate][cb];
                                    cb_begin = sfBandIndex_s[self.cur_frame.hdr.smpl_rate][cb]*3;                                  
                            else: 
                                cb += 1
                                next_cb_boundary = sfBandIndex_l[self.cur_frame.hdr.smpl_rate][cb+1]
                 
                        #Compute global scaling
                        self.cur_frame.decoded_data.dq_vals[gr][ch][sb][ss] = pow( 2.0 , (0.25 * (self.cur_frame.side_info.global_gain[ch][gr] - 210.0)))

                        #Compute block dependent scaling
                        if (self.cur_frame.side_info.window_switching_flag[ch][gr] and (
                            ((self.cur_frame.side_info.block_type[ch][gr] == 2) and (self.cur_frame.side_info.mixed_block_flag[ch][gr] == 0)) or
                            ((self.cur_frame.side_info.block_type[ch][gr] == 2) and self.cur_frame.side_info.mixed_block_flag[ch][gr] and (sb >= 2)) )): 
                            #SHORT
                            self.cur_frame.decoded_data.dq_vals[gr][ch][sb][ss] *= pow(2.0, 0.25 * -8.0 * self.cur_frame.side_info.subblock_gain[ch][gr][(((sb*18)+ss) - cb_begin)/cb_width])
                            self.cur_frame.decoded_data.dq_vals[gr][ch][sb][ss] *= pow(2.0, 0.25 * -2.0 * 
                                (1.0+self.cur_frame.side_info.scalefac_scale[ch][gr]) * self.cur_frame.main_data.scalefac_s[ch][(((sb*18)+ss) - cb_begin)/cb_width][cb])
                        else:    
                            #LONG block types 0,1,3 & 1st 2 subbands of switched blocks 
                            self.cur_frame.decoded_data.dq_vals[gr][ch][sb][ss] *= pow(2.0, -0.5 * 
                                (1.0+self.cur_frame.side_info.scalefac_scale[ch][gr]) * (self.cur_frame.main_data.scalefac_l[ch][cb] + self.cur_frame.side_info.preflag[ch][gr] * pretab[cb]))

                        #Scale quantized value        
                        self.cur_frame.decoded_data.dq_vals[gr][ch][sb][ss] *= pow( abs(self.cur_frame.main_data.q_vals[gr][ch][sb][ss]), (4.0/3.0) )
                        if (self.cur_frame.main_data.q_vals[gr][ch][sb][ss]<0):
                            self.cur_frame.decoded_data.dq_vals[gr][ch][sb][ss] = -self.cur_frame.decoded_data.dq_vals[gr][ch][sb][ss]
        

    def process_stereo(self):
        has_intensity_stereo = (self.cur_frame.hdr.mode_extention & INTENSITY_STEREO_BIT)
        has_mid_side_stereo = (self.cur_frame.hdr.mode_extention & MID_SIDE_STEREO_BIT)
        lr      = self.cur_frame.decoded_data.lr
        dq_vals = self.cur_frame.decoded_data.dq_vals
        
        for gr in xrange(2):                       
            if (self.cur_frame.hdr.n_channels==2): 
                is_pos = [7 for dummy in xrange(576)]

                if(has_intensity_stereo):
                    is_ratio = process_intensity_stereo(self, gr, is_pos)
                            
                for sb in xrange(SBLIMIT):
                    for ss in xrange(SSLIMIT): 
                        i = (sb*18)+ss
                        if ( is_pos[i] == 7 ): 
                            if (has_mid_side_stereo ): 
                                lr[gr][0][sb][ss] = (dq_vals[gr][0][sb][ss]+dq_vals[gr][1][sb][ss])/1.41421356
                                lr[gr][1][sb][ss] = (dq_vals[gr][0][sb][ss]-dq_vals[gr][1][sb][ss])/1.41421356                   
                            else: 
                                lr[gr][0][sb][ss] = dq_vals[gr][0][sb][ss]
                                lr[gr][1][sb][ss] = dq_vals[gr][1][sb][ss]
                        elif (has_intensity_stereo ): 
                            lr[gr][0][sb][ss] = dq_vals[gr][0][sb][ss] * (is_ratio[i]/(1+is_ratio[i]))
                            lr[gr][1][sb][ss] = dq_vals[gr][0][sb][ss] * (1/(1+is_ratio[i])) 
                        
                        else: 
                            print "Stereo - Error"                                                   
                     
            else:                 
                for sb in xrange(SBLIMIT):
                    for ss in xrange(SSLIMIT): 
                        lr[gr][0][sb][ss] = dq_vals[gr][0][sb][ss]

        print lr

    def process_intensity_stereo(self, gr, is_pos):
        ch = 0  

        if (self.cur_frame.side_info.window_switching_flag[ch][gr] and (self.cur_frame.side_info.block_type[ch][gr] == 2)):
            is_ratio = process_intensity_stereo__non_standard_window(gr, is_pos)        
        else:
            is_ratio = process_intensity_stereo__standard_window(gr, is_pos)

        return is_ratio

    def process_intensity_stereo__standard_window(self, gr, is_pos):
        smpl_rate = self.cur_frame.hdr.smpl_rate        
        i  = 31
        ss = 17
        sb = 0;
        while ( i >= 0 ):
            if ( self.decoded_data.dq_vals[1][i][ss] != 0.0 ):
                sb = i*18+ss
                i  = -1
            else:
                ss-=1
                if ( ss < 0 ):
                    i -= 1
                    ss = 17
        i = 0
        while ( sfBandIndex_l[smpl_rate][i] <= sb ):
            i += 1

        sfb = i
        i = sfBandIndex_l[smpl_rate][i]
        for sfb in xrange(sfb,21):
            sb = sfBandIndex_l[smpl_rate][sfb+1] - sfBandIndex_l[smpl_rate][sfb]
            for sb in xrange(sb, 0, -1):
                is_pos[i] =  self.cur_frame.main_data.scalefac_l[1][sfb]
                if ( is_pos[i] != 7 ):
                    is_ratio[i] = tan( is_pos[i] * (PI / 12))
                i+=1

        sfb = sfBandIndex_l[smpl_rate][20]
        for sb in xrange(576 - sfBandIndex_l[smpl_rate][21],0,-1):
            is_pos[i]   = is_pos[sfb]
            is_ratio[i] = is_ratio[sfb]
            i += 1
        
        return is_ratio

    def process_intensity_stereo__non_standard_window(self, gr, is_pos):
        ch = 0  
        smpl_rate = self.cur_frame.hdr.smpl_rate

        if (self.cur_frame.side_info.mixed_block_flag[ch][gr]):
            max_sfb = 0;

            for j in xrange(3):
                sfbcnt = 2
                for sfb in xrange(12,2,-1):                   
                    lines = sfBandIndex_s[smpl_rate][sfb+1]-sfBandIndex_s[smpl_rate][sfb];
                    i = 3*sfBandIndex_s[sfreq][sfb] + (j+1) * lines - 1;
                    while ( lines > 0 ):
                        if ( self.decoded_data.dq_vals[1][i/SSLIMIT][i%SSLIMIT] != 0.0 ):
                            sfbcnt = sfb
                            sfb = -10
                            lines = -10
                        lines-=1
                        i-=1

                sfb = sfbcnt + 1

                if ( sfb > max_sfb ):
                    max_sfb = sfb

                while( sfb<12 ):
                    sb = sfBandIndex_s[smpl_rate][sfb+1]-sfBandIndex_s[sfreq][sfb]
                    i = 3*sfBandIndex_s[smpl_rate][sfb] + j * sb
                    for sb in xrange(sb,0,-1):
                        is_pos[i] = self.cur_frame.main_data.scalefac_s[1][j][sfb]
                        if ( is_pos[i] != 7 ):
                            is_ratio[i] = tan( is_pos[i] * (PI / 12))
                        i += 1
                    sfb += 1

                sb = sfBandIndex_s[smpl_rate][11]-sfBandIndex_s[smpl_rate][10];
                sfb = 3*sfBandIndex_s[smpl_rate].s[10] + j * sb;
                sb = sfBandIndex_s[smpl_rate][12]-sfBandIndex_s[smpl_rate][11];
                i = 3*sfBandIndex_s[smpl_rate][11] + j * sb;
                for sb in xrange(sb,0,-1):
                    is_pos[i]   = is_pos[sfb]
                    is_ratio[i] = is_ratio[sfb]
                    i += 1

            if ( max_sfb <= 3 ):
                i = 2
                ss = 17
                sb = -1
                while ( i >= 0 ):
                    if ( self.decoded_data.dq_vals[1][i][ss] != 0.0 ):
                        sb = i*18+ss
                        i = -1
                    else:
                        ss-=1
                        if ( ss < 0 ):
                            i-=1
                            ss = 17
                i = 0
                while ( sfBandIndex_l[smpl_rate][i] <= sb ):
                    i+=1
                sfb = i
                i = sfBandIndex_l[smpl_rate][i]
                for sfb in xrange(sfb, 8):
                    sb = sfBandIndex_l[smpl_rate][sfb+1]-sfBandIndex_l[sfreq][sfb]
                    for sb in xrange(sb, 0, -1):
                        is_pos[i] = self.cur_frame.main_data.scalefac_l[1][sfb];
                        if ( is_pos[i] != 7 ):
                            is_ratio[i] = tan( is_pos[i] * (PI / 12))
                        i+=1

        else:
            for j in xrange(3):
                sfbcnt = -1
                for sfb in xrange(12,-1,-1):
                    lines = sfBandIndex_s[smpl_rate][sfb+1]-sfBandIndex_s[smpl_rate][sfb]
                    i = 3*sfBandIndex_s[smpl_rate][sfb] + (j+1) * lines - 1
                    while ( lines > 0 ):
                        if ( self.decoded_data.dq_vals[1][i/SSLIMIT][i%SSLIMIT] != 0.0 ):
                            sfbcnt = sfb
                            sfb = -10
                            lines = -10                         
                        lines-=1
                        i-=1
            sfb = sfbcnt + 1
            while( sfb<12 ):
                sb = sfBandIndex_s[smpl_rate][sfb+1]-sfBandIndex_s[smpl_rate][sfb]
                i = 3*sfBandIndex_s[smpl_rate][sfb] + j * sb
                for sb in xrange(sb,0,-1):
                    is_pos[i] = self.cur_frame.main_data.scalefac_s[1][j][sfb]
                    if ( is_pos[i] != 7 ):
                        is_ratio[i] = tan( is_pos[i] * (PI / 12))
                    i+=1
                sfb+=1

            sb = sfBandIndex_s[smpl_rate][11]-sfBandIndex_s[sfreq][10]
            sfb = 3*sfBandIndex_s[smpl_rate][10] + j * sb
            sb = sfBandIndex_s[smpl_rate][12]-sfBandIndex_s[sfreq][11]
            i = 3*sfBandIndex_s[smpl_rate][11] + j * sb
            for sb in xrange(sb,-1,-1):
                is_pos[i]   = is_pos[sfb]
                is_ratio[i] = is_ratio[sfb]
                i+=1

        return is_ratio
    
    def reorder_samples(self):
        pass

    def antialias_samples(self):
        pass

    def hybrid_synthesis(self):
        pass

    def polyphase_synthesis(self):
        pass

    def decode_main_info(self):
        for gr in xrange(2):
            for ch in xrange(self.cur_frame.hdr.n_channels):
                part2_start = self.bitbfr.get_pos()                
                if(self.cur_frame.side_info.window_switching_flag[ch][gr] == 1 and 
                   self.cur_frame.side_info.block_type[ch][gr] == 2):
                    if(self.cur_frame.side_info.mixed_block_flag[ch][gr]):
                        #mixed blocks
                        print "mixed scale blocks not supported yet"
                        pass
                    else:
                        #short blocks
                        for i in xrange(2):
                            for sfb in xrange(sfbtable_s[i], sfbtable_s[i+1]):
                                for window in xrange(3):
                                    self.cur_frame.main_data.scalefac_s[ch][window][sfb] = self.bitbfr.read_bits(slen[i][self.cur_frame.side_info.scalefac_compress[ch][gr]])
                        
                        sfb = 12                        
                        for window in xrange(3):
                            self.cur_frame.main_data.scalefac_s[ch][window][sfb] = 0;  
  
                else:
                    #long blocks                   
                    for i in xrange(4):
                        if ((self.cur_frame.side_info.scfsi[ch][i] == 0) or (gr == 0)):
                            for sfb in xrange( sfbtable_l[i], sfbtable_l[i+1]):
                                if(i<2): 
                                    k=0
                                else:    
                                     k=1
                                self.cur_frame.main_data.scalefac_l[ch][sfb] = self.bitbfr.read_bits(slen[k][self.cur_frame.side_info.scalefac_compress[ch][gr]])
                    self.cur_frame.main_data.scalefac_l[ch][22] = 0
                #print self.cur_frame.main_data.scalefac_s
                #print self.cur_frame.main_data.scalefac_l
                self.decode_main_data_huffman(ch, gr, part2_start)

    def decode_main_data_huffman(self, ch, gr, part2_start):
        
        #calculate region boundries
        if(self.cur_frame.side_info.window_switching_flag[ch][gr] == 1 and 
           self.cur_frame.side_info.block_type[ch][gr] == 2):
            #short block
            region1Start = 36; 
            region2Start = 576; 
        else:
            #long block
            region1Start = sfBandIndex_l[self.cur_frame.hdr.smpl_rate][self.cur_frame.side_info.region0_count[ch][gr] + 1]
            region2Start = sfBandIndex_l[self.cur_frame.hdr.smpl_rate][self.cur_frame.side_info.region0_count[ch][gr] + self.cur_frame.side_info.region1_count[ch][gr] + 2]

        #read big value area
        for i in xrange(0, self.cur_frame.side_info.big_values[ch][gr]*2, 2):
            if (i<region1Start): 
                ht_idx = self.cur_frame.side_info.table_select[ch][gr][0]
            elif (i<region2Start): 
                ht_idx = self.cur_frame.side_info.table_select[ch][gr][1]
            else:               
                ht_idx = self.cur_frame.side_info.table_select[ch][gr][2]
            ht = ht_list[ht_idx]
            v, w, x, y = self.huffman_decoder(ht)
            #print "huff bv:%d t:%d v:%d %d" % (i, ht_idx, x, y)            
            self.cur_frame.main_data.q_vals[gr][ch][i/SSLIMIT][i%SSLIMIT]           = x
            self.cur_frame.main_data.q_vals[gr][ch][(i+1)/SSLIMIT][(i+1)%SSLIMIT]   = y

        #read count1 area
        idx = self.cur_frame.side_info.big_values[ch][gr]*2        
        ht = ht_list[self.cur_frame.side_info.count1table_select[ch][gr] + 32] #32 is offset to count1 tables
        while( (self.bitbfr.get_pos() < (part2_start + self.cur_frame.side_info.part2_3_length[ch][gr]) ) and (idx<SBLIMIT*SSLIMIT) ):
            v, w, x, y = self.huffman_decoder(ht)
            #print "huff ct1:%d t:%d v:%d %d %d %d" % (idx, self.cur_frame.side_info.count1table_select[ch][gr] + 32, x, y, v, w)            
            self.cur_frame.main_data.q_vals[gr][ch][idx/SSLIMIT][idx%SSLIMIT] = v;
            self.cur_frame.main_data.q_vals[gr][ch][(idx+1)/SSLIMIT][(idx+1)%SSLIMIT] = w
            self.cur_frame.main_data.q_vals[gr][ch][(idx+2)/SSLIMIT][(idx+2)%SSLIMIT] = x
            self.cur_frame.main_data.q_vals[gr][ch][(idx+3)/SSLIMIT][(idx+3)%SSLIMIT] = y
            idx += 4

        #the rest are zeros 
        

    def huffman_decoder(self, ht):                
        MXOFF = 250         
        v = w = x = y = 0        
        
        #check for empty tree        
        if(ht.treelen == 0):
            return (0,0,0,0)

        #run through huffman tree
        success = False
        pos = 0
        nbits = 0       
        while(pos<ht.treelen and nbits<32):
            #check for end of tree   
            if(ht.values[pos][0] == 0):         
                x = ht.values[pos][1] >> 4;
                y = ht.values[pos][1] & 0xf;
                success = True
                break

            #get more bits to transverse tree            
            bit = self.bitbfr.read_bits(1)
            while(ht.values[pos][bit] >= MXOFF):
                pos += ht.values[pos][bit]
            pos += ht.values[pos][bit]

            nbits += 1

        if(not success):
            print "Failure during huffman decode"
            return (0,0,0,0)
            
        #read sign bits
        if(ht.tbl_type == "quad"):
            v = (y>>3) & 1;
            w = (y>>2) & 1;
            x = (y>>1) & 1;
            y = y & 1; 

            if(v != 0):
                if(self.bitbfr.read_bits(1)):
                    v = -v                   
            if(w != 0):
                if(self.bitbfr.read_bits(1)):
                    w = -w                   
            if(x != 0):
                if(self.bitbfr.read_bits(1)):
                    x = -x                   
            if(y != 0):
                if(self.bitbfr.read_bits(1)):
                    y = -y                   
        else:
            #process escape encodings            
            if(ht.linbits > 0):
                if((ht.xlen-1) == x):
                    x += self.bitbfr.read_bits(ht.linbits)
            if(x != 0):
                if(self.bitbfr.read_bits(1)):
                    x = -x                   

            if(ht.linbits > 0):
                if((ht.ylen-1) == y):
                    y += self.bitbfr.read_bits(ht.linbits)
            if(y != 0):
                if(self.bitbfr.read_bits(1)):
                    y = -y                   
                
        return (v, w, x, y)        

    def decode_side_info(self):
        self.cur_frame.side_info.main_data_begin = self.bitbfr.read_bits(9)

        if(self.cur_frame.side_info.main_data_begin != 0):
            print "Error - dont support bitreservoir yet"

        if(self.cur_frame.hdr.n_channels==1):
            self.cur_frame.side_info.private_bits = self.bitbfr.read_bits(5)
        else:
            self.cur_frame.side_info.private_bits = self.bitbfr.read_bits(3)

        for ch in xrange(self.cur_frame.hdr.n_channels):
            for i in xrange(4):
                self.cur_frame.side_info.scfsi[ch][i] = self.bitbfr.read_bits(1)

        for gr in xrange(2):
             for ch in xrange(self.cur_frame.hdr.n_channels):
                  self.cur_frame.side_info.part2_3_length[ch][gr] = self.bitbfr.read_bits(12)
                  self.cur_frame.side_info.big_values[ch][gr] = self.bitbfr.read_bits(9)
                  self.cur_frame.side_info.global_gain[ch][gr] = self.bitbfr.read_bits(8)
                  self.cur_frame.side_info.scalefac_compress[ch][gr] = self.bitbfr.read_bits(4)
                  self.cur_frame.side_info.window_switching_flag[ch][gr] = self.bitbfr.read_bits(1)
                  if(self.cur_frame.side_info.window_switching_flag[ch][gr]):
                      self.cur_frame.side_info.block_type[ch][gr] = self.bitbfr.read_bits(2)
                      self.cur_frame.side_info.mixed_block_flag[ch][gr] = self.bitbfr.read_bits(1)
                      for i in xrange(2):
                           self.cur_frame.side_info.table_select[ch][gr][i] = self.bitbfr.read_bits(5)
                      for i in xrange(3):
                           self.cur_frame.side_info.subblock_gain[ch][gr][i] = self.bitbfr.read_bits(3)
                      if(self.cur_frame.side_info.block_type[ch][gr] == 2 and self.cur_frame.side_info.mixed_block_flag[ch][gr] == 0):
                          self.cur_frame.side_info.region0_count[ch][gr] = 8
                      else:
                          self.cur_frame.side_info.region0_count[ch][gr] = 7
                      self.cur_frame.side_info.region1_count[ch][gr] = 20 - self.cur_frame.side_info.region0_count[ch][gr]
                  else:
                       for i in xrange(3):
                           self.cur_frame.side_info.table_select[ch][gr][i] = self.bitbfr.read_bits(5)
                       self.cur_frame.side_info.region0_count[ch][gr] = self.bitbfr.read_bits(4)
                       self.cur_frame.side_info.region1_count[ch][gr] = self.bitbfr.read_bits(3)
                       self.cur_frame.side_info.block_type[ch][gr] = 0
                  self.cur_frame.side_info.preflag[ch][gr] = self.bitbfr.read_bits(1)
                  self.cur_frame.side_info.scalefac_scale[ch][gr] = self.bitbfr.read_bits(1)
                  self.cur_frame.side_info.count1table_select[ch][gr] = self.bitbfr.read_bits(1)

        if(dbg_output):
            print "main_data_begin:",  self.cur_frame.side_info.main_data_begin     
            print "privatebits:", self.cur_frame.side_info.private_bits         
            print "scale factor select info:", self.cur_frame.side_info.scfsi                 
            print "part 2_3 len:", self.cur_frame.side_info.part2_3_length        
            print "big values:", self.cur_frame.side_info.big_values          
            print "global gain:", self.cur_frame.side_info.global_gain           
            print "scalefac_compress", self.cur_frame.side_info.scalefac_compress     
            print "win switch flag:", self.cur_frame.side_info.window_switching_flag 
            print "block type:", self.cur_frame.side_info.block_type            
            print "mixed block flag:", self.cur_frame.side_info.mixed_block_flag      
            print "table select:", self.cur_frame.side_info.table_select          
            print "subblock gain:", self.cur_frame.side_info.subblock_gain         
            print "region0_count", self.cur_frame.side_info.region0_count         
            print "region1_count", self.cur_frame.side_info.region1_count         
            print "preflag", self.cur_frame.side_info.preflag               
            print "scalefac_scale", self.cur_frame.side_info.scalefac_scale        
            print "count1table select:", self.cur_frame.side_info.count1table_select    

    def decode_CRC(self):
         if(self.cur_frame.hdr.has_CRC):
            crc = self.bitbfr.read_bits(16)

    def decode_frame_header(self):
  
        self.cur_frame.hdr.mpeg_version   = mp3_hdr_ver_tbl[self.bitbfr.read_bits(1)]  
        self.cur_frame.hdr.layer          = mp3_hdr_layer_tbl[self.bitbfr.read_bits(2)]
        self.cur_frame.hdr.has_CRC        = not self.bitbfr.read_bits(1)
        self.cur_frame.hdr.bitrate        = mp3_hdr_bitrate_tbl[self.bitbfr.read_bits(4)]
        self.cur_frame.hdr.smpl_rate      = mp3_hdr_smpl_rate_tbl[self.bitbfr.read_bits(2)]
        self.cur_frame.hdr.padding        = self.bitbfr.read_bits(1)
        self.bitbfr.read_bits(1)          #private bit
        self.cur_frame.hdr.channel_mode   = mp3_hdr_channel_mode_tbl[self.bitbfr.read_bits(2)]
        self.cur_frame.hdr.mode_extention = self.bitbfr.read_bits(2)
        self.cur_frame.hdr.copyrighted    = self.bitbfr.read_bits(1)
        self.cur_frame.hdr.original       = self.bitbfr.read_bits(1)  
        self.cur_frame.hdr.emphasis       = mp3_hdr_emphasis_tbl[self.bitbfr.read_bits(2)]  

        if(self.cur_frame.hdr.channel_mode == "mono"):         
            self.cur_frame.hdr.n_channels = 1
        else:
            self.cur_frame.hdr.n_channels = 2

        if(dbg_output):
            print "frame header info"            
            print "ver:", self.cur_frame.hdr.mpeg_version
            print "layer:", self.cur_frame.hdr.layer
            print "has CRC:", self.cur_frame.hdr.has_CRC
            print "bitrate(kps):", self.cur_frame.hdr.bitrate
            print "sample rate:", self.cur_frame.hdr.smpl_rate      
            print "padding:", self.cur_frame.hdr.padding        
            print "channel mode:", self.cur_frame.hdr.channel_mode   
            print "n channels:", self.cur_frame.hdr.n_channels            
            print "mode extention:", self.cur_frame.hdr.mode_extention 
            print "copyrighted:", self.cur_frame.hdr.copyrighted              
            print "original copy:", self.cur_frame.hdr.original                
            print "emphasis:", self.cur_frame.hdr.emphasis               


    def find_next_syncword(self):
        #align to byte boundry
        align = self.bitbfr.get_pos()%8
        if(align != 0):        
            self.bitbfr.read_bits(8-align)
    
        cnt = 0        
        while( self.bitbfr.bits_left() > 0):
            b = self.bitbfr.read_bits(4)
            if(b == 0xf):  
                cnt += 1
                if(cnt == 3):
                    break
            else:                
                cnt = 0
        #print "sync %d" % (self.bitbfr.get_pos())


#test code
p = pyMP3("./test2.mp3")
p.decode()