summaryrefslogtreecommitdiff
path: root/ext/mplex/bits.cc
blob: 84d05919afc4e69343f65ec111314fd8c4eef085 (plain)
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
/** @file bits.cc, bit-level output                                              */

/* Copyright (C) 2001, Andrew Stevens <andrew.stevens@philips.com> *

 *
 * Disclaimer of Warranty
 *
 * These software programs are available to the user without any license fee or
 * royalty on an "as is" basis.  The MPEG Software Simulation Group disclaims
 * any and all warranties, whether express, implied, or statuary, including any
 * implied warranties or merchantability or of fitness for a particular
 * purpose.  In no event shall the copyright-holder be liable for any
 * incidental, punitive, or consequential damages of any kind whatsoever
 * arising from the use of these programs.
 *
 * This disclaimer of warranty extends to the user of these programs and user's
 * customers, employees, agents, transferees, successors, and assigns.
 *
 * The MPEG Software Simulation Group does not represent or warrant that the
 * programs furnished hereunder are free of infringement of any third-party
 * patents.
 *
 * Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
 * are subject to royalty fees to patent holders.  Many of these patents are
 * general enough such that they are unavoidable regardless of implementation
 * design.
 *
 */

#include <config.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/param.h>
#include <assert.h>
#include "mjpeg_logging.h"
#include "bits.hh"


/// Initializes the bitstream, sets internal variables.
// TODO: The buffer size should be set dynamically to sensible sizes.
//
BitStream::BitStream ():
user_data (NULL)
{
  totbits = 0LL;
  buffer_start = 0LL;
  eobs = true;
  readpos = 0LL;
  bfr = 0;
  bfr_size = 0;
}

/// Deconstructor. Deletes the internal buffer. 
BitStream::~BitStream ()
{
  delete bfr;
}

/**
   Refills an IBitStream's input buffer based on the internal variables bufcount and bfr_size. 
 */
bool
IBitStream::refill_buffer ()
{
  size_t i;

  if (bufcount >= bfr_size) {
    SetBufSize (bfr_size + 4096);
  }

  i = read_callback (this, bfr + bufcount, static_cast < size_t > (bfr_size - bufcount), user_data);
  bufcount += i;

  if (i == 0) {
    eobs = true;
    return false;
  }
  return true;
}

/**
  Flushes all read input up-to *but not including* bit
  unbuffer_upto.
@param flush_to the number of bits to flush
*/

void
IBitStream::flush (bitcount_t flush_upto)
{
  if (flush_upto > buffer_start + bufcount)
    mjpeg_error_exit1 ("INTERNAL ERROR: attempt to flush input beyond buffered amount");

  if (flush_upto < buffer_start)
    mjpeg_error_exit1
      ("INTERNAL ERROR: attempt to flush input stream before  first buffered byte %d last is %d",
       (int) flush_upto, (int) buffer_start);
  unsigned int bytes_to_flush = static_cast < unsigned int >(flush_upto - buffer_start);

  //
  // Don't bother actually flushing until a good fraction of a buffer
  // will be cleared.
  //

  if (bytes_to_flush < bfr_size * 3 / 4)
    return;

  bufcount -= bytes_to_flush;
  buffer_start = flush_upto;
  byteidx -= bytes_to_flush;
  memmove (bfr, bfr + bytes_to_flush, static_cast < size_t > (bufcount));
}


/**
  Undo scanning / reading
  N.b buffer *must not* be flushed between prepareundo and undochanges.
  @param undo handle to store the undo information
*/
void
IBitStream::prepareundo (BitStreamUndo & undo)
{
  undo = *(static_cast < BitStreamUndo * >(this));
}

/**
Undoes changes committed to an IBitStream. 
@param undo handle to retrieve the undo information   
 */
void
IBitStream::undochanges (BitStreamUndo & undo)
{
  *(static_cast < BitStreamUndo * >(this)) = undo;
}

/**
   Read a number bytes over an IBitStream, using the buffer. 
   @param dst buffer to read to 
   @param length the number of bytes to read
 */
unsigned int
IBitStream::read_buffered_bytes (uint8_t * dst, unsigned int length)
{
  unsigned int to_read = length;

  if (readpos < buffer_start)
    mjpeg_error_exit1
      ("INTERNAL ERROR: access to input stream buffer @ %d: before first buffered byte (%d)",
       (int) readpos, (int) buffer_start);

  if (readpos + length > buffer_start + bufcount) {
  /*
    if (!feof (fileh)) {
      mjpeg_error
	("INTERNAL ERROR: access to input stream buffer beyond last buffered byte @POS=%lld END=%d REQ=%lld + %d bytes",
	 readpos, bufcount, readpos - (bitcount_t) buffer_start, length);
      abort ();
    }
    */
    to_read = static_cast < unsigned int >((buffer_start + bufcount) - readpos);
  }
  memcpy (dst, bfr + (static_cast < unsigned int >(readpos - buffer_start)), to_read);
  // We only ever flush up to the start of a read as we
  // have only scanned up to a header *beginning* a block that is then
  // read
  flush (readpos);
  readpos += to_read;
  return to_read;
}

/** open the device to read the bit stream from it 
@param bs_filename filename to open
@param buf_size size of the internal buffer 
*/
void
IBitStream::open (ReadCallback read_callback, void *user_data, unsigned int buf_size)
{
  this->read_callback = read_callback;
  this->user_data = user_data;

  bfr_size = buf_size;
  if (bfr == NULL)
    bfr = new uint8_t[buf_size];
  else {
    delete bfr;

    bfr = new uint8_t[buf_size];
  }

  byteidx = 0;
  bitidx = 8;
  totbits = 0LL;
  bufcount = 0;
  eobs = false;
  if (!refill_buffer ()) {
    if (bufcount == 0) {
      mjpeg_error_exit1 ("Unable to read.");
    }
  }
}


/** sets the internal buffer size. 
    @param new_buf_size the new internal buffer size 
*/
void
IBitStream::SetBufSize (unsigned int new_buf_size)
{
  assert (bfr != NULL);		// Must be open first!
  assert (new_buf_size >= bfr_size);	// Can only be increased in size...

  if (bfr_size != new_buf_size) {
    uint8_t *new_buf = new uint8_t[new_buf_size];

    memcpy (new_buf, bfr, static_cast < size_t > (bfr_size));
    delete bfr;

    bfr_size = new_buf_size;
    bfr = new_buf;
  }

}

/**
   close the device containing the bit stream after a read process
*/
void
IBitStream::close ()
{
}


// TODO replace with shift ops!

uint8_t
  IBitStream::masks[8] = {
    0x1,
    0x2,
    0x4,
    0x8,
    0x10,
    0x20,
    0x40,
0x80 };

/*read 1 bit from the bit stream 
@returns the read bit, 0 on EOF */
uint32_t
IBitStream::get1bit ()
{
  unsigned int bit;

  if (eobs)
    return 0;

  bit = (bfr[byteidx] & masks[bitidx - 1]) >> (bitidx - 1);
  totbits++;
  bitidx--;
  if (!bitidx) {
    bitidx = 8;
    byteidx++;
    if (byteidx == bufcount) {
      refill_buffer ();
    }
  }

  return bit;
}

/*read N bits from the bit stream 
@returns the read bits, 0 on EOF */
uint32_t
IBitStream::getbits (int N)
{
  uint32_t val = 0;
  int i = N;
  unsigned int j;

  // Optimize: we are on byte boundary and want to read multiple of bytes!
  if ((bitidx == 8) && ((N & 7) == 0)) {
    i = N >> 3;
    while (i > 0) {
      if (eobs)
	return 0;
      val = (val << 8) | bfr[byteidx];
      byteidx++;
      totbits += 8;
      if (byteidx == bufcount) {
	refill_buffer ();
      }
      i--;
    }
  } else {
    while (i > 0) {
      if (eobs)
	return 0;

      j = (bfr[byteidx] & masks[bitidx - 1]) >> (bitidx - 1);
      totbits++;
      bitidx--;
      if (!bitidx) {
	bitidx = 8;
	byteidx++;
	if (byteidx == bufcount) {
	  refill_buffer ();
	}
      }
      val = (val << 1) | j;
      i--;
    }
  }
  return val;
}


/** This function seeks for a byte aligned sync word (max 32 bits) in the bit stream and
    places the bit stream pointer right after the sync.
    This function returns 1 if the sync was found otherwise it returns 0
@param sync the sync word to search for
@param N the number of bits to retrieve
@param lim number of bytes to search through
@returns false on error */

bool
IBitStream::seek_sync (uint32_t sync, int N, int lim)
{
  uint32_t val, val1;
  uint32_t maxi = ((1U << N) - 1); /* pow(2.0, (double)N) - 1 */ ;
  if (maxi == 0) {
    maxi = 0xffffffff;
  }
  while (bitidx != 8) {
    get1bit ();
  }

  val = getbits (N);
  if (eobs)
    return false;
  while ((val & maxi) != sync && --lim) {
    val <<= 8;
    val1 = getbits (8);
    val |= val1;
    if (eobs)
      return false;
  }

  return (!!lim);
}



/* 
 * Local variables:
 *  c-file-style: "stroustrup"
 *  tab-width: 4
 *  indent-tabs-mode: nil
 * End:
 */