1 /*****************************************************************************
2 * bitstream.c: bitstream writing
3 *****************************************************************************
4 * Copyright (C) 2003-2010 x264 project
6 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7 * Fiona Glaser <fiona@x264.com>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
23 * This program is also available under a commercial proprietary license.
24 * For more information, contact us at licensing@x264.com.
25 *****************************************************************************/
29 static uint8_t *x264_nal_escape_c( uint8_t *dst, uint8_t *src, uint8_t *end )
31 if( src < end ) *dst++ = *src++;
32 if( src < end ) *dst++ = *src++;
35 if( src[0] <= 0x03 && !dst[-2] && !dst[-1] )
43 uint8_t *x264_nal_escape_mmxext( uint8_t *dst, uint8_t *src, uint8_t *end );
44 uint8_t *x264_nal_escape_sse2( uint8_t *dst, uint8_t *src, uint8_t *end );
47 /****************************************************************************
49 ****************************************************************************/
50 void x264_nal_encode( x264_t *h, uint8_t *dst, x264_nal_t *nal )
52 uint8_t *src = nal->p_payload;
53 uint8_t *end = nal->p_payload + nal->i_payload;
54 uint8_t *orig_dst = dst;
56 if( h->param.b_annexb )
58 if( nal->b_long_startcode )
64 else /* save room for size later */
68 *dst++ = ( 0x00 << 7 ) | ( nal->i_ref_idc << 5 ) | nal->i_type;
70 dst = h->bsf.nal_escape( dst, src, end );
71 int size = (dst - orig_dst) - 4;
73 /* Write the size header for mp4/etc */
74 if( !h->param.b_annexb )
76 /* Size doesn't include the size of the header we're writing now. */
77 orig_dst[0] = size>>24;
78 orig_dst[1] = size>>16;
79 orig_dst[2] = size>> 8;
80 orig_dst[3] = size>> 0;
83 nal->i_payload = size+4;
84 nal->p_payload = orig_dst;
88 void x264_bitstream_init( int cpu, x264_bitstream_function_t *pf )
90 pf->nal_escape = x264_nal_escape_c;
92 if( cpu&X264_CPU_MMXEXT )
93 pf->nal_escape = x264_nal_escape_mmxext;
94 if( (cpu&X264_CPU_SSE2) && (cpu&X264_CPU_SSE2_IS_FAST) )
95 pf->nal_escape = x264_nal_escape_sse2;