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.

8057 lines
311KB

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