source: 3DVCSoftware/branches/HTM-4.1-dev2-Orange/source/Lib/TLibEncoder/TEncGOP.cpp @ 181

Last change on this file since 181 was 181, checked in by orange, 12 years ago

Integrated JCT3V-B0068 (QTLPC: quadtree limitation + predictive coding of the quadtree for depth coding)

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