Guest User

Untitled

a guest
Sep 30th, 2011
1,699
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. diff --git common/common.c common/common.c
  2. index 69941de..5769b45 100644
  3. --- common/common.c
  4. +++ common/common.c
  5. @@ -24,6 +24,7 @@
  6.   * For more information, contact us at licensing@x264.com.
  7.   *****************************************************************************/
  8.  
  9. +#include <string.h>
  10.  #include "common.h"
  11.  
  12.  #include <stdarg.h>
  13. @@ -70,6 +71,7 @@ void x264_param_default( x264_param_t *param )
  14.      param->i_slice_max_size = 0;
  15.      param->i_slice_max_mbs = 0;
  16.      param->i_slice_count = 0;
  17. +    param->b_mvc = 0;
  18.  
  19.      /* Encoder parameters */
  20.      param->i_frame_reference = 3;
  21. @@ -137,6 +139,7 @@ void x264_param_default( x264_param_t *param )
  22.      param->analyse.b_chroma_me = 1;
  23.      param->analyse.i_mv_range_thread = -1;
  24.      param->analyse.i_mv_range = -1; // set from level_idc
  25. +    param->analyse.i_original_chroma_qp_offset =
  26.      param->analyse.i_chroma_qp_offset = 0;
  27.      param->analyse.b_fast_pskip = 1;
  28.      param->analyse.b_weighted_bipred = 1;
  29. @@ -545,6 +548,8 @@ int x264_param_parse( x264_param_t *p, const char *name, const char *value )
  30.      int name_was_bool;
  31.      int value_was_null = !value;
  32.      int i;
  33. +    int view = 0;
  34. +    int total_bitrate = 0;
  35.  
  36.      if( !name )
  37.          return X264_PARAM_BAD_NAME;
  38. @@ -825,7 +830,7 @@ int x264_param_parse( x264_param_t *p, const char *name, const char *value )
  39.          p->b_visualize = atobool(value);
  40.  #endif
  41.      OPT("dump-yuv")
  42. -        p->psz_dump_yuv = strdup(value);
  43. +        p->psz_dump_yuv[0] = strdup(value);
  44.      OPT2("analyse", "partitions")
  45.      {
  46.          p->analyse.inter = 0;
  47. @@ -847,7 +852,10 @@ int x264_param_parse( x264_param_t *p, const char *name, const char *value )
  48.      OPT2("direct", "direct-pred")
  49.          b_error |= parse_enum( value, x264_direct_pred_names, &p->analyse.i_direct_mv_pred );
  50.      OPT("chroma-qp-offset")
  51. +    {
  52. +        p->analyse.i_original_chroma_qp_offset =
  53.          p->analyse.i_chroma_qp_offset = atoi(value);
  54. +    }
  55.      OPT("me")
  56.          b_error |= parse_enum( value, x264_motion_est_names, &p->analyse.i_me_method );
  57.      OPT2("merange", "me-range")
  58. @@ -894,8 +902,36 @@ int x264_param_parse( x264_param_t *p, const char *name, const char *value )
  59.          p->analyse.i_noise_reduction = atoi(value);
  60.      OPT("bitrate")
  61.      {
  62. -        p->rc.i_bitrate = atoi(value);
  63. -        p->rc.i_rc_method = X264_RC_ABR;
  64. +        int sub_rate_sum = 0;
  65. +        char *bitrate_buf = (char*)x264_malloc(strlen(value) + 1);
  66. +        char *ptr, *save_ptr;
  67. +        if (!bitrate_buf)
  68. +            b_error |= 1;
  69. +        else {
  70. +            strcpy(bitrate_buf, value);
  71. +            for (ptr = strtok_r(bitrate_buf, ":", &save_ptr); view < MAX_DEP_STREAM + 1 && ptr != NULL; ptr = strtok_r(NULL, ":", &save_ptr)) {
  72. +                if (view == 0) total_bitrate = atoi(ptr);
  73. +                else {
  74. +                    p->rc.i_bitrate_dep[view-1] = atoi(ptr);
  75. +                    sub_rate_sum += p->rc.i_bitrate_dep[view-1];
  76. +                }
  77. +                view++;
  78. +            }
  79. +            x264_free(bitrate_buf);
  80. +            b_error |= sub_rate_sum >= total_bitrate;
  81. +            p->rc.i_bitrate = total_bitrate - sub_rate_sum;
  82. +            p->rc.i_rc_method = X264_RC_ABR;
  83. +
  84. +            if (view > 1) {
  85. +                int total_maxrate = p->rc.i_vbv_max_bitrate;
  86. +                if (total_maxrate > 0) {
  87. +                    p->rc.i_vbv_max_bitrate = (int)((float)total_maxrate * (float)p->rc.i_bitrate / (float)total_bitrate);
  88. +                    for (int view_id = 0; view_id<view-1; view_id++) {
  89. +                        p->rc.i_vbv_max_bitrate_dep[view_id] = (int)((float)total_maxrate * (float)p->rc.i_bitrate_dep[view_id] / (float)total_bitrate);
  90. +                    }
  91. +                }
  92. +            }
  93. +        }
  94.      }
  95.      OPT2("qp", "qp_constant")
  96.      {
  97. @@ -920,7 +956,21 @@ int x264_param_parse( x264_param_t *p, const char *name, const char *value )
  98.      OPT("ratetol")
  99.          p->rc.f_rate_tolerance = !strncmp("inf", value, 3) ? 1e9 : atof(value);
  100.      OPT("vbv-maxrate")
  101. -        p->rc.i_vbv_max_bitrate = atoi(value);
  102. +    {
  103. +        int total_maxrate = atoi(value);
  104. +        int total_rate = p->rc.i_bitrate;
  105. +        for (int view_id = 0; view_id < MAX_DEP_STREAM; view_id++) {
  106. +            total_rate += p->rc.i_bitrate_dep[view_id];
  107. +        }
  108. +        if (total_rate > 0) {
  109. +            p->rc.i_vbv_max_bitrate = (int)((float)total_maxrate * (float)p->rc.i_bitrate / (float)total_rate);
  110. +            for (int view_id = 0; view_id < MAX_DEP_STREAM; view_id++) {
  111. +                p->rc.i_vbv_max_bitrate_dep[view_id] = total_maxrate * p->rc.i_bitrate_dep[view_id] / total_rate;
  112. +            }
  113. +        } else {
  114. +            p->rc.i_vbv_max_bitrate = total_maxrate;
  115. +        }
  116. +    }
  117.      OPT("vbv-bufsize")
  118.          p->rc.i_vbv_buffer_size = atoi(value);
  119.      OPT("vbv-init")
  120. @@ -981,6 +1031,18 @@ int x264_param_parse( x264_param_t *p, const char *name, const char *value )
  121.          p->b_fake_interlaced = atobool(value);
  122.      OPT("frame-packing")
  123.          p->i_frame_packing = atoi(value);
  124. +    OPT("timecode-offset")
  125. +    {
  126. +        int hour, minute, second, frame;
  127. +        int field_num = sscanf(value, "%2d:%2d:%2d:%2d", &hour, &minute, &second, &frame);
  128. +        if (field_num != 4) b_error |= -1;
  129. +        else {
  130. +            p->timecode_offset.hour = hour;
  131. +            p->timecode_offset.minute = minute;
  132. +            p->timecode_offset.second = second;
  133. +            p->timecode_offset.frame = frame;
  134. +        }
  135. +    }
  136.      else
  137.          return X264_PARAM_BAD_NAME;
  138.  #undef OPT
  139. @@ -1100,6 +1162,7 @@ void *x264_malloc( int i_size )
  140.      align_buf = malloc( i_size );
  141.  #elif HAVE_MALLOC_H
  142.      align_buf = memalign( 16, i_size );
  143. +//    x264_log( NULL, X264_LOG_INFO, "memalign : %p\n", align_buf);
  144.  #else
  145.      uint8_t *buf = malloc( i_size + 15 + sizeof(void **) );
  146.      if( buf )
  147. @@ -1192,7 +1255,7 @@ error:
  148.  /****************************************************************************
  149.   * x264_param2string:
  150.   ****************************************************************************/
  151. -char *x264_param2string( x264_param_t *p, int b_res )
  152. +char *x264_param2string( x264_param_t *p, int b_res, int view )
  153.  {
  154.      int len = 1000;
  155.      char *buf, *s;
  156. @@ -1271,7 +1334,7 @@ char *x264_param2string( x264_param_t *p, int b_res )
  157.              s += sprintf( s, " crf=%.1f", p->rc.f_rf_constant );
  158.          else
  159.              s += sprintf( s, " bitrate=%d ratetol=%.1f",
  160. -                          p->rc.i_bitrate, p->rc.f_rate_tolerance );
  161. +                          view == 0 ? p->rc.i_bitrate : p->rc.i_bitrate_dep[view-1], p->rc.f_rate_tolerance );
  162.          s += sprintf( s, " qcomp=%.2f qpmin=%d qpmax=%d qpstep=%d",
  163.                        p->rc.f_qcompress, p->rc.i_qp_min, p->rc.i_qp_max, p->rc.i_qp_step );
  164.          if( p->rc.b_stat_read )
  165. @@ -1280,7 +1343,7 @@ char *x264_param2string( x264_param_t *p, int b_res )
  166.          if( p->rc.i_vbv_buffer_size )
  167.          {
  168.              s += sprintf( s, " vbv_maxrate=%d vbv_bufsize=%d",
  169. -                          p->rc.i_vbv_max_bitrate, p->rc.i_vbv_buffer_size );
  170. +                          view == 0 ? p->rc.i_vbv_max_bitrate : p->rc.i_vbv_max_bitrate_dep[view-1], p->rc.i_vbv_buffer_size );
  171.              if( p->rc.i_rc_method == X264_RC_CRF )
  172.                  s += sprintf( s, " crf_max=%.1f", p->rc.f_rf_constant_max );
  173.          }
  174. @@ -1313,3 +1376,34 @@ char *x264_param2string( x264_param_t *p, int b_res )
  175.      return buf;
  176.  }
  177.  
  178. +
  179. +// Here is utilities to show about encoding frames
  180. +void log_ref_list( x264_t *h )
  181. +{
  182. +#if 0
  183. +    int i, j;
  184. +    static char frame_type_name[] = {
  185. +        'P', 'B', 'I'
  186. +    };
  187. +    static int count = 0;
  188. +    x264_log( h, X264_LOG_INFO, "Start log_ref_list() (called %d time(s)).\n", ++count );
  189. +    if( h->fenc != NULL )
  190. +        x264_log( h, X264_LOG_INFO, "Start log_ref_list(%d ,%c-FRAME).\n", h->fenc->i_frame, frame_type_name[h->sh.i_type] );
  191. +    //if (h->param.b_interlaced == 1) {
  192. +    //    x264_log( h, X264_LOG_INFO, "Interlaced.\n" );
  193. +    //} else {
  194. +    //    x264_log( h, X264_LOG_INFO, "Progressive.\n" );
  195. +    //}
  196. +    for (i = 0; i < 2; ++i) {
  197. +        x264_log( h, X264_LOG_INFO, "i_ref[%d]: %d\n", i, h->i_ref[i] );
  198. +        for (j = 0; j < h->i_ref[i]; ++j) {
  199. +           x264_frame_t *fref = h->fref[i][j];
  200. +           x264_log( h, X264_LOG_INFO, "fref[%d][%d]: %d/%d\n", i, j, fref->i_frame, fref->i_coded );
  201. +        }
  202. +        //x264_log( h, X264_LOG_INFO, "fref_nearest[%d]: %d/%d\n", i, h->fref_nearest[i]->i_frame, h->fref_nearest[i]->i_coded );
  203. +        //x264_log( h, X264_LOG_INFO, "b_ref_reorder[%d]: %d/%d\n", i, h->b_ref_reorder[i], h->b_ref_reorder[i] );
  204. +    }
  205. +    x264_log( h, X264_LOG_INFO, "End log_ref_list().\n\n", i, h->i_ref[i] );
  206. +#endif
  207. +}
  208. +
  209. diff --git common/common.h common/common.h
  210. index f2021b6..cb7446a 100644
  211. --- common/common.h
  212. +++ common/common.h
  213. @@ -27,6 +27,8 @@
  214.  #ifndef X264_COMMON_H
  215.  #define X264_COMMON_H
  216.  
  217. +//#define _DEBUG
  218. +
  219.  /****************************************************************************
  220.   * Macros
  221.   ****************************************************************************/
  222. @@ -81,6 +83,14 @@ do {\
  223.  #define NALU_OVERHEAD 5 // startcode + NAL type costs 5 bytes per frame
  224.  #define FILLER_OVERHEAD (NALU_OVERHEAD+1)
  225.  
  226. +#define MAX_MVC_VIEW 2
  227. +
  228. +#define IS_SLICE_TYPE_P(type)  ((type) % 5 == SLICE_TYPE_P)
  229. +#define IS_SLICE_TYPE_B(type)  ((type) % 5 == SLICE_TYPE_B)
  230. +#define IS_SLICE_TYPE_I(type)  ((type) % 5 == SLICE_TYPE_I)
  231. +#define IS_SLICE_TYPE_SP(type) ((type) % 5 == SLICE_TYPE_SP)
  232. +#define IS_SLICE_TYPE_SI(type) ((type) % 5 == SLICE_TYPE_SI)
  233. +
  234.  /****************************************************************************
  235.   * Includes
  236.   ****************************************************************************/
  237. @@ -198,7 +208,7 @@ int64_t x264_mdate( void );
  238.  
  239.  /* x264_param2string: return a (malloced) string containing most of
  240.   * the encoding options */
  241. -char *x264_param2string( x264_param_t *p, int b_res );
  242. +char *x264_param2string( x264_param_t *p, int b_res, int view );
  243.  
  244.  /* log */
  245.  void x264_log( x264_t *h, int i_level, const char *psz_fmt, ... );
  246. @@ -297,6 +307,8 @@ enum slice_type_e
  247.      SLICE_TYPE_P  = 0,
  248.      SLICE_TYPE_B  = 1,
  249.      SLICE_TYPE_I  = 2,
  250. +    SLICE_TYPE_SP = 3,
  251. +    SLICE_TYPE_SI = 4,
  252.  };
  253.  
  254.  static const char slice_type_to_char[] = { 'P', 'B', 'I' };
  255. @@ -318,7 +330,11 @@ typedef struct
  256.      x264_sps_t *sps;
  257.      x264_pps_t *pps;
  258.  
  259. +    x264_sps_t *subset_sps;
  260. +    x264_pps_t *subset_pps;
  261. +
  262.      int i_type;
  263. +    int b_anchor;
  264.      int i_first_mb;
  265.      int i_last_mb;
  266.  
  267. @@ -349,7 +365,7 @@ typedef struct
  268.      {
  269.          int idc;
  270.          int arg;
  271. -    } ref_pic_list_order[2][X264_REF_MAX];
  272. +    } ref_pic_list_order[2][X264_REF_MAX + 1]; /* "+ 1" is for inter-view prediction. */
  273.  
  274.      /* P-frame weighting */
  275.      x264_weight_t weight[X264_REF_MAX*2][3];
  276. @@ -374,6 +390,15 @@ typedef struct
  277.      int i_alpha_c0_offset;
  278.      int i_beta_offset;
  279.  
  280. +    /* MVC slice layer extension */
  281. +    int b_svc_extension_flag;
  282. +    int b_non_idr_flag;
  283. +    int i_priority_id;
  284. +    int i_view_id;
  285. +    int i_temporal_id;
  286. +    int b_anchor_pic_flag;
  287. +    int b_inter_view_flag;
  288. +    int b_reserved_one_bit;
  289.  } x264_slice_header_t;
  290.  
  291.  typedef struct x264_lookahead_t
  292. @@ -384,9 +409,11 @@ typedef struct x264_lookahead_t
  293.      int                           i_last_keyframe;
  294.      int                           i_slicetype_length;
  295.      x264_frame_t                  *last_nonb;
  296. +    x264_frame_t                  *last_nonb_dependent;
  297.      x264_pthread_t                thread_handle;
  298.      x264_sync_frame_list_t        ifbuf;
  299.      x264_sync_frame_list_t        next;
  300. +    x264_sync_frame_list_t        next_dependent;
  301.      x264_sync_frame_list_t        ofbuf;
  302.  } x264_lookahead_t;
  303.  
  304. @@ -421,11 +448,20 @@ struct x264_t
  305.      x264_sps_t      *sps;
  306.      x264_pps_t      *pps;
  307.  
  308. +    x264_sps_t *subset_sps;
  309. +    x264_pps_t *subset_pps;
  310. +
  311. +    int64_t         offset_frame; /* start frame calculated from x264_param_t::timecode_offset */
  312. +
  313.      /**** thread synchronization starts here ****/
  314.  
  315.      /* frame number/poc */
  316.      int             i_frame;
  317.      int             i_frame_num;
  318. +    
  319. +    int             b_once_buffer_filled;
  320. +    
  321. +    int             b_dependent;
  322.  
  323.      int             i_thread_frames; /* Number of different frames being encoded by threads;
  324.                                        * 1 when sliced-threads is on. */
  325. @@ -442,18 +478,22 @@ struct x264_t
  326.      int64_t         i_cpb_delay_lookahead;
  327.  
  328.      int64_t         i_cpb_delay_pir_offset;
  329. +    int64_t         i_cpb_delay_pir_offset_dep;
  330.  
  331.      int             b_queued_intra_refresh;
  332.      int64_t         i_last_idr_pts;
  333. +    int             i_last_idr_frame;
  334.  
  335.      /* We use only one SPS and one PPS */
  336. -    x264_sps_t      sps_array[1];
  337. -    x264_pps_t      pps_array[1];
  338. +    x264_sps_t      sps_array[2];
  339. +    x264_pps_t      pps_array[2];
  340.      int             i_idr_pic_id;
  341.  
  342.      /* quantization matrix for decoding, [cqm][qp%6][coef] */
  343. -    int             (*dequant4_mf[4])[16];   /* [4][6][16] */
  344. -    int             (*dequant8_mf[2])[64];   /* [2][6][64] */
  345. +    //int             (*dequant4_mf[4])[16];   /* [4][6][16] */
  346. +    //int             (*dequant8_mf[2])[64];   /* [2][6][64] */
  347. +    int             dequant4_mf[4][6][16];
  348. +    int             dequant8_mf[2][6][64];
  349.      /* quantization matrix for trellis, [cqm][qp][coef] */
  350.      int             (*unquant4_mf[4])[16];   /* [4][52][16] */
  351.      int             (*unquant8_mf[2])[64];   /* [2][52][64] */
  352. @@ -487,7 +527,7 @@ struct x264_t
  353.          x264_frame_t **blank_unused;
  354.  
  355.          /* frames used for reference + sentinels */
  356. -        x264_frame_t *reference[X264_REF_MAX+2];
  357. +        x264_frame_t *reference[(X264_REF_MAX*2)+3];
  358.  
  359.          int i_last_keyframe;       /* Frame number of the last keyframe */
  360.          int i_last_idr;            /* Frame number of the last IDR (not RP)*/
  361. @@ -526,6 +566,8 @@ struct x264_t
  362.      /* hrd */
  363.      int initial_cpb_removal_delay;
  364.      int initial_cpb_removal_delay_offset;
  365. +    int initial_cpb_removal_delay_dep;
  366. +    int initial_cpb_removal_delay_offset_dep;
  367.      int64_t i_reordered_pts_delay;
  368.  
  369.      /* Current MB DCT coeffs */
  370. @@ -754,6 +796,7 @@ struct x264_t
  371.  
  372.      /* rate control encoding only */
  373.      x264_ratecontrol_t *rc;
  374. +    x264_ratecontrol_t *rc_mvc[1+MAX_DEP_STREAM];
  375.  
  376.      /* stats */
  377.      struct
  378. @@ -812,6 +855,10 @@ struct x264_t
  379.          /* num p-frames weighted */
  380.          int     i_wpred[2];
  381.  
  382. +        /* for MVC rc */
  383. +        int     i_frame_dep_count[3];
  384. +        int64_t i_frame_dep_size[3];
  385. +        double  f_frame_dep_qp[3];
  386.      } stat;
  387.  
  388.      /* 0 = luma 4x4, 1 = luma 8x8, 2 = chroma 4x4 */
  389. @@ -857,5 +904,8 @@ struct x264_t
  390.  #include "x86/util.h"
  391.  #endif
  392.  
  393. +// Here is utilities to learn x264. Do not commit this source.
  394. +void log_ref_list( x264_t * );
  395. +
  396.  #endif
  397.  
  398. diff --git common/frame.h common/frame.h
  399. index 38d0bf2..7dbe566 100644
  400. --- common/frame.h
  401. +++ common/frame.h
  402. @@ -38,6 +38,7 @@ typedef struct x264_frame
  403.      int     i_poc;
  404.      int     i_delta_poc[2];
  405.      int     i_type;
  406. +    int     i_last_type; /* save last type of base view for MVC */
  407.      int     i_qpplus1;
  408.      int64_t i_pts;
  409.      int64_t i_dts;
  410. @@ -156,6 +157,10 @@ typedef struct x264_frame
  411.  
  412.      /* user sei */
  413.      x264_sei_t extra_sei;
  414. +
  415. +    /* for MVV */
  416. +    int is_dependent;
  417. +    int b_inter_view_only;
  418.  } x264_frame_t;
  419.  
  420.  /* synchronized frame list */
  421. diff --git common/macroblock.c common/macroblock.c
  422. index 24c2af9..f1777da 100644
  423. --- common/macroblock.c
  424. +++ common/macroblock.c
  425. @@ -236,7 +236,7 @@ int x264_macroblock_cache_allocate( x264_t *h )
  426.  
  427.      for( int i = 0; i < 2; i++ )
  428.      {
  429. -        int i_refs = X264_MIN(X264_REF_MAX, (i ? 1 + !!h->param.i_bframe_pyramid : h->param.i_frame_reference) ) << h->param.b_interlaced;
  430. +        int i_refs = X264_MIN(X264_REF_MAX, (i ? 1 + !!h->param.i_bframe_pyramid : h->param.i_frame_reference + h->param.b_mvc) ) << h->param.b_interlaced;
  431.          if( h->param.analyse.i_weighted_pred == X264_WEIGHTP_SMART )
  432.              i_refs = X264_MIN(X264_REF_MAX, i_refs + 1 + (BIT_DEPTH == 8)); //smart weights add two duplicate frames, one in >8-bit
  433.  
  434. diff --git common/quant.c common/quant.c
  435. index 8ae20a0..1078c09 100644
  436. --- common/quant.c
  437. +++ common/quant.c
  438. @@ -439,11 +439,13 @@ void x264_quant_init( x264_t *h, int cpu, x264_quant_function_t *pf )
  439.          pf->dequant_4x4 = x264_dequant_4x4_mmx;
  440.          pf->dequant_4x4_dc = x264_dequant_4x4dc_mmxext;
  441.          pf->dequant_8x8 = x264_dequant_8x8_mmx;
  442. +#ifdef ENABLE_FAST_QUANT
  443.          if( h->param.i_cqm_preset == X264_CQM_FLAT )
  444.          {
  445.              pf->dequant_4x4 = x264_dequant_4x4_flat16_mmx;
  446.              pf->dequant_8x8 = x264_dequant_8x8_flat16_mmx;
  447.          }
  448. +#endif
  449.          pf->denoise_dct = x264_denoise_dct_mmx;
  450.  #endif
  451.      }
  452. @@ -484,11 +486,13 @@ void x264_quant_init( x264_t *h, int cpu, x264_quant_function_t *pf )
  453.          pf->dequant_4x4 = x264_dequant_4x4_sse2;
  454.          pf->dequant_4x4_dc = x264_dequant_4x4dc_sse2;
  455.          pf->dequant_8x8 = x264_dequant_8x8_sse2;
  456. +#ifdef ENABLE_FAST_QUANT
  457.          if( h->param.i_cqm_preset == X264_CQM_FLAT )
  458.          {
  459.              pf->dequant_4x4 = x264_dequant_4x4_flat16_sse2;
  460.              pf->dequant_8x8 = x264_dequant_8x8_flat16_sse2;
  461.          }
  462. +#endif
  463.          pf->optimize_chroma_dc = x264_optimize_chroma_dc_sse2;
  464.          pf->denoise_dct = x264_denoise_dct_sse2;
  465.          pf->decimate_score15 = x264_decimate_score15_sse2;
  466. diff --git common/set.c common/set.c
  467. index f8f6a11..b2a6a2b 100644
  468. --- common/set.c
  469. +++ common/set.c
  470. @@ -93,27 +93,31 @@ int x264_cqm_init( x264_t *h )
  471.          for( j = (i<4 ? 0 : 4); j < i; j++ )
  472.              if( !memcmp( h->pps->scaling_list[i], h->pps->scaling_list[j], size*sizeof(uint8_t) ) )
  473.                  break;
  474. -        if( j < i )
  475. +        if( 0 ) // all parameters have to be different to change matrix while encoding.
  476.          {
  477.              h->  quant4_mf[i] = h->  quant4_mf[j];
  478. -            h->dequant4_mf[i] = h->dequant4_mf[j];
  479. +            //h->dequant4_mf[i] = h->dequant4_mf[j];
  480.              h->unquant4_mf[i] = h->unquant4_mf[j];
  481.          }
  482.          else
  483.          {
  484. -            CHECKED_MALLOC( h->  quant4_mf[i], (QP_MAX+1)*size*sizeof(udctcoef) );
  485. -            CHECKED_MALLOC( h->dequant4_mf[i],  6*size*sizeof(int) );
  486. -            CHECKED_MALLOC( h->unquant4_mf[i], (QP_MAX+1)*size*sizeof(int) );
  487. +            if (!h->  quant4_mf[i])
  488. +                CHECKED_MALLOC( h->  quant4_mf[i], (QP_MAX+1)*size*sizeof(udctcoef) );
  489. +            //if (!h->dequant4_mf[i])
  490. +            //    CHECKED_MALLOC( h->dequant4_mf[i],  6*size*sizeof(int) );
  491. +            if (!h->unquant4_mf[i])
  492. +                CHECKED_MALLOC( h->unquant4_mf[i], (QP_MAX+1)*size*sizeof(int) );
  493.          }
  494.  
  495.          for( j = (i<4 ? 0 : 4); j < i; j++ )
  496.              if( deadzone[j&3] == deadzone[i&3] &&
  497.                  !memcmp( h->pps->scaling_list[i], h->pps->scaling_list[j], size*sizeof(uint8_t) ) )
  498.                  break;
  499. -        if( j < i )
  500. +        if(0) // all parameters have to be different to change matrix while encoding.
  501.              h->quant4_bias[i] = h->quant4_bias[j];
  502.          else
  503. -            CHECKED_MALLOC( h->quant4_bias[i], (QP_MAX+1)*size*sizeof(udctcoef) );
  504. +            if (!h->quant4_bias[i])
  505. +                CHECKED_MALLOC( h->quant4_bias[i], (QP_MAX+1)*size*sizeof(udctcoef) );
  506.      }
  507.  
  508.      for( int q = 0; q < 6; q++ )
  509. @@ -188,7 +192,8 @@ int x264_cqm_init( x264_t *h )
  510.  
  511.      /* Emergency mode denoising. */
  512.      x264_emms();
  513. -    CHECKED_MALLOC( h->nr_offset_emergency, sizeof(*h->nr_offset_emergency)*(QP_MAX-QP_MAX_SPEC) );
  514. +    if (!h->nr_offset_emergency)
  515. +        CHECKED_MALLOC( h->nr_offset_emergency, sizeof(*h->nr_offset_emergency)*(QP_MAX-QP_MAX_SPEC) );
  516.      for( int q = 0; q < QP_MAX - QP_MAX_SPEC; q++ )
  517.          for( int cat = 0; cat <= 2; cat++ )
  518.          {
  519. @@ -262,7 +267,7 @@ fail:
  520.          if( j == i )\
  521.          {\
  522.              x264_free( h->  quant##n##_mf[i] );\
  523. -            x264_free( h->dequant##n##_mf[i] );\
  524. +            /*x264_free( h->dequant##n##_mf[i] );*/\
  525.              x264_free( h->unquant##n##_mf[i] );\
  526.          }\
  527.          for( j = 0; j < i; j++ )\
  528. diff --git common/set.h common/set.h
  529. index fb81c1a..b94c546 100644
  530. --- common/set.h
  531. +++ common/set.h
  532. @@ -35,6 +35,7 @@ enum profile_e
  533.      PROFILE_HIGH    = 100,
  534.      PROFILE_HIGH10  = 110,
  535.      PROFILE_HIGH422 = 122,
  536. +    PROFILE_STEREO_HIGH = 128,
  537.      PROFILE_HIGH444 = 144,
  538.      PROFILE_HIGH444_PREDICTIVE = 244,
  539.  };
  540. diff --git encoder/analyse.c encoder/analyse.c
  541. index 29597eb..eb09e6f 100644
  542. --- encoder/analyse.c
  543. +++ encoder/analyse.c
  544. @@ -3576,6 +3576,7 @@ static void x264_analyse_update_cache( x264_t *h, x264_mb_analysis_t *a  )
  545.  
  546.                  default:
  547.                      x264_log( h, X264_LOG_ERROR, "internal error P_L0 and partition=%d\n", h->mb.i_partition );
  548. +           //        exit(1);
  549.                      break;
  550.              }
  551.              break;
  552. diff --git encoder/encoder.c encoder/encoder.c
  553. index d42ca31..7460c96 100644
  554. --- encoder/encoder.c
  555. +++ encoder/encoder.c
  556. @@ -37,11 +37,13 @@
  557.  #include "common/visualize.h"
  558.  #endif
  559.  
  560. +//#define __DEBUG
  561.  //#define DEBUG_MB_TYPE
  562.  
  563.  #define bs_write_ue bs_write_ue_big
  564.  
  565.  static int x264_encoder_frame_end( x264_t *h, x264_t *thread_current,
  566. +                                   x264_t *thread_next,
  567.                                     x264_nal_t **pp_nal, int *pi_nal,
  568.                                     x264_picture_t *pic_out );
  569.  
  570. @@ -66,11 +68,23 @@ static double x264_ssim( double ssim )
  571.  
  572.  static void x264_frame_dump( x264_t *h )
  573.  {
  574. -    FILE *f = fopen( h->param.psz_dump_yuv, "r+b" );
  575. +    int view_id;
  576. +    char *name;
  577. +    if( h->param.b_mvc && (h->fdec->i_frame % 2) )
  578. +        view_id = 1;
  579. +    else
  580. +        view_id = 0;
  581. +    
  582. +    FILE *f = fopen( h->param.psz_dump_yuv[view_id], "r+b" );
  583.      if( !f )
  584. +    {
  585. +        x264_log(h, X264_LOG_ERROR, "Failed to open %s\n", h->param.psz_dump_yuv[view_id]);
  586.          return;
  587. +    }
  588. +
  589.      /* Write the frame in display order */
  590. -    fseek( f, (uint64_t)h->fdec->i_frame * h->param.i_height * h->param.i_width * 3/2 * sizeof(pixel), SEEK_SET );
  591. +    uint64_t offset = ((uint64_t)h->fdec->i_frame / ( h->param.b_mvc + 1 )) * h->param.i_height * h->param.i_width * 3/2 * sizeof(pixel);
  592. +    fseek( f, offset, SEEK_SET );
  593.      for( int y = 0; y < h->param.i_height; y++ )
  594.          fwrite( &h->fdec->plane[0][y*h->fdec->i_stride[0]], sizeof(pixel), h->param.i_width, f );
  595.      int cw = h->param.i_width>>1;
  596. @@ -84,6 +98,32 @@ static void x264_frame_dump( x264_t *h )
  597.      fclose( f );
  598.  }
  599.  
  600. +/* Fill ref_pic_list_reordering and ref_pic_list_order field in slice header. */
  601. +static void create_reordering_inst( x264_t *h, x264_slice_header_t *sh, int list, int pred_frame_num )
  602. +{
  603. +    sh->b_ref_pic_list_reordering[list] = 1;
  604. +    //printf("    RefPicListL%d of the frame %d (frame_num=%d) is\n", list, h->i_frame, h->i_frame_num);
  605. +    for( int i = 0; i < h->i_ref[list]; i++ )
  606. +    {
  607. +        if( !h->b_dependent || h->fref[list][i]->i_frame_num != sh->i_frame_num )
  608. +        {
  609. +            //printf("    h->fref[%d][%d]->i_frame=%d (frame_num=%d) (intra view)\n", list, i, h->fref[list][i]->i_frame, h->fref[list][i]->i_frame_num);
  610. +            int diff = h->fref[list][i]->i_frame_num - pred_frame_num;
  611. +            //printf("    Order inst: idc=%d, arg=%d\n", ( diff > 0 ), (abs(diff) - 1) & ((1 << sh->sps->i_log2_max_frame_num) - 1));
  612. +            sh->ref_pic_list_order[list][i].idc = ( diff > 0 );
  613. +            sh->ref_pic_list_order[list][i].arg = (abs(diff) - 1) & ((1 << sh->sps->i_log2_max_frame_num) - 1);
  614. +            pred_frame_num = h->fref[list][i]->i_frame_num;
  615. +        }
  616. +        else
  617. +        {
  618. +            //printf("    h->fref[%d][%d]->i_frame=%d (frame_num=%d) (inter view)\n", list, i, h->fref[list][i]->i_frame, h->fref[list][i]->i_frame_num);
  619. +            //printf("    Order inst: idc=%d, arg=%d\n", 5, 0);
  620. +            sh->b_ref_pic_list_reordering[list] = 1;
  621. +            sh->ref_pic_list_order[list][i].idc = 5;
  622. +            sh->ref_pic_list_order[list][i].arg = 0;
  623. +        }
  624. +    }
  625. +}
  626.  
  627.  /* Fill "default" values */
  628.  static void x264_slice_header_init( x264_t *h, x264_slice_header_t *sh,
  629. @@ -92,15 +132,27 @@ static void x264_slice_header_init( x264_t *h, x264_slice_header_t *sh,
  630.  {
  631.      x264_param_t *param = &h->param;
  632.  
  633. +    int is_mvc = param->b_mvc;
  634. +    
  635.      /* First we fill all fields */
  636.      sh->sps = sps;
  637.      sh->pps = pps;
  638.  
  639. +    // for MVC slice header extension
  640. +    sh->b_svc_extension_flag = 0;
  641. +    sh->b_non_idr_flag = (i_idr_pic_id < 0);
  642. +    sh->i_priority_id = 0;
  643. +    sh->i_view_id = h->b_dependent;
  644. +    sh->i_temporal_id = 0;
  645. +    sh->b_anchor_pic_flag = (i_idr_pic_id < 0) ? 0 : 1;
  646. +    sh->b_inter_view_flag = 0;
  647. +    sh->b_reserved_one_bit = 1;
  648. +
  649.      sh->i_first_mb  = 0;
  650.      sh->i_last_mb   = h->mb.i_mb_count - 1;
  651.      sh->i_pps_id    = pps->i_id;
  652.  
  653. -    sh->i_frame_num = i_frame;
  654. +    sh->i_frame_num = is_mvc ? i_frame / 2 : i_frame;
  655.  
  656.      sh->b_mbaff = h->param.b_interlaced;
  657.      sh->b_field_pic = 0;    /* no field support for now */
  658. @@ -141,21 +193,42 @@ static void x264_slice_header_init( x264_t *h, x264_slice_header_t *sh,
  659.      sh->i_num_ref_idx_l0_active = 1;
  660.      sh->i_num_ref_idx_l1_active = 1;
  661.  
  662. -    sh->b_ref_pic_list_reordering[0] = h->b_ref_reorder[0];
  663. -    sh->b_ref_pic_list_reordering[1] = h->b_ref_reorder[1];
  664. +    sh->b_ref_pic_list_reordering[0] = 0;//h->b_ref_reorder[0];
  665. +    sh->b_ref_pic_list_reordering[1] = 0;//h->b_ref_reorder[1];
  666.  
  667. +    //printf("\nEncoding frame %d. (idr_pic_id=%d frame_num=%d type=%d)\n", h->i_frame, sh->i_idr_pic_id, sh->i_frame_num, h->fenc->i_type);
  668. +    //if( h->sps != sps ) printf("    This frame has a subset sps/pps.\n");
  669. +    //if( sh->b_non_idr_flag && h->b_dependent ) printf("    This frame is not IDR.\n");
  670. +    
  671.      /* If the ref list isn't in the default order, construct reordering header */
  672.      for( int list = 0; list < 2; list++ )
  673.      {
  674.          if( sh->b_ref_pic_list_reordering[list] )
  675.          {
  676. -            int pred_frame_num = i_frame;
  677. +            create_reordering_inst( h, sh, list, i_frame );
  678. +        }
  679. +        else if( h->b_dependent )
  680. +        {
  681. +            for( int i = 0; i < h->i_ref[list]; i++ )
  682. +                if( h->fref[list][i]->i_frame_num == sh->i_frame_num )
  683. +                {
  684. +                     create_reordering_inst( h, sh, list, i_frame / 2 );
  685. +                     break;
  686. +                }
  687. +        }
  688. +        else
  689. +        {
  690. +            //printf("    RefPicListL%d (with no reordering) of the frame %d is\n", list, h->i_frame);
  691.              for( int i = 0; i < h->i_ref[list]; i++ )
  692.              {
  693. -                int diff = h->fref[list][i]->i_frame_num - pred_frame_num;
  694. -                sh->ref_pic_list_order[list][i].idc = ( diff > 0 );
  695. -                sh->ref_pic_list_order[list][i].arg = (abs(diff) - 1) & ((1 << sps->i_log2_max_frame_num) - 1);
  696. -                pred_frame_num = h->fref[list][i]->i_frame_num;
  697. +                if( !h->b_dependent || h->fref[list][i]->i_frame_num != h->i_frame_num - 1 )
  698. +                {
  699. +                    //printf("    h->fref[list][i]->i_frame=%d (intra view)\n", h->fref[list][i]->i_frame);
  700. +                }
  701. +                else
  702. +                {
  703. +                    //printf("    h->fref[list][i]->i_frame=%d (inter view)\n", h->fref[list][i]->i_frame);
  704. +                }
  705.              }
  706.          }
  707.      }
  708. @@ -177,8 +250,19 @@ static void x264_slice_header_init( x264_t *h, x264_slice_header_t *sh,
  709.      sh->i_beta_offset = param->i_deblocking_filter_beta << 1;
  710.  }
  711.  
  712. -static void x264_slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal_ref_idc )
  713. +static void x264_slice_header_write(x264_t *h,  bs_t *s, x264_slice_header_t *sh, int i_nal_ref_idc )
  714.  {
  715. +    if (sh->b_svc_extension_flag) { // write svc_extension_flag and nal_unit_header_mvc_extension()
  716. +      bs_write1( s, 0 ); // svc_extension_flag -> mvc
  717. +      bs_write1( s, sh->b_non_idr_flag );
  718. +      bs_write( s, 6, sh->i_priority_id );
  719. +      bs_write( s, 10, sh->i_view_id );
  720. +      bs_write( s, 3, sh->i_temporal_id );
  721. +      bs_write1( s, sh->b_anchor_pic_flag );
  722. +      bs_write1( s, sh->b_inter_view_flag );
  723. +      bs_write1( s, sh->b_reserved_one_bit );
  724. +    }
  725. +
  726.      if( sh->b_mbaff )
  727.      {
  728.          assert( sh->i_first_mb % (2*sh->sps->i_mb_width) == 0 );
  729. @@ -188,7 +272,13 @@ static void x264_slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal
  730.          bs_write_ue( s, sh->i_first_mb );
  731.  
  732.      bs_write_ue( s, sh->i_type + 5 );   /* same type things */
  733. -    bs_write_ue( s, sh->i_pps_id );
  734. +
  735. +    if (!sh->b_svc_extension_flag) {
  736. +      bs_write_ue( s, sh->i_pps_id );
  737. +    } else { // for MVC dependent view
  738. +      bs_write_ue( s, 1 );
  739. +    }
  740. +
  741.      bs_write( s, sh->sps->i_log2_max_frame_num, sh->i_frame_num & ((1<<sh->sps->i_log2_max_frame_num)-1) );
  742.  
  743.      if( !sh->sps->b_frame_mbs_only )
  744. @@ -199,11 +289,22 @@ static void x264_slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal
  745.      }
  746.  
  747.      if( sh->i_idr_pic_id >= 0 ) /* NAL IDR */
  748. +    {
  749.          bs_write_ue( s, sh->i_idr_pic_id );
  750. +    }
  751.  
  752. -    if( sh->sps->i_poc_type == 0 )
  753. +    if( sh->sps->i_poc_type == 0 ) // always 0
  754.      {
  755. +      if (!h->param.b_mvc) {
  756.          bs_write( s, sh->sps->i_log2_max_poc_lsb, sh->i_poc & ((1<<sh->sps->i_log2_max_poc_lsb)-1) );
  757. +      } else { // mvc case
  758. +   //if (!sh->b_svc_extension_flag) { // base view
  759. +     bs_write( s, sh->sps->i_log2_max_poc_lsb, (sh->i_poc & ((1<<sh->sps->i_log2_max_poc_lsb)-1)) >> 1 );
  760. +   //} else { // dependent view
  761. +   //  bs_write( s, sh->sps->i_log2_max_poc_lsb, (sh->i_poc & (((1<<sh->sps->i_log2_max_poc_lsb)-1)) - 2) >> 1);
  762. +   //}
  763. +      }
  764. +
  765.          if( sh->pps->b_pic_order && !sh->b_field_pic )
  766.              bs_write_se( s, sh->i_delta_poc_bottom );
  767.      }
  768. @@ -220,7 +321,7 @@ static void x264_slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal
  769.      if( sh->i_type == SLICE_TYPE_B )
  770.          bs_write1( s, sh->b_direct_spatial_mv_pred );
  771.  
  772. -    if( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_B )
  773. +    if( IS_SLICE_TYPE_P(sh->i_type) || IS_SLICE_TYPE_B(sh->i_type) )
  774.      {
  775.          bs_write1( s, sh->b_num_ref_idx_override );
  776.          if( sh->b_num_ref_idx_override )
  777. @@ -232,20 +333,22 @@ static void x264_slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal
  778.      }
  779.  
  780.      /* ref pic list reordering */
  781. -    if( sh->i_type != SLICE_TYPE_I )
  782. +    if( !IS_SLICE_TYPE_I(sh->i_type) )
  783.      {
  784.          bs_write1( s, sh->b_ref_pic_list_reordering[0] );
  785.          if( sh->b_ref_pic_list_reordering[0] )
  786.          {
  787. +           //printf("Reordering %d frame(s).\n", sh->i_num_ref_idx_l0_active);
  788.              for( int i = 0; i < sh->i_num_ref_idx_l0_active; i++ )
  789.              {
  790. +                //printf("Write command idc=%d, arg=%d\n", sh->ref_pic_list_order[0][i].idc, sh->ref_pic_list_order[0][i].arg );
  791.                  bs_write_ue( s, sh->ref_pic_list_order[0][i].idc );
  792.                  bs_write_ue( s, sh->ref_pic_list_order[0][i].arg );
  793.              }
  794.              bs_write_ue( s, 3 );
  795.          }
  796.      }
  797. -    if( sh->i_type == SLICE_TYPE_B )
  798. +    if( IS_SLICE_TYPE_B(sh->i_type) )
  799.      {
  800.          bs_write1( s, sh->b_ref_pic_list_reordering[1] );
  801.          if( sh->b_ref_pic_list_reordering[1] )
  802. @@ -259,6 +362,55 @@ static void x264_slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal
  803.          }
  804.      }
  805.  
  806. +    /* FIXME! most be parameterized */
  807. +    int ref_pic_list_modification_flag_l0 = 1; // always 1
  808. +    int ref_pic_list_modification_flag_l1 = 0; // always 0?
  809. +    int num_modification_of_pic_nums_idc = 4; // num of nums idc
  810. +    
  811. +    int modification_of_pic_nums_idc[4] = { 0, 3, 3, 3 };
  812. +
  813. +    int abs_diff_pic_num_minus1 = 1;
  814. +    int abs_diff_view_idx_minus1 = 1;
  815. +
  816. +    // for MVC ref_pic_list_mvc_modification()
  817. +#if 0
  818. +    if (sh->b_svc_extension_flag) {
  819. +      if ((sh->i_type % 5 != 2) && (sh->i_type % 5 != 4)) { /* if type is neither I nor SI */
  820. +   // ref_pic_list_modification_flag_l0
  821. +   bs_write1( s, ref_pic_list_modification_flag_l0);
  822. +
  823. +   if (ref_pic_list_modification_flag_l0) {
  824. +     for (int i = 0; i < num_modification_of_pic_nums_idc; i++) {
  825. +       // modification_of_pic_nums_idc_l0
  826. +       bs_write_ue( s, modification_of_pic_nums_idc[i] );
  827. +      
  828. +       if ((modification_of_pic_nums_idc[i] == 0) || (modification_of_pic_nums_idc[i] == 1)) {
  829. +         // abs_diff_pic_num_minus1
  830. +         bs_write_ue( s, abs_diff_pic_num_minus1 );
  831. +       } else if (modification_of_pic_nums_idc[i] == 2) {
  832. +         // long_term_pic_num
  833. +         bs_write_ue( s, 0 ); // maybe not used
  834. +       } else if ((modification_of_pic_nums_idc[i] == 4) || (modification_of_pic_nums_idc[i] == 5)) {
  835. +         // abs_diff_view_idx_minus1
  836. +         bs_write_ue( s, abs_diff_view_idx_minus1 );
  837. +       } else if (modification_of_pic_nums_idc[i] == 3) {
  838. +         break;
  839. +       }
  840. +       // modification_of_pic_nums_idc_l0
  841. +     }
  842. +   }
  843. +      }
  844. +
  845. +      if (sh->i_type % 5 == 1) { /* if type is B */
  846. +   // ref_pic_list_modification_flag_l1
  847. +   bs_write1( s, ref_pic_list_modification_flag_l1);
  848. +   if (ref_pic_list_modification_flag_l1) { // always 0
  849. +     // none
  850. +   }
  851. +      }
  852. +    }
  853. +#endif
  854. +
  855.      if( sh->pps->b_weighted_pred && sh->i_type == SLICE_TYPE_P )
  856.      {
  857.          /* pred_weight_table() */
  858. @@ -517,7 +669,7 @@ static int x264_validate_parameters( x264_t *h )
  859.          h->param.rc.f_pb_factor = 1;
  860.          h->param.analyse.b_psnr = 0;
  861.          h->param.analyse.b_ssim = 0;
  862. -        h->param.analyse.i_chroma_qp_offset = 0;
  863. +        h->param.analyse.i_original_chroma_qp_offset = 0;
  864.          h->param.analyse.i_trellis = 0;
  865.          h->param.analyse.b_fast_pskip = 0;
  866.          h->param.analyse.i_noise_reduction = 0;
  867. @@ -563,7 +715,7 @@ static int x264_validate_parameters( x264_t *h )
  868.          else if( h->param.rc.i_vbv_max_bitrate < h->param.rc.i_bitrate &&
  869.                   h->param.rc.i_rc_method == X264_RC_ABR )
  870.          {
  871. -            x264_log( h, X264_LOG_WARNING, "max bitrate less than average bitrate, assuming CBR\n" );
  872. +            x264_log( h, X264_LOG_WARNING, "max bitrate(%d) less than average bitrate(%d), assuming CBR\n", h->param.rc.i_vbv_max_bitrate, h->param.rc.i_bitrate );
  873.              h->param.rc.i_vbv_max_bitrate = h->param.rc.i_bitrate;
  874.          }
  875.      }
  876. @@ -703,7 +855,7 @@ static int x264_validate_parameters( x264_t *h )
  877.          h->param.analyse.inter &= ~X264_ANALYSE_I8x8;
  878.          h->param.analyse.intra &= ~X264_ANALYSE_I8x8;
  879.      }
  880. -    h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -12, 12);
  881. +    h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_original_chroma_qp_offset, -12, 12);
  882.      h->param.analyse.i_trellis = x264_clip3( h->param.analyse.i_trellis, 0, 2 );
  883.      if( !h->param.analyse.b_psy )
  884.      {
  885. @@ -827,6 +979,17 @@ static int x264_validate_parameters( x264_t *h )
  886.          h->param.i_nal_hrd = X264_NAL_HRD_VBR;
  887.      }
  888.  
  889. +    /* timecode offset */
  890. +    if (h->param.timecode_offset.frame < 0 || h->param.timecode_offset.frame >= (int)(fps+0.5f)) h->param.timecode_offset.frame = 0;
  891. +    if (h->param.timecode_offset.second < 0 || h->param.timecode_offset.second > 59) h->param.timecode_offset.second = 0;
  892. +    if (h->param.timecode_offset.minute < 0 || h->param.timecode_offset.minute > 59) h->param.timecode_offset.minute = 0;
  893. +    if (h->param.timecode_offset.hour < 0 || h->param.timecode_offset.hour > 23) h->param.timecode_offset.hour = 0;
  894. +    if (h->param.i_fps_den == 1001 &&
  895. +        h->param.timecode_offset.b_drop &&
  896. +        h->param.timecode_offset.frame < 2 &&
  897. +        h->param.timecode_offset.second == 0 &&
  898. +        (h->param.timecode_offset.minute % 10)) h->param.timecode_offset.frame = 2;
  899. +    
  900.      /* ensure the booleans are 0 or 1 so they can be used in math */
  901.  #define BOOLIFY(x) h->param.x = !!h->param.x
  902.      BOOLIFY( b_cabac );
  903. @@ -912,6 +1075,28 @@ static void x264_set_aspect_ratio( x264_t *h, x264_param_t *param, int initial )
  904.      }
  905.  }
  906.  
  907. +static int64_t calculate_frame_from_timecode( uint32_t num, uint32_t denom, struct timecode time)
  908. +{
  909. +    int64_t frame, second, minute;
  910. +    if (denom == 0) return 0;
  911. +    minute = (time.hour * 60) + time.minute;
  912. +    second = minute * 60 + time.second;
  913. +    if (denom == 1001) {
  914. +        frame = second * num / 1000;
  915. +        if (time.b_drop) {
  916. +            // drop frame is only effective at 30000/1001
  917. +            int64_t minute10 =  minute / 10;
  918. +            int64_t drop_count = (minute - minute10) * 2; /* drop 2frames each minute, except each 10 minutes. */
  919. +            frame -= drop_count;
  920. +        }
  921. +    } else {
  922. +        frame = second * num / denom;
  923. +    }
  924. +    frame += time.frame;
  925. +
  926. +    return frame;
  927. +}
  928. +
  929.  /****************************************************************************
  930.   * x264_encoder_open:
  931.   ****************************************************************************/
  932. @@ -923,6 +1108,163 @@ x264_t *x264_encoder_open( x264_param_t *param )
  933.  
  934.      CHECKED_MALLOCZERO( h, sizeof(x264_t) );
  935.  
  936. +#ifdef __PARAM_DEBUG
  937. +#define PARAM_PRINT(x) printf("%s = %08x\n", #x, param->x);
  938. +#define PARAM_PRINT_F(x) printf("%s = %7.4f\n", #x, param->x);
  939. +#define PARAM_PRINT_P(x) printf("%s = %p\n", #x, param->x);
  940. +#else
  941. +#define PARAM_PRINT(x);
  942. +#define PARAM_PRINT_F(x);
  943. +#define PARAM_PRINT_P(x);
  944. +#endif
  945. +
  946. +    PARAM_PRINT(cpu);
  947. +    PARAM_PRINT(i_threads);
  948. +    PARAM_PRINT(b_sliced_threads);
  949. +    PARAM_PRINT(b_deterministic);
  950. +    PARAM_PRINT(i_sync_lookahead);
  951. +    PARAM_PRINT(i_width);
  952. +    PARAM_PRINT(i_height);
  953. +    PARAM_PRINT(i_csp);
  954. +    PARAM_PRINT(i_level_idc);
  955. +    PARAM_PRINT(i_frame_total);
  956. +    PARAM_PRINT(i_nal_hrd);
  957. +    PARAM_PRINT(vui.i_sar_height);
  958. +    PARAM_PRINT(vui.i_sar_width);
  959. +    PARAM_PRINT(vui.i_overscan);
  960. +    PARAM_PRINT(vui.i_vidformat);
  961. +    PARAM_PRINT(vui.b_fullrange);
  962. +    PARAM_PRINT(vui.i_colorprim);
  963. +    PARAM_PRINT(vui.i_transfer);
  964. +    PARAM_PRINT(vui.i_colmatrix);
  965. +    PARAM_PRINT(vui.i_chroma_loc);
  966. +
  967. +    PARAM_PRINT(i_frame_reference);  /* Maximum number of reference frames */
  968. +    PARAM_PRINT(i_dpb_size);         /* Force a DPB size larger than that implied by B-frames and reference frames.
  969. +                                     * Useful in combination with interactive error resilience. */
  970. +    PARAM_PRINT(i_keyint_max);       /* Force an IDR keyframe at this interval */
  971. +    PARAM_PRINT(i_keyint_min);       /* Scenecuts closer together than this are coded as I, not IDR. */
  972. +    PARAM_PRINT(i_scenecut_threshold); /* how aggressively to insert extra I frames */
  973. +    PARAM_PRINT(b_intra_refresh);    /* Whether or not to use periodic intra refresh instead of IDR frames. */
  974. +
  975. +    PARAM_PRINT(i_bframe);   /* how many b-frame between 2 references pictures */
  976. +    PARAM_PRINT(i_bframe_adaptive);
  977. +    PARAM_PRINT(i_bframe_bias);
  978. +    PARAM_PRINT(i_bframe_pyramid);   /* Keep some B-frames as references: 0=off, 1=strict hierarchical, 2=normal */
  979. +    PARAM_PRINT(i_open_gop);         /* Open gop: 1=display order, 2=bluray compatibility braindamage mode */
  980. +
  981. +    PARAM_PRINT(b_deblocking_filter);
  982. +    PARAM_PRINT(i_deblocking_filter_alphac0);    /* [-6, 6] -6 light filter, 6 strong */
  983. +    PARAM_PRINT(i_deblocking_filter_beta);       /* [-6, 6]  idem */
  984. +
  985. +    PARAM_PRINT(b_cabac);
  986. +    PARAM_PRINT(i_cabac_init_idc);
  987. +
  988. +    PARAM_PRINT(b_interlaced);
  989. +    PARAM_PRINT(b_constrained_intra);
  990. +
  991. +    PARAM_PRINT(i_cqm_preset);
  992. +    PARAM_PRINT_P(psz_cqm_file);
  993. +    
  994. +    PARAM_PRINT(b_mvc);
  995. +
  996. +    PARAM_PRINT(analyse.intra);     /* intra partitions */
  997. +    PARAM_PRINT(analyse.inter);     /* inter partitions */
  998. +
  999. +    PARAM_PRINT(analyse.b_transform_8x8);
  1000. +    PARAM_PRINT(analyse.i_weighted_pred); /* weighting for P-frames */
  1001. +    PARAM_PRINT(analyse.b_weighted_bipred); /* implicit weighting for B-frames */
  1002. +    PARAM_PRINT(analyse.i_direct_mv_pred); /* spatial vs temporal mv prediction */
  1003. +    PARAM_PRINT(analyse.i_chroma_qp_offset);
  1004. +
  1005. +    PARAM_PRINT(analyse.i_me_method); /* motion estimation algorithm to use (X264_ME_*) */
  1006. +    PARAM_PRINT(analyse.i_me_range); /* integer pixel motion estimation search range (from predicted mv) */
  1007. +    PARAM_PRINT(analyse.i_mv_range); /* maximum length of a mv (in pixels). -1 = auto, based on level */
  1008. +    PARAM_PRINT(analyse.i_mv_range_thread); /* minimum space between threads. -1 = auto, based on number of threads. */
  1009. +    PARAM_PRINT(analyse.i_subpel_refine); /* subpixel motion estimation quality */
  1010. +    PARAM_PRINT(analyse.b_chroma_me); /* chroma ME for subpel and mode decision in P-frames */
  1011. +    PARAM_PRINT(analyse.b_mixed_references); /* allow each mb partition to have its own reference number */
  1012. +    PARAM_PRINT(analyse.i_trellis);  /* trellis RD quantization */
  1013. +    PARAM_PRINT(analyse.b_fast_pskip); /* early SKIP detection on P-frames */
  1014. +    PARAM_PRINT(analyse.b_dct_decimate); /* transform coefficient thresholding on P-frames */
  1015. +    PARAM_PRINT(analyse.i_noise_reduction); /* adaptive pseudo-deadzone */
  1016. +    PARAM_PRINT_F(analyse.f_psy_rd); /* Psy RD strength */
  1017. +    PARAM_PRINT_F(analyse.f_psy_trellis); /* Psy trellis strength */
  1018. +    PARAM_PRINT(analyse.b_psy); /* Toggle all psy optimizations */
  1019. +
  1020. +    PARAM_PRINT(analyse.i_luma_deadzone[0]); /* {inter, intra} */
  1021. +    PARAM_PRINT(analyse.i_luma_deadzone[1]); /* {inter, intra} */
  1022. +    PARAM_PRINT(analyse.b_psnr);    /* compute and print PSNR stats */
  1023. +    PARAM_PRINT(analyse.b_ssim);    /* compute and print SSIM stats */
  1024. +
  1025. +    PARAM_PRINT(rc.i_rc_method);    /* X264_RC_* */
  1026. +
  1027. +    PARAM_PRINT(rc.i_qp_constant);  /* 0 to (51 + 6*(x264_bit_depth-8)). 0=lossless */
  1028. +    PARAM_PRINT(rc.i_qp_min);       /* min allowed QP value */
  1029. +    PARAM_PRINT(rc.i_qp_max);       /* max allowed QP value */
  1030. +    PARAM_PRINT(rc.i_qp_step);      /* max QP step between frames */
  1031. +
  1032. +    PARAM_PRINT(rc.i_bitrate);
  1033. +    PARAM_PRINT_F(rc.f_rf_constant);  /* 1pass VBR, nominal QP */
  1034. +    PARAM_PRINT_F(rc.f_rf_constant_max);  /* In CRF mode, maximum CRF as caused by VBV */
  1035. +    PARAM_PRINT_F(rc.f_rate_tolerance);
  1036. +    PARAM_PRINT(rc.i_vbv_max_bitrate);
  1037. +    PARAM_PRINT(rc.i_vbv_buffer_size);
  1038. +    PARAM_PRINT_F(rc.f_vbv_buffer_init); /* <=1: fraction of buffer_size. >1: kbit */
  1039. +    PARAM_PRINT_F(rc.f_ip_factor);
  1040. +    PARAM_PRINT_F(rc.f_pb_factor);
  1041. +
  1042. +    PARAM_PRINT(rc.i_aq_mode);      /* psy adaptive QP. (X264_AQ_*) */
  1043. +    PARAM_PRINT_F(rc.f_aq_strength);
  1044. +    PARAM_PRINT(rc.b_mb_tree);      /* Macroblock-tree ratecontrol. */
  1045. +    PARAM_PRINT(rc.i_lookahead);
  1046. +
  1047. +    PARAM_PRINT(rc.b_stat_write);   /* Enable stat writing in psz_stat_out */
  1048. +    PARAM_PRINT_P(rc.psz_stat_out);
  1049. +    PARAM_PRINT(rc.b_stat_read);    /* Read stat from psz_stat_in and use it */
  1050. +    PARAM_PRINT_P(rc.psz_stat_in);
  1051. +
  1052. +    PARAM_PRINT_F(rc.f_qcompress);    /* 0.0 => cbr, 1.0 => constant qp */
  1053. +    PARAM_PRINT_F(rc.f_qblur);        /* temporally blur quants */
  1054. +    PARAM_PRINT_F(rc.f_complexity_blur); /* temporally blur complexity */
  1055. +    PARAM_PRINT_P(rc.zones);         /* ratecontrol overrides */
  1056. +    PARAM_PRINT(rc.i_zones);        /* number of zone_t's */
  1057. +    PARAM_PRINT_P(rc.psz_zones);     /* alternate method of specifying zones */
  1058. +
  1059. +    PARAM_PRINT(rc.i_bitrate_dep[0]);
  1060. +    PARAM_PRINT(rc.i_vbv_max_bitrate_dep[0]);
  1061. +
  1062. +    PARAM_PRINT(crop_rect.i_left);
  1063. +    PARAM_PRINT(crop_rect.i_top);
  1064. +    PARAM_PRINT(crop_rect.i_right);
  1065. +    PARAM_PRINT(crop_rect.i_bottom);
  1066. +
  1067. +    PARAM_PRINT(timecode_offset.b_drop);
  1068. +    PARAM_PRINT(timecode_offset.hour);
  1069. +    PARAM_PRINT(timecode_offset.minute);
  1070. +    PARAM_PRINT(timecode_offset.second);
  1071. +    PARAM_PRINT(timecode_offset.frame);
  1072. +
  1073. +    PARAM_PRINT(i_frame_packing);
  1074. +    PARAM_PRINT(b_aud);
  1075. +    PARAM_PRINT(b_repeat_headers);
  1076. +    PARAM_PRINT(b_repeat_pps_all_frames);
  1077. +    PARAM_PRINT(b_annexb);
  1078. +    PARAM_PRINT(i_sps_id);
  1079. +    PARAM_PRINT(b_vfr_input);
  1080. +    PARAM_PRINT(b_pulldown);
  1081. +    PARAM_PRINT(i_fps_num);
  1082. +    PARAM_PRINT(i_fps_den);
  1083. +    PARAM_PRINT(i_timebase_num);
  1084. +    PARAM_PRINT(i_timebase_den);
  1085. +
  1086. +    PARAM_PRINT(b_tff);
  1087. +    PARAM_PRINT(b_pic_struct);
  1088. +    PARAM_PRINT(b_fake_interlaced);
  1089. +    PARAM_PRINT(i_slice_max_size);
  1090. +    PARAM_PRINT(i_slice_max_mbs);
  1091. +    PARAM_PRINT(i_slice_count);
  1092. +
  1093.      /* Create a copy of param */
  1094.      memcpy( &h->param, param, sizeof(x264_param_t) );
  1095.  
  1096. @@ -964,9 +1306,17 @@ x264_t *x264_encoder_open( x264_param_t *param )
  1097.      h->sps = &h->sps_array[0];
  1098.      x264_sps_init( h->sps, h->param.i_sps_id, &h->param );
  1099.  
  1100. +    h->subset_sps = &h->sps_array[1];
  1101. +    x264_sps_init( h->subset_sps, 1, &h->param );
  1102. +
  1103.      h->pps = &h->pps_array[0];
  1104.      x264_pps_init( h->pps, h->param.i_sps_id, &h->param, h->sps );
  1105.  
  1106. +    h->subset_pps = &h->pps_array[1];
  1107. +    x264_pps_init( h->subset_pps, 1, &h->param, h->subset_sps );
  1108. +    if( h->subset_pps->i_num_ref_idx_l0_default_active > 2 )
  1109. +        h->subset_pps->i_num_ref_idx_l0_default_active--;
  1110. +
  1111.      x264_set_aspect_ratio( h, &h->param, 1 );
  1112.  
  1113.      x264_validate_levels( h, 1 );
  1114. @@ -992,6 +1342,8 @@ x264_t *x264_encoder_open( x264_param_t *param )
  1115.      h->frames.i_delay += h->param.i_sync_lookahead;
  1116.      h->frames.i_delay += h->param.b_vfr_input;
  1117.      h->frames.i_bframe_delay = h->param.i_bframe ? (h->param.i_bframe_pyramid ? 2 : 1) : 0;
  1118. +    if( h->param.b_mvc )
  1119. +        h->frames.i_bframe_delay *= 2;
  1120.  
  1121.      h->frames.i_max_ref0 = h->param.i_frame_reference;
  1122.      h->frames.i_max_ref1 = X264_MIN( h->sps->vui.i_num_reorder_frames, h->param.i_frame_reference );
  1123. @@ -1012,7 +1364,13 @@ x264_t *x264_encoder_open( x264_param_t *param )
  1124.      h->frames.i_largest_pts = h->frames.i_second_largest_pts = -1;
  1125.      h->frames.i_poc_last_open_gop = -1;
  1126.  
  1127. -    CHECKED_MALLOCZERO( h->frames.unused[0], (h->frames.i_delay + 3) * sizeof(x264_frame_t *) );
  1128. +    h->offset_frame = calculate_frame_from_timecode(h->param.i_fps_num, h->param.i_fps_den, h->param.timecode_offset);
  1129. +    if (h->param.b_mvc) {
  1130. +        h->offset_frame *= 2;
  1131. +    }
  1132. +    
  1133. +    CHECKED_MALLOCZERO( h->frames.unused[0], (h->frames.i_delay + 3) * sizeof(x264_frame_t *) * ((h->param.b_mvc) ? 2 : 1));
  1134. +
  1135.      /* Allocate room for max refs plus a few extra just in case. */
  1136.      CHECKED_MALLOCZERO( h->frames.unused[1], (h->i_thread_frames + X264_REF_MAX + 4) * sizeof(x264_frame_t *) );
  1137.      CHECKED_MALLOCZERO( h->frames.current, (h->param.i_sync_lookahead + h->param.i_bframe
  1138. @@ -1149,21 +1507,36 @@ x264_t *x264_encoder_open( x264_param_t *param )
  1139.          x264_log( h, X264_LOG_DEBUG, "CPB size: %i bits\n", h->sps->vui.hrd.i_cpb_size_unscaled );
  1140.      }
  1141.  
  1142. -    if( h->param.psz_dump_yuv )
  1143. +    if( h->param.psz_dump_yuv[0] )
  1144.      {
  1145. -        /* create or truncate the reconstructed video file */
  1146. -        FILE *f = fopen( h->param.psz_dump_yuv, "w" );
  1147. -        if( !f )
  1148. +        if( h->param.b_mvc )
  1149.          {
  1150. -            x264_log( h, X264_LOG_ERROR, "dump_yuv: can't write to %s\n", h->param.psz_dump_yuv );
  1151. -            goto fail;
  1152. +            static const char *dep_suffix = "_dep";
  1153. +            size_t namelen = strlen(h->param.psz_dump_yuv[0]),
  1154. +                   sufflen = strlen(dep_suffix);
  1155. +            h->param.psz_dump_yuv[1] = calloc( namelen + sufflen + 1, sizeof(char) );
  1156. +            memcpy( h->param.psz_dump_yuv[1], h->param.psz_dump_yuv[0], namelen - 4 ); /* without extension */
  1157. +            h->param.psz_dump_yuv[1][namelen - 4] = '\0';
  1158. +            strcat( h->param.psz_dump_yuv[1], dep_suffix);
  1159. +            strcat( h->param.psz_dump_yuv[1], h->param.psz_dump_yuv[0] + namelen - 4);
  1160.          }
  1161. -        else if( !x264_is_regular_file( f ) )
  1162. +        
  1163. +        /* create or truncate the reconstructed video file */
  1164. +        for( int i = 0; i < 2 && h->param.psz_dump_yuv[i] != NULL ; i++ )
  1165.          {
  1166. -            x264_log( h, X264_LOG_ERROR, "dump_yuv: incompatible with non-regular file %s\n", h->param.psz_dump_yuv );
  1167. -            goto fail;
  1168. +            FILE *f = fopen( h->param.psz_dump_yuv[i], "w" );
  1169. +            if( !f )
  1170. +            {
  1171. +                x264_log( h, X264_LOG_ERROR, "dump_yuv: can't write to %s\n", h->param.psz_dump_yuv[i] );
  1172. +                goto fail;
  1173. +            }
  1174. +            else if( !x264_is_regular_file( f ) )
  1175. +            {
  1176. +                x264_log( h, X264_LOG_ERROR, "dump_yuv: incompatible with non-regular file %s\n", h->param.psz_dump_yuv[i] );
  1177. +                goto fail;
  1178. +            }
  1179. +            fclose( f );
  1180.          }
  1181. -        fclose( f );
  1182.      }
  1183.  
  1184.      const char *profile = h->sps->i_profile_idc == PROFILE_BASELINE ? "Constrained Baseline" :
  1185. @@ -1242,6 +1615,23 @@ int x264_encoder_reconfig( x264_t *h, x264_param_t *param )
  1186.      COPY( i_slice_count );
  1187.      COPY( b_tff );
  1188.  
  1189. +    if (param->i_cqm_preset >= X264_CQM_FLAT && param->i_cqm_preset <= X264_CQM_CUSTOM) {
  1190. +        COPY( i_cqm_preset );
  1191. +        if (param->i_cqm_preset == X264_CQM_CUSTOM) {
  1192. +            memcpy(h->param.cqm_4iy, param->cqm_4iy, 16);
  1193. +            memcpy(h->param.cqm_4ic, param->cqm_4ic, 16);
  1194. +            memcpy(h->param.cqm_8iy, param->cqm_8iy, 64);
  1195. +            memcpy(h->param.cqm_4py, param->cqm_4py, 16);
  1196. +            memcpy(h->param.cqm_4pc, param->cqm_4pc, 16);
  1197. +            memcpy(h->param.cqm_8py, param->cqm_8py, 64);
  1198. +        }
  1199. +
  1200. +        x264_pps_init ( h->pps, h->pps->i_id, &h->param, h->sps );
  1201. +        if (h->subset_sps && h->subset_pps) x264_pps_init ( h->subset_pps, h->subset_pps->i_id, &h->param, h->subset_sps );
  1202. +
  1203. +        if (x264_cqm_init( h ) < 0) return -1;
  1204. +    }
  1205. +
  1206.      /* VBV can't be turned on if it wasn't on to begin with */
  1207.      if( h->param.rc.i_vbv_max_bitrate > 0 && h->param.rc.i_vbv_buffer_size > 0 &&
  1208.            param->rc.i_vbv_max_bitrate > 0 &&   param->rc.i_vbv_buffer_size > 0 )
  1209. @@ -1291,7 +1681,7 @@ void x264_encoder_parameters( x264_t *h, x264_param_t *param )
  1210.  static void x264_nal_start( x264_t *h, int i_type, int i_ref_idc )
  1211.  {
  1212.      x264_nal_t *nal = &h->out.nal[h->out.i_nal];
  1213. -
  1214. +    
  1215.      nal->i_ref_idc        = i_ref_idc;
  1216.      nal->i_type           = i_type;
  1217.      nal->b_long_startcode = 1;
  1218. @@ -1572,28 +1962,99 @@ static inline int x264_reference_distance( x264_t *h, x264_frame_t *frame )
  1219.  
  1220.  static inline void x264_reference_build_list( x264_t *h, int i_poc )
  1221.  {
  1222. -    int b_ok;
  1223.  
  1224. +#ifdef _DEBUG
  1225. +    x264_log(h, X264_LOG_INFO, "Start x264_reference_build_list(). (Frame number: %d)\n", h->fenc->i_frame );
  1226. +#endif
  1227. +
  1228. +    int b_ok;
  1229. +    int remove_num = h->sh.i_mmco_remove_from_end;
  1230. +    
  1231.      /* build ref list 0/1 */
  1232.      h->mb.pic.i_fref[0] = h->i_ref[0] = 0;
  1233.      h->mb.pic.i_fref[1] = h->i_ref[1] = 0;
  1234.      if( h->sh.i_type == SLICE_TYPE_I )
  1235.          return;
  1236.  
  1237. +    //for( int i = 0; h->frames.reference[i]; i++ )
  1238. +    //    printf( "Reference frame is %d.\n",  h->frames.reference[i]->i_frame );
  1239. +    x264_frame_t *base_view = NULL;
  1240. +    if ( h->param.b_mvc )
  1241. +    {
  1242. +        for( int i = 0; h->frames.reference[i]; i++ )
  1243. +        {
  1244. +
  1245. +#ifdef _DEBUG
  1246. +     x264_log(h, X264_LOG_INFO, "h->frames.reference[%d]->i_frame %d\n",  i, h->frames.reference[i]->i_frame);
  1247. +     x264_log(h, X264_LOG_INFO, "h->fenc->i_frame - 1 = %d\n",  h->fenc->i_frame - 1);
  1248. +#endif
  1249. +
  1250. +            if ( h->frames.reference[i]->i_frame == h->fenc->i_frame - 1 )
  1251. +            {
  1252. +                //assert( base_view == NULL );
  1253. +                if ( base_view != NULL )
  1254. +         x264_log( h, X264_LOG_WARNING, "A duplicated base view frame found. (Frame number: %d)\n", h->fenc->i_frame );
  1255. +
  1256. +                base_view = h->frames.reference[i];
  1257. +            }
  1258. +        }
  1259. +        
  1260. +        /* Insert an inter-view reference frame to L0. */
  1261. +        if ( h->b_dependent ) /* The frame being encoded is dependent view. */
  1262. +        {
  1263. +            if (base_view != NULL)
  1264. +                h->fref[0][h->i_ref[0]++] = base_view;
  1265. +            else
  1266. +                x264_log( h, X264_LOG_WARNING, "No base view frame found. (Frame number: %d)\n", h->fenc->i_frame );
  1267. +        }
  1268. +    }
  1269. +    
  1270.      for( int i = 0; h->frames.reference[i]; i++ )
  1271.      {
  1272. -        if( h->frames.reference[i]->b_corrupt )
  1273. +
  1274. +#ifdef __DEBUG
  1275. +     x264_log(h, X264_LOG_INFO, "h->frames.reference[%d]->i_frame %d\n",  i, h->frames.reference[i]->i_frame);
  1276. +#endif
  1277. +
  1278. +        if( h->frames.reference[i]->b_corrupt ) {
  1279. +#ifdef __DEBUG
  1280. +            x264_log( h, X264_LOG_INFO, "b_corrupt : ref frame %d : poc=%d\n",
  1281. +                      h->frames.reference[i]->i_frame, h->frames.reference[i]->i_poc);
  1282. +#endif
  1283.              continue;
  1284. -        if( h->frames.reference[i]->i_poc < i_poc )
  1285. -            h->fref[0][h->i_ref[0]++] = h->frames.reference[i];
  1286. -        else if( h->frames.reference[i]->i_poc > i_poc )
  1287. -            h->fref[1][h->i_ref[1]++] = h->frames.reference[i];
  1288. +        }
  1289. +        if( !h->param.b_mvc || h->frames.reference[i]->i_frame % 2 == h->fenc->i_frame % 2 )
  1290. +        {
  1291. +#ifdef __DEBUG
  1292. +            x264_log( h, X264_LOG_INFO, "ref frame %d : poc=%d (Frame number: %d)\n",
  1293. +                      h->frames.reference[i]->i_frame, h->frames.reference[i]->i_poc,
  1294. +                      h->fenc->i_frame );
  1295. +#endif
  1296. +            if( h->frames.reference[i]->i_poc < i_poc )
  1297. +            {
  1298. +#ifdef __DEBUG
  1299. +                x264_log( h, X264_LOG_INFO, "Set base view frame(%d) to L0 at %d. (Frame number: %d)\n", h->frames.reference[i]->i_frame, h->i_ref[0], h->fenc->i_frame );
  1300. +#endif
  1301. +                h->fref[0][h->i_ref[0]++] = h->frames.reference[i];
  1302. +            }
  1303. +            else if( h->frames.reference[i]->i_poc > i_poc )
  1304. +            {
  1305. +#ifdef __DEBUG
  1306. +                x264_log( h, X264_LOG_INFO, "Set base view frame(%d) to L1 at %d. (Frame number: %d)\n", h->frames.reference[i]->i_frame, h->i_ref[0], h->fenc->i_frame );
  1307. +#endif
  1308. +                h->fref[1][h->i_ref[1]++] = h->frames.reference[i];
  1309. +            }
  1310. +        }
  1311.      }
  1312.  
  1313.      /* Order reference lists by distance from the current frame. */
  1314.      for( int list = 0; list < 2; list++ )
  1315.      {
  1316. -        h->fref_nearest[list] = h->fref[list][0];
  1317. +        int pos = 0;
  1318. +        do {
  1319. +            h->fref_nearest[list] = h->fref[list][pos];
  1320. +            pos++;
  1321. +        } while (h->param.b_mvc && pos < h->i_ref[list] && (h->fref_nearest[list]->i_poc & (~2)) == (h->fenc->i_poc & (~2)));
  1322.          do
  1323.          {
  1324.              b_ok = 1;
  1325. @@ -1612,8 +2073,12 @@ static inline void x264_reference_build_list( x264_t *h, int i_poc )
  1326.          } while( !b_ok );
  1327.      }
  1328.  
  1329. -    if( h->sh.i_mmco_remove_from_end )
  1330. -        for( int i = h->i_ref[0]-1; i >= h->i_ref[0] - h->sh.i_mmco_remove_from_end; i-- )
  1331. +    if ( h->param.b_mvc )
  1332. +    {
  1333. +        remove_num /= 2;
  1334. +    }
  1335. +    if( remove_num )
  1336. +        for( int i = h->i_ref[0]-1; i >= h->i_ref[0] - remove_num; i-- )
  1337.          {
  1338.              int diff = h->i_frame_num - h->fref[0][i]->i_frame_num;
  1339.              h->sh.mmco[h->sh.i_mmco_command_count].i_poc = h->fref[0][i]->i_poc;
  1340. @@ -1623,11 +2088,13 @@ static inline void x264_reference_build_list( x264_t *h, int i_poc )
  1341.      x264_reference_check_reorder( h );
  1342.  
  1343.      h->i_ref[1] = X264_MIN( h->i_ref[1], h->frames.i_max_ref1 );
  1344. -    h->i_ref[0] = X264_MIN( h->i_ref[0], h->frames.i_max_ref0 );
  1345. -    h->i_ref[0] = X264_MIN( h->i_ref[0], h->param.i_frame_reference ); // if reconfig() has lowered the limit
  1346. +    //h->i_ref[0] = X264_MIN( h->i_ref[0], h->frames.i_max_ref0 );
  1347. +    //h->i_ref[0] = X264_MIN( h->i_ref[0], h->param.i_frame_reference ); // if reconfig() has lowered the limit
  1348. +    h->i_ref[0] = X264_MIN( h->i_ref[0], h->frames.i_max_ref0 + h->b_dependent );
  1349. +    h->i_ref[0] = X264_MIN( h->i_ref[0], h->param.i_frame_reference + h->b_dependent ); // if reconfig() has lowered the limit
  1350.  
  1351.      /* add duplicates */
  1352. -    if( h->fenc->i_type == X264_TYPE_P )
  1353. +    if( h->fenc->i_type == X264_TYPE_P || h->fenc->i_type == X264_TYPE_ANCHOR)
  1354.      {
  1355.          int idx = -1;
  1356.          if( h->param.analyse.i_weighted_pred >= X264_WEIGHTP_SIMPLE )
  1357. @@ -1665,6 +2132,18 @@ static inline void x264_reference_build_list( x264_t *h, int i_poc )
  1358.      assert( h->i_ref[0] + h->i_ref[1] <= X264_REF_MAX );
  1359.      h->mb.pic.i_fref[0] = h->i_ref[0];
  1360.      h->mb.pic.i_fref[1] = h->i_ref[1];
  1361. +    
  1362. +#ifdef __DEBUG
  1363. +    for (int j = 0; j < 2; j++) {
  1364. +        x264_log(h, X264_LOG_INFO, "i_ref%d=%d\n", j, h->i_ref[j]);
  1365. +        for (int i = 0; i < h->i_ref[j]; ++i) {
  1366. +            x264_log(h, X264_LOG_INFO, "ref%d[%2d] : no = %4d, poc = %2d\n",
  1367. +                     j, i,
  1368. +                     h->fref[j][i] ? h->fref[j][i]->i_frame : 9999,
  1369. +                     h->fref[j][i] ? h->fref[j][i]->i_poc : -1);
  1370. +        }
  1371. +    }
  1372. +#endif
  1373.  }
  1374.  
  1375.  static void x264_fdec_filter_row( x264_t *h, int mb_y, int b_inloop )
  1376. @@ -1677,7 +2156,7 @@ static void x264_fdec_filter_row( x264_t *h, int mb_y, int b_inloop )
  1377.      int min_y = mb_y - (1 << h->sh.b_mbaff);
  1378.      int b_start = min_y == h->i_threadslice_start;
  1379.      int max_y = b_end ? h->i_threadslice_end : mb_y;
  1380. -    b_deblock &= b_hpel || h->param.psz_dump_yuv;
  1381. +    b_deblock &= b_hpel || h->param.psz_dump_yuv[0];
  1382.      if( h->param.b_sliced_threads && b_start && min_y && !b_inloop )
  1383.      {
  1384.          b_deblock = 0;         /* We already deblocked on the inloop pass. */
  1385. @@ -1744,6 +2223,38 @@ static void x264_fdec_filter_row( x264_t *h, int mb_y, int b_inloop )
  1386.  
  1387.  static inline int x264_reference_update( x264_t *h )
  1388.  {
  1389. +    x264_sps_t * sps = h->b_dependent ? h->subset_sps : h->sps;
  1390. +
  1391. +#ifdef __DEBUG
  1392. +    x264_log(h, X264_LOG_INFO, "x264_reference_update called h->fdec->i_frame %d, (%s), frame=%d\n", h->fdec->i_frame, h->b_dependent ? "d" : "m", h->i_frame);
  1393. +#endif
  1394. +
  1395. +    /* Delete all inter-view only frames. */
  1396. +    /* h->i_frame is not updated in this timing. */
  1397. +    if( (h->i_frame % 2) == 1 )
  1398. +        for( int i = 0; h->frames.reference[i]; i++ ) {
  1399. +#ifdef __DEBUG
  1400. +            x264_log(h, X264_LOG_INFO, "ref frame %d\n", h->frames.reference[i]->i_frame);
  1401. +#endif
  1402. +            if( h->frames.reference[i]->b_inter_view_only && h->frames.reference[i]->i_type == X264_TYPE_B )
  1403. +            {
  1404. +                //printf("Delete an inter view only frame.\n");
  1405. +#ifdef __DEBUG
  1406. +                x264_log(h, X264_LOG_INFO, "Delete an inter view only frame %d(type=%d) at %d\n", h->frames.reference[i]->i_frame, h->frames.reference[i]->i_type, h->fdec->i_frame);
  1407. +#endif
  1408. +                x264_frame_push_unused( h, x264_frame_shift( &h->frames.reference[i] ) );
  1409. +            }
  1410. +        }
  1411. +#ifdef __DEBUG
  1412. +    x264_log(h, X264_LOG_INFO, "num_ref[view=%d] = %d\n", h->b_dependent, sps->i_num_ref_frames);
  1413. +    for( int j = 0; h->frames.reference[j]; j++ )
  1414. +        x264_log(h, X264_LOG_INFO, "ref[%2d]: no=%5d, poc=%3d\n",
  1415. +                 j, h->frames.reference[j]->i_frame, h->frames.reference[j]->i_poc);
  1416. +    for( int i = 0; i < h->sh.i_mmco_command_count; i++ )
  1417. +        x264_log(h, X264_LOG_INFO, "sh_mmco[%2d]: poc=%3d\n",
  1418. +                 i, h->sh.mmco[i].i_poc);
  1419. +#endif
  1420. +
  1421.      if( !h->fdec->b_kept_as_ref )
  1422.      {
  1423.          if( h->i_thread_frames > 1 )
  1424. @@ -1764,9 +2275,22 @@ static inline int x264_reference_update( x264_t *h )
  1425.  
  1426.      /* move frame in the buffer */
  1427.      x264_frame_push( h->frames.reference, h->fdec );
  1428. -    if( h->frames.reference[h->sps->i_num_ref_frames] )
  1429. +
  1430. +    int ivo_add = h->param.b_mvc && IS_X264_TYPE_B(h->fdec->i_type) ? 1 : 0;
  1431. +    if( h->frames.reference[sps->i_num_ref_frames * (h->param.b_mvc ? 2 : 1) + ivo_add] ) {
  1432. +#ifdef __DEBUG
  1433. +        for( int i = 0; i < sps->i_num_ref_frames * (h->param.b_mvc ? 2 : 1) + ivo_add + (h->param.b_mvc && h->i_frame % 2); i++ )
  1434. +        {
  1435. +            if( !h->frames.reference[i] )
  1436. +                x264_log(h, X264_LOG_ERROR, "There is a NULL frame on the reference list.");
  1437. +        }
  1438. +        x264_log(h, X264_LOG_INFO, "Delete frame %d, last frame %d, dec type %d\n", h->frames.reference[0]->i_frame, h->frames.reference[sps->i_num_ref_frames * (h->param.b_mvc ? 2 : 1)]->i_frame, h->fdec->i_type);
  1439. +#endif
  1440.          x264_frame_push_unused( h, x264_frame_shift( h->frames.reference ) );
  1441. +    }
  1442. +
  1443.      h->fdec = x264_frame_pop_unused( h, 1 );
  1444. +
  1445.      if( !h->fdec )
  1446.          return -1;
  1447.      return 0;
  1448. @@ -1789,7 +2313,7 @@ static inline void x264_reference_hierarchy_reset( x264_t *h )
  1449.      for( int i = 0; h->frames.current[i] && IS_DISPOSABLE( h->frames.current[i]->i_type ); i++ )
  1450.          b_hasdelayframe |= h->frames.current[i]->i_coded
  1451.                          != h->frames.current[i]->i_frame + h->sps->vui.i_num_reorder_frames;
  1452. -
  1453. +    
  1454.      /* This function must handle b-pyramid and clear frames for open-gop */
  1455.      if( h->param.i_bframe_pyramid != X264_B_PYRAMID_STRICT && !b_hasdelayframe && h->frames.i_poc_last_open_gop == -1 )
  1456.          return;
  1457. @@ -1817,7 +2341,7 @@ static inline void x264_reference_hierarchy_reset( x264_t *h )
  1458.          h->sh.i_mmco_remove_from_end = X264_MAX( ref + 2 - h->frames.i_max_dpb, 0 );
  1459.  }
  1460.  
  1461. -static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_global_qp )
  1462. +static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_global_qp, int i_nal_ref_idc )
  1463.  {
  1464.      /* ------------------------ Create slice header  ----------------------- */
  1465.      if( i_nal_type == NAL_SLICE_IDR )
  1466. @@ -1827,6 +2351,38 @@ static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_global_qp )
  1467.          /* alternate id */
  1468.          h->i_idr_pic_id ^= 1;
  1469.      }
  1470. +    else if (i_nal_type == NAL_SLICE_LAYER_EXTENSION) {
  1471. +        if (0/*i_nal_ref_idc == NAL_PRIORITY_HIGHEST*/) {
  1472. +            // this means anchor picture
  1473. +            
  1474. +        } else {
  1475. +            // only works on mvc dependent view.
  1476. +            int idr_pic_id;
  1477. +            if( h->i_last_idr_frame == h->i_frame - 1 )
  1478. +                idr_pic_id = h->i_idr_pic_id;
  1479. +            else
  1480. +                idr_pic_id = -1;
  1481. +        
  1482. +            x264_slice_header_init( h, &h->sh, h->subset_sps, h->subset_pps,
  1483. +                                    idr_pic_id, h->i_frame_num, i_global_qp );
  1484. +            // TODO: Integrate with the else statement below.
  1485. +            h->sh.i_num_ref_idx_l0_active = h->i_ref[0] <= 0 ? 1 : h->i_ref[0];
  1486. +            h->sh.i_num_ref_idx_l1_active = h->i_ref[1] <= 0 ? 1 : h->i_ref[1];
  1487. +            if( h->sh.i_num_ref_idx_l0_active != h->subset_pps->i_num_ref_idx_l0_default_active ||
  1488. +                (h->sh.i_type == SLICE_TYPE_B && h->sh.i_num_ref_idx_l1_active != h->subset_pps->i_num_ref_idx_l1_default_active) )
  1489. +                {
  1490. +                    h->sh.b_num_ref_idx_override = 1;
  1491. +                }
  1492. +#if 0
  1493. +            if( h->sh.i_num_ref_idx_l0_active > 0 )
  1494. +                h->sh.i_num_ref_idx_l0_active--;
  1495. +            
  1496. +            if( h->sh.i_num_ref_idx_l1_active > 0 )
  1497. +                h->sh.i_num_ref_idx_l1_active--;
  1498. +#endif
  1499. +            //h->sh.b_num_ref_idx_override = 1;
  1500. +        }
  1501. +    }
  1502.      else
  1503.      {
  1504.          x264_slice_header_init( h, &h->sh, h->sps, h->pps, -1, h->i_frame_num, i_global_qp );
  1505. @@ -1845,6 +2401,8 @@ static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_global_qp )
  1506.      if( h->sps->i_poc_type == 0 )
  1507.      {
  1508.          h->sh.i_poc = h->fdec->i_poc;
  1509. +        if ( h->param.b_mvc )
  1510. +            h->sh.i_poc = h->sh.i_poc / 2 & ~1;
  1511.          if( h->param.b_interlaced )
  1512.          {
  1513.              h->sh.i_delta_poc_bottom = h->param.b_tff ? 1 : -1;
  1514. @@ -1888,11 +2446,15 @@ static int x264_slice_write( x264_t *h )
  1515.      int b_deblock = h->sh.i_disable_deblocking_filter_idc != 1;
  1516.      int b_hpel = h->fdec->b_kept_as_ref;
  1517.      uint8_t *last_emu_check;
  1518. -    b_deblock &= b_hpel || h->param.psz_dump_yuv;
  1519. +    b_deblock &= b_hpel || h->param.psz_dump_yuv[0];
  1520.      bs_realign( &h->out.bs );
  1521. -
  1522. +    
  1523.      /* Slice */
  1524. -    x264_nal_start( h, h->i_nal_type, h->i_nal_ref_idc );
  1525. +    if (!h->sh.b_svc_extension_flag) {
  1526. +      x264_nal_start( h, h->i_nal_type, h->i_nal_ref_idc );
  1527. +    } else {
  1528. +      x264_nal_start( h, NAL_SLICE_LAYER_EXTENSION, h->i_nal_ref_idc );
  1529. +    }
  1530.      h->out.nal[h->out.i_nal].i_first_mb = h->sh.i_first_mb;
  1531.  
  1532.      /* Slice header */
  1533. @@ -1907,7 +2469,7 @@ static int x264_slice_write( x264_t *h )
  1534.          h->sh.i_qp_delta = h->sh.i_qp - h->pps->i_pic_init_qp;
  1535.      }
  1536.  
  1537. -    x264_slice_header_write( &h->out.bs, &h->sh, h->i_nal_ref_idc );
  1538. +    x264_slice_header_write( h, &h->out.bs, &h->sh, h->i_nal_ref_idc );
  1539.      if( h->param.b_cabac )
  1540.      {
  1541.          /* alignment needed */
  1542. @@ -2160,6 +2722,7 @@ reencode:
  1543.          bs_rbsp_trailing( &h->out.bs );
  1544.          bs_flush( &h->out.bs );
  1545.      }
  1546. +
  1547.      if( x264_nal_end( h ) )
  1548.          return -1;
  1549.  
  1550. @@ -2206,6 +2769,10 @@ static void *x264_slices_write( x264_t *h )
  1551.      int i_slice_num = 0;
  1552.      int last_thread_mb = h->sh.i_last_mb;
  1553.  
  1554. +#ifdef __DEBUG
  1555. +    x264_log(h, X264_LOG_INFO, "[slices_write] %d \n", h->sh.i_type);
  1556. +#endif
  1557. +
  1558.  #if HAVE_VISUALIZE
  1559.      if( h->param.b_visualize )
  1560.          if( x264_visualize_init( h ) )
  1561. @@ -2232,7 +2799,7 @@ static void *x264_slices_write( x264_t *h )
  1562.              return (void *)-1;
  1563.          h->sh.i_first_mb = h->sh.i_last_mb + 1;
  1564.      }
  1565. -
  1566. +    
  1567.  #if HAVE_VISUALIZE
  1568.      if( h->param.b_visualize )
  1569.      {
  1570. @@ -2357,16 +2924,17 @@ int     x264_encoder_encode( x264_t *h,
  1571.                               x264_picture_t *pic_in,
  1572.                               x264_picture_t *pic_out )
  1573.  {
  1574. -    x264_t *thread_current, *thread_prev, *thread_oldest;
  1575. +    x264_t *thread_current, *thread_prev, *thread_oldest, *thread_next_oldest;
  1576.      int i_nal_type, i_nal_ref_idc, i_global_qp;
  1577.      int overhead = NALU_OVERHEAD;
  1578. -
  1579. +    
  1580.      if( h->i_thread_frames > 1 )
  1581.      {
  1582.          thread_prev    = h->thread[ h->i_thread_phase ];
  1583.          h->i_thread_phase = (h->i_thread_phase + 1) % h->i_thread_frames;
  1584.          thread_current = h->thread[ h->i_thread_phase ];
  1585.          thread_oldest  = h->thread[ (h->i_thread_phase + 1) % h->i_thread_frames ];
  1586. +        thread_next_oldest  = h->thread[ (h->i_thread_phase + 2) % h->i_thread_frames ];
  1587.          x264_thread_sync_context( thread_current, thread_prev );
  1588.          x264_thread_sync_ratecontrol( thread_current, thread_prev, thread_oldest );
  1589.          h = thread_current;
  1590. @@ -2381,22 +2949,33 @@ int     x264_encoder_encode( x264_t *h,
  1591.          x264_cpu_mask_misalign_sse();
  1592.  #endif
  1593.  
  1594. -    // ok to call this before encoding any frames, since the initial values of fdec have b_kept_as_ref=0
  1595. -    if( x264_reference_update( h ) )
  1596. -        return -1;
  1597. +#ifdef __DEBUG
  1598. +    x264_log(h, X264_LOG_INFO, "pic_in: %d frame\n", pic_in ? pic_in->i_pts: -1);
  1599. +#endif
  1600. +    if( h->b_once_buffer_filled )
  1601. +        if( x264_reference_update( h ) )
  1602. +            return -1;
  1603. +    h->b_once_buffer_filled = 1; /* will reset below if the buffer has not filled yet. */
  1604.      h->fdec->i_lines_completed = -1;
  1605.  
  1606.      /* no data out */
  1607.      *pi_nal = 0;
  1608.      *pp_nal = NULL;
  1609.  
  1610. +
  1611. +#ifdef __DEBUG
  1612. +    x264_log( h, X264_LOG_INFO, "i_delay %d\n", h->frames.i_delay);
  1613. +#endif
  1614. +
  1615.      /* ------------------- Setup new frame from picture -------------------- */
  1616.      if( pic_in != NULL )
  1617.      {
  1618.          /* 1: Copy the picture to a frame and move it to a buffer */
  1619.          x264_frame_t *fenc = x264_frame_pop_unused( h, 0 );
  1620. -        if( !fenc )
  1621. +        if( !fenc ) {
  1622. +            x264_log(h, X264_LOG_ERROR, "[encoder_encode] cannot pop frame unused \n");
  1623.              return -1;
  1624. +        }
  1625.  
  1626.          if( x264_frame_copy_picture( h, fenc, pic_in ) < 0 )
  1627.              return -1;
  1628. @@ -2405,6 +2984,10 @@ int     x264_encoder_encode( x264_t *h,
  1629.              h->param.i_height != 16 * h->mb.i_mb_height )
  1630.              x264_frame_expand_border_mod16( h, fenc );
  1631.  
  1632. +#ifdef _DEBUG
  1633. +   x264_log(h, X264_LOG_INFO, "[encoder_encode] fenc->i_frame will be frames.i_input %d\n", h->frames.i_input + 1);
  1634. +#endif
  1635. +
  1636.          fenc->i_frame = h->frames.i_input++;
  1637.  
  1638.          if( fenc->i_frame == 0 )
  1639. @@ -2450,12 +3033,15 @@ int     x264_encoder_encode( x264_t *h,
  1640.          /* 2: Place the frame into the queue for its slice type decision */
  1641.          x264_lookahead_put_frame( h, fenc );
  1642.  
  1643. -        if( h->frames.i_input <= h->frames.i_delay + 1 - h->i_thread_frames )
  1644. -        {
  1645. -            /* Nothing yet to encode, waiting for filling of buffers */
  1646. -            pic_out->i_type = X264_TYPE_AUTO;
  1647. -            return 0;
  1648. -        }
  1649. +   if ((!h->param.b_mvc && ( h->frames.i_input <= h->frames.i_delay + 1 - h->i_thread_frames )) ||
  1650. +       (h->param.b_mvc &&  ( (h->frames.i_input / 2) <= h->frames.i_delay + 1 - h->i_thread_frames ))
  1651. +       )
  1652. +     {
  1653. +       /* Nothing yet to encode, waiting for filling of buffers */
  1654. +            h->b_once_buffer_filled = 0;
  1655. +       pic_out->i_type = X264_TYPE_AUTO;
  1656. +       return 0;
  1657. +     }
  1658.      }
  1659.      else
  1660.      {
  1661. @@ -2468,22 +3054,62 @@ int     x264_encoder_encode( x264_t *h,
  1662.  
  1663.      h->i_frame++;
  1664.      /* 3: The picture is analyzed in the lookahead */
  1665. -    if( !h->frames.current[0] )
  1666. +    if( !h->frames.current[0] ) {
  1667.          x264_lookahead_get_frames( h );
  1668.  
  1669. +#ifdef _DEBUG
  1670. +   if ( h->frames.current[0] ) {
  1671. +        x264_log(h, X264_LOG_INFO, "[encoder_encode] get frame h->frames.current[0].i_frame %d type %d\n", h->frames.current[0]->i_frame,  h->frames.current[0]->i_type);
  1672. +   }
  1673. +   if ( h->frames.current[1] ) {
  1674. +        x264_log(h, X264_LOG_INFO, "[encoder_encode] get frame h->frames.current[1].i_frame %d type %d\n", h->frames.current[1]->i_frame,  h->frames.current[1]->i_type);
  1675. +   }
  1676. +   if ( h->frames.current[2] ) {
  1677. +        x264_log(h, X264_LOG_INFO, "[encoder_encode] get frame h->frames.current[2].i_frame %d type %d\n", h->frames.current[2]->i_frame,  h->frames.current[2]->i_type);
  1678. +   }
  1679. +   if ( h->frames.current[3] ) {
  1680. +        x264_log(h, X264_LOG_INFO, "[encoder_encode] get frame h->frames.current[3].i_frame %d type %d\n", h->frames.current[3]->i_frame,  h->frames.current[3]->i_type);
  1681. +   }
  1682. +   if ( h->frames.current[4] ) {
  1683. +        x264_log(h, X264_LOG_INFO, "[encoder_encode] get frame h->frames.current[4].i_frame %d type %d\n", h->frames.current[4]->i_frame,  h->frames.current[4]->i_type);
  1684. +   }
  1685. +   if ( h->frames.current[5] ) {
  1686. +        x264_log(h, X264_LOG_INFO, "[encoder_encode] get frame h->frames.current[5].i_frame %d type %d\n", h->frames.current[5]->i_frame,  h->frames.current[5]->i_type);
  1687. +   }
  1688. +#endif
  1689. +    }
  1690. +
  1691.      if( !h->frames.current[0] && x264_lookahead_is_empty( h ) )
  1692. -        return x264_encoder_frame_end( thread_oldest, thread_current, pp_nal, pi_nal, pic_out );
  1693. +        return x264_encoder_frame_end( thread_oldest, thread_current, thread_next_oldest, pp_nal, pi_nal, pic_out );
  1694.  
  1695.      /* ------------------- Get frame to be encoded ------------------------- */
  1696.      /* 4: get picture to encode */
  1697. -    h->fenc = x264_frame_shift( h->frames.current );
  1698. +
  1699. +    if (h->frames.current[0]) {
  1700. +      h->fenc = x264_frame_shift( h->frames.current );
  1701. +    } else {
  1702. +      // in mvc case, frames.current[0] is null when odd frame
  1703. +
  1704. +#ifdef _DEBUG
  1705. +      x264_log(h, X264_LOG_INFO, "frames.current[0] is null\n");
  1706. +#endif
  1707. +
  1708. +      return 0;
  1709. +    }
  1710. +
  1711. +    h->b_dependent = (h->param.b_mvc && h->fenc->i_frame % 2);
  1712.      if( h->i_frame == h->i_thread_frames - 1 )
  1713.          h->i_reordered_pts_delay = h->fenc->i_reordered_pts;
  1714.      if( h->fenc->param )
  1715.      {
  1716. -        x264_encoder_reconfig( h, h->fenc->param );
  1717. +        if (h->fenc->i_type != X264_TYPE_IDR) {
  1718. +            h->fenc->param->i_cqm_preset = -1; // invalid
  1719. +        }
  1720. +        int reconfig_ret = x264_encoder_reconfig( h, h->fenc->param );
  1721.          if( h->fenc->param->param_free )
  1722.              h->fenc->param->param_free( h->fenc->param );
  1723. +
  1724. +        if (reconfig_ret < 0) return -1;
  1725.      }
  1726.  
  1727.      if( !IS_X264_TYPE_I( h->fenc->i_type ) )
  1728. @@ -2513,55 +3139,76 @@ int     x264_encoder_encode( x264_t *h,
  1729.      h->sh.i_mmco_remove_from_end = 0;
  1730.      h->b_ref_reorder[0] =
  1731.      h->b_ref_reorder[1] = 0;
  1732. +
  1733.      h->fdec->i_poc =
  1734.      h->fenc->i_poc = 2 * ( h->fenc->i_frame - X264_MAX( h->frames.i_last_idr, 0 ) );
  1735.  
  1736.      /* ------------------- Setup frame context ----------------------------- */
  1737.      /* 5: Init data dependent of frame type */
  1738. -    if( h->fenc->i_type == X264_TYPE_IDR )
  1739. +    if( h->fenc->i_type == X264_TYPE_IDR || (h->fenc->i_type == X264_TYPE_I && h->param.i_open_gop == X264_OPEN_GOP_NONE))
  1740.      {
  1741.          /* reset ref pictures */
  1742.          i_nal_type    = NAL_SLICE_IDR;
  1743.          i_nal_ref_idc = NAL_PRIORITY_HIGHEST;
  1744.          h->sh.i_type = SLICE_TYPE_I;
  1745. +        h->sh.b_anchor = 1;
  1746.          x264_reference_reset( h );
  1747.          h->frames.i_poc_last_open_gop = -1;
  1748.      }
  1749.      else if( h->fenc->i_type == X264_TYPE_I )
  1750.      {
  1751. -        i_nal_type    = NAL_SLICE;
  1752. +        i_nal_type    = h->b_dependent ? NAL_SLICE_LAYER_EXTENSION : NAL_SLICE;
  1753.          i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
  1754.          h->sh.i_type = SLICE_TYPE_I;
  1755. +        h->sh.b_anchor = 1;
  1756.          x264_reference_hierarchy_reset( h );
  1757.          if( h->param.i_open_gop )
  1758.              h->frames.i_poc_last_open_gop = h->fenc->b_keyframe ? h->fenc->i_poc : -1;
  1759.      }
  1760. +    else if( h->fenc->i_type == X264_TYPE_ANCHOR )
  1761. +    {
  1762. +        /* reset ref pictures */
  1763. +        i_nal_type    = NAL_SLICE_LAYER_EXTENSION;
  1764. +        i_nal_ref_idc = NAL_PRIORITY_HIGHEST;
  1765. +        h->sh.i_type = SLICE_TYPE_P;
  1766. +        h->sh.b_anchor = 1;
  1767. +        x264_reference_hierarchy_reset( h );
  1768. +        h->frames.i_poc_last_open_gop = -1;
  1769. +    }
  1770.      else if( h->fenc->i_type == X264_TYPE_P )
  1771.      {
  1772. -        i_nal_type    = NAL_SLICE;
  1773. +        i_nal_type    = h->b_dependent ? NAL_SLICE_LAYER_EXTENSION : NAL_SLICE;
  1774.          i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
  1775.          h->sh.i_type = SLICE_TYPE_P;
  1776. +        h->sh.b_anchor = 0;
  1777.          x264_reference_hierarchy_reset( h );
  1778.          h->frames.i_poc_last_open_gop = -1;
  1779.      }
  1780.      else if( h->fenc->i_type == X264_TYPE_BREF )
  1781.      {
  1782. -        i_nal_type    = NAL_SLICE;
  1783. +        i_nal_type    = h->b_dependent ? NAL_SLICE_LAYER_EXTENSION : NAL_SLICE;
  1784.          i_nal_ref_idc = h->param.i_bframe_pyramid == X264_B_PYRAMID_STRICT ? NAL_PRIORITY_LOW : NAL_PRIORITY_HIGH;
  1785.          h->sh.i_type = SLICE_TYPE_B;
  1786. +        h->sh.b_anchor = 0;
  1787.          x264_reference_hierarchy_reset( h );
  1788.      }
  1789.      else    /* B frame */
  1790.      {
  1791. -        i_nal_type    = NAL_SLICE;
  1792. +        i_nal_type    = h->b_dependent ? NAL_SLICE_LAYER_EXTENSION : NAL_SLICE;
  1793.          i_nal_ref_idc = NAL_PRIORITY_DISPOSABLE;
  1794.          h->sh.i_type = SLICE_TYPE_B;
  1795. +        h->sh.b_anchor = 0;
  1796.      }
  1797.  
  1798.      h->fdec->i_type = h->fenc->i_type;
  1799.      h->fdec->i_frame = h->fenc->i_frame;
  1800. +    h->fdec->b_inter_view_only = h->fenc->b_inter_view_only;
  1801.      h->fenc->b_kept_as_ref =
  1802. -    h->fdec->b_kept_as_ref = i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE && h->param.i_keyint_max > 1;
  1803. +    h->fdec->b_kept_as_ref = ( h->param.b_mvc && !h->b_dependent ) ||
  1804. +                             (i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE && h->param.i_keyint_max > 1);
  1805. +#ifdef __DEBUG
  1806. +    x264_log(h, X264_LOG_INFO, "[%4d]: kept as ref = %d\n", h->fenc->i_frame, h->fenc->b_kept_as_ref);
  1807. +#endif
  1808.  
  1809.      h->fdec->i_pts = h->fenc->i_pts;
  1810.      if( h->frames.i_bframe_delay )
  1811. @@ -2575,7 +3222,14 @@ int     x264_encoder_encode( x264_t *h,
  1812.      else
  1813.          h->fdec->i_dts = h->fenc->i_reordered_pts;
  1814.      if( h->fenc->i_type == X264_TYPE_IDR )
  1815. +    {
  1816.          h->i_last_idr_pts = h->fdec->i_pts;
  1817. +        h->i_last_idr_frame = h->fdec->i_frame;
  1818. +    }
  1819. +#ifdef __DEBUG
  1820. +    x264_log(h, X264_LOG_INFO, "[%4d]: pts=%d, bframe_delay=%d, reordered_pts=%d, i_dts=%d\n",
  1821. +             h->fenc->i_frame, h->fenc->i_pts, h->frames.i_bframe_delay, h->fenc->i_reordered_pts, h->fdec->i_dts);
  1822. +#endif
  1823.  
  1824.      /* ------------------- Init                ----------------------------- */
  1825.      /* build ref list 0/1 */
  1826. @@ -2631,7 +3285,7 @@ int     x264_encoder_encode( x264_t *h,
  1827.               * the whole frame and counts as an intra refresh. */
  1828.              h->fdec->f_pir_position = h->mb.i_mb_width;
  1829.          }
  1830. -        else if( h->fenc->i_type == X264_TYPE_P )
  1831. +        else if( h->fenc->i_type == X264_TYPE_P || h->fenc->i_type == X264_TYPE_ANCHOR)
  1832.          {
  1833.              int pocdiff = (h->fdec->i_poc - h->fref[0][0]->i_poc)/2;
  1834.              float increment = X264_MAX( ((float)h->mb.i_mb_width-1) / h->param.i_keyint_max, 1 );
  1835. @@ -2654,7 +3308,7 @@ int     x264_encoder_encode( x264_t *h,
  1836.          }
  1837.      }
  1838.  
  1839. -    if( h->fenc->b_keyframe )
  1840. +    if( h->fenc->b_keyframe || (h->fenc->i_type == X264_TYPE_I && h->param.b_repeat_headers_all_gop))
  1841.      {
  1842.          /* Write SPS and PPS */
  1843.          if( h->param.b_repeat_headers )
  1844. @@ -2676,6 +3330,45 @@ int     x264_encoder_encode( x264_t *h,
  1845.  
  1846.          /* buffering period sei is written in x264_encoder_frame_end */
  1847.      }
  1848. +    else if( (h->b_dependent && h->frames.i_last_keyframe == h->fenc->i_frame - 1) ||
  1849. +             (h->fenc->i_type == X264_TYPE_ANCHOR && h->param.b_repeat_headers_all_gop) )
  1850. +    {
  1851. +      // for MVC subset SPS and subset PPS
  1852. +      /* Write SPS and PPS */
  1853. +      if( h->param.b_repeat_headers )
  1854. +      {
  1855. +        //  printf("Writing subset SPS. (i_frame=%d)\n", h->fenc->i_frame);
  1856. +        /* generate sequence parameters */
  1857. +        x264_nal_start( h, NAL_SUBSET_SPS, NAL_PRIORITY_HIGHEST );
  1858. +        //            x264_sps_write( &h->out.bs, h->subset_sps );
  1859. +        x264_subset_sps_write( &h->out.bs, h->subset_sps );
  1860. +        if( x264_nal_end( h ) )
  1861. +          return -1;
  1862. +        overhead += h->out.nal[h->out.i_nal-1].i_payload + NALU_OVERHEAD;
  1863. +      
  1864. +        /* generate picture parameters */
  1865. +        x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
  1866. +        x264_pps_write( &h->out.bs, h->subset_pps );
  1867. +        if( x264_nal_end( h ) )
  1868. +          return -1;
  1869. +        overhead += h->out.nal[h->out.i_nal-1].i_payload + NALU_OVERHEAD;
  1870. +      }
  1871. +
  1872. +      /* buffering period sei is written in x264_encoder_frame_end */
  1873. +    }
  1874. +    else
  1875. +    {
  1876. +        /* Write PPS */
  1877. +        if( h->param.b_repeat_pps_all_frames )
  1878. +        {
  1879. +            /* generate picture parameters */
  1880. +            x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
  1881. +            x264_pps_write( &h->out.bs, h->pps );
  1882. +            if( x264_nal_end( h ) )
  1883. +                return -1;
  1884. +            overhead += h->out.nal[h->out.i_nal-1].i_payload + NALU_OVERHEAD;
  1885. +        }
  1886. +    }
  1887.  
  1888.      /* write extra sei */
  1889.      for( int i = 0; i < h->fenc->extra_sei.num_payloads; i++ )
  1890. @@ -2693,7 +3386,7 @@ int     x264_encoder_encode( x264_t *h,
  1891.      if( h->fenc->extra_sei.sei_free && h->fenc->extra_sei.payloads )
  1892.          h->fenc->extra_sei.sei_free( h->fenc->extra_sei.payloads );
  1893.  
  1894. -    if( h->fenc->b_keyframe )
  1895. +    if( h->fenc->b_keyframe || h->sh.b_anchor)
  1896.      {
  1897.          if( h->param.b_repeat_headers && h->fenc->i_frame == 0 )
  1898.          {
  1899. @@ -2706,7 +3399,7 @@ int     x264_encoder_encode( x264_t *h,
  1900.              overhead += h->out.nal[h->out.i_nal-1].i_payload + NALU_OVERHEAD - (h->param.b_annexb && h->out.i_nal-1);
  1901.          }
  1902.  
  1903. -        if( h->fenc->i_type != X264_TYPE_IDR )
  1904. +        if( h->fenc->i_type != X264_TYPE_IDR && h->fenc->i_type != X264_TYPE_ANCHOR)
  1905.          {
  1906.              int time_to_recovery = h->param.i_open_gop ? 0 : X264_MIN( h->mb.i_mb_width - 1, h->param.i_keyint_max ) + h->param.i_bframe - 1;
  1907.              x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  1908. @@ -2715,15 +3408,6 @@ int     x264_encoder_encode( x264_t *h,
  1909.                  return -1;
  1910.              overhead += h->out.nal[h->out.i_nal-1].i_payload + NALU_OVERHEAD - (h->param.b_annexb && h->out.i_nal-1);
  1911.          }
  1912. -
  1913. -        if ( h->param.i_frame_packing >= 0 )
  1914. -        {
  1915. -            x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  1916. -            x264_sei_frame_packing_write( h, &h->out.bs );
  1917. -            if( x264_nal_end( h ) )
  1918. -                return -1;
  1919. -            overhead += h->out.nal[h->out.i_nal-1].i_payload + NALU_OVERHEAD - (h->param.b_annexb && h->out.i_nal-1);
  1920. -        }
  1921.      }
  1922.  
  1923.      /* generate sei pic timing */
  1924. @@ -2736,12 +3420,32 @@ int     x264_encoder_encode( x264_t *h,
  1925.          overhead += h->out.nal[h->out.i_nal-1].i_payload + NALU_OVERHEAD - (h->param.b_annexb && h->out.i_nal-1);
  1926.      }
  1927.  
  1928. -    if( h->fenc->b_keyframe && h->param.b_intra_refresh )
  1929. +    if (h->param.b_mvc) {
  1930. +        h->i_cpb_delay_pir_offset_dep = h->i_cpb_delay_pir_offset;
  1931. +    }
  1932. +    if( h->fenc->b_keyframe && h->param.b_intra_refresh ) {
  1933.          h->i_cpb_delay_pir_offset = h->fenc->i_cpb_delay;
  1934. +    }
  1935. +
  1936. +    if( h->fenc->b_keyframe || h->sh.b_anchor)
  1937. +    {
  1938. +        if ( h->param.i_frame_packing >= 0 )
  1939. +        {
  1940. +            x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  1941. +            x264_sei_frame_packing_write( h, &h->out.bs );
  1942. +            if( x264_nal_end( h ) )
  1943. +                return -1;
  1944. +            overhead += h->out.nal[h->out.i_nal-1].i_payload + NALU_OVERHEAD - (h->param.b_annexb && h->out.i_nal-1);
  1945. +        }
  1946. +    }
  1947.  
  1948.      /* Init the rate control */
  1949.      /* FIXME: Include slice header bit cost. */
  1950. +#ifdef __DEBUG
  1951. +    x264_log(h, X264_LOG_INFO, "[%4d]: ratecontrol_start\n", h->fenc->i_frame);
  1952. +#endif
  1953.      x264_ratecontrol_start( h, h->fenc->i_qpplus1, overhead*8 );
  1954. +
  1955.      i_global_qp = x264_ratecontrol_qp( h );
  1956.  
  1957.      pic_out->i_qpplus1 =
  1958. @@ -2752,12 +3456,17 @@ int     x264_encoder_encode( x264_t *h,
  1959.          x264_reference_build_list_optimal( h );
  1960.          x264_reference_check_reorder( h );
  1961.      }
  1962. +    else if ( h->b_dependent )
  1963. +    {
  1964. +        x264_reference_build_list_mvc( h );
  1965. +    }
  1966. +    log_ref_list( h );
  1967.  
  1968.      if( h->i_ref[0] )
  1969.          h->fdec->i_poc_l0ref0 = h->fref[0][0]->i_poc;
  1970.  
  1971.      /* ------------------------ Create slice header  ----------------------- */
  1972. -    x264_slice_init( h, i_nal_type, i_global_qp );
  1973. +    x264_slice_init( h, i_nal_type, i_global_qp, i_nal_ref_idc );
  1974.  
  1975.      /*------------------------- Weights -------------------------------------*/
  1976.      if( h->sh.i_type == SLICE_TYPE_B )
  1977. @@ -2769,30 +3478,58 @@ int     x264_encoder_encode( x264_t *h,
  1978.          h->i_frame_num++;
  1979.  
  1980.      /* Write frame */
  1981. -    h->i_threadslice_start = 0;
  1982. -    h->i_threadslice_end = h->mb.i_mb_height;
  1983. -    if( h->i_thread_frames > 1 )
  1984. -    {
  1985. +    if (!h->b_dependent) {
  1986. +      h->i_threadslice_start = 0;
  1987. +      h->i_threadslice_end = h->mb.i_mb_height;
  1988. +      if( h->i_thread_frames > 1 )
  1989. +      {
  1990.          x264_threadpool_run( h->threadpool, (void*)x264_slices_write, h );
  1991.          h->b_thread_active = 1;
  1992. -    }
  1993. -    else if( h->param.b_sliced_threads )
  1994. -    {
  1995. +      }
  1996. +      else if( h->param.b_sliced_threads )
  1997. +      {
  1998.          if( x264_threaded_slices_write( h ) )
  1999. -            return -1;
  2000. -    }
  2001. -    else
  2002. +          return -1;
  2003. +      }
  2004. +      else
  2005.          if( (intptr_t)x264_slices_write( h ) )
  2006. -            return -1;
  2007. +          return -1;
  2008. +    } else {
  2009. +      /* for dependent view(copy from upper) */
  2010. +      /* Write frame */
  2011. +      h->i_threadslice_start = 0;
  2012. +      h->i_threadslice_end = h->mb.i_mb_height;
  2013. +      
  2014. +      h->sh.b_svc_extension_flag = 1;
  2015. +      
  2016. +      if( h->i_thread_frames > 1 )
  2017. +      {
  2018. +        //  printf("Writing coded slice extension. (frame id: %d)\n", h->i_frame);
  2019. +        x264_threadpool_run( h->threadpool, (void*)x264_slices_write, h );
  2020. +        h->b_thread_active = 1;
  2021. +      }
  2022. +      else if( h->param.b_sliced_threads )
  2023. +      {
  2024. +        if( x264_threaded_slices_write( h ) )
  2025. +          return -1;
  2026. +      }
  2027. +      else
  2028. +      {
  2029. +        if( (intptr_t)x264_slices_write( h ) )
  2030. +          return -1;
  2031. +      }
  2032. +    }
  2033.  
  2034. -    return x264_encoder_frame_end( thread_oldest, thread_current, pp_nal, pi_nal, pic_out );
  2035. +    return x264_encoder_frame_end( thread_oldest, thread_current, thread_next_oldest, pp_nal, pi_nal, pic_out );
  2036.  }
  2037.  
  2038.  static int x264_encoder_frame_end( x264_t *h, x264_t *thread_current,
  2039. +                                   x264_t *thread_next,
  2040.                                     x264_nal_t **pp_nal, int *pi_nal,
  2041.                                     x264_picture_t *pic_out )
  2042.  {
  2043.      char psz_message[80];
  2044. +    x264_sps_t *sps = h->b_dependent ? h->subset_sps : h->sps;
  2045.  
  2046.      if( h->b_thread_active )
  2047.      {
  2048. @@ -2808,9 +3545,13 @@ static int x264_encoder_frame_end( x264_t *h, x264_t *thread_current,
  2049.  
  2050.      x264_emms();
  2051.      /* generate sei buffering period and insert it into place */
  2052. -    if( h->fenc->b_keyframe && h->sps->vui.b_nal_hrd_parameters_present )
  2053. +    if( (h->fenc->b_keyframe || h->fenc->i_type == X264_TYPE_ANCHOR || h->fenc->i_type == X264_TYPE_I) &&
  2054. +        sps->vui.b_nal_hrd_parameters_present )
  2055.      {
  2056.          x264_hrd_fullness( h );
  2057. +        if (h->param.b_mvc && !h->b_dependent) {
  2058. +            x264_hrd_copy_to_dependent(h, thread_next);
  2059. +        }
  2060.          x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  2061.          x264_sei_buffering_period_write( h, &h->out.bs );
  2062.          if( x264_nal_end( h ) )
  2063. @@ -2819,6 +3560,7 @@ static int x264_encoder_frame_end( x264_t *h, x264_t *thread_current,
  2064.          int idx = 0;
  2065.          while( h->out.nal[idx].i_type == NAL_AUD ||
  2066.                 h->out.nal[idx].i_type == NAL_SPS ||
  2067. +               h->out.nal[idx].i_type == NAL_SUBSET_SPS ||
  2068.                 h->out.nal[idx].i_type == NAL_PPS )
  2069.              idx++;
  2070.          x264_nal_t nal_tmp = h->out.nal[h->out.i_nal-1];
  2071. @@ -2837,9 +3579,9 @@ static int x264_encoder_frame_end( x264_t *h, x264_t *thread_current,
  2072.      pic_out->i_pts = h->fdec->i_pts;
  2073.      pic_out->i_dts = h->fdec->i_dts;
  2074.  
  2075. -    if( pic_out->i_pts < pic_out->i_dts )
  2076. -        x264_log( h, X264_LOG_WARNING, "invalid DTS: PTS is less than DTS\n" );
  2077. -
  2078. +    if( pic_out->i_pts < pic_out->i_dts ) {
  2079. +        x264_log( h, X264_LOG_WARNING, "invalid DTS: PTS(%lld) is less than DTS(%lld)\n", pic_out->i_pts, pic_out->i_dts );
  2080. +    }
  2081.      pic_out->img.i_csp = X264_CSP_NV12;
  2082.  #if HIGH_BIT_DEPTH
  2083.      pic_out->img.i_csp |= X264_CSP_HIGH_DEPTH;
  2084. @@ -2896,10 +3638,15 @@ static int x264_encoder_frame_end( x264_t *h, x264_t *thread_current,
  2085.      x264_thread_sync_stat( h, h->thread[0] );
  2086.  
  2087.      /* Slice stat */
  2088. -    h->stat.i_frame_count[h->sh.i_type]++;
  2089. -    h->stat.i_frame_size[h->sh.i_type] += frame_size;
  2090. -    h->stat.f_frame_qp[h->sh.i_type] += h->fdec->f_qp_avg_aq;
  2091. -
  2092. +    if (h->b_dependent) {
  2093. +        h->stat.i_frame_dep_count[h->sh.i_type]++;
  2094. +        h->stat.i_frame_dep_size[h->sh.i_type] += frame_size;
  2095. +        h->stat.f_frame_dep_qp[h->sh.i_type] += h->fdec->f_qp_avg_aq;
  2096. +    } else {
  2097. +        h->stat.i_frame_count[h->sh.i_type]++;
  2098. +        h->stat.i_frame_size[h->sh.i_type] += frame_size;
  2099. +        h->stat.f_frame_qp[h->sh.i_type] += h->fdec->f_qp_avg_aq;
  2100. +    }
  2101.      for( int i = 0; i < X264_MBTYPE_MAX; i++ )
  2102.          h->stat.i_mb_count[h->sh.i_type][i] += h->stat.frame.i_mb_count[i];
  2103.      for( int i = 0; i < X264_PARTTYPE_MAX; i++ )
  2104. @@ -3014,7 +3761,7 @@ static int x264_encoder_frame_end( x264_t *h, x264_t *thread_current,
  2105.              h->fref[0][i] = 0;
  2106.          }
  2107.  
  2108. -    if( h->param.psz_dump_yuv )
  2109. +    if( h->param.psz_dump_yuv[0] )
  2110.          x264_frame_dump( h );
  2111.      x264_emms();
  2112.  
  2113. @@ -3311,6 +4058,12 @@ void    x264_encoder_close  ( x264_t *h )
  2114.  
  2115.      /* rc */
  2116.      x264_ratecontrol_delete( h );
  2117. +    
  2118. +    if( h->param.psz_dump_yuv[1] )
  2119. +    {
  2120. +        free(h->param.psz_dump_yuv[1]);
  2121. +        h->param.psz_dump_yuv[1] = NULL;
  2122. +    }
  2123.  
  2124.      /* param */
  2125.      if( h->param.rc.psz_stat_out )
  2126. @@ -3380,13 +4133,20 @@ int x264_encoder_delayed_frames( x264_t *h )
  2127.      }
  2128.      for( int i = 0; h->frames.current[i]; i++ )
  2129.          delayed_frames++;
  2130. +
  2131.      x264_pthread_mutex_lock( &h->lookahead->ofbuf.mutex );
  2132.      x264_pthread_mutex_lock( &h->lookahead->ifbuf.mutex );
  2133.      x264_pthread_mutex_lock( &h->lookahead->next.mutex );
  2134. +    x264_pthread_mutex_lock( &h->lookahead->next_dependent.mutex );
  2135. +
  2136.      delayed_frames += h->lookahead->ifbuf.i_size + h->lookahead->next.i_size + h->lookahead->ofbuf.i_size;
  2137. +    delayed_frames += h->lookahead->next_dependent.i_size;
  2138. +
  2139. +    x264_pthread_mutex_unlock( &h->lookahead->next_dependent.mutex );
  2140.      x264_pthread_mutex_unlock( &h->lookahead->next.mutex );
  2141.      x264_pthread_mutex_unlock( &h->lookahead->ifbuf.mutex );
  2142.      x264_pthread_mutex_unlock( &h->lookahead->ofbuf.mutex );
  2143. +
  2144.      return delayed_frames;
  2145.  }
  2146.  
  2147. diff --git encoder/lookahead.c encoder/lookahead.c
  2148. index 7e04864..b53a200 100644
  2149. --- encoder/lookahead.c
  2150. +++ encoder/lookahead.c
  2151. @@ -39,9 +39,12 @@
  2152.  #include "common/common.h"
  2153.  #include "analyse.h"
  2154.  
  2155. +//#define __DEBUG
  2156. +
  2157.  static void x264_lookahead_shift( x264_sync_frame_list_t *dst, x264_sync_frame_list_t *src, int count )
  2158.  {
  2159.      int i = count;
  2160. +
  2161.      while( i-- )
  2162.      {
  2163.          assert( dst->i_size < dst->i_max_size );
  2164. @@ -64,20 +67,122 @@ static void x264_lookahead_update_last_nonb( x264_t *h, x264_frame_t *new_nonb )
  2165.      new_nonb->i_reference_count++;
  2166.  }
  2167.  
  2168. +static void x264_lookahead_update_last_nonb_dep( x264_t *h, x264_frame_t *new_nonb )
  2169. +{
  2170. +    if( h->lookahead->last_nonb_dependent )
  2171. +        x264_frame_push_unused( h, h->lookahead->last_nonb_dependent );
  2172. +    h->lookahead->last_nonb_dependent = new_nonb;
  2173. +    new_nonb->i_reference_count++;
  2174. +}
  2175. +
  2176.  #if HAVE_THREAD
  2177.  static void x264_lookahead_slicetype_decide( x264_t *h )
  2178.  {
  2179. -    x264_stack_align( x264_slicetype_decide, h );
  2180.  
  2181. +  static int frameNum = 0;
  2182. +    int b_mvc = h->param.b_mvc;
  2183. +
  2184. +  //  if (!h->param.b_mvc ||
  2185. +  //      (h->param.b_mvc && !(frameNum & 0x1))) {
  2186. +    x264_stack_align( x264_slicetype_decide, h );
  2187. +#ifdef __DEBUG
  2188. +    x264_log(h, X264_LOG_INFO, "[update last_nonb 0]: frame %d\n", h->lookahead->next.list[0]->i_frame);
  2189. +#endif
  2190.      x264_lookahead_update_last_nonb( h, h->lookahead->next.list[0] );
  2191. +    if (b_mvc) x264_lookahead_update_last_nonb_dep( h, h->lookahead->next_dependent.list[0] );
  2192. +    //  }
  2193. +
  2194. +    int shift = h->lookahead->next.list[0]->i_bframes + 1;
  2195.  
  2196.      x264_pthread_mutex_lock( &h->lookahead->ofbuf.mutex );
  2197. -    while( h->lookahead->ofbuf.i_size == h->lookahead->ofbuf.i_max_size )
  2198. +
  2199. +    if (!h->param.b_mvc) {
  2200. +      while( h->lookahead->ofbuf.i_size == h->lookahead->ofbuf.i_max_size ) {
  2201.          x264_pthread_cond_wait( &h->lookahead->ofbuf.cv_empty, &h->lookahead->ofbuf.mutex );
  2202. +      }
  2203. +    } else { // mvc case
  2204. +      while( h->lookahead->ofbuf.i_max_size - h->lookahead->ofbuf.i_size < (shift * 2)) {
  2205. +        x264_pthread_cond_wait( &h->lookahead->ofbuf.cv_empty, &h->lookahead->ofbuf.mutex );
  2206. +      }
  2207. +    }
  2208.  
  2209.      x264_pthread_mutex_lock( &h->lookahead->next.mutex );
  2210. -    x264_lookahead_shift( &h->lookahead->ofbuf, &h->lookahead->next, h->lookahead->next.list[0]->i_bframes + 1 );
  2211. +    x264_pthread_mutex_lock( &h->lookahead->next_dependent.mutex );
  2212. +
  2213. +    if (!h->param.b_mvc) {
  2214. +      x264_lookahead_shift( &h->lookahead->ofbuf, &h->lookahead->next, shift );
  2215. +    } else { // for MVC
  2216. +   for (int i = 0; i < shift; i++) {
  2217. +     int base_i_type = h->lookahead->next.list[0]->i_type;
  2218. +     for (int j = 0; j < X264_BFRAME_MAX + 2; j++) {
  2219. +       for (int k = 0; k < X264_BFRAME_MAX + 2; k++) {
  2220. +         h->lookahead->next_dependent.list[0]->i_cost_est[j][k] = h->lookahead->next.list[0]->i_cost_est[j][k];
  2221. +         h->lookahead->next_dependent.list[0]->i_cost_est_aq[j][k] = h->lookahead->next.list[0]->i_cost_est_aq[j][k];
  2222. +
  2223. +         h->lookahead->next_dependent.list[0]->i_cpb_duration = h->lookahead->next.list[0]->i_cpb_duration;
  2224. +         h->lookahead->next_dependent.list[0]->i_cpb_delay = h->lookahead->next.list[0]->i_cpb_delay;
  2225. +              h->lookahead->next_dependent.list[0]->i_dpb_output_delay = h->lookahead->next.list[0]->i_dpb_output_delay;
  2226. +        
  2227. +#ifdef __DEBUG
  2228. +         if ( h->lookahead->next.list[0]->i_cost_est[j][k] >= 0) {
  2229. +       x264_log(h, X264_LOG_INFO, "i_cost_est[%d][%d] = %d\n", j, k, h->lookahead->next.list[0]->i_cost_est[j][k]);
  2230. +         }
  2231. +#endif
  2232. +       }
  2233. +     }
  2234. +    
  2235. +#ifdef __DEBUG
  2236. +     x264_log(h, X264_LOG_INFO, "base_i_type %d\n", base_i_type);
  2237. +#endif
  2238. +    
  2239. +     int dep_i_type;
  2240. +          int b_anchor = 0;
  2241. +     switch(base_i_type) {
  2242. +     case X264_TYPE_I :
  2243. +     case X264_TYPE_IDR :
  2244. +     case X264_TYPE_KEYFRAME :
  2245. +       dep_i_type = X264_TYPE_ANCHOR;
  2246. +            b_anchor = 1;
  2247. +       break;
  2248. +     case X264_TYPE_P :
  2249. +       dep_i_type = X264_TYPE_P;
  2250. +       break;
  2251. +     case X264_TYPE_B :
  2252. +       dep_i_type = X264_TYPE_B;
  2253. +       break;
  2254. +     case X264_TYPE_BREF :
  2255. +       dep_i_type = X264_TYPE_BREF;
  2256. +       break;
  2257. +     default :
  2258. +       dep_i_type = X264_TYPE_P;
  2259. +       break;
  2260. +     }
  2261. +     h->lookahead->next_dependent.list[0]->i_type = dep_i_type;
  2262. +          //h->lookahead->next_dependent.list[0]->b_anchor = b_anchor;
  2263. +    
  2264. +     x264_lookahead_shift( &h->lookahead->ofbuf, &h->lookahead->next, 1 );
  2265. +    
  2266. +     //x264_log(h, X264_LOG_INFO, "lookahead_shift [next] i_frame %d\n", h->lookahead->next.i_size);
  2267. +
  2268. +#if 0
  2269. +     while( h->lookahead->ofbuf.i_size == h->lookahead->ofbuf.i_max_size ) {
  2270. +       x264_pthread_cond_wait( &h->lookahead->ofbuf.cv_empty, &h->lookahead->ofbuf.mutex );
  2271. +     }
  2272. +#endif
  2273. +
  2274. +    
  2275. +     x264_lookahead_shift( &h->lookahead->ofbuf, &h->lookahead->next_dependent, 1 );
  2276. +     //x264_log(h, X264_LOG_INFO, "lookahead_shift [next_dep] i_frame %d\n", h->lookahead->next_dependent.i_size);
  2277. +
  2278. +     //x264_log(h, X264_LOG_INFO, "ofbuf size %d\n", h->lookahead->ofbuf.i_size);
  2279. +
  2280. +   }
  2281. +    }
  2282. +
  2283.      x264_pthread_mutex_unlock( &h->lookahead->next.mutex );
  2284. +    x264_pthread_mutex_unlock( &h->lookahead->next_dependent.mutex );
  2285. +
  2286. +    frameNum++;
  2287.  
  2288.      /* For MB-tree and VBV lookahead, we have to perform propagation analysis on I-frames too. */
  2289.      if( h->lookahead->b_analyse_keyframe && IS_X264_TYPE_I( h->lookahead->last_nonb->i_type ) )
  2290. @@ -89,6 +194,12 @@ static void x264_lookahead_slicetype_decide( x264_t *h )
  2291.  static void x264_lookahead_thread( x264_t *h )
  2292.  {
  2293.      int shift;
  2294. +    int shift_dependent;
  2295. +
  2296. +    int b_mvc = h->param.b_mvc;
  2297. +
  2298. +    x264_log( h, X264_LOG_INFO, "b_mvc %d\n", b_mvc);
  2299. +
  2300.  #if HAVE_MMX
  2301.      if( h->param.cpu&X264_CPU_SSE_MISALIGN )
  2302.          x264_cpu_mask_misalign_sse();
  2303. @@ -97,28 +208,100 @@ static void x264_lookahead_thread( x264_t *h )
  2304.      {
  2305.          x264_pthread_mutex_lock( &h->lookahead->ifbuf.mutex );
  2306.          x264_pthread_mutex_lock( &h->lookahead->next.mutex );
  2307. -        shift = X264_MIN( h->lookahead->next.i_max_size - h->lookahead->next.i_size, h->lookahead->ifbuf.i_size );
  2308. -        x264_lookahead_shift( &h->lookahead->next, &h->lookahead->ifbuf, shift );
  2309. +        x264_pthread_mutex_lock( &h->lookahead->next_dependent.mutex );
  2310. +
  2311. +   if (!b_mvc) {
  2312. +     shift = X264_MIN( h->lookahead->next.i_max_size - h->lookahead->next.i_size, h->lookahead->ifbuf.i_size );
  2313. +          // base and dependent will be divided to the other buffer
  2314. +          x264_lookahead_shift( &h->lookahead->next, &h->lookahead->ifbuf, shift);
  2315. +   } else {
  2316. +     shift = X264_MIN( h->lookahead->next.i_max_size - h->lookahead->next.i_size, h->lookahead->ifbuf.i_size / 2);
  2317. +     shift_dependent = X264_MIN( h->lookahead->next_dependent.i_max_size - h->lookahead->next_dependent.i_size,
  2318. +                     h->lookahead->ifbuf.i_size / 2);
  2319. +          shift = X264_MIN(shift, shift_dependent);
  2320. +          shift_dependent = shift;
  2321. +#ifdef __DEBUG
  2322. +     if (h->lookahead->ifbuf.i_size > 1) {
  2323. +       x264_log( h, X264_LOG_INFO, "i_size %d\n", h->lookahead->ifbuf.i_size);
  2324. +     }
  2325. +#endif
  2326. +#ifdef __DEBUG
  2327. +     if ((shift > 0) || (shift_dependent > 0)) {
  2328. +       x264_log( h, X264_LOG_INFO, "shift %d shift_dep %d\n", shift, shift_dependent);
  2329. +     }
  2330. +#endif
  2331. +          // base and dependent will be divided to the other buffer
  2332. +          while (shift > 0 || shift_dependent > 0) {
  2333. +              if (shift) {
  2334. +                  x264_lookahead_shift( &h->lookahead->next, &h->lookahead->ifbuf, 1);
  2335. +                  shift--;
  2336. +              }
  2337. +              if (shift_dependent) {
  2338. +                  x264_lookahead_shift( &h->lookahead->next_dependent, &h->lookahead->ifbuf, 1 );
  2339. +                  shift_dependent--;
  2340. +              }
  2341. +          }
  2342. +   }
  2343. +
  2344. +        x264_pthread_mutex_unlock( &h->lookahead->next_dependent.mutex );
  2345.          x264_pthread_mutex_unlock( &h->lookahead->next.mutex );
  2346. -        if( h->lookahead->next.i_size <= h->lookahead->i_slicetype_length + h->param.b_vfr_input )
  2347. +
  2348. +
  2349. +#ifdef __DEBUG____
  2350. +
  2351. +   if (h->lookahead->ifbuf.i_size > 0) {
  2352. +     x264_log( h, X264_LOG_INFO, "ibuf %d ", h->lookahead->ifbuf.i_size);
  2353. +     x264_log( h, X264_LOG_INFO, "next.i_size %d next_dep.i_size %d \n", h->lookahead->next.i_size,
  2354. +           h->lookahead->next_dependent.i_size);
  2355. +       x264_log( h, X264_LOG_INFO, "slice_type_length %d b_vfr %d", h->lookahead->i_slicetype_length,
  2356. +             h->param.b_vfr_input);
  2357. +
  2358. +   }
  2359. +#endif
  2360. +
  2361. +        if ( (!b_mvc && (h->lookahead->next.i_size <= h->lookahead->i_slicetype_length + h->param.b_vfr_input)) ||
  2362. +        (b_mvc && ((h->lookahead->next.i_size <= h->lookahead->i_slicetype_length + h->param.b_vfr_input )
  2363. +           || (h->lookahead->next_dependent.i_size <= h->lookahead->i_slicetype_length + h->param.b_vfr_input) ) ) )
  2364.          {
  2365. -            while( !h->lookahead->ifbuf.i_size && !h->lookahead->b_exit_thread )
  2366. -                x264_pthread_cond_wait( &h->lookahead->ifbuf.cv_fill, &h->lookahead->ifbuf.mutex );
  2367. +            while( !h->lookahead->ifbuf.i_size && !h->lookahead->b_exit_thread ) {
  2368. +         x264_pthread_cond_wait( &h->lookahead->ifbuf.cv_fill, &h->lookahead->ifbuf.mutex );
  2369. +       }
  2370.              x264_pthread_mutex_unlock( &h->lookahead->ifbuf.mutex );
  2371.          }
  2372.          else
  2373.          {
  2374.              x264_pthread_mutex_unlock( &h->lookahead->ifbuf.mutex );
  2375. +       //      x264_log( h, X264_LOG_INFO, "buffer is filled enough\n");
  2376. +       // for base view, slice_type is decided here
  2377. +
  2378.              x264_lookahead_slicetype_decide( h );
  2379. +
  2380.          }
  2381.      }   /* end of input frames */
  2382. +
  2383. +
  2384.      x264_pthread_mutex_lock( &h->lookahead->ifbuf.mutex );
  2385.      x264_pthread_mutex_lock( &h->lookahead->next.mutex );
  2386. -    x264_lookahead_shift( &h->lookahead->next, &h->lookahead->ifbuf, h->lookahead->ifbuf.i_size );
  2387. +    x264_pthread_mutex_lock( &h->lookahead->next_dependent.mutex );
  2388. +
  2389. +    if (!h->param.b_mvc) { // not mvc
  2390. +      x264_lookahead_shift( &h->lookahead->next, &h->lookahead->ifbuf, h->lookahead->ifbuf.i_size );
  2391. +    } else { // mvc
  2392. +      for (int i = 0; i < (h->lookahead->ifbuf.i_size / 2); i++) {
  2393. +   x264_lookahead_shift( &h->lookahead->next, &h->lookahead->ifbuf, 1);
  2394. +   x264_lookahead_shift( &h->lookahead->next_dependent, &h->lookahead->ifbuf, 1);
  2395. +      }
  2396. +    }
  2397. +
  2398. +    x264_pthread_mutex_unlock( &h->lookahead->next_dependent.mutex );
  2399.      x264_pthread_mutex_unlock( &h->lookahead->next.mutex );
  2400.      x264_pthread_mutex_unlock( &h->lookahead->ifbuf.mutex );
  2401. -    while( h->lookahead->next.i_size )
  2402. +
  2403. +
  2404. +    while( h->lookahead->next.i_size ) {
  2405.          x264_lookahead_slicetype_decide( h );
  2406. +    }
  2407. +
  2408.      x264_pthread_mutex_lock( &h->lookahead->ofbuf.mutex );
  2409.      h->lookahead->b_thread_active = 0;
  2410.      x264_pthread_cond_broadcast( &h->lookahead->ofbuf.cv_fill );
  2411. @@ -141,9 +324,13 @@ int x264_lookahead_init( x264_t *h, int i_slicetype_length )
  2412.      /* init frame lists */
  2413.      if( x264_sync_frame_list_init( &look->ifbuf, h->param.i_sync_lookahead+3 ) ||
  2414.          x264_sync_frame_list_init( &look->next, h->frames.i_delay+3 ) ||
  2415. -        x264_sync_frame_list_init( &look->ofbuf, h->frames.i_delay+3 ) )
  2416. +        x264_sync_frame_list_init( &look->ofbuf, (h->frames.i_delay+3) * (h->param.b_mvc ? 2 : 1) ) )
  2417.          goto fail;
  2418.  
  2419. +    /* for MVC lookahead */
  2420. +    if (x264_sync_frame_list_init( &look->next_dependent, h->frames.i_delay + 3))
  2421. +      goto fail;
  2422. +
  2423.      if( !h->param.i_sync_lookahead )
  2424.          return 0;
  2425.  
  2426. @@ -180,25 +367,53 @@ void x264_lookahead_delete( x264_t *h )
  2427.      }
  2428.      x264_sync_frame_list_delete( &h->lookahead->ifbuf );
  2429.      x264_sync_frame_list_delete( &h->lookahead->next );
  2430. +    x264_sync_frame_list_delete( &h->lookahead->next_dependent);
  2431. +
  2432.      if( h->lookahead->last_nonb )
  2433.          x264_frame_push_unused( h, h->lookahead->last_nonb );
  2434. +    if( h->param.b_mvc && h->lookahead->last_nonb_dependent )
  2435. +        x264_frame_push_unused( h, h->lookahead->last_nonb_dependent );
  2436.      x264_sync_frame_list_delete( &h->lookahead->ofbuf );
  2437.      x264_free( h->lookahead );
  2438.  }
  2439.  
  2440.  void x264_lookahead_put_frame( x264_t *h, x264_frame_t *frame )
  2441.  {
  2442. -    if( h->param.i_sync_lookahead )
  2443. -        x264_sync_frame_list_push( &h->lookahead->ifbuf, frame );
  2444. -    else
  2445. +    static int frame_num = 0;
  2446. +    if( h->param.i_sync_lookahead ) { // if lookahead is enabled, base and dependent is divided at the next function
  2447. +      x264_sync_frame_list_push( &h->lookahead->ifbuf, frame );
  2448. +    } else { // if lookahead is disabled, base and dependent is divided here
  2449. +
  2450. +      if (!h->param.b_mvc) {
  2451. +        x264_sync_frame_list_push( &h->lookahead->next, frame );
  2452. +      } else { // mvc case
  2453. +   if (frame_num & 0x1) {
  2454. +     x264_sync_frame_list_push( &h->lookahead->next_dependent, frame );
  2455. +   } else {
  2456. +     x264_sync_frame_list_push( &h->lookahead->next, frame );
  2457. +   }
  2458. +      }
  2459. +
  2460. +      /*
  2461. +      if (h->param.b_mvc && ((frame_num & 0x1) != 0)) {
  2462. +        x264_sync_frame_list_push( &h->lookahead->next_dependent, frame );
  2463. +      } else {
  2464.          x264_sync_frame_list_push( &h->lookahead->next, frame );
  2465. +      }
  2466. +      */
  2467. +    }
  2468. +    frame_num++;
  2469. +
  2470.  }
  2471.  
  2472.  int x264_lookahead_is_empty( x264_t *h )
  2473.  {
  2474.      x264_pthread_mutex_lock( &h->lookahead->ofbuf.mutex );
  2475.      x264_pthread_mutex_lock( &h->lookahead->next.mutex );
  2476. -    int b_empty = !h->lookahead->next.i_size && !h->lookahead->ofbuf.i_size;
  2477. +    x264_pthread_mutex_lock( &h->lookahead->next_dependent.mutex );
  2478. +    //    int b_empty = !h->lookahead->next.i_size && !h->lookahead->ofbuf.i_size;
  2479. +    int b_empty = !h->lookahead->next.i_size && !h->lookahead->ofbuf.i_size && !h->lookahead->next_dependent.i_size;
  2480. +    x264_pthread_mutex_unlock( &h->lookahead->next_dependent.mutex );
  2481.      x264_pthread_mutex_unlock( &h->lookahead->next.mutex );
  2482.      x264_pthread_mutex_unlock( &h->lookahead->ofbuf.mutex );
  2483.      return b_empty;
  2484. @@ -206,26 +421,64 @@ int x264_lookahead_is_empty( x264_t *h )
  2485.  
  2486.  static void x264_lookahead_encoder_shift( x264_t *h )
  2487.  {
  2488. +#ifdef _DEBUG
  2489. +  x264_log(h, X264_LOG_INFO, "encoder_shift ofbuf.i_size %d\n", h->lookahead->ofbuf.i_size);
  2490. +#endif
  2491. +
  2492.      if( !h->lookahead->ofbuf.i_size )
  2493.          return;
  2494. -    int i_frames = h->lookahead->ofbuf.list[0]->i_bframes + 1;
  2495. +
  2496. +    int i_frames;
  2497. +    if (!h->param.b_mvc) {
  2498. +      i_frames = h->lookahead->ofbuf.list[0]->i_bframes + 1;
  2499. +    } else {
  2500. +      i_frames = (h->lookahead->ofbuf.list[0]->i_bframes + 1) * 2;
  2501. +    }
  2502. +
  2503. +#ifdef _DEBUG
  2504. +    x264_log(h, X264_LOG_INFO, "encoder_shift i_frames %d\n", i_frames);
  2505. +#endif
  2506. +
  2507.      while( i_frames-- )
  2508.      {
  2509.          x264_frame_push( h->frames.current, x264_frame_shift( h->lookahead->ofbuf.list ) );
  2510.          h->lookahead->ofbuf.i_size--;
  2511.      }
  2512.      x264_pthread_cond_broadcast( &h->lookahead->ofbuf.cv_empty );
  2513. +
  2514.  }
  2515.  
  2516.  void x264_lookahead_get_frames( x264_t *h )
  2517.  {
  2518. +  static int frameNum = 0;
  2519. +
  2520.      if( h->param.i_sync_lookahead )
  2521.      {   /* We have a lookahead thread, so get frames from there */
  2522.          x264_pthread_mutex_lock( &h->lookahead->ofbuf.mutex );
  2523. -        while( !h->lookahead->ofbuf.i_size && h->lookahead->b_thread_active )
  2524. +
  2525. +   if (!h->param.b_mvc) {
  2526. +     while( !h->lookahead->ofbuf.i_size && h->lookahead->b_thread_active ) {
  2527.              x264_pthread_cond_wait( &h->lookahead->ofbuf.cv_fill, &h->lookahead->ofbuf.mutex );
  2528. -        x264_lookahead_encoder_shift( h );
  2529. +     }
  2530. +    
  2531. +     x264_lookahead_encoder_shift( h );
  2532. +   } else { // mvc case
  2533. +
  2534. +     if ((h->lookahead->next.i_size + h->lookahead->next_dependent.i_size
  2535. +          + h->lookahead->ifbuf.i_size + h->lookahead->ofbuf.i_size) >= 2) {
  2536. +
  2537. +       while( (h->lookahead->ofbuf.i_size < 2) && h->lookahead->b_thread_active ) {
  2538. +         x264_pthread_cond_wait( &h->lookahead->ofbuf.cv_fill, &h->lookahead->ofbuf.mutex );
  2539. +       }
  2540. +
  2541. +       x264_lookahead_encoder_shift( h );
  2542. +     } else { // put frame is only 1. wait for next put frame
  2543. +       return;
  2544. +     }
  2545. +   }
  2546.          x264_pthread_mutex_unlock( &h->lookahead->ofbuf.mutex );
  2547. +
  2548. +   frameNum++;
  2549.      }
  2550.      else
  2551.      {   /* We are not running a lookahead thread, so perform all the slicetype decide on the fly */
  2552. @@ -233,14 +486,149 @@ void x264_lookahead_get_frames( x264_t *h )
  2553.          if( h->frames.current[0] || !h->lookahead->next.i_size )
  2554.              return;
  2555.  
  2556. -        x264_stack_align( x264_slicetype_decide, h );
  2557. -        x264_lookahead_update_last_nonb( h, h->lookahead->next.list[0] );
  2558. -        x264_lookahead_shift( &h->lookahead->ofbuf, &h->lookahead->next, h->lookahead->next.list[0]->i_bframes + 1 );
  2559. +   if (h->param.b_mvc && !h->lookahead->next_dependent.i_size) {
  2560. +     return;
  2561. +   }
  2562. +
  2563. +   int b_frame_pair_exists = 0;
  2564. +   if ((h->lookahead->next.i_size == h->lookahead->next_dependent.i_size) && h->lookahead->next.i_size && h->lookahead->next_dependent.i_size) {
  2565. +     b_frame_pair_exists = 1;
  2566. +   }
  2567. +   //  x264_log(h, X264_LOG_INFO, "lookahead_shift [next] i_frame %d\n", h->lookahead->next.i_size);
  2568. +   //  x264_log(h, X264_LOG_INFO, "lookahead_shift [next_dep] i_frame %d\n", h->lookahead->next_dependent.i_size);
  2569. +
  2570. +   //x264_log(h, X264_LOG_INFO, "i_bframes %d\n",  h->lookahead->next.list[0]->i_bframes);
  2571. +   //x264_log(h, X264_LOG_INFO, "i_reference_count %d\n",  h->lookahead->next.list[0]->i_reference_count);
  2572. +   //x264_log(h, X264_LOG_INFO, "frameNum %d\n",  frameNum);
  2573. +
  2574. +   if (!h->param.b_mvc) {
  2575. +     x264_stack_align( x264_slicetype_decide, h );
  2576. +#ifdef __DEBUG
  2577. +            x264_log(h, X264_LOG_INFO, "[update last_nonb 1]: frame %d\n", h->lookahead->next.list[0]->i_frame);
  2578. +#endif
  2579. +     x264_lookahead_update_last_nonb( h, h->lookahead->next.list[0] );
  2580. +   } else { // mvc case
  2581. +     //      if (!(frameNum & 0x1)) { // if even frame, slicetype_decide is executed
  2582. +     if (b_frame_pair_exists) {
  2583. +       //      x264_log(h, X264_LOG_INFO, "slicetype_decide\n");
  2584. +       x264_stack_align( x264_slicetype_decide, h );
  2585. +
  2586. +#ifdef _DEBUG
  2587. +       if ( h->lookahead->next.list[0] ) {
  2588. +         x264_log(h, X264_LOG_INFO, "[0]i_frame %d\n",  h->lookahead->next.list[0]->i_frame);
  2589. +       }
  2590. +       if ( h->lookahead->next.list[1] ) {
  2591. +         x264_log(h, X264_LOG_INFO, "[1]i_frame %d\n",  h->lookahead->next.list[1]->i_frame);
  2592. +       }
  2593. +       if ( h->lookahead->next.list[2] ) {
  2594. +         x264_log(h, X264_LOG_INFO, "[2]i_frame %d\n",  h->lookahead->next.list[2]->i_frame);
  2595. +       }
  2596. +
  2597. +       if ( h->lookahead->next_dependent.list[0] ) {
  2598. +         x264_log(h, X264_LOG_INFO, "dep[0]i_frame %d\n",  h->lookahead->next_dependent.list[0]->i_frame);
  2599. +       }
  2600. +       if ( h->lookahead->next_dependent.list[1] ) {
  2601. +         x264_log(h, X264_LOG_INFO, "dep[1]i_frame %d\n",  h->lookahead->next_dependent.list[1]->i_frame);
  2602. +       }
  2603. +       if ( h->lookahead->next_dependent.list[2] ) {
  2604. +         x264_log(h, X264_LOG_INFO, "dep[2]i_frame %d\n",  h->lookahead->next_dependent.list[2]->i_frame);
  2605. +       }
  2606. +#endif
  2607. +
  2608. +#ifdef __DEBUG
  2609. +            x264_log(h, X264_LOG_INFO, "[update last_nonb 2]: frame %d\n", h->lookahead->next.list[0]->i_frame);
  2610. +#endif
  2611. +       x264_lookahead_update_last_nonb( h, h->lookahead->next.list[0] );
  2612. +       x264_lookahead_update_last_nonb_dep( h, h->lookahead->next_dependent.list[0] );
  2613. +     }
  2614. +   }
  2615. +
  2616. +   int shift = h->lookahead->next.list[0]->i_bframes + 1;
  2617. +  
  2618. +   if (!h->param.b_mvc) {
  2619. +     x264_lookahead_shift( &h->lookahead->ofbuf, &h->lookahead->next, shift );
  2620. +   } else { // for MVC
  2621. +     //      if (!(frameNum & 0x1)) { // if even frame, next buf data is moved to the ofbuf
  2622. +     if (b_frame_pair_exists) {
  2623. +
  2624. +       // make cost and slice_type for dependent view
  2625. +       for (int i = 0; i < shift; i++) {
  2626. +         int base_i_type = h->lookahead->next.list[0]->i_type;
  2627. +         for (int j = 0; j < X264_BFRAME_MAX + 2; j++) {
  2628. +       for (int k = 0; k < X264_BFRAME_MAX + 2; k++) {
  2629. +         h->lookahead->next_dependent.list[0]->i_cost_est[j][k] = h->lookahead->next.list[0]->i_cost_est[j][k];
  2630. +         h->lookahead->next_dependent.list[0]->i_cost_est_aq[j][k] = h->lookahead->next.list[0]->i_cost_est_aq[j][k];
  2631. +        
  2632. +         h->lookahead->next_dependent.list[0]->i_cpb_duration = h->lookahead->next.list[0]->i_cpb_duration;         
  2633. +
  2634. +#ifdef __DEBUG
  2635. +         if ( h->lookahead->next.list[0]->i_cost_est[j][k] >= 0) {
  2636. +           x264_log(h, X264_LOG_INFO, "i_cost_est[%d][%d] = %d\n", j, k, h->lookahead->next.list[0]->i_cost_est[j][k]);
  2637. +         }
  2638. +#endif
  2639. +       }
  2640. +         }
  2641. +        
  2642. +#ifdef __DEBUG
  2643. +         x264_log(h, X264_LOG_INFO, "base_i_type %d\n", base_i_type);
  2644. +#endif
  2645. +        
  2646. +         int dep_i_type;
  2647. +              int b_anchor = 0;
  2648. +         switch(base_i_type) {
  2649. +         case X264_TYPE_I :
  2650. +         case X264_TYPE_IDR :
  2651. +         case X264_TYPE_KEYFRAME :
  2652. +       dep_i_type = X264_TYPE_ANCHOR;
  2653. +                b_anchor = 1;
  2654. +       break;
  2655. +         case X264_TYPE_P :
  2656. +       dep_i_type = X264_TYPE_P;
  2657. +       break;
  2658. +         case X264_TYPE_B :
  2659. +       dep_i_type = X264_TYPE_B;
  2660. +       break;
  2661. +         case X264_TYPE_BREF :
  2662. +       dep_i_type = X264_TYPE_BREF;
  2663. +       break;
  2664. +         default :
  2665. +       dep_i_type = X264_TYPE_P;
  2666. +       break;
  2667. +         }
  2668. +         h->lookahead->next_dependent.list[0]->i_type = dep_i_type;
  2669. +              //h->lookahead->next_dependent.list[0]->b_anchor = b_anchor;
  2670. +        
  2671. +
  2672. +         x264_lookahead_shift( &h->lookahead->ofbuf, &h->lookahead->next, 1 );
  2673. +         x264_lookahead_shift( &h->lookahead->ofbuf, &h->lookahead->next_dependent, 1 );
  2674. +
  2675. +#ifdef _DEBUG
  2676. +         x264_log(h, X264_LOG_INFO, "lookahead_shift [next] i_frame %d\n", h->lookahead->next.i_size);
  2677. +         x264_log(h, X264_LOG_INFO, "lookahead_shift [next_dep] i_frame %d\n", h->lookahead->next_dependent.i_size);
  2678. +         x264_log(h, X264_LOG_INFO, "ofbuf_suze %d\n", h->lookahead->ofbuf.i_size);
  2679. +#endif
  2680. +       }
  2681. +     }
  2682. +   } // end of MVC case
  2683. +  
  2684.  
  2685.          /* For MB-tree and VBV lookahead, we have to perform propagation analysis on I-frames too. */
  2686. -        if( h->lookahead->b_analyse_keyframe && IS_X264_TYPE_I( h->lookahead->last_nonb->i_type ) )
  2687. +
  2688. +   if (!h->param.b_mvc) {
  2689. +     if( h->lookahead->b_analyse_keyframe && IS_X264_TYPE_I( h->lookahead->last_nonb->i_type ) )
  2690.              x264_stack_align( x264_slicetype_analyse, h, 1 );
  2691.  
  2692. -        x264_lookahead_encoder_shift( h );
  2693. +     x264_lookahead_encoder_shift( h );
  2694. +   } else {
  2695. +     //      if (!(frameNum & 0x1)) {
  2696. +     if (b_frame_pair_exists) {
  2697. +       if( h->lookahead->b_analyse_keyframe && IS_X264_TYPE_I( h->lookahead->last_nonb->i_type ) )
  2698. +         x264_stack_align( x264_slicetype_analyse, h, 1 );
  2699. +
  2700. +       x264_lookahead_encoder_shift( h );
  2701. +     }
  2702. +   }
  2703. +
  2704. +   frameNum++;
  2705.      }
  2706.  }
  2707. diff --git encoder/ratecontrol.c encoder/ratecontrol.c
  2708. index 3abd198..de3e602 100644
  2709. --- encoder/ratecontrol.c
  2710. +++ encoder/ratecontrol.c
  2711. @@ -7,7 +7,7 @@
  2712.   *          Michael Niedermayer <michaelni@gmx.at>
  2713.   *          Gabriel Bouvigne <gabriel.bouvigne@joost.com>
  2714.   *          Jason Garrett-Glaser <darkshikari@gmail.com>
  2715. - *          M蚣s Rullg蚌d <mru@mru.ath.cx>
  2716. + *          M・スns Rullg・スrd <mru@mru.ath.cx>
  2717.   *
  2718.   * This program is free software; you can redistribute it and/or modify
  2719.   * it under the terms of the GNU General Public License as published by
  2720. @@ -30,6 +30,10 @@
  2721.  #define _ISOC99_SOURCE
  2722.  #undef NDEBUG // always check asserts, the speed effect is far too small to disable them
  2723.  
  2724. +//#define _DEBUG
  2725. +//#define __DEBUG
  2726. +//#define __RC_DEBUG
  2727. +
  2728.  #include "common/common.h"
  2729.  #include "ratecontrol.h"
  2730.  #include "me.h"
  2731. @@ -37,6 +41,7 @@
  2732.  typedef struct
  2733.  {
  2734.      int pict_type;
  2735. +    int b_anchor;
  2736.      int frame_type;
  2737.      int kept_as_ref;
  2738.      double qscale;
  2739. @@ -246,6 +251,18 @@ static NOINLINE uint32_t x264_ac_energy_mb( x264_t *h, int mb_x, int mb_y, x264_
  2740.      return var;
  2741.  }
  2742.  
  2743. +static ALWAYS_INLINE int get_view_num( x264_t *h )
  2744. +{
  2745. +    return h->param.b_mvc ? 2 : 1;
  2746. +    //return 1;
  2747. +}
  2748. +
  2749. +static ALWAYS_INLINE int get_view_id( x264_t *h )
  2750. +{
  2751. +    return h->param.b_mvc ? (h->fenc ? h->fenc->i_frame & 1 : 0) : 0;
  2752. +    //return 0;
  2753. +}
  2754. +
  2755.  void x264_adaptive_quant_frame( x264_t *h, x264_frame_t *frame, float *quant_offsets )
  2756.  {
  2757.      /* constants chosen to result in approximately the same overall bitrate as without AQ.
  2758. @@ -353,7 +370,7 @@ void x264_adaptive_quant_frame( x264_t *h, x264_frame_t *frame, float *quant_off
  2759.  
  2760.  int x264_macroblock_tree_read( x264_t *h, x264_frame_t *frame, float *quant_offsets )
  2761.  {
  2762. -    x264_ratecontrol_t *rc = h->rc;
  2763. +    x264_ratecontrol_t *rc = h->rc_mvc[get_view_id(h)];
  2764.      uint8_t i_type_actual = rc->entry[frame->i_frame].pict_type;
  2765.  
  2766.      if( rc->entry[frame->i_frame].kept_as_ref )
  2767. @@ -396,11 +413,14 @@ fail:
  2768.  
  2769.  int x264_reference_build_list_optimal( x264_t *h )
  2770.  {
  2771. -    ratecontrol_entry_t *rce = h->rc->rce;
  2772. +    ratecontrol_entry_t *rce = h->rc_mvc[get_view_id(h)]->rce;
  2773.      x264_frame_t *frames[16];
  2774.      x264_weight_t weights[16][3];
  2775.      int refcount[16];
  2776.  
  2777. +    static int called = 0;
  2778. +    x264_log( h, X264_LOG_INFO, "x264_reference_build_list_optimal() has called %d time(s).\n", ++called);
  2779. +    
  2780.      if( rce->refs != h->i_ref[0] )
  2781.          return -1;
  2782.  
  2783. @@ -431,6 +451,114 @@ int x264_reference_build_list_optimal( x264_t *h )
  2784.      return 0;
  2785.  }
  2786.  
  2787. +static int compare_p_frame(const void *a, const void *b)
  2788. +{
  2789. +    return (*(x264_frame_t **)b)->i_frame - (*(x264_frame_t **)a)->i_frame;
  2790. +}
  2791. +
  2792. +static int compare_b_frame_l0(const void *a, const void *b)
  2793. +{
  2794. +     return (*(x264_frame_t **)b)->i_poc - (*(x264_frame_t **)a)->i_poc;
  2795. +}
  2796. +
  2797. +static int compare_b_frame_l1(const void *a, const void *b)
  2798. +{
  2799. +    return (*(x264_frame_t **)a)->i_poc - (*(x264_frame_t **)b)->i_poc;
  2800. +}
  2801. +
  2802. +static void x264_reference_build_list_b( x264_t *h, int l, int (*compare)(const void *, const void *))
  2803. +{
  2804. +    qsort( h->fref[l], h->i_ref[l], sizeof(x264_frame_t *), compare );
  2805. +    for( int i = 0; i < h->i_ref[l]; i++ )
  2806. +    {
  2807. +        if( (*compare)(&h->fref[l][i], &h->fenc) < 0 )
  2808. +        {
  2809. +            x264_frame_t *tmp = h->fref[l][i];
  2810. +            for( int j = i + 1; j < h->i_ref[l] - i; j++)
  2811. +                h->fref[l][j - 1] = h->fref[l][j];
  2812. +            h->fref[l][h->i_ref[l] - i] = tmp;
  2813. +        }
  2814. +        else
  2815. +            break;
  2816. +    }
  2817. +}
  2818. +
  2819. +int x264_reference_build_list_mvc( x264_t *h )
  2820. +{
  2821. +    for (int i = 0; i < h->i_ref[0]; ++i) {
  2822. +        //x264_log( NULL, X264_LOG_INFO, "x264_reference_build_list_mvc(): %d.\n", h->fref[0][0]->i_frame );
  2823. +    }
  2824. +    
  2825. +    if (h->fenc->i_type == X264_TYPE_P || h->fenc->i_type == X264_TYPE_ANCHOR)
  2826. +    {
  2827. +        qsort( h->fref[0], h->i_ref[0], sizeof(x264_frame_t *),
  2828. +                &compare_p_frame );
  2829. +
  2830. +        if ( h->i_ref[0] >= 2 )
  2831. +        {
  2832. +            /* swap */
  2833. +            h->fref[0][0] = (uintptr_t)h->fref[0][0] ^ (uintptr_t)h->fref[0][1];
  2834. +            h->fref[0][1] = (uintptr_t)h->fref[0][0] ^ (uintptr_t)h->fref[0][1];
  2835. +            h->fref[0][0] = (uintptr_t)h->fref[0][0] ^ (uintptr_t)h->fref[0][1];
  2836. +        }
  2837. +    }
  2838. +    else if( h->fenc->i_type == X264_TYPE_B )
  2839. +    {
  2840. +        x264_frame_t *inter_view[2] = { 0 };
  2841. +        for( int i = 0; i < 2; i++ )
  2842. +            for( int j = 0; j < h->i_ref[i]; j++ )
  2843. +                if ( h->fref[i][j]->i_frame_num == h->i_frame_num / 2 )
  2844. +                {
  2845. +                    inter_view[i] = h->fref[i][j];
  2846. +                    h->fref[i][j] = h->fref[i][h->i_ref[i] - 1];
  2847. +                    h->i_ref[i]--;
  2848. +                    break;
  2849. +                }
  2850. +        
  2851. +        x264_reference_build_list_b( h, 0, &compare_b_frame_l0 );
  2852. +        x264_reference_build_list_b( h, 1, &compare_b_frame_l1 );
  2853. +        
  2854. +        if( inter_view[0] )
  2855. +        {
  2856. +            int i;
  2857. +            for( i = h->i_ref[0]; i > 1; i-- )
  2858. +            {
  2859. +                h->fref[0][i] = h->fref[0][i - 1];
  2860. +            }
  2861. +            h->fref[0][i] = inter_view[0];
  2862. +            h->i_ref[0]++;
  2863. +        }
  2864. +        
  2865. +        if( inter_view[1] )
  2866. +        {
  2867. +            /* Please test here when starting using these code. */
  2868. +            int insert_point = 1;
  2869. +            for( int i = 0; h->fref[1][i]->i_poc < h->fenc->i_poc; i++ )
  2870. +            {
  2871. +                insert_point = i + 2;
  2872. +            }
  2873. +            if( insert_point >= h->i_ref[1])
  2874. +                insert_point = h->i_ref[1] - 1;
  2875. +            for( int i = h->i_ref[1]; i > insert_point; i-- )
  2876. +                h->fref[1][i] = h->fref[1][i - 1];
  2877. +            h->fref[1][insert_point] = inter_view[1];
  2878. +            h->i_ref[1]++;
  2879. +        }
  2880. +    }
  2881. +
  2882. +#ifdef __DEBUG
  2883. +    for (int j = 0; j < 2; j++) {
  2884. +        for (int i = 0; i < h->i_ref[j]; ++i) {
  2885. +            x264_log(h, X264_LOG_INFO, "ref%d[%2d] : no = %4d, poc = %2d\n",
  2886. +                     j, i,
  2887. +                     h->fref[j][i] ? h->fref[j][i]->i_frame : 9999,
  2888. +                     h->fref[j][i] ? h->fref[j][i]->i_poc : -1);
  2889. +        }
  2890. +    }
  2891. +#endif
  2892. +    return 0;
  2893. +}
  2894. +
  2895.  static char *x264_strcat_filename( char *input, char *suffix )
  2896.  {
  2897.      char *output = x264_malloc( strlen( input ) + strlen( suffix ) + 1 );
  2898. @@ -443,224 +571,256 @@ static char *x264_strcat_filename( char *input, char *suffix )
  2899.  
  2900.  void x264_ratecontrol_init_reconfigurable( x264_t *h, int b_init )
  2901.  {
  2902. -    x264_ratecontrol_t *rc = h->rc;
  2903. -    if( !b_init && rc->b_2pass )
  2904. -        return;
  2905. +    int rc_num = get_view_num(h);
  2906.  
  2907. -    if( h->param.rc.i_rc_method == X264_RC_CRF )
  2908. -    {
  2909. -        /* Arbitrary rescaling to make CRF somewhat similar to QP.
  2910. -         * Try to compensate for MB-tree's effects as well. */
  2911. -        double base_cplx = h->mb.i_mb_count * (h->param.i_bframe ? 120 : 80);
  2912. -        double mbtree_offset = h->param.rc.b_mb_tree ? (1.0-h->param.rc.f_qcompress)*13.5 : 0;
  2913. -        rc->rate_factor_constant = pow( base_cplx, 1 - rc->qcompress )
  2914. -                                 / qp2qscale( h->param.rc.f_rf_constant + mbtree_offset + QP_BD_OFFSET );
  2915. -    }
  2916. +    for (int view = 0; view < rc_num; view ++) {
  2917. +        x264_ratecontrol_t *rc = h->rc_mvc[view];
  2918. +        if( !b_init && rc->b_2pass )
  2919. +            return;
  2920.  
  2921. -    if( h->param.rc.i_vbv_max_bitrate > 0 && h->param.rc.i_vbv_buffer_size > 0 )
  2922. -    {
  2923. -        if( h->param.rc.i_vbv_buffer_size < (int)(h->param.rc.i_vbv_max_bitrate / rc->fps) )
  2924. +        x264_sps_t * sps = view == 0 ? h->sps : h->subset_sps;
  2925. +
  2926. +        if( h->param.rc.i_rc_method == X264_RC_CRF )
  2927.          {
  2928. -            h->param.rc.i_vbv_buffer_size = h->param.rc.i_vbv_max_bitrate / rc->fps;
  2929. -            x264_log( h, X264_LOG_WARNING, "VBV buffer size cannot be smaller than one frame, using %d kbit\n",
  2930. -                      h->param.rc.i_vbv_buffer_size );
  2931. +            /* Arbitrary rescaling to make CRF somewhat similar to QP.
  2932. +             * Try to compensate for MB-tree's effects as well. */
  2933. +            double base_cplx = h->mb.i_mb_count * (h->param.i_bframe ? 120 : 80);
  2934. +            double mbtree_offset = h->param.rc.b_mb_tree ? (1.0-h->param.rc.f_qcompress)*13.5 : 0;
  2935. +            rc->rate_factor_constant = pow( base_cplx, 1 - rc->qcompress )
  2936. +                / qp2qscale( h->param.rc.f_rf_constant + mbtree_offset + QP_BD_OFFSET );
  2937.          }
  2938.  
  2939. -        /* We don't support changing the ABR bitrate right now,
  2940. -           so if the stream starts as CBR, keep it CBR. */
  2941. -        if( rc->b_vbv_min_rate )
  2942. -            h->param.rc.i_vbv_max_bitrate = h->param.rc.i_bitrate;
  2943. +        int vbv_max_rate = view == 0 ? h->param.rc.i_vbv_max_bitrate : h->param.rc.i_vbv_max_bitrate_dep[view-1];
  2944. +        float max_rate_ratio = view == 0 ? 1.0f : (float)h->param.rc.i_vbv_max_bitrate_dep[view-1] / (float)h->param.rc.i_vbv_max_bitrate;
  2945. +        if( vbv_max_rate > 0 && h->param.rc.i_vbv_buffer_size > 0 )
  2946. +        {
  2947. +            if( h->param.rc.i_vbv_buffer_size < (int)(vbv_max_rate / rc->fps) )
  2948. +            {
  2949. +                h->param.rc.i_vbv_buffer_size = vbv_max_rate / rc->fps;
  2950. +                x264_log( h, X264_LOG_WARNING, "VBV buffer size cannot be smaller than one frame, using %d kbit\n",
  2951. +                          h->param.rc.i_vbv_buffer_size );
  2952. +            }
  2953.  
  2954. -        int vbv_buffer_size = h->param.rc.i_vbv_buffer_size * 1000;
  2955. -        int vbv_max_bitrate = h->param.rc.i_vbv_max_bitrate * 1000;
  2956. +            /* We don't support changing the ABR bitrate right now,
  2957. +               so if the stream starts as CBR, keep it CBR. */
  2958. +            if( rc->b_vbv_min_rate ) {
  2959. +                if (view == 0) {
  2960. +                    h->param.rc.i_vbv_max_bitrate = h->param.rc.i_bitrate;
  2961. +                    vbv_max_rate = h->param.rc.i_bitrate;
  2962. +                } else {
  2963. +                    h->param.rc.i_vbv_max_bitrate_dep[view-1] = h->param.rc.i_bitrate_dep[view-1];
  2964. +                    vbv_max_rate = h->param.rc.i_bitrate_dep[view-1];
  2965. +                }
  2966. +            }
  2967.  
  2968. -        /* Init HRD */
  2969. -        h->sps->vui.hrd.i_bit_rate_unscaled = vbv_max_bitrate;
  2970. -        h->sps->vui.hrd.i_cpb_size_unscaled = vbv_buffer_size;
  2971. -        if( h->param.i_nal_hrd && b_init )
  2972. -        {
  2973. -            h->sps->vui.hrd.i_cpb_cnt = 1;
  2974. -            h->sps->vui.hrd.b_cbr_hrd = h->param.i_nal_hrd == X264_NAL_HRD_CBR;
  2975. -            h->sps->vui.hrd.i_time_offset_length = 0;
  2976. +            int vbv_buffer_size = h->param.rc.i_vbv_buffer_size * 1000;
  2977. +            int vbv_max_bitrate = vbv_max_rate * 1000;
  2978.  
  2979. -            #define BR_SHIFT  6
  2980. -            #define CPB_SHIFT 4
  2981. +            /* Init HRD */
  2982. +            sps->vui.hrd.i_bit_rate_unscaled = vbv_max_bitrate;
  2983. +            sps->vui.hrd.i_cpb_size_unscaled = vbv_buffer_size;
  2984. +            if( h->param.i_nal_hrd && b_init )
  2985. +            {
  2986. +                sps->vui.hrd.i_cpb_cnt = 1;
  2987. +                sps->vui.hrd.b_cbr_hrd = h->param.i_nal_hrd == X264_NAL_HRD_CBR;
  2988. +                //            h->sps->vui.hrd.i_time_offset_length = 0;
  2989. +                sps->vui.hrd.i_time_offset_length = 24;
  2990.  
  2991. -            int bitrate = 1000*h->param.rc.i_vbv_max_bitrate;
  2992. -            int bufsize = 1000*h->param.rc.i_vbv_buffer_size;
  2993. +                #define BR_SHIFT  6
  2994. +                #define CPB_SHIFT 4
  2995.  
  2996. -            // normalize HRD size and rate to the value / scale notation
  2997. -            h->sps->vui.hrd.i_bit_rate_scale = x264_clip3( x264_ctz( bitrate ) - BR_SHIFT, 0, 15 );
  2998. -            h->sps->vui.hrd.i_bit_rate_value = bitrate >> ( h->sps->vui.hrd.i_bit_rate_scale + BR_SHIFT );
  2999. -            h->sps->vui.hrd.i_bit_rate_unscaled = h->sps->vui.hrd.i_bit_rate_value << ( h->sps->vui.hrd.i_bit_rate_scale + BR_SHIFT );
  3000. -            h->sps->vui.hrd.i_cpb_size_scale = x264_clip3( x264_ctz( bufsize ) - CPB_SHIFT, 0, 15 );
  3001. -            h->sps->vui.hrd.i_cpb_size_value = bufsize >> ( h->sps->vui.hrd.i_cpb_size_scale + CPB_SHIFT );
  3002. -            h->sps->vui.hrd.i_cpb_size_unscaled = h->sps->vui.hrd.i_cpb_size_value << ( h->sps->vui.hrd.i_cpb_size_scale + CPB_SHIFT );
  3003. +                int bitrate = 1000*vbv_max_rate;
  3004. +                int bufsize = 1000*h->param.rc.i_vbv_buffer_size;
  3005.  
  3006. -            #undef CPB_SHIFT
  3007. -            #undef BR_SHIFT
  3008. +                // normalize HRD size and rate to the value / scale notation
  3009. +                sps->vui.hrd.i_bit_rate_scale = x264_clip3( x264_ctz( bitrate ) - BR_SHIFT, 0, 15 );
  3010. +                sps->vui.hrd.i_bit_rate_value = bitrate >> ( sps->vui.hrd.i_bit_rate_scale + BR_SHIFT );
  3011. +                sps->vui.hrd.i_bit_rate_unscaled = sps->vui.hrd.i_bit_rate_value << ( sps->vui.hrd.i_bit_rate_scale + BR_SHIFT );
  3012. +                sps->vui.hrd.i_cpb_size_scale = x264_clip3( x264_ctz( bufsize ) - CPB_SHIFT, 0, 15 );
  3013. +                sps->vui.hrd.i_cpb_size_value = bufsize >> ( sps->vui.hrd.i_cpb_size_scale + CPB_SHIFT );
  3014. +                sps->vui.hrd.i_cpb_size_unscaled = sps->vui.hrd.i_cpb_size_value << ( sps->vui.hrd.i_cpb_size_scale + CPB_SHIFT );
  3015.  
  3016. -            // arbitrary
  3017. -            #define MAX_DURATION 0.5
  3018. +                //sps->vui.hrd.i_cpb_size_unscaled = (float)sps->vui.hrd.i_cpb_size_unscaled * max_rate_ratio;
  3019. +                #undef CPB_SHIFT
  3020. +                #undef BR_SHIFT
  3021.  
  3022. -            int max_cpb_output_delay = X264_MIN( h->param.i_keyint_max * MAX_DURATION * h->sps->vui.i_time_scale / h->sps->vui.i_num_units_in_tick, INT_MAX );
  3023. -            int max_dpb_output_delay = h->sps->vui.i_max_dec_frame_buffering * MAX_DURATION * h->sps->vui.i_time_scale / h->sps->vui.i_num_units_in_tick;
  3024. -            int max_delay = (int)(90000.0 * (double)h->sps->vui.hrd.i_cpb_size_unscaled / h->sps->vui.hrd.i_bit_rate_unscaled + 0.5);
  3025. +                // arbitrary
  3026. +                #define MAX_DURATION 0.5
  3027.  
  3028. -            h->sps->vui.hrd.i_initial_cpb_removal_delay_length = 2 + x264_clip3( 32 - x264_clz( max_delay ), 4, 22 );
  3029. -            h->sps->vui.hrd.i_cpb_removal_delay_length = x264_clip3( 32 - x264_clz( max_cpb_output_delay ), 4, 31 );
  3030. -            h->sps->vui.hrd.i_dpb_output_delay_length  = x264_clip3( 32 - x264_clz( max_dpb_output_delay ), 4, 31 );
  3031. +                int max_cpb_output_delay = X264_MIN( h->param.i_keyint_max * MAX_DURATION * sps->vui.i_time_scale / sps->vui.i_num_units_in_tick, INT_MAX );
  3032. +                int max_dpb_output_delay = sps->vui.i_max_dec_frame_buffering * MAX_DURATION * sps->vui.i_time_scale / sps->vui.i_num_units_in_tick;
  3033. +                int max_delay = (int)(90000.0 * (double)sps->vui.hrd.i_cpb_size_unscaled / sps->vui.hrd.i_bit_rate_unscaled + 0.5);
  3034.  
  3035. -            #undef MAX_DURATION
  3036. +                sps->vui.hrd.i_initial_cpb_removal_delay_length = 2 + x264_clip3( 32 - x264_clz( max_delay ), 4, 22 );
  3037. +                sps->vui.hrd.i_cpb_removal_delay_length = x264_clip3( 32 - x264_clz( max_cpb_output_delay ), 4, 31 );
  3038. +                sps->vui.hrd.i_dpb_output_delay_length  = x264_clip3( 32 - x264_clz( max_dpb_output_delay ), 4, 31 );
  3039.  
  3040. -            vbv_buffer_size = h->sps->vui.hrd.i_cpb_size_unscaled;
  3041. -            vbv_max_bitrate = h->sps->vui.hrd.i_bit_rate_unscaled;
  3042. -        }
  3043. -        else if( h->param.i_nal_hrd && !b_init )
  3044. -        {
  3045. -            x264_log( h, X264_LOG_WARNING, "VBV parameters cannot be changed when NAL HRD is in use\n" );
  3046. -            return;
  3047. -        }
  3048. +                #undef MAX_DURATION
  3049.  
  3050. -        rc->buffer_rate = vbv_max_bitrate / rc->fps;
  3051. -        rc->vbv_max_rate = vbv_max_bitrate;
  3052. -        rc->buffer_size = vbv_buffer_size;
  3053. -        rc->single_frame_vbv = rc->buffer_rate * 1.1 > rc->buffer_size;
  3054. -        rc->cbr_decay = 1.0 - rc->buffer_rate / rc->buffer_size
  3055. -                      * 0.5 * X264_MAX(0, 1.5 - rc->buffer_rate * rc->fps / rc->bitrate);
  3056. -        if( h->param.rc.i_rc_method == X264_RC_CRF && h->param.rc.f_rf_constant_max )
  3057. -        {
  3058. -            rc->rate_factor_max_increment = h->param.rc.f_rf_constant_max - h->param.rc.f_rf_constant;
  3059. -            if( rc->rate_factor_max_increment <= 0 )
  3060. +                vbv_buffer_size = sps->vui.hrd.i_cpb_size_unscaled;
  3061. +                vbv_max_bitrate = sps->vui.hrd.i_bit_rate_unscaled;
  3062. +            }
  3063. +            else if( h->param.i_nal_hrd && !b_init )
  3064.              {
  3065. -                x264_log( h, X264_LOG_WARNING, "CRF max must be greater than CRF\n" );
  3066. -                rc->rate_factor_max_increment = 0;
  3067. +                x264_log( h, X264_LOG_WARNING, "VBV parameters cannot be changed when NAL HRD is in use\n" );
  3068. +                return;
  3069. +            }
  3070. +
  3071. +            rc->buffer_rate = vbv_max_bitrate / rc->fps;
  3072. +            rc->vbv_max_rate = vbv_max_bitrate;
  3073. +            rc->buffer_size = vbv_buffer_size;
  3074. +            rc->single_frame_vbv = rc->buffer_rate * 1.1 > rc->buffer_size;
  3075. +            rc->cbr_decay = 1.0 - rc->buffer_rate / rc->buffer_size
  3076. +                * 0.5 * X264_MAX(0, 1.5 - rc->buffer_rate * rc->fps / rc->bitrate);
  3077. +            if( h->param.rc.i_rc_method == X264_RC_CRF && h->param.rc.f_rf_constant_max )
  3078. +            {
  3079. +                rc->rate_factor_max_increment = h->param.rc.f_rf_constant_max - h->param.rc.f_rf_constant;
  3080. +                if( rc->rate_factor_max_increment <= 0 )
  3081. +                {
  3082. +                    x264_log( h, X264_LOG_WARNING, "CRF max must be greater than CRF\n" );
  3083. +                    rc->rate_factor_max_increment = 0;
  3084. +                }
  3085. +            }
  3086. +            if( b_init )
  3087. +            {
  3088. +                if( h->param.rc.f_vbv_buffer_init > 1. )
  3089. +                    h->param.rc.f_vbv_buffer_init = x264_clip3f( h->param.rc.f_vbv_buffer_init / h->param.rc.i_vbv_buffer_size, 0, 1 );
  3090. +                h->param.rc.f_vbv_buffer_init = x264_clip3f( X264_MAX( h->param.rc.f_vbv_buffer_init, rc->buffer_rate / rc->buffer_size ), 0, 1);
  3091. +                rc->buffer_fill_final = rc->buffer_size * h->param.rc.f_vbv_buffer_init * sps->vui.i_time_scale;
  3092. +                rc->b_vbv = 1;
  3093. +                rc->b_vbv_min_rate = !rc->b_2pass
  3094. +                    && h->param.rc.i_rc_method == X264_RC_ABR
  3095. +                    && vbv_max_rate <= (view==0 ? h->param.rc.i_bitrate : h->param.rc.i_bitrate_dep[view-1]);
  3096.              }
  3097. -        }
  3098. -        if( b_init )
  3099. -        {
  3100. -            if( h->param.rc.f_vbv_buffer_init > 1. )
  3101. -                h->param.rc.f_vbv_buffer_init = x264_clip3f( h->param.rc.f_vbv_buffer_init / h->param.rc.i_vbv_buffer_size, 0, 1 );
  3102. -            h->param.rc.f_vbv_buffer_init = x264_clip3f( X264_MAX( h->param.rc.f_vbv_buffer_init, rc->buffer_rate / rc->buffer_size ), 0, 1);
  3103. -            rc->buffer_fill_final = rc->buffer_size * h->param.rc.f_vbv_buffer_init * h->sps->vui.i_time_scale;
  3104. -            rc->b_vbv = 1;
  3105. -            rc->b_vbv_min_rate = !rc->b_2pass
  3106. -                          && h->param.rc.i_rc_method == X264_RC_ABR
  3107. -                          && h->param.rc.i_vbv_max_bitrate <= h->param.rc.i_bitrate;
  3108.          }
  3109.      }
  3110.  }
  3111.  
  3112.  int x264_ratecontrol_new( x264_t *h )
  3113.  {
  3114. +    int i, j;
  3115.      x264_ratecontrol_t *rc;
  3116.  
  3117.      x264_emms();
  3118.  
  3119. -    CHECKED_MALLOCZERO( h->rc, h->param.i_threads * sizeof(x264_ratecontrol_t) );
  3120. -    rc = h->rc;
  3121. -
  3122. -    rc->b_abr = h->param.rc.i_rc_method != X264_RC_CQP && !h->param.rc.b_stat_read;
  3123. -    rc->b_2pass = h->param.rc.i_rc_method == X264_RC_ABR && h->param.rc.b_stat_read;
  3124. -
  3125. -    /* FIXME: use integers */
  3126. -    if( h->param.i_fps_num > 0 && h->param.i_fps_den > 0 )
  3127. -        rc->fps = (float) h->param.i_fps_num / h->param.i_fps_den;
  3128. -    else
  3129. -        rc->fps = 25.0;
  3130. +    int rc_num = get_view_num(h);
  3131. +    for (int view=0; view<rc_num; view++) {
  3132. +        CHECKED_MALLOCZERO( h->rc_mvc[view], h->param.i_threads * sizeof(x264_ratecontrol_t));
  3133.  
  3134. -    if( h->param.rc.b_mb_tree )
  3135. -    {
  3136. -        h->param.rc.f_pb_factor = 1;
  3137. -        rc->qcompress = 1;
  3138. -    }
  3139. -    else
  3140. -        rc->qcompress = h->param.rc.f_qcompress;
  3141. +        rc = h->rc_mvc[view];
  3142. +        //if (view == 0) h->rc = h->rc_mvc[0];
  3143.  
  3144. -    rc->bitrate = h->param.rc.i_bitrate * 1000.;
  3145. -    rc->rate_tolerance = h->param.rc.f_rate_tolerance;
  3146. -    rc->nmb = h->mb.i_mb_count;
  3147. -    rc->last_non_b_pict_type = -1;
  3148. -    rc->cbr_decay = 1.0;
  3149. +        rc->b_abr = h->param.rc.i_rc_method != X264_RC_CQP && !h->param.rc.b_stat_read;
  3150. +        rc->b_2pass = h->param.rc.i_rc_method == X264_RC_ABR && h->param.rc.b_stat_read;
  3151.  
  3152. -    if( h->param.rc.i_rc_method == X264_RC_CRF && h->param.rc.b_stat_read )
  3153. -    {
  3154. -        x264_log(h, X264_LOG_ERROR, "constant rate-factor is incompatible with 2pass.\n");
  3155. -        return -1;
  3156. -    }
  3157. +        /* FIXME: use integers */
  3158. +        if( h->param.i_fps_num > 0 && h->param.i_fps_den > 0 )
  3159. +            rc->fps = (float) h->param.i_fps_num / h->param.i_fps_den;
  3160. +        else
  3161. +            rc->fps = 25.0;
  3162.  
  3163. -    x264_ratecontrol_init_reconfigurable( h, 1 );
  3164. +        if( h->param.rc.b_mb_tree )
  3165. +            {
  3166. +                h->param.rc.f_pb_factor = 1;
  3167. +                rc->qcompress = 1;
  3168. +            }
  3169. +        else
  3170. +            rc->qcompress = h->param.rc.f_qcompress;
  3171.  
  3172. -    if( h->param.i_nal_hrd )
  3173. -    {
  3174. -        uint64_t denom = (uint64_t)h->sps->vui.hrd.i_bit_rate_unscaled * h->sps->vui.i_time_scale;
  3175. -        uint64_t num = 180000;
  3176. -        x264_reduce_fraction64( &num, &denom );
  3177. -        rc->hrd_multiply_denom = 180000 / num;
  3178. +        if (view == 0) {
  3179. +            rc->bitrate = h->param.rc.i_bitrate * 1000.;
  3180. +        } else {
  3181. +            rc->bitrate = h->param.rc.i_bitrate_dep[view-1] * 1000.;
  3182. +        }
  3183. +        rc->rate_tolerance = h->param.rc.f_rate_tolerance;
  3184. +        rc->nmb = h->mb.i_mb_count;
  3185. +        rc->last_non_b_pict_type = -1;
  3186. +        rc->cbr_decay = 1.0;
  3187.  
  3188. -        double bits_required = log2( 180000 / rc->hrd_multiply_denom )
  3189. -                             + log2( h->sps->vui.i_time_scale )
  3190. -                             + log2( h->sps->vui.hrd.i_cpb_size_unscaled );
  3191. -        if( bits_required >= 63 )
  3192. +        if( h->param.rc.i_rc_method == X264_RC_CRF && h->param.rc.b_stat_read )
  3193.          {
  3194. -            x264_log( h, X264_LOG_ERROR, "HRD with very large timescale and bufsize not supported\n" );
  3195. +            x264_log(h, X264_LOG_ERROR, "constant rate-factor is incompatible with 2pass.\n");
  3196.              return -1;
  3197.          }
  3198.      }
  3199.  
  3200. -    if( rc->rate_tolerance < 0.01 )
  3201. -    {
  3202. -        x264_log(h, X264_LOG_WARNING, "bitrate tolerance too small, using .01\n");
  3203. -        rc->rate_tolerance = 0.01;
  3204. -    }
  3205. +    x264_ratecontrol_init_reconfigurable( h, 1 );
  3206.  
  3207. -    h->mb.b_variable_qp = rc->b_vbv || h->param.rc.i_aq_mode;
  3208. +    for (int view=0; view<rc_num; view++) {
  3209. +        x264_sps_t * sps = view == 0 ? h->sps : h->subset_sps;
  3210. +        rc = h->rc_mvc[view];
  3211.  
  3212. -    if( rc->b_abr )
  3213. -    {
  3214. -        /* FIXME ABR_INIT_QP is actually used only in CRF */
  3215. -#define ABR_INIT_QP (( h->param.rc.i_rc_method == X264_RC_CRF ? h->param.rc.f_rf_constant : 24 ) + QP_BD_OFFSET)
  3216. -        rc->accum_p_norm = .01;
  3217. -        rc->accum_p_qp = ABR_INIT_QP * rc->accum_p_norm;
  3218. -        /* estimated ratio that produces a reasonable QP for the first I-frame */
  3219. -        rc->cplxr_sum = .01 * pow( 7.0e5, rc->qcompress ) * pow( h->mb.i_mb_count, 0.5 );
  3220. -        rc->wanted_bits_window = 1.0 * rc->bitrate / rc->fps;
  3221. -        rc->last_non_b_pict_type = SLICE_TYPE_I;
  3222. -    }
  3223. -
  3224. -    rc->ip_offset = 6.0 * log2f( h->param.rc.f_ip_factor );
  3225. -    rc->pb_offset = 6.0 * log2f( h->param.rc.f_pb_factor );
  3226. -    rc->qp_constant[SLICE_TYPE_P] = h->param.rc.i_qp_constant;
  3227. -    rc->qp_constant[SLICE_TYPE_I] = x264_clip3( h->param.rc.i_qp_constant - rc->ip_offset + 0.5, 0, QP_MAX );
  3228. -    rc->qp_constant[SLICE_TYPE_B] = x264_clip3( h->param.rc.i_qp_constant + rc->pb_offset + 0.5, 0, QP_MAX );
  3229. -    h->mb.ip_offset = rc->ip_offset + 0.5;
  3230. -
  3231. -    rc->lstep = pow( 2, h->param.rc.i_qp_step / 6.0 );
  3232. -    rc->last_qscale = qp2qscale( 26 );
  3233. -    int num_preds = h->param.b_sliced_threads * h->param.i_threads + 1;
  3234. -    CHECKED_MALLOC( rc->pred, 5 * sizeof(predictor_t) * num_preds );
  3235. -    CHECKED_MALLOC( rc->pred_b_from_p, sizeof(predictor_t) );
  3236. -    for( int i = 0; i < 3; i++ )
  3237. -    {
  3238. -        rc->last_qscale_for[i] = qp2qscale( ABR_INIT_QP );
  3239. -        rc->lmin[i] = qp2qscale( h->param.rc.i_qp_min );
  3240. -        rc->lmax[i] = qp2qscale( h->param.rc.i_qp_max );
  3241. -        for( int j = 0; j < num_preds; j++ )
  3242. +        if( h->param.i_nal_hrd )
  3243. +        {
  3244. +            uint64_t denom = (uint64_t)sps->vui.hrd.i_bit_rate_unscaled * sps->vui.i_time_scale;
  3245. +            uint64_t num = 180000;
  3246. +            x264_reduce_fraction64( &num, &denom );
  3247. +            rc->hrd_multiply_denom = 180000 / num;
  3248. +
  3249. +            double bits_required = log2( 180000 / rc->hrd_multiply_denom )
  3250. +                + log2( sps->vui.i_time_scale )
  3251. +                + log2( sps->vui.hrd.i_cpb_size_unscaled );
  3252. +            if( bits_required >= 63 )
  3253. +            {
  3254. +                x264_log( h, X264_LOG_ERROR, "HRD with very large timescale and bufsize not supported\n" );
  3255. +                return -1;
  3256. +            }
  3257. +        }
  3258. +
  3259. +        if( rc->rate_tolerance < 0.01 )
  3260.          {
  3261. -            rc->pred[i+j*5].coeff= 2.0;
  3262. -            rc->pred[i+j*5].count= 1.0;
  3263. -            rc->pred[i+j*5].decay= 0.5;
  3264. -            rc->pred[i+j*5].offset= 0.0;
  3265. +            x264_log(h, X264_LOG_WARNING, "bitrate tolerance too small, using .01\n");
  3266. +            rc->rate_tolerance = 0.01;
  3267.          }
  3268. -        for( int j = 0; j < 2; j++ )
  3269. +
  3270. +        h->mb.b_variable_qp = rc->b_vbv || h->param.rc.i_aq_mode;
  3271. +
  3272. +        if( rc->b_abr )
  3273.          {
  3274. -            rc->row_preds[i][j].coeff= .25;
  3275. -            rc->row_preds[i][j].count= 1.0;
  3276. -            rc->row_preds[i][j].decay= 0.5;
  3277. -            rc->row_preds[i][j].offset= 0.0;
  3278. +            /* FIXME ABR_INIT_QP is actually used only in CRF */
  3279. +#define ABR_INIT_QP (( h->param.rc.i_rc_method == X264_RC_CRF ? h->param.rc.f_rf_constant : 24 ) + QP_BD_OFFSET)
  3280. +            rc->accum_p_norm = .01;
  3281. +            rc->accum_p_qp = ABR_INIT_QP * rc->accum_p_norm;
  3282. +            /* estimated ratio that produces a reasonable QP for the first I-frame */
  3283. +            rc->cplxr_sum = .01 * pow( 7.0e5, rc->qcompress ) * pow( h->mb.i_mb_count, 0.5 );
  3284. +            rc->wanted_bits_window = 1.0 * rc->bitrate / rc->fps;
  3285. +            rc->last_non_b_pict_type = SLICE_TYPE_I;
  3286. +        }
  3287. +
  3288. +        rc->ip_offset = 6.0 * log2f( h->param.rc.f_ip_factor );
  3289. +        rc->pb_offset = 6.0 * log2f( h->param.rc.f_pb_factor );
  3290. +        rc->qp_constant[SLICE_TYPE_P] = h->param.rc.i_qp_constant;
  3291. +        rc->qp_constant[SLICE_TYPE_I] = x264_clip3( h->param.rc.i_qp_constant - rc->ip_offset + 0.5, 0, QP_MAX );
  3292. +        rc->qp_constant[SLICE_TYPE_B] = x264_clip3( h->param.rc.i_qp_constant + rc->pb_offset + 0.5, 0, QP_MAX );
  3293. +        h->mb.ip_offset = rc->ip_offset + 0.5;
  3294. +
  3295. +        rc->lstep = pow( 2, h->param.rc.i_qp_step / 6.0 );
  3296. +        rc->last_qscale = qp2qscale( 26 );
  3297. +        int num_preds = h->param.b_sliced_threads * h->param.i_threads + 1;
  3298. +        CHECKED_MALLOC( rc->pred, 5 * sizeof(predictor_t) * num_preds );
  3299. +        CHECKED_MALLOC( rc->pred_b_from_p, sizeof(predictor_t) );
  3300. +        for( i = 0; i < 3; i++ )
  3301. +        {
  3302. +            rc->last_qscale_for[i] = qp2qscale( ABR_INIT_QP );
  3303. +            rc->lmin[i] = qp2qscale( h->param.rc.i_qp_min );
  3304. +            rc->lmax[i] = qp2qscale( h->param.rc.i_qp_max );
  3305. +            for( j = 0; j < num_preds; j++ )
  3306. +            {
  3307. +                rc->pred[i+j*5].coeff= 2.0;
  3308. +                rc->pred[i+j*5].count= 1.0;
  3309. +                rc->pred[i+j*5].decay= 0.5;
  3310. +                rc->pred[i+j*5].offset= 0.0;
  3311. +            }
  3312. +            for( j = 0; j < 2; j++ )
  3313. +            {
  3314. +                rc->row_preds[i][j].coeff= .25;
  3315. +                rc->row_preds[i][j].count= 1.0;
  3316. +                rc->row_preds[i][j].decay= 0.5;
  3317. +                rc->row_preds[i][j].offset= 0.0;
  3318. +            }
  3319.          }
  3320. +        *rc->pred_b_from_p = rc->pred[0];
  3321.      }
  3322. -    *rc->pred_b_from_p = rc->pred[0];
  3323.  
  3324.      if( parse_zones( h ) < 0 )
  3325.      {
  3326. @@ -668,209 +828,220 @@ int x264_ratecontrol_new( x264_t *h )
  3327.          return -1;
  3328.      }
  3329.  
  3330. -    /* Load stat file and init 2pass algo */
  3331. -    if( h->param.rc.b_stat_read )
  3332. -    {
  3333. -        char *p, *stats_in, *stats_buf;
  3334. -
  3335. -        /* read 1st pass stats */
  3336. -        assert( h->param.rc.psz_stat_in );
  3337. -        stats_buf = stats_in = x264_slurp_file( h->param.rc.psz_stat_in );
  3338. -        if( !stats_buf )
  3339. -        {
  3340. -            x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open stats file\n");
  3341. -            return -1;
  3342. -        }
  3343. -        if( h->param.rc.b_mb_tree )
  3344. +    for (int view=0; view<rc_num; view++) {
  3345. +        rc = h->rc_mvc[view];
  3346. +        /* Load stat file and init 2pass algo */
  3347. +        if( h->param.rc.b_stat_read )
  3348.          {
  3349. -            char *mbtree_stats_in = x264_strcat_filename( h->param.rc.psz_stat_in, ".mbtree" );
  3350. -            if( !mbtree_stats_in )
  3351. -                return -1;
  3352. -            rc->p_mbtree_stat_file_in = fopen( mbtree_stats_in, "rb" );
  3353. -            x264_free( mbtree_stats_in );
  3354. -            if( !rc->p_mbtree_stat_file_in )
  3355. -            {
  3356. -                x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open mbtree stats file\n");
  3357. -                return -1;
  3358. -            }
  3359. -        }
  3360. +            char *p, *stats_in, *stats_buf;
  3361.  
  3362. -        /* check whether 1st pass options were compatible with current options */
  3363. -        if( !strncmp( stats_buf, "#options:", 9 ) )
  3364. -        {
  3365. -            int i, j;
  3366. -            uint32_t k, l;
  3367. -            char *opts = stats_buf;
  3368. -            stats_in = strchr( stats_buf, '\n' );
  3369. -            if( !stats_in )
  3370. -                return -1;
  3371. -            *stats_in = '\0';
  3372. -            stats_in++;
  3373. -            if( sscanf( opts, "#options: %dx%d", &i, &j ) != 2 )
  3374. +            /* read 1st pass stats */
  3375. +            assert( h->param.rc.psz_stat_in );
  3376. +            stats_buf = stats_in = x264_slurp_file( h->param.rc.psz_stat_in );
  3377. +            if( !stats_buf )
  3378.              {
  3379. -                x264_log( h, X264_LOG_ERROR, "resolution specified in stats file not valid\n" );
  3380. +                x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open stats file\n");
  3381.                  return -1;
  3382.              }
  3383. -            else if( h->param.rc.b_mb_tree && (i != h->param.i_width || j != h->param.i_height)  )
  3384. +            if( h->param.rc.b_mb_tree )
  3385.              {
  3386. -                x264_log( h, X264_LOG_ERROR, "MB-tree doesn't support different resolution than 1st pass (%dx%d vs %dx%d)\n",
  3387. -                          h->param.i_width, h->param.i_height, i, j );
  3388. -                return -1;
  3389. -            }
  3390. -
  3391. -            if( ( p = strstr( opts, "timebase=" ) ) && sscanf( p, "timebase=%u/%u", &k, &l ) != 2 )
  3392. -            {
  3393. -                x264_log( h, X264_LOG_ERROR, "timebase specified in stats file not valid\n" );
  3394. -                return -1;
  3395. -            }
  3396. -            if( k != h->param.i_timebase_num || l != h->param.i_timebase_den )
  3397. -            {
  3398. -                x264_log( h, X264_LOG_ERROR, "timebase mismatch with 1st pass (%u/%u vs %u/%u)\n",
  3399. -                          h->param.i_timebase_num, h->param.i_timebase_den, k, l );
  3400. -                return -1;
  3401. -            }
  3402. -
  3403. -            CMP_OPT_FIRST_PASS( "bitdepth", BIT_DEPTH );
  3404. -            CMP_OPT_FIRST_PASS( "weightp", X264_MAX( 0, h->param.analyse.i_weighted_pred ) );
  3405. -            CMP_OPT_FIRST_PASS( "bframes", h->param.i_bframe );
  3406. -            CMP_OPT_FIRST_PASS( "b_pyramid", h->param.i_bframe_pyramid );
  3407. -            CMP_OPT_FIRST_PASS( "intra_refresh", h->param.b_intra_refresh );
  3408. -            CMP_OPT_FIRST_PASS( "open_gop", h->param.i_open_gop );
  3409. +                char *mbtree_stats_in;
  3410. +                if (view == 0) {
  3411. +                    mbtree_stats_in = x264_strcat_filename( h->param.rc.psz_stat_in, ".mbtree" );
  3412. +                } else {
  3413. +                    char buf[12];
  3414. +                    sprintf(buf, ".mbtree_%d", view+1);
  3415. +                    mbtree_stats_in = x264_strcat_filename( h->param.rc.psz_stat_in, buf );
  3416. +                }
  3417.  
  3418. -            if( (p = strstr( opts, "keyint=" )) )
  3419. -            {
  3420. -                p += 7;
  3421. -                char buf[13] = "infinite ";
  3422. -                if( h->param.i_keyint_max != X264_KEYINT_MAX_INFINITE )
  3423. -                    sprintf( buf, "%d ", h->param.i_keyint_max );
  3424. -                if( strncmp( p, buf, strlen(buf) ) )
  3425. +                if( !mbtree_stats_in )
  3426. +                    return -1;
  3427. +                rc->p_mbtree_stat_file_in = fopen( mbtree_stats_in, "rb" );
  3428. +                x264_free( mbtree_stats_in );
  3429. +                if( !rc->p_mbtree_stat_file_in )
  3430.                  {
  3431. -                    x264_log( h, X264_LOG_ERROR, "different keyint setting than first pass (%.*s vs %.*s)\n",
  3432. -                              strlen(buf)-1, buf, strcspn(p, " "), p );
  3433. +                    x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open mbtree stats file\n");
  3434.                      return -1;
  3435.                  }
  3436.              }
  3437.  
  3438. -            if( strstr( opts, "qp=0" ) && h->param.rc.i_rc_method == X264_RC_ABR )
  3439. -                x264_log( h, X264_LOG_WARNING, "1st pass was lossless, bitrate prediction will be inaccurate\n" );
  3440. -
  3441. -            if( !strstr( opts, "direct=3" ) && h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO )
  3442. +            /* check whether 1st pass options were compatible with current options */
  3443. +            if( !strncmp( stats_buf, "#options:", 9 ) )
  3444.              {
  3445. -                x264_log( h, X264_LOG_WARNING, "direct=auto not used on the first pass\n" );
  3446. -                h->mb.b_direct_auto_write = 1;
  3447. -            }
  3448. -
  3449. -            if( ( p = strstr( opts, "b_adapt=" ) ) && sscanf( p, "b_adapt=%d", &i ) && i >= X264_B_ADAPT_NONE && i <= X264_B_ADAPT_TRELLIS )
  3450. -                h->param.i_bframe_adaptive = i;
  3451. -            else if( h->param.i_bframe )
  3452. -            {
  3453. -                x264_log( h, X264_LOG_ERROR, "b_adapt method specified in stats file not valid\n" );
  3454. -                return -1;
  3455. -            }
  3456. +                uint32_t k, l;
  3457. +                char *opts = stats_buf;
  3458. +                stats_in = strchr( stats_buf, '\n' );
  3459. +                if( !stats_in )
  3460. +                    return -1;
  3461. +                *stats_in = '\0';
  3462. +                stats_in++;
  3463. +                if( sscanf( opts, "#options: %dx%d", &i, &j ) != 2 )
  3464. +                {
  3465. +                    x264_log( h, X264_LOG_ERROR, "resolution specified in stats file not valid\n" );
  3466. +                    return -1;
  3467. +                }
  3468. +                else if( h->param.rc.b_mb_tree && (i != h->param.i_width || j != h->param.i_height)  )
  3469. +                {
  3470. +                    x264_log( h, X264_LOG_ERROR, "MB-tree doesn't support different resolution than 1st pass (%dx%d vs %dx%d)\n",
  3471. +                              h->param.i_width, h->param.i_height, i, j );
  3472. +                    return -1;
  3473. +                }
  3474.  
  3475. -            if( (h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size) && ( p = strstr( opts, "rc_lookahead=" ) ) && sscanf( p, "rc_lookahead=%d", &i ) )
  3476. -                h->param.rc.i_lookahead = i;
  3477. -        }
  3478. +                if( ( p = strstr( opts, "timebase=" ) ) && sscanf( p, "timebase=%u/%u", &k, &l ) != 2 )
  3479. +                {
  3480. +                    x264_log( h, X264_LOG_ERROR, "timebase specified in stats file not valid\n" );
  3481. +                    return -1;
  3482. +                }
  3483. +                if( k != h->param.i_timebase_num || l != h->param.i_timebase_den )
  3484. +                {
  3485. +                    x264_log( h, X264_LOG_ERROR, "timebase mismatch with 1st pass (%u/%u vs %u/%u)\n",
  3486. +                              h->param.i_timebase_num, h->param.i_timebase_den, k, l );
  3487. +                    return -1;
  3488. +                }
  3489.  
  3490. -        /* find number of pics */
  3491. -        p = stats_in;
  3492. -        int num_entries;
  3493. -        for( num_entries = -1; p; num_entries++ )
  3494. -            p = strchr( p + 1, ';' );
  3495. -        if( !num_entries )
  3496. -        {
  3497. -            x264_log(h, X264_LOG_ERROR, "empty stats file\n");
  3498. -            return -1;
  3499. -        }
  3500. -        rc->num_entries = num_entries;
  3501. +                CMP_OPT_FIRST_PASS( "bitdepth", BIT_DEPTH );
  3502. +                CMP_OPT_FIRST_PASS( "weightp", X264_MAX( 0, h->param.analyse.i_weighted_pred ) );
  3503. +                CMP_OPT_FIRST_PASS( "bframes", h->param.i_bframe );
  3504. +                CMP_OPT_FIRST_PASS( "b_pyramid", h->param.i_bframe_pyramid );
  3505. +                CMP_OPT_FIRST_PASS( "intra_refresh", h->param.b_intra_refresh );
  3506. +                CMP_OPT_FIRST_PASS( "open_gop", h->param.i_open_gop );
  3507.  
  3508. -        if( h->param.i_frame_total < rc->num_entries && h->param.i_frame_total > 0 )
  3509. -        {
  3510. -            x264_log( h, X264_LOG_WARNING, "2nd pass has fewer frames than 1st pass (%d vs %d)\n",
  3511. -                      h->param.i_frame_total, rc->num_entries );
  3512. -        }
  3513. -        if( h->param.i_frame_total > rc->num_entries )
  3514. -        {
  3515. -            x264_log( h, X264_LOG_ERROR, "2nd pass has more frames than 1st pass (%d vs %d)\n",
  3516. -                      h->param.i_frame_total, rc->num_entries );
  3517. -            return -1;
  3518. -        }
  3519. +                if( (p = strstr( opts, "keyint=" )) )
  3520. +                {
  3521. +                    p += 7;
  3522. +                    char buf[13] = "infinite ";
  3523. +                    if( h->param.i_keyint_max != X264_KEYINT_MAX_INFINITE )
  3524. +                        sprintf( buf, "%d ", h->param.i_keyint_max );
  3525. +                    if( strncmp( p, buf, strlen(buf) ) )
  3526. +                    {
  3527. +                        x264_log( h, X264_LOG_ERROR, "different keyint setting than first pass (%.*s vs %.*s)\n",
  3528. +                                  strlen(buf)-1, buf, strcspn(p, " "), p );
  3529. +                        return -1;
  3530. +                    }
  3531. +                }
  3532.  
  3533. -        CHECKED_MALLOCZERO( rc->entry, rc->num_entries * sizeof(ratecontrol_entry_t) );
  3534. +                if( strstr( opts, "qp=0" ) && h->param.rc.i_rc_method == X264_RC_ABR )
  3535. +                    x264_log( h, X264_LOG_WARNING, "1st pass was lossless, bitrate prediction will be inaccurate\n" );
  3536.  
  3537. -        /* init all to skipped p frames */
  3538. -        for( int i = 0; i < rc->num_entries; i++ )
  3539. -        {
  3540. -            ratecontrol_entry_t *rce = &rc->entry[i];
  3541. -            rce->pict_type = SLICE_TYPE_P;
  3542. -            rce->qscale = rce->new_qscale = qp2qscale( 20 );
  3543. -            rce->misc_bits = rc->nmb + 10;
  3544. -            rce->new_qp = 0;
  3545. -        }
  3546. +                if( !strstr( opts, "direct=3" ) && h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO )
  3547. +                {
  3548. +                    x264_log( h, X264_LOG_WARNING, "direct=auto not used on the first pass\n" );
  3549. +                    h->mb.b_direct_auto_write = 1;
  3550. +                }
  3551.  
  3552. -        /* read stats */
  3553. -        p = stats_in;
  3554. -        for( int i = 0; i < rc->num_entries; i++ )
  3555. -        {
  3556. -            ratecontrol_entry_t *rce;
  3557. -            int frame_number;
  3558. -            char pict_type;
  3559. -            int e;
  3560. -            char *next;
  3561. -            float qp;
  3562. -            int ref;
  3563. +                if( ( p = strstr( opts, "b_adapt=" ) ) && sscanf( p, "b_adapt=%d", &i ) && i >= X264_B_ADAPT_NONE && i <= X264_B_ADAPT_TRELLIS )
  3564. +                    h->param.i_bframe_adaptive = i;
  3565. +                else if( h->param.i_bframe )
  3566. +                {
  3567. +                    x264_log( h, X264_LOG_ERROR, "b_adapt method specified in stats file not valid\n" );
  3568. +                    return -1;
  3569. +                }
  3570.  
  3571. -            next= strchr(p, ';');
  3572. -            if( next )
  3573. -                *next++ = 0; //sscanf is unbelievably slow on long strings
  3574. -            e = sscanf( p, " in:%d ", &frame_number );
  3575. +                if( (h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size) && ( p = strstr( opts, "rc_lookahead=" ) ) && sscanf( p, "rc_lookahead=%d", &i ) )
  3576. +                    h->param.rc.i_lookahead = i;
  3577. +            }
  3578.  
  3579. -            if( frame_number < 0 || frame_number >= rc->num_entries )
  3580. +            /* find number of pics */
  3581. +            p = stats_in;
  3582. +            int num_entries;
  3583. +            for( num_entries = -1; p; num_entries++ )
  3584. +                p = strchr( p + 1, ';' );
  3585. +            x264_log( h, X264_LOG_INFO, "num_entries: %d\n", num_entries ); // tmplog
  3586. +            if( !num_entries )
  3587.              {
  3588. -                x264_log( h, X264_LOG_ERROR, "bad frame number (%d) at stats line %d\n", frame_number, i );
  3589. +                x264_log(h, X264_LOG_ERROR, "empty stats file\n");
  3590.                  return -1;
  3591.              }
  3592. -            rce = &rc->entry[frame_number];
  3593. -            rce->direct_mode = 0;
  3594. -
  3595. -            e += sscanf( p, " in:%*d out:%*d type:%c dur:%"SCNd64" cpbdur:%"SCNd64" q:%f tex:%d mv:%d misc:%d imb:%d pmb:%d smb:%d d:%c",
  3596. -                   &pict_type, &rce->i_duration, &rce->i_cpb_duration, &qp, &rce->tex_bits,
  3597. -                   &rce->mv_bits, &rce->misc_bits, &rce->i_count, &rce->p_count,
  3598. -                   &rce->s_count, &rce->direct_mode );
  3599. -
  3600. -            p = strstr( p, "ref:" );
  3601. -            if( !p )
  3602. -                goto parse_error;
  3603. -            p += 4;
  3604. -            for( ref = 0; ref < 16; ref++ )
  3605. +            rc->num_entries = num_entries;
  3606. +
  3607. +            if( h->param.i_frame_total < rc->num_entries && h->param.i_frame_total > 0 )
  3608.              {
  3609. -                if( sscanf( p, " %d", &rce->refcount[ref] ) != 1 )
  3610. -                    break;
  3611. -                p = strchr( p+1, ' ' );
  3612. -                if( !p )
  3613. -                    goto parse_error;
  3614. +                x264_log( h, X264_LOG_WARNING, "2nd pass has fewer frames than 1st pass (%d vs %d)\n",
  3615. +                          h->param.i_frame_total, rc->num_entries );
  3616. +            }
  3617. +            if( h->param.i_frame_total > rc->num_entries )
  3618. +            {
  3619. +                x264_log( h, X264_LOG_ERROR, "2nd pass has more frames than 1st pass (%d vs %d)\n",
  3620. +                          h->param.i_frame_total, rc->num_entries );
  3621. +                return -1;
  3622.              }
  3623. -            rce->refs = ref;
  3624.  
  3625. -            /* find weights */
  3626. -            rce->i_weight_denom[0] = rce->i_weight_denom[1] = -1;
  3627. -            char *w = strchr( p, 'w' );
  3628. -            if( w )
  3629. +            CHECKED_MALLOCZERO( rc->entry, rc->num_entries * sizeof(ratecontrol_entry_t) );
  3630. +
  3631. +            /* init all to skipped p frames */
  3632. +            for( i = 0; i < rc->num_entries; i++ )
  3633.              {
  3634. -                int count = sscanf( w, "w:%hd,%hd,%hd,%hd,%hd,%hd,%hd,%hd",
  3635. -                                    &rce->i_weight_denom[0], &rce->weight[0][0], &rce->weight[0][1],
  3636. -                                    &rce->i_weight_denom[1], &rce->weight[1][0], &rce->weight[1][1],
  3637. -                                    &rce->weight[2][0], &rce->weight[2][1] );
  3638. -                if( count == 3 )
  3639. -                    rce->i_weight_denom[1] = -1;
  3640. -                else if ( count != 8 )
  3641. -                    rce->i_weight_denom[0] = rce->i_weight_denom[1] = -1;
  3642. +                ratecontrol_entry_t *rce = &rc->entry[i];
  3643. +                rce->pict_type = SLICE_TYPE_P;
  3644. +                rce->b_anchor = 0;
  3645. +                rce->qscale = rce->new_qscale = qp2qscale( 20 );
  3646. +                rce->misc_bits = rc->nmb + 10;
  3647. +                rce->new_qp = 0;
  3648.              }
  3649.  
  3650. -            if( pict_type != 'b' )
  3651. -                rce->kept_as_ref = 1;
  3652. -            switch( pict_type )
  3653. +            /* read stats */
  3654. +            p = stats_in;
  3655. +            for( i = 0; i < rc->num_entries; i++ )
  3656.              {
  3657. +                ratecontrol_entry_t *rce;
  3658. +                int frame_number;
  3659. +                char pict_type;
  3660. +                int e;
  3661. +                char *next;
  3662. +                float qp;
  3663. +                int ref;
  3664. +
  3665. +                next= strchr(p, ';');
  3666. +                if( next )
  3667. +                    *next++ = 0; //sscanf is unbelievably slow on long strings
  3668. +                e = sscanf( p, " in:%d ", &frame_number );
  3669. +
  3670. +                if( frame_number < 0 || frame_number >= rc->num_entries )
  3671. +                {
  3672. +                    x264_log( h, X264_LOG_ERROR, "bad frame number (%d) at stats line %d\n", frame_number, i );
  3673. +                    return -1;
  3674. +                }
  3675. +                rce = &rc->entry[frame_number];
  3676. +                rce->direct_mode = 0;
  3677. +
  3678. +                e += sscanf( p, " in:%*d out:%*d type:%c dur:%"SCNd64" cpbdur:%"SCNd64" q:%f tex:%d mv:%d misc:%d imb:%d pmb:%d smb:%d d:%c",
  3679. +                             &pict_type, &rce->i_duration, &rce->i_cpb_duration, &qp, &rce->tex_bits,
  3680. +                             &rce->mv_bits, &rce->misc_bits, &rce->i_count, &rce->p_count,
  3681. +                             &rce->s_count, &rce->direct_mode );
  3682. +
  3683. +                p = strstr( p, "ref:" );
  3684. +                if( !p )
  3685. +                    goto parse_error;
  3686. +                p += 4;
  3687. +                for( ref = 0; ref < 16; ref++ )
  3688. +                {
  3689. +                    if( sscanf( p, " %d", &rce->refcount[ref] ) != 1 )
  3690. +                        break;
  3691. +                    p = strchr( p+1, ' ' );
  3692. +                    if( !p )
  3693. +                        goto parse_error;
  3694. +                }
  3695. +                rce->refs = ref;
  3696. +
  3697. +                /* find weights */
  3698. +                rce->i_weight_denom[0] = rce->i_weight_denom[1] = -1;
  3699. +                char *w = strchr( p, 'w' );
  3700. +                if( w )
  3701. +                {
  3702. +                    int count = sscanf( w, "w:%hd,%hd,%hd,%hd,%hd,%hd,%hd,%hd",
  3703. +                                        &rce->i_weight_denom[0], &rce->weight[0][0], &rce->weight[0][1],
  3704. +                                        &rce->i_weight_denom[1], &rce->weight[1][0], &rce->weight[1][1],
  3705. +                                        &rce->weight[2][0], &rce->weight[2][1] );
  3706. +                    if( count == 3 )
  3707. +                        rce->i_weight_denom[1] = -1;
  3708. +                    else if ( count != 8 )
  3709. +                        rce->i_weight_denom[0] = rce->i_weight_denom[1] = -1;
  3710. +                }
  3711. +
  3712. +                if( pict_type != 'b' )
  3713. +                    rce->kept_as_ref = 1;
  3714. +                switch( pict_type )
  3715. +                {
  3716.                  case 'I':
  3717.                      rce->frame_type = X264_TYPE_IDR;
  3718.                      rce->pict_type  = SLICE_TYPE_I;
  3719. @@ -892,83 +1063,100 @@ int x264_ratecontrol_new( x264_t *h )
  3720.                      rce->pict_type  = SLICE_TYPE_B;
  3721.                      break;
  3722.                  default:  e = -1; break;
  3723. -            }
  3724. -            if( e < 12 )
  3725. -            {
  3726. +                }
  3727. +                if( e < 12 )
  3728. +                {
  3729.  parse_error:
  3730. -                x264_log( h, X264_LOG_ERROR, "statistics are damaged at line %d, parser out=%d\n", i, e );
  3731. -                return -1;
  3732. +                    x264_log( h, X264_LOG_ERROR, "statistics are damaged at line %d, parser out=%d\n", i, e );
  3733. +                    return -1;
  3734. +                }
  3735. +                rce->qscale = qp2qscale( qp );
  3736. +                p = next;
  3737.              }
  3738. -            rce->qscale = qp2qscale( qp );
  3739. -            p = next;
  3740. -        }
  3741.  
  3742. -        x264_free( stats_buf );
  3743. -
  3744. -        if( h->param.rc.i_rc_method == X264_RC_ABR )
  3745. -        {
  3746. -            if( init_pass2( h ) < 0 )
  3747. -                return -1;
  3748. -        } /* else we're using constant quant, so no need to run the bitrate allocation */
  3749. +            x264_free( stats_buf );
  3750. +        }
  3751.      }
  3752. -
  3753. -    /* Open output file */
  3754. -    /* If input and output files are the same, output to a temp file
  3755. -     * and move it to the real name only when it's complete */
  3756. -    if( h->param.rc.b_stat_write )
  3757. +    if( h->param.rc.i_rc_method == X264_RC_ABR )
  3758.      {
  3759. -        char *p;
  3760. -        rc->psz_stat_file_tmpname = x264_strcat_filename( h->param.rc.psz_stat_out, ".temp" );
  3761. -        if( !rc->psz_stat_file_tmpname )
  3762. -            return -1;
  3763. -
  3764. -        rc->p_stat_file_out = fopen( rc->psz_stat_file_tmpname, "wb" );
  3765. -        if( rc->p_stat_file_out == NULL )
  3766. -        {
  3767. -            x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open stats file\n");
  3768. +        if( init_pass2( h ) < 0 )
  3769.              return -1;
  3770. -        }
  3771. -
  3772. -        p = x264_param2string( &h->param, 1 );
  3773. -        if( p )
  3774. -            fprintf( rc->p_stat_file_out, "#options: %s\n", p );
  3775. -        x264_free( p );
  3776. -        if( h->param.rc.b_mb_tree && !h->param.rc.b_stat_read )
  3777. -        {
  3778. -            rc->psz_mbtree_stat_file_tmpname = x264_strcat_filename( h->param.rc.psz_stat_out, ".mbtree.temp" );
  3779. -            rc->psz_mbtree_stat_file_name = x264_strcat_filename( h->param.rc.psz_stat_out, ".mbtree" );
  3780. -            if( !rc->psz_mbtree_stat_file_tmpname || !rc->psz_mbtree_stat_file_name )
  3781. +    } /* else we're using constant quant, so no need to run the bitrate allocation */
  3782. +
  3783. +    for (int view=0; view<rc_num; view++) {
  3784. +        rc = h->rc_mvc[view];
  3785. +        /* Open output file */
  3786. +        /* If input and output files are the same, output to a temp file
  3787. +         * and move it to the real name only when it's complete */
  3788. +        if( h->param.rc.b_stat_write )
  3789. +        {
  3790. +            char *p;
  3791. +            if (view == 0) {
  3792. +                rc->psz_stat_file_tmpname = x264_strcat_filename( h->param.rc.psz_stat_out, ".temp" );
  3793. +            } else {
  3794. +                char buf[10];
  3795. +                sprintf(buf, ".temp_%d", view+1);
  3796. +                rc->psz_stat_file_tmpname = x264_strcat_filename( h->param.rc.psz_stat_out, buf );
  3797. +            }
  3798. +            if( !rc->psz_stat_file_tmpname )
  3799.                  return -1;
  3800.  
  3801. -            rc->p_mbtree_stat_file_out = fopen( rc->psz_mbtree_stat_file_tmpname, "wb" );
  3802. -            if( rc->p_mbtree_stat_file_out == NULL )
  3803. +            rc->p_stat_file_out = fopen( rc->psz_stat_file_tmpname, "wb" );
  3804. +            if( rc->p_stat_file_out == NULL )
  3805.              {
  3806. -                x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open mbtree stats file\n");
  3807. +                x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open stats file\n");
  3808.                  return -1;
  3809.              }
  3810. +
  3811. +            p = x264_param2string( &h->param, 1, view);
  3812. +            if( p )
  3813. +                fprintf( rc->p_stat_file_out, "#options: %s\n", p );
  3814. +            x264_free( p );
  3815. +            if( h->param.rc.b_mb_tree && !h->param.rc.b_stat_read )
  3816. +            {
  3817. +                rc->psz_mbtree_stat_file_tmpname = x264_strcat_filename( h->param.rc.psz_stat_out, ".mbtree.temp" );
  3818. +                rc->psz_mbtree_stat_file_name = x264_strcat_filename( h->param.rc.psz_stat_out, ".mbtree" );
  3819. +                if( !rc->psz_mbtree_stat_file_tmpname || !rc->psz_mbtree_stat_file_name )
  3820. +                    return -1;
  3821. +
  3822. +                rc->p_mbtree_stat_file_out = fopen( rc->psz_mbtree_stat_file_tmpname, "wb" );
  3823. +                if( rc->p_mbtree_stat_file_out == NULL )
  3824. +                {
  3825. +                    x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open mbtree stats file\n");
  3826. +                    return -1;
  3827. +                }
  3828. +            }
  3829.          }
  3830. -    }
  3831.  
  3832. -    if( h->param.rc.b_mb_tree && (h->param.rc.b_stat_read || h->param.rc.b_stat_write) )
  3833. -    {
  3834. -        CHECKED_MALLOC( rc->qp_buffer[0], h->mb.i_mb_count * sizeof(uint16_t) );
  3835. -        if( h->param.i_bframe_pyramid && h->param.rc.b_stat_read )
  3836. -            CHECKED_MALLOC( rc->qp_buffer[1], h->mb.i_mb_count * sizeof(uint16_t) );
  3837. -        rc->qpbuf_pos = -1;
  3838. +        if( h->param.rc.b_mb_tree && (h->param.rc.b_stat_read || h->param.rc.b_stat_write) )
  3839. +        {
  3840. +            CHECKED_MALLOC( rc->qp_buffer[0], h->mb.i_mb_count * sizeof(uint16_t) );
  3841. +            if( h->param.i_bframe_pyramid && h->param.rc.b_stat_read )
  3842. +                CHECKED_MALLOC( rc->qp_buffer[1], h->mb.i_mb_count * sizeof(uint16_t) );
  3843. +            rc->qpbuf_pos = -1;
  3844. +        }
  3845.      }
  3846.  
  3847. -    for( int i = 0; i<h->param.i_threads; i++ )
  3848. +    for( i = 0; i<h->param.i_threads; i++ )
  3849.      {
  3850. -        h->thread[i]->rc = rc+i;
  3851. -        if( i )
  3852. -        {
  3853. -            rc[i] = rc[0];
  3854. -            h->thread[i]->param = h->param;
  3855. -            h->thread[i]->mb.b_variable_qp = h->mb.b_variable_qp;
  3856. -            h->thread[i]->mb.ip_offset = h->mb.ip_offset;
  3857. +        for (int view=rc_num-1; view>=0; view--) {
  3858. +            rc = h->rc_mvc[view];
  3859. +            h->thread[i]->rc_mvc[view] = rc+i;
  3860. +            if( i )
  3861. +            {
  3862. +                rc[i] = rc[0];
  3863. +            }
  3864. +#ifdef __DEBUG
  3865. +            x264_log(h, X264_LOG_INFO, "thread[%d]->rc_mvc[%d] = %p\n",
  3866. +                     i, view, h->thread[i]->rc_mvc[view]);
  3867. +#endif
  3868.          }
  3869. +        //h->thread[i]->rc = rc+i;
  3870. +        h->thread[i]->param = h->param;
  3871. +        h->thread[i]->mb.b_variable_qp = h->mb.b_variable_qp;
  3872. +        h->thread[i]->mb.ip_offset = h->mb.ip_offset;
  3873.      }
  3874. -
  3875. +    
  3876.      return 0;
  3877.  fail:
  3878.      return -1;
  3879. @@ -1019,8 +1207,12 @@ fail:
  3880.  
  3881.  static int parse_zones( x264_t *h )
  3882.  {
  3883. -    x264_ratecontrol_t *rc = h->rc;
  3884. -    if( h->param.rc.psz_zones && !h->param.rc.i_zones )
  3885. +    int rc_num = get_view_num(h);
  3886. +    if (rc_num > 1) return 0;
  3887. +    int view = 0;
  3888. +
  3889. +    x264_ratecontrol_t *rc = h->rc_mvc[view];
  3890. +    if( h->param.rc.psz_zones && !h->param.rc.i_zones)
  3891.      {
  3892.          char *psz_zones, *p;
  3893.          CHECKED_MALLOC( psz_zones, strlen( h->param.rc.psz_zones )+1 );
  3894. @@ -1085,9 +1277,11 @@ fail:
  3895.  
  3896.  static x264_zone_t *get_zone( x264_t *h, int frame_num )
  3897.  {
  3898. -    for( int i = h->rc->i_zones - 1; i >= 0; i-- )
  3899. +    x264_ratecontrol_t * rc = h->rc_mvc[get_view_id(h)];
  3900. +
  3901. +    for( int i = rc->i_zones - 1; i >= 0; i-- )
  3902.      {
  3903. -        x264_zone_t *z = &h->rc->zones[i];
  3904. +        x264_zone_t *z = &rc->zones[i];
  3905.          if( frame_num >= z->i_start && frame_num <= z->i_end )
  3906.              return z;
  3907.      }
  3908. @@ -1096,72 +1290,83 @@ static x264_zone_t *get_zone( x264_t *h, int frame_num )
  3909.  
  3910.  void x264_ratecontrol_summary( x264_t *h )
  3911.  {
  3912. -    x264_ratecontrol_t *rc = h->rc;
  3913. -    if( rc->b_abr && h->param.rc.i_rc_method == X264_RC_ABR && rc->cbr_decay > .9999 )
  3914. -    {
  3915. -        double base_cplx = h->mb.i_mb_count * (h->param.i_bframe ? 120 : 80);
  3916. -        double mbtree_offset = h->param.rc.b_mb_tree ? (1.0-h->param.rc.f_qcompress)*13.5 : 0;
  3917. -        x264_log( h, X264_LOG_INFO, "final ratefactor: %.2f\n",
  3918. -                  qscale2qp( pow( base_cplx, 1 - rc->qcompress )
  3919. -                             * rc->cplxr_sum / rc->wanted_bits_window ) - mbtree_offset - QP_BD_OFFSET );
  3920. +    int rc_num = get_view_num(h);
  3921. +
  3922. +    for (int view = 0; view < rc_num; view++) {
  3923. +        x264_ratecontrol_t *rc = h->rc_mvc[view];
  3924. +        if( rc->b_abr && h->param.rc.i_rc_method == X264_RC_ABR && rc->cbr_decay > .9999 )
  3925. +        {
  3926. +            char dep_string[15];
  3927. +            if (view > 0) sprintf(dep_string, " (view %d)", view);
  3928. +            double base_cplx = h->mb.i_mb_count * (h->param.i_bframe ? 120 : 80);
  3929. +            double mbtree_offset = h->param.rc.b_mb_tree ? (1.0-h->param.rc.f_qcompress)*13.5 : 0;
  3930. +            x264_log( h, X264_LOG_INFO, "final ratefactor%s: %.2f\n",
  3931. +                      view == 0 ? "" : dep_string,
  3932. +                      qscale2qp( pow( base_cplx, 1 - rc->qcompress )
  3933. +                                 * rc->cplxr_sum / rc->wanted_bits_window ) - mbtree_offset - QP_BD_OFFSET );
  3934. +        }
  3935.      }
  3936.  }
  3937.  
  3938.  void x264_ratecontrol_delete( x264_t *h )
  3939.  {
  3940. -    x264_ratecontrol_t *rc = h->rc;
  3941. -    int b_regular_file;
  3942. +    int rc_num = get_view_num(h);
  3943.  
  3944. -    if( rc->p_stat_file_out )
  3945. -    {
  3946. -        b_regular_file = x264_is_regular_file( rc->p_stat_file_out );
  3947. -        fclose( rc->p_stat_file_out );
  3948. -        if( h->i_frame >= rc->num_entries && b_regular_file )
  3949. -            if( rename( rc->psz_stat_file_tmpname, h->param.rc.psz_stat_out ) != 0 )
  3950. -            {
  3951. -                x264_log( h, X264_LOG_ERROR, "failed to rename \"%s\" to \"%s\"\n",
  3952. -                          rc->psz_stat_file_tmpname, h->param.rc.psz_stat_out );
  3953. -            }
  3954. -        x264_free( rc->psz_stat_file_tmpname );
  3955. -    }
  3956. -    if( rc->p_mbtree_stat_file_out )
  3957. -    {
  3958. -        b_regular_file = x264_is_regular_file( rc->p_mbtree_stat_file_out );
  3959. -        fclose( rc->p_mbtree_stat_file_out );
  3960. -        if( h->i_frame >= rc->num_entries && b_regular_file )
  3961. -            if( rename( rc->psz_mbtree_stat_file_tmpname, rc->psz_mbtree_stat_file_name ) != 0 )
  3962. -            {
  3963. -                x264_log( h, X264_LOG_ERROR, "failed to rename \"%s\" to \"%s\"\n",
  3964. -                          rc->psz_mbtree_stat_file_tmpname, rc->psz_mbtree_stat_file_name );
  3965. -            }
  3966. -        x264_free( rc->psz_mbtree_stat_file_tmpname );
  3967. -        x264_free( rc->psz_mbtree_stat_file_name );
  3968. -    }
  3969. -    if( rc->p_mbtree_stat_file_in )
  3970. -        fclose( rc->p_mbtree_stat_file_in );
  3971. -    x264_free( rc->pred );
  3972. -    x264_free( rc->pred_b_from_p );
  3973. -    x264_free( rc->entry );
  3974. -    x264_free( rc->qp_buffer[0] );
  3975. -    x264_free( rc->qp_buffer[1] );
  3976. -    if( rc->zones )
  3977. -    {
  3978. -        x264_free( rc->zones[0].param );
  3979. -        for( int i = 1; i < rc->i_zones; i++ )
  3980. -            if( rc->zones[i].param != rc->zones[0].param && rc->zones[i].param->param_free )
  3981. -                rc->zones[i].param->param_free( rc->zones[i].param );
  3982. -        x264_free( rc->zones );
  3983. +    for (int view = 0; view < rc_num; view++) {
  3984. +        x264_ratecontrol_t *rc = h->rc_mvc[view];
  3985. +        int b_regular_file;
  3986. +
  3987. +        if( rc->p_stat_file_out )
  3988. +        {
  3989. +            b_regular_file = x264_is_regular_file( rc->p_stat_file_out );
  3990. +            fclose( rc->p_stat_file_out );
  3991. +            if( h->i_frame >= rc->num_entries && b_regular_file )
  3992. +                if( rename( rc->psz_stat_file_tmpname, h->param.rc.psz_stat_out ) != 0 )
  3993. +                {
  3994. +                    x264_log( h, X264_LOG_ERROR, "failed to rename \"%s\" to \"%s\"\n",
  3995. +                              rc->psz_stat_file_tmpname, h->param.rc.psz_stat_out );
  3996. +                }
  3997. +            x264_free( rc->psz_stat_file_tmpname );
  3998. +        }
  3999. +        if( rc->p_mbtree_stat_file_out )
  4000. +        {
  4001. +            b_regular_file = x264_is_regular_file( rc->p_mbtree_stat_file_out );
  4002. +            fclose( rc->p_mbtree_stat_file_out );
  4003. +            if( h->i_frame >= rc->num_entries && b_regular_file )
  4004. +                if( rename( rc->psz_mbtree_stat_file_tmpname, rc->psz_mbtree_stat_file_name ) != 0 )
  4005. +                {
  4006. +                    x264_log( h, X264_LOG_ERROR, "failed to rename \"%s\" to \"%s\"\n",
  4007. +                              rc->psz_mbtree_stat_file_tmpname, rc->psz_mbtree_stat_file_name );
  4008. +                }
  4009. +            x264_free( rc->psz_mbtree_stat_file_tmpname );
  4010. +            x264_free( rc->psz_mbtree_stat_file_name );
  4011. +        }
  4012. +        if( rc->p_mbtree_stat_file_in )
  4013. +            fclose( rc->p_mbtree_stat_file_in );
  4014. +        x264_free( rc->pred );
  4015. +        x264_free( rc->pred_b_from_p );
  4016. +        x264_free( rc->entry );
  4017. +        x264_free( rc->qp_buffer[0] );
  4018. +        x264_free( rc->qp_buffer[1] );
  4019. +        if( rc->zones )
  4020. +        {
  4021. +            x264_free( rc->zones[0].param );
  4022. +            for( int i = 1; i < rc->i_zones; i++ )
  4023. +                if( rc->zones[i].param != rc->zones[0].param && rc->zones[i].param->param_free )
  4024. +                    rc->zones[i].param->param_free( rc->zones[i].param );
  4025. +            x264_free( rc->zones );
  4026. +        }
  4027. +        x264_free( rc );
  4028.      }
  4029. -    x264_free( rc );
  4030.  }
  4031.  
  4032.  static void accum_p_qp_update( x264_t *h, float qp )
  4033.  {
  4034. -    x264_ratecontrol_t *rc = h->rc;
  4035. +    x264_ratecontrol_t *rc = h->rc_mvc[get_view_id(h)];
  4036.      rc->accum_p_qp   *= .95;
  4037.      rc->accum_p_norm *= .95;
  4038.      rc->accum_p_norm += 1;
  4039. -    if( h->sh.i_type == SLICE_TYPE_I )
  4040. +    if( IS_SLICE_TYPE_I(h->sh.i_type)/* || h->sh.b_anchor*/)
  4041.          rc->accum_p_qp += qp + rc->ip_offset;
  4042.      else
  4043.          rc->accum_p_qp += qp;
  4044. @@ -1170,7 +1375,9 @@ static void accum_p_qp_update( x264_t *h, float qp )
  4045.  /* Before encoding a frame, choose a QP for it */
  4046.  void x264_ratecontrol_start( x264_t *h, int i_force_qp, int overhead )
  4047.  {
  4048. -    x264_ratecontrol_t *rc = h->rc;
  4049. +    int view = get_view_id(h);
  4050. +    x264_ratecontrol_t *rc = h->rc_mvc[view];
  4051. +    x264_sps_t * sps = get_view_id(h)==0 ? h->sps : h->subset_sps;
  4052.      ratecontrol_entry_t *rce = NULL;
  4053.      x264_zone_t *zone = get_zone( h, h->fenc->i_frame );
  4054.      float q;
  4055. @@ -1185,9 +1392,9 @@ void x264_ratecontrol_start( x264_t *h, int i_force_qp, int overhead )
  4056.      {
  4057.          int frame = h->fenc->i_frame;
  4058.          assert( frame >= 0 && frame < rc->num_entries );
  4059. -        rce = h->rc->rce = &h->rc->entry[frame];
  4060. +        rce = rc->rce = &rc->entry[frame];
  4061.  
  4062. -        if( h->sh.i_type == SLICE_TYPE_B
  4063. +        if( IS_SLICE_TYPE_B(h->sh.i_type)
  4064.              && h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO )
  4065.          {
  4066.              h->sh.b_direct_spatial_mv_pred = ( rce->direct_mode == 's' );
  4067. @@ -1198,8 +1405,8 @@ void x264_ratecontrol_start( x264_t *h, int i_force_qp, int overhead )
  4068.      if( rc->b_vbv )
  4069.      {
  4070.          memset( h->fdec->i_row_bits, 0, h->mb.i_mb_height * sizeof(int) );
  4071. -        rc->row_pred = &rc->row_preds[h->sh.i_type];
  4072. -        rc->buffer_rate = h->fenc->i_cpb_duration * rc->vbv_max_rate * h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
  4073. +        rc->row_pred = &rc->row_preds[/*h->sh.b_anchor ? SLICE_TYPE_I :*/ h->sh.i_type];
  4074. +        rc->buffer_rate = h->fenc->i_cpb_duration * rc->vbv_max_rate * sps->vui.i_num_units_in_tick / sps->vui.i_time_scale;
  4075.          update_vbv_plan( h, overhead );
  4076.  
  4077.          const x264_level_t *l = x264_levels;
  4078. @@ -1213,12 +1420,12 @@ void x264_ratecontrol_start( x264_t *h, int i_force_qp, int overhead )
  4079.              mincr = 4;
  4080.  
  4081.          /* High 10 doesn't require minCR, so just set the maximum to a large value. */
  4082. -        if( h->sps->i_profile_idc == PROFILE_HIGH10 )
  4083. +        if( sps->i_profile_idc == PROFILE_HIGH10 )
  4084.              rc->frame_size_maximum = 1e9;
  4085.          else
  4086.          {
  4087.              /* The spec has a bizarre special case for the first frame. */
  4088. -            if( h->i_frame == 0 )
  4089. +            if( h->i_frame == 0 || (h->i_frame == 1 && h->param.b_mvc))
  4090.              {
  4091.                  //384 * ( Max( PicSizeInMbs, fR * MaxMBPS ) + MaxMBPS * ( tr( 0 ) - tr,n( 0 ) ) ) / MinCR
  4092.                  double fr = 1. / 172;
  4093. @@ -1228,14 +1435,21 @@ void x264_ratecontrol_start( x264_t *h, int i_force_qp, int overhead )
  4094.              else
  4095.              {
  4096.                  //384 * MaxMBPS * ( tr( n ) - tr( n - 1 ) ) / MinCR
  4097. -                rc->frame_size_maximum = 384 * BIT_DEPTH * ((double)h->fenc->i_cpb_duration * h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale) * l->mbps / mincr;
  4098. +                rc->frame_size_maximum = 384 * BIT_DEPTH * ((double)h->fenc->i_cpb_duration * sps->vui.i_num_units_in_tick / sps->vui.i_time_scale) * l->mbps / mincr;
  4099. +#ifdef __DEBUG
  4100. +                x264_log(h, X264_LOG_INFO, "cpb_duration = %d, num_units_in_tick = %d, time_scale = %d\n",
  4101. +                         h->fenc->i_cpb_duration, sps->vui.i_num_units_in_tick, sps->vui.i_time_scale);
  4102. +#endif
  4103.              }
  4104.          }
  4105.      }
  4106.  
  4107. -    if( h->sh.i_type != SLICE_TYPE_B )
  4108. +    if( !IS_SLICE_TYPE_B(h->sh.i_type) ) {
  4109.          rc->bframes = h->fenc->i_bframes;
  4110. -
  4111. +#ifdef __DEBUG
  4112. +        x264_log(h, X264_LOG_INFO, "[%4d]: rc->bframes = %d (%s)[%p]\n", h->fenc->i_frame, h->fenc->i_bframes, h->b_dependent ? "d" : "m", rc);
  4113. +#endif
  4114. +    }
  4115.      if( i_force_qp != X264_QP_AUTO )
  4116.      {
  4117.          q = i_force_qp - 1;
  4118. @@ -1251,7 +1465,7 @@ void x264_ratecontrol_start( x264_t *h, int i_force_qp, int overhead )
  4119.      }
  4120.      else /* CQP */
  4121.      {
  4122. -        if( h->sh.i_type == SLICE_TYPE_B && h->fdec->b_kept_as_ref )
  4123. +        if( IS_SLICE_TYPE_B(h->sh.i_type) && h->fdec->b_kept_as_ref )
  4124.              q = ( rc->qp_constant[ SLICE_TYPE_B ] + rc->qp_constant[ SLICE_TYPE_P ] ) / 2;
  4125.          else
  4126.              q = rc->qp_constant[ h->sh.i_type ];
  4127. @@ -1278,20 +1492,21 @@ void x264_ratecontrol_start( x264_t *h, int i_force_qp, int overhead )
  4128.  
  4129.      accum_p_qp_update( h, rc->qpm );
  4130.  
  4131. -    if( h->sh.i_type != SLICE_TYPE_B )
  4132. -        rc->last_non_b_pict_type = h->sh.i_type;
  4133. +    if( !IS_SLICE_TYPE_B(h->sh.i_type) ) {
  4134. +        rc->last_non_b_pict_type = h->sh.b_anchor ? SLICE_TYPE_I : h->sh.i_type;
  4135. +    }
  4136.  }
  4137.  
  4138.  static double predict_row_size( x264_t *h, int y, double qp )
  4139.  {
  4140.      /* average between two predictors:
  4141.       * absolute SATD, and scaled bit cost of the colocated row in the previous frame */
  4142. -    x264_ratecontrol_t *rc = h->rc;
  4143. +    x264_ratecontrol_t *rc = h->rc_mvc[get_view_id(h)];
  4144.      double pred_s = predict_size( rc->row_pred[0], qp2qscale( qp ), h->fdec->i_row_satd[y] );
  4145.      double pred_t = 0;
  4146. -    if( h->sh.i_type == SLICE_TYPE_I || qp >= h->fref[0][0]->f_row_qp[y] )
  4147. +    if( h->sh.i_type == SLICE_TYPE_I || h->sh.b_anchor || qp >= h->fref[0][0]->f_row_qp[y] )
  4148.      {
  4149. -        if( h->sh.i_type == SLICE_TYPE_P
  4150. +        if( IS_SLICE_TYPE_P(h->sh.i_type) && !h->sh.b_anchor
  4151.              && h->fref[0][0]->i_type == h->fdec->i_type
  4152.              && h->fref[0][0]->i_row_satd[y] > 0
  4153.              && (abs(h->fref[0][0]->i_row_satd[y] - h->fdec->i_row_satd[y]) < h->fdec->i_row_satd[y]/2))
  4154. @@ -1331,8 +1546,9 @@ static double predict_row_size_sum( x264_t *h, int y, double qp )
  4155.  
  4156.  void x264_ratecontrol_mb( x264_t *h, int bits )
  4157.  {
  4158. -    x264_ratecontrol_t *rc = h->rc;
  4159. +    x264_ratecontrol_t *rc = h->rc_mvc[get_view_id(h)];
  4160.      const int y = h->mb.i_mb_y;
  4161. +    int b_anchor = h->sh.b_anchor;
  4162.  
  4163.      x264_emms();
  4164.  
  4165. @@ -1346,7 +1562,7 @@ void x264_ratecontrol_mb( x264_t *h, int bits )
  4166.      h->fdec->f_row_qp[y] = rc->qpm;
  4167.  
  4168.      update_predictor( rc->row_pred[0], qp2qscale( rc->qpm ), h->fdec->i_row_satd[y], h->fdec->i_row_bits[y] );
  4169. -    if( h->sh.i_type == SLICE_TYPE_P && rc->qpm < h->fref[0][0]->f_row_qp[y] )
  4170. +    if( IS_SLICE_TYPE_P(h->sh.i_type) && !b_anchor && rc->qpm < h->fref[0][0]->f_row_qp[y] )
  4171.          update_predictor( rc->row_pred[1], qp2qscale( rc->qpm ), h->fdec->i_row_satds[0][0][y], h->fdec->i_row_bits[y] );
  4172.  
  4173.      /* tweak quality based on difference from predicted size */
  4174. @@ -1361,7 +1577,7 @@ void x264_ratecontrol_mb( x264_t *h, int bits )
  4175.          float step_size = 0.5;
  4176.  
  4177.          /* B-frames shouldn't use lower QP than their reference frames. */
  4178. -        if( h->sh.i_type == SLICE_TYPE_B )
  4179. +        if( IS_SLICE_TYPE_B(h->sh.i_type) )
  4180.          {
  4181.              qp_min = X264_MAX( qp_min, X264_MAX( h->fref[0][0]->f_row_qp[y+1], h->fref[1][0]->f_row_qp[y+1] ) );
  4182.              rc->qpm = X264_MAX( rc->qpm, qp_min );
  4183. @@ -1393,7 +1609,7 @@ void x264_ratecontrol_mb( x264_t *h, int bits )
  4184.          if( row_bits_so_far( h, y ) < 0.05 * slice_size_planned )
  4185.              return;
  4186.  
  4187. -        if( h->sh.i_type != SLICE_TYPE_I )
  4188. +        if( !IS_SLICE_TYPE_I(h->sh.i_type) && !h->sh.b_anchor)
  4189.              rc_tol /= 2;
  4190.  
  4191.          if( !rc->b_vbv_min_rate )
  4192. @@ -1426,20 +1642,20 @@ void x264_ratecontrol_mb( x264_t *h, int bits )
  4193.              b1 = predict_row_size_sum( h, y, rc->qpm ) + size_of_other_slices;
  4194.          }
  4195.  
  4196. -        h->rc->frame_size_estimated = predict_row_size_sum( h, y, rc->qpm );
  4197. +        rc->frame_size_estimated = predict_row_size_sum( h, y, rc->qpm );
  4198.      }
  4199.  }
  4200.  
  4201.  int x264_ratecontrol_qp( x264_t *h )
  4202.  {
  4203.      x264_emms();
  4204. -    return x264_clip3( h->rc->qpm + .5, h->param.rc.i_qp_min, h->param.rc.i_qp_max );
  4205. +    return x264_clip3( h->rc_mvc[get_view_id(h)]->qpm + .5, h->param.rc.i_qp_min, h->param.rc.i_qp_max );
  4206.  }
  4207.  
  4208.  int x264_ratecontrol_mb_qp( x264_t *h )
  4209.  {
  4210.      x264_emms();
  4211. -    float qp = h->rc->qpm;
  4212. +    float qp = h->rc_mvc[get_view_id(h)]->qpm;
  4213.      if( h->param.rc.i_aq_mode )
  4214.      {
  4215.           /* MB-tree currently doesn't adjust quantizers in unreferenced frames. */
  4216. @@ -1455,7 +1671,8 @@ int x264_ratecontrol_mb_qp( x264_t *h )
  4217.  /* In 2pass, force the same frame types as in the 1st pass */
  4218.  int x264_ratecontrol_slice_type( x264_t *h, int frame_num )
  4219.  {
  4220. -    x264_ratecontrol_t *rc = h->rc;
  4221. +    int view = get_view_id(h);
  4222. +    x264_ratecontrol_t *rc = h->rc_mvc[view];
  4223.      if( h->param.rc.b_stat_read )
  4224.      {
  4225.          if( frame_num >= rc->num_entries )
  4226. @@ -1463,8 +1680,8 @@ int x264_ratecontrol_slice_type( x264_t *h, int frame_num )
  4227.              /* We could try to initialize everything required for ABR and
  4228.               * adaptive B-frames, but that would be complicated.
  4229.               * So just calculate the average QP used so far. */
  4230. -            h->param.rc.i_qp_constant = (h->stat.i_frame_count[SLICE_TYPE_P] == 0) ? 24 + QP_BD_OFFSET
  4231. -                                      : 1 + h->stat.f_frame_qp[SLICE_TYPE_P] / h->stat.i_frame_count[SLICE_TYPE_P];
  4232. +            h->param.rc.i_qp_constant = (view ? h->stat.i_frame_dep_count[SLICE_TYPE_P] : h->stat.i_frame_count[SLICE_TYPE_P]) == 0 ? 24 + QP_BD_OFFSET
  4233. +                : 1 + (view ? h->stat.f_frame_dep_qp[SLICE_TYPE_P] / h->stat.i_frame_dep_count[SLICE_TYPE_P] : h->stat.f_frame_qp[SLICE_TYPE_P] / h->stat.i_frame_count[SLICE_TYPE_P]);
  4234.              rc->qp_constant[SLICE_TYPE_P] = x264_clip3( h->param.rc.i_qp_constant, 0, QP_MAX );
  4235.              rc->qp_constant[SLICE_TYPE_I] = x264_clip3( (int)( qscale2qp( qp2qscale( h->param.rc.i_qp_constant ) / fabs( h->param.rc.f_ip_factor )) + 0.5 ), 0, QP_MAX );
  4236.              rc->qp_constant[SLICE_TYPE_B] = x264_clip3( (int)( qscale2qp( qp2qscale( h->param.rc.i_qp_constant ) * fabs( h->param.rc.f_pb_factor )) + 0.5 ), 0, QP_MAX );
  4237. @@ -1496,7 +1713,7 @@ int x264_ratecontrol_slice_type( x264_t *h, int frame_num )
  4238.  
  4239.  void x264_ratecontrol_set_weights( x264_t *h, x264_frame_t *frm )
  4240.  {
  4241. -    ratecontrol_entry_t *rce = &h->rc->entry[frm->i_frame];
  4242. +    ratecontrol_entry_t *rce = &h->rc_mvc[get_view_id(h)]->entry[frm->i_frame];
  4243.      if( h->param.analyse.i_weighted_pred <= 0 )
  4244.          return;
  4245.  
  4246. @@ -1513,7 +1730,9 @@ void x264_ratecontrol_set_weights( x264_t *h, x264_frame_t *frm )
  4247.  /* After encoding one frame, save stats and update ratecontrol state */
  4248.  int x264_ratecontrol_end( x264_t *h, int bits, int *filler )
  4249.  {
  4250. -    x264_ratecontrol_t *rc = h->rc;
  4251. +    int view = get_view_id(h);
  4252. +    x264_ratecontrol_t *rc = h->rc_mvc[view];
  4253. +    x264_sps_t * sps = get_view_id(h)==0 ? h->sps : h->subset_sps;
  4254.      const int *mbs = h->stat.frame.i_mb_count;
  4255.  
  4256.      x264_emms();
  4257. @@ -1529,8 +1748,8 @@ int x264_ratecontrol_end( x264_t *h, int bits, int *filler )
  4258.  
  4259.      if( h->param.rc.b_stat_write )
  4260.      {
  4261. -        char c_type = h->sh.i_type==SLICE_TYPE_I ? (h->fenc->i_poc==0 ? 'I' : 'i')
  4262. -                    : h->sh.i_type==SLICE_TYPE_P ? 'P'
  4263. +        char c_type = IS_SLICE_TYPE_I(h->sh.i_type) ? (h->fenc->i_poc==0 ? 'I' : 'i')
  4264. +                    : IS_SLICE_TYPE_P(h->sh.i_type) ? 'P'
  4265.                      : h->fenc->b_kept_as_ref ? 'B' : 'b';
  4266.          int dir_frame = h->stat.frame.i_direct_score[1] - h->stat.frame.i_direct_score[0];
  4267.          int dir_avg = h->stat.i_direct_score[1] - h->stat.i_direct_score[0];
  4268. @@ -1599,7 +1818,7 @@ int x264_ratecontrol_end( x264_t *h, int bits, int *filler )
  4269.  
  4270.      if( rc->b_abr )
  4271.      {
  4272. -        if( h->sh.i_type != SLICE_TYPE_B )
  4273. +        if( !IS_SLICE_TYPE_B(h->sh.i_type) )
  4274.              rc->cplxr_sum += bits * qp2qscale( rc->qpa_rc ) / rc->last_rceq;
  4275.          else
  4276.          {
  4277. @@ -1617,11 +1836,14 @@ int x264_ratecontrol_end( x264_t *h, int bits, int *filler )
  4278.  
  4279.      if( h->mb.b_variable_qp )
  4280.      {
  4281. -        if( h->sh.i_type == SLICE_TYPE_B )
  4282. +        if( IS_SLICE_TYPE_B(h->sh.i_type) )
  4283.          {
  4284.              rc->bframe_bits += bits;
  4285.              if( h->fenc->b_last_minigop_bframe )
  4286.              {
  4287. +#ifdef __DEBUG
  4288. +                x264_log(h, X264_LOG_INFO, "[%4d]: rc_end: rc->bframes = %d, (%s)[%p]\n", h->fenc->i_frame, rc->bframes, h->b_dependent ? "d" : "m", rc);
  4289. +#endif
  4290.                  update_predictor( rc->pred_b_from_p, qp2qscale( rc->qpa_rc ),
  4291.                                    h->fref[1][h->i_ref[1]-1]->i_satd, rc->bframe_bits / rc->bframes );
  4292.                  rc->bframe_bits = 0;
  4293. @@ -1632,20 +1854,20 @@ int x264_ratecontrol_end( x264_t *h, int bits, int *filler )
  4294.      *filler = update_vbv( h, bits );
  4295.      rc->filler_bits_sum += *filler * 8;
  4296.  
  4297. -    if( h->sps->vui.b_nal_hrd_parameters_present )
  4298. +    if( sps->vui.b_nal_hrd_parameters_present )
  4299.      {
  4300.          if( h->fenc->i_frame == 0 )
  4301.          {
  4302.              // access unit initialises the HRD
  4303.              h->fenc->hrd_timing.cpb_initial_arrival_time = 0;
  4304. -            rc->initial_cpb_removal_delay = h->initial_cpb_removal_delay;
  4305. -            rc->initial_cpb_removal_delay_offset = h->initial_cpb_removal_delay_offset;
  4306. +            rc->initial_cpb_removal_delay = view ? h->initial_cpb_removal_delay_dep : h->initial_cpb_removal_delay;
  4307. +            rc->initial_cpb_removal_delay_offset = view ? h->initial_cpb_removal_delay_offset_dep : h->initial_cpb_removal_delay_offset;
  4308.              h->fenc->hrd_timing.cpb_removal_time = rc->nrt_first_access_unit = (double)rc->initial_cpb_removal_delay / 90000;
  4309.          }
  4310.          else
  4311.          {
  4312.              h->fenc->hrd_timing.cpb_removal_time = rc->nrt_first_access_unit + (double)(h->fenc->i_cpb_delay - h->i_cpb_delay_pir_offset) *
  4313. -                                                   h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
  4314. +                                                   sps->vui.i_num_units_in_tick / sps->vui.i_time_scale;
  4315.  
  4316.              double cpb_earliest_arrival_time = h->fenc->hrd_timing.cpb_removal_time - (double)rc->initial_cpb_removal_delay / 90000;
  4317.              if( h->fenc->b_keyframe )
  4318. @@ -1657,7 +1879,7 @@ int x264_ratecontrol_end( x264_t *h, int bits, int *filler )
  4319.              else
  4320.                   cpb_earliest_arrival_time -= (double)rc->initial_cpb_removal_delay_offset / 90000;
  4321.  
  4322. -            if( h->sps->vui.hrd.b_cbr_hrd )
  4323. +            if( sps->vui.hrd.b_cbr_hrd )
  4324.                  h->fenc->hrd_timing.cpb_initial_arrival_time = rc->previous_cpb_final_arrival_time;
  4325.              else
  4326.                  h->fenc->hrd_timing.cpb_initial_arrival_time = X264_MAX( rc->previous_cpb_final_arrival_time, cpb_earliest_arrival_time );
  4327. @@ -1665,9 +1887,9 @@ int x264_ratecontrol_end( x264_t *h, int bits, int *filler )
  4328.          int filler_bits = *filler ? X264_MAX( (FILLER_OVERHEAD - h->param.b_annexb), *filler )*8 : 0;
  4329.          // Equation C-6
  4330.          h->fenc->hrd_timing.cpb_final_arrival_time = rc->previous_cpb_final_arrival_time = h->fenc->hrd_timing.cpb_initial_arrival_time +
  4331. -                                                     (double)(bits + filler_bits) / h->sps->vui.hrd.i_bit_rate_unscaled;
  4332. +                                                     (double)(bits + filler_bits) / sps->vui.hrd.i_bit_rate_unscaled;
  4333.  
  4334. -        h->fenc->hrd_timing.dpb_output_time = (double)h->fenc->i_dpb_output_delay * h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale +
  4335. +        h->fenc->hrd_timing.dpb_output_time = (double)h->fenc->i_dpb_output_delay * sps->vui.i_num_units_in_tick / sps->vui.i_time_scale +
  4336.                                                h->fenc->hrd_timing.cpb_removal_time;
  4337.      }
  4338.  
  4339. @@ -1686,7 +1908,9 @@ fail:
  4340.   */
  4341.  static double get_qscale(x264_t *h, ratecontrol_entry_t *rce, double rate_factor, int frame_num)
  4342.  {
  4343. -    x264_ratecontrol_t *rcc= h->rc;
  4344. +    if (h->param.b_mvc) frame_num /= 2;
  4345. +
  4346. +    x264_ratecontrol_t *rcc= h->rc_mvc[get_view_id(h)];
  4347.      x264_zone_t *zone = get_zone( h, frame_num );
  4348.      double q = pow( rce->blurred_complexity, 1 - rcc->qcompress );
  4349.  
  4350. @@ -1713,13 +1937,14 @@ static double get_qscale(x264_t *h, ratecontrol_entry_t *rce, double rate_factor
  4351.  
  4352.  static double get_diff_limited_q(x264_t *h, ratecontrol_entry_t *rce, double q)
  4353.  {
  4354. -    x264_ratecontrol_t *rcc = h->rc;
  4355. +    x264_ratecontrol_t *rcc = h->rc_mvc[get_view_id(h)];
  4356.      const int pict_type = rce->pict_type;
  4357. +    int b_anchor = rce->b_anchor;
  4358.  
  4359.      // force I/B quants as a function of P quants
  4360.      const double last_p_q    = rcc->last_qscale_for[SLICE_TYPE_P];
  4361.      const double last_non_b_q= rcc->last_qscale_for[rcc->last_non_b_pict_type];
  4362. -    if( pict_type == SLICE_TYPE_I )
  4363. +    if( IS_SLICE_TYPE_I(pict_type) || b_anchor)
  4364.      {
  4365.          double iq = q;
  4366.          double pq = qp2qscale( rcc->accum_p_qp / rcc->accum_p_norm );
  4367. @@ -1734,15 +1959,15 @@ static double get_diff_limited_q(x264_t *h, ratecontrol_entry_t *rce, double q)
  4368.          else
  4369.              q = rcc->accum_p_norm * pq / ip_factor + (1 - rcc->accum_p_norm) * iq;
  4370.      }
  4371. -    else if( pict_type == SLICE_TYPE_B )
  4372. +    else if( IS_SLICE_TYPE_B(pict_type) )
  4373.      {
  4374.          if( h->param.rc.f_pb_factor > 0 )
  4375.              q = last_non_b_q;
  4376.          if( !rce->kept_as_ref )
  4377.              q *= fabs( h->param.rc.f_pb_factor );
  4378.      }
  4379. -    else if( pict_type == SLICE_TYPE_P
  4380. -             && rcc->last_non_b_pict_type == SLICE_TYPE_P
  4381. +    else if( IS_SLICE_TYPE_P(pict_type)
  4382. +             && IS_SLICE_TYPE_P(rcc->last_non_b_pict_type)
  4383.               && rce->tex_bits == 0 )
  4384.      {
  4385.          q = last_p_q;
  4386. @@ -1750,7 +1975,7 @@ static double get_diff_limited_q(x264_t *h, ratecontrol_entry_t *rce, double q)
  4387.  
  4388.      /* last qscale / qdiff stuff */
  4389.      if( rcc->last_non_b_pict_type == pict_type &&
  4390. -        (pict_type!=SLICE_TYPE_I || rcc->last_accum_p_norm < 1) )
  4391. +        (!IS_SLICE_TYPE_I(pict_type) || rcc->last_accum_p_norm < 1) )
  4392.      {
  4393.          double last_q = rcc->last_qscale_for[pict_type];
  4394.          double max_qscale = last_q * rcc->lstep;
  4395. @@ -1761,15 +1986,15 @@ static double get_diff_limited_q(x264_t *h, ratecontrol_entry_t *rce, double q)
  4396.      }
  4397.  
  4398.      rcc->last_qscale_for[pict_type] = q;
  4399. -    if( pict_type != SLICE_TYPE_B )
  4400. +    if( !IS_SLICE_TYPE_B(pict_type) )
  4401.          rcc->last_non_b_pict_type = pict_type;
  4402. -    if( pict_type == SLICE_TYPE_I )
  4403. +    if( IS_SLICE_TYPE_I(pict_type) )
  4404.      {
  4405.          rcc->last_accum_p_norm = rcc->accum_p_norm;
  4406.          rcc->accum_p_norm = 0;
  4407.          rcc->accum_p_qp = 0;
  4408.      }
  4409. -    if( pict_type == SLICE_TYPE_P )
  4410. +    if( IS_SLICE_TYPE_P(pict_type) )
  4411.      {
  4412.          float mask = 1 - pow( (float)rce->i_count / rcc->nmb, 2 );
  4413.          rcc->accum_p_qp   = mask * (qscale2qp( q ) + rcc->accum_p_qp);
  4414. @@ -1780,7 +2005,7 @@ static double get_diff_limited_q(x264_t *h, ratecontrol_entry_t *rce, double q)
  4415.  
  4416.  static double predict_size( predictor_t *p, double q, double var )
  4417.  {
  4418. -     return (p->coeff*var + p->offset) / (q*p->count);
  4419. +    return (p->coeff*var + p->offset) / (q*p->count);
  4420.  }
  4421.  
  4422.  static void update_predictor( predictor_t *p, double q, double var, double bits )
  4423. @@ -1808,29 +2033,31 @@ static void update_predictor( predictor_t *p, double q, double var, double bits
  4424.  static int update_vbv( x264_t *h, int bits )
  4425.  {
  4426.      int filler = 0;
  4427. -    int bitrate = h->sps->vui.hrd.i_bit_rate_unscaled;
  4428. -    x264_ratecontrol_t *rcc = h->rc;
  4429. -    x264_ratecontrol_t *rct = h->thread[0]->rc;
  4430. -    uint64_t buffer_size = (uint64_t)h->sps->vui.hrd.i_cpb_size_unscaled * h->sps->vui.i_time_scale;
  4431. +    int view = get_view_id(h);
  4432. +    x264_sps_t * sps = view == 0 ? h->sps : h->subset_sps;
  4433. +    x264_ratecontrol_t *rcc = h->rc_mvc[view];
  4434. +    x264_ratecontrol_t *rct = h->thread[0]->rc_mvc[view];
  4435. +    uint64_t buffer_size = (uint64_t)sps->vui.hrd.i_cpb_size_unscaled * sps->vui.i_time_scale;
  4436. +    int bitrate = sps->vui.hrd.i_bit_rate_unscaled;
  4437.  
  4438.      if( rcc->last_satd >= h->mb.i_mb_count )
  4439. -        update_predictor( &rct->pred[h->sh.i_type], qp2qscale( rcc->qpa_rc ), rcc->last_satd, bits );
  4440. +        update_predictor( &rct->pred[h->sh.b_anchor ? SLICE_TYPE_I : h->sh.i_type], qp2qscale( rcc->qpa_rc ), rcc->last_satd, bits );
  4441.  
  4442.      if( !rcc->b_vbv )
  4443.          return filler;
  4444.  
  4445. -    rct->buffer_fill_final -= (uint64_t)bits * h->sps->vui.i_time_scale;
  4446. +    rct->buffer_fill_final -= (uint64_t)bits * sps->vui.i_time_scale;
  4447.  
  4448.      if( rct->buffer_fill_final < 0 )
  4449. -        x264_log( h, X264_LOG_WARNING, "VBV underflow (frame %d, %.0f bits)\n", h->i_frame, (double)rct->buffer_fill_final / h->sps->vui.i_time_scale );
  4450. +        x264_log( h, X264_LOG_WARNING, "VBV underflow (frame %d, %.0f bits)\n", h->i_frame, (double)rct->buffer_fill_final / sps->vui.i_time_scale );
  4451.      rct->buffer_fill_final = X264_MAX( rct->buffer_fill_final, 0 );
  4452. -    rct->buffer_fill_final += (uint64_t)bitrate * h->sps->vui.i_num_units_in_tick * h->fenc->i_cpb_duration;
  4453. +    rct->buffer_fill_final += (uint64_t)bitrate * sps->vui.i_num_units_in_tick * h->fenc->i_cpb_duration;
  4454.  
  4455. -    if( h->sps->vui.hrd.b_cbr_hrd && rct->buffer_fill_final > buffer_size )
  4456. +    if( sps->vui.hrd.b_cbr_hrd && rct->buffer_fill_final > buffer_size )
  4457.      {
  4458. -        filler = ceil( (rct->buffer_fill_final - buffer_size) / (8. * h->sps->vui.i_time_scale) );
  4459. +        filler = ceil( (rct->buffer_fill_final - buffer_size) / (8. * sps->vui.i_time_scale) );
  4460.          bits = X264_MAX( (FILLER_OVERHEAD - h->param.b_annexb), filler ) * 8;
  4461. -        rct->buffer_fill_final -= (uint64_t)bits * h->sps->vui.i_time_scale;
  4462. +        rct->buffer_fill_final -= (uint64_t)bits * sps->vui.i_time_scale;
  4463.      }
  4464.      else
  4465.          rct->buffer_fill_final = X264_MIN( rct->buffer_fill_final, buffer_size );
  4466. @@ -1840,10 +2067,12 @@ static int update_vbv( x264_t *h, int bits )
  4467.  
  4468.  void x264_hrd_fullness( x264_t *h )
  4469.  {
  4470. -    x264_ratecontrol_t *rct = h->thread[0]->rc;
  4471. -    uint64_t denom = (uint64_t)h->sps->vui.hrd.i_bit_rate_unscaled * h->sps->vui.i_time_scale / rct->hrd_multiply_denom;
  4472. +    int view = get_view_id(h);
  4473. +    x264_ratecontrol_t *rct = h->thread[0]->rc_mvc[view];
  4474. +    x264_sps_t * sps = view==0 ? h->sps : h->subset_sps;
  4475. +    uint64_t denom = (uint64_t)sps->vui.hrd.i_bit_rate_unscaled * sps->vui.i_time_scale / rct->hrd_multiply_denom;
  4476.      uint64_t cpb_state = rct->buffer_fill_final;
  4477. -    uint64_t cpb_size = (uint64_t)h->sps->vui.hrd.i_cpb_size_unscaled * h->sps->vui.i_time_scale;
  4478. +    uint64_t cpb_size = (uint64_t)sps->vui.hrd.i_cpb_size_unscaled * sps->vui.i_time_scale;
  4479.      uint64_t multiply_factor = 180000 / rct->hrd_multiply_denom;
  4480.  
  4481.      if( rct->buffer_fill_final < 0 || rct->buffer_fill_final > cpb_size )
  4482. @@ -1852,28 +2081,42 @@ void x264_hrd_fullness( x264_t *h )
  4483.                     rct->buffer_fill_final < 0 ? "underflow" : "overflow", (float)rct->buffer_fill_final/denom, (float)cpb_size/denom );
  4484.      }
  4485.  
  4486. -    h->initial_cpb_removal_delay = (multiply_factor * cpb_state + denom) / (2*denom);
  4487. -    h->initial_cpb_removal_delay_offset = (multiply_factor * cpb_size + denom) / (2*denom) - h->initial_cpb_removal_delay;
  4488. +    if (!h->b_dependent) {
  4489. +        h->initial_cpb_removal_delay = (multiply_factor * cpb_state + denom) / (2*denom);
  4490. +        h->initial_cpb_removal_delay_offset = (multiply_factor * cpb_size + denom) / (2*denom) - h->initial_cpb_removal_delay;
  4491. +    } else {
  4492. +        h->initial_cpb_removal_delay_dep = (multiply_factor * cpb_state + denom) / (2*denom);
  4493. +        h->initial_cpb_removal_delay_offset_dep = (multiply_factor * cpb_size + denom) / (2*denom) - h->initial_cpb_removal_delay_dep;
  4494. +    }
  4495. +}
  4496. +
  4497. +void x264_hrd_copy_to_dependent(x264_t *h, x264_t *thread_next)
  4498. +{
  4499. +    /* cannot be equal thease values with base ones, so copy base values to them. */
  4500. +    thread_next->initial_cpb_removal_delay = h->initial_cpb_removal_delay;
  4501. +    thread_next->initial_cpb_removal_delay_offset = h->initial_cpb_removal_delay_offset;
  4502.  }
  4503.  
  4504.  // provisionally update VBV according to the planned size of all frames currently in progress
  4505.  static void update_vbv_plan( x264_t *h, int overhead )
  4506.  {
  4507. -    x264_ratecontrol_t *rcc = h->rc;
  4508. -    rcc->buffer_fill = h->thread[0]->rc->buffer_fill_final / h->sps->vui.i_time_scale;
  4509. +    int view = get_view_id(h);
  4510. +    x264_ratecontrol_t *rcc = h->rc_mvc[view];
  4511. +    x264_sps_t *sps = view == 0 ? h->sps : h->subset_sps;
  4512. +    rcc->buffer_fill = h->thread[0]->rc_mvc[view]->buffer_fill_final / sps->vui.i_time_scale;
  4513.      if( h->i_thread_frames > 1 )
  4514.      {
  4515. -        int j = h->rc - h->thread[0]->rc;
  4516. +        int j = h->rc_mvc[view] - h->thread[0]->rc_mvc[view];
  4517.          for( int i = 1; i < h->i_thread_frames; i++ )
  4518.          {
  4519.              x264_t *t = h->thread[ (j+i)%h->i_thread_frames ];
  4520. -            double bits = t->rc->frame_size_planned;
  4521. +            double bits = t->rc_mvc[view]->frame_size_planned;
  4522.              if( !t->b_thread_active )
  4523.                  continue;
  4524. -            bits  = X264_MAX(bits, t->rc->frame_size_estimated);
  4525. +            bits  = X264_MAX(bits, t->rc_mvc[view]->frame_size_estimated);
  4526.              rcc->buffer_fill -= bits;
  4527.              rcc->buffer_fill = X264_MAX( rcc->buffer_fill, 0 );
  4528. -            rcc->buffer_fill += t->rc->buffer_rate;
  4529. +            rcc->buffer_fill += t->rc_mvc[view]->buffer_rate;
  4530.              rcc->buffer_fill = X264_MIN( rcc->buffer_fill, rcc->buffer_size );
  4531.          }
  4532.      }
  4533. @@ -1884,7 +2127,8 @@ static void update_vbv_plan( x264_t *h, int overhead )
  4534.  // apply VBV constraints and clip qscale to between lmin and lmax
  4535.  static double clip_qscale( x264_t *h, int pict_type, double q )
  4536.  {
  4537. -    x264_ratecontrol_t *rcc = h->rc;
  4538. +    int view = get_view_id(h);
  4539. +    x264_ratecontrol_t *rcc = h->rc_mvc[view];
  4540.      double lmin = rcc->lmin[pict_type];
  4541.      double lmax = rcc->lmax[pict_type];
  4542.      if( rcc->rate_factor_max_increment )
  4543. @@ -1907,15 +2151,18 @@ static double clip_qscale( x264_t *h, int pict_type, double q )
  4544.              for( int iterations = 0; iterations < 1000 && terminate != 3; iterations++ )
  4545.              {
  4546.                  double frame_q[3];
  4547. -                double cur_bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
  4548. +                double cur_bits = predict_size( &rcc->pred[h->sh.b_anchor ? SLICE_TYPE_I : h->sh.i_type], q, rcc->last_satd );
  4549.                  double buffer_fill_cur = rcc->buffer_fill - cur_bits;
  4550.                  double target_fill;
  4551.                  double total_duration = 0;
  4552. -                frame_q[0] = h->sh.i_type == SLICE_TYPE_I ? q * h->param.rc.f_ip_factor : q;
  4553. +                frame_q[0] = IS_SLICE_TYPE_I(h->sh.i_type) || h->sh.b_anchor ? q * h->param.rc.f_ip_factor : q;
  4554.                  frame_q[1] = frame_q[0] * h->param.rc.f_pb_factor;
  4555.                  frame_q[2] = frame_q[0] / h->param.rc.f_ip_factor;
  4556.  
  4557.                  /* Loop over the planned future frames. */
  4558. +#ifdef __DEBUG
  4559. +                x264_log(h, X264_LOG_INFO, "buffer_fill_cur = %f, buffer_size = %f\n", buffer_fill_cur, rcc->buffer_size);
  4560. +#endif                    
  4561.                  for( int j = 0; buffer_fill_cur >= 0 && buffer_fill_cur <= rcc->buffer_size; j++ )
  4562.                  {
  4563.                      total_duration += h->fenc->f_planned_cpb_duration[j];
  4564. @@ -1930,10 +2177,17 @@ static double clip_qscale( x264_t *h, int pict_type, double q )
  4565.                  }
  4566.                  /* Try to get to get the buffer at least 50% filled, but don't set an impossible goal. */
  4567.                  target_fill = X264_MIN( rcc->buffer_fill + total_duration * rcc->vbv_max_rate * 0.5, rcc->buffer_size * 0.5 );
  4568. +#ifdef __DEBUG
  4569. +                x264_log(h, X264_LOG_INFO, "buffer_fill = %7.4f, total_duration = %7.4f, vbv_max_rate = %7.4f, buffer_size = %7.4f\n",
  4570. +                         rcc->buffer_fill, total_duration, rcc->vbv_max_rate, rcc->buffer_size);
  4571. +#endif                    
  4572.                  if( buffer_fill_cur < target_fill )
  4573.                  {
  4574.                      q *= 1.01;
  4575.                      terminate |= 1;
  4576. +#ifdef __DEBUG
  4577. +                    x264_log(h, X264_LOG_INFO, "target_fill(a) = %7.4f, q = %7.4f\n", target_fill, q);
  4578. +#endif                    
  4579.                      continue;
  4580.                  }
  4581.                  /* Try to get the buffer no more than 80% filled, but don't set an impossible goal. */
  4582. @@ -1942,16 +2196,22 @@ static double clip_qscale( x264_t *h, int pict_type, double q )
  4583.                  {
  4584.                      q /= 1.01;
  4585.                      terminate |= 2;
  4586. +#ifdef __DEBUG
  4587. +                    x264_log(h, X264_LOG_INFO, "target_fill(b) = %7.4f, q = %7.4f\n", target_fill, q);
  4588. +#endif
  4589.                      continue;
  4590.                  }
  4591. +#ifdef __DEBUG
  4592. +                x264_log(h, X264_LOG_INFO, "target_fill(c) = %7.4f, q = %7.4f\n", target_fill, q);
  4593. +#endif
  4594.                  break;
  4595.              }
  4596.          }
  4597.          /* Fallback to old purely-reactive algorithm: no lookahead. */
  4598.          else
  4599.          {
  4600. -            if( ( pict_type == SLICE_TYPE_P ||
  4601. -                ( pict_type == SLICE_TYPE_I && rcc->last_non_b_pict_type == SLICE_TYPE_I ) ) &&
  4602. +            if( ( IS_SLICE_TYPE_P(pict_type) ||
  4603. +                ( IS_SLICE_TYPE_I(pict_type) && IS_SLICE_TYPE_I(rcc->last_non_b_pict_type) ) ) &&
  4604.                  rcc->buffer_fill/rcc->buffer_size < 0.5 )
  4605.              {
  4606.                  q /= x264_clip3f( 2.0*rcc->buffer_fill/rcc->buffer_size, 0.5, 1.0 );
  4607. @@ -1959,10 +2219,12 @@ static double clip_qscale( x264_t *h, int pict_type, double q )
  4608.  
  4609.              /* Now a hard threshold to make sure the frame fits in VBV.
  4610.               * This one is mostly for I-frames. */
  4611. -            double bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
  4612. +            double bits = predict_size( &rcc->pred[h->sh.b_anchor ? SLICE_TYPE_I : h->sh.i_type], q, rcc->last_satd );
  4613.              double qf = 1.0;
  4614.              /* For small VBVs, allow the frame to use up the entire VBV. */
  4615. -            double max_fill_factor = h->param.rc.i_vbv_buffer_size >= 5*h->param.rc.i_vbv_max_bitrate / rcc->fps ? 2 : 1;
  4616. +
  4617. +            int vbv_max_rate = view == 0 ? h->param.rc.i_vbv_max_bitrate : h->param.rc.i_vbv_max_bitrate_dep[view-1];
  4618. +            double max_fill_factor = h->param.rc.i_vbv_buffer_size >= 5*vbv_max_rate / rcc->fps ? 2 : 1;
  4619.              /* For single-frame VBVs, request that the frame use up the entire VBV. */
  4620.              double min_fill_factor = rcc->single_frame_vbv ? 1 : 2;
  4621.  
  4622. @@ -1976,14 +2238,17 @@ static double clip_qscale( x264_t *h, int pict_type, double q )
  4623.          }
  4624.  
  4625.          /* Apply MinCR restrictions */
  4626. -        double bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
  4627. +        double bits = predict_size( &rcc->pred[h->sh.b_anchor ? SLICE_TYPE_I : h->sh.i_type], q, rcc->last_satd );
  4628. +#ifdef __DEBUG
  4629. +        x264_log(h, X264_LOG_INFO, "bits = %7.4f, predictor.coeff = %7.4f, predictor.offset = %7.4f, bitsMax=%7.4f\n", bits, rcc->pred[h->sh.i_type].coeff, rcc->pred[h->sh.i_type].offset, rcc->frame_size_maximum);
  4630. +#endif
  4631.          if( bits > rcc->frame_size_maximum )
  4632.              q *= bits / rcc->frame_size_maximum;
  4633. -        bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );
  4634. +        bits = predict_size( &rcc->pred[h->sh.b_anchor ? SLICE_TYPE_I : h->sh.i_type], q, rcc->last_satd );
  4635.  
  4636.          /* Check B-frame complexity, and use up any bits that would
  4637.           * overflow before the next P-frame. */
  4638. -        if( h->sh.i_type == SLICE_TYPE_P && !rcc->single_frame_vbv )
  4639. +        if( IS_SLICE_TYPE_P(h->sh.i_type) && !h->sh.b_anchor && !rcc->single_frame_vbv )
  4640.          {
  4641.              int nb = rcc->bframes;
  4642.              double pbbits = bits;
  4643. @@ -2030,13 +2295,24 @@ static double clip_qscale( x264_t *h, int pict_type, double q )
  4644.  static float rate_estimate_qscale( x264_t *h )
  4645.  {
  4646.      float q;
  4647. -    x264_ratecontrol_t *rcc = h->rc;
  4648. +    int view = get_view_id(h);
  4649. +    x264_ratecontrol_t *rcc = h->rc_mvc[view];
  4650.      ratecontrol_entry_t UNINIT(rce);
  4651. -    int pict_type = h->sh.i_type;
  4652. -    int64_t total_bits = 8*(h->stat.i_frame_size[SLICE_TYPE_I]
  4653. -                          + h->stat.i_frame_size[SLICE_TYPE_P]
  4654. -                          + h->stat.i_frame_size[SLICE_TYPE_B])
  4655. -                       - rcc->filler_bits_sum;
  4656. +    int pict_type = h->sh.b_anchor ? SLICE_TYPE_I : h->sh.i_type;
  4657. +    int b_anchor =  h->sh.b_anchor;
  4658. +    int64_t total_bits =
  4659. +        (view
  4660. +         ? 8*(h->stat.i_frame_dep_size[SLICE_TYPE_I]
  4661. +              + h->stat.i_frame_dep_size[SLICE_TYPE_P]
  4662. +              + h->stat.i_frame_dep_size[SLICE_TYPE_B])
  4663. +         : 8*(h->stat.i_frame_size[SLICE_TYPE_I]
  4664. +              + h->stat.i_frame_size[SLICE_TYPE_P]
  4665. +              + h->stat.i_frame_size[SLICE_TYPE_B]))
  4666. +            - rcc->filler_bits_sum;
  4667. +
  4668. +#ifdef __DEBUG
  4669. +    x264_log(h, X264_LOG_INFO, "[rate_estimate_qscale] pict_type %d \n", pict_type);
  4670. +#endif
  4671.  
  4672.      if( rcc->b_2pass )
  4673.      {
  4674. @@ -2048,7 +2324,7 @@ static float rate_estimate_qscale( x264_t *h )
  4675.          }
  4676.      }
  4677.  
  4678. -    if( pict_type == SLICE_TYPE_B )
  4679. +    if( IS_SLICE_TYPE_B(pict_type ) )
  4680.      {
  4681.          /* B-frames don't have independent ratecontrol, but rather get the
  4682.           * average QP of the two adjacent P-frames + an offset */
  4683. @@ -2083,7 +2359,7 @@ static float rate_estimate_qscale( x264_t *h )
  4684.              rcc->frame_size_planned = qscale2bits( &rce, qp2qscale( q ) );
  4685.          else
  4686.              rcc->frame_size_planned = predict_size( rcc->pred_b_from_p, qp2qscale( q ), h->fref[1][h->i_ref[1]-1]->i_satd );
  4687. -        h->rc->frame_size_estimated = rcc->frame_size_planned;
  4688. +        h->rc_mvc[view]->frame_size_estimated = rcc->frame_size_planned;
  4689.  
  4690.          /* For row SATDs */
  4691.          if( rcc->b_vbv )
  4692. @@ -2106,14 +2382,14 @@ static float rate_estimate_qscale( x264_t *h )
  4693.              {
  4694.                  if( h->i_thread_frames > 1 )
  4695.                  {
  4696. -                    int j = h->rc - h->thread[0]->rc;
  4697. +                    int j = h->rc_mvc[view] - h->thread[0]->rc_mvc[view];
  4698.                      for( int i = 1; i < h->i_thread_frames; i++ )
  4699.                      {
  4700.                          x264_t *t = h->thread[ (j+i)%h->i_thread_frames ];
  4701. -                        double bits = t->rc->frame_size_planned;
  4702. +                        double bits = t->rc_mvc[view]->frame_size_planned;
  4703.                          if( !t->b_thread_active )
  4704.                              continue;
  4705. -                        bits  = X264_MAX(bits, t->rc->frame_size_estimated);
  4706. +                        bits  = X264_MAX(bits, t->rc_mvc[view]->frame_size_estimated);
  4707.                          predicted_bits += (int64_t)bits;
  4708.                      }
  4709.                  }
  4710. @@ -2185,6 +2461,9 @@ static float rate_estimate_qscale( x264_t *h )
  4711.              double wanted_bits, overflow = 1;
  4712.  
  4713.              rcc->last_satd = x264_rc_analyse_slice( h );
  4714. +#ifdef __DEBUG
  4715. +            x264_log(h, X264_LOG_INFO, "(%s): last_satd[%d] = %d\n", h->b_dependent ? "d" : "m", h->i_frame, rcc->last_satd);
  4716. +#endif
  4717.              rcc->short_term_cplxsum *= 0.5;
  4718.              rcc->short_term_cplxcount *= 0.5;
  4719.              rcc->short_term_cplxsum += rcc->last_satd / (CLIP_DURATION(h->fenc->f_duration) / BASE_FRAME_DURATION);
  4720. @@ -2198,6 +2477,7 @@ static float rate_estimate_qscale( x264_t *h )
  4721.              rce.s_count = 0;
  4722.              rce.qscale = 1;
  4723.              rce.pict_type = pict_type;
  4724. +            rce.b_anchor = b_anchor;
  4725.  
  4726.              if( h->param.rc.i_rc_method == X264_RC_CRF )
  4727.              {
  4728. @@ -2206,14 +2486,16 @@ static float rate_estimate_qscale( x264_t *h )
  4729.              else
  4730.              {
  4731.                  q = get_qscale( h, &rce, rcc->wanted_bits_window / rcc->cplxr_sum, h->fenc->i_frame );
  4732. -
  4733. +#ifdef __RC_DEBUG
  4734. +                x264_log(h, X264_LOG_INFO, "(%s): qscale = %7.4f\n", h->b_dependent ? "d" : "m", q);
  4735. +#endif
  4736.                  /* ABR code can potentially be counterproductive in CBR, so just don't bother.
  4737.                   * Don't run it if the frame complexity is zero either. */
  4738.                  if( !rcc->b_vbv_min_rate && rcc->last_satd )
  4739.                  {
  4740.                      // FIXME is it simpler to keep track of wanted_bits in ratecontrol_end?
  4741.                      int i_frame_done = h->i_frame + 1 - h->i_thread_frames;
  4742. -                    double time_done = i_frame_done / rcc->fps;
  4743. +                    double time_done = i_frame_done / ((h->param.b_mvc ? 2 : 1) * rcc->fps);
  4744.                      if( h->param.b_vfr_input && i_frame_done > 0 )
  4745.                          time_done = ((double)(h->fenc->i_reordered_pts - h->i_reordered_pts_delay)) * h->param.i_timebase_num / h->param.i_timebase_den;
  4746.                      wanted_bits = time_done * rcc->bitrate;
  4747. @@ -2226,14 +2508,14 @@ static float rate_estimate_qscale( x264_t *h )
  4748.                  }
  4749.              }
  4750.  
  4751. -            if( pict_type == SLICE_TYPE_I && h->param.i_keyint_max > 1
  4752. +            if( (IS_SLICE_TYPE_I(pict_type) || b_anchor) && h->param.i_keyint_max > 1
  4753.                  /* should test _next_ pict type, but that isn't decided yet */
  4754. -                && rcc->last_non_b_pict_type != SLICE_TYPE_I )
  4755. +                && !IS_SLICE_TYPE_I(rcc->last_non_b_pict_type) )
  4756.              {
  4757.                  q = qp2qscale( rcc->accum_p_qp / rcc->accum_p_norm );
  4758.                  q /= fabs( h->param.rc.f_ip_factor );
  4759.              }
  4760. -            else if( h->i_frame > 0 )
  4761. +            else if( (!h->param.b_mvc && h->i_frame > 0) || h->i_frame > 1)
  4762.              {
  4763.                  if( h->param.rc.i_rc_method != X264_RC_CRF )
  4764.                  {
  4765. @@ -2255,8 +2537,14 @@ static float rate_estimate_qscale( x264_t *h )
  4766.              }
  4767.              rcc->qp_novbv = qscale2qp( q );
  4768.  
  4769. +#ifdef __RC_DEBUG
  4770. +            x264_log(h, X264_LOG_INFO, "(%s): qscale2 = %7.4f\n", h->b_dependent ? "d" : "m", q);
  4771. +#endif
  4772.              //FIXME use get_diff_limited_q() ?
  4773.              q = clip_qscale( h, pict_type, q );
  4774. +#ifdef __RC_DEBUG
  4775. +            x264_log(h, X264_LOG_INFO, "(%s): qscale3 = %7.4f\n", h->b_dependent ? "d" : "m", q);
  4776. +#endif
  4777.          }
  4778.  
  4779.          rcc->last_qscale_for[pict_type] =
  4780. @@ -2273,49 +2561,54 @@ static float rate_estimate_qscale( x264_t *h )
  4781.          /* Always use up the whole VBV in this case. */
  4782.          if( rcc->single_frame_vbv )
  4783.              rcc->frame_size_planned = rcc->buffer_rate;
  4784. -        h->rc->frame_size_estimated = rcc->frame_size_planned;
  4785. +        h->rc_mvc[view]->frame_size_estimated = rcc->frame_size_planned;
  4786. +#ifdef __RC_DEBUG
  4787. +        x264_log(h, X264_LOG_INFO, "(%s): qscalef = %7.4f\n", h->b_dependent ? "d" : "m", q);
  4788. +#endif
  4789.          return q;
  4790.      }
  4791.  }
  4792.  
  4793.  void x264_threads_normalize_predictors( x264_t *h )
  4794.  {
  4795. +    int view = get_view_id(h);
  4796.      double totalsize = 0;
  4797.      for( int i = 0; i < h->param.i_threads; i++ )
  4798. -        totalsize += h->thread[i]->rc->slice_size_planned;
  4799. -    double factor = h->rc->frame_size_planned / totalsize;
  4800. +        totalsize += h->thread[i]->rc_mvc[view]->slice_size_planned;
  4801. +    double factor = h->rc_mvc[view]->frame_size_planned / totalsize;
  4802.      for( int i = 0; i < h->param.i_threads; i++ )
  4803. -        h->thread[i]->rc->slice_size_planned *= factor;
  4804. +        h->thread[i]->rc_mvc[view]->slice_size_planned *= factor;
  4805.  }
  4806.  
  4807.  void x264_threads_distribute_ratecontrol( x264_t *h )
  4808.  {
  4809.      int row;
  4810. -    x264_ratecontrol_t *rc = h->rc;
  4811. +    int view = get_view_id(h);
  4812. +    x264_ratecontrol_t *rc = h->rc_mvc[view];
  4813.  
  4814.      /* Initialize row predictors */
  4815. -    if( h->i_frame == 0 )
  4816. +    if(h->i_frame == view)
  4817.          for( int i = 0; i < h->param.i_threads; i++ )
  4818.          {
  4819. -            x264_ratecontrol_t *t = h->thread[i]->rc;
  4820. +            x264_ratecontrol_t *t = h->thread[i]->rc_mvc[view];
  4821.              memcpy( t->row_preds, rc->row_preds, sizeof(rc->row_preds) );
  4822.          }
  4823.  
  4824.      for( int i = 0; i < h->param.i_threads; i++ )
  4825.      {
  4826.          x264_t *t = h->thread[i];
  4827. -        memcpy( t->rc, rc, offsetof(x264_ratecontrol_t, row_pred) );
  4828. -        t->rc->row_pred = &t->rc->row_preds[h->sh.i_type];
  4829. +        memcpy( t->rc_mvc[view], rc, offsetof(x264_ratecontrol_t, row_pred) );
  4830. +        t->rc_mvc[view]->row_pred = &t->rc_mvc[view]->row_preds[h->sh.i_type];
  4831.          /* Calculate the planned slice size. */
  4832.          if( rc->b_vbv && rc->frame_size_planned )
  4833.          {
  4834.              int size = 0;
  4835.              for( row = t->i_threadslice_start; row < t->i_threadslice_end; row++ )
  4836.                  size += h->fdec->i_row_satd[row];
  4837. -            t->rc->slice_size_planned = predict_size( &rc->pred[h->sh.i_type + (i+1)*5], rc->qpm, size );
  4838. +            t->rc_mvc[view]->slice_size_planned = predict_size( &rc->pred[h->sh.i_type + (i+1)*5], rc->qpm, size );
  4839.          }
  4840.          else
  4841. -            t->rc->slice_size_planned = 0;
  4842. +            t->rc_mvc[view]->slice_size_planned = 0;
  4843.      }
  4844.      if( rc->b_vbv && rc->frame_size_planned )
  4845.      {
  4846. @@ -2328,25 +2621,26 @@ void x264_threads_distribute_ratecontrol( x264_t *h )
  4847.              {
  4848.                  x264_t *t = h->thread[i];
  4849.                  float max_frame_error = X264_MAX( 0.05, 1.0 / (t->i_threadslice_end - t->i_threadslice_start) );
  4850. -                t->rc->slice_size_planned += 2 * max_frame_error * rc->frame_size_planned;
  4851. +                t->rc_mvc[view]->slice_size_planned += 2 * max_frame_error * rc->frame_size_planned;
  4852.              }
  4853.              x264_threads_normalize_predictors( h );
  4854.          }
  4855.  
  4856.          for( int i = 0; i < h->param.i_threads; i++ )
  4857. -            h->thread[i]->rc->frame_size_estimated = h->thread[i]->rc->slice_size_planned;
  4858. +            h->thread[i]->rc_mvc[view]->frame_size_estimated = h->thread[i]->rc_mvc[view]->slice_size_planned;
  4859.      }
  4860.  }
  4861.  
  4862.  void x264_threads_merge_ratecontrol( x264_t *h )
  4863.  {
  4864. -    x264_ratecontrol_t *rc = h->rc;
  4865. +    int view = get_view_id(h);
  4866. +    x264_ratecontrol_t *rc = h->rc_mvc[view];
  4867.      x264_emms();
  4868.  
  4869.      for( int i = 0; i < h->param.i_threads; i++ )
  4870.      {
  4871.          x264_t *t = h->thread[i];
  4872. -        x264_ratecontrol_t *rct = h->thread[i]->rc;
  4873. +        x264_ratecontrol_t *rct = h->thread[i]->rc_mvc[view];
  4874.          if( h->param.rc.i_vbv_buffer_size )
  4875.          {
  4876.              int size = 0;
  4877. @@ -2367,7 +2661,8 @@ void x264_thread_sync_ratecontrol( x264_t *cur, x264_t *prev, x264_t *next )
  4878.  {
  4879.      if( cur != prev )
  4880.      {
  4881. -#define COPY(var) memcpy(&cur->rc->var, &prev->rc->var, sizeof(cur->rc->var))
  4882. +        for (int view = 0; view < get_view_num(cur); view++) {
  4883. +#define COPY(var) memcpy(&cur->rc_mvc[view]->var, &prev->rc_mvc[view]->var, sizeof(cur->rc_mvc[view]->var))
  4884.          /* these vars are updated in x264_ratecontrol_start()
  4885.           * so copy them from the context that most recently started (prev)
  4886.           * to the context that's about to start (cur). */
  4887. @@ -2391,10 +2686,12 @@ void x264_thread_sync_ratecontrol( x264_t *cur, x264_t *prev, x264_t *next )
  4888.          COPY(rate_factor_constant);
  4889.          COPY(bitrate);
  4890.  #undef COPY
  4891. +        }
  4892.      }
  4893.      if( cur != next )
  4894.      {
  4895. -#define COPY(var) next->rc->var = cur->rc->var
  4896. +        for (int view = 0; view < get_view_num(cur); view++) {
  4897. +#define COPY(var) next->rc_mvc[view]->var = cur->rc_mvc[view]->var
  4898.          /* these vars are updated in x264_ratecontrol_end()
  4899.           * so copy them from the context that most recently ended (cur)
  4900.           * to the context that's about to end (next) */
  4901. @@ -2408,6 +2705,7 @@ void x264_thread_sync_ratecontrol( x264_t *cur, x264_t *prev, x264_t *next )
  4902.          COPY(nrt_first_access_unit);
  4903.          COPY(previous_cpb_final_arrival_time);
  4904.  #undef COPY
  4905. +        }
  4906.      }
  4907.      //FIXME row_preds[] (not strictly necessary, but would improve prediction)
  4908.      /* the rest of the variables are either constant or thread-local */
  4909. @@ -2418,7 +2716,8 @@ static int find_underflow( x264_t *h, double *fills, int *t0, int *t1, int over
  4910.      /* find an interval ending on an overflow or underflow (depending on whether
  4911.       * we're adding or removing bits), and starting on the earliest frame that
  4912.       * can influence the buffer fill of that end frame. */
  4913. -    x264_ratecontrol_t *rcc = h->rc;
  4914. +    x264_ratecontrol_t *rcc = h->rc_mvc[get_view_id(h)];
  4915. +    x264_sps_t * sps = get_view_id(h)==0 ? h->sps : h->subset_sps;
  4916.      const double buffer_min = (over ? .1 : .1) * rcc->buffer_size;
  4917.      const double buffer_max = .9 * rcc->buffer_size;
  4918.      double fill = fills[*t0-1];
  4919. @@ -2426,7 +2725,7 @@ static int find_underflow( x264_t *h, double *fills, int *t0, int *t1, int over
  4920.      int start = -1, end = -1;
  4921.      for( int i = *t0; i < rcc->num_entries; i++ )
  4922.      {
  4923. -        fill += (rcc->entry[i].i_cpb_duration * rcc->vbv_max_rate * h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale -
  4924. +        fill += (rcc->entry[i].i_cpb_duration * rcc->vbv_max_rate * sps->vui.i_num_units_in_tick / sps->vui.i_time_scale -
  4925.                   qscale2bits( &rcc->entry[i], rcc->entry[i].new_qscale )) * parity;
  4926.          fill = x264_clip3f(fill, 0, rcc->buffer_size);
  4927.          fills[i] = fill;
  4928. @@ -2446,7 +2745,7 @@ static int find_underflow( x264_t *h, double *fills, int *t0, int *t1, int over
  4929.  
  4930.  static int fix_underflow( x264_t *h, int t0, int t1, double adjustment, double qscale_min, double qscale_max)
  4931.  {
  4932. -    x264_ratecontrol_t *rcc = h->rc;
  4933. +    x264_ratecontrol_t *rcc = h->rc_mvc[get_view_id(h)];
  4934.      double qscale_orig, qscale_new;
  4935.      int adjusted = 0;
  4936.      if( t0 > 0 )
  4937. @@ -2465,7 +2764,7 @@ static int fix_underflow( x264_t *h, int t0, int t1, double adjustment, double q
  4938.  
  4939.  static double count_expected_bits( x264_t *h )
  4940.  {
  4941. -    x264_ratecontrol_t *rcc = h->rc;
  4942. +    x264_ratecontrol_t *rcc = h->rc_mvc[get_view_id(h)];
  4943.      double expected_bits = 0;
  4944.      for( int i = 0; i < rcc->num_entries; i++ )
  4945.      {
  4946. @@ -2483,7 +2782,7 @@ static int vbv_pass2( x264_t *h, double all_available_bits )
  4947.       * last frame in the interval no longer underflows.  Recompute intervals and repeat.
  4948.       * Then do the converse to put bits back into overflow areas until target size is met */
  4949.  
  4950. -    x264_ratecontrol_t *rcc = h->rc;
  4951. +    x264_ratecontrol_t *rcc = h->rc_mvc[get_view_id(h)];
  4952.      double *fills;
  4953.      double expected_bits = 0;
  4954.      double adjustment;
  4955. @@ -2542,7 +2841,12 @@ fail:
  4956.  
  4957.  static int init_pass2( x264_t *h )
  4958.  {
  4959. -    x264_ratecontrol_t *rcc = h->rc;
  4960. +    int rc_num = get_view_num(h);
  4961. +
  4962. +    // unsupported 2pass encode at mvc;
  4963. +    if (rc_num > 1) return 0;
  4964. +
  4965. +    x264_ratecontrol_t *rcc = h->rc_mvc[0];
  4966.      uint64_t all_const_bits = 0;
  4967.      double timescale = (double)h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
  4968.      double duration = 0;
  4969. diff --git encoder/ratecontrol.h encoder/ratecontrol.h
  4970. index f5aa9a8..eb3e16a 100644
  4971. --- encoder/ratecontrol.h
  4972. +++ encoder/ratecontrol.h
  4973. @@ -47,6 +47,7 @@ void x264_ratecontrol_init_reconfigurable( x264_t *h, int b_init );
  4974.  void x264_adaptive_quant_frame( x264_t *h, x264_frame_t *frame, float *quant_offsets );
  4975.  int  x264_macroblock_tree_read( x264_t *h, x264_frame_t *frame, float *quant_offsets );
  4976.  int  x264_reference_build_list_optimal( x264_t *h );
  4977. +int  x264_reference_build_list_mvc( x264_t *h );
  4978.  void x264_thread_sync_ratecontrol( x264_t *cur, x264_t *prev, x264_t *next );
  4979.  void x264_ratecontrol_start( x264_t *, int i_force_qp, int overhead );
  4980.  int  x264_ratecontrol_slice_type( x264_t *, int i_frame );
  4981. @@ -63,5 +64,6 @@ int x264_weighted_reference_duplicate( x264_t *h, int i_ref, const x264_weight_t
  4982.  void x264_threads_distribute_ratecontrol( x264_t *h );
  4983.  void x264_threads_merge_ratecontrol( x264_t *h );
  4984.  void x264_hrd_fullness( x264_t *h );
  4985. +void x264_hrd_copy_to_dependent( x264_t *h, x264_t *thread_next );
  4986.  #endif
  4987.  
  4988. diff --git encoder/set.c encoder/set.c
  4989. index 78f1b56..ffeef3c 100644
  4990. --- encoder/set.c
  4991. +++ encoder/set.c
  4992. @@ -74,6 +74,39 @@ static void scaling_list_write( bs_t *s, x264_pps_t *pps, int idx )
  4993.      }
  4994.  }
  4995.  
  4996. +static void calculate_timecode_from_frame(int64_t frame, int num, int denom, struct timecode *time)
  4997. +{
  4998. +    if (denom == 0) {
  4999. +        time->hour = 0;
  5000. +        time->minute = 0;
  5001. +        time->second = 0;
  5002. +        time->frame = 0;
  5003. +        return;
  5004. +    }
  5005. +
  5006. +    if (denom == 1001 && time->b_drop) {
  5007. +        int32_t minute10_frame_count = 10 * 60 * num / 1000 - 18;
  5008. +        int32_t minute_frame_count = 60 * num / 1000 - 2;
  5009. +        int32_t ten_min_count = frame / minute10_frame_count;
  5010. +        int32_t remain = frame - (int64_t)minute10_frame_count * ten_min_count;
  5011. +        int32_t one_min_count = 0;
  5012. +        if (remain > 2) {
  5013. +            one_min_count = (remain - 2) / minute_frame_count;
  5014. +        }
  5015. +        frame += ten_min_count * 18 + one_min_count * 2;
  5016. +    }
  5017. +    if (denom == 1001) denom = 1000;
  5018. +
  5019. +    int32_t fps = num/denom;
  5020. +    time->frame = frame % fps;
  5021. +    frame /= fps;
  5022. +    time->second = frame % 60;
  5023. +    frame /= 60;
  5024. +    time->minute = frame % 60;
  5025. +    frame /= 60;
  5026. +    time->hour = frame % 24;
  5027. +}
  5028. +
  5029.  void x264_sei_write( bs_t *s, uint8_t *payload, int payload_size, int payload_type )
  5030.  {
  5031.      int i;
  5032. @@ -106,6 +139,8 @@ void x264_sps_init( x264_sps_t *sps, int i_id, x264_param_t *param )
  5033.          sps->i_profile_idc  = PROFILE_HIGH444_PREDICTIVE;
  5034.      else if( BIT_DEPTH > 8 )
  5035.          sps->i_profile_idc  = PROFILE_HIGH10;
  5036. +    else if (( param->b_mvc ) && (i_id != 0))
  5037. +        sps->i_profile_idc = PROFILE_STEREO_HIGH;
  5038.      else if( param->analyse.b_transform_8x8 || param->i_cqm_preset != X264_CQM_FLAT )
  5039.          sps->i_profile_idc  = PROFILE_HIGH;
  5040.      else if( param->b_cabac || param->i_bframe > 0 || param->b_interlaced || param->b_fake_interlaced || param->analyse.i_weighted_pred > 0 )
  5041. @@ -146,14 +181,18 @@ void x264_sps_init( x264_sps_t *sps, int i_id, x264_param_t *param )
  5042.  
  5043.      /* number of refs + current frame */
  5044.      int max_frame_num = sps->vui.i_max_dec_frame_buffering * (!!param->i_bframe_pyramid+1) + 1;
  5045. +
  5046.      /* Intra refresh cannot write a recovery time greater than max frame num-1 */
  5047.      if( param->b_intra_refresh )
  5048.      {
  5049.          int time_to_recovery = X264_MIN( sps->i_mb_width - 1, param->i_keyint_max ) + param->i_bframe - 1;
  5050.          max_frame_num = X264_MAX( max_frame_num, time_to_recovery+1 );
  5051.      }
  5052. +    if (param->b_mvc) max_frame_num *= 2;
  5053. +
  5054. +    // for MVC
  5055. +    sps->i_log2_max_frame_num = param->b_mvc ? 8 : 4;
  5056.  
  5057. -    sps->i_log2_max_frame_num = 4;
  5058.      while( (1 << sps->i_log2_max_frame_num) <= max_frame_num )
  5059.          sps->i_log2_max_frame_num++;
  5060.  
  5061. @@ -161,7 +200,9 @@ void x264_sps_init( x264_sps_t *sps, int i_id, x264_param_t *param )
  5062.      if( sps->i_poc_type == 0 )
  5063.      {
  5064.          int max_delta_poc = (param->i_bframe + 2) * (!!param->i_bframe_pyramid + 1) * 2;
  5065. -        sps->i_log2_max_poc_lsb = 4;
  5066. +
  5067. +        sps->i_log2_max_poc_lsb = param->b_mvc ? 8 : 4;
  5068. +
  5069.          while( (1 << sps->i_log2_max_poc_lsb) <= max_delta_poc * 2 )
  5070.              sps->i_log2_max_poc_lsb++;
  5071.      }
  5072. @@ -254,7 +295,7 @@ void x264_sps_init( x264_sps_t *sps, int i_id, x264_param_t *param )
  5073.  
  5074.      // NOTE: HRD related parts of the SPS are initialised in x264_ratecontrol_init_reconfigurable
  5075.  
  5076. -    sps->vui.b_bitstream_restriction = 1;
  5077. +    sps->vui.b_bitstream_restriction = 0;
  5078.      if( sps->vui.b_bitstream_restriction )
  5079.      {
  5080.          sps->vui.b_motion_vectors_over_pic_boundaries = 1;
  5081. @@ -428,6 +469,250 @@ void x264_sps_write( bs_t *s, x264_sps_t *sps )
  5082.      bs_flush( s );
  5083.  }
  5084.  
  5085. +void x264_subset_sps_write( bs_t *s, x264_sps_t *sps )
  5086. +{
  5087. +    bs_realign( s );
  5088. +    bs_write( s, 8, sps->i_profile_idc );
  5089. +    bs_write1( s, sps->b_constraint_set0 );
  5090. +    bs_write1( s, sps->b_constraint_set1 );
  5091. +    bs_write1( s, sps->b_constraint_set2 );
  5092. +    bs_write1( s, sps->b_constraint_set3 );
  5093. +
  5094. +    bs_write( s, 4, 0 );    /* reserved */
  5095. +
  5096. +    bs_write( s, 8, sps->i_level_idc );
  5097. +
  5098. +    bs_write_ue( s, sps->i_id );
  5099. +
  5100. +    if( sps->i_profile_idc >= PROFILE_HIGH )
  5101. +    {
  5102. +        bs_write_ue( s, 1 ); // chroma_format_idc = 4:2:0
  5103. +        bs_write_ue( s, BIT_DEPTH-8 ); // bit_depth_luma_minus8
  5104. +        bs_write_ue( s, BIT_DEPTH-8 ); // bit_depth_chroma_minus8
  5105. +        bs_write1( s, sps->b_qpprime_y_zero_transform_bypass );
  5106. +        bs_write1( s, 0 ); // seq_scaling_matrix_present_flag
  5107. +    }
  5108. +
  5109. +    bs_write_ue( s, sps->i_log2_max_frame_num - 4 );
  5110. +    bs_write_ue( s, sps->i_poc_type );
  5111. +    if( sps->i_poc_type == 0 )
  5112. +    {
  5113. +        bs_write_ue( s, sps->i_log2_max_poc_lsb - 4 );
  5114. +    }
  5115. +    else if( sps->i_poc_type == 1 )
  5116. +    {
  5117. +        bs_write1( s, sps->b_delta_pic_order_always_zero );
  5118. +        bs_write_se( s, sps->i_offset_for_non_ref_pic );
  5119. +        bs_write_se( s, sps->i_offset_for_top_to_bottom_field );
  5120. +        bs_write_ue( s, sps->i_num_ref_frames_in_poc_cycle );
  5121. +
  5122. +        for( int i = 0; i < sps->i_num_ref_frames_in_poc_cycle; i++ )
  5123. +            bs_write_se( s, sps->i_offset_for_ref_frame[i] );
  5124. +    }
  5125. +    bs_write_ue( s, sps->i_num_ref_frames );
  5126. +    bs_write1( s, sps->b_gaps_in_frame_num_value_allowed );
  5127. +    bs_write_ue( s, sps->i_mb_width - 1 );
  5128. +    bs_write_ue( s, (sps->i_mb_height >> !sps->b_frame_mbs_only) - 1);
  5129. +    bs_write1( s, sps->b_frame_mbs_only );
  5130. +    if( !sps->b_frame_mbs_only )
  5131. +        bs_write1( s, sps->b_mb_adaptive_frame_field );
  5132. +    bs_write1( s, sps->b_direct8x8_inference );
  5133. +
  5134. +    bs_write1( s, sps->b_crop );
  5135. +    if( sps->b_crop )
  5136. +    {
  5137. +        bs_write_ue( s, sps->crop.i_left   / 2 );
  5138. +        bs_write_ue( s, sps->crop.i_right  / 2 );
  5139. +        bs_write_ue( s, sps->crop.i_top    / 2 );
  5140. +        bs_write_ue( s, sps->crop.i_bottom / 2 );
  5141. +    }
  5142. +
  5143. +    bs_write1( s, sps->b_vui );
  5144. +    if( sps->b_vui )
  5145. +    {
  5146. +        bs_write1( s, sps->vui.b_aspect_ratio_info_present );
  5147. +        if( sps->vui.b_aspect_ratio_info_present )
  5148. +        {
  5149. +            int i;
  5150. +            static const struct { uint8_t w, h, sar; } sar[] =
  5151. +            {
  5152. +                // aspect_ratio_idc = 0 -> unspecified
  5153. +                {  1,  1, 1 }, { 12, 11, 2 }, { 10, 11, 3 }, { 16, 11, 4 },
  5154. +                { 40, 33, 5 }, { 24, 11, 6 }, { 20, 11, 7 }, { 32, 11, 8 },
  5155. +                { 80, 33, 9 }, { 18, 11, 10}, { 15, 11, 11}, { 64, 33, 12},
  5156. +                {160, 99, 13}, {  4,  3, 14}, {  3,  2, 15}, {  2,  1, 16},
  5157. +                // aspect_ratio_idc = [17..254] -> reserved
  5158. +                { 0, 0, 255 }
  5159. +            };
  5160. +            for( i = 0; sar[i].sar != 255; i++ )
  5161. +            {
  5162. +                if( sar[i].w == sps->vui.i_sar_width &&
  5163. +                    sar[i].h == sps->vui.i_sar_height )
  5164. +                    break;
  5165. +            }
  5166. +            bs_write( s, 8, sar[i].sar );
  5167. +            if( sar[i].sar == 255 ) /* aspect_ratio_idc (extended) */
  5168. +            {
  5169. +                bs_write( s, 16, sps->vui.i_sar_width );
  5170. +                bs_write( s, 16, sps->vui.i_sar_height );
  5171. +            }
  5172. +        }
  5173. +
  5174. +        bs_write1( s, sps->vui.b_overscan_info_present );
  5175. +        if( sps->vui.b_overscan_info_present )
  5176. +            bs_write1( s, sps->vui.b_overscan_info );
  5177. +
  5178. +        bs_write1( s, sps->vui.b_signal_type_present );
  5179. +        if( sps->vui.b_signal_type_present )
  5180. +        {
  5181. +            bs_write( s, 3, sps->vui.i_vidformat );
  5182. +            bs_write1( s, sps->vui.b_fullrange );
  5183. +            bs_write1( s, sps->vui.b_color_description_present );
  5184. +            if( sps->vui.b_color_description_present )
  5185. +            {
  5186. +                bs_write( s, 8, sps->vui.i_colorprim );
  5187. +                bs_write( s, 8, sps->vui.i_transfer );
  5188. +                bs_write( s, 8, sps->vui.i_colmatrix );
  5189. +            }
  5190. +        }
  5191. +
  5192. +        bs_write1( s, sps->vui.b_chroma_loc_info_present );
  5193. +        if( sps->vui.b_chroma_loc_info_present )
  5194. +        {
  5195. +            bs_write_ue( s, sps->vui.i_chroma_loc_top );
  5196. +            bs_write_ue( s, sps->vui.i_chroma_loc_bottom );
  5197. +        }
  5198. +
  5199. +        bs_write1( s, sps->vui.b_timing_info_present );
  5200. +        if( sps->vui.b_timing_info_present )
  5201. +        {
  5202. +            bs_write32( s, sps->vui.i_num_units_in_tick );
  5203. +            bs_write32( s, sps->vui.i_time_scale );
  5204. +            bs_write1( s, sps->vui.b_fixed_frame_rate );
  5205. +        }
  5206. +
  5207. +        bs_write1( s, sps->vui.b_nal_hrd_parameters_present );
  5208. +        if( sps->vui.b_nal_hrd_parameters_present )
  5209. +        {
  5210. +            //            bs_write_ue( s, sps->vui.hrd.i_cpb_cnt - 1 );
  5211. +            bs_write_ue( s, 0 );
  5212. +            bs_write( s, 4, sps->vui.hrd.i_bit_rate_scale );
  5213. +            bs_write( s, 4, sps->vui.hrd.i_cpb_size_scale );
  5214. +
  5215. +            bs_write_ue( s, sps->vui.hrd.i_bit_rate_value - 1 );
  5216. +            bs_write_ue( s, sps->vui.hrd.i_cpb_size_value - 1 );
  5217. +
  5218. +            bs_write1( s, sps->vui.hrd.b_cbr_hrd );
  5219. +
  5220. +            bs_write( s, 5, sps->vui.hrd.i_initial_cpb_removal_delay_length - 1 );
  5221. +            bs_write( s, 5, sps->vui.hrd.i_cpb_removal_delay_length - 1 );
  5222. +            bs_write( s, 5, sps->vui.hrd.i_dpb_output_delay_length - 1 );
  5223. +            bs_write( s, 5, sps->vui.hrd.i_time_offset_length );
  5224. +        }
  5225. +
  5226. +        bs_write1( s, sps->vui.b_vcl_hrd_parameters_present );
  5227. +
  5228. +        if( sps->vui.b_nal_hrd_parameters_present || sps->vui.b_vcl_hrd_parameters_present )
  5229. +            bs_write1( s, 0 );   /* low_delay_hrd_flag */
  5230. +
  5231. +        bs_write1( s, sps->vui.b_pic_struct_present );
  5232. +        bs_write1( s, sps->vui.b_bitstream_restriction );
  5233. +        if( sps->vui.b_bitstream_restriction )
  5234. +        {
  5235. +            bs_write1( s, sps->vui.b_motion_vectors_over_pic_boundaries );
  5236. +            bs_write_ue( s, sps->vui.i_max_bytes_per_pic_denom );
  5237. +            bs_write_ue( s, sps->vui.i_max_bits_per_mb_denom );
  5238. +            bs_write_ue( s, sps->vui.i_log2_max_mv_length_horizontal );
  5239. +            bs_write_ue( s, sps->vui.i_log2_max_mv_length_vertical );
  5240. +            bs_write_ue( s, sps->vui.i_num_reorder_frames );
  5241. +            bs_write_ue( s, sps->vui.i_max_dec_frame_buffering );
  5242. +        }
  5243. +    }
  5244. +
  5245. +    bs_write1( s, 1 ); /* bit_equal_to_one f(1) */
  5246. +
  5247. +    // seq_parameter_set_mvc_extension()
  5248. +    int num_views_minus1 = 1;
  5249. +
  5250. +    int num_anchor_refs_l0 = 1;
  5251. +    int num_anchor_refs_l1 = 0;
  5252. +    int anchor_ref_l0 = 0;
  5253. +
  5254. +    int num_non_anchor_refs_l0 = 1;
  5255. +    int num_non_anchor_refs_l1 = 0;
  5256. +
  5257. +    int non_anchor_ref_l0 = 0;
  5258. +
  5259. +    bs_write_ue( s, num_views_minus1 );
  5260. +    
  5261. +    // view_id[i]
  5262. +    for (int i = 0; i <= num_views_minus1; i++) {
  5263. +      bs_write_ue( s, i );
  5264. +    }
  5265. +
  5266. +    for (int i = 1; i <= num_views_minus1; i++) {
  5267. +      // num_anchor_refs_l0
  5268. +      bs_write_ue( s, num_anchor_refs_l0 );
  5269. +      for ( int j = 0; j < num_anchor_refs_l0; j++) {
  5270. +   // anchor_ref_l0
  5271. +   bs_write_ue( s, anchor_ref_l0 );
  5272. +      }
  5273. +      
  5274. +      // num_anchor_refs_l1
  5275. +      bs_write_ue( s, num_anchor_refs_l1 );
  5276. +      
  5277. +      // num_non_anchor_refs_l0
  5278. +      bs_write_ue( s, num_non_anchor_refs_l0 );
  5279. +
  5280. +      for ( int j = 0; j < num_non_anchor_refs_l0; j++) {
  5281. +   // non_anchor_ref_l0
  5282. +   bs_write_ue( s, non_anchor_ref_l0 );
  5283. +      }
  5284. +
  5285. +      bs_write_ue( s, num_non_anchor_refs_l1 );
  5286. +    }
  5287. +
  5288. +    int num_level_values_signalled_minus1 = 0;
  5289. +    bs_write_ue( s, num_level_values_signalled_minus1 );
  5290. +    
  5291. +    int applicable_op_temporal_id[1][2] = {{0, 0}};
  5292. +    int applicable_op_num_target_views_minus1[1][2] = {{0, 1}};
  5293. +    
  5294. +    
  5295. +    for (int i = 0; i <= num_level_values_signalled_minus1; i++) {
  5296. +      bs_write( s, 8, sps->i_level_idc );
  5297. +      int num_applicable_ops_minus1 = 1;
  5298. +      bs_write_ue( s, num_applicable_ops_minus1 );
  5299. +      
  5300. +      for ( int j = 0; j <= num_applicable_ops_minus1; j++) {
  5301. +   bs_write( s, 3, applicable_op_temporal_id[i][j] );
  5302. +   bs_write_ue( s, applicable_op_num_target_views_minus1[i][j] );
  5303. +  
  5304. +   //  for ( int k = 0; k <= applicable_op_num_target_views_minus1[i][j]; k++) {
  5305. +     if (applicable_op_num_target_views_minus1[i][j] == 0) {
  5306. +       bs_write_ue( s, 0 );
  5307. +     } else {
  5308. +       bs_write_ue( s, 0 );
  5309. +       bs_write_ue( s, 1 );
  5310. +     }
  5311. +     //    }
  5312. +   // applicable_op_num_views_minus1
  5313. +   bs_write_ue( s, j );
  5314. +      }
  5315. +    }
  5316. +
  5317. +    // mvc_vui_parameters_present_flag
  5318. +    bs_write1( s, 0 );
  5319. +
  5320. +    // additional_extension2_flag
  5321. +    bs_write1( s, 0 );
  5322. +
  5323. +    bs_rbsp_trailing( s );
  5324. +    bs_flush( s );
  5325. +}
  5326. +
  5327. +
  5328. +
  5329.  void x264_pps_init( x264_pps_t *pps, int i_id, x264_param_t *param, x264_sps_t *sps )
  5330.  {
  5331.      pps->i_id = i_id;
  5332. @@ -562,7 +847,7 @@ int x264_sei_version_write( x264_t *h, bs_t *s )
  5333.          0xdc, 0x45, 0xe9, 0xbd, 0xe6, 0xd9, 0x48, 0xb7,
  5334.          0x96, 0x2c, 0xd8, 0x20, 0xd9, 0x23, 0xee, 0xef
  5335.      };
  5336. -    char *opts = x264_param2string( &h->param, 0 );
  5337. +    char *opts = x264_param2string( &h->param, 0, 0);
  5338.      char *payload;
  5339.      int length;
  5340.  
  5341. @@ -588,7 +873,7 @@ fail:
  5342.  
  5343.  void x264_sei_buffering_period_write( x264_t *h, bs_t *s )
  5344.  {
  5345. -    x264_sps_t *sps = h->sps;
  5346. +    x264_sps_t *sps = h->b_dependent ? h->subset_sps : h->sps;
  5347.      bs_t q;
  5348.      uint8_t tmp_buf[100];
  5349.      bs_init( &q, tmp_buf, 100 );
  5350. @@ -596,6 +881,10 @@ void x264_sei_buffering_period_write( x264_t *h, bs_t *s )
  5351.      bs_realign( &q );
  5352.      bs_write_ue( &q, sps->i_id );
  5353.  
  5354. +//    printf("[%4d](%s): sps = %d, cpb_length = %d, cpb_delay = %d, cpb_offset = %d   h=%p  \n",
  5355. +//           h->fenc->i_frame, h->b_dependent ? "d" : "m", sps->i_id, sps->vui.hrd.i_initial_cpb_removal_delay_length,
  5356. +//           h->initial_cpb_removal_delay, h->initial_cpb_removal_delay_offset, h);
  5357. +    
  5358.      if( sps->vui.b_nal_hrd_parameters_present )
  5359.      {
  5360.          bs_write( &q, sps->vui.hrd.i_initial_cpb_removal_delay_length, h->initial_cpb_removal_delay );
  5361. @@ -610,7 +899,12 @@ void x264_sei_buffering_period_write( x264_t *h, bs_t *s )
  5362.  
  5363.  void x264_sei_pic_timing_write( x264_t *h, bs_t *s )
  5364.  {
  5365. -    x264_sps_t *sps = h->sps;
  5366. +    x264_sps_t *sps = h->b_dependent ? h->subset_sps : h->sps;
  5367. +
  5368. +    struct timecode time;
  5369. +    time.b_drop = h->param.timecode_offset.b_drop;
  5370. +    calculate_timecode_from_frame((h->i_frame >> (h->param.b_mvc ? 1 : 0)) + h->offset_frame, h->param.i_fps_num, h->param.i_fps_den, &time);
  5371. +
  5372.      bs_t q;
  5373.      uint8_t tmp_buf[100];
  5374.      bs_init( &q, tmp_buf, 100 );
  5375. @@ -619,18 +913,61 @@ void x264_sei_pic_timing_write( x264_t *h, bs_t *s )
  5376.  
  5377.      if( sps->vui.b_nal_hrd_parameters_present || sps->vui.b_vcl_hrd_parameters_present )
  5378.      {
  5379. -        bs_write( &q, sps->vui.hrd.i_cpb_removal_delay_length, h->fenc->i_cpb_delay - h->i_cpb_delay_pir_offset );
  5380. +        bs_write( &q, sps->vui.hrd.i_cpb_removal_delay_length, h->fenc->i_cpb_delay - (h->b_dependent ? h->i_cpb_delay_pir_offset_dep : h->i_cpb_delay_pir_offset) );
  5381.          bs_write( &q, sps->vui.hrd.i_dpb_output_delay_length, h->fenc->i_dpb_output_delay );
  5382. +        
  5383. +//        printf("[%4d](%s): cpb=%4lld, dpb=%4lld\n",
  5384. +//               h->fenc->i_frame, h->b_dependent ? "d" : "m",
  5385. +//               h->fenc->i_cpb_delay - (h->b_dependent ? h->i_cpb_delay_pir_offset_dep : h->i_cpb_delay_pir_offset),
  5386. +//               h->fenc->i_dpb_output_delay);
  5387.      }
  5388.  
  5389.      if( sps->vui.b_pic_struct_present )
  5390.      {
  5391. -        bs_write( &q, 4, h->fenc->i_pic_struct-1 ); // We use index 0 for "Auto"
  5392. +        int i_pic_struct = h->fenc->i_pic_struct;
  5393. +        bs_write( &q, 4, i_pic_struct-1 ); // We use index 0 for "Auto"
  5394.  
  5395.          // These clock timestamps are not standardised so we don't set them
  5396.          // They could be time of origin, capture or alternative ideal display
  5397. +   /*
  5398.          for( int i = 0; i < num_clock_ts[h->fenc->i_pic_struct]; i++ )
  5399.              bs_write1( &q, 0 ); // clock_timestamp_flag
  5400. +   */
  5401. +
  5402. +        int numClockTS = i_pic_struct < 4 ? 1 : i_pic_struct < 6 ? 2 : i_pic_struct < 8 ? 3 : i_pic_struct == 8 ? 2 : 3;
  5403. +
  5404. +        for (int clocks=0; clocks<numClockTS; clocks++) {
  5405. +            // for MVC
  5406. +            bs_write1( &q, 1 ); // clock_timestamp_flag
  5407. +            // ct_type
  5408. +            bs_write(&q, 2, h->param.b_interlaced ? 1 : 0);
  5409. +            // nuit_field_based_flag
  5410. +            bs_write1(&q, 1);
  5411. +            // counting_type
  5412. +            bs_write(&q, 5, time.b_drop ? 4 : 1);
  5413. +            // full_timestamp_flag
  5414. +            bs_write1(&q, clocks == 0 ? 1 : 0);
  5415. +            // discontinuity_flag
  5416. +            bs_write1(&q, 0);
  5417. +            // cnt_dropped_flag
  5418. +            bs_write1(&q, time.b_drop ? 4 : 0);
  5419. +            // nframes
  5420. +            bs_write(&q, 8, time.frame);
  5421. +            if (clocks == 0) {
  5422. +                // seconds_value
  5423. +                bs_write(&q, 6, time.second);
  5424. +                // minutes_value
  5425. +                bs_write(&q, 6, time.minute);
  5426. +                // hours_value
  5427. +                bs_write(&q, 5, time.hour);
  5428. +            } else {
  5429. +                // seconds_flag = false
  5430. +                bs_write(&q, 1, 0);
  5431. +            }
  5432. +            // time_offset
  5433. +            // sps->vui.hrd.i_time_offset_length = 24
  5434. +            bs_write(&q, sps->vui.hrd.i_time_offset_length, 0);
  5435. +        }
  5436.      }
  5437.  
  5438.      bs_align_10( &q );
  5439. @@ -669,7 +1006,7 @@ void x264_sei_frame_packing_write( x264_t *h, bs_t *s )
  5440.          bs_write( &q, 4, 0 );                     // frame1_grid_position_y
  5441.      }
  5442.      bs_write( &q, 8, 0 );                         // frame_packing_arrangement_reserved_byte
  5443. -    bs_write_ue( &q, 1 );                         // frame_packing_arrangement_repetition_period
  5444. +    bs_write_ue( &q, 0 );                         // frame_packing_arrangement_repetition_period
  5445.      bs_write1( &q, 0 );                           // frame_packing_arrangement_extension_flag
  5446.  
  5447.      bs_align_10( &q );
  5448. diff --git encoder/set.h encoder/set.h
  5449. index 7fcca13..fc54c85 100644
  5450. --- encoder/set.h
  5451. +++ encoder/set.h
  5452. @@ -29,6 +29,8 @@
  5453.  
  5454.  void x264_sps_init( x264_sps_t *sps, int i_id, x264_param_t *param );
  5455.  void x264_sps_write( bs_t *s, x264_sps_t *sps );
  5456. +void x264_subset_sps_write( bs_t *s, x264_sps_t *sps );
  5457. +
  5458.  void x264_pps_init( x264_pps_t *pps, int i_id, x264_param_t *param, x264_sps_t *sps );
  5459.  void x264_pps_write( bs_t *s, x264_pps_t *pps );
  5460.  void x264_sei_recovery_point_write( x264_t *h, bs_t *s, int recovery_frame_cnt );
  5461. diff --git encoder/slicetype.c encoder/slicetype.c
  5462. index 1e0c80a..1c83e32 100644
  5463. --- encoder/slicetype.c
  5464. +++ encoder/slicetype.c
  5465. @@ -25,6 +25,8 @@
  5466.   * For more information, contact us at licensing@x264.com.
  5467.   *****************************************************************************/
  5468.  
  5469. +//#define __DEBUG
  5470. +
  5471.  #include "common/common.h"
  5472.  #include "macroblock.h"
  5473.  #include "me.h"
  5474. @@ -70,9 +72,19 @@ static void x264_weight_get_h264( int weight_nonh264, int offset, x264_weight_t
  5475.  
  5476.  static NOINLINE pixel *x264_weight_cost_init_luma( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, pixel *dest )
  5477.  {
  5478. -    int ref0_distance = fenc->i_frame - ref->i_frame - 1;
  5479. +  int ref0_distance;
  5480. +
  5481. +  int b_mvc = h->param.b_mvc;
  5482. +
  5483. +  ref0_distance = fenc->i_frame / (b_mvc ? 2 : 1) - ref->i_frame / (b_mvc ? 2 : 1) - 1;
  5484. +
  5485.      /* Note: this will never run during lookahead as weights_analyse is only called if no
  5486.       * motion search has been done. */
  5487. +
  5488. +#ifdef __DEBUG
  5489. +    x264_log(h, X264_LOG_INFO, "[weight_cost_init_luma] ref0_distance %d (enc=%d, ref=%d)\n", ref0_distance, fenc->i_frame, ref->i_frame);
  5490. +#endif
  5491. +
  5492.      if( fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF )
  5493.      {
  5494.          int i_stride = fenc->i_stride_lowres;
  5495. @@ -92,6 +104,7 @@ static NOINLINE pixel *x264_weight_cost_init_luma( x264_t *h, x264_frame_t *fenc
  5496.          x264_emms();
  5497.          return dest;
  5498.      }
  5499. +
  5500.      x264_emms();
  5501.      return ref->lowres[0];
  5502.  }
  5503. @@ -105,7 +118,8 @@ static NOINLINE pixel *x264_weight_cost_init_luma( x264_t *h, x264_frame_t *fenc
  5504.  
  5505.  static NOINLINE void x264_weight_cost_init_chroma( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, pixel *dstu, pixel *dstv )
  5506.  {
  5507. -    int ref0_distance = fenc->i_frame - ref->i_frame - 1;
  5508. +    int b_mvc = h->param.b_mvc;
  5509. +    int ref0_distance = (fenc->i_frame / (b_mvc ? 2 : 1)) - (ref->i_frame / (b_mvc ? 2 : 1)) - 1;
  5510.      int i_stride = fenc->i_stride[1];
  5511.      int i_offset = i_stride / 2;
  5512.      int i_lines = fenc->i_lines[1];
  5513. @@ -219,13 +233,20 @@ static NOINLINE unsigned int x264_weight_cost_chroma( x264_t *h, x264_frame_t *f
  5514.  
  5515.  void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int b_lookahead )
  5516.  {
  5517. -    int i_delta_index = fenc->i_frame - ref->i_frame - 1;
  5518. +    int b_mvc = h->param.b_mvc;
  5519. +    int i_delta_index = (fenc->i_frame / (b_mvc ? 2 : 1)) - (ref->i_frame / (b_mvc ? 2 : 1)) - 1;
  5520. +
  5521. +#ifdef __DEBUG
  5522. +    x264_log(h, X264_LOG_INFO, "[weights_analyse] i_delta_index  fenc->i_frame %d ref->i_frame %d - 1\n", fenc->i_frame, ref->i_frame);
  5523. +#endif
  5524. +
  5525.      /* epsilon is chosen to require at least a numerator of 127 (with denominator = 128) */
  5526.      const float epsilon = 1.f/128.f;
  5527.      x264_weight_t *weights = fenc->weight[0];
  5528.      SET_WEIGHT( weights[0], 0, 1, 0, 0 );
  5529.      SET_WEIGHT( weights[1], 0, 1, 0, 0 );
  5530.      SET_WEIGHT( weights[2], 0, 1, 0, 0 );
  5531. +
  5532.      /* Don't check chroma in lookahead, or if there wasn't a luma weight. */
  5533.      for( int plane = 0; plane <= 2 && !( plane && ( !weights[0].weightfn || b_lookahead ) ); plane++ )
  5534.      {
  5535. @@ -271,10 +292,17 @@ void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int
  5536.              {
  5537.                  x264_mb_analysis_t a;
  5538.                  x264_lowres_context_init( h, &a );
  5539. -                x264_slicetype_frame_cost( h, &a, &fenc, 0, 0, 0, 0 );
  5540. +#ifdef __DEBUG
  5541. +       x264_log(h, X264_LOG_INFO, "[weights_analyse] slicetype_frame_cost is called by weights analyse\n");
  5542. +#endif
  5543. +       x264_slicetype_frame_cost( h, &a, &fenc, 0, 0, 0, 0 );
  5544.              }
  5545. +       //      x264_log(h, X264_LOG_INFO, "weights analyse 0\n");
  5546. +
  5547.              mcbuf = x264_weight_cost_init_luma( h, fenc, ref, h->mb.p_weight_buf[0] );
  5548. +       //      x264_log(h, X264_LOG_INFO, "weights analyse 0\n");
  5549.              origscore = minscore = x264_weight_cost_luma( h, fenc, mcbuf, NULL );
  5550. +       //      x264_log(h, X264_LOG_INFO, "weights analyse 0\n");
  5551.          }
  5552.          else
  5553.          {
  5554. @@ -290,6 +318,9 @@ void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int
  5555.          if( !minscore )
  5556.              continue;
  5557.  
  5558. +   //  x264_log(h, X264_LOG_INFO, "weights analyse 1\n");
  5559. +
  5560. +
  5561.          // This gives a slight improvement due to rounding errors but only tests one offset in lookahead.
  5562.          // Currently only searches within +/- 1 of the best offset found so far.
  5563.          // TODO: Try other offsets/multipliers/combinations thereof?
  5564. @@ -312,6 +343,8 @@ void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int
  5565.          }
  5566.          x264_emms();
  5567.  
  5568. +   //  x264_log(h, X264_LOG_INFO, "weights analyse 2\n");
  5569. +
  5570.          /* FIXME: More analysis can be done here on SAD vs. SATD termination. */
  5571.          /* 0.2% termination derived experimentally to avoid weird weights in frames that are mostly intra. */
  5572.          if( !found || (minscale == 1 << mindenom && minoff == 0) || (float)minscore / origscore > 0.998f )
  5573. @@ -326,6 +359,7 @@ void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int
  5574.              fenc->f_weighted_cost_delta[i_delta_index] = (float)minscore / origscore;
  5575.      }
  5576.  
  5577. +    //    x264_log(h, X264_LOG_INFO, "weights analyse 3\n");
  5578.      //FIXME, what is the correct way to deal with this?
  5579.      if( weights[1].weightfn && weights[2].weightfn && weights[1].i_denom != weights[2].i_denom )
  5580.      {
  5581. @@ -339,6 +373,7 @@ void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int
  5582.          }
  5583.      }
  5584.  
  5585. +    //    x264_log(h, X264_LOG_INFO, "weights analyse 4\n");
  5586.      if( weights[0].weightfn && b_lookahead )
  5587.      {
  5588.          //scale lowres in lookahead for slicetype_frame_cost
  5589. @@ -350,6 +385,11 @@ void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int
  5590.                                   width, height, &weights[0] );
  5591.          fenc->weighted[0] = h->mb.p_weight_buf[0] + PADH + ref->i_stride_lowres * PADV;
  5592.      }
  5593. +
  5594. +    //    x264_log ( h, X264_LOG_INFO, "weight analyse done \n");
  5595. +
  5596. +
  5597. +
  5598.  }
  5599.  
  5600.  static void x264_slicetype_mb_cost( x264_t *h, x264_mb_analysis_t *a,
  5601. @@ -638,10 +678,18 @@ static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
  5602.       * If we have tried this frame as P, then we have also tried
  5603.       * the preceding frames as B. (is this still true?) */
  5604.      /* Also check that we already calculated the row SATDs for the current frame. */
  5605. -    if( frames[b]->i_cost_est[b-p0][p1-b] >= 0 && (!h->param.rc.i_vbv_buffer_size || frames[b]->i_row_satds[b-p0][p1-b][0] != -1) )
  5606. +    if( frames[b]->i_cost_est[b-p0][p1-b] >= 0 && (!h->param.rc.i_vbv_buffer_size || frames[b]->i_row_satds[b-p0][p1-b][0] != -1) ) {
  5607.          i_score = frames[b]->i_cost_est[b-p0][p1-b];
  5608. +
  5609. +#ifdef __DEBUG
  5610. +   x264_log( h, X264_LOG_INFO, "if 1 p0 %d p1 %d b %d b_intra %d\n", p0, p1, b, b_intra_penalty);
  5611. +#endif
  5612. +    }
  5613.      else
  5614.      {
  5615. +#ifdef __DEBUG
  5616. +        x264_log( h, X264_LOG_INFO, "if 2 p0 %d p1 %d b %d b_intra %d\n", p0, p1, b, b_intra_penalty);
  5617. +#endif
  5618.          int dist_scale_factor = 128;
  5619.          int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
  5620.          int *row_satd_intra = frames[b]->i_row_satds[0][0];
  5621. @@ -654,6 +702,10 @@ static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
  5622.              if( h->param.analyse.i_weighted_pred && b == p1 )
  5623.              {
  5624.                  x264_emms();
  5625. +
  5626. +       //      x264_log( h, X264_LOG_INFO, "param.analyse.i_weighted_pred %d\n", h->param.analyse.i_weighted_pred);
  5627. +
  5628. +       //x264_log( h, X264_LOG_INFO, "[slicetype frame cost] frames[%d] i_frame = %d to weights_analyse\n", b, frames[b]->i_frame);
  5629.                  x264_weights_analyse( h, frames[b], frames[p0], 1 );
  5630.                  w = frames[b]->weight[0];
  5631.              }
  5632. @@ -679,6 +731,7 @@ static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
  5633.  
  5634.          /* The edge mbs seem to reduce the predictive quality of the
  5635.           * whole frame's score, but are needed for a spatial distribution. */
  5636. +
  5637.          if( h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size ||
  5638.              h->mb.i_mb_width <= 2 || h->mb.i_mb_height <= 2 )
  5639.          {
  5640. @@ -714,6 +767,8 @@ static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
  5641.          int nmb = NUM_MBS;
  5642.          i_score += i_score * frames[b]->i_intra_mbs[b-p0] / (nmb * 8);
  5643.      }
  5644. +
  5645. +    //    x264_log( h, X264_LOG_INFO, "return i_score %d\n", i_score);
  5646.      return i_score;
  5647.  }
  5648.  
  5649. @@ -878,8 +933,10 @@ static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t
  5650.  
  5651.      int i = num_frames;
  5652.  
  5653. -    if( b_intra )
  5654. +    if( b_intra ) {
  5655. +      //      x264_log( h, X264_LOG_INFO, "called macroblock_tree\n");
  5656.          x264_slicetype_frame_cost( h, a, frames, 0, 0, 0, 0 );
  5657. +    }
  5658.  
  5659.      while( i > 0 && frames[i]->i_type == X264_TYPE_B )
  5660.          i--;
  5661. @@ -913,12 +970,15 @@ static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t
  5662.              cur_nonb--;
  5663.          if( cur_nonb < idx )
  5664.              break;
  5665. +
  5666. +   //      x264_log( h, X264_LOG_INFO, "called macroblock_tree\n");
  5667.          x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, last_nonb, 0 );
  5668.          memset( frames[cur_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
  5669.          bframes = last_nonb - cur_nonb - 1;
  5670.          if( h->param.i_bframe_pyramid && bframes > 1 )
  5671.          {
  5672.              int middle = (bframes + 1)/2 + cur_nonb;
  5673. +       //      x264_log( h, X264_LOG_INFO, "called macroblock_tree\n");
  5674.              x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, middle, 0 );
  5675.              memset( frames[middle]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
  5676.              while( i > cur_nonb )
  5677. @@ -927,6 +987,7 @@ static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t
  5678.                  int p1 = i < middle ? middle : last_nonb;
  5679.                  if( i != middle )
  5680.                  {
  5681. +         //      x264_log( h, X264_LOG_INFO, "called macroblock_tree\n");
  5682.                      x264_slicetype_frame_cost( h, a, frames, p0, p1, i, 0 );
  5683.                      x264_macroblock_tree_propagate( h, frames, average_duration, p0, p1, i, 0 );
  5684.                  }
  5685. @@ -938,6 +999,7 @@ static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t
  5686.          {
  5687.              while( i > cur_nonb )
  5688.              {
  5689. +         //      x264_log( h, X264_LOG_INFO, "called macroblock_tree\n");
  5690.                  x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, i, 0 );
  5691.                  x264_macroblock_tree_propagate( h, frames, average_duration, cur_nonb, last_nonb, i, 0 );
  5692.                  i--;
  5693. @@ -960,13 +1022,16 @@ static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t
  5694.  
  5695.  static int x264_vbv_frame_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int b )
  5696.  {
  5697. +
  5698. +  //      x264_log( h, X264_LOG_INFO, "called vbv_frame_cost\n");
  5699.      int cost = x264_slicetype_frame_cost( h, a, frames, p0, p1, b, 0 );
  5700.      if( h->param.rc.i_aq_mode )
  5701.      {
  5702. -        if( h->param.rc.b_mb_tree )
  5703. +      if( h->param.rc.b_mb_tree ) {
  5704.              return x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
  5705. -        else
  5706. +      } else {
  5707.              return frames[b]->i_cost_est_aq[b-p0][p1-b];
  5708. +      }
  5709.      }
  5710.      return cost;
  5711.  }
  5712. @@ -977,8 +1042,12 @@ static void x264_calculate_durations( x264_t *h, x264_frame_t *cur_frame, x264_f
  5713.      cur_frame->i_dpb_output_delay = cur_frame->i_field_cnt - *i_coded_fields;
  5714.  
  5715.      // add a correction term for frame reordering
  5716. -    cur_frame->i_dpb_output_delay += h->sps->vui.i_num_reorder_frames*2;
  5717. +    cur_frame->i_dpb_output_delay += cur_frame->i_frame & 1 ? h->subset_sps->vui.i_num_reorder_frames*2 : h->sps->vui.i_num_reorder_frames*2;
  5718.  
  5719. +//    printf("[%4d]: dpb_output_delay = %lld, field_cnt = %lld, coded_fields = %lld, num_reorder_frames*2 = %lld   \n",
  5720. +//           cur_frame->i_frame, cur_frame->i_dpb_output_delay, cur_frame->i_field_cnt, *i_coded_fields,
  5721. +//           cur_frame->i_frame & 1 ? h->subset_sps->vui.i_num_reorder_frames*2 : h->sps->vui.i_num_reorder_frames*2);
  5722. +    
  5723.      // fix possible negative dpb_output_delay because of pulldown changes and reordering
  5724.      if( cur_frame->i_dpb_output_delay < 0 )
  5725.      {
  5726. @@ -1073,6 +1142,8 @@ static int x264_slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_fram
  5727.              next_p++;
  5728.  
  5729.          /* Add the cost of the P-frame found above */
  5730. +   //  x264_log( h, X264_LOG_INFO, "called slicetype_path_cost\n");
  5731. +
  5732.          cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_p, 0 );
  5733.          /* Early terminate if the cost we have found is larger than the best path cost so far */
  5734.          if( cost > threshold )
  5735. @@ -1081,6 +1152,7 @@ static int x264_slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_fram
  5736.          if( h->param.i_bframe_pyramid && next_p - cur_p > 2 )
  5737.          {
  5738.              int middle = cur_p + (next_p - cur_p)/2;
  5739. +       //      x264_log( h, X264_LOG_INFO, "called slicetype_path_cost\n");
  5740.              cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, middle, 0 );
  5741.              for( int next_b = loc; next_b < middle && cost < threshold; next_b++ )
  5742.                  cost += x264_slicetype_frame_cost( h, a, frames, cur_p, middle, next_b, 0 );
  5743. @@ -1088,8 +1160,10 @@ static int x264_slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_fram
  5744.                  cost += x264_slicetype_frame_cost( h, a, frames, middle, next_p, next_b, 0 );
  5745.          }
  5746.          else
  5747. -            for( int next_b = loc; next_b < next_p && cost < threshold; next_b++ )
  5748. +     for( int next_b = loc; next_b < next_p && cost < threshold; next_b++ ) {
  5749. +       //      x264_log( h, X264_LOG_INFO, "called slicetype_path_cost\n");
  5750.                  cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_b, 0 );
  5751. +     }
  5752.  
  5753.          loc = next_p + 1;
  5754.          cur_p = next_p;
  5755. @@ -1132,18 +1206,20 @@ static void x264_slicetype_path( x264_t *h, x264_mb_analysis_t *a, x264_frame_t
  5756.  
  5757.  static int scenecut_internal( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int real_scenecut )
  5758.  {
  5759. +    int b_mvc = h->param.b_mvc;
  5760.      x264_frame_t *frame = frames[p1];
  5761.  
  5762.      /* Don't do scenecuts on the right view of a frame-packed video. */
  5763. -    if( real_scenecut && h->param.i_frame_packing == 5 && (frame->i_frame&1) )
  5764. +    if( real_scenecut && h->param.i_frame_packing == 5 && (frame->i_frame &1) )
  5765.          return 0;
  5766.  
  5767. +    //    x264_log( h, X264_LOG_INFO, "called scenecut_internal\n");
  5768.      x264_slicetype_frame_cost( h, a, frames, p0, p1, p1, 0 );
  5769.  
  5770.      int icost = frame->i_cost_est[0][0];
  5771.      int pcost = frame->i_cost_est[p1-p0][0];
  5772.      float f_bias;
  5773. -    int i_gop_size = frame->i_frame - h->lookahead->i_last_keyframe;
  5774. +    int i_gop_size = (frame->i_frame / (b_mvc ? 2 : 1)) - h->lookahead->i_last_keyframe;
  5775.      float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
  5776.      /* magic numbers pulled out of thin air */
  5777.      float f_thresh_min = f_thresh_max * 0.25;
  5778. @@ -1219,35 +1295,58 @@ static int scenecut( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, in
  5779.  void x264_slicetype_analyse( x264_t *h, int keyframe )
  5780.  {
  5781.      x264_mb_analysis_t a;
  5782. +    x264_mb_analysis_t a_dep;
  5783.      x264_frame_t *frames[X264_LOOKAHEAD_MAX+3] = { NULL, };
  5784. +    x264_frame_t *frames_dep[X264_LOOKAHEAD_MAX+3] = { NULL, };
  5785.      int num_frames, orig_num_frames, keyint_limit, framecnt;
  5786.      int i_mb_count = NUM_MBS;
  5787.      int cost1p0, cost2p0, cost1b1, cost2p1;
  5788.      int i_max_search = X264_MIN( h->lookahead->next.i_size, X264_LOOKAHEAD_MAX );
  5789.      int vbv_lookahead = h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead;
  5790. +
  5791. +    int b_mvc = h->param.b_mvc;
  5792. +    //x264_log( h, X264_LOG_INFO, "[slicetype_analyse] keyframe %d\n", keyframe);
  5793. +
  5794.      if( h->param.b_deterministic )
  5795.          i_max_search = X264_MIN( i_max_search, h->lookahead->i_slicetype_length + !keyframe );
  5796.  
  5797.      assert( h->frames.b_have_lowres );
  5798.  
  5799. +    //  x264_log( h, X264_LOG_INFO, "0\n");
  5800. +
  5801.      if( !h->lookahead->last_nonb )
  5802.          return;
  5803.      frames[0] = h->lookahead->last_nonb;
  5804. -    for( framecnt = 0; framecnt < i_max_search && h->lookahead->next.list[framecnt]->i_type == X264_TYPE_AUTO; framecnt++ )
  5805. +    if (b_mvc) frames_dep[0] = h->lookahead->last_nonb_dependent;
  5806. +
  5807. +#ifdef __DEBUG
  5808. +    x264_log (h, X264_LOG_INFO, "[slicetype_analyse] last_nonb's frame number %d\n", h->lookahead->last_nonb->i_frame);
  5809. +#endif
  5810. +
  5811. +    for( framecnt = 0; framecnt < i_max_search && h->lookahead->next.list[framecnt]->i_type == X264_TYPE_AUTO; framecnt++ ) {
  5812.          frames[framecnt+1] = h->lookahead->next.list[framecnt];
  5813. +        if (b_mvc) frames_dep[framecnt+1] = h->lookahead->next_dependent.list[framecnt];
  5814. +    }
  5815.  
  5816.      x264_lowres_context_init( h, &a );
  5817. +    if (b_mvc) x264_lowres_context_init( h, &a_dep );
  5818.  
  5819.      if( !framecnt )
  5820.      {
  5821. -        if( h->param.rc.b_mb_tree )
  5822. +        if( h->param.rc.b_mb_tree ) {
  5823.              x264_macroblock_tree( h, &a, frames, 0, keyframe );
  5824. +            if (b_mvc) x264_macroblock_tree( h, &a_dep, frames_dep, 0, keyframe );
  5825. +        }
  5826.          return;
  5827.      }
  5828.  
  5829. -    keyint_limit = h->param.i_keyint_max - frames[0]->i_frame + h->lookahead->i_last_keyframe - 1;
  5830. +    keyint_limit = h->param.i_keyint_max - (frames[0]->i_frame / (b_mvc ? 2 : 1)) + h->lookahead->i_last_keyframe - 1;
  5831.      orig_num_frames = num_frames = h->param.b_intra_refresh ? framecnt : X264_MIN( framecnt, keyint_limit );
  5832.  
  5833. +#ifdef __DEBUG
  5834. +    x264_log (h, X264_LOG_INFO, "[slicetype_analyse] num_frames %d valid frames in the nextbuf %d\n", num_frames, h->lookahead->next.i_size);
  5835. +#endif
  5836. +
  5837.      /* This is important psy-wise: if we have a non-scenecut keyframe,
  5838.       * there will be significant visual artifacts if the frames just before
  5839.       * go down in quality due to being referenced less, despite it being
  5840. @@ -1269,6 +1368,9 @@ void x264_slicetype_analyse( x264_t *h, int keyframe )
  5841.          return;
  5842.      }
  5843.  
  5844. +
  5845. +    //    x264_log( h, X264_LOG_INFO, "2 %d\n", h->param.i_bframe_adaptive);
  5846. +
  5847.      if( h->param.i_bframe )
  5848.      {
  5849.          if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
  5850. @@ -1279,25 +1381,46 @@ void x264_slicetype_analyse( x264_t *h, int keyframe )
  5851.                  int best_path_index = (num_frames-1) % (X264_BFRAME_MAX+1);
  5852.  
  5853.                  /* Perform the frametype analysis. */
  5854. -                for( int j = 2; j < num_frames; j++ )
  5855. +                for( int j = 2; j < num_frames; j++ ) {
  5856.                      x264_slicetype_path( h, &a, frames, j, best_paths );
  5857. +                    if (b_mvc) x264_slicetype_path( h, &a_dep, frames_dep, j, best_paths );
  5858. +                }
  5859.  
  5860.                  num_bframes = strspn( best_paths[best_path_index], "B" );
  5861.                  /* Load the results of the analysis into the frame types. */
  5862. -                for( int j = 1; j < num_frames; j++ )
  5863. +                for( int j = 1; j < num_frames; j++ ) {
  5864.                      frames[j]->i_type = best_paths[best_path_index][j-1] == 'B' ? X264_TYPE_B : X264_TYPE_P;
  5865. +                    if (b_mvc) frames_dep[j]->i_type = frames[j]->i_type;
  5866. +                }
  5867.              }
  5868.              frames[num_frames]->i_type = X