BlueGit

ict rusty-teams

Files

rusty-teams / vendor / webrtc-sys / test / benchmark.cc

benchmark.cc

benchmark.cc 13.7 KiB Download Raw
1/*
2 * Copyright (c) 2012 The WebRTC 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 "benchmark.h"
12
13#include <cassert>
14#include <iostream>
15#include <sstream>
16#include <vector>
17#if defined(_WIN32)
18#include <windows.h>
19#endif
20
21#include "api/video/i420_buffer.h"
22#include "common_video/libyuv/include/webrtc_libyuv.h"
23#include "fileutils.h"
24#include "modules/video_coding/utility/simulcast_rate_allocator.h"
25#include "rtc_base/event.h"
26#include "video_source.h"
27
28#define SSIM_CALC 0 // by default, don't compute SSIM
29
30using namespace webrtc;
31
32#define EXPECT_EQ (a, b)
33
34FrameQueueTuple::~FrameQueueTuple() {
35 if (_codecSpecificInfo != NULL) {
36 delete _codecSpecificInfo;
37 }
38 if (_frame != NULL) {
39 delete _frame;
40 }
41}
42
43void FrameQueue::PushFrame(VideoFrame* frame,
44 webrtc::CodecSpecificInfo* codecSpecificInfo) {
45 webrtc::MutexLock cs(&_queueRWLock);
46 _frameBufferQueue.push(new FrameQueueTuple(frame, codecSpecificInfo));
47}
48
49FrameQueueTuple* FrameQueue::PopFrame() {
50 webrtc::MutexLock cs(&_queueRWLock);
51 if (_frameBufferQueue.empty()) {
52 return NULL;
53 }
54 FrameQueueTuple* tuple = _frameBufferQueue.front();
55 _frameBufferQueue.pop();
56 return tuple;
57}
58
59bool FrameQueue::Empty() {
60 webrtc::MutexLock cs(&_queueRWLock);
61 return _frameBufferQueue.empty();
62}
63
64uint32_t VideoEncodeCompleteCallback::EncodedBytes() {
65 return _encodedBytes;
66}
67
68webrtc::EncodedImageCallback::Result
69VideoEncodeCompleteCallback::OnEncodedImage(
70 const webrtc::EncodedImage& encodedImage,
71 const webrtc::CodecSpecificInfo* codecSpecificInfo) {
72 _test.UpdateEncodedBytes(encodedImage.GetEncodedData()->size());
73 _encodedBytes += encodedImage.GetEncodedData()->size();
74
75 if (_encodedFile != NULL) {
76 if (fwrite(encodedImage.GetEncodedData()->data(), 1,
77 encodedImage.GetEncodedData()->size(),
78 _encodedFile) != encodedImage.GetEncodedData()->size()) {
79 fprintf(stderr, "Error writing to encoded file %s\n",
80 _test._outname.c_str());
81 }
82 }
83
84 return webrtc::EncodedImageCallback::Result(
85 webrtc::EncodedImageCallback::Result::OK);
86}
87
88Benchmark::Benchmark()
89 : _resultsFileName(webrtc::test::OutputPath() + "benchmark.txt"),
90 _codecName("Default"),
91 _env(webrtc::CreateEnvironment()) {}
92
93Benchmark::Benchmark(std::string name, std::string description)
94 : _name(name),
95 _description(description),
96 _resultsFileName(webrtc::test::OutputPath() + "benchmark.txt"),
97 _codecName("Default"),
98 _env(webrtc::CreateEnvironment()) {}
99
100Benchmark::Benchmark(std::string name,
101 std::string description,
102 std::string resultsFileName,
103 std::string codecName)
104 : _name(name),
105 _description(description),
106 _resultsFileName(resultsFileName),
107 _codecName(codecName),
108 _cpu(webrtc::CpuWrapper::CreateCpu()),
109 _env(webrtc::CreateEnvironment()) {}
110
111void Benchmark::Perform() {
112 std::vector<const VideoSource*> sources;
113 std::vector<const VideoSource*>::iterator it;
114
115 // Configuration --------------------------
116 sources.push_back(new const VideoSource(
117 webrtc::test::ProjectRootPath() + "resources/FourPeople_1280x720_30.yuv",
118 kWHD));
119 //sources.push_back(
120 // new const VideoSource(webrtc::test::ProjectRootPath() +
121 // "resources/Big_Buck_Bunny_1920x1080_30.yuv",
122 // kWFullHD));
123
124 const VideoSize size[] = {kWHD};
125 const int frameRate[] = {30};
126 // Specifies the framerates for which to perform a speed test.
127 const bool speedTestMask[] = {true};
128 const int bitRate[] = {500, 1000, 2000, 3000, 4000};
129 // Determines the number of iterations to perform to arrive at the speed
130 // result.
131 enum { kSpeedTestIterations = 8 };
132 // ----------------------------------------
133
134 const int nFrameRates = sizeof(frameRate) / sizeof(*frameRate);
135 assert(sizeof(speedTestMask) / sizeof(*speedTestMask) == nFrameRates);
136 const int nBitrates = sizeof(bitRate) / sizeof(*bitRate);
137 int testIterations = 1;
138
139 double fps[nBitrates];
140 uint32_t cpuUsage[nBitrates];
141 double totalEncodeTime[nBitrates];
142 double totalDecodeTime[nBitrates];
143
144 _results.open(_resultsFileName.c_str(), std::fstream::out);
145 _results << GetMagicStr() << std::endl;
146 _results << _codecName << std::endl;
147
148 for (it = sources.begin(); it < sources.end(); it++) {
149 int i = 0;
150 for (int j = 0; j < nFrameRates; j++) {
151 _target = *it;
152 _inname = (*it)->GetFileName();
153 std::cout << (*it)->GetName() << ", "
154 << VideoSource::GetSizeString(size[i]) << ", " << frameRate[j]
155 << " fps" << ", " << _name << std::endl;
156 _results << (*it)->GetName() << "," << VideoSource::GetSizeString(size[i])
157 << "," << frameRate[j] << " fps" << ", " << _name << std::endl
158 << "Bitrate [kbps]";
159
160 if (speedTestMask[j]) {
161 testIterations = kSpeedTestIterations;
162 } else {
163 testIterations = 1;
164 }
165
166 for (int k = 0; k < nBitrates; k++) {
167 _bitRate = (bitRate[k]);
168 double avgFps = 0.0;
169 uint32_t currCpuUsage = 0;
170 totalEncodeTime[k] = 0;
171
172 std::cout << "TargetBitrate [kbps]:" << " " << _bitRate << std::endl;
173
174 for (int l = 0; l < testIterations; l++) {
175 PerformNormalTest();
176 uint32_t cpuUsage = _cpu->CpuUsage();
177 if (cpuUsage > 0) {
178 currCpuUsage += cpuUsage;
179 int coreCount = _cpu->GetNumCores();
180 std::string str = "CPU Usage[%]: cores ";
181 str += std::to_string(coreCount);
182 str += ", usage " + std::to_string(cpuUsage) + "%" +
183 ", Test Iteration: " + std::to_string(l + 1) + "/" +
184 std::to_string(testIterations);
185 std::cout << str << std::flush;
186 for (int i = 0; i < str.length(); ++i) {
187 std::cout << "\b";
188 }
189 }
190 _appendNext = false;
191 avgFps += _framecnt / (_totalEncodeTime);
192 totalEncodeTime[k] += _totalEncodeTime;
193 }
194 avgFps /= testIterations;
195 totalEncodeTime[k] /= testIterations;
196 currCpuUsage /= testIterations;
197
198 double actualBitRate = ActualBitRate(_framecnt) / 1000.0;
199 std::cout << "ActualBitRate [kbps]:" << " " << actualBitRate
200 << std::endl;
201 _results << "," << actualBitRate;
202 fps[k] = avgFps;
203 cpuUsage[k] = currCpuUsage;
204 }
205
206 std::cout << std::endl << "CpuUsage [%]:";
207 _results << std::endl << "CpuUsage [%]";
208 for (int k = 0; k < nBitrates; k++) {
209 std::cout << " " << cpuUsage[k] << "%";
210 _results << "," << cpuUsage[k] << "%";
211 }
212 std::cout << std::endl << "Encode Time[ms]:";
213 _results << std::endl << "Encode Time[ms]";
214 for (int k = 0; k < nBitrates; k++) {
215 std::cout << " " << totalEncodeTime[k];
216 _results << "," << totalEncodeTime[k];
217 }
218
219 if (speedTestMask[j]) {
220 std::cout << std::endl << "Speed [fps]:";
221 _results << std::endl << "Speed [fps]";
222 for (int k = 0; k < nBitrates; k++) {
223 std::cout << " " << static_cast<int>(fps[k] + 0.5);
224 _results << "," << static_cast<int>(fps[k] + 0.5);
225 }
226 }
227 std::cout << std::endl << std::endl;
228 _results << std::endl << std::endl;
229 }
230 i++;
231 delete *it;
232 }
233 _results.close();
234}
235
236void Benchmark::PerformNormalTest() {
237 _encoder = GetNewEncoder(_env);
238 _lengthSourceFrame = _target->GetFrameLength();
239 CodecSettings(_target->GetWidth(), _target->GetHeight(),
240 _target->GetFrameRate(), _bitRate);
241 Setup();
242 std::unique_ptr<webrtc::Event> waitEvent = std::make_unique<webrtc::Event>();
243 //_inputVideoBuffer.VerifyAndAllocate(_lengthSourceFrame);
244 _encoder->InitEncode(&_inst, 4, 1440);
245 CodecSpecific_InitBitrate();
246 //_decoder->InitDecode(&_inst,1);
247
248 FrameQueue frameQueue;
249 VideoEncodeCompleteCallback encCallback(_encodedFile, &frameQueue, *this);
250
251 _encoder->RegisterEncodeCompleteCallback(&encCallback);
252
253 _totalEncodeTime = _totalDecodeTime = 0;
254 _totalEncodePipeTime = _totalDecodePipeTime = 0;
255 bool complete = false;
256 _framecnt = 0;
257 _encFrameCnt = 0;
258 _sumEncBytes = 0;
259 _lengthEncFrame = 0;
260 while (!complete) {
261 complete = Encode();
262 _framecnt++;
263 _encFrameCnt++;
264 /*
265 if (!frameQueue.Empty() || complete) {
266 while (!frameQueue.Empty()) {
267 _frameToDecode = static_cast<FrameQueueTuple*>(frameQueue.PopFrame());
268 int ret = Decode();
269 delete _frameToDecode;
270 _frameToDecode = NULL;
271 if (ret < 0) {
272 fprintf(stderr, "\n\nError in decoder: %d\n\n", ret);
273 exit(EXIT_FAILURE);
274 } else if (ret == 0) {
275 _framecnt++;
276 } else {
277 fprintf(stderr, "\n\nPositive return value from decode!\n\n");
278 }
279 }
280 }*/
281 // waitEvent->Wait(webrtc::TimeDelta::Seconds(5));
282 }
283
284 //_inputVideoBuffer.Free();
285 //_encodedVideoBuffer.Free();
286 //_decodedVideoBuffer.Free();
287
288 Teardown();
289}
290
291void Benchmark::Teardown() {
292 // Use _sourceFile as a check to prevent multiple Teardown() calls.
293 if (_sourceFile == NULL) {
294 return;
295 }
296
297 _encoder->Release();
298
299 fclose(_sourceFile);
300 _sourceFile = NULL;
301
302 delete[] _sourceBuffer;
303 _sourceBuffer = NULL;
304}
305
306void Benchmark::CodecSpecific_InitBitrate() {
307 webrtc::SimulcastRateAllocator init_allocator(_env,_inst);
308
309 if (_bitRate == 0) {
310 VideoBitrateAllocation allocation =
311 init_allocator.Allocate(VideoBitrateAllocationParameters(
312 DataRate::KilobitsPerSec(600), _inst.maxFramerate));
313 _encoder->SetRates(webrtc::VideoEncoder::RateControlParameters(
314 allocation, _inst.maxFramerate));
315 } else {
316 VideoBitrateAllocation allocation =
317 init_allocator.Allocate(VideoBitrateAllocationParameters(
318 DataRate::BitsPerSec(_bitRate), _inst.maxFramerate));
319 _encoder->SetRates(webrtc::VideoEncoder::RateControlParameters(
320 allocation, _inst.maxFramerate));
321 }
322}
323
324bool Benchmark::Encode() {
325 _lengthEncFrame = 0;
326 if (_sourceBuffer == NULL) {
327 _sourceBuffer = new unsigned char[_lengthSourceFrame];
328 }
329 auto size = fread(_sourceBuffer, 1, _lengthSourceFrame, _sourceFile);
330 if (size <= 0) {
331 return true;
332 }
333 // TODO: build video frame from buffer ptr.
334 webrtc::scoped_refptr<webrtc::I420Buffer> buffer(
335 webrtc::I420Buffer::Create(_inst.width, _inst.height));
336
337 buffer->InitializeData();
338
339 memcpy(buffer->MutableDataY(), _sourceBuffer, _lengthSourceFrame);
340
341 webrtc::VideoFrame inputVideoBuffer =
342 webrtc::VideoFrame::Builder()
343 .set_video_frame_buffer(buffer)
344 .set_rtp_timestamp(
345 (unsigned int)(_encFrameCnt * 9e4 / _inst.maxFramerate))
346 .build();
347
348 if (feof(_sourceFile) != 0) {
349 return true;
350 }
351 _encodeCompleteTime = 0;
352 _encodeTimes[inputVideoBuffer.rtp_timestamp()] = tGetTime();
353 std::vector<VideoFrameType> frame_types(1, VideoFrameType::kVideoFrameDelta);
354
355 // check SLI queue
356 _hasReceivedSLI = false;
357 while (!_signalSLI.empty() && _signalSLI.front().delay == 0) {
358 // SLI message has arrived at sender side
359 _hasReceivedSLI = true;
360 _pictureIdSLI = _signalSLI.front().id;
361 _signalSLI.pop_front();
362 }
363 // decrement SLI queue times
364 for (std::list<fbSignal>::iterator it = _signalSLI.begin();
365 it != _signalSLI.end(); it++) {
366 (*it).delay--;
367 }
368
369 // check PLI queue
370 _hasReceivedPLI = false;
371 while (!_signalPLI.empty() && _signalPLI.front().delay == 0) {
372 // PLI message has arrived at sender side
373 _hasReceivedPLI = true;
374 _signalPLI.pop_front();
375 }
376 // decrement PLI queue times
377 for (std::list<fbSignal>::iterator it = _signalPLI.begin();
378 it != _signalPLI.end(); it++) {
379 (*it).delay--;
380 }
381
382 if (_hasReceivedPLI) {
383 // respond to PLI by encoding a key frame
384 frame_types[0] = VideoFrameType::kVideoFrameKey;
385 _hasReceivedPLI = false;
386 _hasReceivedSLI = false; // don't trigger both at once
387 }
388
389 int ret = _encoder->Encode(inputVideoBuffer, &frame_types);
390
391 if (_encodeCompleteTime > 0) {
392 _totalEncodeTime +=
393 _encodeCompleteTime - _encodeTimes[inputVideoBuffer.rtp_timestamp()];
394 } else {
395 _totalEncodeTime += tGetTime() - _encodeTimes[inputVideoBuffer.rtp_timestamp()];
396 }
397 assert(ret >= 0);
398 return false;
399}
400
401webrtc::CodecSpecificInfo* Benchmark::CopyCodecSpecificInfo(
402 const webrtc::CodecSpecificInfo* codecSpecificInfo) const {
403 webrtc::CodecSpecificInfo* info = new webrtc::CodecSpecificInfo;
404 *info = *codecSpecificInfo;
405 return info;
406}
407
408void Benchmark::Setup() {
409 // Use _sourceFile as a check to prevent multiple Setup() calls.
410 if (_sourceFile != NULL) {
411 return;
412 }
413
414 std::stringstream ss;
415 std::string strTestNo;
416 ss << "0";
417 ss >> strTestNo;
418
419 // Check if settings exist. Otherwise use defaults.
420 if (_outname == "") {
421 _outname =
422 webrtc::test::OutputPath() + "out_normaltest" + strTestNo + ".yuv";
423 }
424
425 if (_codecName == "") {
426 _codecName =
427 webrtc::test::OutputPath() + "encoded_normaltest" + strTestNo + ".yuv";
428 }
429
430 if ((_sourceFile = fopen(_inname.c_str(), "rb")) == NULL) {
431 printf("Cannot read file %s.\n", _inname.c_str());
432 exit(1);
433 }
434
435 if ((_encodedFile = fopen(_codecName.c_str(), "wb")) == NULL) {
436 printf("Cannot write encoded file.\n");
437 exit(1);
438 }
439
440 char mode[3] = "wb";
441 if (_appendNext) {
442 strncpy(mode, "ab", 3);
443 }
444
445 // if ((_decodedFile = fopen(_outname.c_str(), mode)) == NULL) {
446 // printf("Cannot write file %s.\n", _outname.c_str());
447 // exit(1);
448 // }
449
450 _appendNext = true;
451}