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.

8093 lines
311KB

  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= s->mb_x + s->mb_y*s->mb_stride;
  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= s->mb_x + s->mb_y*s->mb_stride;
  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= s->mb_x + s->mb_y*s->mb_stride;
  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 = s->mb_x + s->mb_y*s->mb_stride;
  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= s->mb_x + s->mb_y*s->mb_stride;
  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 = s->mb_x + s->mb_y*s->mb_stride;
  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= mb_x + mb_y*s->mb_stride;
  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--;
  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++;
  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= mb_x + mb_y*s->mb_stride;
  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= s->mb_x + s->mb_y*s->mb_stride;
  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= s->mb_x + s->mb_y*s->mb_stride;
  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. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  3975. int partition_count;
  3976. unsigned int mb_type, cbp;
  3977. int dct8x8_allowed= h->pps.transform_8x8_mode;
  3978. s->dsp.clear_blocks(h->mb); //FIXME avoid if already clear (move after skip handlong?
  3979. tprintf(s->avctx, "pic:%d mb:%d/%d\n", h->frame_num, s->mb_x, s->mb_y);
  3980. cbp = 0; /* avoid warning. FIXME: find a solution without slowing
  3981. down the code */
  3982. if(h->slice_type != FF_I_TYPE && h->slice_type != FF_SI_TYPE){
  3983. if(s->mb_skip_run==-1)
  3984. s->mb_skip_run= get_ue_golomb(&s->gb);
  3985. if (s->mb_skip_run--) {
  3986. if(FRAME_MBAFF && (s->mb_y&1) == 0){
  3987. if(s->mb_skip_run==0)
  3988. h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);
  3989. else
  3990. predict_field_decoding_flag(h);
  3991. }
  3992. decode_mb_skip(h);
  3993. return 0;
  3994. }
  3995. }
  3996. if(FRAME_MBAFF){
  3997. if( (s->mb_y&1) == 0 )
  3998. h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);
  3999. }else
  4000. h->mb_field_decoding_flag= (s->picture_structure!=PICT_FRAME);
  4001. h->prev_mb_skipped= 0;
  4002. mb_type= get_ue_golomb(&s->gb);
  4003. if(h->slice_type == FF_B_TYPE){
  4004. if(mb_type < 23){
  4005. partition_count= b_mb_type_info[mb_type].partition_count;
  4006. mb_type= b_mb_type_info[mb_type].type;
  4007. }else{
  4008. mb_type -= 23;
  4009. goto decode_intra_mb;
  4010. }
  4011. }else if(h->slice_type == FF_P_TYPE /*|| h->slice_type == FF_SP_TYPE */){
  4012. if(mb_type < 5){
  4013. partition_count= p_mb_type_info[mb_type].partition_count;
  4014. mb_type= p_mb_type_info[mb_type].type;
  4015. }else{
  4016. mb_type -= 5;
  4017. goto decode_intra_mb;
  4018. }
  4019. }else{
  4020. assert(h->slice_type == FF_I_TYPE);
  4021. decode_intra_mb:
  4022. if(mb_type > 25){
  4023. 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);
  4024. return -1;
  4025. }
  4026. partition_count=0;
  4027. cbp= i_mb_type_info[mb_type].cbp;
  4028. h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;
  4029. mb_type= i_mb_type_info[mb_type].type;
  4030. }
  4031. if(MB_FIELD)
  4032. mb_type |= MB_TYPE_INTERLACED;
  4033. h->slice_table[ mb_xy ]= h->slice_num;
  4034. if(IS_INTRA_PCM(mb_type)){
  4035. unsigned int x, y;
  4036. // We assume these blocks are very rare so we do not optimize it.
  4037. align_get_bits(&s->gb);
  4038. // The pixels are stored in the same order as levels in h->mb array.
  4039. for(y=0; y<16; y++){
  4040. const int index= 4*(y&3) + 32*((y>>2)&1) + 128*(y>>3);
  4041. for(x=0; x<16; x++){
  4042. tprintf(s->avctx, "LUMA ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
  4043. h->mb[index + (x&3) + 16*((x>>2)&1) + 64*(x>>3)]= get_bits(&s->gb, 8);
  4044. }
  4045. }
  4046. for(y=0; y<8; y++){
  4047. const int index= 256 + 4*(y&3) + 32*(y>>2);
  4048. for(x=0; x<8; x++){
  4049. tprintf(s->avctx, "CHROMA U ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
  4050. h->mb[index + (x&3) + 16*(x>>2)]= get_bits(&s->gb, 8);
  4051. }
  4052. }
  4053. for(y=0; y<8; y++){
  4054. const int index= 256 + 64 + 4*(y&3) + 32*(y>>2);
  4055. for(x=0; x<8; x++){
  4056. tprintf(s->avctx, "CHROMA V ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));
  4057. h->mb[index + (x&3) + 16*(x>>2)]= get_bits(&s->gb, 8);
  4058. }
  4059. }
  4060. // In deblocking, the quantizer is 0
  4061. s->current_picture.qscale_table[mb_xy]= 0;
  4062. h->chroma_qp[0] = get_chroma_qp(h, 0, 0);
  4063. h->chroma_qp[1] = get_chroma_qp(h, 1, 0);
  4064. // All coeffs are present
  4065. memset(h->non_zero_count[mb_xy], 16, 16);
  4066. s->current_picture.mb_type[mb_xy]= mb_type;
  4067. return 0;
  4068. }
  4069. if(MB_MBAFF){
  4070. h->ref_count[0] <<= 1;
  4071. h->ref_count[1] <<= 1;
  4072. }
  4073. fill_caches(h, mb_type, 0);
  4074. //mb_pred
  4075. if(IS_INTRA(mb_type)){
  4076. int pred_mode;
  4077. // init_top_left_availability(h);
  4078. if(IS_INTRA4x4(mb_type)){
  4079. int i;
  4080. int di = 1;
  4081. if(dct8x8_allowed && get_bits1(&s->gb)){
  4082. mb_type |= MB_TYPE_8x8DCT;
  4083. di = 4;
  4084. }
  4085. // fill_intra4x4_pred_table(h);
  4086. for(i=0; i<16; i+=di){
  4087. int mode= pred_intra_mode(h, i);
  4088. if(!get_bits1(&s->gb)){
  4089. const int rem_mode= get_bits(&s->gb, 3);
  4090. mode = rem_mode + (rem_mode >= mode);
  4091. }
  4092. if(di==4)
  4093. fill_rectangle( &h->intra4x4_pred_mode_cache[ scan8[i] ], 2, 2, 8, mode, 1 );
  4094. else
  4095. h->intra4x4_pred_mode_cache[ scan8[i] ] = mode;
  4096. }
  4097. write_back_intra_pred_mode(h);
  4098. if( check_intra4x4_pred_mode(h) < 0)
  4099. return -1;
  4100. }else{
  4101. h->intra16x16_pred_mode= check_intra_pred_mode(h, h->intra16x16_pred_mode);
  4102. if(h->intra16x16_pred_mode < 0)
  4103. return -1;
  4104. }
  4105. pred_mode= check_intra_pred_mode(h, get_ue_golomb(&s->gb));
  4106. if(pred_mode < 0)
  4107. return -1;
  4108. h->chroma_pred_mode= pred_mode;
  4109. }else if(partition_count==4){
  4110. int i, j, sub_partition_count[4], list, ref[2][4];
  4111. if(h->slice_type == FF_B_TYPE){
  4112. for(i=0; i<4; i++){
  4113. h->sub_mb_type[i]= get_ue_golomb(&s->gb);
  4114. if(h->sub_mb_type[i] >=13){
  4115. 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);
  4116. return -1;
  4117. }
  4118. sub_partition_count[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  4119. h->sub_mb_type[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  4120. }
  4121. if( IS_DIRECT(h->sub_mb_type[0]) || IS_DIRECT(h->sub_mb_type[1])
  4122. || IS_DIRECT(h->sub_mb_type[2]) || IS_DIRECT(h->sub_mb_type[3])) {
  4123. pred_direct_motion(h, &mb_type);
  4124. h->ref_cache[0][scan8[4]] =
  4125. h->ref_cache[1][scan8[4]] =
  4126. h->ref_cache[0][scan8[12]] =
  4127. h->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;
  4128. }
  4129. }else{
  4130. assert(h->slice_type == FF_P_TYPE || h->slice_type == FF_SP_TYPE); //FIXME SP correct ?
  4131. for(i=0; i<4; i++){
  4132. h->sub_mb_type[i]= get_ue_golomb(&s->gb);
  4133. if(h->sub_mb_type[i] >=4){
  4134. 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);
  4135. return -1;
  4136. }
  4137. sub_partition_count[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  4138. h->sub_mb_type[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  4139. }
  4140. }
  4141. for(list=0; list<h->list_count; list++){
  4142. int ref_count= IS_REF0(mb_type) ? 1 : h->ref_count[list];
  4143. for(i=0; i<4; i++){
  4144. if(IS_DIRECT(h->sub_mb_type[i])) continue;
  4145. if(IS_DIR(h->sub_mb_type[i], 0, list)){
  4146. unsigned int tmp = get_te0_golomb(&s->gb, ref_count); //FIXME init to 0 before and skip?
  4147. if(tmp>=ref_count){
  4148. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", tmp);
  4149. return -1;
  4150. }
  4151. ref[list][i]= tmp;
  4152. }else{
  4153. //FIXME
  4154. ref[list][i] = -1;
  4155. }
  4156. }
  4157. }
  4158. if(dct8x8_allowed)
  4159. dct8x8_allowed = get_dct8x8_allowed(h);
  4160. for(list=0; list<h->list_count; list++){
  4161. for(i=0; i<4; i++){
  4162. if(IS_DIRECT(h->sub_mb_type[i])) {
  4163. h->ref_cache[list][ scan8[4*i] ] = h->ref_cache[list][ scan8[4*i]+1 ];
  4164. continue;
  4165. }
  4166. h->ref_cache[list][ scan8[4*i] ]=h->ref_cache[list][ scan8[4*i]+1 ]=
  4167. h->ref_cache[list][ scan8[4*i]+8 ]=h->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];
  4168. if(IS_DIR(h->sub_mb_type[i], 0, list)){
  4169. const int sub_mb_type= h->sub_mb_type[i];
  4170. const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;
  4171. for(j=0; j<sub_partition_count[i]; j++){
  4172. int mx, my;
  4173. const int index= 4*i + block_width*j;
  4174. int16_t (* mv_cache)[2]= &h->mv_cache[list][ scan8[index] ];
  4175. pred_motion(h, index, block_width, list, h->ref_cache[list][ scan8[index] ], &mx, &my);
  4176. mx += get_se_golomb(&s->gb);
  4177. my += get_se_golomb(&s->gb);
  4178. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4179. if(IS_SUB_8X8(sub_mb_type)){
  4180. mv_cache[ 1 ][0]=
  4181. mv_cache[ 8 ][0]= mv_cache[ 9 ][0]= mx;
  4182. mv_cache[ 1 ][1]=
  4183. mv_cache[ 8 ][1]= mv_cache[ 9 ][1]= my;
  4184. }else if(IS_SUB_8X4(sub_mb_type)){
  4185. mv_cache[ 1 ][0]= mx;
  4186. mv_cache[ 1 ][1]= my;
  4187. }else if(IS_SUB_4X8(sub_mb_type)){
  4188. mv_cache[ 8 ][0]= mx;
  4189. mv_cache[ 8 ][1]= my;
  4190. }
  4191. mv_cache[ 0 ][0]= mx;
  4192. mv_cache[ 0 ][1]= my;
  4193. }
  4194. }else{
  4195. uint32_t *p= (uint32_t *)&h->mv_cache[list][ scan8[4*i] ][0];
  4196. p[0] = p[1]=
  4197. p[8] = p[9]= 0;
  4198. }
  4199. }
  4200. }
  4201. }else if(IS_DIRECT(mb_type)){
  4202. pred_direct_motion(h, &mb_type);
  4203. dct8x8_allowed &= h->sps.direct_8x8_inference_flag;
  4204. }else{
  4205. int list, mx, my, i;
  4206. //FIXME we should set ref_idx_l? to 0 if we use that later ...
  4207. if(IS_16X16(mb_type)){
  4208. for(list=0; list<h->list_count; list++){
  4209. unsigned int val;
  4210. if(IS_DIR(mb_type, 0, list)){
  4211. val= get_te0_golomb(&s->gb, h->ref_count[list]);
  4212. if(val >= h->ref_count[list]){
  4213. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
  4214. return -1;
  4215. }
  4216. }else
  4217. val= LIST_NOT_USED&0xFF;
  4218. fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, val, 1);
  4219. }
  4220. for(list=0; list<h->list_count; list++){
  4221. unsigned int val;
  4222. if(IS_DIR(mb_type, 0, list)){
  4223. pred_motion(h, 0, 4, list, h->ref_cache[list][ scan8[0] ], &mx, &my);
  4224. mx += get_se_golomb(&s->gb);
  4225. my += get_se_golomb(&s->gb);
  4226. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4227. val= pack16to32(mx,my);
  4228. }else
  4229. val=0;
  4230. fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, val, 4);
  4231. }
  4232. }
  4233. else if(IS_16X8(mb_type)){
  4234. for(list=0; list<h->list_count; list++){
  4235. for(i=0; i<2; i++){
  4236. unsigned int val;
  4237. if(IS_DIR(mb_type, i, list)){
  4238. val= get_te0_golomb(&s->gb, h->ref_count[list]);
  4239. if(val >= h->ref_count[list]){
  4240. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
  4241. return -1;
  4242. }
  4243. }else
  4244. val= LIST_NOT_USED&0xFF;
  4245. fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 1);
  4246. }
  4247. }
  4248. for(list=0; list<h->list_count; list++){
  4249. for(i=0; i<2; i++){
  4250. unsigned int val;
  4251. if(IS_DIR(mb_type, i, list)){
  4252. pred_16x8_motion(h, 8*i, list, h->ref_cache[list][scan8[0] + 16*i], &mx, &my);
  4253. mx += get_se_golomb(&s->gb);
  4254. my += get_se_golomb(&s->gb);
  4255. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4256. val= pack16to32(mx,my);
  4257. }else
  4258. val=0;
  4259. fill_rectangle(h->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 4);
  4260. }
  4261. }
  4262. }else{
  4263. assert(IS_8X16(mb_type));
  4264. for(list=0; list<h->list_count; list++){
  4265. for(i=0; i<2; i++){
  4266. unsigned int val;
  4267. if(IS_DIR(mb_type, i, list)){ //FIXME optimize
  4268. val= get_te0_golomb(&s->gb, h->ref_count[list]);
  4269. if(val >= h->ref_count[list]){
  4270. av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);
  4271. return -1;
  4272. }
  4273. }else
  4274. val= LIST_NOT_USED&0xFF;
  4275. fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 1);
  4276. }
  4277. }
  4278. for(list=0; list<h->list_count; list++){
  4279. for(i=0; i<2; i++){
  4280. unsigned int val;
  4281. if(IS_DIR(mb_type, i, list)){
  4282. pred_8x16_motion(h, i*4, list, h->ref_cache[list][ scan8[0] + 2*i ], &mx, &my);
  4283. mx += get_se_golomb(&s->gb);
  4284. my += get_se_golomb(&s->gb);
  4285. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  4286. val= pack16to32(mx,my);
  4287. }else
  4288. val=0;
  4289. fill_rectangle(h->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 4);
  4290. }
  4291. }
  4292. }
  4293. }
  4294. if(IS_INTER(mb_type))
  4295. write_back_motion(h, mb_type);
  4296. if(!IS_INTRA16x16(mb_type)){
  4297. cbp= get_ue_golomb(&s->gb);
  4298. if(cbp > 47){
  4299. av_log(h->s.avctx, AV_LOG_ERROR, "cbp too large (%u) at %d %d\n", cbp, s->mb_x, s->mb_y);
  4300. return -1;
  4301. }
  4302. if(IS_INTRA4x4(mb_type))
  4303. cbp= golomb_to_intra4x4_cbp[cbp];
  4304. else
  4305. cbp= golomb_to_inter_cbp[cbp];
  4306. }
  4307. h->cbp = cbp;
  4308. if(dct8x8_allowed && (cbp&15) && !IS_INTRA(mb_type)){
  4309. if(get_bits1(&s->gb))
  4310. mb_type |= MB_TYPE_8x8DCT;
  4311. }
  4312. s->current_picture.mb_type[mb_xy]= mb_type;
  4313. if(cbp || IS_INTRA16x16(mb_type)){
  4314. int i8x8, i4x4, chroma_idx;
  4315. int dquant;
  4316. GetBitContext *gb= IS_INTRA(mb_type) ? h->intra_gb_ptr : h->inter_gb_ptr;
  4317. const uint8_t *scan, *scan8x8, *dc_scan;
  4318. // fill_non_zero_count_cache(h);
  4319. if(IS_INTERLACED(mb_type)){
  4320. scan8x8= s->qscale ? h->field_scan8x8_cavlc : h->field_scan8x8_cavlc_q0;
  4321. scan= s->qscale ? h->field_scan : h->field_scan_q0;
  4322. dc_scan= luma_dc_field_scan;
  4323. }else{
  4324. scan8x8= s->qscale ? h->zigzag_scan8x8_cavlc : h->zigzag_scan8x8_cavlc_q0;
  4325. scan= s->qscale ? h->zigzag_scan : h->zigzag_scan_q0;
  4326. dc_scan= luma_dc_zigzag_scan;
  4327. }
  4328. dquant= get_se_golomb(&s->gb);
  4329. if( dquant > 25 || dquant < -26 ){
  4330. av_log(h->s.avctx, AV_LOG_ERROR, "dquant out of range (%d) at %d %d\n", dquant, s->mb_x, s->mb_y);
  4331. return -1;
  4332. }
  4333. s->qscale += dquant;
  4334. if(((unsigned)s->qscale) > 51){
  4335. if(s->qscale<0) s->qscale+= 52;
  4336. else s->qscale-= 52;
  4337. }
  4338. h->chroma_qp[0]= get_chroma_qp(h, 0, s->qscale);
  4339. h->chroma_qp[1]= get_chroma_qp(h, 1, s->qscale);
  4340. if(IS_INTRA16x16(mb_type)){
  4341. if( decode_residual(h, h->intra_gb_ptr, h->mb, LUMA_DC_BLOCK_INDEX, dc_scan, h->dequant4_coeff[0][s->qscale], 16) < 0){
  4342. return -1; //FIXME continue if partitioned and other return -1 too
  4343. }
  4344. assert((cbp&15) == 0 || (cbp&15) == 15);
  4345. if(cbp&15){
  4346. for(i8x8=0; i8x8<4; i8x8++){
  4347. for(i4x4=0; i4x4<4; i4x4++){
  4348. const int index= i4x4 + 4*i8x8;
  4349. if( decode_residual(h, h->intra_gb_ptr, h->mb + 16*index, index, scan + 1, h->dequant4_coeff[0][s->qscale], 15) < 0 ){
  4350. return -1;
  4351. }
  4352. }
  4353. }
  4354. }else{
  4355. fill_rectangle(&h->non_zero_count_cache[scan8[0]], 4, 4, 8, 0, 1);
  4356. }
  4357. }else{
  4358. for(i8x8=0; i8x8<4; i8x8++){
  4359. if(cbp & (1<<i8x8)){
  4360. if(IS_8x8DCT(mb_type)){
  4361. DCTELEM *buf = &h->mb[64*i8x8];
  4362. uint8_t *nnz;
  4363. for(i4x4=0; i4x4<4; i4x4++){
  4364. if( decode_residual(h, gb, buf, i4x4+4*i8x8, scan8x8+16*i4x4,
  4365. h->dequant8_coeff[IS_INTRA( mb_type ) ? 0:1][s->qscale], 16) <0 )
  4366. return -1;
  4367. }
  4368. nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
  4369. nnz[0] += nnz[1] + nnz[8] + nnz[9];
  4370. }else{
  4371. for(i4x4=0; i4x4<4; i4x4++){
  4372. const int index= i4x4 + 4*i8x8;
  4373. if( decode_residual(h, gb, h->mb + 16*index, index, scan, h->dequant4_coeff[IS_INTRA( mb_type ) ? 0:3][s->qscale], 16) <0 ){
  4374. return -1;
  4375. }
  4376. }
  4377. }
  4378. }else{
  4379. uint8_t * const nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
  4380. nnz[0] = nnz[1] = nnz[8] = nnz[9] = 0;
  4381. }
  4382. }
  4383. }
  4384. if(cbp&0x30){
  4385. for(chroma_idx=0; chroma_idx<2; chroma_idx++)
  4386. if( decode_residual(h, gb, h->mb + 256 + 16*4*chroma_idx, CHROMA_DC_BLOCK_INDEX, chroma_dc_scan, NULL, 4) < 0){
  4387. return -1;
  4388. }
  4389. }
  4390. if(cbp&0x20){
  4391. for(chroma_idx=0; chroma_idx<2; chroma_idx++){
  4392. const uint32_t *qmul = h->dequant4_coeff[chroma_idx+1+(IS_INTRA( mb_type ) ? 0:3)][h->chroma_qp[chroma_idx]];
  4393. for(i4x4=0; i4x4<4; i4x4++){
  4394. const int index= 16 + 4*chroma_idx + i4x4;
  4395. if( decode_residual(h, gb, h->mb + 16*index, index, scan + 1, qmul, 15) < 0){
  4396. return -1;
  4397. }
  4398. }
  4399. }
  4400. }else{
  4401. uint8_t * const nnz= &h->non_zero_count_cache[0];
  4402. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  4403. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  4404. }
  4405. }else{
  4406. uint8_t * const nnz= &h->non_zero_count_cache[0];
  4407. fill_rectangle(&nnz[scan8[0]], 4, 4, 8, 0, 1);
  4408. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  4409. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  4410. }
  4411. s->current_picture.qscale_table[mb_xy]= s->qscale;
  4412. write_back_non_zero_count(h);
  4413. if(MB_MBAFF){
  4414. h->ref_count[0] >>= 1;
  4415. h->ref_count[1] >>= 1;
  4416. }
  4417. return 0;
  4418. }
  4419. static int decode_cabac_field_decoding_flag(H264Context *h) {
  4420. MpegEncContext * const s = &h->s;
  4421. const int mb_x = s->mb_x;
  4422. const int mb_y = s->mb_y & ~1;
  4423. const int mba_xy = mb_x - 1 + mb_y *s->mb_stride;
  4424. const int mbb_xy = mb_x + (mb_y-2)*s->mb_stride;
  4425. unsigned int ctx = 0;
  4426. if( h->slice_table[mba_xy] == h->slice_num && IS_INTERLACED( s->current_picture.mb_type[mba_xy] ) ) {
  4427. ctx += 1;
  4428. }
  4429. if( h->slice_table[mbb_xy] == h->slice_num && IS_INTERLACED( s->current_picture.mb_type[mbb_xy] ) ) {
  4430. ctx += 1;
  4431. }
  4432. return get_cabac_noinline( &h->cabac, &h->cabac_state[70 + ctx] );
  4433. }
  4434. static int decode_cabac_intra_mb_type(H264Context *h, int ctx_base, int intra_slice) {
  4435. uint8_t *state= &h->cabac_state[ctx_base];
  4436. int mb_type;
  4437. if(intra_slice){
  4438. MpegEncContext * const s = &h->s;
  4439. const int mba_xy = h->left_mb_xy[0];
  4440. const int mbb_xy = h->top_mb_xy;
  4441. int ctx=0;
  4442. if( h->slice_table[mba_xy] == h->slice_num && !IS_INTRA4x4( s->current_picture.mb_type[mba_xy] ) )
  4443. ctx++;
  4444. if( h->slice_table[mbb_xy] == h->slice_num && !IS_INTRA4x4( s->current_picture.mb_type[mbb_xy] ) )
  4445. ctx++;
  4446. if( get_cabac_noinline( &h->cabac, &state[ctx] ) == 0 )
  4447. return 0; /* I4x4 */
  4448. state += 2;
  4449. }else{
  4450. if( get_cabac_noinline( &h->cabac, &state[0] ) == 0 )
  4451. return 0; /* I4x4 */
  4452. }
  4453. if( get_cabac_terminate( &h->cabac ) )
  4454. return 25; /* PCM */
  4455. mb_type = 1; /* I16x16 */
  4456. mb_type += 12 * get_cabac_noinline( &h->cabac, &state[1] ); /* cbp_luma != 0 */
  4457. if( get_cabac_noinline( &h->cabac, &state[2] ) ) /* cbp_chroma */
  4458. mb_type += 4 + 4 * get_cabac_noinline( &h->cabac, &state[2+intra_slice] );
  4459. mb_type += 2 * get_cabac_noinline( &h->cabac, &state[3+intra_slice] );
  4460. mb_type += 1 * get_cabac_noinline( &h->cabac, &state[3+2*intra_slice] );
  4461. return mb_type;
  4462. }
  4463. static int decode_cabac_mb_type( H264Context *h ) {
  4464. MpegEncContext * const s = &h->s;
  4465. if( h->slice_type == FF_I_TYPE ) {
  4466. return decode_cabac_intra_mb_type(h, 3, 1);
  4467. } else if( h->slice_type == FF_P_TYPE ) {
  4468. if( get_cabac_noinline( &h->cabac, &h->cabac_state[14] ) == 0 ) {
  4469. /* P-type */
  4470. if( get_cabac_noinline( &h->cabac, &h->cabac_state[15] ) == 0 ) {
  4471. /* P_L0_D16x16, P_8x8 */
  4472. return 3 * get_cabac_noinline( &h->cabac, &h->cabac_state[16] );
  4473. } else {
  4474. /* P_L0_D8x16, P_L0_D16x8 */
  4475. return 2 - get_cabac_noinline( &h->cabac, &h->cabac_state[17] );
  4476. }
  4477. } else {
  4478. return decode_cabac_intra_mb_type(h, 17, 0) + 5;
  4479. }
  4480. } else if( h->slice_type == FF_B_TYPE ) {
  4481. const int mba_xy = h->left_mb_xy[0];
  4482. const int mbb_xy = h->top_mb_xy;
  4483. int ctx = 0;
  4484. int bits;
  4485. if( h->slice_table[mba_xy] == h->slice_num && !IS_DIRECT( s->current_picture.mb_type[mba_xy] ) )
  4486. ctx++;
  4487. if( h->slice_table[mbb_xy] == h->slice_num && !IS_DIRECT( s->current_picture.mb_type[mbb_xy] ) )
  4488. ctx++;
  4489. if( !get_cabac_noinline( &h->cabac, &h->cabac_state[27+ctx] ) )
  4490. return 0; /* B_Direct_16x16 */
  4491. if( !get_cabac_noinline( &h->cabac, &h->cabac_state[27+3] ) ) {
  4492. return 1 + get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ); /* B_L[01]_16x16 */
  4493. }
  4494. bits = get_cabac_noinline( &h->cabac, &h->cabac_state[27+4] ) << 3;
  4495. bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ) << 2;
  4496. bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] ) << 1;
  4497. bits|= get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] );
  4498. if( bits < 8 )
  4499. return bits + 3; /* B_Bi_16x16 through B_L1_L0_16x8 */
  4500. else if( bits == 13 ) {
  4501. return decode_cabac_intra_mb_type(h, 32, 0) + 23;
  4502. } else if( bits == 14 )
  4503. return 11; /* B_L1_L0_8x16 */
  4504. else if( bits == 15 )
  4505. return 22; /* B_8x8 */
  4506. bits= ( bits<<1 ) | get_cabac_noinline( &h->cabac, &h->cabac_state[27+5] );
  4507. return bits - 4; /* B_L0_Bi_* through B_Bi_Bi_* */
  4508. } else {
  4509. /* TODO SI/SP frames? */
  4510. return -1;
  4511. }
  4512. }
  4513. static int decode_cabac_mb_skip( H264Context *h, int mb_x, int mb_y ) {
  4514. MpegEncContext * const s = &h->s;
  4515. int mba_xy, mbb_xy;
  4516. int ctx = 0;
  4517. if(FRAME_MBAFF){ //FIXME merge with the stuff in fill_caches?
  4518. int mb_xy = mb_x + (mb_y&~1)*s->mb_stride;
  4519. mba_xy = mb_xy - 1;
  4520. if( (mb_y&1)
  4521. && h->slice_table[mba_xy] == h->slice_num
  4522. && MB_FIELD == !!IS_INTERLACED( s->current_picture.mb_type[mba_xy] ) )
  4523. mba_xy += s->mb_stride;
  4524. if( MB_FIELD ){
  4525. mbb_xy = mb_xy - s->mb_stride;
  4526. if( !(mb_y&1)
  4527. && h->slice_table[mbb_xy] == h->slice_num
  4528. && IS_INTERLACED( s->current_picture.mb_type[mbb_xy] ) )
  4529. mbb_xy -= s->mb_stride;
  4530. }else
  4531. mbb_xy = mb_x + (mb_y-1)*s->mb_stride;
  4532. }else{
  4533. int mb_xy = mb_x + mb_y*s->mb_stride;
  4534. mba_xy = mb_xy - 1;
  4535. mbb_xy = mb_xy - (s->mb_stride << FIELD_PICTURE);
  4536. }
  4537. if( h->slice_table[mba_xy] == h->slice_num && !IS_SKIP( s->current_picture.mb_type[mba_xy] ))
  4538. ctx++;
  4539. if( h->slice_table[mbb_xy] == h->slice_num && !IS_SKIP( s->current_picture.mb_type[mbb_xy] ))
  4540. ctx++;
  4541. if( h->slice_type == FF_B_TYPE )
  4542. ctx += 13;
  4543. return get_cabac_noinline( &h->cabac, &h->cabac_state[11+ctx] );
  4544. }
  4545. static int decode_cabac_mb_intra4x4_pred_mode( H264Context *h, int pred_mode ) {
  4546. int mode = 0;
  4547. if( get_cabac( &h->cabac, &h->cabac_state[68] ) )
  4548. return pred_mode;
  4549. mode += 1 * get_cabac( &h->cabac, &h->cabac_state[69] );
  4550. mode += 2 * get_cabac( &h->cabac, &h->cabac_state[69] );
  4551. mode += 4 * get_cabac( &h->cabac, &h->cabac_state[69] );
  4552. if( mode >= pred_mode )
  4553. return mode + 1;
  4554. else
  4555. return mode;
  4556. }
  4557. static int decode_cabac_mb_chroma_pre_mode( H264Context *h) {
  4558. const int mba_xy = h->left_mb_xy[0];
  4559. const int mbb_xy = h->top_mb_xy;
  4560. int ctx = 0;
  4561. /* No need to test for IS_INTRA4x4 and IS_INTRA16x16, as we set chroma_pred_mode_table to 0 */
  4562. if( h->slice_table[mba_xy] == h->slice_num && h->chroma_pred_mode_table[mba_xy] != 0 )
  4563. ctx++;
  4564. if( h->slice_table[mbb_xy] == h->slice_num && h->chroma_pred_mode_table[mbb_xy] != 0 )
  4565. ctx++;
  4566. if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+ctx] ) == 0 )
  4567. return 0;
  4568. if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+3] ) == 0 )
  4569. return 1;
  4570. if( get_cabac_noinline( &h->cabac, &h->cabac_state[64+3] ) == 0 )
  4571. return 2;
  4572. else
  4573. return 3;
  4574. }
  4575. static int decode_cabac_mb_cbp_luma( H264Context *h) {
  4576. int cbp_b, cbp_a, ctx, cbp = 0;
  4577. cbp_a = h->slice_table[h->left_mb_xy[0]] == h->slice_num ? h->left_cbp : -1;
  4578. cbp_b = h->slice_table[h->top_mb_xy] == h->slice_num ? h->top_cbp : -1;
  4579. ctx = !(cbp_a & 0x02) + 2 * !(cbp_b & 0x04);
  4580. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]);
  4581. ctx = !(cbp & 0x01) + 2 * !(cbp_b & 0x08);
  4582. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 1;
  4583. ctx = !(cbp_a & 0x08) + 2 * !(cbp & 0x01);
  4584. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 2;
  4585. ctx = !(cbp & 0x04) + 2 * !(cbp & 0x02);
  4586. cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 3;
  4587. return cbp;
  4588. }
  4589. static int decode_cabac_mb_cbp_chroma( H264Context *h) {
  4590. int ctx;
  4591. int cbp_a, cbp_b;
  4592. cbp_a = (h->left_cbp>>4)&0x03;
  4593. cbp_b = (h-> top_cbp>>4)&0x03;
  4594. ctx = 0;
  4595. if( cbp_a > 0 ) ctx++;
  4596. if( cbp_b > 0 ) ctx += 2;
  4597. if( get_cabac_noinline( &h->cabac, &h->cabac_state[77 + ctx] ) == 0 )
  4598. return 0;
  4599. ctx = 4;
  4600. if( cbp_a == 2 ) ctx++;
  4601. if( cbp_b == 2 ) ctx += 2;
  4602. return 1 + get_cabac_noinline( &h->cabac, &h->cabac_state[77 + ctx] );
  4603. }
  4604. static int decode_cabac_mb_dqp( H264Context *h) {
  4605. int ctx = 0;
  4606. int val = 0;
  4607. if( h->last_qscale_diff != 0 )
  4608. ctx++;
  4609. while( get_cabac_noinline( &h->cabac, &h->cabac_state[60 + ctx] ) ) {
  4610. if( ctx < 2 )
  4611. ctx = 2;
  4612. else
  4613. ctx = 3;
  4614. val++;
  4615. if(val > 102) //prevent infinite loop
  4616. return INT_MIN;
  4617. }
  4618. if( val&0x01 )
  4619. return (val + 1)/2;
  4620. else
  4621. return -(val + 1)/2;
  4622. }
  4623. static int decode_cabac_p_mb_sub_type( H264Context *h ) {
  4624. if( get_cabac( &h->cabac, &h->cabac_state[21] ) )
  4625. return 0; /* 8x8 */
  4626. if( !get_cabac( &h->cabac, &h->cabac_state[22] ) )
  4627. return 1; /* 8x4 */
  4628. if( get_cabac( &h->cabac, &h->cabac_state[23] ) )
  4629. return 2; /* 4x8 */
  4630. return 3; /* 4x4 */
  4631. }
  4632. static int decode_cabac_b_mb_sub_type( H264Context *h ) {
  4633. int type;
  4634. if( !get_cabac( &h->cabac, &h->cabac_state[36] ) )
  4635. return 0; /* B_Direct_8x8 */
  4636. if( !get_cabac( &h->cabac, &h->cabac_state[37] ) )
  4637. return 1 + get_cabac( &h->cabac, &h->cabac_state[39] ); /* B_L0_8x8, B_L1_8x8 */
  4638. type = 3;
  4639. if( get_cabac( &h->cabac, &h->cabac_state[38] ) ) {
  4640. if( get_cabac( &h->cabac, &h->cabac_state[39] ) )
  4641. return 11 + get_cabac( &h->cabac, &h->cabac_state[39] ); /* B_L1_4x4, B_Bi_4x4 */
  4642. type += 4;
  4643. }
  4644. type += 2*get_cabac( &h->cabac, &h->cabac_state[39] );
  4645. type += get_cabac( &h->cabac, &h->cabac_state[39] );
  4646. return type;
  4647. }
  4648. static inline int decode_cabac_mb_transform_size( H264Context *h ) {
  4649. return get_cabac_noinline( &h->cabac, &h->cabac_state[399 + h->neighbor_transform_size] );
  4650. }
  4651. static int decode_cabac_mb_ref( H264Context *h, int list, int n ) {
  4652. int refa = h->ref_cache[list][scan8[n] - 1];
  4653. int refb = h->ref_cache[list][scan8[n] - 8];
  4654. int ref = 0;
  4655. int ctx = 0;
  4656. if( h->slice_type == FF_B_TYPE) {
  4657. if( refa > 0 && !h->direct_cache[scan8[n] - 1] )
  4658. ctx++;
  4659. if( refb > 0 && !h->direct_cache[scan8[n] - 8] )
  4660. ctx += 2;
  4661. } else {
  4662. if( refa > 0 )
  4663. ctx++;
  4664. if( refb > 0 )
  4665. ctx += 2;
  4666. }
  4667. while( get_cabac( &h->cabac, &h->cabac_state[54+ctx] ) ) {
  4668. ref++;
  4669. if( ctx < 4 )
  4670. ctx = 4;
  4671. else
  4672. ctx = 5;
  4673. if(ref >= 32 /*h->ref_list[list]*/){
  4674. av_log(h->s.avctx, AV_LOG_ERROR, "overflow in decode_cabac_mb_ref\n");
  4675. return 0; //FIXME we should return -1 and check the return everywhere
  4676. }
  4677. }
  4678. return ref;
  4679. }
  4680. static int decode_cabac_mb_mvd( H264Context *h, int list, int n, int l ) {
  4681. int amvd = abs( h->mvd_cache[list][scan8[n] - 1][l] ) +
  4682. abs( h->mvd_cache[list][scan8[n] - 8][l] );
  4683. int ctxbase = (l == 0) ? 40 : 47;
  4684. int ctx, mvd;
  4685. if( amvd < 3 )
  4686. ctx = 0;
  4687. else if( amvd > 32 )
  4688. ctx = 2;
  4689. else
  4690. ctx = 1;
  4691. if(!get_cabac(&h->cabac, &h->cabac_state[ctxbase+ctx]))
  4692. return 0;
  4693. mvd= 1;
  4694. ctx= 3;
  4695. while( mvd < 9 && get_cabac( &h->cabac, &h->cabac_state[ctxbase+ctx] ) ) {
  4696. mvd++;
  4697. if( ctx < 6 )
  4698. ctx++;
  4699. }
  4700. if( mvd >= 9 ) {
  4701. int k = 3;
  4702. while( get_cabac_bypass( &h->cabac ) ) {
  4703. mvd += 1 << k;
  4704. k++;
  4705. if(k>24){
  4706. av_log(h->s.avctx, AV_LOG_ERROR, "overflow in decode_cabac_mb_mvd\n");
  4707. return INT_MIN;
  4708. }
  4709. }
  4710. while( k-- ) {
  4711. if( get_cabac_bypass( &h->cabac ) )
  4712. mvd += 1 << k;
  4713. }
  4714. }
  4715. return get_cabac_bypass_sign( &h->cabac, -mvd );
  4716. }
  4717. static inline int get_cabac_cbf_ctx( H264Context *h, int cat, int idx ) {
  4718. int nza, nzb;
  4719. int ctx = 0;
  4720. if( cat == 0 ) {
  4721. nza = h->left_cbp&0x100;
  4722. nzb = h-> top_cbp&0x100;
  4723. } else if( cat == 1 || cat == 2 ) {
  4724. nza = h->non_zero_count_cache[scan8[idx] - 1];
  4725. nzb = h->non_zero_count_cache[scan8[idx] - 8];
  4726. } else if( cat == 3 ) {
  4727. nza = (h->left_cbp>>(6+idx))&0x01;
  4728. nzb = (h-> top_cbp>>(6+idx))&0x01;
  4729. } else {
  4730. assert(cat == 4);
  4731. nza = h->non_zero_count_cache[scan8[16+idx] - 1];
  4732. nzb = h->non_zero_count_cache[scan8[16+idx] - 8];
  4733. }
  4734. if( nza > 0 )
  4735. ctx++;
  4736. if( nzb > 0 )
  4737. ctx += 2;
  4738. return ctx + 4 * cat;
  4739. }
  4740. DECLARE_ASM_CONST(1, const uint8_t, last_coeff_flag_offset_8x8[63]) = {
  4741. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  4742. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  4743. 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
  4744. 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8
  4745. };
  4746. static void decode_cabac_residual( H264Context *h, DCTELEM *block, int cat, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff) {
  4747. const int mb_xy = h->s.mb_x + h->s.mb_y*h->s.mb_stride;
  4748. static const int significant_coeff_flag_offset[2][6] = {
  4749. { 105+0, 105+15, 105+29, 105+44, 105+47, 402 },
  4750. { 277+0, 277+15, 277+29, 277+44, 277+47, 436 }
  4751. };
  4752. static const int last_coeff_flag_offset[2][6] = {
  4753. { 166+0, 166+15, 166+29, 166+44, 166+47, 417 },
  4754. { 338+0, 338+15, 338+29, 338+44, 338+47, 451 }
  4755. };
  4756. static const int coeff_abs_level_m1_offset[6] = {
  4757. 227+0, 227+10, 227+20, 227+30, 227+39, 426
  4758. };
  4759. static const uint8_t significant_coeff_flag_offset_8x8[2][63] = {
  4760. { 0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5,
  4761. 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9,10, 9, 8, 7,
  4762. 7, 6,11,12,13,11, 6, 7, 8, 9,14,10, 9, 8, 6,11,
  4763. 12,13,11, 6, 9,14,10, 9,11,12,13,11,14,10,12 },
  4764. { 0, 1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 7, 7, 8, 4, 5,
  4765. 6, 9,10,10, 8,11,12,11, 9, 9,10,10, 8,11,12,11,
  4766. 9, 9,10,10, 8,11,12,11, 9, 9,10,10, 8,13,13, 9,
  4767. 9,10,10, 8,13,13, 9, 9,10,10,14,14,14,14,14 }
  4768. };
  4769. int index[64];
  4770. int av_unused last;
  4771. int coeff_count = 0;
  4772. int abslevel1 = 1;
  4773. int abslevelgt1 = 0;
  4774. uint8_t *significant_coeff_ctx_base;
  4775. uint8_t *last_coeff_ctx_base;
  4776. uint8_t *abs_level_m1_ctx_base;
  4777. #ifndef ARCH_X86
  4778. #define CABAC_ON_STACK
  4779. #endif
  4780. #ifdef CABAC_ON_STACK
  4781. #define CC &cc
  4782. CABACContext cc;
  4783. cc.range = h->cabac.range;
  4784. cc.low = h->cabac.low;
  4785. cc.bytestream= h->cabac.bytestream;
  4786. #else
  4787. #define CC &h->cabac
  4788. #endif
  4789. /* cat: 0-> DC 16x16 n = 0
  4790. * 1-> AC 16x16 n = luma4x4idx
  4791. * 2-> Luma4x4 n = luma4x4idx
  4792. * 3-> DC Chroma n = iCbCr
  4793. * 4-> AC Chroma n = 4 * iCbCr + chroma4x4idx
  4794. * 5-> Luma8x8 n = 4 * luma8x8idx
  4795. */
  4796. /* read coded block flag */
  4797. if( cat != 5 ) {
  4798. if( get_cabac( CC, &h->cabac_state[85 + get_cabac_cbf_ctx( h, cat, n ) ] ) == 0 ) {
  4799. if( cat == 1 || cat == 2 )
  4800. h->non_zero_count_cache[scan8[n]] = 0;
  4801. else if( cat == 4 )
  4802. h->non_zero_count_cache[scan8[16+n]] = 0;
  4803. #ifdef CABAC_ON_STACK
  4804. h->cabac.range = cc.range ;
  4805. h->cabac.low = cc.low ;
  4806. h->cabac.bytestream= cc.bytestream;
  4807. #endif
  4808. return;
  4809. }
  4810. }
  4811. significant_coeff_ctx_base = h->cabac_state
  4812. + significant_coeff_flag_offset[MB_FIELD][cat];
  4813. last_coeff_ctx_base = h->cabac_state
  4814. + last_coeff_flag_offset[MB_FIELD][cat];
  4815. abs_level_m1_ctx_base = h->cabac_state
  4816. + coeff_abs_level_m1_offset[cat];
  4817. if( cat == 5 ) {
  4818. #define DECODE_SIGNIFICANCE( coefs, sig_off, last_off ) \
  4819. for(last= 0; last < coefs; last++) { \
  4820. uint8_t *sig_ctx = significant_coeff_ctx_base + sig_off; \
  4821. if( get_cabac( CC, sig_ctx )) { \
  4822. uint8_t *last_ctx = last_coeff_ctx_base + last_off; \
  4823. index[coeff_count++] = last; \
  4824. if( get_cabac( CC, last_ctx ) ) { \
  4825. last= max_coeff; \
  4826. break; \
  4827. } \
  4828. } \
  4829. }\
  4830. if( last == max_coeff -1 ) {\
  4831. index[coeff_count++] = last;\
  4832. }
  4833. const uint8_t *sig_off = significant_coeff_flag_offset_8x8[MB_FIELD];
  4834. #if defined(ARCH_X86) && defined(HAVE_7REGS) && defined(HAVE_EBX_AVAILABLE) && !defined(BROKEN_RELOCATIONS)
  4835. coeff_count= decode_significance_8x8_x86(CC, significant_coeff_ctx_base, index, sig_off);
  4836. } else {
  4837. coeff_count= decode_significance_x86(CC, max_coeff, significant_coeff_ctx_base, index);
  4838. #else
  4839. DECODE_SIGNIFICANCE( 63, sig_off[last], last_coeff_flag_offset_8x8[last] );
  4840. } else {
  4841. DECODE_SIGNIFICANCE( max_coeff - 1, last, last );
  4842. #endif
  4843. }
  4844. assert(coeff_count > 0);
  4845. if( cat == 0 )
  4846. h->cbp_table[mb_xy] |= 0x100;
  4847. else if( cat == 1 || cat == 2 )
  4848. h->non_zero_count_cache[scan8[n]] = coeff_count;
  4849. else if( cat == 3 )
  4850. h->cbp_table[mb_xy] |= 0x40 << n;
  4851. else if( cat == 4 )
  4852. h->non_zero_count_cache[scan8[16+n]] = coeff_count;
  4853. else {
  4854. assert( cat == 5 );
  4855. fill_rectangle(&h->non_zero_count_cache[scan8[n]], 2, 2, 8, coeff_count, 1);
  4856. }
  4857. for( coeff_count--; coeff_count >= 0; coeff_count-- ) {
  4858. uint8_t *ctx = (abslevelgt1 != 0 ? 0 : FFMIN( 4, abslevel1 )) + abs_level_m1_ctx_base;
  4859. int j= scantable[index[coeff_count]];
  4860. if( get_cabac( CC, ctx ) == 0 ) {
  4861. if( !qmul ) {
  4862. block[j] = get_cabac_bypass_sign( CC, -1);
  4863. }else{
  4864. block[j] = (get_cabac_bypass_sign( CC, -qmul[j]) + 32) >> 6;
  4865. }
  4866. abslevel1++;
  4867. } else {
  4868. int coeff_abs = 2;
  4869. ctx = 5 + FFMIN( 4, abslevelgt1 ) + abs_level_m1_ctx_base;
  4870. while( coeff_abs < 15 && get_cabac( CC, ctx ) ) {
  4871. coeff_abs++;
  4872. }
  4873. if( coeff_abs >= 15 ) {
  4874. int j = 0;
  4875. while( get_cabac_bypass( CC ) ) {
  4876. j++;
  4877. }
  4878. coeff_abs=1;
  4879. while( j-- ) {
  4880. coeff_abs += coeff_abs + get_cabac_bypass( CC );
  4881. }
  4882. coeff_abs+= 14;
  4883. }
  4884. if( !qmul ) {
  4885. if( get_cabac_bypass( CC ) ) block[j] = -coeff_abs;
  4886. else block[j] = coeff_abs;
  4887. }else{
  4888. if( get_cabac_bypass( CC ) ) block[j] = (-coeff_abs * qmul[j] + 32) >> 6;
  4889. else block[j] = ( coeff_abs * qmul[j] + 32) >> 6;
  4890. }
  4891. abslevelgt1++;
  4892. }
  4893. }
  4894. #ifdef CABAC_ON_STACK
  4895. h->cabac.range = cc.range ;
  4896. h->cabac.low = cc.low ;
  4897. h->cabac.bytestream= cc.bytestream;
  4898. #endif
  4899. }
  4900. static inline void compute_mb_neighbors(H264Context *h)
  4901. {
  4902. MpegEncContext * const s = &h->s;
  4903. const int mb_xy = s->mb_x + s->mb_y*s->mb_stride;
  4904. h->top_mb_xy = mb_xy - s->mb_stride;
  4905. h->left_mb_xy[0] = mb_xy - 1;
  4906. if(FRAME_MBAFF){
  4907. const int pair_xy = s->mb_x + (s->mb_y & ~1)*s->mb_stride;
  4908. const int top_pair_xy = pair_xy - s->mb_stride;
  4909. const int top_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[top_pair_xy]);
  4910. const int left_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[pair_xy-1]);
  4911. const int curr_mb_frame_flag = !MB_FIELD;
  4912. const int bottom = (s->mb_y & 1);
  4913. if (bottom
  4914. ? !curr_mb_frame_flag // bottom macroblock
  4915. : (!curr_mb_frame_flag && !top_mb_frame_flag) // top macroblock
  4916. ) {
  4917. h->top_mb_xy -= s->mb_stride;
  4918. }
  4919. if (left_mb_frame_flag != curr_mb_frame_flag) {
  4920. h->left_mb_xy[0] = pair_xy - 1;
  4921. }
  4922. } else if (FIELD_PICTURE) {
  4923. h->top_mb_xy -= s->mb_stride;
  4924. }
  4925. return;
  4926. }
  4927. /**
  4928. * decodes a macroblock
  4929. * @returns 0 if ok, AC_ERROR / DC_ERROR / MV_ERROR if an error is noticed
  4930. */
  4931. static int decode_mb_cabac(H264Context *h) {
  4932. MpegEncContext * const s = &h->s;
  4933. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  4934. int mb_type, partition_count, cbp = 0;
  4935. int dct8x8_allowed= h->pps.transform_8x8_mode;
  4936. s->dsp.clear_blocks(h->mb); //FIXME avoid if already clear (move after skip handlong?)
  4937. tprintf(s->avctx, "pic:%d mb:%d/%d\n", h->frame_num, s->mb_x, s->mb_y);
  4938. if( h->slice_type != FF_I_TYPE && h->slice_type != FF_SI_TYPE ) {
  4939. int skip;
  4940. /* a skipped mb needs the aff flag from the following mb */
  4941. if( FRAME_MBAFF && s->mb_x==0 && (s->mb_y&1)==0 )
  4942. predict_field_decoding_flag(h);
  4943. if( FRAME_MBAFF && (s->mb_y&1)==1 && h->prev_mb_skipped )
  4944. skip = h->next_mb_skipped;
  4945. else
  4946. skip = decode_cabac_mb_skip( h, s->mb_x, s->mb_y );
  4947. /* read skip flags */
  4948. if( skip ) {
  4949. if( FRAME_MBAFF && (s->mb_y&1)==0 ){
  4950. s->current_picture.mb_type[mb_xy] = MB_TYPE_SKIP;
  4951. h->next_mb_skipped = decode_cabac_mb_skip( h, s->mb_x, s->mb_y+1 );
  4952. if(h->next_mb_skipped)
  4953. predict_field_decoding_flag(h);
  4954. else
  4955. h->mb_mbaff = h->mb_field_decoding_flag = decode_cabac_field_decoding_flag(h);
  4956. }
  4957. decode_mb_skip(h);
  4958. h->cbp_table[mb_xy] = 0;
  4959. h->chroma_pred_mode_table[mb_xy] = 0;
  4960. h->last_qscale_diff = 0;
  4961. return 0;
  4962. }
  4963. }
  4964. if(FRAME_MBAFF){
  4965. if( (s->mb_y&1) == 0 )
  4966. h->mb_mbaff =
  4967. h->mb_field_decoding_flag = decode_cabac_field_decoding_flag(h);
  4968. }else
  4969. h->mb_field_decoding_flag= (s->picture_structure!=PICT_FRAME);
  4970. h->prev_mb_skipped = 0;
  4971. compute_mb_neighbors(h);
  4972. if( ( mb_type = decode_cabac_mb_type( h ) ) < 0 ) {
  4973. av_log( h->s.avctx, AV_LOG_ERROR, "decode_cabac_mb_type failed\n" );
  4974. return -1;
  4975. }
  4976. if( h->slice_type == FF_B_TYPE ) {
  4977. if( mb_type < 23 ){
  4978. partition_count= b_mb_type_info[mb_type].partition_count;
  4979. mb_type= b_mb_type_info[mb_type].type;
  4980. }else{
  4981. mb_type -= 23;
  4982. goto decode_intra_mb;
  4983. }
  4984. } else if( h->slice_type == FF_P_TYPE ) {
  4985. if( mb_type < 5) {
  4986. partition_count= p_mb_type_info[mb_type].partition_count;
  4987. mb_type= p_mb_type_info[mb_type].type;
  4988. } else {
  4989. mb_type -= 5;
  4990. goto decode_intra_mb;
  4991. }
  4992. } else {
  4993. assert(h->slice_type == FF_I_TYPE);
  4994. decode_intra_mb:
  4995. partition_count = 0;
  4996. cbp= i_mb_type_info[mb_type].cbp;
  4997. h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;
  4998. mb_type= i_mb_type_info[mb_type].type;
  4999. }
  5000. if(MB_FIELD)
  5001. mb_type |= MB_TYPE_INTERLACED;
  5002. h->slice_table[ mb_xy ]= h->slice_num;
  5003. if(IS_INTRA_PCM(mb_type)) {
  5004. const uint8_t *ptr;
  5005. unsigned int x, y;
  5006. // We assume these blocks are very rare so we do not optimize it.
  5007. // FIXME The two following lines get the bitstream position in the cabac
  5008. // decode, I think it should be done by a function in cabac.h (or cabac.c).
  5009. ptr= h->cabac.bytestream;
  5010. if(h->cabac.low&0x1) ptr--;
  5011. if(CABAC_BITS==16){
  5012. if(h->cabac.low&0x1FF) ptr--;
  5013. }
  5014. // The pixels are stored in the same order as levels in h->mb array.
  5015. for(y=0; y<16; y++){
  5016. const int index= 4*(y&3) + 32*((y>>2)&1) + 128*(y>>3);
  5017. for(x=0; x<16; x++){
  5018. tprintf(s->avctx, "LUMA ICPM LEVEL (%3d)\n", *ptr);
  5019. h->mb[index + (x&3) + 16*((x>>2)&1) + 64*(x>>3)]= *ptr++;
  5020. }
  5021. }
  5022. for(y=0; y<8; y++){
  5023. const int index= 256 + 4*(y&3) + 32*(y>>2);
  5024. for(x=0; x<8; x++){
  5025. tprintf(s->avctx, "CHROMA U ICPM LEVEL (%3d)\n", *ptr);
  5026. h->mb[index + (x&3) + 16*(x>>2)]= *ptr++;
  5027. }
  5028. }
  5029. for(y=0; y<8; y++){
  5030. const int index= 256 + 64 + 4*(y&3) + 32*(y>>2);
  5031. for(x=0; x<8; x++){
  5032. tprintf(s->avctx, "CHROMA V ICPM LEVEL (%3d)\n", *ptr);
  5033. h->mb[index + (x&3) + 16*(x>>2)]= *ptr++;
  5034. }
  5035. }
  5036. ff_init_cabac_decoder(&h->cabac, ptr, h->cabac.bytestream_end - ptr);
  5037. // All blocks are present
  5038. h->cbp_table[mb_xy] = 0x1ef;
  5039. h->chroma_pred_mode_table[mb_xy] = 0;
  5040. // In deblocking, the quantizer is 0
  5041. s->current_picture.qscale_table[mb_xy]= 0;
  5042. h->chroma_qp[0] = get_chroma_qp(h, 0, 0);
  5043. h->chroma_qp[1] = get_chroma_qp(h, 1, 0);
  5044. // All coeffs are present
  5045. memset(h->non_zero_count[mb_xy], 16, 16);
  5046. s->current_picture.mb_type[mb_xy]= mb_type;
  5047. return 0;
  5048. }
  5049. if(MB_MBAFF){
  5050. h->ref_count[0] <<= 1;
  5051. h->ref_count[1] <<= 1;
  5052. }
  5053. fill_caches(h, mb_type, 0);
  5054. if( IS_INTRA( mb_type ) ) {
  5055. int i, pred_mode;
  5056. if( IS_INTRA4x4( mb_type ) ) {
  5057. if( dct8x8_allowed && decode_cabac_mb_transform_size( h ) ) {
  5058. mb_type |= MB_TYPE_8x8DCT;
  5059. for( i = 0; i < 16; i+=4 ) {
  5060. int pred = pred_intra_mode( h, i );
  5061. int mode = decode_cabac_mb_intra4x4_pred_mode( h, pred );
  5062. fill_rectangle( &h->intra4x4_pred_mode_cache[ scan8[i] ], 2, 2, 8, mode, 1 );
  5063. }
  5064. } else {
  5065. for( i = 0; i < 16; i++ ) {
  5066. int pred = pred_intra_mode( h, i );
  5067. h->intra4x4_pred_mode_cache[ scan8[i] ] = decode_cabac_mb_intra4x4_pred_mode( h, pred );
  5068. //av_log( s->avctx, AV_LOG_ERROR, "i4x4 pred=%d mode=%d\n", pred, h->intra4x4_pred_mode_cache[ scan8[i] ] );
  5069. }
  5070. }
  5071. write_back_intra_pred_mode(h);
  5072. if( check_intra4x4_pred_mode(h) < 0 ) return -1;
  5073. } else {
  5074. h->intra16x16_pred_mode= check_intra_pred_mode( h, h->intra16x16_pred_mode );
  5075. if( h->intra16x16_pred_mode < 0 ) return -1;
  5076. }
  5077. h->chroma_pred_mode_table[mb_xy] =
  5078. pred_mode = decode_cabac_mb_chroma_pre_mode( h );
  5079. pred_mode= check_intra_pred_mode( h, pred_mode );
  5080. if( pred_mode < 0 ) return -1;
  5081. h->chroma_pred_mode= pred_mode;
  5082. } else if( partition_count == 4 ) {
  5083. int i, j, sub_partition_count[4], list, ref[2][4];
  5084. if( h->slice_type == FF_B_TYPE ) {
  5085. for( i = 0; i < 4; i++ ) {
  5086. h->sub_mb_type[i] = decode_cabac_b_mb_sub_type( h );
  5087. sub_partition_count[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  5088. h->sub_mb_type[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  5089. }
  5090. if( IS_DIRECT(h->sub_mb_type[0] | h->sub_mb_type[1] |
  5091. h->sub_mb_type[2] | h->sub_mb_type[3]) ) {
  5092. pred_direct_motion(h, &mb_type);
  5093. h->ref_cache[0][scan8[4]] =
  5094. h->ref_cache[1][scan8[4]] =
  5095. h->ref_cache[0][scan8[12]] =
  5096. h->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;
  5097. if( h->ref_count[0] > 1 || h->ref_count[1] > 1 ) {
  5098. for( i = 0; i < 4; i++ )
  5099. if( IS_DIRECT(h->sub_mb_type[i]) )
  5100. fill_rectangle( &h->direct_cache[scan8[4*i]], 2, 2, 8, 1, 1 );
  5101. }
  5102. }
  5103. } else {
  5104. for( i = 0; i < 4; i++ ) {
  5105. h->sub_mb_type[i] = decode_cabac_p_mb_sub_type( h );
  5106. sub_partition_count[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;
  5107. h->sub_mb_type[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].type;
  5108. }
  5109. }
  5110. for( list = 0; list < h->list_count; list++ ) {
  5111. for( i = 0; i < 4; i++ ) {
  5112. if(IS_DIRECT(h->sub_mb_type[i])) continue;
  5113. if(IS_DIR(h->sub_mb_type[i], 0, list)){
  5114. if( h->ref_count[list] > 1 )
  5115. ref[list][i] = decode_cabac_mb_ref( h, list, 4*i );
  5116. else
  5117. ref[list][i] = 0;
  5118. } else {
  5119. ref[list][i] = -1;
  5120. }
  5121. h->ref_cache[list][ scan8[4*i]+1 ]=
  5122. h->ref_cache[list][ scan8[4*i]+8 ]=h->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];
  5123. }
  5124. }
  5125. if(dct8x8_allowed)
  5126. dct8x8_allowed = get_dct8x8_allowed(h);
  5127. for(list=0; list<h->list_count; list++){
  5128. for(i=0; i<4; i++){
  5129. h->ref_cache[list][ scan8[4*i] ]=h->ref_cache[list][ scan8[4*i]+1 ];
  5130. if(IS_DIRECT(h->sub_mb_type[i])){
  5131. fill_rectangle(h->mvd_cache[list][scan8[4*i]], 2, 2, 8, 0, 4);
  5132. continue;
  5133. }
  5134. if(IS_DIR(h->sub_mb_type[i], 0, list) && !IS_DIRECT(h->sub_mb_type[i])){
  5135. const int sub_mb_type= h->sub_mb_type[i];
  5136. const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;
  5137. for(j=0; j<sub_partition_count[i]; j++){
  5138. int mpx, mpy;
  5139. int mx, my;
  5140. const int index= 4*i + block_width*j;
  5141. int16_t (* mv_cache)[2]= &h->mv_cache[list][ scan8[index] ];
  5142. int16_t (* mvd_cache)[2]= &h->mvd_cache[list][ scan8[index] ];
  5143. pred_motion(h, index, block_width, list, h->ref_cache[list][ scan8[index] ], &mpx, &mpy);
  5144. mx = mpx + decode_cabac_mb_mvd( h, list, index, 0 );
  5145. my = mpy + decode_cabac_mb_mvd( h, list, index, 1 );
  5146. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5147. if(IS_SUB_8X8(sub_mb_type)){
  5148. mv_cache[ 1 ][0]=
  5149. mv_cache[ 8 ][0]= mv_cache[ 9 ][0]= mx;
  5150. mv_cache[ 1 ][1]=
  5151. mv_cache[ 8 ][1]= mv_cache[ 9 ][1]= my;
  5152. mvd_cache[ 1 ][0]=
  5153. mvd_cache[ 8 ][0]= mvd_cache[ 9 ][0]= mx - mpx;
  5154. mvd_cache[ 1 ][1]=
  5155. mvd_cache[ 8 ][1]= mvd_cache[ 9 ][1]= my - mpy;
  5156. }else if(IS_SUB_8X4(sub_mb_type)){
  5157. mv_cache[ 1 ][0]= mx;
  5158. mv_cache[ 1 ][1]= my;
  5159. mvd_cache[ 1 ][0]= mx - mpx;
  5160. mvd_cache[ 1 ][1]= my - mpy;
  5161. }else if(IS_SUB_4X8(sub_mb_type)){
  5162. mv_cache[ 8 ][0]= mx;
  5163. mv_cache[ 8 ][1]= my;
  5164. mvd_cache[ 8 ][0]= mx - mpx;
  5165. mvd_cache[ 8 ][1]= my - mpy;
  5166. }
  5167. mv_cache[ 0 ][0]= mx;
  5168. mv_cache[ 0 ][1]= my;
  5169. mvd_cache[ 0 ][0]= mx - mpx;
  5170. mvd_cache[ 0 ][1]= my - mpy;
  5171. }
  5172. }else{
  5173. uint32_t *p= (uint32_t *)&h->mv_cache[list][ scan8[4*i] ][0];
  5174. uint32_t *pd= (uint32_t *)&h->mvd_cache[list][ scan8[4*i] ][0];
  5175. p[0] = p[1] = p[8] = p[9] = 0;
  5176. pd[0]= pd[1]= pd[8]= pd[9]= 0;
  5177. }
  5178. }
  5179. }
  5180. } else if( IS_DIRECT(mb_type) ) {
  5181. pred_direct_motion(h, &mb_type);
  5182. fill_rectangle(h->mvd_cache[0][scan8[0]], 4, 4, 8, 0, 4);
  5183. fill_rectangle(h->mvd_cache[1][scan8[0]], 4, 4, 8, 0, 4);
  5184. dct8x8_allowed &= h->sps.direct_8x8_inference_flag;
  5185. } else {
  5186. int list, mx, my, i, mpx, mpy;
  5187. if(IS_16X16(mb_type)){
  5188. for(list=0; list<h->list_count; list++){
  5189. if(IS_DIR(mb_type, 0, list)){
  5190. const int ref = h->ref_count[list] > 1 ? decode_cabac_mb_ref( h, list, 0 ) : 0;
  5191. fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, ref, 1);
  5192. }else
  5193. 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
  5194. }
  5195. for(list=0; list<h->list_count; list++){
  5196. if(IS_DIR(mb_type, 0, list)){
  5197. pred_motion(h, 0, 4, list, h->ref_cache[list][ scan8[0] ], &mpx, &mpy);
  5198. mx = mpx + decode_cabac_mb_mvd( h, list, 0, 0 );
  5199. my = mpy + decode_cabac_mb_mvd( h, list, 0, 1 );
  5200. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5201. fill_rectangle(h->mvd_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx-mpx,my-mpy), 4);
  5202. fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx,my), 4);
  5203. }else
  5204. fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, 0, 4);
  5205. }
  5206. }
  5207. else if(IS_16X8(mb_type)){
  5208. for(list=0; list<h->list_count; list++){
  5209. for(i=0; i<2; i++){
  5210. if(IS_DIR(mb_type, i, list)){
  5211. const int ref= h->ref_count[list] > 1 ? decode_cabac_mb_ref( h, list, 8*i ) : 0;
  5212. fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, ref, 1);
  5213. }else
  5214. fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, (LIST_NOT_USED&0xFF), 1);
  5215. }
  5216. }
  5217. for(list=0; list<h->list_count; list++){
  5218. for(i=0; i<2; i++){
  5219. if(IS_DIR(mb_type, i, list)){
  5220. pred_16x8_motion(h, 8*i, list, h->ref_cache[list][scan8[0] + 16*i], &mpx, &mpy);
  5221. mx = mpx + decode_cabac_mb_mvd( h, list, 8*i, 0 );
  5222. my = mpy + decode_cabac_mb_mvd( h, list, 8*i, 1 );
  5223. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5224. fill_rectangle(h->mvd_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack16to32(mx-mpx,my-mpy), 4);
  5225. fill_rectangle(h->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack16to32(mx,my), 4);
  5226. }else{
  5227. fill_rectangle(h->mvd_cache[list][ scan8[0] + 16*i ], 4, 2, 8, 0, 4);
  5228. fill_rectangle(h-> mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, 0, 4);
  5229. }
  5230. }
  5231. }
  5232. }else{
  5233. assert(IS_8X16(mb_type));
  5234. for(list=0; list<h->list_count; list++){
  5235. for(i=0; i<2; i++){
  5236. if(IS_DIR(mb_type, i, list)){ //FIXME optimize
  5237. const int ref= h->ref_count[list] > 1 ? decode_cabac_mb_ref( h, list, 4*i ) : 0;
  5238. fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, ref, 1);
  5239. }else
  5240. fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, (LIST_NOT_USED&0xFF), 1);
  5241. }
  5242. }
  5243. for(list=0; list<h->list_count; list++){
  5244. for(i=0; i<2; i++){
  5245. if(IS_DIR(mb_type, i, list)){
  5246. pred_8x16_motion(h, i*4, list, h->ref_cache[list][ scan8[0] + 2*i ], &mpx, &mpy);
  5247. mx = mpx + decode_cabac_mb_mvd( h, list, 4*i, 0 );
  5248. my = mpy + decode_cabac_mb_mvd( h, list, 4*i, 1 );
  5249. tprintf(s->avctx, "final mv:%d %d\n", mx, my);
  5250. fill_rectangle(h->mvd_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack16to32(mx-mpx,my-mpy), 4);
  5251. fill_rectangle(h->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack16to32(mx,my), 4);
  5252. }else{
  5253. fill_rectangle(h->mvd_cache[list][ scan8[0] + 2*i ], 2, 4, 8, 0, 4);
  5254. fill_rectangle(h-> mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, 0, 4);
  5255. }
  5256. }
  5257. }
  5258. }
  5259. }
  5260. if( IS_INTER( mb_type ) ) {
  5261. h->chroma_pred_mode_table[mb_xy] = 0;
  5262. write_back_motion( h, mb_type );
  5263. }
  5264. if( !IS_INTRA16x16( mb_type ) ) {
  5265. cbp = decode_cabac_mb_cbp_luma( h );
  5266. cbp |= decode_cabac_mb_cbp_chroma( h ) << 4;
  5267. }
  5268. h->cbp_table[mb_xy] = h->cbp = cbp;
  5269. if( dct8x8_allowed && (cbp&15) && !IS_INTRA( mb_type ) ) {
  5270. if( decode_cabac_mb_transform_size( h ) )
  5271. mb_type |= MB_TYPE_8x8DCT;
  5272. }
  5273. s->current_picture.mb_type[mb_xy]= mb_type;
  5274. if( cbp || IS_INTRA16x16( mb_type ) ) {
  5275. const uint8_t *scan, *scan8x8, *dc_scan;
  5276. const uint32_t *qmul;
  5277. int dqp;
  5278. if(IS_INTERLACED(mb_type)){
  5279. scan8x8= s->qscale ? h->field_scan8x8 : h->field_scan8x8_q0;
  5280. scan= s->qscale ? h->field_scan : h->field_scan_q0;
  5281. dc_scan= luma_dc_field_scan;
  5282. }else{
  5283. scan8x8= s->qscale ? h->zigzag_scan8x8 : h->zigzag_scan8x8_q0;
  5284. scan= s->qscale ? h->zigzag_scan : h->zigzag_scan_q0;
  5285. dc_scan= luma_dc_zigzag_scan;
  5286. }
  5287. h->last_qscale_diff = dqp = decode_cabac_mb_dqp( h );
  5288. if( dqp == INT_MIN ){
  5289. av_log(h->s.avctx, AV_LOG_ERROR, "cabac decode of qscale diff failed at %d %d\n", s->mb_x, s->mb_y);
  5290. return -1;
  5291. }
  5292. s->qscale += dqp;
  5293. if(((unsigned)s->qscale) > 51){
  5294. if(s->qscale<0) s->qscale+= 52;
  5295. else s->qscale-= 52;
  5296. }
  5297. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  5298. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  5299. if( IS_INTRA16x16( mb_type ) ) {
  5300. int i;
  5301. //av_log( s->avctx, AV_LOG_ERROR, "INTRA16x16 DC\n" );
  5302. decode_cabac_residual( h, h->mb, 0, 0, dc_scan, NULL, 16);
  5303. if( cbp&15 ) {
  5304. qmul = h->dequant4_coeff[0][s->qscale];
  5305. for( i = 0; i < 16; i++ ) {
  5306. //av_log( s->avctx, AV_LOG_ERROR, "INTRA16x16 AC:%d\n", i );
  5307. decode_cabac_residual(h, h->mb + 16*i, 1, i, scan + 1, qmul, 15);
  5308. }
  5309. } else {
  5310. fill_rectangle(&h->non_zero_count_cache[scan8[0]], 4, 4, 8, 0, 1);
  5311. }
  5312. } else {
  5313. int i8x8, i4x4;
  5314. for( i8x8 = 0; i8x8 < 4; i8x8++ ) {
  5315. if( cbp & (1<<i8x8) ) {
  5316. if( IS_8x8DCT(mb_type) ) {
  5317. decode_cabac_residual(h, h->mb + 64*i8x8, 5, 4*i8x8,
  5318. scan8x8, h->dequant8_coeff[IS_INTRA( mb_type ) ? 0:1][s->qscale], 64);
  5319. } else {
  5320. qmul = h->dequant4_coeff[IS_INTRA( mb_type ) ? 0:3][s->qscale];
  5321. for( i4x4 = 0; i4x4 < 4; i4x4++ ) {
  5322. const int index = 4*i8x8 + i4x4;
  5323. //av_log( s->avctx, AV_LOG_ERROR, "Luma4x4: %d\n", index );
  5324. //START_TIMER
  5325. decode_cabac_residual(h, h->mb + 16*index, 2, index, scan, qmul, 16);
  5326. //STOP_TIMER("decode_residual")
  5327. }
  5328. }
  5329. } else {
  5330. uint8_t * const nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];
  5331. nnz[0] = nnz[1] = nnz[8] = nnz[9] = 0;
  5332. }
  5333. }
  5334. }
  5335. if( cbp&0x30 ){
  5336. int c;
  5337. for( c = 0; c < 2; c++ ) {
  5338. //av_log( s->avctx, AV_LOG_ERROR, "INTRA C%d-DC\n",c );
  5339. decode_cabac_residual(h, h->mb + 256 + 16*4*c, 3, c, chroma_dc_scan, NULL, 4);
  5340. }
  5341. }
  5342. if( cbp&0x20 ) {
  5343. int c, i;
  5344. for( c = 0; c < 2; c++ ) {
  5345. qmul = h->dequant4_coeff[c+1+(IS_INTRA( mb_type ) ? 0:3)][h->chroma_qp[c]];
  5346. for( i = 0; i < 4; i++ ) {
  5347. const int index = 16 + 4 * c + i;
  5348. //av_log( s->avctx, AV_LOG_ERROR, "INTRA C%d-AC %d\n",c, index - 16 );
  5349. decode_cabac_residual(h, h->mb + 16*index, 4, index - 16, scan + 1, qmul, 15);
  5350. }
  5351. }
  5352. } else {
  5353. uint8_t * const nnz= &h->non_zero_count_cache[0];
  5354. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  5355. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  5356. }
  5357. } else {
  5358. uint8_t * const nnz= &h->non_zero_count_cache[0];
  5359. fill_rectangle(&nnz[scan8[0]], 4, 4, 8, 0, 1);
  5360. nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =
  5361. nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;
  5362. h->last_qscale_diff = 0;
  5363. }
  5364. s->current_picture.qscale_table[mb_xy]= s->qscale;
  5365. write_back_non_zero_count(h);
  5366. if(MB_MBAFF){
  5367. h->ref_count[0] >>= 1;
  5368. h->ref_count[1] >>= 1;
  5369. }
  5370. return 0;
  5371. }
  5372. static void filter_mb_edgev( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5373. int i, d;
  5374. const int index_a = qp + h->slice_alpha_c0_offset;
  5375. const int alpha = (alpha_table+52)[index_a];
  5376. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5377. if( bS[0] < 4 ) {
  5378. int8_t tc[4];
  5379. for(i=0; i<4; i++)
  5380. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] : -1;
  5381. h->s.dsp.h264_h_loop_filter_luma(pix, stride, alpha, beta, tc);
  5382. } else {
  5383. /* 16px edge length, because bS=4 is triggered by being at
  5384. * the edge of an intra MB, so all 4 bS are the same */
  5385. for( d = 0; d < 16; d++ ) {
  5386. const int p0 = pix[-1];
  5387. const int p1 = pix[-2];
  5388. const int p2 = pix[-3];
  5389. const int q0 = pix[0];
  5390. const int q1 = pix[1];
  5391. const int q2 = pix[2];
  5392. if( FFABS( p0 - q0 ) < alpha &&
  5393. FFABS( p1 - p0 ) < beta &&
  5394. FFABS( q1 - q0 ) < beta ) {
  5395. if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){
  5396. if( FFABS( p2 - p0 ) < beta)
  5397. {
  5398. const int p3 = pix[-4];
  5399. /* p0', p1', p2' */
  5400. pix[-1] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;
  5401. pix[-2] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;
  5402. pix[-3] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;
  5403. } else {
  5404. /* p0' */
  5405. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5406. }
  5407. if( FFABS( q2 - q0 ) < beta)
  5408. {
  5409. const int q3 = pix[3];
  5410. /* q0', q1', q2' */
  5411. pix[0] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;
  5412. pix[1] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;
  5413. pix[2] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;
  5414. } else {
  5415. /* q0' */
  5416. pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5417. }
  5418. }else{
  5419. /* p0', q0' */
  5420. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5421. pix[ 0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5422. }
  5423. 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]);
  5424. }
  5425. pix += stride;
  5426. }
  5427. }
  5428. }
  5429. static void filter_mb_edgecv( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5430. int i;
  5431. const int index_a = qp + h->slice_alpha_c0_offset;
  5432. const int alpha = (alpha_table+52)[index_a];
  5433. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5434. if( bS[0] < 4 ) {
  5435. int8_t tc[4];
  5436. for(i=0; i<4; i++)
  5437. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] + 1 : 0;
  5438. h->s.dsp.h264_h_loop_filter_chroma(pix, stride, alpha, beta, tc);
  5439. } else {
  5440. h->s.dsp.h264_h_loop_filter_chroma_intra(pix, stride, alpha, beta);
  5441. }
  5442. }
  5443. static void filter_mb_mbaff_edgev( H264Context *h, uint8_t *pix, int stride, int16_t bS[8], int qp[2] ) {
  5444. int i;
  5445. for( i = 0; i < 16; i++, pix += stride) {
  5446. int index_a;
  5447. int alpha;
  5448. int beta;
  5449. int qp_index;
  5450. int bS_index = (i >> 1);
  5451. if (!MB_FIELD) {
  5452. bS_index &= ~1;
  5453. bS_index |= (i & 1);
  5454. }
  5455. if( bS[bS_index] == 0 ) {
  5456. continue;
  5457. }
  5458. qp_index = MB_FIELD ? (i >> 3) : (i & 1);
  5459. index_a = qp[qp_index] + h->slice_alpha_c0_offset;
  5460. alpha = (alpha_table+52)[index_a];
  5461. beta = (beta_table+52)[qp[qp_index] + h->slice_beta_offset];
  5462. if( bS[bS_index] < 4 ) {
  5463. const int tc0 = (tc0_table+52)[index_a][bS[bS_index] - 1];
  5464. const int p0 = pix[-1];
  5465. const int p1 = pix[-2];
  5466. const int p2 = pix[-3];
  5467. const int q0 = pix[0];
  5468. const int q1 = pix[1];
  5469. const int q2 = pix[2];
  5470. if( FFABS( p0 - q0 ) < alpha &&
  5471. FFABS( p1 - p0 ) < beta &&
  5472. FFABS( q1 - q0 ) < beta ) {
  5473. int tc = tc0;
  5474. int i_delta;
  5475. if( FFABS( p2 - p0 ) < beta ) {
  5476. pix[-2] = p1 + av_clip( ( p2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( p1 << 1 ) ) >> 1, -tc0, tc0 );
  5477. tc++;
  5478. }
  5479. if( FFABS( q2 - q0 ) < beta ) {
  5480. pix[1] = q1 + av_clip( ( q2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( q1 << 1 ) ) >> 1, -tc0, tc0 );
  5481. tc++;
  5482. }
  5483. i_delta = av_clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );
  5484. pix[-1] = av_clip_uint8( p0 + i_delta ); /* p0' */
  5485. pix[0] = av_clip_uint8( q0 - i_delta ); /* q0' */
  5486. 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);
  5487. }
  5488. }else{
  5489. const int p0 = pix[-1];
  5490. const int p1 = pix[-2];
  5491. const int p2 = pix[-3];
  5492. const int q0 = pix[0];
  5493. const int q1 = pix[1];
  5494. const int q2 = pix[2];
  5495. if( FFABS( p0 - q0 ) < alpha &&
  5496. FFABS( p1 - p0 ) < beta &&
  5497. FFABS( q1 - q0 ) < beta ) {
  5498. if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){
  5499. if( FFABS( p2 - p0 ) < beta)
  5500. {
  5501. const int p3 = pix[-4];
  5502. /* p0', p1', p2' */
  5503. pix[-1] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;
  5504. pix[-2] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;
  5505. pix[-3] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;
  5506. } else {
  5507. /* p0' */
  5508. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5509. }
  5510. if( FFABS( q2 - q0 ) < beta)
  5511. {
  5512. const int q3 = pix[3];
  5513. /* q0', q1', q2' */
  5514. pix[0] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;
  5515. pix[1] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;
  5516. pix[2] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;
  5517. } else {
  5518. /* q0' */
  5519. pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5520. }
  5521. }else{
  5522. /* p0', q0' */
  5523. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5524. pix[ 0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5525. }
  5526. 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]);
  5527. }
  5528. }
  5529. }
  5530. }
  5531. static void filter_mb_mbaff_edgecv( H264Context *h, uint8_t *pix, int stride, int16_t bS[8], int qp[2] ) {
  5532. int i;
  5533. for( i = 0; i < 8; i++, pix += stride) {
  5534. int index_a;
  5535. int alpha;
  5536. int beta;
  5537. int qp_index;
  5538. int bS_index = i;
  5539. if( bS[bS_index] == 0 ) {
  5540. continue;
  5541. }
  5542. qp_index = MB_FIELD ? (i >> 2) : (i & 1);
  5543. index_a = qp[qp_index] + h->slice_alpha_c0_offset;
  5544. alpha = (alpha_table+52)[index_a];
  5545. beta = (beta_table+52)[qp[qp_index] + h->slice_beta_offset];
  5546. if( bS[bS_index] < 4 ) {
  5547. const int tc = (tc0_table+52)[index_a][bS[bS_index] - 1] + 1;
  5548. const int p0 = pix[-1];
  5549. const int p1 = pix[-2];
  5550. const int q0 = pix[0];
  5551. const int q1 = pix[1];
  5552. if( FFABS( p0 - q0 ) < alpha &&
  5553. FFABS( p1 - p0 ) < beta &&
  5554. FFABS( q1 - q0 ) < beta ) {
  5555. const int i_delta = av_clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );
  5556. pix[-1] = av_clip_uint8( p0 + i_delta ); /* p0' */
  5557. pix[0] = av_clip_uint8( q0 - i_delta ); /* q0' */
  5558. 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);
  5559. }
  5560. }else{
  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. pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2; /* p0' */
  5569. pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2; /* q0' */
  5570. 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]);
  5571. }
  5572. }
  5573. }
  5574. }
  5575. static void filter_mb_edgeh( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5576. int i, d;
  5577. const int index_a = qp + h->slice_alpha_c0_offset;
  5578. const int alpha = (alpha_table+52)[index_a];
  5579. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5580. const int pix_next = stride;
  5581. if( bS[0] < 4 ) {
  5582. int8_t tc[4];
  5583. for(i=0; i<4; i++)
  5584. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] : -1;
  5585. h->s.dsp.h264_v_loop_filter_luma(pix, stride, alpha, beta, tc);
  5586. } else {
  5587. /* 16px edge length, see filter_mb_edgev */
  5588. for( d = 0; d < 16; d++ ) {
  5589. const int p0 = pix[-1*pix_next];
  5590. const int p1 = pix[-2*pix_next];
  5591. const int p2 = pix[-3*pix_next];
  5592. const int q0 = pix[0];
  5593. const int q1 = pix[1*pix_next];
  5594. const int q2 = pix[2*pix_next];
  5595. if( FFABS( p0 - q0 ) < alpha &&
  5596. FFABS( p1 - p0 ) < beta &&
  5597. FFABS( q1 - q0 ) < beta ) {
  5598. const int p3 = pix[-4*pix_next];
  5599. const int q3 = pix[ 3*pix_next];
  5600. if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){
  5601. if( FFABS( p2 - p0 ) < beta) {
  5602. /* p0', p1', p2' */
  5603. pix[-1*pix_next] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;
  5604. pix[-2*pix_next] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;
  5605. pix[-3*pix_next] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;
  5606. } else {
  5607. /* p0' */
  5608. pix[-1*pix_next] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5609. }
  5610. if( FFABS( q2 - q0 ) < beta) {
  5611. /* q0', q1', q2' */
  5612. pix[0*pix_next] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;
  5613. pix[1*pix_next] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;
  5614. pix[2*pix_next] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;
  5615. } else {
  5616. /* q0' */
  5617. pix[0*pix_next] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5618. }
  5619. }else{
  5620. /* p0', q0' */
  5621. pix[-1*pix_next] = ( 2*p1 + p0 + q1 + 2 ) >> 2;
  5622. pix[ 0*pix_next] = ( 2*q1 + q0 + p1 + 2 ) >> 2;
  5623. }
  5624. 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]);
  5625. }
  5626. pix++;
  5627. }
  5628. }
  5629. }
  5630. static void filter_mb_edgech( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {
  5631. int i;
  5632. const int index_a = qp + h->slice_alpha_c0_offset;
  5633. const int alpha = (alpha_table+52)[index_a];
  5634. const int beta = (beta_table+52)[qp + h->slice_beta_offset];
  5635. if( bS[0] < 4 ) {
  5636. int8_t tc[4];
  5637. for(i=0; i<4; i++)
  5638. tc[i] = bS[i] ? (tc0_table+52)[index_a][bS[i] - 1] + 1 : 0;
  5639. h->s.dsp.h264_v_loop_filter_chroma(pix, stride, alpha, beta, tc);
  5640. } else {
  5641. h->s.dsp.h264_v_loop_filter_chroma_intra(pix, stride, alpha, beta);
  5642. }
  5643. }
  5644. 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) {
  5645. MpegEncContext * const s = &h->s;
  5646. int mb_y_firstrow = s->picture_structure == PICT_BOTTOM_FIELD;
  5647. int mb_xy, mb_type;
  5648. int qp, qp0, qp1, qpc, qpc0, qpc1, qp_thresh;
  5649. mb_xy = mb_x + mb_y*s->mb_stride;
  5650. if(mb_x==0 || mb_y==mb_y_firstrow || !s->dsp.h264_loop_filter_strength || h->pps.chroma_qp_diff ||
  5651. (h->deblocking_filter == 2 && (h->slice_table[mb_xy] != h->slice_table[h->top_mb_xy] ||
  5652. h->slice_table[mb_xy] != h->slice_table[mb_xy - 1]))) {
  5653. filter_mb(h, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize);
  5654. return;
  5655. }
  5656. assert(!FRAME_MBAFF);
  5657. mb_type = s->current_picture.mb_type[mb_xy];
  5658. qp = s->current_picture.qscale_table[mb_xy];
  5659. qp0 = s->current_picture.qscale_table[mb_xy-1];
  5660. qp1 = s->current_picture.qscale_table[h->top_mb_xy];
  5661. qpc = get_chroma_qp( h, 0, qp );
  5662. qpc0 = get_chroma_qp( h, 0, qp0 );
  5663. qpc1 = get_chroma_qp( h, 0, qp1 );
  5664. qp0 = (qp + qp0 + 1) >> 1;
  5665. qp1 = (qp + qp1 + 1) >> 1;
  5666. qpc0 = (qpc + qpc0 + 1) >> 1;
  5667. qpc1 = (qpc + qpc1 + 1) >> 1;
  5668. qp_thresh = 15 - h->slice_alpha_c0_offset;
  5669. if(qp <= qp_thresh && qp0 <= qp_thresh && qp1 <= qp_thresh &&
  5670. qpc <= qp_thresh && qpc0 <= qp_thresh && qpc1 <= qp_thresh)
  5671. return;
  5672. if( IS_INTRA(mb_type) ) {
  5673. int16_t bS4[4] = {4,4,4,4};
  5674. int16_t bS3[4] = {3,3,3,3};
  5675. int16_t *bSH = FIELD_PICTURE ? bS3 : bS4;
  5676. if( IS_8x8DCT(mb_type) ) {
  5677. filter_mb_edgev( h, &img_y[4*0], linesize, bS4, qp0 );
  5678. filter_mb_edgev( h, &img_y[4*2], linesize, bS3, qp );
  5679. filter_mb_edgeh( h, &img_y[4*0*linesize], linesize, bSH, qp1 );
  5680. filter_mb_edgeh( h, &img_y[4*2*linesize], linesize, bS3, qp );
  5681. } else {
  5682. filter_mb_edgev( h, &img_y[4*0], linesize, bS4, qp0 );
  5683. filter_mb_edgev( h, &img_y[4*1], linesize, bS3, qp );
  5684. filter_mb_edgev( h, &img_y[4*2], linesize, bS3, qp );
  5685. filter_mb_edgev( h, &img_y[4*3], linesize, bS3, qp );
  5686. filter_mb_edgeh( h, &img_y[4*0*linesize], linesize, bSH, qp1 );
  5687. filter_mb_edgeh( h, &img_y[4*1*linesize], linesize, bS3, qp );
  5688. filter_mb_edgeh( h, &img_y[4*2*linesize], linesize, bS3, qp );
  5689. filter_mb_edgeh( h, &img_y[4*3*linesize], linesize, bS3, qp );
  5690. }
  5691. filter_mb_edgecv( h, &img_cb[2*0], uvlinesize, bS4, qpc0 );
  5692. filter_mb_edgecv( h, &img_cb[2*2], uvlinesize, bS3, qpc );
  5693. filter_mb_edgecv( h, &img_cr[2*0], uvlinesize, bS4, qpc0 );
  5694. filter_mb_edgecv( h, &img_cr[2*2], uvlinesize, bS3, qpc );
  5695. filter_mb_edgech( h, &img_cb[2*0*uvlinesize], uvlinesize, bSH, qpc1 );
  5696. filter_mb_edgech( h, &img_cb[2*2*uvlinesize], uvlinesize, bS3, qpc );
  5697. filter_mb_edgech( h, &img_cr[2*0*uvlinesize], uvlinesize, bSH, qpc1 );
  5698. filter_mb_edgech( h, &img_cr[2*2*uvlinesize], uvlinesize, bS3, qpc );
  5699. return;
  5700. } else {
  5701. DECLARE_ALIGNED_8(int16_t, bS[2][4][4]);
  5702. uint64_t (*bSv)[4] = (uint64_t(*)[4])bS;
  5703. int edges;
  5704. if( IS_8x8DCT(mb_type) && (h->cbp&7) == 7 ) {
  5705. edges = 4;
  5706. bSv[0][0] = bSv[0][2] = bSv[1][0] = bSv[1][2] = 0x0002000200020002ULL;
  5707. } else {
  5708. int mask_edge1 = (mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16)) ? 3 :
  5709. (mb_type & MB_TYPE_16x8) ? 1 : 0;
  5710. int mask_edge0 = (mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16))
  5711. && (s->current_picture.mb_type[mb_xy-1] & (MB_TYPE_16x16 | MB_TYPE_8x16))
  5712. ? 3 : 0;
  5713. int step = IS_8x8DCT(mb_type) ? 2 : 1;
  5714. edges = (mb_type & MB_TYPE_16x16) && !(h->cbp & 15) ? 1 : 4;
  5715. s->dsp.h264_loop_filter_strength( bS, h->non_zero_count_cache, h->ref_cache, h->mv_cache,
  5716. (h->slice_type == FF_B_TYPE), edges, step, mask_edge0, mask_edge1 );
  5717. }
  5718. if( IS_INTRA(s->current_picture.mb_type[mb_xy-1]) )
  5719. bSv[0][0] = 0x0004000400040004ULL;
  5720. if( IS_INTRA(s->current_picture.mb_type[h->top_mb_xy]) )
  5721. bSv[1][0] = FIELD_PICTURE ? 0x0003000300030003ULL : 0x0004000400040004ULL;
  5722. #define FILTER(hv,dir,edge)\
  5723. if(bSv[dir][edge]) {\
  5724. filter_mb_edge##hv( h, &img_y[4*edge*(dir?linesize:1)], linesize, bS[dir][edge], edge ? qp : qp##dir );\
  5725. if(!(edge&1)) {\
  5726. filter_mb_edgec##hv( h, &img_cb[2*edge*(dir?uvlinesize:1)], uvlinesize, bS[dir][edge], edge ? qpc : qpc##dir );\
  5727. filter_mb_edgec##hv( h, &img_cr[2*edge*(dir?uvlinesize:1)], uvlinesize, bS[dir][edge], edge ? qpc : qpc##dir );\
  5728. }\
  5729. }
  5730. if( edges == 1 ) {
  5731. FILTER(v,0,0);
  5732. FILTER(h,1,0);
  5733. } else if( IS_8x8DCT(mb_type) ) {
  5734. FILTER(v,0,0);
  5735. FILTER(v,0,2);
  5736. FILTER(h,1,0);
  5737. FILTER(h,1,2);
  5738. } else {
  5739. FILTER(v,0,0);
  5740. FILTER(v,0,1);
  5741. FILTER(v,0,2);
  5742. FILTER(v,0,3);
  5743. FILTER(h,1,0);
  5744. FILTER(h,1,1);
  5745. FILTER(h,1,2);
  5746. FILTER(h,1,3);
  5747. }
  5748. #undef FILTER
  5749. }
  5750. }
  5751. 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) {
  5752. MpegEncContext * const s = &h->s;
  5753. const int mb_xy= mb_x + mb_y*s->mb_stride;
  5754. const int mb_type = s->current_picture.mb_type[mb_xy];
  5755. const int mvy_limit = IS_INTERLACED(mb_type) ? 2 : 4;
  5756. int first_vertical_edge_done = 0;
  5757. int dir;
  5758. /* FIXME: A given frame may occupy more than one position in
  5759. * the reference list. So ref2frm should be populated with
  5760. * frame numbers, not indices. */
  5761. static const int ref2frm[34] = {-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
  5762. 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
  5763. //for sufficiently low qp, filtering wouldn't do anything
  5764. //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
  5765. if(!FRAME_MBAFF){
  5766. int qp_thresh = 15 - h->slice_alpha_c0_offset - FFMAX(0, FFMAX(h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1]));
  5767. int qp = s->current_picture.qscale_table[mb_xy];
  5768. if(qp <= qp_thresh
  5769. && (mb_x == 0 || ((qp + s->current_picture.qscale_table[mb_xy-1] + 1)>>1) <= qp_thresh)
  5770. && (mb_y == 0 || ((qp + s->current_picture.qscale_table[h->top_mb_xy] + 1)>>1) <= qp_thresh)){
  5771. return;
  5772. }
  5773. }
  5774. if (FRAME_MBAFF
  5775. // left mb is in picture
  5776. && h->slice_table[mb_xy-1] != 255
  5777. // and current and left pair do not have the same interlaced type
  5778. && (IS_INTERLACED(mb_type) != IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]))
  5779. // and left mb is in the same slice if deblocking_filter == 2
  5780. && (h->deblocking_filter!=2 || h->slice_table[mb_xy-1] == h->slice_table[mb_xy])) {
  5781. /* First vertical edge is different in MBAFF frames
  5782. * There are 8 different bS to compute and 2 different Qp
  5783. */
  5784. const int pair_xy = mb_x + (mb_y&~1)*s->mb_stride;
  5785. const int left_mb_xy[2] = { pair_xy-1, pair_xy-1+s->mb_stride };
  5786. int16_t bS[8];
  5787. int qp[2];
  5788. int bqp[2];
  5789. int rqp[2];
  5790. int mb_qp, mbn0_qp, mbn1_qp;
  5791. int i;
  5792. first_vertical_edge_done = 1;
  5793. if( IS_INTRA(mb_type) )
  5794. bS[0] = bS[1] = bS[2] = bS[3] = bS[4] = bS[5] = bS[6] = bS[7] = 4;
  5795. else {
  5796. for( i = 0; i < 8; i++ ) {
  5797. int mbn_xy = MB_FIELD ? left_mb_xy[i>>2] : left_mb_xy[i&1];
  5798. if( IS_INTRA( s->current_picture.mb_type[mbn_xy] ) )
  5799. bS[i] = 4;
  5800. else if( h->non_zero_count_cache[12+8*(i>>1)] != 0 ||
  5801. /* FIXME: with 8x8dct + cavlc, should check cbp instead of nnz */
  5802. h->non_zero_count[mbn_xy][MB_FIELD ? i&3 : (i>>2)+(mb_y&1)*2] )
  5803. bS[i] = 2;
  5804. else
  5805. bS[i] = 1;
  5806. }
  5807. }
  5808. mb_qp = s->current_picture.qscale_table[mb_xy];
  5809. mbn0_qp = s->current_picture.qscale_table[left_mb_xy[0]];
  5810. mbn1_qp = s->current_picture.qscale_table[left_mb_xy[1]];
  5811. qp[0] = ( mb_qp + mbn0_qp + 1 ) >> 1;
  5812. bqp[0] = ( get_chroma_qp( h, 0, mb_qp ) +
  5813. get_chroma_qp( h, 0, mbn0_qp ) + 1 ) >> 1;
  5814. rqp[0] = ( get_chroma_qp( h, 1, mb_qp ) +
  5815. get_chroma_qp( h, 1, mbn0_qp ) + 1 ) >> 1;
  5816. qp[1] = ( mb_qp + mbn1_qp + 1 ) >> 1;
  5817. bqp[1] = ( get_chroma_qp( h, 0, mb_qp ) +
  5818. get_chroma_qp( h, 0, mbn1_qp ) + 1 ) >> 1;
  5819. rqp[1] = ( get_chroma_qp( h, 1, mb_qp ) +
  5820. get_chroma_qp( h, 1, mbn1_qp ) + 1 ) >> 1;
  5821. /* Filter edge */
  5822. 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);
  5823. { int i; for (i = 0; i < 8; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
  5824. filter_mb_mbaff_edgev ( h, &img_y [0], linesize, bS, qp );
  5825. filter_mb_mbaff_edgecv( h, &img_cb[0], uvlinesize, bS, bqp );
  5826. filter_mb_mbaff_edgecv( h, &img_cr[0], uvlinesize, bS, rqp );
  5827. }
  5828. /* dir : 0 -> vertical edge, 1 -> horizontal edge */
  5829. for( dir = 0; dir < 2; dir++ )
  5830. {
  5831. int edge;
  5832. const int mbm_xy = dir == 0 ? mb_xy -1 : h->top_mb_xy;
  5833. const int mbm_type = s->current_picture.mb_type[mbm_xy];
  5834. int start = h->slice_table[mbm_xy] == 255 ? 1 : 0;
  5835. const int edges = (mb_type & (MB_TYPE_16x16|MB_TYPE_SKIP))
  5836. == (MB_TYPE_16x16|MB_TYPE_SKIP) ? 1 : 4;
  5837. // how often to recheck mv-based bS when iterating between edges
  5838. const int mask_edge = (mb_type & (MB_TYPE_16x16 | (MB_TYPE_16x8 << dir))) ? 3 :
  5839. (mb_type & (MB_TYPE_8x16 >> dir)) ? 1 : 0;
  5840. // how often to recheck mv-based bS when iterating along each edge
  5841. const int mask_par0 = mb_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir));
  5842. if (first_vertical_edge_done) {
  5843. start = 1;
  5844. first_vertical_edge_done = 0;
  5845. }
  5846. if (h->deblocking_filter==2 && h->slice_table[mbm_xy] != h->slice_table[mb_xy])
  5847. start = 1;
  5848. if (FRAME_MBAFF && (dir == 1) && ((mb_y&1) == 0) && start == 0
  5849. && !IS_INTERLACED(mb_type)
  5850. && IS_INTERLACED(mbm_type)
  5851. ) {
  5852. // This is a special case in the norm where the filtering must
  5853. // be done twice (one each of the field) even if we are in a
  5854. // frame macroblock.
  5855. //
  5856. static const int nnz_idx[4] = {4,5,6,3};
  5857. unsigned int tmp_linesize = 2 * linesize;
  5858. unsigned int tmp_uvlinesize = 2 * uvlinesize;
  5859. int mbn_xy = mb_xy - 2 * s->mb_stride;
  5860. int qp;
  5861. int i, j;
  5862. int16_t bS[4];
  5863. for(j=0; j<2; j++, mbn_xy += s->mb_stride){
  5864. if( IS_INTRA(mb_type) ||
  5865. IS_INTRA(s->current_picture.mb_type[mbn_xy]) ) {
  5866. bS[0] = bS[1] = bS[2] = bS[3] = 3;
  5867. } else {
  5868. const uint8_t *mbn_nnz = h->non_zero_count[mbn_xy];
  5869. for( i = 0; i < 4; i++ ) {
  5870. if( h->non_zero_count_cache[scan8[0]+i] != 0 ||
  5871. mbn_nnz[nnz_idx[i]] != 0 )
  5872. bS[i] = 2;
  5873. else
  5874. bS[i] = 1;
  5875. }
  5876. }
  5877. // Do not use s->qscale as luma quantizer because it has not the same
  5878. // value in IPCM macroblocks.
  5879. qp = ( s->current_picture.qscale_table[mb_xy] + s->current_picture.qscale_table[mbn_xy] + 1 ) >> 1;
  5880. 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);
  5881. { int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
  5882. filter_mb_edgeh( h, &img_y[j*linesize], tmp_linesize, bS, qp );
  5883. filter_mb_edgech( h, &img_cb[j*uvlinesize], tmp_uvlinesize, bS,
  5884. ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5885. filter_mb_edgech( h, &img_cr[j*uvlinesize], tmp_uvlinesize, bS,
  5886. ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5887. }
  5888. start = 1;
  5889. }
  5890. /* Calculate bS */
  5891. for( edge = start; edge < edges; edge++ ) {
  5892. /* mbn_xy: neighbor macroblock */
  5893. const int mbn_xy = edge > 0 ? mb_xy : mbm_xy;
  5894. const int mbn_type = s->current_picture.mb_type[mbn_xy];
  5895. int16_t bS[4];
  5896. int qp;
  5897. if( (edge&1) && IS_8x8DCT(mb_type) )
  5898. continue;
  5899. if( IS_INTRA(mb_type) ||
  5900. IS_INTRA(mbn_type) ) {
  5901. int value;
  5902. if (edge == 0) {
  5903. if ( (!IS_INTERLACED(mb_type) && !IS_INTERLACED(mbm_type))
  5904. || ((FRAME_MBAFF || (s->picture_structure != PICT_FRAME)) && (dir == 0))
  5905. ) {
  5906. value = 4;
  5907. } else {
  5908. value = 3;
  5909. }
  5910. } else {
  5911. value = 3;
  5912. }
  5913. bS[0] = bS[1] = bS[2] = bS[3] = value;
  5914. } else {
  5915. int i, l;
  5916. int mv_done;
  5917. if( edge & mask_edge ) {
  5918. bS[0] = bS[1] = bS[2] = bS[3] = 0;
  5919. mv_done = 1;
  5920. }
  5921. else if( FRAME_MBAFF && IS_INTERLACED(mb_type ^ mbn_type)) {
  5922. bS[0] = bS[1] = bS[2] = bS[3] = 1;
  5923. mv_done = 1;
  5924. }
  5925. else if( mask_par0 && (edge || (mbn_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir)))) ) {
  5926. int b_idx= 8 + 4 + edge * (dir ? 8:1);
  5927. int bn_idx= b_idx - (dir ? 8:1);
  5928. int v = 0;
  5929. for( l = 0; !v && l < 1 + (h->slice_type == FF_B_TYPE); l++ ) {
  5930. v |= ref2frm[h->ref_cache[l][b_idx]+2] != ref2frm[h->ref_cache[l][bn_idx]+2] ||
  5931. FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[l][bn_idx][0] ) >= 4 ||
  5932. FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[l][bn_idx][1] ) >= mvy_limit;
  5933. }
  5934. bS[0] = bS[1] = bS[2] = bS[3] = v;
  5935. mv_done = 1;
  5936. }
  5937. else
  5938. mv_done = 0;
  5939. for( i = 0; i < 4; i++ ) {
  5940. int x = dir == 0 ? edge : i;
  5941. int y = dir == 0 ? i : edge;
  5942. int b_idx= 8 + 4 + x + 8*y;
  5943. int bn_idx= b_idx - (dir ? 8:1);
  5944. if( h->non_zero_count_cache[b_idx] != 0 ||
  5945. h->non_zero_count_cache[bn_idx] != 0 ) {
  5946. bS[i] = 2;
  5947. }
  5948. else if(!mv_done)
  5949. {
  5950. bS[i] = 0;
  5951. for( l = 0; l < 1 + (h->slice_type == FF_B_TYPE); l++ ) {
  5952. if( ref2frm[h->ref_cache[l][b_idx]+2] != ref2frm[h->ref_cache[l][bn_idx]+2] ||
  5953. FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[l][bn_idx][0] ) >= 4 ||
  5954. FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[l][bn_idx][1] ) >= mvy_limit ) {
  5955. bS[i] = 1;
  5956. break;
  5957. }
  5958. }
  5959. }
  5960. }
  5961. if(bS[0]+bS[1]+bS[2]+bS[3] == 0)
  5962. continue;
  5963. }
  5964. /* Filter edge */
  5965. // Do not use s->qscale as luma quantizer because it has not the same
  5966. // value in IPCM macroblocks.
  5967. qp = ( s->current_picture.qscale_table[mb_xy] + s->current_picture.qscale_table[mbn_xy] + 1 ) >> 1;
  5968. //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]);
  5969. 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);
  5970. { int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
  5971. if( dir == 0 ) {
  5972. filter_mb_edgev( h, &img_y[4*edge], linesize, bS, qp );
  5973. if( (edge&1) == 0 ) {
  5974. filter_mb_edgecv( h, &img_cb[2*edge], uvlinesize, bS,
  5975. ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5976. filter_mb_edgecv( h, &img_cr[2*edge], uvlinesize, bS,
  5977. ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5978. }
  5979. } else {
  5980. filter_mb_edgeh( h, &img_y[4*edge*linesize], linesize, bS, qp );
  5981. if( (edge&1) == 0 ) {
  5982. filter_mb_edgech( h, &img_cb[2*edge*uvlinesize], uvlinesize, bS,
  5983. ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5984. filter_mb_edgech( h, &img_cr[2*edge*uvlinesize], uvlinesize, bS,
  5985. ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);
  5986. }
  5987. }
  5988. }
  5989. }
  5990. }
  5991. static int decode_slice(struct AVCodecContext *avctx, H264Context *h){
  5992. MpegEncContext * const s = &h->s;
  5993. const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;
  5994. s->mb_skip_run= -1;
  5995. if( h->pps.cabac ) {
  5996. int i;
  5997. /* realign */
  5998. align_get_bits( &s->gb );
  5999. /* init cabac */
  6000. ff_init_cabac_states( &h->cabac);
  6001. ff_init_cabac_decoder( &h->cabac,
  6002. s->gb.buffer + get_bits_count(&s->gb)/8,
  6003. ( s->gb.size_in_bits - get_bits_count(&s->gb) + 7)/8);
  6004. /* calculate pre-state */
  6005. for( i= 0; i < 460; i++ ) {
  6006. int pre;
  6007. if( h->slice_type == FF_I_TYPE )
  6008. pre = av_clip( ((cabac_context_init_I[i][0] * s->qscale) >>4 ) + cabac_context_init_I[i][1], 1, 126 );
  6009. else
  6010. 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 );
  6011. if( pre <= 63 )
  6012. h->cabac_state[i] = 2 * ( 63 - pre ) + 0;
  6013. else
  6014. h->cabac_state[i] = 2 * ( pre - 64 ) + 1;
  6015. }
  6016. for(;;){
  6017. //START_TIMER
  6018. int ret = decode_mb_cabac(h);
  6019. int eos;
  6020. //STOP_TIMER("decode_mb_cabac")
  6021. if(ret>=0) hl_decode_mb(h);
  6022. if( ret >= 0 && FRAME_MBAFF ) { //FIXME optimal? or let mb_decode decode 16x32 ?
  6023. s->mb_y++;
  6024. if(ret>=0) ret = decode_mb_cabac(h);
  6025. if(ret>=0) hl_decode_mb(h);
  6026. s->mb_y--;
  6027. }
  6028. eos = get_cabac_terminate( &h->cabac );
  6029. if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  6030. 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);
  6031. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  6032. return -1;
  6033. }
  6034. if( ++s->mb_x >= s->mb_width ) {
  6035. s->mb_x = 0;
  6036. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  6037. ++s->mb_y;
  6038. if(FIELD_OR_MBAFF_PICTURE) {
  6039. ++s->mb_y;
  6040. }
  6041. }
  6042. if( eos || s->mb_y >= s->mb_height ) {
  6043. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  6044. 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);
  6045. return 0;
  6046. }
  6047. }
  6048. } else {
  6049. for(;;){
  6050. int ret = decode_mb_cavlc(h);
  6051. if(ret>=0) hl_decode_mb(h);
  6052. if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
  6053. s->mb_y++;
  6054. ret = decode_mb_cavlc(h);
  6055. if(ret>=0) hl_decode_mb(h);
  6056. s->mb_y--;
  6057. }
  6058. if(ret<0){
  6059. av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  6060. 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);
  6061. return -1;
  6062. }
  6063. if(++s->mb_x >= s->mb_width){
  6064. s->mb_x=0;
  6065. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  6066. ++s->mb_y;
  6067. if(FIELD_OR_MBAFF_PICTURE) {
  6068. ++s->mb_y;
  6069. }
  6070. if(s->mb_y >= s->mb_height){
  6071. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  6072. if(get_bits_count(&s->gb) == s->gb.size_in_bits ) {
  6073. 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);
  6074. return 0;
  6075. }else{
  6076. 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);
  6077. return -1;
  6078. }
  6079. }
  6080. }
  6081. if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
  6082. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  6083. if(get_bits_count(&s->gb) == s->gb.size_in_bits ){
  6084. 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);
  6085. return 0;
  6086. }else{
  6087. 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);
  6088. return -1;
  6089. }
  6090. }
  6091. }
  6092. }
  6093. #if 0
  6094. for(;s->mb_y < s->mb_height; s->mb_y++){
  6095. for(;s->mb_x < s->mb_width; s->mb_x++){
  6096. int ret= decode_mb(h);
  6097. hl_decode_mb(h);
  6098. if(ret<0){
  6099. av_log(s->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  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. if(++s->mb_x >= s->mb_width){
  6104. s->mb_x=0;
  6105. if(++s->mb_y >= s->mb_height){
  6106. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  6107. 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);
  6108. return 0;
  6109. }else{
  6110. 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);
  6111. return -1;
  6112. }
  6113. }
  6114. }
  6115. if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){
  6116. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  6117. 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);
  6118. return 0;
  6119. }else{
  6120. 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);
  6121. return -1;
  6122. }
  6123. }
  6124. }
  6125. s->mb_x=0;
  6126. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  6127. }
  6128. #endif
  6129. return -1; //not reached
  6130. }
  6131. static int decode_unregistered_user_data(H264Context *h, int size){
  6132. MpegEncContext * const s = &h->s;
  6133. uint8_t user_data[16+256];
  6134. int e, build, i;
  6135. if(size<16)
  6136. return -1;
  6137. for(i=0; i<sizeof(user_data)-1 && i<size; i++){
  6138. user_data[i]= get_bits(&s->gb, 8);
  6139. }
  6140. user_data[i]= 0;
  6141. e= sscanf(user_data+16, "x264 - core %d"/*%s - H.264/MPEG-4 AVC codec - Copyleft 2005 - http://www.videolan.org/x264.html*/, &build);
  6142. if(e==1 && build>=0)
  6143. h->x264_build= build;
  6144. if(s->avctx->debug & FF_DEBUG_BUGS)
  6145. av_log(s->avctx, AV_LOG_DEBUG, "user data:\"%s\"\n", user_data+16);
  6146. for(; i<size; i++)
  6147. skip_bits(&s->gb, 8);
  6148. return 0;
  6149. }
  6150. static int decode_sei(H264Context *h){
  6151. MpegEncContext * const s = &h->s;
  6152. while(get_bits_count(&s->gb) + 16 < s->gb.size_in_bits){
  6153. int size, type;
  6154. type=0;
  6155. do{
  6156. type+= show_bits(&s->gb, 8);
  6157. }while(get_bits(&s->gb, 8) == 255);
  6158. size=0;
  6159. do{
  6160. size+= show_bits(&s->gb, 8);
  6161. }while(get_bits(&s->gb, 8) == 255);
  6162. switch(type){
  6163. case 5:
  6164. if(decode_unregistered_user_data(h, size) < 0)
  6165. return -1;
  6166. break;
  6167. default:
  6168. skip_bits(&s->gb, 8*size);
  6169. }
  6170. //FIXME check bits here
  6171. align_get_bits(&s->gb);
  6172. }
  6173. return 0;
  6174. }
  6175. static inline void decode_hrd_parameters(H264Context *h, SPS *sps){
  6176. MpegEncContext * const s = &h->s;
  6177. int cpb_count, i;
  6178. cpb_count = get_ue_golomb(&s->gb) + 1;
  6179. get_bits(&s->gb, 4); /* bit_rate_scale */
  6180. get_bits(&s->gb, 4); /* cpb_size_scale */
  6181. for(i=0; i<cpb_count; i++){
  6182. get_ue_golomb(&s->gb); /* bit_rate_value_minus1 */
  6183. get_ue_golomb(&s->gb); /* cpb_size_value_minus1 */
  6184. get_bits1(&s->gb); /* cbr_flag */
  6185. }
  6186. get_bits(&s->gb, 5); /* initial_cpb_removal_delay_length_minus1 */
  6187. get_bits(&s->gb, 5); /* cpb_removal_delay_length_minus1 */
  6188. get_bits(&s->gb, 5); /* dpb_output_delay_length_minus1 */
  6189. get_bits(&s->gb, 5); /* time_offset_length */
  6190. }
  6191. static inline int decode_vui_parameters(H264Context *h, SPS *sps){
  6192. MpegEncContext * const s = &h->s;
  6193. int aspect_ratio_info_present_flag;
  6194. unsigned int aspect_ratio_idc;
  6195. int nal_hrd_parameters_present_flag, vcl_hrd_parameters_present_flag;
  6196. aspect_ratio_info_present_flag= get_bits1(&s->gb);
  6197. if( aspect_ratio_info_present_flag ) {
  6198. aspect_ratio_idc= get_bits(&s->gb, 8);
  6199. if( aspect_ratio_idc == EXTENDED_SAR ) {
  6200. sps->sar.num= get_bits(&s->gb, 16);
  6201. sps->sar.den= get_bits(&s->gb, 16);
  6202. }else if(aspect_ratio_idc < sizeof(pixel_aspect)/sizeof(*pixel_aspect)){
  6203. sps->sar= pixel_aspect[aspect_ratio_idc];
  6204. }else{
  6205. av_log(h->s.avctx, AV_LOG_ERROR, "illegal aspect ratio\n");
  6206. return -1;
  6207. }
  6208. }else{
  6209. sps->sar.num=
  6210. sps->sar.den= 0;
  6211. }
  6212. // s->avctx->aspect_ratio= sar_width*s->width / (float)(s->height*sar_height);
  6213. if(get_bits1(&s->gb)){ /* overscan_info_present_flag */
  6214. get_bits1(&s->gb); /* overscan_appropriate_flag */
  6215. }
  6216. if(get_bits1(&s->gb)){ /* video_signal_type_present_flag */
  6217. get_bits(&s->gb, 3); /* video_format */
  6218. get_bits1(&s->gb); /* video_full_range_flag */
  6219. if(get_bits1(&s->gb)){ /* colour_description_present_flag */
  6220. get_bits(&s->gb, 8); /* colour_primaries */
  6221. get_bits(&s->gb, 8); /* transfer_characteristics */
  6222. get_bits(&s->gb, 8); /* matrix_coefficients */
  6223. }
  6224. }
  6225. if(get_bits1(&s->gb)){ /* chroma_location_info_present_flag */
  6226. get_ue_golomb(&s->gb); /* chroma_sample_location_type_top_field */
  6227. get_ue_golomb(&s->gb); /* chroma_sample_location_type_bottom_field */
  6228. }
  6229. sps->timing_info_present_flag = get_bits1(&s->gb);
  6230. if(sps->timing_info_present_flag){
  6231. sps->num_units_in_tick = get_bits_long(&s->gb, 32);
  6232. sps->time_scale = get_bits_long(&s->gb, 32);
  6233. sps->fixed_frame_rate_flag = get_bits1(&s->gb);
  6234. }
  6235. nal_hrd_parameters_present_flag = get_bits1(&s->gb);
  6236. if(nal_hrd_parameters_present_flag)
  6237. decode_hrd_parameters(h, sps);
  6238. vcl_hrd_parameters_present_flag = get_bits1(&s->gb);
  6239. if(vcl_hrd_parameters_present_flag)
  6240. decode_hrd_parameters(h, sps);
  6241. if(nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag)
  6242. get_bits1(&s->gb); /* low_delay_hrd_flag */
  6243. get_bits1(&s->gb); /* pic_struct_present_flag */
  6244. sps->bitstream_restriction_flag = get_bits1(&s->gb);
  6245. if(sps->bitstream_restriction_flag){
  6246. unsigned int num_reorder_frames;
  6247. get_bits1(&s->gb); /* motion_vectors_over_pic_boundaries_flag */
  6248. get_ue_golomb(&s->gb); /* max_bytes_per_pic_denom */
  6249. get_ue_golomb(&s->gb); /* max_bits_per_mb_denom */
  6250. get_ue_golomb(&s->gb); /* log2_max_mv_length_horizontal */
  6251. get_ue_golomb(&s->gb); /* log2_max_mv_length_vertical */
  6252. num_reorder_frames= get_ue_golomb(&s->gb);
  6253. get_ue_golomb(&s->gb); /*max_dec_frame_buffering*/
  6254. if(num_reorder_frames > 16 /*max_dec_frame_buffering || max_dec_frame_buffering > 16*/){
  6255. av_log(h->s.avctx, AV_LOG_ERROR, "illegal num_reorder_frames %d\n", num_reorder_frames);
  6256. return -1;
  6257. }
  6258. sps->num_reorder_frames= num_reorder_frames;
  6259. }
  6260. return 0;
  6261. }
  6262. static void decode_scaling_list(H264Context *h, uint8_t *factors, int size,
  6263. const uint8_t *jvt_list, const uint8_t *fallback_list){
  6264. MpegEncContext * const s = &h->s;
  6265. int i, last = 8, next = 8;
  6266. const uint8_t *scan = size == 16 ? zigzag_scan : zigzag_scan8x8;
  6267. if(!get_bits1(&s->gb)) /* matrix not written, we use the predicted one */
  6268. memcpy(factors, fallback_list, size*sizeof(uint8_t));
  6269. else
  6270. for(i=0;i<size;i++){
  6271. if(next)
  6272. next = (last + get_se_golomb(&s->gb)) & 0xff;
  6273. if(!i && !next){ /* matrix not written, we use the preset one */
  6274. memcpy(factors, jvt_list, size*sizeof(uint8_t));
  6275. break;
  6276. }
  6277. last = factors[scan[i]] = next ? next : last;
  6278. }
  6279. }
  6280. static void decode_scaling_matrices(H264Context *h, SPS *sps, PPS *pps, int is_sps,
  6281. uint8_t (*scaling_matrix4)[16], uint8_t (*scaling_matrix8)[64]){
  6282. MpegEncContext * const s = &h->s;
  6283. int fallback_sps = !is_sps && sps->scaling_matrix_present;
  6284. const uint8_t *fallback[4] = {
  6285. fallback_sps ? sps->scaling_matrix4[0] : default_scaling4[0],
  6286. fallback_sps ? sps->scaling_matrix4[3] : default_scaling4[1],
  6287. fallback_sps ? sps->scaling_matrix8[0] : default_scaling8[0],
  6288. fallback_sps ? sps->scaling_matrix8[1] : default_scaling8[1]
  6289. };
  6290. if(get_bits1(&s->gb)){
  6291. sps->scaling_matrix_present |= is_sps;
  6292. decode_scaling_list(h,scaling_matrix4[0],16,default_scaling4[0],fallback[0]); // Intra, Y
  6293. decode_scaling_list(h,scaling_matrix4[1],16,default_scaling4[0],scaling_matrix4[0]); // Intra, Cr
  6294. decode_scaling_list(h,scaling_matrix4[2],16,default_scaling4[0],scaling_matrix4[1]); // Intra, Cb
  6295. decode_scaling_list(h,scaling_matrix4[3],16,default_scaling4[1],fallback[1]); // Inter, Y
  6296. decode_scaling_list(h,scaling_matrix4[4],16,default_scaling4[1],scaling_matrix4[3]); // Inter, Cr
  6297. decode_scaling_list(h,scaling_matrix4[5],16,default_scaling4[1],scaling_matrix4[4]); // Inter, Cb
  6298. if(is_sps || pps->transform_8x8_mode){
  6299. decode_scaling_list(h,scaling_matrix8[0],64,default_scaling8[0],fallback[2]); // Intra, Y
  6300. decode_scaling_list(h,scaling_matrix8[1],64,default_scaling8[1],fallback[3]); // Inter, Y
  6301. }
  6302. } else if(fallback_sps) {
  6303. memcpy(scaling_matrix4, sps->scaling_matrix4, 6*16*sizeof(uint8_t));
  6304. memcpy(scaling_matrix8, sps->scaling_matrix8, 2*64*sizeof(uint8_t));
  6305. }
  6306. }
  6307. /**
  6308. * Returns and optionally allocates SPS / PPS structures in the supplied array 'vec'
  6309. */
  6310. static void *
  6311. alloc_parameter_set(H264Context *h, void **vec, const unsigned int id, const unsigned int max,
  6312. const size_t size, const char *name)
  6313. {
  6314. if(id>=max) {
  6315. av_log(h->s.avctx, AV_LOG_ERROR, "%s_id (%d) out of range\n", name, id);
  6316. return NULL;
  6317. }
  6318. if(!vec[id]) {
  6319. vec[id] = av_mallocz(size);
  6320. if(vec[id] == NULL)
  6321. av_log(h->s.avctx, AV_LOG_ERROR, "cannot allocate memory for %s\n", name);
  6322. }
  6323. return vec[id];
  6324. }
  6325. static inline int decode_seq_parameter_set(H264Context *h){
  6326. MpegEncContext * const s = &h->s;
  6327. int profile_idc, level_idc;
  6328. unsigned int sps_id, tmp, mb_width, mb_height;
  6329. int i;
  6330. SPS *sps;
  6331. profile_idc= get_bits(&s->gb, 8);
  6332. get_bits1(&s->gb); //constraint_set0_flag
  6333. get_bits1(&s->gb); //constraint_set1_flag
  6334. get_bits1(&s->gb); //constraint_set2_flag
  6335. get_bits1(&s->gb); //constraint_set3_flag
  6336. get_bits(&s->gb, 4); // reserved
  6337. level_idc= get_bits(&s->gb, 8);
  6338. sps_id= get_ue_golomb(&s->gb);
  6339. sps = alloc_parameter_set(h, (void **)h->sps_buffers, sps_id, MAX_SPS_COUNT, sizeof(SPS), "sps");
  6340. if(sps == NULL)
  6341. return -1;
  6342. sps->profile_idc= profile_idc;
  6343. sps->level_idc= level_idc;
  6344. if(sps->profile_idc >= 100){ //high profile
  6345. if(get_ue_golomb(&s->gb) == 3) //chroma_format_idc
  6346. get_bits1(&s->gb); //residual_color_transform_flag
  6347. get_ue_golomb(&s->gb); //bit_depth_luma_minus8
  6348. get_ue_golomb(&s->gb); //bit_depth_chroma_minus8
  6349. sps->transform_bypass = get_bits1(&s->gb);
  6350. decode_scaling_matrices(h, sps, NULL, 1, sps->scaling_matrix4, sps->scaling_matrix8);
  6351. }else
  6352. sps->scaling_matrix_present = 0;
  6353. sps->log2_max_frame_num= get_ue_golomb(&s->gb) + 4;
  6354. sps->poc_type= get_ue_golomb(&s->gb);
  6355. if(sps->poc_type == 0){ //FIXME #define
  6356. sps->log2_max_poc_lsb= get_ue_golomb(&s->gb) + 4;
  6357. } else if(sps->poc_type == 1){//FIXME #define
  6358. sps->delta_pic_order_always_zero_flag= get_bits1(&s->gb);
  6359. sps->offset_for_non_ref_pic= get_se_golomb(&s->gb);
  6360. sps->offset_for_top_to_bottom_field= get_se_golomb(&s->gb);
  6361. tmp= get_ue_golomb(&s->gb);
  6362. if(tmp >= sizeof(sps->offset_for_ref_frame) / sizeof(sps->offset_for_ref_frame[0])){
  6363. av_log(h->s.avctx, AV_LOG_ERROR, "poc_cycle_length overflow %u\n", tmp);
  6364. return -1;
  6365. }
  6366. sps->poc_cycle_length= tmp;
  6367. for(i=0; i<sps->poc_cycle_length; i++)
  6368. sps->offset_for_ref_frame[i]= get_se_golomb(&s->gb);
  6369. }else if(sps->poc_type != 2){
  6370. av_log(h->s.avctx, AV_LOG_ERROR, "illegal POC type %d\n", sps->poc_type);
  6371. return -1;
  6372. }
  6373. tmp= get_ue_golomb(&s->gb);
  6374. if(tmp > MAX_PICTURE_COUNT-2 || tmp >= 32){
  6375. av_log(h->s.avctx, AV_LOG_ERROR, "too many reference frames\n");
  6376. return -1;
  6377. }
  6378. sps->ref_frame_count= tmp;
  6379. sps->gaps_in_frame_num_allowed_flag= get_bits1(&s->gb);
  6380. mb_width= get_ue_golomb(&s->gb) + 1;
  6381. mb_height= get_ue_golomb(&s->gb) + 1;
  6382. if(mb_width >= INT_MAX/16 || mb_height >= INT_MAX/16 ||
  6383. avcodec_check_dimensions(NULL, 16*mb_width, 16*mb_height)){
  6384. av_log(h->s.avctx, AV_LOG_ERROR, "mb_width/height overflow\n");
  6385. return -1;
  6386. }
  6387. sps->mb_width = mb_width;
  6388. sps->mb_height= mb_height;
  6389. sps->frame_mbs_only_flag= get_bits1(&s->gb);
  6390. if(!sps->frame_mbs_only_flag)
  6391. sps->mb_aff= get_bits1(&s->gb);
  6392. else
  6393. sps->mb_aff= 0;
  6394. sps->direct_8x8_inference_flag= get_bits1(&s->gb);
  6395. #ifndef ALLOW_INTERLACE
  6396. if(sps->mb_aff)
  6397. av_log(h->s.avctx, AV_LOG_ERROR, "MBAFF support not included; enable it at compile-time.\n");
  6398. #endif
  6399. if(!sps->direct_8x8_inference_flag && sps->mb_aff)
  6400. av_log(h->s.avctx, AV_LOG_ERROR, "MBAFF + !direct_8x8_inference is not implemented\n");
  6401. sps->crop= get_bits1(&s->gb);
  6402. if(sps->crop){
  6403. sps->crop_left = get_ue_golomb(&s->gb);
  6404. sps->crop_right = get_ue_golomb(&s->gb);
  6405. sps->crop_top = get_ue_golomb(&s->gb);
  6406. sps->crop_bottom= get_ue_golomb(&s->gb);
  6407. if(sps->crop_left || sps->crop_top){
  6408. av_log(h->s.avctx, AV_LOG_ERROR, "insane cropping not completely supported, this could look slightly wrong ...\n");
  6409. }
  6410. if(sps->crop_right >= 8 || sps->crop_bottom >= (8>> !h->sps.frame_mbs_only_flag)){
  6411. av_log(h->s.avctx, AV_LOG_ERROR, "brainfart cropping not supported, this could look slightly wrong ...\n");
  6412. }
  6413. }else{
  6414. sps->crop_left =
  6415. sps->crop_right =
  6416. sps->crop_top =
  6417. sps->crop_bottom= 0;
  6418. }
  6419. sps->vui_parameters_present_flag= get_bits1(&s->gb);
  6420. if( sps->vui_parameters_present_flag )
  6421. decode_vui_parameters(h, sps);
  6422. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  6423. 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",
  6424. sps_id, sps->profile_idc, sps->level_idc,
  6425. sps->poc_type,
  6426. sps->ref_frame_count,
  6427. sps->mb_width, sps->mb_height,
  6428. sps->frame_mbs_only_flag ? "FRM" : (sps->mb_aff ? "MB-AFF" : "PIC-AFF"),
  6429. sps->direct_8x8_inference_flag ? "8B8" : "",
  6430. sps->crop_left, sps->crop_right,
  6431. sps->crop_top, sps->crop_bottom,
  6432. sps->vui_parameters_present_flag ? "VUI" : ""
  6433. );
  6434. }
  6435. return 0;
  6436. }
  6437. static void
  6438. build_qp_table(PPS *pps, int t, int index)
  6439. {
  6440. int i;
  6441. for(i = 0; i < 255; i++)
  6442. pps->chroma_qp_table[t][i & 0xff] = chroma_qp[av_clip(i + index, 0, 51)];
  6443. }
  6444. static inline int decode_picture_parameter_set(H264Context *h, int bit_length){
  6445. MpegEncContext * const s = &h->s;
  6446. unsigned int tmp, pps_id= get_ue_golomb(&s->gb);
  6447. PPS *pps;
  6448. pps = alloc_parameter_set(h, (void **)h->pps_buffers, pps_id, MAX_PPS_COUNT, sizeof(PPS), "pps");
  6449. if(pps == NULL)
  6450. return -1;
  6451. tmp= get_ue_golomb(&s->gb);
  6452. if(tmp>=MAX_SPS_COUNT || h->sps_buffers[tmp] == NULL){
  6453. av_log(h->s.avctx, AV_LOG_ERROR, "sps_id out of range\n");
  6454. return -1;
  6455. }
  6456. pps->sps_id= tmp;
  6457. pps->cabac= get_bits1(&s->gb);
  6458. pps->pic_order_present= get_bits1(&s->gb);
  6459. pps->slice_group_count= get_ue_golomb(&s->gb) + 1;
  6460. if(pps->slice_group_count > 1 ){
  6461. pps->mb_slice_group_map_type= get_ue_golomb(&s->gb);
  6462. av_log(h->s.avctx, AV_LOG_ERROR, "FMO not supported\n");
  6463. switch(pps->mb_slice_group_map_type){
  6464. case 0:
  6465. #if 0
  6466. | for( i = 0; i <= num_slice_groups_minus1; i++ ) | | |
  6467. | run_length[ i ] |1 |ue(v) |
  6468. #endif
  6469. break;
  6470. case 2:
  6471. #if 0
  6472. | for( i = 0; i < num_slice_groups_minus1; i++ ) | | |
  6473. |{ | | |
  6474. | top_left_mb[ i ] |1 |ue(v) |
  6475. | bottom_right_mb[ i ] |1 |ue(v) |
  6476. | } | | |
  6477. #endif
  6478. break;
  6479. case 3:
  6480. case 4:
  6481. case 5:
  6482. #if 0
  6483. | slice_group_change_direction_flag |1 |u(1) |
  6484. | slice_group_change_rate_minus1 |1 |ue(v) |
  6485. #endif
  6486. break;
  6487. case 6:
  6488. #if 0
  6489. | slice_group_id_cnt_minus1 |1 |ue(v) |
  6490. | for( i = 0; i <= slice_group_id_cnt_minus1; i++ | | |
  6491. |) | | |
  6492. | slice_group_id[ i ] |1 |u(v) |
  6493. #endif
  6494. break;
  6495. }
  6496. }
  6497. pps->ref_count[0]= get_ue_golomb(&s->gb) + 1;
  6498. pps->ref_count[1]= get_ue_golomb(&s->gb) + 1;
  6499. if(pps->ref_count[0]-1 > 32-1 || pps->ref_count[1]-1 > 32-1){
  6500. av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow (pps)\n");
  6501. pps->ref_count[0]= pps->ref_count[1]= 1;
  6502. return -1;
  6503. }
  6504. pps->weighted_pred= get_bits1(&s->gb);
  6505. pps->weighted_bipred_idc= get_bits(&s->gb, 2);
  6506. pps->init_qp= get_se_golomb(&s->gb) + 26;
  6507. pps->init_qs= get_se_golomb(&s->gb) + 26;
  6508. pps->chroma_qp_index_offset[0]= get_se_golomb(&s->gb);
  6509. pps->deblocking_filter_parameters_present= get_bits1(&s->gb);
  6510. pps->constrained_intra_pred= get_bits1(&s->gb);
  6511. pps->redundant_pic_cnt_present = get_bits1(&s->gb);
  6512. pps->transform_8x8_mode= 0;
  6513. h->dequant_coeff_pps= -1; //contents of sps/pps can change even if id doesn't, so reinit
  6514. memset(pps->scaling_matrix4, 16, 6*16*sizeof(uint8_t));
  6515. memset(pps->scaling_matrix8, 16, 2*64*sizeof(uint8_t));
  6516. if(get_bits_count(&s->gb) < bit_length){
  6517. pps->transform_8x8_mode= get_bits1(&s->gb);
  6518. decode_scaling_matrices(h, h->sps_buffers[pps->sps_id], pps, 0, pps->scaling_matrix4, pps->scaling_matrix8);
  6519. pps->chroma_qp_index_offset[1]= get_se_golomb(&s->gb); //second_chroma_qp_index_offset
  6520. } else {
  6521. pps->chroma_qp_index_offset[1]= pps->chroma_qp_index_offset[0];
  6522. }
  6523. build_qp_table(pps, 0, pps->chroma_qp_index_offset[0]);
  6524. if(pps->chroma_qp_index_offset[0] != pps->chroma_qp_index_offset[1]) {
  6525. build_qp_table(pps, 1, pps->chroma_qp_index_offset[1]);
  6526. h->pps.chroma_qp_diff= 1;
  6527. } else
  6528. memcpy(pps->chroma_qp_table[1], pps->chroma_qp_table[0], 256);
  6529. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  6530. 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",
  6531. pps_id, pps->sps_id,
  6532. pps->cabac ? "CABAC" : "CAVLC",
  6533. pps->slice_group_count,
  6534. pps->ref_count[0], pps->ref_count[1],
  6535. pps->weighted_pred ? "weighted" : "",
  6536. pps->init_qp, pps->init_qs, pps->chroma_qp_index_offset[0], pps->chroma_qp_index_offset[1],
  6537. pps->deblocking_filter_parameters_present ? "LPAR" : "",
  6538. pps->constrained_intra_pred ? "CONSTR" : "",
  6539. pps->redundant_pic_cnt_present ? "REDU" : "",
  6540. pps->transform_8x8_mode ? "8x8DCT" : ""
  6541. );
  6542. }
  6543. return 0;
  6544. }
  6545. /**
  6546. * Call decode_slice() for each context.
  6547. *
  6548. * @param h h264 master context
  6549. * @param context_count number of contexts to execute
  6550. */
  6551. static void execute_decode_slices(H264Context *h, int context_count){
  6552. MpegEncContext * const s = &h->s;
  6553. AVCodecContext * const avctx= s->avctx;
  6554. H264Context *hx;
  6555. int i;
  6556. if(context_count == 1) {
  6557. decode_slice(avctx, h);
  6558. } else {
  6559. for(i = 1; i < context_count; i++) {
  6560. hx = h->thread_context[i];
  6561. hx->s.error_resilience = avctx->error_resilience;
  6562. hx->s.error_count = 0;
  6563. }
  6564. avctx->execute(avctx, (void *)decode_slice,
  6565. (void **)h->thread_context, NULL, context_count);
  6566. /* pull back stuff from slices to master context */
  6567. hx = h->thread_context[context_count - 1];
  6568. s->mb_x = hx->s.mb_x;
  6569. s->mb_y = hx->s.mb_y;
  6570. s->dropable = hx->s.dropable;
  6571. s->picture_structure = hx->s.picture_structure;
  6572. for(i = 1; i < context_count; i++)
  6573. h->s.error_count += h->thread_context[i]->s.error_count;
  6574. }
  6575. }
  6576. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
  6577. MpegEncContext * const s = &h->s;
  6578. AVCodecContext * const avctx= s->avctx;
  6579. int buf_index=0;
  6580. H264Context *hx; ///< thread context
  6581. int context_count = 0;
  6582. h->max_contexts = avctx->thread_count;
  6583. #if 0
  6584. int i;
  6585. for(i=0; i<50; i++){
  6586. av_log(NULL, AV_LOG_ERROR,"%02X ", buf[i]);
  6587. }
  6588. #endif
  6589. if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
  6590. h->current_slice = 0;
  6591. if (!s->first_field)
  6592. s->current_picture_ptr= NULL;
  6593. }
  6594. for(;;){
  6595. int consumed;
  6596. int dst_length;
  6597. int bit_length;
  6598. const uint8_t *ptr;
  6599. int i, nalsize = 0;
  6600. int err;
  6601. if(h->is_avc) {
  6602. if(buf_index >= buf_size) break;
  6603. nalsize = 0;
  6604. for(i = 0; i < h->nal_length_size; i++)
  6605. nalsize = (nalsize << 8) | buf[buf_index++];
  6606. if(nalsize <= 1 || (nalsize+buf_index > buf_size)){
  6607. if(nalsize == 1){
  6608. buf_index++;
  6609. continue;
  6610. }else{
  6611. av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
  6612. break;
  6613. }
  6614. }
  6615. } else {
  6616. // start code prefix search
  6617. for(; buf_index + 3 < buf_size; buf_index++){
  6618. // This should always succeed in the first iteration.
  6619. if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)
  6620. break;
  6621. }
  6622. if(buf_index+3 >= buf_size) break;
  6623. buf_index+=3;
  6624. }
  6625. hx = h->thread_context[context_count];
  6626. ptr= decode_nal(hx, buf + buf_index, &dst_length, &consumed, h->is_avc ? nalsize : buf_size - buf_index);
  6627. if (ptr==NULL || dst_length < 0){
  6628. return -1;
  6629. }
  6630. while(ptr[dst_length - 1] == 0 && dst_length > 0)
  6631. dst_length--;
  6632. bit_length= !dst_length ? 0 : (8*dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1));
  6633. if(s->avctx->debug&FF_DEBUG_STARTCODE){
  6634. 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);
  6635. }
  6636. if (h->is_avc && (nalsize != consumed)){
  6637. av_log(h->s.avctx, AV_LOG_ERROR, "AVC: Consumed only %d bytes instead of %d\n", consumed, nalsize);
  6638. consumed= nalsize;
  6639. }
  6640. buf_index += consumed;
  6641. if( (s->hurry_up == 1 && h->nal_ref_idc == 0) //FIXME do not discard SEI id
  6642. ||(avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
  6643. continue;
  6644. again:
  6645. err = 0;
  6646. switch(hx->nal_unit_type){
  6647. case NAL_IDR_SLICE:
  6648. if (h->nal_unit_type != NAL_IDR_SLICE) {
  6649. av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices");
  6650. return -1;
  6651. }
  6652. idr(h); //FIXME ensure we don't loose some frames if there is reordering
  6653. case NAL_SLICE:
  6654. init_get_bits(&hx->s.gb, ptr, bit_length);
  6655. hx->intra_gb_ptr=
  6656. hx->inter_gb_ptr= &hx->s.gb;
  6657. hx->s.data_partitioning = 0;
  6658. if((err = decode_slice_header(hx, h)))
  6659. break;
  6660. s->current_picture_ptr->key_frame|= (hx->nal_unit_type == NAL_IDR_SLICE);
  6661. if(hx->redundant_pic_count==0 && hx->s.hurry_up < 5
  6662. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  6663. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type!=FF_B_TYPE)
  6664. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type==FF_I_TYPE)
  6665. && avctx->skip_frame < AVDISCARD_ALL)
  6666. context_count++;
  6667. break;
  6668. case NAL_DPA:
  6669. init_get_bits(&hx->s.gb, ptr, bit_length);
  6670. hx->intra_gb_ptr=
  6671. hx->inter_gb_ptr= NULL;
  6672. hx->s.data_partitioning = 1;
  6673. err = decode_slice_header(hx, h);
  6674. break;
  6675. case NAL_DPB:
  6676. init_get_bits(&hx->intra_gb, ptr, bit_length);
  6677. hx->intra_gb_ptr= &hx->intra_gb;
  6678. break;
  6679. case NAL_DPC:
  6680. init_get_bits(&hx->inter_gb, ptr, bit_length);
  6681. hx->inter_gb_ptr= &hx->inter_gb;
  6682. if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
  6683. && s->context_initialized
  6684. && s->hurry_up < 5
  6685. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  6686. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type!=FF_B_TYPE)
  6687. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type==FF_I_TYPE)
  6688. && avctx->skip_frame < AVDISCARD_ALL)
  6689. context_count++;
  6690. break;
  6691. case NAL_SEI:
  6692. init_get_bits(&s->gb, ptr, bit_length);
  6693. decode_sei(h);
  6694. break;
  6695. case NAL_SPS:
  6696. init_get_bits(&s->gb, ptr, bit_length);
  6697. decode_seq_parameter_set(h);
  6698. if(s->flags& CODEC_FLAG_LOW_DELAY)
  6699. s->low_delay=1;
  6700. if(avctx->has_b_frames < 2)
  6701. avctx->has_b_frames= !s->low_delay;
  6702. break;
  6703. case NAL_PPS:
  6704. init_get_bits(&s->gb, ptr, bit_length);
  6705. decode_picture_parameter_set(h, bit_length);
  6706. break;
  6707. case NAL_AUD:
  6708. case NAL_END_SEQUENCE:
  6709. case NAL_END_STREAM:
  6710. case NAL_FILLER_DATA:
  6711. case NAL_SPS_EXT:
  6712. case NAL_AUXILIARY_SLICE:
  6713. break;
  6714. default:
  6715. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", h->nal_unit_type, bit_length);
  6716. }
  6717. if(context_count == h->max_contexts) {
  6718. execute_decode_slices(h, context_count);
  6719. context_count = 0;
  6720. }
  6721. if (err < 0)
  6722. av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  6723. else if(err == 1) {
  6724. /* Slice could not be decoded in parallel mode, copy down
  6725. * NAL unit stuff to context 0 and restart. Note that
  6726. * rbsp_buffer is not transfered, but since we no longer
  6727. * run in parallel mode this should not be an issue. */
  6728. h->nal_unit_type = hx->nal_unit_type;
  6729. h->nal_ref_idc = hx->nal_ref_idc;
  6730. hx = h;
  6731. goto again;
  6732. }
  6733. }
  6734. if(context_count)
  6735. execute_decode_slices(h, context_count);
  6736. return buf_index;
  6737. }
  6738. /**
  6739. * returns the number of bytes consumed for building the current frame
  6740. */
  6741. static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
  6742. if(s->flags&CODEC_FLAG_TRUNCATED){
  6743. pos -= s->parse_context.last_index;
  6744. if(pos<0) pos=0; // FIXME remove (unneeded?)
  6745. return pos;
  6746. }else{
  6747. if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
  6748. if(pos+10>buf_size) pos=buf_size; // oops ;)
  6749. return pos;
  6750. }
  6751. }
  6752. static int decode_frame(AVCodecContext *avctx,
  6753. void *data, int *data_size,
  6754. const uint8_t *buf, int buf_size)
  6755. {
  6756. H264Context *h = avctx->priv_data;
  6757. MpegEncContext *s = &h->s;
  6758. AVFrame *pict = data;
  6759. int buf_index;
  6760. s->flags= avctx->flags;
  6761. s->flags2= avctx->flags2;
  6762. /* no supplementary picture */
  6763. if (buf_size == 0) {
  6764. Picture *out;
  6765. int i, out_idx;
  6766. //FIXME factorize this with the output code below
  6767. out = h->delayed_pic[0];
  6768. out_idx = 0;
  6769. for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame; i++)
  6770. if(h->delayed_pic[i]->poc < out->poc){
  6771. out = h->delayed_pic[i];
  6772. out_idx = i;
  6773. }
  6774. for(i=out_idx; h->delayed_pic[i]; i++)
  6775. h->delayed_pic[i] = h->delayed_pic[i+1];
  6776. if(out){
  6777. *data_size = sizeof(AVFrame);
  6778. *pict= *(AVFrame*)out;
  6779. }
  6780. return 0;
  6781. }
  6782. if(s->flags&CODEC_FLAG_TRUNCATED){
  6783. int next= ff_h264_find_frame_end(h, buf, buf_size);
  6784. if( ff_combine_frame(&s->parse_context, next, (const uint8_t **)&buf, &buf_size) < 0 )
  6785. return buf_size;
  6786. //printf("next:%d buf_size:%d last_index:%d\n", next, buf_size, s->parse_context.last_index);
  6787. }
  6788. if(h->is_avc && !h->got_avcC) {
  6789. int i, cnt, nalsize;
  6790. unsigned char *p = avctx->extradata;
  6791. if(avctx->extradata_size < 7) {
  6792. av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
  6793. return -1;
  6794. }
  6795. if(*p != 1) {
  6796. av_log(avctx, AV_LOG_ERROR, "Unknown avcC version %d\n", *p);
  6797. return -1;
  6798. }
  6799. /* sps and pps in the avcC always have length coded with 2 bytes,
  6800. so put a fake nal_length_size = 2 while parsing them */
  6801. h->nal_length_size = 2;
  6802. // Decode sps from avcC
  6803. cnt = *(p+5) & 0x1f; // Number of sps
  6804. p += 6;
  6805. for (i = 0; i < cnt; i++) {
  6806. nalsize = AV_RB16(p) + 2;
  6807. if(decode_nal_units(h, p, nalsize) < 0) {
  6808. av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);
  6809. return -1;
  6810. }
  6811. p += nalsize;
  6812. }
  6813. // Decode pps from avcC
  6814. cnt = *(p++); // Number of pps
  6815. for (i = 0; i < cnt; i++) {
  6816. nalsize = AV_RB16(p) + 2;
  6817. if(decode_nal_units(h, p, nalsize) != nalsize) {
  6818. av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);
  6819. return -1;
  6820. }
  6821. p += nalsize;
  6822. }
  6823. // Now store right nal length size, that will be use to parse all other nals
  6824. h->nal_length_size = ((*(((char*)(avctx->extradata))+4))&0x03)+1;
  6825. // Do not reparse avcC
  6826. h->got_avcC = 1;
  6827. }
  6828. if(avctx->frame_number==0 && !h->is_avc && s->avctx->extradata_size){
  6829. if(decode_nal_units(h, s->avctx->extradata, s->avctx->extradata_size) < 0)
  6830. return -1;
  6831. }
  6832. buf_index=decode_nal_units(h, buf, buf_size);
  6833. if(buf_index < 0)
  6834. return -1;
  6835. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
  6836. if (avctx->skip_frame >= AVDISCARD_NONREF || s->hurry_up) return 0;
  6837. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  6838. return -1;
  6839. }
  6840. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
  6841. Picture *out = s->current_picture_ptr;
  6842. Picture *cur = s->current_picture_ptr;
  6843. Picture *prev = h->delayed_output_pic;
  6844. int i, pics, cross_idr, out_of_order, out_idx;
  6845. s->mb_y= 0;
  6846. s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;
  6847. s->current_picture_ptr->pict_type= s->pict_type;
  6848. h->prev_frame_num_offset= h->frame_num_offset;
  6849. h->prev_frame_num= h->frame_num;
  6850. if(!s->dropable) {
  6851. h->prev_poc_msb= h->poc_msb;
  6852. h->prev_poc_lsb= h->poc_lsb;
  6853. execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  6854. }
  6855. /*
  6856. * FIXME: Error handling code does not seem to support interlaced
  6857. * when slices span multiple rows
  6858. * The ff_er_add_slice calls don't work right for bottom
  6859. * fields; they cause massive erroneous error concealing
  6860. * Error marking covers both fields (top and bottom).
  6861. * This causes a mismatched s->error_count
  6862. * and a bad error table. Further, the error count goes to
  6863. * INT_MAX when called for bottom field, because mb_y is
  6864. * past end by one (callers fault) and resync_mb_y != 0
  6865. * causes problems for the first MB line, too.
  6866. */
  6867. if (!FIELD_PICTURE)
  6868. ff_er_frame_end(s);
  6869. MPV_frame_end(s);
  6870. if (s->first_field) {
  6871. /* Wait for second field. */
  6872. *data_size = 0;
  6873. } else {
  6874. cur->interlaced_frame = FIELD_OR_MBAFF_PICTURE;
  6875. /* Derive top_field_first from field pocs. */
  6876. cur->top_field_first = cur->field_poc[0] < cur->field_poc[1];
  6877. //FIXME do something with unavailable reference frames
  6878. #if 0 //decode order
  6879. *data_size = sizeof(AVFrame);
  6880. #else
  6881. /* Sort B-frames into display order */
  6882. if(h->sps.bitstream_restriction_flag
  6883. && s->avctx->has_b_frames < h->sps.num_reorder_frames){
  6884. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  6885. s->low_delay = 0;
  6886. }
  6887. pics = 0;
  6888. while(h->delayed_pic[pics]) pics++;
  6889. assert(pics+1 < sizeof(h->delayed_pic) / sizeof(h->delayed_pic[0]));
  6890. h->delayed_pic[pics++] = cur;
  6891. if(cur->reference == 0)
  6892. cur->reference = DELAYED_PIC_REF;
  6893. cross_idr = 0;
  6894. for(i=0; h->delayed_pic[i]; i++)
  6895. if(h->delayed_pic[i]->key_frame || h->delayed_pic[i]->poc==0)
  6896. cross_idr = 1;
  6897. out = h->delayed_pic[0];
  6898. out_idx = 0;
  6899. for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame; i++)
  6900. if(h->delayed_pic[i]->poc < out->poc){
  6901. out = h->delayed_pic[i];
  6902. out_idx = i;
  6903. }
  6904. out_of_order = !cross_idr && prev && out->poc < prev->poc;
  6905. if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames >= h->sps.num_reorder_frames)
  6906. { }
  6907. else if(prev && pics <= s->avctx->has_b_frames)
  6908. out = prev;
  6909. else if((out_of_order && pics-1 == s->avctx->has_b_frames && pics < 15)
  6910. || (s->low_delay &&
  6911. ((!cross_idr && prev && out->poc > prev->poc + 2)
  6912. || cur->pict_type == FF_B_TYPE)))
  6913. {
  6914. s->low_delay = 0;
  6915. s->avctx->has_b_frames++;
  6916. out = prev;
  6917. }
  6918. else if(out_of_order)
  6919. out = prev;
  6920. if(out_of_order || pics > s->avctx->has_b_frames){
  6921. for(i=out_idx; h->delayed_pic[i]; i++)
  6922. h->delayed_pic[i] = h->delayed_pic[i+1];
  6923. }
  6924. if(prev == out)
  6925. *data_size = 0;
  6926. else
  6927. *data_size = sizeof(AVFrame);
  6928. if(prev && prev != out && prev->reference == DELAYED_PIC_REF)
  6929. prev->reference = 0;
  6930. h->delayed_output_pic = out;
  6931. #endif
  6932. if(out)
  6933. *pict= *(AVFrame*)out;
  6934. else
  6935. av_log(avctx, AV_LOG_DEBUG, "no picture\n");
  6936. }
  6937. }
  6938. assert(pict->data[0] || !*data_size);
  6939. ff_print_debug_info(s, pict);
  6940. //printf("out %d\n", (int)pict->data[0]);
  6941. #if 0 //?
  6942. /* Return the Picture timestamp as the frame number */
  6943. /* we subtract 1 because it is added on utils.c */
  6944. avctx->frame_number = s->picture_number - 1;
  6945. #endif
  6946. return get_consumed_bytes(s, buf_index, buf_size);
  6947. }
  6948. #if 0
  6949. static inline void fill_mb_avail(H264Context *h){
  6950. MpegEncContext * const s = &h->s;
  6951. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  6952. if(s->mb_y){
  6953. h->mb_avail[0]= s->mb_x && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
  6954. h->mb_avail[1]= h->slice_table[mb_xy - s->mb_stride ] == h->slice_num;
  6955. h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
  6956. }else{
  6957. h->mb_avail[0]=
  6958. h->mb_avail[1]=
  6959. h->mb_avail[2]= 0;
  6960. }
  6961. h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
  6962. h->mb_avail[4]= 1; //FIXME move out
  6963. h->mb_avail[5]= 0; //FIXME move out
  6964. }
  6965. #endif
  6966. #ifdef TEST
  6967. #undef printf
  6968. #undef random
  6969. #define COUNT 8000
  6970. #define SIZE (COUNT*40)
  6971. int main(void){
  6972. int i;
  6973. uint8_t temp[SIZE];
  6974. PutBitContext pb;
  6975. GetBitContext gb;
  6976. // int int_temp[10000];
  6977. DSPContext dsp;
  6978. AVCodecContext avctx;
  6979. dsputil_init(&dsp, &avctx);
  6980. init_put_bits(&pb, temp, SIZE);
  6981. printf("testing unsigned exp golomb\n");
  6982. for(i=0; i<COUNT; i++){
  6983. START_TIMER
  6984. set_ue_golomb(&pb, i);
  6985. STOP_TIMER("set_ue_golomb");
  6986. }
  6987. flush_put_bits(&pb);
  6988. init_get_bits(&gb, temp, 8*SIZE);
  6989. for(i=0; i<COUNT; i++){
  6990. int j, s;
  6991. s= show_bits(&gb, 24);
  6992. START_TIMER
  6993. j= get_ue_golomb(&gb);
  6994. if(j != i){
  6995. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  6996. // return -1;
  6997. }
  6998. STOP_TIMER("get_ue_golomb");
  6999. }
  7000. init_put_bits(&pb, temp, SIZE);
  7001. printf("testing signed exp golomb\n");
  7002. for(i=0; i<COUNT; i++){
  7003. START_TIMER
  7004. set_se_golomb(&pb, i - COUNT/2);
  7005. STOP_TIMER("set_se_golomb");
  7006. }
  7007. flush_put_bits(&pb);
  7008. init_get_bits(&gb, temp, 8*SIZE);
  7009. for(i=0; i<COUNT; i++){
  7010. int j, s;
  7011. s= show_bits(&gb, 24);
  7012. START_TIMER
  7013. j= get_se_golomb(&gb);
  7014. if(j != i - COUNT/2){
  7015. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  7016. // return -1;
  7017. }
  7018. STOP_TIMER("get_se_golomb");
  7019. }
  7020. #if 0
  7021. printf("testing 4x4 (I)DCT\n");
  7022. DCTELEM block[16];
  7023. uint8_t src[16], ref[16];
  7024. uint64_t error= 0, max_error=0;
  7025. for(i=0; i<COUNT; i++){
  7026. int j;
  7027. // printf("%d %d %d\n", r1, r2, (r2-r1)*16);
  7028. for(j=0; j<16; j++){
  7029. ref[j]= random()%255;
  7030. src[j]= random()%255;
  7031. }
  7032. h264_diff_dct_c(block, src, ref, 4);
  7033. //normalize
  7034. for(j=0; j<16; j++){
  7035. // printf("%d ", block[j]);
  7036. block[j]= block[j]*4;
  7037. if(j&1) block[j]= (block[j]*4 + 2)/5;
  7038. if(j&4) block[j]= (block[j]*4 + 2)/5;
  7039. }
  7040. // printf("\n");
  7041. s->dsp.h264_idct_add(ref, block, 4);
  7042. /* for(j=0; j<16; j++){
  7043. printf("%d ", ref[j]);
  7044. }
  7045. printf("\n");*/
  7046. for(j=0; j<16; j++){
  7047. int diff= FFABS(src[j] - ref[j]);
  7048. error+= diff*diff;
  7049. max_error= FFMAX(max_error, diff);
  7050. }
  7051. }
  7052. printf("error=%f max_error=%d\n", ((float)error)/COUNT/16, (int)max_error );
  7053. printf("testing quantizer\n");
  7054. for(qp=0; qp<52; qp++){
  7055. for(i=0; i<16; i++)
  7056. src1_block[i]= src2_block[i]= random()%255;
  7057. }
  7058. printf("Testing NAL layer\n");
  7059. uint8_t bitstream[COUNT];
  7060. uint8_t nal[COUNT*2];
  7061. H264Context h;
  7062. memset(&h, 0, sizeof(H264Context));
  7063. for(i=0; i<COUNT; i++){
  7064. int zeros= i;
  7065. int nal_length;
  7066. int consumed;
  7067. int out_length;
  7068. uint8_t *out;
  7069. int j;
  7070. for(j=0; j<COUNT; j++){
  7071. bitstream[j]= (random() % 255) + 1;
  7072. }
  7073. for(j=0; j<zeros; j++){
  7074. int pos= random() % COUNT;
  7075. while(bitstream[pos] == 0){
  7076. pos++;
  7077. pos %= COUNT;
  7078. }
  7079. bitstream[pos]=0;
  7080. }
  7081. START_TIMER
  7082. nal_length= encode_nal(&h, nal, bitstream, COUNT, COUNT*2);
  7083. if(nal_length<0){
  7084. printf("encoding failed\n");
  7085. return -1;
  7086. }
  7087. out= decode_nal(&h, nal, &out_length, &consumed, nal_length);
  7088. STOP_TIMER("NAL")
  7089. if(out_length != COUNT){
  7090. printf("incorrect length %d %d\n", out_length, COUNT);
  7091. return -1;
  7092. }
  7093. if(consumed != nal_length){
  7094. printf("incorrect consumed length %d %d\n", nal_length, consumed);
  7095. return -1;
  7096. }
  7097. if(memcmp(bitstream, out, COUNT)){
  7098. printf("mismatch\n");
  7099. return -1;
  7100. }
  7101. }
  7102. #endif
  7103. printf("Testing RBSP\n");
  7104. return 0;
  7105. }
  7106. #endif /* TEST */
  7107. static av_cold int decode_end(AVCodecContext *avctx)
  7108. {
  7109. H264Context *h = avctx->priv_data;
  7110. MpegEncContext *s = &h->s;
  7111. av_freep(&h->rbsp_buffer[0]);
  7112. av_freep(&h->rbsp_buffer[1]);
  7113. free_tables(h); //FIXME cleanup init stuff perhaps
  7114. MPV_common_end(s);
  7115. // memset(h, 0, sizeof(H264Context));
  7116. return 0;
  7117. }
  7118. AVCodec h264_decoder = {
  7119. "h264",
  7120. CODEC_TYPE_VIDEO,
  7121. CODEC_ID_H264,
  7122. sizeof(H264Context),
  7123. decode_init,
  7124. NULL,
  7125. decode_end,
  7126. decode_frame,
  7127. /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
  7128. .flush= flush_dpb,
  7129. };
  7130. #include "svq3.c"