source: 3DVCSoftware/branches/HTM-4.0-LG/source/Lib/TLibEncoder/TEncGOP.cpp @ 142

Last change on this file since 142 was 110, checked in by lg, 12 years ago

LGE_WVSO_A0119 integration (non-CTC)

  • Property svn:eol-style set to native
File size: 94.3 KB
Line 
1/* The copyright in this software is being made available under the BSD
2 * License, included below. This software may be subject to other third party
3 * and contributor rights, including patent rights, and no such rights are
4 * granted under this license. 
5 *
6 * Copyright (c) 2010-2012, ITU/ISO/IEC
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
11 *
12 *  * Redistributions of source code must retain the above copyright notice,
13 *    this list of conditions and the following disclaimer.
14 *  * Redistributions in binary form must reproduce the above copyright notice,
15 *    this list of conditions and the following disclaimer in the documentation
16 *    and/or other materials provided with the distribution.
17 *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
18 *    be used to endorse or promote products derived from this software without
19 *    specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
31 * THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34/** \file     TEncGOP.cpp
35    \brief    GOP encoder class
36*/
37
38#include <list>
39#include <algorithm>
40
41#include "TEncTop.h"
42#include "TEncGOP.h"
43#include "TEncAnalyze.h"
44#include "libmd5/MD5.h"
45#include "TLibCommon/SEI.h"
46#include "TLibCommon/NAL.h"
47#include "NALwrite.h"
48#include "../../App/TAppEncoder/TAppEncTop.h"
49
50#include <time.h>
51#include <math.h>
52
53using namespace std;
54
55//! \ingroup TLibEncoder
56//! \{
57
58// ====================================================================================================================
59// Constructor / destructor / initialization / destroy
60// ====================================================================================================================
61
62TEncGOP::TEncGOP()
63{
64  m_iLastIDR            = 0;
65  m_iGopSize            = 0;
66  m_iNumPicCoded        = 0; //Niko
67  m_bFirst              = true;
68 
69  m_pcCfg               = NULL;
70  m_pcSliceEncoder      = NULL;
71  m_pcListPic           = NULL;
72 
73  m_pcEntropyCoder      = NULL;
74  m_pcCavlcCoder        = NULL;
75  m_pcSbacCoder         = NULL;
76  m_pcBinCABAC          = NULL;
77#if DEPTH_MAP_GENERATION
78  m_pcDepthMapGenerator = NULL;
79#endif
80#if HHI_INTER_VIEW_RESIDUAL_PRED
81  m_pcResidualGenerator = NULL;
82#endif
83 
84  m_bSeqFirst           = true;
85 
86  m_bRefreshPending     = 0;
87  m_pocCRA              = 0;
88
89  return;
90}
91
92TEncGOP::~TEncGOP()
93{
94}
95
96/** Create list to contain pointers to LCU start addresses of slice.
97 * \param iWidth, iHeight are picture width, height. iMaxCUWidth, iMaxCUHeight are LCU width, height.
98 */
99Void  TEncGOP::create( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight )
100{
101  UInt uiWidthInCU       = ( iWidth %iMaxCUWidth  ) ? iWidth /iMaxCUWidth  + 1 : iWidth /iMaxCUWidth;
102  UInt uiHeightInCU      = ( iHeight%iMaxCUHeight ) ? iHeight/iMaxCUHeight + 1 : iHeight/iMaxCUHeight;
103  UInt uiNumCUsInFrame   = uiWidthInCU * uiHeightInCU;
104  m_uiStoredStartCUAddrForEncodingSlice = new UInt [uiNumCUsInFrame*(1<<(g_uiMaxCUDepth<<1))+1];
105  m_uiStoredStartCUAddrForEncodingEntropySlice = new UInt [uiNumCUsInFrame*(1<<(g_uiMaxCUDepth<<1))+1];
106  m_bLongtermTestPictureHasBeenCoded = 0;
107  m_bLongtermTestPictureHasBeenCoded2 = 0;
108}
109
110Void  TEncGOP::destroy()
111{
112  delete [] m_uiStoredStartCUAddrForEncodingSlice; m_uiStoredStartCUAddrForEncodingSlice = NULL;
113  delete [] m_uiStoredStartCUAddrForEncodingEntropySlice; m_uiStoredStartCUAddrForEncodingEntropySlice = NULL;
114}
115
116Void TEncGOP::init ( TEncTop* pcTEncTop )
117{
118  m_pcEncTop     = pcTEncTop;
119  m_pcCfg                = pcTEncTop;
120  m_pcSliceEncoder       = pcTEncTop->getSliceEncoder();
121  m_pcListPic            = pcTEncTop->getListPic();
122 
123  m_pcEntropyCoder       = pcTEncTop->getEntropyCoder();
124  m_pcCavlcCoder         = pcTEncTop->getCavlcCoder();
125  m_pcSbacCoder          = pcTEncTop->getSbacCoder();
126  m_pcBinCABAC           = pcTEncTop->getBinCABAC();
127  m_pcLoopFilter         = pcTEncTop->getLoopFilter();
128  m_pcBitCounter         = pcTEncTop->getBitCounter();
129 
130#if DEPTH_MAP_GENERATION
131  m_pcDepthMapGenerator  = pcTEncTop->getDepthMapGenerator();
132#endif
133#if HHI_INTER_VIEW_RESIDUAL_PRED
134  m_pcResidualGenerator  = pcTEncTop->getResidualGenerator();
135#endif
136 
137  // Adaptive Loop filter
138  m_pcAdaptiveLoopFilter = pcTEncTop->getAdaptiveLoopFilter();
139  //--Adaptive Loop filter
140  m_pcSAO                = pcTEncTop->getSAO();
141  m_pcRdCost             = pcTEncTop->getRdCost();
142}
143
144// ====================================================================================================================
145// Public member functions
146// ====================================================================================================================
147
148Void TEncGOP::initGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP)
149{
150  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut );
151  m_iNumPicCoded = 0;
152}
153
154Void TEncGOP::compressPicInGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Int iGOPid)
155{
156  TComPic*        pcPic;
157  TComPicYuv*     pcPicYuvRecOut;
158  TComSlice*      pcSlice;
159  TComOutputBitstream  *pcBitstreamRedirect;
160  pcBitstreamRedirect = new TComOutputBitstream;
161#if !REMOVE_TILE_DEPENDENCE
162  OutputNALUnit        *naluBuffered             = NULL;
163  Bool                  bIteratorAtListStart     = false;
164#endif
165  AccessUnit::iterator  itLocationToPushSliceHeaderNALU; // used to store location where NALU containing slice header is to be inserted
166  UInt                  uiOneBitstreamPerSliceLength = 0;
167  TEncSbac* pcSbacCoders = NULL;
168  TComOutputBitstream* pcSubstreamsOut = NULL;
169
170  {
171      UInt uiColDir = 1;
172      //-- For time output for each slice
173      long iBeforeTime = clock();
174     
175      //select uiColDir
176      Int iCloseLeft=1, iCloseRight=-1;
177      for(Int i = 0; i<m_pcCfg->getGOPEntry(iGOPid).m_numRefPics; i++) 
178      {
179        Int iRef = m_pcCfg->getGOPEntry(iGOPid).m_referencePics[i];
180        if(iRef>0&&(iRef<iCloseRight||iCloseRight==-1))
181        {
182          iCloseRight=iRef;
183        }
184        else if(iRef<0&&(iRef>iCloseLeft||iCloseLeft==1))
185        {
186          iCloseLeft=iRef;
187        }
188      }
189      if(iCloseRight>-1)
190      {
191        iCloseRight=iCloseRight+m_pcCfg->getGOPEntry(iGOPid).m_POC-1;
192      }
193      if(iCloseLeft<1) 
194      {
195        iCloseLeft=iCloseLeft+m_pcCfg->getGOPEntry(iGOPid).m_POC-1;
196        while(iCloseLeft<0)
197        {
198          iCloseLeft+=m_iGopSize;
199        }
200      }
201      Int iLeftQP=0, iRightQP=0;
202      for(Int i=0; i<m_iGopSize; i++)
203      {
204        if(m_pcCfg->getGOPEntry(i).m_POC==(iCloseLeft%m_iGopSize)+1)
205        {
206          iLeftQP= m_pcCfg->getGOPEntry(i).m_QPOffset;
207        }
208        if (m_pcCfg->getGOPEntry(i).m_POC==(iCloseRight%m_iGopSize)+1)
209        {
210          iRightQP=m_pcCfg->getGOPEntry(i).m_QPOffset;
211        }
212      }
213      if(iCloseRight>-1&&iRightQP<iLeftQP)
214      {
215        uiColDir=0;
216      }
217
218      /////////////////////////////////////////////////////////////////////////////////////////////////// Initial to start encoding
219      UInt uiPOCCurr = iPOCLast -iNumPicRcvd+ m_pcCfg->getGOPEntry(iGOPid).m_POC;
220      Int iTimeOffset = m_pcCfg->getGOPEntry(iGOPid).m_POC;
221      if(iPOCLast == 0)
222      {
223        uiPOCCurr=0;
224        iTimeOffset = 1;
225      }
226      if(uiPOCCurr>=m_pcCfg->getFrameToBeEncoded())
227      {
228        return;
229      }       
230      if( getNalUnitTypeBaseViewMvc( uiPOCCurr ) == NAL_UNIT_CODED_SLICE_IDR )
231      {
232        m_iLastIDR = uiPOCCurr;
233      }       
234
235      /* start a new access unit: create an entry in the list of output
236       * access units */
237      accessUnitsInGOP.push_back(AccessUnit());
238      AccessUnit& accessUnit = accessUnitsInGOP.back();
239      xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, uiPOCCurr );
240     
241      //  Slice data initialization
242      pcPic->clearSliceBuffer();
243      assert(pcPic->getNumAllocatedSlice() == 1);
244      m_pcSliceEncoder->setSliceIdx(0);
245      pcPic->setCurrSliceIdx(0);
246
247      std::vector<TComAPS>& vAPS = m_pcEncTop->getAPS();
248#if VIDYO_VPS_INTEGRATION
249    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, uiPOCCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getEncTop()->getVPS(), m_pcEncTop->getSPS(), m_pcEncTop->getPPS() );
250#else
251      m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, uiPOCCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS() );
252#endif
253      pcSlice->setLastIDR(m_iLastIDR);
254      pcSlice->setSliceIdx(0);
255      pcSlice->setViewId( m_pcEncTop->getViewId() );
256      pcSlice->setIsDepth( m_pcEncTop->getIsDepth() ); 
257
258      m_pcEncTop->getSPS()->setDisInter4x4(m_pcEncTop->getDisInter4x4());
259      pcSlice->setScalingList ( m_pcEncTop->getScalingList()  );
260      if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_OFF)
261      {
262        m_pcEncTop->getTrQuant()->setFlatScalingList();
263        m_pcEncTop->getTrQuant()->setUseScalingList(false);
264      }
265      else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_DEFAULT)
266      {
267        pcSlice->setDefaultScalingList ();
268        pcSlice->getScalingList()->setScalingListPresentFlag(true);
269        m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList());
270        m_pcEncTop->getTrQuant()->setUseScalingList(true);
271      }
272      else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_FILE_READ)
273      {
274        if(pcSlice->getScalingList()->xParseScalingList(m_pcCfg->getScalingListFile()))
275        {
276          pcSlice->setDefaultScalingList ();
277        }
278#if SCALING_LIST
279        pcSlice->getScalingList()->checkDcOfMatrix();
280#endif
281        pcSlice->getScalingList()->setScalingListPresentFlag(pcSlice->checkDefaultScalingList());
282        m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList());
283        m_pcEncTop->getTrQuant()->setUseScalingList(true);
284      }
285      else
286      {
287        printf("error : ScalingList == %d no support\n",m_pcEncTop->getUseScalingListId());
288        assert(0);
289      }
290
291#if HHI_INTERVIEW_SKIP
292      if ( m_pcEncTop->getInterViewSkip() )
293      {
294        m_pcEncTop->getEncTop()->getUsedPelsMap( pcPic->getViewId(), pcPic->getPOC(), pcPic->getUsedPelsMap() );
295      }
296#endif
297      //  Slice info. refinement
298      if( pcSlice->getSliceType() == B_SLICE )
299      {
300        if( m_pcCfg->getGOPEntry( (getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDV) ? MAX_GOP : iGOPid ).m_sliceType == 'P' ) { pcSlice->setSliceType( P_SLICE ); }
301      }
302
303      // Set the nal unit type
304      pcSlice->setNalUnitType( getNalUnitType(uiPOCCurr) );
305      pcSlice->setNalUnitTypeBaseViewMvc( getNalUnitTypeBaseViewMvc(uiPOCCurr) );
306
307      // Do decoding refresh marking if any
308      pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic);
309
310      if ( !pcSlice->getPPS()->getEnableTMVPFlag() && pcPic->getTLayer() == 0 )
311      {
312        pcSlice->decodingMarkingForNoTMVP( rcListPic, pcSlice->getPOC() );
313      }
314
315      m_pcEncTop->selectReferencePictureSet(pcSlice, uiPOCCurr, iGOPid,rcListPic);
316      pcSlice->getRPS()->setNumberOfLongtermPictures(0);
317
318      if(pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0)
319      {
320         pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS());
321      }
322      pcSlice->applyReferencePictureSet(rcListPic, pcSlice->getRPS());
323
324#if H0566_TLA && H0566_TLA_SET_FOR_SWITCHING_POINTS
325      if(pcSlice->getTLayer() > 0)
326      {
327        if(pcSlice->isTemporalLayerSwitchingPoint(rcListPic, pcSlice->getRPS()))
328        {
329          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA);
330        }
331      }
332#endif
333
334      pcSlice->setNumRefIdx( REF_PIC_LIST_0, min( m_pcCfg->getGOPEntry( (getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDV) ? MAX_GOP : iGOPid ).m_numRefPicsActive, (pcSlice->getRPS()->getNumberOfPictures() + pcSlice->getSPS()->getNumberOfUsableInterViewRefs()) ) );
335      pcSlice->setNumRefIdx( REF_PIC_LIST_1, min( m_pcCfg->getGOPEntry( (getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDV) ? MAX_GOP : iGOPid ).m_numRefPicsActive, (pcSlice->getRPS()->getNumberOfPictures() + pcSlice->getSPS()->getNumberOfUsableInterViewRefs()) ) );
336
337      TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
338      refPicListModification->setRefPicListModificationFlagL0( false );
339#if !H0137_0138_LIST_MODIFICATION
340      refPicListModification->setNumberOfRefPicListModificationsL0(0);
341#endif
342      refPicListModification->setRefPicListModificationFlagL1( false );
343#if !H0137_0138_LIST_MODIFICATION
344      refPicListModification->setNumberOfRefPicListModificationsL1(0);
345#endif
346      xSetRefPicListModificationsMvc( pcSlice, uiPOCCurr, iGOPid );
347
348#if ADAPTIVE_QP_SELECTION
349      pcSlice->setTrQuant( m_pcEncTop->getTrQuant() );
350#endif     
351      //  Set reference list
352      TAppEncTop* tAppEncTop = m_pcEncTop->getEncTop();
353      assert( tAppEncTop != NULL );
354
355      TComPic * const pcTexturePic = m_pcEncTop->getIsDepth() ? tAppEncTop->getPicFromView( m_pcEncTop->getViewId(), pcSlice->getPOC(), false ) : NULL;
356      assert( !m_pcEncTop->getIsDepth() || pcTexturePic != NULL );
357      pcSlice->setTexturePic( pcTexturePic );
358
359      std::vector<TComPic*> apcInterViewRefPics = tAppEncTop->getInterViewRefPics( m_pcEncTop->getViewId(), pcSlice->getPOC(), m_pcEncTop->getIsDepth(), pcSlice->getSPS() );
360      pcSlice->setRefPicListMvc( rcListPic, apcInterViewRefPics );
361
362      //  Slice info. refinement
363      if( pcSlice->getSliceType() == B_SLICE )
364      {
365        if( m_pcCfg->getGOPEntry( (getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDV) ? MAX_GOP : iGOPid ).m_sliceType == 'P' ) { pcSlice->setSliceType( P_SLICE ); }
366      }
367     
368      if (pcSlice->getSliceType() != B_SLICE || !pcSlice->getSPS()->getUseLComb())
369      {
370        pcSlice->setNumRefIdx(REF_PIC_LIST_C, 0);
371        pcSlice->setRefPicListCombinationFlag(false);
372        pcSlice->setRefPicListModificationFlagLC(false);
373      }
374      else
375      {
376        pcSlice->setRefPicListCombinationFlag(pcSlice->getSPS()->getUseLComb());
377        pcSlice->setRefPicListModificationFlagLC(pcSlice->getSPS()->getLCMod());
378        pcSlice->setNumRefIdx(REF_PIC_LIST_C, pcSlice->getNumRefIdx(REF_PIC_LIST_0));
379      }
380     
381      if (pcSlice->getSliceType() == B_SLICE)
382      {
383        pcSlice->setColDir(uiColDir);
384        Bool bLowDelay = true;
385        Int  iCurrPOC  = pcSlice->getPOC();
386        Int iRefIdx = 0;
387
388        for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_0) && bLowDelay; iRefIdx++)
389        {
390          if ( pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx)->getPOC() > iCurrPOC )
391          {
392            bLowDelay = false;
393          }
394        }
395        for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_1) && bLowDelay; iRefIdx++)
396        {
397          if ( pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx)->getPOC() > iCurrPOC )
398          {
399            bLowDelay = false;
400          }
401        }
402
403        pcSlice->setCheckLDC(bLowDelay); 
404      }
405     
406      uiColDir = 1-uiColDir;
407     
408      //-------------------------------------------------------------
409      pcSlice->setRefPOCnViewListsMvc();
410     
411      pcSlice->setNoBackPredFlag( false );
412      if ( pcSlice->getSliceType() == B_SLICE && !pcSlice->getRefPicListCombinationFlag())
413      {
414        if ( pcSlice->getNumRefIdx(RefPicList( 0 ) ) == pcSlice->getNumRefIdx(RefPicList( 1 ) ) )
415        {
416          pcSlice->setNoBackPredFlag( true );
417          int i;
418          for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
419          {
420            if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) ) 
421            {
422              pcSlice->setNoBackPredFlag( false );
423              break;
424            }
425          }
426        }
427      }
428
429      if(pcSlice->getNoBackPredFlag())
430      {
431        pcSlice->setNumRefIdx(REF_PIC_LIST_C, 0);
432      }
433      pcSlice->generateCombinedList();
434     
435#if HHI_VSO
436  Bool bUseVSO = m_pcEncTop->getUseVSO();
437  m_pcRdCost->setUseVSO( bUseVSO );
438#if SAIT_VSO_EST_A0033
439  m_pcRdCost->setUseEstimatedVSD( m_pcEncTop->getUseEstimatedVSD() );
440#endif
441
442  if ( bUseVSO )
443  {
444    Int iVSOMode = m_pcEncTop->getVSOMode();
445    m_pcRdCost->setVSOMode( iVSOMode  );
446#if HHI_VSO_DIST_INT
447    m_pcRdCost->setAllowNegDist( m_pcEncTop->getAllowNegDist() );
448#endif
449
450#if HHI_VSO_SPEEDUP_A0033
451#else
452    if ( iVSOMode == 4 )
453    {
454      m_pcEncTop->getEncTop()->setupRenModel( pcSlice->getPOC(), pcSlice->getViewId(), m_pcEncTop->isDepthCoder() ? 1 : 0 );
455    }
456    else
457    {
458      AOT(true); 
459    }
460#endif
461
462#if SAIT_VSO_EST_A0033
463    m_pcRdCost->setVideoRecPicYuv( m_pcEncTop->getEncTop()->getPicYuvFromView( pcSlice->getViewId(), pcSlice->getPOC(), false, true ) );
464    m_pcRdCost->setDepthPicYuv   ( m_pcEncTop->getEncTop()->getPicYuvFromView( pcSlice->getViewId(), pcSlice->getPOC(), true, false ) );
465#endif
466#if LGE_WVSO_A0119
467    Bool bWVSO  = m_pcEncTop->getWVSO();
468    m_pcRdCost->setWVSO( bWVSO );
469#endif
470
471  }
472#endif
473      /////////////////////////////////////////////////////////////////////////////////////////////////// Compress a slice
474      //  Slice compression
475      if (m_pcCfg->getUseASR())
476      {
477        m_pcSliceEncoder->setSearchRange(pcSlice);
478      }
479
480#if H0111_MVD_L1_ZERO
481      Bool bGPBcheck=false;
482      if ( pcSlice->getSliceType() == B_SLICE)
483      {
484        if ( pcSlice->getNumRefIdx(RefPicList( 0 ) ) == pcSlice->getNumRefIdx(RefPicList( 1 ) ) )
485        {
486          bGPBcheck=true;
487          int i;
488          for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
489          {
490            if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) ) 
491            {
492              bGPBcheck=false;
493              break;
494            }
495          }
496        }
497      }
498      if(bGPBcheck)
499      {
500        pcSlice->setMvdL1ZeroFlag(true);
501      }
502      else
503      {
504        pcSlice->setMvdL1ZeroFlag(false);
505      }
506      pcPic->getSlice(pcSlice->getSliceIdx())->setMvdL1ZeroFlag(pcSlice->getMvdL1ZeroFlag());
507#endif
508
509      UInt uiNumSlices = 1;
510
511      UInt uiInternalAddress = pcPic->getNumPartInCU()-4;
512      UInt uiExternalAddress = pcPic->getPicSym()->getNumberOfCUsInFrame()-1;
513      UInt uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
514      UInt uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
515      UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
516      UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
517      while(uiPosX>=uiWidth||uiPosY>=uiHeight) 
518      {
519        uiInternalAddress--;
520        uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
521        uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
522      }
523      uiInternalAddress++;
524      if(uiInternalAddress==pcPic->getNumPartInCU()) 
525      {
526        uiInternalAddress = 0;
527        uiExternalAddress++;
528      }
529      UInt uiRealEndAddress = uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress;
530
531    UInt uiCummulativeTileWidth;
532    UInt uiCummulativeTileHeight;
533    Int  p, j;
534    UInt uiEncCUAddr;
535   
536#if !REMOVE_TILE_DEPENDENCE
537    if(pcSlice->getPPS()->getTileBehaviorControlPresentFlag() == 1)
538    {
539      pcPic->getPicSym()->setTileBoundaryIndependenceIdr( pcSlice->getPPS()->getTileBoundaryIndependenceIdr() );
540    }
541    else
542    {
543      pcPic->getPicSym()->setTileBoundaryIndependenceIdr( pcSlice->getPPS()->getSPS()->getTileBoundaryIndependenceIdr() );
544
545    }
546#endif
547
548    if( pcSlice->getPPS()->getColumnRowInfoPresent() == 1 )    //derive the tile parameters from PPS
549    {
550      //set NumColumnsMinus1 and NumRowsMinus1
551      pcPic->getPicSym()->setNumColumnsMinus1( pcSlice->getPPS()->getNumColumnsMinus1() );
552      pcPic->getPicSym()->setNumRowsMinus1( pcSlice->getPPS()->getNumRowsMinus1() );
553
554      //create the TComTileArray
555      pcPic->getPicSym()->xCreateTComTileArray();
556
557      if( pcSlice->getPPS()->getUniformSpacingIdr() == 1 )
558      {
559        //set the width for each tile
560        for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
561        {
562          for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1()+1; p++)
563          {
564            pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->
565              setTileWidth( (p+1)*pcPic->getPicSym()->getFrameWidthInCU()/(pcPic->getPicSym()->getNumColumnsMinus1()+1) 
566              - (p*pcPic->getPicSym()->getFrameWidthInCU())/(pcPic->getPicSym()->getNumColumnsMinus1()+1) );
567          }
568        }
569
570        //set the height for each tile
571        for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
572        {
573          for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1()+1; p++)
574          {
575            pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->
576              setTileHeight( (p+1)*pcPic->getPicSym()->getFrameHeightInCU()/(pcPic->getPicSym()->getNumRowsMinus1()+1) 
577              - (p*pcPic->getPicSym()->getFrameHeightInCU())/(pcPic->getPicSym()->getNumRowsMinus1()+1) );   
578          }
579        }
580      }
581      else
582      {
583        //set the width for each tile
584        for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
585        {
586          uiCummulativeTileWidth = 0;
587          for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1(); p++)
588          {
589            pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->setTileWidth( pcSlice->getPPS()->getColumnWidth(p) );
590            uiCummulativeTileWidth += pcSlice->getPPS()->getColumnWidth(p);
591          }
592          pcPic->getPicSym()->getTComTile(j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p)->setTileWidth( pcPic->getPicSym()->getFrameWidthInCU()-uiCummulativeTileWidth );
593        }
594
595        //set the height for each tile
596        for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
597        {
598          uiCummulativeTileHeight = 0;
599          for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1(); p++)
600          {
601            pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->setTileHeight( pcSlice->getPPS()->getRowHeight(p) );
602            uiCummulativeTileHeight += pcSlice->getPPS()->getRowHeight(p);
603          }
604          pcPic->getPicSym()->getTComTile(p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j)->setTileHeight( pcPic->getPicSym()->getFrameHeightInCU()-uiCummulativeTileHeight );
605        }
606      }
607    }
608    else //derive the tile parameters from SPS
609    {
610      //set NumColumnsMins1 and NumRowsMinus1
611      pcPic->getPicSym()->setNumColumnsMinus1( pcSlice->getSPS()->getNumColumnsMinus1() );
612      pcPic->getPicSym()->setNumRowsMinus1( pcSlice->getSPS()->getNumRowsMinus1() );
613
614      //create the TComTileArray
615      pcPic->getPicSym()->xCreateTComTileArray();
616
617      if( pcSlice->getSPS()->getUniformSpacingIdr() == 1 )
618      {
619        //set the width for each tile
620        for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
621        {
622          for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1()+1; p++)
623          {
624            pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->
625              setTileWidth( (p+1)*pcPic->getPicSym()->getFrameWidthInCU()/(pcPic->getPicSym()->getNumColumnsMinus1()+1) 
626              - (p*pcPic->getPicSym()->getFrameWidthInCU())/(pcPic->getPicSym()->getNumColumnsMinus1()+1) );
627          }
628        }
629
630        //set the height for each tile
631        for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
632        {
633          for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1()+1; p++)
634          {
635            pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->
636              setTileHeight( (p+1)*pcPic->getPicSym()->getFrameHeightInCU()/(pcPic->getPicSym()->getNumRowsMinus1()+1) 
637              - (p*pcPic->getPicSym()->getFrameHeightInCU())/(pcPic->getPicSym()->getNumRowsMinus1()+1) );   
638          }
639        }
640      }
641
642      else
643      {
644        //set the width for each tile
645        for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
646        {
647          uiCummulativeTileWidth = 0;
648          for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1(); p++)
649          {
650            pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->setTileWidth( pcSlice->getSPS()->getColumnWidth(p) );
651            uiCummulativeTileWidth += pcSlice->getSPS()->getColumnWidth(p);
652          }
653          pcPic->getPicSym()->getTComTile(j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p)->setTileWidth( pcPic->getPicSym()->getFrameWidthInCU()-uiCummulativeTileWidth );
654        }
655
656        //set the height for each tile
657        for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
658        {
659          uiCummulativeTileHeight = 0;
660          for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1(); p++)
661          {
662            pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->setTileHeight( pcSlice->getSPS()->getRowHeight(p) );
663            uiCummulativeTileHeight += pcSlice->getSPS()->getRowHeight(p);
664          }
665          pcPic->getPicSym()->getTComTile(p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j)->setTileHeight( pcPic->getPicSym()->getFrameHeightInCU()-uiCummulativeTileHeight );
666        }
667      }
668    }
669
670    //initialize each tile of the current picture
671    pcPic->getPicSym()->xInitTiles();
672
673    // Allocate some coders, now we know how many tiles there are.
674    Int iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
675   
676    //generate the Coding Order Map and Inverse Coding Order Map
677    for(p=0, uiEncCUAddr=0; p<pcPic->getPicSym()->getNumberOfCUsInFrame(); p++, uiEncCUAddr = pcPic->getPicSym()->xCalculateNxtCUAddr(uiEncCUAddr))
678    {
679      pcPic->getPicSym()->setCUOrderMap(p, uiEncCUAddr);
680      pcPic->getPicSym()->setInverseCUOrderMap(uiEncCUAddr, p);
681    }
682    pcPic->getPicSym()->setCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());   
683    pcPic->getPicSym()->setInverseCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());
684    if (pcSlice->getPPS()->getEntropyCodingMode())
685    {
686      // Allocate some coders, now we know how many tiles there are.
687      m_pcEncTop->createWPPCoders(iNumSubstreams);
688      pcSbacCoders = m_pcEncTop->getSbacCoders();
689      pcSubstreamsOut = new TComOutputBitstream[iNumSubstreams];
690    }
691
692      UInt uiStartCUAddrSliceIdx = 0; // used to index "m_uiStoredStartCUAddrForEncodingSlice" containing locations of slice boundaries
693      UInt uiStartCUAddrSlice    = 0; // used to keep track of current slice's starting CU addr.
694      pcSlice->setSliceCurStartCUAddr( uiStartCUAddrSlice ); // Setting "start CU addr" for current slice
695      memset(m_uiStoredStartCUAddrForEncodingSlice, 0, sizeof(UInt) * (pcPic->getPicSym()->getNumberOfCUsInFrame()*pcPic->getNumPartInCU()+1));
696
697      UInt uiStartCUAddrEntropySliceIdx = 0; // used to index "m_uiStoredStartCUAddrForEntropyEncodingSlice" containing locations of slice boundaries
698      UInt uiStartCUAddrEntropySlice    = 0; // used to keep track of current Entropy slice's starting CU addr.
699      pcSlice->setEntropySliceCurStartCUAddr( uiStartCUAddrEntropySlice ); // Setting "start CU addr" for current Entropy slice
700     
701      memset(m_uiStoredStartCUAddrForEncodingEntropySlice, 0, sizeof(UInt) * (pcPic->getPicSym()->getNumberOfCUsInFrame()*pcPic->getNumPartInCU()+1));
702      UInt uiNextCUAddr = 0;
703      m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx++]                = uiNextCUAddr;
704      m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx++]  = uiNextCUAddr;
705
706#if DEPTH_MAP_GENERATION
707      // init view component and predict virtual depth map
708      m_pcDepthMapGenerator->initViewComponent( pcPic );
709#if !QC_MULTI_DIS_CAN
710      m_pcDepthMapGenerator->predictDepthMap  ( pcPic );
711#endif
712#endif
713#if HHI_INTER_VIEW_MOTION_PRED
714      m_pcDepthMapGenerator->covertOrgDepthMap( pcPic );
715#endif
716#if HHI_INTER_VIEW_RESIDUAL_PRED
717      m_pcResidualGenerator->initViewComponent( pcPic );
718#endif
719
720      while(uiNextCUAddr<uiRealEndAddress) // determine slice boundaries
721      {
722        pcSlice->setNextSlice       ( false );
723        pcSlice->setNextEntropySlice( false );
724        assert(pcPic->getNumAllocatedSlice() == uiStartCUAddrSliceIdx);
725        m_pcSliceEncoder->precompressSlice( pcPic );
726        m_pcSliceEncoder->compressSlice   ( pcPic );
727
728        Bool bNoBinBitConstraintViolated = (!pcSlice->isNextSlice() && !pcSlice->isNextEntropySlice());
729        if (pcSlice->isNextSlice() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE))
730        {
731          uiStartCUAddrSlice                                              = pcSlice->getSliceCurEndCUAddr();
732          // Reconstruction slice
733          m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx++]  = uiStartCUAddrSlice;
734          // Entropy slice
735          if (uiStartCUAddrEntropySliceIdx>0 && m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx-1] != uiStartCUAddrSlice)
736          {
737            m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx++]  = uiStartCUAddrSlice;
738          }
739         
740          if (uiStartCUAddrSlice < uiRealEndAddress)
741          {
742            pcPic->allocateNewSlice();         
743            pcPic->setCurrSliceIdx                  ( uiStartCUAddrSliceIdx-1 );
744            m_pcSliceEncoder->setSliceIdx           ( uiStartCUAddrSliceIdx-1 );
745            pcSlice = pcPic->getSlice               ( uiStartCUAddrSliceIdx-1 );
746            pcSlice->copySliceInfo                  ( pcPic->getSlice(0)      );
747            pcSlice->setSliceIdx                    ( uiStartCUAddrSliceIdx-1 );
748            pcSlice->setSliceCurStartCUAddr         ( uiStartCUAddrSlice      );
749            pcSlice->setEntropySliceCurStartCUAddr  ( uiStartCUAddrSlice      );
750            pcSlice->setSliceBits(0);
751            uiNumSlices ++;
752          }
753        }
754        else if (pcSlice->isNextEntropySlice() || (bNoBinBitConstraintViolated && m_pcCfg->getEntropySliceMode()==SHARP_FIXED_NUMBER_OF_LCU_IN_ENTROPY_SLICE))
755        {
756          uiStartCUAddrEntropySlice                                                     = pcSlice->getEntropySliceCurEndCUAddr();
757          m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx++]  = uiStartCUAddrEntropySlice;
758          pcSlice->setEntropySliceCurStartCUAddr( uiStartCUAddrEntropySlice );
759        }
760        else
761        {
762          uiStartCUAddrSlice                                                            = pcSlice->getSliceCurEndCUAddr();
763          uiStartCUAddrEntropySlice                                                     = pcSlice->getEntropySliceCurEndCUAddr();
764        }       
765
766        uiNextCUAddr = (uiStartCUAddrSlice > uiStartCUAddrEntropySlice) ? uiStartCUAddrSlice : uiStartCUAddrEntropySlice;
767      }
768      m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx++]                = pcSlice->getSliceCurEndCUAddr();
769      m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx++]  = pcSlice->getSliceCurEndCUAddr();
770     
771      pcSlice = pcPic->getSlice(0);
772
773#if HHI_INTER_VIEW_RESIDUAL_PRED
774      // set residual picture
775      m_pcResidualGenerator->setRecResidualPic( pcPic );
776#endif
777#if DEPTH_MAP_GENERATION
778#if !QC_MULTI_DIS_CAN
779      // update virtual depth map
780      m_pcDepthMapGenerator->updateDepthMap( pcPic );
781#endif
782#endif
783
784      //-- Loop filter
785      Bool bLFCrossTileBoundary = (pcSlice->getPPS()->getTileBehaviorControlPresentFlag() == 1)?
786                                  (pcSlice->getPPS()->getLFCrossTileBoundaryFlag()):(pcSlice->getPPS()->getSPS()->getLFCrossTileBoundaryFlag());
787#if DBL_CONTROL
788      m_pcLoopFilter->setCfg(pcSlice->getPPS()->getDeblockingFilterControlPresent(), pcSlice->getLoopFilterDisable(), pcSlice->getLoopFilterBetaOffset(), pcSlice->getLoopFilterTcOffset(), bLFCrossTileBoundary);
789#else
790      m_pcLoopFilter->setCfg(pcSlice->getLoopFilterDisable(), pcSlice->getLoopFilterBetaOffset(), pcSlice->getLoopFilterTcOffset(), bLFCrossTileBoundary);
791#endif
792      m_pcLoopFilter->loopFilterPic( pcPic );
793
794      pcSlice = pcPic->getSlice(0);
795      if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
796      {
797        Int sliceGranularity = pcSlice->getPPS()->getSliceGranularity();
798        pcPic->createNonDBFilterInfo(m_uiStoredStartCUAddrForEncodingSlice, uiNumSlices, sliceGranularity, pcSlice->getSPS()->getLFCrossSliceBoundaryFlag(),pcPic->getPicSym()->getNumTiles() ,bLFCrossTileBoundary);
799      }
800
801
802      pcSlice = pcPic->getSlice(0);
803
804      if(pcSlice->getSPS()->getUseSAO())
805      {
806        m_pcSAO->createPicSaoInfo(pcPic, uiNumSlices);
807      }
808
809#if LCU_SYNTAX_ALF
810      AlfParamSet* alfSliceParams = NULL;
811      std::vector<AlfCUCtrlInfo>* alfCUCtrlParam = NULL;
812#else
813      std::vector<AlfCUCtrlInfo> vAlfCUCtrlParam;
814#endif
815      pcSlice = pcPic->getSlice(0);
816
817      if(pcSlice->getSPS()->getUseALF())
818      {
819#if LCU_SYNTAX_ALF
820        m_pcAdaptiveLoopFilter->createPicAlfInfo(pcPic, uiNumSlices, pcSlice->getSliceQp());
821        m_pcAdaptiveLoopFilter->initALFEnc(m_pcCfg->getALFParamInSlice(), m_pcCfg->getALFPicBasedEncode(), uiNumSlices, alfSliceParams, alfCUCtrlParam);
822#else
823        vAlfCUCtrlParam.resize(uiNumSlices);
824        m_pcAdaptiveLoopFilter->createPicAlfInfo(pcPic, uiNumSlices);
825#endif
826      }
827
828      /////////////////////////////////////////////////////////////////////////////////////////////////// File writing
829      // Set entropy coder
830      m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
831
832      /* write various header sets. */
833      if ( m_bSeqFirst )
834      {
835#if VIDYO_VPS_INTEGRATION
836        {
837          OutputNALUnit nalu(NAL_UNIT_VPS, true, m_pcEncTop->getLayerId());
838          m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
839          m_pcEntropyCoder->encodeVPS(m_pcEncTop->getEncTop()->getVPS());
840          writeRBSPTrailingBits(nalu.m_Bitstream);
841          accessUnit.push_back(new NALUnitEBSP(nalu));
842        }
843#endif
844#if NAL_REF_FLAG
845#if VIDYO_VPS_INTEGRATION
846        OutputNALUnit nalu(NAL_UNIT_SPS, true, m_pcEncTop->getLayerId());
847#else
848        OutputNALUnit nalu(NAL_UNIT_SPS, true, m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth());
849#endif
850#else
851        OutputNALUnit nalu(NAL_UNIT_SPS, NAL_REF_IDC_PRIORITY_HIGHEST, m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth());
852#endif
853        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
854#if TILES_WPP_ENTRY_POINT_SIGNALLING
855        pcSlice->getSPS()->setNumSubstreams( pcSlice->getPPS()->getNumSubstreams() );
856#endif
857#if HHI_MPI
858        m_pcEntropyCoder->encodeSPS(pcSlice->getSPS(), m_pcEncTop->getIsDepth());
859#else
860        m_pcEntropyCoder->encodeSPS(pcSlice->getSPS());
861#endif
862        writeRBSPTrailingBits(nalu.m_Bitstream);
863        accessUnit.push_back(new NALUnitEBSP(nalu));
864
865#if NAL_REF_FLAG
866#if VIDYO_VPS_INTEGRATION
867        nalu = NALUnit(NAL_UNIT_PPS, true, m_pcEncTop->getLayerId());
868#else
869        nalu = NALUnit(NAL_UNIT_PPS, true, m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth());
870#endif
871#else
872        nalu = NALUnit(NAL_UNIT_PPS, NAL_REF_IDC_PRIORITY_HIGHEST, m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth());
873#endif
874        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
875        m_pcEntropyCoder->encodePPS(pcSlice->getPPS());
876        writeRBSPTrailingBits(nalu.m_Bitstream);
877        accessUnit.push_back(new NALUnitEBSP(nalu));
878
879        m_bSeqFirst = false;
880      }
881
882      /* use the main bitstream buffer for storing the marshalled picture */
883      m_pcEntropyCoder->setBitstream(NULL);
884
885      uiStartCUAddrSliceIdx = 0;
886      uiStartCUAddrSlice    = 0; 
887
888      uiStartCUAddrEntropySliceIdx = 0;
889      uiStartCUAddrEntropySlice    = 0; 
890      uiNextCUAddr                 = 0;
891      pcSlice = pcPic->getSlice(uiStartCUAddrSliceIdx);
892
893      Int processingState = (pcSlice->getSPS()->getUseALF() || pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getScalingListFlag() || pcSlice->getSPS()->getUseDF())?(EXECUTE_INLOOPFILTER):(ENCODE_SLICE);
894
895      static Int iCurrAPSIdx = 0;
896      Int iCodedAPSIdx = 0;
897      TComSlice* pcSliceForAPS = NULL;
898
899      bool skippedSlice=false;
900      while (uiNextCUAddr < uiRealEndAddress) // Iterate over all slices
901      {
902        switch(processingState)
903        {
904        case ENCODE_SLICE:
905          {
906        pcSlice->setNextSlice       ( false );
907        pcSlice->setNextEntropySlice( false );
908        if (uiNextCUAddr == m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx])
909        {
910          pcSlice = pcPic->getSlice(uiStartCUAddrSliceIdx);
911#if COLLOCATED_REF_IDX
912          if(uiStartCUAddrSliceIdx > 0 && pcSlice->getSliceType()!= I_SLICE)
913          {
914            pcSlice->checkColRefIdx(uiStartCUAddrSliceIdx, pcPic);
915          }
916#endif
917          pcPic->setCurrSliceIdx(uiStartCUAddrSliceIdx);
918          m_pcSliceEncoder->setSliceIdx(uiStartCUAddrSliceIdx);
919          assert(uiStartCUAddrSliceIdx == pcSlice->getSliceIdx());
920          // Reconstruction slice
921          pcSlice->setSliceCurStartCUAddr( uiNextCUAddr );  // to be used in encodeSlice() + context restriction
922          pcSlice->setSliceCurEndCUAddr  ( m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx+1 ] );
923          // Entropy slice
924          pcSlice->setEntropySliceCurStartCUAddr( uiNextCUAddr );  // to be used in encodeSlice() + context restriction
925          pcSlice->setEntropySliceCurEndCUAddr  ( m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx+1 ] );
926
927          pcSlice->setNextSlice       ( true );
928
929          uiStartCUAddrSliceIdx++;
930          uiStartCUAddrEntropySliceIdx++;
931        } 
932        else if (uiNextCUAddr == m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx])
933        {
934          // Entropy slice
935          pcSlice->setEntropySliceCurStartCUAddr( uiNextCUAddr );  // to be used in encodeSlice() + context restriction
936          pcSlice->setEntropySliceCurEndCUAddr  ( m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx+1 ] );
937
938          pcSlice->setNextEntropySlice( true );
939
940          uiStartCUAddrEntropySliceIdx++;
941        }
942
943      pcSlice->setRPS(pcPic->getSlice(0)->getRPS());
944      pcSlice->setRPSidx(pcPic->getSlice(0)->getRPSidx());
945        UInt uiDummyStartCUAddr;
946        UInt uiDummyBoundingCUAddr;
947        m_pcSliceEncoder->xDetermineStartAndBoundingCUAddr(uiDummyStartCUAddr,uiDummyBoundingCUAddr,pcPic,true);
948
949        uiInternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getEntropySliceCurEndCUAddr()-1) % pcPic->getNumPartInCU();
950        uiExternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getEntropySliceCurEndCUAddr()-1) / pcPic->getNumPartInCU();
951        uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
952        uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
953        uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
954        uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
955        while(uiPosX>=uiWidth||uiPosY>=uiHeight)
956        {
957          uiInternalAddress--;
958          uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
959          uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
960        }
961        uiInternalAddress++;
962        if(uiInternalAddress==pcPic->getNumPartInCU())
963        {
964          uiInternalAddress = 0;
965          uiExternalAddress = pcPic->getPicSym()->getCUOrderMap(pcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
966        }
967        UInt uiEndAddress = pcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress);
968        if(uiEndAddress<=pcSlice->getEntropySliceCurStartCUAddr()) {
969          UInt uiBoundingAddrSlice, uiBoundingAddrEntropySlice;
970          uiBoundingAddrSlice        = m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx];         
971          uiBoundingAddrEntropySlice = m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx];         
972          uiNextCUAddr               = min(uiBoundingAddrSlice, uiBoundingAddrEntropySlice);
973          if(pcSlice->isNextSlice())
974          {
975            skippedSlice=true;
976          }
977          continue;
978        }
979        if(skippedSlice) 
980        {
981          pcSlice->setNextSlice       ( true );
982          pcSlice->setNextEntropySlice( false );
983        }
984        skippedSlice=false;
985        if (pcSlice->getPPS()->getEntropyCodingMode())
986        {
987          pcSlice->allocSubstreamSizes( iNumSubstreams );
988          for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
989          pcSubstreamsOut[ui].clear();
990        }
991
992        m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
993        m_pcEntropyCoder->resetEntropy      ();
994        /* start slice NALunit */
995#if H0388
996#if NAL_REF_FLAG
997        OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->isReferenced(),
998#if !VIDYO_VPS_INTEGRATION
999                           m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth(), pcSlice->getTLayer() );
1000#else
1001                           m_pcEncTop->getLayerId(), pcSlice->getTLayer() );
1002#endif
1003#else
1004        OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->isReferenced() ? NAL_REF_IDC_PRIORITY_HIGHEST: NAL_REF_IDC_PRIORITY_LOWEST, 
1005#if !VIDYO_VPS_INTEGRATION
1006                           m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth(), pcSlice->getTLayer() );
1007#else
1008                           m_pcEncTop->getLayerId(), pcSlice->getTLayer() );
1009#endif
1010#endif
1011#else
1012        OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->isReferenced() ? NAL_REF_IDC_PRIORITY_HIGHEST: NAL_REF_IDC_PRIORITY_LOWEST, 
1013#if !VIDYO_VPS_INTEGRATION
1014                           m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth(), pcSlice->getTLayer(), true );
1015#else
1016                           m_pcEncTop->getLayerId(), pcSlice->getTLayer(), true );
1017#endif
1018
1019#endif
1020           
1021        Bool bEntropySlice = (!pcSlice->isNextSlice());
1022        if (!bEntropySlice)
1023        {
1024          uiOneBitstreamPerSliceLength = 0; // start of a new slice
1025        }
1026
1027        // used while writing slice header
1028        Int iTransmitLWHeader = (m_pcCfg->getTileMarkerFlag()==0) ? 0 : 1;
1029        pcSlice->setTileMarkerFlag ( iTransmitLWHeader );
1030        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1031#if !CABAC_INIT_FLAG
1032        pcSlice->setCABACinitIDC(pcSlice->getSliceType());
1033#endif
1034
1035        m_pcEntropyCoder->encodeSliceHeader(pcSlice);
1036
1037        if(pcSlice->isNextSlice())
1038        {
1039          if (pcSlice->getSPS()->getUseALF())
1040          {
1041#if LCU_SYNTAX_ALF
1042            if(pcSlice->getAlfEnabledFlag())
1043#else
1044            if(pcSlice->getAPS()->getAlfEnabled())
1045#endif
1046            {
1047
1048#if LCU_SYNTAX_ALF
1049              if( pcSlice->getSPS()->getUseALFCoefInSlice())
1050              {
1051                Int iNumSUinLCU    = 1<< (g_uiMaxCUDepth << 1); 
1052                Int firstLCUAddr   = pcSlice->getSliceCurStartCUAddr() / iNumSUinLCU; 
1053                Bool isAcrossSlice = pcSlice->getSPS()->getLFCrossSliceBoundaryFlag();
1054                m_pcEntropyCoder->encodeAlfParam( &(alfSliceParams[pcSlice->getSliceIdx()]), false, firstLCUAddr, isAcrossSlice);
1055              }
1056
1057              if( !pcSlice->getSPS()->getUseALFCoefInSlice())
1058              {
1059                AlfCUCtrlInfo& cAlfCUCtrlParam = (*alfCUCtrlParam)[pcSlice->getSliceIdx()];
1060#else
1061              AlfCUCtrlInfo& cAlfCUCtrlParam = vAlfCUCtrlParam[pcSlice->getSliceIdx()];
1062#endif
1063              if(cAlfCUCtrlParam.cu_control_flag)
1064              {
1065                m_pcEntropyCoder->setAlfCtrl( true );
1066                m_pcEntropyCoder->setMaxAlfCtrlDepth(cAlfCUCtrlParam.alf_max_depth);
1067                m_pcCavlcCoder->setAlfCtrl(true);
1068                m_pcCavlcCoder->setMaxAlfCtrlDepth(cAlfCUCtrlParam.alf_max_depth); 
1069              }
1070              else
1071              {
1072                m_pcEntropyCoder->setAlfCtrl(false);
1073              }
1074              m_pcEntropyCoder->encodeAlfCtrlParam(cAlfCUCtrlParam, m_pcAdaptiveLoopFilter->getNumCUsInPic());
1075           
1076#if LCU_SYNTAX_ALF
1077              }
1078#endif           
1079            }
1080          }
1081        }
1082        m_pcEntropyCoder->encodeTileMarkerFlag(pcSlice);
1083
1084        // is it needed?
1085        {
1086          if (!bEntropySlice)
1087          {
1088            pcBitstreamRedirect->writeAlignOne();
1089          }
1090          else
1091          {
1092          // We've not completed our slice header info yet, do the alignment later.
1093          }
1094          m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
1095          m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
1096          m_pcEntropyCoder->resetEntropy    ();
1097          for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams() ; ui++ )
1098          {
1099            m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[ui], pcSlice );
1100            m_pcEntropyCoder->resetEntropy    ();
1101          }
1102        }
1103
1104        if(pcSlice->isNextSlice())
1105        {
1106          // set entropy coder for writing
1107          m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
1108          {
1109            for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams() ; ui++ )
1110            {
1111              m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[ui], pcSlice );
1112              m_pcEntropyCoder->resetEntropy    ();
1113            }
1114            pcSbacCoders[0].load(m_pcSbacCoder);
1115            m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[0], pcSlice );  //ALF is written in substream #0 with CABAC coder #0 (see ALF param encoding below)
1116          }
1117          m_pcEntropyCoder->resetEntropy    ();
1118          // File writing
1119          if (!bEntropySlice)
1120          {
1121            m_pcEntropyCoder->setBitstream(pcBitstreamRedirect);
1122          }
1123          else
1124          {
1125            m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1126          }
1127          // for now, override the TILES_DECODER setting in order to write substreams.
1128            m_pcEntropyCoder->setBitstream    ( &pcSubstreamsOut[0] );
1129
1130        }
1131        pcSlice->setFinalized(true);
1132
1133          m_pcSbacCoder->load( &pcSbacCoders[0] );
1134
1135        pcSlice->setTileOffstForMultES( uiOneBitstreamPerSliceLength );
1136        if (!bEntropySlice)
1137        {
1138          pcSlice->setTileLocationCount ( 0 );
1139          m_pcSliceEncoder->encodeSlice(pcPic, pcBitstreamRedirect, pcSubstreamsOut); // redirect is only used for CAVLC tile position info.
1140        }
1141        else
1142        {
1143          m_pcSliceEncoder->encodeSlice(pcPic, &nalu.m_Bitstream, pcSubstreamsOut); // nalu.m_Bitstream is only used for CAVLC tile position info.
1144        }
1145
1146        {
1147          // Construct the final bitstream by flushing and concatenating substreams.
1148          // The final bitstream is either nalu.m_Bitstream or pcBitstreamRedirect;
1149          UInt* puiSubstreamSizes = pcSlice->getSubstreamSizes();
1150          UInt uiTotalCodedSize = 0; // for padding calcs.
1151          UInt uiNumSubstreamsPerTile = iNumSubstreams;
1152#if !REMOVE_TILE_DEPENDENCE
1153#if WPP_SIMPLIFICATION
1154         if (pcPic->getPicSym()->getTileBoundaryIndependenceIdr() && iNumSubstreams > 1)
1155#else
1156          if (pcPic->getPicSym()->getTileBoundaryIndependenceIdr() && pcSlice->getPPS()->getEntropyCodingSynchro())
1157#endif
1158            uiNumSubstreamsPerTile /= pcPic->getPicSym()->getNumTiles();
1159#else
1160#if WPP_SIMPLIFICATION
1161          if (iNumSubstreams > 1)
1162#else
1163          if (pcSlice->getPPS()->getEntropyCodingSynchro())
1164#endif
1165          {
1166            uiNumSubstreamsPerTile /= pcPic->getPicSym()->getNumTiles();
1167          }
1168#endif
1169          for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
1170          {
1171            // Flush all substreams -- this includes empty ones.
1172            // Terminating bit and flush.
1173            m_pcEntropyCoder->setEntropyCoder   ( &pcSbacCoders[ui], pcSlice );
1174            m_pcEntropyCoder->setBitstream      (  &pcSubstreamsOut[ui] );
1175            m_pcEntropyCoder->encodeTerminatingBit( 1 );
1176            m_pcEntropyCoder->encodeSliceFinish();
1177            pcSubstreamsOut[ui].write( 1, 1 ); // stop bit.
1178#if TILES_WPP_ENTRY_POINT_SIGNALLING
1179            pcSubstreamsOut[ui].writeAlignZero();
1180#endif
1181            // Byte alignment is necessary between tiles when tiles are independent.
1182            uiTotalCodedSize += pcSubstreamsOut[ui].getNumberOfWrittenBits();
1183
1184            {
1185              Bool bNextSubstreamInNewTile = ((ui+1) < iNumSubstreams)
1186                                             && ((ui+1)%uiNumSubstreamsPerTile == 0);
1187              if (bNextSubstreamInNewTile)
1188              {
1189                // byte align.
1190                while (uiTotalCodedSize&0x7)
1191                {
1192                  pcSubstreamsOut[ui].write(0, 1);
1193                  uiTotalCodedSize++;
1194                }
1195              }
1196              Bool bRecordOffsetNext = m_pcCfg->getTileLocationInSliceHeaderFlag()
1197                                            && bNextSubstreamInNewTile;
1198              if (bRecordOffsetNext)
1199                pcSlice->setTileLocation(ui/uiNumSubstreamsPerTile, pcSlice->getTileOffstForMultES()+(uiTotalCodedSize>>3));
1200            }
1201            if (ui+1 < pcSlice->getPPS()->getNumSubstreams())
1202              puiSubstreamSizes[ui] = pcSubstreamsOut[ui].getNumberOfWrittenBits();
1203          }
1204          // Complete the slice header info.
1205          m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
1206          m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1207#if TILES_WPP_ENTRY_POINT_SIGNALLING
1208          if (m_pcCfg->getTileLocationInSliceHeaderFlag()==0) 
1209          {
1210            pcSlice->setTileLocationCount( 0 );
1211          }
1212          m_pcEntropyCoder->encodeTilesWPPEntryPoint( pcSlice );
1213#else
1214          m_pcEntropyCoder->encodeSliceHeaderSubstreamTable(pcSlice);
1215#endif
1216          // Substreams...
1217          TComOutputBitstream *pcOut = pcBitstreamRedirect;
1218          // xWriteTileLocation will perform byte-alignment...
1219          {
1220            if (bEntropySlice)
1221            {
1222              // In these cases, padding is necessary here.
1223              pcOut = &nalu.m_Bitstream;
1224              pcOut->writeAlignOne();
1225            }
1226          }
1227          UInt uiAccumulatedLength = 0;
1228          for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams(); ui++ )
1229          {
1230            pcOut->addSubstream(&pcSubstreamsOut[ui]);
1231
1232            // Update tile marker location information
1233            for (Int uiMrkIdx = 0; uiMrkIdx < pcSubstreamsOut[ui].getTileMarkerLocationCount(); uiMrkIdx++)
1234            {
1235              UInt uiBottom = pcOut->getTileMarkerLocationCount();
1236              pcOut->setTileMarkerLocation      ( uiBottom, uiAccumulatedLength + pcSubstreamsOut[ui].getTileMarkerLocation( uiMrkIdx ) );
1237              pcOut->setTileMarkerLocationCount ( uiBottom + 1 );
1238            }
1239            uiAccumulatedLength = (pcOut->getNumberOfWrittenBits() >> 3);
1240          }
1241        }
1242
1243        UInt uiBoundingAddrSlice, uiBoundingAddrEntropySlice;
1244        uiBoundingAddrSlice        = m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx];         
1245        uiBoundingAddrEntropySlice = m_uiStoredStartCUAddrForEncodingEntropySlice[uiStartCUAddrEntropySliceIdx];         
1246        uiNextCUAddr               = min(uiBoundingAddrSlice, uiBoundingAddrEntropySlice);
1247#if !REMOVE_TILE_DEPENDENCE
1248        Bool bNextCUInNewSlice     = (uiNextCUAddr >= uiRealEndAddress) || (uiNextCUAddr == m_uiStoredStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx]);
1249#endif
1250        // If current NALU is the first NALU of slice (containing slice header) and more NALUs exist (due to multiple entropy slices) then buffer it.
1251        // If current NALU is the last NALU of slice and a NALU was buffered, then (a) Write current NALU (b) Update an write buffered NALU at approproate location in NALU list.
1252        Bool bNALUAlignedWrittenToList    = false; // used to ensure current NALU is not written more than once to the NALU list.
1253#if !REMOVE_TILE_DEPENDENCE
1254        if (pcSlice->getSPS()->getTileBoundaryIndependenceIdr() && !pcSlice->getSPS()->getTileBoundaryIndependenceIdr())
1255        {
1256          if (bNextCUInNewSlice)
1257          {
1258            if (!bEntropySlice) // there were no entropy slices
1259            {
1260              xWriteTileLocationToSliceHeader(nalu, pcBitstreamRedirect, pcSlice);
1261            }
1262            // (a) writing current NALU
1263            writeRBSPTrailingBits(nalu.m_Bitstream);
1264            accessUnit.push_back(new NALUnitEBSP(nalu));
1265            bNALUAlignedWrittenToList = true;
1266
1267            // (b) update and write buffered NALU
1268            if (bEntropySlice) // if entropy slices existed in the slice then perform concatenation for the buffered nalu-bitstream and buffered payload bitstream
1269            {
1270              // Perform bitstream concatenation of slice header and partial slice payload
1271              xWriteTileLocationToSliceHeader((*naluBuffered), pcBitstreamRedirect, pcSlice);
1272              if (bIteratorAtListStart)
1273              {
1274                itLocationToPushSliceHeaderNALU = accessUnit.begin();
1275              }
1276              else
1277              {
1278                itLocationToPushSliceHeaderNALU++;
1279              }
1280              accessUnit.insert(itLocationToPushSliceHeaderNALU, (new NALUnitEBSP((*naluBuffered))) );
1281
1282              // free buffered nalu
1283              delete naluBuffered;
1284              naluBuffered     = NULL;
1285            }
1286          }
1287          else // another entropy slice exists
1288          {
1289            // Is this start-of-slice NALU? i.e. the one containing slice header. If Yes, then buffer it.
1290            if (!bEntropySlice)
1291            {
1292              // store a pointer to where NALU for slice header is to be written in NALU list
1293              itLocationToPushSliceHeaderNALU = accessUnit.end();
1294              if (accessUnit.begin() == accessUnit.end())
1295              {
1296                bIteratorAtListStart = true;
1297              }
1298              else
1299              {
1300                bIteratorAtListStart = false;
1301                itLocationToPushSliceHeaderNALU--;
1302              }
1303
1304              // buffer nalu for later writing
1305#if H0388
1306              naluBuffered = new OutputNALUnit( pcSlice->getNalUnitType(), pcSlice->isReferenced() ? NAL_REF_IDC_PRIORITY_HIGHEST: NAL_REF_IDC_PRIORITY_LOWEST, m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth(), pcSlice->getTLayer() );
1307#else
1308              naluBuffered = new OutputNALUnit(pcSlice->getNalUnitType(), pcSlice->isReferenced() ? NAL_REF_IDC_PRIORITY_HIGHEST: NAL_REF_IDC_PRIORITY_LOWEST, m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth(), pcSlice->getTLayer(), true);
1309#endif
1310              copyNaluData( (*naluBuffered), nalu );
1311
1312              // perform byte-alignment to get appropriate bitstream length (used for explicit tile location signaling in slice header)
1313              writeRBSPTrailingBits((*pcBitstreamRedirect));
1314              bNALUAlignedWrittenToList = true; // This is not really a write to bitsream but buffered for later. The flag is set to prevent writing of current NALU to list.
1315              uiOneBitstreamPerSliceLength += pcBitstreamRedirect->getNumberOfWrittenBits(); // length of bitstream after byte-alignment
1316            }
1317            else // write out entropy slice
1318            {
1319              writeRBSPTrailingBits(nalu.m_Bitstream);
1320              accessUnit.push_back(new NALUnitEBSP(nalu));
1321              bNALUAlignedWrittenToList = true; 
1322              uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits(); // length of bitstream after byte-alignment
1323            }
1324          }
1325        }
1326        else
1327        {
1328#endif
1329        xWriteTileLocationToSliceHeader(nalu, pcBitstreamRedirect, pcSlice);
1330        writeRBSPTrailingBits(nalu.m_Bitstream);
1331        accessUnit.push_back(new NALUnitEBSP(nalu));
1332        bNALUAlignedWrittenToList = true; 
1333        uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits(); // length of bitstream after byte-alignment
1334#if !REMOVE_TILE_DEPENDENCE
1335        }
1336#endif
1337
1338        if (!bNALUAlignedWrittenToList)
1339        {
1340        {
1341          nalu.m_Bitstream.writeAlignZero();
1342        }
1343        accessUnit.push_back(new NALUnitEBSP(nalu));
1344        uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits() + 24; // length of bitstream after byte-alignment + 3 byte startcode 0x000001
1345        }
1346
1347
1348        processingState = ENCODE_SLICE;
1349          }
1350          break;
1351        case EXECUTE_INLOOPFILTER:
1352          {
1353            TComAPS cAPS;
1354            allocAPS(&cAPS, pcSlice->getSPS());
1355#if SAO_UNIT_INTERLEAVING
1356            cAPS.setSaoInterleavingFlag(m_pcCfg->getSaoInterleavingFlag());
1357#endif
1358            // set entropy coder for RD
1359            m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
1360
1361            if ( pcSlice->getSPS()->getUseSAO() )
1362            {
1363              m_pcEntropyCoder->resetEntropy();
1364              m_pcEntropyCoder->setBitstream( m_pcBitCounter );
1365              m_pcSAO->startSaoEnc(pcPic, m_pcEntropyCoder, m_pcEncTop->getRDSbacCoder(), NULL);
1366              SAOParam& cSaoParam = *(cAPS.getSaoParam());
1367
1368#if SAO_CHROMA_LAMBDA
1369              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma());
1370#else
1371#if ALF_CHROMA_LAMBDA
1372              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma());
1373#else
1374              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambda());
1375#endif
1376#endif
1377              m_pcSAO->endSaoEnc();
1378
1379              m_pcAdaptiveLoopFilter->PCMLFDisableProcess(pcPic);
1380            }
1381
1382            // adaptive loop filter
1383#if !LCU_SYNTAX_ALF
1384            UInt64 uiDist, uiBits;
1385#endif
1386            if ( pcSlice->getSPS()->getUseALF())
1387            {
1388              m_pcEntropyCoder->resetEntropy    ();
1389              m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
1390              m_pcAdaptiveLoopFilter->startALFEnc(pcPic, m_pcEntropyCoder );
1391#if LCU_SYNTAX_ALF
1392              AlfParamSet* pAlfEncParam = (pcSlice->getSPS()->getUseALFCoefInSlice())?( alfSliceParams ):( cAPS.getAlfParam());
1393#if ALF_CHROMA_LAMBDA
1394#if HHI_INTERVIEW_SKIP
1395              m_pcAdaptiveLoopFilter->ALFProcess(pAlfEncParam, alfCUCtrlParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma(), m_pcEncTop->getInterViewSkip()  );
1396#else
1397              m_pcAdaptiveLoopFilter->ALFProcess(pAlfEncParam, alfCUCtrlParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma() );
1398#endif
1399#else
1400#if SAO_CHROMA_LAMBDA
1401#if HHI_INTERVIEW_SKIP
1402              m_pcAdaptiveLoopFilter->ALFProcess(pAlfEncParam, alfCUCtrlParam, pcPic->getSlice(0)->getLambdaLuma(), m_pcEncTop->getInterViewSkip());
1403#else
1404              m_pcAdaptiveLoopFilter->ALFProcess(pAlfEncParam, alfCUCtrlParam, pcPic->getSlice(0)->getLambdaLuma());
1405#endif
1406#else
1407#if HHI_INTERVIEW_SKIP
1408              m_pcAdaptiveLoopFilter->ALFProcess(pAlfEncParam, alfCUCtrlParam, pcPic->getSlice(0)->getLambda(), m_pcEncTop->getInterViewSkip() );
1409#else
1410              m_pcAdaptiveLoopFilter->ALFProcess(pAlfEncParam, alfCUCtrlParam, pcPic->getSlice(0)->getLambda());
1411#endif
1412#endif
1413#endif
1414
1415#else
1416              ALFParam& cAlfParam = *( cAPS.getAlfParam());
1417
1418#if ALF_CHROMA_LAMBDA
1419#if HHI_INTERVIEW_SKIP
1420              m_pcAdaptiveLoopFilter->ALFProcess( &cAlfParam, &vAlfCUCtrlParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma(), uiDist, uiBits, m_pcEncTop->getInterViewSkip());
1421#else
1422              m_pcAdaptiveLoopFilter->ALFProcess( &cAlfParam, &vAlfCUCtrlParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma(), uiDist, uiBits);
1423#endif
1424#else
1425#if SAO_CHROMA_LAMBDA
1426#if HHI_INTERVIEW_SKIP
1427              m_pcAdaptiveLoopFilter->ALFProcess( &cAlfParam, &vAlfCUCtrlParam, pcPic->getSlice(0)->getLambdaLuma(), uiDist, uiBits, m_pcEncTop->getInterViewSkip());
1428#else
1429              m_pcAdaptiveLoopFilter->ALFProcess( &cAlfParam, &vAlfCUCtrlParam, pcPic->getSlice(0)->getLambdaLuma(), uiDist, uiBits);
1430#endif
1431#else
1432#if HHI_INTERVIEW_SKIP
1433              m_pcAdaptiveLoopFilter->ALFProcess( &cAlfParam, &vAlfCUCtrlParam, pcPic->getSlice(0)->getLambdaLuma(), uiDist, uiBits, m_pcEncTop->getInterViewSkip());
1434#else
1435              m_pcAdaptiveLoopFilter->ALFProcess( &cAlfParam, &vAlfCUCtrlParam, pcPic->getSlice(0)->getLambda(), uiDist, uiBits);
1436#endif
1437#endif
1438#endif
1439#endif
1440              m_pcAdaptiveLoopFilter->endALFEnc();
1441
1442              m_pcAdaptiveLoopFilter->PCMLFDisableProcess(pcPic);
1443            }
1444            iCodedAPSIdx = iCurrAPSIdx; 
1445            pcSliceForAPS = pcSlice;
1446
1447            assignNewAPS(cAPS, iCodedAPSIdx, vAPS, pcSliceForAPS);
1448            iCurrAPSIdx = (iCurrAPSIdx +1)%MAX_NUM_SUPPORTED_APS;
1449            processingState = ENCODE_APS;
1450
1451            //set APS link to the slices
1452            for(Int s=0; s< uiNumSlices; s++)
1453            {
1454              if (pcSlice->getSPS()->getUseALF())
1455              {
1456#if LCU_SYNTAX_ALF
1457                pcPic->getSlice(s)->setAlfEnabledFlag(  (pcSlice->getSPS()->getUseALFCoefInSlice())?(alfSliceParams[s].isEnabled[ALF_Y]):(cAPS.getAlfEnabled())   );
1458#else
1459                pcPic->getSlice(s)->setAlfEnabledFlag((cAPS.getAlfParam()->alf_flag==1)?true:false);
1460#endif
1461              }
1462              if (pcSlice->getSPS()->getUseSAO())
1463              {
1464                pcPic->getSlice(s)->setSaoEnabledFlag((cAPS.getSaoParam()->bSaoFlag[0]==1)?true:false);
1465              }
1466              pcPic->getSlice(s)->setAPS(&(vAPS[iCodedAPSIdx]));
1467              pcPic->getSlice(s)->setAPSId(iCodedAPSIdx);
1468            }
1469          }
1470          break;
1471        case ENCODE_APS:
1472          {
1473#if NAL_REF_FLAG
1474#if VIDYO_VPS_INTEGRATION
1475            OutputNALUnit nalu(NAL_UNIT_APS, true, m_pcEncTop->getLayerId());
1476#else
1477            OutputNALUnit nalu(NAL_UNIT_APS, true, m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth());
1478#endif
1479#else
1480            OutputNALUnit nalu(NAL_UNIT_APS, NAL_REF_IDC_PRIORITY_HIGHEST, m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth());
1481#endif
1482            encodeAPS(&(vAPS[iCodedAPSIdx]), nalu.m_Bitstream, pcSliceForAPS);
1483            accessUnit.push_back(new NALUnitEBSP(nalu));
1484
1485            processingState = ENCODE_SLICE;
1486          }
1487          break;
1488        default:
1489          {
1490            printf("Not a supported encoding state\n");
1491            assert(0);
1492            exit(-1);
1493          }
1494        }
1495      } // end iteration over slices
1496
1497
1498      if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
1499      {
1500        if(pcSlice->getSPS()->getUseSAO())
1501        {
1502          m_pcSAO->destroyPicSaoInfo();
1503        }
1504
1505        if(pcSlice->getSPS()->getUseALF())
1506        {
1507#if LCU_SYNTAX_ALF
1508          m_pcAdaptiveLoopFilter->uninitALFEnc(alfSliceParams, alfCUCtrlParam);
1509#endif
1510          m_pcAdaptiveLoopFilter->destroyPicAlfInfo();
1511        }
1512
1513        pcPic->destroyNonDBFilterInfo();
1514      }
1515
1516#if HHI_INTERVIEW_SKIP
1517      if (pcPic->getUsedPelsMap())
1518        pcPic->removeUsedPelsMapBuffer() ;
1519#endif
1520#if HHI_INTER_VIEW_MOTION_PRED
1521      pcPic->removeOrgDepthMapBuffer();
1522#endif
1523   
1524   //   pcPic->compressMotion();
1525      m_pocLastCoded = pcPic->getPOC();
1526     
1527      //-- For time output for each slice
1528      Double dEncTime = (double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
1529
1530      const char* digestStr = NULL;
1531      if (m_pcCfg->getPictureDigestEnabled())
1532      {
1533        /* calculate MD5sum for entire reconstructed picture */
1534        SEIpictureDigest sei_recon_picture_digest;
1535        sei_recon_picture_digest.method = SEIpictureDigest::MD5;
1536        calcMD5(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
1537        digestStr = digestToString(sei_recon_picture_digest.digest);
1538
1539#if NAL_REF_FLAG
1540#if VIDYO_VPS_INTEGRATION
1541        OutputNALUnit nalu(NAL_UNIT_SEI, false, m_pcEncTop->getLayerId());
1542#else
1543        OutputNALUnit nalu(NAL_UNIT_SEI, false, m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth());
1544#endif
1545#else
1546        OutputNALUnit nalu(NAL_UNIT_SEI, NAL_REF_IDC_PRIORITY_LOWEST, m_pcEncTop->getViewId(), m_pcEncTop->getIsDepth());
1547#endif
1548
1549        /* write the SEI messages */
1550        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1551        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1552        m_pcEntropyCoder->encodeSEI(sei_recon_picture_digest);
1553        writeRBSPTrailingBits(nalu.m_Bitstream);
1554
1555        /* insert the SEI message NALUnit before any Slice NALUnits */
1556        AccessUnit::iterator it = find_if(accessUnit.begin(), accessUnit.end(), mem_fun(&NALUnit::isSlice));
1557        accessUnit.insert(it, new NALUnitEBSP(nalu));
1558      }
1559
1560      xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), accessUnit, dEncTime );
1561      if (digestStr)
1562        printf(" [MD5:%s]", digestStr);
1563
1564#if FIXED_ROUNDING_FRAME_MEMORY
1565      /* TODO: this should happen after copyToPic(pcPicYuvRecOut) */
1566      pcPic->getPicYuvRec()->xFixedRoundingPic();
1567#endif
1568      pcPic->getPicYuvRec()->copyToPic(pcPicYuvRecOut);
1569     
1570      pcPic->setReconMark   ( true );
1571
1572      pcPic->setUsedForTMVP ( true );
1573
1574      m_bFirst = false;
1575      m_iNumPicCoded++;
1576
1577      /* logging: insert a newline at end of picture period */
1578      printf("\n");
1579      fflush(stdout);
1580  }
1581 
1582  delete[] pcSubstreamsOut;
1583  delete pcBitstreamRedirect;
1584
1585}
1586
1587/** Memory allocation for APS
1588  * \param [out] pAPS APS pointer
1589  * \param [in] pSPS SPS pointer
1590  */
1591Void TEncGOP::allocAPS (TComAPS* pAPS, TComSPS* pSPS)
1592{
1593  if(pSPS->getUseSAO())
1594  {
1595    pAPS->createSaoParam();
1596    m_pcSAO->allocSaoParam(pAPS->getSaoParam());
1597  }
1598  if(pSPS->getUseALF())
1599  {
1600    pAPS->createAlfParam();
1601#if LCU_SYNTAX_ALF
1602    //alf Enabled flag in APS is false after pAPS->createAlfParam();
1603    if(!pSPS->getUseALFCoefInSlice())
1604    {
1605      pAPS->getAlfParam()->create(m_pcAdaptiveLoopFilter->getNumLCUInPicWidth(), m_pcAdaptiveLoopFilter->getNumLCUInPicHeight(), m_pcAdaptiveLoopFilter->getNumCUsInPic());
1606      pAPS->getAlfParam()->createALFParam();
1607    }
1608#else
1609    m_pcAdaptiveLoopFilter->allocALFParam(pAPS->getAlfParam());
1610#endif
1611  }
1612}
1613
1614/** Memory deallocation for APS
1615  * \param [out] pAPS APS pointer
1616  * \param [in] pSPS SPS pointer
1617  */
1618Void TEncGOP::freeAPS (TComAPS* pAPS, TComSPS* pSPS)
1619{
1620  if(pSPS->getUseSAO())
1621  {
1622    if(pAPS->getSaoParam() != NULL)
1623    {
1624      m_pcSAO->freeSaoParam(pAPS->getSaoParam());
1625      pAPS->destroySaoParam();
1626
1627    }
1628  }
1629  if(pSPS->getUseALF())
1630  {
1631    if(pAPS->getAlfParam() != NULL)
1632    {
1633#if LCU_SYNTAX_ALF
1634      if(!pSPS->getUseALFCoefInSlice())
1635      {
1636        pAPS->getAlfParam()->releaseALFParam();
1637      }
1638#else
1639      m_pcAdaptiveLoopFilter->freeALFParam(pAPS->getAlfParam());
1640#endif
1641      pAPS->destroyAlfParam();
1642    }
1643  }
1644}
1645
1646/** Assign APS object into APS container according to APS ID
1647  * \param [in] cAPS APS object
1648  * \param [in] apsID APS ID
1649  * \param [in,out] vAPS APS container
1650  * \param [in] pcSlice pointer to slice
1651  */
1652Void TEncGOP::assignNewAPS(TComAPS& cAPS, Int apsID, std::vector<TComAPS>& vAPS, TComSlice* pcSlice)
1653{
1654
1655  cAPS.setAPSID(apsID);
1656  if(pcSlice->getPOC() == 0)
1657  {
1658    cAPS.setScalingListEnabled(pcSlice->getSPS()->getScalingListFlag());
1659  }
1660  else
1661  {
1662    cAPS.setScalingListEnabled(false);
1663  }
1664
1665  cAPS.setSaoEnabled(pcSlice->getSPS()->getUseSAO() ? (cAPS.getSaoParam()->bSaoFlag[0] ):(false));
1666#if LCU_SYNTAX_ALF
1667  cAPS.setAlfEnabled(pcSlice->getSPS()->getUseALF() ? (cAPS.getAlfParam()->isEnabled[0]):(false));
1668#else
1669  cAPS.setAlfEnabled(pcSlice->getSPS()->getUseALF() ? (cAPS.getAlfParam()->alf_flag ==1):(false));
1670#endif
1671  cAPS.setLoopFilterOffsetInAPS(m_pcCfg->getLoopFilterOffsetInAPS());
1672  cAPS.setLoopFilterDisable(m_pcCfg->getLoopFilterDisable());
1673  cAPS.setLoopFilterBetaOffset(m_pcCfg->getLoopFilterBetaOffset());
1674  cAPS.setLoopFilterTcOffset(m_pcCfg->getLoopFilterTcOffset());
1675
1676  //assign new APS into APS container
1677  Int apsBufSize= (Int)vAPS.size();
1678
1679  if(apsID >= apsBufSize)
1680  {
1681    vAPS.resize(apsID +1);
1682  }
1683
1684  freeAPS(&(vAPS[apsID]), pcSlice->getSPS());
1685  vAPS[apsID] = cAPS;
1686}
1687
1688
1689/** encode APS syntax elements
1690  * \param [in] pcAPS APS pointer
1691  * \param [in, out] APSbs bitstream
1692  * \param [in] pointer to slice (just used for entropy coder initialization)
1693  */
1694Void TEncGOP::encodeAPS(TComAPS* pcAPS, TComOutputBitstream& APSbs, TComSlice* pcSlice)
1695{
1696  m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice);
1697  m_pcEntropyCoder->resetEntropy      ();
1698  m_pcEntropyCoder->setBitstream(&APSbs);
1699
1700  m_pcEntropyCoder->encodeAPSInitInfo(pcAPS);
1701  if(pcAPS->getScalingListEnabled())
1702  {
1703    m_pcEntropyCoder->encodeScalingList( pcSlice->getScalingList() );
1704  }
1705  if(pcAPS->getLoopFilterOffsetInAPS())
1706  {
1707    m_pcEntropyCoder->encodeDFParams(pcAPS);
1708  }
1709#if SAO_UNIT_INTERLEAVING
1710  m_pcEntropyCoder->encodeSaoParam(pcAPS);
1711#else
1712  if(pcAPS->getSaoEnabled())
1713  {
1714    m_pcEntropyCoder->encodeSaoParam(pcAPS->getSaoParam());
1715  }
1716#endif
1717#if LCU_SYNTAX_ALF
1718  m_pcEntropyCoder->encodeAPSAlfFlag( pcAPS->getAlfEnabled()?1:0);
1719#endif
1720  if(pcAPS->getAlfEnabled())
1721  {
1722    m_pcEntropyCoder->encodeAlfParam(pcAPS->getAlfParam());
1723  }
1724
1725  m_pcEntropyCoder->encodeApsExtensionFlag();
1726  //neither SAO and ALF is enabled
1727  writeRBSPTrailingBits(APSbs);
1728}
1729
1730Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits )
1731{
1732  TComSlice* pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
1733  Bool bCalcDist = false;
1734#if DBL_CONTROL
1735  m_pcLoopFilter->setCfg(pcSlice->getPPS()->getDeblockingFilterControlPresent(), pcSlice->getLoopFilterDisable(), m_pcCfg->getLoopFilterBetaOffset(), m_pcCfg->getLoopFilterTcOffset(), m_pcCfg->getLFCrossTileBoundaryFlag());
1736#else
1737  m_pcLoopFilter->setCfg(pcSlice->getLoopFilterDisable(), m_pcCfg->getLoopFilterBetaOffset(), m_pcCfg->getLoopFilterTcOffset(), m_pcCfg->getLFCrossTileBoundaryFlag());
1738#endif
1739  m_pcLoopFilter->loopFilterPic( pcPic );
1740 
1741  m_pcEntropyCoder->setEntropyCoder ( m_pcEncTop->getRDGoOnSbacCoder(), pcSlice );
1742  m_pcEntropyCoder->resetEntropy    ();
1743  m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
1744  pcSlice = pcPic->getSlice(0);
1745  if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
1746  {
1747    pcPic->createNonDBFilterInfo();
1748  }
1749 
1750  // Adaptive Loop filter
1751  if( pcSlice->getSPS()->getUseALF() )
1752  {
1753    m_pcAdaptiveLoopFilter->createPicAlfInfo(pcPic);
1754
1755#if LCU_SYNTAX_ALF
1756    AlfParamSet* alfParamSet;
1757    std::vector<AlfCUCtrlInfo>* alfCUCtrlParam = NULL;
1758    alfParamSet= new AlfParamSet;
1759    alfParamSet->create( m_pcAdaptiveLoopFilter->getNumLCUInPicWidth(), m_pcAdaptiveLoopFilter->getNumLCUInPicHeight(), m_pcAdaptiveLoopFilter->getNumCUsInPic());
1760    alfParamSet->createALFParam();
1761    m_pcAdaptiveLoopFilter->initALFEnc(false, true, 1, alfParamSet, alfCUCtrlParam);
1762#else
1763    ALFParam cAlfParam;
1764    m_pcAdaptiveLoopFilter->allocALFParam(&cAlfParam);
1765#endif   
1766    m_pcAdaptiveLoopFilter->startALFEnc(pcPic, m_pcEntropyCoder);
1767   
1768
1769#if LCU_SYNTAX_ALF
1770
1771#if ALF_CHROMA_LAMBDA
1772#if HHI_INTERVIEW_SKIP
1773    m_pcAdaptiveLoopFilter->ALFProcess(alfParamSet, NULL, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma(), m_pcEncTop->getInterViewSkip()  );
1774#else
1775    m_pcAdaptiveLoopFilter->ALFProcess(alfParamSet, NULL, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma() );
1776#endif
1777#else
1778#if SAO_CHROMA_LAMBDA
1779    m_pcAdaptiveLoopFilter->ALFProcess(alfParamSet, NULL, pcPic->getSlice(0)->getLambdaLuma(), m_pcEncTop->getInterViewSkip());
1780#if HHI_INTERVIEW_SKIP
1781#else
1782    m_pcAdaptiveLoopFilter->ALFProcess(alfParamSet, NULL, pcPic->getSlice(0)->getLambdaLuma());
1783#endif
1784#else
1785#if HHI_INTERVIEW_SKIP
1786    m_pcAdaptiveLoopFilter->ALFProcess(alfParamSet, NULL, pcPic->getSlice(0)->getLambda(), m_pcEncTop->getInterViewSkip());
1787#else
1788    m_pcAdaptiveLoopFilter->ALFProcess(alfParamSet, NULL, pcPic->getSlice(0)->getLambda());
1789#endif
1790#endif
1791#endif
1792
1793#else
1794#if ALF_CHROMA_LAMBDA 
1795    m_pcAdaptiveLoopFilter->ALFProcess(&cAlfParam, NULL, pcSlice->getLambdaLuma(), pcSlice->getLambdaChroma(), ruiDist, ruiBits, m_pcEncTop->getInterViewSkip());
1796#if HHI_INTERVIEW_SKIP
1797#else
1798    m_pcAdaptiveLoopFilter->ALFProcess(&cAlfParam, NULL, pcSlice->getLambdaLuma(), pcSlice->getLambdaChroma(), ruiDist, ruiBits);
1799#endif
1800#else
1801#if SAO_CHROMA_LAMBDA
1802#if HHI_INTERVIEW_SKIP
1803    m_pcAdaptiveLoopFilter->ALFProcess(&cAlfParam, NULL, pcSlice->getLambdaLuma(), ruiDist, ruiBits, m_pcEncTop->getInterViewSkip());
1804#else
1805    m_pcAdaptiveLoopFilter->ALFProcess(&cAlfParam, NULL, pcSlice->getLambdaLuma(), ruiDist, ruiBits);
1806#endif
1807#else
1808#if HHI_INTERVIEW_SKIP
1809    m_pcAdaptiveLoopFilter->ALFProcess(&cAlfParam, NULL, pcSlice->getLambda(), ruiDist, ruiBits, m_pcEncTop->getInterViewSkip());
1810#else
1811    m_pcAdaptiveLoopFilter->ALFProcess(&cAlfParam, NULL, pcSlice->getLambda(), ruiDist, ruiBits);
1812#endif
1813#endif
1814
1815#endif
1816#endif
1817    m_pcAdaptiveLoopFilter->endALFEnc();
1818
1819#if LCU_SYNTAX_ALF
1820    alfParamSet->releaseALFParam();
1821    delete alfParamSet;
1822    delete alfCUCtrlParam;
1823#else
1824    m_pcAdaptiveLoopFilter->freeALFParam(&cAlfParam);
1825#endif
1826    m_pcAdaptiveLoopFilter->PCMLFDisableProcess(pcPic);
1827    m_pcAdaptiveLoopFilter->destroyPicAlfInfo();
1828  }
1829  if( pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
1830  {
1831    pcPic->destroyNonDBFilterInfo();
1832  }
1833 
1834  m_pcEntropyCoder->resetEntropy    ();
1835  ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
1836 
1837  if (!bCalcDist)
1838    ruiDist = xFindDistortionFrame(pcPic->getPicYuvOrg(), pcPic->getPicYuvRec());
1839}
1840
1841// ====================================================================================================================
1842// Protected member functions
1843// ====================================================================================================================
1844
1845Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut )
1846{
1847  assert( iNumPicRcvd > 0 );
1848  //  Exception for the first frame
1849  if ( iPOCLast == 0 )
1850  {
1851    m_iGopSize    = 1;
1852  }
1853  else
1854    m_iGopSize    = m_pcCfg->getGOPSize();
1855 
1856  assert (m_iGopSize > 0); 
1857
1858  return;
1859}
1860
1861Void TEncGOP::xGetBuffer( TComList<TComPic*>&       rcListPic,
1862                         TComList<TComPicYuv*>&    rcListPicYuvRecOut,
1863                         Int                       iNumPicRcvd,
1864                         Int                       iTimeOffset,
1865                         TComPic*&                 rpcPic,
1866                         TComPicYuv*&              rpcPicYuvRecOut,
1867                         UInt                      uiPOCCurr )
1868{
1869  Int i;
1870  //  Rec. output
1871  TComList<TComPicYuv*>::iterator     iterPicYuvRec = rcListPicYuvRecOut.end();
1872  for ( i = 0; i < iNumPicRcvd - iTimeOffset + 1; i++ )
1873  {
1874    iterPicYuvRec--;
1875  }
1876 
1877  rpcPicYuvRecOut = *(iterPicYuvRec);
1878 
1879  //  Current pic.
1880  TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
1881  while (iterPic != rcListPic.end())
1882  {
1883    rpcPic = *(iterPic);
1884    rpcPic->setCurrSliceIdx(0);
1885    if (rpcPic->getPOC() == (Int)uiPOCCurr)
1886    {
1887      break;
1888    }
1889    iterPic++;
1890  }
1891 
1892  assert (rpcPic->getPOC() == (Int)uiPOCCurr);
1893 
1894  return;
1895}
1896
1897UInt64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1)
1898{
1899  Int     x, y;
1900  Pel*  pSrc0   = pcPic0 ->getLumaAddr();
1901  Pel*  pSrc1   = pcPic1 ->getLumaAddr();
1902#if IBDI_DISTORTION
1903  Int  iShift = g_uiBitIncrement;
1904  Int  iOffset = 1<<(g_uiBitIncrement-1);
1905#else
1906  UInt  uiShift = g_uiBitIncrement<<1;
1907#endif
1908  Int   iTemp;
1909 
1910  Int   iStride = pcPic0->getStride();
1911  Int   iWidth  = pcPic0->getWidth();
1912  Int   iHeight = pcPic0->getHeight();
1913 
1914  UInt64  uiTotalDiff = 0;
1915 
1916  for( y = 0; y < iHeight; y++ )
1917  {
1918    for( x = 0; x < iWidth; x++ )
1919    {
1920#if IBDI_DISTORTION
1921      iTemp = ((pSrc0[x]+iOffset)>>iShift) - ((pSrc1[x]+iOffset)>>iShift); uiTotalDiff += iTemp * iTemp;
1922#else
1923      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
1924#endif
1925    }
1926    pSrc0 += iStride;
1927    pSrc1 += iStride;
1928  }
1929 
1930  iHeight >>= 1;
1931  iWidth  >>= 1;
1932  iStride >>= 1;
1933 
1934  pSrc0  = pcPic0->getCbAddr();
1935  pSrc1  = pcPic1->getCbAddr();
1936 
1937  for( y = 0; y < iHeight; y++ )
1938  {
1939    for( x = 0; x < iWidth; x++ )
1940    {
1941#if IBDI_DISTORTION
1942      iTemp = ((pSrc0[x]+iOffset)>>iShift) - ((pSrc1[x]+iOffset)>>iShift); uiTotalDiff += iTemp * iTemp;
1943#else
1944      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
1945#endif
1946    }
1947    pSrc0 += iStride;
1948    pSrc1 += iStride;
1949  }
1950 
1951  pSrc0  = pcPic0->getCrAddr();
1952  pSrc1  = pcPic1->getCrAddr();
1953 
1954  for( y = 0; y < iHeight; y++ )
1955  {
1956    for( x = 0; x < iWidth; x++ )
1957    {
1958#if IBDI_DISTORTION
1959      iTemp = ((pSrc0[x]+iOffset)>>iShift) - ((pSrc1[x]+iOffset)>>iShift); uiTotalDiff += iTemp * iTemp;
1960#else
1961      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
1962#endif
1963    }
1964    pSrc0 += iStride;
1965    pSrc1 += iStride;
1966  }
1967 
1968  return uiTotalDiff;
1969}
1970
1971#if VERBOSE_RATE
1972static const char* nalUnitTypeToString(NalUnitType type)
1973{
1974  switch (type)
1975  {
1976  case NAL_UNIT_CODED_SLICE: return "SLICE";
1977#if H0566_TLA
1978  case NAL_UNIT_CODED_SLICE_IDV: return "IDV";
1979  case NAL_UNIT_CODED_SLICE_CRA: return "CRA";
1980  case NAL_UNIT_CODED_SLICE_TLA: return "TLA";
1981#else
1982  case NAL_UNIT_CODED_SLICE_CDR: return "CDR";
1983#endif
1984  case NAL_UNIT_CODED_SLICE_IDR: return "IDR";
1985  case NAL_UNIT_SEI: return "SEI";
1986  case NAL_UNIT_SPS: return "SPS";
1987  case NAL_UNIT_PPS: return "PPS";
1988  case NAL_UNIT_FILLER_DATA: return "FILLER";
1989  default: return "UNK";
1990  }
1991}
1992#endif
1993
1994Void TEncGOP::xCalculateAddPSNR( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit& accessUnit, Double dEncTime )
1995{
1996  Int     x, y;
1997  UInt64 uiSSDY  = 0;
1998  UInt64 uiSSDU  = 0;
1999  UInt64 uiSSDV  = 0;
2000 
2001  Double  dYPSNR  = 0.0;
2002  Double  dUPSNR  = 0.0;
2003  Double  dVPSNR  = 0.0;
2004 
2005  //===== calculate PSNR =====
2006  Pel*  pOrg    = pcPic ->getPicYuvOrg()->getLumaAddr();
2007  Pel*  pRec    = pcPicD->getLumaAddr();
2008  Int   iStride = pcPicD->getStride();
2009 
2010  Int   iWidth;
2011  Int   iHeight;
2012 
2013  iWidth  = pcPicD->getWidth () - m_pcEncTop->getPad(0);
2014  iHeight = pcPicD->getHeight() - m_pcEncTop->getPad(1);
2015 
2016  Int   iSize   = iWidth*iHeight;
2017 
2018  for( y = 0; y < iHeight; y++ )
2019  {
2020    for( x = 0; x < iWidth; x++ )
2021    {
2022      Int iDiff = (Int)( pOrg[x] - pRec[x] );
2023      uiSSDY   += iDiff * iDiff;
2024    }
2025    pOrg += iStride;
2026    pRec += iStride;
2027  }
2028 
2029#if HHI_VSO
2030#if HHI_VSO_SYNTH_DIST_OUT
2031  if ( m_pcRdCost->getUseRenModel() )
2032  {
2033    unsigned int maxval = 255 * (1<<(g_uiBitDepth + g_uiBitIncrement -8));
2034    Double fRefValueY = (double) maxval * maxval * iSize;
2035    Double fRefValueC = fRefValueY / 4.0;
2036    TRenModel*  pcRenModel = m_pcEncTop->getEncTop()->getRenModel();
2037    Int64 iDistVSOY, iDistVSOU, iDistVSOV;
2038    pcRenModel->getTotalSSE( iDistVSOY, iDistVSOU, iDistVSOV );
2039    dYPSNR = ( iDistVSOY ? 10.0 * log10( fRefValueY / (Double) iDistVSOY ) : 99.99 );
2040    dUPSNR = ( iDistVSOU ? 10.0 * log10( fRefValueC / (Double) iDistVSOU ) : 99.99 );
2041    dVPSNR = ( iDistVSOV ? 10.0 * log10( fRefValueC / (Double) iDistVSOV ) : 99.99 );
2042  }
2043  else
2044#endif
2045#endif
2046  {
2047  iHeight >>= 1;
2048  iWidth  >>= 1;
2049  iStride >>= 1;
2050  pOrg  = pcPic ->getPicYuvOrg()->getCbAddr();
2051  pRec  = pcPicD->getCbAddr();
2052 
2053  for( y = 0; y < iHeight; y++ )
2054  {
2055    for( x = 0; x < iWidth; x++ )
2056    {
2057      Int iDiff = (Int)( pOrg[x] - pRec[x] );
2058      uiSSDU   += iDiff * iDiff;
2059    }
2060    pOrg += iStride;
2061    pRec += iStride;
2062  }
2063 
2064  pOrg  = pcPic ->getPicYuvOrg()->getCrAddr();
2065  pRec  = pcPicD->getCrAddr();
2066 
2067  for( y = 0; y < iHeight; y++ )
2068  {
2069    for( x = 0; x < iWidth; x++ )
2070    {
2071      Int iDiff = (Int)( pOrg[x] - pRec[x] );
2072      uiSSDV   += iDiff * iDiff;
2073    }
2074    pOrg += iStride;
2075    pRec += iStride;
2076  }
2077 
2078  unsigned int maxval = 255 * (1<<(g_uiBitDepth + g_uiBitIncrement -8));
2079  Double fRefValueY = (double) maxval * maxval * iSize;
2080  Double fRefValueC = fRefValueY / 4.0;
2081  dYPSNR            = ( uiSSDY ? 10.0 * log10( fRefValueY / (Double)uiSSDY ) : 99.99 );
2082  dUPSNR            = ( uiSSDU ? 10.0 * log10( fRefValueC / (Double)uiSSDU ) : 99.99 );
2083  dVPSNR            = ( uiSSDV ? 10.0 * log10( fRefValueC / (Double)uiSSDV ) : 99.99 );
2084  }
2085  /* calculate the size of the access unit, excluding:
2086   *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
2087   *  - SEI NAL units
2088   */
2089  unsigned numRBSPBytes = 0;
2090  for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
2091  {
2092    unsigned numRBSPBytes_nal = unsigned((*it)->m_nalUnitData.str().size());
2093#if VERBOSE_RATE
2094    printf("*** %6s numBytesInNALunit: %u\n", nalUnitTypeToString((*it)->m_nalUnitType), numRBSPBytes_nal);
2095#endif
2096    if ((*it)->m_nalUnitType != NAL_UNIT_SEI)
2097      numRBSPBytes += numRBSPBytes_nal;
2098  }
2099
2100  unsigned uibits = numRBSPBytes * 8;
2101  m_vRVM_RP.push_back( uibits );
2102
2103  //===== add PSNR =====
2104  m_pcEncTop->getAnalyzeAll()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2105  TComSlice*  pcSlice = pcPic->getSlice(0);
2106  if (pcSlice->isIntra())
2107  {
2108    m_pcEncTop->getAnalyzeI()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2109  }
2110  if (pcSlice->isInterP())
2111  {
2112    m_pcEncTop->getAnalyzeP()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2113  }
2114  if (pcSlice->isInterB())
2115  {
2116    m_pcEncTop->getAnalyzeB()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2117  }
2118
2119  Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
2120  if (!pcSlice->isReferenced()) c += 32;
2121
2122#if ADAPTIVE_QP_SELECTION
2123  printf("%s   View %3d POC %4d TId: %1d ( %c-SLICE, nQP %d QP %d ) %10d bits",
2124         pcSlice->getIsDepth() ? "Depth  " : "Texture",
2125         pcSlice->getViewId(),
2126         pcSlice->getPOC(),
2127         pcSlice->getTLayer(),
2128         c,
2129         pcSlice->getSliceQpBase(),
2130         pcSlice->getSliceQp(),
2131         uibits );
2132#else
2133  printf("%s   View %3d POC %4d TId: %1d ( %c-SLICE, QP %d ) %10d bits",
2134         pcSlice->getIsDepth() ? "Depth  " : "Texture",
2135         pcSlice->getViewId(),
2136         pcSlice->getPOC()-pcSlice->getLastIDR(),
2137         pcSlice->getTLayer(),
2138         c,
2139         pcSlice->getSliceQp(),
2140         uibits );
2141#endif
2142
2143  printf(" [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", dYPSNR, dUPSNR, dVPSNR );
2144  printf(" [ET %5.0f ]", dEncTime );
2145 
2146  for (Int iRefList = 0; iRefList < 2; iRefList++)
2147  {
2148    printf(" [L%d ", iRefList);
2149    for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(RefPicList(iRefList)); iRefIndex++)
2150    {
2151      if( pcSlice->getViewId() != pcSlice->getRefViewId( RefPicList(iRefList), iRefIndex ) )
2152      {
2153        printf( "V%d ", pcSlice->getRefViewId( RefPicList(iRefList), iRefIndex ) );
2154      }
2155      else
2156      {
2157        printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)-pcSlice->getLastIDR());
2158      }
2159    }
2160    printf("]");
2161  }
2162  if(pcSlice->getNumRefIdx(REF_PIC_LIST_C)>0 && !pcSlice->getNoBackPredFlag())
2163  {
2164    printf(" [LC ");
2165    for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(REF_PIC_LIST_C); iRefIndex++)
2166    {
2167      if( pcSlice->getViewId() != pcSlice->getRefViewId( (RefPicList)pcSlice->getListIdFromIdxOfLC(iRefIndex), pcSlice->getRefIdxFromIdxOfLC(iRefIndex) ) )
2168      {
2169        printf( "V%d ", pcSlice->getRefViewId( (RefPicList)pcSlice->getListIdFromIdxOfLC(iRefIndex), pcSlice->getRefIdxFromIdxOfLC(iRefIndex) ) );
2170      }
2171      else
2172      {
2173        printf ("%d ", pcSlice->getRefPOC((RefPicList)pcSlice->getListIdFromIdxOfLC(iRefIndex), pcSlice->getRefIdxFromIdxOfLC(iRefIndex))-pcSlice->getLastIDR());
2174      }
2175    }
2176    printf("]");
2177  }
2178}
2179
2180/** Function for deciding the nal_unit_type.
2181 * \param uiPOCCurr POC of the current picture
2182 * \returns the nal_unit type of the picture
2183 * This function checks the configuration and returns the appropriate nal_unit_type for the picture.
2184 */
2185NalUnitType TEncGOP::getNalUnitType(UInt uiPOCCurr)
2186{
2187  Bool bInterViewOnlySlice = ( m_pcCfg->getGOPEntry(MAX_GOP).m_POC == 0 && (m_pcCfg->getGOPEntry(MAX_GOP).m_sliceType == 'P' || m_pcCfg->getGOPEntry(MAX_GOP).m_sliceType == 'B') );
2188
2189  if (uiPOCCurr == 0)
2190  {
2191    if( bInterViewOnlySlice ) 
2192    { 
2193      return NAL_UNIT_CODED_SLICE_IDV; 
2194    }
2195    else
2196    { 
2197      return NAL_UNIT_CODED_SLICE_IDR;
2198    }
2199  }
2200  if (uiPOCCurr % m_pcCfg->getIntraPeriod() == 0)
2201  {
2202    if (m_pcCfg->getDecodingRefreshType() == 1)
2203    {
2204      if( bInterViewOnlySlice ) 
2205      { 
2206        return NAL_UNIT_CODED_SLICE_IDV; 
2207      }
2208      else
2209      { 
2210#if H0566_TLA
2211      return NAL_UNIT_CODED_SLICE_CRA;
2212#else
2213      return NAL_UNIT_CODED_SLICE_CDR;
2214#endif
2215      }
2216    }
2217    else if (m_pcCfg->getDecodingRefreshType() == 2)
2218    {
2219      if( bInterViewOnlySlice ) 
2220      { 
2221        return NAL_UNIT_CODED_SLICE_IDV; 
2222      }
2223      else
2224      { 
2225        return NAL_UNIT_CODED_SLICE_IDR;
2226      }
2227    }
2228  }
2229  return NAL_UNIT_CODED_SLICE;
2230}
2231
2232NalUnitType TEncGOP::getNalUnitTypeBaseViewMvc(UInt uiPOCCurr)
2233{
2234  if( uiPOCCurr == 0 )
2235  {
2236    return NAL_UNIT_CODED_SLICE_IDR;
2237  }
2238  if( uiPOCCurr % m_pcCfg->getIntraPeriod() == 0 )
2239  {
2240    if( m_pcCfg->getDecodingRefreshType() == 1 )
2241    {
2242#if H0566_TLA
2243      return NAL_UNIT_CODED_SLICE_CRA;
2244#else
2245      return NAL_UNIT_CODED_SLICE_CDR;
2246#endif
2247    }
2248    else if( m_pcCfg->getDecodingRefreshType() == 2 )
2249    {
2250      return NAL_UNIT_CODED_SLICE_IDR;
2251    }
2252  }
2253  return NAL_UNIT_CODED_SLICE;
2254}
2255
2256Double TEncGOP::xCalculateRVM()
2257{
2258  Double dRVM = 0;
2259 
2260  if( m_pcCfg->getGOPSize() == 1 && m_pcCfg->getIntraPeriod() != 1 && m_pcCfg->getFrameToBeEncoded() > RVM_VCEGAM10_M * 2 )
2261  {
2262    // calculate RVM only for lowdelay configurations
2263    std::vector<Double> vRL , vB;
2264    size_t N = m_vRVM_RP.size();
2265    vRL.resize( N );
2266    vB.resize( N );
2267   
2268    Int i;
2269    Double dRavg = 0 , dBavg = 0;
2270    vB[RVM_VCEGAM10_M] = 0;
2271    for( i = RVM_VCEGAM10_M + 1 ; i < N - RVM_VCEGAM10_M + 1 ; i++ )
2272    {
2273      vRL[i] = 0;
2274      for( Int j = i - RVM_VCEGAM10_M ; j <= i + RVM_VCEGAM10_M - 1 ; j++ )
2275        vRL[i] += m_vRVM_RP[j];
2276      vRL[i] /= ( 2 * RVM_VCEGAM10_M );
2277      vB[i] = vB[i-1] + m_vRVM_RP[i] - vRL[i];
2278      dRavg += m_vRVM_RP[i];
2279      dBavg += vB[i];
2280    }
2281   
2282    dRavg /= ( N - 2 * RVM_VCEGAM10_M );
2283    dBavg /= ( N - 2 * RVM_VCEGAM10_M );
2284   
2285    double dSigamB = 0;
2286    for( i = RVM_VCEGAM10_M + 1 ; i < N - RVM_VCEGAM10_M + 1 ; i++ )
2287    {
2288      Double tmp = vB[i] - dBavg;
2289      dSigamB += tmp * tmp;
2290    }
2291    dSigamB = sqrt( dSigamB / ( N - 2 * RVM_VCEGAM10_M ) );
2292   
2293    double f = sqrt( 12.0 * ( RVM_VCEGAM10_M - 1 ) / ( RVM_VCEGAM10_M + 1 ) );
2294   
2295    dRVM = dSigamB / dRavg * f;
2296  }
2297 
2298  return( dRVM );
2299}
2300
2301/** Determine the difference between consecutive tile sizes (in bytes) and writes it to  bistream rNalu [slice header]
2302 * \param rpcBitstreamRedirect contains the bitstream to be concatenated to rNalu. rpcBitstreamRedirect contains slice payload. rpcSlice contains tile location information.
2303 * \returns Updates rNalu to contain concatenated bitstream. rpcBitstreamRedirect is cleared at the end of this function call.
2304 */
2305Void TEncGOP::xWriteTileLocationToSliceHeader (OutputNALUnit& rNalu, TComOutputBitstream*& rpcBitstreamRedirect, TComSlice*& rpcSlice)
2306{
2307  {
2308#if !TILES_WPP_ENTRY_POINT_SIGNALLING
2309    Int iTransmitTileLocationInSliceHeader = (rpcSlice->getTileLocationCount()==0 || m_pcCfg->getTileLocationInSliceHeaderFlag()==0) ? 0 : 1;
2310    rNalu.m_Bitstream.write(iTransmitTileLocationInSliceHeader, 1);   // write flag indicating whether tile location information communicated in slice header
2311
2312    if (iTransmitTileLocationInSliceHeader)
2313    {
2314      rNalu.m_Bitstream.write(rpcSlice->getTileLocationCount()-1, 5);   // write number of tiles
2315
2316      Int *aiDiff;
2317      aiDiff = new Int [rpcSlice->getTileLocationCount()];
2318
2319      // Find largest number of bits required by Diff
2320      Int iLastSize = 0, iDiffMax = 0, iDiffMin = 0;
2321      for (UInt uiIdx=0; uiIdx<rpcSlice->getTileLocationCount(); uiIdx++)
2322      {
2323        Int iCurDiff, iCurSize;
2324        if (uiIdx==0)
2325        {
2326          iCurDiff  = rpcSlice->getTileLocation( uiIdx );
2327          iLastSize = rpcSlice->getTileLocation( uiIdx );
2328        }
2329        else
2330        {
2331          iCurSize  = rpcSlice->getTileLocation( uiIdx )  - rpcSlice->getTileLocation( uiIdx-1 );
2332          iCurDiff  = iCurSize - iLastSize;
2333          iLastSize = iCurSize;
2334        }
2335        // Store Diff so it may be written to slice header later without re-calculating.
2336        aiDiff[uiIdx] = iCurDiff;
2337
2338        if (iCurDiff>iDiffMax)
2339        {
2340          iDiffMax = iCurDiff;
2341        }
2342        if (iCurDiff<iDiffMin)
2343        {
2344          iDiffMin = iCurDiff;
2345        }
2346      }
2347
2348      Int iDiffMinAbs, iDiffMaxAbs;
2349      iDiffMinAbs = (iDiffMin<0) ? (-iDiffMin) : iDiffMin;
2350      iDiffMaxAbs = (iDiffMax<0) ? (-iDiffMax) : iDiffMax;
2351
2352      Int iBitsUsedByDiff = 0, iDiffAbsLargest;
2353      iDiffAbsLargest = (iDiffMinAbs < iDiffMaxAbs) ? iDiffMaxAbs : iDiffMinAbs;       
2354      while (1)
2355      {
2356        if (iDiffAbsLargest >= (1 << iBitsUsedByDiff) )
2357        {
2358          iBitsUsedByDiff++;
2359        }
2360        else
2361        {
2362          break;
2363        }
2364      }
2365      iBitsUsedByDiff++;
2366
2367      if (iBitsUsedByDiff > 32)
2368      {
2369        printf("\nDiff magnitude uses more than 32-bits");
2370        assert ( 0 );
2371        exit ( 0 ); // trying to catch any problems with using fixed bits for Diff information
2372      }
2373
2374      rNalu.m_Bitstream.write( iBitsUsedByDiff-1, 5 ); // write number of bits used by Diff
2375
2376      // Write diff to slice header (rNalu)
2377      for (UInt uiIdx=0; uiIdx<rpcSlice->getTileLocationCount(); uiIdx++)
2378      {
2379        Int iCurDiff = aiDiff[uiIdx];
2380
2381        // write sign of diff
2382        if (uiIdx!=0)
2383        {
2384          if (iCurDiff<0)         
2385          {
2386            rNalu.m_Bitstream.write(1, 1);
2387          }
2388          else
2389          {
2390            rNalu.m_Bitstream.write(0, 1);
2391          }
2392        }
2393
2394        // write abs value of diff
2395        Int iAbsDiff = (iCurDiff<0) ? (-iCurDiff) : iCurDiff;
2396        if (iAbsDiff > ((((UInt64)1)<<32)-1))
2397        {
2398          printf("\niAbsDiff exceeds 32-bit limit");
2399          exit(0);
2400        }
2401        rNalu.m_Bitstream.write( iAbsDiff, iBitsUsedByDiff-1 ); 
2402      }
2403
2404      delete [] aiDiff;
2405    }
2406#endif
2407  }
2408
2409  // Byte-align
2410  rNalu.m_Bitstream.writeAlignOne();
2411
2412  // Update tile marker locations
2413  TComOutputBitstream *pcOut = &rNalu.m_Bitstream;
2414  UInt uiAccumulatedLength   = pcOut->getNumberOfWrittenBits() >> 3;
2415  for (Int uiMrkIdx = 0; uiMrkIdx < rpcBitstreamRedirect->getTileMarkerLocationCount(); uiMrkIdx++)
2416  {
2417    UInt uiBottom = pcOut->getTileMarkerLocationCount();
2418    pcOut->setTileMarkerLocation      ( uiBottom, uiAccumulatedLength + rpcBitstreamRedirect->getTileMarkerLocation( uiMrkIdx ) );
2419    pcOut->setTileMarkerLocationCount ( uiBottom + 1 );
2420  }
2421
2422  // Perform bitstream concatenation
2423  if (rpcBitstreamRedirect->getNumberOfWrittenBits() > 0)
2424  {
2425    UInt uiBitCount  = rpcBitstreamRedirect->getNumberOfWrittenBits();
2426    if (rpcBitstreamRedirect->getByteStreamLength()>0)
2427    {
2428      UChar *pucStart  =  reinterpret_cast<UChar*>(rpcBitstreamRedirect->getByteStream());
2429      UInt uiWriteByteCount = 0;
2430      while (uiWriteByteCount < (uiBitCount >> 3) )
2431      {
2432        UInt uiBits = (*pucStart);
2433        rNalu.m_Bitstream.write(uiBits, 8);
2434        pucStart++;
2435        uiWriteByteCount++;
2436      }
2437    }
2438    UInt uiBitsHeld = (uiBitCount & 0x07);
2439    for (UInt uiIdx=0; uiIdx < uiBitsHeld; uiIdx++)
2440    {
2441      rNalu.m_Bitstream.write((rpcBitstreamRedirect->getHeldBits() & (1 << (7-uiIdx))) >> (7-uiIdx), 1);
2442    }         
2443  }
2444
2445  m_pcEntropyCoder->setBitstream(&rNalu.m_Bitstream);
2446
2447  delete rpcBitstreamRedirect;
2448  rpcBitstreamRedirect = new TComOutputBitstream;
2449}
2450
2451Void TEncGOP::xSetRefPicListModificationsMvc( TComSlice* pcSlice, UInt uiPOCCurr, UInt iGOPid )
2452{
2453  if( pcSlice->getSliceType() == I_SLICE || !(pcSlice->getSPS()->getListsModificationPresentFlag()) || pcSlice->getSPS()->getNumberOfUsableInterViewRefs() == 0 )
2454  {
2455    return;
2456  }
2457
2458  // analyze inter-view modifications
2459  GOPEntryMvc gem = m_pcCfg->getGOPEntry( (getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDV) ? MAX_GOP : iGOPid );
2460  Int numL0Modifications = 0;
2461  Int numL1Modifications = 0;
2462  for( Int k = 0; k < gem.m_numInterViewRefPics; k++ )
2463  {
2464    if( gem.m_interViewRefPosL0[k] > 0 ) { numL0Modifications++; }
2465    if( gem.m_interViewRefPosL1[k] > 0 ) { numL1Modifications++; }
2466  }
2467
2468  TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
2469  Int maxRefListSize = pcSlice->getNumPocTotalCurrMvc();
2470  Int numTemporalRefs = pcSlice->getNumPocTotalCurr();
2471
2472  // set L0 inter-view modifications
2473  if( (maxRefListSize > 1) && (numL0Modifications > 0) )
2474  {
2475    refPicListModification->setRefPicListModificationFlagL0( true );
2476    Int tempListEntryL0[16];
2477    for( Int k = 0; k < 16; k++ ) { tempListEntryL0[k] = -1; }
2478   
2479    Bool hasModification = false;
2480    for( Int k = 0; k < gem.m_numInterViewRefPics; k++ )
2481    {
2482      if( gem.m_interViewRefPosL0[k] > 0 )
2483      {
2484        for( Int l = 0; l < pcSlice->getSPS()->getNumberOfUsableInterViewRefs(); l++ )
2485        {
2486          if( gem.m_interViewRefs[k] == pcSlice->getSPS()->getUsableInterViewRef( l ) && (gem.m_interViewRefPosL0[k] - 1) != (numTemporalRefs + l) )
2487          {
2488            tempListEntryL0[gem.m_interViewRefPosL0[k]-1] = numTemporalRefs + l;
2489            hasModification = true;
2490          }
2491        }
2492      }
2493    }
2494
2495    if( hasModification )
2496    {
2497      Int temporalRefIdx = 0;
2498      for( Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_0 ); i++ )
2499      {
2500        if( tempListEntryL0[i] >= 0 ) 
2501        {
2502          refPicListModification->setRefPicSetIdxL0( i, tempListEntryL0[i] );
2503        }
2504        else
2505        {
2506          refPicListModification->setRefPicSetIdxL0( i, temporalRefIdx );
2507          temporalRefIdx++;
2508        }
2509      }
2510    }
2511    else
2512    {
2513      refPicListModification->setRefPicListModificationFlagL0( false );
2514    }
2515  }
2516
2517  // set L1 inter-view modifications
2518  if( (maxRefListSize > 1) && (numL1Modifications > 0) )
2519  {
2520    refPicListModification->setRefPicListModificationFlagL1( true );
2521    Int tempListEntryL1[16];
2522    for( Int k = 0; k < 16; k++ ) { tempListEntryL1[k] = -1; }
2523
2524    Bool hasModification = false;
2525    for( Int k = 0; k < gem.m_numInterViewRefPics; k++ )
2526    {
2527      if( gem.m_interViewRefPosL1[k] > 0 )
2528      {
2529        for( Int l = 0; l < pcSlice->getSPS()->getNumberOfUsableInterViewRefs(); l++ )
2530        {
2531          if( gem.m_interViewRefs[k] == pcSlice->getSPS()->getUsableInterViewRef( l ) && (gem.m_interViewRefPosL1[k] - 1) != (numTemporalRefs + l) )
2532          {
2533            tempListEntryL1[gem.m_interViewRefPosL1[k]-1] = numTemporalRefs + l;
2534            hasModification = true;
2535          }
2536        }
2537      }
2538    }
2539
2540    if( hasModification )
2541    {
2542      Int temporalRefIdx = 0;
2543      for( Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_1 ); i++ )
2544      {
2545        if( tempListEntryL1[i] >= 0 ) 
2546        {
2547          refPicListModification->setRefPicSetIdxL1( i, tempListEntryL1[i] );
2548        }
2549        else
2550        {
2551          refPicListModification->setRefPicSetIdxL1( i, temporalRefIdx );
2552          temporalRefIdx++;
2553        }
2554      }
2555    } 
2556    else
2557    {
2558      refPicListModification->setRefPicListModificationFlagL1( false );
2559    }
2560  }
2561
2562  return;
2563}
2564//! \}
Note: See TracBrowser for help on using the repository browser.