Encoder now writes data directly in the user buffer
[opus.git] / libcelt / entenc.c
1 #ifdef HAVE_CONFIG_H
2 #include "config.h"
3 #endif
4
5 #include "os_support.h"
6 #include "entenc.h"
7 #include "arch.h"
8
9
10 #define EC_BUFFER_INCREMENT (256)
11
12 void ec_byte_writeinit_buffer(ec_byte_buffer *_b, unsigned char *_buf, long _size){
13   _b->ptr=_b->buf=_buf;
14   _b->storage=_size;
15 }
16
17 void ec_byte_writeinit(ec_byte_buffer *_b){
18   _b->ptr=_b->buf=celt_alloc(EC_BUFFER_INCREMENT*sizeof(char));
19   _b->storage=EC_BUFFER_INCREMENT;
20 }
21
22 void ec_byte_writetrunc(ec_byte_buffer *_b,long _bytes){
23   _b->ptr=_b->buf+_bytes;
24 }
25
26 void ec_byte_write1(ec_byte_buffer *_b,unsigned _value){
27   ptrdiff_t endbyte;
28   endbyte=_b->ptr-_b->buf;
29   if(endbyte>=_b->storage){
30     celt_fatal("range encoder overflow\n");
31   }
32   *(_b->ptr++)=(unsigned char)_value;
33 }
34
35 void ec_byte_write4(ec_byte_buffer *_b,ec_uint32 _value){
36   ptrdiff_t endbyte;
37   endbyte=_b->ptr-_b->buf;
38   if(endbyte+4>_b->storage){
39     celt_fatal("range encoder overflow\n");
40   }
41   *(_b->ptr++)=(unsigned char)_value;
42   _value>>=8;
43   *(_b->ptr++)=(unsigned char)_value;
44   _value>>=8;
45   *(_b->ptr++)=(unsigned char)_value;
46   _value>>=8;
47   *(_b->ptr++)=(unsigned char)_value;
48 }
49
50 void ec_byte_writecopy(ec_byte_buffer *_b,void *_source,long _bytes){
51   ptrdiff_t endbyte;
52   endbyte=_b->ptr-_b->buf;
53   if(endbyte+_bytes>_b->storage){
54     celt_fatal("range encoder overflow\n");
55   }
56   memmove(_b->ptr,_source,_bytes);
57   _b->ptr+=_bytes;
58 }
59
60 void ec_byte_writeclear(ec_byte_buffer *_b){
61   celt_free(_b->buf);
62 }
63
64
65
66 void ec_enc_bits(ec_enc *_this,ec_uint32 _fl,int _ftb){
67   unsigned fl;
68   unsigned ft;
69   while(_ftb>EC_UNIT_BITS){
70     _ftb-=EC_UNIT_BITS;
71     fl=(unsigned)(_fl>>_ftb)&EC_UNIT_MASK;
72     ec_encode_bin(_this,fl,fl+1,EC_UNIT_BITS);
73   }
74   ft=1<<_ftb;
75   fl=(unsigned)_fl&ft-1;
76   ec_encode_bin(_this,fl,fl+1,_ftb);
77 }
78
79 void ec_enc_uint(ec_enc *_this,ec_uint32 _fl,ec_uint32 _ft){
80   unsigned  ft;
81   unsigned  fl;
82   int       ftb;
83   _ft--;
84   ftb=EC_ILOG(_ft)&-!!_ft;
85   if(ftb>EC_UNIT_BITS){
86     ftb-=EC_UNIT_BITS;
87     ft=(_ft>>ftb)+1;
88     fl=(unsigned)(_fl>>ftb);
89     ec_encode(_this,fl,fl+1,ft);
90     ec_enc_bits(_this,_fl,ftb);
91   } else {
92     ec_encode(_this,_fl,_fl+1,_ft+1);
93   }
94 }
95