]> rtime.felk.cvut.cz Git - opencv.git/blob - opencv/tests/cxts/cxts.cpp
improved robustness of the performance tests; added setTrackbarPos & getTrackbarPos...
[opencv.git] / opencv / tests / cxts / cxts.cpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
5 //  By downloading, copying, installing or using the software you agree to this license.
6 //  If you do not agree to this license, do not download, install,
7 //  copy or use the software.
8 //
9 //
10 //                        Intel License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
15 //
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
18 //
19 //   * Redistribution's of source code must retain the above copyright notice,
20 //     this list of conditions and the following disclaimer.
21 //
22 //   * Redistribution's in binary form must reproduce the above copyright notice,
23 //     this list of conditions and the following disclaimer in the documentation
24 //     and/or other materials provided with the distribution.
25 //
26 //   * The name of Intel Corporation may not be used to endorse or promote products
27 //     derived from this software without specific prior written permission.
28 //
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // warranties of merchantability and fitness for a particular purpose are disclaimed.
32 // In no event shall the Intel Corporation or contributors be liable for any direct,
33 // indirect, incidental, special, exemplary, or consequential damages
34 // (including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort (including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
39 //
40 //M*/
41
42 #include "_cxts.h"
43 #include <ctype.h>
44 #include <stdarg.h>
45 #include <fcntl.h>
46 #include <time.h>
47 #if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64
48 #include <io.h>
49 #else
50 #include <unistd.h>
51 #endif
52
53 CvTest* CvTest::first = 0;
54 CvTest* CvTest::last = 0;
55 int CvTest::test_count = 0;
56
57 /*****************************************************************************************\
58 *                                Exception and memory handlers                            *
59 \*****************************************************************************************/
60
61 // a few platform-dependent declarations
62
63 #define CV_TS_NORMAL 0
64 #define CV_TS_BLUE   1
65 #define CV_TS_GREEN  2
66 #define CV_TS_RED    4
67
68 #if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64
69 #include <windows.h>
70
71 #ifdef _MSC_VER
72 #include <eh.h>
73 #endif
74
75 #ifdef _MSC_VER
76 static void cv_seh_translator( unsigned int /*u*/, EXCEPTION_POINTERS* pExp )
77 {
78     int code = CvTS::FAIL_EXCEPTION;
79     switch( pExp->ExceptionRecord->ExceptionCode )
80     {
81     case EXCEPTION_ACCESS_VIOLATION:
82     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
83     case EXCEPTION_DATATYPE_MISALIGNMENT:
84     case EXCEPTION_FLT_STACK_CHECK:
85     case EXCEPTION_STACK_OVERFLOW:
86     case EXCEPTION_IN_PAGE_ERROR:
87         code = CvTS::FAIL_MEMORY_EXCEPTION;
88         break;
89     case EXCEPTION_FLT_DENORMAL_OPERAND:
90     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
91     case EXCEPTION_FLT_INEXACT_RESULT:
92     case EXCEPTION_FLT_INVALID_OPERATION:
93     case EXCEPTION_FLT_OVERFLOW:
94     case EXCEPTION_FLT_UNDERFLOW:
95     case EXCEPTION_INT_DIVIDE_BY_ZERO:
96     case EXCEPTION_INT_OVERFLOW:
97         code = CvTS::FAIL_ARITHM_EXCEPTION;
98         break;
99     case EXCEPTION_BREAKPOINT:
100     case EXCEPTION_ILLEGAL_INSTRUCTION:
101     case EXCEPTION_INVALID_DISPOSITION:
102     case EXCEPTION_NONCONTINUABLE_EXCEPTION:
103     case EXCEPTION_PRIV_INSTRUCTION:
104     case EXCEPTION_SINGLE_STEP:
105         code = CvTS::FAIL_EXCEPTION;
106     }
107     throw code;
108 }
109 #endif
110
111 #define CV_TS_TRY_BLOCK_BEGIN                   \
112     try {
113
114 #define CV_TS_TRY_BLOCK_END                     \
115     } catch( int _code ) {                      \
116         ts->set_failed_test_info( _code );      \
117     }
118
119 static void change_color( int color )
120 {
121     static int normal_attributes = -1;
122     HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
123     fflush(stdout);
124
125     if( normal_attributes < 0 )
126     {
127         CONSOLE_SCREEN_BUFFER_INFO info;
128         GetConsoleScreenBufferInfo( hstdout, &info );
129         normal_attributes = info.wAttributes;
130     }
131
132     SetConsoleTextAttribute( hstdout,
133         (WORD)(color == CV_TS_NORMAL ? normal_attributes :
134         ((color & CV_TS_BLUE ? FOREGROUND_BLUE : 0)|
135         (color & CV_TS_GREEN ? FOREGROUND_GREEN : 0)|
136         (color & CV_TS_RED ? FOREGROUND_RED : 0)|FOREGROUND_INTENSITY)) );
137 }
138
139 #else
140
141 #include <signal.h>
142
143 static const int cv_ts_sig_id[] = { SIGSEGV, SIGBUS, SIGFPE, SIGILL, -1 };
144
145 static jmp_buf cv_ts_jmp_mark;
146
147 void cv_signal_handler( int sig_code )
148 {
149     int code = CvTS::FAIL_EXCEPTION;
150     switch( sig_code )
151     {
152     case SIGFPE:
153         code = CvTS::FAIL_ARITHM_EXCEPTION;
154         break;
155     case SIGSEGV:
156     case SIGBUS:
157         code = CvTS::FAIL_ARITHM_EXCEPTION;
158         break;
159     case SIGILL:
160         code = CvTS::FAIL_EXCEPTION;
161     }
162
163     longjmp( cv_ts_jmp_mark, code );
164 }
165
166 #define CV_TS_TRY_BLOCK_BEGIN                   \
167     {                                           \
168         int _code = setjmp( cv_ts_jmp_mark );   \
169         if( !_code ) {
170
171 #define CV_TS_TRY_BLOCK_END                     \
172         }                                       \
173         else  {                                 \
174             ts->set_failed_test_info( _code );  \
175         }                                       \
176     }
177
178 static void change_color( int color )
179 {
180     static const uchar ansi_tab[] = { 30, 34, 32, 36, 31, 35, 33, 37 };
181     char buf[16];
182     int code = 0;
183     fflush( stdout );
184     if( color != CV_TS_NORMAL )
185         code = ansi_tab[color & (CV_TS_BLUE|CV_TS_GREEN|CV_TS_RED)];
186     sprintf( buf, "\x1b[%dm", code );
187     fputs( buf, stdout );
188 }
189
190 #endif
191
192 /***************************** memory manager *****************************/
193
194 typedef struct CvTestAllocBlock
195 {
196     struct CvTestAllocBlock* prev;
197     struct CvTestAllocBlock* next;
198     char* origin;
199     char* data;
200     size_t size;
201     int index;
202 }
203 CvTestAllocBlock;
204
205
206 class CvTestMemoryManager
207 {
208 public:
209     CvTestMemoryManager( CvTS* ts );
210     virtual ~CvTestMemoryManager();
211
212     virtual void clear_and_check( int min_index = -1 );
213     virtual void start_tracking( int index_to_stop_at=-1 );
214     virtual void stop_tracking_and_check();
215     int get_alloc_index() { return index; }
216
217     static void* alloc_proxy( size_t size, void* userdata );
218     static int free_proxy( void* ptr, void* userdata );
219
220 protected:
221     virtual void* alloc( size_t size );
222     virtual int free( void* ptr );
223     virtual int free_block( CvTestAllocBlock* block );
224
225     int index;
226     int track_blocks;
227     int show_msg_box;
228     int index_to_stop_at;
229     const char* guard_pattern;
230     int guard_size;
231     int block_align;
232     enum { MAX_MARKS = 1024 };
233     int marks[MAX_MARKS];
234     int marks_top;
235     CvTS* ts;
236     CvTestAllocBlock* first;
237     CvTestAllocBlock* last;
238 };
239
240
241 void* CvTestMemoryManager::alloc_proxy( size_t size, void* userdata )
242 {
243     return ((CvTestMemoryManager*)userdata)->alloc( size );
244 }
245
246
247 int CvTestMemoryManager::free_proxy( void* ptr, void* userdata )
248 {
249     return ((CvTestMemoryManager*)userdata)->free( ptr );
250 }
251
252
253 CvTestMemoryManager::CvTestMemoryManager( CvTS* _test_system )
254 {
255     ts = _test_system;
256     guard_pattern = "THIS IS A GUARD PATTERN!";
257     guard_size = (int)strlen(guard_pattern);
258     block_align = CV_MALLOC_ALIGN;
259     track_blocks = 0;
260     marks_top = 0;
261     first = last = 0;
262     index = 0;
263     index_to_stop_at = -1;
264     show_msg_box = 1;
265 }
266
267
268 CvTestMemoryManager::~CvTestMemoryManager()
269 {
270     clear_and_check();
271 }
272
273
274 void CvTestMemoryManager::clear_and_check( int min_index )
275 {
276     int alloc_index = -1;
277     CvTestAllocBlock* block;
278     int leak_size = 0, leak_block_count = 0, mem_size = 0;
279     void* mem_addr = 0;
280
281     while( marks_top > 0 && marks[marks_top - 1] >= min_index )
282         marks_top--;
283
284     for( block = last; block != 0; )
285     {
286         CvTestAllocBlock* prev = block->prev;
287         if( block->index < min_index )
288             break;
289         leak_size += (int)block->size;
290         leak_block_count++;
291         alloc_index = block->index;
292         mem_addr = block->data;
293         mem_size = (int)block->size;
294         free_block( block );
295         block = prev;
296     }
297     track_blocks--;
298     if( leak_block_count > 0 )
299     {
300         ts->set_failed_test_info( CvTS::FAIL_MEMORY_LEAK, alloc_index );
301         ts->printf( CvTS::LOG, "Memory leaks: %u blocks, %u bytes total\n"
302                     "%s leaked block: %p, %u bytes\n",
303                     leak_block_count, leak_size, leak_block_count > 1 ? "The first" : "The",
304                     mem_addr, mem_size );
305     }
306
307     index = block ? block->index + 1 : 0;
308 }
309
310
311 void CvTestMemoryManager::start_tracking( int _index_to_stop_at )
312 {
313     track_blocks--;
314     marks[marks_top++] = index;
315     assert( marks_top <= MAX_MARKS );
316     track_blocks+=2;
317     index_to_stop_at = _index_to_stop_at >= index ? _index_to_stop_at : -1;
318 }
319
320
321 void CvTestMemoryManager::stop_tracking_and_check()
322 {
323     if( marks_top > 0 )
324     {
325         int min_index = marks[--marks_top];
326         clear_and_check( min_index );
327     }
328 }
329
330
331 int CvTestMemoryManager::free_block( CvTestAllocBlock* block )
332 {
333     int code = 0;
334     char* data = block->data;
335
336     if( block->origin == 0 || ((size_t)block->origin & (sizeof(double)-1)) != 0 )
337         code = CvTS::FAIL_MEMORY_CORRUPTION_BEGIN;
338
339     if( memcmp( data - guard_size, guard_pattern, guard_size ) != 0 )
340         code = CvTS::FAIL_MEMORY_CORRUPTION_BEGIN;
341     else if( memcmp( data + block->size, guard_pattern, guard_size ) != 0 )
342         code = CvTS::FAIL_MEMORY_CORRUPTION_END;
343
344     if( code >= 0 )
345     {
346         if( block->prev )
347             block->prev->next = block->next;
348         else if( first == block )
349             first = block->next;
350
351         if( block->next )
352             block->next->prev = block->prev;
353         else if( last == block )
354             last = block->prev;
355
356         free( block->origin );
357     }
358     else
359     {
360         ts->set_failed_test_info( code, block->index );
361         ts->printf( CvTS::LOG, "Corrupted block (%s): %p, %u bytes\n",
362                     code == CvTS::FAIL_MEMORY_CORRUPTION_BEGIN ? "beginning" : "end",
363                     block->data, block->size );
364     }
365
366     return code;
367 }
368
369
370 void* CvTestMemoryManager::alloc( size_t size )
371 {
372     char* data;
373     CvTestAllocBlock* block;
374     size_t new_size = sizeof(*block) + size + guard_size*2 + block_align + sizeof(size_t)*2;
375     char* ptr = (char*)malloc( new_size );
376
377     if( !ptr )
378         return 0;
379
380     data = (char*)cvAlignPtr( ptr + sizeof(size_t) + sizeof(*block) + guard_size, block_align );
381     block = (CvTestAllocBlock*)cvAlignPtr( data - guard_size -
382             sizeof(size_t) - sizeof(*block), sizeof(size_t) );
383     block->origin = ptr;
384     block->data = data;
385     block->size = 0;
386     block->index = -1;
387     block->next = block->prev = 0;
388     memcpy( data - guard_size, guard_pattern, guard_size );
389     memcpy( data + size, guard_pattern, guard_size );
390
391     if( track_blocks > 0 )
392     {
393         track_blocks--;
394         block->size = size;
395
396         if( index == index_to_stop_at )
397         {
398             if( show_msg_box )
399             {
400         #if defined WIN32 || defined _WIN32
401                 MessageBox( NULL, "The block that is corrupted and/or not deallocated has been just allocated\n"
402                             "Press Ok to start debugging", "Memory Manager", MB_ICONERROR|MB_OK|MB_SYSTEMMODAL );
403         #endif
404             }
405             CV_DBG_BREAK();
406         }
407
408         block->index = index++;
409
410         block->prev = last;
411         block->next = 0;
412         if( last )
413             last = last->next = block;
414         else
415             first = last = block;
416
417         track_blocks++;
418     }
419
420     return data;
421 }
422
423
424 int CvTestMemoryManager::free( void* ptr )
425 {
426     char* data = (char*)ptr;
427     CvTestAllocBlock* block = (CvTestAllocBlock*)
428         cvAlignPtr( data - guard_size - sizeof(size_t) - sizeof(*block), sizeof(size_t) );
429
430     int code = free_block( block );
431     if( code < 0 && ts->is_debug_mode() )
432         CV_DBG_BREAK();
433     return 0;
434 }
435
436
437 /***************************** error handler *****************************/
438
439 #if 0
440 static int cvTestErrorCallback( int status, const char* func_name, const char* err_msg,
441                          const char* file_name, int line, void* userdata )
442 {
443     if( status < 0 && status != CV_StsBackTrace && status != CV_StsAutoTrace )
444         ((CvTS*)userdata)->set_failed_test_info( CvTS::FAIL_ERROR_IN_CALLED_FUNC );
445
446     // print error message
447     return cvStdErrReport( status, func_name, err_msg, file_name, line, 0 );
448 }
449 #endif
450
451 /*****************************************************************************************\
452 *                                    Base Class for Tests                                 *
453 \*****************************************************************************************/
454
455 CvTest::CvTest( const char* _test_name, const char* _test_funcs, const char* _test_descr ) :
456     name(_test_name ? _test_name : ""), tested_functions(_test_funcs ? _test_funcs : ""),
457     description(_test_descr ? _test_descr : ""), ts(0)
458 {
459     if( last )
460         last->next = this;
461     else
462         first = this;
463     last = this;
464     test_count++;
465     ts = 0;
466     hdr_state = 0;
467
468     timing_param_names = 0;
469     timing_param_current = 0;
470     timing_param_seqs = 0;
471     timing_param_idxs = 0;
472     timing_param_count = -1;
473
474     test_case_count = -1;
475     support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE;
476 }
477
478 CvTest::~CvTest()
479 {
480     clear();
481 }
482
483 CvTest* CvTest::get_first_test()
484 {
485     return first;
486 }
487
488 void CvTest::clear()
489 {
490     if( timing_param_current )
491         free( timing_param_current );
492     if( timing_param_seqs )
493         free( timing_param_seqs );
494     if( timing_param_idxs )
495         free( timing_param_idxs );
496
497     timing_param_current = 0;
498     timing_param_seqs = 0;
499     timing_param_idxs = 0;
500     timing_param_count = -1;
501 }
502
503
504 int CvTest::init( CvTS* _test_system )
505 {
506     clear();
507     ts = _test_system;
508     return read_params( ts->get_file_storage() );
509 }
510
511
512 const char* CvTest::get_parent_name( const char* name, char* buffer )
513 {
514     const char* dash_pos = strrchr( name ? name : "", '-' );
515     if( !dash_pos )
516         return 0;
517
518     if( name != (const char*)buffer )
519         strncpy( buffer, name, dash_pos - name );
520     buffer[dash_pos - name] = '\0';
521     return buffer;
522 }
523
524
525 const CvFileNode* CvTest::find_param( CvFileStorage* fs, const char* param_name )
526 {
527     char buffer[256];
528     const char* name = get_name();
529     CvFileNode* node = 0;
530
531     for(;;)
532     {
533         if( !name )
534             break;
535         node = cvGetFileNodeByName( fs, 0, name );
536         if( node )
537         {
538             node = cvGetFileNodeByName( fs, node, param_name );
539             if( node )
540                 break;
541         }
542         name = get_parent_name( name, buffer );
543     }
544
545     return node;
546 }
547
548
549 void CvTest::start_write_param( CvFileStorage* fs )
550 {
551     if( hdr_state == 0 )
552     {
553         cvStartWriteStruct( fs, get_name(), CV_NODE_MAP );
554         hdr_state = 1;
555     }
556 }
557
558
559 void CvTest::write_param( CvFileStorage* fs, const char* paramname, int val )
560 {
561     if( !ts->find_written_param( this, paramname, CV_NODE_INT, &val) )
562     {
563         start_write_param( fs );
564         cvWriteInt( fs, paramname, val );
565     }
566 }
567
568
569 void CvTest::write_param( CvFileStorage* fs, const char* paramname, double val )
570 {
571     if( !ts->find_written_param( this, paramname, CV_NODE_REAL, &val) )
572     {
573         start_write_param( fs );
574         cvWriteReal( fs, paramname, val );
575     }
576 }
577
578
579 void CvTest::write_param( CvFileStorage* fs, const char* paramname, const char* val )
580 {
581     if( !ts->find_written_param( this, paramname, CV_NODE_STRING, &val) )
582     {
583         start_write_param( fs );
584         cvWriteString( fs, paramname, val );
585     }
586 }
587
588
589 void CvTest::write_string_list( CvFileStorage* fs, const char* paramname, const char** val, int count )
590 {
591     if( val )
592     {
593         start_write_param( fs );
594         int i;
595         if( count < 0 )
596             count = INT_MAX;
597
598         cvStartWriteStruct( fs, paramname, CV_NODE_SEQ + CV_NODE_FLOW );
599         for( i = 0; i < count && val[i] != 0; i++ )
600             cvWriteString( fs, 0, val[i] );
601         cvEndWriteStruct( fs );
602     }
603 }
604
605
606 void CvTest::write_int_list( CvFileStorage* fs, const char* paramname,
607                              const int* val, int count, int stop_value )
608 {
609     if( val )
610     {
611         start_write_param( fs );
612         int i;
613         if( count < 0 )
614             count = INT_MAX;
615
616         cvStartWriteStruct( fs, paramname, CV_NODE_SEQ + CV_NODE_FLOW );
617         for( i = 0; i < count && val[i] != stop_value; i++ )
618             cvWriteInt( fs, 0, val[i] );
619         cvEndWriteStruct( fs );
620     }
621 }
622
623
624 void CvTest::write_real_list( CvFileStorage* fs, const char* paramname,
625                               const double* val, int count, double stop_value )
626 {
627     if( val )
628     {
629         start_write_param( fs );
630         int i;
631         if( count < 0 )
632             count = INT_MAX;
633
634         cvStartWriteStruct( fs, paramname, CV_NODE_SEQ + CV_NODE_FLOW );
635         for( i = 0; i < count && val[i] != stop_value; i++ )
636             cvWriteReal( fs, 0, val[i] );
637         cvEndWriteStruct( fs );
638     }
639 }
640
641
642 int CvTest::read_params( CvFileStorage* fs )
643 {
644     int code = 0;
645
646     if( ts->get_testing_mode() == CvTS::TIMING_MODE )
647     {
648         timing_param_names = find_param( fs, "timing_params" );
649         if( CV_NODE_IS_SEQ(timing_param_names->tag) )
650         {
651             CvSeq* seq = timing_param_names->data.seq;
652             CvSeqReader reader;
653             cvStartReadSeq( seq, &reader );
654             int i;
655
656             timing_param_count = seq->total;
657             timing_param_seqs = (const CvFileNode**)malloc( timing_param_count*sizeof(timing_param_seqs[0]));
658             timing_param_idxs = (int*)malloc( timing_param_count*sizeof(timing_param_idxs[0]));
659             timing_param_current = (const CvFileNode**)malloc( timing_param_count*sizeof(timing_param_current[0]));
660             test_case_count = 1;
661
662             for( i = 0; i < timing_param_count; i++ )
663             {
664                 CvFileNode* param_name = (CvFileNode*)(reader.ptr);
665
666                 if( !CV_NODE_IS_STRING(param_name->tag) )
667                 {
668                     ts->printf( CvTS::LOG, "ERROR: name of timing parameter #%d is not a string\n", i );
669                     code = -1;
670                     break;
671                 }
672
673                 timing_param_idxs[i] = 0;
674                 timing_param_current[i] = 0;
675                 timing_param_seqs[i] = find_param( fs, param_name->data.str.ptr );
676                 if( !timing_param_seqs[i] )
677                 {
678                     ts->printf( CvTS::LOG, "ERROR: timing parameter %s is not found\n", param_name->data.str.ptr );
679                     code = -1;
680                     break;
681                 }
682
683                 if( CV_NODE_IS_SEQ(timing_param_seqs[i]->tag) )
684                     test_case_count *= timing_param_seqs[i]->data.seq->total;
685
686                 CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
687             }
688
689             if( i < timing_param_count )
690                 timing_param_count = 0;
691         }
692         else
693         {
694             ts->printf( CvTS::LOG, "ERROR: \"timing_params\" is not found" );
695             code = -1;
696         }
697     }
698
699     return code;
700 }
701
702
703 int CvTest::get_next_timing_param_tuple()
704 {
705     bool increment;
706     int i;
707
708     if( timing_param_count <= 0 || !timing_param_names || !timing_param_seqs )
709         return -1;
710
711     increment = timing_param_current[0] != 0; // if already have some valid test tuple, move to the next
712     for( i = 0; i < timing_param_count; i++ )
713     {
714         const CvFileNode* node = timing_param_seqs[i];
715         int total = CV_NODE_IS_SEQ(node->tag) ? node->data.seq->total : 1;
716         int new_idx = timing_param_idxs[i];
717
718         if( !timing_param_current[i] )
719             timing_param_idxs[i] = new_idx = 0;
720         else if( increment )
721         {
722             new_idx++;
723             if( new_idx >= total )
724                 new_idx = 0;
725             else if( total > 1 )
726                 increment = false;
727         }
728
729         if( !timing_param_current[i] || new_idx != timing_param_idxs[i] )
730         {
731             if( CV_NODE_IS_SEQ(node->tag) )
732                 timing_param_current[i] = (CvFileNode*)cvGetSeqElem( node->data.seq, new_idx );
733             else
734                 timing_param_current[i] = node;
735             timing_param_idxs[i] = new_idx;
736         }
737     }
738
739     return !increment; // return 0 in case of overflow (i.e. if there is no more test cases)
740 }
741
742
743 const CvFileNode* CvTest::find_timing_param( const char* paramname )
744 {
745     if( timing_param_names )
746     {
747         int i;
748         CvSeqReader reader;
749         cvStartReadSeq( timing_param_names->data.seq, &reader, 0 );
750
751         for( i = 0; i < timing_param_count; i++ )
752         {
753             const char* ptr = ((const CvFileNode*)(reader.ptr))->data.str.ptr;
754             if( ptr[0] == paramname[0] && strcmp(ptr, paramname) == 0 )
755                 return timing_param_current[i];
756             CV_NEXT_SEQ_ELEM( reader.seq->elem_size, reader );
757         }
758     }
759     return 0;
760 }
761
762
763 int CvTest::write_defaults(CvTS* _ts)
764 {
765     ts = _ts;
766     hdr_state = 0;
767     write_default_params( ts->get_file_storage() );
768     if( hdr_state )
769         cvEndWriteStruct( ts->get_file_storage() );
770     return 0;
771 }
772
773
774 int CvTest::write_default_params( CvFileStorage* fs )
775 {
776     if( ts->get_testing_mode() == CvTS::TIMING_MODE )
777         write_string_list( fs, "timing_params", default_timing_param_names, timing_param_count );
778     return 0;
779 }
780
781
782 bool CvTest::can_do_fast_forward()
783 {
784     return true;
785 }
786
787
788 int CvTest::get_support_testing_modes()
789 {
790     return support_testing_modes;
791 }
792
793 void CvTest::safe_run( int start_from )
794 {
795     CV_TS_TRY_BLOCK_BEGIN;
796
797     run( start_from );
798
799     CV_TS_TRY_BLOCK_END;
800 }
801
802
803 void CvTest::run( int start_from )
804 {
805     int i, test_case_idx, count = get_test_case_count();
806     int64 t_start = cvGetTickCount();
807     double freq = cv::getTickFrequency();
808     bool ff = can_do_fast_forward();
809     int progress = 0, code;
810     std::vector<double> v_cpe, v_time;
811
812     for( test_case_idx = ff && start_from >= 0 ? start_from : 0;
813          count < 0 || test_case_idx < count; test_case_idx++ )
814     {
815         ts->update_context( this, test_case_idx, ff );
816         int64 t00 = 0, t0 = 0, t1 = 0, t2 = 0, t3 = 0;
817         double t_acc = 0, t_cpu_acc = 0;
818
819         if( ts->get_testing_mode() == CvTS::TIMING_MODE )
820         {
821             const int iterations = 20;
822             code = prepare_test_case( test_case_idx );
823
824             if( code < 0 || ts->get_err_code() < 0 )
825                 return;
826
827             if( code == 0 )
828                 continue;
829                 
830             v_cpe.resize(0);
831             v_time.resize(0);
832
833             for( i = 0; i < iterations; i++ )
834             {
835                 for(;;)
836                 {
837                                         t0 = cv::getTickCount();
838                                         t2 = cv::getCPUTickCount();
839                                         run_func();
840                                         t3 = cv::getCPUTickCount();
841                                         t1 = cv::getTickCount();
842                                         if( ts->get_err_code() < 0 )
843                                                 return;
844
845                                         if( t3 - t2 > 0 && t1 - t0 > 1 )
846                                                 break;
847                                 }
848
849                                 if( i == 0 )
850                                         t00 = t0;
851                                 v_cpe.push_back((double)(t3 - t2));
852                                 v_time.push_back((double)(t1 - t0));
853                 if( i >= 5 && t1 - t00 > freq*5 )
854                     break;
855             }
856
857                         sort(v_cpe.begin(), v_cpe.end());
858                         sort(v_time.begin(), v_time.end());
859                         
860             t_cpu_acc = v_cpe[i/2];
861             t_acc = v_time[i/2];
862             print_time( test_case_idx, t_acc, t_cpu_acc );
863         }
864         else
865         {
866             code = prepare_test_case( test_case_idx );
867             if( code < 0 || ts->get_err_code() < 0 )
868                 return;
869
870             if( code == 0 )
871                 continue;
872
873             run_func();
874             if( ts->get_err_code() < 0 )
875                 return;
876
877             if( validate_test_results( test_case_idx ) < 0 || ts->get_err_code() < 0 )
878                 return;
879         }
880
881         progress = update_progress( progress, test_case_idx, count, (double)(t1 - t_start)/(freq*1000) );
882     }
883 }
884
885
886 void CvTest::run_func()
887 {
888     assert(0);
889 }
890
891
892 int CvTest::get_test_case_count()
893 {
894     return test_case_count;
895 }
896
897
898 int CvTest::prepare_test_case( int )
899 {
900     return 0;
901 }
902
903
904 int CvTest::validate_test_results( int )
905 {
906     return 0;
907 }
908
909
910 void CvTest::print_time( int /*test_case_idx*/, double /*time_usecs*/, double /*time_cpu_clocks*/ )
911 {
912 }
913
914
915 int CvTest::update_progress( int progress, int test_case_idx, int count, double dt )
916 {
917     int width = 60 - (int)strlen(get_name());
918     if( count > 0 )
919     {
920         int t = cvRound( ((double)test_case_idx * width)/count );
921         if( t > progress )
922         {
923             ts->printf( CvTS::CONSOLE, "." );
924             progress = t;
925         }
926     }
927     else if( cvRound(dt) > progress )
928     {
929         ts->printf( CvTS::CONSOLE, "." );
930         progress = cvRound(dt);
931     }
932
933     return progress;
934 }
935
936 /*****************************************************************************************\
937 *                                 Base Class for Test System                              *
938 \*****************************************************************************************/
939
940 /******************************** Constructors/Destructors ******************************/
941
942 CvTS::CvTS()
943 {
944     start_time = 0;
945     version = CV_TS_VERSION;
946     memory_manager = 0;
947     /*
948     memory_manager = new CvTestMemoryManager(this);
949     cvSetMemoryManager( CvTestMemoryManager::alloc_proxy,
950                         CvTestMemoryManager::free_proxy,
951                         memory_manager );*/
952     ostrm_suffixes[SUMMARY_IDX] = ".sum";
953     ostrm_suffixes[LOG_IDX] = ".log";
954     ostrm_suffixes[CSV_IDX] = ".csv";
955     ostrm_suffixes[CONSOLE_IDX] = 0;
956     ostrm_base_name = 0;
957     memset( output_streams, 0, sizeof(output_streams) );
958     memset( &params, 0, sizeof(params) );
959     selected_tests = new CvTestPtrVec();
960     failed_tests = new CvTestInfoVec();
961     written_params = new CvTestPtrVec();
962
963     clear();
964 }
965
966
967 void CvTS::clear()
968 {
969     int i;
970     CvTest* test;
971
972     for( test = get_first_test(); test != 0; test = test->get_next() )
973         test->clear();
974
975     for( i = 0; i <= CONSOLE_IDX; i++ )
976     {
977         if( i == LOG_IDX )
978             fflush( stderr );
979         else if( i == CONSOLE_IDX )
980             fflush( stdout );
981
982         if( i < CONSOLE_IDX && output_streams[i].f )
983         {
984             fclose( output_streams[i].f );
985             output_streams[i].f = 0;
986         }
987
988         if( i == LOG_IDX && output_streams[i].default_handle > 0 )
989         {
990             dup2( output_streams[i].default_handle, 2 );
991             output_streams[i].default_handle = 0;
992         }
993         output_streams[i].enable = 1;
994     }
995     cvReleaseFileStorage( &fs );
996     selected_tests->clear();
997     failed_tests->clear();
998     if( ostrm_base_name )
999     {
1000         free( ostrm_base_name );
1001         ostrm_base_name = 0;
1002     }
1003     params.rng_seed = (uint64)-1;
1004     params.debug_mode = 1;
1005     params.print_only_failed = 0;
1006     params.skip_header = 0;
1007     params.test_mode = CORRECTNESS_CHECK_MODE;
1008     params.timing_mode = MIN_TIME;
1009     params.use_optimized = -1;
1010     params.color_terminal = 1;
1011
1012     if( memory_manager )
1013         memory_manager->clear_and_check();
1014 }
1015
1016
1017 CvTS::~CvTS()
1018 {
1019     clear();
1020     set_data_path(0);
1021
1022     if( written_params )
1023     {
1024         for( int i = 0; i < written_params->size(); i++ )
1025             free( written_params->at(i) );
1026         delete written_params;
1027     }
1028
1029     delete selected_tests;
1030     delete failed_tests;
1031 }
1032
1033
1034 const char* CvTS::str_from_code( int code )
1035 {
1036     switch( code )
1037     {
1038     case OK: return "Ok";
1039     case FAIL_GENERIC: return "Generic/Unknown";
1040     case FAIL_MISSING_TEST_DATA: return "No test data";
1041     case FAIL_INVALID_TEST_DATA: return "Invalid test data";
1042     case FAIL_ERROR_IN_CALLED_FUNC: return "cvError invoked";
1043     case FAIL_EXCEPTION: return "Hardware/OS exception";
1044     case FAIL_MEMORY_EXCEPTION: return "Invalid memory access";
1045     case FAIL_ARITHM_EXCEPTION: return "Arithmetic exception";
1046     case FAIL_MEMORY_CORRUPTION_BEGIN: return "Corrupted memblock (beginning)";
1047     case FAIL_MEMORY_CORRUPTION_END: return "Corrupted memblock (end)";
1048     case FAIL_MEMORY_LEAK: return "Memory leak";
1049     case FAIL_INVALID_OUTPUT: return "Invalid function output";
1050     case FAIL_MISMATCH: return "Unexpected output";
1051     case FAIL_BAD_ACCURACY: return "Bad accuracy";
1052     case FAIL_HANG: return "Infinite loop(?)";
1053     case FAIL_BAD_ARG_CHECK: return "Incorrect handling of bad arguments";
1054     default: return "Generic/Unknown";
1055     }
1056 }
1057
1058 /************************************** Running tests **********************************/
1059
1060 void CvTS::make_output_stream_base_name( const char* config_name )
1061 {
1062     int k, len = (int)strlen( config_name );
1063
1064     if( ostrm_base_name )
1065         free( ostrm_base_name );
1066
1067     for( k = len-1; k >= 0; k-- )
1068     {
1069         char c = config_name[k];
1070         if( c == '.' || c == '/' || c == '\\' || c == ':' )
1071             break;
1072     }
1073
1074     if( k > 0 && config_name[k] == '.' )
1075         len = k;
1076
1077     ostrm_base_name = (char*)malloc( len + 1 );
1078     memcpy( ostrm_base_name, config_name, len );
1079     ostrm_base_name[len] = '\0';
1080 }
1081
1082
1083 void CvTS::set_handlers( bool on )
1084 {
1085     if( on )
1086     {
1087         cvSetErrMode( CV_ErrModeParent );
1088         cvRedirectError( cvStdErrReport );
1089     #if defined WIN32 || defined _WIN32
1090         #ifdef _MSC_VER
1091         _set_se_translator( cv_seh_translator );
1092         #endif
1093     #else
1094         for( int i = 0; cv_ts_sig_id[i] >= 0; i++ )
1095             signal( cv_ts_sig_id[i], cv_signal_handler );
1096     #endif
1097     }
1098     else
1099     {
1100         cvSetErrMode( CV_ErrModeLeaf );
1101         cvRedirectError( cvGuiBoxReport );
1102     #if defined WIN32 || defined _WIN32
1103         #ifdef _MSC_VER
1104         _set_se_translator( 0 );
1105         #endif
1106     #else
1107         for( int i = 0; cv_ts_sig_id[i] >= 0; i++ )
1108             signal( cv_ts_sig_id[i], SIG_DFL );
1109     #endif
1110     }
1111 }
1112
1113
1114 void CvTS::set_data_path( const char* data_path )
1115 {
1116     if( data_path == params.data_path )
1117         return;
1118
1119     if( params.data_path )
1120         delete[] params.data_path;
1121     if( data_path )
1122     {
1123         int size = (int)strlen(data_path)+1;
1124         bool append_slash = data_path[size-1] != '/' && data_path[size-1] != '\\';
1125         params.data_path = new char[size+1];
1126         memcpy( params.data_path, data_path, size );
1127         if( append_slash )
1128             strcat( params.data_path, "/" );
1129     }
1130 }
1131
1132
1133 typedef struct CvTsParamVal
1134 {
1135     const char* fullname;
1136     const void* val;
1137 }
1138 CvTsParamVal;
1139
1140 int CvTS::find_written_param( CvTest* test, const char* paramname, int valtype, const void* val )
1141 {
1142     const char* testname = test->get_name();
1143     bool add_to_list = test->get_func_list()[0] == '\0';
1144     char buffer[256];
1145     int paramname_len = (int)strlen(paramname);
1146     int paramval_len = valtype == CV_NODE_INT ? (int)sizeof(int) :
1147         valtype == CV_NODE_REAL ? (int)sizeof(double) : -1;
1148     const char* name = CvTest::get_parent_name( testname, buffer );
1149
1150     if( !fs )
1151         return -1;
1152
1153     if( paramval_len < 0 )
1154     {
1155         assert(0); // unsupported parameter type
1156         return -1;
1157     }
1158
1159     while( name )
1160     {
1161         int i, len = (int)strlen(buffer);
1162         buffer[len] = '.';
1163         memcpy( buffer + len + 1, paramname, paramname_len + 1 );
1164         for( i = 0; i < written_params->size(); i++ )
1165         {
1166             CvTsParamVal* param = (CvTsParamVal*)written_params->at(i);
1167             if( strcmp( param->fullname, buffer ) == 0 )
1168             {
1169                 if( (paramval_len > 0 && memcmp( param->val, val, paramval_len ) == 0) ||
1170                     (paramval_len < 0 && strcmp( (const char*)param->val, (const char*)val ) == 0) )
1171                     return 1;
1172                 break;
1173             }
1174         }
1175         if( i < written_params->size() )
1176             break;
1177         buffer[len] = '\0';
1178         name = CvTest::get_parent_name( buffer, buffer );
1179     }
1180
1181     if( add_to_list )
1182     {
1183         int bufsize, fullname_len = (int)strlen(testname) + paramname_len + 2;
1184         CvTsParamVal* param;
1185         if( paramval_len < 0 )
1186             paramval_len = (int)strlen((const char*)val) + 1;
1187         bufsize = sizeof(*param) + fullname_len + paramval_len;
1188         param = (CvTsParamVal*)malloc(bufsize);
1189         param->fullname = (const char*)(param + 1);
1190         param->val = param->fullname + fullname_len;
1191         sprintf( (char*)param->fullname, "%s.%s", testname, paramname );
1192         memcpy( (void*)param->val, val, paramval_len );
1193         written_params->push( param );
1194     }
1195
1196     return 0;
1197 }
1198
1199
1200 #ifndef MAX_PATH
1201 #define MAX_PATH 1024
1202 #endif
1203
1204 static int CV_CDECL cmp_test_names( const void* a, const void* b )
1205 {
1206     return strcmp( (*(const CvTest**)a)->get_name(), (*(const CvTest**)b)->get_name() );
1207 }
1208
1209 int CvTS::run( int argc, char** argv )
1210 {
1211     time( &start_time );
1212
1213     int i, write_params = 0;
1214     int list_tests = 0;
1215     CvTestPtrVec all_tests;
1216     CvTest* test;
1217
1218     // 0. reset all the parameters, reorder tests
1219     clear();
1220
1221     for( test = get_first_test(), i = 0; test != 0; test = test->get_next(), i++ )
1222         all_tests.push(test);
1223
1224     if( all_tests.size() > 0 && all_tests.data() )
1225         qsort( all_tests.data(), all_tests.size(), sizeof(CvTest*), cmp_test_names );
1226
1227     // 1. parse command line options
1228     for( i = 1; i < argc; i++ )
1229     {
1230         if( strcmp( argv[i], "-h" ) == 0 || strcmp( argv[i], "--help" ) == 0 )
1231         {
1232             print_help();
1233             return 0;
1234         }
1235         else if( strcmp( argv[i], "-f" ) == 0 )
1236             config_name = argv[++i];
1237         else if( strcmp( argv[i], "-w" ) == 0 )
1238             write_params = 1;
1239         else if( strcmp( argv[i], "-t" ) == 0 )
1240             params.test_mode = TIMING_MODE;
1241         else if( strcmp( argv[i], "-O0" ) == 0 || strcmp( argv[i], "-O1" ) == 0 )
1242             params.use_optimized = argv[i][2] - '0';
1243         else if( strcmp( argv[i], "-l" ) == 0 )
1244             list_tests = 1;
1245         else if( strcmp( argv[i], "-d" ) == 0 )
1246             set_data_path(argv[++i]);
1247         else if( strcmp( argv[i], "-nc" ) == 0 )
1248             params.color_terminal = 0;
1249     }
1250
1251 #if 0
1252 //#if !defined WIN32 && !defined _WIN32
1253     if (! config_name )
1254     {    
1255       char * confname = getenv("configname");
1256       if (confname)
1257         config_name = confname;
1258     }
1259     
1260     if( !params.data_path || !params.data_path[0] )
1261     {
1262         char* datapath = getenv("datapath");
1263         if( datapath )
1264             set_data_path(datapath);
1265     }
1266     
1267     // this is the fallback for the current OpenCV autotools setup
1268     if( !params.data_path || !params.data_path[0] )
1269     {
1270         char* srcdir = getenv("srcdir");
1271         char buf[1024];
1272         if( srcdir )
1273         {
1274             sprintf( buf, "%s/../../opencv_extra/testdata/", srcdir );
1275             set_data_path(buf);
1276         }
1277     }
1278 #endif
1279
1280     if( write_params )
1281     {
1282         if( !config_name )
1283         {
1284             printf( LOG, "ERROR: output config name is not specified\n" );
1285             return -1;
1286         }
1287         fs = cvOpenFileStorage( config_name, 0, CV_STORAGE_WRITE );
1288         if( !fs )
1289         {
1290             printf( LOG, "ERROR: could not open config file %s\n", config_name );
1291             return -1;
1292         }
1293         cvWriteComment( fs, CV_TS_VERSION " config file", 0 );
1294         cvStartWriteStruct( fs, "common", CV_NODE_MAP );
1295         write_default_params( fs );
1296         cvEndWriteStruct( fs );
1297
1298         for( i = 0; i < all_tests.size(); i++ )
1299         {
1300             test = (CvTest*)all_tests[i];
1301             if( !(test->get_support_testing_modes() & get_testing_mode()) )
1302                 continue;
1303             test->write_defaults( this );
1304             test->clear();
1305         }
1306         cvReleaseFileStorage( &fs );
1307         return 0;
1308     }
1309
1310     if( !config_name )
1311         printf( LOG, "WARNING: config name is not specified, using default parameters\n" );
1312     else
1313     {
1314         // 2. read common parameters of test system
1315         fs = cvOpenFileStorage( config_name, 0, CV_STORAGE_READ );
1316         if( !fs )
1317         {
1318             printf( LOG, "ERROR: could not open config file %s", config_name );
1319             return -1;
1320         }
1321     }
1322
1323     if( read_params(fs) < 0 )
1324         return -1;
1325
1326     if( !ostrm_base_name )
1327         make_output_stream_base_name( config_name ? config_name : argv[0] );
1328
1329     ostream_testname_mask = -1; // disable printing test names at initial stage
1330
1331     // 3. open file streams
1332     for( i = 0; i < CONSOLE_IDX; i++ )
1333     {
1334         char filename[MAX_PATH];
1335         sprintf( filename, "%s%s", ostrm_base_name, ostrm_suffixes[i] );
1336         output_streams[i].f = fopen( filename, "wt" );
1337         if( !output_streams[i].f )
1338         {
1339             printf( LOG, "ERROR: could not open %s\n", filename );
1340             return -1;
1341         }
1342
1343         if( i == LOG_IDX )
1344         {
1345             // redirect stderr to log file
1346             fflush( stderr );
1347             output_streams[i].default_handle = dup(2);
1348             dup2( fileno(output_streams[i].f), 2 );
1349         }
1350     }
1351
1352     // 4. traverse through the list of all registered tests.
1353     // Initialize the selected tests and put them into the separate sequence
1354     for( i = 0; i < all_tests.size(); i++ )
1355     {
1356         test = (CvTest*)all_tests[i];
1357         if( !(test->get_support_testing_modes() & get_testing_mode()) )
1358             continue;
1359
1360         if( strcmp( test->get_func_list(), "" ) != 0 && filter(test) )
1361         {
1362             if( test->init(this) >= 0 )
1363             {
1364                 selected_tests->push( test );
1365                 if( list_tests )
1366                     ::printf( "%s\n", test->get_name() );
1367             }
1368             else
1369                 printf( LOG, "WARNING: an error occured during test %s initialization\n", test->get_name() );
1370         }
1371     }
1372
1373     if( list_tests )
1374     {
1375         clear();
1376         return 0;
1377     }
1378
1379     // 5. setup all the neccessary handlers and print header
1380     set_handlers( !params.debug_mode );
1381
1382     if( params.use_optimized == 0 )
1383         cvUseOptimized(0);
1384
1385     if( !params.skip_header )
1386         print_summary_header( SUMMARY + LOG + CONSOLE + CSV );
1387     rng = params.rng_seed;
1388     update_context( 0, -1, true );
1389
1390     // 6. run all the tests
1391     for( i = 0; i < selected_tests->size(); i++ )
1392     {
1393         CvTest* test = (CvTest*)selected_tests->at(i);
1394         int code;
1395         CvTestInfo temp;
1396
1397         if( memory_manager )
1398             memory_manager->start_tracking();
1399         update_context( test, -1, true );
1400         current_test_info.rng_seed0 = current_test_info.rng_seed;
1401         
1402         ostream_testname_mask = 0; // reset "test name was printed" flags
1403         if( output_streams[LOG_IDX].f )
1404             fflush( output_streams[LOG_IDX].f );
1405
1406         temp = current_test_info;
1407         test->safe_run(0);
1408         if( get_err_code() >= 0 )
1409         {
1410             update_context( test, -1, false );
1411             current_test_info.rng_seed = temp.rng_seed;
1412             current_test_info.base_alloc_index = temp.base_alloc_index;
1413         }
1414         test->clear();
1415         if( memory_manager )
1416             memory_manager->stop_tracking_and_check();
1417
1418         code = get_err_code();
1419         if( code >= 0 )
1420         {
1421             if( !params.print_only_failed )
1422             {
1423                 printf( SUMMARY + CONSOLE, "\t" );
1424                 set_color( CV_TS_GREEN );
1425                 printf( SUMMARY + CONSOLE, "Ok\n" );
1426                 set_color( CV_TS_NORMAL );
1427             }
1428         }
1429         else
1430         {
1431             printf( SUMMARY + CONSOLE, "\t" );
1432             set_color( CV_TS_RED );
1433             printf( SUMMARY + CONSOLE, "FAIL(%s)\n", str_from_code(code) );
1434             set_color( CV_TS_NORMAL );
1435             printf( LOG, "context: test case = %d, seed = %08x%08x\n",
1436                     current_test_info.test_case_idx,
1437                     (unsigned)(current_test_info.rng_seed>>32),
1438                     (unsigned)(current_test_info.rng_seed));
1439             failed_tests->push(current_test_info);
1440             if( params.rerun_immediately )
1441                 break;
1442         }
1443     }
1444
1445     ostream_testname_mask = -1;
1446     print_summary_tailer( SUMMARY + CONSOLE + LOG );
1447
1448     if( !params.debug_mode && (params.rerun_failed || params.rerun_immediately) )
1449     {
1450         set_handlers(0);
1451         update_context( 0, -1, true );
1452         for( i = 0; i < failed_tests->size(); i++ )
1453         {
1454             CvTestInfo info = failed_tests->at(i);
1455             if( (info.code == FAIL_MEMORY_CORRUPTION_BEGIN ||
1456                 info.code == FAIL_MEMORY_CORRUPTION_END ||
1457                 info.code == FAIL_MEMORY_LEAK) && memory_manager )
1458                 memory_manager->start_tracking( info.alloc_index - info.base_alloc_index
1459                                                 + memory_manager->get_alloc_index() );
1460             rng = info.rng_seed;
1461             test->safe_run( info.test_case_idx );
1462         }
1463     }
1464     int nfailed = failed_tests ? (int)failed_tests->size() : 0;
1465     clear();
1466
1467     return nfailed;
1468 }
1469
1470
1471 void CvTS::print_help()
1472 {
1473     ::printf(
1474         "Usage: <test_executable> [{-h|--help}][-l] [-w] [-t] [-f <config_name>] [-d <data_path>] [-O{0|1}]\n\n"
1475         "-d - specify the test data path\n\n"
1476         "-f - use parameters from the provided config XML/YAML file instead of the default parameters\n\n"
1477         "-h or --help - print this help information\n\n"
1478         "-l - list all the registered tests or subset of the tests, selected in the config file, and exit\n\n"
1479         "-nc - do not use colors in the console output\n\n"     
1480         "-O{0|1} - disable/enable on-fly detection of IPP and other supported optimized libs. It's enabled by default\n\n"
1481         "-t - switch to the performance testing mode instead of the default algorithmic/correctness testing mode\n\n"
1482         "-w - write default parameters of the algorithmic or performance (when -t is passed) tests to the specifed config file (see -f) and exit\n\n"
1483         //"Test data path and config file can also be specified by the environment variables 'config' and 'datapath'.\n\n"
1484         );
1485 }
1486
1487
1488 #if defined WIN32 || defined _WIN32
1489 const char* default_data_path = "../tests/cv/testdata/";
1490 #else
1491 const char* default_data_path = "../../../../tests/cv/testdata/";
1492 #endif
1493
1494
1495 int CvTS::read_params( CvFileStorage* fs )
1496 {
1497     CvFileNode* node = fs ? cvGetFileNodeByName( fs, 0, "common" ) : 0;
1498     params.debug_mode = cvReadIntByName( fs, node, "debug_mode", 1 ) != 0;
1499     params.skip_header = cvReadIntByName( fs, node, "skip_header", 0 ) != 0;
1500     params.print_only_failed = cvReadIntByName( fs, node, "print_only_failed", 0 ) != 0;
1501     params.rerun_failed = cvReadIntByName( fs, node, "rerun_failed", 0 ) != 0;
1502     params.rerun_immediately = cvReadIntByName( fs, node, "rerun_immediately", 0 ) != 0;
1503     const char* str = cvReadStringByName( fs, node, "filter_mode", "tests" );
1504     params.test_filter_mode = strcmp( str, "functions" ) == 0 ? CHOOSE_FUNCTIONS : CHOOSE_TESTS;
1505     str = cvReadStringByName( fs, node, "test_mode", params.test_mode == TIMING_MODE ? "timing" : "correctness" );
1506     params.test_mode = strcmp( str, "timing" ) == 0 || strcmp( str, "performance" ) == 0 ?
1507                         TIMING_MODE : CORRECTNESS_CHECK_MODE;
1508     str = cvReadStringByName( fs, node, "timing_mode", params.timing_mode == AVG_TIME ? "avg" : "min" );
1509     params.timing_mode = strcmp( str, "average" ) == 0 || strcmp( str, "avg" ) == 0 ? AVG_TIME : MIN_TIME;
1510     params.test_filter_pattern = cvReadStringByName( fs, node, params.test_filter_mode == CHOOSE_FUNCTIONS ?
1511                                                      "functions" : "tests", "" );
1512     params.resource_path = cvReadStringByName( fs, node, "." );
1513     if( params.use_optimized < 0 )
1514         params.use_optimized = cvReadIntByName( fs, node, "use_optimized", -1 );
1515     if( !params.data_path || !params.data_path[0] )
1516     {
1517         const char* data_path =
1518             cvReadStringByName( fs, node, "data_path", default_data_path );
1519         set_data_path(data_path);
1520     }
1521     params.test_case_count_scale = cvReadRealByName( fs, node, "test_case_count_scale", 1. );
1522     if( params.test_case_count_scale <= 0 )
1523         params.test_case_count_scale = 1.;
1524     str = cvReadStringByName( fs, node, "seed", 0 );
1525     params.rng_seed = 0;
1526     if( str && strlen(str) == 16 )
1527     {
1528         params.rng_seed = 0;
1529         for( int i = 0; i < 16; i++ )
1530         {
1531             int c = tolower(str[i]);
1532             if( !isxdigit(c) )
1533             {
1534                 params.rng_seed = 0;
1535                 break;
1536             }
1537             params.rng_seed = params.rng_seed * 16 +
1538                 (str[i] < 'a' ? str[i] - '0' : str[i] - 'a' + 10);
1539         }
1540     }
1541
1542     if( params.rng_seed == 0 )
1543         params.rng_seed = cvGetTickCount();
1544
1545     str = cvReadStringByName( fs, node, "output_file_base_name", 0 );
1546     if( str )
1547         make_output_stream_base_name( str );
1548
1549     return 0;
1550 }
1551
1552
1553 void CvTS::write_default_params( CvFileStorage* fs )
1554 {
1555     read_params(0); // fill parameters with default values
1556
1557     cvWriteInt( fs, "debug_mode", params.debug_mode );
1558     cvWriteInt( fs, "skip_header", params.skip_header );
1559     cvWriteInt( fs, "print_only_failed", params.print_only_failed );
1560     cvWriteInt( fs, "rerun_failed", params.rerun_failed );
1561     cvWriteInt( fs, "rerun_immediately", params.rerun_immediately );
1562     cvWriteString( fs, "filter_mode", params.test_filter_mode == CHOOSE_FUNCTIONS ? "functions" : "tests" );
1563     cvWriteString( fs, "test_mode", params.test_mode == TIMING_MODE ? "timing" : "correctness" );
1564     cvWriteString( fs, "data_path", params.data_path ? params.data_path : default_data_path, 1 );
1565     if( params.test_mode == TIMING_MODE )
1566         cvWriteString( fs, "timing_mode", params.timing_mode == AVG_TIME ? "avg" : "min" );
1567     // test_filter, seed & output_file_base_name are not written
1568 }
1569
1570
1571 void CvTS::enable_output_streams( int stream_mask, int value )
1572 {
1573     for( int i = 0; i < MAX_IDX; i++ )
1574         if( stream_mask & (1 << i) )
1575             output_streams[i].enable = value != 0;
1576 }
1577
1578
1579 void CvTS::update_context( CvTest* test, int test_case_idx, bool update_ts_context )
1580 {
1581     current_test_info.test = test;
1582     current_test_info.test_case_idx = test_case_idx;
1583     current_test_info.alloc_index = 0;
1584     current_test_info.code = 0;
1585     cvSetErrStatus( CV_StsOk );
1586     if( update_ts_context )
1587     {
1588         current_test_info.rng_seed = rng;
1589         current_test_info.base_alloc_index = memory_manager ?
1590             memory_manager->get_alloc_index() : 0;
1591     }
1592 }
1593
1594
1595 void CvTS::set_failed_test_info( int fail_code, int alloc_index )
1596 {
1597     if( fail_code == FAIL_MEMORY_CORRUPTION_BEGIN ||
1598         fail_code == FAIL_MEMORY_CORRUPTION_END ||
1599         current_test_info.code >= 0 )
1600     {
1601         current_test_info.code = fail_code;
1602         current_test_info.alloc_index = alloc_index;
1603     }
1604 }
1605
1606
1607 const char* CvTS::get_libs_info( const char** addon_modules )
1608 {
1609     const char* all_info = 0;
1610     cvGetModuleInfo( 0, &all_info, addon_modules );
1611     return all_info;
1612 }
1613
1614
1615 void CvTS::print_summary_header( int streams )
1616 {
1617     char csv_header[256], *ptr = csv_header;
1618     int i;
1619
1620     printf( streams, "Engine: %s\n", version );
1621     time_t t1;
1622     time( &t1 );
1623     struct tm *t2 = localtime( &t1 );
1624     char buf[1024];
1625     strftime( buf, sizeof(buf)-1, "%c", t2 );
1626     printf( streams, "Execution Date & Time: %s\n", buf );
1627     printf( streams, "Config File: %s\n", config_name );
1628     const char* plugins = 0;
1629     const char* lib_verinfo = get_libs_info( &plugins );
1630     printf( streams, "Tested Libraries: %s\n", lib_verinfo );
1631     printf( streams, "Optimized Low-level Plugin\'s: %s\n", plugins );
1632     printf( streams, "=================================================\n");
1633
1634     sprintf( ptr, "funcName,dataType,channels,size," );
1635     ptr += strlen(ptr);
1636
1637     for( i = 0; i < CvTest::TIMING_EXTRA_PARAMS; i++ )
1638     {
1639         sprintf( ptr, "param%d,", i );
1640         ptr += strlen(ptr);
1641     }
1642
1643     sprintf( ptr, "CPE,Time(uSecs)" );
1644     printf( CSV, "%s\n", csv_header );
1645 }
1646
1647
1648 void CvTS::print_summary_tailer( int streams )
1649 {
1650     printf( streams, "=================================================\n");
1651     if( selected_tests && failed_tests )
1652     {
1653         time_t end_time;
1654         time( &end_time );
1655         double total_time = difftime( end_time, start_time );
1656         printf( streams, "Summary: %d out of %d tests failed\n",
1657             failed_tests->size(), selected_tests->size() );
1658         int minutes = cvFloor(total_time/60.);
1659         int seconds = cvRound(total_time - minutes*60);
1660         int hours = minutes / 60;
1661         minutes %= 60;
1662         printf( streams, "Running time: %02d:%02d:%02d\n", hours, minutes, seconds );
1663     }
1664 }
1665
1666
1667 void CvTS::vprintf( int streams, const char* fmt, va_list l )
1668 {
1669     if( streams )
1670     {
1671         char str[1 << 14];
1672         vsprintf( str, fmt, l );
1673
1674         for( int i = 0; i < MAX_IDX; i++ )
1675         {
1676             if( (streams & (1 << i)) && output_streams[i].enable )
1677             {
1678                 FILE* f = i == CONSOLE_IDX ? stdout :
1679                           i == LOG_IDX ? stderr : output_streams[i].f;
1680                 if( f )
1681                 {
1682                     if( i != CSV_IDX && !(ostream_testname_mask & (1 << i)) && current_test_info.test )
1683                     {
1684                         fprintf( f, "-------------------------------------------------\n" );
1685                         if( i == CONSOLE_IDX || i == SUMMARY_IDX )
1686                                                         fprintf( f, "[%08x%08x]\n", (int)(current_test_info.rng_seed0 >> 32),
1687                                                             (int)(current_test_info.rng_seed0));
1688                         fprintf( f, "%s: ", current_test_info.test->get_name() );
1689                         fflush( f );
1690                         ostream_testname_mask |= 1 << i;
1691                     }
1692                     fputs( str, f );
1693                     if( i == CONSOLE_IDX )
1694                         fflush(f);
1695                 }
1696             }
1697         }
1698     }
1699 }
1700
1701
1702 void CvTS::printf( int streams, const char* fmt, ... )
1703 {
1704     if( streams )
1705     {
1706         va_list l;
1707         va_start( l, fmt );
1708         vprintf( streams, fmt, l );
1709         va_end( l );
1710     }
1711 }
1712
1713 void CvTS::set_color(int color)
1714 {
1715     if( params.color_terminal )
1716         change_color(color);
1717 }
1718
1719 static char* cv_strnstr( const char* str, int len,
1720                          const char* pattern,
1721                          int pattern_len = -1,
1722                          int whole_word = 1 )
1723 {
1724     int i;
1725
1726     if( len < 0 && pattern_len < 0 )
1727         return (char*)strstr( str, pattern );
1728
1729     if( len < 0 )
1730         len = (int)strlen( str );
1731
1732     if( pattern_len < 0 )
1733         pattern_len = (int)strlen( pattern );
1734
1735     for( i = 0; i < len - pattern_len + 1; i++ )
1736     {
1737         int j = i + pattern_len;
1738         if( str[i] == pattern[0] &&
1739             memcmp( str + i, pattern, pattern_len ) == 0 &&
1740             (!whole_word ||
1741             ((i == 0 || (!isalnum(str[i-1]) && str[i-1] != '_')) &&
1742              (j == len || (!isalnum(str[j]) && str[j] != '_')))))
1743             return (char*)(str + i);
1744     }
1745
1746     return 0;
1747 }
1748
1749
1750 int CvTS::filter( CvTest* test )
1751 {
1752     const char* pattern = params.test_filter_pattern;
1753     int inverse = 0;
1754
1755     if( pattern && pattern[0] == '!' )
1756     {
1757         inverse = 1;
1758         pattern++;
1759     }
1760
1761     if( !pattern || strcmp( pattern, "" ) == 0 || strcmp( pattern, "*" ) == 0 )
1762         return 1 ^ inverse;
1763
1764     if( params.test_filter_mode == CHOOSE_TESTS )
1765     {
1766         int found = 0;
1767
1768         while( pattern && *pattern )
1769         {
1770             char *ptr, *endptr = (char*)strchr( pattern, ',' );
1771             int len, have_wildcard;
1772             int t_name_len;
1773
1774             if( endptr )
1775                 *endptr = '\0';
1776
1777             ptr = (char*)strchr( pattern, '*' );
1778             if( ptr )
1779             {
1780                 len = (int)(ptr - pattern);
1781                 have_wildcard = 1;
1782             }
1783             else
1784             {
1785                 len = (int)strlen( pattern );
1786                 have_wildcard = 0;
1787             }
1788
1789             t_name_len = (int)strlen( test->get_name() );
1790             found = (t_name_len == len || (have_wildcard && t_name_len > len)) &&
1791                     (len == 0 || memcmp( test->get_name(), pattern, len ) == 0);
1792             if( endptr )
1793             {
1794                 *endptr = ',';
1795                 pattern = endptr + 1;
1796                 while( isspace(*pattern) )
1797                     pattern++;
1798             }
1799
1800             if( found || !endptr )
1801                 break;
1802         }
1803
1804         return found ^ inverse;
1805     }
1806     else
1807     {
1808         assert( params.test_filter_mode == CHOOSE_FUNCTIONS );
1809         int glob_len = (int)strlen( pattern );
1810         const char* ptr = test->get_func_list();
1811         const char *tmp_ptr;
1812
1813         while( ptr && *ptr )
1814         {
1815             const char* endptr = ptr - 1;
1816             const char* name_ptr;
1817             const char* name_first_match;
1818             int name_len;
1819             char c;
1820
1821             do c = *++endptr;
1822             while( isspace(c) );
1823
1824             if( !c )
1825                 break;
1826
1827             assert( isalpha(c) );
1828             name_ptr = endptr;
1829
1830             do c = *++endptr;
1831             while( isalnum(c) || c == '_' );
1832
1833             if( c == ':' ) // class
1834             {
1835                 assert( endptr[1] == ':' );
1836                 endptr = endptr + 2;
1837                 name_len = (int)(endptr - name_ptr);
1838
1839                 // find the first occurence of the class name
1840                 // in pattern
1841                 name_first_match = cv_strnstr( pattern,
1842                                       glob_len, name_ptr, name_len, 1 );
1843
1844                 if( *endptr == '*' )
1845                 {
1846                     if( name_first_match )
1847                         return 1 ^ inverse;
1848                 }
1849                 else
1850                 {
1851                     assert( *endptr == '{' ); // a list of methods
1852
1853                     if( !name_first_match )
1854                     {
1855                         // skip all the methods, if there is no such a class name
1856                         // in pattern
1857                         endptr = strchr( endptr, '}' );
1858                         assert( endptr != 0 );
1859                         endptr--;
1860                     }
1861
1862                     for( ;; )
1863                     {
1864                         const char* method_name_ptr;
1865                         int method_name_len;
1866
1867                         do c = *++endptr;
1868                         while( isspace(c) );
1869
1870                         if( c == '}' )
1871                             break;
1872                         assert( isalpha(c) );
1873
1874                         method_name_ptr = endptr;
1875
1876                         do c = *++endptr;
1877                         while( isalnum(c) || c == '_' );
1878
1879                         method_name_len = (int)(endptr - method_name_ptr);
1880
1881                         // search for class_name::* or
1882                         // class_name::{...method_name...}
1883                         tmp_ptr = name_first_match;
1884                         do
1885                         {
1886                             const char* tmp_ptr2;
1887                             tmp_ptr += name_len;
1888                             if( *tmp_ptr == '*' )
1889                                 return 1;
1890                             assert( *tmp_ptr == '{' );
1891                             tmp_ptr2 = strchr( tmp_ptr, '}' );
1892                             assert( tmp_ptr2 );
1893
1894                             if( cv_strnstr( tmp_ptr, (int)(tmp_ptr2 - tmp_ptr) + 1,
1895                                              method_name_ptr, method_name_len, 1 ))
1896                                 return 1 ^ inverse;
1897
1898                             tmp_ptr = cv_strnstr( tmp_ptr2, glob_len -
1899                                                    (int)(tmp_ptr2 - pattern),
1900                                                    name_ptr, name_len, 1 );
1901                         }
1902                         while( tmp_ptr );
1903
1904                         endptr--;
1905                         do c = *++endptr;
1906                         while( isspace(c) );
1907
1908                         if( c != ',' )
1909                             endptr--;
1910                     }
1911                 }
1912             }
1913             else
1914             {
1915                 assert( !c || isspace(c) || c == ',' );
1916                 name_len = (int)(endptr - name_ptr);
1917                 tmp_ptr = pattern;
1918
1919                 for(;;)
1920                 {
1921                     const char *tmp_ptr2, *tmp_ptr3;
1922
1923                     tmp_ptr = cv_strnstr( tmp_ptr, glob_len -
1924                         (int)(tmp_ptr - pattern), name_ptr, name_len, 1 );
1925
1926                     if( !tmp_ptr )
1927                         break;
1928
1929                     // make sure it is not a method
1930                     tmp_ptr2 = strchr( tmp_ptr, '}' );
1931                     if( !tmp_ptr2 )
1932                         return 1 ^ inverse;
1933
1934                     tmp_ptr3 = strchr( tmp_ptr, '{' );
1935                     if( tmp_ptr3 < tmp_ptr2 )
1936                         return 1 ^ inverse;
1937
1938                     tmp_ptr = tmp_ptr2 + 1;
1939                 }
1940
1941                 endptr--;
1942             }
1943
1944             do c = *++endptr;
1945             while( isspace(c) );
1946
1947             if( c == ',' )
1948                 endptr++;
1949             ptr = endptr;
1950         }
1951
1952         return 0 ^ inverse;
1953     }
1954 }
1955
1956 /* End of file. */