source: 3DVCSoftware/branches/HTM-3.1-Poznan-Univ/source/Lib/TLibEncoder/TEncGOP.cpp @ 368

Last change on this file since 368 was 77, checked in by tech, 13 years ago

Merged with branch/HTM-3.0Samsung REV74 including:

  • restricted residual prediction m24766
  • Inter-view residual prediction m24938
  • VPS concept m24714,m24878, m24945,m24896, m2491
  • reference list modification, restriction on IDR m24876, m24874
  • depth based motion parameter prediction m24829

Fixed bugs:

  • interview prediction
  • VSO

Added:

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