DecApp.cpp 63.3 KB
Newer Older
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
/* The copyright in this software is being made available under the BSD
 * License, included below. This software may be subject to other third party
 * and contributor rights, including patent rights, and no such rights are
 * granted under this license.
 *
 * Copyright (c) 2010-2023, ITU/ISO/IEC
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
 *    be used to endorse or promote products derived from this software without
 *    specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

/** \file     DecApp.cpp
    \brief    Decoder application class
*/

#include <list>
#include <vector>
#include <stdio.h>
#include <fcntl.h>

#include "DecApp.h"
#include "DecoderLib/AnnexBread.h"
#include "DecoderLib/NALread.h"
#if RExt__DECODER_DEBUG_STATISTICS
#include "CommonLib/CodingStatistics.h"
#endif
#include "CommonLib/dtrace_codingstruct.h"

//! \ingroup DecoderApp
//! \{

static int calcGcd(int a, int b)
{
  // assume that a >= b
  return b == 0 ? a : calcGcd(b, a % b);
}


// ====================================================================================================================
// Constructor / destructor / initialization / destroy
// ====================================================================================================================

DecApp::DecApp()
: m_iPOCLastDisplay(-MAX_INT)
{
  for (int i = 0; i < MAX_NUM_LAYER_IDS; i++)
  {
    m_newCLVS[i] = true;
  }
}

// ====================================================================================================================
// Public member functions
// ====================================================================================================================

/**
 - create internal class
 - initialize internal class
 - until the end of the bitstream, call decoding function in DecApp class
 - delete allocated buffers
 - destroy internal class
 - returns the number of mismatching pictures
 */
uint32_t DecApp::decode()
{
  int      poc;
  PicList *pcListPic = nullptr;
  
#if GREEN_METADATA_SEI_ENABLED
  FeatureCounterStruct featureCounter;
  FeatureCounterStruct featureCounterOld;
  std::ifstream        bitstreamSize(m_bitstreamFileName.c_str(), std::ifstream::in | std::ifstream::binary);
  std::streampos fsize = 0;
  fsize = bitstreamSize.tellg();
  bitstreamSize.seekg( 0, std::ios::end );
  featureCounter.bytes = (int) bitstreamSize.tellg() - (int) fsize;
  bitstreamSize.close();
#endif

  std::ifstream bitstreamFile(m_bitstreamFileName.c_str(), std::ifstream::in | std::ifstream::binary);
  if (!bitstreamFile)
  {
    EXIT( "Failed to open bitstream file " << m_bitstreamFileName.c_str() << " for reading" ) ;
  }

  InputByteStream bytestream(bitstreamFile);

  if (!m_outputDecodedSEIMessagesFilename.empty() && m_outputDecodedSEIMessagesFilename!="-")
  {
    m_seiMessageFileStream.open(m_outputDecodedSEIMessagesFilename.c_str(), std::ios::out);
    if (!m_seiMessageFileStream.is_open() || !m_seiMessageFileStream.good())
    {
      EXIT( "Unable to open file "<< m_outputDecodedSEIMessagesFilename.c_str() << " for writing decoded SEI messages");
    }
  }

  if (!m_oplFilename.empty() && m_oplFilename!="-")
  {
    m_oplFileStream.open(m_oplFilename.c_str(), std::ios::out);
    if (!m_oplFileStream.is_open() || !m_oplFileStream.good())
    {
      EXIT( "Unable to open file "<< m_oplFilename.c_str() << " to write an opl-file for conformance testing (see JVET-P2008 for details)");
    }
  }

  // create & initialize internal classes
  xCreateDecLib();

  m_iPOCLastDisplay += m_iSkipFrame;      // set the last displayed POC correctly for skip forward.

  // clear contents of colour-remap-information-SEI output file
  if (!m_colourRemapSEIFileName.empty())
  {
    std::ofstream ofile(m_colourRemapSEIFileName.c_str());
    if (!ofile.good() || !ofile.is_open())
    {
      EXIT( "Unable to open file " << m_colourRemapSEIFileName.c_str() << " for writing colour-remap-information-SEI video");
    }
  }

  // clear contents of annotated-Regions-SEI output file
  if (!m_annotatedRegionsSEIFileName.empty())
  {
    std::ofstream ofile(m_annotatedRegionsSEIFileName.c_str());
    if (!ofile.good() || !ofile.is_open())
    {
      fprintf(stderr, "\nUnable to open file '%s' for writing annotated-Regions-SEI\n", m_annotatedRegionsSEIFileName.c_str());
      exit(EXIT_FAILURE);
    }
  }

  // main decoder loop
  bool loopFiltered[MAX_VPS_LAYERS] = { false };

  bool bPicSkipped = false;

#if JVET_Z0120_SII_SEI_PROCESSING
  bool openedPostFile = false;
  setShutterFilterFlag(!m_shutterIntervalPostFileName.empty());   // not apply shutter interval SEI processing if filename is not specified.
  m_cDecLib.setShutterFilterFlag(getShutterFilterFlag());
#endif

  bool isEosPresentInPu = false;
  bool isEosPresentInLastPu = false;

  bool outputPicturePresentInBitstream = false;
  auto setOutputPicturePresentInStream = [&]()
  {
    if( !outputPicturePresentInBitstream )
    {
      PicList::iterator iterPic = pcListPic->begin();
      while (!outputPicturePresentInBitstream && iterPic != pcListPic->end())
      {
        Picture *pcPic = *(iterPic++);
        if (pcPic->neededForOutput)
        {
          outputPicturePresentInBitstream = true;
        }
      }
    }
  };

    m_cDecLib.setHTidExternalSetFlag(m_mTidExternalSet);
    m_cDecLib.setTOlsIdxExternalFlag(m_tOlsIdxTidExternalSet);

#if GREEN_METADATA_SEI_ENABLED
    m_cDecLib.setFeatureAnalysisFramewise( m_GMFAFramewise);
    m_cDecLib.setGMFAFile(m_GMFAFile);
#endif
  
  bool gdrRecoveryPeriod[MAX_NUM_LAYER_IDS] = { false };
  bool prevPicSkipped = true;
  int lastNaluLayerId = -1;
  bool decodedSliceInAU = false;

  while (!!bitstreamFile)
  {
    InputNALUnit nalu;
    nalu.m_nalUnitType = NAL_UNIT_INVALID;

    // determine if next NAL unit will be the first one from a new picture
    bool bNewPicture = m_cDecLib.isNewPicture(&bitstreamFile, &bytestream);
    bool bNewAccessUnit = bNewPicture && decodedSliceInAU && m_cDecLib.isNewAccessUnit( bNewPicture, &bitstreamFile, &bytestream );
    if(!bNewPicture)
    {
      AnnexBStats stats = AnnexBStats();

      // find next NAL unit in stream
      byteStreamNALUnit(bytestream, nalu.getBitstream().getFifo(), stats);
      if (nalu.getBitstream().getFifo().empty())
      {
        /* this can happen if the following occur:
         *  - empty input file
         *  - two back-to-back start_code_prefixes
         *  - start_code_prefix immediately followed by EOF
         */
        msg( ERROR, "Warning: Attempt to decode an empty NAL unit\n");
      }
      else
      {
        // read NAL unit header
        read(nalu);

        // flush output for first slice of an IDR picture
        if(m_cDecLib.getFirstSliceInPicture() &&
            (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_W_RADL ||
             nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP))
        {
          if (!m_cDecLib.getMixedNaluTypesInPicFlag())
          {
            m_newCLVS[nalu.m_nuhLayerId] = true;   // An IDR picture starts a new CLVS
            xFlushOutput(pcListPic, nalu.m_nuhLayerId);
          }
          else
          {
            m_newCLVS[nalu.m_nuhLayerId] = false;
          }
        }
        else if (m_cDecLib.getFirstSliceInPicture() && nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_CRA && isEosPresentInLastPu)
        {
          // A CRA that is immediately preceded by an EOS is a CLVSS
          m_newCLVS[nalu.m_nuhLayerId] = true;
          xFlushOutput(pcListPic, nalu.m_nuhLayerId);
        }
        else if (m_cDecLib.getFirstSliceInPicture() && nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_CRA && !isEosPresentInLastPu)
        {
          // A CRA that is not immediately precede by an EOS is not a CLVSS
          m_newCLVS[nalu.m_nuhLayerId] = false;
        }
        else if(m_cDecLib.getFirstSliceInPicture() && !isEosPresentInLastPu)
        {
          m_newCLVS[nalu.m_nuhLayerId] = false;
        }

        // parse NAL unit syntax if within target decoding layer
        if( ( m_iMaxTemporalLayer < 0 || nalu.m_temporalId <= m_iMaxTemporalLayer ) && xIsNaluWithinTargetDecLayerIdSet( &nalu ) )
        {
          CHECK(nalu.m_temporalId > m_iMaxTemporalLayer, "bitstream shall not include any NAL unit with TemporalId greater than HighestTid");
          if (m_targetDecLayerIdSet.size())
          {
            CHECK(std::find(m_targetDecLayerIdSet.begin(), m_targetDecLayerIdSet.end(), nalu.m_nuhLayerId) == m_targetDecLayerIdSet.end(), "bitstream shall not contain any other layers than included in the OLS with OlsIdx");
          }
          if (bPicSkipped)
          {
            if ((nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL) || (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA) || (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_RASL) || (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_RADL) || (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_W_RADL) || (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP) || (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_CRA) || (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_GDR))
            {
              if (decodedSliceInAU && m_cDecLib.isSliceNaluFirstInAU(true, nalu))
              {
                m_cDecLib.resetAccessUnitNals();
                m_cDecLib.resetAccessUnitApsNals();
                m_cDecLib.resetAccessUnitPicInfo();
              }
              bPicSkipped = false;
            }
          }

          int skipFrameCounter = m_iSkipFrame;
          m_cDecLib.decode(nalu, m_iSkipFrame, m_iPOCLastDisplay, m_targetOlsIdx);

          if ( prevPicSkipped && nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_GDR )
          {
            gdrRecoveryPeriod[nalu.m_nuhLayerId] = true;
          }

          if ( skipFrameCounter == 1 && ( nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_GDR  || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_CRA ))
          {
            skipFrameCounter--;
          }

          if ( m_iSkipFrame < skipFrameCounter  &&
              ((nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL) || (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA) || (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_RASL) || (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_RADL) || (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_W_RADL) || (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP) || (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_CRA) || (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_GDR)))
          {
            if (decodedSliceInAU && m_cDecLib.isSliceNaluFirstInAU(true, nalu))
            {
              m_cDecLib.checkSeiInPictureUnit();
              m_cDecLib.resetPictureSeiNalus();
              m_cDecLib.checkAPSInPictureUnit();
              m_cDecLib.resetPictureUnitNals();
              m_cDecLib.resetAccessUnitSeiTids();
              m_cDecLib.checkSEIInAccessUnit();
              m_cDecLib.resetAccessUnitSeiPayLoadTypes();
              m_cDecLib.resetAccessUnitNals();
              m_cDecLib.resetAccessUnitApsNals();
              m_cDecLib.resetAccessUnitPicInfo();
            }
            bPicSkipped = true;
            m_iSkipFrame++;   // skipFrame count restore, the real decrement occur at the begin of next frame
          }

          if (nalu.m_nalUnitType == NAL_UNIT_OPI)
          {
            if (!m_cDecLib.getHTidExternalSetFlag() && m_cDecLib.getOPI()->getHtidInfoPresentFlag())
            {
              m_iMaxTemporalLayer = m_cDecLib.getOPI()->getOpiHtidPlus1()-1;
            }
            m_cDecLib.setHTidOpiSetFlag(m_cDecLib.getOPI()->getHtidInfoPresentFlag());
          }
          if (nalu.m_nalUnitType == NAL_UNIT_VPS)
          {
            m_cDecLib.deriveTargetOutputLayerSet( m_cDecLib.getVPS()->m_targetOlsIdx );
            m_targetDecLayerIdSet = m_cDecLib.getVPS()->m_targetLayerIdSet;
            m_targetOutputLayerIdSet = m_cDecLib.getVPS()->m_targetOutputLayerIdSet;
          }
          if (nalu.isSlice())
          {
            decodedSliceInAU = true;
          }
        }
        else
        {
          bPicSkipped = true;
          if (nalu.isSlice())
          {
            m_cDecLib.setFirstSliceInPicture(false);
          }
        }
      }

      if( nalu.isSlice() && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_RASL)
      {
        prevPicSkipped = bPicSkipped;
      }

      // once an EOS NAL unit appears in the current PU, mark the variable isEosPresentInPu as true
      if (nalu.m_nalUnitType == NAL_UNIT_EOS)
      {
        isEosPresentInPu = true;
        m_newCLVS[nalu.m_nuhLayerId] = true;  //The presence of EOS means that the next picture is the beginning of new CLVS
      }
      // within the current PU, only EOS and EOB are allowed to be sent after an EOS nal unit
      if(isEosPresentInPu)
      {
        CHECK(nalu.m_nalUnitType != NAL_UNIT_EOS && nalu.m_nalUnitType != NAL_UNIT_EOB, "When an EOS NAL unit is present in a PU, it shall be the last NAL unit among all NAL units within the PU other than other EOS NAL units or an EOB NAL unit");
      }
      lastNaluLayerId = nalu.m_nuhLayerId;
    }
    else
    {
      nalu.m_nuhLayerId = lastNaluLayerId;
    }

    if (bNewPicture || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS)
    {
      if (!m_cDecLib.getFirstSliceInSequence(nalu.m_nuhLayerId) && !bPicSkipped)
      {
        if (!loopFiltered[nalu.m_nuhLayerId] || bitstreamFile)
        {
          m_cDecLib.executeLoopFilters();
          m_cDecLib.finishPicture(poc, pcListPic, INFO, m_newCLVS[nalu.m_nuhLayerId]);
        }
        loopFiltered[nalu.m_nuhLayerId] = (nalu.m_nalUnitType == NAL_UNIT_EOS);
        if (nalu.m_nalUnitType == NAL_UNIT_EOS)
        {
          m_cDecLib.setFirstSliceInSequence(true, nalu.m_nuhLayerId);
        }

        m_cDecLib.updateAssociatedIRAP();
        m_cDecLib.updatePrevGDRInSameLayer();
        m_cDecLib.updatePrevIRAPAndGDRSubpic();

        if (gdrRecoveryPeriod[nalu.m_nuhLayerId])
        {
          if (m_cDecLib.getGDRRecoveryPocReached())
          {
            gdrRecoveryPeriod[nalu.m_nuhLayerId] = false;
          }
        }
      }
      else
      {
        m_cDecLib.setFirstSliceInPicture(true);
      }
    }

    if( pcListPic )
    {
      if ( gdrRecoveryPeriod[nalu.m_nuhLayerId] ) // Suppress YUV and OPL output during GDR recovery
      {
        PicList::iterator iterPic = pcListPic->begin();
        while (iterPic != pcListPic->end())
        {
          Picture *pcPic = *(iterPic++);
          if (pcPic->layerId == nalu.m_nuhLayerId)
          {
            pcPic->neededForOutput = false;
          }
        }
      }

      BitDepths layerOutputBitDepth;

      PicList::iterator iterPicLayer = pcListPic->begin();
      for (; iterPicLayer != pcListPic->end(); ++iterPicLayer)
      {
        if ((*iterPicLayer)->layerId == nalu.m_nuhLayerId)
        {
          break;
        }
      }
      if (iterPicLayer != pcListPic->end())
      {
        BitDepths &bitDepths = (*iterPicLayer)->m_bitDepths;

        for (auto channelType: { ChannelType::LUMA, ChannelType::CHROMA })
        {
          if (m_outputBitDepth[channelType] == 0)
          {
            layerOutputBitDepth[channelType] = bitDepths[channelType];
          }
          else
          {
            layerOutputBitDepth[channelType] = m_outputBitDepth[channelType];
          }
        }
        if (m_packedYUVMode
            && (layerOutputBitDepth[ChannelType::LUMA] != 10 && layerOutputBitDepth[ChannelType::LUMA] != 12))
        {
          EXIT("Invalid output bit-depth for packed YUV output, aborting\n");
        }

        if (!m_reconFileName.empty() && !m_cVideoIOYuvReconFile[nalu.m_nuhLayerId].isOpen())
        {
          std::string reconFileName = m_reconFileName;
          if (m_reconFileName.compare("/dev/null") && m_cDecLib.getVPS() != nullptr && m_cDecLib.getVPS()->getMaxLayers() > 1 && xIsNaluWithinTargetOutputLayerIdSet(&nalu))
          {
            size_t      pos         = reconFileName.find_last_of('.');
            std::string layerString = std::string(".layer") + std::to_string(nalu.m_nuhLayerId);
            if (pos != std::string::npos)
            {
              reconFileName.insert(pos, layerString);
            }
            else
            {
              reconFileName.append(layerString);
            }
          }
          if ((m_cDecLib.getVPS() != nullptr && (m_cDecLib.getVPS()->getMaxLayers() == 1 || xIsNaluWithinTargetOutputLayerIdSet(&nalu))) || m_cDecLib.getVPS() == nullptr)
          {
            if (isY4mFileExt(reconFileName))
            {
              const auto sps        = pcListPic->front()->cs->sps;
            int        frameRate  = 50;
              int        frameScale = 1;
              if(sps->getGeneralHrdParametersPresentFlag())
              {
                const auto hrd                 = sps->getGeneralHrdParameters();
                const auto olsHrdParam         = sps->getOlsHrdParameters()[sps->getMaxTLayers() - 1];
                int        elementDurationInTc = 1;
                if (olsHrdParam.getFixedPicRateWithinCvsFlag())
                {
                  elementDurationInTc = olsHrdParam.getElementDurationInTcMinus1() + 1;
                }
                else
                {
                  msg(WARNING, "\nWarning: No fixed picture rate info is found in the bitstream, best guess is used.\n");
                }
                frameRate  = hrd->getTimeScale() * elementDurationInTc;
                frameScale = hrd->getNumUnitsInTick();
                int gcd    = calcGcd(std::max(frameRate, frameScale), std::min(frameRate, frameScale));
                frameRate /= gcd;
                frameScale /= gcd;
              }
              else
              {
                msg(WARNING, "\nWarning: No frame rate info found in the bitstream, default 50 fps is used.\n");
              }
              const auto pps = pcListPic->front()->cs->pps;
              auto confWindow = pps->getConformanceWindow();
              const auto sx = SPS::getWinUnitX(sps->getChromaFormatIdc());
              const auto sy = SPS::getWinUnitY(sps->getChromaFormatIdc());
              const int picWidth = pps->getPicWidthInLumaSamples() - (confWindow.getWindowLeftOffset() + confWindow.getWindowRightOffset()) * sx;
              const int picHeight = pps->getPicHeightInLumaSamples() - (confWindow.getWindowTopOffset() + confWindow.getWindowBottomOffset()) * sy;
              m_cVideoIOYuvReconFile[nalu.m_nuhLayerId].setOutputY4mInfo(picWidth, picHeight, frameRate, frameScale,
                                                                         layerOutputBitDepth[ChannelType::LUMA],
                                                                         sps->getChromaFormatIdc());
            }
            m_cVideoIOYuvReconFile[nalu.m_nuhLayerId].open(reconFileName, true, layerOutputBitDepth,
                                                           layerOutputBitDepth, bitDepths);   // write mode
          }
        }
        // update file bitdepth shift if recon bitdepth changed between sequences
        for (auto channelType: { ChannelType::LUMA, ChannelType::CHROMA })
        {
          int reconBitdepth = (*iterPicLayer)->m_bitDepths[( ChannelType) channelType];
          int fileBitdepth  = m_cVideoIOYuvReconFile[nalu.m_nuhLayerId].getFileBitdepth(channelType);
          int bitdepthShift = m_cVideoIOYuvReconFile[nalu.m_nuhLayerId].getBitdepthShift(channelType);
          if (fileBitdepth + bitdepthShift != reconBitdepth)
          {
            m_cVideoIOYuvReconFile[nalu.m_nuhLayerId].setBitdepthShift(channelType, reconBitdepth - fileBitdepth);
          }
        }

        if (!m_SEIFGSFileName.empty() && !m_videoIOYuvSEIFGSFile[nalu.m_nuhLayerId].isOpen())
        {
          std::string SEIFGSFileName = m_SEIFGSFileName;
          if (m_SEIFGSFileName.compare("/dev/null") && m_cDecLib.getVPS() != nullptr && m_cDecLib.getVPS()->getMaxLayers() > 1 && xIsNaluWithinTargetOutputLayerIdSet(&nalu))
          {
            size_t      pos         = SEIFGSFileName.find_last_of('.');
            std::string layerString = std::string(".layer") + std::to_string(nalu.m_nuhLayerId);
            if (pos != std::string::npos)
            {
              SEIFGSFileName.insert(pos, layerString);
            }
            else
            {
              SEIFGSFileName.append(layerString);
            }
          }
          if ((m_cDecLib.getVPS() != nullptr && (m_cDecLib.getVPS()->getMaxLayers() == 1 || xIsNaluWithinTargetOutputLayerIdSet(&nalu))) || m_cDecLib.getVPS() == nullptr)
          {
            m_videoIOYuvSEIFGSFile[nalu.m_nuhLayerId].open(SEIFGSFileName, true, layerOutputBitDepth,
                                                           layerOutputBitDepth, bitDepths);   // write mode
          }
        }
        // update file bitdepth shift if recon bitdepth changed between sequences
        if (!m_SEIFGSFileName.empty())
        {
          for (const auto channelType: { ChannelType::LUMA, ChannelType::CHROMA })
          {
            int reconBitdepth = (*iterPicLayer)->m_bitDepths[( ChannelType) channelType];
            int fileBitdepth  = m_videoIOYuvSEIFGSFile[nalu.m_nuhLayerId].getFileBitdepth(channelType);
            int bitdepthShift = m_videoIOYuvSEIFGSFile[nalu.m_nuhLayerId].getBitdepthShift(channelType);
            if (fileBitdepth + bitdepthShift != reconBitdepth)
            {
              m_videoIOYuvSEIFGSFile[nalu.m_nuhLayerId].setBitdepthShift(channelType, reconBitdepth - fileBitdepth);
            }
          }
        }

        if (!m_SEICTIFileName.empty() && !m_cVideoIOYuvSEICTIFile[nalu.m_nuhLayerId].isOpen())
        {
          std::string SEICTIFileName = m_SEICTIFileName;
          if (m_SEICTIFileName.compare("/dev/null") && m_cDecLib.getVPS() != nullptr && m_cDecLib.getVPS()->getMaxLayers() > 1 && xIsNaluWithinTargetOutputLayerIdSet(&nalu))
          {
            size_t pos = SEICTIFileName.find_last_of('.');
            if (pos != std::string::npos)
            {
              SEICTIFileName.insert(pos, std::to_string(nalu.m_nuhLayerId));
            }
            else
            {
              SEICTIFileName.append(std::to_string(nalu.m_nuhLayerId));
            }
          }
          if ((m_cDecLib.getVPS() != nullptr && (m_cDecLib.getVPS()->getMaxLayers() == 1 || xIsNaluWithinTargetOutputLayerIdSet(&nalu))) || m_cDecLib.getVPS() == nullptr)
          {
            m_cVideoIOYuvSEICTIFile[nalu.m_nuhLayerId].open(SEICTIFileName, true, layerOutputBitDepth,
                                                            layerOutputBitDepth, bitDepths);   // write mode
          }
        }
      }
      if (!m_annotatedRegionsSEIFileName.empty())
      {
        xOutputAnnotatedRegions(pcListPic);
      }

#if JVET_Z0120_SII_SEI_PROCESSING
      PicList::iterator iterPic = pcListPic->begin();
      Picture* pcPic = *(iterPic);
      SEIMessages       shutterIntervalInfo = getSeisByType(pcPic->SEIs, SEI::PayloadType::SHUTTER_INTERVAL_INFO);

      if (!m_shutterIntervalPostFileName.empty())
      {
        bool                    hasValidSII = true;
        SEIShutterIntervalInfo *curSIIInfo  = nullptr;
        if ((pcPic->getPictureType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL ||
          pcPic->getPictureType() == NAL_UNIT_CODED_SLICE_IDR_N_LP) && m_newCLVS[nalu.m_nuhLayerId])
        {
          IdrSiiInfo curSII;
          curSII.m_picPoc = pcPic->getPOC();

          curSII.m_isValidSii                             = false;
          curSII.m_siiInfo.m_siiEnabled                   = false;
          curSII.m_siiInfo.m_siiNumUnitsInShutterInterval = 0;
          curSII.m_siiInfo.m_siiTimeScale = 0;
          curSII.m_siiInfo.m_siiMaxSubLayersMinus1 = 0;
          curSII.m_siiInfo.m_siiFixedSIwithinCLVS = 0;

          if (shutterIntervalInfo.size() > 0)
          {
            SEIShutterIntervalInfo *seiShutterIntervalInfo = (SEIShutterIntervalInfo*) *(shutterIntervalInfo.begin());
            curSII.m_isValidSii                            = true;

            curSII.m_siiInfo.m_siiEnabled = seiShutterIntervalInfo->m_siiEnabled;
            curSII.m_siiInfo.m_siiNumUnitsInShutterInterval = seiShutterIntervalInfo->m_siiNumUnitsInShutterInterval;
            curSII.m_siiInfo.m_siiTimeScale = seiShutterIntervalInfo->m_siiTimeScale;
            curSII.m_siiInfo.m_siiMaxSubLayersMinus1 = seiShutterIntervalInfo->m_siiMaxSubLayersMinus1;
            curSII.m_siiInfo.m_siiFixedSIwithinCLVS = seiShutterIntervalInfo->m_siiFixedSIwithinCLVS;
            curSII.m_siiInfo.m_siiSubLayerNumUnitsInSI.clear();
            for (int i = 0; i < seiShutterIntervalInfo->m_siiSubLayerNumUnitsInSI.size(); i++)
            {
              curSII.m_siiInfo.m_siiSubLayerNumUnitsInSI.push_back(seiShutterIntervalInfo->m_siiSubLayerNumUnitsInSI[i]);
            }

            uint32_t tmpInfo = (uint32_t)(m_activeSiiInfo.size() + 1);
            m_activeSiiInfo.insert(std::pair<uint32_t, IdrSiiInfo>(tmpInfo, curSII));
            curSIIInfo = seiShutterIntervalInfo;
          }
          else
          {
            curSII.m_isValidSii = false;
            hasValidSII         = false;
            uint32_t tmpInfo = (uint32_t)(m_activeSiiInfo.size() + 1);
            m_activeSiiInfo.insert(std::pair<uint32_t, IdrSiiInfo>(tmpInfo, curSII));
          }
        }
        else
        {
          if (m_activeSiiInfo.size() == 1)
          {
            curSIIInfo = &(m_activeSiiInfo.begin()->second.m_siiInfo);
          }
          else
          {
            bool isLast = true;
            for (int i = 1; i < m_activeSiiInfo.size() + 1; i++)
            {
              if (pcPic->getPOC() <= m_activeSiiInfo.at(i).m_picPoc)
              {
                if (m_activeSiiInfo[i - 1].m_isValidSii)
                {
                  curSIIInfo = &(m_activeSiiInfo.at(i - 1).m_siiInfo);
                }
                else
                {
                  hasValidSII = false;
                }
                isLast = false;
                break;
              }
            }
            if (isLast)
            {
              uint32_t tmpInfo = (uint32_t)(m_activeSiiInfo.size());
              curSIIInfo = &(m_activeSiiInfo.at(tmpInfo).m_siiInfo);
            }
          }
        }

        if (hasValidSII)
        {
          if (!curSIIInfo->m_siiFixedSIwithinCLVS)
          {
            uint32_t siiMaxSubLayersMinus1 = curSIIInfo->m_siiMaxSubLayersMinus1;
            uint32_t numUnitsLFR = curSIIInfo->m_siiSubLayerNumUnitsInSI[0];
            uint32_t numUnitsHFR = curSIIInfo->m_siiSubLayerNumUnitsInSI[siiMaxSubLayersMinus1];

            int blending_ratio = (numUnitsLFR / numUnitsHFR);
            bool checkEqualValuesOfSFR = true;
            bool checkSubLayerSI       = false;
            int i;

            //supports only the case of SFR = HFR / 2
            if (curSIIInfo->m_siiSubLayerNumUnitsInSI[siiMaxSubLayersMinus1] <
                        curSIIInfo->m_siiSubLayerNumUnitsInSI[siiMaxSubLayersMinus1 - 1])
            {
              checkSubLayerSI = true;
            }
            else
            {
              fprintf(stderr, "Warning: Shutter Interval SEI message processing is disabled due to SFR != (HFR / 2) \n");
            }
            //check shutter interval for all sublayer remains same for SFR pictures
            for (i = 1; i < siiMaxSubLayersMinus1; i++)
            {
              if (curSIIInfo->m_siiSubLayerNumUnitsInSI[0] != curSIIInfo->m_siiSubLayerNumUnitsInSI[i])
              {
                checkEqualValuesOfSFR = false;
              }
            }
            if (!checkEqualValuesOfSFR)
            {
              fprintf(stderr, "Warning: Shutter Interval SEI message processing is disabled when shutter interval is not same for SFR sublayers \n");
            }
            if (checkSubLayerSI && checkEqualValuesOfSFR)
            {
              setShutterFilterFlag(numUnitsLFR == blending_ratio * numUnitsHFR);
              setBlendingRatio(blending_ratio);
            }
            else
            {
              setShutterFilterFlag(false);
            }

            const SPS* activeSPS = pcListPic->front()->cs->sps;

            if (numUnitsLFR == blending_ratio * numUnitsHFR && activeSPS->getMaxTLayers() == 1 && activeSPS->getMaxDecPicBuffering(0) == 1)
            {
              fprintf(stderr, "Warning: Shutter Interval SEI message processing is disabled for single TempLayer and single frame in DPB\n");
              setShutterFilterFlag(false);
            }
          }
          else
          {
            fprintf(stderr, "Warning: Shutter Interval SEI message processing is disabled for fixed shutter interval case\n");
            setShutterFilterFlag(false);
          }
        }
        else
        {
          fprintf(stderr, "Warning: Shutter Interval information should be specified in SII-SEI message\n");
          setShutterFilterFlag(false);
        }
      }


      if (iterPicLayer != pcListPic->end())
      {
        if ((!m_shutterIntervalPostFileName.empty()) && (!openedPostFile) && getShutterFilterFlag())
        {
          BitDepths &bitDepths = (*iterPicLayer)->m_bitDepths;
          std::ofstream ofile(m_shutterIntervalPostFileName.c_str());
          if (!ofile.good() || !ofile.is_open())
          {
            fprintf(stderr, "\nUnable to open file '%s' for writing shutter-interval-SEI video\n", m_shutterIntervalPostFileName.c_str());
            exit(EXIT_FAILURE);
          }
          m_cTVideoIOYuvSIIPostFile.open(m_shutterIntervalPostFileName, true, layerOutputBitDepth, layerOutputBitDepth,
                                         bitDepths);   // write mode
          openedPostFile = true;
        }
      }
#endif

      // write reconstruction to file
      if( bNewPicture )
      {
        setOutputPicturePresentInStream();
        xWriteOutput( pcListPic, nalu.m_temporalId );
      }
      if (nalu.m_nalUnitType == NAL_UNIT_EOS)
      {
        if (!m_annotatedRegionsSEIFileName.empty() && bNewPicture)
        {
          xOutputAnnotatedRegions(pcListPic);
        }
        setOutputPicturePresentInStream();
        xWriteOutput( pcListPic, nalu.m_temporalId );
        m_cDecLib.setFirstSliceInPicture (false);
      }
      // write reconstruction to file -- for additional bumping as defined in C.5.2.3
      if (!bNewPicture && ((nalu.m_nalUnitType >= NAL_UNIT_CODED_SLICE_TRAIL && nalu.m_nalUnitType <= NAL_UNIT_RESERVED_IRAP_VCL_11)
        || (nalu.m_nalUnitType >= NAL_UNIT_CODED_SLICE_IDR_W_RADL && nalu.m_nalUnitType <= NAL_UNIT_CODED_SLICE_GDR)))
      {
        setOutputPicturePresentInStream();
        xWriteOutput( pcListPic, nalu.m_temporalId );
      }
    }
    if( bNewPicture )
    {
      m_cDecLib.checkSeiInPictureUnit();
      m_cDecLib.resetPictureSeiNalus();
      // reset the EOS present status for the next PU check
      isEosPresentInLastPu = isEosPresentInPu;
      isEosPresentInPu = false;
    }
    if (bNewPicture || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS)
    {
      m_cDecLib.checkAPSInPictureUnit();
      m_cDecLib.resetPictureUnitNals();
    }
    if (bNewAccessUnit || !bitstreamFile)
    {
      m_cDecLib.CheckNoOutputPriorPicFlagsInAccessUnit();
      m_cDecLib.resetAccessUnitNoOutputPriorPicFlags();
      m_cDecLib.checkLayerIdIncludedInCvss();
      m_cDecLib.checkSEIInAccessUnit();
      m_cDecLib.resetAccessUnitNestedSliSeiInfo();
      m_cDecLib.resetIsFirstAuInCvs();
      m_cDecLib.resetAccessUnitEos();
      m_cDecLib.resetAudIrapOrGdrAuFlag();
    }
    if(bNewAccessUnit)
    {
      decodedSliceInAU = false;
      m_cDecLib.checkTidLayerIdInAccessUnit();
      m_cDecLib.resetAccessUnitSeiTids();
      m_cDecLib.resetAccessUnitSeiPayLoadTypes();
      m_cDecLib.checkSeiContentInAccessUnit();
      m_cDecLib.resetAccessUnitSeiNalus();
      m_cDecLib.resetAccessUnitNals();
      m_cDecLib.resetAccessUnitApsNals();
      m_cDecLib.resetAccessUnitPicInfo();
    }
#if GREEN_METADATA_SEI_ENABLED
    if (m_GMFA && m_GMFAFramewise && bNewPicture)
    {
      FeatureCounterStruct featureCounterUpdated = m_cDecLib.getFeatureCounter();
      writeGMFAOutput(featureCounterUpdated, featureCounterOld, m_GMFAFile,false);
      featureCounterOld = m_cDecLib.getFeatureCounter();
    }
#endif
  }
  if (!m_annotatedRegionsSEIFileName.empty())
  {
    xOutputAnnotatedRegions(pcListPic);
  }
  // May need to check again one more time as in case one the bitstream has only one picture, the first check may miss it
  setOutputPicturePresentInStream();
  CHECK(!outputPicturePresentInBitstream, "It is required that there shall be at least one picture with PictureOutputFlag equal to 1 in the bitstream")
  
#if GREEN_METADATA_SEI_ENABLED
  if (m_GMFA && m_GMFAFramewise) //Last frame
  {
    FeatureCounterStruct featureCounterUpdated = m_cDecLib.getFeatureCounter();
    writeGMFAOutput(featureCounterUpdated, featureCounterOld, m_GMFAFile, false);
    featureCounterOld = m_cDecLib.getFeatureCounter();
  }
  
  if (m_GMFA)
  {
    // Summary
    FeatureCounterStruct featureCounterFinal = m_cDecLib.getFeatureCounter();
    FeatureCounterStruct dummy;
    writeGMFAOutput(featureCounterFinal, dummy, m_GMFAFile, true);
  }
#endif
Alberto Gonzalez's avatar
Alberto Gonzalez committed
840 841 842 843

#if JVET_AC0074_USE_OF_NNPFC_FOR_PIC_RATE_UPSAMPLING
  m_cDecLib.applyNnPostFilter();
#endif
Alberto Gonzalez's avatar
Alberto Gonzalez committed
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
  
  xFlushOutput( pcListPic );

#if JVET_Z0120_SII_SEI_PROCESSING
  if (!m_shutterIntervalPostFileName.empty() && getShutterFilterFlag())
  {
    m_cTVideoIOYuvSIIPostFile.close();
  }
#endif

  // get the number of checksum errors
  uint32_t nRet = m_cDecLib.getNumberOfChecksumErrorsDetected();

  // delete buffers
  m_cDecLib.deletePicBuffer();
  // destroy internal classes
  xDestroyDecLib();

#if RExt__DECODER_DEBUG_STATISTICS
  CodingStatistics::DestroyInstance();
#endif

  destroyROM();

  return nRet;
}



void DecApp::writeLineToOutputLog(Picture * pcPic)
{
  if (m_oplFileStream.is_open() && m_oplFileStream.good())
  {
    const SPS *   sps             = pcPic->cs->sps;
Alberto Gonzalez's avatar
Alberto Gonzalez committed
878
    ChromaFormat  chromaFormatIdc = sps->getChromaFormatIdc();
Alberto Gonzalez's avatar
Alberto Gonzalez committed
879
    const Window &conf            = pcPic->getConformanceWindow();
Alberto Gonzalez's avatar
Alberto Gonzalez committed
880 881 882 883
    const int     leftOffset      = conf.getWindowLeftOffset() * SPS::getWinUnitX(chromaFormatIdc);
    const int     rightOffset     = conf.getWindowRightOffset() * SPS::getWinUnitX(chromaFormatIdc);
    const int     topOffset       = conf.getWindowTopOffset() * SPS::getWinUnitY(chromaFormatIdc);
    const int     bottomOffset    = conf.getWindowBottomOffset() * SPS::getWinUnitY(chromaFormatIdc);
Alberto Gonzalez's avatar
Alberto Gonzalez committed
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
    PictureHash   recon_digest;
    auto numChar = calcMD5WithCropping(((const Picture *) pcPic)->getRecoBuf(), recon_digest, sps->getBitDepths(),
                                       leftOffset, rightOffset, topOffset, bottomOffset);

    const int croppedWidth  = pcPic->Y().width - leftOffset - rightOffset;
    const int croppedHeight = pcPic->Y().height - topOffset - bottomOffset;

    m_oplFileStream << std::setw(3) << pcPic->layerId << ",";
    m_oplFileStream << std::setw(8) << pcPic->getPOC() << "," << std::setw(5) << croppedWidth << "," << std::setw(5)
                    << croppedHeight << "," << hashToString(recon_digest, numChar) << "\n";
  }
}

// ====================================================================================================================
// Protected member functions
// ====================================================================================================================

void DecApp::xCreateDecLib()
{
  initROM();

  // create decoder class
  m_cDecLib.create();

  // initialize decoder class
  m_cDecLib.init(
#if JVET_J0090_MEMORY_BANDWITH_MEASURE
    m_cacheCfgFile
#endif
  );
  m_cDecLib.setDecodedPictureHashSEIEnabled(m_decodedPictureHashSEIEnabled);


  if (!m_outputDecodedSEIMessagesFilename.empty())
  {
    std::ostream &os=m_seiMessageFileStream.is_open() ? m_seiMessageFileStream : std::cout;
    m_cDecLib.setDecodedSEIMessageOutputStream(&os);
  }
#if JVET_S0257_DUMP_360SEI_MESSAGE
  if (!m_outputDecoded360SEIMessagesFilename.empty())
  {
    m_cDecLib.setDecoded360SEIMessageFileName(m_outputDecoded360SEIMessagesFilename);
  }
#endif
  m_cDecLib.m_targetSubPicIdx = this->m_targetSubPicIdx;
  m_cDecLib.initScalingList();
#if GDR_LEAK_TEST
  m_cDecLib.m_gdrPocRandomAccess = this->m_gdrPocRandomAccess;
#endif // GDR_LEAK_TEST
}

void DecApp::xDestroyDecLib()
{
  if( !m_reconFileName.empty() )
  {
    for( auto & recFile : m_cVideoIOYuvReconFile )
    {
      recFile.second.close();
    }
  }
  if (!m_SEIFGSFileName.empty())
  {
    for (auto &recFile: m_videoIOYuvSEIFGSFile)
    {
      recFile.second.close();
    }
  }
  if (!m_SEICTIFileName.empty())
  {
    for (auto& recFile : m_cVideoIOYuvSEICTIFile)
    {
      recFile.second.close();
    }
  }

  // destroy decoder class
  m_cDecLib.destroy();
}


/** \param pcListPic list of pictures to be written to file
    \param tId       temporal sub-layer ID
 */
void DecApp::xWriteOutput( PicList* pcListPic, uint32_t tId )
{
  if (pcListPic->empty())
  {
    return;
  }

  PicList::iterator iterPic   = pcListPic->begin();
  int numPicsNotYetDisplayed = 0;
  int dpbFullness = 0;
  uint32_t maxNumReorderPicsHighestTid;
  uint32_t maxDecPicBufferingHighestTid;
  const VPS* referredVPS = pcListPic->front()->cs->vps;

  if( referredVPS == nullptr || referredVPS->m_numLayersInOls[referredVPS->m_targetOlsIdx] == 1 )
  {
    const SPS* activeSPS = (pcListPic->front()->cs->sps);
    const int temporalId = (m_iMaxTemporalLayer == -1 || m_iMaxTemporalLayer >= activeSPS->getMaxTLayers())
      ? activeSPS->getMaxTLayers() - 1
      : m_iMaxTemporalLayer;
    maxNumReorderPicsHighestTid = activeSPS->getMaxNumReorderPics( temporalId );
    maxDecPicBufferingHighestTid = activeSPS->getMaxDecPicBuffering( temporalId );
  }
  else
  {
    const int temporalId = (m_iMaxTemporalLayer == -1 || m_iMaxTemporalLayer >= referredVPS->getMaxSubLayers())
      ? referredVPS->getMaxSubLayers() - 1
      : m_iMaxTemporalLayer;
    maxNumReorderPicsHighestTid = referredVPS->getMaxNumReorderPics( temporalId );
    maxDecPicBufferingHighestTid = referredVPS->getMaxDecPicBuffering( temporalId );
  }

  while (iterPic != pcListPic->end())
  {
    Picture* pcPic = *(iterPic);
    if(pcPic->neededForOutput && pcPic->getPOC() >= m_iPOCLastDisplay)
    {
      numPicsNotYetDisplayed++;
      dpbFullness++;
    }
    else if(pcPic->referenced)
    {
      dpbFullness++;
    }
    iterPic++;
  }

  iterPic = pcListPic->begin();

Alberto Gonzalez's avatar
Alberto Gonzalez committed
1016
  if (numPicsNotYetDisplayed>=2)
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1017 1018 1019 1020 1021
  {
    iterPic++;
  }

  Picture* pcPic = *(iterPic);
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1022
  if( numPicsNotYetDisplayed>=2 && pcPic->fieldPic ) //Field Decoding
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1023 1024 1025 1026 1027 1028 1029 1030
  {
    PicList::iterator endPic   = pcListPic->end();
    endPic--;
    iterPic   = pcListPic->begin();
    while (iterPic != endPic)
    {
      Picture* pcPicTop = *(iterPic);
      iterPic++;
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
      PicList::iterator iterPic2 = iterPic;
      while (iterPic2 != pcListPic->end())
      {
        if ((*iterPic2)->layerId == pcPicTop->layerId && (*iterPic2)->fieldPic && (*iterPic2)->topField != pcPicTop->topField)
        {
          break;
        }
        iterPic2++;
      }
      if (iterPic2 == pcListPic->end())
      {
        continue;
      }
      
      Picture* pcPicBottom = *(iterPic2);
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1046 1047 1048

      if ( pcPicTop->neededForOutput && pcPicBottom->neededForOutput &&
          (numPicsNotYetDisplayed >  maxNumReorderPicsHighestTid || dpbFullness > maxDecPicBufferingHighestTid) &&
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1049
          pcPicBottom->getPOC() >= m_iPOCLastDisplay )
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
      {
        // write to file
        numPicsNotYetDisplayed = numPicsNotYetDisplayed-2;
        if ( !m_reconFileName.empty() )
        {
          const Window &conf = pcPicTop->getConformanceWindow();
          const bool isTff = pcPicTop->topField;

          bool display = true;

          if (display)
          {
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1062 1063 1064 1065 1066 1067 1068 1069
            m_cVideoIOYuvReconFile[pcPicTop->layerId].write(
              pcPicTop->getRecoBuf(), pcPicBottom->getRecoBuf(), m_outputColourSpaceConvert,
              false,   // TODO: m_packedYUVMode,
              conf.getWindowLeftOffset() * SPS::getWinUnitX(pcPicTop->cs->sps->getChromaFormatIdc()),
              conf.getWindowRightOffset() * SPS::getWinUnitX(pcPicTop->cs->sps->getChromaFormatIdc()),
              conf.getWindowTopOffset() * SPS::getWinUnitY(pcPicTop->cs->sps->getChromaFormatIdc()),
              conf.getWindowBottomOffset() * SPS::getWinUnitY(pcPicTop->cs->sps->getChromaFormatIdc()),
              ChromaFormat::UNDEFINED, isTff);
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
          }
        }
        writeLineToOutputLog(pcPicTop);
        writeLineToOutputLog(pcPicBottom);

        // update POC of display order
        m_iPOCLastDisplay = pcPicBottom->getPOC();

        // erase non-referenced picture in the reference picture list after display
        if ( ! pcPicTop->referenced && pcPicTop->reconstructed )
        {
          pcPicTop->reconstructed = false;
        }
        if ( ! pcPicBottom->referenced && pcPicBottom->reconstructed )
        {
          pcPicBottom->reconstructed = false;
        }
        pcPicTop->neededForOutput = false;
        pcPicBottom->neededForOutput = false;
      }
    }
  }
  else if( !pcPic->fieldPic ) //Frame Decoding
  {
    iterPic = pcListPic->begin();

    while (iterPic != pcListPic->end())
    {
      pcPic = *(iterPic);

      if(pcPic->neededForOutput && pcPic->getPOC() >= m_iPOCLastDisplay &&
        (numPicsNotYetDisplayed >  maxNumReorderPicsHighestTid || dpbFullness > maxDecPicBufferingHighestTid))
      {
        // write to file
        numPicsNotYetDisplayed--;
        if (!pcPic->referenced)
        {
          dpbFullness--;
        }


        if (!m_reconFileName.empty())
        {
          const Window &conf = pcPic->getConformanceWindow();
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1114
          ChromaFormat  chromaFormatIdc = pcPic->m_chromaFormatIdc;
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1115 1116 1117 1118 1119
          if( m_upscaledOutput )
          {
            const SPS* sps = pcPic->cs->sps;
            m_cVideoIOYuvReconFile[pcPic->layerId].writeUpscaledPicture(
              *sps, *pcPic->cs->pps, pcPic->getRecoBuf(), m_outputColourSpaceConvert, m_packedYUVMode, m_upscaledOutput,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1120
              ChromaFormat::UNDEFINED, m_clipOutputVideoToRec709Range, m_upscaleFilterForDisplay);
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1121 1122 1123 1124 1125 1126
          }
          else
          {
            m_cVideoIOYuvReconFile[pcPic->layerId].write(
              pcPic->getRecoBuf().get(COMPONENT_Y).width, pcPic->getRecoBuf().get(COMPONENT_Y).height,
              pcPic->getRecoBuf(), m_outputColourSpaceConvert, m_packedYUVMode,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1127 1128 1129 1130
              conf.getWindowLeftOffset() * SPS::getWinUnitX(chromaFormatIdc),
              conf.getWindowRightOffset() * SPS::getWinUnitX(chromaFormatIdc),
              conf.getWindowTopOffset() * SPS::getWinUnitY(chromaFormatIdc),
              conf.getWindowBottomOffset() * SPS::getWinUnitY(chromaFormatIdc), ChromaFormat::UNDEFINED,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1131 1132 1133 1134 1135 1136 1137 1138
              m_clipOutputVideoToRec709Range);
            }
        }
        // Perform FGS on decoded frame and write to output FGS file
        if (!m_SEIFGSFileName.empty())
        {
          const Window& conf            = pcPic->getConformanceWindow();
          const SPS* sps                = pcPic->cs->sps;
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1139
          ChromaFormat  chromaFormatIdc    = sps->getChromaFormatIdc();
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1140 1141 1142 1143
          if (m_upscaledOutput)
          {
            m_videoIOYuvSEIFGSFile[pcPic->layerId].writeUpscaledPicture(
              *sps, *pcPic->cs->pps, pcPic->getDisplayBufFG(), m_outputColourSpaceConvert, m_packedYUVMode,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1144
              m_upscaledOutput, ChromaFormat::UNDEFINED, m_clipOutputVideoToRec709Range, m_upscaleFilterForDisplay);
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1145 1146 1147 1148 1149 1150
          }
          else
          {
            m_videoIOYuvSEIFGSFile[pcPic->layerId].write(
              pcPic->getRecoBuf().get(COMPONENT_Y).width, pcPic->getRecoBuf().get(COMPONENT_Y).height,
              pcPic->getDisplayBufFG(), m_outputColourSpaceConvert, m_packedYUVMode,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1151 1152 1153 1154
              conf.getWindowLeftOffset() * SPS::getWinUnitX(chromaFormatIdc),
              conf.getWindowRightOffset() * SPS::getWinUnitX(chromaFormatIdc),
              conf.getWindowTopOffset() * SPS::getWinUnitY(chromaFormatIdc),
              conf.getWindowBottomOffset() * SPS::getWinUnitY(chromaFormatIdc), ChromaFormat::UNDEFINED,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
              m_clipOutputVideoToRec709Range);
          }
        }


#if JVET_Z0120_SII_SEI_PROCESSING
        if (!m_shutterIntervalPostFileName.empty() && getShutterFilterFlag())
        {
          int blendingRatio = getBlendingRatio();
          pcPic->xOutputPostFilteredPic(pcPic, pcListPic, blendingRatio);

          const Window &conf = pcPic->getConformanceWindow();
          const SPS* sps = pcPic->cs->sps;
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1168
          ChromaFormat  chromaFormatIdc = sps->getChromaFormatIdc();
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1169 1170 1171 1172

          m_cTVideoIOYuvSIIPostFile.write(pcPic->getPostRecBuf().get(COMPONENT_Y).width,
                                          pcPic->getPostRecBuf().get(COMPONENT_Y).height, pcPic->getPostRecBuf(),
                                          m_outputColourSpaceConvert, m_packedYUVMode,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1173 1174 1175 1176 1177
                                          conf.getWindowLeftOffset() * SPS::getWinUnitX(chromaFormatIdc),
                                          conf.getWindowRightOffset() * SPS::getWinUnitX(chromaFormatIdc),
                                          conf.getWindowTopOffset() * SPS::getWinUnitY(chromaFormatIdc),
                                          conf.getWindowBottomOffset() * SPS::getWinUnitY(chromaFormatIdc),
                                          ChromaFormat::UNDEFINED, m_clipOutputVideoToRec709Range);
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1178 1179 1180 1181 1182 1183 1184 1185
        }
#endif

        // Perform CTI on decoded frame and write to output CTI file
        if (!m_SEICTIFileName.empty())
        {
          const Window& conf = pcPic->getConformanceWindow();
          const SPS* sps = pcPic->cs->sps;
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1186
          ChromaFormat  chromaFormatIdc = sps->getChromaFormatIdc();
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1187 1188 1189 1190
          if (m_upscaledOutput)
          {
            m_cVideoIOYuvSEICTIFile[pcPic->layerId].writeUpscaledPicture(
              *sps, *pcPic->cs->pps, pcPic->getDisplayBuf(), m_outputColourSpaceConvert, m_packedYUVMode,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1191
              m_upscaledOutput, ChromaFormat::UNDEFINED, m_clipOutputVideoToRec709Range, m_upscaleFilterForDisplay);
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1192 1193 1194 1195 1196 1197
          }
          else
          {
            m_cVideoIOYuvSEICTIFile[pcPic->layerId].write(
              pcPic->getRecoBuf().get(COMPONENT_Y).width, pcPic->getRecoBuf().get(COMPONENT_Y).height,
              pcPic->getDisplayBuf(), m_outputColourSpaceConvert, m_packedYUVMode,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1198 1199 1200 1201
              conf.getWindowLeftOffset() * SPS::getWinUnitX(chromaFormatIdc),
              conf.getWindowRightOffset() * SPS::getWinUnitX(chromaFormatIdc),
              conf.getWindowTopOffset() * SPS::getWinUnitY(chromaFormatIdc),
              conf.getWindowBottomOffset() * SPS::getWinUnitY(chromaFormatIdc), ChromaFormat::UNDEFINED,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
              m_clipOutputVideoToRec709Range);
          }
        }
        writeLineToOutputLog(pcPic);

        // update POC of display order
        m_iPOCLastDisplay = pcPic->getPOC();

        // erase non-referenced picture in the reference picture list after display
        if (!pcPic->referenced && pcPic->reconstructed)
        {
          pcPic->reconstructed = false;
        }
        pcPic->neededForOutput = false;
      }

      iterPic++;
    }
  }
}

/** \param pcListPic list of pictures to be written to file
 */
void DecApp::xFlushOutput( PicList* pcListPic, const int layerId )
{
  if(!pcListPic || pcListPic->empty())
  {
    return;
  }
  PicList::iterator iterPic   = pcListPic->begin();

  iterPic   = pcListPic->begin();
  Picture* pcPic = *(iterPic);

  if (pcPic->fieldPic ) //Field Decoding
  {
    PicList::iterator endPic = pcListPic->end();
    while (iterPic != endPic)
    {
      Picture *pcPicTop = *iterPic;
      iterPic++;

Alberto Gonzalez's avatar
Alberto Gonzalez committed
1244
      if (pcPicTop == nullptr || (pcPicTop->layerId != layerId && layerId != NOT_VALID))
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1245 1246 1247 1248
      {
        continue;
      }

Alberto Gonzalez's avatar
Alberto Gonzalez committed
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
      PicList::iterator iterPic2 = iterPic;
      while (iterPic2 != endPic)
      {
        if ((*iterPic2) != nullptr && (*iterPic2)->layerId == pcPicTop->layerId && (*iterPic2)->fieldPic && (*iterPic2)->topField != pcPicTop->topField)
        {
          break;
        }
        iterPic2++;
      }
      Picture *pcPicBottom = iterPic2 == endPic ? nullptr : *iterPic2;

      if (pcPicBottom != nullptr && pcPicTop->neededForOutput && pcPicBottom->neededForOutput)
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1261 1262 1263 1264 1265 1266 1267
      {
          // write to file
          if ( !m_reconFileName.empty() )
          {
            const Window &conf = pcPicTop->getConformanceWindow();
            const bool    isTff   = pcPicTop->topField;

Alberto Gonzalez's avatar
Alberto Gonzalez committed
1268 1269 1270 1271 1272 1273 1274 1275
            m_cVideoIOYuvReconFile[pcPicTop->layerId].write(
              pcPicTop->getRecoBuf(), pcPicBottom->getRecoBuf(), m_outputColourSpaceConvert,
              false,   // TODO: m_packedYUVMode,
              conf.getWindowLeftOffset() * SPS::getWinUnitX(pcPicTop->cs->sps->getChromaFormatIdc()),
              conf.getWindowRightOffset() * SPS::getWinUnitX(pcPicTop->cs->sps->getChromaFormatIdc()),
              conf.getWindowTopOffset() * SPS::getWinUnitY(pcPicTop->cs->sps->getChromaFormatIdc()),
              conf.getWindowBottomOffset() * SPS::getWinUnitY(pcPicTop->cs->sps->getChromaFormatIdc()),
              ChromaFormat::UNDEFINED, isTff);
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
          }
          writeLineToOutputLog(pcPicTop);
          writeLineToOutputLog(pcPicBottom);
        // update POC of display order
        m_iPOCLastDisplay = pcPicBottom->getPOC();

        // erase non-referenced picture in the reference picture list after display
        if( ! pcPicTop->referenced && pcPicTop->reconstructed )
        {
          pcPicTop->reconstructed = false;
        }
        if( ! pcPicBottom->referenced && pcPicBottom->reconstructed )
        {
          pcPicBottom->reconstructed = false;
        }
        pcPicTop->neededForOutput = false;
        pcPicBottom->neededForOutput = false;

        pcPicTop->destroy();
        delete pcPicTop;
        pcPicBottom->destroy();
        delete pcPicBottom;
        iterPic--;
        *iterPic = nullptr;
        iterPic++;
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1301
        *iterPic2 = nullptr;
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
      }
      else
      {
        pcPicTop->destroy();
        delete pcPicTop;
        iterPic--;
        *iterPic = nullptr;
        iterPic++;
      }
    }
  }
  else //Frame decoding
  {
    while (iterPic != pcListPic->end())
    {
      pcPic = *(iterPic);

      if( pcPic->layerId != layerId && layerId != NOT_VALID )
      {
        iterPic++;
        continue;
      }

      if (pcPic->neededForOutput)
      {
          // write to file
          if (!m_reconFileName.empty())
          {
            const Window &conf = pcPic->getConformanceWindow();
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1331
            ChromaFormat  chromaFormatIdc = pcPic->m_chromaFormatIdc;
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1332 1333 1334 1335 1336
            if( m_upscaledOutput )
            {
              const SPS* sps = pcPic->cs->sps;
              m_cVideoIOYuvReconFile[pcPic->layerId].writeUpscaledPicture(
                *sps, *pcPic->cs->pps, pcPic->getRecoBuf(), m_outputColourSpaceConvert, m_packedYUVMode,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1337
                m_upscaledOutput, ChromaFormat::UNDEFINED, m_clipOutputVideoToRec709Range, m_upscaleFilterForDisplay);
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1338 1339 1340 1341 1342 1343
            }
            else
            {
              m_cVideoIOYuvReconFile[pcPic->layerId].write(
                pcPic->getRecoBuf().get(COMPONENT_Y).width, pcPic->getRecoBuf().get(COMPONENT_Y).height,
                pcPic->getRecoBuf(), m_outputColourSpaceConvert, m_packedYUVMode,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1344 1345 1346 1347
                conf.getWindowLeftOffset() * SPS::getWinUnitX(chromaFormatIdc),
                conf.getWindowRightOffset() * SPS::getWinUnitX(chromaFormatIdc),
                conf.getWindowTopOffset() * SPS::getWinUnitY(chromaFormatIdc),
                conf.getWindowBottomOffset() * SPS::getWinUnitY(chromaFormatIdc), ChromaFormat::UNDEFINED,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1348 1349 1350 1351 1352 1353
                m_clipOutputVideoToRec709Range);
              }
          }
          // Perform FGS on decoded frame and write to output FGS file
          if (!m_SEIFGSFileName.empty())
          {
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1354 1355 1356
            const Window& conf            = pcPic->getConformanceWindow();
            const SPS*    sps             = pcPic->cs->sps;
            ChromaFormat  chromaFormatIdc = sps->getChromaFormatIdc();
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1357 1358 1359 1360
            if (m_upscaledOutput)
            {
              m_videoIOYuvSEIFGSFile[pcPic->layerId].writeUpscaledPicture(
                *sps, *pcPic->cs->pps, pcPic->getDisplayBufFG(), m_outputColourSpaceConvert, m_packedYUVMode,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1361
                m_upscaledOutput, ChromaFormat::UNDEFINED, m_clipOutputVideoToRec709Range, m_upscaleFilterForDisplay);
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1362 1363 1364 1365 1366 1367
            }
            else
            {
              m_videoIOYuvSEIFGSFile[pcPic->layerId].write(
                pcPic->getRecoBuf().get(COMPONENT_Y).width, pcPic->getRecoBuf().get(COMPONENT_Y).height,
                pcPic->getDisplayBufFG(), m_outputColourSpaceConvert, m_packedYUVMode,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1368 1369 1370 1371
                conf.getWindowLeftOffset() * SPS::getWinUnitX(chromaFormatIdc),
                conf.getWindowRightOffset() * SPS::getWinUnitX(chromaFormatIdc),
                conf.getWindowTopOffset() * SPS::getWinUnitY(chromaFormatIdc),
                conf.getWindowBottomOffset() * SPS::getWinUnitY(chromaFormatIdc), ChromaFormat::UNDEFINED,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
                m_clipOutputVideoToRec709Range);
            }
          }

#if JVET_Z0120_SII_SEI_PROCESSING
          if (!m_shutterIntervalPostFileName.empty() && getShutterFilterFlag())
          {
            int blendingRatio = getBlendingRatio();
            pcPic->xOutputPostFilteredPic(pcPic, pcListPic, blendingRatio);

            const Window &conf = pcPic->getConformanceWindow();
            const SPS* sps = pcPic->cs->sps;
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1384
            ChromaFormat  chromaFormatIdc = sps->getChromaFormatIdc();
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1385 1386 1387 1388

            m_cTVideoIOYuvSIIPostFile.write(pcPic->getPostRecBuf().get(COMPONENT_Y).width,
                                            pcPic->getPostRecBuf().get(COMPONENT_Y).height, pcPic->getPostRecBuf(),
                                            m_outputColourSpaceConvert, m_packedYUVMode,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1389 1390 1391 1392 1393
                                            conf.getWindowLeftOffset() * SPS::getWinUnitX(chromaFormatIdc),
                                            conf.getWindowRightOffset() * SPS::getWinUnitX(chromaFormatIdc),
                                            conf.getWindowTopOffset() * SPS::getWinUnitY(chromaFormatIdc),
                                            conf.getWindowBottomOffset() * SPS::getWinUnitY(chromaFormatIdc),
                                            ChromaFormat::UNDEFINED, m_clipOutputVideoToRec709Range);
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1394 1395 1396 1397 1398 1399 1400 1401
          }
#endif

          // Perform CTI on decoded frame and write to output CTI file
          if (!m_SEICTIFileName.empty())
          {
            const Window& conf = pcPic->getConformanceWindow();
            const SPS* sps = pcPic->cs->sps;
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1402
            ChromaFormat  chromaFormatIdc = sps->getChromaFormatIdc();
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1403 1404 1405 1406
            if (m_upscaledOutput)
            {
              m_cVideoIOYuvSEICTIFile[pcPic->layerId].writeUpscaledPicture(
                *sps, *pcPic->cs->pps, pcPic->getDisplayBuf(), m_outputColourSpaceConvert, m_packedYUVMode,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1407
                m_upscaledOutput, ChromaFormat::UNDEFINED, m_clipOutputVideoToRec709Range, m_upscaleFilterForDisplay);
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1408 1409 1410 1411 1412 1413
            }
            else
            {
              m_cVideoIOYuvSEICTIFile[pcPic->layerId].write(
                pcPic->getRecoBuf().get(COMPONENT_Y).width, pcPic->getRecoBuf().get(COMPONENT_Y).height,
                pcPic->getDisplayBuf(), m_outputColourSpaceConvert, m_packedYUVMode,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1414 1415 1416 1417
                conf.getWindowLeftOffset() * SPS::getWinUnitX(chromaFormatIdc),
                conf.getWindowRightOffset() * SPS::getWinUnitX(chromaFormatIdc),
                conf.getWindowTopOffset() * SPS::getWinUnitY(chromaFormatIdc),
                conf.getWindowBottomOffset() * SPS::getWinUnitY(chromaFormatIdc), ChromaFormat::UNDEFINED,
Alberto Gonzalez's avatar
Alberto Gonzalez committed
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
                m_clipOutputVideoToRec709Range);
            }
          }
          writeLineToOutputLog(pcPic);
        // update POC of display order
        m_iPOCLastDisplay = pcPic->getPOC();

        // erase non-referenced picture in the reference picture list after display
        if (!pcPic->referenced && pcPic->reconstructed)
        {
          pcPic->reconstructed = false;
        }
        pcPic->neededForOutput = false;
      }
#if JVET_Z0120_SII_SEI_PROCESSING
      if (pcPic != nullptr && (m_shutterIntervalPostFileName.empty() || !getShutterFilterFlag()))
#else
      if(pcPic != nullptr)
#endif
      {
        pcPic->destroy();
        delete pcPic;
        pcPic    = nullptr;
        *iterPic = nullptr;
      }
      iterPic++;
    }
  }

  if( layerId != NOT_VALID )
  {
    pcListPic->remove_if([](Picture* p) { return p == nullptr; });
  }
  else
  {
    pcListPic->clear();
  }
  m_iPOCLastDisplay = -MAX_INT;
}

/** \param pcListPic list of pictures to be written to file
 */
void DecApp::xOutputAnnotatedRegions(PicList* pcListPic)
{
  if(!pcListPic || pcListPic->empty())
  {
    return;
  }
  PicList::iterator iterPic   = pcListPic->begin();

  while (iterPic != pcListPic->end())
  {
    Picture* pcPic = *(iterPic);
    if (pcPic->neededForOutput)
    {
      // Check if any annotated region SEI has arrived
      SEIMessages annotatedRegionSEIs = getSeisByType(pcPic->SEIs, SEI::PayloadType::ANNOTATED_REGIONS);
      for(auto it=annotatedRegionSEIs.begin(); it!=annotatedRegionSEIs.end(); it++)
      {
        const SEIAnnotatedRegions &seiAnnotatedRegions = *(SEIAnnotatedRegions*)(*it);

        if (seiAnnotatedRegions.m_hdr.m_cancelFlag)
        {
          m_arObjects.clear();
          m_arLabels.clear();
        }
        else
        {
          if (m_arHeader.m_receivedSettingsOnce)
          {
            // validate those settings that must stay constant are constant.
            assert(m_arHeader.m_occludedObjectFlag              == seiAnnotatedRegions.m_hdr.m_occludedObjectFlag);
            assert(m_arHeader.m_partialObjectFlagPresentFlag    == seiAnnotatedRegions.m_hdr.m_partialObjectFlagPresentFlag);
            assert(m_arHeader.m_objectConfidenceInfoPresentFlag == seiAnnotatedRegions.m_hdr.m_objectConfidenceInfoPresentFlag);
            assert((!m_arHeader.m_objectConfidenceInfoPresentFlag) || m_arHeader.m_objectConfidenceLength == seiAnnotatedRegions.m_hdr.m_objectConfidenceLength);
          }
          else
          {
            m_arHeader.m_receivedSettingsOnce=true;
            m_arHeader=seiAnnotatedRegions.m_hdr; // copy the settings.
          }
          // Process label updates
          if (seiAnnotatedRegions.m_hdr.m_objectLabelPresentFlag)
          {
            for(auto srcIt=seiAnnotatedRegions.m_annotatedLabels.begin(); srcIt!=seiAnnotatedRegions.m_annotatedLabels.end(); srcIt++)
            {
              const uint32_t labIdx = srcIt->first;
              if (srcIt->second.labelValid)
              {
                m_arLabels[labIdx] = srcIt->second.label;
              }
              else
              {
                m_arLabels.erase(labIdx);
              }
            }
          }

          // Process object updates
          for(auto srcIt=seiAnnotatedRegions.m_annotatedRegions.begin(); srcIt!=seiAnnotatedRegions.m_annotatedRegions.end(); srcIt++)
          {
            uint32_t objIdx = srcIt->first;
            const SEIAnnotatedRegions::AnnotatedRegionObject &src =srcIt->second;

            if (src.objectCancelFlag)
            {
              m_arObjects.erase(objIdx);
            }
            else
            {
              auto destIt = m_arObjects.find(objIdx);

              if (destIt == m_arObjects.end())
              {
                //New object arrived, needs to be appended to the map of tracked objects
                m_arObjects[objIdx] = src;
              }
              else //Existing object, modifications to be done
              {
                SEIAnnotatedRegions::AnnotatedRegionObject &dst=destIt->second;

                if (seiAnnotatedRegions.m_hdr.m_objectLabelPresentFlag && src.objectLabelValid)
                {
                  dst.objectLabelValid=true;
                  dst.objLabelIdx = src.objLabelIdx;
                }
                if (src.boundingBoxValid)
                {
                  dst.boundingBoxTop    = src.boundingBoxTop   ;
                  dst.boundingBoxLeft   = src.boundingBoxLeft  ;
                  dst.boundingBoxWidth  = src.boundingBoxWidth ;
                  dst.boundingBoxHeight = src.boundingBoxHeight;
                  if (seiAnnotatedRegions.m_hdr.m_partialObjectFlagPresentFlag)
                  {
                    dst.partialObjectFlag = src.partialObjectFlag;
                  }
                  if (seiAnnotatedRegions.m_hdr.m_objectConfidenceInfoPresentFlag)
                  {
                    dst.objectConfidence = src.objectConfidence;
                  }
                }
              }
            }
          }
        }
      }

      if (!m_arObjects.empty())
      {
        FILE *fpPersist = fopen(m_annotatedRegionsSEIFileName.c_str(), "ab");
        if (fpPersist == nullptr)
        {
          std::cout << "Not able to open file for writing persist SEI messages" << std::endl;
        }
        else
        {
          fprintf(fpPersist, "\n");
          fprintf(fpPersist, "Number of objects = %d\n", (int)m_arObjects.size());
          for (auto it = m_arObjects.begin(); it != m_arObjects.end(); ++it)
          {
            fprintf(fpPersist, "Object Idx = %d\n",    it->first);
            fprintf(fpPersist, "Object Top = %d\n",    it->second.boundingBoxTop);
            fprintf(fpPersist, "Object Left = %d\n",   it->second.boundingBoxLeft);
            fprintf(fpPersist, "Object Width = %d\n",  it->second.boundingBoxWidth);
            fprintf(fpPersist, "Object Height = %d\n", it->second.boundingBoxHeight);
            if (it->second.objectLabelValid)
            {
              auto labelIt=m_arLabels.find(it->second.objLabelIdx);
              fprintf(fpPersist, "Object Label = %s\n", labelIt!=m_arLabels.end() ? (labelIt->second.c_str()) : "<UNKNOWN>");
            }
            if (m_arHeader.m_partialObjectFlagPresentFlag)
            {
              fprintf(fpPersist, "Object Partial = %d\n", it->second.partialObjectFlag?1:0);
            }
            if (m_arHeader.m_objectConfidenceInfoPresentFlag)
            {
              fprintf(fpPersist, "Object Conf = %d\n", it->second.objectConfidence);
            }
          }
          fclose(fpPersist);
        }
      }
    }
   iterPic++;
  }
}

/** \param nalu Input nalu to check whether its LayerId is within targetDecLayerIdSet
 */
bool DecApp::xIsNaluWithinTargetDecLayerIdSet( const InputNALUnit* nalu ) const
{
  if( !m_targetDecLayerIdSet.size() ) // By default, the set is empty, meaning all LayerIds are allowed
  {
    return true;
  }

  return std::find(m_targetDecLayerIdSet.begin(), m_targetDecLayerIdSet.end(), nalu->m_nuhLayerId)
         != m_targetDecLayerIdSet.end();
}

/** \param nalu Input nalu to check whether its LayerId is within targetOutputLayerIdSet
 */
bool DecApp::xIsNaluWithinTargetOutputLayerIdSet( const InputNALUnit* nalu ) const
{
  if( !m_targetOutputLayerIdSet.size() ) // By default, the set is empty, meaning all LayerIds are allowed
  {
    return true;
  }

  return std::find(m_targetOutputLayerIdSet.begin(), m_targetOutputLayerIdSet.end(), nalu->m_nuhLayerId)
         != m_targetOutputLayerIdSet.end();
}



//! \}