/*
 * Copyright (c) 2021, Alliance for Open Media. All rights reserved
 *
 * This source code is subject to the terms of the BSD 3-Clause Clear License
 * and the Alliance for Open Media Patent License 1.0. If the BSD 3-Clause Clear
 * License was not distributed with this source code in the LICENSE file, you
 * can obtain it at aomedia.org/license/software-license/bsd-3-c-c/.  If the
 * Alliance for Open Media Patent License 1.0 was not distributed with this
 * source code in the PATENTS file, you can obtain it at
 * aomedia.org/license/patent-license/.
 */

#include <cstdio>
#include <cstdlib>
#include <string>
#include "third_party/googletest/src/googletest/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"
#include "test/md5_helper.h"
#include "avm_mem/avm_mem.h"

namespace {
class TileIndependenceTest
    : public ::libavm_test::CodecTestWith3Params<int, int, int>,
      public ::libavm_test::EncoderTest {
 protected:
  TileIndependenceTest()
      : EncoderTest(GET_PARAM(0)), md5_fw_order_(), md5_inv_order_(),
        n_tile_cols_(GET_PARAM(1)), n_tile_rows_(GET_PARAM(2)),
        n_tile_groups_(GET_PARAM(3)) {
    init_flags_ = AVM_CODEC_USE_PSNR;
    avm_codec_dec_cfg_t cfg = avm_codec_dec_cfg_t();
    cfg.w = 352;
    cfg.h = 288;
    cfg.threads = 1;
    fw_dec_ = codec_->CreateDecoder(cfg, 0);
    inv_dec_ = codec_->CreateDecoder(cfg, 0);
    inv_dec_->Control(AV2_INVERT_TILE_DECODE_ORDER, 1);
  }

  virtual ~TileIndependenceTest() {
    delete fw_dec_;
    delete inv_dec_;
  }

  virtual void SetUp() {
    InitializeConfig();
    SetMode(libavm_test::kOnePassGood);
  }

  virtual void PreEncodeFrameHook(libavm_test::VideoSource *video,
                                  libavm_test::Encoder *encoder) {
    if (video->frame() == 0) {
      encoder->Control(AV2E_SET_TILE_COLUMNS, n_tile_cols_);
      encoder->Control(AV2E_SET_TILE_ROWS, n_tile_rows_);
      SetCpuUsed(encoder);
    } else if (video->frame() == 3) {
      encoder->Control(AV2E_SET_NUM_TG, n_tile_groups_);
    }
  }

  virtual void SetCpuUsed(libavm_test::Encoder *encoder) {
    encoder->Control(AVME_SET_CPUUSED, 5);
  }

  void UpdateMD5(::libavm_test::Decoder *dec, const avm_codec_cx_pkt_t *pkt,
                 ::libavm_test::MD5 *md5,
                 ::libavm_test::DxDataIterator *dec_iter) {
    const avm_image_t *img;
    if (pkt->kind == AVM_CODEC_CX_FRAME_PKT) {
      const avm_codec_err_t res = dec->DecodeFrame(
          reinterpret_cast<uint8_t *>(pkt->data.frame.buf), pkt->data.frame.sz);
      if (res != AVM_CODEC_OK) {
        abort_ = true;
        ASSERT_EQ(AVM_CODEC_OK, res);
      }
      img = dec->GetDxData().Next();
    } else {
      assert(dec_iter != NULL);
      img = dec_iter->Peek();
    }
    md5->Add(img);
  }

  virtual void FramePktHook(const avm_codec_cx_pkt_t *pkt,
                            ::libavm_test::DxDataIterator *dec_iter) {
    UpdateMD5(fw_dec_, pkt, &md5_fw_order_, dec_iter);
    UpdateMD5(inv_dec_, pkt, &md5_inv_order_, dec_iter);
  }

  void DoTest() {
    const avm_rational timebase = { 33333333, 1000000000 };
    cfg_.g_timebase = timebase;
    cfg_.rc_target_bitrate = 500;
    cfg_.g_lag_in_frames = 12;
    cfg_.rc_end_usage = AVM_VBR;

    libavm_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288,
                                       timebase.den, timebase.num, 0, 5);
    ASSERT_NO_FATAL_FAILURE(RunLoop(&video));

    const char *md5_fw_str = md5_fw_order_.Get();
    const char *md5_inv_str = md5_inv_order_.Get();
    ASSERT_STREQ(md5_fw_str, md5_inv_str);
  }

  ::libavm_test::MD5 md5_fw_order_, md5_inv_order_;
  ::libavm_test::Decoder *fw_dec_, *inv_dec_;

 private:
  int n_tile_cols_;
  int n_tile_rows_;
  int n_tile_groups_;
};

// run an encode with 2 or 4 tiles, and do the decode both in normal and
// inverted tile ordering. Ensure that the MD5 of the output in both cases
// is identical. If so, tiles are considered independent and the test passes.
TEST_P(TileIndependenceTest, MD5Match) { DoTest(); }

class TileIndependenceTestLarge : public TileIndependenceTest {
  virtual void SetCpuUsed(libavm_test::Encoder *encoder) {
    encoder->Control(AVME_SET_CPUUSED, 1);
  }
};

TEST_P(TileIndependenceTestLarge, MD5Match) { DoTest(); }

AV2_INSTANTIATE_TEST_SUITE(TileIndependenceTest, ::testing::Values(0, 1),
                           ::testing::Values(0, 1), ::testing::Values(1, 2, 4));
AV2_INSTANTIATE_TEST_SUITE(TileIndependenceTestLarge, ::testing::Values(0, 1),
                           ::testing::Values(0, 1), ::testing::Values(1, 2, 4));
}  // namespace
