fixed chapter font size.
[swftools.git] / lib / bladeenc / formatbitstream2.c
1 /*
2                         (c) Copyright 1998-2001 - Tord Jansson
3                         ======================================
4
5                 This file is part of the BladeEnc MP3 Encoder, based on
6                 ISO's reference code for MPEG Layer 3 compression.
7
8                 This file doesn't contain any of the ISO reference code and
9                 is copyright Tord Jansson (tord.jansson@swipnet.se).
10
11         BladeEnc is free software; you can redistribute this file
12         and/or modify it under the terms of the GNU Lesser General Public
13         License as published by the Free Software Foundation; either
14         version 2.1 of the License, or (at your option) any later version.
15
16
17
18         ------------    Changes    ------------
19
20         2000-12-05  Andre Piotrowski
21
22         -       reformatted, slightly optimized
23
24         2001-01-12  ap
25
26         -       use some explicit type casting to avoid compiler warnings
27 */
28
29 #include        <stdio.h>
30 #include        <stdlib.h>
31
32 #if defined(_MSC)
33 #include        <malloc.h>
34 #endif
35
36 #include        "common.h"
37 #include        "formatbitstream2.h"
38
39
40
41
42
43 extern  char    *pEncodedOutput;
44 extern  int             outputBit;
45
46
47
48
49
50 /*____ Structure Definitions _________________________________________________*/
51
52 typedef         struct HeaderDef
53                         {
54                                 int                                             size;
55                                 int                                             frameSize;
56                                 char                                    data[128];
57                                 struct HeaderDef                *pNext;
58                         }                                               Header;
59
60
61
62
63
64 /*____ Function Prototypes ___________________________________________________*/
65
66 static  int                             writeMainDataBits (BF_FrameData *psFrame, BitHolder *psBH);
67 static  void                    putbits (unsigned int val, int n);
68 static  int                             generateHeader (BF_FrameData *psFrame);
69
70
71
72
73
74 /*____ Static Data ___________________________________________________________*/
75
76 static  int                             BitsRemaining     = 0;
77 static  Header                  *pHeaderChain     = NULL;
78 static  Header                  *pFreeHeaderChain = NULL;
79
80
81
82
83
84 /*____ initFormatBitstream() ________________________________________________*/
85
86 void                                    initFormatBitstream (void)
87 {
88         BitsRemaining    = 0;
89         pHeaderChain     = NULL;
90         pFreeHeaderChain = NULL;
91 }
92
93
94
95
96
97 /*____ exitFormatBitstream() _________________________________________________*/
98
99 void                                    exitFormatBitstream (void)
100 {
101         Header                                  *psFree;
102
103         /* Fill out the last frame with 0xFF */
104
105         flushFrame ();
106
107         /* Dealocate Headers */
108
109         while (pHeaderChain != NULL)
110         {
111                 psFree = pHeaderChain;
112                 pHeaderChain = psFree->pNext;
113                 free (psFree);
114         }
115
116         while (pFreeHeaderChain != NULL)
117         {
118                 psFree = pFreeHeaderChain;
119                 pFreeHeaderChain = psFree->pNext;
120                 free (psFree);
121         }
122 }
123
124
125
126
127
128 /*____ flushFrame() _________________________________________________________*/
129
130 void                                    flushFrame (void)
131 {
132         /* Fill out the last frame with 0xFF */
133
134         while (BitsRemaining > 32)
135         {
136                 putbits (0xFFFFFFFF, 32);
137                         BitsRemaining -= 32;
138         }
139
140         if (BitsRemaining > 0)
141                 putbits (0xFFFFFFFF, BitsRemaining);
142
143         BitsRemaining = 0;
144 }
145
146
147
148
149
150 /*____ initBitHolder() ______________________________________________________*/
151
152 BitHolder                               *initBitHolder
153 (
154         BitHolder                               *wp,
155         int                                             elements
156 )
157 {
158         wp->element      = (BitHolderElement *) malloc (sizeof(BitHolderElement) * elements);
159         wp->max_elements = elements;
160         wp->nrEntries    = 0;
161
162         return wp;
163 }
164
165
166
167
168
169 /*____ exitBitHolder() ______________________________________________________*/
170
171 void                                    exitBitHolder (BitHolder * wp)
172 {
173         mem_free ((void **)&wp->element);
174 /*
175         if (wp->element != NULL)
176         {
177                 free (wp->element);
178                 wp->element = NULL;
179         }
180 */
181 }
182
183
184
185
186
187 /*____ addBits() ____________________________________________________________*/
188
189 void                                    addBits
190 (
191         BitHolder                               *wp,
192         unsigned int                    value,
193         int                                             length
194 )
195 {
196         if (length != 0)
197         {
198                 if (wp->nrEntries == wp->max_elements)
199                 {
200                         printf ("ERROR: BitHolder overflow!\n");
201                         exit (-1);
202                 }
203
204                 value &= 0xFFFFFFFF >> (32-length);
205
206                 wp->element[wp->nrEntries].value  = value;
207                 wp->element[wp->nrEntries].length = length;
208                 wp->nrEntries++;
209         }
210 }
211
212
213
214
215
216 /*____ writeFrame() _________________________________________________________*/
217
218 void                                    writeFrame
219 (
220         BF_FrameData                    *psFrame,
221         BF_FrameResults                 *results
222 )
223 {
224         int                                             bits;
225         int                                             gr, ch;
226
227         int                                             sizeRemainHeaders, sizeRemainFrames;
228         Header                                  *psHeader;
229
230
231         /* Generate and save header, return size of SideInfo.*/
232
233         results->SILength = generateHeader (psFrame);
234
235
236         /* Put the bits and compute size of mainData */
237
238         bits = 0;
239         for (gr = 0;  gr < psFrame->nGranules;  gr++)
240         {
241                 for (ch = 0;  ch < psFrame->nChannels;  ch++)
242                 {
243                         bits += writeMainDataBits (psFrame, &psFrame->scaleFactors[gr][ch]);
244                         bits += writeMainDataBits (psFrame, &psFrame->   codedData[gr][ch]);
245                         bits += writeMainDataBits (psFrame, &psFrame->userSpectrum[gr][ch]);
246                 }
247         }
248         bits += writeMainDataBits (psFrame, &psFrame->userFrameData);
249
250         results->mainDataLength = bits;
251
252
253         /* calculate nextBackPointer */
254
255         sizeRemainHeaders = 0;
256         sizeRemainFrames  = 0;
257
258         for (psHeader = pHeaderChain;  psHeader != NULL;  psHeader = psHeader->pNext)
259         {
260                 sizeRemainHeaders += psHeader->size;
261                 sizeRemainFrames  += psHeader->frameSize;
262         }
263
264
265         results->nextBackPtr = (BitsRemaining / 8) + sizeRemainFrames - sizeRemainHeaders;      /* BitsRemaining must be dividable by 8 */
266 }
267
268
269
270
271
272 /*=============================================================================
273                                                                         >>> Static Functions <<<
274 =============================================================================*/
275
276
277
278
279
280 /*____ writeBitHolder() _____________________________________________________*/
281
282 static  void                    writeBitHolder (BitHolder *part)
283 {
284         BitHolderElement                *ep;
285         int                                             i;
286
287         ep = part->element;
288         for (i = 0;  i < part->nrEntries;  i++, ep++)
289                 putbits (ep->value, ep->length);
290 }
291
292
293
294
295
296 /*____ calcCRC() ____________________________________________________________*/
297
298 static  int                             calcCRC
299 (
300         char                                    *pData,
301         int                                             size
302 )
303 {
304         int                                             i;
305         int                                             crc = 0xffff;
306         int                                             masking;
307         int                                             carry;
308         int                                             data;
309
310         for (i = 2;  i < size;  i++)
311         {
312                 if (i != 4  &&  i != 5)
313                 {
314                         masking = 1 << 8;
315                         data    = pData[i];
316                         while (masking >>= 1)
317                         {
318                                 carry = crc & 0x8000;
319                                 crc <<= 1;
320                                 /*
321                                         if ( (carry == 0) != ((data & masking) == 0) )
322                                 */
323                                 if (!carry ^ !(data & masking))
324                                         crc ^= 0x8005;
325                         }
326                 }
327         }
328
329         crc &= 0xffff;
330         return crc;
331 }
332
333
334
335
336
337 /*____ generateHeader() ____________________________________________________*/
338
339 static  int                             generateHeader (BF_FrameData *psFrame)
340 {
341         int                                             gr, ch;
342         int                                             crc;
343         Header                                  *psHeader;
344         Header                                  **wpLink;
345         char                                    *pOldEncodedOutput;
346
347
348         /* Get a Free Header structure */
349
350         if( pFreeHeaderChain == NULL )
351         psHeader = (Header *) malloc( sizeof( Header ) );
352         else
353         {
354         psHeader = pFreeHeaderChain;
355         pFreeHeaderChain = psHeader->pNext;
356         }
357         psHeader->pNext = NULL;
358         for( wpLink = &pHeaderChain ; * wpLink != NULL ; wpLink = &((*wpLink)->pNext) )
359         {}   /* avoid compiler warning */
360         *wpLink = psHeader;
361
362
363         /* Generate the Header */
364
365         pOldEncodedOutput = pEncodedOutput;
366         pEncodedOutput = psHeader->data;
367         pEncodedOutput[0] = 0;                                                                          /* Need to be cleared since we OR in data... */
368
369
370         writeBitHolder (&psFrame->header);
371         writeBitHolder (&psFrame->frameSI);
372
373         for (ch = 0;  ch < psFrame->nChannels;  ch++)
374                 writeBitHolder (&psFrame->channelSI[ch]);
375
376         for (gr = 0;  gr < psFrame->nGranules;  gr++)
377                 for (ch = 0;  ch < psFrame->nChannels;  ch++)
378                         writeBitHolder (&psFrame->spectrumSI[gr][ch]);
379
380
381         /* Checksum generation (if CRC enabled).*/
382
383         if (!(psHeader->data[1] & 0x1))
384         {
385                 crc = calcCRC (psHeader->data, pEncodedOutput - psHeader->data);
386                 psHeader->data[4] = (char) (crc >> 8);
387                 psHeader->data[5] = (char) crc;
388         }
389
390
391         psHeader->size      = pEncodedOutput - psHeader->data;
392         psHeader->frameSize = psFrame->frameLength / 8;
393
394         pEncodedOutput = pOldEncodedOutput;
395
396
397         return  psHeader->size * 8;
398 }
399
400
401
402
403
404 /*____ writeHeader() _______________________________________________________*/
405
406 static  int                             writeHeader (void)
407 {
408         Header                                  *psHeader;
409
410         psHeader = pHeaderChain;
411         memcpy (pEncodedOutput, psHeader->data, psHeader->size);
412         pEncodedOutput += psHeader->size;
413         *pEncodedOutput = 0;
414
415         pHeaderChain = psHeader->pNext;
416         psHeader->pNext = pFreeHeaderChain;
417         pFreeHeaderChain = psHeader;
418
419         return  (psHeader->frameSize - psHeader->size) * 8;
420 }
421
422
423
424
425
426 /*____ writeMainDataBits() __________________________________________________*/
427
428 static  int                             writeMainDataBits
429 (
430         BF_FrameData                    *psFrame,   /* avoid compiler warning */
431         BitHolder                               *psBH
432 )
433 {
434         BitHolderElement                *psElem = psBH->element;
435         int                                             i, bits = 0;
436         unsigned int                    val;
437         int                                             nBits;
438
439         for (i = 0;  i < psBH->nrEntries;  i++, psElem++)
440         {
441                 val   = psElem->value;
442                 nBits = psElem->length;
443
444                 if (BitsRemaining == 0)
445                         BitsRemaining = writeHeader ();
446
447                 if (nBits > BitsRemaining)
448                 {
449                         nBits -= BitsRemaining;
450                         putbits (val >> nBits, BitsRemaining);
451                         BitsRemaining = writeHeader ();
452                 }
453
454                 putbits (val, nBits);
455                 BitsRemaining -= nBits;
456
457                 bits += psElem->length;
458         }
459
460         return  bits;
461 }
462
463
464
465
466
467 /*____ putbits() _____________________________________________________________*/
468
469
470 /*write n bits into the bit stream */
471
472 static  void                    putbits
473 (
474         unsigned int                    val,
475         int                                             n
476 )
477 {
478
479         if (n == 0)
480                 return;
481
482         while (n >= outputBit)
483         {
484                 n -= outputBit;
485
486                 *pEncodedOutput |= val >> n;
487
488                 outputBit = 8;
489                 pEncodedOutput++;
490                 *pEncodedOutput = 0;
491         }
492
493         if (n > 0)   /* n < outputBit */
494         {
495                 outputBit -= n;
496
497                 *pEncodedOutput |= val << outputBit;
498         }
499 }
500
501
502