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.

8028 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. if( h->pps.cabac ) {
  1809. CHECKED_ALLOCZ(h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t))
  1810. CHECKED_ALLOCZ(h->mvd_table[0], 32*big_mb_num * sizeof(uint16_t));
  1811. CHECKED_ALLOCZ(h->mvd_table[1], 32*big_mb_num * sizeof(uint16_t));
  1812. CHECKED_ALLOCZ(h->direct_table, 32*big_mb_num * sizeof(uint8_t));
  1813. }
  1814. memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride) * sizeof(uint8_t));
  1815. h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
  1816. CHECKED_ALLOCZ(h->mb2b_xy , big_mb_num * sizeof(uint32_t));
  1817. CHECKED_ALLOCZ(h->mb2b8_xy , big_mb_num * sizeof(uint32_t));
  1818. for(y=0; y<s->mb_height; y++){
  1819. for(x=0; x<s->mb_width; x++){
  1820. const int mb_xy= x + y*s->mb_stride;
  1821. const int b_xy = 4*x + 4*y*h->b_stride;
  1822. const int b8_xy= 2*x + 2*y*h->b8_stride;
  1823. h->mb2b_xy [mb_xy]= b_xy;
  1824. h->mb2b8_xy[mb_xy]= b8_xy;
  1825. }
  1826. }
  1827. s->obmc_scratchpad = NULL;
  1828. if(!h->dequant4_coeff[0])
  1829. init_dequant_tables(h);
  1830. return 0;
  1831. fail:
  1832. free_tables(h);
  1833. return -1;
  1834. }
  1835. /**
  1836. * Mimic alloc_tables(), but for every context thread.
  1837. */
  1838. static void clone_tables(H264Context *dst, H264Context *src){
  1839. dst->intra4x4_pred_mode = src->intra4x4_pred_mode;
  1840. dst->non_zero_count = src->non_zero_count;
  1841. dst->slice_table = src->slice_table;
  1842. dst->cbp_table = src->cbp_table;
  1843. dst->mb2b_xy = src->mb2b_xy;
  1844. dst->mb2b8_xy = src->mb2b8_xy;
  1845. dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
  1846. dst->mvd_table[0] = src->mvd_table[0];
  1847. dst->mvd_table[1] = src->mvd_table[1];
  1848. dst->direct_table = src->direct_table;
  1849. dst->s.obmc_scratchpad = NULL;
  1850. ff_h264_pred_init(&dst->hpc, src->s.codec_id);
  1851. }
  1852. /**
  1853. * Init context
  1854. * Allocate buffers which are not shared amongst multiple threads.
  1855. */
  1856. static int context_init(H264Context *h){
  1857. MpegEncContext * const s = &h->s;
  1858. CHECKED_ALLOCZ(h->top_borders[0], h->s.mb_width * (16+8+8) * sizeof(uint8_t))
  1859. CHECKED_ALLOCZ(h->top_borders[1], h->s.mb_width * (16+8+8) * sizeof(uint8_t))
  1860. // edge emu needs blocksize + filter length - 1 (=17x17 for halfpel / 21x21 for h264)
  1861. CHECKED_ALLOCZ(s->allocated_edge_emu_buffer,
  1862. (s->width+64)*2*21*2); //(width + edge + align)*interlaced*MBsize*tolerance
  1863. s->edge_emu_buffer= s->allocated_edge_emu_buffer + (s->width+64)*2*21;
  1864. return 0;
  1865. fail:
  1866. return -1; // free_tables will clean up for us
  1867. }
  1868. static void common_init(H264Context *h){
  1869. MpegEncContext * const s = &h->s;
  1870. s->width = s->avctx->width;
  1871. s->height = s->avctx->height;
  1872. s->codec_id= s->avctx->codec->id;
  1873. ff_h264_pred_init(&h->hpc, s->codec_id);
  1874. h->dequant_coeff_pps= -1;
  1875. s->unrestricted_mv=1;
  1876. s->decode=1; //FIXME
  1877. memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
  1878. memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
  1879. }
  1880. static int decode_init(AVCodecContext *avctx){
  1881. H264Context *h= avctx->priv_data;
  1882. MpegEncContext * const s = &h->s;
  1883. MPV_decode_defaults(s);
  1884. s->avctx = avctx;
  1885. common_init(h);
  1886. s->out_format = FMT_H264;
  1887. s->workaround_bugs= avctx->workaround_bugs;
  1888. // set defaults
  1889. // s->decode_mb= ff_h263_decode_mb;
  1890. s->quarter_sample = 1;
  1891. s->low_delay= 1;
  1892. avctx->pix_fmt= PIX_FMT_YUV420P;
  1893. decode_init_vlc();
  1894. if(avctx->extradata_size > 0 && avctx->extradata &&
  1895. *(char *)avctx->extradata == 1){
  1896. h->is_avc = 1;
  1897. h->got_avcC = 0;
  1898. } else {
  1899. h->is_avc = 0;
  1900. }
  1901. h->thread_context[0] = h;
  1902. return 0;
  1903. }
  1904. static int frame_start(H264Context *h){
  1905. MpegEncContext * const s = &h->s;
  1906. int i;
  1907. if(MPV_frame_start(s, s->avctx) < 0)
  1908. return -1;
  1909. ff_er_frame_start(s);
  1910. /*
  1911. * MPV_frame_start uses pict_type to derive key_frame.
  1912. * This is incorrect for H.264; IDR markings must be used.
  1913. * Zero here; IDR markings per slice in frame or fields are OR'd in later.
  1914. * See decode_nal_units().
  1915. */
  1916. s->current_picture_ptr->key_frame= 0;
  1917. assert(s->linesize && s->uvlinesize);
  1918. for(i=0; i<16; i++){
  1919. h->block_offset[i]= 4*((scan8[i] - scan8[0])&7) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
  1920. h->block_offset[24+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->linesize*((scan8[i] - scan8[0])>>3);
  1921. }
  1922. for(i=0; i<4; i++){
  1923. h->block_offset[16+i]=
  1924. h->block_offset[20+i]= 4*((scan8[i] - scan8[0])&7) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
  1925. h->block_offset[24+16+i]=
  1926. h->block_offset[24+20+i]= 4*((scan8[i] - scan8[0])&7) + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
  1927. }
  1928. /* can't be in alloc_tables because linesize isn't known there.
  1929. * FIXME: redo bipred weight to not require extra buffer? */
  1930. for(i = 0; i < s->avctx->thread_count; i++)
  1931. if(!h->thread_context[i]->s.obmc_scratchpad)
  1932. h->thread_context[i]->s.obmc_scratchpad = av_malloc(16*2*s->linesize + 8*2*s->uvlinesize);
  1933. /* some macroblocks will be accessed before they're available */
  1934. if(FRAME_MBAFF || s->avctx->thread_count > 1)
  1935. memset(h->slice_table, -1, (s->mb_height*s->mb_stride-1) * sizeof(uint8_t));
  1936. // s->decode= (s->flags&CODEC_FLAG_PSNR) || !s->encoding || s->current_picture.reference /*|| h->contains_intra*/ || 1;
  1937. return 0;
  1938. }
  1939. 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){
  1940. MpegEncContext * const s = &h->s;
  1941. int i;
  1942. src_y -= linesize;
  1943. src_cb -= uvlinesize;
  1944. src_cr -= uvlinesize;
  1945. // There are two lines saved, the line above the the top macroblock of a pair,
  1946. // and the line above the bottom macroblock
  1947. h->left_border[0]= h->top_borders[0][s->mb_x][15];
  1948. for(i=1; i<17; i++){
  1949. h->left_border[i]= src_y[15+i* linesize];
  1950. }
  1951. *(uint64_t*)(h->top_borders[0][s->mb_x]+0)= *(uint64_t*)(src_y + 16*linesize);
  1952. *(uint64_t*)(h->top_borders[0][s->mb_x]+8)= *(uint64_t*)(src_y +8+16*linesize);
  1953. if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1954. h->left_border[17 ]= h->top_borders[0][s->mb_x][16+7];
  1955. h->left_border[17+9]= h->top_borders[0][s->mb_x][24+7];
  1956. for(i=1; i<9; i++){
  1957. h->left_border[i+17 ]= src_cb[7+i*uvlinesize];
  1958. h->left_border[i+17+9]= src_cr[7+i*uvlinesize];
  1959. }
  1960. *(uint64_t*)(h->top_borders[0][s->mb_x]+16)= *(uint64_t*)(src_cb+8*uvlinesize);
  1961. *(uint64_t*)(h->top_borders[0][s->mb_x]+24)= *(uint64_t*)(src_cr+8*uvlinesize);
  1962. }
  1963. }
  1964. 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){
  1965. MpegEncContext * const s = &h->s;
  1966. int temp8, i;
  1967. uint64_t temp64;
  1968. int deblock_left;
  1969. int deblock_top;
  1970. int mb_xy;
  1971. if(h->deblocking_filter == 2) {
  1972. mb_xy = s->mb_x + s->mb_y*s->mb_stride;
  1973. deblock_left = h->slice_table[mb_xy] == h->slice_table[mb_xy - 1];
  1974. deblock_top = h->slice_table[mb_xy] == h->slice_table[h->top_mb_xy];
  1975. } else {
  1976. deblock_left = (s->mb_x > 0);
  1977. deblock_top = (s->mb_y > 0);
  1978. }
  1979. src_y -= linesize + 1;
  1980. src_cb -= uvlinesize + 1;
  1981. src_cr -= uvlinesize + 1;
  1982. #define XCHG(a,b,t,xchg)\
  1983. t= a;\
  1984. if(xchg)\
  1985. a= b;\
  1986. b= t;
  1987. if(deblock_left){
  1988. for(i = !deblock_top; i<17; i++){
  1989. XCHG(h->left_border[i ], src_y [i* linesize], temp8, xchg);
  1990. }
  1991. }
  1992. if(deblock_top){
  1993. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+0), *(uint64_t*)(src_y +1), temp64, xchg);
  1994. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+8), *(uint64_t*)(src_y +9), temp64, 1);
  1995. if(s->mb_x+1 < s->mb_width){
  1996. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x+1]), *(uint64_t*)(src_y +17), temp64, 1);
  1997. }
  1998. }
  1999. if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  2000. if(deblock_left){
  2001. for(i = !deblock_top; i<9; i++){
  2002. XCHG(h->left_border[i+17 ], src_cb[i*uvlinesize], temp8, xchg);
  2003. XCHG(h->left_border[i+17+9], src_cr[i*uvlinesize], temp8, xchg);
  2004. }
  2005. }
  2006. if(deblock_top){
  2007. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+16), *(uint64_t*)(src_cb+1), temp64, 1);
  2008. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+24), *(uint64_t*)(src_cr+1), temp64, 1);
  2009. }
  2010. }
  2011. }
  2012. static inline void backup_pair_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize){
  2013. MpegEncContext * const s = &h->s;
  2014. int i;
  2015. src_y -= 2 * linesize;
  2016. src_cb -= 2 * uvlinesize;
  2017. src_cr -= 2 * uvlinesize;
  2018. // There are two lines saved, the line above the the top macroblock of a pair,
  2019. // and the line above the bottom macroblock
  2020. h->left_border[0]= h->top_borders[0][s->mb_x][15];
  2021. h->left_border[1]= h->top_borders[1][s->mb_x][15];
  2022. for(i=2; i<34; i++){
  2023. h->left_border[i]= src_y[15+i* linesize];
  2024. }
  2025. *(uint64_t*)(h->top_borders[0][s->mb_x]+0)= *(uint64_t*)(src_y + 32*linesize);
  2026. *(uint64_t*)(h->top_borders[0][s->mb_x]+8)= *(uint64_t*)(src_y +8+32*linesize);
  2027. *(uint64_t*)(h->top_borders[1][s->mb_x]+0)= *(uint64_t*)(src_y + 33*linesize);
  2028. *(uint64_t*)(h->top_borders[1][s->mb_x]+8)= *(uint64_t*)(src_y +8+33*linesize);
  2029. if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  2030. h->left_border[34 ]= h->top_borders[0][s->mb_x][16+7];
  2031. h->left_border[34+ 1]= h->top_borders[1][s->mb_x][16+7];
  2032. h->left_border[34+18 ]= h->top_borders[0][s->mb_x][24+7];
  2033. h->left_border[34+18+1]= h->top_borders[1][s->mb_x][24+7];
  2034. for(i=2; i<18; i++){
  2035. h->left_border[i+34 ]= src_cb[7+i*uvlinesize];
  2036. h->left_border[i+34+18]= src_cr[7+i*uvlinesize];
  2037. }
  2038. *(uint64_t*)(h->top_borders[0][s->mb_x]+16)= *(uint64_t*)(src_cb+16*uvlinesize);
  2039. *(uint64_t*)(h->top_borders[0][s->mb_x]+24)= *(uint64_t*)(src_cr+16*uvlinesize);
  2040. *(uint64_t*)(h->top_borders[1][s->mb_x]+16)= *(uint64_t*)(src_cb+17*uvlinesize);
  2041. *(uint64_t*)(h->top_borders[1][s->mb_x]+24)= *(uint64_t*)(src_cr+17*uvlinesize);
  2042. }
  2043. }
  2044. 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){
  2045. MpegEncContext * const s = &h->s;
  2046. int temp8, i;
  2047. uint64_t temp64;
  2048. int deblock_left = (s->mb_x > 0);
  2049. int deblock_top = (s->mb_y > 1);
  2050. 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);
  2051. src_y -= 2 * linesize + 1;
  2052. src_cb -= 2 * uvlinesize + 1;
  2053. src_cr -= 2 * uvlinesize + 1;
  2054. #define XCHG(a,b,t,xchg)\
  2055. t= a;\
  2056. if(xchg)\
  2057. a= b;\
  2058. b= t;
  2059. if(deblock_left){
  2060. for(i = (!deblock_top)<<1; i<34; i++){
  2061. XCHG(h->left_border[i ], src_y [i* linesize], temp8, xchg);
  2062. }
  2063. }
  2064. if(deblock_top){
  2065. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+0), *(uint64_t*)(src_y +1), temp64, xchg);
  2066. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+8), *(uint64_t*)(src_y +9), temp64, 1);
  2067. XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+0), *(uint64_t*)(src_y +1 +linesize), temp64, xchg);
  2068. XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+8), *(uint64_t*)(src_y +9 +linesize), temp64, 1);
  2069. if(s->mb_x+1 < s->mb_width){
  2070. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x+1]), *(uint64_t*)(src_y +17), temp64, 1);
  2071. XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x+1]), *(uint64_t*)(src_y +17 +linesize), temp64, 1);
  2072. }
  2073. }
  2074. if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  2075. if(deblock_left){
  2076. for(i = (!deblock_top) << 1; i<18; i++){
  2077. XCHG(h->left_border[i+34 ], src_cb[i*uvlinesize], temp8, xchg);
  2078. XCHG(h->left_border[i+34+18], src_cr[i*uvlinesize], temp8, xchg);
  2079. }
  2080. }
  2081. if(deblock_top){
  2082. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+16), *(uint64_t*)(src_cb+1), temp64, 1);
  2083. XCHG(*(uint64_t*)(h->top_borders[0][s->mb_x]+24), *(uint64_t*)(src_cr+1), temp64, 1);
  2084. XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+16), *(uint64_t*)(src_cb+1 +uvlinesize), temp64, 1);
  2085. XCHG(*(uint64_t*)(h->top_borders[1][s->mb_x]+24), *(uint64_t*)(src_cr+1 +uvlinesize), temp64, 1);
  2086. }
  2087. }
  2088. }
  2089. static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple){
  2090. MpegEncContext * const s = &h->s;
  2091. const int mb_x= s->mb_x;
  2092. const int mb_y= s->mb_y;
  2093. const int mb_xy= mb_x + mb_y*s->mb_stride;
  2094. const int mb_type= s->current_picture.mb_type[mb_xy];
  2095. uint8_t *dest_y, *dest_cb, *dest_cr;
  2096. int linesize, uvlinesize /*dct_offset*/;
  2097. int i;
  2098. int *block_offset = &h->block_offset[0];
  2099. const unsigned int bottom = mb_y & 1;
  2100. const int transform_bypass = (s->qscale == 0 && h->sps.transform_bypass), is_h264 = (simple || s->codec_id == CODEC_ID_H264);
  2101. void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
  2102. void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
  2103. dest_y = s->current_picture.data[0] + (mb_y * 16* s->linesize ) + mb_x * 16;
  2104. dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
  2105. dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
  2106. s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + 64, s->linesize, 4);
  2107. s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + 64, dest_cr - dest_cb, 2);
  2108. if (!simple && MB_FIELD) {
  2109. linesize = h->mb_linesize = s->linesize * 2;
  2110. uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
  2111. block_offset = &h->block_offset[24];
  2112. if(mb_y&1){ //FIXME move out of this func?
  2113. dest_y -= s->linesize*15;
  2114. dest_cb-= s->uvlinesize*7;
  2115. dest_cr-= s->uvlinesize*7;
  2116. }
  2117. if(FRAME_MBAFF) {
  2118. int list;
  2119. for(list=0; list<h->list_count; list++){
  2120. if(!USES_LIST(mb_type, list))
  2121. continue;
  2122. if(IS_16X16(mb_type)){
  2123. int8_t *ref = &h->ref_cache[list][scan8[0]];
  2124. fill_rectangle(ref, 4, 4, 8, 16+*ref^(s->mb_y&1), 1);
  2125. }else{
  2126. for(i=0; i<16; i+=4){
  2127. //FIXME can refs be smaller than 8x8 when !direct_8x8_inference ?
  2128. int ref = h->ref_cache[list][scan8[i]];
  2129. if(ref >= 0)
  2130. fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, 16+ref^(s->mb_y&1), 1);
  2131. }
  2132. }
  2133. }
  2134. }
  2135. } else {
  2136. linesize = h->mb_linesize = s->linesize;
  2137. uvlinesize = h->mb_uvlinesize = s->uvlinesize;
  2138. // dct_offset = s->linesize * 16;
  2139. }
  2140. if(transform_bypass){
  2141. idct_dc_add =
  2142. idct_add = IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
  2143. }else if(IS_8x8DCT(mb_type)){
  2144. idct_dc_add = s->dsp.h264_idct8_dc_add;
  2145. idct_add = s->dsp.h264_idct8_add;
  2146. }else{
  2147. idct_dc_add = s->dsp.h264_idct_dc_add;
  2148. idct_add = s->dsp.h264_idct_add;
  2149. }
  2150. if(!simple && FRAME_MBAFF && h->deblocking_filter && IS_INTRA(mb_type)
  2151. && (!bottom || !IS_INTRA(s->current_picture.mb_type[mb_xy-s->mb_stride]))){
  2152. int mbt_y = mb_y&~1;
  2153. uint8_t *top_y = s->current_picture.data[0] + (mbt_y * 16* s->linesize ) + mb_x * 16;
  2154. uint8_t *top_cb = s->current_picture.data[1] + (mbt_y * 8 * s->uvlinesize) + mb_x * 8;
  2155. uint8_t *top_cr = s->current_picture.data[2] + (mbt_y * 8 * s->uvlinesize) + mb_x * 8;
  2156. xchg_pair_border(h, top_y, top_cb, top_cr, s->linesize, s->uvlinesize, 1);
  2157. }
  2158. if (!simple && IS_INTRA_PCM(mb_type)) {
  2159. unsigned int x, y;
  2160. // The pixels are stored in h->mb array in the same order as levels,
  2161. // copy them in output in the correct order.
  2162. for(i=0; i<16; i++) {
  2163. for (y=0; y<4; y++) {
  2164. for (x=0; x<4; x++) {
  2165. *(dest_y + block_offset[i] + y*linesize + x) = h->mb[i*16+y*4+x];
  2166. }
  2167. }
  2168. }
  2169. for(i=16; i<16+4; i++) {
  2170. for (y=0; y<4; y++) {
  2171. for (x=0; x<4; x++) {
  2172. *(dest_cb + block_offset[i] + y*uvlinesize + x) = h->mb[i*16+y*4+x];
  2173. }
  2174. }
  2175. }
  2176. for(i=20; i<20+4; i++) {
  2177. for (y=0; y<4; y++) {
  2178. for (x=0; x<4; x++) {
  2179. *(dest_cr + block_offset[i] + y*uvlinesize + x) = h->mb[i*16+y*4+x];
  2180. }
  2181. }
  2182. }
  2183. } else {
  2184. if(IS_INTRA(mb_type)){
  2185. if(h->deblocking_filter && (simple || !FRAME_MBAFF))
  2186. xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, simple);
  2187. if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  2188. h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
  2189. h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
  2190. }
  2191. if(IS_INTRA4x4(mb_type)){
  2192. if(simple || !s->encoding){
  2193. if(IS_8x8DCT(mb_type)){
  2194. for(i=0; i<16; i+=4){
  2195. uint8_t * const ptr= dest_y + block_offset[i];
  2196. const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
  2197. const int nnz = h->non_zero_count_cache[ scan8[i] ];
  2198. h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
  2199. (h->topright_samples_available<<i)&0x4000, linesize);
  2200. if(nnz){
  2201. if(nnz == 1 && h->mb[i*16])
  2202. idct_dc_add(ptr, h->mb + i*16, linesize);
  2203. else
  2204. idct_add(ptr, h->mb + i*16, linesize);
  2205. }
  2206. }
  2207. }else
  2208. for(i=0; i<16; i++){
  2209. uint8_t * const ptr= dest_y + block_offset[i];
  2210. uint8_t *topright;
  2211. const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
  2212. int nnz, tr;
  2213. if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
  2214. const int topright_avail= (h->topright_samples_available<<i)&0x8000;
  2215. assert(mb_y || linesize <= block_offset[i]);
  2216. if(!topright_avail){
  2217. tr= ptr[3 - linesize]*0x01010101;
  2218. topright= (uint8_t*) &tr;
  2219. }else
  2220. topright= ptr + 4 - linesize;
  2221. }else
  2222. topright= NULL;
  2223. h->hpc.pred4x4[ dir ](ptr, topright, linesize);
  2224. nnz = h->non_zero_count_cache[ scan8[i] ];
  2225. if(nnz){
  2226. if(is_h264){
  2227. if(nnz == 1 && h->mb[i*16])
  2228. idct_dc_add(ptr, h->mb + i*16, linesize);
  2229. else
  2230. idct_add(ptr, h->mb + i*16, linesize);
  2231. }else
  2232. svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
  2233. }
  2234. }
  2235. }
  2236. }else{
  2237. h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
  2238. if(is_h264){
  2239. if(!transform_bypass)
  2240. h264_luma_dc_dequant_idct_c(h->mb, s->qscale, h->dequant4_coeff[0][s->qscale][0]);
  2241. }else
  2242. svq3_luma_dc_dequant_idct_c(h->mb, s->qscale);
  2243. }
  2244. if(h->deblocking_filter && (simple || !FRAME_MBAFF))
  2245. xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple);
  2246. }else if(is_h264){
  2247. hl_motion(h, dest_y, dest_cb, dest_cr,
  2248. s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
  2249. s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
  2250. s->dsp.weight_h264_pixels_tab, s->dsp.biweight_h264_pixels_tab);
  2251. }
  2252. if(!IS_INTRA4x4(mb_type)){
  2253. if(is_h264){
  2254. if(IS_INTRA16x16(mb_type)){
  2255. for(i=0; i<16; i++){
  2256. if(h->non_zero_count_cache[ scan8[i] ])
  2257. idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
  2258. else if(h->mb[i*16])
  2259. idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);
  2260. }
  2261. }else{
  2262. const int di = IS_8x8DCT(mb_type) ? 4 : 1;
  2263. for(i=0; i<16; i+=di){
  2264. int nnz = h->non_zero_count_cache[ scan8[i] ];
  2265. if(nnz){
  2266. if(nnz==1 && h->mb[i*16])
  2267. idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);
  2268. else
  2269. idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);
  2270. }
  2271. }
  2272. }
  2273. }else{
  2274. for(i=0; i<16; i++){
  2275. if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
  2276. uint8_t * const ptr= dest_y + block_offset[i];
  2277. svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
  2278. }
  2279. }
  2280. }
  2281. }
  2282. if(simple || !ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  2283. uint8_t *dest[2] = {dest_cb, dest_cr};
  2284. if(transform_bypass){
  2285. idct_add = idct_dc_add = s->dsp.add_pixels4;
  2286. }else{
  2287. idct_add = s->dsp.h264_idct_add;
  2288. idct_dc_add = s->dsp.h264_idct_dc_add;
  2289. 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]);
  2290. 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]);
  2291. }
  2292. if(is_h264){
  2293. for(i=16; i<16+8; i++){
  2294. if(h->non_zero_count_cache[ scan8[i] ])
  2295. idct_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
  2296. else if(h->mb[i*16])
  2297. idct_dc_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);
  2298. }
  2299. }else{
  2300. for(i=16; i<16+8; i++){
  2301. if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
  2302. uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];
  2303. svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, chroma_qp[s->qscale + 12] - 12, 2);
  2304. }
  2305. }
  2306. }
  2307. }
  2308. }
  2309. if(h->deblocking_filter) {
  2310. if (!simple && FRAME_MBAFF) {
  2311. //FIXME try deblocking one mb at a time?
  2312. // the reduction in load/storing mvs and such might outweigh the extra backup/xchg_border
  2313. const int mb_y = s->mb_y - 1;
  2314. uint8_t *pair_dest_y, *pair_dest_cb, *pair_dest_cr;
  2315. const int mb_xy= mb_x + mb_y*s->mb_stride;
  2316. const int mb_type_top = s->current_picture.mb_type[mb_xy];
  2317. const int mb_type_bottom= s->current_picture.mb_type[mb_xy+s->mb_stride];
  2318. if (!bottom) return;
  2319. pair_dest_y = s->current_picture.data[0] + (mb_y * 16* s->linesize ) + mb_x * 16;
  2320. pair_dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
  2321. pair_dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
  2322. if(IS_INTRA(mb_type_top | mb_type_bottom))
  2323. xchg_pair_border(h, pair_dest_y, pair_dest_cb, pair_dest_cr, s->linesize, s->uvlinesize, 0);
  2324. backup_pair_border(h, pair_dest_y, pair_dest_cb, pair_dest_cr, s->linesize, s->uvlinesize);
  2325. // deblock a pair
  2326. // top
  2327. s->mb_y--;
  2328. 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);
  2329. fill_caches(h, mb_type_top, 1); //FIXME don't fill stuff which isn't used by filter_mb
  2330. h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
  2331. h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
  2332. filter_mb(h, mb_x, mb_y, pair_dest_y, pair_dest_cb, pair_dest_cr, linesize, uvlinesize);
  2333. // bottom
  2334. s->mb_y++;
  2335. tprintf(h->s.avctx, "call mbaff filter_mb\n");
  2336. fill_caches(h, mb_type_bottom, 1); //FIXME don't fill stuff which isn't used by filter_mb
  2337. h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy+s->mb_stride]);
  2338. h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy+s->mb_stride]);
  2339. filter_mb(h, mb_x, mb_y+1, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  2340. } else {
  2341. tprintf(h->s.avctx, "call filter_mb\n");
  2342. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, simple);
  2343. fill_caches(h, mb_type, 1); //FIXME don't fill stuff which isn't used by filter_mb
  2344. filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  2345. }
  2346. }
  2347. }
  2348. /**
  2349. * Process a macroblock; this case avoids checks for expensive uncommon cases.
  2350. */
  2351. static void hl_decode_mb_simple(H264Context *h){
  2352. hl_decode_mb_internal(h, 1);
  2353. }
  2354. /**
  2355. * Process a macroblock; this handles edge cases, such as interlacing.
  2356. */
  2357. static void av_noinline hl_decode_mb_complex(H264Context *h){
  2358. hl_decode_mb_internal(h, 0);
  2359. }
  2360. static void hl_decode_mb(H264Context *h){
  2361. MpegEncContext * const s = &h->s;
  2362. const int mb_x= s->mb_x;
  2363. const int mb_y= s->mb_y;
  2364. const int mb_xy= mb_x + mb_y*s->mb_stride;
  2365. const int mb_type= s->current_picture.mb_type[mb_xy];
  2366. 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;
  2367. if(!s->decode)
  2368. return;
  2369. if (is_complex)
  2370. hl_decode_mb_complex(h);
  2371. else hl_decode_mb_simple(h);
  2372. }
  2373. static void pic_as_field(Picture *pic, const int parity){
  2374. int i;
  2375. for (i = 0; i < 4; ++i) {
  2376. if (parity == PICT_BOTTOM_FIELD)
  2377. pic->data[i] += pic->linesize[i];
  2378. pic->reference = parity;
  2379. pic->linesize[i] *= 2;
  2380. }
  2381. }
  2382. static int split_field_copy(Picture *dest, Picture *src,
  2383. int parity, int id_add){
  2384. int match = !!(src->reference & parity);
  2385. if (match) {
  2386. *dest = *src;
  2387. pic_as_field(dest, parity);
  2388. dest->pic_id *= 2;
  2389. dest->pic_id += id_add;
  2390. }
  2391. return match;
  2392. }
  2393. /**
  2394. * Split one reference list into field parts, interleaving by parity
  2395. * as per H.264 spec section 8.2.4.2.5. Output fields have their data pointers
  2396. * set to look at the actual start of data for that field.
  2397. *
  2398. * @param dest output list
  2399. * @param dest_len maximum number of fields to put in dest
  2400. * @param src the source reference list containing fields and/or field pairs
  2401. * (aka short_ref/long_ref, or
  2402. * refFrameListXShortTerm/refFrameListLongTerm in spec-speak)
  2403. * @param src_len number of Picture's in source (pairs and unmatched fields)
  2404. * @param parity the parity of the picture being decoded/needing
  2405. * these ref pics (PICT_{TOP,BOTTOM}_FIELD)
  2406. * @return number of fields placed in dest
  2407. */
  2408. static int split_field_half_ref_list(Picture *dest, int dest_len,
  2409. Picture *src, int src_len, int parity){
  2410. int same_parity = 1;
  2411. int same_i = 0;
  2412. int opp_i = 0;
  2413. int out_i;
  2414. int field_output;
  2415. for (out_i = 0; out_i < dest_len; out_i += field_output) {
  2416. if (same_parity && same_i < src_len) {
  2417. field_output = split_field_copy(dest + out_i, src + same_i,
  2418. parity, 1);
  2419. same_parity = !field_output;
  2420. same_i++;
  2421. } else if (opp_i < src_len) {
  2422. field_output = split_field_copy(dest + out_i, src + opp_i,
  2423. PICT_FRAME - parity, 0);
  2424. same_parity = field_output;
  2425. opp_i++;
  2426. } else {
  2427. break;
  2428. }
  2429. }
  2430. return out_i;
  2431. }
  2432. /**
  2433. * Split the reference frame list into a reference field list.
  2434. * This implements H.264 spec 8.2.4.2.5 for a combined input list.
  2435. * The input list contains both reference field pairs and
  2436. * unmatched reference fields; it is ordered as spec describes
  2437. * RefPicListX for frames in 8.2.4.2.1 and 8.2.4.2.3, except that
  2438. * unmatched field pairs are also present. Conceptually this is equivalent
  2439. * to concatenation of refFrameListXShortTerm with refFrameListLongTerm.
  2440. *
  2441. * @param dest output reference list where ordered fields are to be placed
  2442. * @param dest_len max number of fields to place at dest
  2443. * @param src source reference list, as described above
  2444. * @param src_len number of pictures (pairs and unmatched fields) in src
  2445. * @param parity parity of field being currently decoded
  2446. * (one of PICT_{TOP,BOTTOM}_FIELD)
  2447. * @param long_i index into src array that holds first long reference picture,
  2448. * or src_len if no long refs present.
  2449. */
  2450. static int split_field_ref_list(Picture *dest, int dest_len,
  2451. Picture *src, int src_len,
  2452. int parity, int long_i){
  2453. int i = split_field_half_ref_list(dest, dest_len, src, long_i, parity);
  2454. dest += i;
  2455. dest_len -= i;
  2456. i += split_field_half_ref_list(dest, dest_len, src + long_i,
  2457. src_len - long_i, parity);
  2458. return i;
  2459. }
  2460. /**
  2461. * fills the default_ref_list.
  2462. */
  2463. static int fill_default_ref_list(H264Context *h){
  2464. MpegEncContext * const s = &h->s;
  2465. int i;
  2466. int smallest_poc_greater_than_current = -1;
  2467. int structure_sel;
  2468. Picture sorted_short_ref[32];
  2469. Picture field_entry_list[2][32];
  2470. Picture *frame_list[2];
  2471. if (FIELD_PICTURE) {
  2472. structure_sel = PICT_FRAME;
  2473. frame_list[0] = field_entry_list[0];
  2474. frame_list[1] = field_entry_list[1];
  2475. } else {
  2476. structure_sel = 0;
  2477. frame_list[0] = h->default_ref_list[0];
  2478. frame_list[1] = h->default_ref_list[1];
  2479. }
  2480. if(h->slice_type==B_TYPE){
  2481. int list;
  2482. int len[2];
  2483. int short_len[2];
  2484. int out_i;
  2485. int limit= INT_MIN;
  2486. /* sort frame according to poc in B slice */
  2487. for(out_i=0; out_i<h->short_ref_count; out_i++){
  2488. int best_i=INT_MIN;
  2489. int best_poc=INT_MAX;
  2490. for(i=0; i<h->short_ref_count; i++){
  2491. const int poc= h->short_ref[i]->poc;
  2492. if(poc > limit && poc < best_poc){
  2493. best_poc= poc;
  2494. best_i= i;
  2495. }
  2496. }
  2497. assert(best_i != INT_MIN);
  2498. limit= best_poc;
  2499. sorted_short_ref[out_i]= *h->short_ref[best_i];
  2500. 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);
  2501. if (-1 == smallest_poc_greater_than_current) {
  2502. if (h->short_ref[best_i]->poc >= s->current_picture_ptr->poc) {
  2503. smallest_poc_greater_than_current = out_i;
  2504. }
  2505. }
  2506. }
  2507. tprintf(h->s.avctx, "current poc: %d, smallest_poc_greater_than_current: %d\n", s->current_picture_ptr->poc, smallest_poc_greater_than_current);
  2508. // find the largest poc
  2509. for(list=0; list<2; list++){
  2510. int index = 0;
  2511. int j= -99;
  2512. int step= list ? -1 : 1;
  2513. for(i=0; i<h->short_ref_count && index < h->ref_count[list]; i++, j+=step) {
  2514. int sel;
  2515. while(j<0 || j>= h->short_ref_count){
  2516. if(j != -99 && step == (list ? -1 : 1))
  2517. return -1;
  2518. step = -step;
  2519. j= smallest_poc_greater_than_current + (step>>1);
  2520. }
  2521. sel = sorted_short_ref[j].reference | structure_sel;
  2522. if(sel != PICT_FRAME) continue;
  2523. frame_list[list][index ]= sorted_short_ref[j];
  2524. frame_list[list][index++].pic_id= sorted_short_ref[j].frame_num;
  2525. }
  2526. short_len[list] = index;
  2527. for(i = 0; i < 16 && index < h->ref_count[ list ]; i++){
  2528. int sel;
  2529. if(h->long_ref[i] == NULL) continue;
  2530. sel = h->long_ref[i]->reference | structure_sel;
  2531. if(sel != PICT_FRAME) continue;
  2532. frame_list[ list ][index ]= *h->long_ref[i];
  2533. frame_list[ list ][index++].pic_id= i;;
  2534. }
  2535. len[list] = index;
  2536. if(list && (smallest_poc_greater_than_current<=0 || smallest_poc_greater_than_current>=h->short_ref_count) && (1 < index)){
  2537. // swap the two first elements of L1 when
  2538. // L0 and L1 are identical
  2539. Picture temp= frame_list[1][0];
  2540. frame_list[1][0] = frame_list[1][1];
  2541. frame_list[1][1] = temp;
  2542. }
  2543. }
  2544. for(list=0; list<2; list++){
  2545. if (FIELD_PICTURE)
  2546. len[list] = split_field_ref_list(h->default_ref_list[list],
  2547. h->ref_count[list],
  2548. frame_list[list],
  2549. len[list],
  2550. s->picture_structure,
  2551. short_len[list]);
  2552. if(len[list] < h->ref_count[ list ])
  2553. memset(&h->default_ref_list[list][len[list]], 0, sizeof(Picture)*(h->ref_count[ list ] - len[list]));
  2554. }
  2555. }else{
  2556. int index=0;
  2557. int short_len;
  2558. for(i=0; i<h->short_ref_count; i++){
  2559. int sel;
  2560. sel = h->short_ref[i]->reference | structure_sel;
  2561. if(sel != PICT_FRAME) continue;
  2562. frame_list[0][index ]= *h->short_ref[i];
  2563. frame_list[0][index++].pic_id= h->short_ref[i]->frame_num;
  2564. }
  2565. short_len = index;
  2566. for(i = 0; i < 16; i++){
  2567. int sel;
  2568. if(h->long_ref[i] == NULL) continue;
  2569. sel = h->long_ref[i]->reference | structure_sel;
  2570. if(sel != PICT_FRAME) continue;
  2571. frame_list[0][index ]= *h->long_ref[i];
  2572. frame_list[0][index++].pic_id= i;;
  2573. }
  2574. if (FIELD_PICTURE)
  2575. index = split_field_ref_list(h->default_ref_list[0],
  2576. h->ref_count[0], frame_list[0],
  2577. index, s->picture_structure,
  2578. short_len);
  2579. if(index < h->ref_count[0])
  2580. memset(&h->default_ref_list[0][index], 0, sizeof(Picture)*(h->ref_count[0] - index));
  2581. }
  2582. #ifdef TRACE
  2583. for (i=0; i<h->ref_count[0]; i++) {
  2584. 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]);
  2585. }
  2586. if(h->slice_type==B_TYPE){
  2587. for (i=0; i<h->ref_count[1]; i++) {
  2588. 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]);
  2589. }
  2590. }
  2591. #endif
  2592. return 0;
  2593. }
  2594. static void print_short_term(H264Context *h);
  2595. static void print_long_term(H264Context *h);
  2596. /**
  2597. * Extract structure information about the picture described by pic_num in
  2598. * the current decoding context (frame or field). Note that pic_num is
  2599. * picture number without wrapping (so, 0<=pic_num<max_pic_num).
  2600. * @param pic_num picture number for which to extract structure information
  2601. * @param structure one of PICT_XXX describing structure of picture
  2602. * with pic_num
  2603. * @return frame number (short term) or long term index of picture
  2604. * described by pic_num
  2605. */
  2606. static int pic_num_extract(H264Context *h, int pic_num, int *structure){
  2607. MpegEncContext * const s = &h->s;
  2608. *structure = s->picture_structure;
  2609. if(FIELD_PICTURE){
  2610. if (!(pic_num & 1))
  2611. /* opposite field */
  2612. *structure ^= PICT_FRAME;
  2613. pic_num >>= 1;
  2614. }
  2615. return pic_num;
  2616. }
  2617. static int decode_ref_pic_list_reordering(H264Context *h){
  2618. MpegEncContext * const s = &h->s;
  2619. int list, index, pic_structure;
  2620. print_short_term(h);
  2621. print_long_term(h);
  2622. if(h->slice_type==I_TYPE || h->slice_type==SI_TYPE) return 0; //FIXME move before func
  2623. for(list=0; list<h->list_count; list++){
  2624. memcpy(h->ref_list[list], h->default_ref_list[list], sizeof(Picture)*h->ref_count[list]);
  2625. if(get_bits1(&s->gb)){
  2626. int pred= h->curr_pic_num;
  2627. for(index=0; ; index++){
  2628. unsigned int reordering_of_pic_nums_idc= get_ue_golomb(&s->gb);
  2629. unsigned int pic_id;
  2630. int i;
  2631. Picture *ref = NULL;
  2632. if(reordering_of_pic_nums_idc==3)
  2633. break;
  2634. if(index >= h->ref_count[list]){
  2635. av_log(h->s.avctx, AV_LOG_ERROR, "reference count overflow\n");
  2636. return -1;
  2637. }
  2638. if(reordering_of_pic_nums_idc<3){
  2639. if(reordering_of_pic_nums_idc<2){
  2640. const unsigned int abs_diff_pic_num= get_ue_golomb(&s->gb) + 1;
  2641. int frame_num;
  2642. if(abs_diff_pic_num > h->max_pic_num){
  2643. av_log(h->s.avctx, AV_LOG_ERROR, "abs_diff_pic_num overflow\n");
  2644. return -1;
  2645. }
  2646. if(reordering_of_pic_nums_idc == 0) pred-= abs_diff_pic_num;
  2647. else pred+= abs_diff_pic_num;
  2648. pred &= h->max_pic_num - 1;
  2649. frame_num = pic_num_extract(h, pred, &pic_structure);
  2650. for(i= h->short_ref_count-1; i>=0; i--){
  2651. ref = h->short_ref[i];
  2652. assert(ref->reference);
  2653. assert(!ref->long_ref);
  2654. if(ref->data[0] != NULL &&
  2655. ref->frame_num == frame_num &&
  2656. (ref->reference & pic_structure) &&
  2657. ref->long_ref == 0) // ignore non existing pictures by testing data[0] pointer
  2658. break;
  2659. }
  2660. if(i>=0)
  2661. ref->pic_id= pred;
  2662. }else{
  2663. int long_idx;
  2664. pic_id= get_ue_golomb(&s->gb); //long_term_pic_idx
  2665. long_idx= pic_num_extract(h, pic_id, &pic_structure);
  2666. if(long_idx>31){
  2667. av_log(h->s.avctx, AV_LOG_ERROR, "long_term_pic_idx overflow\n");
  2668. return -1;
  2669. }
  2670. ref = h->long_ref[long_idx];
  2671. assert(!(ref && !ref->reference));
  2672. if(ref && (ref->reference & pic_structure)){
  2673. ref->pic_id= pic_id;
  2674. assert(ref->long_ref);
  2675. i=0;
  2676. }else{
  2677. i=-1;
  2678. }
  2679. }
  2680. if (i < 0) {
  2681. av_log(h->s.avctx, AV_LOG_ERROR, "reference picture missing during reorder\n");
  2682. memset(&h->ref_list[list][index], 0, sizeof(Picture)); //FIXME
  2683. } else {
  2684. for(i=index; i+1<h->ref_count[list]; i++){
  2685. if(ref->long_ref == h->ref_list[list][i].long_ref && ref->pic_id == h->ref_list[list][i].pic_id)
  2686. break;
  2687. }
  2688. for(; i > index; i--){
  2689. h->ref_list[list][i]= h->ref_list[list][i-1];
  2690. }
  2691. h->ref_list[list][index]= *ref;
  2692. if (FIELD_PICTURE){
  2693. pic_as_field(&h->ref_list[list][index], pic_structure);
  2694. }
  2695. }
  2696. }else{
  2697. av_log(h->s.avctx, AV_LOG_ERROR, "illegal reordering_of_pic_nums_idc\n");
  2698. return -1;
  2699. }
  2700. }
  2701. }
  2702. }
  2703. for(list=0; list<h->list_count; list++){
  2704. for(index= 0; index < h->ref_count[list]; index++){
  2705. if(!h->ref_list[list][index].data[0])
  2706. h->ref_list[list][index]= s->current_picture;
  2707. }
  2708. }
  2709. if(h->slice_type==B_TYPE && !h->direct_spatial_mv_pred)
  2710. direct_dist_scale_factor(h);
  2711. direct_ref_list_init(h);
  2712. return 0;
  2713. }
  2714. static void fill_mbaff_ref_list(H264Context *h){
  2715. int list, i, j;
  2716. for(list=0; list<2; list++){ //FIXME try list_count
  2717. for(i=0; i<h->ref_count[list]; i++){
  2718. Picture *frame = &h->ref_list[list][i];
  2719. Picture *field = &h->ref_list[list][16+2*i];
  2720. field[0] = *frame;
  2721. for(j=0; j<3; j++)
  2722. field[0].linesize[j] <<= 1;
  2723. field[0].reference = PICT_TOP_FIELD;
  2724. field[1] = field[0];
  2725. for(j=0; j<3; j++)
  2726. field[1].data[j] += frame->linesize[j];
  2727. field[1].reference = PICT_BOTTOM_FIELD;
  2728. h->luma_weight[list][16+2*i] = h->luma_weight[list][16+2*i+1] = h->luma_weight[list][i];
  2729. h->luma_offset[list][16+2*i] = h->luma_offset[list][16+2*i+1] = h->luma_offset[list][i];
  2730. for(j=0; j<2; j++){
  2731. h->chroma_weight[list][16+2*i][j] = h->chroma_weight[list][16+2*i+1][j] = h->chroma_weight[list][i][j];
  2732. h->chroma_offset[list][16+2*i][j] = h->chroma_offset[list][16+2*i+1][j] = h->chroma_offset[list][i][j];
  2733. }
  2734. }
  2735. }
  2736. for(j=0; j<h->ref_count[1]; j++){
  2737. for(i=0; i<h->ref_count[0]; i++)
  2738. h->implicit_weight[j][16+2*i] = h->implicit_weight[j][16+2*i+1] = h->implicit_weight[j][i];
  2739. memcpy(h->implicit_weight[16+2*j], h->implicit_weight[j], sizeof(*h->implicit_weight));
  2740. memcpy(h->implicit_weight[16+2*j+1], h->implicit_weight[j], sizeof(*h->implicit_weight));
  2741. }
  2742. }
  2743. static int pred_weight_table(H264Context *h){
  2744. MpegEncContext * const s = &h->s;
  2745. int list, i;
  2746. int luma_def, chroma_def;
  2747. h->use_weight= 0;
  2748. h->use_weight_chroma= 0;
  2749. h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
  2750. h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
  2751. luma_def = 1<<h->luma_log2_weight_denom;
  2752. chroma_def = 1<<h->chroma_log2_weight_denom;
  2753. for(list=0; list<2; list++){
  2754. for(i=0; i<h->ref_count[list]; i++){
  2755. int luma_weight_flag, chroma_weight_flag;
  2756. luma_weight_flag= get_bits1(&s->gb);
  2757. if(luma_weight_flag){
  2758. h->luma_weight[list][i]= get_se_golomb(&s->gb);
  2759. h->luma_offset[list][i]= get_se_golomb(&s->gb);
  2760. if( h->luma_weight[list][i] != luma_def
  2761. || h->luma_offset[list][i] != 0)
  2762. h->use_weight= 1;
  2763. }else{
  2764. h->luma_weight[list][i]= luma_def;
  2765. h->luma_offset[list][i]= 0;
  2766. }
  2767. chroma_weight_flag= get_bits1(&s->gb);
  2768. if(chroma_weight_flag){
  2769. int j;
  2770. for(j=0; j<2; j++){
  2771. h->chroma_weight[list][i][j]= get_se_golomb(&s->gb);
  2772. h->chroma_offset[list][i][j]= get_se_golomb(&s->gb);
  2773. if( h->chroma_weight[list][i][j] != chroma_def
  2774. || h->chroma_offset[list][i][j] != 0)
  2775. h->use_weight_chroma= 1;
  2776. }
  2777. }else{
  2778. int j;
  2779. for(j=0; j<2; j++){
  2780. h->chroma_weight[list][i][j]= chroma_def;
  2781. h->chroma_offset[list][i][j]= 0;
  2782. }
  2783. }
  2784. }
  2785. if(h->slice_type != B_TYPE) break;
  2786. }
  2787. h->use_weight= h->use_weight || h->use_weight_chroma;
  2788. return 0;
  2789. }
  2790. static void implicit_weight_table(H264Context *h){
  2791. MpegEncContext * const s = &h->s;
  2792. int ref0, ref1;
  2793. int cur_poc = s->current_picture_ptr->poc;
  2794. if( h->ref_count[0] == 1 && h->ref_count[1] == 1
  2795. && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
  2796. h->use_weight= 0;
  2797. h->use_weight_chroma= 0;
  2798. return;
  2799. }
  2800. h->use_weight= 2;
  2801. h->use_weight_chroma= 2;
  2802. h->luma_log2_weight_denom= 5;
  2803. h->chroma_log2_weight_denom= 5;
  2804. for(ref0=0; ref0 < h->ref_count[0]; ref0++){
  2805. int poc0 = h->ref_list[0][ref0].poc;
  2806. for(ref1=0; ref1 < h->ref_count[1]; ref1++){
  2807. int poc1 = h->ref_list[1][ref1].poc;
  2808. int td = av_clip(poc1 - poc0, -128, 127);
  2809. if(td){
  2810. int tb = av_clip(cur_poc - poc0, -128, 127);
  2811. int tx = (16384 + (FFABS(td) >> 1)) / td;
  2812. int dist_scale_factor = av_clip((tb*tx + 32) >> 6, -1024, 1023) >> 2;
  2813. if(dist_scale_factor < -64 || dist_scale_factor > 128)
  2814. h->implicit_weight[ref0][ref1] = 32;
  2815. else
  2816. h->implicit_weight[ref0][ref1] = 64 - dist_scale_factor;
  2817. }else
  2818. h->implicit_weight[ref0][ref1] = 32;
  2819. }
  2820. }
  2821. }
  2822. /**
  2823. * Mark a picture as no longer needed for reference. The refmask
  2824. * argument allows unreferencing of individual fields or the whole frame.
  2825. * If the picture becomes entirely unreferenced, but is being held for
  2826. * display purposes, it is marked as such.
  2827. * @param refmask mask of fields to unreference; the mask is bitwise
  2828. * anded with the reference marking of pic
  2829. * @return non-zero if pic becomes entirely unreferenced (except possibly
  2830. * for display purposes) zero if one of the fields remains in
  2831. * reference
  2832. */
  2833. static inline int unreference_pic(H264Context *h, Picture *pic, int refmask){
  2834. int i;
  2835. if (pic->reference &= refmask) {
  2836. return 0;
  2837. } else {
  2838. if(pic == h->delayed_output_pic)
  2839. pic->reference=DELAYED_PIC_REF;
  2840. else{
  2841. for(i = 0; h->delayed_pic[i]; i++)
  2842. if(pic == h->delayed_pic[i]){
  2843. pic->reference=DELAYED_PIC_REF;
  2844. break;
  2845. }
  2846. }
  2847. return 1;
  2848. }
  2849. }
  2850. /**
  2851. * instantaneous decoder refresh.
  2852. */
  2853. static void idr(H264Context *h){
  2854. int i;
  2855. for(i=0; i<16; i++){
  2856. if (h->long_ref[i] != NULL) {
  2857. unreference_pic(h, h->long_ref[i], 0);
  2858. h->long_ref[i]= NULL;
  2859. }
  2860. }
  2861. h->long_ref_count=0;
  2862. for(i=0; i<h->short_ref_count; i++){
  2863. unreference_pic(h, h->short_ref[i], 0);
  2864. h->short_ref[i]= NULL;
  2865. }
  2866. h->short_ref_count=0;
  2867. }
  2868. /* forget old pics after a seek */
  2869. static void flush_dpb(AVCodecContext *avctx){
  2870. H264Context *h= avctx->priv_data;
  2871. int i;
  2872. for(i=0; i<16; i++) {
  2873. if(h->delayed_pic[i])
  2874. h->delayed_pic[i]->reference= 0;
  2875. h->delayed_pic[i]= NULL;
  2876. }
  2877. if(h->delayed_output_pic)
  2878. h->delayed_output_pic->reference= 0;
  2879. h->delayed_output_pic= NULL;
  2880. idr(h);
  2881. if(h->s.current_picture_ptr)
  2882. h->s.current_picture_ptr->reference= 0;
  2883. h->s.first_field= 0;
  2884. ff_mpeg_flush(avctx);
  2885. }
  2886. /**
  2887. * Find a Picture in the short term reference list by frame number.
  2888. * @param frame_num frame number to search for
  2889. * @param idx the index into h->short_ref where returned picture is found
  2890. * undefined if no picture found.
  2891. * @return pointer to the found picture, or NULL if no pic with the provided
  2892. * frame number is found
  2893. */
  2894. static Picture * find_short(H264Context *h, int frame_num, int *idx){
  2895. MpegEncContext * const s = &h->s;
  2896. int i;
  2897. for(i=0; i<h->short_ref_count; i++){
  2898. Picture *pic= h->short_ref[i];
  2899. if(s->avctx->debug&FF_DEBUG_MMCO)
  2900. av_log(h->s.avctx, AV_LOG_DEBUG, "%d %d %p\n", i, pic->frame_num, pic);
  2901. if(pic->frame_num == frame_num) {
  2902. *idx = i;
  2903. return pic;
  2904. }
  2905. }
  2906. return NULL;
  2907. }
  2908. /**
  2909. * Remove a picture from the short term reference list by its index in
  2910. * that list. This does no checking on the provided index; it is assumed
  2911. * to be valid. Other list entries are shifted down.
  2912. * @param i index into h->short_ref of picture to remove.
  2913. */
  2914. static void remove_short_at_index(H264Context *h, int i){
  2915. assert(i > 0 && i < h->short_ref_count);
  2916. h->short_ref[i]= NULL;
  2917. if (--h->short_ref_count)
  2918. memmove(&h->short_ref[i], &h->short_ref[i+1], (h->short_ref_count - i)*sizeof(Picture*));
  2919. }
  2920. /**
  2921. *
  2922. * @return the removed picture or NULL if an error occurs
  2923. */
  2924. static Picture * remove_short(H264Context *h, int frame_num){
  2925. MpegEncContext * const s = &h->s;
  2926. Picture *pic;
  2927. int i;
  2928. if(s->avctx->debug&FF_DEBUG_MMCO)
  2929. av_log(h->s.avctx, AV_LOG_DEBUG, "remove short %d count %d\n", frame_num, h->short_ref_count);
  2930. pic = find_short(h, frame_num, &i);
  2931. if (pic)
  2932. remove_short_at_index(h, i);
  2933. return pic;
  2934. }
  2935. /**
  2936. * Remove a picture from the long term reference list by its index in
  2937. * that list. This does no checking on the provided index; it is assumed
  2938. * to be valid. The removed entry is set to NULL. Other entries are unaffected.
  2939. * @param i index into h->long_ref of picture to remove.
  2940. */
  2941. static void remove_long_at_index(H264Context *h, int i){
  2942. h->long_ref[i]= NULL;
  2943. h->long_ref_count--;
  2944. }
  2945. /**
  2946. *
  2947. * @return the removed picture or NULL if an error occurs
  2948. */
  2949. static Picture * remove_long(H264Context *h, int i){
  2950. Picture *pic;
  2951. pic= h->long_ref[i];
  2952. if (pic)
  2953. remove_long_at_index(h, i);
  2954. return pic;
  2955. }
  2956. /**
  2957. * print short term list
  2958. */
  2959. static void print_short_term(H264Context *h) {
  2960. uint32_t i;
  2961. if(h->s.avctx->debug&FF_DEBUG_MMCO) {
  2962. av_log(h->s.avctx, AV_LOG_DEBUG, "short term list:\n");
  2963. for(i=0; i<h->short_ref_count; i++){
  2964. Picture *pic= h->short_ref[i];
  2965. av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
  2966. }
  2967. }
  2968. }
  2969. /**
  2970. * print long term list
  2971. */
  2972. static void print_long_term(H264Context *h) {
  2973. uint32_t i;
  2974. if(h->s.avctx->debug&FF_DEBUG_MMCO) {
  2975. av_log(h->s.avctx, AV_LOG_DEBUG, "long term list:\n");
  2976. for(i = 0; i < 16; i++){
  2977. Picture *pic= h->long_ref[i];
  2978. if (pic) {
  2979. av_log(h->s.avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n", i, pic->frame_num, pic->poc, pic->data[0]);
  2980. }
  2981. }
  2982. }
  2983. }
  2984. /**
  2985. * Executes the reference picture marking (memory management control operations).
  2986. */
  2987. static int execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count){
  2988. MpegEncContext * const s = &h->s;
  2989. int i, j;
  2990. int current_ref_assigned=0;
  2991. Picture *pic;
  2992. if((s->avctx->debug&FF_DEBUG_MMCO) && mmco_count==0)
  2993. av_log(h->s.avctx, AV_LOG_DEBUG, "no mmco here\n");
  2994. for(i=0; i<mmco_count; i++){
  2995. int structure, frame_num, unref_pic;
  2996. if(s->avctx->debug&FF_DEBUG_MMCO)
  2997. 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);
  2998. switch(mmco[i].opcode){
  2999. case MMCO_SHORT2UNUSED:
  3000. if(s->avctx->debug&FF_DEBUG_MMCO)
  3001. 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);
  3002. frame_num = pic_num_extract(h, mmco[i].short_pic_num, &structure);
  3003. pic = find_short(h, frame_num, &j);
  3004. if (pic) {
  3005. if (unreference_pic(h, pic, structure ^ PICT_FRAME))
  3006. remove_short_at_index(h, j);
  3007. } else if(s->avctx->debug&FF_DEBUG_MMCO)
  3008. av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref short failure\n");
  3009. break;
  3010. case MMCO_SHORT2LONG:
  3011. if (FIELD_PICTURE && mmco[i].long_arg < h->long_ref_count &&
  3012. h->long_ref[mmco[i].long_arg]->frame_num ==
  3013. mmco[i].short_pic_num / 2) {
  3014. /* do nothing, we've already moved this field pair. */
  3015. } else {
  3016. int frame_num = mmco[i].short_pic_num >> FIELD_PICTURE;
  3017. pic= remove_long(h, mmco[i].long_arg);
  3018. if(pic) unreference_pic(h, pic, 0);
  3019. h->long_ref[ mmco[i].long_arg ]= remove_short(h, frame_num);
  3020. if (h->long_ref[ mmco[i].long_arg ]){
  3021. h->long_ref[ mmco[i].long_arg ]->long_ref=1;
  3022. h->long_ref_count++;
  3023. }
  3024. }
  3025. break;
  3026. case MMCO_LONG2UNUSED:
  3027. j = pic_num_extract(h, mmco[i].long_arg, &structure);
  3028. pic = h->long_ref[j];
  3029. if (pic) {
  3030. if (unreference_pic(h, pic, structure ^ PICT_FRAME))
  3031. remove_long_at_index(h, j);
  3032. } else if(s->avctx->debug&FF_DEBUG_MMCO)
  3033. av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref long failure\n");
  3034. break;
  3035. case MMCO_LONG:
  3036. unref_pic = 1;
  3037. if (FIELD_PICTURE && !s->first_field) {
  3038. if (h->long_ref[mmco[i].long_arg] == s->current_picture_ptr) {
  3039. /* Just mark second field as referenced */
  3040. unref_pic = 0;
  3041. } else if (s->current_picture_ptr->reference) {
  3042. /* First field in pair is in short term list or
  3043. * at a different long term index.
  3044. * This is not allowed; see 7.4.3, notes 2 and 3.
  3045. * Report the problem and keep the pair where it is,
  3046. * and mark this field valid.
  3047. */
  3048. av_log(h->s.avctx, AV_LOG_ERROR,
  3049. "illegal long term reference assignment for second "
  3050. "field in complementary field pair (first field is "
  3051. "short term or has non-matching long index)\n");
  3052. unref_pic = 0;
  3053. }
  3054. }
  3055. if (unref_pic) {
  3056. pic= remove_long(h, mmco[i].long_arg);
  3057. if(pic) unreference_pic(h, pic, 0);
  3058. h->long_ref[ mmco[i].long_arg ]= s->current_picture_ptr;
  3059. h->long_ref[ mmco[i].long_arg ]->long_ref=1;
  3060. h->long_ref_count++;
  3061. }
  3062. s->current_picture_ptr->reference |= s->picture_structure;
  3063. current_ref_assigned=1;
  3064. break;
  3065. case MMCO_SET_MAX_LONG:
  3066. assert(mmco[i].long_arg <= 16);
  3067. // just remove the long term which index is greater than new max
  3068. for(j = mmco[i].long_arg; j<16; j++){
  3069. pic = remove_long(h, j);
  3070. if (pic) unreference_pic(h, pic, 0);
  3071. }
  3072. break;
  3073. case MMCO_RESET:
  3074. while(h->short_ref_count){
  3075. pic= remove_short(h, h->short_ref[0]->frame_num);
  3076. if(pic) unreference_pic(h, pic, 0);
  3077. }
  3078. for(j = 0; j < 16; j++) {
  3079. pic= remove_long(h, j);
  3080. if(pic) unreference_pic(h, pic, 0);
  3081. }
  3082. break;
  3083. default: assert(0);
  3084. }
  3085. }
  3086. if (!current_ref_assigned && FIELD_PICTURE &&
  3087. !s->first_field && s->current_picture_ptr->reference) {
  3088. /* Second field of complementary field pair; the first field of
  3089. * which is already referenced. If short referenced, it
  3090. * should be first entry in short_ref. If not, it must exist
  3091. * in long_ref; trying to put it on the short list here is an
  3092. * error in the encoded bit stream (ref: 7.4.3, NOTE 2 and 3).
  3093. */
  3094. if (h->short_ref_count && h->short_ref[0] == s->current_picture_ptr) {
  3095. /* Just mark the second field valid */
  3096. s->current_picture_ptr->reference = PICT_FRAME;
  3097. } else if (s->current_picture_ptr->long_ref) {
  3098. av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term reference "
  3099. "assignment for second field "
  3100. "in complementary field pair "
  3101. "(first field is long term)\n");
  3102. } else {
  3103. /*
  3104. * First field in reference, but not in any sensible place on our
  3105. * reference lists. This shouldn't happen unless reference
  3106. * handling somewhere else is wrong.
  3107. */
  3108. assert(0);
  3109. }
  3110. current_ref_assigned = 1;
  3111. }
  3112. if(!current_ref_assigned){
  3113. pic= remove_short(h, s->current_picture_ptr->frame_num);
  3114. if(pic){
  3115. unreference_pic(h, pic, 0);
  3116. av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term buffer state detected\n");
  3117. }
  3118. if(h->short_ref_count)
  3119. memmove(&h->short_ref[1], &h->short_ref[0], h->short_ref_count*sizeof(Picture*));
  3120. h->short_ref[0]= s->current_picture_ptr;
  3121. h->short_ref[0]->long_ref=0;
  3122. h->short_ref_count++;
  3123. s->current_picture_ptr->reference |= s->picture_structure;
  3124. }
  3125. if (h->long_ref_count + h->short_ref_count > h->sps.ref_frame_count){
  3126. /* We have too many reference frames, probably due to corrupted
  3127. * stream. Need to discard one frame. Prevents overrun of the
  3128. * short_ref and long_ref buffers.
  3129. */
  3130. av_log(h->s.avctx, AV_LOG_ERROR,
  3131. "number of reference frames exceeds max (probably "
  3132. "corrupt input), discarding one\n");
  3133. if (h->long_ref_count) {
  3134. for (i = 0; i < 16; ++i)
  3135. if (h->long_ref[i])
  3136. break;
  3137. assert(i < 16);
  3138. pic = h->long_ref[i];
  3139. remove_long_at_index(h, i);
  3140. } else {
  3141. pic = h->short_ref[h->short_ref_count - 1];
  3142. remove_short_at_index(h, h->short_ref_count - 1);
  3143. }
  3144. unreference_pic(h, pic, 0);
  3145. }
  3146. print_short_term(h);
  3147. print_long_term(h);
  3148. return 0;
  3149. }
  3150. static int decode_ref_pic_marking(H264Context *h, GetBitContext *gb){
  3151. MpegEncContext * const s = &h->s;
  3152. int i;
  3153. if(h->nal_unit_type == NAL_IDR_SLICE){ //FIXME fields
  3154. s->broken_link= get_bits1(gb) -1;
  3155. h->mmco[0].long_arg= get_bits1(gb) - 1; // current_long_term_idx
  3156. if(h->mmco[0].long_arg == -1)
  3157. h->mmco_index= 0;
  3158. else{
  3159. h->mmco[0].opcode= MMCO_LONG;
  3160. h->mmco_index= 1;
  3161. }
  3162. }else{
  3163. if(get_bits1(gb)){ // adaptive_ref_pic_marking_mode_flag
  3164. for(i= 0; i<MAX_MMCO_COUNT; i++) {
  3165. MMCOOpcode opcode= get_ue_golomb(gb);
  3166. h->mmco[i].opcode= opcode;
  3167. if(opcode==MMCO_SHORT2UNUSED || opcode==MMCO_SHORT2LONG){
  3168. h->mmco[i].short_pic_num= (h->curr_pic_num - get_ue_golomb(gb) - 1) & (h->max_pic_num - 1);
  3169. /* if(h->mmco[i].short_pic_num >= h->short_ref_count || h->short_ref[ h->mmco[i].short_pic_num ] == NULL){
  3170. av_log(s->avctx, AV_LOG_ERROR, "illegal short ref in memory management control operation %d\n", mmco);
  3171. return -1;
  3172. }*/
  3173. }
  3174. if(opcode==MMCO_SHORT2LONG || opcode==MMCO_LONG2UNUSED || opcode==MMCO_LONG || opcode==MMCO_SET_MAX_LONG){
  3175. unsigned int long_arg= get_ue_golomb(gb);
  3176. if(long_arg >= 32 || (long_arg >= 16 && !(opcode == MMCO_LONG2UNUSED && FIELD_PICTURE))){
  3177. av_log(h->s.avctx, AV_LOG_ERROR, "illegal long ref in memory management control operation %d\n", opcode);
  3178. return -1;
  3179. }
  3180. h->mmco[i].long_arg= long_arg;
  3181. }
  3182. if(opcode > (unsigned)MMCO_LONG){
  3183. av_log(h->s.avctx, AV_LOG_ERROR, "illegal memory management control operation %d\n", opcode);
  3184. return -1;
  3185. }
  3186. if(opcode == MMCO_END)
  3187. break;
  3188. }
  3189. h->mmco_index= i;
  3190. }else{
  3191. assert(h->long_ref_count + h->short_ref_count <= h->sps.ref_frame_count);
  3192. if(h->short_ref_count && h->long_ref_count + h->short_ref_count == h->sps.ref_frame_count &&
  3193. !(FIELD_PICTURE && !s->first_field && s->current_picture_ptr->reference)) {
  3194. h->mmco[0].opcode= MMCO_SHORT2UNUSED;
  3195. h->mmco[0].short_pic_num= h->short_ref[ h->short_ref_count - 1 ]->frame_num;
  3196. h->mmco_index= 1;
  3197. if (FIELD_PICTURE) {
  3198. h->mmco[0].short_pic_num *= 2;
  3199. h->mmco[1].opcode= MMCO_SHORT2UNUSED;
  3200. h->mmco[1].short_pic_num= h->mmco[0].short_pic_num + 1;
  3201. h->mmco_index= 2;
  3202. }
  3203. }else
  3204. h->mmco_index= 0;
  3205. }
  3206. }
  3207. return 0;
  3208. }
  3209. static int init_poc(H264Context *h){
  3210. MpegEncContext * const s = &h->s;
  3211. const int max_frame_num= 1<<h->sps.log2_max_frame_num;
  3212. int field_poc[2];
  3213. if(h->nal_unit_type == NAL_IDR_SLICE){
  3214. h->frame_num_offset= 0;
  3215. }else{
  3216. if(h->frame_num < h->prev_frame_num)
  3217. h->frame_num_offset= h->prev_frame_num_offset + max_frame_num;
  3218. else
  3219. h->frame_num_offset= h->prev_frame_num_offset;
  3220. }
  3221. if(h->sps.poc_type==0){
  3222. const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
  3223. if(h->nal_unit_type == NAL_IDR_SLICE){
  3224. h->prev_poc_msb=
  3225. h->prev_poc_lsb= 0;
  3226. }
  3227. 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 if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
  3230. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  3231. else
  3232. h->poc_msb = h->prev_poc_msb;
  3233. //printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
  3234. field_poc[0] =
  3235. field_poc[1] = h->poc_msb + h->poc_lsb;
  3236. if(s->picture_structure == PICT_FRAME)
  3237. field_poc[1] += h->delta_poc_bottom;
  3238. }else if(h->sps.poc_type==1){
  3239. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  3240. int i;
  3241. if(h->sps.poc_cycle_length != 0)
  3242. abs_frame_num = h->frame_num_offset + h->frame_num;
  3243. else
  3244. abs_frame_num = 0;
  3245. if(h->nal_ref_idc==0 && abs_frame_num > 0)
  3246. abs_frame_num--;
  3247. expected_delta_per_poc_cycle = 0;
  3248. for(i=0; i < h->sps.poc_cycle_length; i++)
  3249. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
  3250. if(abs_frame_num > 0){
  3251. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  3252. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  3253. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  3254. for(i = 0; i <= frame_num_in_poc_cycle; i++)
  3255. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
  3256. } else
  3257. expectedpoc = 0;
  3258. if(h->nal_ref_idc == 0)
  3259. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  3260. field_poc[0] = expectedpoc + h->delta_poc[0];
  3261. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  3262. if(s->picture_structure == PICT_FRAME)
  3263. field_poc[1] += h->delta_poc[1];
  3264. }else{
  3265. int poc;
  3266. if(h->nal_unit_type == NAL_IDR_SLICE){
  3267. poc= 0;
  3268. }else{
  3269. if(h->nal_ref_idc) poc= 2*(h->frame_num_offset + h->frame_num);
  3270. else poc= 2*(h->frame_num_offset + h->frame_num) - 1;
  3271. }
  3272. field_poc[0]= poc;
  3273. field_poc[1]= poc;
  3274. }
  3275. if(s->picture_structure != PICT_BOTTOM_FIELD) {
  3276. s->current_picture_ptr->field_poc[0]= field_poc[0];
  3277. s->current_picture_ptr->poc = field_poc[0];
  3278. }
  3279. if(s->picture_structure != PICT_TOP_FIELD) {
  3280. s->current_picture_ptr->field_poc[1]= field_poc[1];
  3281. s->current_picture_ptr->poc = field_poc[1];
  3282. }
  3283. if(!FIELD_PICTURE || !s->first_field) {
  3284. Picture *cur = s->current_picture_ptr;
  3285. cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
  3286. }
  3287. return 0;
  3288. }
  3289. /**
  3290. * initialize scan tables
  3291. */
  3292. static void init_scan_tables(H264Context *h){
  3293. MpegEncContext * const s = &h->s;
  3294. int i;
  3295. if(s->dsp.h264_idct_add == ff_h264_idct_add_c){ //FIXME little ugly
  3296. memcpy(h->zigzag_scan, zigzag_scan, 16*sizeof(uint8_t));
  3297. memcpy(h-> field_scan, field_scan, 16*sizeof(uint8_t));
  3298. }else{
  3299. for(i=0; i<16; i++){
  3300. #define T(x) (x>>2) | ((x<<2) & 0xF)
  3301. h->zigzag_scan[i] = T(zigzag_scan[i]);
  3302. h-> field_scan[i] = T( field_scan[i]);
  3303. #undef T
  3304. }
  3305. }
  3306. if(s->dsp.h264_idct8_add == ff_h264_idct8_add_c){
  3307. memcpy(h->zigzag_scan8x8, zigzag_scan8x8, 64*sizeof(uint8_t));
  3308. memcpy(h->zigzag_scan8x8_cavlc, zigzag_scan8x8_cavlc, 64*sizeof(uint8_t));
  3309. memcpy(h->field_scan8x8, field_scan8x8, 64*sizeof(uint8_t));
  3310. memcpy(h->field_scan8x8_cavlc, field_scan8x8_cavlc, 64*sizeof(uint8_t));
  3311. }else{
  3312. for(i=0; i<64; i++){
  3313. #define T(x) (x>>3) | ((x&7)<<3)
  3314. h->zigzag_scan8x8[i] = T(zigzag_scan8x8[i]);
  3315. h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
  3316. h->field_scan8x8[i] = T(field_scan8x8[i]);
  3317. h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
  3318. #undef T
  3319. }
  3320. }
  3321. if(h->sps.transform_bypass){ //FIXME same ugly
  3322. h->zigzag_scan_q0 = zigzag_scan;
  3323. h->zigzag_scan8x8_q0 = zigzag_scan8x8;
  3324. h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
  3325. h->field_scan_q0 = field_scan;
  3326. h->field_scan8x8_q0 = field_scan8x8;
  3327. h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
  3328. }else{
  3329. h->zigzag_scan_q0 = h->zigzag_scan;
  3330. h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
  3331. h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
  3332. h->field_scan_q0 = h->field_scan;
  3333. h->field_scan8x8_q0 = h->field_scan8x8;
  3334. h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
  3335. }
  3336. }
  3337. /**
  3338. * Replicates H264 "master" context to thread contexts.
  3339. */
  3340. static void clone_slice(H264Context *dst, H264Context *src)
  3341. {
  3342. memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
  3343. dst->s.current_picture_ptr = src->s.current_picture_ptr;
  3344. dst->s.current_picture = src->s.current_picture;
  3345. dst->s.linesize = src->s.linesize;
  3346. dst->s.uvlinesize = src->s.uvlinesize;
  3347. dst->s.first_field = src->s.first_field;
  3348. dst->prev_poc_msb = src->prev_poc_msb;
  3349. dst->prev_poc_lsb = src->prev_poc_lsb;
  3350. dst->prev_frame_num_offset = src->prev_frame_num_offset;
  3351. dst->prev_frame_num = src->prev_frame_num;
  3352. dst->short_ref_count = src->short_ref_count;
  3353. memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
  3354. memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
  3355. memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
  3356. memcpy(dst->ref_list, src->ref_list, sizeof(dst->ref_list));
  3357. memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
  3358. memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
  3359. }
  3360. /**
  3361. * decodes a slice header.
  3362. * this will allso call MPV_common_init() and frame_start() as needed
  3363. *
  3364. * @param h h264context
  3365. * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
  3366. *
  3367. * @return 0 if okay, <0 if an error occured, 1 if decoding must not be multithreaded
  3368. */
  3369. static int decode_slice_header(H264Context *h, H264Context *h0){
  3370. MpegEncContext * const s = &h->s;
  3371. MpegEncContext * const s0 = &h0->s;
  3372. unsigned int first_mb_in_slice;
  3373. unsigned int pps_id;
  3374. int num_ref_idx_active_override_flag;
  3375. static const uint8_t slice_type_map[5]= {P_TYPE, B_TYPE, I_TYPE, SP_TYPE, SI_TYPE};
  3376. unsigned int slice_type, tmp, i;
  3377. int default_ref_list_done = 0;
  3378. int last_pic_structure;
  3379. s->dropable= h->nal_ref_idc == 0;
  3380. if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc){
  3381. s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
  3382. s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
  3383. }else{
  3384. s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
  3385. s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
  3386. }
  3387. first_mb_in_slice= get_ue_golomb(&s->gb);
  3388. if((s->flags2 & CODEC_FLAG2_CHUNKS) && first_mb_in_slice == 0){
  3389. h0->current_slice = 0;
  3390. if (!s0->first_field)
  3391. s->current_picture_ptr= NULL;
  3392. }
  3393. slice_type= get_ue_golomb(&s->gb);
  3394. if(slice_type > 9){
  3395. 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);
  3396. return -1;
  3397. }
  3398. if(slice_type > 4){
  3399. slice_type -= 5;
  3400. h->slice_type_fixed=1;
  3401. }else
  3402. h->slice_type_fixed=0;
  3403. slice_type= slice_type_map[ slice_type ];
  3404. if (slice_type == I_TYPE
  3405. || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
  3406. default_ref_list_done = 1;
  3407. }
  3408. h->slice_type= slice_type;
  3409. s->pict_type= h->slice_type; // to make a few old func happy, it's wrong though
  3410. if (s->pict_type == B_TYPE && s0->last_picture_ptr == NULL) {
  3411. av_log(h->s.avctx, AV_LOG_ERROR,
  3412. "B picture before any references, skipping\n");
  3413. return -1;
  3414. }
  3415. pps_id= get_ue_golomb(&s->gb);
  3416. if(pps_id>=MAX_PPS_COUNT){
  3417. av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
  3418. return -1;
  3419. }
  3420. if(!h0->pps_buffers[pps_id]) {
  3421. av_log(h->s.avctx, AV_LOG_ERROR, "non existing PPS referenced\n");
  3422. return -1;
  3423. }
  3424. h->pps= *h0->pps_buffers[pps_id];
  3425. if(!h0->sps_buffers[h->pps.sps_id]) {
  3426. av_log(h->s.avctx, AV_LOG_ERROR, "non existing SPS referenced\n");
  3427. return -1;
  3428. }
  3429. h->sps = *h0->sps_buffers[h->pps.sps_id];
  3430. if(h == h0 && h->dequant_coeff_pps != pps_id){
  3431. h->dequant_coeff_pps = pps_id;
  3432. init_dequant_tables(h);
  3433. }
  3434. s->mb_width= h->sps.mb_width;
  3435. s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
  3436. h->b_stride= s->mb_width*4;
  3437. h->b8_stride= s->mb_width*2;
  3438. s->width = 16*s->mb_width - 2*(h->sps.crop_left + h->sps.crop_right );
  3439. if(h->sps.frame_mbs_only_flag)
  3440. s->height= 16*s->mb_height - 2*(h->sps.crop_top + h->sps.crop_bottom);
  3441. else
  3442. s->height= 16*s->mb_height - 4*(h->sps.crop_top + h->sps.crop_bottom); //FIXME recheck
  3443. if (s->context_initialized
  3444. && ( s->width != s->avctx->width || s->height != s->avctx->height)) {
  3445. if(h != h0)
  3446. return -1; // width / height changed during parallelized decoding
  3447. free_tables(h);
  3448. MPV_common_end(s);
  3449. }
  3450. if (!s->context_initialized) {
  3451. if(h != h0)
  3452. return -1; // we cant (re-)initialize context during parallel decoding
  3453. if (MPV_common_init(s) < 0)
  3454. return -1;
  3455. s->first_field = 0;
  3456. init_scan_tables(h);
  3457. alloc_tables(h);
  3458. for(i = 1; i < s->avctx->thread_count; i++) {
  3459. H264Context *c;
  3460. c = h->thread_context[i] = av_malloc(sizeof(H264Context));
  3461. memcpy(c, h, sizeof(MpegEncContext));
  3462. memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
  3463. c->sps = h->sps;
  3464. c->pps = h->pps;
  3465. init_scan_tables(c);
  3466. clone_tables(c, h);
  3467. }
  3468. for(i = 0; i < s->avctx->thread_count; i++)
  3469. if(context_init(h->thread_context[i]) < 0)
  3470. return -1;
  3471. s->avctx->width = s->width;
  3472. s->avctx->height = s->height;
  3473. s->avctx->sample_aspect_ratio= h->sps.sar;
  3474. if(!s->avctx->sample_aspect_ratio.den)
  3475. s->avctx->sample_aspect_ratio.den = 1;
  3476. if(h->sps.timing_info_present_flag){
  3477. s->avctx->time_base= (AVRational){h->sps.num_units_in_tick * 2, h->sps.time_scale};
  3478. if(h->x264_build > 0 && h->x264_build < 44)
  3479. s->avctx->time_base.den *= 2;
  3480. av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
  3481. s->avctx->time_base.num, s->avctx->time_base.den, 1<<30);
  3482. }
  3483. }
  3484. h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);
  3485. h->mb_mbaff = 0;
  3486. h->mb_aff_frame = 0;
  3487. last_pic_structure = s0->picture_structure;
  3488. if(h->sps.frame_mbs_only_flag){
  3489. s->picture_structure= PICT_FRAME;
  3490. }else{
  3491. if(get_bits1(&s->gb)) { //field_pic_flag
  3492. s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
  3493. } else {
  3494. s->picture_structure= PICT_FRAME;
  3495. h->mb_aff_frame = h->sps.mb_aff;
  3496. }
  3497. }
  3498. if(h0->current_slice == 0){
  3499. /* See if we have a decoded first field looking for a pair... */
  3500. if (s0->first_field) {
  3501. assert(s0->current_picture_ptr);
  3502. assert(s0->current_picture_ptr->data[0]);
  3503. assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
  3504. /* figure out if we have a complementary field pair */
  3505. if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
  3506. /*
  3507. * Previous field is unmatched. Don't display it, but let it
  3508. * remain for reference if marked as such.
  3509. */
  3510. s0->current_picture_ptr = NULL;
  3511. s0->first_field = FIELD_PICTURE;
  3512. } else {
  3513. if (h->nal_ref_idc &&
  3514. s0->current_picture_ptr->reference &&
  3515. s0->current_picture_ptr->frame_num != h->frame_num) {
  3516. /*
  3517. * This and previous field were reference, but had
  3518. * different frame_nums. Consider this field first in
  3519. * pair. Throw away previous field except for reference
  3520. * purposes.
  3521. */
  3522. s0->first_field = 1;
  3523. s0->current_picture_ptr = NULL;
  3524. } else {
  3525. /* Second field in complementary pair */
  3526. s0->first_field = 0;
  3527. }
  3528. }
  3529. } else {
  3530. /* Frame or first field in a potentially complementary pair */
  3531. assert(!s0->current_picture_ptr);
  3532. s0->first_field = FIELD_PICTURE;
  3533. }
  3534. if((!FIELD_PICTURE || s0->first_field) && frame_start(h) < 0) {
  3535. s0->first_field = 0;
  3536. return -1;
  3537. }
  3538. }
  3539. if(h != h0)
  3540. clone_slice(h, h0);
  3541. s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
  3542. assert(s->mb_num == s->mb_width * s->mb_height);
  3543. if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
  3544. first_mb_in_slice >= s->mb_num){
  3545. av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  3546. return -1;
  3547. }
  3548. s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
  3549. s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
  3550. if (s->picture_structure == PICT_BOTTOM_FIELD)
  3551. s->resync_mb_y = s->mb_y = s->mb_y + 1;
  3552. assert(s->mb_y < s->mb_height);
  3553. if(s->picture_structure==PICT_FRAME){
  3554. h->curr_pic_num= h->frame_num;
  3555. h->max_pic_num= 1<< h->sps.log2_max_frame_num;
  3556. }else{
  3557. h->curr_pic_num= 2*h->frame_num + 1;
  3558. h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
  3559. }
  3560. if(h->nal_unit_type == NAL_IDR_SLICE){
  3561. get_ue_golomb(&s->gb); /* idr_pic_id */
  3562. }
  3563. if(h->sps.poc_type==0){
  3564. h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
  3565. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
  3566. h->delta_poc_bottom= get_se_golomb(&s->gb);
  3567. }
  3568. }
  3569. if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
  3570. h->delta_poc[0]= get_se_golomb(&s->gb);
  3571. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
  3572. h->delta_poc[1]= get_se_golomb(&s->gb);
  3573. }
  3574. init_poc(h);
  3575. if(h->pps.redundant_pic_cnt_present){
  3576. h->redundant_pic_count= get_ue_golomb(&s->gb);
  3577. }
  3578. //set defaults, might be overriden a few line later
  3579. h->ref_count[0]= h->pps.ref_count[0];
  3580. h->ref_count[1]= h->pps.ref_count[1];
  3581. if(h->slice_type == P_TYPE || h->slice_type == SP_TYPE || h->slice_type == B_TYPE){
  3582. if(h->slice_type == B_TYPE){
  3583. h->direct_spatial_mv_pred= get_bits1(&s->gb);
  3584. if(FIELD_OR_MBAFF_PICTURE && h->direct_spatial_mv_pred)
  3585. av_log(h->s.avctx, AV_LOG_ERROR, "Interlaced pictures + spatial direct mode is not implemented\n");
  3586. }
  3587. num_ref_idx_active_override_flag= get_bits1(&s->gb);
  3588. if(num_ref_idx_active_override_flag){
  3589. h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
  3590. if(h->slice_type==B_TYPE)
  3591. h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
  3592. if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
  3593. av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
  3594. h->ref_count[0]= h->ref_count[1]= 1;
  3595. return -1;
  3596. }
  3597. }
  3598. if(h->slice_type == B_TYPE)
  3599. h->list_count= 2;
  3600. else
  3601. h->list_count= 1;
  3602. }else
  3603. h->list_count= 0;
  3604. if(!default_ref_list_done){
  3605. fill_default_ref_list(h);
  3606. }
  3607. if(decode_ref_pic_list_reordering(h) < 0)
  3608. return -1;
  3609. if( (h->pps.weighted_pred && (h->slice_type == P_TYPE || h->slice_type == SP_TYPE ))
  3610. || (h->pps.weighted_bipred_idc==1 && h->slice_type==B_TYPE ) )
  3611. pred_weight_table(h);
  3612. else if(h->pps.weighted_bipred_idc==2 && h->slice_type==B_TYPE)
  3613. implicit_weight_table(h);
  3614. else
  3615. h->use_weight = 0;
  3616. if(h->nal_ref_idc)
  3617. decode_ref_pic_marking(h0, &s->gb);
  3618. if(FRAME_MBAFF)
  3619. fill_mbaff_ref_list(h);
  3620. if( h->slice_type != I_TYPE && h->slice_type != SI_TYPE && h->pps.cabac ){
  3621. tmp = get_ue_golomb(&s->gb);
  3622. if(tmp > 2){
  3623. av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
  3624. return -1;
  3625. }
  3626. h->cabac_init_idc= tmp;
  3627. }
  3628. h->last_qscale_diff = 0;
  3629. tmp = h->pps.init_qp + get_se_golomb(&s->gb);
  3630. if(tmp>51){
  3631. av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  3632. return -1;
  3633. }
  3634. s->qscale= tmp;
  3635. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  3636. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  3637. //FIXME qscale / qp ... stuff
  3638. if(h->slice_type == SP_TYPE){
  3639. get_bits1(&s->gb); /* sp_for_switch_flag */
  3640. }
  3641. if(h->slice_type==SP_TYPE || h->slice_type == SI_TYPE){
  3642. get_se_golomb(&s->gb); /* slice_qs_delta */
  3643. }
  3644. h->deblocking_filter = 1;
  3645. h->slice_alpha_c0_offset = 0;
  3646. h->slice_beta_offset = 0;
  3647. if( h->pps.deblocking_filter_parameters_present ) {
  3648. tmp= get_ue_golomb(&s->gb);
  3649. if(tmp > 2){
  3650. av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
  3651. return -1;
  3652. }
  3653. h->deblocking_filter= tmp;
  3654. if(h->deblocking_filter < 2)
  3655. h->deblocking_filter^= 1; // 1<->0
  3656. if( h->deblocking_filter ) {
  3657. h->slice_alpha_c0_offset = get_se_golomb(&s->gb) << 1;
  3658. h->slice_beta_offset = get_se_golomb(&s->gb) << 1;
  3659. }
  3660. }
  3661. if( s->avctx->skip_loop_filter >= AVDISCARD_ALL
  3662. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type != I_TYPE)
  3663. ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR && h->slice_type == B_TYPE)
  3664. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
  3665. h->deblocking_filter= 0;
  3666. if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
  3667. if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
  3668. /* Cheat slightly for speed:
  3669. Do not bother to deblock across slices. */
  3670. h->deblocking_filter = 2;
  3671. } else {
  3672. h0->max_contexts = 1;
  3673. if(!h0->single_decode_warning) {
  3674. av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  3675. h0->single_decode_warning = 1;
  3676. }
  3677. if(h != h0)
  3678. return 1; // deblocking switched inside frame
  3679. }
  3680. }
  3681. #if 0 //FMO
  3682. if( h->pps.num_slice_groups > 1 && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
  3683. slice_group_change_cycle= get_bits(&s->gb, ?);
  3684. #endif
  3685. h0->last_slice_type = slice_type;
  3686. h->slice_num = ++h0->current_slice;
  3687. h->emu_edge_width= (s->flags&CODEC_FLAG_EMU_EDGE) ? 0 : 16;
  3688. h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
  3689. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  3690. 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",
  3691. h->slice_num,
  3692. (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
  3693. first_mb_in_slice,
  3694. av_get_pict_type_char(h->slice_type),
  3695. pps_id, h->frame_num,
  3696. s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
  3697. h->ref_count[0], h->ref_count[1],
  3698. s->qscale,
  3699. h->deblocking_filter, h->slice_alpha_c0_offset/2, h->slice_beta_offset/2,
  3700. h->use_weight,
  3701. h->use_weight==1 && h->use_weight_chroma ? "c" : ""
  3702. );
  3703. }
  3704. return 0;
  3705. }
  3706. /**
  3707. *
  3708. */
  3709. static inline int get_level_prefix(GetBitContext *gb){
  3710. unsigned int buf;
  3711. int log;
  3712. OPEN_READER(re, gb);
  3713. UPDATE_CACHE(re, gb);
  3714. buf=GET_CACHE(re, gb);
  3715. log= 32 - av_log2(buf);
  3716. #ifdef TRACE
  3717. print_bin(buf>>(32-log), log);
  3718. 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__);
  3719. #endif
  3720. LAST_SKIP_BITS(re, gb, log);
  3721. CLOSE_READER(re, gb);
  3722. return log-1;
  3723. }
  3724. static inline int get_dct8x8_allowed(H264Context *h){
  3725. int i;
  3726. for(i=0; i<4; i++){
  3727. if(!IS_SUB_8X8(h->sub_mb_type[i])
  3728. || (!h->sps.direct_8x8_inference_flag && IS_DIRECT(h->sub_mb_type[i])))
  3729. return 0;
  3730. }
  3731. return 1;
  3732. }
  3733. /**
  3734. * decodes a residual block.
  3735. * @param n block index
  3736. * @param scantable scantable
  3737. * @param max_coeff number of coefficients in the block
  3738. * @return <0 if an error occured
  3739. */
  3740. static int decode_residual(H264Context *h, GetBitContext *gb, DCTELEM *block, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff){
  3741. MpegEncContext * const s = &h->s;
  3742. 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};
  3743. int level[16];
  3744. int zeros_left, coeff_num, coeff_token, total_coeff, i, j, trailing_ones, run_before;
  3745. //FIXME put trailing_onex into the context
  3746. if(n == CHROMA_DC_BLOCK_INDEX){
  3747. coeff_token= get_vlc2(gb, chroma_dc_coeff_token_vlc.table, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 1);
  3748. total_coeff= coeff_token>>2;
  3749. }else{
  3750. if(n == LUMA_DC_BLOCK_INDEX){
  3751. total_coeff= pred_non_zero_count(h, 0);
  3752. coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
  3753. total_coeff= coeff_token>>2;
  3754. }else{
  3755. total_coeff= pred_non_zero_count(h, n);
  3756. coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);
  3757. total_coeff= coeff_token>>2;
  3758. h->non_zero_count_cache[ scan8[n] ]= total_coeff;
  3759. }
  3760. }
  3761. //FIXME set last_non_zero?
  3762. if(total_coeff==0)
  3763. return 0;
  3764. if(total_coeff > (unsigned)max_coeff) {
  3765. av_log(h->s.avctx, AV_LOG_ERROR, "corrupted macroblock %d %d (total_coeff=%d)\n", s->mb_x, s->mb_y, total_coeff);
  3766. return -1;
  3767. }
  3768. trailing_ones= coeff_token&3;
  3769. tprintf(h->s.avctx, "trailing:%d, total:%d\n", trailing_ones, total_coeff);
  3770. assert(total_coeff<=16);
  3771. for(i=0; i<trailing_ones; i++){
  3772. level[i]= 1 - 2*get_bits1(gb);
  3773. }
  3774. if(i<total_coeff) {
  3775. int level_code, mask;
  3776. int suffix_length = total_coeff > 10 && trailing_ones < 3;
  3777. int prefix= get_level_prefix(gb);
  3778. //first coefficient has suffix_length equal to 0 or 1
  3779. if(prefix<14){ //FIXME try to build a large unified VLC table for all this
  3780. if(suffix_length)
  3781. level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length); //part
  3782. else
  3783. level_code= (prefix<<suffix_length); //part
  3784. }else if(prefix==14){
  3785. if(suffix_length)
  3786. level_code= (prefix<<suffix_length) + get_bits(gb, suffix_length); //part
  3787. else
  3788. level_code= prefix + get_bits(gb, 4); //part
  3789. }else if(prefix==15){
  3790. level_code= (prefix<<suffix_length) + get_bits(gb, 12); //part
  3791. if(suffix_length==0) level_code+=15; //FIXME doesn't make (much)sense
  3792. }else{
  3793. av_log(h->s.avctx, AV_LOG_ERROR, "prefix too large at %d %d\n", s->mb_x, s->mb_y);
  3794. return -1;
  3795. }
  3796. if(trailing_ones < 3) level_code += 2;
  3797. suffix_length = 1;
  3798. if(level_code > 5)
  3799. suffix_length++;
  3800. mask= -(level_code&1);
  3801. level[i]= (((2+level_code)>>1) ^ mask) - mask;
  3802. i++;
  3803. //remaining coefficients have suffix_length > 0
  3804. for(;i<total_coeff;i++) {
  3805. static const int suffix_limit[7] = {0,5,11,23,47,95,INT_MAX };
  3806. prefix = get_level_prefix(gb);
  3807. if(prefix<15){
  3808. level_code = (prefix<<suffix_length) + get_bits(gb, suffix_length);
  3809. }else if(prefix==15){
  3810. level_code = (prefix<<suffix_length) + get_bits(gb, 12);
  3811. }else{
  3812. av_log(h->s.avctx, AV_LOG_ERROR, "prefix too large at %d %d\n", s->mb_x, s->mb_y);
  3813. return -1;
  3814. }
  3815. mask= -(level_code&1);
  3816. level[i]= (((2+level_code)>>1) ^ mask) - mask;
  3817. if(level_code > suffix_limit[suffix_length])
  3818. suffix_length++;
  3819. }
  3820. }
  3821. if(total_coeff == max_coeff)
  3822. zeros_left=0;
  3823. else{
  3824. if(n == CHROMA_DC_BLOCK_INDEX)
  3825. zeros_left= get_vlc2(gb, chroma_dc_total_zeros_vlc[ total_coeff-1 ].table, CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 1);
  3826. else
  3827. zeros_left= get_vlc2(gb, total_zeros_vlc[ total_coeff-1 ].table, TOTAL_ZEROS_VLC_BITS, 1);
  3828. }
  3829. coeff_num = zeros_left + total_coeff - 1;
  3830. j = scantable[coeff_num];
  3831. if(n > 24){
  3832. block[j] = level[0];
  3833. for(i=1;i<total_coeff;i++) {
  3834. if(zeros_left <= 0)
  3835. run_before = 0;
  3836. else if(zeros_left < 7){
  3837. run_before= get_vlc2(gb, run_vlc[zeros_left-1].table, RUN_VLC_BITS, 1);
  3838. }else{
  3839. run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
  3840. }
  3841. zeros_left -= run_before;
  3842. coeff_num -= 1 + run_before;
  3843. j= scantable[ coeff_num ];
  3844. block[j]= level[i];
  3845. }
  3846. }else{
  3847. block[j] = (level[0] * qmul[j] + 32)>>6;
  3848. for(i=1;i<total_coeff;i++) {
  3849. if(zeros_left <= 0)
  3850. run_before = 0;
  3851. else if(zeros_left < 7){
  3852. run_before= get_vlc2(gb, run_vlc[zeros_left-1].table, RUN_VLC_BITS, 1);
  3853. }else{
  3854. run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);
  3855. }
  3856. zeros_left -= run_before;
  3857. coeff_num -= 1 + run_before;
  3858. j= scantable[ coeff_num ];
  3859. block[j]= (level[i] * qmul[j] + 32)>>6;
  3860. }
  3861. }
  3862. if(zeros_left<0){
  3863. av_log(h->s.avctx, AV_LOG_ERROR, "negative number of zero coeffs at %d %d\n", s->mb_x, s->mb_y);
  3864. return -1;
  3865. }
  3866. return 0;
  3867. }
  3868. static void predict_field_decoding_flag(H264Context *h){
  3869. MpegEncContext * const s = &h->s;
  3870. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  3871. int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
  3872. ? s->current_picture.mb_type[mb_xy-1]
  3873. : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
  3874. ? s->current_picture.mb_type[mb_xy-s->mb_stride]
  3875. : 0;
  3876. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  3877. }
  3878. /**
  3879. * decodes a P_SKIP or B_SKIP macroblock
  3880. */
  3881. static void decode_mb_skip(H264Context *h){
  3882. MpegEncContext * const s = &h->s;
  3883. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  3884. int mb_type=0;
  3885. memset(h->non_zero_count[mb_xy], 0, 16);
  3886. memset(h->non_zero_count_cache + 8, 0, 8*5); //FIXME ugly, remove pfui
  3887. if(MB_FIELD)
  3888. mb_type|= MB_TYPE_INTERLACED;
  3889. if( h->slice_type == B_TYPE )
  3890. {
  3891. // just for fill_caches. pred_direct_motion will set the real mb_type
  3892. mb_type|= MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P0L1|MB_TYPE_DIRECT2|MB_TYPE_SKIP;
  3893. fill_caches(h, mb_type, 0); //FIXME check what is needed and what not ...
  3894. pred_direct_motion(h, &mb_type);
  3895. mb_type|= MB_TYPE_SKIP;
  3896. }
  3897. else
  3898. {
  3899. int mx, my;
  3900. mb_type|= MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P1L0|MB_TYPE_SKIP;
  3901. fill_caches(h, mb_type, 0); //FIXME check what is needed and what not ...
  3902. pred_pskip_motion(h, &mx, &my);
  3903. fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, 0, 1);
  3904. fill_rectangle( h->mv_cache[0][scan8[0]], 4, 4, 8, pack16to32(mx,my), 4);
  3905. }
  3906. write_back_motion(h, mb_type);
  3907. s->current_picture.mb_type[mb_xy]= mb_type;
  3908. s->current_picture.qscale_table[mb_xy]= s->qscale;
  3909. h->slice_table[ mb_xy ]= h->slice_num;
  3910. h->prev_mb_skipped= 1;
  3911. }
  3912. /**
  3913. * decodes a macroblock
  3914. * @returns 0 if ok, AC_ERROR / DC_ERROR / MV_ERROR if an error is noticed
  3915. */
  3916. static int decode_mb_cavlc(H264Context *h){
  3917. MpegEncContext * const s = &h->s;
  3918. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  3919. int partition_count;
  3920. unsigned int mb_type, cbp;
  3921. int dct8x8_allowed= h->pps.transform_8x8_mode;
  3922. s->dsp.clear_blocks(h->mb); //FIXME avoid if already clear (move after skip handlong?
  3923. tprintf(s->avctx, "pic:%d mb:%d/%d\n", h->frame_num, s->mb_x, s->mb_y);
  3924. cbp = 0; /* avoid warning. FIXME: find a solution without slowing
  3925. down the code */
  3926. if(h->slice_type != I_TYPE && h->slice_type != SI_TYPE){
  3927. if(s->mb_skip_run==-1)
  3928. s->mb_skip_run= get_ue_golomb(&s->gb);
  3929. if (s->mb_skip_run--) {
  3930. if(FRAME_MBAFF && (s->mb_y&1) == 0){
  3931. if(s->mb_skip_run==0)
  3932. h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);
  3933. else
  3934. predict_field_decoding_flag(h);
  3935. }
  3936. decode_mb_skip(h);
  3937. return 0;
  3938. }
  3939. }
  3940. if(FRAME_MBAFF){
  3941. if( (s->mb_y&1) == 0 )
  3942. h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);
  3943. }else
  3944. h->mb_field_decoding_flag= (s->picture_structure!=PICT_FRAME);
  3945. h->prev_mb_skipped= 0;
  3946. mb_type= get_ue_golomb(&s->gb);
  3947. if(h->slice_type == B_TYPE){
  3948. if(mb_type < 23){
  3949. partition_count= b_mb_type_info[mb_type].partition_count;
  3950. mb_type= b_mb_type_info[mb_type].type;
  3951. }else{
  3952. mb_type -= 23;
  3953. goto decode_intra_mb;
  3954. }
  3955. }else if(h->slice_type == P_TYPE /*|| h->slice_type == SP_TYPE */){
  3956. if(mb_type < 5){
  3957. partition_count= p_mb_type_info[mb_type].partition_count;
  3958. mb_type= p_mb_type_info[mb_type].type;
  3959. }else{
  3960. mb_type -= 5;
  3961. goto decode_intra_mb;
  3962. }
  3963. }else{
  3964. assert(h->slice_type == I_TYPE);
  3965. decode_intra_mb:
  3966. if(mb_type > 25){
  3967. 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);
  3968. return -1;
  3969. }
  3970. partition_count=0;
  3971. cbp= i_mb_type_info[mb_type].cbp;
  3972. h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;
  3973. mb_type= i_mb_type_info[mb_type].type;
  3974. }
  3975. if(MB_FIELD)
  3976. mb_type |= MB_TYPE_INTERLACED;
  3977. h->slice_table[ mb_xy ]= h->slice_num;
  3978. if(IS_INTRA_PCM(mb_type)){
  3979. unsigned int x, y;
  3980. // We assume these blocks are very rare so we do not optimize it.
  3981. align_get_bits(&s->gb);
  3982. // The pixels are stored in the same order as levels in h->mb array.
  3983. for(y=0; y<16; y++){
  3984. const int index= 4*(y&3) + 32*((y>>2)&1) + 128*(y>>3);
  3985. for(x=0; x<16; x++){
  3986. tprintf(s->avctx, "LUMA ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
  3987. h->mb[index + (x&3) + 16*((x>>2)&1) + 64*(x>>3)]= get_bits(&s->gb, 8);
  3988. }
  3989. }
  3990. for(y=0; y<8; y++){
  3991. const int index= 256 + 4*(y&3) + 32*(y>>2);
  3992. for(x=0; x<8; x++){
  3993. tprintf(s->avctx, "CHROMA U ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
  3994. h->mb[index + (x&3) + 16*(x>>2)]= get_bits(&s->gb, 8);
  3995. }
  3996. }
  3997. for(y=0; y<8; y++){
  3998. const int index= 256 + 64 + 4*(y&3) + 32*(y>>2);
  3999. for(x=0; x<8; x++){
  4000. tprintf(s->avctx, "CHROMA V ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
  4001. h->mb[index + (x&3) + 16*(x>>2)]= get_bits(&s->gb, 8);
  4002. }
  4003. }
  4004. // In deblocking, the quantizer is 0
  4005. s->current_picture.qscale_table[mb_xy]= 0;
  4006. h->chroma_qp[0] = get_chroma_qp(h, 0, 0);
  4007. h->chroma_qp[1] = get_chroma_qp(h, 1, 0);
  4008. // All coeffs are present
  4009. memset(h->non_zero_count[mb_xy], 16, 16);
  4010. s->current_picture.mb_type[mb_xy]= mb_type;
  4011. return 0;
  4012. }
  4013. if(MB_MBAFF){
  4014. h->ref_count[0] <<= 1;
  4015. h->ref_count[1] <<= 1;
  4016. }
  4017. fill_caches(h, mb_type, 0);
  4018. //mb_pred
  4019. if(IS_INTRA(mb_type)){
  4020. int pred_mode;
  4021. // init_top_left_availability(h);
  4022. if(IS_INTRA4x4(mb_type)){
  4023. int i;
  4024. int di = 1;
  4025. if(dct8x8_allowed && get_bits1(&s->gb)){
  4026. mb_type |= MB_TYPE_8x8DCT;
  4027. di = 4;
  4028. }
  4029. // fill_intra4x4_pred_table(h);
  4030. for(i=0; i<16; i+=di){
  4031. int mode= pred_intra_mode(h, i);
  4032. if(!get_bits1(&s->gb)){
  4033. const int rem_mode= get_bits(&s->gb, 3);
  4034. mode = rem_mode + (rem_mode >= mode);
  4035. }
  4036. if(di==4)
  4037. fill_rectangle( &h->intra4x4_pred_mode_cache[ scan8[i] ], 2, 2, 8, mode, 1 );
  4038. else
  4039. h->intra4x4_pred_mode_cache[ scan8[i] ] = mode;
  4040. }
  4041. write_back_intra_pred_mode(h);
  4042. if( check_intra4x4_pred_mode(h) < 0)
  4043. return -1;
  4044. }else{
  4045. h->intra16x16_pred_mode= check_intra_pred_mode(h, h->intra16x16_pred_mode);
  4046. if(h->intra16x16_pred_mode < 0)
  4047. return -1;
  4048. }
  4049. pred_mode= check_intra_pred_mode(h, get_ue_golomb(&s->gb));
  4050. if(pred_mode < 0)
  4051. return -1;
  4052. h->chroma_pred_mode= pred_mode;
  4053. }else if(partition_count==4){
  4054. int i, j, sub_partition_count[4], list, ref[2][4];
  4055. if(h->slice_type == B_TYPE){
  4056. for(i=0; i<4; i++){
  4057. h->sub_mb_type[i]= get_ue_golomb(&s->gb);
  4058. if(h->sub_mb_type[i] >=13){
  4059. 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);
  4060. return -1;
  4061. }
  4062. sub_partition_count[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  4063. h->sub_mb_type[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  4064. }
  4065. if( IS_DIRECT(h->sub_mb_type[0]) || IS_DIRECT(h->sub_mb_type[1])
  4066. || IS_DIRECT(h->sub_mb_type[2]) || IS_DIRECT(h->sub_mb_type[3])) {
  4067. pred_direct_motion(h, &mb_type);
  4068. h->ref_cache[0][scan8[4]] =
  4069. h->ref_cache[1][scan8[4]] =
  4070. h->ref_cache[0][scan8[12]] =
  4071. h->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;
  4072. }
  4073. }else{
  4074. assert(h->slice_type == P_TYPE || h->slice_type == SP_TYPE); //FIXME SP correct ?
  4075. for(i=0; i<4; i++){
  4076. h->sub_mb_type[i]= get_ue_golomb(&s->gb);
  4077. if(h->sub_mb_type[i] >=4){
  4078. 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);
  4079. return -1;
  4080. }
  4081. sub_partition_count[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  4082. h->sub_mb_type[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  4083. }
  4084. }
  4085. for(list=0; list<h->list_count; list++){
  4086. int ref_count= IS_REF0(mb_type) ? 1 : h->ref_count[list];
  4087. for(i=0; i<4; i++){
  4088. if(IS_DIRECT(h->sub_mb_type[i])) continue;
  4089. if(IS_DIR(h->sub_mb_type[i], 0, list)){
  4090. unsigned int tmp = get_te0_golomb(&s->gb, ref_count); //FIXME init to 0 before and skip?
  4091. if(tmp>=ref_count){
  4092. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", tmp);
  4093. return -1;
  4094. }
  4095. ref[list][i]= tmp;
  4096. }else{
  4097. //FIXME
  4098. ref[list][i] = -1;
  4099. }
  4100. }
  4101. }
  4102. if(dct8x8_allowed)
  4103. dct8x8_allowed = get_dct8x8_allowed(h);
  4104. for(list=0; list<h->list_count; list++){
  4105. for(i=0; i<4; i++){
  4106. if(IS_DIRECT(h->sub_mb_type[i])) {
  4107. h->ref_cache[list][ scan8[4*i] ] = h->ref_cache[list][ scan8[4*i]+1 ];
  4108. continue;
  4109. }
  4110. h->ref_cache[list][ scan8[4*i] ]=h->ref_cache[list][ scan8[4*i]+1 ]=
  4111. h->ref_cache[list][ scan8[4*i]+8 ]=h->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];
  4112. if(IS_DIR(h->sub_mb_type[i], 0, list)){
  4113. const int sub_mb_type= h->sub_mb_type[i];
  4114. const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;
  4115. for(j=0; j<sub_partition_count[i]; j++){
  4116. int mx, my;
  4117. const int index= 4*i + block_width*j;
  4118. int16_t (* mv_cache)[2]= &h->mv_cache[list][ scan8[index] ];
  4119. pred_motion(h, index, block_width, list, h->ref_cache[list][ scan8[index] ], &mx, &my);
  4120. mx += get_se_golomb(&s->gb);
  4121. my += get_se_golomb(&s->gb);
  4122. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4123. if(IS_SUB_8X8(sub_mb_type)){
  4124. mv_cache[ 1 ][0]=
  4125. mv_cache[ 8 ][0]= mv_cache[ 9 ][0]= mx;
  4126. mv_cache[ 1 ][1]=
  4127. mv_cache[ 8 ][1]= mv_cache[ 9 ][1]= my;
  4128. }else if(IS_SUB_8X4(sub_mb_type)){
  4129. mv_cache[ 1 ][0]= mx;
  4130. mv_cache[ 1 ][1]= my;
  4131. }else if(IS_SUB_4X8(sub_mb_type)){
  4132. mv_cache[ 8 ][0]= mx;
  4133. mv_cache[ 8 ][1]= my;
  4134. }
  4135. mv_cache[ 0 ][0]= mx;
  4136. mv_cache[ 0 ][1]= my;
  4137. }
  4138. }else{
  4139. uint32_t *p= (uint32_t *)&h->mv_cache[list][ scan8[4*i] ][0];
  4140. p[0] = p[1]=
  4141. p[8] = p[9]= 0;
  4142. }
  4143. }
  4144. }
  4145. }else if(IS_DIRECT(mb_type)){
  4146. pred_direct_motion(h, &mb_type);
  4147. dct8x8_allowed &= h->sps.direct_8x8_inference_flag;
  4148. }else{
  4149. int list, mx, my, i;
  4150. //FIXME we should set ref_idx_l? to 0 if we use that later ...
  4151. if(IS_16X16(mb_type)){
  4152. for(list=0; list<h->list_count; list++){
  4153. unsigned int val;
  4154. if(IS_DIR(mb_type, 0, list)){
  4155. val= get_te0_golomb(&s->gb, h->ref_count[list]);
  4156. if(val >= h->ref_count[list]){
  4157. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
  4158. return -1;
  4159. }
  4160. }else
  4161. val= LIST_NOT_USED&0xFF;
  4162. fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, val, 1);
  4163. }
  4164. for(list=0; list<h->list_count; list++){
  4165. unsigned int val;
  4166. if(IS_DIR(mb_type, 0, list)){
  4167. pred_motion(h, 0, 4, list, h->ref_cache[list][ scan8[0] ], &mx, &my);
  4168. mx += get_se_golomb(&s->gb);
  4169. my += get_se_golomb(&s->gb);
  4170. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4171. val= pack16to32(mx,my);
  4172. }else
  4173. val=0;
  4174. fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, val, 4);
  4175. }
  4176. }
  4177. else if(IS_16X8(mb_type)){
  4178. for(list=0; list<h->list_count; list++){
  4179. for(i=0; i<2; i++){
  4180. unsigned int val;
  4181. if(IS_DIR(mb_type, i, list)){
  4182. val= get_te0_golomb(&s->gb, h->ref_count[list]);
  4183. if(val >= h->ref_count[list]){
  4184. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
  4185. return -1;
  4186. }
  4187. }else
  4188. val= LIST_NOT_USED&0xFF;
  4189. fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 1);
  4190. }
  4191. }
  4192. for(list=0; list<h->list_count; list++){
  4193. for(i=0; i<2; i++){
  4194. unsigned int val;
  4195. if(IS_DIR(mb_type, i, list)){
  4196. pred_16x8_motion(h, 8*i, list, h->ref_cache[list][scan8[0] + 16*i], &mx, &my);
  4197. mx += get_se_golomb(&s->gb);
  4198. my += get_se_golomb(&s->gb);
  4199. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4200. val= pack16to32(mx,my);
  4201. }else
  4202. val=0;
  4203. fill_rectangle(h->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 4);
  4204. }
  4205. }
  4206. }else{
  4207. assert(IS_8X16(mb_type));
  4208. for(list=0; list<h->list_count; list++){
  4209. for(i=0; i<2; i++){
  4210. unsigned int val;
  4211. if(IS_DIR(mb_type, i, list)){ //FIXME optimize
  4212. val= get_te0_golomb(&s->gb, h->ref_count[list]);
  4213. if(val >= h->ref_count[list]){
  4214. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
  4215. return -1;
  4216. }
  4217. }else
  4218. val= LIST_NOT_USED&0xFF;
  4219. fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 1);
  4220. }
  4221. }
  4222. for(list=0; list<h->list_count; list++){
  4223. for(i=0; i<2; i++){
  4224. unsigned int val;
  4225. if(IS_DIR(mb_type, i, list)){
  4226. pred_8x16_motion(h, i*4, list, h->ref_cache[list][ scan8[0] + 2*i ], &mx, &my);
  4227. mx += get_se_golomb(&s->gb);
  4228. my += get_se_golomb(&s->gb);
  4229. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4230. val= pack16to32(mx,my);
  4231. }else
  4232. val=0;
  4233. fill_rectangle(h->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 4);
  4234. }
  4235. }
  4236. }
  4237. }
  4238. if(IS_INTER(mb_type))
  4239. write_back_motion(h, mb_type);
  4240. if(!IS_INTRA16x16(mb_type)){
  4241. cbp= get_ue_golomb(&s->gb);
  4242. if(cbp > 47){
  4243. av_log(h->s.avctx, AV_LOG_ERROR, "cbp too large (%u) at %d %d\n", cbp, s->mb_x, s->mb_y);
  4244. return -1;
  4245. }
  4246. if(IS_INTRA4x4(mb_type))
  4247. cbp= golomb_to_intra4x4_cbp[cbp];
  4248. else
  4249. cbp= golomb_to_inter_cbp[cbp];
  4250. }
  4251. h->cbp = cbp;
  4252. if(dct8x8_allowed && (cbp&15) && !IS_INTRA(mb_type)){
  4253. if(get_bits1(&s->gb))
  4254. mb_type |= MB_TYPE_8x8DCT;
  4255. }
  4256. s->current_picture.mb_type[mb_xy]= mb_type;
  4257. if(cbp || IS_INTRA16x16(mb_type)){
  4258. int i8x8, i4x4, chroma_idx;
  4259. int dquant;
  4260. GetBitContext *gb= IS_INTRA(mb_type) ? h->intra_gb_ptr : h->inter_gb_ptr;
  4261. const uint8_t *scan, *scan8x8, *dc_scan;
  4262. // fill_non_zero_count_cache(h);
  4263. if(IS_INTERLACED(mb_type)){
  4264. scan8x8= s->qscale ? h->field_scan8x8_cavlc : h->field_scan8x8_cavlc_q0;
  4265. scan= s->qscale ? h->field_scan : h->field_scan_q0;
  4266. dc_scan= luma_dc_field_scan;
  4267. }else{
  4268. scan8x8= s->qscale ? h->zigzag_scan8x8_cavlc : h->zigzag_scan8x8_cavlc_q0;
  4269. scan= s->qscale ? h->zigzag_scan : h->zigzag_scan_q0;
  4270. dc_scan= luma_dc_zigzag_scan;
  4271. }
  4272. dquant= get_se_golomb(&s->gb);
  4273. if( dquant > 25 || dquant < -26 ){
  4274. av_log(h->s.avctx, AV_LOG_ERROR, "dquant out of range (%d) at %d %d\n", dquant, s->mb_x, s->mb_y);
  4275. return -1;
  4276. }
  4277. s->qscale += dquant;
  4278. if(((unsigned)s->qscale) > 51){
  4279. if(s->qscale<0) s->qscale+= 52;
  4280. else s->qscale-= 52;
  4281. }
  4282. h->chroma_qp[0]= get_chroma_qp(h, 0, s->qscale);
  4283. h->chroma_qp[1]= get_chroma_qp(h, 1, s->qscale);
  4284. if(IS_INTRA16x16(mb_type)){
  4285. if( decode_residual(h, h->intra_gb_ptr, h->mb, LUMA_DC_BLOCK_INDEX, dc_scan, h->dequant4_coeff[0][s->qscale], 16) < 0){
  4286. return -1; //FIXME continue if partitioned and other return -1 too
  4287. }
  4288. assert((cbp&15) == 0 || (cbp&15) == 15);
  4289. if(cbp&15){
  4290. for(i8x8=0; i8x8<4; i8x8++){
  4291. for(i4x4=0; i4x4<4; i4x4++){
  4292. const int index= i4x4 + 4*i8x8;
  4293. if( decode_residual(h, h->intra_gb_ptr, h->mb + 16*index, index, scan + 1, h->dequant4_coeff[0][s->qscale], 15) < 0 ){
  4294. return -1;
  4295. }
  4296. }
  4297. }
  4298. }else{
  4299. fill_rectangle(&h->non_zero_count_cache[scan8[0]], 4, 4, 8, 0, 1);
  4300. }
  4301. }else{
  4302. for(i8x8=0; i8x8<4; i8x8++){
  4303. if(cbp & (1<<i8x8)){
  4304. if(IS_8x8DCT(mb_type)){
  4305. DCTELEM *buf = &h->mb[64*i8x8];
  4306. uint8_t *nnz;
  4307. for(i4x4=0; i4x4<4; i4x4++){
  4308. if( decode_residual(h, gb, buf, i4x4+4*i8x8, scan8x8+16*i4x4,
  4309. h->dequant8_coeff[IS_INTRA( mb_type ) ? 0:1][s->qscale], 16) <0 )
  4310. return -1;
  4311. }
  4312. nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
  4313. nnz[0] += nnz[1] + nnz[8] + nnz[9];
  4314. }else{
  4315. for(i4x4=0; i4x4<4; i4x4++){
  4316. const int index= i4x4 + 4*i8x8;
  4317. if( decode_residual(h, gb, h->mb + 16*index, index, scan, h->dequant4_coeff[IS_INTRA( mb_type ) ? 0:3][s->qscale], 16) <0 ){
  4318. return -1;
  4319. }
  4320. }
  4321. }
  4322. }else{
  4323. uint8_t * const nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
  4324. nnz[0] = nnz[1] = nnz[8] = nnz[9] = 0;
  4325. }
  4326. }
  4327. }
  4328. if(cbp&0x30){
  4329. for(chroma_idx=0; chroma_idx<2; chroma_idx++)
  4330. if( decode_residual(h, gb, h->mb + 256 + 16*4*chroma_idx, CHROMA_DC_BLOCK_INDEX, chroma_dc_scan, NULL, 4) < 0){
  4331. return -1;
  4332. }
  4333. }
  4334. if(cbp&0x20){
  4335. for(chroma_idx=0; chroma_idx<2; chroma_idx++){
  4336. const uint32_t *qmul = h->dequant4_coeff[chroma_idx+1+(IS_INTRA( mb_type ) ? 0:3)][h->chroma_qp[chroma_idx]];
  4337. for(i4x4=0; i4x4<4; i4x4++){
  4338. const int index= 16 + 4*chroma_idx + i4x4;
  4339. if( decode_residual(h, gb, h->mb + 16*index, index, scan + 1, qmul, 15) < 0){
  4340. return -1;
  4341. }
  4342. }
  4343. }
  4344. }else{
  4345. uint8_t * const nnz= &h->non_zero_count_cache[0];
  4346. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  4347. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  4348. }
  4349. }else{
  4350. uint8_t * const nnz= &h->non_zero_count_cache[0];
  4351. fill_rectangle(&nnz[scan8[0]], 4, 4, 8, 0, 1);
  4352. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  4353. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  4354. }
  4355. s->current_picture.qscale_table[mb_xy]= s->qscale;
  4356. write_back_non_zero_count(h);
  4357. if(MB_MBAFF){
  4358. h->ref_count[0] >>= 1;
  4359. h->ref_count[1] >>= 1;
  4360. }
  4361. return 0;
  4362. }
  4363. static int decode_cabac_field_decoding_flag(H264Context *h) {
  4364. MpegEncContext * const s = &h->s;
  4365. const int mb_x = s->mb_x;
  4366. const int mb_y = s->mb_y & ~1;
  4367. const int mba_xy = mb_x - 1 + mb_y *s->mb_stride;
  4368. const int mbb_xy = mb_x + (mb_y-2)*s->mb_stride;
  4369. unsigned int ctx = 0;
  4370. if( h->slice_table[mba_xy] == h->slice_num && IS_INTERLACED( s->current_picture.mb_type[mba_xy] ) ) {
  4371. ctx += 1;
  4372. }
  4373. if( h->slice_table[mbb_xy] == h->slice_num && IS_INTERLACED( s->current_picture.mb_type[mbb_xy] ) ) {
  4374. ctx += 1;
  4375. }
  4376. return get_cabac_noinline( &h->cabac, &h->cabac_state[70 + ctx] );
  4377. }
  4378. static int decode_cabac_intra_mb_type(H264Context *h, int ctx_base, int intra_slice) {
  4379. uint8_t *state= &h->cabac_state[ctx_base];
  4380. int mb_type;
  4381. if(intra_slice){
  4382. MpegEncContext * const s = &h->s;
  4383. const int mba_xy = h->left_mb_xy[0];
  4384. const int mbb_xy = h->top_mb_xy;
  4385. int ctx=0;
  4386. if( h->slice_table[mba_xy] == h->slice_num && !IS_INTRA4x4( s->current_picture.mb_type[mba_xy] ) )
  4387. ctx++;
  4388. if( h->slice_table[mbb_xy] == h->slice_num && !IS_INTRA4x4( s->current_picture.mb_type[mbb_xy] ) )
  4389. ctx++;
  4390. if( get_cabac_noinline( &h->cabac, &state[ctx] ) == 0 )
  4391. return 0; /* I4x4 */
  4392. state += 2;
  4393. }else{
  4394. if( get_cabac_noinline( &h->cabac, &state[0] ) == 0 )
  4395. return 0; /* I4x4 */
  4396. }
  4397. if( get_cabac_terminate( &h->cabac ) )
  4398. return 25; /* PCM */
  4399. mb_type = 1; /* I16x16 */
  4400. mb_type += 12 * get_cabac_noinline( &h->cabac, &state[1] ); /* cbp_luma != 0 */
  4401. if( get_cabac_noinline( &h->cabac, &state[2] ) ) /* cbp_chroma */
  4402. mb_type += 4 + 4 * get_cabac_noinline( &h->cabac, &state[2+intra_slice] );
  4403. mb_type += 2 * get_cabac_noinline( &h->cabac, &state[3+intra_slice] );
  4404. mb_type += 1 * get_cabac_noinline( &h->cabac, &state[3+2*intra_slice] );
  4405. return mb_type;
  4406. }
  4407. static int decode_cabac_mb_type( H264Context *h ) {
  4408. MpegEncContext * const s = &h->s;
  4409. if( h->slice_type == I_TYPE ) {
  4410. return decode_cabac_intra_mb_type(h, 3, 1);
  4411. } else if( h->slice_type == P_TYPE ) {
  4412. if( get_cabac_noinline( &h->cabac, &h->cabac_state[14] ) == 0 ) {
  4413. /* P-type */
  4414. if( get_cabac_noinline( &h->cabac, &h->cabac_state[15] ) == 0 ) {
  4415. /* P_L0_D16x16, P_8x8 */
  4416. return 3 * get_cabac_noinline( &h->cabac, &h->cabac_state[16] );
  4417. } else {
  4418. /* P_L0_D8x16, P_L0_D16x8 */
  4419. return 2 - get_cabac_noinline( &h->cabac, &h->cabac_state[17] );
  4420. }
  4421. } else {
  4422. return decode_cabac_intra_mb_type(h, 17, 0) + 5;
  4423. }
  4424. } else if( h->slice_type == B_TYPE ) {
  4425. const int mba_xy = h->left_mb_xy[0];
  4426. const int mbb_xy = h->top_mb_xy;
  4427. int ctx = 0;
  4428. int bits;
  4429. if( h->slice_table[mba_xy] == h->slice_num && !IS_DIRECT( s->current_picture.mb_type[mba_xy] ) )
  4430. ctx++;
  4431. if( h->slice_table[mbb_xy] == h->slice_num && !IS_DIRECT( s->current_picture.mb_type[mbb_xy] ) )
  4432. ctx++;
  4433. if( !get_cabac_noinline( &h->cabac, &h->cabac_state[27+ctx] ) )
  4434. return 0; /* B_Direct_16x16 */
  4435. if( !get_cabac_noinline( &h->cabac, &h->cabac_state[27+3] ) ) {
  4436. return 1 + get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ); /* B_L[01]_16x16 */
  4437. }
  4438. bits = get_cabac_noinline( &h->cabac, &h->cabac_state[27+4] ) << 3;
  4439. bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ) << 2;
  4440. bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ) << 1;
  4441. bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] );
  4442. if( bits < 8 )
  4443. return bits + 3; /* B_Bi_16x16 through B_L1_L0_16x8 */
  4444. else if( bits == 13 ) {
  4445. return decode_cabac_intra_mb_type(h, 32, 0) + 23;
  4446. } else if( bits == 14 )
  4447. return 11; /* B_L1_L0_8x16 */
  4448. else if( bits == 15 )
  4449. return 22; /* B_8x8 */
  4450. bits= ( bits<<1 ) | get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] );
  4451. return bits - 4; /* B_L0_Bi_* through B_Bi_Bi_* */
  4452. } else {
  4453. /* TODO SI/SP frames? */
  4454. return -1;
  4455. }
  4456. }
  4457. static int decode_cabac_mb_skip( H264Context *h, int mb_x, int mb_y ) {
  4458. MpegEncContext * const s = &h->s;
  4459. int mba_xy, mbb_xy;
  4460. int ctx = 0;
  4461. if(FRAME_MBAFF){ //FIXME merge with the stuff in fill_caches?
  4462. int mb_xy = mb_x + (mb_y&~1)*s->mb_stride;
  4463. mba_xy = mb_xy - 1;
  4464. if( (mb_y&1)
  4465. && h->slice_table[mba_xy] == h->slice_num
  4466. && MB_FIELD == !!IS_INTERLACED( s->current_picture.mb_type[mba_xy] ) )
  4467. mba_xy += s->mb_stride;
  4468. if( MB_FIELD ){
  4469. mbb_xy = mb_xy - s->mb_stride;
  4470. if( !(mb_y&1)
  4471. && h->slice_table[mbb_xy] == h->slice_num
  4472. && IS_INTERLACED( s->current_picture.mb_type[mbb_xy] ) )
  4473. mbb_xy -= s->mb_stride;
  4474. }else
  4475. mbb_xy = mb_x + (mb_y-1)*s->mb_stride;
  4476. }else{
  4477. int mb_xy = mb_x + mb_y*s->mb_stride;
  4478. mba_xy = mb_xy - 1;
  4479. mbb_xy = mb_xy - (s->mb_stride << FIELD_PICTURE);
  4480. }
  4481. if( h->slice_table[mba_xy] == h->slice_num && !IS_SKIP( s->current_picture.mb_type[mba_xy] ))
  4482. ctx++;
  4483. if( h->slice_table[mbb_xy] == h->slice_num && !IS_SKIP( s->current_picture.mb_type[mbb_xy] ))
  4484. ctx++;
  4485. if( h->slice_type == B_TYPE )
  4486. ctx += 13;
  4487. return get_cabac_noinline( &h->cabac, &h->cabac_state[11+ctx] );
  4488. }
  4489. static int decode_cabac_mb_intra4x4_pred_mode( H264Context *h, int pred_mode ) {
  4490. int mode = 0;
  4491. if( get_cabac( &h->cabac, &h->cabac_state[68] ) )
  4492. return pred_mode;
  4493. mode += 1 * get_cabac( &h->cabac, &h->cabac_state[69] );
  4494. mode += 2 * get_cabac( &h->cabac, &h->cabac_state[69] );
  4495. mode += 4 * get_cabac( &h->cabac, &h->cabac_state[69] );
  4496. if( mode >= pred_mode )
  4497. return mode + 1;
  4498. else
  4499. return mode;
  4500. }
  4501. static int decode_cabac_mb_chroma_pre_mode( H264Context *h) {
  4502. const int mba_xy = h->left_mb_xy[0];
  4503. const int mbb_xy = h->top_mb_xy;
  4504. int ctx = 0;
  4505. /* No need to test for IS_INTRA4x4 and IS_INTRA16x16, as we set chroma_pred_mode_table to 0 */
  4506. if( h->slice_table[mba_xy] == h->slice_num && h->chroma_pred_mode_table[mba_xy] != 0 )
  4507. ctx++;
  4508. if( h->slice_table[mbb_xy] == h->slice_num && h->chroma_pred_mode_table[mbb_xy] != 0 )
  4509. ctx++;
  4510. if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+ctx] ) == 0 )
  4511. return 0;
  4512. if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+3] ) == 0 )
  4513. return 1;
  4514. if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+3] ) == 0 )
  4515. return 2;
  4516. else
  4517. return 3;
  4518. }
  4519. static int decode_cabac_mb_cbp_luma( H264Context *h) {
  4520. int cbp_b, cbp_a, ctx, cbp = 0;
  4521. cbp_a = h->slice_table[h->left_mb_xy[0]] == h->slice_num ? h->left_cbp : -1;
  4522. cbp_b = h->slice_table[h->top_mb_xy] == h->slice_num ? h->top_cbp : -1;
  4523. ctx = !(cbp_a & 0x02) + 2 * !(cbp_b & 0x04);
  4524. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]);
  4525. ctx = !(cbp & 0x01) + 2 * !(cbp_b & 0x08);
  4526. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 1;
  4527. ctx = !(cbp_a & 0x08) + 2 * !(cbp & 0x01);
  4528. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 2;
  4529. ctx = !(cbp & 0x04) + 2 * !(cbp & 0x02);
  4530. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 3;
  4531. return cbp;
  4532. }
  4533. static int decode_cabac_mb_cbp_chroma( H264Context *h) {
  4534. int ctx;
  4535. int cbp_a, cbp_b;
  4536. cbp_a = (h->left_cbp>>4)&0x03;
  4537. cbp_b = (h-> top_cbp>>4)&0x03;
  4538. ctx = 0;
  4539. if( cbp_a > 0 ) ctx++;
  4540. if( cbp_b > 0 ) ctx += 2;
  4541. if( get_cabac_noinline( &h->cabac, &h->cabac_state[77 + ctx] ) == 0 )
  4542. return 0;
  4543. ctx = 4;
  4544. if( cbp_a == 2 ) ctx++;
  4545. if( cbp_b == 2 ) ctx += 2;
  4546. return 1 + get_cabac_noinline( &h->cabac, &h->cabac_state[77 + ctx] );
  4547. }
  4548. static int decode_cabac_mb_dqp( H264Context *h) {
  4549. int ctx = 0;
  4550. int val = 0;
  4551. if( h->last_qscale_diff != 0 )
  4552. ctx++;
  4553. while( get_cabac_noinline( &h->cabac, &h->cabac_state[60 + ctx] ) ) {
  4554. if( ctx < 2 )
  4555. ctx = 2;
  4556. else
  4557. ctx = 3;
  4558. val++;
  4559. if(val > 102) //prevent infinite loop
  4560. return INT_MIN;
  4561. }
  4562. if( val&0x01 )
  4563. return (val + 1)/2;
  4564. else
  4565. return -(val + 1)/2;
  4566. }
  4567. static int decode_cabac_p_mb_sub_type( H264Context *h ) {
  4568. if( get_cabac( &h->cabac, &h->cabac_state[21] ) )
  4569. return 0; /* 8x8 */
  4570. if( !get_cabac( &h->cabac, &h->cabac_state[22] ) )
  4571. return 1; /* 8x4 */
  4572. if( get_cabac( &h->cabac, &h->cabac_state[23] ) )
  4573. return 2; /* 4x8 */
  4574. return 3; /* 4x4 */
  4575. }
  4576. static int decode_cabac_b_mb_sub_type( H264Context *h ) {
  4577. int type;
  4578. if( !get_cabac( &h->cabac, &h->cabac_state[36] ) )
  4579. return 0; /* B_Direct_8x8 */
  4580. if( !get_cabac( &h->cabac, &h->cabac_state[37] ) )
  4581. return 1 + get_cabac( &h->cabac, &h->cabac_state[39] ); /* B_L0_8x8, B_L1_8x8 */
  4582. type = 3;
  4583. if( get_cabac( &h->cabac, &h->cabac_state[38] ) ) {
  4584. if( get_cabac( &h->cabac, &h->cabac_state[39] ) )
  4585. return 11 + get_cabac( &h->cabac, &h->cabac_state[39] ); /* B_L1_4x4, B_Bi_4x4 */
  4586. type += 4;
  4587. }
  4588. type += 2*get_cabac( &h->cabac, &h->cabac_state[39] );
  4589. type += get_cabac( &h->cabac, &h->cabac_state[39] );
  4590. return type;
  4591. }
  4592. static inline int decode_cabac_mb_transform_size( H264Context *h ) {
  4593. return get_cabac_noinline( &h->cabac, &h->cabac_state[399 + h->neighbor_transform_size] );
  4594. }
  4595. static int decode_cabac_mb_ref( H264Context *h, int list, int n ) {
  4596. int refa = h->ref_cache[list][scan8[n] - 1];
  4597. int refb = h->ref_cache[list][scan8[n] - 8];
  4598. int ref = 0;
  4599. int ctx = 0;
  4600. if( h->slice_type == B_TYPE) {
  4601. if( refa > 0 && !h->direct_cache[scan8[n] - 1] )
  4602. ctx++;
  4603. if( refb > 0 && !h->direct_cache[scan8[n] - 8] )
  4604. ctx += 2;
  4605. } else {
  4606. if( refa > 0 )
  4607. ctx++;
  4608. if( refb > 0 )
  4609. ctx += 2;
  4610. }
  4611. while( get_cabac( &h->cabac, &h->cabac_state[54+ctx] ) ) {
  4612. ref++;
  4613. if( ctx < 4 )
  4614. ctx = 4;
  4615. else
  4616. ctx = 5;
  4617. if(ref >= 32 /*h->ref_list[list]*/){
  4618. av_log(h->s.avctx, AV_LOG_ERROR, "overflow in decode_cabac_mb_ref\n");
  4619. return 0; //FIXME we should return -1 and check the return everywhere
  4620. }
  4621. }
  4622. return ref;
  4623. }
  4624. static int decode_cabac_mb_mvd( H264Context *h, int list, int n, int l ) {
  4625. int amvd = abs( h->mvd_cache[list][scan8[n] - 1][l] ) +
  4626. abs( h->mvd_cache[list][scan8[n] - 8][l] );
  4627. int ctxbase = (l == 0) ? 40 : 47;
  4628. int ctx, mvd;
  4629. if( amvd < 3 )
  4630. ctx = 0;
  4631. else if( amvd > 32 )
  4632. ctx = 2;
  4633. else
  4634. ctx = 1;
  4635. if(!get_cabac(&h->cabac, &h->cabac_state[ctxbase+ctx]))
  4636. return 0;
  4637. mvd= 1;
  4638. ctx= 3;
  4639. while( mvd < 9 && get_cabac( &h->cabac, &h->cabac_state[ctxbase+ctx] ) ) {
  4640. mvd++;
  4641. if( ctx < 6 )
  4642. ctx++;
  4643. }
  4644. if( mvd >= 9 ) {
  4645. int k = 3;
  4646. while( get_cabac_bypass( &h->cabac ) ) {
  4647. mvd += 1 << k;
  4648. k++;
  4649. if(k>24){
  4650. av_log(h->s.avctx, AV_LOG_ERROR, "overflow in decode_cabac_mb_mvd\n");
  4651. return INT_MIN;
  4652. }
  4653. }
  4654. while( k-- ) {
  4655. if( get_cabac_bypass( &h->cabac ) )
  4656. mvd += 1 << k;
  4657. }
  4658. }
  4659. return get_cabac_bypass_sign( &h->cabac, -mvd );
  4660. }
  4661. static inline int get_cabac_cbf_ctx( H264Context *h, int cat, int idx ) {
  4662. int nza, nzb;
  4663. int ctx = 0;
  4664. if( cat == 0 ) {
  4665. nza = h->left_cbp&0x100;
  4666. nzb = h-> top_cbp&0x100;
  4667. } else if( cat == 1 || cat == 2 ) {
  4668. nza = h->non_zero_count_cache[scan8[idx] - 1];
  4669. nzb = h->non_zero_count_cache[scan8[idx] - 8];
  4670. } else if( cat == 3 ) {
  4671. nza = (h->left_cbp>>(6+idx))&0x01;
  4672. nzb = (h-> top_cbp>>(6+idx))&0x01;
  4673. } else {
  4674. assert(cat == 4);
  4675. nza = h->non_zero_count_cache[scan8[16+idx] - 1];
  4676. nzb = h->non_zero_count_cache[scan8[16+idx] - 8];
  4677. }
  4678. if( nza > 0 )
  4679. ctx++;
  4680. if( nzb > 0 )
  4681. ctx += 2;
  4682. return ctx + 4 * cat;
  4683. }
  4684. static const attribute_used uint8_t last_coeff_flag_offset_8x8[63] = {
  4685. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  4686. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  4687. 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
  4688. 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8
  4689. };
  4690. static void decode_cabac_residual( H264Context *h, DCTELEM *block, int cat, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff) {
  4691. const int mb_xy = h->s.mb_x + h->s.mb_y*h->s.mb_stride;
  4692. static const int significant_coeff_flag_offset[2][6] = {
  4693. { 105+0, 105+15, 105+29, 105+44, 105+47, 402 },
  4694. { 277+0, 277+15, 277+29, 277+44, 277+47, 436 }
  4695. };
  4696. static const int last_coeff_flag_offset[2][6] = {
  4697. { 166+0, 166+15, 166+29, 166+44, 166+47, 417 },
  4698. { 338+0, 338+15, 338+29, 338+44, 338+47, 451 }
  4699. };
  4700. static const int coeff_abs_level_m1_offset[6] = {
  4701. 227+0, 227+10, 227+20, 227+30, 227+39, 426
  4702. };
  4703. static const uint8_t significant_coeff_flag_offset_8x8[2][63] = {
  4704. { 0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5,
  4705. 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9,10, 9, 8, 7,
  4706. 7, 6,11,12,13,11, 6, 7, 8, 9,14,10, 9, 8, 6,11,
  4707. 12,13,11, 6, 9,14,10, 9,11,12,13,11,14,10,12 },
  4708. { 0, 1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 7, 7, 8, 4, 5,
  4709. 6, 9,10,10, 8,11,12,11, 9, 9,10,10, 8,11,12,11,
  4710. 9, 9,10,10, 8,11,12,11, 9, 9,10,10, 8,13,13, 9,
  4711. 9,10,10, 8,13,13, 9, 9,10,10,14,14,14,14,14 }
  4712. };
  4713. int index[64];
  4714. int av_unused last;
  4715. int coeff_count = 0;
  4716. int abslevel1 = 1;
  4717. int abslevelgt1 = 0;
  4718. uint8_t *significant_coeff_ctx_base;
  4719. uint8_t *last_coeff_ctx_base;
  4720. uint8_t *abs_level_m1_ctx_base;
  4721. #ifndef ARCH_X86
  4722. #define CABAC_ON_STACK
  4723. #endif
  4724. #ifdef CABAC_ON_STACK
  4725. #define CC &cc
  4726. CABACContext cc;
  4727. cc.range = h->cabac.range;
  4728. cc.low = h->cabac.low;
  4729. cc.bytestream= h->cabac.bytestream;
  4730. #else
  4731. #define CC &h->cabac
  4732. #endif
  4733. /* cat: 0-> DC 16x16 n = 0
  4734. * 1-> AC 16x16 n = luma4x4idx
  4735. * 2-> Luma4x4 n = luma4x4idx
  4736. * 3-> DC Chroma n = iCbCr
  4737. * 4-> AC Chroma n = 4 * iCbCr + chroma4x4idx
  4738. * 5-> Luma8x8 n = 4 * luma8x8idx
  4739. */
  4740. /* read coded block flag */
  4741. if( cat != 5 ) {
  4742. if( get_cabac( CC, &h->cabac_state[85 + get_cabac_cbf_ctx( h, cat, n ) ] ) == 0 ) {
  4743. if( cat == 1 || cat == 2 )
  4744. h->non_zero_count_cache[scan8[n]] = 0;
  4745. else if( cat == 4 )
  4746. h->non_zero_count_cache[scan8[16+n]] = 0;
  4747. #ifdef CABAC_ON_STACK
  4748. h->cabac.range = cc.range ;
  4749. h->cabac.low = cc.low ;
  4750. h->cabac.bytestream= cc.bytestream;
  4751. #endif
  4752. return;
  4753. }
  4754. }
  4755. significant_coeff_ctx_base = h->cabac_state
  4756. + significant_coeff_flag_offset[MB_FIELD][cat];
  4757. last_coeff_ctx_base = h->cabac_state
  4758. + last_coeff_flag_offset[MB_FIELD][cat];
  4759. abs_level_m1_ctx_base = h->cabac_state
  4760. + coeff_abs_level_m1_offset[cat];
  4761. if( cat == 5 ) {
  4762. #define DECODE_SIGNIFICANCE( coefs, sig_off, last_off ) \
  4763. for(last= 0; last < coefs; last++) { \
  4764. uint8_t *sig_ctx = significant_coeff_ctx_base + sig_off; \
  4765. if( get_cabac( CC, sig_ctx )) { \
  4766. uint8_t *last_ctx = last_coeff_ctx_base + last_off; \
  4767. index[coeff_count++] = last; \
  4768. if( get_cabac( CC, last_ctx ) ) { \
  4769. last= max_coeff; \
  4770. break; \
  4771. } \
  4772. } \
  4773. }\
  4774. if( last == max_coeff -1 ) {\
  4775. index[coeff_count++] = last;\
  4776. }
  4777. const uint8_t *sig_off = significant_coeff_flag_offset_8x8[MB_FIELD];
  4778. #if defined(ARCH_X86) && defined(HAVE_7REGS) && defined(HAVE_EBX_AVAILABLE) && !defined(BROKEN_RELOCATIONS)
  4779. coeff_count= decode_significance_8x8_x86(CC, significant_coeff_ctx_base, index, sig_off);
  4780. } else {
  4781. coeff_count= decode_significance_x86(CC, max_coeff, significant_coeff_ctx_base, index);
  4782. #else
  4783. DECODE_SIGNIFICANCE( 63, sig_off[last], last_coeff_flag_offset_8x8[last] );
  4784. } else {
  4785. DECODE_SIGNIFICANCE( max_coeff - 1, last, last );
  4786. #endif
  4787. }
  4788. assert(coeff_count > 0);
  4789. if( cat == 0 )
  4790. h->cbp_table[mb_xy] |= 0x100;
  4791. else if( cat == 1 || cat == 2 )
  4792. h->non_zero_count_cache[scan8[n]] = coeff_count;
  4793. else if( cat == 3 )
  4794. h->cbp_table[mb_xy] |= 0x40 << n;
  4795. else if( cat == 4 )
  4796. h->non_zero_count_cache[scan8[16+n]] = coeff_count;
  4797. else {
  4798. assert( cat == 5 );
  4799. fill_rectangle(&h->non_zero_count_cache[scan8[n]], 2, 2, 8, coeff_count, 1);
  4800. }
  4801. for( coeff_count--; coeff_count >= 0; coeff_count-- ) {
  4802. uint8_t *ctx = (abslevelgt1 != 0 ? 0 : FFMIN( 4, abslevel1 )) + abs_level_m1_ctx_base;
  4803. int j= scantable[index[coeff_count]];
  4804. if( get_cabac( CC, ctx ) == 0 ) {
  4805. if( !qmul ) {
  4806. block[j] = get_cabac_bypass_sign( CC, -1);
  4807. }else{
  4808. block[j] = (get_cabac_bypass_sign( CC, -qmul[j]) + 32) >> 6;;
  4809. }
  4810. abslevel1++;
  4811. } else {
  4812. int coeff_abs = 2;
  4813. ctx = 5 + FFMIN( 4, abslevelgt1 ) + abs_level_m1_ctx_base;
  4814. while( coeff_abs < 15 && get_cabac( CC, ctx ) ) {
  4815. coeff_abs++;
  4816. }
  4817. if( coeff_abs >= 15 ) {
  4818. int j = 0;
  4819. while( get_cabac_bypass( CC ) ) {
  4820. j++;
  4821. }
  4822. coeff_abs=1;
  4823. while( j-- ) {
  4824. coeff_abs += coeff_abs + get_cabac_bypass( CC );
  4825. }
  4826. coeff_abs+= 14;
  4827. }
  4828. if( !qmul ) {
  4829. if( get_cabac_bypass( CC ) ) block[j] = -coeff_abs;
  4830. else block[j] = coeff_abs;
  4831. }else{
  4832. if( get_cabac_bypass( CC ) ) block[j] = (-coeff_abs * qmul[j] + 32) >> 6;
  4833. else block[j] = ( coeff_abs * qmul[j] + 32) >> 6;
  4834. }
  4835. abslevelgt1++;
  4836. }
  4837. }
  4838. #ifdef CABAC_ON_STACK
  4839. h->cabac.range = cc.range ;
  4840. h->cabac.low = cc.low ;
  4841. h->cabac.bytestream= cc.bytestream;
  4842. #endif
  4843. }
  4844. static inline void compute_mb_neighbors(H264Context *h)
  4845. {
  4846. MpegEncContext * const s = &h->s;
  4847. const int mb_xy = s->mb_x + s->mb_y*s->mb_stride;
  4848. h->top_mb_xy = mb_xy - s->mb_stride;
  4849. h->left_mb_xy[0] = mb_xy - 1;
  4850. if(FRAME_MBAFF){
  4851. const int pair_xy = s->mb_x + (s->mb_y & ~1)*s->mb_stride;
  4852. const int top_pair_xy = pair_xy - s->mb_stride;
  4853. const int top_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[top_pair_xy]);
  4854. const int left_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[pair_xy-1]);
  4855. const int curr_mb_frame_flag = !MB_FIELD;
  4856. const int bottom = (s->mb_y & 1);
  4857. if (bottom
  4858. ? !curr_mb_frame_flag // bottom macroblock
  4859. : (!curr_mb_frame_flag && !top_mb_frame_flag) // top macroblock
  4860. ) {
  4861. h->top_mb_xy -= s->mb_stride;
  4862. }
  4863. if (left_mb_frame_flag != curr_mb_frame_flag) {
  4864. h->left_mb_xy[0] = pair_xy - 1;
  4865. }
  4866. } else if (FIELD_PICTURE) {
  4867. h->top_mb_xy -= s->mb_stride;
  4868. }
  4869. return;
  4870. }
  4871. /**
  4872. * decodes a macroblock
  4873. * @returns 0 if ok, AC_ERROR / DC_ERROR / MV_ERROR if an error is noticed
  4874. */
  4875. static int decode_mb_cabac(H264Context *h) {
  4876. MpegEncContext * const s = &h->s;
  4877. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  4878. int mb_type, partition_count, cbp = 0;
  4879. int dct8x8_allowed= h->pps.transform_8x8_mode;
  4880. s->dsp.clear_blocks(h->mb); //FIXME avoid if already clear (move after skip handlong?)
  4881. tprintf(s->avctx, "pic:%d mb:%d/%d\n", h->frame_num, s->mb_x, s->mb_y);
  4882. if( h->slice_type != I_TYPE && h->slice_type != SI_TYPE ) {
  4883. int skip;
  4884. /* a skipped mb needs the aff flag from the following mb */
  4885. if( FRAME_MBAFF && s->mb_x==0 && (s->mb_y&1)==0 )
  4886. predict_field_decoding_flag(h);
  4887. if( FRAME_MBAFF && (s->mb_y&1)==1 && h->prev_mb_skipped )
  4888. skip = h->next_mb_skipped;
  4889. else
  4890. skip = decode_cabac_mb_skip( h, s->mb_x, s->mb_y );
  4891. /* read skip flags */
  4892. if( skip ) {
  4893. if( FRAME_MBAFF && (s->mb_y&1)==0 ){
  4894. s->current_picture.mb_type[mb_xy] = MB_TYPE_SKIP;
  4895. h->next_mb_skipped = decode_cabac_mb_skip( h, s->mb_x, s->mb_y+1 );
  4896. if(h->next_mb_skipped)
  4897. predict_field_decoding_flag(h);
  4898. else
  4899. h->mb_mbaff = h->mb_field_decoding_flag = decode_cabac_field_decoding_flag(h);
  4900. }
  4901. decode_mb_skip(h);
  4902. h->cbp_table[mb_xy] = 0;
  4903. h->chroma_pred_mode_table[mb_xy] = 0;
  4904. h->last_qscale_diff = 0;
  4905. return 0;
  4906. }
  4907. }
  4908. if(FRAME_MBAFF){
  4909. if( (s->mb_y&1) == 0 )
  4910. h->mb_mbaff =
  4911. h->mb_field_decoding_flag = decode_cabac_field_decoding_flag(h);
  4912. }else
  4913. h->mb_field_decoding_flag= (s->picture_structure!=PICT_FRAME);
  4914. h->prev_mb_skipped = 0;
  4915. compute_mb_neighbors(h);
  4916. if( ( mb_type = decode_cabac_mb_type( h ) ) < 0 ) {
  4917. av_log( h->s.avctx, AV_LOG_ERROR, "decode_cabac_mb_type failed\n" );
  4918. return -1;
  4919. }
  4920. if( h->slice_type == B_TYPE ) {
  4921. if( mb_type < 23 ){
  4922. partition_count= b_mb_type_info[mb_type].partition_count;
  4923. mb_type= b_mb_type_info[mb_type].type;
  4924. }else{
  4925. mb_type -= 23;
  4926. goto decode_intra_mb;
  4927. }
  4928. } else if( h->slice_type == P_TYPE ) {
  4929. if( mb_type < 5) {
  4930. partition_count= p_mb_type_info[mb_type].partition_count;
  4931. mb_type= p_mb_type_info[mb_type].type;
  4932. } else {
  4933. mb_type -= 5;
  4934. goto decode_intra_mb;
  4935. }
  4936. } else {
  4937. assert(h->slice_type == I_TYPE);
  4938. decode_intra_mb:
  4939. partition_count = 0;
  4940. cbp= i_mb_type_info[mb_type].cbp;
  4941. h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;
  4942. mb_type= i_mb_type_info[mb_type].type;
  4943. }
  4944. if(MB_FIELD)
  4945. mb_type |= MB_TYPE_INTERLACED;
  4946. h->slice_table[ mb_xy ]= h->slice_num;
  4947. if(IS_INTRA_PCM(mb_type)) {
  4948. const uint8_t *ptr;
  4949. unsigned int x, y;
  4950. // We assume these blocks are very rare so we do not optimize it.
  4951. // FIXME The two following lines get the bitstream position in the cabac
  4952. // decode, I think it should be done by a function in cabac.h (or cabac.c).
  4953. ptr= h->cabac.bytestream;
  4954. if(h->cabac.low&0x1) ptr--;
  4955. if(CABAC_BITS==16){
  4956. if(h->cabac.low&0x1FF) ptr--;
  4957. }
  4958. // The pixels are stored in the same order as levels in h->mb array.
  4959. for(y=0; y<16; y++){
  4960. const int index= 4*(y&3) + 32*((y>>2)&1) + 128*(y>>3);
  4961. for(x=0; x<16; x++){
  4962. tprintf(s->avctx, "LUMA ICPM LEVEL (%3d)\n", *ptr);
  4963. h->mb[index + (x&3) + 16*((x>>2)&1) + 64*(x>>3)]= *ptr++;
  4964. }
  4965. }
  4966. for(y=0; y<8; y++){
  4967. const int index= 256 + 4*(y&3) + 32*(y>>2);
  4968. for(x=0; x<8; x++){
  4969. tprintf(s->avctx, "CHROMA U ICPM LEVEL (%3d)\n", *ptr);
  4970. h->mb[index + (x&3) + 16*(x>>2)]= *ptr++;
  4971. }
  4972. }
  4973. for(y=0; y<8; y++){
  4974. const int index= 256 + 64 + 4*(y&3) + 32*(y>>2);
  4975. for(x=0; x<8; x++){
  4976. tprintf(s->avctx, "CHROMA V ICPM LEVEL (%3d)\n", *ptr);
  4977. h->mb[index + (x&3) + 16*(x>>2)]= *ptr++;
  4978. }
  4979. }
  4980. ff_init_cabac_decoder(&h->cabac, ptr, h->cabac.bytestream_end - ptr);
  4981. // All blocks are present
  4982. h->cbp_table[mb_xy] = 0x1ef;
  4983. h->chroma_pred_mode_table[mb_xy] = 0;
  4984. // In deblocking, the quantizer is 0
  4985. s->current_picture.qscale_table[mb_xy]= 0;
  4986. h->chroma_qp[0] = get_chroma_qp(h, 0, 0);
  4987. h->chroma_qp[1] = get_chroma_qp(h, 1, 0);
  4988. // All coeffs are present
  4989. memset(h->non_zero_count[mb_xy], 16, 16);
  4990. s->current_picture.mb_type[mb_xy]= mb_type;
  4991. return 0;
  4992. }
  4993. if(MB_MBAFF){
  4994. h->ref_count[0] <<= 1;
  4995. h->ref_count[1] <<= 1;
  4996. }
  4997. fill_caches(h, mb_type, 0);
  4998. if( IS_INTRA( mb_type ) ) {
  4999. int i, pred_mode;
  5000. if( IS_INTRA4x4( mb_type ) ) {
  5001. if( dct8x8_allowed && decode_cabac_mb_transform_size( h ) ) {
  5002. mb_type |= MB_TYPE_8x8DCT;
  5003. for( i = 0; i < 16; i+=4 ) {
  5004. int pred = pred_intra_mode( h, i );
  5005. int mode = decode_cabac_mb_intra4x4_pred_mode( h, pred );
  5006. fill_rectangle( &h->intra4x4_pred_mode_cache[ scan8[i] ], 2, 2, 8, mode, 1 );
  5007. }
  5008. } else {
  5009. for( i = 0; i < 16; i++ ) {
  5010. int pred = pred_intra_mode( h, i );
  5011. h->intra4x4_pred_mode_cache[ scan8[i] ] = decode_cabac_mb_intra4x4_pred_mode( h, pred );
  5012. //av_log( s->avctx, AV_LOG_ERROR, "i4x4 pred=%d mode=%d\n", pred, h->intra4x4_pred_mode_cache[ scan8[i] ] );
  5013. }
  5014. }
  5015. write_back_intra_pred_mode(h);
  5016. if( check_intra4x4_pred_mode(h) < 0 ) return -1;
  5017. } else {
  5018. h->intra16x16_pred_mode= check_intra_pred_mode( h, h->intra16x16_pred_mode );
  5019. if( h->intra16x16_pred_mode < 0 ) return -1;
  5020. }
  5021. h->chroma_pred_mode_table[mb_xy] =
  5022. pred_mode = decode_cabac_mb_chroma_pre_mode( h );
  5023. pred_mode= check_intra_pred_mode( h, pred_mode );
  5024. if( pred_mode < 0 ) return -1;
  5025. h->chroma_pred_mode= pred_mode;
  5026. } else if( partition_count == 4 ) {
  5027. int i, j, sub_partition_count[4], list, ref[2][4];
  5028. if( h->slice_type == B_TYPE ) {
  5029. for( i = 0; i < 4; i++ ) {
  5030. h->sub_mb_type[i] = decode_cabac_b_mb_sub_type( h );
  5031. sub_partition_count[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  5032. h->sub_mb_type[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  5033. }
  5034. if( IS_DIRECT(h->sub_mb_type[0] | h->sub_mb_type[1] |
  5035. h->sub_mb_type[2] | h->sub_mb_type[3]) ) {
  5036. pred_direct_motion(h, &mb_type);
  5037. h->ref_cache[0][scan8[4]] =
  5038. h->ref_cache[1][scan8[4]] =
  5039. h->ref_cache[0][scan8[12]] =
  5040. h->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;
  5041. if( h->ref_count[0] > 1 || h->ref_count[1] > 1 ) {
  5042. for( i = 0; i < 4; i++ )
  5043. if( IS_DIRECT(h->sub_mb_type[i]) )
  5044. fill_rectangle( &h->direct_cache[scan8[4*i]], 2, 2, 8, 1, 1 );
  5045. }
  5046. }
  5047. } else {
  5048. for( i = 0; i < 4; i++ ) {
  5049. h->sub_mb_type[i] = decode_cabac_p_mb_sub_type( h );
  5050. sub_partition_count[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  5051. h->sub_mb_type[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  5052. }
  5053. }
  5054. for( list = 0; list < h->list_count; list++ ) {
  5055. for( i = 0; i < 4; i++ ) {
  5056. if(IS_DIRECT(h->sub_mb_type[i])) continue;
  5057. if(IS_DIR(h->sub_mb_type[i], 0, list)){
  5058. if( h->ref_count[list] > 1 )
  5059. ref[list][i] = decode_cabac_mb_ref( h, list, 4*i );
  5060. else
  5061. ref[list][i] = 0;
  5062. } else {
  5063. ref[list][i] = -1;
  5064. }
  5065. h->ref_cache[list][ scan8[4*i]+1 ]=
  5066. h->ref_cache[list][ scan8[4*i]+8 ]=h->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];
  5067. }
  5068. }
  5069. if(dct8x8_allowed)
  5070. dct8x8_allowed = get_dct8x8_allowed(h);
  5071. for(list=0; list<h->list_count; list++){
  5072. for(i=0; i<4; i++){
  5073. h->ref_cache[list][ scan8[4*i] ]=h->ref_cache[list][ scan8[4*i]+1 ];
  5074. if(IS_DIRECT(h->sub_mb_type[i])){
  5075. fill_rectangle(h->mvd_cache[list][scan8[4*i]], 2, 2, 8, 0, 4);
  5076. continue;
  5077. }
  5078. if(IS_DIR(h->sub_mb_type[i], 0, list) && !IS_DIRECT(h->sub_mb_type[i])){
  5079. const int sub_mb_type= h->sub_mb_type[i];
  5080. const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;
  5081. for(j=0; j<sub_partition_count[i]; j++){
  5082. int mpx, mpy;
  5083. int mx, my;
  5084. const int index= 4*i + block_width*j;
  5085. int16_t (* mv_cache)[2]= &h->mv_cache[list][ scan8[index] ];
  5086. int16_t (* mvd_cache)[2]= &h->mvd_cache[list][ scan8[index] ];
  5087. pred_motion(h, index, block_width, list, h->ref_cache[list][ scan8[index] ], &mpx, &mpy);
  5088. mx = mpx + decode_cabac_mb_mvd( h, list, index, 0 );
  5089. my = mpy + decode_cabac_mb_mvd( h, list, index, 1 );
  5090. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5091. if(IS_SUB_8X8(sub_mb_type)){
  5092. mv_cache[ 1 ][0]=
  5093. mv_cache[ 8 ][0]= mv_cache[ 9 ][0]= mx;
  5094. mv_cache[ 1 ][1]=
  5095. mv_cache[ 8 ][1]= mv_cache[ 9 ][1]= my;
  5096. mvd_cache[ 1 ][0]=
  5097. mvd_cache[ 8 ][0]= mvd_cache[ 9 ][0]= mx - mpx;
  5098. mvd_cache[ 1 ][1]=
  5099. mvd_cache[ 8 ][1]= mvd_cache[ 9 ][1]= my - mpy;
  5100. }else if(IS_SUB_8X4(sub_mb_type)){
  5101. mv_cache[ 1 ][0]= mx;
  5102. mv_cache[ 1 ][1]= my;
  5103. mvd_cache[ 1 ][0]= mx - mpx;
  5104. mvd_cache[ 1 ][1]= my - mpy;
  5105. }else if(IS_SUB_4X8(sub_mb_type)){
  5106. mv_cache[ 8 ][0]= mx;
  5107. mv_cache[ 8 ][1]= my;
  5108. mvd_cache[ 8 ][0]= mx - mpx;
  5109. mvd_cache[ 8 ][1]= my - mpy;
  5110. }
  5111. mv_cache[ 0 ][0]= mx;
  5112. mv_cache[ 0 ][1]= my;
  5113. mvd_cache[ 0 ][0]= mx - mpx;
  5114. mvd_cache[ 0 ][1]= my - mpy;
  5115. }
  5116. }else{
  5117. uint32_t *p= (uint32_t *)&h->mv_cache[list][ scan8[4*i] ][0];
  5118. uint32_t *pd= (uint32_t *)&h->mvd_cache[list][ scan8[4*i] ][0];
  5119. p[0] = p[1] = p[8] = p[9] = 0;
  5120. pd[0]= pd[1]= pd[8]= pd[9]= 0;
  5121. }
  5122. }
  5123. }
  5124. } else if( IS_DIRECT(mb_type) ) {
  5125. pred_direct_motion(h, &mb_type);
  5126. fill_rectangle(h->mvd_cache[0][scan8[0]], 4, 4, 8, 0, 4);
  5127. fill_rectangle(h->mvd_cache[1][scan8[0]], 4, 4, 8, 0, 4);
  5128. dct8x8_allowed &= h->sps.direct_8x8_inference_flag;
  5129. } else {
  5130. int list, mx, my, i, mpx, mpy;
  5131. if(IS_16X16(mb_type)){
  5132. for(list=0; list<h->list_count; list++){
  5133. if(IS_DIR(mb_type, 0, list)){
  5134. const int ref = h->ref_count[list] > 1 ? decode_cabac_mb_ref( h, list, 0 ) : 0;
  5135. fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, ref, 1);
  5136. }else
  5137. 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
  5138. }
  5139. for(list=0; list<h->list_count; list++){
  5140. if(IS_DIR(mb_type, 0, list)){
  5141. pred_motion(h, 0, 4, list, h->ref_cache[list][ scan8[0] ], &mpx, &mpy);
  5142. mx = mpx + decode_cabac_mb_mvd( h, list, 0, 0 );
  5143. my = mpy + decode_cabac_mb_mvd( h, list, 0, 1 );
  5144. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5145. fill_rectangle(h->mvd_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx-mpx,my-mpy), 4);
  5146. fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx,my), 4);
  5147. }else
  5148. fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, 0, 4);
  5149. }
  5150. }
  5151. else if(IS_16X8(mb_type)){
  5152. for(list=0; list<h->list_count; list++){
  5153. for(i=0; i<2; i++){
  5154. if(IS_DIR(mb_type, i, list)){
  5155. const int ref= h->ref_count[list] > 1 ? decode_cabac_mb_ref( h, list, 8*i ) : 0;
  5156. fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, ref, 1);
  5157. }else
  5158. fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, (LIST_NOT_USED&0xFF), 1);
  5159. }
  5160. }
  5161. for(list=0; list<h->list_count; list++){
  5162. for(i=0; i<2; i++){
  5163. if(IS_DIR(mb_type, i, list)){
  5164. pred_16x8_motion(h, 8*i, list, h->ref_cache[list][scan8[0] + 16*i], &mpx, &mpy);
  5165. mx = mpx + decode_cabac_mb_mvd( h, list, 8*i, 0 );
  5166. my = mpy + decode_cabac_mb_mvd( h, list, 8*i, 1 );
  5167. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5168. fill_rectangle(h->mvd_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack16to32(mx-mpx,my-mpy), 4);
  5169. fill_rectangle(h->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack16to32(mx,my), 4);
  5170. }else{
  5171. fill_rectangle(h->mvd_cache[list][ scan8[0] + 16*i ], 4, 2, 8, 0, 4);
  5172. fill_rectangle(h-> mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, 0, 4);
  5173. }
  5174. }
  5175. }
  5176. }else{
  5177. assert(IS_8X16(mb_type));
  5178. for(list=0; list<h->list_count; list++){
  5179. for(i=0; i<2; i++){
  5180. if(IS_DIR(mb_type, i, list)){ //FIXME optimize
  5181. const int ref= h->ref_count[list] > 1 ? decode_cabac_mb_ref( h, list, 4*i ) : 0;
  5182. fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, ref, 1);
  5183. }else
  5184. fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, (LIST_NOT_USED&0xFF), 1);
  5185. }
  5186. }
  5187. for(list=0; list<h->list_count; list++){
  5188. for(i=0; i<2; i++){
  5189. if(IS_DIR(mb_type, i, list)){
  5190. pred_8x16_motion(h, i*4, list, h->ref_cache[list][ scan8[0] + 2*i ], &mpx, &mpy);
  5191. mx = mpx + decode_cabac_mb_mvd( h, list, 4*i, 0 );
  5192. my = mpy + decode_cabac_mb_mvd( h, list, 4*i, 1 );
  5193. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5194. fill_rectangle(h->mvd_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack16to32(mx-mpx,my-mpy), 4);
  5195. fill_rectangle(h->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack16to32(mx,my), 4);
  5196. }else{
  5197. fill_rectangle(h->mvd_cache[list][ scan8[0] + 2*i ], 2, 4, 8, 0, 4);
  5198. fill_rectangle(h-> mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, 0, 4);
  5199. }
  5200. }
  5201. }
  5202. }
  5203. }
  5204. if( IS_INTER( mb_type ) ) {
  5205. h->chroma_pred_mode_table[mb_xy] = 0;
  5206. write_back_motion( h, mb_type );
  5207. }
  5208. if( !IS_INTRA16x16( mb_type ) ) {
  5209. cbp = decode_cabac_mb_cbp_luma( h );
  5210. cbp |= decode_cabac_mb_cbp_chroma( h ) << 4;
  5211. }
  5212. h->cbp_table[mb_xy] = h->cbp = cbp;
  5213. if( dct8x8_allowed && (cbp&15) && !IS_INTRA( mb_type ) ) {
  5214. if( decode_cabac_mb_transform_size( h ) )
  5215. mb_type |= MB_TYPE_8x8DCT;
  5216. }
  5217. s->current_picture.mb_type[mb_xy]= mb_type;
  5218. if( cbp || IS_INTRA16x16( mb_type ) ) {
  5219. const uint8_t *scan, *scan8x8, *dc_scan;
  5220. const uint32_t *qmul;
  5221. int dqp;
  5222. if(IS_INTERLACED(mb_type)){
  5223. scan8x8= s->qscale ? h->field_scan8x8 : h->field_scan8x8_q0;
  5224. scan= s->qscale ? h->field_scan : h->field_scan_q0;
  5225. dc_scan= luma_dc_field_scan;
  5226. }else{
  5227. scan8x8= s->qscale ? h->zigzag_scan8x8 : h->zigzag_scan8x8_q0;
  5228. scan= s->qscale ? h->zigzag_scan : h->zigzag_scan_q0;
  5229. dc_scan= luma_dc_zigzag_scan;
  5230. }
  5231. h->last_qscale_diff = dqp = decode_cabac_mb_dqp( h );
  5232. if( dqp == INT_MIN ){
  5233. av_log(h->s.avctx, AV_LOG_ERROR, "cabac decode of qscale diff failed at %d %d\n", s->mb_x, s->mb_y);
  5234. return -1;
  5235. }
  5236. s->qscale += dqp;
  5237. if(((unsigned)s->qscale) > 51){
  5238. if(s->qscale<0) s->qscale+= 52;
  5239. else s->qscale-= 52;
  5240. }
  5241. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  5242. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  5243. if( IS_INTRA16x16( mb_type ) ) {
  5244. int i;
  5245. //av_log( s->avctx, AV_LOG_ERROR, "INTRA16x16 DC\n" );
  5246. decode_cabac_residual( h, h->mb, 0, 0, dc_scan, NULL, 16);
  5247. if( cbp&15 ) {
  5248. qmul = h->dequant4_coeff[0][s->qscale];
  5249. for( i = 0; i < 16; i++ ) {
  5250. //av_log( s->avctx, AV_LOG_ERROR, "INTRA16x16 AC:%d\n", i );
  5251. decode_cabac_residual(h, h->mb + 16*i, 1, i, scan + 1, qmul, 15);
  5252. }
  5253. } else {
  5254. fill_rectangle(&h->non_zero_count_cache[scan8[0]], 4, 4, 8, 0, 1);
  5255. }
  5256. } else {
  5257. int i8x8, i4x4;
  5258. for( i8x8 = 0; i8x8 < 4; i8x8++ ) {
  5259. if( cbp & (1<<i8x8) ) {
  5260. if( IS_8x8DCT(mb_type) ) {
  5261. decode_cabac_residual(h, h->mb + 64*i8x8, 5, 4*i8x8,
  5262. scan8x8, h->dequant8_coeff[IS_INTRA( mb_type ) ? 0:1][s->qscale], 64);
  5263. } else {
  5264. qmul = h->dequant4_coeff[IS_INTRA( mb_type ) ? 0:3][s->qscale];
  5265. for( i4x4 = 0; i4x4 < 4; i4x4++ ) {
  5266. const int index = 4*i8x8 + i4x4;
  5267. //av_log( s->avctx, AV_LOG_ERROR, "Luma4x4: %d\n", index );
  5268. //START_TIMER
  5269. decode_cabac_residual(h, h->mb + 16*index, 2, index, scan, qmul, 16);
  5270. //STOP_TIMER("decode_residual")
  5271. }
  5272. }
  5273. } else {
  5274. uint8_t * const nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
  5275. nnz[0] = nnz[1] = nnz[8] = nnz[9] = 0;
  5276. }
  5277. }
  5278. }
  5279. if( cbp&0x30 ){
  5280. int c;
  5281. for( c = 0; c < 2; c++ ) {
  5282. //av_log( s->avctx, AV_LOG_ERROR, "INTRA C%d-DC\n",c );
  5283. decode_cabac_residual(h, h->mb + 256 + 16*4*c, 3, c, chroma_dc_scan, NULL, 4);
  5284. }
  5285. }
  5286. if( cbp&0x20 ) {
  5287. int c, i;
  5288. for( c = 0; c < 2; c++ ) {
  5289. qmul = h->dequant4_coeff[c+1+(IS_INTRA( mb_type ) ? 0:3)][h->chroma_qp[c]];
  5290. for( i = 0; i < 4; i++ ) {
  5291. const int index = 16 + 4 * c + i;
  5292. //av_log( s->avctx, AV_LOG_ERROR, "INTRA C%d-AC %d\n",c, index - 16 );
  5293. decode_cabac_residual(h, h->mb + 16*index, 4, index - 16, scan + 1, qmul, 15);
  5294. }
  5295. }
  5296. } else {
  5297. uint8_t * const nnz= &h->non_zero_count_cache[0];
  5298. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  5299. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  5300. }
  5301. } else {
  5302. uint8_t * const nnz= &h->non_zero_count_cache[0];
  5303. fill_rectangle(&nnz[scan8[0]], 4, 4, 8, 0, 1);
  5304. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  5305. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  5306. h->last_qscale_diff = 0;
  5307. }
  5308. s->current_picture.qscale_table[mb_xy]= s->qscale;
  5309. write_back_non_zero_count(h);
  5310. if(MB_MBAFF){
  5311. h->ref_count[0] >>= 1;
  5312. h->ref_count[1] >>= 1;
  5313. }
  5314. return 0;
  5315. }
  5316. static void filter_mb_edgev( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5317. int i, d;
  5318. const int index_a = qp + h->slice_alpha_c0_offset;
  5319. const int alpha = (alpha_table+52)[index_a];
  5320. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5321. if( bS[0] < 4 ) {
  5322. int8_t tc[4];
  5323. for(i=0; i<4; i++)
  5324. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] : -1;
  5325. h->s.dsp.h264_h_loop_filter_luma(pix, stride, alpha, beta, tc);
  5326. } else {
  5327. /* 16px edge length, because bS=4 is triggered by being at
  5328. * the edge of an intra MB, so all 4 bS are the same */
  5329. for( d = 0; d < 16; d++ ) {
  5330. const int p0 = pix[-1];
  5331. const int p1 = pix[-2];
  5332. const int p2 = pix[-3];
  5333. const int q0 = pix[0];
  5334. const int q1 = pix[1];
  5335. const int q2 = pix[2];
  5336. if( FFABS( p0 - q0 ) < alpha &&
  5337. FFABS( p1 - p0 ) < beta &&
  5338. FFABS( q1 - q0 ) < beta ) {
  5339. if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){
  5340. if( FFABS( p2 - p0 ) < beta)
  5341. {
  5342. const int p3 = pix[-4];
  5343. /* p0', p1', p2' */
  5344. pix[-1] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;
  5345. pix[-2] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;
  5346. pix[-3] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;
  5347. } else {
  5348. /* p0' */
  5349. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5350. }
  5351. if( FFABS( q2 - q0 ) < beta)
  5352. {
  5353. const int q3 = pix[3];
  5354. /* q0', q1', q2' */
  5355. pix[0] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;
  5356. pix[1] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;
  5357. pix[2] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;
  5358. } else {
  5359. /* q0' */
  5360. pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5361. }
  5362. }else{
  5363. /* p0', q0' */
  5364. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5365. pix[ 0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5366. }
  5367. 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]);
  5368. }
  5369. pix += stride;
  5370. }
  5371. }
  5372. }
  5373. static void filter_mb_edgecv( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5374. int i;
  5375. const int index_a = qp + h->slice_alpha_c0_offset;
  5376. const int alpha = (alpha_table+52)[index_a];
  5377. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5378. if( bS[0] < 4 ) {
  5379. int8_t tc[4];
  5380. for(i=0; i<4; i++)
  5381. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] + 1 : 0;
  5382. h->s.dsp.h264_h_loop_filter_chroma(pix, stride, alpha, beta, tc);
  5383. } else {
  5384. h->s.dsp.h264_h_loop_filter_chroma_intra(pix, stride, alpha, beta);
  5385. }
  5386. }
  5387. static void filter_mb_mbaff_edgev( H264Context *h, uint8_t *pix, int stride, int16_t bS[8], int qp[2] ) {
  5388. int i;
  5389. for( i = 0; i < 16; i++, pix += stride) {
  5390. int index_a;
  5391. int alpha;
  5392. int beta;
  5393. int qp_index;
  5394. int bS_index = (i >> 1);
  5395. if (!MB_FIELD) {
  5396. bS_index &= ~1;
  5397. bS_index |= (i & 1);
  5398. }
  5399. if( bS[bS_index] == 0 ) {
  5400. continue;
  5401. }
  5402. qp_index = MB_FIELD ? (i >> 3) : (i & 1);
  5403. index_a = qp[qp_index] + h->slice_alpha_c0_offset;
  5404. alpha = (alpha_table+52)[index_a];
  5405. beta = (beta_table+52)[qp[qp_index] + h->slice_beta_offset];
  5406. if( bS[bS_index] < 4 ) {
  5407. const int tc0 = (tc0_table+52)[index_a][bS[bS_index] - 1];
  5408. const int p0 = pix[-1];
  5409. const int p1 = pix[-2];
  5410. const int p2 = pix[-3];
  5411. const int q0 = pix[0];
  5412. const int q1 = pix[1];
  5413. const int q2 = pix[2];
  5414. if( FFABS( p0 - q0 ) < alpha &&
  5415. FFABS( p1 - p0 ) < beta &&
  5416. FFABS( q1 - q0 ) < beta ) {
  5417. int tc = tc0;
  5418. int i_delta;
  5419. if( FFABS( p2 - p0 ) < beta ) {
  5420. pix[-2] = p1 + av_clip( ( p2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( p1 << 1 ) ) >> 1, -tc0, tc0 );
  5421. tc++;
  5422. }
  5423. if( FFABS( q2 - q0 ) < beta ) {
  5424. pix[1] = q1 + av_clip( ( q2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( q1 << 1 ) ) >> 1, -tc0, tc0 );
  5425. tc++;
  5426. }
  5427. i_delta = av_clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );
  5428. pix[-1] = av_clip_uint8( p0 + i_delta ); /* p0' */
  5429. pix[0] = av_clip_uint8( q0 - i_delta ); /* q0' */
  5430. 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);
  5431. }
  5432. }else{
  5433. const int p0 = pix[-1];
  5434. const int p1 = pix[-2];
  5435. const int p2 = pix[-3];
  5436. const int q0 = pix[0];
  5437. const int q1 = pix[1];
  5438. const int q2 = pix[2];
  5439. if( FFABS( p0 - q0 ) < alpha &&
  5440. FFABS( p1 - p0 ) < beta &&
  5441. FFABS( q1 - q0 ) < beta ) {
  5442. if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){
  5443. if( FFABS( p2 - p0 ) < beta)
  5444. {
  5445. const int p3 = pix[-4];
  5446. /* p0', p1', p2' */
  5447. pix[-1] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;
  5448. pix[-2] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;
  5449. pix[-3] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;
  5450. } else {
  5451. /* p0' */
  5452. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5453. }
  5454. if( FFABS( q2 - q0 ) < beta)
  5455. {
  5456. const int q3 = pix[3];
  5457. /* q0', q1', q2' */
  5458. pix[0] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;
  5459. pix[1] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;
  5460. pix[2] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;
  5461. } else {
  5462. /* q0' */
  5463. pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5464. }
  5465. }else{
  5466. /* p0', q0' */
  5467. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5468. pix[ 0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5469. }
  5470. 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]);
  5471. }
  5472. }
  5473. }
  5474. }
  5475. static void filter_mb_mbaff_edgecv( H264Context *h, uint8_t *pix, int stride, int16_t bS[8], int qp[2] ) {
  5476. int i;
  5477. for( i = 0; i < 8; i++, pix += stride) {
  5478. int index_a;
  5479. int alpha;
  5480. int beta;
  5481. int qp_index;
  5482. int bS_index = i;
  5483. if( bS[bS_index] == 0 ) {
  5484. continue;
  5485. }
  5486. qp_index = MB_FIELD ? (i >> 2) : (i & 1);
  5487. index_a = qp[qp_index] + h->slice_alpha_c0_offset;
  5488. alpha = (alpha_table+52)[index_a];
  5489. beta = (beta_table+52)[qp[qp_index] + h->slice_beta_offset];
  5490. if( bS[bS_index] < 4 ) {
  5491. const int tc = (tc0_table+52)[index_a][bS[bS_index] - 1] + 1;
  5492. const int p0 = pix[-1];
  5493. const int p1 = pix[-2];
  5494. const int q0 = pix[0];
  5495. const int q1 = pix[1];
  5496. if( FFABS( p0 - q0 ) < alpha &&
  5497. FFABS( p1 - p0 ) < beta &&
  5498. FFABS( q1 - q0 ) < beta ) {
  5499. const int i_delta = av_clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );
  5500. pix[-1] = av_clip_uint8( p0 + i_delta ); /* p0' */
  5501. pix[0] = av_clip_uint8( q0 - i_delta ); /* q0' */
  5502. 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);
  5503. }
  5504. }else{
  5505. const int p0 = pix[-1];
  5506. const int p1 = pix[-2];
  5507. const int q0 = pix[0];
  5508. const int q1 = pix[1];
  5509. if( FFABS( p0 - q0 ) < alpha &&
  5510. FFABS( p1 - p0 ) < beta &&
  5511. FFABS( q1 - q0 ) < beta ) {
  5512. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2; /* p0' */
  5513. pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2; /* q0' */
  5514. 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]);
  5515. }
  5516. }
  5517. }
  5518. }
  5519. static void filter_mb_edgeh( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5520. int i, d;
  5521. const int index_a = qp + h->slice_alpha_c0_offset;
  5522. const int alpha = (alpha_table+52)[index_a];
  5523. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5524. const int pix_next = stride;
  5525. if( bS[0] < 4 ) {
  5526. int8_t tc[4];
  5527. for(i=0; i<4; i++)
  5528. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] : -1;
  5529. h->s.dsp.h264_v_loop_filter_luma(pix, stride, alpha, beta, tc);
  5530. } else {
  5531. /* 16px edge length, see filter_mb_edgev */
  5532. for( d = 0; d < 16; d++ ) {
  5533. const int p0 = pix[-1*pix_next];
  5534. const int p1 = pix[-2*pix_next];
  5535. const int p2 = pix[-3*pix_next];
  5536. const int q0 = pix[0];
  5537. const int q1 = pix[1*pix_next];
  5538. const int q2 = pix[2*pix_next];
  5539. if( FFABS( p0 - q0 ) < alpha &&
  5540. FFABS( p1 - p0 ) < beta &&
  5541. FFABS( q1 - q0 ) < beta ) {
  5542. const int p3 = pix[-4*pix_next];
  5543. const int q3 = pix[ 3*pix_next];
  5544. if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){
  5545. if( FFABS( p2 - p0 ) < beta) {
  5546. /* p0', p1', p2' */
  5547. pix[-1*pix_next] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;
  5548. pix[-2*pix_next] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;
  5549. pix[-3*pix_next] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;
  5550. } else {
  5551. /* p0' */
  5552. pix[-1*pix_next] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5553. }
  5554. if( FFABS( q2 - q0 ) < beta) {
  5555. /* q0', q1', q2' */
  5556. pix[0*pix_next] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;
  5557. pix[1*pix_next] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;
  5558. pix[2*pix_next] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;
  5559. } else {
  5560. /* q0' */
  5561. pix[0*pix_next] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5562. }
  5563. }else{
  5564. /* p0', q0' */
  5565. pix[-1*pix_next] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5566. pix[ 0*pix_next] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5567. }
  5568. 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]);
  5569. }
  5570. pix++;
  5571. }
  5572. }
  5573. }
  5574. static void filter_mb_edgech( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5575. int i;
  5576. const int index_a = qp + h->slice_alpha_c0_offset;
  5577. const int alpha = (alpha_table+52)[index_a];
  5578. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5579. if( bS[0] < 4 ) {
  5580. int8_t tc[4];
  5581. for(i=0; i<4; i++)
  5582. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] + 1 : 0;
  5583. h->s.dsp.h264_v_loop_filter_chroma(pix, stride, alpha, beta, tc);
  5584. } else {
  5585. h->s.dsp.h264_v_loop_filter_chroma_intra(pix, stride, alpha, beta);
  5586. }
  5587. }
  5588. 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) {
  5589. MpegEncContext * const s = &h->s;
  5590. int mb_y_firstrow = s->picture_structure == PICT_BOTTOM_FIELD;
  5591. int mb_xy, mb_type;
  5592. int qp, qp0, qp1, qpc, qpc0, qpc1, qp_thresh;
  5593. mb_xy = mb_x + mb_y*s->mb_stride;
  5594. if(mb_x==0 || mb_y==mb_y_firstrow || !s->dsp.h264_loop_filter_strength || h->pps.chroma_qp_diff ||
  5595. (h->deblocking_filter == 2 && (h->slice_table[mb_xy] != h->slice_table[h->top_mb_xy] ||
  5596. h->slice_table[mb_xy] != h->slice_table[mb_xy - 1]))) {
  5597. filter_mb(h, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize);
  5598. return;
  5599. }
  5600. assert(!FRAME_MBAFF);
  5601. mb_type = s->current_picture.mb_type[mb_xy];
  5602. qp = s->current_picture.qscale_table[mb_xy];
  5603. qp0 = s->current_picture.qscale_table[mb_xy-1];
  5604. qp1 = s->current_picture.qscale_table[h->top_mb_xy];
  5605. qpc = get_chroma_qp( h, 0, qp );
  5606. qpc0 = get_chroma_qp( h, 0, qp0 );
  5607. qpc1 = get_chroma_qp( h, 0, qp1 );
  5608. qp0 = (qp + qp0 + 1) >> 1;
  5609. qp1 = (qp + qp1 + 1) >> 1;
  5610. qpc0 = (qpc + qpc0 + 1) >> 1;
  5611. qpc1 = (qpc + qpc1 + 1) >> 1;
  5612. qp_thresh = 15 - h->slice_alpha_c0_offset;
  5613. if(qp <= qp_thresh && qp0 <= qp_thresh && qp1 <= qp_thresh &&
  5614. qpc <= qp_thresh && qpc0 <= qp_thresh && qpc1 <= qp_thresh)
  5615. return;
  5616. if( IS_INTRA(mb_type) ) {
  5617. int16_t bS4[4] = {4,4,4,4};
  5618. int16_t bS3[4] = {3,3,3,3};
  5619. int16_t *bSH = FIELD_PICTURE ? bS3 : bS4;
  5620. if( IS_8x8DCT(mb_type) ) {
  5621. filter_mb_edgev( h, &img_y[4*0], linesize, bS4, qp0 );
  5622. filter_mb_edgev( h, &img_y[4*2], linesize, bS3, qp );
  5623. filter_mb_edgeh( h, &img_y[4*0*linesize], linesize, bSH, qp1 );
  5624. filter_mb_edgeh( h, &img_y[4*2*linesize], linesize, bS3, qp );
  5625. } else {
  5626. filter_mb_edgev( h, &img_y[4*0], linesize, bS4, qp0 );
  5627. filter_mb_edgev( h, &img_y[4*1], linesize, bS3, qp );
  5628. filter_mb_edgev( h, &img_y[4*2], linesize, bS3, qp );
  5629. filter_mb_edgev( h, &img_y[4*3], linesize, bS3, qp );
  5630. filter_mb_edgeh( h, &img_y[4*0*linesize], linesize, bSH, qp1 );
  5631. filter_mb_edgeh( h, &img_y[4*1*linesize], linesize, bS3, qp );
  5632. filter_mb_edgeh( h, &img_y[4*2*linesize], linesize, bS3, qp );
  5633. filter_mb_edgeh( h, &img_y[4*3*linesize], linesize, bS3, qp );
  5634. }
  5635. filter_mb_edgecv( h, &img_cb[2*0], uvlinesize, bS4, qpc0 );
  5636. filter_mb_edgecv( h, &img_cb[2*2], uvlinesize, bS3, qpc );
  5637. filter_mb_edgecv( h, &img_cr[2*0], uvlinesize, bS4, qpc0 );
  5638. filter_mb_edgecv( h, &img_cr[2*2], uvlinesize, bS3, qpc );
  5639. filter_mb_edgech( h, &img_cb[2*0*uvlinesize], uvlinesize, bSH, qpc1 );
  5640. filter_mb_edgech( h, &img_cb[2*2*uvlinesize], uvlinesize, bS3, qpc );
  5641. filter_mb_edgech( h, &img_cr[2*0*uvlinesize], uvlinesize, bSH, qpc1 );
  5642. filter_mb_edgech( h, &img_cr[2*2*uvlinesize], uvlinesize, bS3, qpc );
  5643. return;
  5644. } else {
  5645. DECLARE_ALIGNED_8(int16_t, bS[2][4][4]);
  5646. uint64_t (*bSv)[4] = (uint64_t(*)[4])bS;
  5647. int edges;
  5648. if( IS_8x8DCT(mb_type) && (h->cbp&7) == 7 ) {
  5649. edges = 4;
  5650. bSv[0][0] = bSv[0][2] = bSv[1][0] = bSv[1][2] = 0x0002000200020002ULL;
  5651. } else {
  5652. int mask_edge1 = (mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16)) ? 3 :
  5653. (mb_type & MB_TYPE_16x8) ? 1 : 0;
  5654. int mask_edge0 = (mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16))
  5655. && (s->current_picture.mb_type[mb_xy-1] & (MB_TYPE_16x16 | MB_TYPE_8x16))
  5656. ? 3 : 0;
  5657. int step = IS_8x8DCT(mb_type) ? 2 : 1;
  5658. edges = (mb_type & MB_TYPE_16x16) && !(h->cbp & 15) ? 1 : 4;
  5659. s->dsp.h264_loop_filter_strength( bS, h->non_zero_count_cache, h->ref_cache, h->mv_cache,
  5660. (h->slice_type == B_TYPE), edges, step, mask_edge0, mask_edge1 );
  5661. }
  5662. if( IS_INTRA(s->current_picture.mb_type[mb_xy-1]) )
  5663. bSv[0][0] = 0x0004000400040004ULL;
  5664. if( IS_INTRA(s->current_picture.mb_type[h->top_mb_xy]) )
  5665. bSv[1][0] = FIELD_PICTURE ? 0x0003000300030003ULL : 0x0004000400040004ULL;
  5666. #define FILTER(hv,dir,edge)\
  5667. if(bSv[dir][edge]) {\
  5668. filter_mb_edge##hv( h, &img_y[4*edge*(dir?linesize:1)], linesize, bS[dir][edge], edge ? qp : qp##dir );\
  5669. if(!(edge&1)) {\
  5670. filter_mb_edgec##hv( h, &img_cb[2*edge*(dir?uvlinesize:1)], uvlinesize, bS[dir][edge], edge ? qpc : qpc##dir );\
  5671. filter_mb_edgec##hv( h, &img_cr[2*edge*(dir?uvlinesize:1)], uvlinesize, bS[dir][edge], edge ? qpc : qpc##dir );\
  5672. }\
  5673. }
  5674. if( edges == 1 ) {
  5675. FILTER(v,0,0);
  5676. FILTER(h,1,0);
  5677. } else if( IS_8x8DCT(mb_type) ) {
  5678. FILTER(v,0,0);
  5679. FILTER(v,0,2);
  5680. FILTER(h,1,0);
  5681. FILTER(h,1,2);
  5682. } else {
  5683. FILTER(v,0,0);
  5684. FILTER(v,0,1);
  5685. FILTER(v,0,2);
  5686. FILTER(v,0,3);
  5687. FILTER(h,1,0);
  5688. FILTER(h,1,1);
  5689. FILTER(h,1,2);
  5690. FILTER(h,1,3);
  5691. }
  5692. #undef FILTER
  5693. }
  5694. }
  5695. 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) {
  5696. MpegEncContext * const s = &h->s;
  5697. const int mb_xy= mb_x + mb_y*s->mb_stride;
  5698. const int mb_type = s->current_picture.mb_type[mb_xy];
  5699. const int mvy_limit = IS_INTERLACED(mb_type) ? 2 : 4;
  5700. int first_vertical_edge_done = 0;
  5701. int dir;
  5702. /* FIXME: A given frame may occupy more than one position in
  5703. * the reference list. So ref2frm should be populated with
  5704. * frame numbers, not indices. */
  5705. static const int ref2frm[34] = {-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
  5706. 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
  5707. //for sufficiently low qp, filtering wouldn't do anything
  5708. //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
  5709. if(!FRAME_MBAFF){
  5710. 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]));
  5711. int qp = s->current_picture.qscale_table[mb_xy];
  5712. if(qp <= qp_thresh
  5713. && (mb_x == 0 || ((qp + s->current_picture.qscale_table[mb_xy-1] + 1)>>1) <= qp_thresh)
  5714. && (mb_y == 0 || ((qp + s->current_picture.qscale_table[h->top_mb_xy] + 1)>>1) <= qp_thresh)){
  5715. return;
  5716. }
  5717. }
  5718. if (FRAME_MBAFF
  5719. // left mb is in picture
  5720. && h->slice_table[mb_xy-1] != 255
  5721. // and current and left pair do not have the same interlaced type
  5722. && (IS_INTERLACED(mb_type) != IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]))
  5723. // and left mb is in the same slice if deblocking_filter == 2
  5724. && (h->deblocking_filter!=2 || h->slice_table[mb_xy-1] == h->slice_table[mb_xy])) {
  5725. /* First vertical edge is different in MBAFF frames
  5726. * There are 8 different bS to compute and 2 different Qp
  5727. */
  5728. const int pair_xy = mb_x + (mb_y&~1)*s->mb_stride;
  5729. const int left_mb_xy[2] = { pair_xy-1, pair_xy-1+s->mb_stride };
  5730. int16_t bS[8];
  5731. int qp[2];
  5732. int bqp[2];
  5733. int rqp[2];
  5734. int mb_qp, mbn0_qp, mbn1_qp;
  5735. int i;
  5736. first_vertical_edge_done = 1;
  5737. if( IS_INTRA(mb_type) )
  5738. bS[0] = bS[1] = bS[2] = bS[3] = bS[4] = bS[5] = bS[6] = bS[7] = 4;
  5739. else {
  5740. for( i = 0; i < 8; i++ ) {
  5741. int mbn_xy = MB_FIELD ? left_mb_xy[i>>2] : left_mb_xy[i&1];
  5742. if( IS_INTRA( s->current_picture.mb_type[mbn_xy] ) )
  5743. bS[i] = 4;
  5744. else if( h->non_zero_count_cache[12+8*(i>>1)] != 0 ||
  5745. /* FIXME: with 8x8dct + cavlc, should check cbp instead of nnz */
  5746. h->non_zero_count[mbn_xy][MB_FIELD ? i&3 : (i>>2)+(mb_y&1)*2] )
  5747. bS[i] = 2;
  5748. else
  5749. bS[i] = 1;
  5750. }
  5751. }
  5752. mb_qp = s->current_picture.qscale_table[mb_xy];
  5753. mbn0_qp = s->current_picture.qscale_table[left_mb_xy[0]];
  5754. mbn1_qp = s->current_picture.qscale_table[left_mb_xy[1]];
  5755. qp[0] = ( mb_qp + mbn0_qp + 1 ) >> 1;
  5756. bqp[0] = ( get_chroma_qp( h, 0, mb_qp ) +
  5757. get_chroma_qp( h, 0, mbn0_qp ) + 1 ) >> 1;
  5758. rqp[0] = ( get_chroma_qp( h, 1, mb_qp ) +
  5759. get_chroma_qp( h, 1, mbn0_qp ) + 1 ) >> 1;
  5760. qp[1] = ( mb_qp + mbn1_qp + 1 ) >> 1;
  5761. bqp[1] = ( get_chroma_qp( h, 0, mb_qp ) +
  5762. get_chroma_qp( h, 0, mbn1_qp ) + 1 ) >> 1;
  5763. rqp[1] = ( get_chroma_qp( h, 1, mb_qp ) +
  5764. get_chroma_qp( h, 1, mbn1_qp ) + 1 ) >> 1;
  5765. /* Filter edge */
  5766. 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);
  5767. { int i; for (i = 0; i < 8; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
  5768. filter_mb_mbaff_edgev ( h, &img_y [0], linesize, bS, qp );
  5769. filter_mb_mbaff_edgecv( h, &img_cb[0], uvlinesize, bS, bqp );
  5770. filter_mb_mbaff_edgecv( h, &img_cr[0], uvlinesize, bS, rqp );
  5771. }
  5772. /* dir : 0 -> vertical edge, 1 -> horizontal edge */
  5773. for( dir = 0; dir < 2; dir++ )
  5774. {
  5775. int edge;
  5776. const int mbm_xy = dir == 0 ? mb_xy -1 : h->top_mb_xy;
  5777. const int mbm_type = s->current_picture.mb_type[mbm_xy];
  5778. int start = h->slice_table[mbm_xy] == 255 ? 1 : 0;
  5779. const int edges = (mb_type & (MB_TYPE_16x16|MB_TYPE_SKIP))
  5780. == (MB_TYPE_16x16|MB_TYPE_SKIP) ? 1 : 4;
  5781. // how often to recheck mv-based bS when iterating between edges
  5782. const int mask_edge = (mb_type & (MB_TYPE_16x16 | (MB_TYPE_16x8 << dir))) ? 3 :
  5783. (mb_type & (MB_TYPE_8x16 >> dir)) ? 1 : 0;
  5784. // how often to recheck mv-based bS when iterating along each edge
  5785. const int mask_par0 = mb_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir));
  5786. if (first_vertical_edge_done) {
  5787. start = 1;
  5788. first_vertical_edge_done = 0;
  5789. }
  5790. if (h->deblocking_filter==2 && h->slice_table[mbm_xy] != h->slice_table[mb_xy])
  5791. start = 1;
  5792. if (FRAME_MBAFF && (dir == 1) && ((mb_y&1) == 0) && start == 0
  5793. && !IS_INTERLACED(mb_type)
  5794. && IS_INTERLACED(mbm_type)
  5795. ) {
  5796. // This is a special case in the norm where the filtering must
  5797. // be done twice (one each of the field) even if we are in a
  5798. // frame macroblock.
  5799. //
  5800. static const int nnz_idx[4] = {4,5,6,3};
  5801. unsigned int tmp_linesize = 2 * linesize;
  5802. unsigned int tmp_uvlinesize = 2 * uvlinesize;
  5803. int mbn_xy = mb_xy - 2 * s->mb_stride;
  5804. int qp;
  5805. int i, j;
  5806. int16_t bS[4];
  5807. for(j=0; j<2; j++, mbn_xy += s->mb_stride){
  5808. if( IS_INTRA(mb_type) ||
  5809. IS_INTRA(s->current_picture.mb_type[mbn_xy]) ) {
  5810. bS[0] = bS[1] = bS[2] = bS[3] = 3;
  5811. } else {
  5812. const uint8_t *mbn_nnz = h->non_zero_count[mbn_xy];
  5813. for( i = 0; i < 4; i++ ) {
  5814. if( h->non_zero_count_cache[scan8[0]+i] != 0 ||
  5815. mbn_nnz[nnz_idx[i]] != 0 )
  5816. bS[i] = 2;
  5817. else
  5818. bS[i] = 1;
  5819. }
  5820. }
  5821. // Do not use s->qscale as luma quantizer because it has not the same
  5822. // value in IPCM macroblocks.
  5823. qp = ( s->current_picture.qscale_table[mb_xy] + s->current_picture.qscale_table[mbn_xy] + 1 ) >> 1;
  5824. 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);
  5825. { int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
  5826. filter_mb_edgeh( h, &img_y[j*linesize], tmp_linesize, bS, qp );
  5827. filter_mb_edgech( h, &img_cb[j*uvlinesize], tmp_uvlinesize, bS,
  5828. ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5829. filter_mb_edgech( h, &img_cr[j*uvlinesize], tmp_uvlinesize, bS,
  5830. ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5831. }
  5832. start = 1;
  5833. }
  5834. /* Calculate bS */
  5835. for( edge = start; edge < edges; edge++ ) {
  5836. /* mbn_xy: neighbor macroblock */
  5837. const int mbn_xy = edge > 0 ? mb_xy : mbm_xy;
  5838. const int mbn_type = s->current_picture.mb_type[mbn_xy];
  5839. int16_t bS[4];
  5840. int qp;
  5841. if( (edge&1) && IS_8x8DCT(mb_type) )
  5842. continue;
  5843. if( IS_INTRA(mb_type) ||
  5844. IS_INTRA(mbn_type) ) {
  5845. int value;
  5846. if (edge == 0) {
  5847. if ( (!IS_INTERLACED(mb_type) && !IS_INTERLACED(mbm_type))
  5848. || ((FRAME_MBAFF || (s->picture_structure != PICT_FRAME)) && (dir == 0))
  5849. ) {
  5850. value = 4;
  5851. } else {
  5852. value = 3;
  5853. }
  5854. } else {
  5855. value = 3;
  5856. }
  5857. bS[0] = bS[1] = bS[2] = bS[3] = value;
  5858. } else {
  5859. int i, l;
  5860. int mv_done;
  5861. if( edge & mask_edge ) {
  5862. bS[0] = bS[1] = bS[2] = bS[3] = 0;
  5863. mv_done = 1;
  5864. }
  5865. else if( FRAME_MBAFF && IS_INTERLACED(mb_type ^ mbn_type)) {
  5866. bS[0] = bS[1] = bS[2] = bS[3] = 1;
  5867. mv_done = 1;
  5868. }
  5869. else if( mask_par0 && (edge || (mbn_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir)))) ) {
  5870. int b_idx= 8 + 4 + edge * (dir ? 8:1);
  5871. int bn_idx= b_idx - (dir ? 8:1);
  5872. int v = 0;
  5873. for( l = 0; !v && l < 1 + (h->slice_type == B_TYPE); l++ ) {
  5874. v |= ref2frm[h->ref_cache[l][b_idx]+2] != ref2frm[h->ref_cache[l][bn_idx]+2] ||
  5875. FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[l][bn_idx][0] ) >= 4 ||
  5876. FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[l][bn_idx][1] ) >= mvy_limit;
  5877. }
  5878. bS[0] = bS[1] = bS[2] = bS[3] = v;
  5879. mv_done = 1;
  5880. }
  5881. else
  5882. mv_done = 0;
  5883. for( i = 0; i < 4; i++ ) {
  5884. int x = dir == 0 ? edge : i;
  5885. int y = dir == 0 ? i : edge;
  5886. int b_idx= 8 + 4 + x + 8*y;
  5887. int bn_idx= b_idx - (dir ? 8:1);
  5888. if( h->non_zero_count_cache[b_idx] != 0 ||
  5889. h->non_zero_count_cache[bn_idx] != 0 ) {
  5890. bS[i] = 2;
  5891. }
  5892. else if(!mv_done)
  5893. {
  5894. bS[i] = 0;
  5895. for( l = 0; l < 1 + (h->slice_type == B_TYPE); l++ ) {
  5896. if( ref2frm[h->ref_cache[l][b_idx]+2] != ref2frm[h->ref_cache[l][bn_idx]+2] ||
  5897. FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[l][bn_idx][0] ) >= 4 ||
  5898. FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[l][bn_idx][1] ) >= mvy_limit ) {
  5899. bS[i] = 1;
  5900. break;
  5901. }
  5902. }
  5903. }
  5904. }
  5905. if(bS[0]+bS[1]+bS[2]+bS[3] == 0)
  5906. continue;
  5907. }
  5908. /* Filter edge */
  5909. // Do not use s->qscale as luma quantizer because it has not the same
  5910. // value in IPCM macroblocks.
  5911. qp = ( s->current_picture.qscale_table[mb_xy] + s->current_picture.qscale_table[mbn_xy] + 1 ) >> 1;
  5912. //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]);
  5913. 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);
  5914. { int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
  5915. if( dir == 0 ) {
  5916. filter_mb_edgev( h, &img_y[4*edge], linesize, bS, qp );
  5917. if( (edge&1) == 0 ) {
  5918. filter_mb_edgecv( h, &img_cb[2*edge], uvlinesize, bS,
  5919. ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5920. filter_mb_edgecv( h, &img_cr[2*edge], uvlinesize, bS,
  5921. ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5922. }
  5923. } else {
  5924. filter_mb_edgeh( h, &img_y[4*edge*linesize], linesize, bS, qp );
  5925. if( (edge&1) == 0 ) {
  5926. filter_mb_edgech( h, &img_cb[2*edge*uvlinesize], uvlinesize, bS,
  5927. ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5928. filter_mb_edgech( h, &img_cr[2*edge*uvlinesize], uvlinesize, bS,
  5929. ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5930. }
  5931. }
  5932. }
  5933. }
  5934. }
  5935. static int decode_slice(struct AVCodecContext *avctx, H264Context *h){
  5936. MpegEncContext * const s = &h->s;
  5937. const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;
  5938. s->mb_skip_run= -1;
  5939. if( h->pps.cabac ) {
  5940. int i;
  5941. /* realign */
  5942. align_get_bits( &s->gb );
  5943. /* init cabac */
  5944. ff_init_cabac_states( &h->cabac);
  5945. ff_init_cabac_decoder( &h->cabac,
  5946. s->gb.buffer + get_bits_count(&s->gb)/8,
  5947. ( s->gb.size_in_bits - get_bits_count(&s->gb) + 7)/8);
  5948. /* calculate pre-state */
  5949. for( i= 0; i < 460; i++ ) {
  5950. int pre;
  5951. if( h->slice_type == I_TYPE )
  5952. pre = av_clip( ((cabac_context_init_I[i][0] * s->qscale) >>4 ) + cabac_context_init_I[i][1], 1, 126 );
  5953. else
  5954. 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 );
  5955. if( pre <= 63 )
  5956. h->cabac_state[i] = 2 * ( 63 - pre ) + 0;
  5957. else
  5958. h->cabac_state[i] = 2 * ( pre - 64 ) + 1;
  5959. }
  5960. for(;;){
  5961. //START_TIMER
  5962. int ret = decode_mb_cabac(h);
  5963. int eos;
  5964. //STOP_TIMER("decode_mb_cabac")
  5965. if(ret>=0) hl_decode_mb(h);
  5966. if( ret >= 0 && FRAME_MBAFF ) { //FIXME optimal? or let mb_decode decode 16x32 ?
  5967. s->mb_y++;
  5968. if(ret>=0) ret = decode_mb_cabac(h);
  5969. if(ret>=0) hl_decode_mb(h);
  5970. s->mb_y--;
  5971. }
  5972. eos = get_cabac_terminate( &h->cabac );
  5973. if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  5974. 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);
  5975. 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);
  5976. return -1;
  5977. }
  5978. if( ++s->mb_x >= s->mb_width ) {
  5979. s->mb_x = 0;
  5980. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  5981. ++s->mb_y;
  5982. if(FIELD_OR_MBAFF_PICTURE) {
  5983. ++s->mb_y;
  5984. }
  5985. }
  5986. if( eos || s->mb_y >= s->mb_height ) {
  5987. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  5988. 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);
  5989. return 0;
  5990. }
  5991. }
  5992. } else {
  5993. for(;;){
  5994. int ret = decode_mb_cavlc(h);
  5995. if(ret>=0) hl_decode_mb(h);
  5996. if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
  5997. s->mb_y++;
  5998. ret = decode_mb_cavlc(h);
  5999. if(ret>=0) hl_decode_mb(h);
  6000. s->mb_y--;
  6001. }
  6002. if(ret<0){
  6003. av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  6004. 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);
  6005. return -1;
  6006. }
  6007. if(++s->mb_x >= s->mb_width){
  6008. s->mb_x=0;
  6009. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  6010. ++s->mb_y;
  6011. if(FIELD_OR_MBAFF_PICTURE) {
  6012. ++s->mb_y;
  6013. }
  6014. if(s->mb_y >= s->mb_height){
  6015. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  6016. if(get_bits_count(&s->gb) == s->gb.size_in_bits ) {
  6017. 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);
  6018. return 0;
  6019. }else{
  6020. 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);
  6021. return -1;
  6022. }
  6023. }
  6024. }
  6025. if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
  6026. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  6027. if(get_bits_count(&s->gb) == s->gb.size_in_bits ){
  6028. 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);
  6029. return 0;
  6030. }else{
  6031. 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);
  6032. return -1;
  6033. }
  6034. }
  6035. }
  6036. }
  6037. #if 0
  6038. for(;s->mb_y < s->mb_height; s->mb_y++){
  6039. for(;s->mb_x < s->mb_width; s->mb_x++){
  6040. int ret= decode_mb(h);
  6041. hl_decode_mb(h);
  6042. if(ret<0){
  6043. av_log(s->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  6044. 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);
  6045. return -1;
  6046. }
  6047. if(++s->mb_x >= s->mb_width){
  6048. s->mb_x=0;
  6049. if(++s->mb_y >= s->mb_height){
  6050. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  6051. 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);
  6052. return 0;
  6053. }else{
  6054. 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);
  6055. return -1;
  6056. }
  6057. }
  6058. }
  6059. if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){
  6060. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  6061. 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);
  6062. return 0;
  6063. }else{
  6064. 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);
  6065. return -1;
  6066. }
  6067. }
  6068. }
  6069. s->mb_x=0;
  6070. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  6071. }
  6072. #endif
  6073. return -1; //not reached
  6074. }
  6075. static int decode_unregistered_user_data(H264Context *h, int size){
  6076. MpegEncContext * const s = &h->s;
  6077. uint8_t user_data[16+256];
  6078. int e, build, i;
  6079. if(size<16)
  6080. return -1;
  6081. for(i=0; i<sizeof(user_data)-1 && i<size; i++){
  6082. user_data[i]= get_bits(&s->gb, 8);
  6083. }
  6084. user_data[i]= 0;
  6085. e= sscanf(user_data+16, "x264 - core %d"/*%s - H.264/MPEG-4 AVC codec - Copyleft 2005 - http://www.videolan.org/x264.html*/, &build);
  6086. if(e==1 && build>=0)
  6087. h->x264_build= build;
  6088. if(s->avctx->debug & FF_DEBUG_BUGS)
  6089. av_log(s->avctx, AV_LOG_DEBUG, "user data:\"%s\"\n", user_data+16);
  6090. for(; i<size; i++)
  6091. skip_bits(&s->gb, 8);
  6092. return 0;
  6093. }
  6094. static int decode_sei(H264Context *h){
  6095. MpegEncContext * const s = &h->s;
  6096. while(get_bits_count(&s->gb) + 16 < s->gb.size_in_bits){
  6097. int size, type;
  6098. type=0;
  6099. do{
  6100. type+= show_bits(&s->gb, 8);
  6101. }while(get_bits(&s->gb, 8) == 255);
  6102. size=0;
  6103. do{
  6104. size+= show_bits(&s->gb, 8);
  6105. }while(get_bits(&s->gb, 8) == 255);
  6106. switch(type){
  6107. case 5:
  6108. if(decode_unregistered_user_data(h, size) < 0)
  6109. return -1;
  6110. break;
  6111. default:
  6112. skip_bits(&s->gb, 8*size);
  6113. }
  6114. //FIXME check bits here
  6115. align_get_bits(&s->gb);
  6116. }
  6117. return 0;
  6118. }
  6119. static inline void decode_hrd_parameters(H264Context *h, SPS *sps){
  6120. MpegEncContext * const s = &h->s;
  6121. int cpb_count, i;
  6122. cpb_count = get_ue_golomb(&s->gb) + 1;
  6123. get_bits(&s->gb, 4); /* bit_rate_scale */
  6124. get_bits(&s->gb, 4); /* cpb_size_scale */
  6125. for(i=0; i<cpb_count; i++){
  6126. get_ue_golomb(&s->gb); /* bit_rate_value_minus1 */
  6127. get_ue_golomb(&s->gb); /* cpb_size_value_minus1 */
  6128. get_bits1(&s->gb); /* cbr_flag */
  6129. }
  6130. get_bits(&s->gb, 5); /* initial_cpb_removal_delay_length_minus1 */
  6131. get_bits(&s->gb, 5); /* cpb_removal_delay_length_minus1 */
  6132. get_bits(&s->gb, 5); /* dpb_output_delay_length_minus1 */
  6133. get_bits(&s->gb, 5); /* time_offset_length */
  6134. }
  6135. static inline int decode_vui_parameters(H264Context *h, SPS *sps){
  6136. MpegEncContext * const s = &h->s;
  6137. int aspect_ratio_info_present_flag;
  6138. unsigned int aspect_ratio_idc;
  6139. int nal_hrd_parameters_present_flag, vcl_hrd_parameters_present_flag;
  6140. aspect_ratio_info_present_flag= get_bits1(&s->gb);
  6141. if( aspect_ratio_info_present_flag ) {
  6142. aspect_ratio_idc= get_bits(&s->gb, 8);
  6143. if( aspect_ratio_idc == EXTENDED_SAR ) {
  6144. sps->sar.num= get_bits(&s->gb, 16);
  6145. sps->sar.den= get_bits(&s->gb, 16);
  6146. }else if(aspect_ratio_idc < 14){
  6147. sps->sar= pixel_aspect[aspect_ratio_idc];
  6148. }else{
  6149. av_log(h->s.avctx, AV_LOG_ERROR, "illegal aspect ratio\n");
  6150. return -1;
  6151. }
  6152. }else{
  6153. sps->sar.num=
  6154. sps->sar.den= 0;
  6155. }
  6156. // s->avctx->aspect_ratio= sar_width*s->width / (float)(s->height*sar_height);
  6157. if(get_bits1(&s->gb)){ /* overscan_info_present_flag */
  6158. get_bits1(&s->gb); /* overscan_appropriate_flag */
  6159. }
  6160. if(get_bits1(&s->gb)){ /* video_signal_type_present_flag */
  6161. get_bits(&s->gb, 3); /* video_format */
  6162. get_bits1(&s->gb); /* video_full_range_flag */
  6163. if(get_bits1(&s->gb)){ /* colour_description_present_flag */
  6164. get_bits(&s->gb, 8); /* colour_primaries */
  6165. get_bits(&s->gb, 8); /* transfer_characteristics */
  6166. get_bits(&s->gb, 8); /* matrix_coefficients */
  6167. }
  6168. }
  6169. if(get_bits1(&s->gb)){ /* chroma_location_info_present_flag */
  6170. get_ue_golomb(&s->gb); /* chroma_sample_location_type_top_field */
  6171. get_ue_golomb(&s->gb); /* chroma_sample_location_type_bottom_field */
  6172. }
  6173. sps->timing_info_present_flag = get_bits1(&s->gb);
  6174. if(sps->timing_info_present_flag){
  6175. sps->num_units_in_tick = get_bits_long(&s->gb, 32);
  6176. sps->time_scale = get_bits_long(&s->gb, 32);
  6177. sps->fixed_frame_rate_flag = get_bits1(&s->gb);
  6178. }
  6179. nal_hrd_parameters_present_flag = get_bits1(&s->gb);
  6180. if(nal_hrd_parameters_present_flag)
  6181. decode_hrd_parameters(h, sps);
  6182. vcl_hrd_parameters_present_flag = get_bits1(&s->gb);
  6183. if(vcl_hrd_parameters_present_flag)
  6184. decode_hrd_parameters(h, sps);
  6185. if(nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag)
  6186. get_bits1(&s->gb); /* low_delay_hrd_flag */
  6187. get_bits1(&s->gb); /* pic_struct_present_flag */
  6188. sps->bitstream_restriction_flag = get_bits1(&s->gb);
  6189. if(sps->bitstream_restriction_flag){
  6190. unsigned int num_reorder_frames;
  6191. get_bits1(&s->gb); /* motion_vectors_over_pic_boundaries_flag */
  6192. get_ue_golomb(&s->gb); /* max_bytes_per_pic_denom */
  6193. get_ue_golomb(&s->gb); /* max_bits_per_mb_denom */
  6194. get_ue_golomb(&s->gb); /* log2_max_mv_length_horizontal */
  6195. get_ue_golomb(&s->gb); /* log2_max_mv_length_vertical */
  6196. num_reorder_frames= get_ue_golomb(&s->gb);
  6197. get_ue_golomb(&s->gb); /*max_dec_frame_buffering*/
  6198. if(num_reorder_frames > 16 /*max_dec_frame_buffering || max_dec_frame_buffering > 16*/){
  6199. av_log(h->s.avctx, AV_LOG_ERROR, "illegal num_reorder_frames %d\n", num_reorder_frames);
  6200. return -1;
  6201. }
  6202. sps->num_reorder_frames= num_reorder_frames;
  6203. }
  6204. return 0;
  6205. }
  6206. static void decode_scaling_list(H264Context *h, uint8_t *factors, int size,
  6207. const uint8_t *jvt_list, const uint8_t *fallback_list){
  6208. MpegEncContext * const s = &h->s;
  6209. int i, last = 8, next = 8;
  6210. const uint8_t *scan = size == 16 ? zigzag_scan : zigzag_scan8x8;
  6211. if(!get_bits1(&s->gb)) /* matrix not written, we use the predicted one */
  6212. memcpy(factors, fallback_list, size*sizeof(uint8_t));
  6213. else
  6214. for(i=0;i<size;i++){
  6215. if(next)
  6216. next = (last + get_se_golomb(&s->gb)) & 0xff;
  6217. if(!i && !next){ /* matrix not written, we use the preset one */
  6218. memcpy(factors, jvt_list, size*sizeof(uint8_t));
  6219. break;
  6220. }
  6221. last = factors[scan[i]] = next ? next : last;
  6222. }
  6223. }
  6224. static void decode_scaling_matrices(H264Context *h, SPS *sps, PPS *pps, int is_sps,
  6225. uint8_t (*scaling_matrix4)[16], uint8_t (*scaling_matrix8)[64]){
  6226. MpegEncContext * const s = &h->s;
  6227. int fallback_sps = !is_sps && sps->scaling_matrix_present;
  6228. const uint8_t *fallback[4] = {
  6229. fallback_sps ? sps->scaling_matrix4[0] : default_scaling4[0],
  6230. fallback_sps ? sps->scaling_matrix4[3] : default_scaling4[1],
  6231. fallback_sps ? sps->scaling_matrix8[0] : default_scaling8[0],
  6232. fallback_sps ? sps->scaling_matrix8[1] : default_scaling8[1]
  6233. };
  6234. if(get_bits1(&s->gb)){
  6235. sps->scaling_matrix_present |= is_sps;
  6236. decode_scaling_list(h,scaling_matrix4[0],16,default_scaling4[0],fallback[0]); // Intra, Y
  6237. decode_scaling_list(h,scaling_matrix4[1],16,default_scaling4[0],scaling_matrix4[0]); // Intra, Cr
  6238. decode_scaling_list(h,scaling_matrix4[2],16,default_scaling4[0],scaling_matrix4[1]); // Intra, Cb
  6239. decode_scaling_list(h,scaling_matrix4[3],16,default_scaling4[1],fallback[1]); // Inter, Y
  6240. decode_scaling_list(h,scaling_matrix4[4],16,default_scaling4[1],scaling_matrix4[3]); // Inter, Cr
  6241. decode_scaling_list(h,scaling_matrix4[5],16,default_scaling4[1],scaling_matrix4[4]); // Inter, Cb
  6242. if(is_sps || pps->transform_8x8_mode){
  6243. decode_scaling_list(h,scaling_matrix8[0],64,default_scaling8[0],fallback[2]); // Intra, Y
  6244. decode_scaling_list(h,scaling_matrix8[1],64,default_scaling8[1],fallback[3]); // Inter, Y
  6245. }
  6246. } else if(fallback_sps) {
  6247. memcpy(scaling_matrix4, sps->scaling_matrix4, 6*16*sizeof(uint8_t));
  6248. memcpy(scaling_matrix8, sps->scaling_matrix8, 2*64*sizeof(uint8_t));
  6249. }
  6250. }
  6251. /**
  6252. * Returns and optionally allocates SPS / PPS structures in the supplied array 'vec'
  6253. */
  6254. static void *
  6255. alloc_parameter_set(H264Context *h, void **vec, const unsigned int id, const unsigned int max,
  6256. const size_t size, const char *name)
  6257. {
  6258. if(id>=max) {
  6259. av_log(h->s.avctx, AV_LOG_ERROR, "%s_id (%d) out of range\n", name, id);
  6260. return NULL;
  6261. }
  6262. if(!vec[id]) {
  6263. vec[id] = av_mallocz(size);
  6264. if(vec[id] == NULL)
  6265. av_log(h->s.avctx, AV_LOG_ERROR, "cannot allocate memory for %s\n", name);
  6266. }
  6267. return vec[id];
  6268. }
  6269. static inline int decode_seq_parameter_set(H264Context *h){
  6270. MpegEncContext * const s = &h->s;
  6271. int profile_idc, level_idc;
  6272. unsigned int sps_id, tmp, mb_width, mb_height;
  6273. int i;
  6274. SPS *sps;
  6275. profile_idc= get_bits(&s->gb, 8);
  6276. get_bits1(&s->gb); //constraint_set0_flag
  6277. get_bits1(&s->gb); //constraint_set1_flag
  6278. get_bits1(&s->gb); //constraint_set2_flag
  6279. get_bits1(&s->gb); //constraint_set3_flag
  6280. get_bits(&s->gb, 4); // reserved
  6281. level_idc= get_bits(&s->gb, 8);
  6282. sps_id= get_ue_golomb(&s->gb);
  6283. sps = alloc_parameter_set(h, (void **)h->sps_buffers, sps_id, MAX_SPS_COUNT, sizeof(SPS), "sps");
  6284. if(sps == NULL)
  6285. return -1;
  6286. sps->profile_idc= profile_idc;
  6287. sps->level_idc= level_idc;
  6288. if(sps->profile_idc >= 100){ //high profile
  6289. if(get_ue_golomb(&s->gb) == 3) //chroma_format_idc
  6290. get_bits1(&s->gb); //residual_color_transform_flag
  6291. get_ue_golomb(&s->gb); //bit_depth_luma_minus8
  6292. get_ue_golomb(&s->gb); //bit_depth_chroma_minus8
  6293. sps->transform_bypass = get_bits1(&s->gb);
  6294. decode_scaling_matrices(h, sps, NULL, 1, sps->scaling_matrix4, sps->scaling_matrix8);
  6295. }else
  6296. sps->scaling_matrix_present = 0;
  6297. sps->log2_max_frame_num= get_ue_golomb(&s->gb) + 4;
  6298. sps->poc_type= get_ue_golomb(&s->gb);
  6299. if(sps->poc_type == 0){ //FIXME #define
  6300. sps->log2_max_poc_lsb= get_ue_golomb(&s->gb) + 4;
  6301. } else if(sps->poc_type == 1){//FIXME #define
  6302. sps->delta_pic_order_always_zero_flag= get_bits1(&s->gb);
  6303. sps->offset_for_non_ref_pic= get_se_golomb(&s->gb);
  6304. sps->offset_for_top_to_bottom_field= get_se_golomb(&s->gb);
  6305. tmp= get_ue_golomb(&s->gb);
  6306. if(tmp >= sizeof(sps->offset_for_ref_frame) / sizeof(sps->offset_for_ref_frame[0])){
  6307. av_log(h->s.avctx, AV_LOG_ERROR, "poc_cycle_length overflow %u\n", tmp);
  6308. return -1;
  6309. }
  6310. sps->poc_cycle_length= tmp;
  6311. for(i=0; i<sps->poc_cycle_length; i++)
  6312. sps->offset_for_ref_frame[i]= get_se_golomb(&s->gb);
  6313. }else if(sps->poc_type != 2){
  6314. av_log(h->s.avctx, AV_LOG_ERROR, "illegal POC type %d\n", sps->poc_type);
  6315. return -1;
  6316. }
  6317. tmp= get_ue_golomb(&s->gb);
  6318. if(tmp > MAX_PICTURE_COUNT-2 || tmp >= 32){
  6319. av_log(h->s.avctx, AV_LOG_ERROR, "too many reference frames\n");
  6320. return -1;
  6321. }
  6322. sps->ref_frame_count= tmp;
  6323. sps->gaps_in_frame_num_allowed_flag= get_bits1(&s->gb);
  6324. mb_width= get_ue_golomb(&s->gb) + 1;
  6325. mb_height= get_ue_golomb(&s->gb) + 1;
  6326. if(mb_width >= INT_MAX/16 || mb_height >= INT_MAX/16 ||
  6327. avcodec_check_dimensions(NULL, 16*mb_width, 16*mb_height)){
  6328. av_log(h->s.avctx, AV_LOG_ERROR, "mb_width/height overflow\n");
  6329. return -1;
  6330. }
  6331. sps->mb_width = mb_width;
  6332. sps->mb_height= mb_height;
  6333. sps->frame_mbs_only_flag= get_bits1(&s->gb);
  6334. if(!sps->frame_mbs_only_flag)
  6335. sps->mb_aff= get_bits1(&s->gb);
  6336. else
  6337. sps->mb_aff= 0;
  6338. sps->direct_8x8_inference_flag= get_bits1(&s->gb);
  6339. #ifndef ALLOW_INTERLACE
  6340. if(sps->mb_aff)
  6341. av_log(h->s.avctx, AV_LOG_ERROR, "MBAFF support not included; enable it at compile-time.\n");
  6342. #endif
  6343. if(!sps->direct_8x8_inference_flag && sps->mb_aff)
  6344. av_log(h->s.avctx, AV_LOG_ERROR, "MBAFF + !direct_8x8_inference is not implemented\n");
  6345. sps->crop= get_bits1(&s->gb);
  6346. if(sps->crop){
  6347. sps->crop_left = get_ue_golomb(&s->gb);
  6348. sps->crop_right = get_ue_golomb(&s->gb);
  6349. sps->crop_top = get_ue_golomb(&s->gb);
  6350. sps->crop_bottom= get_ue_golomb(&s->gb);
  6351. if(sps->crop_left || sps->crop_top){
  6352. av_log(h->s.avctx, AV_LOG_ERROR, "insane cropping not completely supported, this could look slightly wrong ...\n");
  6353. }
  6354. }else{
  6355. sps->crop_left =
  6356. sps->crop_right =
  6357. sps->crop_top =
  6358. sps->crop_bottom= 0;
  6359. }
  6360. sps->vui_parameters_present_flag= get_bits1(&s->gb);
  6361. if( sps->vui_parameters_present_flag )
  6362. decode_vui_parameters(h, sps);
  6363. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  6364. 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",
  6365. sps_id, sps->profile_idc, sps->level_idc,
  6366. sps->poc_type,
  6367. sps->ref_frame_count,
  6368. sps->mb_width, sps->mb_height,
  6369. sps->frame_mbs_only_flag ? "FRM" : (sps->mb_aff ? "MB-AFF" : "PIC-AFF"),
  6370. sps->direct_8x8_inference_flag ? "8B8" : "",
  6371. sps->crop_left, sps->crop_right,
  6372. sps->crop_top, sps->crop_bottom,
  6373. sps->vui_parameters_present_flag ? "VUI" : ""
  6374. );
  6375. }
  6376. return 0;
  6377. }
  6378. static void
  6379. build_qp_table(PPS *pps, int t, int index)
  6380. {
  6381. int i;
  6382. for(i = 0; i < 255; i++)
  6383. pps->chroma_qp_table[t][i & 0xff] = chroma_qp[av_clip(i + index, 0, 51)];
  6384. }
  6385. static inline int decode_picture_parameter_set(H264Context *h, int bit_length){
  6386. MpegEncContext * const s = &h->s;
  6387. unsigned int tmp, pps_id= get_ue_golomb(&s->gb);
  6388. PPS *pps;
  6389. pps = alloc_parameter_set(h, (void **)h->pps_buffers, pps_id, MAX_PPS_COUNT, sizeof(PPS), "pps");
  6390. if(pps == NULL)
  6391. return -1;
  6392. tmp= get_ue_golomb(&s->gb);
  6393. if(tmp>=MAX_SPS_COUNT || h->sps_buffers[tmp] == NULL){
  6394. av_log(h->s.avctx, AV_LOG_ERROR, "sps_id out of range\n");
  6395. return -1;
  6396. }
  6397. pps->sps_id= tmp;
  6398. pps->cabac= get_bits1(&s->gb);
  6399. pps->pic_order_present= get_bits1(&s->gb);
  6400. pps->slice_group_count= get_ue_golomb(&s->gb) + 1;
  6401. if(pps->slice_group_count > 1 ){
  6402. pps->mb_slice_group_map_type= get_ue_golomb(&s->gb);
  6403. av_log(h->s.avctx, AV_LOG_ERROR, "FMO not supported\n");
  6404. switch(pps->mb_slice_group_map_type){
  6405. case 0:
  6406. #if 0
  6407. | for( i = 0; i <= num_slice_groups_minus1; i++ ) | | |
  6408. | run_length[ i ] |1 |ue(v) |
  6409. #endif
  6410. break;
  6411. case 2:
  6412. #if 0
  6413. | for( i = 0; i < num_slice_groups_minus1; i++ ) | | |
  6414. |{ | | |
  6415. | top_left_mb[ i ] |1 |ue(v) |
  6416. | bottom_right_mb[ i ] |1 |ue(v) |
  6417. | } | | |
  6418. #endif
  6419. break;
  6420. case 3:
  6421. case 4:
  6422. case 5:
  6423. #if 0
  6424. | slice_group_change_direction_flag |1 |u(1) |
  6425. | slice_group_change_rate_minus1 |1 |ue(v) |
  6426. #endif
  6427. break;
  6428. case 6:
  6429. #if 0
  6430. | slice_group_id_cnt_minus1 |1 |ue(v) |
  6431. | for( i = 0; i <= slice_group_id_cnt_minus1; i++ | | |
  6432. |) | | |
  6433. | slice_group_id[ i ] |1 |u(v) |
  6434. #endif
  6435. break;
  6436. }
  6437. }
  6438. pps->ref_count[0]= get_ue_golomb(&s->gb) + 1;
  6439. pps->ref_count[1]= get_ue_golomb(&s->gb) + 1;
  6440. if(pps->ref_count[0]-1 > 32-1 || pps->ref_count[1]-1 > 32-1){
  6441. av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow (pps)\n");
  6442. pps->ref_count[0]= pps->ref_count[1]= 1;
  6443. return -1;
  6444. }
  6445. pps->weighted_pred= get_bits1(&s->gb);
  6446. pps->weighted_bipred_idc= get_bits(&s->gb, 2);
  6447. pps->init_qp= get_se_golomb(&s->gb) + 26;
  6448. pps->init_qs= get_se_golomb(&s->gb) + 26;
  6449. pps->chroma_qp_index_offset[0]= get_se_golomb(&s->gb);
  6450. pps->deblocking_filter_parameters_present= get_bits1(&s->gb);
  6451. pps->constrained_intra_pred= get_bits1(&s->gb);
  6452. pps->redundant_pic_cnt_present = get_bits1(&s->gb);
  6453. pps->transform_8x8_mode= 0;
  6454. h->dequant_coeff_pps= -1; //contents of sps/pps can change even if id doesn't, so reinit
  6455. memset(pps->scaling_matrix4, 16, 6*16*sizeof(uint8_t));
  6456. memset(pps->scaling_matrix8, 16, 2*64*sizeof(uint8_t));
  6457. if(get_bits_count(&s->gb) < bit_length){
  6458. pps->transform_8x8_mode= get_bits1(&s->gb);
  6459. decode_scaling_matrices(h, h->sps_buffers[pps->sps_id], pps, 0, pps->scaling_matrix4, pps->scaling_matrix8);
  6460. pps->chroma_qp_index_offset[1]= get_se_golomb(&s->gb); //second_chroma_qp_index_offset
  6461. } else {
  6462. pps->chroma_qp_index_offset[1]= pps->chroma_qp_index_offset[0];
  6463. }
  6464. build_qp_table(pps, 0, pps->chroma_qp_index_offset[0]);
  6465. if(pps->chroma_qp_index_offset[0] != pps->chroma_qp_index_offset[1]) {
  6466. build_qp_table(pps, 1, pps->chroma_qp_index_offset[1]);
  6467. h->pps.chroma_qp_diff= 1;
  6468. } else
  6469. memcpy(pps->chroma_qp_table[1], pps->chroma_qp_table[0], 256);
  6470. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  6471. 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",
  6472. pps_id, pps->sps_id,
  6473. pps->cabac ? "CABAC" : "CAVLC",
  6474. pps->slice_group_count,
  6475. pps->ref_count[0], pps->ref_count[1],
  6476. pps->weighted_pred ? "weighted" : "",
  6477. pps->init_qp, pps->init_qs, pps->chroma_qp_index_offset[0], pps->chroma_qp_index_offset[1],
  6478. pps->deblocking_filter_parameters_present ? "LPAR" : "",
  6479. pps->constrained_intra_pred ? "CONSTR" : "",
  6480. pps->redundant_pic_cnt_present ? "REDU" : "",
  6481. pps->transform_8x8_mode ? "8x8DCT" : ""
  6482. );
  6483. }
  6484. return 0;
  6485. }
  6486. /**
  6487. * Call decode_slice() for each context.
  6488. *
  6489. * @param h h264 master context
  6490. * @param context_count number of contexts to execute
  6491. */
  6492. static void execute_decode_slices(H264Context *h, int context_count){
  6493. MpegEncContext * const s = &h->s;
  6494. AVCodecContext * const avctx= s->avctx;
  6495. H264Context *hx;
  6496. int i;
  6497. if(context_count == 1) {
  6498. decode_slice(avctx, h);
  6499. } else {
  6500. for(i = 1; i < context_count; i++) {
  6501. hx = h->thread_context[i];
  6502. hx->s.error_resilience = avctx->error_resilience;
  6503. hx->s.error_count = 0;
  6504. }
  6505. avctx->execute(avctx, (void *)decode_slice,
  6506. (void **)h->thread_context, NULL, context_count);
  6507. /* pull back stuff from slices to master context */
  6508. hx = h->thread_context[context_count - 1];
  6509. s->mb_x = hx->s.mb_x;
  6510. s->mb_y = hx->s.mb_y;
  6511. s->dropable = hx->s.dropable;
  6512. s->picture_structure = hx->s.picture_structure;
  6513. for(i = 1; i < context_count; i++)
  6514. h->s.error_count += h->thread_context[i]->s.error_count;
  6515. }
  6516. }
  6517. static int decode_nal_units(H264Context *h, uint8_t *buf, int buf_size){
  6518. MpegEncContext * const s = &h->s;
  6519. AVCodecContext * const avctx= s->avctx;
  6520. int buf_index=0;
  6521. H264Context *hx; ///< thread context
  6522. int context_count = 0;
  6523. h->max_contexts = avctx->thread_count;
  6524. #if 0
  6525. int i;
  6526. for(i=0; i<50; i++){
  6527. av_log(NULL, AV_LOG_ERROR,"%02X ", buf[i]);
  6528. }
  6529. #endif
  6530. if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
  6531. h->current_slice = 0;
  6532. if (!s->first_field)
  6533. s->current_picture_ptr= NULL;
  6534. }
  6535. for(;;){
  6536. int consumed;
  6537. int dst_length;
  6538. int bit_length;
  6539. uint8_t *ptr;
  6540. int i, nalsize = 0;
  6541. int err;
  6542. if(h->is_avc) {
  6543. if(buf_index >= buf_size) break;
  6544. nalsize = 0;
  6545. for(i = 0; i < h->nal_length_size; i++)
  6546. nalsize = (nalsize << 8) | buf[buf_index++];
  6547. if(nalsize <= 1 || (nalsize+buf_index > buf_size)){
  6548. if(nalsize == 1){
  6549. buf_index++;
  6550. continue;
  6551. }else{
  6552. av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
  6553. break;
  6554. }
  6555. }
  6556. } else {
  6557. // start code prefix search
  6558. for(; buf_index + 3 < buf_size; buf_index++){
  6559. // This should always succeed in the first iteration.
  6560. if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)
  6561. break;
  6562. }
  6563. if(buf_index+3 >= buf_size) break;
  6564. buf_index+=3;
  6565. }
  6566. hx = h->thread_context[context_count];
  6567. ptr= decode_nal(hx, buf + buf_index, &dst_length, &consumed, h->is_avc ? nalsize : buf_size - buf_index);
  6568. if (ptr==NULL || dst_length < 0){
  6569. return -1;
  6570. }
  6571. while(ptr[dst_length - 1] == 0 && dst_length > 0)
  6572. dst_length--;
  6573. bit_length= !dst_length ? 0 : (8*dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1));
  6574. if(s->avctx->debug&FF_DEBUG_STARTCODE){
  6575. 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);
  6576. }
  6577. if (h->is_avc && (nalsize != consumed))
  6578. av_log(h->s.avctx, AV_LOG_ERROR, "AVC: Consumed only %d bytes instead of %d\n", consumed, nalsize);
  6579. buf_index += consumed;
  6580. if( (s->hurry_up == 1 && h->nal_ref_idc == 0) //FIXME do not discard SEI id
  6581. ||(avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
  6582. continue;
  6583. again:
  6584. err = 0;
  6585. switch(hx->nal_unit_type){
  6586. case NAL_IDR_SLICE:
  6587. if (h->nal_unit_type != NAL_IDR_SLICE) {
  6588. av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices");
  6589. return -1;
  6590. }
  6591. idr(h); //FIXME ensure we don't loose some frames if there is reordering
  6592. case NAL_SLICE:
  6593. init_get_bits(&hx->s.gb, ptr, bit_length);
  6594. hx->intra_gb_ptr=
  6595. hx->inter_gb_ptr= &hx->s.gb;
  6596. hx->s.data_partitioning = 0;
  6597. if((err = decode_slice_header(hx, h)))
  6598. break;
  6599. s->current_picture_ptr->key_frame|= (hx->nal_unit_type == NAL_IDR_SLICE);
  6600. if(hx->redundant_pic_count==0 && hx->s.hurry_up < 5
  6601. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  6602. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type!=B_TYPE)
  6603. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type==I_TYPE)
  6604. && avctx->skip_frame < AVDISCARD_ALL)
  6605. context_count++;
  6606. break;
  6607. case NAL_DPA:
  6608. init_get_bits(&hx->s.gb, ptr, bit_length);
  6609. hx->intra_gb_ptr=
  6610. hx->inter_gb_ptr= NULL;
  6611. hx->s.data_partitioning = 1;
  6612. err = decode_slice_header(hx, h);
  6613. break;
  6614. case NAL_DPB:
  6615. init_get_bits(&hx->intra_gb, ptr, bit_length);
  6616. hx->intra_gb_ptr= &hx->intra_gb;
  6617. break;
  6618. case NAL_DPC:
  6619. init_get_bits(&hx->inter_gb, ptr, bit_length);
  6620. hx->inter_gb_ptr= &hx->inter_gb;
  6621. if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
  6622. && s->context_initialized
  6623. && s->hurry_up < 5
  6624. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  6625. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type!=B_TYPE)
  6626. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type==I_TYPE)
  6627. && avctx->skip_frame < AVDISCARD_ALL)
  6628. context_count++;
  6629. break;
  6630. case NAL_SEI:
  6631. init_get_bits(&s->gb, ptr, bit_length);
  6632. decode_sei(h);
  6633. break;
  6634. case NAL_SPS:
  6635. init_get_bits(&s->gb, ptr, bit_length);
  6636. decode_seq_parameter_set(h);
  6637. if(s->flags& CODEC_FLAG_LOW_DELAY)
  6638. s->low_delay=1;
  6639. if(avctx->has_b_frames < 2)
  6640. avctx->has_b_frames= !s->low_delay;
  6641. break;
  6642. case NAL_PPS:
  6643. init_get_bits(&s->gb, ptr, bit_length);
  6644. decode_picture_parameter_set(h, bit_length);
  6645. break;
  6646. case NAL_AUD:
  6647. case NAL_END_SEQUENCE:
  6648. case NAL_END_STREAM:
  6649. case NAL_FILLER_DATA:
  6650. case NAL_SPS_EXT:
  6651. case NAL_AUXILIARY_SLICE:
  6652. break;
  6653. default:
  6654. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", h->nal_unit_type, bit_length);
  6655. }
  6656. if(context_count == h->max_contexts) {
  6657. execute_decode_slices(h, context_count);
  6658. context_count = 0;
  6659. }
  6660. if (err < 0)
  6661. av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  6662. else if(err == 1) {
  6663. /* Slice could not be decoded in parallel mode, copy down
  6664. * NAL unit stuff to context 0 and restart. Note that
  6665. * rbsp_buffer is not transfered, but since we no longer
  6666. * run in parallel mode this should not be an issue. */
  6667. h->nal_unit_type = hx->nal_unit_type;
  6668. h->nal_ref_idc = hx->nal_ref_idc;
  6669. hx = h;
  6670. goto again;
  6671. }
  6672. }
  6673. if(context_count)
  6674. execute_decode_slices(h, context_count);
  6675. return buf_index;
  6676. }
  6677. /**
  6678. * returns the number of bytes consumed for building the current frame
  6679. */
  6680. static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
  6681. if(s->flags&CODEC_FLAG_TRUNCATED){
  6682. pos -= s->parse_context.last_index;
  6683. if(pos<0) pos=0; // FIXME remove (unneeded?)
  6684. return pos;
  6685. }else{
  6686. if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
  6687. if(pos+10>buf_size) pos=buf_size; // oops ;)
  6688. return pos;
  6689. }
  6690. }
  6691. static int decode_frame(AVCodecContext *avctx,
  6692. void *data, int *data_size,
  6693. uint8_t *buf, int buf_size)
  6694. {
  6695. H264Context *h = avctx->priv_data;
  6696. MpegEncContext *s = &h->s;
  6697. AVFrame *pict = data;
  6698. int buf_index;
  6699. s->flags= avctx->flags;
  6700. s->flags2= avctx->flags2;
  6701. /* no supplementary picture */
  6702. if (buf_size == 0) {
  6703. Picture *out;
  6704. int i, out_idx;
  6705. //FIXME factorize this with the output code below
  6706. out = h->delayed_pic[0];
  6707. out_idx = 0;
  6708. for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame; i++)
  6709. if(h->delayed_pic[i]->poc < out->poc){
  6710. out = h->delayed_pic[i];
  6711. out_idx = i;
  6712. }
  6713. for(i=out_idx; h->delayed_pic[i]; i++)
  6714. h->delayed_pic[i] = h->delayed_pic[i+1];
  6715. if(out){
  6716. *data_size = sizeof(AVFrame);
  6717. *pict= *(AVFrame*)out;
  6718. }
  6719. return 0;
  6720. }
  6721. if(s->flags&CODEC_FLAG_TRUNCATED){
  6722. int next= ff_h264_find_frame_end(h, buf, buf_size);
  6723. if( ff_combine_frame(&s->parse_context, next, (const uint8_t **)&buf, &buf_size) < 0 )
  6724. return buf_size;
  6725. //printf("next:%d buf_size:%d last_index:%d\n", next, buf_size, s->parse_context.last_index);
  6726. }
  6727. if(h->is_avc && !h->got_avcC) {
  6728. int i, cnt, nalsize;
  6729. unsigned char *p = avctx->extradata;
  6730. if(avctx->extradata_size < 7) {
  6731. av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
  6732. return -1;
  6733. }
  6734. if(*p != 1) {
  6735. av_log(avctx, AV_LOG_ERROR, "Unknown avcC version %d\n", *p);
  6736. return -1;
  6737. }
  6738. /* sps and pps in the avcC always have length coded with 2 bytes,
  6739. so put a fake nal_length_size = 2 while parsing them */
  6740. h->nal_length_size = 2;
  6741. // Decode sps from avcC
  6742. cnt = *(p+5) & 0x1f; // Number of sps
  6743. p += 6;
  6744. for (i = 0; i < cnt; i++) {
  6745. nalsize = AV_RB16(p) + 2;
  6746. if(decode_nal_units(h, p, nalsize) < 0) {
  6747. av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);
  6748. return -1;
  6749. }
  6750. p += nalsize;
  6751. }
  6752. // Decode pps from avcC
  6753. cnt = *(p++); // Number of pps
  6754. for (i = 0; i < cnt; i++) {
  6755. nalsize = AV_RB16(p) + 2;
  6756. if(decode_nal_units(h, p, nalsize) != nalsize) {
  6757. av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);
  6758. return -1;
  6759. }
  6760. p += nalsize;
  6761. }
  6762. // Now store right nal length size, that will be use to parse all other nals
  6763. h->nal_length_size = ((*(((char*)(avctx->extradata))+4))&0x03)+1;
  6764. // Do not reparse avcC
  6765. h->got_avcC = 1;
  6766. }
  6767. if(avctx->frame_number==0 && !h->is_avc && s->avctx->extradata_size){
  6768. if(decode_nal_units(h, s->avctx->extradata, s->avctx->extradata_size) < 0)
  6769. return -1;
  6770. }
  6771. buf_index=decode_nal_units(h, buf, buf_size);
  6772. if(buf_index < 0)
  6773. return -1;
  6774. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
  6775. if (avctx->skip_frame >= AVDISCARD_NONREF || s->hurry_up) return 0;
  6776. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  6777. return -1;
  6778. }
  6779. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
  6780. Picture *out = s->current_picture_ptr;
  6781. Picture *cur = s->current_picture_ptr;
  6782. Picture *prev = h->delayed_output_pic;
  6783. int i, pics, cross_idr, out_of_order, out_idx;
  6784. s->mb_y= 0;
  6785. s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;
  6786. s->current_picture_ptr->pict_type= s->pict_type;
  6787. h->prev_frame_num_offset= h->frame_num_offset;
  6788. h->prev_frame_num= h->frame_num;
  6789. if(!s->dropable) {
  6790. h->prev_poc_msb= h->poc_msb;
  6791. h->prev_poc_lsb= h->poc_lsb;
  6792. execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  6793. }
  6794. /*
  6795. * FIXME: Error handling code does not seem to support interlaced
  6796. * when slices span multiple rows
  6797. * The ff_er_add_slice calls don't work right for bottom
  6798. * fields; they cause massive erroneous error concealing
  6799. * Error marking covers both fields (top and bottom).
  6800. * This causes a mismatched s->error_count
  6801. * and a bad error table. Further, the error count goes to
  6802. * INT_MAX when called for bottom field, because mb_y is
  6803. * past end by one (callers fault) and resync_mb_y != 0
  6804. * causes problems for the first MB line, too.
  6805. */
  6806. if (!FIELD_PICTURE)
  6807. ff_er_frame_end(s);
  6808. MPV_frame_end(s);
  6809. if (s->first_field) {
  6810. /* Wait for second field. */
  6811. *data_size = 0;
  6812. } else {
  6813. cur->interlaced_frame = FIELD_OR_MBAFF_PICTURE;
  6814. /* Derive top_field_first from field pocs. */
  6815. cur->top_field_first = cur->field_poc[0] < cur->field_poc[1];
  6816. //FIXME do something with unavailable reference frames
  6817. #if 0 //decode order
  6818. *data_size = sizeof(AVFrame);
  6819. #else
  6820. /* Sort B-frames into display order */
  6821. if(h->sps.bitstream_restriction_flag
  6822. && s->avctx->has_b_frames < h->sps.num_reorder_frames){
  6823. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  6824. s->low_delay = 0;
  6825. }
  6826. pics = 0;
  6827. while(h->delayed_pic[pics]) pics++;
  6828. assert(pics+1 < sizeof(h->delayed_pic) / sizeof(h->delayed_pic[0]));
  6829. h->delayed_pic[pics++] = cur;
  6830. if(cur->reference == 0)
  6831. cur->reference = DELAYED_PIC_REF;
  6832. cross_idr = 0;
  6833. for(i=0; h->delayed_pic[i]; i++)
  6834. if(h->delayed_pic[i]->key_frame || h->delayed_pic[i]->poc==0)
  6835. cross_idr = 1;
  6836. out = h->delayed_pic[0];
  6837. out_idx = 0;
  6838. for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame; i++)
  6839. if(h->delayed_pic[i]->poc < out->poc){
  6840. out = h->delayed_pic[i];
  6841. out_idx = i;
  6842. }
  6843. out_of_order = !cross_idr && prev && out->poc < prev->poc;
  6844. if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames >= h->sps.num_reorder_frames)
  6845. { }
  6846. else if(prev && pics <= s->avctx->has_b_frames)
  6847. out = prev;
  6848. else if((out_of_order && pics-1 == s->avctx->has_b_frames && pics < 15)
  6849. || (s->low_delay &&
  6850. ((!cross_idr && prev && out->poc > prev->poc + 2)
  6851. || cur->pict_type == B_TYPE)))
  6852. {
  6853. s->low_delay = 0;
  6854. s->avctx->has_b_frames++;
  6855. out = prev;
  6856. }
  6857. else if(out_of_order)
  6858. out = prev;
  6859. if(out_of_order || pics > s->avctx->has_b_frames){
  6860. for(i=out_idx; h->delayed_pic[i]; i++)
  6861. h->delayed_pic[i] = h->delayed_pic[i+1];
  6862. }
  6863. if(prev == out)
  6864. *data_size = 0;
  6865. else
  6866. *data_size = sizeof(AVFrame);
  6867. if(prev && prev != out && prev->reference == DELAYED_PIC_REF)
  6868. prev->reference = 0;
  6869. h->delayed_output_pic = out;
  6870. #endif
  6871. if(out)
  6872. *pict= *(AVFrame*)out;
  6873. else
  6874. av_log(avctx, AV_LOG_DEBUG, "no picture\n");
  6875. }
  6876. }
  6877. assert(pict->data[0] || !*data_size);
  6878. ff_print_debug_info(s, pict);
  6879. //printf("out %d\n", (int)pict->data[0]);
  6880. #if 0 //?
  6881. /* Return the Picture timestamp as the frame number */
  6882. /* we subtract 1 because it is added on utils.c */
  6883. avctx->frame_number = s->picture_number - 1;
  6884. #endif
  6885. return get_consumed_bytes(s, buf_index, buf_size);
  6886. }
  6887. #if 0
  6888. static inline void fill_mb_avail(H264Context *h){
  6889. MpegEncContext * const s = &h->s;
  6890. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  6891. if(s->mb_y){
  6892. h->mb_avail[0]= s->mb_x && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
  6893. h->mb_avail[1]= h->slice_table[mb_xy - s->mb_stride ] == h->slice_num;
  6894. h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
  6895. }else{
  6896. h->mb_avail[0]=
  6897. h->mb_avail[1]=
  6898. h->mb_avail[2]= 0;
  6899. }
  6900. h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
  6901. h->mb_avail[4]= 1; //FIXME move out
  6902. h->mb_avail[5]= 0; //FIXME move out
  6903. }
  6904. #endif
  6905. #if 0 //selftest
  6906. #undef random
  6907. #define COUNT 8000
  6908. #define SIZE (COUNT*40)
  6909. int main(void){
  6910. int i;
  6911. uint8_t temp[SIZE];
  6912. PutBitContext pb;
  6913. GetBitContext gb;
  6914. // int int_temp[10000];
  6915. DSPContext dsp;
  6916. AVCodecContext avctx;
  6917. dsputil_init(&dsp, &avctx);
  6918. init_put_bits(&pb, temp, SIZE);
  6919. printf("testing unsigned exp golomb\n");
  6920. for(i=0; i<COUNT; i++){
  6921. START_TIMER
  6922. set_ue_golomb(&pb, i);
  6923. STOP_TIMER("set_ue_golomb");
  6924. }
  6925. flush_put_bits(&pb);
  6926. init_get_bits(&gb, temp, 8*SIZE);
  6927. for(i=0; i<COUNT; i++){
  6928. int j, s;
  6929. s= show_bits(&gb, 24);
  6930. START_TIMER
  6931. j= get_ue_golomb(&gb);
  6932. if(j != i){
  6933. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  6934. // return -1;
  6935. }
  6936. STOP_TIMER("get_ue_golomb");
  6937. }
  6938. init_put_bits(&pb, temp, SIZE);
  6939. printf("testing signed exp golomb\n");
  6940. for(i=0; i<COUNT; i++){
  6941. START_TIMER
  6942. set_se_golomb(&pb, i - COUNT/2);
  6943. STOP_TIMER("set_se_golomb");
  6944. }
  6945. flush_put_bits(&pb);
  6946. init_get_bits(&gb, temp, 8*SIZE);
  6947. for(i=0; i<COUNT; i++){
  6948. int j, s;
  6949. s= show_bits(&gb, 24);
  6950. START_TIMER
  6951. j= get_se_golomb(&gb);
  6952. if(j != i - COUNT/2){
  6953. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  6954. // return -1;
  6955. }
  6956. STOP_TIMER("get_se_golomb");
  6957. }
  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. #if 0
  6991. printf("testing quantizer\n");
  6992. for(qp=0; qp<52; qp++){
  6993. for(i=0; i<16; i++)
  6994. src1_block[i]= src2_block[i]= random()%255;
  6995. }
  6996. #endif
  6997. printf("Testing NAL layer\n");
  6998. uint8_t bitstream[COUNT];
  6999. uint8_t nal[COUNT*2];
  7000. H264Context h;
  7001. memset(&h, 0, sizeof(H264Context));
  7002. for(i=0; i<COUNT; i++){
  7003. int zeros= i;
  7004. int nal_length;
  7005. int consumed;
  7006. int out_length;
  7007. uint8_t *out;
  7008. int j;
  7009. for(j=0; j<COUNT; j++){
  7010. bitstream[j]= (random() % 255) + 1;
  7011. }
  7012. for(j=0; j<zeros; j++){
  7013. int pos= random() % COUNT;
  7014. while(bitstream[pos] == 0){
  7015. pos++;
  7016. pos %= COUNT;
  7017. }
  7018. bitstream[pos]=0;
  7019. }
  7020. START_TIMER
  7021. nal_length= encode_nal(&h, nal, bitstream, COUNT, COUNT*2);
  7022. if(nal_length<0){
  7023. printf("encoding failed\n");
  7024. return -1;
  7025. }
  7026. out= decode_nal(&h, nal, &out_length, &consumed, nal_length);
  7027. STOP_TIMER("NAL")
  7028. if(out_length != COUNT){
  7029. printf("incorrect length %d %d\n", out_length, COUNT);
  7030. return -1;
  7031. }
  7032. if(consumed != nal_length){
  7033. printf("incorrect consumed length %d %d\n", nal_length, consumed);
  7034. return -1;
  7035. }
  7036. if(memcmp(bitstream, out, COUNT)){
  7037. printf("mismatch\n");
  7038. return -1;
  7039. }
  7040. }
  7041. printf("Testing RBSP\n");
  7042. return 0;
  7043. }
  7044. #endif
  7045. static int decode_end(AVCodecContext *avctx)
  7046. {
  7047. H264Context *h = avctx->priv_data;
  7048. MpegEncContext *s = &h->s;
  7049. av_freep(&h->rbsp_buffer[0]);
  7050. av_freep(&h->rbsp_buffer[1]);
  7051. free_tables(h); //FIXME cleanup init stuff perhaps
  7052. MPV_common_end(s);
  7053. // memset(h, 0, sizeof(H264Context));
  7054. return 0;
  7055. }
  7056. AVCodec h264_decoder = {
  7057. "h264",
  7058. CODEC_TYPE_VIDEO,
  7059. CODEC_ID_H264,
  7060. sizeof(H264Context),
  7061. decode_init,
  7062. NULL,
  7063. decode_end,
  7064. decode_frame,
  7065. /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
  7066. .flush= flush_dpb,
  7067. };
  7068. #include "svq3.c"