1 /******************************************************************************
2  *
3  * Copyright (C) 2015 The Android Open Source Project
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at:
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  *****************************************************************************
18  * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
19 */
20 
21 /**
22 ******************************************************************************
23 * @file
24 *  ih264e_bitstream.c
25 *
26 * @brief
27 *  This file contains function definitions related to bitstream generation
28 *
29 * @author
30 *  ittiam
31 *
32 * @par List of Functions:
33 *  - ih264e_bitstrm_init()
34 *  - ih264e_put_bits()
35 *  - ih264e_put_bit()
36 *  - ih264e_put_rbsp_trailing_bits()
37 *  - ih264e_put_uev()
38 *  - ih264e_put_sev()
39 *  - ih264e_put_nal_start_code_prefix()
40 *
41 ******************************************************************************
42 */
43 
44 /*****************************************************************************/
45 /* File Includes                                                             */
46 /*****************************************************************************/
47 
48 /* System include files */
49 #include <stdio.h>
50 #include <string.h>
51 #include <stdlib.h>
52 #include <assert.h>
53 #include <stdarg.h>
54 #include <math.h>
55 
56 /* User include files */
57 #include "ih264e_config.h"
58 #include "ih264_typedefs.h"
59 #include "ih264_platform_macros.h"
60 #include "ih264_debug.h"
61 #include "ih264e_error.h"
62 #include "ih264e_bitstream.h"
63 #include "ih264_defs.h"
64 #include "ih264_macros.h"
65 
66 
67 /*****************************************************************************/
68 /* Function Definitions                                                      */
69 /*****************************************************************************/
70 
71 /**
72 ******************************************************************************
73 *
74 *  @brief Initializes the encoder bitstream engine
75 *
76 *  @par   Description
77 *  This routine needs to be called at start of slice/frame encode
78 *
79 *  @param[in]   ps_bitstrm
80 *  pointer to bitstream context (handle)
81 *
82 *  @param[in]   p1_bitstrm_buf
83 *  bitstream buffer pointer where the encoded stream is generated in byte order
84 *
85 *  @param[in]   u4_max_bitstrm_size
86 *  indicates maximum bitstream buffer size. (in bytes)
87 *  If actual stream size exceeds the maximum size, encoder should
88 *   1. Not corrupt data beyond u4_max_bitstrm_size bytes
89 *   2. Report an error back to application indicating overflow
90 *
91 *  @return      success or failure error code
92 *
93 ******************************************************************************
94 */
ih264e_bitstrm_init(bitstrm_t * ps_bitstrm,UWORD8 * pu1_bitstrm_buf,UWORD32 u4_max_bitstrm_size)95 IH264E_ERROR_T ih264e_bitstrm_init(bitstrm_t *ps_bitstrm,
96                                    UWORD8 *pu1_bitstrm_buf,
97                                    UWORD32 u4_max_bitstrm_size)
98 {
99     ps_bitstrm->pu1_strm_buffer  = pu1_bitstrm_buf;
100     ps_bitstrm->u4_max_strm_size = u4_max_bitstrm_size;
101 
102     /* Default init values for other members of bitstream context */
103     ps_bitstrm->u4_strm_buf_offset  = 0;
104     ps_bitstrm->u4_cur_word         = 0;
105     ps_bitstrm->i4_bits_left_in_cw  = WORD_SIZE;
106     ps_bitstrm->i4_zero_bytes_run   = 0;
107 
108     return(IH264E_SUCCESS);
109 }
110 
111 /**
112 ******************************************************************************
113 *
114 *  @brief puts a code with specified number of bits into the bitstream
115 *
116 *  @par   Description
117 *  inserts code_len number of bits from lsb of code_val into the
118 *  bitstream. updates context members like u4_cur_word, u4_strm_buf_offset and
119 *  i4_bits_left_in_cw. If the total words (u4_strm_buf_offset) exceeds max
120 *  available size (u4_max_strm_size), returns error without corrupting data
121 *  beyond it
122 *
123 *  @param[in]    ps_bitstrm
124 *  pointer to bitstream context (handle)
125 *
126 *  @param[in]    u4_code_val
127 *  code value that needs to be inserted in the stream.
128 *
129 *  @param[in]    code_len
130 *  indicates code length (in bits) of code_val that would be inserted in
131 *  bitstream buffer size. Range of length[1:WORD_SIZE]
132 *
133 *  @remarks     Assumptions: all bits from bit position code_len to msb of
134 *   code_val shall be zero
135 *
136 *  @return      success or failure error code
137 *
138 ******************************************************************************
139 */
ih264e_put_bits(bitstrm_t * ps_bitstrm,UWORD32 u4_code_val,WORD32 code_len)140 IH264E_ERROR_T ih264e_put_bits(bitstrm_t *ps_bitstrm,
141                                UWORD32 u4_code_val,
142                                WORD32 code_len)
143 {
144     UWORD32 u4_cur_word = ps_bitstrm->u4_cur_word;
145     WORD32  bits_left_in_cw = ps_bitstrm->i4_bits_left_in_cw;
146 
147 
148     /* check assumptions made in the module */
149     ASSERT(code_len > 0 && code_len <= WORD_SIZE);
150 
151     if(code_len < WORD_SIZE)
152         ASSERT((u4_code_val >> code_len) == 0);
153 
154     /* sanity check on the bitstream engine state */
155     ASSERT(bits_left_in_cw > 0 && bits_left_in_cw <= WORD_SIZE);
156 
157     ASSERT(ps_bitstrm->i4_zero_bytes_run <= EPB_ZERO_BYTES);
158 
159     ASSERT(ps_bitstrm->pu1_strm_buffer != NULL);
160 
161 
162     if(bits_left_in_cw > code_len)
163     {
164         /*******************************************************************/
165         /* insert the code in local bitstream word and return              */
166         /* code is inserted in position of bits left (post decrement)      */
167         /*******************************************************************/
168         bits_left_in_cw -= code_len;
169         u4_cur_word     |= (u4_code_val << bits_left_in_cw);
170 
171         ps_bitstrm->u4_cur_word         = u4_cur_word;
172         ps_bitstrm->i4_bits_left_in_cw  = bits_left_in_cw;
173 
174         return(IH264E_SUCCESS);
175     }
176     else
177     {
178         /********************************************************************/
179         /* 1. insert partial code corresponding to bits left in cur word    */
180         /* 2. flush all the bits of cur word to bitstream                   */
181         /* 3. insert emulation prevention bytes while flushing the bits     */
182         /* 4. insert remaining bits of code starting from msb of cur word   */
183         /* 5. update bitsleft in current word and stream buffer offset      */
184         /********************************************************************/
185         UWORD32 u4_strm_buf_offset  = ps_bitstrm->u4_strm_buf_offset;
186 
187         UWORD32 u4_max_strm_size    = ps_bitstrm->u4_max_strm_size;
188 
189         WORD32  zero_run            = ps_bitstrm->i4_zero_bytes_run;
190 
191         UWORD8* pu1_strm_buf        = ps_bitstrm->pu1_strm_buffer;
192 
193         WORD32  i, rem_bits = (code_len - bits_left_in_cw);
194 
195 
196         /*********************************************************************/
197         /* Bitstream overflow check                                          */
198         /* NOTE: corner case of epb bytes (max 2 for 32bit word) not handled */
199         /*********************************************************************/
200         if((u4_strm_buf_offset + (WORD_SIZE>>3)) >= u4_max_strm_size)
201         {
202             /* return without corrupting the buffer beyond its size */
203             return(IH264E_BITSTREAM_BUFFER_OVERFLOW);
204         }
205 
206         /* insert parital code corresponding to bits left in cur word */
207         u4_cur_word |= u4_code_val >> rem_bits;
208 
209         for(i = WORD_SIZE; i > 0; i -= 8)
210         {
211             /* flush the bits in cur word byte by byte and copy to stream */
212             UWORD8   u1_next_byte = (u4_cur_word >> (i-8)) & 0xFF;
213 
214             PUTBYTE_EPB(pu1_strm_buf, u4_strm_buf_offset, u1_next_byte, zero_run);
215         }
216 
217         /* insert the remaining bits from code val into current word */
218         u4_cur_word = rem_bits ? (u4_code_val << (WORD_SIZE - rem_bits)) : 0;
219 
220         /* update the state variables and return success */
221         ps_bitstrm->u4_cur_word         = u4_cur_word;
222         ps_bitstrm->i4_bits_left_in_cw  = WORD_SIZE - rem_bits;
223         ps_bitstrm->i4_zero_bytes_run   = zero_run;
224         ps_bitstrm->u4_strm_buf_offset  = u4_strm_buf_offset;
225         return (IH264E_SUCCESS);
226     }
227 }
228 
229 /**
230 ******************************************************************************
231 *
232 *  @brief inserts a 1-bit code into the bitstream
233 *
234 *  @par   Description
235 *  inserts 1bit lsb of code_val into the bitstream
236 *  updates context members like u4_cur_word, u4_strm_buf_offset and
237 *  i4_bits_left_in_cw. If the total words (u4_strm_buf_offset) exceeds max
238 *  available size (u4_max_strm_size), returns error without corrupting data
239 *  beyond it
240 *
241 *  @param[in]    ps_bitstrm
242 *  pointer to bitstream context (handle)
243 *
244 *  @param[in]    u4_code_val
245 *  code value that needs to be inserted in the stream.
246 *
247 *  @remarks     Assumptions: all bits from bit position 1 to msb of code_val
248 *  shall be zero
249 *
250 *  @return      success or failure error code
251 *
252 ******************************************************************************
253 */
ih264e_put_bit(bitstrm_t * ps_bitstrm,UWORD32 u4_code_val)254 IH264E_ERROR_T ih264e_put_bit(bitstrm_t *ps_bitstrm, UWORD32 u4_code_val)
255 {
256     /* call the put bits function for 1 bit and return */
257     return(ih264e_put_bits(ps_bitstrm, u4_code_val, 1));
258 }
259 
260 /**
261 ******************************************************************************
262 *
263 *  @brief inserts rbsp trailing bits at the end of stream buffer (NAL)
264 *
265 *  @par   Description
266 *  inserts rbsp trailing bits, updates context members like u4_cur_word and
267 *  i4_bits_left_in_cw and flushes the same in the bitstream buffer. If the
268 *  total words (u4_strm_buf_offset) exceeds max available size
269 *  (u4_max_strm_size), returns error without corrupting data beyond it
270 *
271 *  @param[in]    ps_bitstrm
272 *  pointer to bitstream context (handle)
273 *
274 *  @return      success or failure error code
275 *
276 ******************************************************************************
277 */
ih264e_put_rbsp_trailing_bits(bitstrm_t * ps_bitstrm)278 IH264E_ERROR_T ih264e_put_rbsp_trailing_bits(bitstrm_t *ps_bitstrm)
279 {
280     WORD32 i;
281     UWORD32 u4_cur_word = ps_bitstrm->u4_cur_word;
282     WORD32  bits_left_in_cw = ps_bitstrm->i4_bits_left_in_cw;
283     WORD32  bytes_left_in_cw = (bits_left_in_cw - 1) >> 3;
284 
285     UWORD32 u4_strm_buf_offset  = ps_bitstrm->u4_strm_buf_offset;
286     UWORD32 u4_max_strm_size    = ps_bitstrm->u4_max_strm_size;
287     WORD32  zero_run            = ps_bitstrm->i4_zero_bytes_run;
288     UWORD8* pu1_strm_buf        = ps_bitstrm->pu1_strm_buffer;
289 
290     /*********************************************************************/
291     /* Bitstream overflow check                                          */
292     /* NOTE: corner case of epb bytes (max 2 for 32bit word) not handled */
293     /*********************************************************************/
294     if((u4_strm_buf_offset + (WORD_SIZE>>3) - bytes_left_in_cw) >=
295         u4_max_strm_size)
296     {
297         /* return without corrupting the buffer beyond its size */
298         return(IH264E_BITSTREAM_BUFFER_OVERFLOW);
299     }
300 
301     /* insert a 1 at the end of current word and flush all the bits */
302     u4_cur_word |= (1 << (bits_left_in_cw - 1));
303 
304     /* get the bits to be inserted in msbdb of the word */
305     //u4_cur_word <<= (WORD_SIZE - bytes_left_in_cw + 1);
306 
307     for(i = WORD_SIZE; i > (bytes_left_in_cw*8); i -= 8)
308     {
309         /* flush the bits in cur word byte by byte  and copy to stream */
310         UWORD8   u1_next_byte = (u4_cur_word >> (i-8)) & 0xFF;
311 
312         PUTBYTE_EPB(pu1_strm_buf, u4_strm_buf_offset, u1_next_byte, zero_run);
313     }
314 
315     /* update the stream offset */
316     ps_bitstrm->u4_strm_buf_offset  = u4_strm_buf_offset;
317 
318     /* Default init values for scratch variables of bitstream context */
319     ps_bitstrm->u4_cur_word         = 0;
320     ps_bitstrm->i4_bits_left_in_cw  = WORD_SIZE;
321     ps_bitstrm->i4_zero_bytes_run   = 0;
322 
323     return (IH264E_SUCCESS);
324 }
325 
326 /**
327 ******************************************************************************
328 *
329 *  @brief puts exponential golomb code of a unsigned integer into bitstream
330 *
331 *  @par   Description
332 *  computes uev code for given syntax element and inserts the same into
333 *  bitstream by calling ih264e_put_bits() interface.
334 *
335 *  @param[in]    ps_bitstrm
336 *  pointer to bitstream context (handle)
337 *
338 *  @param[in]    u4_code_num
339 *  unsigned integer input whose golomb code is written in stream
340 *
341 *  @remarks     Assumptions: code value can be represented in less than 16bits
342 *
343 *  @return      success or failure error code
344 *
345 ******************************************************************************
346 */
ih264e_put_uev(bitstrm_t * ps_bitstrm,UWORD32 u4_code_num)347 IH264E_ERROR_T ih264e_put_uev(bitstrm_t *ps_bitstrm, UWORD32 u4_code_num)
348 {
349     UWORD32 u4_bit_str, u4_range;
350     IH264E_ERROR_T e_error;
351 
352     /* convert the codenum to exp-golomb bit code: Table 9-2 JCTVC-J1003_d7 */
353     u4_bit_str = u4_code_num + 1;
354 
355     /* get range of the bit string and put using put_bits()                 */
356     GETRANGE(u4_range, u4_bit_str);
357 
358     e_error = ih264e_put_bits(ps_bitstrm, u4_bit_str, (2 * u4_range - 1));
359 
360     return(e_error);
361 }
362 
363 /**
364 ******************************************************************************
365 *
366 *  @brief puts exponential golomb code of a signed integer into bitstream
367 *
368 *  @par   Description
369 *  computes sev code for given syntax element and inserts the same into
370 *  bitstream by calling ih264e_put_bits() interface.
371 *
372 *  @param[in]    ps_bitstrm
373 *  pointer to bitstream context (handle)
374 *
375 *  @param[in]    syntax_elem
376 *  signed integer input whose golomb code is written in stream
377 *
378 *  @remarks     Assumptions: code value can be represented in less than 16bits
379 *
380 *  @return      success or failure error code
381 *
382 ******************************************************************************
383 */
ih264e_put_sev(bitstrm_t * ps_bitstrm,WORD32 syntax_elem)384 IH264E_ERROR_T ih264e_put_sev(bitstrm_t *ps_bitstrm, WORD32 syntax_elem)
385 {
386     UWORD32 u4_code_num, u4_bit_str, u4_range;
387     IH264E_ERROR_T e_error;
388 
389     /************************************************************************/
390     /* convert the codenum to exp-golomb bit code for signed syntax element */
391     /* See Table9-2 and Table 9-3 of standard JCTVC-J1003_d7                */
392     /************************************************************************/
393     if(syntax_elem <= 0)
394     {
395         /* codeNum for non-positive integer =  2*abs(x) : Table9-3  */
396         u4_code_num = ((-syntax_elem) << 1);
397     }
398     else
399     {
400         /* codeNum for positive integer     =  2x-1     : Table9-3  */
401         u4_code_num = (syntax_elem << 1) - 1;
402     }
403 
404     /* convert the codenum to exp-golomb bit code: Table 9-2 JCTVC-J1003_d7 */
405     u4_bit_str = u4_code_num + 1;
406 
407     /* get range of the bit string and put using put_bits()                 */
408     GETRANGE(u4_range, u4_bit_str);
409 
410     e_error = ih264e_put_bits(ps_bitstrm, u4_bit_str, (2 * u4_range - 1));
411 
412     return(e_error);
413 }
414 
415 /**
416 ******************************************************************************
417 *
418 *  @brief insert NAL start code prefix (0x000001) into bitstream with an option
419 *  of inserting leading_zero_8bits (which makes startcode prefix as 0x00000001)
420 *
421 *  @par   Description
422 *  Although start code prefix could have been put by calling ih264e_put_bits(),
423 *  ih264e_put_nal_start_code_prefix() is specially added to make sure emulation
424 *  prevention insertion is not done for the NAL start code prefix which will
425 *  surely happen otherwise by calling ih264e_put_bits() interface.
426 *
427 *  @param[in]    ps_bitstrm
428 *  pointer to bitstream context (handle)
429 *
430 *  @param[in]    insert_leading_zero_8bits
431 *  flag indicating if one more zero bytes needs to prefixed before start code
432 *
433 *  @return      success or failure error code
434 *
435 ******************************************************************************
436 */
ih264e_put_nal_start_code_prefix(bitstrm_t * ps_bitstrm,WORD32 insert_leading_zero_8bits)437 IH264E_ERROR_T ih264e_put_nal_start_code_prefix(bitstrm_t *ps_bitstrm,
438                                                 WORD32 insert_leading_zero_8bits)
439 {
440     UWORD32 u4_strm_buf_offset  = ps_bitstrm->u4_strm_buf_offset;
441     UWORD8* pu1_strm_buf        = ps_bitstrm->pu1_strm_buffer;
442 
443     /* Bitstream buffer overflow check assuming worst case of 4 bytes */
444     if((u4_strm_buf_offset + 4) >= ps_bitstrm->u4_max_strm_size)
445     {
446         return(IH264E_BITSTREAM_BUFFER_OVERFLOW);
447     }
448 
449     /* Insert leading zero 8 bits conditionally */
450     if(insert_leading_zero_8bits)
451     {
452         pu1_strm_buf[u4_strm_buf_offset] = 0x00;
453         u4_strm_buf_offset++;
454     }
455 
456     /* Insert NAL start code prefix 0x00 00 01 */
457     pu1_strm_buf[u4_strm_buf_offset] = 0x00;
458     u4_strm_buf_offset++;
459 
460     pu1_strm_buf[u4_strm_buf_offset] = 0x00;
461     u4_strm_buf_offset++;
462 
463     pu1_strm_buf[u4_strm_buf_offset] = 0x01;
464     u4_strm_buf_offset++;
465 
466     /* update the stream offset */
467     ps_bitstrm->u4_strm_buf_offset = u4_strm_buf_offset;
468 
469     return (IH264E_SUCCESS);
470 }
471 
472