Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / webrtc / modules / video_coding / main / test / quality_modes_test.cc
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 "webrtc/modules/video_coding/main/test/quality_modes_test.h"
12
13 #include <iostream>
14 #include <sstream>
15 #include <string>
16 #include <time.h>
17
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"
28
29 using namespace webrtc;
30
31 int qualityModeTest(const CmdArgs& args)
32 {
33   SimulatedClock clock(0);
34   NullEventFactory event_factory;
35   VideoCodingModule* vcm = VideoCodingModule::Create(&clock, &event_factory);
36   QualityModesTest QMTest(vcm, &clock);
37   QMTest.Perform(args);
38   VideoCodingModule::Destroy(vcm);
39   return 0;
40 }
41
42 QualityModesTest::QualityModesTest(VideoCodingModule* vcm,
43                                    Clock* clock):
44 NormalTest(vcm, clock),
45 _vpm()
46 {
47     //
48 }
49
50 QualityModesTest::~QualityModesTest()
51 {
52     //
53 }
54
55 void
56 QualityModesTest::Setup(const CmdArgs& args)
57 {
58   NormalTest::Setup(args);
59   _inname = args.inputFile;
60   _outname = args.outputFile;
61   fv_outfilename_ = args.fv_outputfile;
62
63   filename_testvideo_ =
64       _inname.substr(_inname.find_last_of("\\/") + 1,_inname.length());
65
66   _encodedName = test::OutputPath() + "encoded_qmtest.yuv";
67
68   //NATIVE/SOURCE VALUES
69   _nativeWidth = args.width;
70   _nativeHeight = args.height;
71   _nativeFrameRate =args.frameRate;
72
73   //TARGET/ENCODER VALUES
74   _width = args.width;
75   _height = args.height;
76   _frameRate = args.frameRate;
77
78   _bitRate = args.bitRate;
79
80   _flagSSIM = true;
81
82   _lengthSourceFrame  = 3*_nativeWidth*_nativeHeight/2;
83
84   if ((_sourceFile = fopen(_inname.c_str(), "rb")) == NULL)
85   {
86     printf("Cannot read file %s.\n", _inname.c_str());
87     exit(1);
88   }
89   if ((_encodedFile = fopen(_encodedName.c_str(), "wb")) == NULL)
90   {
91     printf("Cannot write encoded file.\n");
92     exit(1);
93   }
94   if ((_decodedFile = fopen(_outname.c_str(),  "wb")) == NULL)
95   {
96     printf("Cannot write file %s.\n", _outname.c_str());
97     exit(1);
98   }
99
100   DataLog::CreateLog();
101
102   feature_table_name_ = fv_outfilename_;
103
104   DataLog::AddTable(feature_table_name_);
105
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);
115
116   _log.open((test::OutputPath() + "TestLog.txt").c_str(),
117             std::fstream::out | std::fstream::app);
118 }
119
120 void
121 QualityModesTest::Print()
122 {
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;
147   if (_flagSSIM == 1)
148   {
149     printf("***computing SSIM***\n");
150     I420SSIMFromFiles(_inname.c_str(), _outname.c_str(), _nativeWidth,
151                       _nativeHeight, &ssim);
152     printf("SSIM: %f \n", ssim.average);
153   }
154   (_log) << std::endl;
155
156   printf("\nVCM Quality Modes Test: \n\n%i tests completed\n", vcmMacrosTests);
157   if (vcmMacrosErrors > 0)
158   {
159     printf("%i FAILED\n\n", vcmMacrosErrors);
160   }
161   else
162   {
163     printf("ALL PASSED\n\n");
164   }
165 }
166 void
167 QualityModesTest::Teardown()
168 {
169   _log.close();
170   fclose(_sourceFile);
171   fclose(_decodedFile);
172   fclose(_encodedFile);
173   return;
174 }
175
176 int32_t
177 QualityModesTest::Perform(const CmdArgs& args)
178 {
179   Setup(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};
185
186   uint32_t numChanges = sizeof(updateFrameNum)/sizeof(*updateFrameNum);
187   uint8_t change = 0;// change counter
188
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++)
196   {
197     _vcm->Codec(i, &codec);
198     if(strncmp(codec.plName,"VP8" , 5) == 0)
199     {
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;
205
206       // Will also set and init the desired codec
207       TEST(_vcm->RegisterSendCodec(&codec, 2, 1440) == VCM_OK);
208       i = NumberOfCodecs;
209     }
210   }
211
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);
222
223   //quality modes callback
224   QMTestVideoSettingsCallback QMCallback;
225   QMCallback.RegisterVCM(_vcm);
226   QMCallback.RegisterVPM(_vpm);
227   //_vcm->RegisterVideoQMCallback(&QMCallback);
228
229   ///////////////////////
230   /// Start Test
231   ///////////////////////
232   _vpm->EnableTemporalDecimation(true);
233   _vpm->EnableContentAnalysis(true);
234   _vpm->SetInputFrameResampleMode(kFastRescaling);
235
236   // disabling internal VCM frame dropper
237   _vcm->EnableFrameDropper(false);
238
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);
244
245   SendStatsTest sendStats;
246   sendStats.set_framerate(static_cast<uint32_t>(_frameRate));
247   sendStats.set_bitrate(1000 * _bitRate);
248   _vcm->RegisterSendStatisticsCallback(&sendStats);
249
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);
257
258   //tmp  - disabling VPM frame dropping
259   _vpm->EnableTemporalDecimation(false);
260
261   int32_t ret = 0;
262   _numFramesDroppedVPM = 0;
263
264   do {
265     if (fread(tmpBuffer, 1, _lengthSourceFrame, _sourceFile) > 0) {
266       _frameCnt++;
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);
275
276       _timeStamp +=
277           (uint32_t)(9e4 / static_cast<float>(codec.maxFramerate));
278       sourceFrame.set_timestamp(_timeStamp);
279
280       ret = _vpm->PreprocessFrame(sourceFrame, &decimatedFrame);
281       if (ret  == 1)
282       {
283         printf("VD: frame drop %d \n",_frameCnt);
284         _numFramesDroppedVPM += 1;
285         continue; // frame drop
286       }
287       else if (ret < 0)
288       {
289         printf("Error in PreprocessFrame: %d\n", ret);
290         //exit(1);
291       }
292       // Frame was not re-sampled => use original.
293       if (decimatedFrame == NULL)
294       {
295         decimatedFrame = &sourceFrame;
296       }
297       contentMetrics = _vpm->ContentMetrics();
298       if (contentMetrics == NULL)
299       {
300         printf("error: contentMetrics = NULL\n");
301       }
302
303       // counting only encoding time
304       _encodeTimes[int(sourceFrame.timestamp())] =
305           clock()/(double)CLOCKS_PER_SEC;
306
307       int32_t ret = _vcm->AddVideoFrame(*decimatedFrame, contentMetrics);
308
309       _totalEncodeTime += clock()/(double)CLOCKS_PER_SEC -
310           _encodeTimes[int(sourceFrame.timestamp())];
311
312       if (ret < 0)
313       {
314         printf("Error in AddFrame: %d\n", ret);
315         //exit(1);
316       }
317
318       // Same timestamp value for encode and decode
319       _decodeTimes[int(sourceFrame.timestamp())] =
320           clock()/(double)CLOCKS_PER_SEC;
321       ret = _vcm->Decode();
322
323       _totalDecodeTime += clock()/(double)CLOCKS_PER_SEC -
324           _decodeTimes[int(sourceFrame.timestamp())];
325
326       if (ret < 0)
327       {
328         printf("Error in Decode: %d\n", ret);
329         //exit(1);
330       }
331       if (_vcm->TimeUntilNextProcess() <= 0)
332       {
333         _vcm->Process();
334       }
335       // mimicking setTargetRates - update every 1 sec
336       // this will trigger QMSelect
337       if (_frameCnt%((int)_frameRate) == 0)
338       {
339         _vcm->SetChannelParameters(static_cast<uint32_t>(1000 * _bitRate), 0,
340                                    1);
341       }
342
343       // check for bit rate update
344       if (change < numChanges && _frameCnt == updateFrameNum[change])
345       {
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);
352         change++;
353       }
354
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);
363
364       DataLog::InsertCell(feature_table_name_, "width", _nativeHeight);
365       DataLog::InsertCell(feature_table_name_, "height", _nativeWidth);
366
367       DataLog::InsertCell(feature_table_name_, "num pixels",
368                           _nativeHeight * _nativeWidth);
369
370       DataLog::InsertCell(feature_table_name_, "frame rate", _nativeFrameRate);
371       DataLog::NextRow(feature_table_name_);
372
373       static_cast<SimulatedClock*>(_clock)->AdvanceTimeMilliseconds(
374           1000 / _nativeFrameRate);
375   }
376
377   } while (feof(_sourceFile) == 0);
378   _decodeCallback.WriteEnd(_frameCnt);
379
380
381   double endTime = clock()/(double)CLOCKS_PER_SEC;
382   _testTotalTime = endTime - startTime;
383   _sumEncBytes = _encodeCompleteCallback.EncodedBytes();
384
385   delete tmpBuffer;
386   delete waitEvent;
387   _vpm->Reset();
388   Teardown();
389   Print();
390   VideoProcessingModule::Destroy(_vpm);
391   return 0;
392 }
393
394 // implementing callback to be called from
395 // VCM to update VPM of frame rate and size
396 QMTestVideoSettingsCallback::QMTestVideoSettingsCallback():
397 _vpm(NULL),
398 _vcm(NULL)
399 {
400   //
401 }
402
403 void
404 QMTestVideoSettingsCallback::RegisterVPM(VideoProcessingModule *vpm)
405 {
406   _vpm = vpm;
407 }
408 void
409 QMTestVideoSettingsCallback::RegisterVCM(VideoCodingModule *vcm)
410 {
411   _vcm = vcm;
412 }
413
414 bool
415 QMTestVideoSettingsCallback::Updated()
416 {
417   if (_updated)
418   {
419     _updated = false;
420     return true;
421   }
422   return false;
423 }
424
425 int32_t
426 QMTestVideoSettingsCallback::SetVideoQMSettings(const uint32_t frameRate,
427                                                 const uint32_t width,
428                                                 const uint32_t height)
429 {
430   int32_t retVal = 0;
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?
434   if (!retVal)
435   {
436     // first get current settings
437     VideoCodec currentCodec;
438     _vcm->SendCodec(&currentCodec);
439     // now set new values:
440     currentCodec.height = (uint16_t)height;
441     currentCodec.width = (uint16_t)width;
442     currentCodec.maxFramerate = (uint8_t)frameRate;
443
444     // re-register encoder
445     retVal = _vcm->RegisterSendCodec(&currentCodec, 2, 1440);
446     _updated = true;
447   }
448
449   return retVal;
450 }
451
452 // Decoded Frame Callback Implementation
453 VCMQMDecodeCompleCallback::VCMQMDecodeCompleCallback(
454     FILE* decodedFile, int frame_rate, std::string feature_table_name):
455 _decodedFile(decodedFile),
456 _decodedBytes(0),
457 //_test(test),
458 _origWidth(0),
459 _origHeight(0),
460 _decWidth(0),
461 _decHeight(0),
462 //_interpolator(NULL),
463 _decBuffer(NULL),
464 _frameCnt(0),
465 frame_rate_(frame_rate),
466 frames_cnt_since_drop_(0),
467 feature_table_name_(feature_table_name)
468 {
469     //
470 }
471
472 VCMQMDecodeCompleCallback::~VCMQMDecodeCompleCallback()
473  {
474 //     if (_interpolator != NULL)
475 //     {
476 //         deleteInterpolator(_interpolator);
477 //         _interpolator = NULL;
478 //     }
479    if (_decBuffer != NULL)
480    {
481      delete [] _decBuffer;
482      _decBuffer = NULL;
483    }
484  }
485
486 int32_t
487 VCMQMDecodeCompleCallback::FrameToRender(I420VideoFrame& videoFrame)
488 {
489   ++frames_cnt_since_drop_;
490
491   // When receiving the first coded frame the last_frame variable is not set
492   if (last_frame_.IsZeroSize()) {
493     last_frame_.CopyFrame(videoFrame);
494   }
495
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_));
500
501   // If so...put the last frames into the encoded stream to make up for the
502   // skipped frame(s)
503   while (num_frames_skipped > 0) {
504     PrintI420VideoFrame(last_frame_, _decodedFile);
505     _frameCnt++;
506     --num_frames_skipped;
507     frames_cnt_since_drop_ = 1; // Reset counter
508
509   }
510
511   DataLog::InsertCell(
512         feature_table_name_,"num frames since drop",frames_cnt_since_drop_);
513
514   if (_origWidth == videoFrame.width() && _origHeight == videoFrame.height())
515   {
516     if (PrintI420VideoFrame(videoFrame, _decodedFile) < 0) {
517       return -1;
518     }
519     _frameCnt++;
520     // no need for interpolator and decBuffer
521     if (_decBuffer != NULL)
522     {
523       delete [] _decBuffer;
524       _decBuffer = NULL;
525     }
526     _decWidth = 0;
527     _decHeight = 0;
528   }
529   else
530   {
531     // TODO(mikhal): Add support for scaling.
532     return -1;
533   }
534
535   _decodedBytes += CalcBufferSize(kI420, videoFrame.width(),
536                                   videoFrame.height());
537   videoFrame.SwapFrame(&last_frame_);
538   return VCM_OK;
539 }
540
541 int32_t VCMQMDecodeCompleCallback::DecodedBytes()
542 {
543   return _decodedBytes;
544 }
545
546 void VCMQMDecodeCompleCallback::SetOriginalFrameDimensions(int32_t width,
547                                                            int32_t height)
548 {
549   _origWidth = width;
550   _origHeight = height;
551 }
552
553 int32_t VCMQMDecodeCompleCallback::buildInterpolator()
554 {
555   uint32_t decFrameLength  = _origWidth*_origHeight*3 >> 1;
556   if (_decBuffer != NULL)
557   {
558     delete [] _decBuffer;
559   }
560   _decBuffer = new uint8_t[decFrameLength];
561   if (_decBuffer == NULL)
562   {
563     return -1;
564   }
565   return 0;
566 }
567
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)
574 {
575   int num_missing_frames = input_frame_count - _frameCnt;
576
577   for (int n = num_missing_frames; n > 0; --n) {
578     PrintI420VideoFrame(last_frame_, _decodedFile);
579     _frameCnt++;
580   }
581 }