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.

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