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.

8020 lines
308KB

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