1/*
2 *  Copyright (c) 2012 The WebM project authors. All Rights Reserved.
3 *
4 *  Use of this source code is governed by a BSD-style license
5 *  that can be found in the LICENSE file in the root of the source
6 *  tree. An additional intellectual property rights grant can be found
7 *  in the file PATENTS.  All contributing project authors may
8 *  be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include <math.h>
12#include <stdlib.h>
13#include <string.h>
14
15#include "third_party/googletest/src/include/gtest/gtest.h"
16
17#include "vp9/decoder/vp9_reader.h"
18#include "vp9/encoder/vp9_writer.h"
19
20#include "test/acm_random.h"
21#include "vpx/vpx_integer.h"
22
23using libvpx_test::ACMRandom;
24
25namespace {
26const int num_tests = 10;
27}  // namespace
28
29TEST(VP9, TestBitIO) {
30  ACMRandom rnd(ACMRandom::DeterministicSeed());
31  for (int n = 0; n < num_tests; ++n) {
32    for (int method = 0; method <= 7; ++method) {   // we generate various proba
33      const int kBitsToTest = 1000;
34      uint8_t probas[kBitsToTest];
35
36      for (int i = 0; i < kBitsToTest; ++i) {
37        const int parity = i & 1;
38        probas[i] =
39          (method == 0) ? 0 : (method == 1) ? 255 :
40          (method == 2) ? 128 :
41          (method == 3) ? rnd.Rand8() :
42          (method == 4) ? (parity ? 0 : 255) :
43            // alternate between low and high proba:
44            (method == 5) ? (parity ? rnd(128) : 255 - rnd(128)) :
45            (method == 6) ?
46            (parity ? rnd(64) : 255 - rnd(64)) :
47            (parity ? rnd(32) : 255 - rnd(32));
48      }
49      for (int bit_method = 0; bit_method <= 3; ++bit_method) {
50        const int random_seed = 6432;
51        const int kBufferSize = 10000;
52        ACMRandom bit_rnd(random_seed);
53        vp9_writer bw;
54        uint8_t bw_buffer[kBufferSize];
55        vp9_start_encode(&bw, bw_buffer);
56
57        int bit = (bit_method == 0) ? 0 : (bit_method == 1) ? 1 : 0;
58        for (int i = 0; i < kBitsToTest; ++i) {
59          if (bit_method == 2) {
60            bit = (i & 1);
61          } else if (bit_method == 3) {
62            bit = bit_rnd(2);
63          }
64          vp9_write(&bw, bit, static_cast<int>(probas[i]));
65        }
66
67        vp9_stop_encode(&bw);
68
69        // First bit should be zero
70        GTEST_ASSERT_EQ(bw_buffer[0] & 0x80, 0);
71
72        vp9_reader br;
73        vp9_reader_init(&br, bw_buffer, kBufferSize, NULL, NULL);
74        bit_rnd.Reset(random_seed);
75        for (int i = 0; i < kBitsToTest; ++i) {
76          if (bit_method == 2) {
77            bit = (i & 1);
78          } else if (bit_method == 3) {
79            bit = bit_rnd(2);
80          }
81          GTEST_ASSERT_EQ(vp9_read(&br, probas[i]), bit)
82              << "pos: " << i << " / " << kBitsToTest
83              << " bit_method: " << bit_method
84              << " method: " << method;
85        }
86      }
87    }
88  }
89}
90