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

Last change on this file since 142 was 117, checked in by tech, 12 years ago

Cleanup

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