2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
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.
11 #include "webrtc/modules/video_coding/main/test/quality_modes_test.h"
18 #include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
19 #include "webrtc/modules/video_coding/main/interface/video_coding.h"
20 #include "webrtc/modules/video_coding/main/test/test_callbacks.h"
21 #include "webrtc/modules/video_coding/main/test/test_macros.h"
22 #include "webrtc/modules/video_coding/main/test/test_util.h"
23 #include "webrtc/system_wrappers/interface/clock.h"
24 #include "webrtc/system_wrappers/interface/data_log.h"
25 #include "webrtc/system_wrappers/interface/data_log.h"
26 #include "webrtc/test/testsupport/fileutils.h"
27 #include "webrtc/test/testsupport/metrics/video_metrics.h"
29 using namespace webrtc;
31 int qualityModeTest(const CmdArgs& args)
33 SimulatedClock clock(0);
34 NullEventFactory event_factory;
35 VideoCodingModule* vcm = VideoCodingModule::Create(&clock, &event_factory);
36 QualityModesTest QMTest(vcm, &clock);
38 VideoCodingModule::Destroy(vcm);
42 QualityModesTest::QualityModesTest(VideoCodingModule* vcm,
44 NormalTest(vcm, clock),
50 QualityModesTest::~QualityModesTest()
56 QualityModesTest::Setup(const CmdArgs& args)
58 NormalTest::Setup(args);
59 _inname = args.inputFile;
60 _outname = args.outputFile;
61 fv_outfilename_ = args.fv_outputfile;
64 _inname.substr(_inname.find_last_of("\\/") + 1,_inname.length());
66 _encodedName = test::OutputPath() + "encoded_qmtest.yuv";
68 //NATIVE/SOURCE VALUES
69 _nativeWidth = args.width;
70 _nativeHeight = args.height;
71 _nativeFrameRate =args.frameRate;
73 //TARGET/ENCODER VALUES
75 _height = args.height;
76 _frameRate = args.frameRate;
78 _bitRate = args.bitRate;
82 _lengthSourceFrame = 3*_nativeWidth*_nativeHeight/2;
84 if ((_sourceFile = fopen(_inname.c_str(), "rb")) == NULL)
86 printf("Cannot read file %s.\n", _inname.c_str());
89 if ((_encodedFile = fopen(_encodedName.c_str(), "wb")) == NULL)
91 printf("Cannot write encoded file.\n");
94 if ((_decodedFile = fopen(_outname.c_str(), "wb")) == NULL)
96 printf("Cannot write file %s.\n", _outname.c_str());
100 DataLog::CreateLog();
102 feature_table_name_ = fv_outfilename_;
104 DataLog::AddTable(feature_table_name_);
106 DataLog::AddColumn(feature_table_name_, "motion magnitude", 1);
107 DataLog::AddColumn(feature_table_name_, "spatial prediction error", 1);
108 DataLog::AddColumn(feature_table_name_, "spatial pred err horizontal", 1);
109 DataLog::AddColumn(feature_table_name_, "spatial pred err vertical", 1);
110 DataLog::AddColumn(feature_table_name_, "width", 1);
111 DataLog::AddColumn(feature_table_name_, "height", 1);
112 DataLog::AddColumn(feature_table_name_, "num pixels", 1);
113 DataLog::AddColumn(feature_table_name_, "frame rate", 1);
114 DataLog::AddColumn(feature_table_name_, "num frames since drop", 1);
116 _log.open((test::OutputPath() + "TestLog.txt").c_str(),
117 std::fstream::out | std::fstream::app);
121 QualityModesTest::Print()
123 std::cout << "Quality Modes Test Completed!" << std::endl;
124 (_log) << "Quality Modes Test Completed!" << std::endl;
125 (_log) << "Input file: " << _inname << std::endl;
126 (_log) << "Output file: " << _outname << std::endl;
127 (_log) << "Total run time: " << _testTotalTime << std::endl;
128 printf("Total run time: %f s \n", _testTotalTime);
129 double ActualBitRate = 8.0*( _sumEncBytes / (_frameCnt / _nativeFrameRate));
130 double actualBitRate = ActualBitRate / 1000.0;
131 double avgEncTime = _totalEncodeTime / _frameCnt;
132 double avgDecTime = _totalDecodeTime / _frameCnt;
133 webrtc::test::QualityMetricsResult psnr,ssim;
134 I420PSNRFromFiles(_inname.c_str(), _outname.c_str(), _nativeWidth,
135 _nativeHeight, &psnr);
136 printf("Actual bitrate: %f kbps\n", actualBitRate);
137 printf("Target bitrate: %f kbps\n", _bitRate);
138 ( _log) << "Actual bitrate: " << actualBitRate<< " kbps\tTarget: " <<
139 _bitRate << " kbps" << std::endl;
140 printf("Average encode time: %f s\n", avgEncTime);
141 ( _log) << "Average encode time: " << avgEncTime << " s" << std::endl;
142 printf("Average decode time: %f s\n", avgDecTime);
143 ( _log) << "Average decode time: " << avgDecTime << " s" << std::endl;
144 printf("PSNR: %f \n", psnr.average);
145 printf("**Number of frames dropped in VPM***%d \n",_numFramesDroppedVPM);
146 ( _log) << "PSNR: " << psnr.average << std::endl;
149 printf("***computing SSIM***\n");
150 I420SSIMFromFiles(_inname.c_str(), _outname.c_str(), _nativeWidth,
151 _nativeHeight, &ssim);
152 printf("SSIM: %f \n", ssim.average);
156 printf("\nVCM Quality Modes Test: \n\n%i tests completed\n", vcmMacrosTests);
157 if (vcmMacrosErrors > 0)
159 printf("%i FAILED\n\n", vcmMacrosErrors);
163 printf("ALL PASSED\n\n");
167 QualityModesTest::Teardown()
171 fclose(_decodedFile);
172 fclose(_encodedFile);
177 QualityModesTest::Perform(const CmdArgs& args)
180 // changing bit/frame rate during the test
181 const float bitRateUpdate[] = {1000};
182 const float frameRateUpdate[] = {30};
183 // frame num at which an update will occur
184 const int updateFrameNum[] = {10000};
186 uint32_t numChanges = sizeof(updateFrameNum)/sizeof(*updateFrameNum);
187 uint8_t change = 0;// change counter
189 _vpm = VideoProcessingModule::Create(1);
190 EventWrapper* waitEvent = EventWrapper::Create();
191 VideoCodec codec;//both send and receive
192 _vcm->InitializeReceiver();
193 _vcm->InitializeSender();
194 int32_t NumberOfCodecs = _vcm->NumberOfCodecs();
195 for (int i = 0; i < NumberOfCodecs; i++)
197 _vcm->Codec(i, &codec);
198 if(strncmp(codec.plName,"VP8" , 5) == 0)
200 codec.startBitrate = (int)_bitRate;
201 codec.maxFramerate = (uint8_t) _frameRate;
202 codec.width = (uint16_t)_width;
203 codec.height = (uint16_t)_height;
204 codec.codecSpecific.VP8.frameDroppingOn = false;
206 // Will also set and init the desired codec
207 TEST(_vcm->RegisterSendCodec(&codec, 2, 1440) == VCM_OK);
212 // register a decoder (same codec for decoder and encoder )
213 TEST(_vcm->RegisterReceiveCodec(&codec, 2) == VCM_OK);
214 /* Callback Settings */
215 VCMQMDecodeCompleCallback _decodeCallback(
216 _decodedFile, _nativeFrameRate, feature_table_name_);
217 _vcm->RegisterReceiveCallback(&_decodeCallback);
218 VCMNTEncodeCompleteCallback _encodeCompleteCallback(_encodedFile, *this);
219 _vcm->RegisterTransportCallback(&_encodeCompleteCallback);
220 // encode and decode with the same vcm
221 _encodeCompleteCallback.RegisterReceiverVCM(_vcm);
223 //quality modes callback
224 QMTestVideoSettingsCallback QMCallback;
225 QMCallback.RegisterVCM(_vcm);
226 QMCallback.RegisterVPM(_vpm);
227 //_vcm->RegisterVideoQMCallback(&QMCallback);
229 ///////////////////////
231 ///////////////////////
232 _vpm->EnableTemporalDecimation(true);
233 _vpm->EnableContentAnalysis(true);
234 _vpm->SetInputFrameResampleMode(kFastRescaling);
236 // disabling internal VCM frame dropper
237 _vcm->EnableFrameDropper(false);
239 I420VideoFrame sourceFrame;
240 I420VideoFrame *decimatedFrame = NULL;
241 uint8_t* tmpBuffer = new uint8_t[_lengthSourceFrame];
242 double startTime = clock()/(double)CLOCKS_PER_SEC;
243 _vcm->SetChannelParameters(static_cast<uint32_t>(1000 * _bitRate), 0, 0);
245 SendStatsTest sendStats;
246 sendStats.set_framerate(static_cast<uint32_t>(_frameRate));
247 sendStats.set_bitrate(1000 * _bitRate);
248 _vcm->RegisterSendStatisticsCallback(&sendStats);
250 VideoContentMetrics* contentMetrics = NULL;
251 // setting user frame rate
252 _vpm->SetMaxFramerate((uint32_t)(_nativeFrameRate+ 0.5f));
253 // for starters: keeping native values:
254 _vpm->SetTargetResolution(_width, _height,
255 (uint32_t)(_frameRate+ 0.5f));
256 _decodeCallback.SetOriginalFrameDimensions(_nativeWidth, _nativeHeight);
258 //tmp - disabling VPM frame dropping
259 _vpm->EnableTemporalDecimation(false);
262 _numFramesDroppedVPM = 0;
265 if (fread(tmpBuffer, 1, _lengthSourceFrame, _sourceFile) > 0) {
267 int size_y = _nativeWidth * _nativeHeight;
268 int size_uv = ((_nativeWidth + 1) / 2) * ((_nativeHeight + 1) / 2);
269 sourceFrame.CreateFrame(size_y, tmpBuffer,
270 size_uv, tmpBuffer + size_y,
271 size_uv, tmpBuffer + size_y + size_uv,
272 _nativeWidth, _nativeHeight,
273 _nativeWidth, (_nativeWidth + 1) / 2,
274 (_nativeWidth + 1) / 2);
277 (uint32_t)(9e4 / static_cast<float>(codec.maxFramerate));
278 sourceFrame.set_timestamp(_timeStamp);
280 ret = _vpm->PreprocessFrame(sourceFrame, &decimatedFrame);
283 printf("VD: frame drop %d \n",_frameCnt);
284 _numFramesDroppedVPM += 1;
285 continue; // frame drop
289 printf("Error in PreprocessFrame: %d\n", ret);
292 // Frame was not re-sampled => use original.
293 if (decimatedFrame == NULL)
295 decimatedFrame = &sourceFrame;
297 contentMetrics = _vpm->ContentMetrics();
298 if (contentMetrics == NULL)
300 printf("error: contentMetrics = NULL\n");
303 // counting only encoding time
304 _encodeTimes[int(sourceFrame.timestamp())] =
305 clock()/(double)CLOCKS_PER_SEC;
307 int32_t ret = _vcm->AddVideoFrame(*decimatedFrame, contentMetrics);
309 _totalEncodeTime += clock()/(double)CLOCKS_PER_SEC -
310 _encodeTimes[int(sourceFrame.timestamp())];
314 printf("Error in AddFrame: %d\n", ret);
318 // Same timestamp value for encode and decode
319 _decodeTimes[int(sourceFrame.timestamp())] =
320 clock()/(double)CLOCKS_PER_SEC;
321 ret = _vcm->Decode();
323 _totalDecodeTime += clock()/(double)CLOCKS_PER_SEC -
324 _decodeTimes[int(sourceFrame.timestamp())];
328 printf("Error in Decode: %d\n", ret);
331 if (_vcm->TimeUntilNextProcess() <= 0)
335 // mimicking setTargetRates - update every 1 sec
336 // this will trigger QMSelect
337 if (_frameCnt%((int)_frameRate) == 0)
339 _vcm->SetChannelParameters(static_cast<uint32_t>(1000 * _bitRate), 0,
343 // check for bit rate update
344 if (change < numChanges && _frameCnt == updateFrameNum[change])
346 _bitRate = bitRateUpdate[change];
347 _frameRate = frameRateUpdate[change];
348 codec.startBitrate = (int)_bitRate;
349 codec.maxFramerate = (uint8_t) _frameRate;
350 // Will also set and init the desired codec
351 TEST(_vcm->RegisterSendCodec(&codec, 2, 1440) == VCM_OK);
355 DataLog::InsertCell(feature_table_name_, "motion magnitude",
356 contentMetrics->motion_magnitude);
357 DataLog::InsertCell(feature_table_name_, "spatial prediction error",
358 contentMetrics->spatial_pred_err);
359 DataLog::InsertCell(feature_table_name_, "spatial pred err horizontal",
360 contentMetrics->spatial_pred_err_h);
361 DataLog::InsertCell(feature_table_name_, "spatial pred err vertical",
362 contentMetrics->spatial_pred_err_v);
364 DataLog::InsertCell(feature_table_name_, "width", _nativeHeight);
365 DataLog::InsertCell(feature_table_name_, "height", _nativeWidth);
367 DataLog::InsertCell(feature_table_name_, "num pixels",
368 _nativeHeight * _nativeWidth);
370 DataLog::InsertCell(feature_table_name_, "frame rate", _nativeFrameRate);
371 DataLog::NextRow(feature_table_name_);
373 static_cast<SimulatedClock*>(_clock)->AdvanceTimeMilliseconds(
374 1000 / _nativeFrameRate);
377 } while (feof(_sourceFile) == 0);
378 _decodeCallback.WriteEnd(_frameCnt);
381 double endTime = clock()/(double)CLOCKS_PER_SEC;
382 _testTotalTime = endTime - startTime;
383 _sumEncBytes = _encodeCompleteCallback.EncodedBytes();
390 VideoProcessingModule::Destroy(_vpm);
394 // implementing callback to be called from
395 // VCM to update VPM of frame rate and size
396 QMTestVideoSettingsCallback::QMTestVideoSettingsCallback():
404 QMTestVideoSettingsCallback::RegisterVPM(VideoProcessingModule *vpm)
409 QMTestVideoSettingsCallback::RegisterVCM(VideoCodingModule *vcm)
415 QMTestVideoSettingsCallback::Updated()
426 QMTestVideoSettingsCallback::SetVideoQMSettings(const uint32_t frameRate,
427 const uint32_t width,
428 const uint32_t height)
431 printf("QM updates: W = %d, H = %d, FR = %d, \n", width, height, frameRate);
432 retVal = _vpm->SetTargetResolution(width, height, frameRate);
433 //Initialize codec with new values - is this the best place to do it?
436 // first get current settings
437 VideoCodec currentCodec;
438 _vcm->SendCodec(¤tCodec);
439 // now set new values:
440 currentCodec.height = (uint16_t)height;
441 currentCodec.width = (uint16_t)width;
442 currentCodec.maxFramerate = (uint8_t)frameRate;
444 // re-register encoder
445 retVal = _vcm->RegisterSendCodec(¤tCodec, 2, 1440);
452 // Decoded Frame Callback Implementation
453 VCMQMDecodeCompleCallback::VCMQMDecodeCompleCallback(
454 FILE* decodedFile, int frame_rate, std::string feature_table_name):
455 _decodedFile(decodedFile),
462 //_interpolator(NULL),
465 frame_rate_(frame_rate),
466 frames_cnt_since_drop_(0),
467 feature_table_name_(feature_table_name)
472 VCMQMDecodeCompleCallback::~VCMQMDecodeCompleCallback()
474 // if (_interpolator != NULL)
476 // deleteInterpolator(_interpolator);
477 // _interpolator = NULL;
479 if (_decBuffer != NULL)
481 delete [] _decBuffer;
487 VCMQMDecodeCompleCallback::FrameToRender(I420VideoFrame& videoFrame)
489 ++frames_cnt_since_drop_;
491 // When receiving the first coded frame the last_frame variable is not set
492 if (last_frame_.IsZeroSize()) {
493 last_frame_.CopyFrame(videoFrame);
496 // Check if there were frames skipped.
497 int num_frames_skipped = static_cast<int>( 0.5f +
498 (videoFrame.timestamp() - (last_frame_.timestamp() + (9e4 / frame_rate_))) /
499 (9e4 / frame_rate_));
501 // If so...put the last frames into the encoded stream to make up for the
503 while (num_frames_skipped > 0) {
504 PrintI420VideoFrame(last_frame_, _decodedFile);
506 --num_frames_skipped;
507 frames_cnt_since_drop_ = 1; // Reset counter
512 feature_table_name_,"num frames since drop",frames_cnt_since_drop_);
514 if (_origWidth == videoFrame.width() && _origHeight == videoFrame.height())
516 if (PrintI420VideoFrame(videoFrame, _decodedFile) < 0) {
520 // no need for interpolator and decBuffer
521 if (_decBuffer != NULL)
523 delete [] _decBuffer;
531 // TODO(mikhal): Add support for scaling.
535 _decodedBytes += CalcBufferSize(kI420, videoFrame.width(),
536 videoFrame.height());
537 videoFrame.SwapFrame(&last_frame_);
541 int32_t VCMQMDecodeCompleCallback::DecodedBytes()
543 return _decodedBytes;
546 void VCMQMDecodeCompleCallback::SetOriginalFrameDimensions(int32_t width,
550 _origHeight = height;
553 int32_t VCMQMDecodeCompleCallback::buildInterpolator()
555 uint32_t decFrameLength = _origWidth*_origHeight*3 >> 1;
556 if (_decBuffer != NULL)
558 delete [] _decBuffer;
560 _decBuffer = new uint8_t[decFrameLength];
561 if (_decBuffer == NULL)
568 // This function checks if the total number of frames processed in the encoding
569 // process is the same as the number of frames rendered. If not, the last
570 // frame (or several consecutive frames from the end) must have been dropped. If
571 // this is the case, the last frame is repeated so that there are as many
572 // frames rendered as there are number of frames encoded.
573 void VCMQMDecodeCompleCallback::WriteEnd(int input_frame_count)
575 int num_missing_frames = input_frame_count - _frameCnt;
577 for (int n = num_missing_frames; n > 0; --n) {
578 PrintI420VideoFrame(last_frame_, _decodedFile);