aboutsummaryrefslogtreecommitdiff
path: root/tests/c2_e2e_test/jni/common.cpp
blob: 50f4cdfb324ca27b3486e4c5cdd714e6da66a15a (plain)
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
// Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// #define LOG_NDEBUG 0
#define LOG_TAG "Common"

#include "common.h"

#include <strings.h>
#include <time.h>

#include <algorithm>
#include <cmath>
#include <numeric>
#include <sstream>

#include <log/log.h>

namespace android {

InputFile::InputFile(std::string file_path) {
    file_ = std::ifstream(file_path);
}

InputFile::InputFile(std::string file_path, std::ios_base::openmode openmode) {
    file_ = std::ifstream(file_path, openmode);
}

bool InputFile::IsValid() const {
    return file_.is_open();
}

size_t InputFile::GetLength() {
    int current_pos = file_.tellg();

    file_.seekg(0, file_.end);
    size_t ret = file_.tellg();

    file_.seekg(current_pos, file_.beg);
    return ret;
}

void InputFile::Rewind() {
    file_.clear();
    file_.seekg(0);
}

CachedInputFileStream::CachedInputFileStream(std::string file_path)
      : InputFile(file_path, std::ifstream::binary) {
    if (IsValid()) {
        data_.resize(GetLength());
        file_.read(data_.data(), GetLength());
    }
}

size_t CachedInputFileStream::Read(char* buffer, size_t size) {
    memcpy(buffer, data_.data() + position_, size);
    position_ += size;
    return size;
}

void CachedInputFileStream::Rewind() {
    position_ = 0;
}

InputFileASCII::InputFileASCII(std::string file_path) : InputFile(file_path) {}

bool InputFileASCII::ReadLine(std::string* line) {
    std::string read_line;
    while (std::getline(file_, read_line)) {
        if (read_line.empty())  // be careful: an empty line might be read
            continue;           //             even if none exist.
        *line = read_line;
        return true;
    }
    return false;  // no more lines
}

IVFWriter::IVFWriter(std::ofstream* output_file, VideoCodecType codec)
      : output_file_(output_file), codec_(codec) {}

bool IVFWriter::WriteHeader(const Size& resolution, uint32_t frame_rate, uint32_t num_frames) {
    constexpr uint16_t kIVFHeaderSize = 32;
    char header[kIVFHeaderSize];

    // Helper lambdas to write 16bit and 32bit data, expects the device to use little endian.
    auto write16 = [&header](int i, uint16_t data) { memcpy(&header[i], &data, sizeof(data)); };
    auto write32 = [&header](int i, uint32_t data) { memcpy(&header[i], &data, sizeof(data)); };

    const char* codec_str;
    switch (codec_) {
    case VideoCodecType::VP8:
        codec_str = "VP80";
        break;
    case VideoCodecType::VP9:
        codec_str = "VP90";
        break;
    default:
        printf("[ERR] Unknown codec: \n");
        return false;
    }

    strcpy(&header[0], "DKIF");  // Bytes 0-3 of an IVF file header always contain 'DKIF' signature.
    constexpr uint16_t kVersion = 0;
    write16(4, kVersion);
    write16(6, kIVFHeaderSize);
    strcpy(&header[8], codec_str);
    write16(12, resolution.width);
    write16(14, resolution.height);
    write32(16, frame_rate);
    write32(20, 1);
    write32(24, num_frames);
    write32(28, 0);  // Reserved.

    output_file_->write(header, kIVFHeaderSize);
    return !output_file_->bad();
}

bool IVFWriter::WriteFrame(const uint8_t* data, uint32_t data_size, uint64_t timestamp) {
    constexpr size_t kIVFFrameHeaderSize = 12;
    char frame_header[kIVFFrameHeaderSize];
    memcpy(&frame_header[0], &data_size, sizeof(data_size));
    memcpy(&frame_header[4], &timestamp, sizeof(timestamp));
    output_file_->write(frame_header, kIVFFrameHeaderSize);
    output_file_->write(reinterpret_cast<const char*>(data), data_size);
    return !output_file_->bad();
}

bool IVFWriter::SetNumFrames(uint32_t num_frames) {
    output_file_->seekp(24);
    output_file_->write(reinterpret_cast<const char*>(&num_frames), sizeof(num_frames));
    return !output_file_->bad();
}

bool OutputFile::Open(const std::string& file_path, VideoCodecType codec) {
    output_file_.open(file_path, std::ofstream::binary);
    if (!output_file_.is_open()) {
        return false;
    }

    if ((codec == VideoCodecType::VP8) || (codec == VideoCodecType::VP9)) {
        ivf_writer_ = std::make_unique<IVFWriter>(&output_file_, codec);
    }
    return true;
}

void OutputFile::Close() {
    if (ivf_writer_) {
        ivf_writer_->SetNumFrames(frame_index_);
        ivf_writer_.reset();
    }
    output_file_.close();
}

bool OutputFile::IsOpen() {
    return output_file_.is_open();
}

// Write the file header.
bool OutputFile::WriteHeader(const Size& resolution, uint32_t frame_rate, uint32_t num_frames) {
    return !ivf_writer_ || ivf_writer_->WriteHeader(resolution, frame_rate, num_frames);
}

bool OutputFile::WriteFrame(uint32_t data_size, const uint8_t* data) {
    if (ivf_writer_) {
        return (ivf_writer_->WriteFrame(data, data_size, frame_index_++));
    } else {
        output_file_.write(reinterpret_cast<const char*>(data), data_size);
        return (output_file_.fail());
    }
}

bool FPSCalculator::RecordFrameTimeDiff() {
    int64_t now_us = GetNowUs();
    if (last_frame_time_us_ != 0) {
        int64_t frame_diff_us = now_us - last_frame_time_us_;
        if (frame_diff_us <= 0) return false;
        frame_time_diffs_us_.push_back(static_cast<double>(frame_diff_us));
    }
    last_frame_time_us_ = now_us;
    return true;
}

// Reference: (https://cs.corp.google.com/android/cts/common/device-side/util/
//             src/com/android/compatibility/common/util/MediaPerfUtils.java)
//            addPerformanceStatsToLog
double FPSCalculator::CalculateFPS() const {
    std::vector<double> moving_avgs = MovingAvgOverSum();
    std::sort(moving_avgs.begin(), moving_avgs.end());

    int index = static_cast<int>(std::round(kRegardedPercentile * (moving_avgs.size() - 1) / 100));
    ALOGD("Frame decode time stats (us): { min=%.4f, regarded=%.4f, "
          "max=%.4f}, window=%.0f",
          moving_avgs[0], moving_avgs[index], moving_avgs[moving_avgs.size() - 1],
          kMovingAvgWindowUs);

    return 1E6 / moving_avgs[index];
}

// Reference: (https://cs.corp.google.com/android/cts/common/device-side/util/
//             src/com/android/compatibility/common/util/MediaUtils.java)
//            movingAverageOverSum
std::vector<double> FPSCalculator::MovingAvgOverSum() const {
    std::vector<double> moving_avgs;

    double sum = std::accumulate(frame_time_diffs_us_.begin(), frame_time_diffs_us_.end(), 0.0);
    int data_size = static_cast<int>(frame_time_diffs_us_.size());
    double avg = sum / data_size;
    if (kMovingAvgWindowUs >= sum) {
        moving_avgs.push_back(avg);
        return moving_avgs;
    }

    int samples = static_cast<int>(std::ceil((sum - kMovingAvgWindowUs) / avg));
    double cumulative_sum = 0;
    int num = 0;
    int bi = 0;
    int ei = 0;
    double space = kMovingAvgWindowUs;
    double foot = 0;

    int ix = 0;
    while (ix < samples) {
        while (ei < data_size && frame_time_diffs_us_[ei] <= space) {
            space -= frame_time_diffs_us_[ei];
            cumulative_sum += frame_time_diffs_us_[ei];
            num++;
            ei++;
        }

        if (num > 0) {
            moving_avgs.push_back(cumulative_sum / num);
        } else if (bi > 0 && foot > space) {
            moving_avgs.push_back(frame_time_diffs_us_[bi - 1]);
        } else if (ei == data_size) {
            break;
        } else {
            moving_avgs.push_back(frame_time_diffs_us_[ei]);
        }

        ix++;
        foot -= avg;
        space += avg;

        while (bi < ei && foot < 0) {
            foot += frame_time_diffs_us_[bi];
            cumulative_sum -= frame_time_diffs_us_[bi];
            num--;
            bi++;
        }
    }
    return moving_avgs;
}

VideoCodecType VideoCodecProfileToType(VideoCodecProfile profile) {
    if (profile >= H264PROFILE_MIN && profile <= H264PROFILE_MAX) return VideoCodecType::H264;
    if (profile >= VP8PROFILE_MIN && profile <= VP8PROFILE_MAX) return VideoCodecType::VP8;
    if (profile >= VP9PROFILE_MIN && profile <= VP9PROFILE_MAX) return VideoCodecType::VP9;
    return VideoCodecType::UNKNOWN;
}

std::vector<std::string> SplitString(const std::string& src, char delim) {
    std::stringstream ss(src);
    std::string item;
    std::vector<std::string> ret;
    while (std::getline(ss, item, delim)) {
        ret.push_back(item);
    }
    return ret;
}

int64_t GetNowUs() {
    struct timespec t;
    t.tv_sec = t.tv_nsec = 0;
    clock_gettime(CLOCK_MONOTONIC, &t);
    int64_t nsecs = static_cast<int64_t>(t.tv_sec) * 1000000000LL + t.tv_nsec;
    return nsecs / 1000ll;
}

const char* GetMimeType(VideoCodecType type) {
    switch (type) {
    case VideoCodecType::H264:
        return "video/avc";
    case VideoCodecType::VP8:
        return "video/x-vnd.on2.vp8";
    case VideoCodecType::VP9:
        return "video/x-vnd.on2.vp9";
    default:  // unknown type
        return nullptr;
    }
}

}  // namespace android