You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

8027 lines
308KB

  1. /*
  2. * H.26L/H.264/AVC/JVT/14496-10/... encoder/decoder
  3. * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file h264.c
  23. * H.264 / AVC / MPEG4 part10 codec.
  24. * @author Michael Niedermayer <michaelni@gmx.at>
  25. */
  26. #include "dsputil.h"
  27. #include "avcodec.h"
  28. #include "mpegvideo.h"
  29. #include "h264.h"
  30. #include "h264data.h"
  31. #include "h264_parser.h"
  32. #include "golomb.h"
  33. #include "rectangle.h"
  34. #include "cabac.h"
  35. //#undef NDEBUG
  36. #include <assert.h>
  37. /**
  38. * Value of Picture.reference when Picture is not a reference picture, but
  39. * is held for delayed output.
  40. */
  41. #define DELAYED_PIC_REF 4
  42. static VLC coeff_token_vlc[4];
  43. static VLC chroma_dc_coeff_token_vlc;
  44. static VLC total_zeros_vlc[15];
  45. static VLC chroma_dc_total_zeros_vlc[3];
  46. static VLC run_vlc[6];
  47. static VLC run7_vlc;
  48. static void svq3_luma_dc_dequant_idct_c(DCTELEM *block, int qp);
  49. static void svq3_add_idct_c(uint8_t *dst, DCTELEM *block, int stride, int qp, int dc);
  50. static void filter_mb( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize);
  51. static void filter_mb_fast( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize);
  52. static av_always_inline uint32_t pack16to32(int a, int b){
  53. #ifdef WORDS_BIGENDIAN
  54. return (b&0xFFFF) + (a<<16);
  55. #else
  56. return (a&0xFFFF) + (b<<16);
  57. #endif
  58. }
  59. const uint8_t ff_rem6[52]={
  60. 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
  61. };
  62. const uint8_t ff_div6[52]={
  63. 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  64. };
  65. static void fill_caches(H264Context *h, int mb_type, int for_deblock){
  66. MpegEncContext * const s = &h->s;
  67. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  68. int topleft_xy, top_xy, topright_xy, left_xy[2];
  69. int topleft_type, top_type, topright_type, left_type[2];
  70. int left_block[8];
  71. int i;
  72. top_xy = mb_xy - (s->mb_stride << FIELD_PICTURE);
  73. //FIXME deblocking could skip the intra and nnz parts.
  74. if(for_deblock && (h->slice_num == 1 || h->slice_table[mb_xy] == h->slice_table[top_xy]) && !FRAME_MBAFF)
  75. return;
  76. //wow what a mess, why didn't they simplify the interlacing&intra stuff, i can't imagine that these complex rules are worth it
  77. topleft_xy = top_xy - 1;
  78. topright_xy= top_xy + 1;
  79. left_xy[1] = left_xy[0] = mb_xy-1;
  80. left_block[0]= 0;
  81. left_block[1]= 1;
  82. left_block[2]= 2;
  83. left_block[3]= 3;
  84. left_block[4]= 7;
  85. left_block[5]= 10;
  86. left_block[6]= 8;
  87. left_block[7]= 11;
  88. if(FRAME_MBAFF){
  89. const int pair_xy = s->mb_x + (s->mb_y & ~1)*s->mb_stride;
  90. const int top_pair_xy = pair_xy - s->mb_stride;
  91. const int topleft_pair_xy = top_pair_xy - 1;
  92. const int topright_pair_xy = top_pair_xy + 1;
  93. const int topleft_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[topleft_pair_xy]);
  94. const int top_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[top_pair_xy]);
  95. const int topright_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[topright_pair_xy]);
  96. const int left_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[pair_xy-1]);
  97. const int curr_mb_frame_flag = !IS_INTERLACED(mb_type);
  98. const int bottom = (s->mb_y & 1);
  99. tprintf(s->avctx, "fill_caches: curr_mb_frame_flag:%d, left_mb_frame_flag:%d, topleft_mb_frame_flag:%d, top_mb_frame_flag:%d, topright_mb_frame_flag:%d\n", curr_mb_frame_flag, left_mb_frame_flag, topleft_mb_frame_flag, top_mb_frame_flag, topright_mb_frame_flag);
  100. if (bottom
  101. ? !curr_mb_frame_flag // bottom macroblock
  102. : (!curr_mb_frame_flag && !top_mb_frame_flag) // top macroblock
  103. ) {
  104. top_xy -= s->mb_stride;
  105. }
  106. if (bottom
  107. ? !curr_mb_frame_flag // bottom macroblock
  108. : (!curr_mb_frame_flag && !topleft_mb_frame_flag) // top macroblock
  109. ) {
  110. topleft_xy -= s->mb_stride;
  111. }
  112. if (bottom
  113. ? !curr_mb_frame_flag // bottom macroblock
  114. : (!curr_mb_frame_flag && !topright_mb_frame_flag) // top macroblock
  115. ) {
  116. topright_xy -= s->mb_stride;
  117. }
  118. if (left_mb_frame_flag != curr_mb_frame_flag) {
  119. left_xy[1] = left_xy[0] = pair_xy - 1;
  120. if (curr_mb_frame_flag) {
  121. if (bottom) {
  122. left_block[0]= 2;
  123. left_block[1]= 2;
  124. left_block[2]= 3;
  125. left_block[3]= 3;
  126. left_block[4]= 8;
  127. left_block[5]= 11;
  128. left_block[6]= 8;
  129. left_block[7]= 11;
  130. } else {
  131. left_block[0]= 0;
  132. left_block[1]= 0;
  133. left_block[2]= 1;
  134. left_block[3]= 1;
  135. left_block[4]= 7;
  136. left_block[5]= 10;
  137. left_block[6]= 7;
  138. left_block[7]= 10;
  139. }
  140. } else {
  141. left_xy[1] += s->mb_stride;
  142. //left_block[0]= 0;
  143. left_block[1]= 2;
  144. left_block[2]= 0;
  145. left_block[3]= 2;
  146. //left_block[4]= 7;
  147. left_block[5]= 10;
  148. left_block[6]= 7;
  149. left_block[7]= 10;
  150. }
  151. }
  152. }
  153. h->top_mb_xy = top_xy;
  154. h->left_mb_xy[0] = left_xy[0];
  155. h->left_mb_xy[1] = left_xy[1];
  156. if(for_deblock){
  157. topleft_type = 0;
  158. topright_type = 0;
  159. top_type = h->slice_table[top_xy ] < 255 ? s->current_picture.mb_type[top_xy] : 0;
  160. left_type[0] = h->slice_table[left_xy[0] ] < 255 ? s->current_picture.mb_type[left_xy[0]] : 0;
  161. left_type[1] = h->slice_table[left_xy[1] ] < 255 ? s->current_picture.mb_type[left_xy[1]] : 0;
  162. if(FRAME_MBAFF && !IS_INTRA(mb_type)){
  163. int list;
  164. int v = *(uint16_t*)&h->non_zero_count[mb_xy][14];
  165. for(i=0; i<16; i++)
  166. h->non_zero_count_cache[scan8[i]] = (v>>i)&1;
  167. for(list=0; list<h->list_count; list++){
  168. if(USES_LIST(mb_type,list)){
  169. uint32_t *src = (uint32_t*)s->current_picture.motion_val[list][h->mb2b_xy[mb_xy]];
  170. uint32_t *dst = (uint32_t*)h->mv_cache[list][scan8[0]];
  171. int8_t *ref = &s->current_picture.ref_index[list][h->mb2b8_xy[mb_xy]];
  172. for(i=0; i<4; i++, dst+=8, src+=h->b_stride){
  173. dst[0] = src[0];
  174. dst[1] = src[1];
  175. dst[2] = src[2];
  176. dst[3] = src[3];
  177. }
  178. *(uint32_t*)&h->ref_cache[list][scan8[ 0]] =
  179. *(uint32_t*)&h->ref_cache[list][scan8[ 2]] = pack16to32(ref[0],ref[1])*0x0101;
  180. ref += h->b8_stride;
  181. *(uint32_t*)&h->ref_cache[list][scan8[ 8]] =
  182. *(uint32_t*)&h->ref_cache[list][scan8[10]] = pack16to32(ref[0],ref[1])*0x0101;
  183. }else{
  184. fill_rectangle(&h-> mv_cache[list][scan8[ 0]], 4, 4, 8, 0, 4);
  185. fill_rectangle(&h->ref_cache[list][scan8[ 0]], 4, 4, 8, (uint8_t)LIST_NOT_USED, 1);
  186. }
  187. }
  188. }
  189. }else{
  190. topleft_type = h->slice_table[topleft_xy ] == h->slice_num ? s->current_picture.mb_type[topleft_xy] : 0;
  191. top_type = h->slice_table[top_xy ] == h->slice_num ? s->current_picture.mb_type[top_xy] : 0;
  192. topright_type= h->slice_table[topright_xy] == h->slice_num ? s->current_picture.mb_type[topright_xy]: 0;
  193. left_type[0] = h->slice_table[left_xy[0] ] == h->slice_num ? s->current_picture.mb_type[left_xy[0]] : 0;
  194. left_type[1] = h->slice_table[left_xy[1] ] == h->slice_num ? s->current_picture.mb_type[left_xy[1]] : 0;
  195. }
  196. if(IS_INTRA(mb_type)){
  197. h->topleft_samples_available=
  198. h->top_samples_available=
  199. h->left_samples_available= 0xFFFF;
  200. h->topright_samples_available= 0xEEEA;
  201. if(!IS_INTRA(top_type) && (top_type==0 || h->pps.constrained_intra_pred)){
  202. h->topleft_samples_available= 0xB3FF;
  203. h->top_samples_available= 0x33FF;
  204. h->topright_samples_available= 0x26EA;
  205. }
  206. for(i=0; i<2; i++){
  207. if(!IS_INTRA(left_type[i]) && (left_type[i]==0 || h->pps.constrained_intra_pred)){
  208. h->topleft_samples_available&= 0xDF5F;
  209. h->left_samples_available&= 0x5F5F;
  210. }
  211. }
  212. if(!IS_INTRA(topleft_type) && (topleft_type==0 || h->pps.constrained_intra_pred))
  213. h->topleft_samples_available&= 0x7FFF;
  214. if(!IS_INTRA(topright_type) && (topright_type==0 || h->pps.constrained_intra_pred))
  215. h->topright_samples_available&= 0xFBFF;
  216. if(IS_INTRA4x4(mb_type)){
  217. if(IS_INTRA4x4(top_type)){
  218. h->intra4x4_pred_mode_cache[4+8*0]= h->intra4x4_pred_mode[top_xy][4];
  219. h->intra4x4_pred_mode_cache[5+8*0]= h->intra4x4_pred_mode[top_xy][5];
  220. h->intra4x4_pred_mode_cache[6+8*0]= h->intra4x4_pred_mode[top_xy][6];
  221. h->intra4x4_pred_mode_cache[7+8*0]= h->intra4x4_pred_mode[top_xy][3];
  222. }else{
  223. int pred;
  224. if(!top_type || (IS_INTER(top_type) && h->pps.constrained_intra_pred))
  225. pred= -1;
  226. else{
  227. pred= 2;
  228. }
  229. h->intra4x4_pred_mode_cache[4+8*0]=
  230. h->intra4x4_pred_mode_cache[5+8*0]=
  231. h->intra4x4_pred_mode_cache[6+8*0]=
  232. h->intra4x4_pred_mode_cache[7+8*0]= pred;
  233. }
  234. for(i=0; i<2; i++){
  235. if(IS_INTRA4x4(left_type[i])){
  236. h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[0+2*i]];
  237. h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[1+2*i]];
  238. }else{
  239. int pred;
  240. if(!left_type[i] || (IS_INTER(left_type[i]) && h->pps.constrained_intra_pred))
  241. pred= -1;
  242. else{
  243. pred= 2;
  244. }
  245. h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]=
  246. h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= pred;
  247. }
  248. }
  249. }
  250. }
  251. /*
  252. 0 . T T. T T T T
  253. 1 L . .L . . . .
  254. 2 L . .L . . . .
  255. 3 . T TL . . . .
  256. 4 L . .L . . . .
  257. 5 L . .. . . . .
  258. */
  259. //FIXME constraint_intra_pred & partitioning & nnz (lets hope this is just a typo in the spec)
  260. if(top_type){
  261. h->non_zero_count_cache[4+8*0]= h->non_zero_count[top_xy][4];
  262. h->non_zero_count_cache[5+8*0]= h->non_zero_count[top_xy][5];
  263. h->non_zero_count_cache[6+8*0]= h->non_zero_count[top_xy][6];
  264. h->non_zero_count_cache[7+8*0]= h->non_zero_count[top_xy][3];
  265. h->non_zero_count_cache[1+8*0]= h->non_zero_count[top_xy][9];
  266. h->non_zero_count_cache[2+8*0]= h->non_zero_count[top_xy][8];
  267. h->non_zero_count_cache[1+8*3]= h->non_zero_count[top_xy][12];
  268. h->non_zero_count_cache[2+8*3]= h->non_zero_count[top_xy][11];
  269. }else{
  270. h->non_zero_count_cache[4+8*0]=
  271. h->non_zero_count_cache[5+8*0]=
  272. h->non_zero_count_cache[6+8*0]=
  273. h->non_zero_count_cache[7+8*0]=
  274. h->non_zero_count_cache[1+8*0]=
  275. h->non_zero_count_cache[2+8*0]=
  276. h->non_zero_count_cache[1+8*3]=
  277. h->non_zero_count_cache[2+8*3]= h->pps.cabac && !IS_INTRA(mb_type) ? 0 : 64;
  278. }
  279. for (i=0; i<2; i++) {
  280. if(left_type[i]){
  281. h->non_zero_count_cache[3+8*1 + 2*8*i]= h->non_zero_count[left_xy[i]][left_block[0+2*i]];
  282. h->non_zero_count_cache[3+8*2 + 2*8*i]= h->non_zero_count[left_xy[i]][left_block[1+2*i]];
  283. h->non_zero_count_cache[0+8*1 + 8*i]= h->non_zero_count[left_xy[i]][left_block[4+2*i]];
  284. h->non_zero_count_cache[0+8*4 + 8*i]= h->non_zero_count[left_xy[i]][left_block[5+2*i]];
  285. }else{
  286. h->non_zero_count_cache[3+8*1 + 2*8*i]=
  287. h->non_zero_count_cache[3+8*2 + 2*8*i]=
  288. h->non_zero_count_cache[0+8*1 + 8*i]=
  289. h->non_zero_count_cache[0+8*4 + 8*i]= h->pps.cabac && !IS_INTRA(mb_type) ? 0 : 64;
  290. }
  291. }
  292. if( h->pps.cabac ) {
  293. // top_cbp
  294. if(top_type) {
  295. h->top_cbp = h->cbp_table[top_xy];
  296. } else if(IS_INTRA(mb_type)) {
  297. h->top_cbp = 0x1C0;
  298. } else {
  299. h->top_cbp = 0;
  300. }
  301. // left_cbp
  302. if (left_type[0]) {
  303. h->left_cbp = h->cbp_table[left_xy[0]] & 0x1f0;
  304. } else if(IS_INTRA(mb_type)) {
  305. h->left_cbp = 0x1C0;
  306. } else {
  307. h->left_cbp = 0;
  308. }
  309. if (left_type[0]) {
  310. h->left_cbp |= ((h->cbp_table[left_xy[0]]>>((left_block[0]&(~1))+1))&0x1) << 1;
  311. }
  312. if (left_type[1]) {
  313. h->left_cbp |= ((h->cbp_table[left_xy[1]]>>((left_block[2]&(~1))+1))&0x1) << 3;
  314. }
  315. }
  316. #if 1
  317. if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
  318. int list;
  319. for(list=0; list<h->list_count; list++){
  320. if(!USES_LIST(mb_type, list) && !IS_DIRECT(mb_type) && !h->deblocking_filter){
  321. /*if(!h->mv_cache_clean[list]){
  322. memset(h->mv_cache [list], 0, 8*5*2*sizeof(int16_t)); //FIXME clean only input? clean at all?
  323. memset(h->ref_cache[list], PART_NOT_AVAILABLE, 8*5*sizeof(int8_t));
  324. h->mv_cache_clean[list]= 1;
  325. }*/
  326. continue;
  327. }
  328. h->mv_cache_clean[list]= 0;
  329. if(USES_LIST(top_type, list)){
  330. const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
  331. const int b8_xy= h->mb2b8_xy[top_xy] + h->b8_stride;
  332. *(uint32_t*)h->mv_cache[list][scan8[0] + 0 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 0];
  333. *(uint32_t*)h->mv_cache[list][scan8[0] + 1 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 1];
  334. *(uint32_t*)h->mv_cache[list][scan8[0] + 2 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 2];
  335. *(uint32_t*)h->mv_cache[list][scan8[0] + 3 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 3];
  336. h->ref_cache[list][scan8[0] + 0 - 1*8]=
  337. h->ref_cache[list][scan8[0] + 1 - 1*8]= s->current_picture.ref_index[list][b8_xy + 0];
  338. h->ref_cache[list][scan8[0] + 2 - 1*8]=
  339. h->ref_cache[list][scan8[0] + 3 - 1*8]= s->current_picture.ref_index[list][b8_xy + 1];
  340. }else{
  341. *(uint32_t*)h->mv_cache [list][scan8[0] + 0 - 1*8]=
  342. *(uint32_t*)h->mv_cache [list][scan8[0] + 1 - 1*8]=
  343. *(uint32_t*)h->mv_cache [list][scan8[0] + 2 - 1*8]=
  344. *(uint32_t*)h->mv_cache [list][scan8[0] + 3 - 1*8]= 0;
  345. *(uint32_t*)&h->ref_cache[list][scan8[0] + 0 - 1*8]= ((top_type ? LIST_NOT_USED : PART_NOT_AVAILABLE)&0xFF)*0x01010101;
  346. }
  347. for(i=0; i<2; i++){
  348. int cache_idx = scan8[0] - 1 + i*2*8;
  349. if(USES_LIST(left_type[i], list)){
  350. const int b_xy= h->mb2b_xy[left_xy[i]] + 3;
  351. const int b8_xy= h->mb2b8_xy[left_xy[i]] + 1;
  352. *(uint32_t*)h->mv_cache[list][cache_idx ]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[0+i*2]];
  353. *(uint32_t*)h->mv_cache[list][cache_idx+8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[1+i*2]];
  354. h->ref_cache[list][cache_idx ]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[0+i*2]>>1)];
  355. h->ref_cache[list][cache_idx+8]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[1+i*2]>>1)];
  356. }else{
  357. *(uint32_t*)h->mv_cache [list][cache_idx ]=
  358. *(uint32_t*)h->mv_cache [list][cache_idx+8]= 0;
  359. h->ref_cache[list][cache_idx ]=
  360. h->ref_cache[list][cache_idx+8]= left_type[i] ? LIST_NOT_USED : PART_NOT_AVAILABLE;
  361. }
  362. }
  363. if((for_deblock || (IS_DIRECT(mb_type) && !h->direct_spatial_mv_pred)) && !FRAME_MBAFF)
  364. continue;
  365. if(USES_LIST(topleft_type, list)){
  366. const int b_xy = h->mb2b_xy[topleft_xy] + 3 + 3*h->b_stride;
  367. const int b8_xy= h->mb2b8_xy[topleft_xy] + 1 + h->b8_stride;
  368. *(uint32_t*)h->mv_cache[list][scan8[0] - 1 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy];
  369. h->ref_cache[list][scan8[0] - 1 - 1*8]= s->current_picture.ref_index[list][b8_xy];
  370. }else{
  371. *(uint32_t*)h->mv_cache[list][scan8[0] - 1 - 1*8]= 0;
  372. h->ref_cache[list][scan8[0] - 1 - 1*8]= topleft_type ? LIST_NOT_USED : PART_NOT_AVAILABLE;
  373. }
  374. if(USES_LIST(topright_type, list)){
  375. const int b_xy= h->mb2b_xy[topright_xy] + 3*h->b_stride;
  376. const int b8_xy= h->mb2b8_xy[topright_xy] + h->b8_stride;
  377. *(uint32_t*)h->mv_cache[list][scan8[0] + 4 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy];
  378. h->ref_cache[list][scan8[0] + 4 - 1*8]= s->current_picture.ref_index[list][b8_xy];
  379. }else{
  380. *(uint32_t*)h->mv_cache [list][scan8[0] + 4 - 1*8]= 0;
  381. h->ref_cache[list][scan8[0] + 4 - 1*8]= topright_type ? LIST_NOT_USED : PART_NOT_AVAILABLE;
  382. }
  383. if((IS_SKIP(mb_type) || IS_DIRECT(mb_type)) && !FRAME_MBAFF)
  384. continue;
  385. h->ref_cache[list][scan8[5 ]+1] =
  386. h->ref_cache[list][scan8[7 ]+1] =
  387. h->ref_cache[list][scan8[13]+1] = //FIXME remove past 3 (init somewhere else)
  388. h->ref_cache[list][scan8[4 ]] =
  389. h->ref_cache[list][scan8[12]] = PART_NOT_AVAILABLE;
  390. *(uint32_t*)h->mv_cache [list][scan8[5 ]+1]=
  391. *(uint32_t*)h->mv_cache [list][scan8[7 ]+1]=
  392. *(uint32_t*)h->mv_cache [list][scan8[13]+1]= //FIXME remove past 3 (init somewhere else)
  393. *(uint32_t*)h->mv_cache [list][scan8[4 ]]=
  394. *(uint32_t*)h->mv_cache [list][scan8[12]]= 0;
  395. if( h->pps.cabac ) {
  396. /* XXX beurk, Load mvd */
  397. if(USES_LIST(top_type, list)){
  398. const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
  399. *(uint32_t*)h->mvd_cache[list][scan8[0] + 0 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 0];
  400. *(uint32_t*)h->mvd_cache[list][scan8[0] + 1 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 1];
  401. *(uint32_t*)h->mvd_cache[list][scan8[0] + 2 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 2];
  402. *(uint32_t*)h->mvd_cache[list][scan8[0] + 3 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 3];
  403. }else{
  404. *(uint32_t*)h->mvd_cache [list][scan8[0] + 0 - 1*8]=
  405. *(uint32_t*)h->mvd_cache [list][scan8[0] + 1 - 1*8]=
  406. *(uint32_t*)h->mvd_cache [list][scan8[0] + 2 - 1*8]=
  407. *(uint32_t*)h->mvd_cache [list][scan8[0] + 3 - 1*8]= 0;
  408. }
  409. if(USES_LIST(left_type[0], list)){
  410. const int b_xy= h->mb2b_xy[left_xy[0]] + 3;
  411. *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 0*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[0]];
  412. *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[1]];
  413. }else{
  414. *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 0*8]=
  415. *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 1*8]= 0;
  416. }
  417. if(USES_LIST(left_type[1], list)){
  418. const int b_xy= h->mb2b_xy[left_xy[1]] + 3;
  419. *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 2*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[2]];
  420. *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 3*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[3]];
  421. }else{
  422. *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 2*8]=
  423. *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 3*8]= 0;
  424. }
  425. *(uint32_t*)h->mvd_cache [list][scan8[5 ]+1]=
  426. *(uint32_t*)h->mvd_cache [list][scan8[7 ]+1]=
  427. *(uint32_t*)h->mvd_cache [list][scan8[13]+1]= //FIXME remove past 3 (init somewhere else)
  428. *(uint32_t*)h->mvd_cache [list][scan8[4 ]]=
  429. *(uint32_t*)h->mvd_cache [list][scan8[12]]= 0;
  430. if(h->slice_type == B_TYPE){
  431. fill_rectangle(&h->direct_cache[scan8[0]], 4, 4, 8, 0, 1);
  432. if(IS_DIRECT(top_type)){
  433. *(uint32_t*)&h->direct_cache[scan8[0] - 1*8]= 0x01010101;
  434. }else if(IS_8X8(top_type)){
  435. int b8_xy = h->mb2b8_xy[top_xy] + h->b8_stride;
  436. h->direct_cache[scan8[0] + 0 - 1*8]= h->direct_table[b8_xy];
  437. h->direct_cache[scan8[0] + 2 - 1*8]= h->direct_table[b8_xy + 1];
  438. }else{
  439. *(uint32_t*)&h->direct_cache[scan8[0] - 1*8]= 0;
  440. }
  441. if(IS_DIRECT(left_type[0]))
  442. h->direct_cache[scan8[0] - 1 + 0*8]= 1;
  443. else if(IS_8X8(left_type[0]))
  444. h->direct_cache[scan8[0] - 1 + 0*8]= h->direct_table[h->mb2b8_xy[left_xy[0]] + 1 + h->b8_stride*(left_block[0]>>1)];
  445. else
  446. h->direct_cache[scan8[0] - 1 + 0*8]= 0;
  447. if(IS_DIRECT(left_type[1]))
  448. h->direct_cache[scan8[0] - 1 + 2*8]= 1;
  449. else if(IS_8X8(left_type[1]))
  450. h->direct_cache[scan8[0] - 1 + 2*8]= h->direct_table[h->mb2b8_xy[left_xy[1]] + 1 + h->b8_stride*(left_block[2]>>1)];
  451. else
  452. h->direct_cache[scan8[0] - 1 + 2*8]= 0;
  453. }
  454. }
  455. if(FRAME_MBAFF){
  456. #define MAP_MVS\
  457. MAP_F2F(scan8[0] - 1 - 1*8, topleft_type)\
  458. MAP_F2F(scan8[0] + 0 - 1*8, top_type)\
  459. MAP_F2F(scan8[0] + 1 - 1*8, top_type)\
  460. MAP_F2F(scan8[0] + 2 - 1*8, top_type)\
  461. MAP_F2F(scan8[0] + 3 - 1*8, top_type)\
  462. MAP_F2F(scan8[0] + 4 - 1*8, topright_type)\
  463. MAP_F2F(scan8[0] - 1 + 0*8, left_type[0])\
  464. MAP_F2F(scan8[0] - 1 + 1*8, left_type[0])\
  465. MAP_F2F(scan8[0] - 1 + 2*8, left_type[1])\
  466. MAP_F2F(scan8[0] - 1 + 3*8, left_type[1])
  467. if(MB_FIELD){
  468. #define MAP_F2F(idx, mb_type)\
  469. if(!IS_INTERLACED(mb_type) && h->ref_cache[list][idx] >= 0){\
  470. h->ref_cache[list][idx] <<= 1;\
  471. h->mv_cache[list][idx][1] /= 2;\
  472. h->mvd_cache[list][idx][1] /= 2;\
  473. }
  474. MAP_MVS
  475. #undef MAP_F2F
  476. }else{
  477. #define MAP_F2F(idx, mb_type)\
  478. if(IS_INTERLACED(mb_type) && h->ref_cache[list][idx] >= 0){\
  479. h->ref_cache[list][idx] >>= 1;\
  480. h->mv_cache[list][idx][1] <<= 1;\
  481. h->mvd_cache[list][idx][1] <<= 1;\
  482. }
  483. MAP_MVS
  484. #undef MAP_F2F
  485. }
  486. }
  487. }
  488. }
  489. #endif
  490. h->neighbor_transform_size= !!IS_8x8DCT(top_type) + !!IS_8x8DCT(left_type[0]);
  491. }
  492. static inline void write_back_intra_pred_mode(H264Context *h){
  493. MpegEncContext * const s = &h->s;
  494. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  495. h->intra4x4_pred_mode[mb_xy][0]= h->intra4x4_pred_mode_cache[7+8*1];
  496. h->intra4x4_pred_mode[mb_xy][1]= h->intra4x4_pred_mode_cache[7+8*2];
  497. h->intra4x4_pred_mode[mb_xy][2]= h->intra4x4_pred_mode_cache[7+8*3];
  498. h->intra4x4_pred_mode[mb_xy][3]= h->intra4x4_pred_mode_cache[7+8*4];
  499. h->intra4x4_pred_mode[mb_xy][4]= h->intra4x4_pred_mode_cache[4+8*4];
  500. h->intra4x4_pred_mode[mb_xy][5]= h->intra4x4_pred_mode_cache[5+8*4];
  501. h->intra4x4_pred_mode[mb_xy][6]= h->intra4x4_pred_mode_cache[6+8*4];
  502. }
  503. /**
  504. * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
  505. */
  506. static inline int check_intra4x4_pred_mode(H264Context *h){
  507. MpegEncContext * const s = &h->s;
  508. static const int8_t top [12]= {-1, 0,LEFT_DC_PRED,-1,-1,-1,-1,-1, 0};
  509. static const int8_t left[12]= { 0,-1, TOP_DC_PRED, 0,-1,-1,-1, 0,-1,DC_128_PRED};
  510. int i;
  511. if(!(h->top_samples_available&0x8000)){
  512. for(i=0; i<4; i++){
  513. int status= top[ h->intra4x4_pred_mode_cache[scan8[0] + i] ];
  514. if(status<0){
  515. av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
  516. return -1;
  517. } else if(status){
  518. h->intra4x4_pred_mode_cache[scan8[0] + i]= status;
  519. }
  520. }
  521. }
  522. if(!(h->left_samples_available&0x8000)){
  523. for(i=0; i<4; i++){
  524. int status= left[ h->intra4x4_pred_mode_cache[scan8[0] + 8*i] ];
  525. if(status<0){
  526. av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
  527. return -1;
  528. } else if(status){
  529. h->intra4x4_pred_mode_cache[scan8[0] + 8*i]= status;
  530. }
  531. }
  532. }
  533. return 0;
  534. } //FIXME cleanup like next
  535. /**
  536. * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
  537. */
  538. static inline int check_intra_pred_mode(H264Context *h, int mode){
  539. MpegEncContext * const s = &h->s;
  540. static const int8_t top [7]= {LEFT_DC_PRED8x8, 1,-1,-1};
  541. static const int8_t left[7]= { TOP_DC_PRED8x8,-1, 2,-1,DC_128_PRED8x8};
  542. if(mode > 6U) {
  543. av_log(h->s.avctx, AV_LOG_ERROR, "out of range intra chroma pred mode at %d %d\n", s->mb_x, s->mb_y);
  544. return -1;
  545. }
  546. if(!(h->top_samples_available&0x8000)){
  547. mode= top[ mode ];
  548. if(mode<0){
  549. av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);
  550. return -1;
  551. }
  552. }
  553. if(!(h->left_samples_available&0x8000)){
  554. mode= left[ mode ];
  555. if(mode<0){
  556. av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);
  557. return -1;
  558. }
  559. }
  560. return mode;
  561. }
  562. /**
  563. * gets the predicted intra4x4 prediction mode.
  564. */
  565. static inline int pred_intra_mode(H264Context *h, int n){
  566. const int index8= scan8[n];
  567. const int left= h->intra4x4_pred_mode_cache[index8 - 1];
  568. const int top = h->intra4x4_pred_mode_cache[index8 - 8];
  569. const int min= FFMIN(left, top);
  570. tprintf(h->s.avctx, "mode:%d %d min:%d\n", left ,top, min);
  571. if(min<0) return DC_PRED;
  572. else return min;
  573. }
  574. static inline void write_back_non_zero_count(H264Context *h){
  575. MpegEncContext * const s = &h->s;
  576. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  577. h->non_zero_count[mb_xy][0]= h->non_zero_count_cache[7+8*1];
  578. h->non_zero_count[mb_xy][1]= h->non_zero_count_cache[7+8*2];
  579. h->non_zero_count[mb_xy][2]= h->non_zero_count_cache[7+8*3];
  580. h->non_zero_count[mb_xy][3]= h->non_zero_count_cache[7+8*4];
  581. h->non_zero_count[mb_xy][4]= h->non_zero_count_cache[4+8*4];
  582. h->non_zero_count[mb_xy][5]= h->non_zero_count_cache[5+8*4];
  583. h->non_zero_count[mb_xy][6]= h->non_zero_count_cache[6+8*4];
  584. h->non_zero_count[mb_xy][9]= h->non_zero_count_cache[1+8*2];
  585. h->non_zero_count[mb_xy][8]= h->non_zero_count_cache[2+8*2];
  586. h->non_zero_count[mb_xy][7]= h->non_zero_count_cache[2+8*1];
  587. h->non_zero_count[mb_xy][12]=h->non_zero_count_cache[1+8*5];
  588. h->non_zero_count[mb_xy][11]=h->non_zero_count_cache[2+8*5];
  589. h->non_zero_count[mb_xy][10]=h->non_zero_count_cache[2+8*4];
  590. if(FRAME_MBAFF){
  591. // store all luma nnzs, for deblocking
  592. int v = 0, i;
  593. for(i=0; i<16; i++)
  594. v += (!!h->non_zero_count_cache[scan8[i]]) << i;
  595. *(uint16_t*)&h->non_zero_count[mb_xy][14] = v;
  596. }
  597. }
  598. /**
  599. * gets the predicted number of non zero coefficients.
  600. * @param n block index
  601. */
  602. static inline int pred_non_zero_count(H264Context *h, int n){
  603. const int index8= scan8[n];
  604. const int left= h->non_zero_count_cache[index8 - 1];
  605. const int top = h->non_zero_count_cache[index8 - 8];
  606. int i= left + top;
  607. if(i<64) i= (i+1)>>1;
  608. tprintf(h->s.avctx, "pred_nnz L%X T%X n%d s%d P%X\n", left, top, n, scan8[n], i&31);
  609. return i&31;
  610. }
  611. static inline int fetch_diagonal_mv(H264Context *h, const int16_t **C, int i, int list, int part_width){
  612. const int topright_ref= h->ref_cache[list][ i - 8 + part_width ];
  613. MpegEncContext *s = &h->s;
  614. /* there is no consistent mapping of mvs to neighboring locations that will
  615. * make mbaff happy, so we can't move all this logic to fill_caches */
  616. if(FRAME_MBAFF){
  617. const uint32_t *mb_types = s->current_picture_ptr->mb_type;
  618. const int16_t *mv;
  619. *(uint32_t*)h->mv_cache[list][scan8[0]-2] = 0;
  620. *C = h->mv_cache[list][scan8[0]-2];
  621. if(!MB_FIELD
  622. && (s->mb_y&1) && i < scan8[0]+8 && topright_ref != PART_NOT_AVAILABLE){
  623. int topright_xy = s->mb_x + (s->mb_y-1)*s->mb_stride + (i == scan8[0]+3);
  624. if(IS_INTERLACED(mb_types[topright_xy])){
  625. #define SET_DIAG_MV(MV_OP, REF_OP, X4, Y4)\
  626. const int x4 = X4, y4 = Y4;\
  627. const int mb_type = mb_types[(x4>>2)+(y4>>2)*s->mb_stride];\
  628. if(!USES_LIST(mb_type,list) && !IS_8X8(mb_type))\
  629. return LIST_NOT_USED;\
  630. mv = s->current_picture_ptr->motion_val[list][x4 + y4*h->b_stride];\
  631. h->mv_cache[list][scan8[0]-2][0] = mv[0];\
  632. h->mv_cache[list][scan8[0]-2][1] = mv[1] MV_OP;\
  633. return s->current_picture_ptr->ref_index[list][(x4>>1) + (y4>>1)*h->b8_stride] REF_OP;
  634. SET_DIAG_MV(*2, >>1, s->mb_x*4+(i&7)-4+part_width, s->mb_y*4-1);
  635. }
  636. }
  637. if(topright_ref == PART_NOT_AVAILABLE
  638. && ((s->mb_y&1) || i >= scan8[0]+8) && (i&7)==4
  639. && h->ref_cache[list][scan8[0]-1] != PART_NOT_AVAILABLE){
  640. if(!MB_FIELD
  641. && IS_INTERLACED(mb_types[h->left_mb_xy[0]])){
  642. SET_DIAG_MV(*2, >>1, s->mb_x*4-1, (s->mb_y|1)*4+(s->mb_y&1)*2+(i>>4)-1);
  643. }
  644. if(MB_FIELD
  645. && !IS_INTERLACED(mb_types[h->left_mb_xy[0]])
  646. && i >= scan8[0]+8){
  647. // leftshift will turn LIST_NOT_USED into PART_NOT_AVAILABLE, but that's ok.
  648. SET_DIAG_MV(>>1, <<1, s->mb_x*4-1, (s->mb_y&~1)*4 - 1 + ((i-scan8[0])>>3)*2);
  649. }
  650. }
  651. #undef SET_DIAG_MV
  652. }
  653. if(topright_ref != PART_NOT_AVAILABLE){
  654. *C= h->mv_cache[list][ i - 8 + part_width ];
  655. return topright_ref;
  656. }else{
  657. tprintf(s->avctx, "topright MV not available\n");
  658. *C= h->mv_cache[list][ i - 8 - 1 ];
  659. return h->ref_cache[list][ i - 8 - 1 ];
  660. }
  661. }
  662. /**
  663. * gets the predicted MV.
  664. * @param n the block index
  665. * @param part_width the width of the partition (4, 8,16) -> (1, 2, 4)
  666. * @param mx the x component of the predicted motion vector
  667. * @param my the y component of the predicted motion vector
  668. */
  669. static inline void pred_motion(H264Context * const h, int n, int part_width, int list, int ref, int * const mx, int * const my){
  670. const int index8= scan8[n];
  671. const int top_ref= h->ref_cache[list][ index8 - 8 ];
  672. const int left_ref= h->ref_cache[list][ index8 - 1 ];
  673. const int16_t * const A= h->mv_cache[list][ index8 - 1 ];
  674. const int16_t * const B= h->mv_cache[list][ index8 - 8 ];
  675. const int16_t * C;
  676. int diagonal_ref, match_count;
  677. assert(part_width==1 || part_width==2 || part_width==4);
  678. /* mv_cache
  679. B . . A T T T T
  680. U . . L . . , .
  681. U . . L . . . .
  682. U . . L . . , .
  683. . . . L . . . .
  684. */
  685. diagonal_ref= fetch_diagonal_mv(h, &C, index8, list, part_width);
  686. match_count= (diagonal_ref==ref) + (top_ref==ref) + (left_ref==ref);
  687. tprintf(h->s.avctx, "pred_motion match_count=%d\n", match_count);
  688. if(match_count > 1){ //most common
  689. *mx= mid_pred(A[0], B[0], C[0]);
  690. *my= mid_pred(A[1], B[1], C[1]);
  691. }else if(match_count==1){
  692. if(left_ref==ref){
  693. *mx= A[0];
  694. *my= A[1];
  695. }else if(top_ref==ref){
  696. *mx= B[0];
  697. *my= B[1];
  698. }else{
  699. *mx= C[0];
  700. *my= C[1];
  701. }
  702. }else{
  703. if(top_ref == PART_NOT_AVAILABLE && diagonal_ref == PART_NOT_AVAILABLE && left_ref != PART_NOT_AVAILABLE){
  704. *mx= A[0];
  705. *my= A[1];
  706. }else{
  707. *mx= mid_pred(A[0], B[0], C[0]);
  708. *my= mid_pred(A[1], B[1], C[1]);
  709. }
  710. }
  711. tprintf(h->s.avctx, "pred_motion (%2d %2d %2d) (%2d %2d %2d) (%2d %2d %2d) -> (%2d %2d %2d) at %2d %2d %d list %d\n", top_ref, B[0], B[1], diagonal_ref, C[0], C[1], left_ref, A[0], A[1], ref, *mx, *my, h->s.mb_x, h->s.mb_y, n, list);
  712. }
  713. /**
  714. * gets the directionally predicted 16x8 MV.
  715. * @param n the block index
  716. * @param mx the x component of the predicted motion vector
  717. * @param my the y component of the predicted motion vector
  718. */
  719. static inline void pred_16x8_motion(H264Context * const h, int n, int list, int ref, int * const mx, int * const my){
  720. if(n==0){
  721. const int top_ref= h->ref_cache[list][ scan8[0] - 8 ];
  722. const int16_t * const B= h->mv_cache[list][ scan8[0] - 8 ];
  723. tprintf(h->s.avctx, "pred_16x8: (%2d %2d %2d) at %2d %2d %d list %d\n", top_ref, B[0], B[1], h->s.mb_x, h->s.mb_y, n, list);
  724. if(top_ref == ref){
  725. *mx= B[0];
  726. *my= B[1];
  727. return;
  728. }
  729. }else{
  730. const int left_ref= h->ref_cache[list][ scan8[8] - 1 ];
  731. const int16_t * const A= h->mv_cache[list][ scan8[8] - 1 ];
  732. tprintf(h->s.avctx, "pred_16x8: (%2d %2d %2d) at %2d %2d %d list %d\n", left_ref, A[0], A[1], h->s.mb_x, h->s.mb_y, n, list);
  733. if(left_ref == ref){
  734. *mx= A[0];
  735. *my= A[1];
  736. return;
  737. }
  738. }
  739. //RARE
  740. pred_motion(h, n, 4, list, ref, mx, my);
  741. }
  742. /**
  743. * gets the directionally predicted 8x16 MV.
  744. * @param n the block index
  745. * @param mx the x component of the predicted motion vector
  746. * @param my the y component of the predicted motion vector
  747. */
  748. static inline void pred_8x16_motion(H264Context * const h, int n, int list, int ref, int * const mx, int * const my){
  749. if(n==0){
  750. const int left_ref= h->ref_cache[list][ scan8[0] - 1 ];
  751. const int16_t * const A= h->mv_cache[list][ scan8[0] - 1 ];
  752. tprintf(h->s.avctx, "pred_8x16: (%2d %2d %2d) at %2d %2d %d list %d\n", left_ref, A[0], A[1], h->s.mb_x, h->s.mb_y, n, list);
  753. if(left_ref == ref){
  754. *mx= A[0];
  755. *my= A[1];
  756. return;
  757. }
  758. }else{
  759. const int16_t * C;
  760. int diagonal_ref;
  761. diagonal_ref= fetch_diagonal_mv(h, &C, scan8[4], list, 2);
  762. tprintf(h->s.avctx, "pred_8x16: (%2d %2d %2d) at %2d %2d %d list %d\n", diagonal_ref, C[0], C[1], h->s.mb_x, h->s.mb_y, n, list);
  763. if(diagonal_ref == ref){
  764. *mx= C[0];
  765. *my= C[1];
  766. return;
  767. }
  768. }
  769. //RARE
  770. pred_motion(h, n, 2, list, ref, mx, my);
  771. }
  772. static inline void pred_pskip_motion(H264Context * const h, int * const mx, int * const my){
  773. const int top_ref = h->ref_cache[0][ scan8[0] - 8 ];
  774. const int left_ref= h->ref_cache[0][ scan8[0] - 1 ];
  775. tprintf(h->s.avctx, "pred_pskip: (%d) (%d) at %2d %2d\n", top_ref, left_ref, h->s.mb_x, h->s.mb_y);
  776. if(top_ref == PART_NOT_AVAILABLE || left_ref == PART_NOT_AVAILABLE
  777. || (top_ref == 0 && *(uint32_t*)h->mv_cache[0][ scan8[0] - 8 ] == 0)
  778. || (left_ref == 0 && *(uint32_t*)h->mv_cache[0][ scan8[0] - 1 ] == 0)){
  779. *mx = *my = 0;
  780. return;
  781. }
  782. pred_motion(h, 0, 4, 0, 0, mx, my);
  783. return;
  784. }
  785. static inline void direct_dist_scale_factor(H264Context * const h){
  786. const int poc = h->s.current_picture_ptr->poc;
  787. const int poc1 = h->ref_list[1][0].poc;
  788. int i;
  789. for(i=0; i<h->ref_count[0]; i++){
  790. int poc0 = h->ref_list[0][i].poc;
  791. int td = av_clip(poc1 - poc0, -128, 127);
  792. if(td == 0 /* FIXME || pic0 is a long-term ref */){
  793. h->dist_scale_factor[i] = 256;
  794. }else{
  795. int tb = av_clip(poc - poc0, -128, 127);
  796. int tx = (16384 + (FFABS(td) >> 1)) / td;
  797. h->dist_scale_factor[i] = av_clip((tb*tx + 32) >> 6, -1024, 1023);
  798. }
  799. }
  800. if(FRAME_MBAFF){
  801. for(i=0; i<h->ref_count[0]; i++){
  802. h->dist_scale_factor_field[2*i] =
  803. h->dist_scale_factor_field[2*i+1] = h->dist_scale_factor[i];
  804. }
  805. }
  806. }
  807. static inline void direct_ref_list_init(H264Context * const h){
  808. MpegEncContext * const s = &h->s;
  809. Picture * const ref1 = &h->ref_list[1][0];
  810. Picture * const cur = s->current_picture_ptr;
  811. int list, i, j;
  812. if(cur->pict_type == I_TYPE)
  813. cur->ref_count[0] = 0;
  814. if(cur->pict_type != B_TYPE)
  815. cur->ref_count[1] = 0;
  816. for(list=0; list<2; list++){
  817. cur->ref_count[list] = h->ref_count[list];
  818. for(j=0; j<h->ref_count[list]; j++)
  819. cur->ref_poc[list][j] = h->ref_list[list][j].poc;
  820. }
  821. if(cur->pict_type != B_TYPE || h->direct_spatial_mv_pred)
  822. return;
  823. for(list=0; list<2; list++){
  824. for(i=0; i<ref1->ref_count[list]; i++){
  825. const int poc = ref1->ref_poc[list][i];
  826. h->map_col_to_list0[list][i] = 0; /* bogus; fills in for missing frames */
  827. for(j=0; j<h->ref_count[list]; j++)
  828. if(h->ref_list[list][j].poc == poc){
  829. h->map_col_to_list0[list][i] = j;
  830. break;
  831. }
  832. }
  833. }
  834. if(FRAME_MBAFF){
  835. for(list=0; list<2; list++){
  836. for(i=0; i<ref1->ref_count[list]; i++){
  837. j = h->map_col_to_list0[list][i];
  838. h->map_col_to_list0_field[list][2*i] = 2*j;
  839. h->map_col_to_list0_field[list][2*i+1] = 2*j+1;
  840. }
  841. }
  842. }
  843. }
  844. static inline void pred_direct_motion(H264Context * const h, int *mb_type){
  845. MpegEncContext * const s = &h->s;
  846. const int mb_xy = s->mb_x + s->mb_y*s->mb_stride;
  847. const int b8_xy = 2*s->mb_x + 2*s->mb_y*h->b8_stride;
  848. const int b4_xy = 4*s->mb_x + 4*s->mb_y*h->b_stride;
  849. const int mb_type_col = h->ref_list[1][0].mb_type[mb_xy];
  850. const int16_t (*l1mv0)[2] = (const int16_t (*)[2]) &h->ref_list[1][0].motion_val[0][b4_xy];
  851. const int16_t (*l1mv1)[2] = (const int16_t (*)[2]) &h->ref_list[1][0].motion_val[1][b4_xy];
  852. const int8_t *l1ref0 = &h->ref_list[1][0].ref_index[0][b8_xy];
  853. const int8_t *l1ref1 = &h->ref_list[1][0].ref_index[1][b8_xy];
  854. const int is_b8x8 = IS_8X8(*mb_type);
  855. unsigned int sub_mb_type;
  856. int i8, i4;
  857. #define MB_TYPE_16x16_OR_INTRA (MB_TYPE_16x16|MB_TYPE_INTRA4x4|MB_TYPE_INTRA16x16|MB_TYPE_INTRA_PCM)
  858. if(IS_8X8(mb_type_col) && !h->sps.direct_8x8_inference_flag){
  859. /* FIXME save sub mb types from previous frames (or derive from MVs)
  860. * so we know exactly what block size to use */
  861. sub_mb_type = MB_TYPE_8x8|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_4x4 */
  862. *mb_type = MB_TYPE_8x8|MB_TYPE_L0L1;
  863. }else if(!is_b8x8 && (mb_type_col & MB_TYPE_16x16_OR_INTRA)){
  864. sub_mb_type = MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_8x8 */
  865. *mb_type = MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_16x16 */
  866. }else{
  867. sub_mb_type = MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2; /* B_SUB_8x8 */
  868. *mb_type = MB_TYPE_8x8|MB_TYPE_L0L1;
  869. }
  870. if(!is_b8x8)
  871. *mb_type |= MB_TYPE_DIRECT2;
  872. if(MB_FIELD)
  873. *mb_type |= MB_TYPE_INTERLACED;
  874. tprintf(s->avctx, "mb_type = %08x, sub_mb_type = %08x, is_b8x8 = %d, mb_type_col = %08x\n", *mb_type, sub_mb_type, is_b8x8, mb_type_col);
  875. if(h->direct_spatial_mv_pred){
  876. int ref[2];
  877. int mv[2][2];
  878. int list;
  879. /* FIXME interlacing + spatial direct uses wrong colocated block positions */
  880. /* ref = min(neighbors) */
  881. for(list=0; list<2; list++){
  882. int refa = h->ref_cache[list][scan8[0] - 1];
  883. int refb = h->ref_cache[list][scan8[0] - 8];
  884. int refc = h->ref_cache[list][scan8[0] - 8 + 4];
  885. if(refc == -2)
  886. refc = h->ref_cache[list][scan8[0] - 8 - 1];
  887. ref[list] = refa;
  888. if(ref[list] < 0 || (refb < ref[list] && refb >= 0))
  889. ref[list] = refb;
  890. if(ref[list] < 0 || (refc < ref[list] && refc >= 0))
  891. ref[list] = refc;
  892. if(ref[list] < 0)
  893. ref[list] = -1;
  894. }
  895. if(ref[0] < 0 && ref[1] < 0){
  896. ref[0] = ref[1] = 0;
  897. mv[0][0] = mv[0][1] =
  898. mv[1][0] = mv[1][1] = 0;
  899. }else{
  900. for(list=0; list<2; list++){
  901. if(ref[list] >= 0)
  902. pred_motion(h, 0, 4, list, ref[list], &mv[list][0], &mv[list][1]);
  903. else
  904. mv[list][0] = mv[list][1] = 0;
  905. }
  906. }
  907. if(ref[1] < 0){
  908. *mb_type &= ~MB_TYPE_P0L1;
  909. sub_mb_type &= ~MB_TYPE_P0L1;
  910. }else if(ref[0] < 0){
  911. *mb_type &= ~MB_TYPE_P0L0;
  912. sub_mb_type &= ~MB_TYPE_P0L0;
  913. }
  914. if(IS_16X16(*mb_type)){
  915. int a=0, b=0;
  916. fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, (uint8_t)ref[0], 1);
  917. fill_rectangle(&h->ref_cache[1][scan8[0]], 4, 4, 8, (uint8_t)ref[1], 1);
  918. if(!IS_INTRA(mb_type_col)
  919. && ( (l1ref0[0] == 0 && FFABS(l1mv0[0][0]) <= 1 && FFABS(l1mv0[0][1]) <= 1)
  920. || (l1ref0[0] < 0 && l1ref1[0] == 0 && FFABS(l1mv1[0][0]) <= 1 && FFABS(l1mv1[0][1]) <= 1
  921. && (h->x264_build>33 || !h->x264_build)))){
  922. if(ref[0] > 0)
  923. a= pack16to32(mv[0][0],mv[0][1]);
  924. if(ref[1] > 0)
  925. b= pack16to32(mv[1][0],mv[1][1]);
  926. }else{
  927. a= pack16to32(mv[0][0],mv[0][1]);
  928. b= pack16to32(mv[1][0],mv[1][1]);
  929. }
  930. fill_rectangle(&h->mv_cache[0][scan8[0]], 4, 4, 8, a, 4);
  931. fill_rectangle(&h->mv_cache[1][scan8[0]], 4, 4, 8, b, 4);
  932. }else{
  933. for(i8=0; i8<4; i8++){
  934. const int x8 = i8&1;
  935. const int y8 = i8>>1;
  936. if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
  937. continue;
  938. h->sub_mb_type[i8] = sub_mb_type;
  939. fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, pack16to32(mv[0][0],mv[0][1]), 4);
  940. fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, pack16to32(mv[1][0],mv[1][1]), 4);
  941. fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[0], 1);
  942. fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, (uint8_t)ref[1], 1);
  943. /* col_zero_flag */
  944. if(!IS_INTRA(mb_type_col) && ( l1ref0[x8 + y8*h->b8_stride] == 0
  945. || (l1ref0[x8 + y8*h->b8_stride] < 0 && l1ref1[x8 + y8*h->b8_stride] == 0
  946. && (h->x264_build>33 || !h->x264_build)))){
  947. const int16_t (*l1mv)[2]= l1ref0[x8 + y8*h->b8_stride] == 0 ? l1mv0 : l1mv1;
  948. if(IS_SUB_8X8(sub_mb_type)){
  949. const int16_t *mv_col = l1mv[x8*3 + y8*3*h->b_stride];
  950. if(FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1){
  951. if(ref[0] == 0)
  952. fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, 0, 4);
  953. if(ref[1] == 0)
  954. fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, 0, 4);
  955. }
  956. }else
  957. for(i4=0; i4<4; i4++){
  958. const int16_t *mv_col = l1mv[x8*2 + (i4&1) + (y8*2 + (i4>>1))*h->b_stride];
  959. if(FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1){
  960. if(ref[0] == 0)
  961. *(uint32_t*)h->mv_cache[0][scan8[i8*4+i4]] = 0;
  962. if(ref[1] == 0)
  963. *(uint32_t*)h->mv_cache[1][scan8[i8*4+i4]] = 0;
  964. }
  965. }
  966. }
  967. }
  968. }
  969. }else{ /* direct temporal mv pred */
  970. const int *map_col_to_list0[2] = {h->map_col_to_list0[0], h->map_col_to_list0[1]};
  971. const int *dist_scale_factor = h->dist_scale_factor;
  972. if(FRAME_MBAFF){
  973. if(IS_INTERLACED(*mb_type)){
  974. map_col_to_list0[0] = h->map_col_to_list0_field[0];
  975. map_col_to_list0[1] = h->map_col_to_list0_field[1];
  976. dist_scale_factor = h->dist_scale_factor_field;
  977. }
  978. if(IS_INTERLACED(*mb_type) != IS_INTERLACED(mb_type_col)){
  979. /* FIXME assumes direct_8x8_inference == 1 */
  980. const int pair_xy = s->mb_x + (s->mb_y&~1)*s->mb_stride;
  981. int mb_types_col[2];
  982. int y_shift;
  983. *mb_type = MB_TYPE_8x8|MB_TYPE_L0L1
  984. | (is_b8x8 ? 0 : MB_TYPE_DIRECT2)
  985. | (*mb_type & MB_TYPE_INTERLACED);
  986. sub_mb_type = MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2|MB_TYPE_16x16;
  987. if(IS_INTERLACED(*mb_type)){
  988. /* frame to field scaling */
  989. mb_types_col[0] = h->ref_list[1][0].mb_type[pair_xy];
  990. mb_types_col[1] = h->ref_list[1][0].mb_type[pair_xy+s->mb_stride];
  991. if(s->mb_y&1){
  992. l1ref0 -= 2*h->b8_stride;
  993. l1ref1 -= 2*h->b8_stride;
  994. l1mv0 -= 4*h->b_stride;
  995. l1mv1 -= 4*h->b_stride;
  996. }
  997. y_shift = 0;
  998. if( (mb_types_col[0] & MB_TYPE_16x16_OR_INTRA)
  999. && (mb_types_col[1] & MB_TYPE_16x16_OR_INTRA)
  1000. && !is_b8x8)
  1001. *mb_type |= MB_TYPE_16x8;
  1002. else
  1003. *mb_type |= MB_TYPE_8x8;
  1004. }else{
  1005. /* field to frame scaling */
  1006. /* col_mb_y = (mb_y&~1) + (topAbsDiffPOC < bottomAbsDiffPOC ? 0 : 1)
  1007. * but in MBAFF, top and bottom POC are equal */
  1008. int dy = (s->mb_y&1) ? 1 : 2;
  1009. mb_types_col[0] =
  1010. mb_types_col[1] = h->ref_list[1][0].mb_type[pair_xy+s->mb_stride];
  1011. l1ref0 += dy*h->b8_stride;
  1012. l1ref1 += dy*h->b8_stride;
  1013. l1mv0 += 2*dy*h->b_stride;
  1014. l1mv1 += 2*dy*h->b_stride;
  1015. y_shift = 2;
  1016. if((mb_types_col[0] & (MB_TYPE_16x16_OR_INTRA|MB_TYPE_16x8))
  1017. && !is_b8x8)
  1018. *mb_type |= MB_TYPE_16x16;
  1019. else
  1020. *mb_type |= MB_TYPE_8x8;
  1021. }
  1022. for(i8=0; i8<4; i8++){
  1023. const int x8 = i8&1;
  1024. const int y8 = i8>>1;
  1025. int ref0, scale;
  1026. const int16_t (*l1mv)[2]= l1mv0;
  1027. if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
  1028. continue;
  1029. h->sub_mb_type[i8] = sub_mb_type;
  1030. fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, 0, 1);
  1031. if(IS_INTRA(mb_types_col[y8])){
  1032. fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, 0, 1);
  1033. fill_rectangle(&h-> mv_cache[0][scan8[i8*4]], 2, 2, 8, 0, 4);
  1034. fill_rectangle(&h-> mv_cache[1][scan8[i8*4]], 2, 2, 8, 0, 4);
  1035. continue;
  1036. }
  1037. ref0 = l1ref0[x8 + (y8*2>>y_shift)*h->b8_stride];
  1038. if(ref0 >= 0)
  1039. ref0 = map_col_to_list0[0][ref0*2>>y_shift];
  1040. else{
  1041. ref0 = map_col_to_list0[1][l1ref1[x8 + (y8*2>>y_shift)*h->b8_stride]*2>>y_shift];
  1042. l1mv= l1mv1;
  1043. }
  1044. scale = dist_scale_factor[ref0];
  1045. fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, ref0, 1);
  1046. {
  1047. const int16_t *mv_col = l1mv[x8*3 + (y8*6>>y_shift)*h->b_stride];
  1048. int my_col = (mv_col[1]<<y_shift)/2;
  1049. int mx = (scale * mv_col[0] + 128) >> 8;
  1050. int my = (scale * my_col + 128) >> 8;
  1051. fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, pack16to32(mx,my), 4);
  1052. fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, pack16to32(mx-mv_col[0],my-my_col), 4);
  1053. }
  1054. }
  1055. return;
  1056. }
  1057. }
  1058. /* one-to-one mv scaling */
  1059. if(IS_16X16(*mb_type)){
  1060. int ref, mv0, mv1;
  1061. fill_rectangle(&h->ref_cache[1][scan8[0]], 4, 4, 8, 0, 1);
  1062. if(IS_INTRA(mb_type_col)){
  1063. ref=mv0=mv1=0;
  1064. }else{
  1065. const int ref0 = l1ref0[0] >= 0 ? map_col_to_list0[0][l1ref0[0]]
  1066. : map_col_to_list0[1][l1ref1[0]];
  1067. const int scale = dist_scale_factor[ref0];
  1068. const int16_t *mv_col = l1ref0[0] >= 0 ? l1mv0[0] : l1mv1[0];
  1069. int mv_l0[2];
  1070. mv_l0[0] = (scale * mv_col[0] + 128) >> 8;
  1071. mv_l0[1] = (scale * mv_col[1] + 128) >> 8;
  1072. ref= ref0;
  1073. mv0= pack16to32(mv_l0[0],mv_l0[1]);
  1074. mv1= pack16to32(mv_l0[0]-mv_col[0],mv_l0[1]-mv_col[1]);
  1075. }
  1076. fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
  1077. fill_rectangle(&h-> mv_cache[0][scan8[0]], 4, 4, 8, mv0, 4);
  1078. fill_rectangle(&h-> mv_cache[1][scan8[0]], 4, 4, 8, mv1, 4);
  1079. }else{
  1080. for(i8=0; i8<4; i8++){
  1081. const int x8 = i8&1;
  1082. const int y8 = i8>>1;
  1083. int ref0, scale;
  1084. const int16_t (*l1mv)[2]= l1mv0;
  1085. if(is_b8x8 && !IS_DIRECT(h->sub_mb_type[i8]))
  1086. continue;
  1087. h->sub_mb_type[i8] = sub_mb_type;
  1088. fill_rectangle(&h->ref_cache[1][scan8[i8*4]], 2, 2, 8, 0, 1);
  1089. if(IS_INTRA(mb_type_col)){
  1090. fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, 0, 1);
  1091. fill_rectangle(&h-> mv_cache[0][scan8[i8*4]], 2, 2, 8, 0, 4);
  1092. fill_rectangle(&h-> mv_cache[1][scan8[i8*4]], 2, 2, 8, 0, 4);
  1093. continue;
  1094. }
  1095. ref0 = l1ref0[x8 + y8*h->b8_stride];
  1096. if(ref0 >= 0)
  1097. ref0 = map_col_to_list0[0][ref0];
  1098. else{
  1099. ref0 = map_col_to_list0[1][l1ref1[x8 + y8*h->b8_stride]];
  1100. l1mv= l1mv1;
  1101. }
  1102. scale = dist_scale_factor[ref0];
  1103. fill_rectangle(&h->ref_cache[0][scan8[i8*4]], 2, 2, 8, ref0, 1);
  1104. if(IS_SUB_8X8(sub_mb_type)){
  1105. const int16_t *mv_col = l1mv[x8*3 + y8*3*h->b_stride];
  1106. int mx = (scale * mv_col[0] + 128) >> 8;
  1107. int my = (scale * mv_col[1] + 128) >> 8;
  1108. fill_rectangle(&h->mv_cache[0][scan8[i8*4]], 2, 2, 8, pack16to32(mx,my), 4);
  1109. fill_rectangle(&h->mv_cache[1][scan8[i8*4]], 2, 2, 8, pack16to32(mx-mv_col[0],my-mv_col[1]), 4);
  1110. }else
  1111. for(i4=0; i4<4; i4++){
  1112. const int16_t *mv_col = l1mv[x8*2 + (i4&1) + (y8*2 + (i4>>1))*h->b_stride];
  1113. int16_t *mv_l0 = h->mv_cache[0][scan8[i8*4+i4]];
  1114. mv_l0[0] = (scale * mv_col[0] + 128) >> 8;
  1115. mv_l0[1] = (scale * mv_col[1] + 128) >> 8;
  1116. *(uint32_t*)h->mv_cache[1][scan8[i8*4+i4]] =
  1117. pack16to32(mv_l0[0]-mv_col[0],mv_l0[1]-mv_col[1]);
  1118. }
  1119. }
  1120. }
  1121. }
  1122. }
  1123. static inline void write_back_motion(H264Context *h, int mb_type){
  1124. MpegEncContext * const s = &h->s;
  1125. const int b_xy = 4*s->mb_x + 4*s->mb_y*h->b_stride;
  1126. const int b8_xy= 2*s->mb_x + 2*s->mb_y*h->b8_stride;
  1127. int list;
  1128. if(!USES_LIST(mb_type, 0))
  1129. fill_rectangle(&s->current_picture.ref_index[0][b8_xy], 2, 2, h->b8_stride, (uint8_t)LIST_NOT_USED, 1);
  1130. for(list=0; list<h->list_count; list++){
  1131. int y;
  1132. if(!USES_LIST(mb_type, list))
  1133. continue;
  1134. for(y=0; y<4; y++){
  1135. *(uint64_t*)s->current_picture.motion_val[list][b_xy + 0 + y*h->b_stride]= *(uint64_t*)h->mv_cache[list][scan8[0]+0 + 8*y];
  1136. *(uint64_t*)s->current_picture.motion_val[list][b_xy + 2 + y*h->b_stride]= *(uint64_t*)h->mv_cache[list][scan8[0]+2 + 8*y];
  1137. }
  1138. if( h->pps.cabac ) {
  1139. if(IS_SKIP(mb_type))
  1140. fill_rectangle(h->mvd_table[list][b_xy], 4, 4, h->b_stride, 0, 4);
  1141. else
  1142. for(y=0; y<4; y++){
  1143. *(uint64_t*)h->mvd_table[list][b_xy + 0 + y*h->b_stride]= *(uint64_t*)h->mvd_cache[list][scan8[0]+0 + 8*y];
  1144. *(uint64_t*)h->mvd_table[list][b_xy + 2 + y*h->b_stride]= *(uint64_t*)h->mvd_cache[list][scan8[0]+2 + 8*y];
  1145. }
  1146. }
  1147. {
  1148. int8_t *ref_index = &s->current_picture.ref_index[list][b8_xy];
  1149. ref_index[0+0*h->b8_stride]= h->ref_cache[list][scan8[0]];
  1150. ref_index[1+0*h->b8_stride]= h->ref_cache[list][scan8[4]];
  1151. ref_index[0+1*h->b8_stride]= h->ref_cache[list][scan8[8]];
  1152. ref_index[1+1*h->b8_stride]= h->ref_cache[list][scan8[12]];
  1153. }
  1154. }
  1155. if(h->slice_type == B_TYPE && h->pps.cabac){
  1156. if(IS_8X8(mb_type)){
  1157. uint8_t *direct_table = &h->direct_table[b8_xy];
  1158. direct_table[1+0*h->b8_stride] = IS_DIRECT(h->sub_mb_type[1]) ? 1 : 0;
  1159. direct_table[0+1*h->b8_stride] = IS_DIRECT(h->sub_mb_type[2]) ? 1 : 0;
  1160. direct_table[1+1*h->b8_stride] = IS_DIRECT(h->sub_mb_type[3]) ? 1 : 0;
  1161. }
  1162. }
  1163. }
  1164. /**
  1165. * Decodes a network abstraction layer unit.
  1166. * @param consumed is the number of bytes used as input
  1167. * @param length is the length of the array
  1168. * @param dst_length is the number of decoded bytes FIXME here or a decode rbsp tailing?
  1169. * @returns decoded bytes, might be src+1 if no escapes
  1170. */
  1171. static uint8_t *decode_nal(H264Context *h, uint8_t *src, int *dst_length, int *consumed, int length){
  1172. int i, si, di;
  1173. uint8_t *dst;
  1174. int bufidx;
  1175. // src[0]&0x80; //forbidden bit
  1176. h->nal_ref_idc= src[0]>>5;
  1177. h->nal_unit_type= src[0]&0x1F;
  1178. src++; length--;
  1179. #if 0
  1180. for(i=0; i<length; i++)
  1181. printf("%2X ", src[i]);
  1182. #endif
  1183. for(i=0; i+1<length; i+=2){
  1184. if(src[i]) continue;
  1185. if(i>0 && src[i-1]==0) i--;
  1186. if(i+2<length && src[i+1]==0 && src[i+2]<=3){
  1187. if(src[i+2]!=3){
  1188. /* startcode, so we must be past the end */
  1189. length=i;
  1190. }
  1191. break;
  1192. }
  1193. }
  1194. if(i>=length-1){ //no escaped 0
  1195. *dst_length= length;
  1196. *consumed= length+1; //+1 for the header
  1197. return src;
  1198. }
  1199. bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0; // use second escape buffer for inter data
  1200. h->rbsp_buffer[bufidx]= av_fast_realloc(h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length);
  1201. dst= h->rbsp_buffer[bufidx];
  1202. if (dst == NULL){
  1203. return NULL;
  1204. }
  1205. //printf("decoding esc\n");
  1206. si=di=0;
  1207. while(si<length){
  1208. //remove escapes (very rare 1:2^22)
  1209. if(si+2<length && src[si]==0 && src[si+1]==0 && src[si+2]<=3){
  1210. if(src[si+2]==3){ //escape
  1211. dst[di++]= 0;
  1212. dst[di++]= 0;
  1213. si+=3;
  1214. continue;
  1215. }else //next start code
  1216. break;
  1217. }
  1218. dst[di++]= src[si++];
  1219. }
  1220. *dst_length= di;
  1221. *consumed= si + 1;//+1 for the header
  1222. //FIXME store exact number of bits in the getbitcontext (it is needed for decoding)
  1223. return dst;
  1224. }
  1225. /**
  1226. * identifies the exact end of the bitstream
  1227. * @return the length of the trailing, or 0 if damaged
  1228. */
  1229. static int decode_rbsp_trailing(H264Context *h, uint8_t *src){
  1230. int v= *src;
  1231. int r;
  1232. tprintf(h->s.avctx, "rbsp trailing %X\n", v);
  1233. for(r=1; r<9; r++){
  1234. if(v&1) return r;
  1235. v>>=1;
  1236. }
  1237. return 0;
  1238. }
  1239. /**
  1240. * idct tranforms the 16 dc values and dequantize them.
  1241. * @param qp quantization parameter
  1242. */
  1243. static void h264_luma_dc_dequant_idct_c(DCTELEM *block, int qp, int qmul){
  1244. #define stride 16
  1245. int i;
  1246. int temp[16]; //FIXME check if this is a good idea
  1247. static const int x_offset[4]={0, 1*stride, 4* stride, 5*stride};
  1248. static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
  1249. //memset(block, 64, 2*256);
  1250. //return;
  1251. for(i=0; i<4; i++){
  1252. const int offset= y_offset[i];
  1253. const int z0= block[offset+stride*0] + block[offset+stride*4];
  1254. const int z1= block[offset+stride*0] - block[offset+stride*4];
  1255. const int z2= block[offset+stride*1] - block[offset+stride*5];
  1256. const int z3= block[offset+stride*1] + block[offset+stride*5];
  1257. temp[4*i+0]= z0+z3;
  1258. temp[4*i+1]= z1+z2;
  1259. temp[4*i+2]= z1-z2;
  1260. temp[4*i+3]= z0-z3;
  1261. }
  1262. for(i=0; i<4; i++){
  1263. const int offset= x_offset[i];
  1264. const int z0= temp[4*0+i] + temp[4*2+i];
  1265. const int z1= temp[4*0+i] - temp[4*2+i];
  1266. const int z2= temp[4*1+i] - temp[4*3+i];
  1267. const int z3= temp[4*1+i] + temp[4*3+i];
  1268. block[stride*0 +offset]= ((((z0 + z3)*qmul + 128 ) >> 8)); //FIXME think about merging this into decode_resdual
  1269. block[stride*2 +offset]= ((((z1 + z2)*qmul + 128 ) >> 8));
  1270. block[stride*8 +offset]= ((((z1 - z2)*qmul + 128 ) >> 8));
  1271. block[stride*10+offset]= ((((z0 - z3)*qmul + 128 ) >> 8));
  1272. }
  1273. }
  1274. #if 0
  1275. /**
  1276. * dct tranforms the 16 dc values.
  1277. * @param qp quantization parameter ??? FIXME
  1278. */
  1279. static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
  1280. // const int qmul= dequant_coeff[qp][0];
  1281. int i;
  1282. int temp[16]; //FIXME check if this is a good idea
  1283. static const int x_offset[4]={0, 1*stride, 4* stride, 5*stride};
  1284. static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
  1285. for(i=0; i<4; i++){
  1286. const int offset= y_offset[i];
  1287. const int z0= block[offset+stride*0] + block[offset+stride*4];
  1288. const int z1= block[offset+stride*0] - block[offset+stride*4];
  1289. const int z2= block[offset+stride*1] - block[offset+stride*5];
  1290. const int z3= block[offset+stride*1] + block[offset+stride*5];
  1291. temp[4*i+0]= z0+z3;
  1292. temp[4*i+1]= z1+z2;
  1293. temp[4*i+2]= z1-z2;
  1294. temp[4*i+3]= z0-z3;
  1295. }
  1296. for(i=0; i<4; i++){
  1297. const int offset= x_offset[i];
  1298. const int z0= temp[4*0+i] + temp[4*2+i];
  1299. const int z1= temp[4*0+i] - temp[4*2+i];
  1300. const int z2= temp[4*1+i] - temp[4*3+i];
  1301. const int z3= temp[4*1+i] + temp[4*3+i];
  1302. block[stride*0 +offset]= (z0 + z3)>>1;
  1303. block[stride*2 +offset]= (z1 + z2)>>1;
  1304. block[stride*8 +offset]= (z1 - z2)>>1;
  1305. block[stride*10+offset]= (z0 - z3)>>1;
  1306. }
  1307. }
  1308. #endif
  1309. #undef xStride
  1310. #undef stride
  1311. static void chroma_dc_dequant_idct_c(DCTELEM *block, int qp, int qmul){
  1312. const int stride= 16*2;
  1313. const int xStride= 16;
  1314. int a,b,c,d,e;
  1315. a= block[stride*0 + xStride*0];
  1316. b= block[stride*0 + xStride*1];
  1317. c= block[stride*1 + xStride*0];
  1318. d= block[stride*1 + xStride*1];
  1319. e= a-b;
  1320. a= a+b;
  1321. b= c-d;
  1322. c= c+d;
  1323. block[stride*0 + xStride*0]= ((a+c)*qmul) >> 7;
  1324. block[stride*0 + xStride*1]= ((e+b)*qmul) >> 7;
  1325. block[stride*1 + xStride*0]= ((a-c)*qmul) >> 7;
  1326. block[stride*1 + xStride*1]= ((e-b)*qmul) >> 7;
  1327. }
  1328. #if 0
  1329. static void chroma_dc_dct_c(DCTELEM *block){
  1330. const int stride= 16*2;
  1331. const int xStride= 16;
  1332. int a,b,c,d,e;
  1333. a= block[stride*0 + xStride*0];
  1334. b= block[stride*0 + xStride*1];
  1335. c= block[stride*1 + xStride*0];
  1336. d= block[stride*1 + xStride*1];
  1337. e= a-b;
  1338. a= a+b;
  1339. b= c-d;
  1340. c= c+d;
  1341. block[stride*0 + xStride*0]= (a+c);
  1342. block[stride*0 + xStride*1]= (e+b);
  1343. block[stride*1 + xStride*0]= (a-c);
  1344. block[stride*1 + xStride*1]= (e-b);
  1345. }
  1346. #endif
  1347. /**
  1348. * gets the chroma qp.
  1349. */
  1350. static inline int get_chroma_qp(H264Context *h, int t, int qscale){
  1351. return h->pps.chroma_qp_table[t][qscale & 0xff];
  1352. }
  1353. //FIXME need to check that this does not overflow signed 32 bit for low qp, i am not sure, it's very close
  1354. //FIXME check that gcc inlines this (and optimizes intra & separate_dc stuff away)
  1355. static inline int quantize_c(DCTELEM *block, uint8_t *scantable, int qscale, int intra, int separate_dc){
  1356. int i;
  1357. const int * const quant_table= quant_coeff[qscale];
  1358. const int bias= intra ? (1<<QUANT_SHIFT)/3 : (1<<QUANT_SHIFT)/6;
  1359. const unsigned int threshold1= (1<<QUANT_SHIFT) - bias - 1;
  1360. const unsigned int threshold2= (threshold1<<1);
  1361. int last_non_zero;
  1362. if(separate_dc){
  1363. if(qscale<=18){
  1364. //avoid overflows
  1365. const int dc_bias= intra ? (1<<(QUANT_SHIFT-2))/3 : (1<<(QUANT_SHIFT-2))/6;
  1366. const unsigned int dc_threshold1= (1<<(QUANT_SHIFT-2)) - dc_bias - 1;
  1367. const unsigned int dc_threshold2= (dc_threshold1<<1);
  1368. int level= block[0]*quant_coeff[qscale+18][0];
  1369. if(((unsigned)(level+dc_threshold1))>dc_threshold2){
  1370. if(level>0){
  1371. level= (dc_bias + level)>>(QUANT_SHIFT-2);
  1372. block[0]= level;
  1373. }else{
  1374. level= (dc_bias - level)>>(QUANT_SHIFT-2);
  1375. block[0]= -level;
  1376. }
  1377. // last_non_zero = i;
  1378. }else{
  1379. block[0]=0;
  1380. }
  1381. }else{
  1382. const int dc_bias= intra ? (1<<(QUANT_SHIFT+1))/3 : (1<<(QUANT_SHIFT+1))/6;
  1383. const unsigned int dc_threshold1= (1<<(QUANT_SHIFT+1)) - dc_bias - 1;
  1384. const unsigned int dc_threshold2= (dc_threshold1<<1);
  1385. int level= block[0]*quant_table[0];
  1386. if(((unsigned)(level+dc_threshold1))>dc_threshold2){
  1387. if(level>0){
  1388. level= (dc_bias + level)>>(QUANT_SHIFT+1);
  1389. block[0]= level;
  1390. }else{
  1391. level= (dc_bias - level)>>(QUANT_SHIFT+1);
  1392. block[0]= -level;
  1393. }
  1394. // last_non_zero = i;
  1395. }else{
  1396. block[0]=0;
  1397. }
  1398. }
  1399. last_non_zero= 0;
  1400. i=1;
  1401. }else{
  1402. last_non_zero= -1;
  1403. i=0;
  1404. }
  1405. for(; i<16; i++){
  1406. const int j= scantable[i];
  1407. int level= block[j]*quant_table[j];
  1408. // if( bias+level >= (1<<(QMAT_SHIFT - 3))
  1409. // || bias-level >= (1<<(QMAT_SHIFT - 3))){
  1410. if(((unsigned)(level+threshold1))>threshold2){
  1411. if(level>0){
  1412. level= (bias + level)>>QUANT_SHIFT;
  1413. block[j]= level;
  1414. }else{
  1415. level= (bias - level)>>QUANT_SHIFT;
  1416. block[j]= -level;
  1417. }
  1418. last_non_zero = i;
  1419. }else{
  1420. block[j]=0;
  1421. }
  1422. }
  1423. return last_non_zero;
  1424. }
  1425. static inline void mc_dir_part(H264Context *h, Picture *pic, int n, int square, int chroma_height, int delta, int list,
  1426. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1427. int src_x_offset, int src_y_offset,
  1428. qpel_mc_func *qpix_op, h264_chroma_mc_func chroma_op){
  1429. MpegEncContext * const s = &h->s;
  1430. const int mx= h->mv_cache[list][ scan8[n] ][0] + src_x_offset*8;
  1431. int my= h->mv_cache[list][ scan8[n] ][1] + src_y_offset*8;
  1432. const int luma_xy= (mx&3) + ((my&3)<<2);
  1433. uint8_t * src_y = pic->data[0] + (mx>>2) + (my>>2)*h->mb_linesize;
  1434. uint8_t * src_cb, * src_cr;
  1435. int extra_width= h->emu_edge_width;
  1436. int extra_height= h->emu_edge_height;
  1437. int emu=0;
  1438. const int full_mx= mx>>2;
  1439. const int full_my= my>>2;
  1440. const int pic_width = 16*s->mb_width;
  1441. const int pic_height = 16*s->mb_height >> MB_FIELD;
  1442. if(!pic->data[0]) //FIXME this is unacceptable, some senseable error concealment must be done for missing reference frames
  1443. return;
  1444. if(mx&7) extra_width -= 3;
  1445. if(my&7) extra_height -= 3;
  1446. if( full_mx < 0-extra_width
  1447. || full_my < 0-extra_height
  1448. || full_mx + 16/*FIXME*/ > pic_width + extra_width
  1449. || full_my + 16/*FIXME*/ > pic_height + extra_height){
  1450. ff_emulated_edge_mc(s->edge_emu_buffer, src_y - 2 - 2*h->mb_linesize, h->mb_linesize, 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
  1451. src_y= s->edge_emu_buffer + 2 + 2*h->mb_linesize;
  1452. emu=1;
  1453. }
  1454. qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); //FIXME try variable height perhaps?
  1455. if(!square){
  1456. qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
  1457. }
  1458. if(ENABLE_GRAY && s->flags&CODEC_FLAG_GRAY) return;
  1459. if(MB_FIELD){
  1460. // chroma offset when predicting from a field of opposite parity
  1461. my += 2 * ((s->mb_y & 1) - (pic->reference - 1));
  1462. emu |= (my>>3) < 0 || (my>>3) + 8 >= (pic_height>>1);
  1463. }
  1464. src_cb= pic->data[1] + (mx>>3) + (my>>3)*h->mb_uvlinesize;
  1465. src_cr= pic->data[2] + (mx>>3) + (my>>3)*h->mb_uvlinesize;
  1466. if(emu){
  1467. ff_emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
  1468. src_cb= s->edge_emu_buffer;
  1469. }
  1470. chroma_op(dest_cb, src_cb, h->mb_uvlinesize, chroma_height, mx&7, my&7);
  1471. if(emu){
  1472. ff_emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
  1473. src_cr= s->edge_emu_buffer;
  1474. }
  1475. chroma_op(dest_cr, src_cr, h->mb_uvlinesize, chroma_height, mx&7, my&7);
  1476. }
  1477. static inline void mc_part_std(H264Context *h, int n, int square, int chroma_height, int delta,
  1478. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1479. int x_offset, int y_offset,
  1480. qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
  1481. qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
  1482. int list0, int list1){
  1483. MpegEncContext * const s = &h->s;
  1484. qpel_mc_func *qpix_op= qpix_put;
  1485. h264_chroma_mc_func chroma_op= chroma_put;
  1486. dest_y += 2*x_offset + 2*y_offset*h-> mb_linesize;
  1487. dest_cb += x_offset + y_offset*h->mb_uvlinesize;
  1488. dest_cr += x_offset + y_offset*h->mb_uvlinesize;
  1489. x_offset += 8*s->mb_x;
  1490. y_offset += 8*(s->mb_y >> MB_FIELD);
  1491. if(list0){
  1492. Picture *ref= &h->ref_list[0][ h->ref_cache[0][ scan8[n] ] ];
  1493. mc_dir_part(h, ref, n, square, chroma_height, delta, 0,
  1494. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  1495. qpix_op, chroma_op);
  1496. qpix_op= qpix_avg;
  1497. chroma_op= chroma_avg;
  1498. }
  1499. if(list1){
  1500. Picture *ref= &h->ref_list[1][ h->ref_cache[1][ scan8[n] ] ];
  1501. mc_dir_part(h, ref, n, square, chroma_height, delta, 1,
  1502. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  1503. qpix_op, chroma_op);
  1504. }
  1505. }
  1506. static inline void mc_part_weighted(H264Context *h, int n, int square, int chroma_height, int delta,
  1507. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1508. int x_offset, int y_offset,
  1509. qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
  1510. h264_weight_func luma_weight_op, h264_weight_func chroma_weight_op,
  1511. h264_biweight_func luma_weight_avg, h264_biweight_func chroma_weight_avg,
  1512. int list0, int list1){
  1513. MpegEncContext * const s = &h->s;
  1514. dest_y += 2*x_offset + 2*y_offset*h-> mb_linesize;
  1515. dest_cb += x_offset + y_offset*h->mb_uvlinesize;
  1516. dest_cr += x_offset + y_offset*h->mb_uvlinesize;
  1517. x_offset += 8*s->mb_x;
  1518. y_offset += 8*(s->mb_y >> MB_FIELD);
  1519. if(list0 && list1){
  1520. /* don't optimize for luma-only case, since B-frames usually
  1521. * use implicit weights => chroma too. */
  1522. uint8_t *tmp_cb = s->obmc_scratchpad;
  1523. uint8_t *tmp_cr = s->obmc_scratchpad + 8;
  1524. uint8_t *tmp_y = s->obmc_scratchpad + 8*h->mb_uvlinesize;
  1525. int refn0 = h->ref_cache[0][ scan8[n] ];
  1526. int refn1 = h->ref_cache[1][ scan8[n] ];
  1527. mc_dir_part(h, &h->ref_list[0][refn0], n, square, chroma_height, delta, 0,
  1528. dest_y, dest_cb, dest_cr,
  1529. x_offset, y_offset, qpix_put, chroma_put);
  1530. mc_dir_part(h, &h->ref_list[1][refn1], n, square, chroma_height, delta, 1,
  1531. tmp_y, tmp_cb, tmp_cr,
  1532. x_offset, y_offset, qpix_put, chroma_put);
  1533. if(h->use_weight == 2){
  1534. int weight0 = h->implicit_weight[refn0][refn1];
  1535. int weight1 = 64 - weight0;
  1536. luma_weight_avg( dest_y, tmp_y, h-> mb_linesize, 5, weight0, weight1, 0);
  1537. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, 5, weight0, weight1, 0);
  1538. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, 5, weight0, weight1, 0);
  1539. }else{
  1540. luma_weight_avg(dest_y, tmp_y, h->mb_linesize, h->luma_log2_weight_denom,
  1541. h->luma_weight[0][refn0], h->luma_weight[1][refn1],
  1542. h->luma_offset[0][refn0] + h->luma_offset[1][refn1]);
  1543. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
  1544. h->chroma_weight[0][refn0][0], h->chroma_weight[1][refn1][0],
  1545. h->chroma_offset[0][refn0][0] + h->chroma_offset[1][refn1][0]);
  1546. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
  1547. h->chroma_weight[0][refn0][1], h->chroma_weight[1][refn1][1],
  1548. h->chroma_offset[0][refn0][1] + h->chroma_offset[1][refn1][1]);
  1549. }
  1550. }else{
  1551. int list = list1 ? 1 : 0;
  1552. int refn = h->ref_cache[list][ scan8[n] ];
  1553. Picture *ref= &h->ref_list[list][refn];
  1554. mc_dir_part(h, ref, n, square, chroma_height, delta, list,
  1555. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  1556. qpix_put, chroma_put);
  1557. luma_weight_op(dest_y, h->mb_linesize, h->luma_log2_weight_denom,
  1558. h->luma_weight[list][refn], h->luma_offset[list][refn]);
  1559. if(h->use_weight_chroma){
  1560. chroma_weight_op(dest_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
  1561. h->chroma_weight[list][refn][0], h->chroma_offset[list][refn][0]);
  1562. chroma_weight_op(dest_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
  1563. h->chroma_weight[list][refn][1], h->chroma_offset[list][refn][1]);
  1564. }
  1565. }
  1566. }
  1567. static inline void mc_part(H264Context *h, int n, int square, int chroma_height, int delta,
  1568. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1569. int x_offset, int y_offset,
  1570. qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
  1571. qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
  1572. h264_weight_func *weight_op, h264_biweight_func *weight_avg,
  1573. int list0, int list1){
  1574. if((h->use_weight==2 && list0 && list1
  1575. && (h->implicit_weight[ h->ref_cache[0][scan8[n]] ][ h->ref_cache[1][scan8[n]] ] != 32))
  1576. || h->use_weight==1)
  1577. mc_part_weighted(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
  1578. x_offset, y_offset, qpix_put, chroma_put,
  1579. weight_op[0], weight_op[3], weight_avg[0], weight_avg[3], list0, list1);
  1580. else
  1581. mc_part_std(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
  1582. x_offset, y_offset, qpix_put, chroma_put, qpix_avg, chroma_avg, list0, list1);
  1583. }
  1584. static inline void prefetch_motion(H264Context *h, int list){
  1585. /* fetch pixels for estimated mv 4 macroblocks ahead
  1586. * optimized for 64byte cache lines */
  1587. MpegEncContext * const s = &h->s;
  1588. const int refn = h->ref_cache[list][scan8[0]];
  1589. if(refn >= 0){
  1590. const int mx= (h->mv_cache[list][scan8[0]][0]>>2) + 16*s->mb_x + 8;
  1591. const int my= (h->mv_cache[list][scan8[0]][1]>>2) + 16*s->mb_y;
  1592. uint8_t **src= h->ref_list[list][refn].data;
  1593. int off= mx + (my + (s->mb_x&3)*4)*h->mb_linesize + 64;
  1594. s->dsp.prefetch(src[0]+off, s->linesize, 4);
  1595. off= (mx>>1) + ((my>>1) + (s->mb_x&7))*s->uvlinesize + 64;
  1596. s->dsp.prefetch(src[1]+off, src[2]-src[1], 2);
  1597. }
  1598. }
  1599. static void hl_motion(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1600. qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
  1601. qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
  1602. h264_weight_func *weight_op, h264_biweight_func *weight_avg){
  1603. MpegEncContext * const s = &h->s;
  1604. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  1605. const int mb_type= s->current_picture.mb_type[mb_xy];
  1606. assert(IS_INTER(mb_type));
  1607. prefetch_motion(h, 0);
  1608. if(IS_16X16(mb_type)){
  1609. mc_part(h, 0, 1, 8, 0, dest_y, dest_cb, dest_cr, 0, 0,
  1610. qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
  1611. &weight_op[0], &weight_avg[0],
  1612. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
  1613. }else if(IS_16X8(mb_type)){
  1614. mc_part(h, 0, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 0,
  1615. qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
  1616. &weight_op[1], &weight_avg[1],
  1617. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
  1618. mc_part(h, 8, 0, 4, 8, dest_y, dest_cb, dest_cr, 0, 4,
  1619. qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
  1620. &weight_op[1], &weight_avg[1],
  1621. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
  1622. }else if(IS_8X16(mb_type)){
  1623. mc_part(h, 0, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
  1624. qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
  1625. &weight_op[2], &weight_avg[2],
  1626. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1));
  1627. mc_part(h, 4, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
  1628. qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
  1629. &weight_op[2], &weight_avg[2],
  1630. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1));
  1631. }else{
  1632. int i;
  1633. assert(IS_8X8(mb_type));
  1634. for(i=0; i<4; i++){
  1635. const int sub_mb_type= h->sub_mb_type[i];
  1636. const int n= 4*i;
  1637. int x_offset= (i&1)<<2;
  1638. int y_offset= (i&2)<<1;
  1639. if(IS_SUB_8X8(sub_mb_type)){
  1640. mc_part(h, n, 1, 4, 0, dest_y, dest_cb, dest_cr, x_offset, y_offset,
  1641. qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
  1642. &weight_op[3], &weight_avg[3],
  1643. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  1644. }else if(IS_SUB_8X4(sub_mb_type)){
  1645. mc_part(h, n , 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset,
  1646. qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
  1647. &weight_op[4], &weight_avg[4],
  1648. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  1649. mc_part(h, n+2, 0, 2, 4, dest_y, dest_cb, dest_cr, x_offset, y_offset+2,
  1650. qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
  1651. &weight_op[4], &weight_avg[4],
  1652. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  1653. }else if(IS_SUB_4X8(sub_mb_type)){
  1654. mc_part(h, n , 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset, y_offset,
  1655. qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
  1656. &weight_op[5], &weight_avg[5],
  1657. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  1658. mc_part(h, n+1, 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset+2, y_offset,
  1659. qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
  1660. &weight_op[5], &weight_avg[5],
  1661. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  1662. }else{
  1663. int j;
  1664. assert(IS_SUB_4X4(sub_mb_type));
  1665. for(j=0; j<4; j++){
  1666. int sub_x_offset= x_offset + 2*(j&1);
  1667. int sub_y_offset= y_offset + (j&2);
  1668. mc_part(h, n+j, 1, 2, 0, dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
  1669. qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
  1670. &weight_op[6], &weight_avg[6],
  1671. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1));
  1672. }
  1673. }
  1674. }
  1675. }
  1676. prefetch_motion(h, 1);
  1677. }
  1678. static void decode_init_vlc(void){
  1679. static int done = 0;
  1680. if (!done) {
  1681. int i;
  1682. done = 1;
  1683. init_vlc(&chroma_dc_coeff_token_vlc, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 4*5,
  1684. &chroma_dc_coeff_token_len [0], 1, 1,
  1685. &chroma_dc_coeff_token_bits[0], 1, 1, 1);
  1686. for(i=0; i<4; i++){
  1687. init_vlc(&coeff_token_vlc[i], COEFF_TOKEN_VLC_BITS, 4*17,
  1688. &coeff_token_len [i][0], 1, 1,
  1689. &coeff_token_bits[i][0], 1, 1, 1);
  1690. }
  1691. for(i=0; i<3; i++){
  1692. init_vlc(&chroma_dc_total_zeros_vlc[i], CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 4,
  1693. &chroma_dc_total_zeros_len [i][0], 1, 1,
  1694. &chroma_dc_total_zeros_bits[i][0], 1, 1, 1);
  1695. }
  1696. for(i=0; i<15; i++){
  1697. init_vlc(&total_zeros_vlc[i], TOTAL_ZEROS_VLC_BITS, 16,
  1698. &total_zeros_len [i][0], 1, 1,
  1699. &total_zeros_bits[i][0], 1, 1, 1);
  1700. }
  1701. for(i=0; i<6; i++){
  1702. init_vlc(&run_vlc[i], RUN_VLC_BITS, 7,
  1703. &run_len [i][0], 1, 1,
  1704. &run_bits[i][0], 1, 1, 1);
  1705. }
  1706. init_vlc(&run7_vlc, RUN7_VLC_BITS, 16,
  1707. &run_len [6][0], 1, 1,
  1708. &run_bits[6][0], 1, 1, 1);
  1709. }
  1710. }
  1711. static void free_tables(H264Context *h){
  1712. int i;
  1713. H264Context *hx;
  1714. av_freep(&h->intra4x4_pred_mode);
  1715. av_freep(&h->chroma_pred_mode_table);
  1716. av_freep(&h->cbp_table);
  1717. av_freep(&h->mvd_table[0]);
  1718. av_freep(&h->mvd_table[1]);
  1719. av_freep(&h->direct_table);
  1720. av_freep(&h->non_zero_count);
  1721. av_freep(&h->slice_table_base);
  1722. h->slice_table= NULL;
  1723. av_freep(&h->mb2b_xy);
  1724. av_freep(&h->mb2b8_xy);
  1725. for(i = 0; i < MAX_SPS_COUNT; i++)
  1726. av_freep(h->sps_buffers + i);
  1727. for(i = 0; i < MAX_PPS_COUNT; i++)
  1728. av_freep(h->pps_buffers + i);
  1729. for(i = 0; i < h->s.avctx->thread_count; i++) {
  1730. hx = h->thread_context[i];
  1731. if(!hx) continue;
  1732. av_freep(&hx->top_borders[1]);
  1733. av_freep(&hx->top_borders[0]);
  1734. av_freep(&hx->s.obmc_scratchpad);
  1735. av_freep(&hx->s.allocated_edge_emu_buffer);
  1736. }
  1737. }
  1738. static void init_dequant8_coeff_table(H264Context *h){
  1739. int i,q,x;
  1740. const int transpose = (h->s.dsp.h264_idct8_add != ff_h264_idct8_add_c); //FIXME ugly
  1741. h->dequant8_coeff[0] = h->dequant8_buffer[0];
  1742. h->dequant8_coeff[1] = h->dequant8_buffer[1];
  1743. for(i=0; i<2; i++ ){
  1744. if(i && !memcmp(h->pps.scaling_matrix8[0], h->pps.scaling_matrix8[1], 64*sizeof(uint8_t))){
  1745. h->dequant8_coeff[1] = h->dequant8_buffer[0];
  1746. break;
  1747. }
  1748. for(q=0; q<52; q++){
  1749. int shift = ff_div6[q];
  1750. int idx = ff_rem6[q];
  1751. for(x=0; x<64; x++)
  1752. h->dequant8_coeff[i][q][transpose ? (x>>3)|((x&7)<<3) : x] =
  1753. ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *
  1754. h->pps.scaling_matrix8[i][x]) << shift;
  1755. }
  1756. }
  1757. }
  1758. static void init_dequant4_coeff_table(H264Context *h){
  1759. int i,j,q,x;
  1760. const int transpose = (h->s.dsp.h264_idct_add != ff_h264_idct_add_c); //FIXME ugly
  1761. for(i=0; i<6; i++ ){
  1762. h->dequant4_coeff[i] = h->dequant4_buffer[i];
  1763. for(j=0; j<i; j++){
  1764. if(!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16*sizeof(uint8_t))){
  1765. h->dequant4_coeff[i] = h->dequant4_buffer[j];
  1766. break;
  1767. }
  1768. }
  1769. if(j<i)
  1770. continue;
  1771. for(q=0; q<52; q++){
  1772. int shift = ff_div6[q] + 2;
  1773. int idx = ff_rem6[q];
  1774. for(x=0; x<16; x++)
  1775. h->dequant4_coeff[i][q][transpose ? (x>>2)|((x<<2)&0xF) : x] =
  1776. ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *
  1777. h->pps.scaling_matrix4[i][x]) << shift;
  1778. }
  1779. }
  1780. }
  1781. static void init_dequant_tables(H264Context *h){
  1782. int i,x;
  1783. init_dequant4_coeff_table(h);
  1784. if(h->pps.transform_8x8_mode)
  1785. init_dequant8_coeff_table(h);
  1786. if(h->sps.transform_bypass){
  1787. for(i=0; i<6; i++)
  1788. for(x=0; x<16; x++)
  1789. h->dequant4_coeff[i][0][x] = 1<<6;
  1790. if(h->pps.transform_8x8_mode)
  1791. for(i=0; i<2; i++)
  1792. for(x=0; x<64; x++)
  1793. h->dequant8_coeff[i][0][x] = 1<<6;
  1794. }
  1795. }
  1796. /**
  1797. * allocates tables.
  1798. * needs width/height
  1799. */
  1800. static int alloc_tables(H264Context *h){
  1801. MpegEncContext * const s = &h->s;
  1802. const int big_mb_num= s->mb_stride * (s->mb_height+1);
  1803. int x,y;
  1804. CHECKED_ALLOCZ(h->intra4x4_pred_mode, big_mb_num * 8 * sizeof(uint8_t))
  1805. CHECKED_ALLOCZ(h->non_zero_count , big_mb_num * 16 * sizeof(uint8_t))
  1806. CHECKED_ALLOCZ(h->slice_table_base , (big_mb_num+s->mb_stride) * sizeof(uint8_t))
  1807. CHECKED_ALLOCZ(h->cbp_table, big_mb_num * sizeof(uint16_t))
  1808. CHECKED_ALLOCZ(h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t))
  1809. CHECKED_ALLOCZ(h->mvd_table[0], 32*big_mb_num * sizeof(uint16_t));
  1810. CHECKED_ALLOCZ(h->mvd_table[1], 32*big_mb_num * sizeof(uint16_t));
  1811. CHECKED_ALLOCZ(h->direct_table, 32*big_mb_num * sizeof(uint8_t));
  1812. memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride) * sizeof(uint8_t));
  1813. h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
  1814. CHECKED_ALLOCZ(h->mb2b_xy , big_mb_num * sizeof(uint32_t));
  1815. CHECKED_ALLOCZ(h->mb2b8_xy , big_mb_num * sizeof(uint32_t));
  1816. for(y=0; y<s->mb_height; y++){
  1817. for(x=0; x<s->mb_width; x++){
  1818. const int mb_xy= x + y*s->mb_stride;
  1819. const int b_xy = 4*x + 4*y*h->b_stride;
  1820. const int b8_xy= 2*x + 2*y*h->b8_stride;
  1821. h->mb2b_xy [mb_xy]= b_xy;
  1822. h->mb2b8_xy[mb_xy]= b8_xy;
  1823. }
  1824. }
  1825. s->obmc_scratchpad = NULL;
  1826. if(!h->dequant4_coeff[0])
  1827. init_dequant_tables(h);
  1828. return 0;
  1829. fail:
  1830. free_tables(h);
  1831. return -1;
  1832. }
  1833. /**
  1834. * Mimic alloc_tables(), but for every context thread.
  1835. */
  1836. static void clone_tables(H264Context *dst, H264Context *src){
  1837. dst->intra4x4_pred_mode = src->intra4x4_pred_mode;
  1838. dst->non_zero_count = src->non_zero_count;
  1839. dst->slice_table = src->slice_table;
  1840. dst->cbp_table = src->cbp_table;
  1841. dst->mb2b_xy = src->mb2b_xy;
  1842. dst->mb2b8_xy = src->mb2b8_xy;
  1843. dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
  1844. dst->mvd_table[0] = src->mvd_table[0];
  1845. dst->mvd_table[1] = src->mvd_table[1];
  1846. dst->direct_table = src->direct_table;
  1847. dst->s.obmc_scratchpad = NULL;
  1848. ff_h264_pred_init(&dst->hpc, src->s.codec_id);
  1849. }
  1850. /**
  1851. * Init context
  1852. * Allocate buffers which are not shared amongst multiple threads.
  1853. */
  1854. static int context_init(H264Context *h){
  1855. MpegEncContext * const s = &h->s;
  1856. CHECKED_ALLOCZ(h->top_borders[0], h->s.mb_width * (16+8+8) * sizeof(uint8_t))
  1857. CHECKED_ALLOCZ(h->top_borders[1], h->s.mb_width * (16+8+8) * sizeof(uint8_t))
  1858. // edge emu needs blocksize + filter length - 1 (=17x17 for halfpel / 21x21 for h264)
  1859. CHECKED_ALLOCZ(s->allocated_edge_emu_buffer,
  1860. (s->width+64)*2*21*2); //(width + edge + align)*interlaced*MBsize*tolerance
  1861. s->edge_emu_buffer= s->allocated_edge_emu_buffer + (s->width+64)*2*21;
  1862. return 0;
  1863. fail:
  1864. return -1; // free_tables will clean up for us
  1865. }
  1866. static void common_init(H264Context *h){
  1867. MpegEncContext * const s = &h->s;
  1868. s->width = s->avctx->width;
  1869. s->height = s->avctx->height;
  1870. s->codec_id= s->avctx->codec->id;
  1871. ff_h264_pred_init(&h->hpc, s->codec_id);
  1872. h->dequant_coeff_pps= -1;
  1873. s->unrestricted_mv=1;
  1874. s->decode=1; //FIXME
  1875. memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
  1876. memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
  1877. }
  1878. static int decode_init(AVCodecContext *avctx){
  1879. H264Context *h= avctx->priv_data;
  1880. MpegEncContext * const s = &h->s;
  1881. MPV_decode_defaults(s);
  1882. s->avctx = avctx;
  1883. common_init(h);
  1884. s->out_format = FMT_H264;
  1885. s->workaround_bugs= avctx->workaround_bugs;
  1886. // set defaults
  1887. // s->decode_mb= ff_h263_decode_mb;
  1888. s->quarter_sample = 1;
  1889. s->low_delay= 1;
  1890. avctx->pix_fmt= PIX_FMT_YUV420P;
  1891. decode_init_vlc();
  1892. if(avctx->extradata_size > 0 && avctx->extradata &&
  1893. *(char *)avctx->extradata == 1){
  1894. h->is_avc = 1;
  1895. h->got_avcC = 0;
  1896. } else {
  1897. h->is_avc = 0;
  1898. }
  1899. h->thread_context[0] = h;
  1900. return 0;
  1901. }
  1902. static int frame_start(H264Context *h){
  1903. MpegEncContext * const s = &h->s;
  1904. int i;
  1905. if(MPV_frame_start(s, s->avctx) < 0)
  1906. return -1;
  1907. ff_er_frame_start(s);
  1908. /*
  1909. * MPV_frame_start uses pict_type to derive key_frame.
  1910. * This is incorrect for H.264; IDR markings must be used.
  1911. * Zero here; IDR markings per slice in frame or fields are OR'd in later.
  1912. * See decode_nal_units().
  1913. */
  1914. s->current_picture_ptr->key_frame= 0;
  1915. assert(s->linesize && s->uvlinesize);
  1916. for(i=0; i<16; i++){
  1917. h->block_offset[i]= 4*((scan8[i] - scan8[0])&7) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
  1918. h->block_offset[24+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->linesize*((scan8[i] - scan8[0])>>3);
  1919. }
  1920. for(i=0; i<4; i++){
  1921. h->block_offset[16+i]=
  1922. h->block_offset[20+i]= 4*((scan8[i] - scan8[0])&7) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
  1923. h->block_offset[24+16+i]=
  1924. h->block_offset[24+20+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
  1925. }
  1926. /* can't be in alloc_tables because linesize isn't known there.
  1927. * FIXME: redo bipred weight to not require extra buffer? */
  1928. for(i = 0; i < s->avctx->thread_count; i++)
  1929. if(!h->thread_context[i]->s.obmc_scratchpad)
  1930. h->thread_context[i]->s.obmc_scratchpad = av_malloc(16*2*s->linesize + 8*2*s->uvlinesize);
  1931. /* some macroblocks will be accessed before they're available */
  1932. if(FRAME_MBAFF || s->avctx->thread_count > 1)
  1933. memset(h->slice_table, -1, (s->mb_height*s->mb_stride-1) * sizeof(uint8_t));
  1934. // s->decode= (s->flags&CODEC_FLAG_PSNR) || !s->encoding || s->current_picture.reference /*|| h->contains_intra*/ || 1;
  1935. return 0;
  1936. }
  1937. static inline void backup_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int simple){
  1938. MpegEncContext * const s = &h->s;
  1939. int i;
  1940. src_y -= linesize;
  1941. src_cb -= uvlinesize;
  1942. src_cr -= uvlinesize;
  1943. // There are two lines saved, the line above the the top macroblock of a pair,
  1944. // and the line above the bottom macroblock
  1945. h->left_border[0]= h->top_borders[0][s->mb_x][15];
  1946. for(i=1; i<17; i++){
  1947. h->left_border[i]= src_y[15+i* linesize];
  1948. }
  1949. *(uint64_t*)(h->top_borders[0][s->mb_x]+0)= *(uint64_t*)(src_y + 16*linesize);
  1950. *(uint64_t*)(h->top_borders[0][s->mb_x]+8)= *(uint64_t*)(src_y +8+16*linesize);
  1951. if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1952. h->left_border[17 ]= h->top_borders[0][s->mb_x][16+7];
  1953. h->left_border[17+9]= h->top_borders[0][s->mb_x][24+7];
  1954. for(i=1; i<9; i++){
  1955. h->left_border[i+17 ]= src_cb[7+i*uvlinesize];
  1956. h->left_border[i+17+9]= src_cr[7+i*uvlinesize];
  1957. }
  1958. *(uint64_t*)(h->top_borders[0][s->mb_x]+16)= *(uint64_t*)(src_cb+8*uvlinesize);
  1959. *(uint64_t*)(h->top_borders[0][s->mb_x]+24)= *(uint64_t*)(src_cr+8*uvlinesize);
  1960. }
  1961. }
  1962. static inline void xchg_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int xchg, int simple){
  1963. MpegEncContext * const s = &h->s;
  1964. int temp8, i;
  1965. uint64_t temp64;
  1966. int deblock_left;
  1967. int deblock_top;
  1968. int mb_xy;
  1969. if(h->deblocking_filter == 2) {
  1970. mb_xy = s->mb_x + s->mb_y*s->mb_stride;
  1971. deblock_left = h->slice_table[mb_xy] == h->slice_table[mb_xy - 1];
  1972. deblock_top = h->slice_table[mb_xy] == h->slice_table[h->top_mb_xy];
  1973. } else {
  1974. deblock_left = (s->mb_x > 0);
  1975. deblock_top = (s->mb_y > 0);
  1976. }
  1977. src_y -= linesize + 1;
  1978. src_cb -= uvlinesize + 1;
  1979. src_cr -= uvlinesize + 1;
  1980. #define XCHG(a,b,t,xchg)\
  1981. t= a;\
  1982. if(xchg)\
  1983. a= b;\
  1984. b= t;
  1985. if(deblock_left){
  1986. for(i = !deblock_top; i<17; i++){
  1987. XCHG(h->left_border[i ], src_y [i* linesize], temp8, xchg);
  1988. }
  1989. }
  1990. if(deblock_top){
  1991. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+0), *(uint64_t*)(src_y +1), temp64, xchg);
  1992. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+8), *(uint64_t*)(src_y +9), temp64, 1);
  1993. if(s->mb_x+1 < s->mb_width){
  1994. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x+1]), *(uint64_t*)(src_y +17), temp64, 1);
  1995. }
  1996. }
  1997. if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1998. if(deblock_left){
  1999. for(i = !deblock_top; i<9; i++){
  2000. XCHG(h->left_border[i+17 ], src_cb[i*uvlinesize], temp8, xchg);
  2001. XCHG(h->left_border[i+17+9], src_cr[i*uvlinesize], temp8, xchg);
  2002. }
  2003. }
  2004. if(deblock_top){
  2005. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+16), *(uint64_t*)(src_cb+1), temp64, 1);
  2006. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+24), *(uint64_t*)(src_cr+1), temp64, 1);
  2007. }
  2008. }
  2009. }
  2010. static inline void backup_pair_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize){
  2011. MpegEncContext * const s = &h->s;
  2012. int i;
  2013. src_y -= 2 * linesize;
  2014. src_cb -= 2 * uvlinesize;
  2015. src_cr -= 2 * uvlinesize;
  2016. // There are two lines saved, the line above the the top macroblock of a pair,
  2017. // and the line above the bottom macroblock
  2018. h->left_border[0]= h->top_borders[0][s->mb_x][15];
  2019. h->left_border[1]= h->top_borders[1][s->mb_x][15];
  2020. for(i=2; i<34; i++){
  2021. h->left_border[i]= src_y[15+i* linesize];
  2022. }
  2023. *(uint64_t*)(h->top_borders[0][s->mb_x]+0)= *(uint64_t*)(src_y + 32*linesize);
  2024. *(uint64_t*)(h->top_borders[0][s->mb_x]+8)= *(uint64_t*)(src_y +8+32*linesize);
  2025. *(uint64_t*)(h->top_borders[1][s->mb_x]+0)= *(uint64_t*)(src_y + 33*linesize);
  2026. *(uint64_t*)(h->top_borders[1][s->mb_x]+8)= *(uint64_t*)(src_y +8+33*linesize);
  2027. if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  2028. h->left_border[34 ]= h->top_borders[0][s->mb_x][16+7];
  2029. h->left_border[34+ 1]= h->top_borders[1][s->mb_x][16+7];
  2030. h->left_border[34+18 ]= h->top_borders[0][s->mb_x][24+7];
  2031. h->left_border[34+18+1]= h->top_borders[1][s->mb_x][24+7];
  2032. for(i=2; i<18; i++){
  2033. h->left_border[i+34 ]= src_cb[7+i*uvlinesize];
  2034. h->left_border[i+34+18]= src_cr[7+i*uvlinesize];
  2035. }
  2036. *(uint64_t*)(h->top_borders[0][s->mb_x]+16)= *(uint64_t*)(src_cb+16*uvlinesize);
  2037. *(uint64_t*)(h->top_borders[0][s->mb_x]+24)= *(uint64_t*)(src_cr+16*uvlinesize);
  2038. *(uint64_t*)(h->top_borders[1][s->mb_x]+16)= *(uint64_t*)(src_cb+17*uvlinesize);
  2039. *(uint64_t*)(h->top_borders[1][s->mb_x]+24)= *(uint64_t*)(src_cr+17*uvlinesize);
  2040. }
  2041. }
  2042. static inline void xchg_pair_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int xchg){
  2043. MpegEncContext * const s = &h->s;
  2044. int temp8, i;
  2045. uint64_t temp64;
  2046. int deblock_left = (s->mb_x > 0);
  2047. int deblock_top = (s->mb_y > 1);
  2048. tprintf(s->avctx, "xchg_pair_border: src_y:%p src_cb:%p src_cr:%p ls:%d uvls:%d\n", src_y, src_cb, src_cr, linesize, uvlinesize);
  2049. src_y -= 2 * linesize + 1;
  2050. src_cb -= 2 * uvlinesize + 1;
  2051. src_cr -= 2 * uvlinesize + 1;
  2052. #define XCHG(a,b,t,xchg)\
  2053. t= a;\
  2054. if(xchg)\
  2055. a= b;\
  2056. b= t;
  2057. if(deblock_left){
  2058. for(i = (!deblock_top)<<1; i<34; i++){
  2059. XCHG(h->left_border[i ], src_y [i* linesize], temp8, xchg);
  2060. }
  2061. }
  2062. if(deblock_top){
  2063. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+0), *(uint64_t*)(src_y +1), temp64, xchg);
  2064. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+8), *(uint64_t*)(src_y +9), temp64, 1);
  2065. XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+0), *(uint64_t*)(src_y +1 +linesize), temp64, xchg);
  2066. XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+8), *(uint64_t*)(src_y +9 +linesize), temp64, 1);
  2067. if(s->mb_x+1 < s->mb_width){
  2068. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x+1]), *(uint64_t*)(src_y +17), temp64, 1);
  2069. XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x+1]), *(uint64_t*)(src_y +17 +linesize), temp64, 1);
  2070. }
  2071. }
  2072. if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  2073. if(deblock_left){
  2074. for(i = (!deblock_top) << 1; i<18; i++){
  2075. XCHG(h->left_border[i+34 ], src_cb[i*uvlinesize], temp8, xchg);
  2076. XCHG(h->left_border[i+34+18], src_cr[i*uvlinesize], temp8, xchg);
  2077. }
  2078. }
  2079. if(deblock_top){
  2080. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+16), *(uint64_t*)(src_cb+1), temp64, 1);
  2081. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+24), *(uint64_t*)(src_cr+1), temp64, 1);
  2082. XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+16), *(uint64_t*)(src_cb+1 +uvlinesize), temp64, 1);
  2083. XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+24), *(uint64_t*)(src_cr+1 +uvlinesize), temp64, 1);
  2084. }
  2085. }
  2086. }
  2087. static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple){
  2088. MpegEncContext * const s = &h->s;
  2089. const int mb_x= s->mb_x;
  2090. const int mb_y= s->mb_y;
  2091. const int mb_xy= mb_x + mb_y*s->mb_stride;
  2092. const int mb_type= s->current_picture.mb_type[mb_xy];
  2093. uint8_t *dest_y, *dest_cb, *dest_cr;
  2094. int linesize, uvlinesize /*dct_offset*/;
  2095. int i;
  2096. int *block_offset = &h->block_offset[0];
  2097. const unsigned int bottom = mb_y & 1;
  2098. const int transform_bypass = (s->qscale == 0 && h->sps.transform_bypass), is_h264 = (simple || s->codec_id == CODEC_ID_H264);
  2099. void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
  2100. void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
  2101. dest_y = s->current_picture.data[0] + (mb_y * 16* s->linesize ) + mb_x * 16;
  2102. dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
  2103. dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
  2104. s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + 64, s->linesize, 4);
  2105. s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + 64, dest_cr - dest_cb, 2);
  2106. if (!simple && MB_FIELD) {
  2107. linesize = h->mb_linesize = s->linesize * 2;
  2108. uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
  2109. block_offset = &h->block_offset[24];
  2110. if(mb_y&1){ //FIXME move out of this func?
  2111. dest_y -= s->linesize*15;
  2112. dest_cb-= s->uvlinesize*7;
  2113. dest_cr-= s->uvlinesize*7;
  2114. }
  2115. if(FRAME_MBAFF) {
  2116. int list;
  2117. for(list=0; list<h->list_count; list++){
  2118. if(!USES_LIST(mb_type, list))
  2119. continue;
  2120. if(IS_16X16(mb_type)){
  2121. int8_t *ref = &h->ref_cache[list][scan8[0]];
  2122. fill_rectangle(ref, 4, 4, 8, 16+*ref^(s->mb_y&1), 1);
  2123. }else{
  2124. for(i=0; i<16; i+=4){
  2125. //FIXME can refs be smaller than 8x8 when !direct_8x8_inference ?
  2126. int ref = h->ref_cache[list][scan8[i]];
  2127. if(ref >= 0)
  2128. fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, 16+ref^(s->mb_y&1), 1);
  2129. }
  2130. }
  2131. }
  2132. }
  2133. } else {
  2134. linesize = h->mb_linesize = s->linesize;
  2135. uvlinesize = h->mb_uvlinesize = s->uvlinesize;
  2136. // dct_offset = s->linesize * 16;
  2137. }
  2138. if(transform_bypass){
  2139. idct_dc_add =
  2140. idct_add = IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
  2141. }else if(IS_8x8DCT(mb_type)){
  2142. idct_dc_add = s->dsp.h264_idct8_dc_add;
  2143. idct_add = s->dsp.h264_idct8_add;
  2144. }else{
  2145. idct_dc_add = s->dsp.h264_idct_dc_add;
  2146. idct_add = s->dsp.h264_idct_add;
  2147. }
  2148. if(!simple && FRAME_MBAFF && h->deblocking_filter && IS_INTRA(mb_type)
  2149. && (!bottom || !IS_INTRA(s->current_picture.mb_type[mb_xy-s->mb_stride]))){
  2150. int mbt_y = mb_y&~1;
  2151. uint8_t *top_y = s->current_picture.data[0] + (mbt_y * 16* s->linesize ) + mb_x * 16;
  2152. uint8_t *top_cb = s->current_picture.data[1] + (mbt_y * 8 * s->uvlinesize) + mb_x * 8;
  2153. uint8_t *top_cr = s->current_picture.data[2] + (mbt_y * 8 * s->uvlinesize) + mb_x * 8;
  2154. xchg_pair_border(h, top_y, top_cb, top_cr, s->linesize, s->uvlinesize, 1);
  2155. }
  2156. if (!simple && IS_INTRA_PCM(mb_type)) {
  2157. unsigned int x, y;
  2158. // The pixels are stored in h->mb array in the same order as levels,
  2159. // copy them in output in the correct order.
  2160. for(i=0; i<16; i++) {
  2161. for (y=0; y<4; y++) {
  2162. for (x=0; x<4; x++) {
  2163. *(dest_y + block_offset[i] + y*linesize + x) = h->mb[i*16+y*4+x];
  2164. }
  2165. }
  2166. }
  2167. for(i=16; i<16+4; i++) {
  2168. for (y=0; y<4; y++) {
  2169. for (x=0; x<4; x++) {
  2170. *(dest_cb + block_offset[i] + y*uvlinesize + x) = h->mb[i*16+y*4+x];
  2171. }
  2172. }
  2173. }
  2174. for(i=20; i<20+4; i++) {
  2175. for (y=0; y<4; y++) {
  2176. for (x=0; x<4; x++) {
  2177. *(dest_cr + block_offset[i] + y*uvlinesize + x) = h->mb[i*16+y*4+x];
  2178. }
  2179. }
  2180. }
  2181. } else {
  2182. if(IS_INTRA(mb_type)){
  2183. if(h->deblocking_filter && (simple || !FRAME_MBAFF))
  2184. xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, simple);
  2185. if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  2186. h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
  2187. h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
  2188. }
  2189. if(IS_INTRA4x4(mb_type)){
  2190. if(simple || !s->encoding){
  2191. if(IS_8x8DCT(mb_type)){
  2192. for(i=0; i<16; i+=4){
  2193. uint8_t * const ptr= dest_y + block_offset[i];
  2194. const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
  2195. const int nnz = h->non_zero_count_cache[ scan8[i] ];
  2196. h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
  2197. (h->topright_samples_available<<i)&0x4000, linesize);
  2198. if(nnz){
  2199. if(nnz == 1 && h->mb[i*16])
  2200. idct_dc_add(ptr, h->mb + i*16, linesize);
  2201. else
  2202. idct_add(ptr, h->mb + i*16, linesize);
  2203. }
  2204. }
  2205. }else
  2206. for(i=0; i<16; i++){
  2207. uint8_t * const ptr= dest_y + block_offset[i];
  2208. uint8_t *topright;
  2209. const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
  2210. int nnz, tr;
  2211. if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
  2212. const int topright_avail= (h->topright_samples_available<<i)&0x8000;
  2213. assert(mb_y || linesize <= block_offset[i]);
  2214. if(!topright_avail){
  2215. tr= ptr[3 - linesize]*0x01010101;
  2216. topright= (uint8_t*) &tr;
  2217. }else
  2218. topright= ptr + 4 - linesize;
  2219. }else
  2220. topright= NULL;
  2221. h->hpc.pred4x4[ dir ](ptr, topright, linesize);
  2222. nnz = h->non_zero_count_cache[ scan8[i] ];
  2223. if(nnz){
  2224. if(is_h264){
  2225. if(nnz == 1 && h->mb[i*16])
  2226. idct_dc_add(ptr, h->mb + i*16, linesize);
  2227. else
  2228. idct_add(ptr, h->mb + i*16, linesize);
  2229. }else
  2230. svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
  2231. }
  2232. }
  2233. }
  2234. }else{
  2235. h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
  2236. if(is_h264){
  2237. if(!transform_bypass)
  2238. h264_luma_dc_dequant_idct_c(h->mb, s->qscale, h->dequant4_coeff[0][s->qscale][0]);
  2239. }else
  2240. svq3_luma_dc_dequant_idct_c(h->mb, s->qscale);
  2241. }
  2242. if(h->deblocking_filter && (simple || !FRAME_MBAFF))
  2243. xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple);
  2244. }else if(is_h264){
  2245. hl_motion(h, dest_y, dest_cb, dest_cr,
  2246. s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
  2247. s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
  2248. s->dsp.weight_h264_pixels_tab, s->dsp.biweight_h264_pixels_tab);
  2249. }
  2250. if(!IS_INTRA4x4(mb_type)){
  2251. if(is_h264){
  2252. if(IS_INTRA16x16(mb_type)){
  2253. for(i=0; i<16; i++){
  2254. if(h->non_zero_count_cache[ scan8[i] ])
  2255. idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
  2256. else if(h->mb[i*16])
  2257. idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);
  2258. }
  2259. }else{
  2260. const int di = IS_8x8DCT(mb_type) ? 4 : 1;
  2261. for(i=0; i<16; i+=di){
  2262. int nnz = h->non_zero_count_cache[ scan8[i] ];
  2263. if(nnz){
  2264. if(nnz==1 && h->mb[i*16])
  2265. idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);
  2266. else
  2267. idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
  2268. }
  2269. }
  2270. }
  2271. }else{
  2272. for(i=0; i<16; i++){
  2273. if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
  2274. uint8_t * const ptr= dest_y + block_offset[i];
  2275. svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
  2276. }
  2277. }
  2278. }
  2279. }
  2280. if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  2281. uint8_t *dest[2] = {dest_cb, dest_cr};
  2282. if(transform_bypass){
  2283. idct_add = idct_dc_add = s->dsp.add_pixels4;
  2284. }else{
  2285. idct_add = s->dsp.h264_idct_add;
  2286. idct_dc_add = s->dsp.h264_idct_dc_add;
  2287. chroma_dc_dequant_idct_c(h->mb + 16*16, h->chroma_qp[0], h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
  2288. chroma_dc_dequant_idct_c(h->mb + 16*16+4*16, h->chroma_qp[1], h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
  2289. }
  2290. if(is_h264){
  2291. for(i=16; i<16+8; i++){
  2292. if(h->non_zero_count_cache[ scan8[i] ])
  2293. idct_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
  2294. else if(h->mb[i*16])
  2295. idct_dc_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
  2296. }
  2297. }else{
  2298. for(i=16; i<16+8; i++){
  2299. if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
  2300. uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];
  2301. svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, chroma_qp[s->qscale + 12] - 12, 2);
  2302. }
  2303. }
  2304. }
  2305. }
  2306. }
  2307. if(h->deblocking_filter) {
  2308. if (!simple && FRAME_MBAFF) {
  2309. //FIXME try deblocking one mb at a time?
  2310. // the reduction in load/storing mvs and such might outweigh the extra backup/xchg_border
  2311. const int mb_y = s->mb_y - 1;
  2312. uint8_t *pair_dest_y, *pair_dest_cb, *pair_dest_cr;
  2313. const int mb_xy= mb_x + mb_y*s->mb_stride;
  2314. const int mb_type_top = s->current_picture.mb_type[mb_xy];
  2315. const int mb_type_bottom= s->current_picture.mb_type[mb_xy+s->mb_stride];
  2316. if (!bottom) return;
  2317. pair_dest_y = s->current_picture.data[0] + (mb_y * 16* s->linesize ) + mb_x * 16;
  2318. pair_dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
  2319. pair_dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
  2320. if(IS_INTRA(mb_type_top | mb_type_bottom))
  2321. xchg_pair_border(h, pair_dest_y, pair_dest_cb, pair_dest_cr, s->linesize, s->uvlinesize, 0);
  2322. backup_pair_border(h, pair_dest_y, pair_dest_cb, pair_dest_cr, s->linesize, s->uvlinesize);
  2323. // deblock a pair
  2324. // top
  2325. s->mb_y--;
  2326. tprintf(h->s.avctx, "call mbaff filter_mb mb_x:%d mb_y:%d pair_dest_y = %p, dest_y = %p\n", mb_x, mb_y, pair_dest_y, dest_y);
  2327. fill_caches(h, mb_type_top, 1); //FIXME don't fill stuff which isn't used by filter_mb
  2328. h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
  2329. h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
  2330. filter_mb(h, mb_x, mb_y, pair_dest_y, pair_dest_cb, pair_dest_cr, linesize, uvlinesize);
  2331. // bottom
  2332. s->mb_y++;
  2333. tprintf(h->s.avctx, "call mbaff filter_mb\n");
  2334. fill_caches(h, mb_type_bottom, 1); //FIXME don't fill stuff which isn't used by filter_mb
  2335. h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy+s->mb_stride]);
  2336. h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy+s->mb_stride]);
  2337. filter_mb(h, mb_x, mb_y+1, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  2338. } else {
  2339. tprintf(h->s.avctx, "call filter_mb\n");
  2340. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, simple);
  2341. fill_caches(h, mb_type, 1); //FIXME don't fill stuff which isn't used by filter_mb
  2342. filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  2343. }
  2344. }
  2345. }
  2346. /**
  2347. * Process a macroblock; this case avoids checks for expensive uncommon cases.
  2348. */
  2349. static void hl_decode_mb_simple(H264Context *h){
  2350. hl_decode_mb_internal(h, 1);
  2351. }
  2352. /**
  2353. * Process a macroblock; this handles edge cases, such as interlacing.
  2354. */
  2355. static void av_noinline hl_decode_mb_complex(H264Context *h){
  2356. hl_decode_mb_internal(h, 0);
  2357. }
  2358. static void hl_decode_mb(H264Context *h){
  2359. MpegEncContext * const s = &h->s;
  2360. const int mb_x= s->mb_x;
  2361. const int mb_y= s->mb_y;
  2362. const int mb_xy= mb_x + mb_y*s->mb_stride;
  2363. const int mb_type= s->current_picture.mb_type[mb_xy];
  2364. int is_complex = FRAME_MBAFF || MB_FIELD || IS_INTRA_PCM(mb_type) || s->codec_id != CODEC_ID_H264 || (ENABLE_GRAY && (s->flags&CODEC_FLAG_GRAY)) || s->encoding;
  2365. if(!s->decode)
  2366. return;
  2367. if (is_complex)
  2368. hl_decode_mb_complex(h);
  2369. else hl_decode_mb_simple(h);
  2370. }
  2371. static void pic_as_field(Picture *pic, const int parity){
  2372. int i;
  2373. for (i = 0; i < 4; ++i) {
  2374. if (parity == PICT_BOTTOM_FIELD)
  2375. pic->data[i] += pic->linesize[i];
  2376. pic->reference = parity;
  2377. pic->linesize[i] *= 2;
  2378. }
  2379. }
  2380. static int split_field_copy(Picture *dest, Picture *src,
  2381. int parity, int id_add){
  2382. int match = !!(src->reference & parity);
  2383. if (match) {
  2384. *dest = *src;
  2385. pic_as_field(dest, parity);
  2386. dest->pic_id *= 2;
  2387. dest->pic_id += id_add;
  2388. }
  2389. return match;
  2390. }
  2391. /**
  2392. * Split one reference list into field parts, interleaving by parity
  2393. * as per H.264 spec section 8.2.4.2.5. Output fields have their data pointers
  2394. * set to look at the actual start of data for that field.
  2395. *
  2396. * @param dest output list
  2397. * @param dest_len maximum number of fields to put in dest
  2398. * @param src the source reference list containing fields and/or field pairs
  2399. * (aka short_ref/long_ref, or
  2400. * refFrameListXShortTerm/refFrameListLongTerm in spec-speak)
  2401. * @param src_len number of Picture's in source (pairs and unmatched fields)
  2402. * @param parity the parity of the picture being decoded/needing
  2403. * these ref pics (PICT_{TOP,BOTTOM}_FIELD)
  2404. * @return number of fields placed in dest
  2405. */
  2406. static int split_field_half_ref_list(Picture *dest, int dest_len,
  2407. Picture *src, int src_len, int parity){
  2408. int same_parity = 1;
  2409. int same_i = 0;
  2410. int opp_i = 0;
  2411. int out_i;
  2412. int field_output;
  2413. for (out_i = 0; out_i < dest_len; out_i += field_output) {
  2414. if (same_parity && same_i < src_len) {
  2415. field_output = split_field_copy(dest + out_i, src + same_i,
  2416. parity, 1);
  2417. same_parity = !field_output;
  2418. same_i++;
  2419. } else if (opp_i < src_len) {
  2420. field_output = split_field_copy(dest + out_i, src + opp_i,
  2421. PICT_FRAME - parity, 0);
  2422. same_parity = field_output;
  2423. opp_i++;
  2424. } else {
  2425. break;
  2426. }
  2427. }
  2428. return out_i;
  2429. }
  2430. /**
  2431. * Split the reference frame list into a reference field list.
  2432. * This implements H.264 spec 8.2.4.2.5 for a combined input list.
  2433. * The input list contains both reference field pairs and
  2434. * unmatched reference fields; it is ordered as spec describes
  2435. * RefPicListX for frames in 8.2.4.2.1 and 8.2.4.2.3, except that
  2436. * unmatched field pairs are also present. Conceptually this is equivalent
  2437. * to concatenation of refFrameListXShortTerm with refFrameListLongTerm.
  2438. *
  2439. * @param dest output reference list where ordered fields are to be placed
  2440. * @param dest_len max number of fields to place at dest
  2441. * @param src source reference list, as described above
  2442. * @param src_len number of pictures (pairs and unmatched fields) in src
  2443. * @param parity parity of field being currently decoded
  2444. * (one of PICT_{TOP,BOTTOM}_FIELD)
  2445. * @param long_i index into src array that holds first long reference picture,
  2446. * or src_len if no long refs present.
  2447. */
  2448. static int split_field_ref_list(Picture *dest, int dest_len,
  2449. Picture *src, int src_len,
  2450. int parity, int long_i){
  2451. int i = split_field_half_ref_list(dest, dest_len, src, long_i, parity);
  2452. dest += i;
  2453. dest_len -= i;
  2454. i += split_field_half_ref_list(dest, dest_len, src + long_i,
  2455. src_len - long_i, parity);
  2456. return i;
  2457. }
  2458. /**
  2459. * fills the default_ref_list.
  2460. */
  2461. static int fill_default_ref_list(H264Context *h){
  2462. MpegEncContext * const s = &h->s;
  2463. int i;
  2464. int smallest_poc_greater_than_current = -1;
  2465. int structure_sel;
  2466. Picture sorted_short_ref[32];
  2467. Picture field_entry_list[2][32];
  2468. Picture *frame_list[2];
  2469. if (FIELD_PICTURE) {
  2470. structure_sel = PICT_FRAME;
  2471. frame_list[0] = field_entry_list[0];
  2472. frame_list[1] = field_entry_list[1];
  2473. } else {
  2474. structure_sel = 0;
  2475. frame_list[0] = h->default_ref_list[0];
  2476. frame_list[1] = h->default_ref_list[1];
  2477. }
  2478. if(h->slice_type==B_TYPE){
  2479. int list;
  2480. int len[2];
  2481. int short_len[2];
  2482. int out_i;
  2483. int limit= INT_MIN;
  2484. /* sort frame according to poc in B slice */
  2485. for(out_i=0; out_i<h->short_ref_count; out_i++){
  2486. int best_i=INT_MIN;
  2487. int best_poc=INT_MAX;
  2488. for(i=0; i<h->short_ref_count; i++){
  2489. const int poc= h->short_ref[i]->poc;
  2490. if(poc > limit && poc < best_poc){
  2491. best_poc= poc;
  2492. best_i= i;
  2493. }
  2494. }
  2495. assert(best_i != INT_MIN);
  2496. limit= best_poc;
  2497. sorted_short_ref[out_i]= *h->short_ref[best_i];
  2498. tprintf(h->s.avctx, "sorted poc: %d->%d poc:%d fn:%d\n", best_i, out_i, sorted_short_ref[out_i].poc, sorted_short_ref[out_i].frame_num);
  2499. if (-1 == smallest_poc_greater_than_current) {
  2500. if (h->short_ref[best_i]->poc >= s->current_picture_ptr->poc) {
  2501. smallest_poc_greater_than_current = out_i;
  2502. }
  2503. }
  2504. }
  2505. tprintf(h->s.avctx, "current poc: %d, smallest_poc_greater_than_current: %d\n", s->current_picture_ptr->poc, smallest_poc_greater_than_current);
  2506. // find the largest poc
  2507. for(list=0; list<2; list++){
  2508. int index = 0;
  2509. int j= -99;
  2510. int step= list ? -1 : 1;
  2511. for(i=0; i<h->short_ref_count && index < h->ref_count[list]; i++, j+=step) {
  2512. int sel;
  2513. while(j<0 || j>= h->short_ref_count){
  2514. if(j != -99 && step == (list ? -1 : 1))
  2515. return -1;
  2516. step = -step;
  2517. j= smallest_poc_greater_than_current + (step>>1);
  2518. }
  2519. sel = sorted_short_ref[j].reference | structure_sel;
  2520. if(sel != PICT_FRAME) continue;
  2521. frame_list[list][index ]= sorted_short_ref[j];
  2522. frame_list[list][index++].pic_id= sorted_short_ref[j].frame_num;
  2523. }
  2524. short_len[list] = index;
  2525. for(i = 0; i < 16 && index < h->ref_count[ list ]; i++){
  2526. int sel;
  2527. if(h->long_ref[i] == NULL) continue;
  2528. sel = h->long_ref[i]->reference | structure_sel;
  2529. if(sel != PICT_FRAME) continue;
  2530. frame_list[ list ][index ]= *h->long_ref[i];
  2531. frame_list[ list ][index++].pic_id= i;;
  2532. }
  2533. len[list] = index;
  2534. if(list && (smallest_poc_greater_than_current<=0 || smallest_poc_greater_than_current>=h->short_ref_count) && (1 < index)){
  2535. // swap the two first elements of L1 when
  2536. // L0 and L1 are identical
  2537. Picture temp= frame_list[1][0];
  2538. frame_list[1][0] = frame_list[1][1];
  2539. frame_list[1][1] = temp;
  2540. }
  2541. }
  2542. for(list=0; list<2; list++){
  2543. if (FIELD_PICTURE)
  2544. len[list] = split_field_ref_list(h->default_ref_list[list],
  2545. h->ref_count[list],
  2546. frame_list[list],
  2547. len[list],
  2548. s->picture_structure,
  2549. short_len[list]);
  2550. if(len[list] < h->ref_count[ list ])
  2551. memset(&h->default_ref_list[list][len[list]], 0, sizeof(Picture)*(h->ref_count[ list ] - len[list]));
  2552. }
  2553. }else{
  2554. int index=0;
  2555. int short_len;
  2556. for(i=0; i<h->short_ref_count; i++){
  2557. int sel;
  2558. sel = h->short_ref[i]->reference | structure_sel;
  2559. if(sel != PICT_FRAME) continue;
  2560. frame_list[0][index ]= *h->short_ref[i];
  2561. frame_list[0][index++].pic_id= h->short_ref[i]->frame_num;
  2562. }
  2563. short_len = index;
  2564. for(i = 0; i < 16; i++){
  2565. int sel;
  2566. if(h->long_ref[i] == NULL) continue;
  2567. sel = h->long_ref[i]->reference | structure_sel;
  2568. if(sel != PICT_FRAME) continue;
  2569. frame_list[0][index ]= *h->long_ref[i];
  2570. frame_list[0][index++].pic_id= i;;
  2571. }
  2572. if (FIELD_PICTURE)
  2573. index = split_field_ref_list(h->default_ref_list[0],
  2574. h->ref_count[0], frame_list[0],
  2575. index, s->picture_structure,
  2576. short_len);
  2577. if(index < h->ref_count[0])
  2578. memset(&h->default_ref_list[0][index], 0, sizeof(Picture)*(h->ref_count[0] - index));
  2579. }
  2580. #ifdef TRACE
  2581. for (i=0; i<h->ref_count[0]; i++) {
  2582. tprintf(h->s.avctx, "List0: %s fn:%d 0x%p\n", (h->default_ref_list[0][i].long_ref ? "LT" : "ST"), h->default_ref_list[0][i].pic_id, h->default_ref_list[0][i].data[0]);
  2583. }
  2584. if(h->slice_type==B_TYPE){
  2585. for (i=0; i<h->ref_count[1]; i++) {
  2586. tprintf(h->s.avctx, "List1: %s fn:%d 0x%p\n", (h->default_ref_list[1][i].long_ref ? "LT" : "ST"), h->default_ref_list[1][i].pic_id, h->default_ref_list[0][i].data[0]);
  2587. }
  2588. }
  2589. #endif
  2590. return 0;
  2591. }
  2592. static void print_short_term(H264Context *h);
  2593. static void print_long_term(H264Context *h);
  2594. /**
  2595. * Extract structure information about the picture described by pic_num in
  2596. * the current decoding context (frame or field). Note that pic_num is
  2597. * picture number without wrapping (so, 0<=pic_num<max_pic_num).
  2598. * @param pic_num picture number for which to extract structure information
  2599. * @param structure one of PICT_XXX describing structure of picture
  2600. * with pic_num
  2601. * @return frame number (short term) or long term index of picture
  2602. * described by pic_num
  2603. */
  2604. static int pic_num_extract(H264Context *h, int pic_num, int *structure){
  2605. MpegEncContext * const s = &h->s;
  2606. *structure = s->picture_structure;
  2607. if(FIELD_PICTURE){
  2608. if (!(pic_num & 1))
  2609. /* opposite field */
  2610. *structure ^= PICT_FRAME;
  2611. pic_num >>= 1;
  2612. }
  2613. return pic_num;
  2614. }
  2615. static int decode_ref_pic_list_reordering(H264Context *h){
  2616. MpegEncContext * const s = &h->s;
  2617. int list, index, pic_structure;
  2618. print_short_term(h);
  2619. print_long_term(h);
  2620. if(h->slice_type==I_TYPE || h->slice_type==SI_TYPE) return 0; //FIXME move before func
  2621. for(list=0; list<h->list_count; list++){
  2622. memcpy(h->ref_list[list], h->default_ref_list[list], sizeof(Picture)*h->ref_count[list]);
  2623. if(get_bits1(&s->gb)){
  2624. int pred= h->curr_pic_num;
  2625. for(index=0; ; index++){
  2626. unsigned int reordering_of_pic_nums_idc= get_ue_golomb(&s->gb);
  2627. unsigned int pic_id;
  2628. int i;
  2629. Picture *ref = NULL;
  2630. if(reordering_of_pic_nums_idc==3)
  2631. break;
  2632. if(index >= h->ref_count[list]){
  2633. av_log(h->s.avctx, AV_LOG_ERROR, "reference count overflow\n");
  2634. return -1;
  2635. }
  2636. if(reordering_of_pic_nums_idc<3){
  2637. if(reordering_of_pic_nums_idc<2){
  2638. const unsigned int abs_diff_pic_num= get_ue_golomb(&s->gb) + 1;
  2639. int frame_num;
  2640. if(abs_diff_pic_num > h->max_pic_num){
  2641. av_log(h->s.avctx, AV_LOG_ERROR, "abs_diff_pic_num overflow\n");
  2642. return -1;
  2643. }
  2644. if(reordering_of_pic_nums_idc == 0) pred-= abs_diff_pic_num;
  2645. else pred+= abs_diff_pic_num;
  2646. pred &= h->max_pic_num - 1;
  2647. frame_num = pic_num_extract(h, pred, &pic_structure);
  2648. for(i= h->short_ref_count-1; i>=0; i--){
  2649. ref = h->short_ref[i];
  2650. assert(ref->reference);
  2651. assert(!ref->long_ref);
  2652. if(ref->data[0] != NULL &&
  2653. ref->frame_num == frame_num &&
  2654. (ref->reference & pic_structure) &&
  2655. ref->long_ref == 0) // ignore non existing pictures by testing data[0] pointer
  2656. break;
  2657. }
  2658. if(i>=0)
  2659. ref->pic_id= pred;
  2660. }else{
  2661. int long_idx;
  2662. pic_id= get_ue_golomb(&s->gb); //long_term_pic_idx
  2663. long_idx= pic_num_extract(h, pic_id, &pic_structure);
  2664. if(long_idx>31){
  2665. av_log(h->s.avctx, AV_LOG_ERROR, "long_term_pic_idx overflow\n");
  2666. return -1;
  2667. }
  2668. ref = h->long_ref[long_idx];
  2669. assert(!(ref && !ref->reference));
  2670. if(ref && (ref->reference & pic_structure)){
  2671. ref->pic_id= pic_id;
  2672. assert(ref->long_ref);
  2673. i=0;
  2674. }else{
  2675. i=-1;
  2676. }
  2677. }
  2678. if (i < 0) {
  2679. av_log(h->s.avctx, AV_LOG_ERROR, "reference picture missing during reorder\n");
  2680. memset(&h->ref_list[list][index], 0, sizeof(Picture)); //FIXME
  2681. } else {
  2682. for(i=index; i+1<h->ref_count[list]; i++){
  2683. if(ref->long_ref == h->ref_list[list][i].long_ref && ref->pic_id == h->ref_list[list][i].pic_id)
  2684. break;
  2685. }
  2686. for(; i > index; i--){
  2687. h->ref_list[list][i]= h->ref_list[list][i-1];
  2688. }
  2689. h->ref_list[list][index]= *ref;
  2690. if (FIELD_PICTURE){
  2691. pic_as_field(&h->ref_list[list][index], pic_structure);
  2692. }
  2693. }
  2694. }else{
  2695. av_log(h->s.avctx, AV_LOG_ERROR, "illegal reordering_of_pic_nums_idc\n");
  2696. return -1;
  2697. }
  2698. }
  2699. }
  2700. }
  2701. for(list=0; list<h->list_count; list++){
  2702. for(index= 0; index < h->ref_count[list]; index++){
  2703. if(!h->ref_list[list][index].data[0])
  2704. h->ref_list[list][index]= s->current_picture;
  2705. }
  2706. }
  2707. if(h->slice_type==B_TYPE && !h->direct_spatial_mv_pred)
  2708. direct_dist_scale_factor(h);
  2709. direct_ref_list_init(h);
  2710. return 0;
  2711. }
  2712. static void fill_mbaff_ref_list(H264Context *h){
  2713. int list, i, j;
  2714. for(list=0; list<2; list++){ //FIXME try list_count
  2715. for(i=0; i<h->ref_count[list]; i++){
  2716. Picture *frame = &h->ref_list[list][i];
  2717. Picture *field = &h->ref_list[list][16+2*i];
  2718. field[0] = *frame;
  2719. for(j=0; j<3; j++)
  2720. field[0].linesize[j] <<= 1;
  2721. field[0].reference = PICT_TOP_FIELD;
  2722. field[1] = field[0];
  2723. for(j=0; j<3; j++)
  2724. field[1].data[j] += frame->linesize[j];
  2725. field[1].reference = PICT_BOTTOM_FIELD;
  2726. h->luma_weight[list][16+2*i] = h->luma_weight[list][16+2*i+1] = h->luma_weight[list][i];
  2727. h->luma_offset[list][16+2*i] = h->luma_offset[list][16+2*i+1] = h->luma_offset[list][i];
  2728. for(j=0; j<2; j++){
  2729. h->chroma_weight[list][16+2*i][j] = h->chroma_weight[list][16+2*i+1][j] = h->chroma_weight[list][i][j];
  2730. h->chroma_offset[list][16+2*i][j] = h->chroma_offset[list][16+2*i+1][j] = h->chroma_offset[list][i][j];
  2731. }
  2732. }
  2733. }
  2734. for(j=0; j<h->ref_count[1]; j++){
  2735. for(i=0; i<h->ref_count[0]; i++)
  2736. h->implicit_weight[j][16+2*i] = h->implicit_weight[j][16+2*i+1] = h->implicit_weight[j][i];
  2737. memcpy(h->implicit_weight[16+2*j], h->implicit_weight[j], sizeof(*h->implicit_weight));
  2738. memcpy(h->implicit_weight[16+2*j+1], h->implicit_weight[j], sizeof(*h->implicit_weight));
  2739. }
  2740. }
  2741. static int pred_weight_table(H264Context *h){
  2742. MpegEncContext * const s = &h->s;
  2743. int list, i;
  2744. int luma_def, chroma_def;
  2745. h->use_weight= 0;
  2746. h->use_weight_chroma= 0;
  2747. h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
  2748. h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
  2749. luma_def = 1<<h->luma_log2_weight_denom;
  2750. chroma_def = 1<<h->chroma_log2_weight_denom;
  2751. for(list=0; list<2; list++){
  2752. for(i=0; i<h->ref_count[list]; i++){
  2753. int luma_weight_flag, chroma_weight_flag;
  2754. luma_weight_flag= get_bits1(&s->gb);
  2755. if(luma_weight_flag){
  2756. h->luma_weight[list][i]= get_se_golomb(&s->gb);
  2757. h->luma_offset[list][i]= get_se_golomb(&s->gb);
  2758. if( h->luma_weight[list][i] != luma_def
  2759. || h->luma_offset[list][i] != 0)
  2760. h->use_weight= 1;
  2761. }else{
  2762. h->luma_weight[list][i]= luma_def;
  2763. h->luma_offset[list][i]= 0;
  2764. }
  2765. chroma_weight_flag= get_bits1(&s->gb);
  2766. if(chroma_weight_flag){
  2767. int j;
  2768. for(j=0; j<2; j++){
  2769. h->chroma_weight[list][i][j]= get_se_golomb(&s->gb);
  2770. h->chroma_offset[list][i][j]= get_se_golomb(&s->gb);
  2771. if( h->chroma_weight[list][i][j] != chroma_def
  2772. || h->chroma_offset[list][i][j] != 0)
  2773. h->use_weight_chroma= 1;
  2774. }
  2775. }else{
  2776. int j;
  2777. for(j=0; j<2; j++){
  2778. h->chroma_weight[list][i][j]= chroma_def;
  2779. h->chroma_offset[list][i][j]= 0;
  2780. }
  2781. }
  2782. }
  2783. if(h->slice_type != B_TYPE) break;
  2784. }
  2785. h->use_weight= h->use_weight || h->use_weight_chroma;
  2786. return 0;
  2787. }
  2788. static void implicit_weight_table(H264Context *h){
  2789. MpegEncContext * const s = &h->s;
  2790. int ref0, ref1;
  2791. int cur_poc = s->current_picture_ptr->poc;
  2792. if( h->ref_count[0] == 1 && h->ref_count[1] == 1
  2793. && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
  2794. h->use_weight= 0;
  2795. h->use_weight_chroma= 0;
  2796. return;
  2797. }
  2798. h->use_weight= 2;
  2799. h->use_weight_chroma= 2;
  2800. h->luma_log2_weight_denom= 5;
  2801. h->chroma_log2_weight_denom= 5;
  2802. for(ref0=0; ref0 < h->ref_count[0]; ref0++){
  2803. int poc0 = h->ref_list[0][ref0].poc;
  2804. for(ref1=0; ref1 < h->ref_count[1]; ref1++){
  2805. int poc1 = h->ref_list[1][ref1].poc;
  2806. int td = av_clip(poc1 - poc0, -128, 127);
  2807. if(td){
  2808. int tb = av_clip(cur_poc - poc0, -128, 127);
  2809. int tx = (16384 + (FFABS(td) >> 1)) / td;
  2810. int dist_scale_factor = av_clip((tb*tx + 32) >> 6, -1024, 1023) >> 2;
  2811. if(dist_scale_factor < -64 || dist_scale_factor > 128)
  2812. h->implicit_weight[ref0][ref1] = 32;
  2813. else
  2814. h->implicit_weight[ref0][ref1] = 64 - dist_scale_factor;
  2815. }else
  2816. h->implicit_weight[ref0][ref1] = 32;
  2817. }
  2818. }
  2819. }
  2820. /**
  2821. * Mark a picture as no longer needed for reference. The refmask
  2822. * argument allows unreferencing of individual fields or the whole frame.
  2823. * If the picture becomes entirely unreferenced, but is being held for
  2824. * display purposes, it is marked as such.
  2825. * @param refmask mask of fields to unreference; the mask is bitwise
  2826. * anded with the reference marking of pic
  2827. * @return non-zero if pic becomes entirely unreferenced (except possibly
  2828. * for display purposes) zero if one of the fields remains in
  2829. * reference
  2830. */
  2831. static inline int unreference_pic(H264Context *h, Picture *pic, int refmask){
  2832. int i;
  2833. if (pic->reference &= refmask) {
  2834. return 0;
  2835. } else {
  2836. if(pic == h->delayed_output_pic)
  2837. pic->reference=DELAYED_PIC_REF;
  2838. else{
  2839. for(i = 0; h->delayed_pic[i]; i++)
  2840. if(pic == h->delayed_pic[i]){
  2841. pic->reference=DELAYED_PIC_REF;
  2842. break;
  2843. }
  2844. }
  2845. return 1;
  2846. }
  2847. }
  2848. /**
  2849. * instantaneous decoder refresh.
  2850. */
  2851. static void idr(H264Context *h){
  2852. int i;
  2853. for(i=0; i<16; i++){
  2854. if (h->long_ref[i] != NULL) {
  2855. unreference_pic(h, h->long_ref[i], 0);
  2856. h->long_ref[i]= NULL;
  2857. }
  2858. }
  2859. h->long_ref_count=0;
  2860. for(i=0; i<h->short_ref_count; i++){
  2861. unreference_pic(h, h->short_ref[i], 0);
  2862. h->short_ref[i]= NULL;
  2863. }
  2864. h->short_ref_count=0;
  2865. }
  2866. /* forget old pics after a seek */
  2867. static void flush_dpb(AVCodecContext *avctx){
  2868. H264Context *h= avctx->priv_data;
  2869. int i;
  2870. for(i=0; i<16; i++) {
  2871. if(h->delayed_pic[i])
  2872. h->delayed_pic[i]->reference= 0;
  2873. h->delayed_pic[i]= NULL;
  2874. }
  2875. if(h->delayed_output_pic)
  2876. h->delayed_output_pic->reference= 0;
  2877. h->delayed_output_pic= NULL;
  2878. idr(h);
  2879. if(h->s.current_picture_ptr)
  2880. h->s.current_picture_ptr->reference= 0;
  2881. h->s.first_field= 0;
  2882. ff_mpeg_flush(avctx);
  2883. }
  2884. /**
  2885. * Find a Picture in the short term reference list by frame number.
  2886. * @param frame_num frame number to search for
  2887. * @param idx the index into h->short_ref where returned picture is found
  2888. * undefined if no picture found.
  2889. * @return pointer to the found picture, or NULL if no pic with the provided
  2890. * frame number is found
  2891. */
  2892. static Picture * find_short(H264Context *h, int frame_num, int *idx){
  2893. MpegEncContext * const s = &h->s;
  2894. int i;
  2895. for(i=0; i<h->short_ref_count; i++){
  2896. Picture *pic= h->short_ref[i];
  2897. if(s->avctx->debug&FF_DEBUG_MMCO)
  2898. av_log(h->s.avctx, AV_LOG_DEBUG, "%d %d %p\n", i, pic->frame_num, pic);
  2899. if(pic->frame_num == frame_num) {
  2900. *idx = i;
  2901. return pic;
  2902. }
  2903. }
  2904. return NULL;
  2905. }
  2906. /**
  2907. * Remove a picture from the short term reference list by its index in
  2908. * that list. This does no checking on the provided index; it is assumed
  2909. * to be valid. Other list entries are shifted down.
  2910. * @param i index into h->short_ref of picture to remove.
  2911. */
  2912. static void remove_short_at_index(H264Context *h, int i){
  2913. assert(i > 0 && i < h->short_ref_count);
  2914. h->short_ref[i]= NULL;
  2915. if (--h->short_ref_count)
  2916. memmove(&h->short_ref[i], &h->short_ref[i+1], (h->short_ref_count - i)*sizeof(Picture*));
  2917. }
  2918. /**
  2919. *
  2920. * @return the removed picture or NULL if an error occurs
  2921. */
  2922. static Picture * remove_short(H264Context *h, int frame_num){
  2923. MpegEncContext * const s = &h->s;
  2924. Picture *pic;
  2925. int i;
  2926. if(s->avctx->debug&FF_DEBUG_MMCO)
  2927. av_log(h->s.avctx, AV_LOG_DEBUG, "remove short %d count %d\n", frame_num, h->short_ref_count);
  2928. pic = find_short(h, frame_num, &i);
  2929. if (pic)
  2930. remove_short_at_index(h, i);
  2931. return pic;
  2932. }
  2933. /**
  2934. * Remove a picture from the long term reference list by its index in
  2935. * that list. This does no checking on the provided index; it is assumed
  2936. * to be valid. The removed entry is set to NULL. Other entries are unaffected.
  2937. * @param i index into h->long_ref of picture to remove.
  2938. */
  2939. static void remove_long_at_index(H264Context *h, int i){
  2940. h->long_ref[i]= NULL;
  2941. h->long_ref_count--;
  2942. }
  2943. /**
  2944. *
  2945. * @return the removed picture or NULL if an error occurs
  2946. */
  2947. static Picture * remove_long(H264Context *h, int i){
  2948. Picture *pic;
  2949. pic= h->long_ref[i];
  2950. if (pic)
  2951. remove_long_at_index(h, i);
  2952. return pic;
  2953. }
  2954. /**
  2955. * print short term list
  2956. */
  2957. static void print_short_term(H264Context *h) {
  2958. uint32_t i;
  2959. if(h->s.avctx->debug&FF_DEBUG_MMCO) {
  2960. av_log(h->s.avctx, AV_LOG_DEBUG, "short term list:\n");
  2961. for(i=0; i<h->short_ref_count; i++){
  2962. Picture *pic= h->short_ref[i];
  2963. av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
  2964. }
  2965. }
  2966. }
  2967. /**
  2968. * print long term list
  2969. */
  2970. static void print_long_term(H264Context *h) {
  2971. uint32_t i;
  2972. if(h->s.avctx->debug&FF_DEBUG_MMCO) {
  2973. av_log(h->s.avctx, AV_LOG_DEBUG, "long term list:\n");
  2974. for(i = 0; i < 16; i++){
  2975. Picture *pic= h->long_ref[i];
  2976. if (pic) {
  2977. av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
  2978. }
  2979. }
  2980. }
  2981. }
  2982. /**
  2983. * Executes the reference picture marking (memory management control operations).
  2984. */
  2985. static int execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count){
  2986. MpegEncContext * const s = &h->s;
  2987. int i, j;
  2988. int current_ref_assigned=0;
  2989. Picture *pic;
  2990. if((s->avctx->debug&FF_DEBUG_MMCO) && mmco_count==0)
  2991. av_log(h->s.avctx, AV_LOG_DEBUG, "no mmco here\n");
  2992. for(i=0; i<mmco_count; i++){
  2993. int structure, frame_num, unref_pic;
  2994. if(s->avctx->debug&FF_DEBUG_MMCO)
  2995. av_log(h->s.avctx, AV_LOG_DEBUG, "mmco:%d %d %d\n", h->mmco[i].opcode, h->mmco[i].short_pic_num, h->mmco[i].long_arg);
  2996. switch(mmco[i].opcode){
  2997. case MMCO_SHORT2UNUSED:
  2998. if(s->avctx->debug&FF_DEBUG_MMCO)
  2999. av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref short %d count %d\n", h->mmco[i].short_pic_num, h->short_ref_count);
  3000. frame_num = pic_num_extract(h, mmco[i].short_pic_num, &structure);
  3001. pic = find_short(h, frame_num, &j);
  3002. if (pic) {
  3003. if (unreference_pic(h, pic, structure ^ PICT_FRAME))
  3004. remove_short_at_index(h, j);
  3005. } else if(s->avctx->debug&FF_DEBUG_MMCO)
  3006. av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref short failure\n");
  3007. break;
  3008. case MMCO_SHORT2LONG:
  3009. if (FIELD_PICTURE && mmco[i].long_arg < h->long_ref_count &&
  3010. h->long_ref[mmco[i].long_arg]->frame_num ==
  3011. mmco[i].short_pic_num / 2) {
  3012. /* do nothing, we've already moved this field pair. */
  3013. } else {
  3014. int frame_num = mmco[i].short_pic_num >> FIELD_PICTURE;
  3015. pic= remove_long(h, mmco[i].long_arg);
  3016. if(pic) unreference_pic(h, pic, 0);
  3017. h->long_ref[ mmco[i].long_arg ]= remove_short(h, frame_num);
  3018. if (h->long_ref[ mmco[i].long_arg ]){
  3019. h->long_ref[ mmco[i].long_arg ]->long_ref=1;
  3020. h->long_ref_count++;
  3021. }
  3022. }
  3023. break;
  3024. case MMCO_LONG2UNUSED:
  3025. j = pic_num_extract(h, mmco[i].long_arg, &structure);
  3026. pic = h->long_ref[j];
  3027. if (pic) {
  3028. if (unreference_pic(h, pic, structure ^ PICT_FRAME))
  3029. remove_long_at_index(h, j);
  3030. } else if(s->avctx->debug&FF_DEBUG_MMCO)
  3031. av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref long failure\n");
  3032. break;
  3033. case MMCO_LONG:
  3034. unref_pic = 1;
  3035. if (FIELD_PICTURE && !s->first_field) {
  3036. if (h->long_ref[mmco[i].long_arg] == s->current_picture_ptr) {
  3037. /* Just mark second field as referenced */
  3038. unref_pic = 0;
  3039. } else if (s->current_picture_ptr->reference) {
  3040. /* First field in pair is in short term list or
  3041. * at a different long term index.
  3042. * This is not allowed; see 7.4.3, notes 2 and 3.
  3043. * Report the problem and keep the pair where it is,
  3044. * and mark this field valid.
  3045. */
  3046. av_log(h->s.avctx, AV_LOG_ERROR,
  3047. "illegal long term reference assignment for second "
  3048. "field in complementary field pair (first field is "
  3049. "short term or has non-matching long index)\n");
  3050. unref_pic = 0;
  3051. }
  3052. }
  3053. if (unref_pic) {
  3054. pic= remove_long(h, mmco[i].long_arg);
  3055. if(pic) unreference_pic(h, pic, 0);
  3056. h->long_ref[ mmco[i].long_arg ]= s->current_picture_ptr;
  3057. h->long_ref[ mmco[i].long_arg ]->long_ref=1;
  3058. h->long_ref_count++;
  3059. }
  3060. s->current_picture_ptr->reference |= s->picture_structure;
  3061. current_ref_assigned=1;
  3062. break;
  3063. case MMCO_SET_MAX_LONG:
  3064. assert(mmco[i].long_arg <= 16);
  3065. // just remove the long term which index is greater than new max
  3066. for(j = mmco[i].long_arg; j<16; j++){
  3067. pic = remove_long(h, j);
  3068. if (pic) unreference_pic(h, pic, 0);
  3069. }
  3070. break;
  3071. case MMCO_RESET:
  3072. while(h->short_ref_count){
  3073. pic= remove_short(h, h->short_ref[0]->frame_num);
  3074. if(pic) unreference_pic(h, pic, 0);
  3075. }
  3076. for(j = 0; j < 16; j++) {
  3077. pic= remove_long(h, j);
  3078. if(pic) unreference_pic(h, pic, 0);
  3079. }
  3080. break;
  3081. default: assert(0);
  3082. }
  3083. }
  3084. if (!current_ref_assigned && FIELD_PICTURE &&
  3085. !s->first_field && s->current_picture_ptr->reference) {
  3086. /* Second field of complementary field pair; the first field of
  3087. * which is already referenced. If short referenced, it
  3088. * should be first entry in short_ref. If not, it must exist
  3089. * in long_ref; trying to put it on the short list here is an
  3090. * error in the encoded bit stream (ref: 7.4.3, NOTE 2 and 3).
  3091. */
  3092. if (h->short_ref_count && h->short_ref[0] == s->current_picture_ptr) {
  3093. /* Just mark the second field valid */
  3094. s->current_picture_ptr->reference = PICT_FRAME;
  3095. } else if (s->current_picture_ptr->long_ref) {
  3096. av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term reference "
  3097. "assignment for second field "
  3098. "in complementary field pair "
  3099. "(first field is long term)\n");
  3100. } else {
  3101. /*
  3102. * First field in reference, but not in any sensible place on our
  3103. * reference lists. This shouldn't happen unless reference
  3104. * handling somewhere else is wrong.
  3105. */
  3106. assert(0);
  3107. }
  3108. current_ref_assigned = 1;
  3109. }
  3110. if(!current_ref_assigned){
  3111. pic= remove_short(h, s->current_picture_ptr->frame_num);
  3112. if(pic){
  3113. unreference_pic(h, pic, 0);
  3114. av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term buffer state detected\n");
  3115. }
  3116. if(h->short_ref_count)
  3117. memmove(&h->short_ref[1], &h->short_ref[0], h->short_ref_count*sizeof(Picture*));
  3118. h->short_ref[0]= s->current_picture_ptr;
  3119. h->short_ref[0]->long_ref=0;
  3120. h->short_ref_count++;
  3121. s->current_picture_ptr->reference |= s->picture_structure;
  3122. }
  3123. if (h->long_ref_count + h->short_ref_count > h->sps.ref_frame_count){
  3124. /* We have too many reference frames, probably due to corrupted
  3125. * stream. Need to discard one frame. Prevents overrun of the
  3126. * short_ref and long_ref buffers.
  3127. */
  3128. av_log(h->s.avctx, AV_LOG_ERROR,
  3129. "number of reference frames exceeds max (probably "
  3130. "corrupt input), discarding one\n");
  3131. if (h->long_ref_count) {
  3132. for (i = 0; i < 16; ++i)
  3133. if (h->long_ref[i])
  3134. break;
  3135. assert(i < 16);
  3136. pic = h->long_ref[i];
  3137. remove_long_at_index(h, i);
  3138. } else {
  3139. pic = h->short_ref[h->short_ref_count - 1];
  3140. remove_short_at_index(h, h->short_ref_count - 1);
  3141. }
  3142. unreference_pic(h, pic, 0);
  3143. }
  3144. print_short_term(h);
  3145. print_long_term(h);
  3146. return 0;
  3147. }
  3148. static int decode_ref_pic_marking(H264Context *h, GetBitContext *gb){
  3149. MpegEncContext * const s = &h->s;
  3150. int i;
  3151. if(h->nal_unit_type == NAL_IDR_SLICE){ //FIXME fields
  3152. s->broken_link= get_bits1(gb) -1;
  3153. h->mmco[0].long_arg= get_bits1(gb) - 1; // current_long_term_idx
  3154. if(h->mmco[0].long_arg == -1)
  3155. h->mmco_index= 0;
  3156. else{
  3157. h->mmco[0].opcode= MMCO_LONG;
  3158. h->mmco_index= 1;
  3159. }
  3160. }else{
  3161. if(get_bits1(gb)){ // adaptive_ref_pic_marking_mode_flag
  3162. for(i= 0; i<MAX_MMCO_COUNT; i++) {
  3163. MMCOOpcode opcode= get_ue_golomb(gb);
  3164. h->mmco[i].opcode= opcode;
  3165. if(opcode==MMCO_SHORT2UNUSED || opcode==MMCO_SHORT2LONG){
  3166. h->mmco[i].short_pic_num= (h->curr_pic_num - get_ue_golomb(gb) - 1) & (h->max_pic_num - 1);
  3167. /* if(h->mmco[i].short_pic_num >= h->short_ref_count || h->short_ref[ h->mmco[i].short_pic_num ] == NULL){
  3168. av_log(s->avctx, AV_LOG_ERROR, "illegal short ref in memory management control operation %d\n", mmco);
  3169. return -1;
  3170. }*/
  3171. }
  3172. if(opcode==MMCO_SHORT2LONG || opcode==MMCO_LONG2UNUSED || opcode==MMCO_LONG || opcode==MMCO_SET_MAX_LONG){
  3173. unsigned int long_arg= get_ue_golomb(gb);
  3174. if(long_arg >= 32 || (long_arg >= 16 && !(opcode == MMCO_LONG2UNUSED && FIELD_PICTURE))){
  3175. av_log(h->s.avctx, AV_LOG_ERROR, "illegal long ref in memory management control operation %d\n", opcode);
  3176. return -1;
  3177. }
  3178. h->mmco[i].long_arg= long_arg;
  3179. }
  3180. if(opcode > (unsigned)MMCO_LONG){
  3181. av_log(h->s.avctx, AV_LOG_ERROR, "illegal memory management control operation %d\n", opcode);
  3182. return -1;
  3183. }
  3184. if(opcode == MMCO_END)
  3185. break;
  3186. }
  3187. h->mmco_index= i;
  3188. }else{
  3189. assert(h->long_ref_count + h->short_ref_count <= h->sps.ref_frame_count);
  3190. if(h->short_ref_count && h->long_ref_count + h->short_ref_count == h->sps.ref_frame_count &&
  3191. !(FIELD_PICTURE && !s->first_field && s->current_picture_ptr->reference)) {
  3192. h->mmco[0].opcode= MMCO_SHORT2UNUSED;
  3193. h->mmco[0].short_pic_num= h->short_ref[ h->short_ref_count - 1 ]->frame_num;
  3194. h->mmco_index= 1;
  3195. if (FIELD_PICTURE) {
  3196. h->mmco[0].short_pic_num *= 2;
  3197. h->mmco[1].opcode= MMCO_SHORT2UNUSED;
  3198. h->mmco[1].short_pic_num= h->mmco[0].short_pic_num + 1;
  3199. h->mmco_index= 2;
  3200. }
  3201. }else
  3202. h->mmco_index= 0;
  3203. }
  3204. }
  3205. return 0;
  3206. }
  3207. static int init_poc(H264Context *h){
  3208. MpegEncContext * const s = &h->s;
  3209. const int max_frame_num= 1<<h->sps.log2_max_frame_num;
  3210. int field_poc[2];
  3211. if(h->nal_unit_type == NAL_IDR_SLICE){
  3212. h->frame_num_offset= 0;
  3213. }else{
  3214. if(h->frame_num < h->prev_frame_num)
  3215. h->frame_num_offset= h->prev_frame_num_offset + max_frame_num;
  3216. else
  3217. h->frame_num_offset= h->prev_frame_num_offset;
  3218. }
  3219. if(h->sps.poc_type==0){
  3220. const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
  3221. if(h->nal_unit_type == NAL_IDR_SLICE){
  3222. h->prev_poc_msb=
  3223. h->prev_poc_lsb= 0;
  3224. }
  3225. if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
  3226. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  3227. else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
  3228. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  3229. else
  3230. h->poc_msb = h->prev_poc_msb;
  3231. //printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
  3232. field_poc[0] =
  3233. field_poc[1] = h->poc_msb + h->poc_lsb;
  3234. if(s->picture_structure == PICT_FRAME)
  3235. field_poc[1] += h->delta_poc_bottom;
  3236. }else if(h->sps.poc_type==1){
  3237. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  3238. int i;
  3239. if(h->sps.poc_cycle_length != 0)
  3240. abs_frame_num = h->frame_num_offset + h->frame_num;
  3241. else
  3242. abs_frame_num = 0;
  3243. if(h->nal_ref_idc==0 && abs_frame_num > 0)
  3244. abs_frame_num--;
  3245. expected_delta_per_poc_cycle = 0;
  3246. for(i=0; i < h->sps.poc_cycle_length; i++)
  3247. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
  3248. if(abs_frame_num > 0){
  3249. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  3250. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  3251. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  3252. for(i = 0; i <= frame_num_in_poc_cycle; i++)
  3253. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
  3254. } else
  3255. expectedpoc = 0;
  3256. if(h->nal_ref_idc == 0)
  3257. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  3258. field_poc[0] = expectedpoc + h->delta_poc[0];
  3259. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  3260. if(s->picture_structure == PICT_FRAME)
  3261. field_poc[1] += h->delta_poc[1];
  3262. }else{
  3263. int poc;
  3264. if(h->nal_unit_type == NAL_IDR_SLICE){
  3265. poc= 0;
  3266. }else{
  3267. if(h->nal_ref_idc) poc= 2*(h->frame_num_offset + h->frame_num);
  3268. else poc= 2*(h->frame_num_offset + h->frame_num) - 1;
  3269. }
  3270. field_poc[0]= poc;
  3271. field_poc[1]= poc;
  3272. }
  3273. if(s->picture_structure != PICT_BOTTOM_FIELD) {
  3274. s->current_picture_ptr->field_poc[0]= field_poc[0];
  3275. s->current_picture_ptr->poc = field_poc[0];
  3276. }
  3277. if(s->picture_structure != PICT_TOP_FIELD) {
  3278. s->current_picture_ptr->field_poc[1]= field_poc[1];
  3279. s->current_picture_ptr->poc = field_poc[1];
  3280. }
  3281. if(!FIELD_PICTURE || !s->first_field) {
  3282. Picture *cur = s->current_picture_ptr;
  3283. cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
  3284. }
  3285. return 0;
  3286. }
  3287. /**
  3288. * initialize scan tables
  3289. */
  3290. static void init_scan_tables(H264Context *h){
  3291. MpegEncContext * const s = &h->s;
  3292. int i;
  3293. if(s->dsp.h264_idct_add == ff_h264_idct_add_c){ //FIXME little ugly
  3294. memcpy(h->zigzag_scan, zigzag_scan, 16*sizeof(uint8_t));
  3295. memcpy(h-> field_scan, field_scan, 16*sizeof(uint8_t));
  3296. }else{
  3297. for(i=0; i<16; i++){
  3298. #define T(x) (x>>2) | ((x<<2) & 0xF)
  3299. h->zigzag_scan[i] = T(zigzag_scan[i]);
  3300. h-> field_scan[i] = T( field_scan[i]);
  3301. #undef T
  3302. }
  3303. }
  3304. if(s->dsp.h264_idct8_add == ff_h264_idct8_add_c){
  3305. memcpy(h->zigzag_scan8x8, zigzag_scan8x8, 64*sizeof(uint8_t));
  3306. memcpy(h->zigzag_scan8x8_cavlc, zigzag_scan8x8_cavlc, 64*sizeof(uint8_t));
  3307. memcpy(h->field_scan8x8, field_scan8x8, 64*sizeof(uint8_t));
  3308. memcpy(h->field_scan8x8_cavlc, field_scan8x8_cavlc, 64*sizeof(uint8_t));
  3309. }else{
  3310. for(i=0; i<64; i++){
  3311. #define T(x) (x>>3) | ((x&7)<<3)
  3312. h->zigzag_scan8x8[i] = T(zigzag_scan8x8[i]);
  3313. h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
  3314. h->field_scan8x8[i] = T(field_scan8x8[i]);
  3315. h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
  3316. #undef T
  3317. }
  3318. }
  3319. if(h->sps.transform_bypass){ //FIXME same ugly
  3320. h->zigzag_scan_q0 = zigzag_scan;
  3321. h->zigzag_scan8x8_q0 = zigzag_scan8x8;
  3322. h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
  3323. h->field_scan_q0 = field_scan;
  3324. h->field_scan8x8_q0 = field_scan8x8;
  3325. h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
  3326. }else{
  3327. h->zigzag_scan_q0 = h->zigzag_scan;
  3328. h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
  3329. h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
  3330. h->field_scan_q0 = h->field_scan;
  3331. h->field_scan8x8_q0 = h->field_scan8x8;
  3332. h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
  3333. }
  3334. }
  3335. /**
  3336. * Replicates H264 "master" context to thread contexts.
  3337. */
  3338. static void clone_slice(H264Context *dst, H264Context *src)
  3339. {
  3340. memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
  3341. dst->s.current_picture_ptr = src->s.current_picture_ptr;
  3342. dst->s.current_picture = src->s.current_picture;
  3343. dst->s.linesize = src->s.linesize;
  3344. dst->s.uvlinesize = src->s.uvlinesize;
  3345. dst->s.first_field = src->s.first_field;
  3346. dst->prev_poc_msb = src->prev_poc_msb;
  3347. dst->prev_poc_lsb = src->prev_poc_lsb;
  3348. dst->prev_frame_num_offset = src->prev_frame_num_offset;
  3349. dst->prev_frame_num = src->prev_frame_num;
  3350. dst->short_ref_count = src->short_ref_count;
  3351. memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
  3352. memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
  3353. memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
  3354. memcpy(dst->ref_list, src->ref_list, sizeof(dst->ref_list));
  3355. memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
  3356. memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
  3357. }
  3358. /**
  3359. * decodes a slice header.
  3360. * this will allso call MPV_common_init() and frame_start() as needed
  3361. *
  3362. * @param h h264context
  3363. * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
  3364. *
  3365. * @return 0 if okay, <0 if an error occured, 1 if decoding must not be multithreaded
  3366. */
  3367. static int decode_slice_header(H264Context *h, H264Context *h0){
  3368. MpegEncContext * const s = &h->s;
  3369. MpegEncContext * const s0 = &h0->s;
  3370. unsigned int first_mb_in_slice;
  3371. unsigned int pps_id;
  3372. int num_ref_idx_active_override_flag;
  3373. static const uint8_t slice_type_map[5]= {P_TYPE, B_TYPE, I_TYPE, SP_TYPE, SI_TYPE};
  3374. unsigned int slice_type, tmp, i;
  3375. int default_ref_list_done = 0;
  3376. int last_pic_structure;
  3377. s->dropable= h->nal_ref_idc == 0;
  3378. if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc){
  3379. s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
  3380. s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
  3381. }else{
  3382. s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
  3383. s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
  3384. }
  3385. first_mb_in_slice= get_ue_golomb(&s->gb);
  3386. if((s->flags2 & CODEC_FLAG2_CHUNKS) && first_mb_in_slice == 0){
  3387. h0->current_slice = 0;
  3388. if (!s0->first_field)
  3389. s->current_picture_ptr= NULL;
  3390. }
  3391. slice_type= get_ue_golomb(&s->gb);
  3392. if(slice_type > 9){
  3393. av_log(h->s.avctx, AV_LOG_ERROR, "slice type too large (%d) at %d %d\n", h->slice_type, s->mb_x, s->mb_y);
  3394. return -1;
  3395. }
  3396. if(slice_type > 4){
  3397. slice_type -= 5;
  3398. h->slice_type_fixed=1;
  3399. }else
  3400. h->slice_type_fixed=0;
  3401. slice_type= slice_type_map[ slice_type ];
  3402. if (slice_type == I_TYPE
  3403. || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
  3404. default_ref_list_done = 1;
  3405. }
  3406. h->slice_type= slice_type;
  3407. s->pict_type= h->slice_type; // to make a few old func happy, it's wrong though
  3408. if (s->pict_type == B_TYPE && s0->last_picture_ptr == NULL) {
  3409. av_log(h->s.avctx, AV_LOG_ERROR,
  3410. "B picture before any references, skipping\n");
  3411. return -1;
  3412. }
  3413. pps_id= get_ue_golomb(&s->gb);
  3414. if(pps_id>=MAX_PPS_COUNT){
  3415. av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
  3416. return -1;
  3417. }
  3418. if(!h0->pps_buffers[pps_id]) {
  3419. av_log(h->s.avctx, AV_LOG_ERROR, "non existing PPS referenced\n");
  3420. return -1;
  3421. }
  3422. h->pps= *h0->pps_buffers[pps_id];
  3423. if(!h0->sps_buffers[h->pps.sps_id]) {
  3424. av_log(h->s.avctx, AV_LOG_ERROR, "non existing SPS referenced\n");
  3425. return -1;
  3426. }
  3427. h->sps = *h0->sps_buffers[h->pps.sps_id];
  3428. if(h == h0 && h->dequant_coeff_pps != pps_id){
  3429. h->dequant_coeff_pps = pps_id;
  3430. init_dequant_tables(h);
  3431. }
  3432. s->mb_width= h->sps.mb_width;
  3433. s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
  3434. h->b_stride= s->mb_width*4;
  3435. h->b8_stride= s->mb_width*2;
  3436. s->width = 16*s->mb_width - 2*(h->sps.crop_left + h->sps.crop_right );
  3437. if(h->sps.frame_mbs_only_flag)
  3438. s->height= 16*s->mb_height - 2*(h->sps.crop_top + h->sps.crop_bottom);
  3439. else
  3440. s->height= 16*s->mb_height - 4*(h->sps.crop_top + h->sps.crop_bottom); //FIXME recheck
  3441. if (s->context_initialized
  3442. && ( s->width != s->avctx->width || s->height != s->avctx->height)) {
  3443. if(h != h0)
  3444. return -1; // width / height changed during parallelized decoding
  3445. free_tables(h);
  3446. MPV_common_end(s);
  3447. }
  3448. if (!s->context_initialized) {
  3449. if(h != h0)
  3450. return -1; // we cant (re-)initialize context during parallel decoding
  3451. if (MPV_common_init(s) < 0)
  3452. return -1;
  3453. s->first_field = 0;
  3454. init_scan_tables(h);
  3455. alloc_tables(h);
  3456. for(i = 1; i < s->avctx->thread_count; i++) {
  3457. H264Context *c;
  3458. c = h->thread_context[i] = av_malloc(sizeof(H264Context));
  3459. memcpy(c, h, sizeof(MpegEncContext));
  3460. memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
  3461. c->sps = h->sps;
  3462. c->pps = h->pps;
  3463. init_scan_tables(c);
  3464. clone_tables(c, h);
  3465. }
  3466. for(i = 0; i < s->avctx->thread_count; i++)
  3467. if(context_init(h->thread_context[i]) < 0)
  3468. return -1;
  3469. s->avctx->width = s->width;
  3470. s->avctx->height = s->height;
  3471. s->avctx->sample_aspect_ratio= h->sps.sar;
  3472. if(!s->avctx->sample_aspect_ratio.den)
  3473. s->avctx->sample_aspect_ratio.den = 1;
  3474. if(h->sps.timing_info_present_flag){
  3475. s->avctx->time_base= (AVRational){h->sps.num_units_in_tick * 2, h->sps.time_scale};
  3476. if(h->x264_build > 0 && h->x264_build < 44)
  3477. s->avctx->time_base.den *= 2;
  3478. av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
  3479. s->avctx->time_base.num, s->avctx->time_base.den, 1<<30);
  3480. }
  3481. }
  3482. h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);
  3483. h->mb_mbaff = 0;
  3484. h->mb_aff_frame = 0;
  3485. last_pic_structure = s0->picture_structure;
  3486. if(h->sps.frame_mbs_only_flag){
  3487. s->picture_structure= PICT_FRAME;
  3488. }else{
  3489. if(get_bits1(&s->gb)) { //field_pic_flag
  3490. s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
  3491. } else {
  3492. s->picture_structure= PICT_FRAME;
  3493. h->mb_aff_frame = h->sps.mb_aff;
  3494. }
  3495. }
  3496. if(h0->current_slice == 0){
  3497. /* See if we have a decoded first field looking for a pair... */
  3498. if (s0->first_field) {
  3499. assert(s0->current_picture_ptr);
  3500. assert(s0->current_picture_ptr->data[0]);
  3501. assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
  3502. /* figure out if we have a complementary field pair */
  3503. if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
  3504. /*
  3505. * Previous field is unmatched. Don't display it, but let it
  3506. * remain for reference if marked as such.
  3507. */
  3508. s0->current_picture_ptr = NULL;
  3509. s0->first_field = FIELD_PICTURE;
  3510. } else {
  3511. if (h->nal_ref_idc &&
  3512. s0->current_picture_ptr->reference &&
  3513. s0->current_picture_ptr->frame_num != h->frame_num) {
  3514. /*
  3515. * This and previous field were reference, but had
  3516. * different frame_nums. Consider this field first in
  3517. * pair. Throw away previous field except for reference
  3518. * purposes.
  3519. */
  3520. s0->first_field = 1;
  3521. s0->current_picture_ptr = NULL;
  3522. } else {
  3523. /* Second field in complementary pair */
  3524. s0->first_field = 0;
  3525. }
  3526. }
  3527. } else {
  3528. /* Frame or first field in a potentially complementary pair */
  3529. assert(!s0->current_picture_ptr);
  3530. s0->first_field = FIELD_PICTURE;
  3531. }
  3532. if((!FIELD_PICTURE || s0->first_field) && frame_start(h) < 0) {
  3533. s0->first_field = 0;
  3534. return -1;
  3535. }
  3536. }
  3537. if(h != h0)
  3538. clone_slice(h, h0);
  3539. s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
  3540. assert(s->mb_num == s->mb_width * s->mb_height);
  3541. if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
  3542. first_mb_in_slice >= s->mb_num){
  3543. av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  3544. return -1;
  3545. }
  3546. s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
  3547. s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
  3548. if (s->picture_structure == PICT_BOTTOM_FIELD)
  3549. s->resync_mb_y = s->mb_y = s->mb_y + 1;
  3550. assert(s->mb_y < s->mb_height);
  3551. if(s->picture_structure==PICT_FRAME){
  3552. h->curr_pic_num= h->frame_num;
  3553. h->max_pic_num= 1<< h->sps.log2_max_frame_num;
  3554. }else{
  3555. h->curr_pic_num= 2*h->frame_num + 1;
  3556. h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
  3557. }
  3558. if(h->nal_unit_type == NAL_IDR_SLICE){
  3559. get_ue_golomb(&s->gb); /* idr_pic_id */
  3560. }
  3561. if(h->sps.poc_type==0){
  3562. h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
  3563. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
  3564. h->delta_poc_bottom= get_se_golomb(&s->gb);
  3565. }
  3566. }
  3567. if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
  3568. h->delta_poc[0]= get_se_golomb(&s->gb);
  3569. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
  3570. h->delta_poc[1]= get_se_golomb(&s->gb);
  3571. }
  3572. init_poc(h);
  3573. if(h->pps.redundant_pic_cnt_present){
  3574. h->redundant_pic_count= get_ue_golomb(&s->gb);
  3575. }
  3576. //set defaults, might be overriden a few line later
  3577. h->ref_count[0]= h->pps.ref_count[0];
  3578. h->ref_count[1]= h->pps.ref_count[1];
  3579. if(h->slice_type == P_TYPE || h->slice_type == SP_TYPE || h->slice_type == B_TYPE){
  3580. if(h->slice_type == B_TYPE){
  3581. h->direct_spatial_mv_pred= get_bits1(&s->gb);
  3582. if(FIELD_OR_MBAFF_PICTURE && h->direct_spatial_mv_pred)
  3583. av_log(h->s.avctx, AV_LOG_ERROR, "Interlaced pictures + spatial direct mode is not implemented\n");
  3584. }
  3585. num_ref_idx_active_override_flag= get_bits1(&s->gb);
  3586. if(num_ref_idx_active_override_flag){
  3587. h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
  3588. if(h->slice_type==B_TYPE)
  3589. h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
  3590. if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
  3591. av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
  3592. h->ref_count[0]= h->ref_count[1]= 1;
  3593. return -1;
  3594. }
  3595. }
  3596. if(h->slice_type == B_TYPE)
  3597. h->list_count= 2;
  3598. else
  3599. h->list_count= 1;
  3600. }else
  3601. h->list_count= 0;
  3602. if(!default_ref_list_done){
  3603. fill_default_ref_list(h);
  3604. }
  3605. if(decode_ref_pic_list_reordering(h) < 0)
  3606. return -1;
  3607. if( (h->pps.weighted_pred && (h->slice_type == P_TYPE || h->slice_type == SP_TYPE ))
  3608. || (h->pps.weighted_bipred_idc==1 && h->slice_type==B_TYPE ) )
  3609. pred_weight_table(h);
  3610. else if(h->pps.weighted_bipred_idc==2 && h->slice_type==B_TYPE)
  3611. implicit_weight_table(h);
  3612. else
  3613. h->use_weight = 0;
  3614. if(h->nal_ref_idc)
  3615. decode_ref_pic_marking(h0, &s->gb);
  3616. if(FRAME_MBAFF)
  3617. fill_mbaff_ref_list(h);
  3618. if( h->slice_type != I_TYPE && h->slice_type != SI_TYPE && h->pps.cabac ){
  3619. tmp = get_ue_golomb(&s->gb);
  3620. if(tmp > 2){
  3621. av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
  3622. return -1;
  3623. }
  3624. h->cabac_init_idc= tmp;
  3625. }
  3626. h->last_qscale_diff = 0;
  3627. tmp = h->pps.init_qp + get_se_golomb(&s->gb);
  3628. if(tmp>51){
  3629. av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  3630. return -1;
  3631. }
  3632. s->qscale= tmp;
  3633. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  3634. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  3635. //FIXME qscale / qp ... stuff
  3636. if(h->slice_type == SP_TYPE){
  3637. get_bits1(&s->gb); /* sp_for_switch_flag */
  3638. }
  3639. if(h->slice_type==SP_TYPE || h->slice_type == SI_TYPE){
  3640. get_se_golomb(&s->gb); /* slice_qs_delta */
  3641. }
  3642. h->deblocking_filter = 1;
  3643. h->slice_alpha_c0_offset = 0;
  3644. h->slice_beta_offset = 0;
  3645. if( h->pps.deblocking_filter_parameters_present ) {
  3646. tmp= get_ue_golomb(&s->gb);
  3647. if(tmp > 2){
  3648. av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
  3649. return -1;
  3650. }
  3651. h->deblocking_filter= tmp;
  3652. if(h->deblocking_filter < 2)
  3653. h->deblocking_filter^= 1; // 1<->0
  3654. if( h->deblocking_filter ) {
  3655. h->slice_alpha_c0_offset = get_se_golomb(&s->gb) << 1;
  3656. h->slice_beta_offset = get_se_golomb(&s->gb) << 1;
  3657. }
  3658. }
  3659. if( s->avctx->skip_loop_filter >= AVDISCARD_ALL
  3660. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type != I_TYPE)
  3661. ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR && h->slice_type == B_TYPE)
  3662. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
  3663. h->deblocking_filter= 0;
  3664. if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
  3665. if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
  3666. /* Cheat slightly for speed:
  3667. Do not bother to deblock across slices. */
  3668. h->deblocking_filter = 2;
  3669. } else {
  3670. h0->max_contexts = 1;
  3671. if(!h0->single_decode_warning) {
  3672. av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  3673. h0->single_decode_warning = 1;
  3674. }
  3675. if(h != h0)
  3676. return 1; // deblocking switched inside frame
  3677. }
  3678. }
  3679. #if 0 //FMO
  3680. if( h->pps.num_slice_groups > 1 && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
  3681. slice_group_change_cycle= get_bits(&s->gb, ?);
  3682. #endif
  3683. h0->last_slice_type = slice_type;
  3684. h->slice_num = ++h0->current_slice;
  3685. h->emu_edge_width= (s->flags&CODEC_FLAG_EMU_EDGE) ? 0 : 16;
  3686. h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
  3687. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  3688. av_log(h->s.avctx, AV_LOG_DEBUG, "slice:%d %s mb:%d %c pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s\n",
  3689. h->slice_num,
  3690. (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
  3691. first_mb_in_slice,
  3692. av_get_pict_type_char(h->slice_type),
  3693. pps_id, h->frame_num,
  3694. s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
  3695. h->ref_count[0], h->ref_count[1],
  3696. s->qscale,
  3697. h->deblocking_filter, h->slice_alpha_c0_offset/2, h->slice_beta_offset/2,
  3698. h->use_weight,
  3699. h->use_weight==1 && h->use_weight_chroma ? "c" : ""
  3700. );
  3701. }
  3702. return 0;
  3703. }
  3704. /**
  3705. *
  3706. */
  3707. static inline int get_level_prefix(GetBitContext *gb){
  3708. unsigned int buf;
  3709. int log;
  3710. OPEN_READER(re, gb);
  3711. UPDATE_CACHE(re, gb);
  3712. buf=GET_CACHE(re, gb);
  3713. log= 32 - av_log2(buf);
  3714. #ifdef TRACE
  3715. print_bin(buf>>(32-log), log);
  3716. av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d lpr @%5d in %s get_level_prefix\n", buf>>(32-log), log, log-1, get_bits_count(gb), __FILE__);
  3717. #endif
  3718. LAST_SKIP_BITS(re, gb, log);
  3719. CLOSE_READER(re, gb);
  3720. return log-1;
  3721. }
  3722. static inline int get_dct8x8_allowed(H264Context *h){
  3723. int i;
  3724. for(i=0; i<4; i++){
  3725. if(!IS_SUB_8X8(h->sub_mb_type[i])
  3726. || (!h->sps.direct_8x8_inference_flag && IS_DIRECT(h->sub_mb_type[i])))
  3727. return 0;
  3728. }
  3729. return 1;
  3730. }
  3731. /**
  3732. * decodes a residual block.
  3733. * @param n block index
  3734. * @param scantable scantable
  3735. * @param max_coeff number of coefficients in the block
  3736. * @return <0 if an error occured
  3737. */
  3738. static int decode_residual(H264Context *h, GetBitContext *gb, DCTELEM *block, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff){
  3739. MpegEncContext * const s = &h->s;
  3740. static const int coeff_token_table_index[17]= {0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3};
  3741. int level[16];
  3742. int zeros_left, coeff_num, coeff_token, total_coeff, i, j, trailing_ones, run_before;
  3743. //FIXME put trailing_onex into the context
  3744. if(n == CHROMA_DC_BLOCK_INDEX){
  3745. coeff_token= get_vlc2(gb, chroma_dc_coeff_token_vlc.table, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 1);
  3746. total_coeff= coeff_token>>2;
  3747. }else{
  3748. if(n == LUMA_DC_BLOCK_INDEX){
  3749. total_coeff= pred_non_zero_count(h, 0);
  3750. coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
  3751. total_coeff= coeff_token>>2;
  3752. }else{
  3753. total_coeff= pred_non_zero_count(h, n);
  3754. coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
  3755. total_coeff= coeff_token>>2;
  3756. h->non_zero_count_cache[ scan8[n] ]= total_coeff;
  3757. }
  3758. }
  3759. //FIXME set last_non_zero?
  3760. if(total_coeff==0)
  3761. return 0;
  3762. if(total_coeff > (unsigned)max_coeff) {
  3763. av_log(h->s.avctx, AV_LOG_ERROR, "corrupted macroblock %d %d (total_coeff=%d)\n", s->mb_x, s->mb_y, total_coeff);
  3764. return -1;
  3765. }
  3766. trailing_ones= coeff_token&3;
  3767. tprintf(h->s.avctx, "trailing:%d, total:%d\n", trailing_ones, total_coeff);
  3768. assert(total_coeff<=16);
  3769. for(i=0; i<trailing_ones; i++){
  3770. level[i]= 1 - 2*get_bits1(gb);
  3771. }
  3772. if(i<total_coeff) {
  3773. int level_code, mask;
  3774. int suffix_length = total_coeff > 10 && trailing_ones < 3;
  3775. int prefix= get_level_prefix(gb);
  3776. //first coefficient has suffix_length equal to 0 or 1
  3777. if(prefix<14){ //FIXME try to build a large unified VLC table for all this
  3778. if(suffix_length)
  3779. level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length); //part
  3780. else
  3781. level_code= (prefix<<suffix_length); //part
  3782. }else if(prefix==14){
  3783. if(suffix_length)
  3784. level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length); //part
  3785. else
  3786. level_code= prefix + get_bits(gb, 4); //part
  3787. }else if(prefix==15){
  3788. level_code= (prefix<<suffix_length) + get_bits(gb, 12); //part
  3789. if(suffix_length==0) level_code+=15; //FIXME doesn't make (much)sense
  3790. }else{
  3791. av_log(h->s.avctx, AV_LOG_ERROR, "prefix too large at %d %d\n", s->mb_x, s->mb_y);
  3792. return -1;
  3793. }
  3794. if(trailing_ones < 3) level_code += 2;
  3795. suffix_length = 1;
  3796. if(level_code > 5)
  3797. suffix_length++;
  3798. mask= -(level_code&1);
  3799. level[i]= (((2+level_code)>>1) ^ mask) - mask;
  3800. i++;
  3801. //remaining coefficients have suffix_length > 0
  3802. for(;i<total_coeff;i++) {
  3803. static const int suffix_limit[7] = {0,5,11,23,47,95,INT_MAX };
  3804. prefix = get_level_prefix(gb);
  3805. if(prefix<15){
  3806. level_code = (prefix<<suffix_length) + get_bits(gb, suffix_length);
  3807. }else if(prefix==15){
  3808. level_code = (prefix<<suffix_length) + get_bits(gb, 12);
  3809. }else{
  3810. av_log(h->s.avctx, AV_LOG_ERROR, "prefix too large at %d %d\n", s->mb_x, s->mb_y);
  3811. return -1;
  3812. }
  3813. mask= -(level_code&1);
  3814. level[i]= (((2+level_code)>>1) ^ mask) - mask;
  3815. if(level_code > suffix_limit[suffix_length])
  3816. suffix_length++;
  3817. }
  3818. }
  3819. if(total_coeff == max_coeff)
  3820. zeros_left=0;
  3821. else{
  3822. if(n == CHROMA_DC_BLOCK_INDEX)
  3823. zeros_left= get_vlc2(gb, chroma_dc_total_zeros_vlc[ total_coeff-1 ].table, CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 1);
  3824. else
  3825. zeros_left= get_vlc2(gb, total_zeros_vlc[ total_coeff-1 ].table, TOTAL_ZEROS_VLC_BITS, 1);
  3826. }
  3827. coeff_num = zeros_left + total_coeff - 1;
  3828. j = scantable[coeff_num];
  3829. if(n > 24){
  3830. block[j] = level[0];
  3831. for(i=1;i<total_coeff;i++) {
  3832. if(zeros_left <= 0)
  3833. run_before = 0;
  3834. else if(zeros_left < 7){
  3835. run_before= get_vlc2(gb, run_vlc[zeros_left-1].table, RUN_VLC_BITS, 1);
  3836. }else{
  3837. run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
  3838. }
  3839. zeros_left -= run_before;
  3840. coeff_num -= 1 + run_before;
  3841. j= scantable[ coeff_num ];
  3842. block[j]= level[i];
  3843. }
  3844. }else{
  3845. block[j] = (level[0] * qmul[j] + 32)>>6;
  3846. for(i=1;i<total_coeff;i++) {
  3847. if(zeros_left <= 0)
  3848. run_before = 0;
  3849. else if(zeros_left < 7){
  3850. run_before= get_vlc2(gb, run_vlc[zeros_left-1].table, RUN_VLC_BITS, 1);
  3851. }else{
  3852. run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
  3853. }
  3854. zeros_left -= run_before;
  3855. coeff_num -= 1 + run_before;
  3856. j= scantable[ coeff_num ];
  3857. block[j]= (level[i] * qmul[j] + 32)>>6;
  3858. }
  3859. }
  3860. if(zeros_left<0){
  3861. av_log(h->s.avctx, AV_LOG_ERROR, "negative number of zero coeffs at %d %d\n", s->mb_x, s->mb_y);
  3862. return -1;
  3863. }
  3864. return 0;
  3865. }
  3866. static void predict_field_decoding_flag(H264Context *h){
  3867. MpegEncContext * const s = &h->s;
  3868. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  3869. int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
  3870. ? s->current_picture.mb_type[mb_xy-1]
  3871. : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
  3872. ? s->current_picture.mb_type[mb_xy-s->mb_stride]
  3873. : 0;
  3874. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  3875. }
  3876. /**
  3877. * decodes a P_SKIP or B_SKIP macroblock
  3878. */
  3879. static void decode_mb_skip(H264Context *h){
  3880. MpegEncContext * const s = &h->s;
  3881. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  3882. int mb_type=0;
  3883. memset(h->non_zero_count[mb_xy], 0, 16);
  3884. memset(h->non_zero_count_cache + 8, 0, 8*5); //FIXME ugly, remove pfui
  3885. if(MB_FIELD)
  3886. mb_type|= MB_TYPE_INTERLACED;
  3887. if( h->slice_type == B_TYPE )
  3888. {
  3889. // just for fill_caches. pred_direct_motion will set the real mb_type
  3890. mb_type|= MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2|MB_TYPE_SKIP;
  3891. fill_caches(h, mb_type, 0); //FIXME check what is needed and what not ...
  3892. pred_direct_motion(h, &mb_type);
  3893. mb_type|= MB_TYPE_SKIP;
  3894. }
  3895. else
  3896. {
  3897. int mx, my;
  3898. mb_type|= MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P1L0|MB_TYPE_SKIP;
  3899. fill_caches(h, mb_type, 0); //FIXME check what is needed and what not ...
  3900. pred_pskip_motion(h, &mx, &my);
  3901. fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, 0, 1);
  3902. fill_rectangle( h->mv_cache[0][scan8[0]], 4, 4, 8, pack16to32(mx,my), 4);
  3903. }
  3904. write_back_motion(h, mb_type);
  3905. s->current_picture.mb_type[mb_xy]= mb_type;
  3906. s->current_picture.qscale_table[mb_xy]= s->qscale;
  3907. h->slice_table[ mb_xy ]= h->slice_num;
  3908. h->prev_mb_skipped= 1;
  3909. }
  3910. /**
  3911. * decodes a macroblock
  3912. * @returns 0 if ok, AC_ERROR / DC_ERROR / MV_ERROR if an error is noticed
  3913. */
  3914. static int decode_mb_cavlc(H264Context *h){
  3915. MpegEncContext * const s = &h->s;
  3916. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  3917. int partition_count;
  3918. unsigned int mb_type, cbp;
  3919. int dct8x8_allowed= h->pps.transform_8x8_mode;
  3920. s->dsp.clear_blocks(h->mb); //FIXME avoid if already clear (move after skip handlong?
  3921. tprintf(s->avctx, "pic:%d mb:%d/%d\n", h->frame_num, s->mb_x, s->mb_y);
  3922. cbp = 0; /* avoid warning. FIXME: find a solution without slowing
  3923. down the code */
  3924. if(h->slice_type != I_TYPE && h->slice_type != SI_TYPE){
  3925. if(s->mb_skip_run==-1)
  3926. s->mb_skip_run= get_ue_golomb(&s->gb);
  3927. if (s->mb_skip_run--) {
  3928. if(FRAME_MBAFF && (s->mb_y&1) == 0){
  3929. if(s->mb_skip_run==0)
  3930. h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);
  3931. else
  3932. predict_field_decoding_flag(h);
  3933. }
  3934. decode_mb_skip(h);
  3935. return 0;
  3936. }
  3937. }
  3938. if(FRAME_MBAFF){
  3939. if( (s->mb_y&1) == 0 )
  3940. h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);
  3941. }else
  3942. h->mb_field_decoding_flag= (s->picture_structure!=PICT_FRAME);
  3943. h->prev_mb_skipped= 0;
  3944. mb_type= get_ue_golomb(&s->gb);
  3945. if(h->slice_type == B_TYPE){
  3946. if(mb_type < 23){
  3947. partition_count= b_mb_type_info[mb_type].partition_count;
  3948. mb_type= b_mb_type_info[mb_type].type;
  3949. }else{
  3950. mb_type -= 23;
  3951. goto decode_intra_mb;
  3952. }
  3953. }else if(h->slice_type == P_TYPE /*|| h->slice_type == SP_TYPE */){
  3954. if(mb_type < 5){
  3955. partition_count= p_mb_type_info[mb_type].partition_count;
  3956. mb_type= p_mb_type_info[mb_type].type;
  3957. }else{
  3958. mb_type -= 5;
  3959. goto decode_intra_mb;
  3960. }
  3961. }else{
  3962. assert(h->slice_type == I_TYPE);
  3963. decode_intra_mb:
  3964. if(mb_type > 25){
  3965. av_log(h->s.avctx, AV_LOG_ERROR, "mb_type %d in %c slice too large at %d %d\n", mb_type, av_get_pict_type_char(h->slice_type), s->mb_x, s->mb_y);
  3966. return -1;
  3967. }
  3968. partition_count=0;
  3969. cbp= i_mb_type_info[mb_type].cbp;
  3970. h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;
  3971. mb_type= i_mb_type_info[mb_type].type;
  3972. }
  3973. if(MB_FIELD)
  3974. mb_type |= MB_TYPE_INTERLACED;
  3975. h->slice_table[ mb_xy ]= h->slice_num;
  3976. if(IS_INTRA_PCM(mb_type)){
  3977. unsigned int x, y;
  3978. // We assume these blocks are very rare so we do not optimize it.
  3979. align_get_bits(&s->gb);
  3980. // The pixels are stored in the same order as levels in h->mb array.
  3981. for(y=0; y<16; y++){
  3982. const int index= 4*(y&3) + 32*((y>>2)&1) + 128*(y>>3);
  3983. for(x=0; x<16; x++){
  3984. tprintf(s->avctx, "LUMA ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
  3985. h->mb[index + (x&3) + 16*((x>>2)&1) + 64*(x>>3)]= get_bits(&s->gb, 8);
  3986. }
  3987. }
  3988. for(y=0; y<8; y++){
  3989. const int index= 256 + 4*(y&3) + 32*(y>>2);
  3990. for(x=0; x<8; x++){
  3991. tprintf(s->avctx, "CHROMA U ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
  3992. h->mb[index + (x&3) + 16*(x>>2)]= get_bits(&s->gb, 8);
  3993. }
  3994. }
  3995. for(y=0; y<8; y++){
  3996. const int index= 256 + 64 + 4*(y&3) + 32*(y>>2);
  3997. for(x=0; x<8; x++){
  3998. tprintf(s->avctx, "CHROMA V ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
  3999. h->mb[index + (x&3) + 16*(x>>2)]= get_bits(&s->gb, 8);
  4000. }
  4001. }
  4002. // In deblocking, the quantizer is 0
  4003. s->current_picture.qscale_table[mb_xy]= 0;
  4004. h->chroma_qp[0] = get_chroma_qp(h, 0, 0);
  4005. h->chroma_qp[1] = get_chroma_qp(h, 1, 0);
  4006. // All coeffs are present
  4007. memset(h->non_zero_count[mb_xy], 16, 16);
  4008. s->current_picture.mb_type[mb_xy]= mb_type;
  4009. return 0;
  4010. }
  4011. if(MB_MBAFF){
  4012. h->ref_count[0] <<= 1;
  4013. h->ref_count[1] <<= 1;
  4014. }
  4015. fill_caches(h, mb_type, 0);
  4016. //mb_pred
  4017. if(IS_INTRA(mb_type)){
  4018. int pred_mode;
  4019. // init_top_left_availability(h);
  4020. if(IS_INTRA4x4(mb_type)){
  4021. int i;
  4022. int di = 1;
  4023. if(dct8x8_allowed && get_bits1(&s->gb)){
  4024. mb_type |= MB_TYPE_8x8DCT;
  4025. di = 4;
  4026. }
  4027. // fill_intra4x4_pred_table(h);
  4028. for(i=0; i<16; i+=di){
  4029. int mode= pred_intra_mode(h, i);
  4030. if(!get_bits1(&s->gb)){
  4031. const int rem_mode= get_bits(&s->gb, 3);
  4032. mode = rem_mode + (rem_mode >= mode);
  4033. }
  4034. if(di==4)
  4035. fill_rectangle( &h->intra4x4_pred_mode_cache[ scan8[i] ], 2, 2, 8, mode, 1 );
  4036. else
  4037. h->intra4x4_pred_mode_cache[ scan8[i] ] = mode;
  4038. }
  4039. write_back_intra_pred_mode(h);
  4040. if( check_intra4x4_pred_mode(h) < 0)
  4041. return -1;
  4042. }else{
  4043. h->intra16x16_pred_mode= check_intra_pred_mode(h, h->intra16x16_pred_mode);
  4044. if(h->intra16x16_pred_mode < 0)
  4045. return -1;
  4046. }
  4047. pred_mode= check_intra_pred_mode(h, get_ue_golomb(&s->gb));
  4048. if(pred_mode < 0)
  4049. return -1;
  4050. h->chroma_pred_mode= pred_mode;
  4051. }else if(partition_count==4){
  4052. int i, j, sub_partition_count[4], list, ref[2][4];
  4053. if(h->slice_type == B_TYPE){
  4054. for(i=0; i<4; i++){
  4055. h->sub_mb_type[i]= get_ue_golomb(&s->gb);
  4056. if(h->sub_mb_type[i] >=13){
  4057. av_log(h->s.avctx, AV_LOG_ERROR, "B sub_mb_type %u out of range at %d %d\n", h->sub_mb_type[i], s->mb_x, s->mb_y);
  4058. return -1;
  4059. }
  4060. sub_partition_count[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  4061. h->sub_mb_type[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  4062. }
  4063. if( IS_DIRECT(h->sub_mb_type[0]) || IS_DIRECT(h->sub_mb_type[1])
  4064. || IS_DIRECT(h->sub_mb_type[2]) || IS_DIRECT(h->sub_mb_type[3])) {
  4065. pred_direct_motion(h, &mb_type);
  4066. h->ref_cache[0][scan8[4]] =
  4067. h->ref_cache[1][scan8[4]] =
  4068. h->ref_cache[0][scan8[12]] =
  4069. h->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;
  4070. }
  4071. }else{
  4072. assert(h->slice_type == P_TYPE || h->slice_type == SP_TYPE); //FIXME SP correct ?
  4073. for(i=0; i<4; i++){
  4074. h->sub_mb_type[i]= get_ue_golomb(&s->gb);
  4075. if(h->sub_mb_type[i] >=4){
  4076. av_log(h->s.avctx, AV_LOG_ERROR, "P sub_mb_type %u out of range at %d %d\n", h->sub_mb_type[i], s->mb_x, s->mb_y);
  4077. return -1;
  4078. }
  4079. sub_partition_count[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  4080. h->sub_mb_type[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  4081. }
  4082. }
  4083. for(list=0; list<h->list_count; list++){
  4084. int ref_count= IS_REF0(mb_type) ? 1 : h->ref_count[list];
  4085. for(i=0; i<4; i++){
  4086. if(IS_DIRECT(h->sub_mb_type[i])) continue;
  4087. if(IS_DIR(h->sub_mb_type[i], 0, list)){
  4088. unsigned int tmp = get_te0_golomb(&s->gb, ref_count); //FIXME init to 0 before and skip?
  4089. if(tmp>=ref_count){
  4090. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", tmp);
  4091. return -1;
  4092. }
  4093. ref[list][i]= tmp;
  4094. }else{
  4095. //FIXME
  4096. ref[list][i] = -1;
  4097. }
  4098. }
  4099. }
  4100. if(dct8x8_allowed)
  4101. dct8x8_allowed = get_dct8x8_allowed(h);
  4102. for(list=0; list<h->list_count; list++){
  4103. for(i=0; i<4; i++){
  4104. if(IS_DIRECT(h->sub_mb_type[i])) {
  4105. h->ref_cache[list][ scan8[4*i] ] = h->ref_cache[list][ scan8[4*i]+1 ];
  4106. continue;
  4107. }
  4108. h->ref_cache[list][ scan8[4*i] ]=h->ref_cache[list][ scan8[4*i]+1 ]=
  4109. h->ref_cache[list][ scan8[4*i]+8 ]=h->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];
  4110. if(IS_DIR(h->sub_mb_type[i], 0, list)){
  4111. const int sub_mb_type= h->sub_mb_type[i];
  4112. const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;
  4113. for(j=0; j<sub_partition_count[i]; j++){
  4114. int mx, my;
  4115. const int index= 4*i + block_width*j;
  4116. int16_t (* mv_cache)[2]= &h->mv_cache[list][ scan8[index] ];
  4117. pred_motion(h, index, block_width, list, h->ref_cache[list][ scan8[index] ], &mx, &my);
  4118. mx += get_se_golomb(&s->gb);
  4119. my += get_se_golomb(&s->gb);
  4120. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4121. if(IS_SUB_8X8(sub_mb_type)){
  4122. mv_cache[ 1 ][0]=
  4123. mv_cache[ 8 ][0]= mv_cache[ 9 ][0]= mx;
  4124. mv_cache[ 1 ][1]=
  4125. mv_cache[ 8 ][1]= mv_cache[ 9 ][1]= my;
  4126. }else if(IS_SUB_8X4(sub_mb_type)){
  4127. mv_cache[ 1 ][0]= mx;
  4128. mv_cache[ 1 ][1]= my;
  4129. }else if(IS_SUB_4X8(sub_mb_type)){
  4130. mv_cache[ 8 ][0]= mx;
  4131. mv_cache[ 8 ][1]= my;
  4132. }
  4133. mv_cache[ 0 ][0]= mx;
  4134. mv_cache[ 0 ][1]= my;
  4135. }
  4136. }else{
  4137. uint32_t *p= (uint32_t *)&h->mv_cache[list][ scan8[4*i] ][0];
  4138. p[0] = p[1]=
  4139. p[8] = p[9]= 0;
  4140. }
  4141. }
  4142. }
  4143. }else if(IS_DIRECT(mb_type)){
  4144. pred_direct_motion(h, &mb_type);
  4145. dct8x8_allowed &= h->sps.direct_8x8_inference_flag;
  4146. }else{
  4147. int list, mx, my, i;
  4148. //FIXME we should set ref_idx_l? to 0 if we use that later ...
  4149. if(IS_16X16(mb_type)){
  4150. for(list=0; list<h->list_count; list++){
  4151. unsigned int val;
  4152. if(IS_DIR(mb_type, 0, list)){
  4153. val= get_te0_golomb(&s->gb, h->ref_count[list]);
  4154. if(val >= h->ref_count[list]){
  4155. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
  4156. return -1;
  4157. }
  4158. }else
  4159. val= LIST_NOT_USED&0xFF;
  4160. fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, val, 1);
  4161. }
  4162. for(list=0; list<h->list_count; list++){
  4163. unsigned int val;
  4164. if(IS_DIR(mb_type, 0, list)){
  4165. pred_motion(h, 0, 4, list, h->ref_cache[list][ scan8[0] ], &mx, &my);
  4166. mx += get_se_golomb(&s->gb);
  4167. my += get_se_golomb(&s->gb);
  4168. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4169. val= pack16to32(mx,my);
  4170. }else
  4171. val=0;
  4172. fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, val, 4);
  4173. }
  4174. }
  4175. else if(IS_16X8(mb_type)){
  4176. for(list=0; list<h->list_count; list++){
  4177. for(i=0; i<2; i++){
  4178. unsigned int val;
  4179. if(IS_DIR(mb_type, i, list)){
  4180. val= get_te0_golomb(&s->gb, h->ref_count[list]);
  4181. if(val >= h->ref_count[list]){
  4182. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
  4183. return -1;
  4184. }
  4185. }else
  4186. val= LIST_NOT_USED&0xFF;
  4187. fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 1);
  4188. }
  4189. }
  4190. for(list=0; list<h->list_count; list++){
  4191. for(i=0; i<2; i++){
  4192. unsigned int val;
  4193. if(IS_DIR(mb_type, i, list)){
  4194. pred_16x8_motion(h, 8*i, list, h->ref_cache[list][scan8[0] + 16*i], &mx, &my);
  4195. mx += get_se_golomb(&s->gb);
  4196. my += get_se_golomb(&s->gb);
  4197. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4198. val= pack16to32(mx,my);
  4199. }else
  4200. val=0;
  4201. fill_rectangle(h->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 4);
  4202. }
  4203. }
  4204. }else{
  4205. assert(IS_8X16(mb_type));
  4206. for(list=0; list<h->list_count; list++){
  4207. for(i=0; i<2; i++){
  4208. unsigned int val;
  4209. if(IS_DIR(mb_type, i, list)){ //FIXME optimize
  4210. val= get_te0_golomb(&s->gb, h->ref_count[list]);
  4211. if(val >= h->ref_count[list]){
  4212. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
  4213. return -1;
  4214. }
  4215. }else
  4216. val= LIST_NOT_USED&0xFF;
  4217. fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 1);
  4218. }
  4219. }
  4220. for(list=0; list<h->list_count; list++){
  4221. for(i=0; i<2; i++){
  4222. unsigned int val;
  4223. if(IS_DIR(mb_type, i, list)){
  4224. pred_8x16_motion(h, i*4, list, h->ref_cache[list][ scan8[0] + 2*i ], &mx, &my);
  4225. mx += get_se_golomb(&s->gb);
  4226. my += get_se_golomb(&s->gb);
  4227. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4228. val= pack16to32(mx,my);
  4229. }else
  4230. val=0;
  4231. fill_rectangle(h->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 4);
  4232. }
  4233. }
  4234. }
  4235. }
  4236. if(IS_INTER(mb_type))
  4237. write_back_motion(h, mb_type);
  4238. if(!IS_INTRA16x16(mb_type)){
  4239. cbp= get_ue_golomb(&s->gb);
  4240. if(cbp > 47){
  4241. av_log(h->s.avctx, AV_LOG_ERROR, "cbp too large (%u) at %d %d\n", cbp, s->mb_x, s->mb_y);
  4242. return -1;
  4243. }
  4244. if(IS_INTRA4x4(mb_type))
  4245. cbp= golomb_to_intra4x4_cbp[cbp];
  4246. else
  4247. cbp= golomb_to_inter_cbp[cbp];
  4248. }
  4249. h->cbp = cbp;
  4250. if(dct8x8_allowed && (cbp&15) && !IS_INTRA(mb_type)){
  4251. if(get_bits1(&s->gb))
  4252. mb_type |= MB_TYPE_8x8DCT;
  4253. }
  4254. s->current_picture.mb_type[mb_xy]= mb_type;
  4255. if(cbp || IS_INTRA16x16(mb_type)){
  4256. int i8x8, i4x4, chroma_idx;
  4257. int dquant;
  4258. GetBitContext *gb= IS_INTRA(mb_type) ? h->intra_gb_ptr : h->inter_gb_ptr;
  4259. const uint8_t *scan, *scan8x8, *dc_scan;
  4260. // fill_non_zero_count_cache(h);
  4261. if(IS_INTERLACED(mb_type)){
  4262. scan8x8= s->qscale ? h->field_scan8x8_cavlc : h->field_scan8x8_cavlc_q0;
  4263. scan= s->qscale ? h->field_scan : h->field_scan_q0;
  4264. dc_scan= luma_dc_field_scan;
  4265. }else{
  4266. scan8x8= s->qscale ? h->zigzag_scan8x8_cavlc : h->zigzag_scan8x8_cavlc_q0;
  4267. scan= s->qscale ? h->zigzag_scan : h->zigzag_scan_q0;
  4268. dc_scan= luma_dc_zigzag_scan;
  4269. }
  4270. dquant= get_se_golomb(&s->gb);
  4271. if( dquant > 25 || dquant < -26 ){
  4272. av_log(h->s.avctx, AV_LOG_ERROR, "dquant out of range (%d) at %d %d\n", dquant, s->mb_x, s->mb_y);
  4273. return -1;
  4274. }
  4275. s->qscale += dquant;
  4276. if(((unsigned)s->qscale) > 51){
  4277. if(s->qscale<0) s->qscale+= 52;
  4278. else s->qscale-= 52;
  4279. }
  4280. h->chroma_qp[0]= get_chroma_qp(h, 0, s->qscale);
  4281. h->chroma_qp[1]= get_chroma_qp(h, 1, s->qscale);
  4282. if(IS_INTRA16x16(mb_type)){
  4283. if( decode_residual(h, h->intra_gb_ptr, h->mb, LUMA_DC_BLOCK_INDEX, dc_scan, h->dequant4_coeff[0][s->qscale], 16) < 0){
  4284. return -1; //FIXME continue if partitioned and other return -1 too
  4285. }
  4286. assert((cbp&15) == 0 || (cbp&15) == 15);
  4287. if(cbp&15){
  4288. for(i8x8=0; i8x8<4; i8x8++){
  4289. for(i4x4=0; i4x4<4; i4x4++){
  4290. const int index= i4x4 + 4*i8x8;
  4291. if( decode_residual(h, h->intra_gb_ptr, h->mb + 16*index, index, scan + 1, h->dequant4_coeff[0][s->qscale], 15) < 0 ){
  4292. return -1;
  4293. }
  4294. }
  4295. }
  4296. }else{
  4297. fill_rectangle(&h->non_zero_count_cache[scan8[0]], 4, 4, 8, 0, 1);
  4298. }
  4299. }else{
  4300. for(i8x8=0; i8x8<4; i8x8++){
  4301. if(cbp & (1<<i8x8)){
  4302. if(IS_8x8DCT(mb_type)){
  4303. DCTELEM *buf = &h->mb[64*i8x8];
  4304. uint8_t *nnz;
  4305. for(i4x4=0; i4x4<4; i4x4++){
  4306. if( decode_residual(h, gb, buf, i4x4+4*i8x8, scan8x8+16*i4x4,
  4307. h->dequant8_coeff[IS_INTRA( mb_type ) ? 0:1][s->qscale], 16) <0 )
  4308. return -1;
  4309. }
  4310. nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
  4311. nnz[0] += nnz[1] + nnz[8] + nnz[9];
  4312. }else{
  4313. for(i4x4=0; i4x4<4; i4x4++){
  4314. const int index= i4x4 + 4*i8x8;
  4315. if( decode_residual(h, gb, h->mb + 16*index, index, scan, h->dequant4_coeff[IS_INTRA( mb_type ) ? 0:3][s->qscale], 16) <0 ){
  4316. return -1;
  4317. }
  4318. }
  4319. }
  4320. }else{
  4321. uint8_t * const nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
  4322. nnz[0] = nnz[1] = nnz[8] = nnz[9] = 0;
  4323. }
  4324. }
  4325. }
  4326. if(cbp&0x30){
  4327. for(chroma_idx=0; chroma_idx<2; chroma_idx++)
  4328. if( decode_residual(h, gb, h->mb + 256 + 16*4*chroma_idx, CHROMA_DC_BLOCK_INDEX, chroma_dc_scan, NULL, 4) < 0){
  4329. return -1;
  4330. }
  4331. }
  4332. if(cbp&0x20){
  4333. for(chroma_idx=0; chroma_idx<2; chroma_idx++){
  4334. const uint32_t *qmul = h->dequant4_coeff[chroma_idx+1+(IS_INTRA( mb_type ) ? 0:3)][h->chroma_qp[chroma_idx]];
  4335. for(i4x4=0; i4x4<4; i4x4++){
  4336. const int index= 16 + 4*chroma_idx + i4x4;
  4337. if( decode_residual(h, gb, h->mb + 16*index, index, scan + 1, qmul, 15) < 0){
  4338. return -1;
  4339. }
  4340. }
  4341. }
  4342. }else{
  4343. uint8_t * const nnz= &h->non_zero_count_cache[0];
  4344. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  4345. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  4346. }
  4347. }else{
  4348. uint8_t * const nnz= &h->non_zero_count_cache[0];
  4349. fill_rectangle(&nnz[scan8[0]], 4, 4, 8, 0, 1);
  4350. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  4351. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  4352. }
  4353. s->current_picture.qscale_table[mb_xy]= s->qscale;
  4354. write_back_non_zero_count(h);
  4355. if(MB_MBAFF){
  4356. h->ref_count[0] >>= 1;
  4357. h->ref_count[1] >>= 1;
  4358. }
  4359. return 0;
  4360. }
  4361. static int decode_cabac_field_decoding_flag(H264Context *h) {
  4362. MpegEncContext * const s = &h->s;
  4363. const int mb_x = s->mb_x;
  4364. const int mb_y = s->mb_y & ~1;
  4365. const int mba_xy = mb_x - 1 + mb_y *s->mb_stride;
  4366. const int mbb_xy = mb_x + (mb_y-2)*s->mb_stride;
  4367. unsigned int ctx = 0;
  4368. if( h->slice_table[mba_xy] == h->slice_num && IS_INTERLACED( s->current_picture.mb_type[mba_xy] ) ) {
  4369. ctx += 1;
  4370. }
  4371. if( h->slice_table[mbb_xy] == h->slice_num && IS_INTERLACED( s->current_picture.mb_type[mbb_xy] ) ) {
  4372. ctx += 1;
  4373. }
  4374. return get_cabac_noinline( &h->cabac, &h->cabac_state[70 + ctx] );
  4375. }
  4376. static int decode_cabac_intra_mb_type(H264Context *h, int ctx_base, int intra_slice) {
  4377. uint8_t *state= &h->cabac_state[ctx_base];
  4378. int mb_type;
  4379. if(intra_slice){
  4380. MpegEncContext * const s = &h->s;
  4381. const int mba_xy = h->left_mb_xy[0];
  4382. const int mbb_xy = h->top_mb_xy;
  4383. int ctx=0;
  4384. if( h->slice_table[mba_xy] == h->slice_num && !IS_INTRA4x4( s->current_picture.mb_type[mba_xy] ) )
  4385. ctx++;
  4386. if( h->slice_table[mbb_xy] == h->slice_num && !IS_INTRA4x4( s->current_picture.mb_type[mbb_xy] ) )
  4387. ctx++;
  4388. if( get_cabac_noinline( &h->cabac, &state[ctx] ) == 0 )
  4389. return 0; /* I4x4 */
  4390. state += 2;
  4391. }else{
  4392. if( get_cabac_noinline( &h->cabac, &state[0] ) == 0 )
  4393. return 0; /* I4x4 */
  4394. }
  4395. if( get_cabac_terminate( &h->cabac ) )
  4396. return 25; /* PCM */
  4397. mb_type = 1; /* I16x16 */
  4398. mb_type += 12 * get_cabac_noinline( &h->cabac, &state[1] ); /* cbp_luma != 0 */
  4399. if( get_cabac_noinline( &h->cabac, &state[2] ) ) /* cbp_chroma */
  4400. mb_type += 4 + 4 * get_cabac_noinline( &h->cabac, &state[2+intra_slice] );
  4401. mb_type += 2 * get_cabac_noinline( &h->cabac, &state[3+intra_slice] );
  4402. mb_type += 1 * get_cabac_noinline( &h->cabac, &state[3+2*intra_slice] );
  4403. return mb_type;
  4404. }
  4405. static int decode_cabac_mb_type( H264Context *h ) {
  4406. MpegEncContext * const s = &h->s;
  4407. if( h->slice_type == I_TYPE ) {
  4408. return decode_cabac_intra_mb_type(h, 3, 1);
  4409. } else if( h->slice_type == P_TYPE ) {
  4410. if( get_cabac_noinline( &h->cabac, &h->cabac_state[14] ) == 0 ) {
  4411. /* P-type */
  4412. if( get_cabac_noinline( &h->cabac, &h->cabac_state[15] ) == 0 ) {
  4413. /* P_L0_D16x16, P_8x8 */
  4414. return 3 * get_cabac_noinline( &h->cabac, &h->cabac_state[16] );
  4415. } else {
  4416. /* P_L0_D8x16, P_L0_D16x8 */
  4417. return 2 - get_cabac_noinline( &h->cabac, &h->cabac_state[17] );
  4418. }
  4419. } else {
  4420. return decode_cabac_intra_mb_type(h, 17, 0) + 5;
  4421. }
  4422. } else if( h->slice_type == B_TYPE ) {
  4423. const int mba_xy = h->left_mb_xy[0];
  4424. const int mbb_xy = h->top_mb_xy;
  4425. int ctx = 0;
  4426. int bits;
  4427. if( h->slice_table[mba_xy] == h->slice_num && !IS_DIRECT( s->current_picture.mb_type[mba_xy] ) )
  4428. ctx++;
  4429. if( h->slice_table[mbb_xy] == h->slice_num && !IS_DIRECT( s->current_picture.mb_type[mbb_xy] ) )
  4430. ctx++;
  4431. if( !get_cabac_noinline( &h->cabac, &h->cabac_state[27+ctx] ) )
  4432. return 0; /* B_Direct_16x16 */
  4433. if( !get_cabac_noinline( &h->cabac, &h->cabac_state[27+3] ) ) {
  4434. return 1 + get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ); /* B_L[01]_16x16 */
  4435. }
  4436. bits = get_cabac_noinline( &h->cabac, &h->cabac_state[27+4] ) << 3;
  4437. bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ) << 2;
  4438. bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ) << 1;
  4439. bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] );
  4440. if( bits < 8 )
  4441. return bits + 3; /* B_Bi_16x16 through B_L1_L0_16x8 */
  4442. else if( bits == 13 ) {
  4443. return decode_cabac_intra_mb_type(h, 32, 0) + 23;
  4444. } else if( bits == 14 )
  4445. return 11; /* B_L1_L0_8x16 */
  4446. else if( bits == 15 )
  4447. return 22; /* B_8x8 */
  4448. bits= ( bits<<1 ) | get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] );
  4449. return bits - 4; /* B_L0_Bi_* through B_Bi_Bi_* */
  4450. } else {
  4451. /* TODO SI/SP frames? */
  4452. return -1;
  4453. }
  4454. }
  4455. static int decode_cabac_mb_skip( H264Context *h, int mb_x, int mb_y ) {
  4456. MpegEncContext * const s = &h->s;
  4457. int mba_xy, mbb_xy;
  4458. int ctx = 0;
  4459. if(FRAME_MBAFF){ //FIXME merge with the stuff in fill_caches?
  4460. int mb_xy = mb_x + (mb_y&~1)*s->mb_stride;
  4461. mba_xy = mb_xy - 1;
  4462. if( (mb_y&1)
  4463. && h->slice_table[mba_xy] == h->slice_num
  4464. && MB_FIELD == !!IS_INTERLACED( s->current_picture.mb_type[mba_xy] ) )
  4465. mba_xy += s->mb_stride;
  4466. if( MB_FIELD ){
  4467. mbb_xy = mb_xy - s->mb_stride;
  4468. if( !(mb_y&1)
  4469. && h->slice_table[mbb_xy] == h->slice_num
  4470. && IS_INTERLACED( s->current_picture.mb_type[mbb_xy] ) )
  4471. mbb_xy -= s->mb_stride;
  4472. }else
  4473. mbb_xy = mb_x + (mb_y-1)*s->mb_stride;
  4474. }else{
  4475. int mb_xy = mb_x + mb_y*s->mb_stride;
  4476. mba_xy = mb_xy - 1;
  4477. mbb_xy = mb_xy - (s->mb_stride << FIELD_PICTURE);
  4478. }
  4479. if( h->slice_table[mba_xy] == h->slice_num && !IS_SKIP( s->current_picture.mb_type[mba_xy] ))
  4480. ctx++;
  4481. if( h->slice_table[mbb_xy] == h->slice_num && !IS_SKIP( s->current_picture.mb_type[mbb_xy] ))
  4482. ctx++;
  4483. if( h->slice_type == B_TYPE )
  4484. ctx += 13;
  4485. return get_cabac_noinline( &h->cabac, &h->cabac_state[11+ctx] );
  4486. }
  4487. static int decode_cabac_mb_intra4x4_pred_mode( H264Context *h, int pred_mode ) {
  4488. int mode = 0;
  4489. if( get_cabac( &h->cabac, &h->cabac_state[68] ) )
  4490. return pred_mode;
  4491. mode += 1 * get_cabac( &h->cabac, &h->cabac_state[69] );
  4492. mode += 2 * get_cabac( &h->cabac, &h->cabac_state[69] );
  4493. mode += 4 * get_cabac( &h->cabac, &h->cabac_state[69] );
  4494. if( mode >= pred_mode )
  4495. return mode + 1;
  4496. else
  4497. return mode;
  4498. }
  4499. static int decode_cabac_mb_chroma_pre_mode( H264Context *h) {
  4500. const int mba_xy = h->left_mb_xy[0];
  4501. const int mbb_xy = h->top_mb_xy;
  4502. int ctx = 0;
  4503. /* No need to test for IS_INTRA4x4 and IS_INTRA16x16, as we set chroma_pred_mode_table to 0 */
  4504. if( h->slice_table[mba_xy] == h->slice_num && h->chroma_pred_mode_table[mba_xy] != 0 )
  4505. ctx++;
  4506. if( h->slice_table[mbb_xy] == h->slice_num && h->chroma_pred_mode_table[mbb_xy] != 0 )
  4507. ctx++;
  4508. if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+ctx] ) == 0 )
  4509. return 0;
  4510. if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+3] ) == 0 )
  4511. return 1;
  4512. if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+3] ) == 0 )
  4513. return 2;
  4514. else
  4515. return 3;
  4516. }
  4517. static int decode_cabac_mb_cbp_luma( H264Context *h) {
  4518. int cbp_b, cbp_a, ctx, cbp = 0;
  4519. cbp_a = h->slice_table[h->left_mb_xy[0]] == h->slice_num ? h->left_cbp : -1;
  4520. cbp_b = h->slice_table[h->top_mb_xy] == h->slice_num ? h->top_cbp : -1;
  4521. ctx = !(cbp_a & 0x02) + 2 * !(cbp_b & 0x04);
  4522. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]);
  4523. ctx = !(cbp & 0x01) + 2 * !(cbp_b & 0x08);
  4524. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 1;
  4525. ctx = !(cbp_a & 0x08) + 2 * !(cbp & 0x01);
  4526. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 2;
  4527. ctx = !(cbp & 0x04) + 2 * !(cbp & 0x02);
  4528. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 3;
  4529. return cbp;
  4530. }
  4531. static int decode_cabac_mb_cbp_chroma( H264Context *h) {
  4532. int ctx;
  4533. int cbp_a, cbp_b;
  4534. cbp_a = (h->left_cbp>>4)&0x03;
  4535. cbp_b = (h-> top_cbp>>4)&0x03;
  4536. ctx = 0;
  4537. if( cbp_a > 0 ) ctx++;
  4538. if( cbp_b > 0 ) ctx += 2;
  4539. if( get_cabac_noinline( &h->cabac, &h->cabac_state[77 + ctx] ) == 0 )
  4540. return 0;
  4541. ctx = 4;
  4542. if( cbp_a == 2 ) ctx++;
  4543. if( cbp_b == 2 ) ctx += 2;
  4544. return 1 + get_cabac_noinline( &h->cabac, &h->cabac_state[77 + ctx] );
  4545. }
  4546. static int decode_cabac_mb_dqp( H264Context *h) {
  4547. int ctx = 0;
  4548. int val = 0;
  4549. if( h->last_qscale_diff != 0 )
  4550. ctx++;
  4551. while( get_cabac_noinline( &h->cabac, &h->cabac_state[60 + ctx] ) ) {
  4552. if( ctx < 2 )
  4553. ctx = 2;
  4554. else
  4555. ctx = 3;
  4556. val++;
  4557. if(val > 102) //prevent infinite loop
  4558. return INT_MIN;
  4559. }
  4560. if( val&0x01 )
  4561. return (val + 1)/2;
  4562. else
  4563. return -(val + 1)/2;
  4564. }
  4565. static int decode_cabac_p_mb_sub_type( H264Context *h ) {
  4566. if( get_cabac( &h->cabac, &h->cabac_state[21] ) )
  4567. return 0; /* 8x8 */
  4568. if( !get_cabac( &h->cabac, &h->cabac_state[22] ) )
  4569. return 1; /* 8x4 */
  4570. if( get_cabac( &h->cabac, &h->cabac_state[23] ) )
  4571. return 2; /* 4x8 */
  4572. return 3; /* 4x4 */
  4573. }
  4574. static int decode_cabac_b_mb_sub_type( H264Context *h ) {
  4575. int type;
  4576. if( !get_cabac( &h->cabac, &h->cabac_state[36] ) )
  4577. return 0; /* B_Direct_8x8 */
  4578. if( !get_cabac( &h->cabac, &h->cabac_state[37] ) )
  4579. return 1 + get_cabac( &h->cabac, &h->cabac_state[39] ); /* B_L0_8x8, B_L1_8x8 */
  4580. type = 3;
  4581. if( get_cabac( &h->cabac, &h->cabac_state[38] ) ) {
  4582. if( get_cabac( &h->cabac, &h->cabac_state[39] ) )
  4583. return 11 + get_cabac( &h->cabac, &h->cabac_state[39] ); /* B_L1_4x4, B_Bi_4x4 */
  4584. type += 4;
  4585. }
  4586. type += 2*get_cabac( &h->cabac, &h->cabac_state[39] );
  4587. type += get_cabac( &h->cabac, &h->cabac_state[39] );
  4588. return type;
  4589. }
  4590. static inline int decode_cabac_mb_transform_size( H264Context *h ) {
  4591. return get_cabac_noinline( &h->cabac, &h->cabac_state[399 + h->neighbor_transform_size] );
  4592. }
  4593. static int decode_cabac_mb_ref( H264Context *h, int list, int n ) {
  4594. int refa = h->ref_cache[list][scan8[n] - 1];
  4595. int refb = h->ref_cache[list][scan8[n] - 8];
  4596. int ref = 0;
  4597. int ctx = 0;
  4598. if( h->slice_type == B_TYPE) {
  4599. if( refa > 0 && !h->direct_cache[scan8[n] - 1] )
  4600. ctx++;
  4601. if( refb > 0 && !h->direct_cache[scan8[n] - 8] )
  4602. ctx += 2;
  4603. } else {
  4604. if( refa > 0 )
  4605. ctx++;
  4606. if( refb > 0 )
  4607. ctx += 2;
  4608. }
  4609. while( get_cabac( &h->cabac, &h->cabac_state[54+ctx] ) ) {
  4610. ref++;
  4611. if( ctx < 4 )
  4612. ctx = 4;
  4613. else
  4614. ctx = 5;
  4615. if(ref >= 32 /*h->ref_list[list]*/){
  4616. av_log(h->s.avctx, AV_LOG_ERROR, "overflow in decode_cabac_mb_ref\n");
  4617. return 0; //FIXME we should return -1 and check the return everywhere
  4618. }
  4619. }
  4620. return ref;
  4621. }
  4622. static int decode_cabac_mb_mvd( H264Context *h, int list, int n, int l ) {
  4623. int amvd = abs( h->mvd_cache[list][scan8[n] - 1][l] ) +
  4624. abs( h->mvd_cache[list][scan8[n] - 8][l] );
  4625. int ctxbase = (l == 0) ? 40 : 47;
  4626. int ctx, mvd;
  4627. if( amvd < 3 )
  4628. ctx = 0;
  4629. else if( amvd > 32 )
  4630. ctx = 2;
  4631. else
  4632. ctx = 1;
  4633. if(!get_cabac(&h->cabac, &h->cabac_state[ctxbase+ctx]))
  4634. return 0;
  4635. mvd= 1;
  4636. ctx= 3;
  4637. while( mvd < 9 && get_cabac( &h->cabac, &h->cabac_state[ctxbase+ctx] ) ) {
  4638. mvd++;
  4639. if( ctx < 6 )
  4640. ctx++;
  4641. }
  4642. if( mvd >= 9 ) {
  4643. int k = 3;
  4644. while( get_cabac_bypass( &h->cabac ) ) {
  4645. mvd += 1 << k;
  4646. k++;
  4647. if(k>24){
  4648. av_log(h->s.avctx, AV_LOG_ERROR, "overflow in decode_cabac_mb_mvd\n");
  4649. return INT_MIN;
  4650. }
  4651. }
  4652. while( k-- ) {
  4653. if( get_cabac_bypass( &h->cabac ) )
  4654. mvd += 1 << k;
  4655. }
  4656. }
  4657. return get_cabac_bypass_sign( &h->cabac, -mvd );
  4658. }
  4659. static inline int get_cabac_cbf_ctx( H264Context *h, int cat, int idx ) {
  4660. int nza, nzb;
  4661. int ctx = 0;
  4662. if( cat == 0 ) {
  4663. nza = h->left_cbp&0x100;
  4664. nzb = h-> top_cbp&0x100;
  4665. } else if( cat == 1 || cat == 2 ) {
  4666. nza = h->non_zero_count_cache[scan8[idx] - 1];
  4667. nzb = h->non_zero_count_cache[scan8[idx] - 8];
  4668. } else if( cat == 3 ) {
  4669. nza = (h->left_cbp>>(6+idx))&0x01;
  4670. nzb = (h-> top_cbp>>(6+idx))&0x01;
  4671. } else {
  4672. assert(cat == 4);
  4673. nza = h->non_zero_count_cache[scan8[16+idx] - 1];
  4674. nzb = h->non_zero_count_cache[scan8[16+idx] - 8];
  4675. }
  4676. if( nza > 0 )
  4677. ctx++;
  4678. if( nzb > 0 )
  4679. ctx += 2;
  4680. return ctx + 4 * cat;
  4681. }
  4682. static const attribute_used uint8_t last_coeff_flag_offset_8x8[63] = {
  4683. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  4684. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  4685. 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
  4686. 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8
  4687. };
  4688. static void decode_cabac_residual( H264Context *h, DCTELEM *block, int cat, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff) {
  4689. const int mb_xy = h->s.mb_x + h->s.mb_y*h->s.mb_stride;
  4690. static const int significant_coeff_flag_offset[2][6] = {
  4691. { 105+0, 105+15, 105+29, 105+44, 105+47, 402 },
  4692. { 277+0, 277+15, 277+29, 277+44, 277+47, 436 }
  4693. };
  4694. static const int last_coeff_flag_offset[2][6] = {
  4695. { 166+0, 166+15, 166+29, 166+44, 166+47, 417 },
  4696. { 338+0, 338+15, 338+29, 338+44, 338+47, 451 }
  4697. };
  4698. static const int coeff_abs_level_m1_offset[6] = {
  4699. 227+0, 227+10, 227+20, 227+30, 227+39, 426
  4700. };
  4701. static const uint8_t significant_coeff_flag_offset_8x8[2][63] = {
  4702. { 0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5,
  4703. 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9,10, 9, 8, 7,
  4704. 7, 6,11,12,13,11, 6, 7, 8, 9,14,10, 9, 8, 6,11,
  4705. 12,13,11, 6, 9,14,10, 9,11,12,13,11,14,10,12 },
  4706. { 0, 1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 7, 7, 8, 4, 5,
  4707. 6, 9,10,10, 8,11,12,11, 9, 9,10,10, 8,11,12,11,
  4708. 9, 9,10,10, 8,11,12,11, 9, 9,10,10, 8,13,13, 9,
  4709. 9,10,10, 8,13,13, 9, 9,10,10,14,14,14,14,14 }
  4710. };
  4711. int index[64];
  4712. int av_unused last;
  4713. int coeff_count = 0;
  4714. int abslevel1 = 1;
  4715. int abslevelgt1 = 0;
  4716. uint8_t *significant_coeff_ctx_base;
  4717. uint8_t *last_coeff_ctx_base;
  4718. uint8_t *abs_level_m1_ctx_base;
  4719. #ifndef ARCH_X86
  4720. #define CABAC_ON_STACK
  4721. #endif
  4722. #ifdef CABAC_ON_STACK
  4723. #define CC &cc
  4724. CABACContext cc;
  4725. cc.range = h->cabac.range;
  4726. cc.low = h->cabac.low;
  4727. cc.bytestream= h->cabac.bytestream;
  4728. #else
  4729. #define CC &h->cabac
  4730. #endif
  4731. /* cat: 0-> DC 16x16 n = 0
  4732. * 1-> AC 16x16 n = luma4x4idx
  4733. * 2-> Luma4x4 n = luma4x4idx
  4734. * 3-> DC Chroma n = iCbCr
  4735. * 4-> AC Chroma n = 4 * iCbCr + chroma4x4idx
  4736. * 5-> Luma8x8 n = 4 * luma8x8idx
  4737. */
  4738. /* read coded block flag */
  4739. if( cat != 5 ) {
  4740. if( get_cabac( CC, &h->cabac_state[85 + get_cabac_cbf_ctx( h, cat, n ) ] ) == 0 ) {
  4741. if( cat == 1 || cat == 2 )
  4742. h->non_zero_count_cache[scan8[n]] = 0;
  4743. else if( cat == 4 )
  4744. h->non_zero_count_cache[scan8[16+n]] = 0;
  4745. #ifdef CABAC_ON_STACK
  4746. h->cabac.range = cc.range ;
  4747. h->cabac.low = cc.low ;
  4748. h->cabac.bytestream= cc.bytestream;
  4749. #endif
  4750. return;
  4751. }
  4752. }
  4753. significant_coeff_ctx_base = h->cabac_state
  4754. + significant_coeff_flag_offset[MB_FIELD][cat];
  4755. last_coeff_ctx_base = h->cabac_state
  4756. + last_coeff_flag_offset[MB_FIELD][cat];
  4757. abs_level_m1_ctx_base = h->cabac_state
  4758. + coeff_abs_level_m1_offset[cat];
  4759. if( cat == 5 ) {
  4760. #define DECODE_SIGNIFICANCE( coefs, sig_off, last_off ) \
  4761. for(last= 0; last < coefs; last++) { \
  4762. uint8_t *sig_ctx = significant_coeff_ctx_base + sig_off; \
  4763. if( get_cabac( CC, sig_ctx )) { \
  4764. uint8_t *last_ctx = last_coeff_ctx_base + last_off; \
  4765. index[coeff_count++] = last; \
  4766. if( get_cabac( CC, last_ctx ) ) { \
  4767. last= max_coeff; \
  4768. break; \
  4769. } \
  4770. } \
  4771. }\
  4772. if( last == max_coeff -1 ) {\
  4773. index[coeff_count++] = last;\
  4774. }
  4775. const uint8_t *sig_off = significant_coeff_flag_offset_8x8[MB_FIELD];
  4776. #if defined(ARCH_X86) && defined(HAVE_7REGS) && defined(HAVE_EBX_AVAILABLE) && !defined(BROKEN_RELOCATIONS)
  4777. coeff_count= decode_significance_8x8_x86(CC, significant_coeff_ctx_base, index, sig_off);
  4778. } else {
  4779. coeff_count= decode_significance_x86(CC, max_coeff, significant_coeff_ctx_base, index);
  4780. #else
  4781. DECODE_SIGNIFICANCE( 63, sig_off[last], last_coeff_flag_offset_8x8[last] );
  4782. } else {
  4783. DECODE_SIGNIFICANCE( max_coeff - 1, last, last );
  4784. #endif
  4785. }
  4786. assert(coeff_count > 0);
  4787. if( cat == 0 )
  4788. h->cbp_table[mb_xy] |= 0x100;
  4789. else if( cat == 1 || cat == 2 )
  4790. h->non_zero_count_cache[scan8[n]] = coeff_count;
  4791. else if( cat == 3 )
  4792. h->cbp_table[mb_xy] |= 0x40 << n;
  4793. else if( cat == 4 )
  4794. h->non_zero_count_cache[scan8[16+n]] = coeff_count;
  4795. else {
  4796. assert( cat == 5 );
  4797. fill_rectangle(&h->non_zero_count_cache[scan8[n]], 2, 2, 8, coeff_count, 1);
  4798. }
  4799. for( coeff_count--; coeff_count >= 0; coeff_count-- ) {
  4800. uint8_t *ctx = (abslevelgt1 != 0 ? 0 : FFMIN( 4, abslevel1 )) + abs_level_m1_ctx_base;
  4801. int j= scantable[index[coeff_count]];
  4802. if( get_cabac( CC, ctx ) == 0 ) {
  4803. if( !qmul ) {
  4804. block[j] = get_cabac_bypass_sign( CC, -1);
  4805. }else{
  4806. block[j] = (get_cabac_bypass_sign( CC, -qmul[j]) + 32) >> 6;;
  4807. }
  4808. abslevel1++;
  4809. } else {
  4810. int coeff_abs = 2;
  4811. ctx = 5 + FFMIN( 4, abslevelgt1 ) + abs_level_m1_ctx_base;
  4812. while( coeff_abs < 15 && get_cabac( CC, ctx ) ) {
  4813. coeff_abs++;
  4814. }
  4815. if( coeff_abs >= 15 ) {
  4816. int j = 0;
  4817. while( get_cabac_bypass( CC ) ) {
  4818. j++;
  4819. }
  4820. coeff_abs=1;
  4821. while( j-- ) {
  4822. coeff_abs += coeff_abs + get_cabac_bypass( CC );
  4823. }
  4824. coeff_abs+= 14;
  4825. }
  4826. if( !qmul ) {
  4827. if( get_cabac_bypass( CC ) ) block[j] = -coeff_abs;
  4828. else block[j] = coeff_abs;
  4829. }else{
  4830. if( get_cabac_bypass( CC ) ) block[j] = (-coeff_abs * qmul[j] + 32) >> 6;
  4831. else block[j] = ( coeff_abs * qmul[j] + 32) >> 6;
  4832. }
  4833. abslevelgt1++;
  4834. }
  4835. }
  4836. #ifdef CABAC_ON_STACK
  4837. h->cabac.range = cc.range ;
  4838. h->cabac.low = cc.low ;
  4839. h->cabac.bytestream= cc.bytestream;
  4840. #endif
  4841. }
  4842. static inline void compute_mb_neighbors(H264Context *h)
  4843. {
  4844. MpegEncContext * const s = &h->s;
  4845. const int mb_xy = s->mb_x + s->mb_y*s->mb_stride;
  4846. h->top_mb_xy = mb_xy - s->mb_stride;
  4847. h->left_mb_xy[0] = mb_xy - 1;
  4848. if(FRAME_MBAFF){
  4849. const int pair_xy = s->mb_x + (s->mb_y & ~1)*s->mb_stride;
  4850. const int top_pair_xy = pair_xy - s->mb_stride;
  4851. const int top_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[top_pair_xy]);
  4852. const int left_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[pair_xy-1]);
  4853. const int curr_mb_frame_flag = !MB_FIELD;
  4854. const int bottom = (s->mb_y & 1);
  4855. if (bottom
  4856. ? !curr_mb_frame_flag // bottom macroblock
  4857. : (!curr_mb_frame_flag && !top_mb_frame_flag) // top macroblock
  4858. ) {
  4859. h->top_mb_xy -= s->mb_stride;
  4860. }
  4861. if (left_mb_frame_flag != curr_mb_frame_flag) {
  4862. h->left_mb_xy[0] = pair_xy - 1;
  4863. }
  4864. } else if (FIELD_PICTURE) {
  4865. h->top_mb_xy -= s->mb_stride;
  4866. }
  4867. return;
  4868. }
  4869. /**
  4870. * decodes a macroblock
  4871. * @returns 0 if ok, AC_ERROR / DC_ERROR / MV_ERROR if an error is noticed
  4872. */
  4873. static int decode_mb_cabac(H264Context *h) {
  4874. MpegEncContext * const s = &h->s;
  4875. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  4876. int mb_type, partition_count, cbp = 0;
  4877. int dct8x8_allowed= h->pps.transform_8x8_mode;
  4878. s->dsp.clear_blocks(h->mb); //FIXME avoid if already clear (move after skip handlong?)
  4879. tprintf(s->avctx, "pic:%d mb:%d/%d\n", h->frame_num, s->mb_x, s->mb_y);
  4880. if( h->slice_type != I_TYPE && h->slice_type != SI_TYPE ) {
  4881. int skip;
  4882. /* a skipped mb needs the aff flag from the following mb */
  4883. if( FRAME_MBAFF && s->mb_x==0 && (s->mb_y&1)==0 )
  4884. predict_field_decoding_flag(h);
  4885. if( FRAME_MBAFF && (s->mb_y&1)==1 && h->prev_mb_skipped )
  4886. skip = h->next_mb_skipped;
  4887. else
  4888. skip = decode_cabac_mb_skip( h, s->mb_x, s->mb_y );
  4889. /* read skip flags */
  4890. if( skip ) {
  4891. if( FRAME_MBAFF && (s->mb_y&1)==0 ){
  4892. s->current_picture.mb_type[mb_xy] = MB_TYPE_SKIP;
  4893. h->next_mb_skipped = decode_cabac_mb_skip( h, s->mb_x, s->mb_y+1 );
  4894. if(h->next_mb_skipped)
  4895. predict_field_decoding_flag(h);
  4896. else
  4897. h->mb_mbaff = h->mb_field_decoding_flag = decode_cabac_field_decoding_flag(h);
  4898. }
  4899. decode_mb_skip(h);
  4900. h->cbp_table[mb_xy] = 0;
  4901. h->chroma_pred_mode_table[mb_xy] = 0;
  4902. h->last_qscale_diff = 0;
  4903. return 0;
  4904. }
  4905. }
  4906. if(FRAME_MBAFF){
  4907. if( (s->mb_y&1) == 0 )
  4908. h->mb_mbaff =
  4909. h->mb_field_decoding_flag = decode_cabac_field_decoding_flag(h);
  4910. }else
  4911. h->mb_field_decoding_flag= (s->picture_structure!=PICT_FRAME);
  4912. h->prev_mb_skipped = 0;
  4913. compute_mb_neighbors(h);
  4914. if( ( mb_type = decode_cabac_mb_type( h ) ) < 0 ) {
  4915. av_log( h->s.avctx, AV_LOG_ERROR, "decode_cabac_mb_type failed\n" );
  4916. return -1;
  4917. }
  4918. if( h->slice_type == B_TYPE ) {
  4919. if( mb_type < 23 ){
  4920. partition_count= b_mb_type_info[mb_type].partition_count;
  4921. mb_type= b_mb_type_info[mb_type].type;
  4922. }else{
  4923. mb_type -= 23;
  4924. goto decode_intra_mb;
  4925. }
  4926. } else if( h->slice_type == P_TYPE ) {
  4927. if( mb_type < 5) {
  4928. partition_count= p_mb_type_info[mb_type].partition_count;
  4929. mb_type= p_mb_type_info[mb_type].type;
  4930. } else {
  4931. mb_type -= 5;
  4932. goto decode_intra_mb;
  4933. }
  4934. } else {
  4935. assert(h->slice_type == I_TYPE);
  4936. decode_intra_mb:
  4937. partition_count = 0;
  4938. cbp= i_mb_type_info[mb_type].cbp;
  4939. h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;
  4940. mb_type= i_mb_type_info[mb_type].type;
  4941. }
  4942. if(MB_FIELD)
  4943. mb_type |= MB_TYPE_INTERLACED;
  4944. h->slice_table[ mb_xy ]= h->slice_num;
  4945. if(IS_INTRA_PCM(mb_type)) {
  4946. const uint8_t *ptr;
  4947. unsigned int x, y;
  4948. // We assume these blocks are very rare so we do not optimize it.
  4949. // FIXME The two following lines get the bitstream position in the cabac
  4950. // decode, I think it should be done by a function in cabac.h (or cabac.c).
  4951. ptr= h->cabac.bytestream;
  4952. if(h->cabac.low&0x1) ptr--;
  4953. if(CABAC_BITS==16){
  4954. if(h->cabac.low&0x1FF) ptr--;
  4955. }
  4956. // The pixels are stored in the same order as levels in h->mb array.
  4957. for(y=0; y<16; y++){
  4958. const int index= 4*(y&3) + 32*((y>>2)&1) + 128*(y>>3);
  4959. for(x=0; x<16; x++){
  4960. tprintf(s->avctx, "LUMA ICPM LEVEL (%3d)\n", *ptr);
  4961. h->mb[index + (x&3) + 16*((x>>2)&1) + 64*(x>>3)]= *ptr++;
  4962. }
  4963. }
  4964. for(y=0; y<8; y++){
  4965. const int index= 256 + 4*(y&3) + 32*(y>>2);
  4966. for(x=0; x<8; x++){
  4967. tprintf(s->avctx, "CHROMA U ICPM LEVEL (%3d)\n", *ptr);
  4968. h->mb[index + (x&3) + 16*(x>>2)]= *ptr++;
  4969. }
  4970. }
  4971. for(y=0; y<8; y++){
  4972. const int index= 256 + 64 + 4*(y&3) + 32*(y>>2);
  4973. for(x=0; x<8; x++){
  4974. tprintf(s->avctx, "CHROMA V ICPM LEVEL (%3d)\n", *ptr);
  4975. h->mb[index + (x&3) + 16*(x>>2)]= *ptr++;
  4976. }
  4977. }
  4978. ff_init_cabac_decoder(&h->cabac, ptr, h->cabac.bytestream_end - ptr);
  4979. // All blocks are present
  4980. h->cbp_table[mb_xy] = 0x1ef;
  4981. h->chroma_pred_mode_table[mb_xy] = 0;
  4982. // In deblocking, the quantizer is 0
  4983. s->current_picture.qscale_table[mb_xy]= 0;
  4984. h->chroma_qp[0] = get_chroma_qp(h, 0, 0);
  4985. h->chroma_qp[1] = get_chroma_qp(h, 1, 0);
  4986. // All coeffs are present
  4987. memset(h->non_zero_count[mb_xy], 16, 16);
  4988. s->current_picture.mb_type[mb_xy]= mb_type;
  4989. return 0;
  4990. }
  4991. if(MB_MBAFF){
  4992. h->ref_count[0] <<= 1;
  4993. h->ref_count[1] <<= 1;
  4994. }
  4995. fill_caches(h, mb_type, 0);
  4996. if( IS_INTRA( mb_type ) ) {
  4997. int i, pred_mode;
  4998. if( IS_INTRA4x4( mb_type ) ) {
  4999. if( dct8x8_allowed && decode_cabac_mb_transform_size( h ) ) {
  5000. mb_type |= MB_TYPE_8x8DCT;
  5001. for( i = 0; i < 16; i+=4 ) {
  5002. int pred = pred_intra_mode( h, i );
  5003. int mode = decode_cabac_mb_intra4x4_pred_mode( h, pred );
  5004. fill_rectangle( &h->intra4x4_pred_mode_cache[ scan8[i] ], 2, 2, 8, mode, 1 );
  5005. }
  5006. } else {
  5007. for( i = 0; i < 16; i++ ) {
  5008. int pred = pred_intra_mode( h, i );
  5009. h->intra4x4_pred_mode_cache[ scan8[i] ] = decode_cabac_mb_intra4x4_pred_mode( h, pred );
  5010. //av_log( s->avctx, AV_LOG_ERROR, "i4x4 pred=%d mode=%d\n", pred, h->intra4x4_pred_mode_cache[ scan8[i] ] );
  5011. }
  5012. }
  5013. write_back_intra_pred_mode(h);
  5014. if( check_intra4x4_pred_mode(h) < 0 ) return -1;
  5015. } else {
  5016. h->intra16x16_pred_mode= check_intra_pred_mode( h, h->intra16x16_pred_mode );
  5017. if( h->intra16x16_pred_mode < 0 ) return -1;
  5018. }
  5019. h->chroma_pred_mode_table[mb_xy] =
  5020. pred_mode = decode_cabac_mb_chroma_pre_mode( h );
  5021. pred_mode= check_intra_pred_mode( h, pred_mode );
  5022. if( pred_mode < 0 ) return -1;
  5023. h->chroma_pred_mode= pred_mode;
  5024. } else if( partition_count == 4 ) {
  5025. int i, j, sub_partition_count[4], list, ref[2][4];
  5026. if( h->slice_type == B_TYPE ) {
  5027. for( i = 0; i < 4; i++ ) {
  5028. h->sub_mb_type[i] = decode_cabac_b_mb_sub_type( h );
  5029. sub_partition_count[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  5030. h->sub_mb_type[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  5031. }
  5032. if( IS_DIRECT(h->sub_mb_type[0] | h->sub_mb_type[1] |
  5033. h->sub_mb_type[2] | h->sub_mb_type[3]) ) {
  5034. pred_direct_motion(h, &mb_type);
  5035. h->ref_cache[0][scan8[4]] =
  5036. h->ref_cache[1][scan8[4]] =
  5037. h->ref_cache[0][scan8[12]] =
  5038. h->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;
  5039. if( h->ref_count[0] > 1 || h->ref_count[1] > 1 ) {
  5040. for( i = 0; i < 4; i++ )
  5041. if( IS_DIRECT(h->sub_mb_type[i]) )
  5042. fill_rectangle( &h->direct_cache[scan8[4*i]], 2, 2, 8, 1, 1 );
  5043. }
  5044. }
  5045. } else {
  5046. for( i = 0; i < 4; i++ ) {
  5047. h->sub_mb_type[i] = decode_cabac_p_mb_sub_type( h );
  5048. sub_partition_count[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  5049. h->sub_mb_type[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  5050. }
  5051. }
  5052. for( list = 0; list < h->list_count; list++ ) {
  5053. for( i = 0; i < 4; i++ ) {
  5054. if(IS_DIRECT(h->sub_mb_type[i])) continue;
  5055. if(IS_DIR(h->sub_mb_type[i], 0, list)){
  5056. if( h->ref_count[list] > 1 )
  5057. ref[list][i] = decode_cabac_mb_ref( h, list, 4*i );
  5058. else
  5059. ref[list][i] = 0;
  5060. } else {
  5061. ref[list][i] = -1;
  5062. }
  5063. h->ref_cache[list][ scan8[4*i]+1 ]=
  5064. h->ref_cache[list][ scan8[4*i]+8 ]=h->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];
  5065. }
  5066. }
  5067. if(dct8x8_allowed)
  5068. dct8x8_allowed = get_dct8x8_allowed(h);
  5069. for(list=0; list<h->list_count; list++){
  5070. for(i=0; i<4; i++){
  5071. h->ref_cache[list][ scan8[4*i] ]=h->ref_cache[list][ scan8[4*i]+1 ];
  5072. if(IS_DIRECT(h->sub_mb_type[i])){
  5073. fill_rectangle(h->mvd_cache[list][scan8[4*i]], 2, 2, 8, 0, 4);
  5074. continue;
  5075. }
  5076. if(IS_DIR(h->sub_mb_type[i], 0, list) && !IS_DIRECT(h->sub_mb_type[i])){
  5077. const int sub_mb_type= h->sub_mb_type[i];
  5078. const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;
  5079. for(j=0; j<sub_partition_count[i]; j++){
  5080. int mpx, mpy;
  5081. int mx, my;
  5082. const int index= 4*i + block_width*j;
  5083. int16_t (* mv_cache)[2]= &h->mv_cache[list][ scan8[index] ];
  5084. int16_t (* mvd_cache)[2]= &h->mvd_cache[list][ scan8[index] ];
  5085. pred_motion(h, index, block_width, list, h->ref_cache[list][ scan8[index] ], &mpx, &mpy);
  5086. mx = mpx + decode_cabac_mb_mvd( h, list, index, 0 );
  5087. my = mpy + decode_cabac_mb_mvd( h, list, index, 1 );
  5088. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5089. if(IS_SUB_8X8(sub_mb_type)){
  5090. mv_cache[ 1 ][0]=
  5091. mv_cache[ 8 ][0]= mv_cache[ 9 ][0]= mx;
  5092. mv_cache[ 1 ][1]=
  5093. mv_cache[ 8 ][1]= mv_cache[ 9 ][1]= my;
  5094. mvd_cache[ 1 ][0]=
  5095. mvd_cache[ 8 ][0]= mvd_cache[ 9 ][0]= mx - mpx;
  5096. mvd_cache[ 1 ][1]=
  5097. mvd_cache[ 8 ][1]= mvd_cache[ 9 ][1]= my - mpy;
  5098. }else if(IS_SUB_8X4(sub_mb_type)){
  5099. mv_cache[ 1 ][0]= mx;
  5100. mv_cache[ 1 ][1]= my;
  5101. mvd_cache[ 1 ][0]= mx - mpx;
  5102. mvd_cache[ 1 ][1]= my - mpy;
  5103. }else if(IS_SUB_4X8(sub_mb_type)){
  5104. mv_cache[ 8 ][0]= mx;
  5105. mv_cache[ 8 ][1]= my;
  5106. mvd_cache[ 8 ][0]= mx - mpx;
  5107. mvd_cache[ 8 ][1]= my - mpy;
  5108. }
  5109. mv_cache[ 0 ][0]= mx;
  5110. mv_cache[ 0 ][1]= my;
  5111. mvd_cache[ 0 ][0]= mx - mpx;
  5112. mvd_cache[ 0 ][1]= my - mpy;
  5113. }
  5114. }else{
  5115. uint32_t *p= (uint32_t *)&h->mv_cache[list][ scan8[4*i] ][0];
  5116. uint32_t *pd= (uint32_t *)&h->mvd_cache[list][ scan8[4*i] ][0];
  5117. p[0] = p[1] = p[8] = p[9] = 0;
  5118. pd[0]= pd[1]= pd[8]= pd[9]= 0;
  5119. }
  5120. }
  5121. }
  5122. } else if( IS_DIRECT(mb_type) ) {
  5123. pred_direct_motion(h, &mb_type);
  5124. fill_rectangle(h->mvd_cache[0][scan8[0]], 4, 4, 8, 0, 4);
  5125. fill_rectangle(h->mvd_cache[1][scan8[0]], 4, 4, 8, 0, 4);
  5126. dct8x8_allowed &= h->sps.direct_8x8_inference_flag;
  5127. } else {
  5128. int list, mx, my, i, mpx, mpy;
  5129. if(IS_16X16(mb_type)){
  5130. for(list=0; list<h->list_count; list++){
  5131. if(IS_DIR(mb_type, 0, list)){
  5132. const int ref = h->ref_count[list] > 1 ? decode_cabac_mb_ref( h, list, 0 ) : 0;
  5133. fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, ref, 1);
  5134. }else
  5135. fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, (uint8_t)LIST_NOT_USED, 1); //FIXME factorize and the other fill_rect below too
  5136. }
  5137. for(list=0; list<h->list_count; list++){
  5138. if(IS_DIR(mb_type, 0, list)){
  5139. pred_motion(h, 0, 4, list, h->ref_cache[list][ scan8[0] ], &mpx, &mpy);
  5140. mx = mpx + decode_cabac_mb_mvd( h, list, 0, 0 );
  5141. my = mpy + decode_cabac_mb_mvd( h, list, 0, 1 );
  5142. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5143. fill_rectangle(h->mvd_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx-mpx,my-mpy), 4);
  5144. fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx,my), 4);
  5145. }else
  5146. fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, 0, 4);
  5147. }
  5148. }
  5149. else if(IS_16X8(mb_type)){
  5150. for(list=0; list<h->list_count; list++){
  5151. for(i=0; i<2; i++){
  5152. if(IS_DIR(mb_type, i, list)){
  5153. const int ref= h->ref_count[list] > 1 ? decode_cabac_mb_ref( h, list, 8*i ) : 0;
  5154. fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, ref, 1);
  5155. }else
  5156. fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, (LIST_NOT_USED&0xFF), 1);
  5157. }
  5158. }
  5159. for(list=0; list<h->list_count; list++){
  5160. for(i=0; i<2; i++){
  5161. if(IS_DIR(mb_type, i, list)){
  5162. pred_16x8_motion(h, 8*i, list, h->ref_cache[list][scan8[0] + 16*i], &mpx, &mpy);
  5163. mx = mpx + decode_cabac_mb_mvd( h, list, 8*i, 0 );
  5164. my = mpy + decode_cabac_mb_mvd( h, list, 8*i, 1 );
  5165. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5166. fill_rectangle(h->mvd_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack16to32(mx-mpx,my-mpy), 4);
  5167. fill_rectangle(h->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack16to32(mx,my), 4);
  5168. }else{
  5169. fill_rectangle(h->mvd_cache[list][ scan8[0] + 16*i ], 4, 2, 8, 0, 4);
  5170. fill_rectangle(h-> mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, 0, 4);
  5171. }
  5172. }
  5173. }
  5174. }else{
  5175. assert(IS_8X16(mb_type));
  5176. for(list=0; list<h->list_count; list++){
  5177. for(i=0; i<2; i++){
  5178. if(IS_DIR(mb_type, i, list)){ //FIXME optimize
  5179. const int ref= h->ref_count[list] > 1 ? decode_cabac_mb_ref( h, list, 4*i ) : 0;
  5180. fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, ref, 1);
  5181. }else
  5182. fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, (LIST_NOT_USED&0xFF), 1);
  5183. }
  5184. }
  5185. for(list=0; list<h->list_count; list++){
  5186. for(i=0; i<2; i++){
  5187. if(IS_DIR(mb_type, i, list)){
  5188. pred_8x16_motion(h, i*4, list, h->ref_cache[list][ scan8[0] + 2*i ], &mpx, &mpy);
  5189. mx = mpx + decode_cabac_mb_mvd( h, list, 4*i, 0 );
  5190. my = mpy + decode_cabac_mb_mvd( h, list, 4*i, 1 );
  5191. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5192. fill_rectangle(h->mvd_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack16to32(mx-mpx,my-mpy), 4);
  5193. fill_rectangle(h->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack16to32(mx,my), 4);
  5194. }else{
  5195. fill_rectangle(h->mvd_cache[list][ scan8[0] + 2*i ], 2, 4, 8, 0, 4);
  5196. fill_rectangle(h-> mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, 0, 4);
  5197. }
  5198. }
  5199. }
  5200. }
  5201. }
  5202. if( IS_INTER( mb_type ) ) {
  5203. h->chroma_pred_mode_table[mb_xy] = 0;
  5204. write_back_motion( h, mb_type );
  5205. }
  5206. if( !IS_INTRA16x16( mb_type ) ) {
  5207. cbp = decode_cabac_mb_cbp_luma( h );
  5208. cbp |= decode_cabac_mb_cbp_chroma( h ) << 4;
  5209. }
  5210. h->cbp_table[mb_xy] = h->cbp = cbp;
  5211. if( dct8x8_allowed && (cbp&15) && !IS_INTRA( mb_type ) ) {
  5212. if( decode_cabac_mb_transform_size( h ) )
  5213. mb_type |= MB_TYPE_8x8DCT;
  5214. }
  5215. s->current_picture.mb_type[mb_xy]= mb_type;
  5216. if( cbp || IS_INTRA16x16( mb_type ) ) {
  5217. const uint8_t *scan, *scan8x8, *dc_scan;
  5218. const uint32_t *qmul;
  5219. int dqp;
  5220. if(IS_INTERLACED(mb_type)){
  5221. scan8x8= s->qscale ? h->field_scan8x8 : h->field_scan8x8_q0;
  5222. scan= s->qscale ? h->field_scan : h->field_scan_q0;
  5223. dc_scan= luma_dc_field_scan;
  5224. }else{
  5225. scan8x8= s->qscale ? h->zigzag_scan8x8 : h->zigzag_scan8x8_q0;
  5226. scan= s->qscale ? h->zigzag_scan : h->zigzag_scan_q0;
  5227. dc_scan= luma_dc_zigzag_scan;
  5228. }
  5229. h->last_qscale_diff = dqp = decode_cabac_mb_dqp( h );
  5230. if( dqp == INT_MIN ){
  5231. av_log(h->s.avctx, AV_LOG_ERROR, "cabac decode of qscale diff failed at %d %d\n", s->mb_x, s->mb_y);
  5232. return -1;
  5233. }
  5234. s->qscale += dqp;
  5235. if(((unsigned)s->qscale) > 51){
  5236. if(s->qscale<0) s->qscale+= 52;
  5237. else s->qscale-= 52;
  5238. }
  5239. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  5240. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  5241. if( IS_INTRA16x16( mb_type ) ) {
  5242. int i;
  5243. //av_log( s->avctx, AV_LOG_ERROR, "INTRA16x16 DC\n" );
  5244. decode_cabac_residual( h, h->mb, 0, 0, dc_scan, NULL, 16);
  5245. if( cbp&15 ) {
  5246. qmul = h->dequant4_coeff[0][s->qscale];
  5247. for( i = 0; i < 16; i++ ) {
  5248. //av_log( s->avctx, AV_LOG_ERROR, "INTRA16x16 AC:%d\n", i );
  5249. decode_cabac_residual(h, h->mb + 16*i, 1, i, scan + 1, qmul, 15);
  5250. }
  5251. } else {
  5252. fill_rectangle(&h->non_zero_count_cache[scan8[0]], 4, 4, 8, 0, 1);
  5253. }
  5254. } else {
  5255. int i8x8, i4x4;
  5256. for( i8x8 = 0; i8x8 < 4; i8x8++ ) {
  5257. if( cbp & (1<<i8x8) ) {
  5258. if( IS_8x8DCT(mb_type) ) {
  5259. decode_cabac_residual(h, h->mb + 64*i8x8, 5, 4*i8x8,
  5260. scan8x8, h->dequant8_coeff[IS_INTRA( mb_type ) ? 0:1][s->qscale], 64);
  5261. } else {
  5262. qmul = h->dequant4_coeff[IS_INTRA( mb_type ) ? 0:3][s->qscale];
  5263. for( i4x4 = 0; i4x4 < 4; i4x4++ ) {
  5264. const int index = 4*i8x8 + i4x4;
  5265. //av_log( s->avctx, AV_LOG_ERROR, "Luma4x4: %d\n", index );
  5266. //START_TIMER
  5267. decode_cabac_residual(h, h->mb + 16*index, 2, index, scan, qmul, 16);
  5268. //STOP_TIMER("decode_residual")
  5269. }
  5270. }
  5271. } else {
  5272. uint8_t * const nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
  5273. nnz[0] = nnz[1] = nnz[8] = nnz[9] = 0;
  5274. }
  5275. }
  5276. }
  5277. if( cbp&0x30 ){
  5278. int c;
  5279. for( c = 0; c < 2; c++ ) {
  5280. //av_log( s->avctx, AV_LOG_ERROR, "INTRA C%d-DC\n",c );
  5281. decode_cabac_residual(h, h->mb + 256 + 16*4*c, 3, c, chroma_dc_scan, NULL, 4);
  5282. }
  5283. }
  5284. if( cbp&0x20 ) {
  5285. int c, i;
  5286. for( c = 0; c < 2; c++ ) {
  5287. qmul = h->dequant4_coeff[c+1+(IS_INTRA( mb_type ) ? 0:3)][h->chroma_qp[c]];
  5288. for( i = 0; i < 4; i++ ) {
  5289. const int index = 16 + 4 * c + i;
  5290. //av_log( s->avctx, AV_LOG_ERROR, "INTRA C%d-AC %d\n",c, index - 16 );
  5291. decode_cabac_residual(h, h->mb + 16*index, 4, index - 16, scan + 1, qmul, 15);
  5292. }
  5293. }
  5294. } else {
  5295. uint8_t * const nnz= &h->non_zero_count_cache[0];
  5296. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  5297. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  5298. }
  5299. } else {
  5300. uint8_t * const nnz= &h->non_zero_count_cache[0];
  5301. fill_rectangle(&nnz[scan8[0]], 4, 4, 8, 0, 1);
  5302. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  5303. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  5304. h->last_qscale_diff = 0;
  5305. }
  5306. s->current_picture.qscale_table[mb_xy]= s->qscale;
  5307. write_back_non_zero_count(h);
  5308. if(MB_MBAFF){
  5309. h->ref_count[0] >>= 1;
  5310. h->ref_count[1] >>= 1;
  5311. }
  5312. return 0;
  5313. }
  5314. static void filter_mb_edgev( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5315. int i, d;
  5316. const int index_a = qp + h->slice_alpha_c0_offset;
  5317. const int alpha = (alpha_table+52)[index_a];
  5318. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5319. if( bS[0] < 4 ) {
  5320. int8_t tc[4];
  5321. for(i=0; i<4; i++)
  5322. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] : -1;
  5323. h->s.dsp.h264_h_loop_filter_luma(pix, stride, alpha, beta, tc);
  5324. } else {
  5325. /* 16px edge length, because bS=4 is triggered by being at
  5326. * the edge of an intra MB, so all 4 bS are the same */
  5327. for( d = 0; d < 16; d++ ) {
  5328. const int p0 = pix[-1];
  5329. const int p1 = pix[-2];
  5330. const int p2 = pix[-3];
  5331. const int q0 = pix[0];
  5332. const int q1 = pix[1];
  5333. const int q2 = pix[2];
  5334. if( FFABS( p0 - q0 ) < alpha &&
  5335. FFABS( p1 - p0 ) < beta &&
  5336. FFABS( q1 - q0 ) < beta ) {
  5337. if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){
  5338. if( FFABS( p2 - p0 ) < beta)
  5339. {
  5340. const int p3 = pix[-4];
  5341. /* p0', p1', p2' */
  5342. pix[-1] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;
  5343. pix[-2] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;
  5344. pix[-3] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;
  5345. } else {
  5346. /* p0' */
  5347. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5348. }
  5349. if( FFABS( q2 - q0 ) < beta)
  5350. {
  5351. const int q3 = pix[3];
  5352. /* q0', q1', q2' */
  5353. pix[0] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;
  5354. pix[1] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;
  5355. pix[2] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;
  5356. } else {
  5357. /* q0' */
  5358. pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5359. }
  5360. }else{
  5361. /* p0', q0' */
  5362. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5363. pix[ 0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5364. }
  5365. tprintf(h->s.avctx, "filter_mb_edgev i:%d d:%d\n# bS:4 -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x]\n", i, d, p2, p1, p0, q0, q1, q2, pix[-2], pix[-1], pix[0], pix[1]);
  5366. }
  5367. pix += stride;
  5368. }
  5369. }
  5370. }
  5371. static void filter_mb_edgecv( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5372. int i;
  5373. const int index_a = qp + h->slice_alpha_c0_offset;
  5374. const int alpha = (alpha_table+52)[index_a];
  5375. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5376. if( bS[0] < 4 ) {
  5377. int8_t tc[4];
  5378. for(i=0; i<4; i++)
  5379. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] + 1 : 0;
  5380. h->s.dsp.h264_h_loop_filter_chroma(pix, stride, alpha, beta, tc);
  5381. } else {
  5382. h->s.dsp.h264_h_loop_filter_chroma_intra(pix, stride, alpha, beta);
  5383. }
  5384. }
  5385. static void filter_mb_mbaff_edgev( H264Context *h, uint8_t *pix, int stride, int16_t bS[8], int qp[2] ) {
  5386. int i;
  5387. for( i = 0; i < 16; i++, pix += stride) {
  5388. int index_a;
  5389. int alpha;
  5390. int beta;
  5391. int qp_index;
  5392. int bS_index = (i >> 1);
  5393. if (!MB_FIELD) {
  5394. bS_index &= ~1;
  5395. bS_index |= (i & 1);
  5396. }
  5397. if( bS[bS_index] == 0 ) {
  5398. continue;
  5399. }
  5400. qp_index = MB_FIELD ? (i >> 3) : (i & 1);
  5401. index_a = qp[qp_index] + h->slice_alpha_c0_offset;
  5402. alpha = (alpha_table+52)[index_a];
  5403. beta = (beta_table+52)[qp[qp_index] + h->slice_beta_offset];
  5404. if( bS[bS_index] < 4 ) {
  5405. const int tc0 = (tc0_table+52)[index_a][bS[bS_index] - 1];
  5406. const int p0 = pix[-1];
  5407. const int p1 = pix[-2];
  5408. const int p2 = pix[-3];
  5409. const int q0 = pix[0];
  5410. const int q1 = pix[1];
  5411. const int q2 = pix[2];
  5412. if( FFABS( p0 - q0 ) < alpha &&
  5413. FFABS( p1 - p0 ) < beta &&
  5414. FFABS( q1 - q0 ) < beta ) {
  5415. int tc = tc0;
  5416. int i_delta;
  5417. if( FFABS( p2 - p0 ) < beta ) {
  5418. pix[-2] = p1 + av_clip( ( p2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( p1 << 1 ) ) >> 1, -tc0, tc0 );
  5419. tc++;
  5420. }
  5421. if( FFABS( q2 - q0 ) < beta ) {
  5422. pix[1] = q1 + av_clip( ( q2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( q1 << 1 ) ) >> 1, -tc0, tc0 );
  5423. tc++;
  5424. }
  5425. i_delta = av_clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );
  5426. pix[-1] = av_clip_uint8( p0 + i_delta ); /* p0' */
  5427. pix[0] = av_clip_uint8( q0 - i_delta ); /* q0' */
  5428. tprintf(h->s.avctx, "filter_mb_mbaff_edgev i:%d, qp:%d, indexA:%d, alpha:%d, beta:%d, tc:%d\n# bS:%d -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x]\n", i, qp[qp_index], index_a, alpha, beta, tc, bS[bS_index], pix[-3], p1, p0, q0, q1, pix[2], p1, pix[-1], pix[0], q1);
  5429. }
  5430. }else{
  5431. const int p0 = pix[-1];
  5432. const int p1 = pix[-2];
  5433. const int p2 = pix[-3];
  5434. const int q0 = pix[0];
  5435. const int q1 = pix[1];
  5436. const int q2 = pix[2];
  5437. if( FFABS( p0 - q0 ) < alpha &&
  5438. FFABS( p1 - p0 ) < beta &&
  5439. FFABS( q1 - q0 ) < beta ) {
  5440. if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){
  5441. if( FFABS( p2 - p0 ) < beta)
  5442. {
  5443. const int p3 = pix[-4];
  5444. /* p0', p1', p2' */
  5445. pix[-1] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;
  5446. pix[-2] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;
  5447. pix[-3] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;
  5448. } else {
  5449. /* p0' */
  5450. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5451. }
  5452. if( FFABS( q2 - q0 ) < beta)
  5453. {
  5454. const int q3 = pix[3];
  5455. /* q0', q1', q2' */
  5456. pix[0] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;
  5457. pix[1] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;
  5458. pix[2] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;
  5459. } else {
  5460. /* q0' */
  5461. pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5462. }
  5463. }else{
  5464. /* p0', q0' */
  5465. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5466. pix[ 0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5467. }
  5468. tprintf(h->s.avctx, "filter_mb_mbaff_edgev i:%d, qp:%d, indexA:%d, alpha:%d, beta:%d\n# bS:4 -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x, %02x, %02x]\n", i, qp[qp_index], index_a, alpha, beta, p2, p1, p0, q0, q1, q2, pix[-3], pix[-2], pix[-1], pix[0], pix[1], pix[2]);
  5469. }
  5470. }
  5471. }
  5472. }
  5473. static void filter_mb_mbaff_edgecv( H264Context *h, uint8_t *pix, int stride, int16_t bS[8], int qp[2] ) {
  5474. int i;
  5475. for( i = 0; i < 8; i++, pix += stride) {
  5476. int index_a;
  5477. int alpha;
  5478. int beta;
  5479. int qp_index;
  5480. int bS_index = i;
  5481. if( bS[bS_index] == 0 ) {
  5482. continue;
  5483. }
  5484. qp_index = MB_FIELD ? (i >> 2) : (i & 1);
  5485. index_a = qp[qp_index] + h->slice_alpha_c0_offset;
  5486. alpha = (alpha_table+52)[index_a];
  5487. beta = (beta_table+52)[qp[qp_index] + h->slice_beta_offset];
  5488. if( bS[bS_index] < 4 ) {
  5489. const int tc = (tc0_table+52)[index_a][bS[bS_index] - 1] + 1;
  5490. const int p0 = pix[-1];
  5491. const int p1 = pix[-2];
  5492. const int q0 = pix[0];
  5493. const int q1 = pix[1];
  5494. if( FFABS( p0 - q0 ) < alpha &&
  5495. FFABS( p1 - p0 ) < beta &&
  5496. FFABS( q1 - q0 ) < beta ) {
  5497. const int i_delta = av_clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );
  5498. pix[-1] = av_clip_uint8( p0 + i_delta ); /* p0' */
  5499. pix[0] = av_clip_uint8( q0 - i_delta ); /* q0' */
  5500. tprintf(h->s.avctx, "filter_mb_mbaff_edgecv i:%d, qp:%d, indexA:%d, alpha:%d, beta:%d, tc:%d\n# bS:%d -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x]\n", i, qp[qp_index], index_a, alpha, beta, tc, bS[bS_index], pix[-3], p1, p0, q0, q1, pix[2], p1, pix[-1], pix[0], q1);
  5501. }
  5502. }else{
  5503. const int p0 = pix[-1];
  5504. const int p1 = pix[-2];
  5505. const int q0 = pix[0];
  5506. const int q1 = pix[1];
  5507. if( FFABS( p0 - q0 ) < alpha &&
  5508. FFABS( p1 - p0 ) < beta &&
  5509. FFABS( q1 - q0 ) < beta ) {
  5510. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2; /* p0' */
  5511. pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2; /* q0' */
  5512. tprintf(h->s.avctx, "filter_mb_mbaff_edgecv i:%d\n# bS:4 -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x, %02x, %02x]\n", i, pix[-3], p1, p0, q0, q1, pix[2], pix[-3], pix[-2], pix[-1], pix[0], pix[1], pix[2]);
  5513. }
  5514. }
  5515. }
  5516. }
  5517. static void filter_mb_edgeh( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5518. int i, d;
  5519. const int index_a = qp + h->slice_alpha_c0_offset;
  5520. const int alpha = (alpha_table+52)[index_a];
  5521. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5522. const int pix_next = stride;
  5523. if( bS[0] < 4 ) {
  5524. int8_t tc[4];
  5525. for(i=0; i<4; i++)
  5526. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] : -1;
  5527. h->s.dsp.h264_v_loop_filter_luma(pix, stride, alpha, beta, tc);
  5528. } else {
  5529. /* 16px edge length, see filter_mb_edgev */
  5530. for( d = 0; d < 16; d++ ) {
  5531. const int p0 = pix[-1*pix_next];
  5532. const int p1 = pix[-2*pix_next];
  5533. const int p2 = pix[-3*pix_next];
  5534. const int q0 = pix[0];
  5535. const int q1 = pix[1*pix_next];
  5536. const int q2 = pix[2*pix_next];
  5537. if( FFABS( p0 - q0 ) < alpha &&
  5538. FFABS( p1 - p0 ) < beta &&
  5539. FFABS( q1 - q0 ) < beta ) {
  5540. const int p3 = pix[-4*pix_next];
  5541. const int q3 = pix[ 3*pix_next];
  5542. if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){
  5543. if( FFABS( p2 - p0 ) < beta) {
  5544. /* p0', p1', p2' */
  5545. pix[-1*pix_next] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;
  5546. pix[-2*pix_next] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;
  5547. pix[-3*pix_next] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;
  5548. } else {
  5549. /* p0' */
  5550. pix[-1*pix_next] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5551. }
  5552. if( FFABS( q2 - q0 ) < beta) {
  5553. /* q0', q1', q2' */
  5554. pix[0*pix_next] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;
  5555. pix[1*pix_next] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;
  5556. pix[2*pix_next] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;
  5557. } else {
  5558. /* q0' */
  5559. pix[0*pix_next] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5560. }
  5561. }else{
  5562. /* p0', q0' */
  5563. pix[-1*pix_next] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5564. pix[ 0*pix_next] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5565. }
  5566. tprintf(h->s.avctx, "filter_mb_edgeh i:%d d:%d, qp:%d, indexA:%d, alpha:%d, beta:%d\n# bS:%d -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x]\n", i, d, qp, index_a, alpha, beta, bS[i], p2, p1, p0, q0, q1, q2, pix[-2*pix_next], pix[-pix_next], pix[0], pix[pix_next]);
  5567. }
  5568. pix++;
  5569. }
  5570. }
  5571. }
  5572. static void filter_mb_edgech( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5573. int i;
  5574. const int index_a = qp + h->slice_alpha_c0_offset;
  5575. const int alpha = (alpha_table+52)[index_a];
  5576. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5577. if( bS[0] < 4 ) {
  5578. int8_t tc[4];
  5579. for(i=0; i<4; i++)
  5580. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] + 1 : 0;
  5581. h->s.dsp.h264_v_loop_filter_chroma(pix, stride, alpha, beta, tc);
  5582. } else {
  5583. h->s.dsp.h264_v_loop_filter_chroma_intra(pix, stride, alpha, beta);
  5584. }
  5585. }
  5586. static void filter_mb_fast( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize) {
  5587. MpegEncContext * const s = &h->s;
  5588. int mb_y_firstrow = s->picture_structure == PICT_BOTTOM_FIELD;
  5589. int mb_xy, mb_type;
  5590. int qp, qp0, qp1, qpc, qpc0, qpc1, qp_thresh;
  5591. mb_xy = mb_x + mb_y*s->mb_stride;
  5592. if(mb_x==0 || mb_y==mb_y_firstrow || !s->dsp.h264_loop_filter_strength || h->pps.chroma_qp_diff ||
  5593. (h->deblocking_filter == 2 && (h->slice_table[mb_xy] != h->slice_table[h->top_mb_xy] ||
  5594. h->slice_table[mb_xy] != h->slice_table[mb_xy - 1]))) {
  5595. filter_mb(h, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize);
  5596. return;
  5597. }
  5598. assert(!FRAME_MBAFF);
  5599. mb_type = s->current_picture.mb_type[mb_xy];
  5600. qp = s->current_picture.qscale_table[mb_xy];
  5601. qp0 = s->current_picture.qscale_table[mb_xy-1];
  5602. qp1 = s->current_picture.qscale_table[h->top_mb_xy];
  5603. qpc = get_chroma_qp( h, 0, qp );
  5604. qpc0 = get_chroma_qp( h, 0, qp0 );
  5605. qpc1 = get_chroma_qp( h, 0, qp1 );
  5606. qp0 = (qp + qp0 + 1) >> 1;
  5607. qp1 = (qp + qp1 + 1) >> 1;
  5608. qpc0 = (qpc + qpc0 + 1) >> 1;
  5609. qpc1 = (qpc + qpc1 + 1) >> 1;
  5610. qp_thresh = 15 - h->slice_alpha_c0_offset;
  5611. if(qp <= qp_thresh && qp0 <= qp_thresh && qp1 <= qp_thresh &&
  5612. qpc <= qp_thresh && qpc0 <= qp_thresh && qpc1 <= qp_thresh)
  5613. return;
  5614. if( IS_INTRA(mb_type) ) {
  5615. int16_t bS4[4] = {4,4,4,4};
  5616. int16_t bS3[4] = {3,3,3,3};
  5617. int16_t *bSH = FIELD_PICTURE ? bS3 : bS4;
  5618. if( IS_8x8DCT(mb_type) ) {
  5619. filter_mb_edgev( h, &img_y[4*0], linesize, bS4, qp0 );
  5620. filter_mb_edgev( h, &img_y[4*2], linesize, bS3, qp );
  5621. filter_mb_edgeh( h, &img_y[4*0*linesize], linesize, bSH, qp1 );
  5622. filter_mb_edgeh( h, &img_y[4*2*linesize], linesize, bS3, qp );
  5623. } else {
  5624. filter_mb_edgev( h, &img_y[4*0], linesize, bS4, qp0 );
  5625. filter_mb_edgev( h, &img_y[4*1], linesize, bS3, qp );
  5626. filter_mb_edgev( h, &img_y[4*2], linesize, bS3, qp );
  5627. filter_mb_edgev( h, &img_y[4*3], linesize, bS3, qp );
  5628. filter_mb_edgeh( h, &img_y[4*0*linesize], linesize, bSH, qp1 );
  5629. filter_mb_edgeh( h, &img_y[4*1*linesize], linesize, bS3, qp );
  5630. filter_mb_edgeh( h, &img_y[4*2*linesize], linesize, bS3, qp );
  5631. filter_mb_edgeh( h, &img_y[4*3*linesize], linesize, bS3, qp );
  5632. }
  5633. filter_mb_edgecv( h, &img_cb[2*0], uvlinesize, bS4, qpc0 );
  5634. filter_mb_edgecv( h, &img_cb[2*2], uvlinesize, bS3, qpc );
  5635. filter_mb_edgecv( h, &img_cr[2*0], uvlinesize, bS4, qpc0 );
  5636. filter_mb_edgecv( h, &img_cr[2*2], uvlinesize, bS3, qpc );
  5637. filter_mb_edgech( h, &img_cb[2*0*uvlinesize], uvlinesize, bSH, qpc1 );
  5638. filter_mb_edgech( h, &img_cb[2*2*uvlinesize], uvlinesize, bS3, qpc );
  5639. filter_mb_edgech( h, &img_cr[2*0*uvlinesize], uvlinesize, bSH, qpc1 );
  5640. filter_mb_edgech( h, &img_cr[2*2*uvlinesize], uvlinesize, bS3, qpc );
  5641. return;
  5642. } else {
  5643. DECLARE_ALIGNED_8(int16_t, bS[2][4][4]);
  5644. uint64_t (*bSv)[4] = (uint64_t(*)[4])bS;
  5645. int edges;
  5646. if( IS_8x8DCT(mb_type) && (h->cbp&7) == 7 ) {
  5647. edges = 4;
  5648. bSv[0][0] = bSv[0][2] = bSv[1][0] = bSv[1][2] = 0x0002000200020002ULL;
  5649. } else {
  5650. int mask_edge1 = (mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16)) ? 3 :
  5651. (mb_type & MB_TYPE_16x8) ? 1 : 0;
  5652. int mask_edge0 = (mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16))
  5653. && (s->current_picture.mb_type[mb_xy-1] & (MB_TYPE_16x16 | MB_TYPE_8x16))
  5654. ? 3 : 0;
  5655. int step = IS_8x8DCT(mb_type) ? 2 : 1;
  5656. edges = (mb_type & MB_TYPE_16x16) && !(h->cbp & 15) ? 1 : 4;
  5657. s->dsp.h264_loop_filter_strength( bS, h->non_zero_count_cache, h->ref_cache, h->mv_cache,
  5658. (h->slice_type == B_TYPE), edges, step, mask_edge0, mask_edge1 );
  5659. }
  5660. if( IS_INTRA(s->current_picture.mb_type[mb_xy-1]) )
  5661. bSv[0][0] = 0x0004000400040004ULL;
  5662. if( IS_INTRA(s->current_picture.mb_type[h->top_mb_xy]) )
  5663. bSv[1][0] = FIELD_PICTURE ? 0x0003000300030003ULL : 0x0004000400040004ULL;
  5664. #define FILTER(hv,dir,edge)\
  5665. if(bSv[dir][edge]) {\
  5666. filter_mb_edge##hv( h, &img_y[4*edge*(dir?linesize:1)], linesize, bS[dir][edge], edge ? qp : qp##dir );\
  5667. if(!(edge&1)) {\
  5668. filter_mb_edgec##hv( h, &img_cb[2*edge*(dir?uvlinesize:1)], uvlinesize, bS[dir][edge], edge ? qpc : qpc##dir );\
  5669. filter_mb_edgec##hv( h, &img_cr[2*edge*(dir?uvlinesize:1)], uvlinesize, bS[dir][edge], edge ? qpc : qpc##dir );\
  5670. }\
  5671. }
  5672. if( edges == 1 ) {
  5673. FILTER(v,0,0);
  5674. FILTER(h,1,0);
  5675. } else if( IS_8x8DCT(mb_type) ) {
  5676. FILTER(v,0,0);
  5677. FILTER(v,0,2);
  5678. FILTER(h,1,0);
  5679. FILTER(h,1,2);
  5680. } else {
  5681. FILTER(v,0,0);
  5682. FILTER(v,0,1);
  5683. FILTER(v,0,2);
  5684. FILTER(v,0,3);
  5685. FILTER(h,1,0);
  5686. FILTER(h,1,1);
  5687. FILTER(h,1,2);
  5688. FILTER(h,1,3);
  5689. }
  5690. #undef FILTER
  5691. }
  5692. }
  5693. static void filter_mb( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize) {
  5694. MpegEncContext * const s = &h->s;
  5695. const int mb_xy= mb_x + mb_y*s->mb_stride;
  5696. const int mb_type = s->current_picture.mb_type[mb_xy];
  5697. const int mvy_limit = IS_INTERLACED(mb_type) ? 2 : 4;
  5698. int first_vertical_edge_done = 0;
  5699. int dir;
  5700. /* FIXME: A given frame may occupy more than one position in
  5701. * the reference list. So ref2frm should be populated with
  5702. * frame numbers, not indices. */
  5703. static const int ref2frm[34] = {-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
  5704. 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
  5705. //for sufficiently low qp, filtering wouldn't do anything
  5706. //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
  5707. if(!FRAME_MBAFF){
  5708. int qp_thresh = 15 - h->slice_alpha_c0_offset - FFMAX(0, FFMAX(h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1]));
  5709. int qp = s->current_picture.qscale_table[mb_xy];
  5710. if(qp <= qp_thresh
  5711. && (mb_x == 0 || ((qp + s->current_picture.qscale_table[mb_xy-1] + 1)>>1) <= qp_thresh)
  5712. && (mb_y == 0 || ((qp + s->current_picture.qscale_table[h->top_mb_xy] + 1)>>1) <= qp_thresh)){
  5713. return;
  5714. }
  5715. }
  5716. if (FRAME_MBAFF
  5717. // left mb is in picture
  5718. && h->slice_table[mb_xy-1] != 255
  5719. // and current and left pair do not have the same interlaced type
  5720. && (IS_INTERLACED(mb_type) != IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]))
  5721. // and left mb is in the same slice if deblocking_filter == 2
  5722. && (h->deblocking_filter!=2 || h->slice_table[mb_xy-1] == h->slice_table[mb_xy])) {
  5723. /* First vertical edge is different in MBAFF frames
  5724. * There are 8 different bS to compute and 2 different Qp
  5725. */
  5726. const int pair_xy = mb_x + (mb_y&~1)*s->mb_stride;
  5727. const int left_mb_xy[2] = { pair_xy-1, pair_xy-1+s->mb_stride };
  5728. int16_t bS[8];
  5729. int qp[2];
  5730. int bqp[2];
  5731. int rqp[2];
  5732. int mb_qp, mbn0_qp, mbn1_qp;
  5733. int i;
  5734. first_vertical_edge_done = 1;
  5735. if( IS_INTRA(mb_type) )
  5736. bS[0] = bS[1] = bS[2] = bS[3] = bS[4] = bS[5] = bS[6] = bS[7] = 4;
  5737. else {
  5738. for( i = 0; i < 8; i++ ) {
  5739. int mbn_xy = MB_FIELD ? left_mb_xy[i>>2] : left_mb_xy[i&1];
  5740. if( IS_INTRA( s->current_picture.mb_type[mbn_xy] ) )
  5741. bS[i] = 4;
  5742. else if( h->non_zero_count_cache[12+8*(i>>1)] != 0 ||
  5743. /* FIXME: with 8x8dct + cavlc, should check cbp instead of nnz */
  5744. h->non_zero_count[mbn_xy][MB_FIELD ? i&3 : (i>>2)+(mb_y&1)*2] )
  5745. bS[i] = 2;
  5746. else
  5747. bS[i] = 1;
  5748. }
  5749. }
  5750. mb_qp = s->current_picture.qscale_table[mb_xy];
  5751. mbn0_qp = s->current_picture.qscale_table[left_mb_xy[0]];
  5752. mbn1_qp = s->current_picture.qscale_table[left_mb_xy[1]];
  5753. qp[0] = ( mb_qp + mbn0_qp + 1 ) >> 1;
  5754. bqp[0] = ( get_chroma_qp( h, 0, mb_qp ) +
  5755. get_chroma_qp( h, 0, mbn0_qp ) + 1 ) >> 1;
  5756. rqp[0] = ( get_chroma_qp( h, 1, mb_qp ) +
  5757. get_chroma_qp( h, 1, mbn0_qp ) + 1 ) >> 1;
  5758. qp[1] = ( mb_qp + mbn1_qp + 1 ) >> 1;
  5759. bqp[1] = ( get_chroma_qp( h, 0, mb_qp ) +
  5760. get_chroma_qp( h, 0, mbn1_qp ) + 1 ) >> 1;
  5761. rqp[1] = ( get_chroma_qp( h, 1, mb_qp ) +
  5762. get_chroma_qp( h, 1, mbn1_qp ) + 1 ) >> 1;
  5763. /* Filter edge */
  5764. tprintf(s->avctx, "filter mb:%d/%d MBAFF, QPy:%d/%d, QPb:%d/%d QPr:%d/%d ls:%d uvls:%d", mb_x, mb_y, qp[0], qp[1], bqp[0], bqp[1], rqp[0], rqp[1], linesize, uvlinesize);
  5765. { int i; for (i = 0; i < 8; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
  5766. filter_mb_mbaff_edgev ( h, &img_y [0], linesize, bS, qp );
  5767. filter_mb_mbaff_edgecv( h, &img_cb[0], uvlinesize, bS, bqp );
  5768. filter_mb_mbaff_edgecv( h, &img_cr[0], uvlinesize, bS, rqp );
  5769. }
  5770. /* dir : 0 -> vertical edge, 1 -> horizontal edge */
  5771. for( dir = 0; dir < 2; dir++ )
  5772. {
  5773. int edge;
  5774. const int mbm_xy = dir == 0 ? mb_xy -1 : h->top_mb_xy;
  5775. const int mbm_type = s->current_picture.mb_type[mbm_xy];
  5776. int start = h->slice_table[mbm_xy] == 255 ? 1 : 0;
  5777. const int edges = (mb_type & (MB_TYPE_16x16|MB_TYPE_SKIP))
  5778. == (MB_TYPE_16x16|MB_TYPE_SKIP) ? 1 : 4;
  5779. // how often to recheck mv-based bS when iterating between edges
  5780. const int mask_edge = (mb_type & (MB_TYPE_16x16 | (MB_TYPE_16x8 << dir))) ? 3 :
  5781. (mb_type & (MB_TYPE_8x16 >> dir)) ? 1 : 0;
  5782. // how often to recheck mv-based bS when iterating along each edge
  5783. const int mask_par0 = mb_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir));
  5784. if (first_vertical_edge_done) {
  5785. start = 1;
  5786. first_vertical_edge_done = 0;
  5787. }
  5788. if (h->deblocking_filter==2 && h->slice_table[mbm_xy] != h->slice_table[mb_xy])
  5789. start = 1;
  5790. if (FRAME_MBAFF && (dir == 1) && ((mb_y&1) == 0) && start == 0
  5791. && !IS_INTERLACED(mb_type)
  5792. && IS_INTERLACED(mbm_type)
  5793. ) {
  5794. // This is a special case in the norm where the filtering must
  5795. // be done twice (one each of the field) even if we are in a
  5796. // frame macroblock.
  5797. //
  5798. static const int nnz_idx[4] = {4,5,6,3};
  5799. unsigned int tmp_linesize = 2 * linesize;
  5800. unsigned int tmp_uvlinesize = 2 * uvlinesize;
  5801. int mbn_xy = mb_xy - 2 * s->mb_stride;
  5802. int qp;
  5803. int i, j;
  5804. int16_t bS[4];
  5805. for(j=0; j<2; j++, mbn_xy += s->mb_stride){
  5806. if( IS_INTRA(mb_type) ||
  5807. IS_INTRA(s->current_picture.mb_type[mbn_xy]) ) {
  5808. bS[0] = bS[1] = bS[2] = bS[3] = 3;
  5809. } else {
  5810. const uint8_t *mbn_nnz = h->non_zero_count[mbn_xy];
  5811. for( i = 0; i < 4; i++ ) {
  5812. if( h->non_zero_count_cache[scan8[0]+i] != 0 ||
  5813. mbn_nnz[nnz_idx[i]] != 0 )
  5814. bS[i] = 2;
  5815. else
  5816. bS[i] = 1;
  5817. }
  5818. }
  5819. // Do not use s->qscale as luma quantizer because it has not the same
  5820. // value in IPCM macroblocks.
  5821. qp = ( s->current_picture.qscale_table[mb_xy] + s->current_picture.qscale_table[mbn_xy] + 1 ) >> 1;
  5822. tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d ls:%d uvls:%d", mb_x, mb_y, dir, edge, qp, tmp_linesize, tmp_uvlinesize);
  5823. { int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
  5824. filter_mb_edgeh( h, &img_y[j*linesize], tmp_linesize, bS, qp );
  5825. filter_mb_edgech( h, &img_cb[j*uvlinesize], tmp_uvlinesize, bS,
  5826. ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5827. filter_mb_edgech( h, &img_cr[j*uvlinesize], tmp_uvlinesize, bS,
  5828. ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5829. }
  5830. start = 1;
  5831. }
  5832. /* Calculate bS */
  5833. for( edge = start; edge < edges; edge++ ) {
  5834. /* mbn_xy: neighbor macroblock */
  5835. const int mbn_xy = edge > 0 ? mb_xy : mbm_xy;
  5836. const int mbn_type = s->current_picture.mb_type[mbn_xy];
  5837. int16_t bS[4];
  5838. int qp;
  5839. if( (edge&1) && IS_8x8DCT(mb_type) )
  5840. continue;
  5841. if( IS_INTRA(mb_type) ||
  5842. IS_INTRA(mbn_type) ) {
  5843. int value;
  5844. if (edge == 0) {
  5845. if ( (!IS_INTERLACED(mb_type) && !IS_INTERLACED(mbm_type))
  5846. || ((FRAME_MBAFF || (s->picture_structure != PICT_FRAME)) && (dir == 0))
  5847. ) {
  5848. value = 4;
  5849. } else {
  5850. value = 3;
  5851. }
  5852. } else {
  5853. value = 3;
  5854. }
  5855. bS[0] = bS[1] = bS[2] = bS[3] = value;
  5856. } else {
  5857. int i, l;
  5858. int mv_done;
  5859. if( edge & mask_edge ) {
  5860. bS[0] = bS[1] = bS[2] = bS[3] = 0;
  5861. mv_done = 1;
  5862. }
  5863. else if( FRAME_MBAFF && IS_INTERLACED(mb_type ^ mbn_type)) {
  5864. bS[0] = bS[1] = bS[2] = bS[3] = 1;
  5865. mv_done = 1;
  5866. }
  5867. else if( mask_par0 && (edge || (mbn_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir)))) ) {
  5868. int b_idx= 8 + 4 + edge * (dir ? 8:1);
  5869. int bn_idx= b_idx - (dir ? 8:1);
  5870. int v = 0;
  5871. for( l = 0; !v && l < 1 + (h->slice_type == B_TYPE); l++ ) {
  5872. v |= ref2frm[h->ref_cache[l][b_idx]+2] != ref2frm[h->ref_cache[l][bn_idx]+2] ||
  5873. FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[l][bn_idx][0] ) >= 4 ||
  5874. FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[l][bn_idx][1] ) >= mvy_limit;
  5875. }
  5876. bS[0] = bS[1] = bS[2] = bS[3] = v;
  5877. mv_done = 1;
  5878. }
  5879. else
  5880. mv_done = 0;
  5881. for( i = 0; i < 4; i++ ) {
  5882. int x = dir == 0 ? edge : i;
  5883. int y = dir == 0 ? i : edge;
  5884. int b_idx= 8 + 4 + x + 8*y;
  5885. int bn_idx= b_idx - (dir ? 8:1);
  5886. if( h->non_zero_count_cache[b_idx] != 0 ||
  5887. h->non_zero_count_cache[bn_idx] != 0 ) {
  5888. bS[i] = 2;
  5889. }
  5890. else if(!mv_done)
  5891. {
  5892. bS[i] = 0;
  5893. for( l = 0; l < 1 + (h->slice_type == B_TYPE); l++ ) {
  5894. if( ref2frm[h->ref_cache[l][b_idx]+2] != ref2frm[h->ref_cache[l][bn_idx]+2] ||
  5895. FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[l][bn_idx][0] ) >= 4 ||
  5896. FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[l][bn_idx][1] ) >= mvy_limit ) {
  5897. bS[i] = 1;
  5898. break;
  5899. }
  5900. }
  5901. }
  5902. }
  5903. if(bS[0]+bS[1]+bS[2]+bS[3] == 0)
  5904. continue;
  5905. }
  5906. /* Filter edge */
  5907. // Do not use s->qscale as luma quantizer because it has not the same
  5908. // value in IPCM macroblocks.
  5909. qp = ( s->current_picture.qscale_table[mb_xy] + s->current_picture.qscale_table[mbn_xy] + 1 ) >> 1;
  5910. //tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d, QPc:%d, QPcn:%d\n", mb_x, mb_y, dir, edge, qp, h->chroma_qp, s->current_picture.qscale_table[mbn_xy]);
  5911. tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d ls:%d uvls:%d", mb_x, mb_y, dir, edge, qp, linesize, uvlinesize);
  5912. { int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
  5913. if( dir == 0 ) {
  5914. filter_mb_edgev( h, &img_y[4*edge], linesize, bS, qp );
  5915. if( (edge&1) == 0 ) {
  5916. filter_mb_edgecv( h, &img_cb[2*edge], uvlinesize, bS,
  5917. ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5918. filter_mb_edgecv( h, &img_cr[2*edge], uvlinesize, bS,
  5919. ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5920. }
  5921. } else {
  5922. filter_mb_edgeh( h, &img_y[4*edge*linesize], linesize, bS, qp );
  5923. if( (edge&1) == 0 ) {
  5924. filter_mb_edgech( h, &img_cb[2*edge*uvlinesize], uvlinesize, bS,
  5925. ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5926. filter_mb_edgech( h, &img_cr[2*edge*uvlinesize], uvlinesize, bS,
  5927. ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5928. }
  5929. }
  5930. }
  5931. }
  5932. }
  5933. static int decode_slice(struct AVCodecContext *avctx, H264Context *h){
  5934. MpegEncContext * const s = &h->s;
  5935. const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;
  5936. s->mb_skip_run= -1;
  5937. if( h->pps.cabac ) {
  5938. int i;
  5939. /* realign */
  5940. align_get_bits( &s->gb );
  5941. /* init cabac */
  5942. ff_init_cabac_states( &h->cabac);
  5943. ff_init_cabac_decoder( &h->cabac,
  5944. s->gb.buffer + get_bits_count(&s->gb)/8,
  5945. ( s->gb.size_in_bits - get_bits_count(&s->gb) + 7)/8);
  5946. /* calculate pre-state */
  5947. for( i= 0; i < 460; i++ ) {
  5948. int pre;
  5949. if( h->slice_type == I_TYPE )
  5950. pre = av_clip( ((cabac_context_init_I[i][0] * s->qscale) >>4 ) + cabac_context_init_I[i][1], 1, 126 );
  5951. else
  5952. pre = av_clip( ((cabac_context_init_PB[h->cabac_init_idc][i][0] * s->qscale) >>4 ) + cabac_context_init_PB[h->cabac_init_idc][i][1], 1, 126 );
  5953. if( pre <= 63 )
  5954. h->cabac_state[i] = 2 * ( 63 - pre ) + 0;
  5955. else
  5956. h->cabac_state[i] = 2 * ( pre - 64 ) + 1;
  5957. }
  5958. for(;;){
  5959. //START_TIMER
  5960. int ret = decode_mb_cabac(h);
  5961. int eos;
  5962. //STOP_TIMER("decode_mb_cabac")
  5963. if(ret>=0) hl_decode_mb(h);
  5964. if( ret >= 0 && FRAME_MBAFF ) { //FIXME optimal? or let mb_decode decode 16x32 ?
  5965. s->mb_y++;
  5966. if(ret>=0) ret = decode_mb_cabac(h);
  5967. if(ret>=0) hl_decode_mb(h);
  5968. s->mb_y--;
  5969. }
  5970. eos = get_cabac_terminate( &h->cabac );
  5971. if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  5972. av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d, bytestream (%td)\n", s->mb_x, s->mb_y, h->cabac.bytestream_end - h->cabac.bytestream);
  5973. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  5974. return -1;
  5975. }
  5976. if( ++s->mb_x >= s->mb_width ) {
  5977. s->mb_x = 0;
  5978. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  5979. ++s->mb_y;
  5980. if(FIELD_OR_MBAFF_PICTURE) {
  5981. ++s->mb_y;
  5982. }
  5983. }
  5984. if( eos || s->mb_y >= s->mb_height ) {
  5985. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  5986. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  5987. return 0;
  5988. }
  5989. }
  5990. } else {
  5991. for(;;){
  5992. int ret = decode_mb_cavlc(h);
  5993. if(ret>=0) hl_decode_mb(h);
  5994. if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
  5995. s->mb_y++;
  5996. ret = decode_mb_cavlc(h);
  5997. if(ret>=0) hl_decode_mb(h);
  5998. s->mb_y--;
  5999. }
  6000. if(ret<0){
  6001. av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  6002. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  6003. return -1;
  6004. }
  6005. if(++s->mb_x >= s->mb_width){
  6006. s->mb_x=0;
  6007. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  6008. ++s->mb_y;
  6009. if(FIELD_OR_MBAFF_PICTURE) {
  6010. ++s->mb_y;
  6011. }
  6012. if(s->mb_y >= s->mb_height){
  6013. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  6014. if(get_bits_count(&s->gb) == s->gb.size_in_bits ) {
  6015. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  6016. return 0;
  6017. }else{
  6018. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  6019. return -1;
  6020. }
  6021. }
  6022. }
  6023. if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
  6024. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  6025. if(get_bits_count(&s->gb) == s->gb.size_in_bits ){
  6026. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  6027. return 0;
  6028. }else{
  6029. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  6030. return -1;
  6031. }
  6032. }
  6033. }
  6034. }
  6035. #if 0
  6036. for(;s->mb_y < s->mb_height; s->mb_y++){
  6037. for(;s->mb_x < s->mb_width; s->mb_x++){
  6038. int ret= decode_mb(h);
  6039. hl_decode_mb(h);
  6040. if(ret<0){
  6041. av_log(s->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  6042. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  6043. return -1;
  6044. }
  6045. if(++s->mb_x >= s->mb_width){
  6046. s->mb_x=0;
  6047. if(++s->mb_y >= s->mb_height){
  6048. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  6049. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  6050. return 0;
  6051. }else{
  6052. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  6053. return -1;
  6054. }
  6055. }
  6056. }
  6057. if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){
  6058. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  6059. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  6060. return 0;
  6061. }else{
  6062. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  6063. return -1;
  6064. }
  6065. }
  6066. }
  6067. s->mb_x=0;
  6068. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  6069. }
  6070. #endif
  6071. return -1; //not reached
  6072. }
  6073. static int decode_unregistered_user_data(H264Context *h, int size){
  6074. MpegEncContext * const s = &h->s;
  6075. uint8_t user_data[16+256];
  6076. int e, build, i;
  6077. if(size<16)
  6078. return -1;
  6079. for(i=0; i<sizeof(user_data)-1 && i<size; i++){
  6080. user_data[i]= get_bits(&s->gb, 8);
  6081. }
  6082. user_data[i]= 0;
  6083. e= sscanf(user_data+16, "x264 - core %d"/*%s - H.264/MPEG-4 AVC codec - Copyleft 2005 - http://www.videolan.org/x264.html*/, &build);
  6084. if(e==1 && build>=0)
  6085. h->x264_build= build;
  6086. if(s->avctx->debug & FF_DEBUG_BUGS)
  6087. av_log(s->avctx, AV_LOG_DEBUG, "user data:\"%s\"\n", user_data+16);
  6088. for(; i<size; i++)
  6089. skip_bits(&s->gb, 8);
  6090. return 0;
  6091. }
  6092. static int decode_sei(H264Context *h){
  6093. MpegEncContext * const s = &h->s;
  6094. while(get_bits_count(&s->gb) + 16 < s->gb.size_in_bits){
  6095. int size, type;
  6096. type=0;
  6097. do{
  6098. type+= show_bits(&s->gb, 8);
  6099. }while(get_bits(&s->gb, 8) == 255);
  6100. size=0;
  6101. do{
  6102. size+= show_bits(&s->gb, 8);
  6103. }while(get_bits(&s->gb, 8) == 255);
  6104. switch(type){
  6105. case 5:
  6106. if(decode_unregistered_user_data(h, size) < 0)
  6107. return -1;
  6108. break;
  6109. default:
  6110. skip_bits(&s->gb, 8*size);
  6111. }
  6112. //FIXME check bits here
  6113. align_get_bits(&s->gb);
  6114. }
  6115. return 0;
  6116. }
  6117. static inline void decode_hrd_parameters(H264Context *h, SPS *sps){
  6118. MpegEncContext * const s = &h->s;
  6119. int cpb_count, i;
  6120. cpb_count = get_ue_golomb(&s->gb) + 1;
  6121. get_bits(&s->gb, 4); /* bit_rate_scale */
  6122. get_bits(&s->gb, 4); /* cpb_size_scale */
  6123. for(i=0; i<cpb_count; i++){
  6124. get_ue_golomb(&s->gb); /* bit_rate_value_minus1 */
  6125. get_ue_golomb(&s->gb); /* cpb_size_value_minus1 */
  6126. get_bits1(&s->gb); /* cbr_flag */
  6127. }
  6128. get_bits(&s->gb, 5); /* initial_cpb_removal_delay_length_minus1 */
  6129. get_bits(&s->gb, 5); /* cpb_removal_delay_length_minus1 */
  6130. get_bits(&s->gb, 5); /* dpb_output_delay_length_minus1 */
  6131. get_bits(&s->gb, 5); /* time_offset_length */
  6132. }
  6133. static inline int decode_vui_parameters(H264Context *h, SPS *sps){
  6134. MpegEncContext * const s = &h->s;
  6135. int aspect_ratio_info_present_flag;
  6136. unsigned int aspect_ratio_idc;
  6137. int nal_hrd_parameters_present_flag, vcl_hrd_parameters_present_flag;
  6138. aspect_ratio_info_present_flag= get_bits1(&s->gb);
  6139. if( aspect_ratio_info_present_flag ) {
  6140. aspect_ratio_idc= get_bits(&s->gb, 8);
  6141. if( aspect_ratio_idc == EXTENDED_SAR ) {
  6142. sps->sar.num= get_bits(&s->gb, 16);
  6143. sps->sar.den= get_bits(&s->gb, 16);
  6144. }else if(aspect_ratio_idc < 14){
  6145. sps->sar= pixel_aspect[aspect_ratio_idc];
  6146. }else{
  6147. av_log(h->s.avctx, AV_LOG_ERROR, "illegal aspect ratio\n");
  6148. return -1;
  6149. }
  6150. }else{
  6151. sps->sar.num=
  6152. sps->sar.den= 0;
  6153. }
  6154. // s->avctx->aspect_ratio= sar_width*s->width / (float)(s->height*sar_height);
  6155. if(get_bits1(&s->gb)){ /* overscan_info_present_flag */
  6156. get_bits1(&s->gb); /* overscan_appropriate_flag */
  6157. }
  6158. if(get_bits1(&s->gb)){ /* video_signal_type_present_flag */
  6159. get_bits(&s->gb, 3); /* video_format */
  6160. get_bits1(&s->gb); /* video_full_range_flag */
  6161. if(get_bits1(&s->gb)){ /* colour_description_present_flag */
  6162. get_bits(&s->gb, 8); /* colour_primaries */
  6163. get_bits(&s->gb, 8); /* transfer_characteristics */
  6164. get_bits(&s->gb, 8); /* matrix_coefficients */
  6165. }
  6166. }
  6167. if(get_bits1(&s->gb)){ /* chroma_location_info_present_flag */
  6168. get_ue_golomb(&s->gb); /* chroma_sample_location_type_top_field */
  6169. get_ue_golomb(&s->gb); /* chroma_sample_location_type_bottom_field */
  6170. }
  6171. sps->timing_info_present_flag = get_bits1(&s->gb);
  6172. if(sps->timing_info_present_flag){
  6173. sps->num_units_in_tick = get_bits_long(&s->gb, 32);
  6174. sps->time_scale = get_bits_long(&s->gb, 32);
  6175. sps->fixed_frame_rate_flag = get_bits1(&s->gb);
  6176. }
  6177. nal_hrd_parameters_present_flag = get_bits1(&s->gb);
  6178. if(nal_hrd_parameters_present_flag)
  6179. decode_hrd_parameters(h, sps);
  6180. vcl_hrd_parameters_present_flag = get_bits1(&s->gb);
  6181. if(vcl_hrd_parameters_present_flag)
  6182. decode_hrd_parameters(h, sps);
  6183. if(nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag)
  6184. get_bits1(&s->gb); /* low_delay_hrd_flag */
  6185. get_bits1(&s->gb); /* pic_struct_present_flag */
  6186. sps->bitstream_restriction_flag = get_bits1(&s->gb);
  6187. if(sps->bitstream_restriction_flag){
  6188. unsigned int num_reorder_frames;
  6189. get_bits1(&s->gb); /* motion_vectors_over_pic_boundaries_flag */
  6190. get_ue_golomb(&s->gb); /* max_bytes_per_pic_denom */
  6191. get_ue_golomb(&s->gb); /* max_bits_per_mb_denom */
  6192. get_ue_golomb(&s->gb); /* log2_max_mv_length_horizontal */
  6193. get_ue_golomb(&s->gb); /* log2_max_mv_length_vertical */
  6194. num_reorder_frames= get_ue_golomb(&s->gb);
  6195. get_ue_golomb(&s->gb); /*max_dec_frame_buffering*/
  6196. if(num_reorder_frames > 16 /*max_dec_frame_buffering || max_dec_frame_buffering > 16*/){
  6197. av_log(h->s.avctx, AV_LOG_ERROR, "illegal num_reorder_frames %d\n", num_reorder_frames);
  6198. return -1;
  6199. }
  6200. sps->num_reorder_frames= num_reorder_frames;
  6201. }
  6202. return 0;
  6203. }
  6204. static void decode_scaling_list(H264Context *h, uint8_t *factors, int size,
  6205. const uint8_t *jvt_list, const uint8_t *fallback_list){
  6206. MpegEncContext * const s = &h->s;
  6207. int i, last = 8, next = 8;
  6208. const uint8_t *scan = size == 16 ? zigzag_scan : zigzag_scan8x8;
  6209. if(!get_bits1(&s->gb)) /* matrix not written, we use the predicted one */
  6210. memcpy(factors, fallback_list, size*sizeof(uint8_t));
  6211. else
  6212. for(i=0;i<size;i++){
  6213. if(next)
  6214. next = (last + get_se_golomb(&s->gb)) & 0xff;
  6215. if(!i && !next){ /* matrix not written, we use the preset one */
  6216. memcpy(factors, jvt_list, size*sizeof(uint8_t));
  6217. break;
  6218. }
  6219. last = factors[scan[i]] = next ? next : last;
  6220. }
  6221. }
  6222. static void decode_scaling_matrices(H264Context *h, SPS *sps, PPS *pps, int is_sps,
  6223. uint8_t (*scaling_matrix4)[16], uint8_t (*scaling_matrix8)[64]){
  6224. MpegEncContext * const s = &h->s;
  6225. int fallback_sps = !is_sps && sps->scaling_matrix_present;
  6226. const uint8_t *fallback[4] = {
  6227. fallback_sps ? sps->scaling_matrix4[0] : default_scaling4[0],
  6228. fallback_sps ? sps->scaling_matrix4[3] : default_scaling4[1],
  6229. fallback_sps ? sps->scaling_matrix8[0] : default_scaling8[0],
  6230. fallback_sps ? sps->scaling_matrix8[1] : default_scaling8[1]
  6231. };
  6232. if(get_bits1(&s->gb)){
  6233. sps->scaling_matrix_present |= is_sps;
  6234. decode_scaling_list(h,scaling_matrix4[0],16,default_scaling4[0],fallback[0]); // Intra, Y
  6235. decode_scaling_list(h,scaling_matrix4[1],16,default_scaling4[0],scaling_matrix4[0]); // Intra, Cr
  6236. decode_scaling_list(h,scaling_matrix4[2],16,default_scaling4[0],scaling_matrix4[1]); // Intra, Cb
  6237. decode_scaling_list(h,scaling_matrix4[3],16,default_scaling4[1],fallback[1]); // Inter, Y
  6238. decode_scaling_list(h,scaling_matrix4[4],16,default_scaling4[1],scaling_matrix4[3]); // Inter, Cr
  6239. decode_scaling_list(h,scaling_matrix4[5],16,default_scaling4[1],scaling_matrix4[4]); // Inter, Cb
  6240. if(is_sps || pps->transform_8x8_mode){
  6241. decode_scaling_list(h,scaling_matrix8[0],64,default_scaling8[0],fallback[2]); // Intra, Y
  6242. decode_scaling_list(h,scaling_matrix8[1],64,default_scaling8[1],fallback[3]); // Inter, Y
  6243. }
  6244. } else if(fallback_sps) {
  6245. memcpy(scaling_matrix4, sps->scaling_matrix4, 6*16*sizeof(uint8_t));
  6246. memcpy(scaling_matrix8, sps->scaling_matrix8, 2*64*sizeof(uint8_t));
  6247. }
  6248. }
  6249. /**
  6250. * Returns and optionally allocates SPS / PPS structures in the supplied array 'vec'
  6251. */
  6252. static void *
  6253. alloc_parameter_set(H264Context *h, void **vec, const unsigned int id, const unsigned int max,
  6254. const size_t size, const char *name)
  6255. {
  6256. if(id>=max) {
  6257. av_log(h->s.avctx, AV_LOG_ERROR, "%s_id (%d) out of range\n", name, id);
  6258. return NULL;
  6259. }
  6260. if(!vec[id]) {
  6261. vec[id] = av_mallocz(size);
  6262. if(vec[id] == NULL)
  6263. av_log(h->s.avctx, AV_LOG_ERROR, "cannot allocate memory for %s\n", name);
  6264. }
  6265. return vec[id];
  6266. }
  6267. static inline int decode_seq_parameter_set(H264Context *h){
  6268. MpegEncContext * const s = &h->s;
  6269. int profile_idc, level_idc;
  6270. unsigned int sps_id, tmp, mb_width, mb_height;
  6271. int i;
  6272. SPS *sps;
  6273. profile_idc= get_bits(&s->gb, 8);
  6274. get_bits1(&s->gb); //constraint_set0_flag
  6275. get_bits1(&s->gb); //constraint_set1_flag
  6276. get_bits1(&s->gb); //constraint_set2_flag
  6277. get_bits1(&s->gb); //constraint_set3_flag
  6278. get_bits(&s->gb, 4); // reserved
  6279. level_idc= get_bits(&s->gb, 8);
  6280. sps_id= get_ue_golomb(&s->gb);
  6281. sps = alloc_parameter_set(h, (void **)h->sps_buffers, sps_id, MAX_SPS_COUNT, sizeof(SPS), "sps");
  6282. if(sps == NULL)
  6283. return -1;
  6284. sps->profile_idc= profile_idc;
  6285. sps->level_idc= level_idc;
  6286. if(sps->profile_idc >= 100){ //high profile
  6287. if(get_ue_golomb(&s->gb) == 3) //chroma_format_idc
  6288. get_bits1(&s->gb); //residual_color_transform_flag
  6289. get_ue_golomb(&s->gb); //bit_depth_luma_minus8
  6290. get_ue_golomb(&s->gb); //bit_depth_chroma_minus8
  6291. sps->transform_bypass = get_bits1(&s->gb);
  6292. decode_scaling_matrices(h, sps, NULL, 1, sps->scaling_matrix4, sps->scaling_matrix8);
  6293. }else
  6294. sps->scaling_matrix_present = 0;
  6295. sps->log2_max_frame_num= get_ue_golomb(&s->gb) + 4;
  6296. sps->poc_type= get_ue_golomb(&s->gb);
  6297. if(sps->poc_type == 0){ //FIXME #define
  6298. sps->log2_max_poc_lsb= get_ue_golomb(&s->gb) + 4;
  6299. } else if(sps->poc_type == 1){//FIXME #define
  6300. sps->delta_pic_order_always_zero_flag= get_bits1(&s->gb);
  6301. sps->offset_for_non_ref_pic= get_se_golomb(&s->gb);
  6302. sps->offset_for_top_to_bottom_field= get_se_golomb(&s->gb);
  6303. tmp= get_ue_golomb(&s->gb);
  6304. if(tmp >= sizeof(sps->offset_for_ref_frame) / sizeof(sps->offset_for_ref_frame[0])){
  6305. av_log(h->s.avctx, AV_LOG_ERROR, "poc_cycle_length overflow %u\n", tmp);
  6306. return -1;
  6307. }
  6308. sps->poc_cycle_length= tmp;
  6309. for(i=0; i<sps->poc_cycle_length; i++)
  6310. sps->offset_for_ref_frame[i]= get_se_golomb(&s->gb);
  6311. }else if(sps->poc_type != 2){
  6312. av_log(h->s.avctx, AV_LOG_ERROR, "illegal POC type %d\n", sps->poc_type);
  6313. return -1;
  6314. }
  6315. tmp= get_ue_golomb(&s->gb);
  6316. if(tmp > MAX_PICTURE_COUNT-2 || tmp >= 32){
  6317. av_log(h->s.avctx, AV_LOG_ERROR, "too many reference frames\n");
  6318. return -1;
  6319. }
  6320. sps->ref_frame_count= tmp;
  6321. sps->gaps_in_frame_num_allowed_flag= get_bits1(&s->gb);
  6322. mb_width= get_ue_golomb(&s->gb) + 1;
  6323. mb_height= get_ue_golomb(&s->gb) + 1;
  6324. if(mb_width >= INT_MAX/16 || mb_height >= INT_MAX/16 ||
  6325. avcodec_check_dimensions(NULL, 16*mb_width, 16*mb_height)){
  6326. av_log(h->s.avctx, AV_LOG_ERROR, "mb_width/height overflow\n");
  6327. return -1;
  6328. }
  6329. sps->mb_width = mb_width;
  6330. sps->mb_height= mb_height;
  6331. sps->frame_mbs_only_flag= get_bits1(&s->gb);
  6332. if(!sps->frame_mbs_only_flag)
  6333. sps->mb_aff= get_bits1(&s->gb);
  6334. else
  6335. sps->mb_aff= 0;
  6336. sps->direct_8x8_inference_flag= get_bits1(&s->gb);
  6337. #ifndef ALLOW_INTERLACE
  6338. if(sps->mb_aff)
  6339. av_log(h->s.avctx, AV_LOG_ERROR, "MBAFF support not included; enable it at compile-time.\n");
  6340. #endif
  6341. if(!sps->direct_8x8_inference_flag && sps->mb_aff)
  6342. av_log(h->s.avctx, AV_LOG_ERROR, "MBAFF + !direct_8x8_inference is not implemented\n");
  6343. sps->crop= get_bits1(&s->gb);
  6344. if(sps->crop){
  6345. sps->crop_left = get_ue_golomb(&s->gb);
  6346. sps->crop_right = get_ue_golomb(&s->gb);
  6347. sps->crop_top = get_ue_golomb(&s->gb);
  6348. sps->crop_bottom= get_ue_golomb(&s->gb);
  6349. if(sps->crop_left || sps->crop_top){
  6350. av_log(h->s.avctx, AV_LOG_ERROR, "insane cropping not completely supported, this could look slightly wrong ...\n");
  6351. }
  6352. }else{
  6353. sps->crop_left =
  6354. sps->crop_right =
  6355. sps->crop_top =
  6356. sps->crop_bottom= 0;
  6357. }
  6358. sps->vui_parameters_present_flag= get_bits1(&s->gb);
  6359. if( sps->vui_parameters_present_flag )
  6360. decode_vui_parameters(h, sps);
  6361. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  6362. av_log(h->s.avctx, AV_LOG_DEBUG, "sps:%u profile:%d/%d poc:%d ref:%d %dx%d %s %s crop:%d/%d/%d/%d %s\n",
  6363. sps_id, sps->profile_idc, sps->level_idc,
  6364. sps->poc_type,
  6365. sps->ref_frame_count,
  6366. sps->mb_width, sps->mb_height,
  6367. sps->frame_mbs_only_flag ? "FRM" : (sps->mb_aff ? "MB-AFF" : "PIC-AFF"),
  6368. sps->direct_8x8_inference_flag ? "8B8" : "",
  6369. sps->crop_left, sps->crop_right,
  6370. sps->crop_top, sps->crop_bottom,
  6371. sps->vui_parameters_present_flag ? "VUI" : ""
  6372. );
  6373. }
  6374. return 0;
  6375. }
  6376. static void
  6377. build_qp_table(PPS *pps, int t, int index)
  6378. {
  6379. int i;
  6380. for(i = 0; i < 255; i++)
  6381. pps->chroma_qp_table[t][i & 0xff] = chroma_qp[av_clip(i + index, 0, 51)];
  6382. }
  6383. static inline int decode_picture_parameter_set(H264Context *h, int bit_length){
  6384. MpegEncContext * const s = &h->s;
  6385. unsigned int tmp, pps_id= get_ue_golomb(&s->gb);
  6386. PPS *pps;
  6387. pps = alloc_parameter_set(h, (void **)h->pps_buffers, pps_id, MAX_PPS_COUNT, sizeof(PPS), "pps");
  6388. if(pps == NULL)
  6389. return -1;
  6390. tmp= get_ue_golomb(&s->gb);
  6391. if(tmp>=MAX_SPS_COUNT || h->sps_buffers[tmp] == NULL){
  6392. av_log(h->s.avctx, AV_LOG_ERROR, "sps_id out of range\n");
  6393. return -1;
  6394. }
  6395. pps->sps_id= tmp;
  6396. pps->cabac= get_bits1(&s->gb);
  6397. pps->pic_order_present= get_bits1(&s->gb);
  6398. pps->slice_group_count= get_ue_golomb(&s->gb) + 1;
  6399. if(pps->slice_group_count > 1 ){
  6400. pps->mb_slice_group_map_type= get_ue_golomb(&s->gb);
  6401. av_log(h->s.avctx, AV_LOG_ERROR, "FMO not supported\n");
  6402. switch(pps->mb_slice_group_map_type){
  6403. case 0:
  6404. #if 0
  6405. | for( i = 0; i <= num_slice_groups_minus1; i++ ) | | |
  6406. | run_length[ i ] |1 |ue(v) |
  6407. #endif
  6408. break;
  6409. case 2:
  6410. #if 0
  6411. | for( i = 0; i < num_slice_groups_minus1; i++ ) | | |
  6412. |{ | | |
  6413. | top_left_mb[ i ] |1 |ue(v) |
  6414. | bottom_right_mb[ i ] |1 |ue(v) |
  6415. | } | | |
  6416. #endif
  6417. break;
  6418. case 3:
  6419. case 4:
  6420. case 5:
  6421. #if 0
  6422. | slice_group_change_direction_flag |1 |u(1) |
  6423. | slice_group_change_rate_minus1 |1 |ue(v) |
  6424. #endif
  6425. break;
  6426. case 6:
  6427. #if 0
  6428. | slice_group_id_cnt_minus1 |1 |ue(v) |
  6429. | for( i = 0; i <= slice_group_id_cnt_minus1; i++ | | |
  6430. |) | | |
  6431. | slice_group_id[ i ] |1 |u(v) |
  6432. #endif
  6433. break;
  6434. }
  6435. }
  6436. pps->ref_count[0]= get_ue_golomb(&s->gb) + 1;
  6437. pps->ref_count[1]= get_ue_golomb(&s->gb) + 1;
  6438. if(pps->ref_count[0]-1 > 32-1 || pps->ref_count[1]-1 > 32-1){
  6439. av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow (pps)\n");
  6440. pps->ref_count[0]= pps->ref_count[1]= 1;
  6441. return -1;
  6442. }
  6443. pps->weighted_pred= get_bits1(&s->gb);
  6444. pps->weighted_bipred_idc= get_bits(&s->gb, 2);
  6445. pps->init_qp= get_se_golomb(&s->gb) + 26;
  6446. pps->init_qs= get_se_golomb(&s->gb) + 26;
  6447. pps->chroma_qp_index_offset[0]= get_se_golomb(&s->gb);
  6448. pps->deblocking_filter_parameters_present= get_bits1(&s->gb);
  6449. pps->constrained_intra_pred= get_bits1(&s->gb);
  6450. pps->redundant_pic_cnt_present = get_bits1(&s->gb);
  6451. pps->transform_8x8_mode= 0;
  6452. h->dequant_coeff_pps= -1; //contents of sps/pps can change even if id doesn't, so reinit
  6453. memset(pps->scaling_matrix4, 16, 6*16*sizeof(uint8_t));
  6454. memset(pps->scaling_matrix8, 16, 2*64*sizeof(uint8_t));
  6455. if(get_bits_count(&s->gb) < bit_length){
  6456. pps->transform_8x8_mode= get_bits1(&s->gb);
  6457. decode_scaling_matrices(h, h->sps_buffers[pps->sps_id], pps, 0, pps->scaling_matrix4, pps->scaling_matrix8);
  6458. pps->chroma_qp_index_offset[1]= get_se_golomb(&s->gb); //second_chroma_qp_index_offset
  6459. } else {
  6460. pps->chroma_qp_index_offset[1]= pps->chroma_qp_index_offset[0];
  6461. }
  6462. build_qp_table(pps, 0, pps->chroma_qp_index_offset[0]);
  6463. if(pps->chroma_qp_index_offset[0] != pps->chroma_qp_index_offset[1]) {
  6464. build_qp_table(pps, 1, pps->chroma_qp_index_offset[1]);
  6465. h->pps.chroma_qp_diff= 1;
  6466. } else
  6467. memcpy(pps->chroma_qp_table[1], pps->chroma_qp_table[0], 256);
  6468. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  6469. av_log(h->s.avctx, AV_LOG_DEBUG, "pps:%u sps:%u %s slice_groups:%d ref:%d/%d %s qp:%d/%d/%d/%d %s %s %s %s\n",
  6470. pps_id, pps->sps_id,
  6471. pps->cabac ? "CABAC" : "CAVLC",
  6472. pps->slice_group_count,
  6473. pps->ref_count[0], pps->ref_count[1],
  6474. pps->weighted_pred ? "weighted" : "",
  6475. pps->init_qp, pps->init_qs, pps->chroma_qp_index_offset[0], pps->chroma_qp_index_offset[1],
  6476. pps->deblocking_filter_parameters_present ? "LPAR" : "",
  6477. pps->constrained_intra_pred ? "CONSTR" : "",
  6478. pps->redundant_pic_cnt_present ? "REDU" : "",
  6479. pps->transform_8x8_mode ? "8x8DCT" : ""
  6480. );
  6481. }
  6482. return 0;
  6483. }
  6484. /**
  6485. * Call decode_slice() for each context.
  6486. *
  6487. * @param h h264 master context
  6488. * @param context_count number of contexts to execute
  6489. */
  6490. static void execute_decode_slices(H264Context *h, int context_count){
  6491. MpegEncContext * const s = &h->s;
  6492. AVCodecContext * const avctx= s->avctx;
  6493. H264Context *hx;
  6494. int i;
  6495. if(context_count == 1) {
  6496. decode_slice(avctx, h);
  6497. } else {
  6498. for(i = 1; i < context_count; i++) {
  6499. hx = h->thread_context[i];
  6500. hx->s.error_resilience = avctx->error_resilience;
  6501. hx->s.error_count = 0;
  6502. }
  6503. avctx->execute(avctx, (void *)decode_slice,
  6504. (void **)h->thread_context, NULL, context_count);
  6505. /* pull back stuff from slices to master context */
  6506. hx = h->thread_context[context_count - 1];
  6507. s->mb_x = hx->s.mb_x;
  6508. s->mb_y = hx->s.mb_y;
  6509. s->dropable = hx->s.dropable;
  6510. s->picture_structure = hx->s.picture_structure;
  6511. for(i = 1; i < context_count; i++)
  6512. h->s.error_count += h->thread_context[i]->s.error_count;
  6513. }
  6514. }
  6515. static int decode_nal_units(H264Context *h, uint8_t *buf, int buf_size){
  6516. MpegEncContext * const s = &h->s;
  6517. AVCodecContext * const avctx= s->avctx;
  6518. int buf_index=0;
  6519. H264Context *hx; ///< thread context
  6520. int context_count = 0;
  6521. h->max_contexts = avctx->thread_count;
  6522. #if 0
  6523. int i;
  6524. for(i=0; i<50; i++){
  6525. av_log(NULL, AV_LOG_ERROR,"%02X ", buf[i]);
  6526. }
  6527. #endif
  6528. if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
  6529. h->current_slice = 0;
  6530. if (!s->first_field)
  6531. s->current_picture_ptr= NULL;
  6532. }
  6533. for(;;){
  6534. int consumed;
  6535. int dst_length;
  6536. int bit_length;
  6537. uint8_t *ptr;
  6538. int i, nalsize = 0;
  6539. int err;
  6540. if(h->is_avc) {
  6541. if(buf_index >= buf_size) break;
  6542. nalsize = 0;
  6543. for(i = 0; i < h->nal_length_size; i++)
  6544. nalsize = (nalsize << 8) | buf[buf_index++];
  6545. if(nalsize <= 1 || (nalsize+buf_index > buf_size)){
  6546. if(nalsize == 1){
  6547. buf_index++;
  6548. continue;
  6549. }else{
  6550. av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
  6551. break;
  6552. }
  6553. }
  6554. } else {
  6555. // start code prefix search
  6556. for(; buf_index + 3 < buf_size; buf_index++){
  6557. // This should always succeed in the first iteration.
  6558. if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)
  6559. break;
  6560. }
  6561. if(buf_index+3 >= buf_size) break;
  6562. buf_index+=3;
  6563. }
  6564. hx = h->thread_context[context_count];
  6565. ptr= decode_nal(hx, buf + buf_index, &dst_length, &consumed, h->is_avc ? nalsize : buf_size - buf_index);
  6566. if (ptr==NULL || dst_length < 0){
  6567. return -1;
  6568. }
  6569. while(ptr[dst_length - 1] == 0 && dst_length > 0)
  6570. dst_length--;
  6571. bit_length= !dst_length ? 0 : (8*dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1));
  6572. if(s->avctx->debug&FF_DEBUG_STARTCODE){
  6573. av_log(h->s.avctx, AV_LOG_DEBUG, "NAL %d at %d/%d length %d\n", hx->nal_unit_type, buf_index, buf_size, dst_length);
  6574. }
  6575. if (h->is_avc && (nalsize != consumed))
  6576. av_log(h->s.avctx, AV_LOG_ERROR, "AVC: Consumed only %d bytes instead of %d\n", consumed, nalsize);
  6577. buf_index += consumed;
  6578. if( (s->hurry_up == 1 && h->nal_ref_idc == 0) //FIXME do not discard SEI id
  6579. ||(avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
  6580. continue;
  6581. again:
  6582. err = 0;
  6583. switch(hx->nal_unit_type){
  6584. case NAL_IDR_SLICE:
  6585. if (h->nal_unit_type != NAL_IDR_SLICE) {
  6586. av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices");
  6587. return -1;
  6588. }
  6589. idr(h); //FIXME ensure we don't loose some frames if there is reordering
  6590. case NAL_SLICE:
  6591. init_get_bits(&hx->s.gb, ptr, bit_length);
  6592. hx->intra_gb_ptr=
  6593. hx->inter_gb_ptr= &hx->s.gb;
  6594. hx->s.data_partitioning = 0;
  6595. if((err = decode_slice_header(hx, h)))
  6596. break;
  6597. s->current_picture_ptr->key_frame|= (hx->nal_unit_type == NAL_IDR_SLICE);
  6598. if(hx->redundant_pic_count==0 && hx->s.hurry_up < 5
  6599. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  6600. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type!=B_TYPE)
  6601. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type==I_TYPE)
  6602. && avctx->skip_frame < AVDISCARD_ALL)
  6603. context_count++;
  6604. break;
  6605. case NAL_DPA:
  6606. init_get_bits(&hx->s.gb, ptr, bit_length);
  6607. hx->intra_gb_ptr=
  6608. hx->inter_gb_ptr= NULL;
  6609. hx->s.data_partitioning = 1;
  6610. err = decode_slice_header(hx, h);
  6611. break;
  6612. case NAL_DPB:
  6613. init_get_bits(&hx->intra_gb, ptr, bit_length);
  6614. hx->intra_gb_ptr= &hx->intra_gb;
  6615. break;
  6616. case NAL_DPC:
  6617. init_get_bits(&hx->inter_gb, ptr, bit_length);
  6618. hx->inter_gb_ptr= &hx->inter_gb;
  6619. if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
  6620. && s->context_initialized
  6621. && s->hurry_up < 5
  6622. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  6623. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type!=B_TYPE)
  6624. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type==I_TYPE)
  6625. && avctx->skip_frame < AVDISCARD_ALL)
  6626. context_count++;
  6627. break;
  6628. case NAL_SEI:
  6629. init_get_bits(&s->gb, ptr, bit_length);
  6630. decode_sei(h);
  6631. break;
  6632. case NAL_SPS:
  6633. init_get_bits(&s->gb, ptr, bit_length);
  6634. decode_seq_parameter_set(h);
  6635. if(s->flags& CODEC_FLAG_LOW_DELAY)
  6636. s->low_delay=1;
  6637. if(avctx->has_b_frames < 2)
  6638. avctx->has_b_frames= !s->low_delay;
  6639. break;
  6640. case NAL_PPS:
  6641. init_get_bits(&s->gb, ptr, bit_length);
  6642. decode_picture_parameter_set(h, bit_length);
  6643. break;
  6644. case NAL_AUD:
  6645. case NAL_END_SEQUENCE:
  6646. case NAL_END_STREAM:
  6647. case NAL_FILLER_DATA:
  6648. case NAL_SPS_EXT:
  6649. case NAL_AUXILIARY_SLICE:
  6650. break;
  6651. default:
  6652. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", h->nal_unit_type, bit_length);
  6653. }
  6654. if(context_count == h->max_contexts) {
  6655. execute_decode_slices(h, context_count);
  6656. context_count = 0;
  6657. }
  6658. if (err < 0)
  6659. av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  6660. else if(err == 1) {
  6661. /* Slice could not be decoded in parallel mode, copy down
  6662. * NAL unit stuff to context 0 and restart. Note that
  6663. * rbsp_buffer is not transfered, but since we no longer
  6664. * run in parallel mode this should not be an issue. */
  6665. h->nal_unit_type = hx->nal_unit_type;
  6666. h->nal_ref_idc = hx->nal_ref_idc;
  6667. hx = h;
  6668. goto again;
  6669. }
  6670. }
  6671. if(context_count)
  6672. execute_decode_slices(h, context_count);
  6673. return buf_index;
  6674. }
  6675. /**
  6676. * returns the number of bytes consumed for building the current frame
  6677. */
  6678. static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
  6679. if(s->flags&CODEC_FLAG_TRUNCATED){
  6680. pos -= s->parse_context.last_index;
  6681. if(pos<0) pos=0; // FIXME remove (unneeded?)
  6682. return pos;
  6683. }else{
  6684. if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
  6685. if(pos+10>buf_size) pos=buf_size; // oops ;)
  6686. return pos;
  6687. }
  6688. }
  6689. static int decode_frame(AVCodecContext *avctx,
  6690. void *data, int *data_size,
  6691. uint8_t *buf, int buf_size)
  6692. {
  6693. H264Context *h = avctx->priv_data;
  6694. MpegEncContext *s = &h->s;
  6695. AVFrame *pict = data;
  6696. int buf_index;
  6697. s->flags= avctx->flags;
  6698. s->flags2= avctx->flags2;
  6699. /* no supplementary picture */
  6700. if (buf_size == 0) {
  6701. Picture *out;
  6702. int i, out_idx;
  6703. //FIXME factorize this with the output code below
  6704. out = h->delayed_pic[0];
  6705. out_idx = 0;
  6706. for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame; i++)
  6707. if(h->delayed_pic[i]->poc < out->poc){
  6708. out = h->delayed_pic[i];
  6709. out_idx = i;
  6710. }
  6711. for(i=out_idx; h->delayed_pic[i]; i++)
  6712. h->delayed_pic[i] = h->delayed_pic[i+1];
  6713. if(out){
  6714. *data_size = sizeof(AVFrame);
  6715. *pict= *(AVFrame*)out;
  6716. }
  6717. return 0;
  6718. }
  6719. if(s->flags&CODEC_FLAG_TRUNCATED){
  6720. int next= ff_h264_find_frame_end(h, buf, buf_size);
  6721. if( ff_combine_frame(&s->parse_context, next, (const uint8_t **)&buf, &buf_size) < 0 )
  6722. return buf_size;
  6723. //printf("next:%d buf_size:%d last_index:%d\n", next, buf_size, s->parse_context.last_index);
  6724. }
  6725. if(h->is_avc && !h->got_avcC) {
  6726. int i, cnt, nalsize;
  6727. unsigned char *p = avctx->extradata;
  6728. if(avctx->extradata_size < 7) {
  6729. av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
  6730. return -1;
  6731. }
  6732. if(*p != 1) {
  6733. av_log(avctx, AV_LOG_ERROR, "Unknown avcC version %d\n", *p);
  6734. return -1;
  6735. }
  6736. /* sps and pps in the avcC always have length coded with 2 bytes,
  6737. so put a fake nal_length_size = 2 while parsing them */
  6738. h->nal_length_size = 2;
  6739. // Decode sps from avcC
  6740. cnt = *(p+5) & 0x1f; // Number of sps
  6741. p += 6;
  6742. for (i = 0; i < cnt; i++) {
  6743. nalsize = AV_RB16(p) + 2;
  6744. if(decode_nal_units(h, p, nalsize) < 0) {
  6745. av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);
  6746. return -1;
  6747. }
  6748. p += nalsize;
  6749. }
  6750. // Decode pps from avcC
  6751. cnt = *(p++); // Number of pps
  6752. for (i = 0; i < cnt; i++) {
  6753. nalsize = AV_RB16(p) + 2;
  6754. if(decode_nal_units(h, p, nalsize) != nalsize) {
  6755. av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);
  6756. return -1;
  6757. }
  6758. p += nalsize;
  6759. }
  6760. // Now store right nal length size, that will be use to parse all other nals
  6761. h->nal_length_size = ((*(((char*)(avctx->extradata))+4))&0x03)+1;
  6762. // Do not reparse avcC
  6763. h->got_avcC = 1;
  6764. }
  6765. if(avctx->frame_number==0 && !h->is_avc && s->avctx->extradata_size){
  6766. if(decode_nal_units(h, s->avctx->extradata, s->avctx->extradata_size) < 0)
  6767. return -1;
  6768. }
  6769. buf_index=decode_nal_units(h, buf, buf_size);
  6770. if(buf_index < 0)
  6771. return -1;
  6772. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
  6773. if (avctx->skip_frame >= AVDISCARD_NONREF || s->hurry_up) return 0;
  6774. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  6775. return -1;
  6776. }
  6777. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
  6778. Picture *out = s->current_picture_ptr;
  6779. Picture *cur = s->current_picture_ptr;
  6780. Picture *prev = h->delayed_output_pic;
  6781. int i, pics, cross_idr, out_of_order, out_idx;
  6782. s->mb_y= 0;
  6783. s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;
  6784. s->current_picture_ptr->pict_type= s->pict_type;
  6785. h->prev_frame_num_offset= h->frame_num_offset;
  6786. h->prev_frame_num= h->frame_num;
  6787. if(!s->dropable) {
  6788. h->prev_poc_msb= h->poc_msb;
  6789. h->prev_poc_lsb= h->poc_lsb;
  6790. execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  6791. }
  6792. /*
  6793. * FIXME: Error handling code does not seem to support interlaced
  6794. * when slices span multiple rows
  6795. * The ff_er_add_slice calls don't work right for bottom
  6796. * fields; they cause massive erroneous error concealing
  6797. * Error marking covers both fields (top and bottom).
  6798. * This causes a mismatched s->error_count
  6799. * and a bad error table. Further, the error count goes to
  6800. * INT_MAX when called for bottom field, because mb_y is
  6801. * past end by one (callers fault) and resync_mb_y != 0
  6802. * causes problems for the first MB line, too.
  6803. */
  6804. if (!FIELD_PICTURE)
  6805. ff_er_frame_end(s);
  6806. MPV_frame_end(s);
  6807. if (s->first_field) {
  6808. /* Wait for second field. */
  6809. *data_size = 0;
  6810. } else {
  6811. cur->interlaced_frame = FIELD_OR_MBAFF_PICTURE;
  6812. /* Derive top_field_first from field pocs. */
  6813. cur->top_field_first = cur->field_poc[0] < cur->field_poc[1];
  6814. //FIXME do something with unavailable reference frames
  6815. #if 0 //decode order
  6816. *data_size = sizeof(AVFrame);
  6817. #else
  6818. /* Sort B-frames into display order */
  6819. if(h->sps.bitstream_restriction_flag
  6820. && s->avctx->has_b_frames < h->sps.num_reorder_frames){
  6821. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  6822. s->low_delay = 0;
  6823. }
  6824. pics = 0;
  6825. while(h->delayed_pic[pics]) pics++;
  6826. assert(pics+1 < sizeof(h->delayed_pic) / sizeof(h->delayed_pic[0]));
  6827. h->delayed_pic[pics++] = cur;
  6828. if(cur->reference == 0)
  6829. cur->reference = DELAYED_PIC_REF;
  6830. cross_idr = 0;
  6831. for(i=0; h->delayed_pic[i]; i++)
  6832. if(h->delayed_pic[i]->key_frame || h->delayed_pic[i]->poc==0)
  6833. cross_idr = 1;
  6834. out = h->delayed_pic[0];
  6835. out_idx = 0;
  6836. for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame; i++)
  6837. if(h->delayed_pic[i]->poc < out->poc){
  6838. out = h->delayed_pic[i];
  6839. out_idx = i;
  6840. }
  6841. out_of_order = !cross_idr && prev && out->poc < prev->poc;
  6842. if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames >= h->sps.num_reorder_frames)
  6843. { }
  6844. else if(prev && pics <= s->avctx->has_b_frames)
  6845. out = prev;
  6846. else if((out_of_order && pics-1 == s->avctx->has_b_frames && pics < 15)
  6847. || (s->low_delay &&
  6848. ((!cross_idr && prev && out->poc > prev->poc + 2)
  6849. || cur->pict_type == B_TYPE)))
  6850. {
  6851. s->low_delay = 0;
  6852. s->avctx->has_b_frames++;
  6853. out = prev;
  6854. }
  6855. else if(out_of_order)
  6856. out = prev;
  6857. if(out_of_order || pics > s->avctx->has_b_frames){
  6858. for(i=out_idx; h->delayed_pic[i]; i++)
  6859. h->delayed_pic[i] = h->delayed_pic[i+1];
  6860. }
  6861. if(prev == out)
  6862. *data_size = 0;
  6863. else
  6864. *data_size = sizeof(AVFrame);
  6865. if(prev && prev != out && prev->reference == DELAYED_PIC_REF)
  6866. prev->reference = 0;
  6867. h->delayed_output_pic = out;
  6868. #endif
  6869. if(out)
  6870. *pict= *(AVFrame*)out;
  6871. else
  6872. av_log(avctx, AV_LOG_DEBUG, "no picture\n");
  6873. }
  6874. }
  6875. assert(pict->data[0] || !*data_size);
  6876. ff_print_debug_info(s, pict);
  6877. //printf("out %d\n", (int)pict->data[0]);
  6878. #if 0 //?
  6879. /* Return the Picture timestamp as the frame number */
  6880. /* we subtract 1 because it is added on utils.c */
  6881. avctx->frame_number = s->picture_number - 1;
  6882. #endif
  6883. return get_consumed_bytes(s, buf_index, buf_size);
  6884. }
  6885. #if 0
  6886. static inline void fill_mb_avail(H264Context *h){
  6887. MpegEncContext * const s = &h->s;
  6888. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  6889. if(s->mb_y){
  6890. h->mb_avail[0]= s->mb_x && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
  6891. h->mb_avail[1]= h->slice_table[mb_xy - s->mb_stride ] == h->slice_num;
  6892. h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
  6893. }else{
  6894. h->mb_avail[0]=
  6895. h->mb_avail[1]=
  6896. h->mb_avail[2]= 0;
  6897. }
  6898. h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
  6899. h->mb_avail[4]= 1; //FIXME move out
  6900. h->mb_avail[5]= 0; //FIXME move out
  6901. }
  6902. #endif
  6903. #ifdef TEST
  6904. #undef printf
  6905. #undef random
  6906. #define COUNT 8000
  6907. #define SIZE (COUNT*40)
  6908. int main(void){
  6909. int i;
  6910. uint8_t temp[SIZE];
  6911. PutBitContext pb;
  6912. GetBitContext gb;
  6913. // int int_temp[10000];
  6914. DSPContext dsp;
  6915. AVCodecContext avctx;
  6916. dsputil_init(&dsp, &avctx);
  6917. init_put_bits(&pb, temp, SIZE);
  6918. printf("testing unsigned exp golomb\n");
  6919. for(i=0; i<COUNT; i++){
  6920. START_TIMER
  6921. set_ue_golomb(&pb, i);
  6922. STOP_TIMER("set_ue_golomb");
  6923. }
  6924. flush_put_bits(&pb);
  6925. init_get_bits(&gb, temp, 8*SIZE);
  6926. for(i=0; i<COUNT; i++){
  6927. int j, s;
  6928. s= show_bits(&gb, 24);
  6929. START_TIMER
  6930. j= get_ue_golomb(&gb);
  6931. if(j != i){
  6932. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  6933. // return -1;
  6934. }
  6935. STOP_TIMER("get_ue_golomb");
  6936. }
  6937. init_put_bits(&pb, temp, SIZE);
  6938. printf("testing signed exp golomb\n");
  6939. for(i=0; i<COUNT; i++){
  6940. START_TIMER
  6941. set_se_golomb(&pb, i - COUNT/2);
  6942. STOP_TIMER("set_se_golomb");
  6943. }
  6944. flush_put_bits(&pb);
  6945. init_get_bits(&gb, temp, 8*SIZE);
  6946. for(i=0; i<COUNT; i++){
  6947. int j, s;
  6948. s= show_bits(&gb, 24);
  6949. START_TIMER
  6950. j= get_se_golomb(&gb);
  6951. if(j != i - COUNT/2){
  6952. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  6953. // return -1;
  6954. }
  6955. STOP_TIMER("get_se_golomb");
  6956. }
  6957. #if 0
  6958. printf("testing 4x4 (I)DCT\n");
  6959. DCTELEM block[16];
  6960. uint8_t src[16], ref[16];
  6961. uint64_t error= 0, max_error=0;
  6962. for(i=0; i<COUNT; i++){
  6963. int j;
  6964. // printf("%d %d %d\n", r1, r2, (r2-r1)*16);
  6965. for(j=0; j<16; j++){
  6966. ref[j]= random()%255;
  6967. src[j]= random()%255;
  6968. }
  6969. h264_diff_dct_c(block, src, ref, 4);
  6970. //normalize
  6971. for(j=0; j<16; j++){
  6972. // printf("%d ", block[j]);
  6973. block[j]= block[j]*4;
  6974. if(j&1) block[j]= (block[j]*4 + 2)/5;
  6975. if(j&4) block[j]= (block[j]*4 + 2)/5;
  6976. }
  6977. // printf("\n");
  6978. s->dsp.h264_idct_add(ref, block, 4);
  6979. /* for(j=0; j<16; j++){
  6980. printf("%d ", ref[j]);
  6981. }
  6982. printf("\n");*/
  6983. for(j=0; j<16; j++){
  6984. int diff= FFABS(src[j] - ref[j]);
  6985. error+= diff*diff;
  6986. max_error= FFMAX(max_error, diff);
  6987. }
  6988. }
  6989. printf("error=%f max_error=%d\n", ((float)error)/COUNT/16, (int)max_error );
  6990. printf("testing quantizer\n");
  6991. for(qp=0; qp<52; qp++){
  6992. for(i=0; i<16; i++)
  6993. src1_block[i]= src2_block[i]= random()%255;
  6994. }
  6995. printf("Testing NAL layer\n");
  6996. uint8_t bitstream[COUNT];
  6997. uint8_t nal[COUNT*2];
  6998. H264Context h;
  6999. memset(&h, 0, sizeof(H264Context));
  7000. for(i=0; i<COUNT; i++){
  7001. int zeros= i;
  7002. int nal_length;
  7003. int consumed;
  7004. int out_length;
  7005. uint8_t *out;
  7006. int j;
  7007. for(j=0; j<COUNT; j++){
  7008. bitstream[j]= (random() % 255) + 1;
  7009. }
  7010. for(j=0; j<zeros; j++){
  7011. int pos= random() % COUNT;
  7012. while(bitstream[pos] == 0){
  7013. pos++;
  7014. pos %= COUNT;
  7015. }
  7016. bitstream[pos]=0;
  7017. }
  7018. START_TIMER
  7019. nal_length= encode_nal(&h, nal, bitstream, COUNT, COUNT*2);
  7020. if(nal_length<0){
  7021. printf("encoding failed\n");
  7022. return -1;
  7023. }
  7024. out= decode_nal(&h, nal, &out_length, &consumed, nal_length);
  7025. STOP_TIMER("NAL")
  7026. if(out_length != COUNT){
  7027. printf("incorrect length %d %d\n", out_length, COUNT);
  7028. return -1;
  7029. }
  7030. if(consumed != nal_length){
  7031. printf("incorrect consumed length %d %d\n", nal_length, consumed);
  7032. return -1;
  7033. }
  7034. if(memcmp(bitstream, out, COUNT)){
  7035. printf("mismatch\n");
  7036. return -1;
  7037. }
  7038. }
  7039. #endif
  7040. printf("Testing RBSP\n");
  7041. return 0;
  7042. }
  7043. #endif /* TEST */
  7044. static int decode_end(AVCodecContext *avctx)
  7045. {
  7046. H264Context *h = avctx->priv_data;
  7047. MpegEncContext *s = &h->s;
  7048. av_freep(&h->rbsp_buffer[0]);
  7049. av_freep(&h->rbsp_buffer[1]);
  7050. free_tables(h); //FIXME cleanup init stuff perhaps
  7051. MPV_common_end(s);
  7052. // memset(h, 0, sizeof(H264Context));
  7053. return 0;
  7054. }
  7055. AVCodec h264_decoder = {
  7056. "h264",
  7057. CODEC_TYPE_VIDEO,
  7058. CODEC_ID_H264,
  7059. sizeof(H264Context),
  7060. decode_init,
  7061. NULL,
  7062. decode_end,
  7063. decode_frame,
  7064. /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
  7065. .flush= flush_dpb,
  7066. };
  7067. #include "svq3.c"