2 - denote 1 zero found
1 - denote 2 zeros found
0 - denote >= 3 zeros found
3 - no this state
4 - denote 2 zeros and 1 one found, i.e., 001
5 - denote at least 3 zeros and 1 one found, i.e., 0001 or 00001,etc
6. - no this state
7 - init state
8 - state greater and equal 8 denote two slice header found
static int ff_h264_find_frame_end(H264Context *h, const uint8_t *buf, int buf_size)
{int i, j;
uint32_t state;
ParseContext *pc = &(h->s.parse_context);
int next_avc= h->is_avc ? 0 : buf_size;
// mb_addr= pc->mb_addr - 1;
state= pc->state;
if(state>13)
state= 7;
if(h->is_avc && !h->nal_length_size)
av_log(h->s.avctx, AV_LOG_ERROR, "AVC-parser: nal length size invalid\n");
for(i=0; i<buf_size; i++){
if(i >= next_avc) {
int nalsize = 0;
i = next_avc;
for(j = 0; j < h->nal_length_size; j++)
nalsize = (nalsize << 8) | buf[i++];
if(nalsize <= 0 || nalsize > buf_size - i){
av_log(h->s.avctx, AV_LOG_ERROR, "AVC-parser: nal size %d remaining %d\n", nalsize, buf_size - i);
return buf_size;
}
next_avc= i + nalsize;
state= 5;
}
if(state==7){
#if HAVE_FAST_UNALIGNED
/* we check i<buf_size instead of i+3/7 because its simpler
* and there should be FF_INPUT_BUFFER_PADDING_SIZE bytes at the end
*/
# if HAVE_FAST_64BIT
// when no one zero arise in continuous 8 bytes, forward 8 bytes
while(i<next_avc && !((~*(const uint64_t*)(buf+i) & (*(const uint64_t*)(buf+i) - 0x0101010101010101ULL)) & 0x8080808080808080ULL))i+=8;
# else
// when no one zero arise in continuous 4 bytes, forward 4 bytes
while(i<next_avc && !((~*(const uint32_t*)(buf+i) & (*(const uint32_t*)(buf+i) - 0x01010101U)) & 0x80808080U))i+=4;
# endif
#endif
for(; i<next_avc; i++){
if(!buf[i]){
state=2;
break;
}
}
}else if(state<=2){
if(buf[i]==1) state^= 5; //2->7, 1->4, 0->5
else if(buf[i]) state = 7;
else state>>=1; //2->1, 1->0, 0->0
}else if(state<=5){
int v= buf[i] & 0x1F;
if(v==6 || v==7 || v==8 || v==9){ // 7 denote sps, 8 denote pps, 9 denote access unit delimiter
if(pc->frame_start_found){
i++;
goto found;
}
}else if(v==1 || v==2 || v==5){ // 1 denote coded slice of a non-IDR picture, 2 deonte coded slice data partition A, 5 denote coded slice of an IDR picture
state+=8;
continue;
}
state= 7;
}else { // to be continued
h->parse_history[h->parse_history_count++]= buf[i];
if(h->parse_history_count>3){
unsigned int mb, last_mb= h->parse_last_mb;
GetBitContext gb;
init_get_bits(&gb, h->parse_history, 8*h->parse_history_count);
h->parse_history_count=0;
mb= get_ue_golomb_long(&gb);
last_mb= h->parse_last_mb;
h->parse_last_mb= mb;
if(pc->frame_start_found){
if(mb <= last_mb)
goto found;
}else
pc->frame_start_found = 1;
state= 7;
}
}
}
pc->state= state;
if(h->is_avc)
return next_avc;
return END_NOT_FOUND;
found:
pc->state=7;
pc->frame_start_found= 0;
if(h->is_avc)
return next_avc;
return i-(state&5) - 3*(state>7);
}