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.

8108 lines
312KB

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