1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
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.
10 // Intel License Agreement
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
19 // * Redistribution's of source code must retain the above copyright notice,
20 // this list of conditions and the following disclaimer.
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.
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.
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.
45 /****************************************************************************************\
46 * Common macros and type definitions *
47 \****************************************************************************************/
49 #define cv_isprint(c) ((signed char)(c) >= (signed char)' ')
50 #define cv_isprint_or_tab(c) ((signed char)(c) >= (signed char)' ' || (c) == '\t')
52 static char* icv_itoa( int _val, char* buffer, int /*radix*/ )
55 char* ptr=buffer + 23 /* enough even for 64-bit integers */;
56 unsigned val = abs(_val);
61 unsigned r = val / radix;
62 *--ptr = (char)(val - (r*radix) + '0');
74 typedef struct CvGenericHash
82 typedef CvGenericHash CvStringHash;
84 typedef struct CvFileMapNode
87 const CvStringHashNode* key;
88 struct CvFileMapNode* next;
92 typedef struct CvXMLStackRecord
101 #define CV_XML_OPENING_TAG 1
102 #define CV_XML_CLOSING_TAG 2
103 #define CV_XML_EMPTY_TAG 3
104 #define CV_XML_HEADER_TAG 4
105 #define CV_XML_DIRECTIVE_TAG 5
107 //typedef void (*CvParse)( struct CvFileStorage* fs );
108 typedef void (*CvStartWriteStruct)( struct CvFileStorage* fs, const char* key,
109 int struct_flags, const char* type_name );
110 typedef void (*CvEndWriteStruct)( struct CvFileStorage* fs );
111 typedef void (*CvWriteInt)( struct CvFileStorage* fs, const char* key, int value );
112 typedef void (*CvWriteReal)( struct CvFileStorage* fs, const char* key, double value );
113 typedef void (*CvWriteString)( struct CvFileStorage* fs, const char* key,
114 const char* value, int quote );
115 typedef void (*CvWriteComment)( struct CvFileStorage* fs, const char* comment, int eol_comment );
116 typedef void (*CvStartNextStream)( struct CvFileStorage* fs );
118 typedef struct CvFileStorage
124 CvMemStorage* memstorage;
125 CvMemStorage* dststorage;
126 CvMemStorage* strstorage;
127 CvStringHash* str_hash;
145 CvStartWriteStruct start_write_struct;
146 CvEndWriteStruct end_write_struct;
147 CvWriteInt write_int;
148 CvWriteReal write_real;
149 CvWriteString write_string;
150 CvWriteComment write_comment;
151 CvStartNextStream start_next_stream;
157 #define CV_YML_INDENT 3
158 #define CV_XML_INDENT 2
159 #define CV_YML_INDENT_FLOW 1
160 #define CV_FS_MAX_LEN 4096
162 #define CV_FILE_STORAGE ('Y' + ('A' << 8) + ('M' << 16) + ('L' << 24))
163 #define CV_IS_FILE_STORAGE(fs) ((fs) != 0 && (fs)->flags == CV_FILE_STORAGE)
165 #define CV_CHECK_FILE_STORAGE(fs) \
167 if( !CV_IS_FILE_STORAGE(fs) ) \
168 CV_ERROR( (fs) ? CV_StsBadArg : CV_StsNullPtr, \
169 "Invalid pointer to file storage" ); \
172 #define CV_CHECK_OUTPUT_FILE_STORAGE(fs) \
174 CV_CHECK_FILE_STORAGE(fs); \
175 if( !fs->write_mode ) \
176 CV_ERROR( CV_StsError, "The file storage is opened for reading" ); \
180 cvAttrValue( const CvAttrList* attr, const char* attr_name )
182 while( attr && attr->attr )
185 for( i = 0; attr->attr[i*2] != 0; i++ )
187 if( strcmp( attr_name, attr->attr[i*2] ) == 0 )
188 return attr->attr[i*2+1];
197 static CvGenericHash*
198 cvCreateMap( int flags, int header_size, int elem_size,
199 CvMemStorage* storage, int start_tab_size )
201 CvGenericHash* map = 0;
203 CV_FUNCNAME( "cvCreateMap" );
207 if( header_size < (int)sizeof(CvGenericHash) )
208 CV_ERROR( CV_StsBadSize, "Too small map header_size" );
210 if( start_tab_size <= 0 )
213 CV_CALL( map = (CvGenericHash*)cvCreateSet( flags, header_size, elem_size, storage ));
215 map->tab_size = start_tab_size;
216 start_tab_size *= sizeof(map->table[0]);
217 CV_CALL( map->table = (void**)cvMemStorageAlloc( storage, start_tab_size ));
218 memset( map->table, 0, start_tab_size );
222 if( cvGetErrStatus() < 0 )
229 #define CV_PARSE_ERROR( errmsg ) \
231 icvParseError( fs, cvFuncName, (errmsg), __FILE__, __LINE__ ); \
237 icvParseError( CvFileStorage* fs, const char* func_name,
238 const char* err_msg, const char* source_file, int source_line )
241 sprintf( buf, "%s(%d): %s", fs->filename, fs->lineno, err_msg );
242 cvError( CV_StsParseError, func_name, buf, source_file, source_line );
247 icvFSCreateCollection( CvFileStorage* fs, int tag, CvFileNode* collection )
249 CV_FUNCNAME( "icvFSCreateCollection" );
253 if( CV_NODE_IS_MAP(tag) )
255 if( collection->tag != CV_NODE_NONE )
257 assert( fs->is_xml != 0 );
258 CV_PARSE_ERROR( "Sequence element should not have name (use <_></_>)" );
261 CV_CALL( collection->data.map = cvCreateMap( 0, sizeof(CvFileNodeHash),
262 sizeof(CvFileMapNode), fs->memstorage, 16 ));
267 CV_CALL( seq = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvFileNode), fs->memstorage ));
269 // if <collection> contains some scalar element, add it to the newly created collection
270 if( CV_NODE_TYPE(collection->tag) != CV_NODE_NONE )
271 cvSeqPush( seq, collection );
273 collection->data.seq = seq;
276 collection->tag = tag;
277 cvSetSeqBlockSize( collection->data.seq, 8 );
284 icvFSReleaseCollection( CvSeq* seq )
288 int is_map = CV_IS_SET(seq);
290 int i, total = seq->total;
291 cvStartReadSeq( seq, &reader, 0 );
293 for( i = 0; i < total; i++ )
295 CvFileNode* node = (CvFileNode*)reader.ptr;
297 if( (!is_map || CV_IS_SET_ELEM( node )) && CV_NODE_IS_COLLECTION(node->tag) )
299 if( CV_NODE_IS_USER(node->tag) && node->info && node->data.obj.decoded )
300 cvRelease( (void**)&node->data.obj.decoded );
301 if( !CV_NODE_SEQ_IS_SIMPLE( node->data.seq ))
302 icvFSReleaseCollection( node->data.seq );
304 CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
311 icvFSDoResize( CvFileStorage* fs, char* ptr, int len )
314 CV_FUNCNAME( "icvFSDoResize" );
318 int written_len = (int)(ptr - fs->buffer_start);
319 int new_size = (int)((fs->buffer_end - fs->buffer_start)*3/2);
320 new_size = MAX( written_len + len, new_size );
321 CV_CALL( new_ptr = (char*)cvAlloc( new_size + 256 ));
322 fs->buffer = new_ptr + (fs->buffer - fs->buffer_start);
323 if( written_len > 0 )
324 memcpy( new_ptr, fs->buffer_start, written_len );
325 fs->buffer_start = new_ptr;
326 fs->buffer_end = fs->buffer_start + new_size;
327 new_ptr += written_len;
335 inline char* icvFSResizeWriteBuffer( CvFileStorage* fs, char* ptr, int len )
337 return ptr + len < fs->buffer_end ? ptr : icvFSDoResize( fs, ptr, len );
342 icvFSFlush( CvFileStorage* fs )
344 char* ptr = fs->buffer;
347 if( ptr > fs->buffer_start + fs->space )
351 fputs( fs->buffer_start, fs->file );
352 fs->buffer = fs->buffer_start;
355 indent = fs->struct_indent;
357 if( fs->space != indent )
359 if( fs->space < indent )
360 memset( fs->buffer_start + fs->space, ' ', indent - fs->space );
364 ptr = fs->buffer = fs->buffer_start + fs->space;
370 /* closes file storage and deallocates buffers */
372 cvReleaseFileStorage( CvFileStorage** p_fs )
374 CV_FUNCNAME("cvReleaseFileStorage" );
379 CV_ERROR( CV_StsNullPtr, "NULL double pointer to file storage" );
383 CvFileStorage* fs = *p_fs;
386 if( fs->write_mode && fs->file )
388 if( fs->write_stack )
390 while( fs->write_stack->total > 0 )
391 cvEndWriteStruct(fs);
395 fputs("</opencv_storage>\n", fs->file );
398 //icvFSReleaseCollection( fs->roots ); // delete all the user types recursively
406 cvReleaseMemStorage( &fs->strstorage );
408 cvFree( &fs->buffer_start );
409 cvReleaseMemStorage( &fs->memstorage );
411 memset( fs, 0, sizeof(*fs) );
419 #define CV_HASHVAL_SCALE 33
421 CV_IMPL CvStringHashNode*
422 cvGetHashedKey( CvFileStorage* fs, const char* str, int len, int create_missing )
424 CvStringHashNode* node = 0;
425 CV_FUNCNAME( "cvGetHashedKey" );
429 unsigned hashval = 0;
431 CvStringHash* map = fs->str_hash;
438 for( i = 0; str[i] != '\0'; i++ )
439 hashval = hashval*CV_HASHVAL_SCALE + (unsigned char)str[i];
442 else for( i = 0; i < len; i++ )
443 hashval = hashval*CV_HASHVAL_SCALE + (unsigned char)str[i];
446 tab_size = map->tab_size;
447 if( (tab_size & (tab_size - 1)) == 0 )
448 i = (int)(hashval & (tab_size - 1));
450 i = (int)(hashval % tab_size);
452 for( node = (CvStringHashNode*)(map->table[i]); node != 0; node = node->next )
454 if( node->hashval == hashval &&
455 node->str.len == len &&
456 memcmp( node->str.ptr, str, len ) == 0 )
460 if( !node && create_missing )
462 node = (CvStringHashNode*)cvSetNew( (CvSet*)map );
463 node->hashval = hashval;
464 CV_CALL( node->str = cvMemStorageAllocString( map->storage, str, len ));
465 node->next = (CvStringHashNode*)(map->table[i]);
466 map->table[i] = node;
476 cvGetFileNode( CvFileStorage* fs, CvFileNode* _map_node,
477 const CvStringHashNode* key,
480 CvFileNode* value = 0;
482 CV_FUNCNAME( "cvGetFileNode" );
486 int k = 0, attempts = 1;
491 CV_CHECK_FILE_STORAGE(fs);
494 CV_ERROR( CV_StsNullPtr, "Null key element" );
500 attempts = fs->roots->total;
503 for( k = 0; k < attempts; k++ )
506 CvFileNode* map_node = _map_node;
507 CvFileMapNode* another;
511 map_node = (CvFileNode*)cvGetSeqElem( fs->roots, k );
513 if( !CV_NODE_IS_MAP(map_node->tag) )
515 if( (!CV_NODE_IS_SEQ(map_node->tag) || map_node->data.seq->total != 0) &&
516 CV_NODE_TYPE(map_node->tag) != CV_NODE_NONE )
517 CV_ERROR( CV_StsError, "The node is neither a map nor an empty collection" );
521 map = map_node->data.map;
522 tab_size = map->tab_size;
524 if( (tab_size & (tab_size - 1)) == 0 )
525 i = (int)(key->hashval & (tab_size - 1));
527 i = (int)(key->hashval % tab_size);
529 for( another = (CvFileMapNode*)(map->table[i]); another != 0; another = another->next )
530 if( another->key == key )
532 if( !create_missing )
534 value = &another->value;
537 CV_PARSE_ERROR( "Duplicated key" );
540 if( k == attempts - 1 && create_missing )
542 CvFileMapNode* node = (CvFileMapNode*)cvSetNew( (CvSet*)map );
545 node->next = (CvFileMapNode*)(map->table[i]);
546 map->table[i] = node;
547 value = (CvFileNode*)node;
558 cvGetFileNodeByName( const CvFileStorage* fs, const CvFileNode* _map_node, const char* str )
560 CvFileNode* value = 0;
561 CV_FUNCNAME( "cvGetFileNodeByName" );
565 int i, len, tab_size;
566 unsigned hashval = 0;
567 int k = 0, attempts = 1;
572 CV_CHECK_FILE_STORAGE(fs);
575 CV_ERROR( CV_StsNullPtr, "Null element name" );
577 for( i = 0; str[i] != '\0'; i++ )
578 hashval = hashval*CV_HASHVAL_SCALE + (unsigned char)str[i];
586 attempts = fs->roots->total;
589 for( k = 0; k < attempts; k++ )
592 const CvFileNode* map_node = _map_node;
593 CvFileMapNode* another;
596 map_node = (CvFileNode*)cvGetSeqElem( fs->roots, k );
598 if( !CV_NODE_IS_MAP(map_node->tag) )
600 if( (!CV_NODE_IS_SEQ(map_node->tag) || map_node->data.seq->total != 0) &&
601 CV_NODE_TYPE(map_node->tag) != CV_NODE_NONE )
602 CV_ERROR( CV_StsError, "The node is neither a map nor an empty collection" );
606 map = map_node->data.map;
607 tab_size = map->tab_size;
609 if( (tab_size & (tab_size - 1)) == 0 )
610 i = (int)(hashval & (tab_size - 1));
612 i = (int)(hashval % tab_size);
614 for( another = (CvFileMapNode*)(map->table[i]); another != 0; another = another->next )
616 const CvStringHashNode* key = another->key;
618 if( key->hashval == hashval &&
619 key->str.len == len &&
620 memcmp( key->str.ptr, str, len ) == 0 )
622 value = &another->value;
635 cvGetRootFileNode( const CvFileStorage* fs, int stream_index )
637 CvFileNode* value = 0;
638 CV_FUNCNAME( "cvGetRootFileNode" );
642 CV_CHECK_FILE_STORAGE(fs);
644 if( !fs->roots || (unsigned)stream_index >= (unsigned)fs->roots->total )
647 value = (CvFileNode*)cvGetSeqElem( fs->roots, stream_index );
655 /* returns the sequence element by its index */
656 /*CV_IMPL CvFileNode*
657 cvGetFileNodeFromSeq( CvFileStorage* fs,
658 CvFileNode* seq_node, int index )
660 CvFileNode* value = 0;
662 CV_FUNCNAME( "cvGetFileNodeFromSeq" );
670 else if( !CV_NODE_IS_SEQ(seq_node->tag) )
672 if( CV_NODE_IS_MAP(seq_node->tag) )
673 CV_ERROR( CV_StsError, "The node is map. Use cvGetFileNodeFromMap()." );
674 if( CV_NODE_TYPE(seq_node->tag) == CV_NODE_NONE )
675 CV_ERROR( CV_StsError, "The node is an empty object (None)." );
676 if( index != 0 && index != -1 )
677 CV_ERROR( CV_StsOutOfRange, "" );
682 seq = seq_node->data.seq;
685 CV_ERROR( CV_StsNullPtr, "The file storage is empty" );
687 value = (CvFileNode*)cvGetSeqElem( seq, index, 0 );
696 icvDoubleToString( char* buf, double value )
702 ieee754_hi = (unsigned)(val.u >> 32);
704 if( (ieee754_hi & 0x7ff00000) != 0x7ff00000 )
706 int ivalue = cvRound(value);
707 if( ivalue == value )
708 sprintf( buf, "%d.", ivalue );
711 static const char* fmt[] = {"%.16e", "%.16f"};
712 double avalue = fabs(value);
714 sprintf( buf, fmt[0.01 <= avalue && avalue < 1000], value );
715 if( *ptr == '+' || *ptr == '-' )
717 for( ; isdigit(*ptr); ptr++ )
725 unsigned ieee754_lo = (unsigned)val.u;
726 if( (ieee754_hi & 0x7fffffff) + (ieee754_lo != 0) > 0x7ff00000 )
727 strcpy( buf, ".Nan" );
729 strcpy( buf, (int)ieee754_hi < 0 ? "-.Inf" : ".Inf" );
737 icvFloatToString( char* buf, float value )
744 if( (ieee754 & 0x7f800000) != 0x7f800000 )
746 int ivalue = cvRound(value);
747 if( ivalue == value )
748 sprintf( buf, "%d.", ivalue );
751 static const char* fmt[] = {"%.8e", "%.8f"};
752 double avalue = fabs((double)value);
754 sprintf( buf, fmt[0.01 <= avalue && avalue < 1000], value );
755 if( *ptr == '+' || *ptr == '-' )
757 for( ; isdigit(*ptr); ptr++ )
765 if( (ieee754 & 0x7fffffff) != 0x7f800000 )
766 strcpy( buf, ".Nan" );
768 strcpy( buf, (int)ieee754 < 0 ? "-.Inf" : ".Inf" );
776 icvProcessSpecialDouble( CvFileStorage* fs, char* buf, double* value, char** endptr )
778 CV_FUNCNAME( "icvProcessSpecialDouble" );
783 int inf_hi = 0x7ff00000;
785 if( c == '-' || c == '+' )
787 inf_hi = c == '-' ? 0xfff00000 : 0x7ff00000;
792 CV_PARSE_ERROR( "Bad format of floating-point constant" );
794 if( toupper(buf[1]) == 'I' && toupper(buf[2]) == 'N' && toupper(buf[3]) == 'F' )
795 *(uint64*)value = ((uint64)inf_hi << 32);
796 else if( toupper(buf[1]) == 'N' && toupper(buf[2]) == 'A' && toupper(buf[3]) == 'N' )
797 *(uint64*)value = (uint64)-1;
799 CV_PARSE_ERROR( "Bad format of floating-point constant" );
807 static double icv_strtod( CvFileStorage* fs, char* ptr, char** endptr )
809 double fval = strtod( ptr, endptr );
810 if( **endptr == '.' )
812 char* dot_pos = *endptr;
814 double fval2 = strtod( ptr, endptr );
816 if( *endptr > dot_pos )
822 if( *endptr == ptr || isalpha(**endptr) )
823 icvProcessSpecialDouble( fs, ptr, &fval, endptr );
829 /****************************************************************************************\
831 \****************************************************************************************/
834 icvYMLSkipSpaces( CvFileStorage* fs, char* ptr, int min_indent, int max_comment_indent )
836 CV_FUNCNAME( "icvYMLSkipSpaces" );
846 if( ptr - fs->buffer_start > max_comment_indent )
850 else if( cv_isprint(*ptr) )
852 if( ptr - fs->buffer_start < min_indent )
853 CV_PARSE_ERROR( "Incorrect indentation" );
856 else if( *ptr == '\0' || *ptr == '\n' || *ptr == '\r' )
858 int max_size = (int)(fs->buffer_end - fs->buffer_start);
859 ptr = fgets( fs->buffer_start, max_size, fs->file );
862 // emulate end of stream
863 ptr = fs->buffer_start;
864 ptr[0] = ptr[1] = ptr[2] = '.';
871 int l = (int)strlen(ptr);
872 if( ptr[l-1] != '\n' && ptr[l-1] != '\r' && !feof(fs->file) )
873 CV_PARSE_ERROR( "Too long string or a last string w/o newline" );
879 CV_PARSE_ERROR( *ptr == '\t' ? "Tabs are prohibited in YAML!" : "Invalid character" );
889 icvYMLParseKey( CvFileStorage* fs, char* ptr,
890 CvFileNode* map_node, CvFileNode** value_placeholder )
892 CV_FUNCNAME( "icvYMLParseKey" );
897 char *endptr = ptr - 1, *saveptr;
898 CvStringHashNode* str_hash_node;
901 CV_PARSE_ERROR( "Key may not start with \'-\'" );
904 while( cv_isprint(c) && c != ':' );
907 CV_PARSE_ERROR( "Missing \':\'" );
909 saveptr = endptr + 1;
915 CV_PARSE_ERROR( "An empty key" );
917 CV_CALL( str_hash_node = cvGetHashedKey( fs, ptr, (int)(endptr - ptr), 1 ));
918 CV_CALL( *value_placeholder = cvGetFileNode( fs, map_node, str_hash_node, 1 ));
928 icvYMLParseValue( CvFileStorage* fs, char* ptr, CvFileNode* node,
929 int parent_flags, int min_indent )
931 CV_FUNCNAME( "icvYMLParseValue" );
935 char buf[CV_FS_MAX_LEN + 1024];
937 char c = ptr[0], d = ptr[1];
938 int is_parent_flow = CV_NODE_IS_FLOW(parent_flags);
939 int value_type = CV_NODE_NONE;
942 memset( node, 0, sizeof(*node) );
944 if( c == '!' ) // handle explicit type specification
946 if( d == '!' || d == '^' )
949 value_type |= CV_NODE_USER;
954 while( cv_isprint(d) && d != ' ' );
955 len = (int)(endptr - ptr);
957 CV_PARSE_ERROR( "Empty type name" );
961 if( len == 3 && !CV_NODE_IS_USER(value_type) )
963 if( memcmp( ptr, "str", 3 ) == 0 )
964 value_type = CV_NODE_STRING;
965 else if( memcmp( ptr, "int", 3 ) == 0 )
966 value_type = CV_NODE_INT;
967 else if( memcmp( ptr, "seq", 3 ) == 0 )
968 value_type = CV_NODE_SEQ;
969 else if( memcmp( ptr, "map", 3 ) == 0 )
970 value_type = CV_NODE_MAP;
972 else if( len == 5 && !CV_NODE_IS_USER(value_type) )
974 if( memcmp( ptr, "float", 5 ) == 0 )
975 value_type = CV_NODE_REAL;
977 else if( CV_NODE_IS_USER(value_type) )
979 CV_CALL( node->info = cvFindType( ptr ));
981 node->tag &= ~CV_NODE_USER;
985 CV_CALL( ptr = icvYMLSkipSpaces( fs, endptr, min_indent, INT_MAX ));
989 if( !CV_NODE_IS_USER(value_type) )
991 if( value_type == CV_NODE_STRING && c != '\'' && c != '\"' )
993 if( value_type == CV_NODE_INT )
995 if( value_type == CV_NODE_REAL )
1001 (c == '-' || c == '+') && (isdigit(d) || d == '.') ||
1002 c == '.' && isalnum(d)) // a number
1006 endptr = ptr + (c == '-' || c == '+');
1007 while( isdigit(*endptr) )
1009 if( *endptr == '.' || *endptr == 'e' )
1012 fval = icv_strtod( fs, ptr, &endptr );
1013 /*if( endptr == ptr || isalpha(*endptr) )
1014 CV_CALL( icvProcessSpecialDouble( fs, endptr, &fval, &endptr ));*/
1016 node->tag = CV_NODE_REAL;
1017 node->data.f = fval;
1022 ival = (int)strtol( ptr, &endptr, 0 );
1023 node->tag = CV_NODE_INT;
1024 node->data.i = ival;
1027 if( !endptr || endptr == ptr )
1028 CV_PARSE_ERROR( "Invalid numeric value (inconsistent explicit type specification?)" );
1032 else if( c == '\'' || c == '\"' ) // an explicit string
1034 node->tag = CV_NODE_STRING;
1036 for( len = 0; len < CV_FS_MAX_LEN; )
1039 if( isalnum(c) || (c != '\'' && cv_isprint(c)))
1041 else if( c == '\'' )
1049 CV_PARSE_ERROR( "Invalid character" );
1052 for( len = 0; len < CV_FS_MAX_LEN; )
1055 if( isalnum(c) || (c != '\\' && c != '\"' && cv_isprint(c)))
1057 else if( c == '\"' )
1062 else if( c == '\\' )
1067 else if( d == '\"' || d == '\\' || d == '\'' )
1075 else if( d == 'x' || isdigit(d) && d < '8' )
1077 int val, is_hex = d == 'x';
1080 val = strtol( ptr + is_hex, &endptr, is_hex ? 8 : 16 );
1082 if( endptr == ptr + is_hex )
1086 buf[len++] = (char)val;
1092 CV_PARSE_ERROR( "Invalid character" );
1095 if( len >= CV_FS_MAX_LEN )
1096 CV_PARSE_ERROR( "Too long string literal" );
1098 CV_CALL( node->data.str = cvMemStorageAllocString( fs->memstorage, buf, len ));
1100 else if( c == '[' || c == '{' ) // collection as a flow
1102 int new_min_indent = min_indent + !is_parent_flow;
1103 int struct_flags = CV_NODE_FLOW + (c == '{' ? CV_NODE_MAP : CV_NODE_SEQ);
1106 CV_CALL( icvFSCreateCollection( fs, CV_NODE_TYPE(struct_flags) +
1107 (node->info ? CV_NODE_USER : 0), node ));
1109 d = c == '[' ? ']' : '}';
1113 CvFileNode* elem = 0;
1115 CV_CALL( ptr = icvYMLSkipSpaces( fs, ptr, new_min_indent, INT_MAX ));
1116 if( *ptr == '}' || *ptr == ']' )
1119 CV_PARSE_ERROR( "The wrong closing bracket" );
1124 if( node->data.seq->total != 0 )
1127 CV_PARSE_ERROR( "Missing , between the elements" );
1128 CV_CALL( ptr = icvYMLSkipSpaces( fs, ptr + 1, new_min_indent, INT_MAX ));
1131 if( CV_NODE_IS_MAP(struct_flags) )
1133 CV_CALL( ptr = icvYMLParseKey( fs, ptr, node, &elem ));
1134 CV_CALL( ptr = icvYMLSkipSpaces( fs, ptr, new_min_indent, INT_MAX ));
1140 elem = (CvFileNode*)cvSeqPush( node->data.seq, 0 );
1142 CV_CALL( ptr = icvYMLParseValue( fs, ptr, elem, struct_flags, new_min_indent ));
1143 if( CV_NODE_IS_MAP(struct_flags) )
1144 elem->tag |= CV_NODE_NAMED;
1145 is_simple &= !CV_NODE_IS_COLLECTION(elem->tag);
1147 node->data.seq->flags |= is_simple ? CV_NODE_SEQ_SIMPLE : 0;
1151 int indent, struct_flags, is_simple;
1153 if( is_parent_flow || c != '-' )
1155 // implicit (one-line) string or nested block-style collection
1156 if( !is_parent_flow )
1159 CV_PARSE_ERROR( "Complex keys are not supported" );
1160 if( c == '|' || c == '>' )
1161 CV_PARSE_ERROR( "Multi-line text literals are not supported" );
1168 while( cv_isprint(c) &&
1169 (!is_parent_flow || c != ',' && c != '}' && c != ']') &&
1170 (is_parent_flow || c != ':' || value_type == CV_NODE_STRING));
1173 CV_PARSE_ERROR( "Invalid character" );
1175 if( is_parent_flow || c != ':' )
1177 char* str_end = endptr;
1178 node->tag = CV_NODE_STRING;
1179 // strip spaces in the end of string
1181 while( str_end > ptr && c == ' ' );
1183 CV_CALL( node->data.str = cvMemStorageAllocString( fs->memstorage, ptr, (int)(str_end - ptr) ));
1187 struct_flags = CV_NODE_MAP;
1190 struct_flags = CV_NODE_SEQ;
1192 CV_CALL( icvFSCreateCollection( fs, struct_flags +
1193 (node->info ? CV_NODE_USER : 0), node ));
1195 indent = (int)(ptr - fs->buffer_start);
1200 CvFileNode* elem = 0;
1202 if( CV_NODE_IS_MAP(struct_flags) )
1204 CV_CALL( ptr = icvYMLParseKey( fs, ptr, node, &elem ));
1210 CV_PARSE_ERROR( "Block sequence elements must be preceded with \'-\'" );
1212 CV_CALL( elem = (CvFileNode*)cvSeqPush( node->data.seq, 0 ));
1215 CV_CALL( ptr = icvYMLSkipSpaces( fs, ptr, indent + 1, INT_MAX ));
1216 CV_CALL( ptr = icvYMLParseValue( fs, ptr, elem, struct_flags, indent + 1 ));
1217 if( CV_NODE_IS_MAP(struct_flags) )
1218 elem->tag |= CV_NODE_NAMED;
1219 is_simple &= !CV_NODE_IS_COLLECTION(elem->tag);
1221 CV_CALL( ptr = icvYMLSkipSpaces( fs, ptr, 0, INT_MAX ));
1222 if( ptr - fs->buffer_start != indent )
1224 if( ptr - fs->buffer_start < indent )
1227 CV_PARSE_ERROR( "Incorrect indentation" );
1229 if( memcmp( ptr, "...", 3 ) == 0 )
1233 node->data.seq->flags |= is_simple ? CV_NODE_SEQ_SIMPLE : 0;
1243 icvYMLParse( CvFileStorage* fs )
1245 CV_FUNCNAME( "icvYMLParse" );
1249 char* ptr = fs->buffer_start;
1254 // 0. skip leading comments and directives and ...
1255 // 1. reach the first item
1258 CV_CALL( ptr = icvYMLSkipSpaces( fs, ptr, 0, INT_MAX ));
1264 if( memcmp( ptr, "%YAML:", 6 ) == 0 &&
1265 memcmp( ptr, "%YAML:1.", 8 ) != 0 )
1266 CV_PARSE_ERROR( "Unsupported YAML version (it must be 1.x)" );
1269 else if( *ptr == '-' )
1271 if( memcmp(ptr, "---", 3) == 0 )
1279 else if( isalnum(*ptr) || *ptr=='_')
1282 CV_PARSE_ERROR( "The YAML streams must start with '---', except the first one" );
1286 CV_PARSE_ERROR( "Invalid or unsupported syntax" );
1289 CV_CALL( ptr = icvYMLSkipSpaces( fs, ptr, 0, INT_MAX ));
1290 if( memcmp( ptr, "...", 3 ) != 0 )
1292 // 2. parse the collection
1293 CvFileNode* root_node = (CvFileNode*)cvSeqPush( fs->roots, 0 );
1295 CV_CALL( ptr = icvYMLParseValue( fs, ptr, root_node, CV_NODE_NONE, 0 ));
1296 if( !CV_NODE_IS_COLLECTION(root_node->tag) )
1297 CV_PARSE_ERROR( "Only collections as YAML streams are supported by this parser" );
1299 // 3. parse until the end of file or next collection
1300 CV_CALL( ptr = icvYMLSkipSpaces( fs, ptr, 0, INT_MAX ));
1315 /****************************************************************************************\
1317 \****************************************************************************************/
1320 icvYMLWrite( CvFileStorage* fs, const char* key, const char* data, const char* cvFuncName )
1322 //CV_FUNCNAME( "icvYMLWrite" );
1331 struct_flags = fs->struct_flags;
1333 if( key && key[0] == '\0' )
1336 if( CV_NODE_IS_COLLECTION(struct_flags) )
1338 if( (CV_NODE_IS_MAP(struct_flags) ^ (key != 0)) )
1339 CV_ERROR( CV_StsBadArg, "An attempt to add element without a key to a map, "
1340 "or add element with key to sequence" );
1345 struct_flags = CV_NODE_EMPTY | (key ? CV_NODE_MAP : CV_NODE_SEQ);
1350 keylen = (int)strlen(key);
1352 CV_ERROR( CV_StsBadArg, "The key is an empty" );
1354 if( keylen > CV_FS_MAX_LEN )
1355 CV_ERROR( CV_StsBadArg, "The key is too long" );
1359 datalen = (int)strlen(data);
1361 if( CV_NODE_IS_FLOW(struct_flags) )
1365 if( !CV_NODE_IS_EMPTY(struct_flags) )
1367 new_offset = (int)(ptr - fs->buffer_start) + keylen + datalen;
1368 if( new_offset > fs->wrap_margin && new_offset - fs->struct_indent > 10 )
1371 ptr = icvFSFlush(fs);
1378 ptr = icvFSFlush(fs);
1379 if( !CV_NODE_IS_MAP(struct_flags) )
1389 if( !isalpha(key[0]) && key[0] != '_' )
1390 CV_ERROR( CV_StsBadArg, "Key must start with a letter or _" );
1392 ptr = icvFSResizeWriteBuffer( fs, ptr, keylen );
1394 for( i = 0; i < keylen; i++ )
1399 if( !isalnum(c) && c != '-' && c != '_' && c != ' ' )
1400 CV_ERROR( CV_StsBadArg, "Invalid character occurs in the key" );
1405 if( !CV_NODE_IS_FLOW(struct_flags) && data )
1411 ptr = icvFSResizeWriteBuffer( fs, ptr, datalen );
1412 memcpy( ptr, data, datalen );
1417 fs->struct_flags = struct_flags & ~CV_NODE_EMPTY;
1424 icvYMLStartWriteStruct( CvFileStorage* fs, const char* key, int struct_flags,
1425 const char* type_name CV_DEFAULT(0))
1427 CV_FUNCNAME( "icvYMLStartWriteStruct" );
1432 char buf[CV_FS_MAX_LEN + 1024];
1433 const char* data = 0;
1435 struct_flags = (struct_flags & (CV_NODE_TYPE_MASK|CV_NODE_FLOW)) | CV_NODE_EMPTY;
1436 if( !CV_NODE_IS_COLLECTION(struct_flags))
1437 CV_ERROR( CV_StsBadArg,
1438 "Some collection type - CV_NODE_SEQ or CV_NODE_MAP, must be specified" );
1440 if( CV_NODE_IS_FLOW(struct_flags) )
1442 char c = CV_NODE_IS_MAP(struct_flags) ? '{' : '[';
1443 struct_flags |= CV_NODE_FLOW;
1446 sprintf( buf, "!!%s %c", type_name, c );
1454 else if( type_name )
1456 sprintf( buf, "!!%s", type_name );
1460 CV_CALL( icvYMLWrite( fs, key, data, cvFuncName ));
1462 parent_flags = fs->struct_flags;
1463 cvSeqPush( fs->write_stack, &parent_flags );
1464 fs->struct_flags = struct_flags;
1466 if( !CV_NODE_IS_FLOW(parent_flags) )
1467 fs->struct_indent += CV_YML_INDENT + CV_NODE_IS_FLOW(struct_flags);
1474 icvYMLEndWriteStruct( CvFileStorage* fs )
1476 CV_FUNCNAME( "icvYMLEndWriteStruct" );
1480 int parent_flags = 0, struct_flags;
1483 struct_flags = fs->struct_flags;
1484 if( fs->write_stack->total == 0 )
1485 CV_ERROR( CV_StsError, "EndWriteStruct w/o matching StartWriteStruct" );
1487 cvSeqPop( fs->write_stack, &parent_flags );
1489 if( CV_NODE_IS_FLOW(struct_flags) )
1492 if( ptr > fs->buffer_start + fs->struct_indent && !CV_NODE_IS_EMPTY(struct_flags) )
1494 *ptr++ = CV_NODE_IS_MAP(struct_flags) ? '}' : ']';
1497 else if( CV_NODE_IS_EMPTY(struct_flags) )
1499 ptr = icvFSFlush(fs);
1500 memcpy( ptr, CV_NODE_IS_MAP(struct_flags) ? "{}" : "[]", 2 );
1501 fs->buffer = ptr + 2;
1504 if( !CV_NODE_IS_FLOW(parent_flags) )
1505 fs->struct_indent -= CV_YML_INDENT + CV_NODE_IS_FLOW(struct_flags);
1506 assert( fs->struct_indent >= 0 );
1508 fs->struct_flags = parent_flags;
1515 icvYMLStartNextStream( CvFileStorage* fs )
1517 //CV_FUNCNAME( "icvYMLStartNextStream" );
1523 while( fs->write_stack->total > 0 )
1524 icvYMLEndWriteStruct(fs);
1526 fs->struct_indent = 0;
1528 fputs( "...\n", fs->file );
1529 fputs( "---\n", fs->file );
1530 fs->buffer = fs->buffer_start;
1538 icvYMLWriteInt( CvFileStorage* fs, const char* key, int value )
1540 CV_FUNCNAME( "icvYMLWriteInt" );
1545 CV_CALL( icvYMLWrite( fs, key, icv_itoa( value, buf, 10 ), cvFuncName ));
1552 icvYMLWriteReal( CvFileStorage* fs, const char* key, double value )
1554 CV_FUNCNAME( "icvYMLWriteReal" );
1559 CV_CALL( icvYMLWrite( fs, key, icvDoubleToString( buf, value ), cvFuncName ));
1566 icvYMLWriteString( CvFileStorage* fs, const char* key,
1567 const char* str, int quote CV_DEFAULT(0))
1569 CV_FUNCNAME( "icvYMLWriteString" );
1573 char buf[CV_FS_MAX_LEN*4+16];
1574 char* data = (char*)str;
1578 CV_ERROR( CV_StsNullPtr, "Null string pointer" );
1580 len = (int)strlen(str);
1581 if( len > CV_FS_MAX_LEN )
1582 CV_ERROR( CV_StsBadArg, "The written string is too long" );
1584 if( quote || len == 0 || str[0] != str[len-1] || str[0] != '\"' && str[0] != '\'' )
1586 int need_quote = quote || len == 0;
1589 for( i = 0; i < len; i++ )
1593 if( !need_quote && !isalnum(c) && c != '_' && c != ' ' && c != '-' &&
1594 c != '(' && c != ')' && c != '/' && c != '+' && c != ';' )
1597 if( !isalnum(c) && (!cv_isprint(c) || c == '\\' || c == '\'' || c == '\"') )
1602 else if( c == '\n' )
1604 else if( c == '\r' )
1606 else if( c == '\t' )
1610 sprintf( data, "x%02x", c );
1617 if( !need_quote && (isdigit(str[0]) ||
1618 str[0] == '+' || str[0] == '-' || str[0] == '.' ))
1624 data = buf + !need_quote;
1627 CV_CALL( icvYMLWrite( fs, key, data, cvFuncName ));
1634 icvYMLWriteComment( CvFileStorage* fs, const char* comment, int eol_comment )
1636 CV_FUNCNAME( "icvYMLWriteComment" );
1640 int len; //, indent;
1646 CV_ERROR( CV_StsNullPtr, "Null comment" );
1648 len = (int)strlen(comment);
1649 eol = strchr(comment, '\n');
1650 multiline = eol != 0;
1653 if( !eol_comment || multiline ||
1654 fs->buffer_end - ptr < len || ptr == fs->buffer_start )
1655 ptr = icvFSFlush( fs );
1665 ptr = icvFSResizeWriteBuffer( fs, ptr, (int)(eol - comment) + 1 );
1666 memcpy( ptr, comment, eol - comment + 1 );
1667 fs->buffer = ptr + (eol - comment);
1669 eol = strchr( comment, '\n' );
1673 len = (int)strlen(comment);
1674 ptr = icvFSResizeWriteBuffer( fs, ptr, len );
1675 memcpy( ptr, comment, len );
1676 fs->buffer = ptr + len;
1679 ptr = icvFSFlush( fs );
1686 /****************************************************************************************\
1688 \****************************************************************************************/
1690 #define CV_XML_INSIDE_COMMENT 1
1691 #define CV_XML_INSIDE_TAG 2
1692 #define CV_XML_INSIDE_DIRECTIVE 3
1695 icvXMLSkipSpaces( CvFileStorage* fs, char* ptr, int mode )
1697 CV_FUNCNAME( "icvXMLSkipSpaces" );
1708 if( mode == CV_XML_INSIDE_COMMENT )
1711 while( cv_isprint_or_tab(c) && (c != '-' || ptr[1] != '-' || ptr[2] != '>') );
1715 assert( ptr[1] == '-' && ptr[2] == '>' );
1720 else if( mode == CV_XML_INSIDE_DIRECTIVE )
1722 // !!!NOTE!!! This is not quite correct, but should work in most cases
1730 } while( cv_isprint_or_tab(c) );
1735 while( c == ' ' || c == '\t' );
1737 if( c == '<' && ptr[1] == '!' && ptr[2] == '-' && ptr[3] == '-' )
1740 CV_PARSE_ERROR( "Comments are not allowed here" );
1741 mode = CV_XML_INSIDE_COMMENT;
1744 else if( cv_isprint(c) )
1748 if( !cv_isprint(*ptr) )
1750 int max_size = (int)(fs->buffer_end - fs->buffer_start);
1751 if( *ptr != '\0' && *ptr != '\n' && *ptr != '\r' )
1752 CV_PARSE_ERROR( "Invalid character in the stream" );
1753 ptr = fgets( fs->buffer_start, max_size, fs->file );
1756 ptr = fs->buffer_start;
1763 int l = (int)strlen(ptr);
1764 if( ptr[l-1] != '\n' && ptr[l-1] != '\r' && !feof(fs->file) )
1765 CV_PARSE_ERROR( "Too long string or a last string w/o newline" );
1778 icvXMLParseTag( CvFileStorage* fs, char* ptr, CvStringHashNode** _tag,
1779 CvAttrList** _list, int* _tag_type );
1782 icvXMLParseValue( CvFileStorage* fs, char* ptr, CvFileNode* node,
1783 int value_type CV_DEFAULT(CV_NODE_NONE))
1785 CV_FUNCNAME( "icvXMLParseValue" );
1789 CvFileNode *elem = node;
1790 int have_space = 1, is_simple = 1;
1791 int is_user_type = CV_NODE_IS_USER(value_type);
1792 memset( node, 0, sizeof(*node) );
1794 value_type = CV_NODE_TYPE(value_type);
1801 if( isspace(c) || c == '\0' || c == '<' && ptr[1] == '!' && ptr[2] == '-' )
1803 CV_CALL( ptr = icvXMLSkipSpaces( fs, ptr, 0 ));
1812 CvStringHashNode *key = 0, *key2 = 0;
1813 CvAttrList* list = 0;
1814 CvTypeInfo* info = 0;
1817 const char* type_name = 0;
1818 int elem_type = CV_NODE_NONE;
1823 CV_CALL( ptr = icvXMLParseTag( fs, ptr, &key, &list, &tag_type ));
1825 if( tag_type == CV_XML_DIRECTIVE_TAG )
1826 CV_PARSE_ERROR( "Directive tags are not allowed here" );
1827 if( tag_type == CV_XML_EMPTY_TAG )
1828 CV_PARSE_ERROR( "Empty tags are not supported" );
1830 assert( tag_type == CV_XML_OPENING_TAG );
1832 type_name = list ? cvAttrValue( list, "type_id" ) : 0;
1835 if( strcmp( type_name, "str" ) == 0 )
1836 elem_type = CV_NODE_STRING;
1837 else if( strcmp( type_name, "map" ) == 0 )
1838 elem_type = CV_NODE_MAP;
1839 else if( strcmp( type_name, "seq" ) == 0 )
1840 elem_type = CV_NODE_MAP;
1843 CV_CALL( info = cvFindType( type_name ));
1845 elem_type = CV_NODE_USER;
1849 is_noname = key->str.len == 1 && key->str.ptr[0] == '_';
1850 if( !CV_NODE_IS_COLLECTION(node->tag) )
1852 CV_CALL( icvFSCreateCollection( fs, is_noname ? CV_NODE_SEQ : CV_NODE_MAP, node ));
1854 else if( is_noname ^ CV_NODE_IS_SEQ(node->tag) )
1855 CV_PARSE_ERROR( is_noname ? "Map element should have a name" :
1856 "Sequence element should not have name (use <_></_>)" );
1859 elem = (CvFileNode*)cvSeqPush( node->data.seq, 0 );
1861 CV_CALL( elem = cvGetFileNode( fs, node, key, 1 ));
1863 CV_CALL( ptr = icvXMLParseValue( fs, ptr, elem, elem_type));
1865 elem->tag |= CV_NODE_NAMED;
1866 is_simple &= !CV_NODE_IS_COLLECTION(elem->tag);
1868 CV_CALL( ptr = icvXMLParseTag( fs, ptr, &key2, &list, &tag_type ));
1869 if( tag_type != CV_XML_CLOSING_TAG || key2 != key )
1870 CV_PARSE_ERROR( "Mismatched closing tag" );
1876 CV_PARSE_ERROR( "There should be space between literals" );
1879 if( node->tag != CV_NODE_NONE )
1881 if( !CV_NODE_IS_COLLECTION(node->tag) )
1882 CV_CALL( icvFSCreateCollection( fs, CV_NODE_SEQ, node ));
1884 elem = (CvFileNode*)cvSeqPush( node->data.seq, 0 );
1888 if( value_type != CV_NODE_STRING &&
1889 (isdigit(c) || (c == '-' || c == '+') &&
1890 (isdigit(d) || d == '.') || c == '.' && isalnum(d)) ) // a number
1894 endptr = ptr + (c == '-' || c == '+');
1895 while( isdigit(*endptr) )
1897 if( *endptr == '.' || *endptr == 'e' )
1899 fval = icv_strtod( fs, ptr, &endptr );
1900 /*if( endptr == ptr || isalpha(*endptr) )
1901 CV_CALL( icvProcessSpecialDouble( fs, ptr, &fval, &endptr ));*/
1902 elem->tag = CV_NODE_REAL;
1903 elem->data.f = fval;
1907 ival = (int)strtol( ptr, &endptr, 0 );
1908 elem->tag = CV_NODE_INT;
1909 elem->data.i = ival;
1913 CV_PARSE_ERROR( "Invalid numeric value (inconsistent explicit type specification?)" );
1920 char buf[CV_FS_MAX_LEN+16];
1921 int i = 0, len, is_quoted = 0;
1922 elem->tag = CV_NODE_STRING;
1936 CV_PARSE_ERROR( "Literal \" is not allowed within a string. Use "" );
1940 else if( !cv_isprint(c) || c == '<' || (!is_quoted && isspace(c)))
1943 CV_PARSE_ERROR( "Closing \" is expected" );
1946 else if( c == '\'' || c == '>' )
1948 CV_PARSE_ERROR( "Literal \' or > are not allowed. Use ' or >" );
1956 val = (int)strtol( ptr, &endptr, 0 );
1957 if( (unsigned)val > (unsigned)255 ||
1958 !endptr || *endptr != ';' )
1959 CV_PARSE_ERROR( "Invalid numeric value in the string" );
1966 while( isalnum(c) );
1968 CV_PARSE_ERROR( "Invalid character in the symbol entity name" );
1969 len = (int)(endptr - ptr);
1970 if( len == 2 && memcmp( ptr, "lt", len ) == 0 )
1972 else if( len == 2 && memcmp( ptr, "gt", len ) == 0 )
1974 else if( len == 3 && memcmp( ptr, "amp", len ) == 0 )
1976 else if( len == 4 && memcmp( ptr, "apos", len ) == 0 )
1978 else if( len == 4 && memcmp( ptr, "quot", len ) == 0 )
1982 memcpy( buf + i, ptr-1, len + 2 );
1990 if( i >= CV_FS_MAX_LEN )
1991 CV_PARSE_ERROR( "Too long string literal" );
1993 CV_CALL( elem->data.str = cvMemStorageAllocString( fs->memstorage, buf, i ));
1996 if( !CV_NODE_IS_COLLECTION(value_type) && value_type != CV_NODE_NONE )
2002 if( (CV_NODE_TYPE(node->tag) == CV_NODE_NONE ||
2003 CV_NODE_TYPE(node->tag) != value_type &&
2004 !CV_NODE_IS_COLLECTION(node->tag)) &&
2005 CV_NODE_IS_COLLECTION(value_type) )
2007 CV_CALL( icvFSCreateCollection( fs, CV_NODE_IS_MAP(value_type) ?
2008 CV_NODE_MAP : CV_NODE_SEQ, node ));
2011 if( value_type != CV_NODE_NONE &&
2012 value_type != CV_NODE_TYPE(node->tag) )
2013 CV_PARSE_ERROR( "The actual type is different from the specified type" );
2015 if( CV_NODE_IS_COLLECTION(node->tag) && is_simple )
2016 node->data.seq->flags |= CV_NODE_SEQ_SIMPLE;
2018 node->tag |= is_user_type ? CV_NODE_USER : 0;
2027 icvXMLParseTag( CvFileStorage* fs, char* ptr, CvStringHashNode** _tag,
2028 CvAttrList** _list, int* _tag_type )
2031 CvStringHashNode* tagname = 0;
2032 CvAttrList *first = 0, *last = 0;
2033 int count = 0, max_count = 4;
2034 int attr_buf_size = (max_count*2 + 1)*sizeof(char*) + sizeof(CvAttrList);
2036 CV_FUNCNAME( "icvXMLParseTag" );
2045 CV_PARSE_ERROR( "Tag should start with \'<\'" );
2048 if( isalnum(*ptr) || *ptr == '_' )
2049 tag_type = CV_XML_OPENING_TAG;
2050 else if( *ptr == '/' )
2052 tag_type = CV_XML_CLOSING_TAG;
2055 else if( *ptr == '?' )
2057 tag_type = CV_XML_HEADER_TAG;
2060 else if( *ptr == '!' )
2062 tag_type = CV_XML_DIRECTIVE_TAG;
2063 assert( ptr[1] != '-' || ptr[2] != '-' );
2067 CV_PARSE_ERROR( "Unknown tag type" );
2071 CvStringHashNode* attrname;
2073 if( !isalpha(*ptr) && *ptr != '_' )
2074 CV_PARSE_ERROR( "Name should start with a letter or underscore" );
2078 while( isalnum(c) || c == '_' || c == '-' );
2080 CV_CALL( attrname = cvGetHashedKey( fs, ptr, (int)(endptr - ptr), 1 ));
2087 if( tag_type == CV_XML_CLOSING_TAG )
2088 CV_PARSE_ERROR( "Closing tag should not contain any attributes" );
2090 if( !last || count >= max_count )
2094 CV_CALL( chunk = (CvAttrList*)cvMemStorageAlloc( fs->memstorage, attr_buf_size ));
2095 memset( chunk, 0, attr_buf_size );
2096 chunk->attr = (const char**)(chunk + 1);
2099 first = last = chunk;
2101 last = last->next = chunk;
2103 last->attr[count*2] = attrname->str.ptr;
2112 CV_CALL( ptr = icvXMLSkipSpaces( fs, ptr, CV_XML_INSIDE_TAG ));
2114 CV_PARSE_ERROR( "Attribute name should be followed by \'=\'" );
2118 if( c != '\"' && c != '\'' )
2120 CV_CALL( ptr = icvXMLSkipSpaces( fs, ptr, CV_XML_INSIDE_TAG ));
2121 if( *ptr != '\"' && *ptr != '\'' )
2122 CV_PARSE_ERROR( "Attribute value should be put into single or double quotes" );
2125 ptr = icvXMLParseValue( fs, ptr, &stub, CV_NODE_STRING );
2126 assert( stub.tag == CV_NODE_STRING );
2127 last->attr[count*2+1] = stub.data.str.ptr;
2132 have_space = isspace(c) || c == '\0';
2136 CV_CALL( ptr = icvXMLSkipSpaces( fs, ptr, CV_XML_INSIDE_TAG ));
2142 if( tag_type == CV_XML_HEADER_TAG )
2143 CV_PARSE_ERROR( "Invalid closing tag for <?xml ..." );
2147 else if( c == '?' && tag_type == CV_XML_HEADER_TAG )
2150 CV_PARSE_ERROR( "Invalid closing tag for <?xml ..." );
2154 else if( c == '/' && ptr[1] == '>' && tag_type == CV_XML_OPENING_TAG )
2156 tag_type = CV_XML_EMPTY_TAG;
2162 CV_PARSE_ERROR( "There should be space between attributes" );
2168 *_tag_type = tag_type;
2176 icvXMLParse( CvFileStorage* fs )
2178 CV_FUNCNAME( "icvXMLParse" );
2182 char* ptr = fs->buffer_start;
2183 CvStringHashNode *key = 0, *key2 = 0;
2184 CvAttrList* list = 0;
2187 // CV_XML_INSIDE_TAG is used to prohibit leading comments
2188 CV_CALL( ptr = icvXMLSkipSpaces( fs, ptr, CV_XML_INSIDE_TAG ));
2190 if( memcmp( ptr, "<?xml", 5 ) != 0 )
2191 CV_PARSE_ERROR( "Valid XML should start with \'<?xml ...?>\'" );
2193 CV_CALL( ptr = icvXMLParseTag( fs, ptr, &key, &list, &tag_type ));
2196 const char* version = cvAttrValue( list, "version" );
2197 if( version && strncmp( version, "1.", 2 ) != 0 )
2198 CV_ERROR( CV_StsParseError, "Unsupported version of XML" );
2201 const char* encoding = cvAttrValue( list, "encoding" );
2202 if( encoding && strcmp( encoding, "ASCII" ) != 0 )
2203 CV_PARSE_ERROR( "Unsupported encoding" );
2206 while( *ptr != '\0' )
2208 CV_CALL( ptr = icvXMLSkipSpaces( fs, ptr, 0 ));
2212 CvFileNode* root_node;
2213 CV_CALL( ptr = icvXMLParseTag( fs, ptr, &key, &list, &tag_type ));
2214 if( tag_type != CV_XML_OPENING_TAG ||
2215 strcmp(key->str.ptr,"opencv_storage") != 0 )
2216 CV_PARSE_ERROR( "<opencv_storage> tag is missing" );
2218 root_node = (CvFileNode*)cvSeqPush( fs->roots, 0 );
2219 CV_CALL( ptr = icvXMLParseValue( fs, ptr, root_node, CV_NODE_NONE ));
2220 CV_CALL( ptr = icvXMLParseTag( fs, ptr, &key2, &list, &tag_type ));
2221 if( tag_type != CV_XML_CLOSING_TAG || key != key2 )
2222 CV_PARSE_ERROR( "</opencv_storage> tag is missing" );
2223 CV_CALL( ptr = icvXMLSkipSpaces( fs, ptr, 0 ));
2227 assert( fs->dummy_eof != 0 );
2233 /****************************************************************************************\
2235 \****************************************************************************************/
2237 #define icvXMLFlush icvFSFlush
2240 icvXMLWriteTag( CvFileStorage* fs, const char* key, int tag_type, CvAttrList list )
2242 CV_FUNCNAME( "icvXMLWriteTag" );
2246 char* ptr = fs->buffer;
2248 int struct_flags = fs->struct_flags;
2250 if( key && key[0] == '\0' )
2253 if( tag_type == CV_XML_OPENING_TAG || tag_type == CV_XML_EMPTY_TAG )
2255 if( CV_NODE_IS_COLLECTION(struct_flags) )
2257 if( CV_NODE_IS_MAP(struct_flags) ^ (key != 0) )
2258 CV_ERROR( CV_StsBadArg, "An attempt to add element without a key to a map, "
2259 "or add element with key to sequence" );
2263 struct_flags = CV_NODE_EMPTY + (key ? CV_NODE_MAP : CV_NODE_SEQ);
2267 if( !CV_NODE_IS_EMPTY(struct_flags) )
2268 ptr = icvXMLFlush(fs);
2273 else if( key[0] == '_' && key[1] == '\0' )
2274 CV_ERROR( CV_StsBadArg, "A single _ is a reserved tag name" );
2276 len = (int)strlen( key );
2278 if( tag_type == CV_XML_CLOSING_TAG )
2281 CV_ERROR( CV_StsBadArg, "Closing tag should not include any attributes" );
2285 if( !isalpha(key[0]) && key[0] != '_' )
2286 CV_ERROR( CV_StsBadArg, "Key should start with a letter or _" );
2288 ptr = icvFSResizeWriteBuffer( fs, ptr, len );
2289 for( i = 0; i < len; i++ )
2292 if( !isalnum(c) && c != '_' && c != '-' )
2293 CV_ERROR( CV_StsBadArg, "Invalid character in the key" );
2300 const char** attr = list.attr;
2302 for( ; attr && attr[0] != 0; attr += 2 )
2304 int len0 = (int)strlen(attr[0]);
2305 int len1 = (int)strlen(attr[1]);
2307 ptr = icvFSResizeWriteBuffer( fs, ptr, len0 + len1 + 4 );
2309 memcpy( ptr, attr[0], len0 );
2313 memcpy( ptr, attr[1], len1 );
2322 if( tag_type == CV_XML_EMPTY_TAG )
2326 fs->struct_flags = struct_flags & ~CV_NODE_EMPTY;
2333 icvXMLStartWriteStruct( CvFileStorage* fs, const char* key, int struct_flags,
2334 const char* type_name CV_DEFAULT(0))
2336 CV_FUNCNAME( "icvXMLStartWriteStruct" );
2340 CvXMLStackRecord parent;
2341 const char* attr[10];
2344 struct_flags = (struct_flags & (CV_NODE_TYPE_MASK|CV_NODE_FLOW)) | CV_NODE_EMPTY;
2345 if( !CV_NODE_IS_COLLECTION(struct_flags))
2346 CV_ERROR( CV_StsBadArg,
2347 "Some collection type: CV_NODE_SEQ or CV_NODE_MAP must be specified" );
2351 attr[idx++] = "type_id";
2352 attr[idx++] = type_name;
2356 CV_CALL( icvXMLWriteTag( fs, key, CV_XML_OPENING_TAG, cvAttrList(attr,0) ));
2358 parent.struct_flags = fs->struct_flags & ~CV_NODE_EMPTY;
2359 parent.struct_indent = fs->struct_indent;
2360 parent.struct_tag = fs->struct_tag;
2361 cvSaveMemStoragePos( fs->strstorage, &parent.pos );
2362 cvSeqPush( fs->write_stack, &parent );
2364 fs->struct_indent += CV_XML_INDENT;
2365 if( !CV_NODE_IS_FLOW(struct_flags) )
2368 fs->struct_flags = struct_flags;
2371 CV_CALL( fs->struct_tag = cvMemStorageAllocString( fs->strstorage, (char*)key, -1 ));
2375 fs->struct_tag.ptr = 0;
2376 fs->struct_tag.len = 0;
2384 icvXMLEndWriteStruct( CvFileStorage* fs )
2386 CV_FUNCNAME( "icvXMLStartWriteStruct" );
2390 CvXMLStackRecord parent;
2392 if( fs->write_stack->total == 0 )
2393 CV_ERROR( CV_StsError, "An extra closing tag" );
2395 CV_CALL( icvXMLWriteTag( fs, fs->struct_tag.ptr, CV_XML_CLOSING_TAG, cvAttrList(0,0) ));
2396 cvSeqPop( fs->write_stack, &parent );
2398 fs->struct_indent = parent.struct_indent;
2399 fs->struct_flags = parent.struct_flags;
2400 fs->struct_tag = parent.struct_tag;
2401 cvRestoreMemStoragePos( fs->strstorage, &parent.pos );
2408 icvXMLStartNextStream( CvFileStorage* fs )
2410 //CV_FUNCNAME( "icvXMLStartNextStream" );
2416 while( fs->write_stack->total > 0 )
2417 icvXMLEndWriteStruct(fs);
2419 fs->struct_indent = 0;
2421 /* XML does not allow multiple top-level elements,
2422 so we just put a comment and continue
2423 the current (and the only) "stream" */
2424 fputs( "\n<!-- next stream -->\n", fs->file );
2425 /*fputs( "</opencv_storage>\n", fs->file );
2426 fputs( "<opencv_storage>\n", fs->file );*/
2427 fs->buffer = fs->buffer_start;
2435 icvXMLWriteScalar( CvFileStorage* fs, const char* key, const char* data, int len )
2437 CV_FUNCNAME( "icvXMLWriteScalar" );
2441 if( CV_NODE_IS_MAP(fs->struct_flags) ||
2442 (!CV_NODE_IS_COLLECTION(fs->struct_flags) && key) )
2444 icvXMLWriteTag( fs, key, CV_XML_OPENING_TAG, cvAttrList(0,0) );
2445 char* ptr = icvFSResizeWriteBuffer( fs, fs->buffer, len );
2446 memcpy( ptr, data, len );
2447 fs->buffer = ptr + len;
2448 icvXMLWriteTag( fs, key, CV_XML_CLOSING_TAG, cvAttrList(0,0) );
2452 char* ptr = fs->buffer;
2453 int new_offset = (int)(ptr - fs->buffer_start) + len;
2456 CV_ERROR( CV_StsBadArg, "elements with keys can not be written to sequence" );
2458 fs->struct_flags = CV_NODE_SEQ;
2460 if( (new_offset > fs->wrap_margin && new_offset - fs->struct_indent > 10) ||
2461 (ptr > fs->buffer_start && ptr[-1] == '>' && !CV_NODE_IS_EMPTY(fs->struct_flags)) )
2463 ptr = icvXMLFlush(fs);
2465 else if( ptr > fs->buffer_start + fs->struct_indent && ptr[-1] != '>' )
2468 memcpy( ptr, data, len );
2469 fs->buffer = ptr + len;
2477 icvXMLWriteInt( CvFileStorage* fs, const char* key, int value )
2479 //CV_FUNCNAME( "cvXMLWriteInt" );
2483 char buf[128], *ptr = icv_itoa( value, buf, 10 );
2484 int len = (int)strlen(ptr);
2485 icvXMLWriteScalar( fs, key, ptr, len );
2492 icvXMLWriteReal( CvFileStorage* fs, const char* key, double value )
2494 //CV_FUNCNAME( "cvXMLWriteReal" );
2499 int len = (int)strlen( icvDoubleToString( buf, value ));
2500 icvXMLWriteScalar( fs, key, buf, len );
2507 icvXMLWriteString( CvFileStorage* fs, const char* key, const char* str, int quote )
2509 CV_FUNCNAME( "cvXMLWriteString" );
2513 char buf[CV_FS_MAX_LEN*6+16];
2514 char* data = (char*)str;
2518 CV_ERROR( CV_StsNullPtr, "Null string pointer" );
2520 len = (int)strlen(str);
2521 if( len > CV_FS_MAX_LEN )
2522 CV_ERROR( CV_StsBadArg, "The written string is too long" );
2524 if( quote || len == 0 || str[0] != '\"' || str[0] != str[len-1] )
2526 int need_quote = quote || len == 0;
2529 for( i = 0; i < len; i++ )
2533 if( !isalnum(c) && (!cv_isprint(c) || c == '<' || c == '>' ||
2534 c == '&' || c == '\'' || c == '\"') )
2539 memcpy(data, "lt", 2);
2544 memcpy(data, "gt", 2);
2549 memcpy(data, "amp", 3);
2552 else if( c == '\'' )
2554 memcpy(data, "apos", 4);
2557 else if( c == '\"' )
2559 memcpy( data, "quot", 4);
2564 sprintf( data, "#x%02x", c );
2576 if( !need_quote && (isdigit(str[0]) ||
2577 str[0] == '+' || str[0] == '-' || str[0] == '.' ))
2582 len = (int)(data - buf) - !need_quote;
2584 data = buf + !need_quote;
2587 icvXMLWriteScalar( fs, key, data, len );
2594 icvXMLWriteComment( CvFileStorage* fs, const char* comment, int eol_comment )
2596 CV_FUNCNAME( "cvXMLWriteComment" );
2606 CV_ERROR( CV_StsNullPtr, "Null comment" );
2608 if( strstr(comment, "--") != 0 )
2609 CV_ERROR( CV_StsBadArg, "Double hyphen \'--\' is not allowed in the comments" );
2611 len = (int)strlen(comment);
2612 eol = strchr(comment, '\n');
2613 multiline = eol != 0;
2616 if( multiline || !eol_comment || fs->buffer_end - ptr < len + 5 )
2617 ptr = icvXMLFlush( fs );
2618 else if( ptr > fs->buffer_start + fs->struct_indent )
2623 ptr = icvFSResizeWriteBuffer( fs, ptr, len + 9 );
2624 sprintf( ptr, "<!-- %s -->", comment );
2625 len = (int)strlen(ptr);
2629 strcpy( ptr, "<!--" );
2633 fs->buffer = ptr + len;
2634 ptr = icvXMLFlush(fs);
2642 ptr = icvFSResizeWriteBuffer( fs, ptr, (int)(eol - comment) + 1 );
2643 memcpy( ptr, comment, eol - comment + 1 );
2644 ptr += eol - comment;
2646 eol = strchr( comment, '\n' );
2650 len = (int)strlen(comment);
2651 ptr = icvFSResizeWriteBuffer( fs, ptr, len );
2652 memcpy( ptr, comment, len );
2657 ptr = icvXMLFlush( fs );
2659 sprintf( ptr, "-->" );
2660 fs->buffer = ptr + 3;
2668 /****************************************************************************************\
2669 * Common High-Level Functions *
2670 \****************************************************************************************/
2672 CV_IMPL CvFileStorage*
2673 cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags )
2675 CvFileStorage* fs = 0;
2678 CV_FUNCNAME("cvOpenFileStorage" );
2682 int default_block_size = 1 << 18;
2683 bool append = (flags & 3) == CV_STORAGE_APPEND;
2686 CV_ERROR( CV_StsNullPtr, "NULL filename" );
2688 CV_CALL( fs = (CvFileStorage*)cvAlloc( sizeof(*fs) ));
2689 memset( fs, 0, sizeof(*fs));
2691 CV_CALL( fs->memstorage = cvCreateMemStorage( default_block_size ));
2692 fs->dststorage = dststorage ? dststorage : fs->memstorage;
2694 CV_CALL( fs->filename = (char*)cvMemStorageAlloc( fs->memstorage, strlen(filename)+1 ));
2695 strcpy( fs->filename, filename );
2697 fs->flags = CV_FILE_STORAGE;
2698 fs->write_mode = (flags & 3) != 0;
2699 fs->file = fopen( fs->filename, !fs->write_mode ? "rt" : !append ? "wt" : "a+t" );
2704 fs->struct_indent = 0;
2705 fs->struct_flags = 0;
2706 fs->wrap_margin = 71;
2708 if( fs->write_mode )
2710 // we use factor=6 for XML (the longest characters (' and ") are encoded with 6 bytes (' and ")
2711 // and factor=4 for YAML ( as we use 4 bytes for non ASCII characters (e.g. \xAB))
2712 int buf_size = CV_FS_MAX_LEN*(fs->is_xml ? 6 : 4) + 1024;
2714 char* dot_pos = strrchr( fs->filename, '.' );
2715 fs->is_xml = dot_pos && (strcmp( dot_pos, ".xml" ) == 0 ||
2716 strcmp( dot_pos, ".XML" ) == 0 || strcmp( dot_pos, ".Xml" ) == 0);
2719 fseek( fs->file, 0, SEEK_END );
2721 fs->write_stack = cvCreateSeq( 0, sizeof(CvSeq), fs->is_xml ?
2722 sizeof(CvXMLStackRecord) : sizeof(int), fs->memstorage );
2724 fs->struct_indent = 0;
2725 fs->struct_flags = CV_NODE_EMPTY;
2726 CV_CALL( fs->buffer_start = fs->buffer = (char*)cvAlloc( buf_size + 1024 ));
2727 fs->buffer_end = fs->buffer_start + buf_size;
2730 int file_size = (int)ftell( fs->file );
2731 CV_CALL( fs->strstorage = cvCreateChildMemStorage( fs->memstorage ));
2732 if( !append || file_size == 0 )
2734 fputs( "<?xml version=\"1.0\"?>\n", fs->file );
2735 fputs( "<opencv_storage>\n", fs->file );
2739 int xml_buf_size = 1 << 10;
2740 char substr[] = "</opencv_storage>";
2741 int last_occurence = -1;
2742 xml_buf_size = MIN(xml_buf_size, file_size);
2743 fseek( fs->file, -xml_buf_size, SEEK_END );
2744 CV_CALL(xml_buf = (char*)cvAlloc( xml_buf_size+2 ));
2745 // find the last occurence of </opencv_storage>
2748 int line_offset = ftell( fs->file );
2749 char* ptr0 = fgets( xml_buf, xml_buf_size, fs->file ), *ptr;
2755 ptr = strstr( ptr, substr );
2758 last_occurence = line_offset + (int)(ptr - ptr0);
2759 ptr += strlen(substr);
2762 if( last_occurence < 0 )
2763 CV_ERROR( CV_StsError, "Could not find </opencv_storage> in the end of file.\n" );
2765 fs->file = fopen( fs->filename, "r+t" );
2766 fseek( fs->file, last_occurence, SEEK_SET );
2767 // replace the last "</opencv_storage>" with " <!-- resumed -->", which has the same length
2768 fputs( " <!-- resumed -->", fs->file );
2769 fseek( fs->file, 0, SEEK_END );
2770 fputs( "\n", fs->file );
2772 fs->start_write_struct = icvXMLStartWriteStruct;
2773 fs->end_write_struct = icvXMLEndWriteStruct;
2774 fs->write_int = icvXMLWriteInt;
2775 fs->write_real = icvXMLWriteReal;
2776 fs->write_string = icvXMLWriteString;
2777 fs->write_comment = icvXMLWriteComment;
2778 fs->start_next_stream = icvXMLStartNextStream;
2783 fputs( "%YAML:1.0\n", fs->file );
2785 fputs( "...\n---\n", fs->file );
2786 fs->start_write_struct = icvYMLStartWriteStruct;
2787 fs->end_write_struct = icvYMLEndWriteStruct;
2788 fs->write_int = icvYMLWriteInt;
2789 fs->write_real = icvYMLWriteReal;
2790 fs->write_string = icvYMLWriteString;
2791 fs->write_comment = icvYMLWriteComment;
2792 fs->start_next_stream = icvYMLStartNextStream;
2798 const char* yaml_signature = "%YAML:";
2800 fgets( buf, sizeof(buf)-2, fs->file );
2801 fs->is_xml = strncmp( buf, yaml_signature, strlen(yaml_signature) ) != 0;
2803 fseek( fs->file, 0, SEEK_END );
2804 buf_size = ftell( fs->file );
2805 fseek( fs->file, 0, SEEK_SET );
2807 buf_size = MIN( buf_size, (1 << 20) );
2808 buf_size = MAX( buf_size, CV_FS_MAX_LEN*2 + 1024 );
2810 CV_CALL( fs->str_hash = cvCreateMap( 0, sizeof(CvStringHash),
2811 sizeof(CvStringHashNode), fs->memstorage, 256 ));
2813 CV_CALL( fs->roots = cvCreateSeq( 0, sizeof(CvSeq),
2814 sizeof(CvFileNode), fs->memstorage ));
2816 CV_CALL( fs->buffer = fs->buffer_start = (char*)cvAlloc( buf_size + 256 ));
2817 fs->buffer_end = fs->buffer_start + buf_size;
2818 fs->buffer[0] = '\n';
2819 fs->buffer[1] = '\0';
2821 //mode = cvGetErrMode();
2822 //cvSetErrMode( CV_ErrModeSilent );
2827 //cvSetErrMode( mode );
2829 // release resources that we do not need anymore
2830 cvFree( &fs->buffer_start );
2831 fs->buffer = fs->buffer_end = 0;
2838 if( cvGetErrStatus() < 0 || !fs->file )
2840 cvReleaseFileStorage( &fs );
2842 else if( !fs->write_mode )
2856 cvStartWriteStruct( CvFileStorage* fs, const char* key, int struct_flags,
2857 const char* type_name, CvAttrList /*attributes*/ )
2859 CV_FUNCNAME( "cvStartWriteStruct" );
2863 CV_CHECK_OUTPUT_FILE_STORAGE(fs);
2864 CV_CALL( fs->start_write_struct( fs, key, struct_flags, type_name ));
2871 cvEndWriteStruct( CvFileStorage* fs )
2873 CV_FUNCNAME( "cvEndWriteStruct" );
2877 CV_CHECK_OUTPUT_FILE_STORAGE(fs);
2878 CV_CALL( fs->end_write_struct( fs ));
2885 cvWriteInt( CvFileStorage* fs, const char* key, int value )
2887 CV_FUNCNAME( "cvWriteInt" );
2891 CV_CHECK_OUTPUT_FILE_STORAGE(fs);
2892 CV_CALL( fs->write_int( fs, key, value ));
2899 cvWriteReal( CvFileStorage* fs, const char* key, double value )
2901 CV_FUNCNAME( "cvWriteReal" );
2905 CV_CHECK_OUTPUT_FILE_STORAGE(fs);
2906 CV_CALL( fs->write_real( fs, key, value ));
2913 cvWriteString( CvFileStorage* fs, const char* key, const char* value, int quote )
2915 CV_FUNCNAME( "cvWriteString" );
2919 CV_CHECK_OUTPUT_FILE_STORAGE(fs);
2920 CV_CALL( fs->write_string( fs, key, value, quote ));
2927 cvWriteComment( CvFileStorage* fs, const char* comment, int eol_comment )
2929 CV_FUNCNAME( "cvWriteComment" );
2933 CV_CHECK_OUTPUT_FILE_STORAGE(fs);
2934 CV_CALL( fs->write_comment( fs, comment, eol_comment ));
2941 cvStartNextStream( CvFileStorage* fs )
2943 CV_FUNCNAME( "cvStartNextStream" );
2947 CV_CHECK_OUTPUT_FILE_STORAGE(fs);
2948 CV_CALL( fs->start_next_stream( fs ));
2954 static const char icvTypeSymbol[] = "ucwsifdr";
2955 #define CV_FS_MAX_FMT_PAIRS 128
2958 icvEncodeFormat( int elem_type, char* dt )
2960 sprintf( dt, "%d%c", CV_MAT_CN(elem_type), icvTypeSymbol[CV_MAT_DEPTH(elem_type)] );
2961 return dt + ( dt[2] == '\0' && dt[0] == '1' );
2965 icvDecodeFormat( const char* dt, int* fmt_pairs, int max_len )
2967 int fmt_pair_count = 0;
2968 CV_FUNCNAME( "icvDecodeFormat" );
2972 int i = 0, k = 0, len = dt ? (int)strlen(dt) : 0;
2977 assert( fmt_pairs != 0 && max_len > 0 );
2981 for( ; k < len; k++ )
2987 int count = c - '0';
2988 if( isdigit(dt[k+1]) )
2991 count = (int)strtol( dt+k, &endptr, 10 );
2992 k = (int)(endptr - dt) - 1;
2996 CV_ERROR( CV_StsBadArg, "Invalid data type specification" );
2998 fmt_pairs[i] = count;
3002 const char* pos = strchr( icvTypeSymbol, c );
3004 CV_ERROR( CV_StsBadArg, "Invalid data type specification" );
3005 if( fmt_pairs[i] == 0 )
3007 fmt_pairs[i+1] = (int)(pos - icvTypeSymbol);
3008 if( i > 0 && fmt_pairs[i+1] == fmt_pairs[i-1] )
3009 fmt_pairs[i-2] += fmt_pairs[i];
3014 CV_ERROR( CV_StsBadArg, "Too long data type specification" );
3020 fmt_pair_count = i/2;
3024 return fmt_pair_count;
3029 icvCalcElemSize( const char* dt, int initial_size )
3032 CV_FUNCNAME( "icvCalcElemSize" );
3036 int fmt_pairs[CV_FS_MAX_FMT_PAIRS], i, fmt_pair_count;
3039 CV_CALL( fmt_pair_count = icvDecodeFormat( dt, fmt_pairs, CV_FS_MAX_FMT_PAIRS ));
3040 fmt_pair_count *= 2;
3041 for( i = 0, size = initial_size; i < fmt_pair_count; i += 2 )
3043 comp_size = CV_ELEM_SIZE(fmt_pairs[i+1]);
3044 size = cvAlign( size, comp_size );
3045 size += comp_size * fmt_pairs[i];
3047 if( initial_size == 0 )
3049 comp_size = CV_ELEM_SIZE(fmt_pairs[1]);
3050 size = cvAlign( size, comp_size );
3060 icvDecodeSimpleFormat( const char* dt )
3064 CV_FUNCNAME( "icvDecodeSimpleFormat" );
3068 int fmt_pairs[CV_FS_MAX_FMT_PAIRS], fmt_pair_count;
3070 CV_CALL( fmt_pair_count = icvDecodeFormat( dt, fmt_pairs, CV_FS_MAX_FMT_PAIRS ));
3071 if( fmt_pair_count != 1 || fmt_pairs[0] > 4 )
3072 CV_ERROR( CV_StsError, "Too complex format for the matrix" );
3074 elem_type = CV_MAKETYPE( fmt_pairs[1], fmt_pairs[0] );
3083 cvWriteRawData( CvFileStorage* fs, const void* _data, int len, const char* dt )
3085 const char* data0 = (const char*)_data;
3087 CV_FUNCNAME( "cvWriteRawData" );
3092 int fmt_pairs[CV_FS_MAX_FMT_PAIRS*2], k, fmt_pair_count;
3095 CV_CHECK_OUTPUT_FILE_STORAGE( fs );
3098 CV_ERROR( CV_StsNullPtr, "Null data pointer" );
3101 CV_ERROR( CV_StsOutOfRange, "Negative number of elements" );
3103 CV_CALL( fmt_pair_count = icvDecodeFormat( dt, fmt_pairs, CV_FS_MAX_FMT_PAIRS ));
3108 if( fmt_pair_count == 1 )
3110 fmt_pairs[0] *= len;
3116 for( k = 0; k < fmt_pair_count; k++ )
3118 int i, count = fmt_pairs[k*2];
3119 int elem_type = fmt_pairs[k*2+1];
3120 int elem_size = CV_ELEM_SIZE(elem_type);
3121 const char* data, *ptr;
3123 offset = cvAlign( offset, elem_size );
3124 data = data0 + offset;
3126 for( i = 0; i < count; i++ )
3131 ptr = icv_itoa( *(uchar*)data, buf, 10 );
3135 ptr = icv_itoa( *(char*)data, buf, 10 );
3139 ptr = icv_itoa( *(ushort*)data, buf, 10 );
3140 data += sizeof(ushort);
3143 ptr = icv_itoa( *(short*)data, buf, 10 );
3144 data += sizeof(short);
3147 ptr = icv_itoa( *(int*)data, buf, 10 );
3148 data += sizeof(int);
3151 ptr = icvFloatToString( buf, *(float*)data );
3152 data += sizeof(float);
3155 ptr = icvDoubleToString( buf, *(double*)data );
3156 data += sizeof(double);
3158 case CV_USRTYPE1: /* reference */
3159 ptr = icv_itoa( (int)*(size_t*)data, buf, 10 );
3160 data += sizeof(size_t);
3169 int buf_len = (int)strlen(ptr);
3170 CV_CALL( icvXMLWriteScalar( fs, 0, ptr, buf_len ));
3173 CV_CALL( icvYMLWrite( fs, 0, ptr, cvFuncName ));
3176 offset = (int)(data - data0);
3185 cvStartReadRawData( const CvFileStorage* fs, const CvFileNode* src, CvSeqReader* reader )
3187 CV_FUNCNAME( "cvStartReadRawData" );
3192 CV_CHECK_FILE_STORAGE( fs );
3194 if( !src || !reader )
3195 CV_ERROR( CV_StsNullPtr, "Null pointer to source file node or reader" );
3197 node_type = CV_NODE_TYPE(src->tag);
3198 if( node_type == CV_NODE_INT || node_type == CV_NODE_REAL )
3200 // emulate reading from 1-element sequence
3201 reader->ptr = (char*)src;
3202 reader->block_max = reader->ptr + sizeof(*src)*2;
3203 reader->block_min = reader->ptr;
3206 else if( node_type == CV_NODE_SEQ )
3208 CV_CALL( cvStartReadSeq( src->data.seq, reader, 0 ));
3210 else if( node_type == CV_NODE_NONE )
3212 memset( reader, 0, sizeof(*reader) );
3215 CV_ERROR( CV_StsBadArg, "The file node should be a numerical scalar or a sequence" );
3222 cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader,
3223 int len, void* _data, const char* dt )
3225 char* data0 = (char*)_data;
3226 CV_FUNCNAME( "cvReadRawDataSlice" );
3230 int fmt_pairs[CV_FS_MAX_FMT_PAIRS*2], k = 0, fmt_pair_count;
3231 int i = 0, offset = 0, count = 0;
3233 CV_CHECK_FILE_STORAGE( fs );
3235 if( !reader || !data0 )
3236 CV_ERROR( CV_StsNullPtr, "Null pointer to reader or destination array" );
3238 if( !reader->seq && len != 1 )
3239 CV_ERROR( CV_StsBadSize, "The readed sequence is a scalar, thus len must be 1" );
3241 CV_CALL( fmt_pair_count = icvDecodeFormat( dt, fmt_pairs, CV_FS_MAX_FMT_PAIRS ));
3245 for( k = 0; k < fmt_pair_count; k++ )
3247 int elem_type = fmt_pairs[k*2+1];
3248 int elem_size = CV_ELEM_SIZE(elem_type);
3251 count = fmt_pairs[k*2];
3252 offset = cvAlign( offset, elem_size );
3253 data = data0 + offset;
3255 for( i = 0; i < count; i++ )
3257 CvFileNode* node = (CvFileNode*)reader->ptr;
3258 if( CV_NODE_IS_INT(node->tag) )
3260 int ival = node->data.i;
3265 *(uchar*)data = CV_CAST_8U(ival);
3269 *(char*)data = CV_CAST_8S(ival);
3272 *(ushort*)data = CV_CAST_16U(ival);
3273 data += sizeof(ushort);
3276 *(short*)data = CV_CAST_16S(ival);
3277 data += sizeof(short);
3281 data += sizeof(int);
3284 *(float*)data = (float)ival;
3285 data += sizeof(float);
3288 *(double*)data = (double)ival;
3289 data += sizeof(double);
3291 case CV_USRTYPE1: /* reference */
3292 *(size_t*)data = ival;
3293 data += sizeof(size_t);
3300 else if( CV_NODE_IS_REAL(node->tag) )
3302 double fval = node->data.f;
3308 ival = cvRound(fval);
3309 *(uchar*)data = CV_CAST_8U(ival);
3313 ival = cvRound(fval);
3314 *(char*)data = CV_CAST_8S(ival);
3317 ival = cvRound(fval);
3318 *(ushort*)data = CV_CAST_16U(ival);
3319 data += sizeof(ushort);
3322 ival = cvRound(fval);
3323 *(short*)data = CV_CAST_16S(ival);
3324 data += sizeof(short);
3327 ival = cvRound(fval);
3329 data += sizeof(int);
3332 *(float*)data = (float)fval;
3333 data += sizeof(float);
3336 *(double*)data = fval;
3337 data += sizeof(double);
3339 case CV_USRTYPE1: /* reference */
3340 ival = cvRound(fval);
3341 *(size_t*)data = ival;
3342 data += sizeof(size_t);
3350 CV_ERROR( CV_StsError,
3351 "The sequence element is not a numerical scalar" );
3353 CV_NEXT_SEQ_ELEM( sizeof(CvFileNode), *reader );
3358 offset = (int)(data - data0);
3363 if( i != count - 1 || k != fmt_pair_count - 1 )
3364 CV_ERROR( CV_StsBadSize,
3365 "The sequence slice does not fit an integer number of records" );
3368 reader->ptr -= sizeof(CvFileNode);
3375 cvReadRawData( const CvFileStorage* fs, const CvFileNode* src,
3376 void* data, const char* dt )
3378 CV_FUNCNAME( "cvReadRawData" );
3385 CV_ERROR( CV_StsNullPtr, "Null pointers to source file node or destination array" );
3387 CV_CALL( cvStartReadRawData( fs, src, &reader ));
3388 cvReadRawDataSlice( fs, &reader, CV_NODE_IS_SEQ(src->tag) ?
3389 src->data.seq->total : 1, data, dt );
3396 icvWriteFileNode( CvFileStorage* fs, const char* name, const CvFileNode* node );
3399 icvWriteCollection( CvFileStorage* fs, const CvFileNode* node )
3401 int i, total = node->data.seq->total;
3402 int elem_size = node->data.seq->elem_size;
3403 int is_map = CV_NODE_IS_MAP(node->tag);
3406 cvStartReadSeq( node->data.seq, &reader, 0 );
3408 for( i = 0; i < total; i++ )
3410 CvFileMapNode* elem = (CvFileMapNode*)reader.ptr;
3411 if( !is_map || CV_IS_SET_ELEM(elem) )
3413 const char* name = is_map ? elem->key->str.ptr : 0;
3414 icvWriteFileNode( fs, name, &elem->value );
3416 CV_NEXT_SEQ_ELEM( elem_size, reader );
3421 icvWriteFileNode( CvFileStorage* fs, const char* name, const CvFileNode* node )
3423 CV_FUNCNAME( "icvWriteFileNode" );
3427 switch( CV_NODE_TYPE(node->tag) )
3430 fs->write_int( fs, name, node->data.i );
3433 fs->write_real( fs, name, node->data.f );
3436 fs->write_string( fs, name, node->data.str.ptr, 0 );
3440 fs->start_write_struct( fs, name, CV_NODE_TYPE(node->tag) +
3441 (CV_NODE_SEQ_IS_SIMPLE(node->data.seq) ? CV_NODE_FLOW : 0),
3442 node->info ? node->info->type_name : 0 );
3443 icvWriteCollection( fs, node );
3444 fs->end_write_struct( fs );
3447 fs->start_write_struct( fs, name, CV_NODE_SEQ, 0 );
3448 fs->end_write_struct( fs );
3451 CV_ERROR( CV_StsBadFlag, "Unknown type of file node" );
3459 cvWriteFileNode( CvFileStorage* fs, const char* new_node_name,
3460 const CvFileNode* node, int embed )
3462 CvFileStorage* dst = 0;
3464 CV_FUNCNAME( "cvWriteFileNode" );
3468 CV_CHECK_OUTPUT_FILE_STORAGE(fs);
3473 if( CV_NODE_IS_COLLECTION(node->tag) && embed )
3475 CV_CALL( icvWriteCollection( fs, node ));
3479 CV_CALL( icvWriteFileNode( fs, new_node_name, node ));
3482 int i, stream_count;
3483 stream_count = fs->roots->total;
3484 for( i = 0; i < stream_count; i++ )
3486 CvFileNode* node = (CvFileNode*)cvGetSeqElem( fs->roots, i, 0 );
3487 icvDumpCollection( dst, node );
3488 if( i < stream_count - 1 )
3489 dst->start_next_stream( dst );
3494 cvReleaseFileStorage( &dst );
3499 cvGetFileNodeName( const CvFileNode* file_node )
3501 return file_node && CV_NODE_HAS_NAME(file_node->tag) ?
3502 ((CvFileMapNode*)file_node)->key->str.ptr : 0;
3505 /****************************************************************************************\
3506 * Reading/Writing etc. for standard types *
3507 \****************************************************************************************/
3509 /*#define CV_TYPE_NAME_MAT "opencv-matrix"
3510 #define CV_TYPE_NAME_MATND "opencv-nd-matrix"
3511 #define CV_TYPE_NAME_SPARSE_MAT "opencv-sparse-matrix"
3512 #define CV_TYPE_NAME_IMAGE "opencv-image"
3513 #define CV_TYPE_NAME_SEQ "opencv-sequence"
3514 #define CV_TYPE_NAME_SEQ_TREE "opencv-sequence-tree"
3515 #define CV_TYPE_NAME_GRAPH "opencv-graph"*/
3517 /******************************* CvMat ******************************/
3520 icvIsMat( const void* ptr )
3522 return CV_IS_MAT_HDR(ptr);
3526 icvWriteMat( CvFileStorage* fs, const char* name,
3527 const void* struct_ptr, CvAttrList /*attr*/ )
3529 CV_FUNCNAME( "icvWriteMat" );
3533 const CvMat* mat = (const CvMat*)struct_ptr;
3538 assert( CV_IS_MAT(mat) );
3540 CV_CALL( cvStartWriteStruct( fs, name, CV_NODE_MAP, CV_TYPE_NAME_MAT ));
3541 cvWriteInt( fs, "rows", mat->rows );
3542 cvWriteInt( fs, "cols", mat->cols );
3543 cvWriteString( fs, "dt", icvEncodeFormat( CV_MAT_TYPE(mat->type), dt ), 0 );
3544 cvStartWriteStruct( fs, "data", CV_NODE_SEQ + CV_NODE_FLOW );
3546 size = cvGetSize(mat);
3547 if( CV_IS_MAT_CONT(mat->type) )
3549 size.width *= size.height;
3553 for( y = 0; y < size.height; y++ )
3554 cvWriteRawData( fs, mat->data.ptr + y*mat->step, size.width, dt );
3555 cvEndWriteStruct( fs );
3556 cvEndWriteStruct( fs );
3563 icvFileNodeSeqLen( CvFileNode* node )
3565 return CV_NODE_IS_COLLECTION(node->tag) ? node->data.seq->total :
3566 CV_NODE_TYPE(node->tag) != CV_NODE_NONE;
3571 icvReadMat( CvFileStorage* fs, CvFileNode* node )
3574 CV_FUNCNAME( "icvReadMat" );
3581 int rows, cols, elem_type;
3583 CV_CALL( rows = cvReadIntByName( fs, node, "rows", 0 ));
3584 cols = cvReadIntByName( fs, node, "cols", 0 );
3585 dt = cvReadStringByName( fs, node, "dt", 0 );
3587 if( rows == 0 || cols == 0 || dt == 0 )
3588 CV_ERROR( CV_StsError, "Some of essential matrix attributes are absent" );
3590 CV_CALL( elem_type = icvDecodeSimpleFormat( dt ));
3592 data = cvGetFileNodeByName( fs, node, "data" );
3594 CV_ERROR( CV_StsError, "The matrix data is not found in file storage" );
3596 if( icvFileNodeSeqLen( data ) != rows*cols*CV_MAT_CN(elem_type) )
3597 CV_ERROR( CV_StsUnmatchedSizes,
3598 "The matrix size does not match to the number of stored elements" );
3600 CV_CALL( mat = cvCreateMat( rows, cols, elem_type ));
3601 CV_CALL( cvReadRawData( fs, data, mat->data.ptr, dt ));
3611 /******************************* CvMatND ******************************/
3614 icvIsMatND( const void* ptr )
3616 return CV_IS_MATND(ptr);
3621 icvWriteMatND( CvFileStorage* fs, const char* name,
3622 const void* struct_ptr, CvAttrList /*attr*/ )
3624 CV_FUNCNAME( "icvWriteMatND" );
3628 void* mat = (void*)struct_ptr;
3630 CvNArrayIterator iterator;
3631 int dims, sizes[CV_MAX_DIM];
3634 assert( CV_IS_MATND(mat) );
3636 CV_CALL( cvStartWriteStruct( fs, name, CV_NODE_MAP, CV_TYPE_NAME_MATND ));
3637 dims = cvGetDims( mat, sizes );
3638 cvStartWriteStruct( fs, "sizes", CV_NODE_SEQ + CV_NODE_FLOW );
3639 cvWriteRawData( fs, sizes, dims, "i" );
3640 cvEndWriteStruct( fs );
3641 cvWriteString( fs, "dt", icvEncodeFormat( cvGetElemType(mat), dt ), 0 );
3642 cvStartWriteStruct( fs, "data", CV_NODE_SEQ + CV_NODE_FLOW );
3644 CV_CALL( cvInitNArrayIterator( 1, &mat, 0, &stub, &iterator ));
3647 cvWriteRawData( fs, iterator.ptr[0], iterator.size.width, dt );
3648 while( cvNextNArraySlice( &iterator ));
3649 cvEndWriteStruct( fs );
3650 cvEndWriteStruct( fs );
3657 icvReadMatND( CvFileStorage* fs, CvFileNode* node )
3660 CV_FUNCNAME( "icvReadMatND" );
3667 CvFileNode* sizes_node;
3668 int sizes[CV_MAX_DIM], dims, elem_type;
3671 CV_CALL( sizes_node = cvGetFileNodeByName( fs, node, "sizes" ));
3672 dt = cvReadStringByName( fs, node, "dt", 0 );
3674 if( !sizes_node || !dt )
3675 CV_ERROR( CV_StsError, "Some of essential matrix attributes are absent" );
3677 dims = CV_NODE_IS_SEQ(sizes_node->tag) ? sizes_node->data.seq->total :
3678 CV_NODE_IS_INT(sizes_node->tag) ? 1 : -1;
3680 if( dims <= 0 || dims > CV_MAX_DIM )
3681 CV_ERROR( CV_StsParseError, "Could not determine the matrix dimensionality" );
3683 CV_CALL( cvReadRawData( fs, sizes_node, sizes, "i" ));
3684 CV_CALL( elem_type = icvDecodeSimpleFormat( dt ));
3686 data = cvGetFileNodeByName( fs, node, "data" );
3688 CV_ERROR( CV_StsError, "The matrix data is not found in file storage" );
3690 for( total_size = CV_MAT_CN(elem_type), i = 0; i < dims; i++ )
3691 total_size *= sizes[i];
3693 if( icvFileNodeSeqLen( data ) != total_size )
3694 CV_ERROR( CV_StsUnmatchedSizes,
3695 "The matrix size does not match to the number of stored elements" );
3697 CV_CALL( mat = cvCreateMatND( dims, sizes, elem_type ));
3698 CV_CALL( cvReadRawData( fs, data, mat->data.ptr, dt ));
3708 /******************************* CvSparseMat ******************************/
3711 icvIsSparseMat( const void* ptr )
3713 return CV_IS_SPARSE_MAT(ptr);
3718 icvSortIdxCmpFunc( const void* _a, const void* _b, void* userdata )
3720 int i, dims = *(int*)userdata;
3721 const int* a = *(const int**)_a;
3722 const int* b = *(const int**)_b;
3724 for( i = 0; i < dims; i++ )
3726 int delta = a[i] - b[i];
3736 icvWriteSparseMat( CvFileStorage* fs, const char* name,
3737 const void* struct_ptr, CvAttrList /*attr*/ )
3739 CvMemStorage* memstorage = 0;
3741 CV_FUNCNAME( "icvWriteSparseMat" );
3745 const CvSparseMat* mat = (const CvSparseMat*)struct_ptr;
3746 CvSparseMatIterator iterator;
3754 assert( CV_IS_SPARSE_MAT(mat) );
3756 CV_CALL( memstorage = cvCreateMemStorage());
3758 CV_CALL( cvStartWriteStruct( fs, name, CV_NODE_MAP, CV_TYPE_NAME_SPARSE_MAT ));
3759 dims = cvGetDims( mat, 0 );
3761 cvStartWriteStruct( fs, "sizes", CV_NODE_SEQ + CV_NODE_FLOW );
3762 cvWriteRawData( fs, mat->size, dims, "i" );
3763 cvEndWriteStruct( fs );
3764 cvWriteString( fs, "dt", icvEncodeFormat( CV_MAT_TYPE(mat->type), dt ), 0 );
3765 cvStartWriteStruct( fs, "data", CV_NODE_SEQ + CV_NODE_FLOW );
3767 elements = cvCreateSeq( CV_SEQ_ELTYPE_PTR, sizeof(CvSeq), sizeof(int*), memstorage );
3769 node = cvInitSparseMatIterator( mat, &iterator );
3772 int* idx = CV_NODE_IDX( mat, node );
3773 cvSeqPush( elements, &idx );
3774 node = cvGetNextSparseNode( &iterator );
3777 cvSeqSort( elements, icvSortIdxCmpFunc, &dims );
3778 cvStartReadSeq( elements, &reader, 0 );
3780 for( i = 0; i < elements->total; i++ )
3786 CV_READ_SEQ_ELEM( idx, reader );
3789 for( ; idx[k] == prev_idx[k]; k++ )
3792 fs->write_int( fs, 0, k - dims + 1 );
3794 for( ; k < dims; k++ )
3795 fs->write_int( fs, 0, idx[k] );
3798 node = (CvSparseNode*)((uchar*)idx - mat->idxoffset );
3799 val = CV_NODE_VAL( mat, node );
3801 cvWriteRawData( fs, val, 1, dt );
3804 cvEndWriteStruct( fs );
3805 cvEndWriteStruct( fs );
3809 cvReleaseMemStorage( &memstorage );
3814 icvReadSparseMat( CvFileStorage* fs, CvFileNode* node )
3817 CV_FUNCNAME( "icvReadSparseMat" );
3824 CvFileNode* sizes_node;
3828 int* sizes = 0, dims, elem_type, cn;
3831 CV_CALL( sizes_node = cvGetFileNodeByName( fs, node, "sizes" ));
3832 dt = cvReadStringByName( fs, node, "dt", 0 );
3834 if( !sizes_node || !dt )
3835 CV_ERROR( CV_StsError, "Some of essential matrix attributes are absent" );
3837 dims = CV_NODE_IS_SEQ(sizes_node->tag) ? sizes_node->data.seq->total :
3838 CV_NODE_IS_INT(sizes_node->tag) ? 1 : -1;
3840 if( dims <= 0 || dims > CV_MAX_DIM_HEAP )
3841 CV_ERROR( CV_StsParseError, "Could not determine sparse matrix dimensionality" );
3843 sizes = (int*)alloca( dims*sizeof(sizes[0]));
3844 CV_CALL( cvReadRawData( fs, sizes_node, sizes, "i" ));
3845 CV_CALL( elem_type = icvDecodeSimpleFormat( dt ));
3847 data = cvGetFileNodeByName( fs, node, "data" );
3848 if( !data || !CV_NODE_IS_SEQ(data->tag) )
3849 CV_ERROR( CV_StsError, "The matrix data is not found in file storage" );
3851 CV_CALL( mat = cvCreateSparseMat( dims, sizes, elem_type ));
3853 cn = CV_MAT_CN(elem_type);
3854 idx = (int*)alloca( dims*sizeof(idx[0]) );
3855 elements = data->data.seq;
3856 cvStartReadRawData( fs, data, &reader );
3858 for( i = 0; i < elements->total; )
3860 CvFileNode* elem = (CvFileNode*)reader.ptr;
3863 if( !CV_NODE_IS_INT(elem->tag ))
3864 CV_ERROR( CV_StsParseError, "Sparse matrix data is corrupted" );
3866 if( i > 0 && k >= 0 )
3874 for( ; k < dims; k++ )
3876 CV_NEXT_SEQ_ELEM( elements->elem_size, reader );
3878 elem = (CvFileNode*)reader.ptr;
3879 if( !CV_NODE_IS_INT(elem->tag ) || elem->data.i < 0 )
3880 CV_ERROR( CV_StsParseError, "Sparse matrix data is corrupted" );
3881 idx[k] = elem->data.i;
3884 CV_NEXT_SEQ_ELEM( elements->elem_size, reader );
3886 CV_CALL( val = cvPtrND( mat, idx, 0, 1, 0 ));
3887 CV_CALL( cvReadRawDataSlice( fs, &reader, cn, val, dt ));
3899 /******************************* IplImage ******************************/
3902 icvIsImage( const void* ptr )
3904 return CV_IS_IMAGE_HDR(ptr);
3908 icvWriteImage( CvFileStorage* fs, const char* name,
3909 const void* struct_ptr, CvAttrList /*attr*/ )
3911 CV_FUNCNAME( "icvWriteImage" );
3915 const IplImage* image = (const IplImage*)struct_ptr;
3916 char dt_buf[16], *dt;
3920 assert( CV_IS_IMAGE(image) );
3922 if( image->dataOrder == IPL_DATA_ORDER_PLANE )
3923 CV_ERROR( CV_StsUnsupportedFormat,
3924 "Images with planar data layout are not supported" );
3926 CV_CALL( cvStartWriteStruct( fs, name, CV_NODE_MAP, CV_TYPE_NAME_IMAGE ));
3927 cvWriteInt( fs, "width", image->width );
3928 cvWriteInt( fs, "height", image->height );
3929 cvWriteString( fs, "origin", image->origin == IPL_ORIGIN_TL
3930 ? "top-left" : "bottom-left", 0 );
3931 cvWriteString( fs, "layout", image->dataOrder == IPL_DATA_ORDER_PLANE
3932 ? "planar" : "interleaved", 0 );
3935 cvStartWriteStruct( fs, "roi", CV_NODE_MAP + CV_NODE_FLOW );
3936 cvWriteInt( fs, "x", image->roi->xOffset );
3937 cvWriteInt( fs, "y", image->roi->yOffset );
3938 cvWriteInt( fs, "width", image->roi->width );
3939 cvWriteInt( fs, "height", image->roi->height );
3940 cvWriteInt( fs, "coi", image->roi->coi );
3941 cvEndWriteStruct( fs );
3944 depth = icvIplToCvDepth(image->depth);
3945 sprintf( dt_buf, "%d%c", image->nChannels, icvTypeSymbol[depth] );
3946 dt = dt_buf + (dt_buf[2] == '\0' && dt_buf[0] == '1');
3947 cvWriteString( fs, "dt", dt, 0 );
3949 size = cvSize(image->width, image->height);
3950 if( size.width*image->nChannels*CV_ELEM_SIZE(depth) == image->widthStep )
3952 size.width *= size.height;
3956 cvStartWriteStruct( fs, "data", CV_NODE_SEQ + CV_NODE_FLOW );
3957 for( y = 0; y < size.height; y++ )
3958 cvWriteRawData( fs, image->imageData + y*image->widthStep, size.width, dt );
3959 cvEndWriteStruct( fs );
3960 cvEndWriteStruct( fs );
3967 icvReadImage( CvFileStorage* fs, CvFileNode* node )
3970 CV_FUNCNAME( "icvReadImage" );
3977 CvFileNode* roi_node;
3980 int y, width, height, elem_type, coi, depth;
3981 const char* origin, *data_order;
3983 CV_CALL( width = cvReadIntByName( fs, node, "width", 0 ));
3984 height = cvReadIntByName( fs, node, "height", 0 );
3985 dt = cvReadStringByName( fs, node, "dt", 0 );
3986 origin = cvReadStringByName( fs, node, "origin", 0 );
3988 if( width == 0 || height == 0 || dt == 0 || origin == 0 )
3989 CV_ERROR( CV_StsError, "Some of essential image attributes are absent" );
3991 CV_CALL( elem_type = icvDecodeSimpleFormat( dt ));
3992 data_order = cvReadStringByName( fs, node, "layout", "interleaved" );
3993 if( strcmp( data_order, "interleaved" ) != 0 )
3994 CV_ERROR( CV_StsError, "Only interleaved images can be read" );
3996 data = cvGetFileNodeByName( fs, node, "data" );
3998 CV_ERROR( CV_StsError, "The image data is not found in file storage" );
4000 if( icvFileNodeSeqLen( data ) != width*height*CV_MAT_CN(elem_type) )
4001 CV_ERROR( CV_StsUnmatchedSizes,
4002 "The matrix size does not match to the number of stored elements" );
4004 depth = cvCvToIplDepth(elem_type);
4005 CV_CALL( image = cvCreateImage( cvSize(width,height), depth, CV_MAT_CN(elem_type) ));
4007 roi_node = cvGetFileNodeByName( fs, node, "roi" );
4010 roi.x = cvReadIntByName( fs, roi_node, "x", 0 );
4011 roi.y = cvReadIntByName( fs, roi_node, "y", 0 );
4012 roi.width = cvReadIntByName( fs, roi_node, "width", 0 );
4013 roi.height = cvReadIntByName( fs, roi_node, "height", 0 );
4014 coi = cvReadIntByName( fs, roi_node, "coi", 0 );
4016 cvSetImageROI( image, roi );
4017 cvSetImageCOI( image, coi );
4020 if( width*CV_ELEM_SIZE(elem_type) == image->widthStep )
4026 width *= CV_MAT_CN(elem_type);
4027 cvStartReadRawData( fs, data, &reader );
4028 for( y = 0; y < height; y++ )
4030 CV_CALL( cvReadRawDataSlice( fs, &reader, width,
4031 image->imageData + y*image->widthStep, dt ));
4042 /******************************* CvSeq ******************************/
4045 icvIsSeq( const void* ptr )
4047 return CV_IS_SEQ(ptr);
4052 icvReleaseSeq( void** ptr )
4054 CV_FUNCNAME( "icvReleaseSeq" );
4059 CV_ERROR( CV_StsNullPtr, "NULL double pointer" );
4061 *ptr = 0; // it's impossible now to release seq, so just clear the pointer
4068 icvCloneSeq( const void* ptr )
4070 return cvSeqSlice( (CvSeq*)ptr, CV_WHOLE_SEQ,
4071 0 /* use the same storage as for the original sequence */, 1 );
4076 icvWriteHeaderData( CvFileStorage* fs, const CvSeq* seq,
4077 CvAttrList* attr, int initial_header_size )
4079 CV_FUNCNAME( "icvWriteHeaderData" );
4083 char header_dt_buf[128];
4084 const char* header_dt = cvAttrValue( attr, "header_dt" );
4089 CV_CALL( dt_header_size = icvCalcElemSize( header_dt, initial_header_size ));
4090 if( dt_header_size > seq->header_size )
4091 CV_ERROR( CV_StsUnmatchedSizes,
4092 "The size of header calculated from \"header_dt\" is greater than header_size" );
4094 else if( seq->header_size > initial_header_size )
4096 if( CV_IS_SEQ(seq) && CV_IS_SEQ_POINT_SET(seq) &&
4097 seq->header_size == sizeof(CvPoint2DSeq) &&
4098 seq->elem_size == sizeof(int)*2 )
4100 CvPoint2DSeq* point_seq = (CvPoint2DSeq*)seq;
4102 cvStartWriteStruct( fs, "rect", CV_NODE_MAP + CV_NODE_FLOW );
4103 cvWriteInt( fs, "x", point_seq->rect.x );
4104 cvWriteInt( fs, "y", point_seq->rect.y );
4105 cvWriteInt( fs, "width", point_seq->rect.width );
4106 cvWriteInt( fs, "height", point_seq->rect.height );
4107 cvEndWriteStruct( fs );
4108 cvWriteInt( fs, "color", point_seq->color );
4110 else if( CV_IS_SEQ(seq) && CV_IS_SEQ_CHAIN(seq) &&
4111 CV_MAT_TYPE(seq->flags) == CV_8UC1 )
4113 CvChain* chain = (CvChain*)seq;
4115 cvStartWriteStruct( fs, "origin", CV_NODE_MAP + CV_NODE_FLOW );
4116 cvWriteInt( fs, "x", chain->origin.x );
4117 cvWriteInt( fs, "y", chain->origin.y );
4118 cvEndWriteStruct( fs );
4122 unsigned extra_size = seq->header_size - initial_header_size;
4123 // a heuristic to provide nice defaults for sequences of int's & float's
4124 if( extra_size % sizeof(int) == 0 )
4125 sprintf( header_dt_buf, "%ui", (unsigned)(extra_size/sizeof(int)) );
4127 sprintf( header_dt_buf, "%uu", extra_size );
4128 header_dt = header_dt_buf;
4134 cvWriteString( fs, "header_dt", header_dt, 0 );
4135 cvStartWriteStruct( fs, "header_user_data", CV_NODE_SEQ + CV_NODE_FLOW );
4136 cvWriteRawData( fs, (uchar*)seq + sizeof(CvSeq), 1, header_dt );
4137 cvEndWriteStruct( fs );
4145 icvGetFormat( const CvSeq* seq, const char* dt_key, CvAttrList* attr,
4146 int initial_elem_size, char* dt_buf )
4150 CV_FUNCNAME( "icvWriteFormat" );
4154 dt = (char*)cvAttrValue( attr, dt_key );
4159 CV_CALL( dt_elem_size = icvCalcElemSize( dt, initial_elem_size ));
4160 if( dt_elem_size != seq->elem_size )
4161 CV_ERROR( CV_StsUnmatchedSizes,
4162 "The size of element calculated from \"dt\" and "
4163 "the elem_size do not match" );
4165 else if( CV_MAT_TYPE(seq->flags) != 0 || seq->elem_size == 1 )
4167 int align = CV_MAT_DEPTH(seq->flags) == CV_64F ? sizeof(double) : sizeof(size_t);
4168 int full_elem_size = cvAlign(CV_ELEM_SIZE(seq->flags) + initial_elem_size, align);
4169 if( seq->elem_size != full_elem_size )
4170 CV_ERROR( CV_StsUnmatchedSizes,
4171 "Size of sequence element (elem_size) is inconsistent with seq->flags" );
4172 dt = icvEncodeFormat( CV_MAT_TYPE(seq->flags), dt_buf );
4174 else if( seq->elem_size > initial_elem_size )
4176 unsigned extra_elem_size = seq->elem_size - initial_elem_size;
4177 // a heuristic to provide nice defaults for sequences of int's & float's
4178 if( extra_elem_size % sizeof(int) == 0 )
4179 sprintf( dt_buf, "%ui", (unsigned)(extra_elem_size/sizeof(int)) );
4181 sprintf( dt_buf, "%uu", extra_elem_size );
4192 icvWriteSeq( CvFileStorage* fs, const char* name,
4193 const void* struct_ptr,
4194 CvAttrList attr, int level )
4196 CV_FUNCNAME( "icvWriteSeq" );
4200 const CvSeq* seq = (CvSeq*)struct_ptr;
4203 char dt_buf[128], *dt;
4205 assert( CV_IS_SEQ( seq ));
4206 CV_CALL( cvStartWriteStruct( fs, name, CV_NODE_MAP, CV_TYPE_NAME_SEQ ));
4209 cvWriteInt( fs, "level", level );
4211 sprintf( buf, "%08x", seq->flags );
4212 cvWriteString( fs, "flags", buf, 1 );
4213 cvWriteInt( fs, "count", seq->total );
4214 CV_CALL( dt = icvGetFormat( seq, "dt", &attr, 0, dt_buf ));
4215 cvWriteString( fs, "dt", dt, 0 );
4217 CV_CALL( icvWriteHeaderData( fs, seq, &attr, sizeof(CvSeq) ));
4218 cvStartWriteStruct( fs, "data", CV_NODE_SEQ + CV_NODE_FLOW );
4220 for( block = seq->first; block; block = block->next )
4222 cvWriteRawData( fs, block->data, block->count, dt );
4223 if( block == seq->first->prev )
4226 cvEndWriteStruct( fs );
4227 cvEndWriteStruct( fs );
4234 icvWriteSeqTree( CvFileStorage* fs, const char* name,
4235 const void* struct_ptr, CvAttrList attr )
4237 CV_FUNCNAME( "icvWriteSeqTree" );
4241 const CvSeq* seq = (CvSeq*)struct_ptr;
4242 const char* recursive_value = cvAttrValue( &attr, "recursive" );
4243 int is_recursive = !(!recursive_value || strcmp(recursive_value,"0") == 0 ||
4244 strlen(recursive_value) == 5 &&
4245 (strcmp(recursive_value,"false") == 0 ||
4246 strcmp(recursive_value,"False") == 0 ||
4247 strcmp(recursive_value,"FALSE") == 0 ));
4249 assert( CV_IS_SEQ( seq ));
4253 CV_CALL( icvWriteSeq( fs, name, seq, attr, -1 ));
4257 CvTreeNodeIterator tree_iterator;
4259 CV_CALL( cvStartWriteStruct( fs, name, CV_NODE_MAP, CV_TYPE_NAME_SEQ_TREE ));
4260 CV_CALL( cvStartWriteStruct( fs, "sequences", CV_NODE_SEQ ));
4261 cvInitTreeNodeIterator( &tree_iterator, seq, INT_MAX );
4265 if( !tree_iterator.node )
4267 CV_CALL( icvWriteSeq( fs, 0, tree_iterator.node, attr, tree_iterator.level ));
4268 cvNextTreeNode( &tree_iterator );
4271 cvEndWriteStruct( fs );
4272 cvEndWriteStruct( fs );
4280 icvReadSeq( CvFileStorage* fs, CvFileNode* node )
4283 CV_FUNCNAME( "icvReadSeq" );
4289 CvFileNode *data, *header_node, *rect_node, *origin_node;
4292 int elem_size, header_size = sizeof(CvSeq);
4293 int fmt_pairs[CV_FS_MAX_FMT_PAIRS], i, fmt_pair_count;
4294 int items_per_elem = 0;
4295 const char* flags_str;
4296 const char* header_dt;
4300 CV_CALL( flags_str = cvReadStringByName( fs, node, "flags", 0 ));
4301 total = cvReadIntByName( fs, node, "count", -1 );
4302 dt = cvReadStringByName( fs, node, "dt", 0 );
4304 if( !flags_str || total == -1 || !dt )
4305 CV_ERROR( CV_StsError, "Some of essential sequence attributes are absent" );
4307 flags = (int)strtol( flags_str, &endptr, 16 );
4308 if( endptr == flags_str || (flags & CV_MAGIC_MASK) != CV_SEQ_MAGIC_VAL )
4309 CV_ERROR( CV_StsError, "The sequence flags are invalid" );
4311 header_dt = cvReadStringByName( fs, node, "header_dt", 0 );
4312 header_node = cvGetFileNodeByName( fs, node, "header_user_data" );
4314 if( (header_dt != 0) ^ (header_node != 0) )
4315 CV_ERROR( CV_StsError,
4316 "One of \"header_dt\" and \"header_user_data\" is there, while the other is not" );
4318 rect_node = cvGetFileNodeByName( fs, node, "rect" );
4319 origin_node = cvGetFileNodeByName( fs, node, "origin" );
4321 if( (header_node != 0) + (rect_node != 0) + (origin_node != 0) > 1 )
4322 CV_ERROR( CV_StsError, "Only one of \"header_user_data\", \"rect\" and \"origin\" tags may occur" );
4326 CV_CALL( header_size = icvCalcElemSize( header_dt, header_size ));
4328 else if( rect_node )
4329 header_size = sizeof(CvPoint2DSeq);
4330 else if( origin_node )
4331 header_size = sizeof(CvChain);
4333 CV_CALL( elem_size = icvCalcElemSize( dt, 0 ));
4334 CV_CALL( seq = cvCreateSeq( flags, header_size, elem_size, fs->dststorage ));
4338 CV_CALL( cvReadRawData( fs, header_node, (char*)seq + sizeof(CvSeq), header_dt ));
4340 else if( rect_node )
4342 CvPoint2DSeq* point_seq = (CvPoint2DSeq*)seq;
4343 point_seq->rect.x = cvReadIntByName( fs, rect_node, "x", 0 );
4344 point_seq->rect.y = cvReadIntByName( fs, rect_node, "y", 0 );
4345 point_seq->rect.width = cvReadIntByName( fs, rect_node, "width", 0 );
4346 point_seq->rect.height = cvReadIntByName( fs, rect_node, "height", 0 );
4347 point_seq->color = cvReadIntByName( fs, node, "color", 0 );
4349 else if( origin_node )
4351 CvChain* chain = (CvChain*)seq;
4352 chain->origin.x = cvReadIntByName( fs, origin_node, "x", 0 );
4353 chain->origin.y = cvReadIntByName( fs, origin_node, "y", 0 );
4356 cvSeqPushMulti( seq, 0, total, 0 );
4357 CV_CALL( fmt_pair_count = icvDecodeFormat( dt, fmt_pairs, CV_FS_MAX_FMT_PAIRS ));
4358 fmt_pair_count *= 2;
4359 for( i = 0; i < fmt_pair_count; i += 2 )
4360 items_per_elem += fmt_pairs[i];
4362 data = cvGetFileNodeByName( fs, node, "data" );
4364 CV_ERROR( CV_StsError, "The image data is not found in file storage" );
4366 if( icvFileNodeSeqLen( data ) != total*items_per_elem )
4367 CV_ERROR( CV_StsError, "The number of stored elements does not match to \"count\"" );
4369 cvStartReadRawData( fs, data, &reader );
4370 for( block = seq->first; block; block = block->next )
4372 int delta = block->count*items_per_elem;
4373 cvReadRawDataSlice( fs, &reader, delta, block->data, dt );
4374 if( block == seq->first->prev )
4387 icvReadSeqTree( CvFileStorage* fs, CvFileNode* node )
4390 CV_FUNCNAME( "icvReadSeqTree" );
4394 CvFileNode *sequences_node = cvGetFileNodeByName( fs, node, "sequences" );
4398 CvSeq* prev_seq = 0;
4403 if( !sequences_node || !CV_NODE_IS_SEQ(sequences_node->tag) )
4404 CV_ERROR( CV_StsParseError,
4405 "opencv-sequence-tree instance should contain a field \"sequences\" that should be a sequence" );
4407 sequences = sequences_node->data.seq;
4408 total = sequences->total;
4410 cvStartReadSeq( sequences, &reader, 0 );
4411 for( i = 0; i < total; i++ )
4413 CvFileNode* elem = (CvFileNode*)reader.ptr;
4416 CV_CALL( seq = (CvSeq*)cvRead( fs, elem ));
4417 CV_CALL( level = cvReadIntByName( fs, elem, "level", -1 ));
4419 CV_ERROR( CV_StsParseError, "All the sequence tree nodes should contain \"level\" field" );
4422 if( level > prev_level )
4424 assert( level == prev_level + 1 );
4428 parent->v_next = seq;
4430 else if( level < prev_level )
4432 for( ; prev_level > level; prev_level-- )
4433 prev_seq = prev_seq->v_prev;
4434 parent = prev_seq->v_prev;
4436 seq->h_prev = prev_seq;
4438 prev_seq->h_next = seq;
4439 seq->v_prev = parent;
4442 CV_NEXT_SEQ_ELEM( sequences->elem_size, reader );
4452 /******************************* CvGraph ******************************/
4455 icvIsGraph( const void* ptr )
4457 return CV_IS_GRAPH(ptr);
4462 icvReleaseGraph( void** ptr )
4464 CV_FUNCNAME( "icvReleaseGraph" );
4469 CV_ERROR( CV_StsNullPtr, "NULL double pointer" );
4471 *ptr = 0; // it's impossible now to release graph, so just clear the pointer
4478 icvCloneGraph( const void* ptr )
4480 return cvCloneGraph( (const CvGraph*)ptr, 0 );
4485 icvWriteGraph( CvFileStorage* fs, const char* name,
4486 const void* struct_ptr, CvAttrList attr )
4489 char* write_buf = 0;
4490 CV_FUNCNAME( "icvWriteGraph" );
4494 const CvGraph* graph = (const CvGraph*)struct_ptr;
4497 int i, k, vtx_count, edge_count;
4498 char vtx_dt_buf[128], *vtx_dt;
4499 char edge_dt_buf[128], *edge_dt;
4502 assert( CV_IS_GRAPH(graph) );
4503 vtx_count = cvGraphGetVtxCount( graph );
4504 edge_count = cvGraphGetEdgeCount( graph );
4505 CV_CALL( flag_buf = (int*)cvAlloc( vtx_count*sizeof(flag_buf[0])));
4508 cvStartReadSeq( (CvSeq*)graph, &reader );
4509 for( i = 0, k = 0; i < graph->total; i++ )
4511 if( CV_IS_SET_ELEM( reader.ptr ))
4513 CvGraphVtx* vtx = (CvGraphVtx*)reader.ptr;
4514 flag_buf[k] = vtx->flags;
4517 CV_NEXT_SEQ_ELEM( graph->elem_size, reader );
4521 CV_CALL( cvStartWriteStruct( fs, name, CV_NODE_MAP, CV_TYPE_NAME_GRAPH ));
4523 sprintf( buf, "%08x", graph->flags );
4524 cvWriteString( fs, "flags", buf, 1 );
4526 cvWriteInt( fs, "vertex_count", vtx_count );
4527 CV_CALL( vtx_dt = icvGetFormat( (CvSeq*)graph, "vertex_dt",
4528 &attr, sizeof(CvGraphVtx), vtx_dt_buf ));
4530 cvWriteString( fs, "vertex_dt", vtx_dt, 0 );
4532 cvWriteInt( fs, "edge_count", edge_count );
4533 CV_CALL( edge_dt = icvGetFormat( (CvSeq*)graph->edges, "edge_dt",
4534 &attr, sizeof(CvGraphEdge), buf ));
4535 sprintf( edge_dt_buf, "2if%s", edge_dt ? edge_dt : "" );
4536 edge_dt = edge_dt_buf;
4537 cvWriteString( fs, "edge_dt", edge_dt, 0 );
4539 CV_CALL( icvWriteHeaderData( fs, (CvSeq*)graph, &attr, sizeof(CvGraph) ));
4541 write_buf_size = MAX( 3*graph->elem_size, 1 << 16 );
4542 write_buf_size = MAX( 3*graph->edges->elem_size, write_buf_size );
4543 CV_CALL( write_buf = (char*)cvAlloc( write_buf_size ));
4545 // as vertices and edges are written in similar way,
4546 // do it as a parametrized 2-iteration loop
4547 for( k = 0; k < 2; k++ )
4549 const char* dt = k == 0 ? vtx_dt : edge_dt;
4552 CvSet* data = k == 0 ? (CvSet*)graph : graph->edges;
4553 int elem_size = data->elem_size;
4554 int write_elem_size = icvCalcElemSize( dt, 0 );
4555 char* src_ptr = write_buf;
4556 int write_max = write_buf_size / write_elem_size, write_count = 0;
4558 // alignment of user part of the edge data following 2if
4559 int edge_user_align = sizeof(float);
4563 int fmt_pairs[CV_FS_MAX_FMT_PAIRS], fmt_pair_count;
4564 fmt_pair_count = icvDecodeFormat( dt, fmt_pairs, CV_FS_MAX_FMT_PAIRS );
4565 if( fmt_pair_count > 2 || CV_ELEM_SIZE(fmt_pairs[2*2+1]) >= (int)sizeof(double))
4566 edge_user_align = sizeof(double);
4569 cvStartWriteStruct( fs, k == 0 ? "vertices" : "edges",
4570 CV_NODE_SEQ + CV_NODE_FLOW );
4571 cvStartReadSeq( (CvSeq*)data, &reader );
4572 for( i = 0; i < data->total; i++ )
4574 if( CV_IS_SET_ELEM( reader.ptr ))
4576 if( k == 0 ) // vertices
4577 memcpy( src_ptr, reader.ptr + sizeof(CvGraphVtx), write_elem_size );
4580 CvGraphEdge* edge = (CvGraphEdge*)reader.ptr;
4581 src_ptr = (char*)cvAlignPtr( src_ptr, sizeof(int) );
4582 ((int*)src_ptr)[0] = edge->vtx[0]->flags;
4583 ((int*)src_ptr)[1] = edge->vtx[1]->flags;
4584 *(float*)(src_ptr + sizeof(int)*2) = edge->weight;
4585 if( elem_size > (int)sizeof(CvGraphEdge) )
4587 char* src_ptr2 = (char*)cvAlignPtr( src_ptr + 2*sizeof(int)
4588 + sizeof(float), edge_user_align );
4589 memcpy( src_ptr2, edge + 1, elem_size - sizeof(CvGraphEdge) );
4592 src_ptr += write_elem_size;
4593 if( ++write_count >= write_max )
4595 cvWriteRawData( fs, write_buf, write_count, dt );
4597 src_ptr = write_buf;
4600 CV_NEXT_SEQ_ELEM( data->elem_size, reader );
4603 if( write_count > 0 )
4604 cvWriteRawData( fs, write_buf, write_count, dt );
4605 cvEndWriteStruct( fs );
4609 cvEndWriteStruct( fs );
4611 // final stage. restore the graph flags
4612 cvStartReadSeq( (CvSeq*)graph, &reader );
4614 for( i = 0; i < graph->total; i++ )
4616 if( CV_IS_SET_ELEM( reader.ptr ))
4617 ((CvGraphVtx*)reader.ptr)->flags = flag_buf[vtx_count++];
4618 CV_NEXT_SEQ_ELEM( graph->elem_size, reader );
4623 cvFree( &write_buf );
4624 cvFree( &flag_buf );
4629 icvReadGraph( CvFileStorage* fs, CvFileNode* node )
4633 CvGraphVtx** vtx_buf = 0;
4634 CV_FUNCNAME( "icvReadGraph" );
4639 CvFileNode *header_node, *vtx_node, *edge_node;
4640 int flags, vtx_count, edge_count;
4641 int vtx_size = sizeof(CvGraphVtx), edge_size, header_size = sizeof(CvGraph);
4642 int src_vtx_size = 0, src_edge_size;
4643 int fmt_pairs[CV_FS_MAX_FMT_PAIRS], fmt_pair_count;
4644 int vtx_items_per_elem = 0, edge_items_per_elem = 0;
4645 int edge_user_align = sizeof(float);
4648 const char* flags_str;
4649 const char* header_dt;
4651 const char* edge_dt;
4654 CV_CALL( flags_str = cvReadStringByName( fs, node, "flags", 0 ));
4655 vtx_dt = cvReadStringByName( fs, node, "vertex_dt", 0 );
4656 edge_dt = cvReadStringByName( fs, node, "edge_dt", 0 );
4657 vtx_count = cvReadIntByName( fs, node, "vertex_count", -1 );
4658 edge_count = cvReadIntByName( fs, node, "edge_count", -1 );
4660 if( !flags_str || vtx_count == -1 || edge_count == -1 || !edge_dt )
4661 CV_ERROR( CV_StsError, "Some of essential sequence attributes are absent" );
4663 flags = (int)strtol( flags_str, &endptr, 16 );
4664 if( endptr == flags_str ||
4665 (flags & (CV_SEQ_KIND_MASK|CV_MAGIC_MASK)) != (CV_GRAPH|CV_SET_MAGIC_VAL))
4666 CV_ERROR( CV_StsError, "Invalid graph signature" );
4668 header_dt = cvReadStringByName( fs, node, "header_dt", 0 );
4669 header_node = cvGetFileNodeByName( fs, node, "header_user_data" );
4671 if( (header_dt != 0) ^ (header_node != 0) )
4672 CV_ERROR( CV_StsError,
4673 "One of \"header_dt\" and \"header_user_data\" is there, while the other is not" );
4676 CV_CALL( header_size = icvCalcElemSize( header_dt, header_size ));
4680 CV_CALL( src_vtx_size = icvCalcElemSize( vtx_dt, 0 ));
4681 CV_CALL( vtx_size = icvCalcElemSize( vtx_dt, vtx_size ));
4682 CV_CALL( fmt_pair_count = icvDecodeFormat( edge_dt,
4683 fmt_pairs, CV_FS_MAX_FMT_PAIRS ));
4684 fmt_pair_count *= 2;
4685 for( i = 0; i < fmt_pair_count; i += 2 )
4686 vtx_items_per_elem += fmt_pairs[i];
4690 char dst_edge_dt_buf[128];
4691 const char* dst_edge_dt = 0;
4693 CV_CALL( fmt_pair_count = icvDecodeFormat( edge_dt,
4694 fmt_pairs, CV_FS_MAX_FMT_PAIRS ));
4695 if( fmt_pair_count < 2 ||
4696 fmt_pairs[0] != 2 || fmt_pairs[1] != CV_32S ||
4697 fmt_pairs[2] < 1 || fmt_pairs[3] != CV_32F )
4698 CV_ERROR( CV_StsBadArg,
4699 "Graph edges should start with 2 integers and a float" );
4701 // alignment of user part of the edge data following 2if
4702 if( fmt_pair_count > 2 && CV_ELEM_SIZE(fmt_pairs[5]) >= (int)sizeof(double))
4703 edge_user_align = sizeof(double);
4705 fmt_pair_count *= 2;
4706 for( i = 0; i < fmt_pair_count; i += 2 )
4707 edge_items_per_elem += fmt_pairs[i];
4709 if( edge_dt[2] == 'f' || edge_dt[2] == '1' && edge_dt[3] == 'f' )
4710 dst_edge_dt = edge_dt + 3 + isdigit(edge_dt[2]);
4713 int val = (int)strtol( edge_dt + 2, &endptr, 10 );
4714 sprintf( dst_edge_dt_buf, "%df%s", val-1, endptr );
4715 dst_edge_dt = dst_edge_dt_buf;
4718 CV_CALL( edge_size = icvCalcElemSize( dst_edge_dt, sizeof(CvGraphEdge) ));
4719 CV_CALL( src_edge_size = icvCalcElemSize( edge_dt, 0 ));
4722 CV_CALL( graph = cvCreateGraph( flags, header_size, vtx_size, edge_size, fs->dststorage ));
4725 CV_CALL( cvReadRawData( fs, header_node, (char*)graph + sizeof(CvGraph), header_dt ));
4727 read_buf_size = MAX( src_vtx_size*3, 1 << 16 );
4728 read_buf_size = MAX( src_edge_size*3, read_buf_size );
4729 CV_CALL( read_buf = (char*)cvAlloc( read_buf_size ));
4730 CV_CALL( vtx_buf = (CvGraphVtx**)cvAlloc( vtx_count * sizeof(vtx_buf[0]) ));
4732 vtx_node = cvGetFileNodeByName( fs, node, "vertices" );
4733 edge_node = cvGetFileNodeByName( fs, node, "edges" );
4735 CV_ERROR( CV_StsBadArg, "No edges data" );
4736 if( vtx_dt && !vtx_node )
4737 CV_ERROR( CV_StsBadArg, "No vertices data" );
4739 // as vertices and edges are read in similar way,
4740 // do it as a parametrized 2-iteration loop
4741 for( k = 0; k < 2; k++ )
4743 const char* dt = k == 0 ? vtx_dt : edge_dt;
4744 int elem_size = k == 0 ? vtx_size : edge_size;
4745 int src_elem_size = k == 0 ? src_vtx_size : src_edge_size;
4746 int items_per_elem = k == 0 ? vtx_items_per_elem : edge_items_per_elem;
4747 int elem_count = k == 0 ? vtx_count : edge_count;
4748 char* dst_ptr = read_buf;
4749 int read_max = read_buf_size /MAX(src_elem_size, 1), read_count = 0;
4751 cvStartReadRawData( fs, k == 0 ? vtx_node : edge_node, &reader );
4753 for( i = 0; i < elem_count; i++ )
4755 if( read_count == 0 && dt )
4757 int count = MIN( elem_count - i, read_max )*items_per_elem;
4758 cvReadRawDataSlice( fs, &reader, count, read_buf, dt );
4766 cvGraphAddVtx( graph, 0, &vtx );
4769 memcpy( vtx + 1, dst_ptr, src_elem_size );
4773 CvGraphEdge* edge = 0;
4774 int vtx1 = ((int*)dst_ptr)[0];
4775 int vtx2 = ((int*)dst_ptr)[1];
4778 if( (unsigned)vtx1 >= (unsigned)vtx_count ||
4779 (unsigned)vtx2 >= (unsigned)vtx_count )
4780 CV_ERROR( CV_StsOutOfRange,
4781 "Some of stored vertex indices are out of range" );
4783 CV_CALL( result = cvGraphAddEdgeByPtr( graph,
4784 vtx_buf[vtx1], vtx_buf[vtx2], 0, &edge ));
4787 CV_ERROR( CV_StsBadArg, "Duplicated edge has occured" );
4789 edge->weight = *(float*)(dst_ptr + sizeof(int)*2);
4790 if( elem_size > (int)sizeof(CvGraphEdge) )
4792 char* dst_ptr2 = (char*)cvAlignPtr( dst_ptr + sizeof(int)*2 +
4793 sizeof(float), edge_user_align );
4794 memcpy( edge + 1, dst_ptr2, elem_size - sizeof(CvGraphEdge) );
4798 dst_ptr += src_elem_size;
4807 cvFree( &read_buf );
4813 /****************************************************************************************\
4815 \****************************************************************************************/
4817 CvTypeInfo *CvType::first = 0, *CvType::last = 0;
4819 CvType::CvType( const char* type_name,
4820 CvIsInstanceFunc is_instance, CvReleaseFunc release,
4821 CvReadFunc read, CvWriteFunc write, CvCloneFunc clone )
4825 _info.header_size = sizeof(_info);
4826 _info.type_name = type_name;
4827 _info.prev = _info.next = 0;
4828 _info.is_instance = is_instance;
4829 _info.release = release;
4830 _info.clone = clone;
4832 _info.write = write;
4834 cvRegisterType( &_info );
4841 cvUnregisterType( info->type_name );
4845 CvType seq_type( CV_TYPE_NAME_SEQ, icvIsSeq, icvReleaseSeq, icvReadSeq,
4846 icvWriteSeqTree /* this is the entry point for
4847 writing a single sequence too */, icvCloneSeq );
4849 CvType seq_tree_type( CV_TYPE_NAME_SEQ_TREE, icvIsSeq, icvReleaseSeq,
4850 icvReadSeqTree, icvWriteSeqTree, icvCloneSeq );
4852 CvType seq_graph_type( CV_TYPE_NAME_GRAPH, icvIsGraph, icvReleaseGraph,
4853 icvReadGraph, icvWriteGraph, icvCloneGraph );
4855 CvType sparse_mat_type( CV_TYPE_NAME_SPARSE_MAT, icvIsSparseMat,
4856 (CvReleaseFunc)cvReleaseSparseMat, icvReadSparseMat,
4857 icvWriteSparseMat, (CvCloneFunc)cvCloneSparseMat );
4859 CvType image_type( CV_TYPE_NAME_IMAGE, icvIsImage, (CvReleaseFunc)cvReleaseImage,
4860 icvReadImage, icvWriteImage, (CvCloneFunc)cvCloneImage );
4862 CvType mat_type( CV_TYPE_NAME_MAT, icvIsMat, (CvReleaseFunc)cvReleaseMat,
4863 icvReadMat, icvWriteMat, (CvCloneFunc)cvCloneMat );
4865 CvType matnd_type( CV_TYPE_NAME_MATND, icvIsMatND, (CvReleaseFunc)cvReleaseMatND,
4866 icvReadMatND, icvWriteMatND, (CvCloneFunc)cvCloneMatND );
4869 cvRegisterType( const CvTypeInfo* _info )
4871 CV_FUNCNAME("cvRegisterType" );
4875 CvTypeInfo* info = 0;
4879 //if( !CvType::first )
4880 // icvCreateStandardTypes();
4882 if( !_info || _info->header_size != sizeof(CvTypeInfo) )
4883 CV_ERROR( CV_StsBadSize, "Invalid type info" );
4885 if( !_info->is_instance || !_info->release ||
4886 !_info->read || !_info->write )
4887 CV_ERROR( CV_StsNullPtr,
4888 "Some of required function pointers "
4889 "(is_instance, release, read or write) are NULL");
4891 c = _info->type_name[0];
4892 if( !isalpha(c) && c != '_' )
4893 CV_ERROR( CV_StsBadArg, "Type name should start with a letter or _" );
4895 len = (int)strlen(_info->type_name);
4897 for( i = 0; i < len; i++ )
4899 c = _info->type_name[i];
4900 if( !isalnum(c) && c != '-' && c != '_' )
4901 CV_ERROR( CV_StsBadArg,
4902 "Type name should contain only letters, digits, - and _" );
4905 CV_CALL( info = (CvTypeInfo*)cvAlloc( sizeof(*info) + len + 1 ));
4908 info->type_name = (char*)(info + 1);
4909 memcpy( (char*)info->type_name, _info->type_name, len + 1 );
4912 info->next = CvType::first;
4915 CvType::first->prev = info;
4917 CvType::last = info;
4918 CvType::first = info;
4925 cvUnregisterType( const char* type_name )
4927 CV_FUNCNAME("cvUnregisterType" );
4933 CV_CALL( info = cvFindType( type_name ));
4937 info->prev->next = info->next;
4939 CvType::first = info->next;
4942 info->next->prev = info->prev;
4944 CvType::last = info->prev;
4946 if( !CvType::first || !CvType::last )
4947 CvType::first = CvType::last = 0;
4959 return CvType::first;
4964 cvFindType( const char* type_name )
4966 CvTypeInfo* info = 0;
4968 for( info = CvType::first; info != 0; info = info->next )
4969 if( strcmp( info->type_name, type_name ) == 0 )
4977 cvTypeOf( const void* struct_ptr )
4979 CvTypeInfo* info = 0;
4981 for( info = CvType::first; info != 0; info = info->next )
4982 if( info->is_instance( struct_ptr ))
4989 /* universal functions */
4991 cvRelease( void** struct_ptr )
4993 CV_FUNCNAME("cvRelease" );
5000 CV_ERROR( CV_StsNullPtr, "NULL double pointer" );
5004 CV_CALL( info = cvTypeOf( *struct_ptr ));
5006 CV_ERROR( CV_StsError, "Unknown object type" );
5007 if( !info->release )
5008 CV_ERROR( CV_StsError, "release function pointer is NULL" );
5010 CV_CALL( info->release( struct_ptr ));
5018 void* cvClone( const void* struct_ptr )
5020 void* struct_copy = 0;
5022 CV_FUNCNAME("cvClone" );
5029 CV_ERROR( CV_StsNullPtr, "NULL structure pointer" );
5031 CV_CALL( info = cvTypeOf( struct_ptr ));
5033 CV_ERROR( CV_StsError, "Unknown object type" );
5035 CV_ERROR( CV_StsError, "clone function pointer is NULL" );
5037 CV_CALL( struct_copy = info->clone( struct_ptr ));
5045 /* reads matrix, image, sequence, graph etc. */
5047 cvRead( CvFileStorage* fs, CvFileNode* node, CvAttrList* list )
5051 CV_FUNCNAME( "cvRead" );
5055 CV_CHECK_FILE_STORAGE( fs );
5060 if( !CV_NODE_IS_USER(node->tag) || !node->info )
5061 CV_ERROR( CV_StsError, "The node does not represent a user object (unknown type?)" );
5063 CV_CALL( obj = node->info->read( fs, node ));
5068 *list = cvAttrList(0,0);
5074 /* writes matrix, image, sequence, graph etc. */
5076 cvWrite( CvFileStorage* fs, const char* name,
5077 const void* ptr, CvAttrList attributes )
5079 CV_FUNCNAME( "cvWrite" );
5085 CV_CHECK_OUTPUT_FILE_STORAGE( fs );
5088 CV_ERROR( CV_StsNullPtr, "Null pointer to the written object" );
5090 CV_CALL( info = cvTypeOf( ptr ));
5092 CV_ERROR( CV_StsBadArg, "Unknown object" );
5095 CV_ERROR( CV_StsBadArg, "The object does not have write function" );
5097 CV_CALL( info->write( fs, name, ptr, attributes ));
5103 /* simple API for reading/writing data */
5105 cvSave( const char* filename, const void* struct_ptr,
5106 const char* _name, const char* comment, CvAttrList attributes )
5108 CvFileStorage* fs = 0;
5110 CV_FUNCNAME( "cvSave" );
5114 char name_buf[CV_FS_MAX_LEN + 256];
5115 char* name = (char*)_name;
5118 CV_ERROR( CV_StsNullPtr, "NULL object pointer" );
5120 CV_CALL( fs = cvOpenFileStorage( filename, 0, CV_STORAGE_WRITE ));
5122 CV_ERROR( CV_StsError, "Could not open the file storage. Check the path and permissions" );
5126 static const char* stubname = "unnamed";
5127 const char* ptr2 = filename + strlen( filename );
5128 const char* ptr = ptr2 - 1;
5130 while( ptr >= filename && *ptr != '\\' && *ptr != '/' && *ptr != ':' )
5132 if( *ptr == '.' && !*ptr2 )
5138 CV_ERROR( CV_StsBadArg, "Invalid filename" );
5142 // name must start with letter or '_'
5143 if( !isalpha(*ptr) && *ptr!= '_' ){
5150 if( !isalnum(c) && c != '-' && c != '_' )
5156 if( strcmp( name, "_" ) == 0 )
5157 strcpy( name, stubname );
5161 CV_CALL( cvWriteComment( fs, comment, 0 ));
5162 CV_CALL( cvWrite( fs, name, struct_ptr, attributes ));
5166 cvReleaseFileStorage( &fs );
5171 cvLoad( const char* filename, CvMemStorage* memstorage,
5172 const char* name, const char** _real_name )
5175 const char* real_name = 0;
5176 CvFileStorage* fs = 0;
5178 CV_FUNCNAME( "cvLoad" );
5182 CvFileNode* node = 0;
5183 CV_CALL( fs = cvOpenFileStorage( filename, memstorage, CV_STORAGE_READ ));
5190 CV_CALL( node = cvGetFileNodeByName( fs, 0, name ));
5195 for( k = 0; k < fs->roots->total; k++ )
5200 node = (CvFileNode*)cvGetSeqElem( fs->roots, k );
5201 if( !CV_NODE_IS_MAP( node->tag ))
5203 seq = node->data.seq;
5206 cvStartReadSeq( seq, &reader, 0 );
5208 // find the first element in the map
5209 for( i = 0; i < seq->total; i++ )
5211 if( CV_IS_SET_ELEM( reader.ptr ))
5213 node = (CvFileNode*)reader.ptr;
5216 CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
5225 CV_ERROR( CV_StsObjectNotFound, "Could not find the/an object in file storage" );
5227 real_name = cvGetFileNodeName( node );
5228 CV_CALL( ptr = cvRead( fs, node, 0 ));
5231 if( !memstorage && (CV_IS_SEQ( ptr ) || CV_IS_SET( ptr )) )
5232 CV_ERROR( CV_StsNullPtr,
5233 "NULL memory storage is passed - the loaded dynamic structure can not be stored" );
5237 cvReleaseFileStorage( &fs );
5238 if( cvGetErrStatus() < 0 )
5240 cvRelease( (void**)&ptr );
5245 *_real_name = real_name;