summaryrefslogtreecommitdiff
path: root/XMPCore/source/XMPMeta-Serialize.cpp
blob: b7373c97f396450357118939dd5393d5e2973f1f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
// =================================================================================================
// Copyright 2003-2009 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE:  Adobe permits you to use, modify, and distribute this file in accordance with the terms
// of the Adobe license agreement accompanying it.
//
// Adobe patent application tracking #P435, entitled 'Unique markers to simplify embedding data of
// one format in a file with a different format', inventors: Sean Parent, Greg Gilley.
// =================================================================================================

#include "public/include/XMP_Environment.h"	// ! This must be the first include!
#include "XMPCore/source/XMPCore_Impl.hpp"

#include "XMPCore/source/XMPMeta.hpp"

#include "public/include/XMP_Version.h"
#include "source/UnicodeInlines.incl_cpp"
#include "source/UnicodeConversions.hpp"

#if XMP_DebugBuild
	#include <iostream>
#endif

using namespace std;

#if XMP_WinBuild
	#pragma warning ( disable : 4533 )	// initialization of '...' is skipped by 'goto ...'
	#pragma warning ( disable : 4702 )	// unreachable code
	#pragma warning ( disable : 4800 )	// forcing value to bool 'true' or 'false' (performance warning)
#endif


// *** Use the XMP_PropIsXyz (Schema, Simple, Struct, Array, ...) macros
// *** Add debug codegen checks, e.g. that typical masking operations really work
// *** Change all uses of strcmp and strncmp to XMP_LitMatch and XMP_LitNMatch


// =================================================================================================
// Local Types and Constants
// =========================

static const char * kPacketHeader  = "<?xpacket begin=\"\xEF\xBB\xBF\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>";
static const char * kPacketTrailer = "<?xpacket end=\"w\"?>";	// ! The w/r is at [size-4].

static const char * kTXMP_SchemaGroup = "XMP_SchemaGroup";

static const char * kRDF_XMPMetaStart = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"";
static const char * kRDF_XMPMetaEnd   = "</x:xmpmeta>";

static const char * kRDF_RDFStart     = "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">";
static const char * kRDF_RDFEnd       = "</rdf:RDF>";

static const char * kRDF_SchemaStart  = "<rdf:Description rdf:about=";
static const char * kRDF_SchemaEnd    = "</rdf:Description>";

static const char * kRDF_StructStart  = "<rdf:Description>";
static const char * kRDF_StructEnd    = "</rdf:Description>";

static const char * kRDF_BagStart     = "<rdf:Bag>";
static const char * kRDF_BagEnd       = "</rdf:Bag>";

static const char * kRDF_SeqStart     = "<rdf:Seq>";
static const char * kRDF_SeqEnd       = "</rdf:Seq>";

static const char * kRDF_AltStart     = "<rdf:Alt>";
static const char * kRDF_AltEnd       = "</rdf:Alt>";

static const char * kRDF_ItemStart    = "<rdf:li>";
static const char * kRDF_ItemEnd      = "</rdf:li>";

static const char * kRDF_ValueStart   = "<rdf:value>";
static const char * kRDF_ValueEnd     = "</rdf:value>";


// =================================================================================================
// Static Variables
// ================


// =================================================================================================
// Local Utilities
// ===============


// -------------------------------------------------------------------------------------------------
// EstimateRDFSize
// ---------------

//  *** Pull the strlen(kXyz) calls into constants.

static size_t
EstimateRDFSize ( const XMP_Node * currNode, XMP_Index indent, size_t indentLen )
{
	size_t outputLen = 2 * (indent*indentLen + currNode->name.size() + 4);	// The property element tags.
	
	if ( ! currNode->qualifiers.empty() ) {
		// This node has qualifiers, assume it is written using rdf:value and estimate the qualifiers.

		indent += 2;	// Everything else is indented inside the rdf:Description element.
		outputLen += 2 * ((indent-1)*indentLen + strlen(kRDF_StructStart) + 2);	// The rdf:Description tags.
		outputLen += 2 * (indent*indentLen + strlen(kRDF_ValueStart) + 2);		// The rdf:value tags.

		for ( size_t qualNum = 0, qualLim = currNode->qualifiers.size(); qualNum < qualLim; ++qualNum ) {
			const XMP_Node * currQual = currNode->qualifiers[qualNum];
			outputLen += EstimateRDFSize ( currQual, indent, indentLen );
		}

	}
	
	if ( currNode->options & kXMP_PropValueIsStruct ) {
		indent += 1;
		outputLen += 2 * (indent*indentLen + strlen(kRDF_StructStart) + 2);	// The rdf:Description tags.
	} else if ( currNode->options & kXMP_PropValueIsArray ) {
		indent += 2;
		outputLen += 2 * ((indent-1)*indentLen + strlen(kRDF_BagStart) + 2);		// The rdf:Bag/Seq/Alt tags.
		outputLen += 2 * currNode->children.size() * (strlen(kRDF_ItemStart) + 2);	// The rdf:li tags, indent counted in children.
	} else if ( ! (currNode->options & kXMP_SchemaNode) ) {
		outputLen += currNode->value.size();	// This is a leaf value node.
	}

	for ( size_t childNum = 0, childLim = currNode->children.size(); childNum < childLim; ++childNum ) {
		const XMP_Node * currChild = currNode->children[childNum];
		outputLen += EstimateRDFSize ( currChild, indent+1, indentLen );
	}

	return outputLen;
	
}	// EstimateRDFSize


// -------------------------------------------------------------------------------------------------
// DeclareOneNamespace
// -------------------

static void
DeclareOneNamespace	( XMP_StringPtr   nsPrefix,
					  XMP_StringPtr   nsURI,
					  XMP_VarString	& usedNS,		// ! A catenation of the prefixes with colons.
					  XMP_VarString & outputStr,
					  XMP_StringPtr   newline,
					  XMP_StringPtr   indentStr,
					  XMP_Index       indent )
{
	XMP_VarString boundedPrefix = ":";
	boundedPrefix += nsPrefix;
	size_t nsPos = usedNS.find ( boundedPrefix );

	if ( nsPos == XMP_VarString::npos ) {
		
		outputStr += newline;
		for ( ; indent > 0; --indent ) outputStr += indentStr;
		outputStr += "xmlns:";
		outputStr += nsPrefix;
		outputStr[outputStr.size()-1] = '=';	// Change the colon to =.
		outputStr += '"';
		outputStr += nsURI;
		outputStr += '"';

		usedNS += nsPrefix;

	}

}	// DeclareOneNamespace


// -------------------------------------------------------------------------------------------------
// DeclareElemNamespace
// --------------------

static void
DeclareElemNamespace ( const XMP_VarString & elemName,
					   XMP_VarString &		 usedNS,
					   XMP_VarString &		 outputStr,
					   XMP_StringPtr		 newline,
					   XMP_StringPtr		 indentStr,
					   XMP_Index			 indent )
{
	size_t colonPos = elemName.find ( ':' );

	if ( colonPos != XMP_VarString::npos ) {
		XMP_VarString nsPrefix ( elemName.substr ( 0, colonPos+1 ) );
		XMP_StringPtr nsURI;
		bool nsFound = sRegisteredNamespaces->GetURI ( nsPrefix.c_str(), &nsURI, 0 );
		XMP_Enforce ( nsFound );
		DeclareOneNamespace ( nsPrefix.c_str(), nsURI, usedNS, outputStr, newline, indentStr, indent );
	}

}	// DeclareElemNamespace


// -------------------------------------------------------------------------------------------------
// DeclareUsedNamespaces
// ---------------------

static void
DeclareUsedNamespaces ( const XMP_Node * currNode,
						XMP_VarString &  usedNS,
						XMP_VarString &	 outputStr,
						XMP_StringPtr	 newline,
						XMP_StringPtr	 indentStr,
						XMP_Index		 indent )
{

	if ( currNode->options & kXMP_SchemaNode ) {
		// The schema node name is the URI, the value is the prefix.
		DeclareOneNamespace ( currNode->value.c_str(), currNode->name.c_str(), usedNS, outputStr, newline, indentStr, indent );
	} else if ( currNode->options & kXMP_PropValueIsStruct ) {
		for ( size_t fieldNum = 0, fieldLim = currNode->children.size(); fieldNum < fieldLim; ++fieldNum ) {
			const XMP_Node * currField = currNode->children[fieldNum];
			DeclareElemNamespace ( currField->name, usedNS, outputStr, newline, indentStr, indent );
		}
	}

	for ( size_t childNum = 0, childLim = currNode->children.size(); childNum < childLim; ++childNum ) {
		const XMP_Node * currChild = currNode->children[childNum];
		DeclareUsedNamespaces ( currChild, usedNS, outputStr, newline, indentStr, indent );
	}

	for ( size_t qualNum = 0, qualLim = currNode->qualifiers.size(); qualNum < qualLim; ++qualNum ) {
		const XMP_Node * currQual = currNode->qualifiers[qualNum];
		DeclareElemNamespace ( currQual->name, usedNS, outputStr, newline, indentStr, indent );
		DeclareUsedNamespaces ( currQual, usedNS, outputStr, newline, indentStr, indent );
	}
	
}	// DeclareUsedNamespaces

// -------------------------------------------------------------------------------------------------
// EmitRDFArrayTag
// ---------------

enum {
	kIsStartTag = true,
	kIsEndTag   = false
};

static void
EmitRDFArrayTag	( XMP_OptionBits  arrayForm,
				  XMP_VarString & outputStr,
				  XMP_StringPtr	  newline,
				  XMP_StringPtr	  indentStr,
				  XMP_Index		  indent,
				  XMP_Index		  arraySize,
				  bool			  isStartTag )
{
	if ( (! isStartTag) && (arraySize == 0) ) return;
	
	for ( XMP_Index level = indent; level > 0; --level ) outputStr += indentStr;
	if ( isStartTag ) {
		outputStr += "<rdf:";
	} else {
		outputStr += "</rdf:";
	}

	if ( arrayForm & kXMP_PropArrayIsAlternate ) {
		outputStr += "Alt";
	} else if ( arrayForm & kXMP_PropArrayIsOrdered ) {
		outputStr += "Seq";
	} else {
		outputStr += "Bag";
	}
	
	if ( isStartTag && (arraySize == 0) ) outputStr += '/';
	outputStr += '>';
	outputStr += newline;

}	// EmitRDFArrayTag


// -------------------------------------------------------------------------------------------------
// AppendNodeValue
// ---------------
//
// Append a property or qualifier value to the output with appropriate XML escaping. The escaped
// characters for elements and attributes are '&', '<', '>', and ASCII controls (tab, LF, CR). In
// addition, '"' is escaped for attributes. For efficiency, this is done in a double loop. The outer
// loop makes sure the whole value is processed. The inner loop does a contiguous unescaped run
// followed by one escaped character (if we're not at the end).
//
// We depend on parsing and SetProperty logic to make sure there are no invalid ASCII controls in
// the XMP values. The XML spec only allows tab, LF, and CR. Others are not even allowed as
// numeric escape sequences.

enum {
	kForAttribute = true,
	kForElement   = false
};

static void
AppendNodeValue ( XMP_VarString & outputStr, const XMP_VarString & value, bool forAttribute )
{

	unsigned char * runStart = (unsigned char *) value.c_str();
	unsigned char * runLimit  = runStart + value.size();
	unsigned char * runEnd;
	unsigned char   ch;
	
	while ( runStart < runLimit ) {
	
		for ( runEnd = runStart; runEnd < runLimit; ++runEnd ) {
			ch = *runEnd;
			if ( forAttribute && (ch == '"') ) break;
			if ( (ch < 0x20) || (ch == '&') || (ch == '<') || (ch == '>') ) break;
		}
		
		outputStr.append ( (char *) runStart, (runEnd - runStart) );
		
		if ( runEnd < runLimit ) {

			if ( ch < 0x20 ) {
			
				XMP_Assert ( (ch == kTab) || (ch == kLF) || (ch == kCR) );

				char hexBuf[16];
				memcpy ( hexBuf, "&#xn;", 6 );	// AUDIT: Length of "&#xn;" is 5, hexBuf size is 16.
				hexBuf[3] = kHexDigits[ch&0xF];
				outputStr.append ( hexBuf, 5 );

			} else {

				if ( ch == '"' ) {
					outputStr += "&quot;";
				} else if ( ch == '<' ) {
					outputStr += "&lt;";
				} else if ( ch == '>' ) {
					outputStr += "&gt;";
				} else {
					XMP_Assert ( ch == '&' );
					outputStr += "&amp;";
				}

			}

			++runEnd;

		}
		
		runStart = runEnd;
	
	}

}	// AppendNodeValue


// -------------------------------------------------------------------------------------------------
// CanBeRDFAttrProp
// ----------------

static bool
CanBeRDFAttrProp ( const XMP_Node * propNode )
{
	
	if ( propNode->name[0] == '[' ) return false;
	if ( ! propNode->qualifiers.empty() ) return false;
	if ( propNode->options & kXMP_PropValueIsURI ) return false;
	if ( propNode->options & kXMP_PropCompositeMask ) return false;
	
	return true;
	
}	// CanBeRDFAttrProp


// -------------------------------------------------------------------------------------------------
// IsRDFAttrQualifier
// ------------------

static XMP_StringPtr sAttrQualifiers[] = { "xml:lang", "rdf:resource", "rdf:ID", "rdf:bagID", "rdf:nodeID", "" };

static bool
IsRDFAttrQualifier ( XMP_VarString qualName )
{

	for ( size_t i = 0; *sAttrQualifiers[i] != 0; ++i ) {
		if ( qualName == sAttrQualifiers[i] ) return true;
	}

	return false;
	
}	// IsRDFAttrQualifier


// -------------------------------------------------------------------------------------------------
// StartOuterRDFDescription
// ------------------------
//
// Start the outer rdf:Description element, including all needed xmlns attributes. Leave the element
// open so that the compact form can add proprtty attributes.

static void
StartOuterRDFDescription ( const XMP_Node & xmpTree,
						   XMP_VarString &  outputStr,
						   XMP_StringPtr	newline,
						   XMP_StringPtr	indentStr,
						   XMP_Index		baseIndent )
{
	
	// Begin the outer rdf:Description start tag.
	
	for ( XMP_Index level = baseIndent+2; level > 0; --level ) outputStr += indentStr;
	outputStr += kRDF_SchemaStart;
	outputStr += '"';
	outputStr += xmpTree.name;
	outputStr += '"';
	
	// Write all necessary xmlns attributes.

	XMP_VarString usedNS;
	usedNS.reserve ( 400 );	// The predefined prefixes add up to about 320 bytes.
	usedNS = ":xml:rdf:";

	for ( size_t schema = 0, schemaLim = xmpTree.children.size(); schema != schemaLim; ++schema ) {
		const XMP_Node * currSchema = xmpTree.children[schema];
		DeclareUsedNamespaces ( currSchema, usedNS, outputStr, newline, indentStr, baseIndent+4 );
	}

}	// StartOuterRDFDescription

// -------------------------------------------------------------------------------------------------
// SerializeCanonicalRDFProperty
// -----------------------------
//
// Recursively handles the "value" for a node. It does not matter if it is a top level property, a
// field of a struct, or an item of an array.  The indent is that for the property element. An
// xml:lang qualifier is written as an attribute of the property start tag, not by itself forcing
// the qualified property form. The patterns below mostly ignore attribute qualifiers like xml:lang.
// Except for the one struct case, attribute qualifiers don't affect the output form.
//
//	<ns:UnqualifiedSimpleProperty>value</ns:UnqualifiedSimpleProperty>
//
//	<ns:UnqualifiedStructProperty>	(If no rdf:resource qualifier)
//		<rdf:Description>
//			... Fields, same forms as top level properties
//		</rdf:Description>
//	</ns:UnqualifiedStructProperty>
//
//	<ns:ResourceStructProperty rdf:resource="URI"
//		... Fields as attributes
//	>
//
//	<ns:UnqualifiedArrayProperty>
//		<rdf:Bag> or Seq or Alt
//			... Array items as rdf:li elements, same forms as top level properties
//		</rdf:Bag>
//	</ns:UnqualifiedArrayProperty>
//
//	<ns:QualifiedProperty>
//		<rdf:Description>
//			<rdf:value> ... Property "value" following the unqualified forms ... </rdf:value>
//			... Qualifiers looking like named struct fields
//		</rdf:Description>
//	</ns:QualifiedProperty>

enum { kUseCanonicalRDF = true, kUseAdobeVerboseRDF = false };
enum { kEmitAsRDFValue = true, kEmitAsNormalValue = false };

static void
SerializeCanonicalRDFProperty ( const XMP_Node * propNode,
								XMP_VarString &  outputStr,
								XMP_StringPtr	 newline,
								XMP_StringPtr	 indentStr,
								XMP_Index		 indent,
								bool			 useCanonicalRDF,
								bool			 emitAsRDFValue )
{
	XMP_Index level;
	bool emitEndTag   = true;
	bool indentEndTag = true;

	XMP_OptionBits propForm = propNode->options & kXMP_PropCompositeMask;

	// ------------------------------------------------------------------------------------------
	// Determine the XML element name. Open the start tag with the name and attribute qualifiers.
	
	XMP_StringPtr elemName = propNode->name.c_str();
	if ( emitAsRDFValue ) {
		elemName= "rdf:value";
	} else if ( *elemName == '[' ) {
		elemName = "rdf:li";
	}

	for ( level = indent; level > 0; --level ) outputStr += indentStr;
	outputStr += '<';
	outputStr += elemName;

	bool hasGeneralQualifiers = false;
	bool hasRDFResourceQual   = false;
	
	for ( size_t qualNum = 0, qualLim = propNode->qualifiers.size(); qualNum < qualLim; ++qualNum ) {
		const XMP_Node * currQual = propNode->qualifiers[qualNum];
		if ( ! IsRDFAttrQualifier ( currQual->name ) ) {
			hasGeneralQualifiers = true;
		} else {
			if ( currQual->name == "rdf:resource" ) hasRDFResourceQual = true;
			if ( ! emitAsRDFValue ) {
				outputStr += ' ';
				outputStr += currQual->name;
				outputStr += "=\"";
				AppendNodeValue ( outputStr, currQual->value, kForAttribute );
				outputStr += '"';
			}
		}
	}
	
	// --------------------------------------------------------
	// Process the property according to the standard patterns.
	
	if ( hasGeneralQualifiers && (! emitAsRDFValue) ) {
	
		// -----------------------------------------------------------------------------------------
		// This node has general, non-attribute, qualifiers. Emit using the qualified property form.
		// ! The value is output by a recursive call ON THE SAME NODE with emitAsRDFValue set.

		if ( hasRDFResourceQual ) {
			XMP_Throw ( "Can't mix rdf:resource and general qualifiers", kXMPErr_BadRDF );
		}

		if ( ! useCanonicalRDF ) {
			outputStr += " rdf:parseType=\"Resource\">";
			outputStr += newline;
		} else {
			outputStr += '>';
			outputStr += newline;
			indent += 1;
			for ( level = indent; level > 0; --level ) outputStr += indentStr;
			outputStr += "<rdf:Description>";
			outputStr += newline;
		}

		SerializeCanonicalRDFProperty ( propNode, outputStr, newline, indentStr, indent+1,
										useCanonicalRDF, kEmitAsRDFValue );

		for ( size_t qualNum = 0, qualLim = propNode->qualifiers.size(); qualNum < qualLim; ++qualNum ) {
			const XMP_Node * currQual = propNode->qualifiers[qualNum];
			if ( IsRDFAttrQualifier ( currQual->name ) ) continue;
			SerializeCanonicalRDFProperty ( currQual, outputStr, newline, indentStr, indent+1,
											useCanonicalRDF, kEmitAsNormalValue );
		}
		
		if ( useCanonicalRDF ) {
			for ( level = indent; level > 0; --level ) outputStr += indentStr;
			outputStr += "</rdf:Description>";
			outputStr += newline;
			indent -= 1;
		}
		
	} else {

		// --------------------------------------------------------------------
		// This node has no general qualifiers. Emit using an unqualified form.
		
		if ( propForm == 0 ) {
		
			// --------------------------
			// This is a simple property.
			
			if ( propNode->options & kXMP_PropValueIsURI ) {
				outputStr += " rdf:resource=\"";
				AppendNodeValue ( outputStr, propNode->value, kForAttribute );
				outputStr += "\"/>";
				outputStr += newline;
				emitEndTag = false;
			} else if ( propNode->value.empty() ) {
				outputStr += "/>";
				outputStr += newline;
				emitEndTag = false;
			} else {
				outputStr += '>';
				AppendNodeValue ( outputStr, propNode->value, kForElement );
				indentEndTag = false;
			}
			
		} else if ( propForm & kXMP_PropValueIsArray ) {
		
			// This is an array.
			outputStr += '>';
			outputStr += newline;
			EmitRDFArrayTag ( propForm, outputStr, newline, indentStr, indent+1, propNode->children.size(), kIsStartTag );
			if ( XMP_ArrayIsAltText(propNode->options) ) NormalizeLangArray ( (XMP_Node*)propNode );
			for ( size_t childNum = 0, childLim = propNode->children.size(); childNum < childLim; ++childNum ) {
				const XMP_Node * currChild = propNode->children[childNum];
				SerializeCanonicalRDFProperty ( currChild, outputStr, newline, indentStr, indent+2,
												useCanonicalRDF, kEmitAsNormalValue );
			}
			EmitRDFArrayTag ( propForm, outputStr, newline, indentStr, indent+1, propNode->children.size(), kIsEndTag );
		
		
		} else if ( ! hasRDFResourceQual ) {
		
			// This is a "normal" struct, use the nested field element form form.
			XMP_Assert ( propForm & kXMP_PropValueIsStruct );
			if ( propNode->children.size() == 0 ) {
				if ( ! useCanonicalRDF ) {
					outputStr += " rdf:parseType=\"Resource\"/>";
					outputStr += newline;
					emitEndTag = false;
				} else {
					outputStr += '>';
					outputStr += newline;
					for ( level = indent+1; level > 0; --level ) outputStr += indentStr;
					outputStr += "<rdf:Description/>";
					outputStr += newline;
				}
			} else {
				if ( ! useCanonicalRDF ) {
					outputStr += " rdf:parseType=\"Resource\">";
					outputStr += newline;
				} else {
					outputStr += '>';
					outputStr += newline;
					indent += 1;
					for ( level = indent; level > 0; --level ) outputStr += indentStr;
					outputStr += "<rdf:Description>";
					outputStr += newline;
				}
				for ( size_t childNum = 0, childLim = propNode->children.size(); childNum < childLim; ++childNum ) {
					const XMP_Node * currChild = propNode->children[childNum];
					SerializeCanonicalRDFProperty ( currChild, outputStr, newline, indentStr, indent+1,
													useCanonicalRDF, kEmitAsNormalValue );
				}
				if ( useCanonicalRDF ) {
					for ( level = indent; level > 0; --level ) outputStr += indentStr;
					outputStr += "</rdf:Description>";
					outputStr += newline;
					indent -= 1;
				}
			}
		
		} else {
		
			// This is a struct with an rdf:resource attribute, use the "empty property element" form.
			XMP_Assert ( propForm & kXMP_PropValueIsStruct );
			for ( size_t childNum = 0, childLim = propNode->children.size(); childNum < childLim; ++childNum ) {
				const XMP_Node * currChild = propNode->children[childNum];
				if ( ! CanBeRDFAttrProp ( currChild ) ) {
					XMP_Throw ( "Can't mix rdf:resource and complex fields", kXMPErr_BadRDF );
				}
				outputStr += newline;
				for ( level = indent+1; level > 0; --level ) outputStr += indentStr;
				outputStr += ' ';
				outputStr += currChild->name;
				outputStr += "=\"";
				outputStr += currChild->value;
				outputStr += '"';
			}
			outputStr += "/>";
			outputStr += newline;
			emitEndTag = false;
		
		}
		
	}
	
	// ----------------------------------
	// Emit the property element end tag.
	
	if ( emitEndTag ) {
		if ( indentEndTag ) for ( level = indent; level > 0; --level ) outputStr += indentStr;
		outputStr += "</";
		outputStr += elemName;
		outputStr += '>';
		outputStr += newline;
	}
	
}	// SerializeCanonicalRDFProperty


// -------------------------------------------------------------------------------------------------
// SerializeCanonicalRDFSchemas
// ----------------------------
//
// Each schema's properties are written to the single rdf:Description element. All of the necessary
// namespaces are declared in the rdf:Description element. The baseIndent is the base level for the
// entire serialization, that of the x:xmpmeta element. An xml:lang qualifier is written as an
// attribute of the property start tag, not by itself forcing the qualified property form.
//
//	<rdf:Description rdf:about="TreeName"
//			xmlns:ns="URI" ... >
//
//		... The actual properties of the schema, see SerializeCanonicalRDFProperty
//
//		<!-- ns1:Alias is aliased to ns2:Actual -->  ... If alias comments are wanted
//
//	</rdf:Description>

static void
SerializeCanonicalRDFSchemas ( const XMP_Node & xmpTree,
							   XMP_VarString &	outputStr,
							   XMP_StringPtr	newline,
							   XMP_StringPtr	indentStr,
							   XMP_Index		baseIndent,
							   bool				useCanonicalRDF )
{

	StartOuterRDFDescription ( xmpTree, outputStr, newline, indentStr, baseIndent );
	
	if ( xmpTree.children.size() > 0 ) {
		outputStr += ">";
		outputStr += newline;
	} else {
		outputStr += "/>";
		outputStr += newline;
		return;	// ! Done if there are no XMP properties.
	}

	for ( size_t schemaNum = 0, schemaLim = xmpTree.children.size(); schemaNum < schemaLim; ++schemaNum ) {
		const XMP_Node * currSchema = xmpTree.children[schemaNum];
		for ( size_t propNum = 0, propLim = currSchema->children.size(); propNum < propLim; ++propNum ) {
			const XMP_Node * currProp = currSchema->children[propNum];
			SerializeCanonicalRDFProperty ( currProp, outputStr, newline, indentStr, baseIndent+3,
											useCanonicalRDF, kEmitAsNormalValue );
		}
	}
	
	// Write the rdf:Description end tag.
	for ( XMP_Index level = baseIndent+2; level > 0; --level ) outputStr += indentStr;
	outputStr += kRDF_SchemaEnd;
	outputStr += newline;

}	// SerializeCanonicalRDFSchemas


// -------------------------------------------------------------------------------------------------
// SerializeCompactRDFAttrProps
// ----------------------------
//
// Write each of the parent's simple unqualified properties as an attribute. Returns true if all
// of the properties are written as attributes.

static bool
SerializeCompactRDFAttrProps ( const XMP_Node *	parentNode,
							   XMP_VarString &	outputStr,
							   XMP_StringPtr	newline,
							   XMP_StringPtr	indentStr,
							   XMP_Index		indent )
{
	size_t prop, propLim;
	bool allAreAttrs = true;

	for ( prop = 0, propLim = parentNode->children.size(); prop != propLim; ++prop ) {

		const XMP_Node * currProp = parentNode->children[prop];
		if ( ! CanBeRDFAttrProp ( currProp ) ) {
			allAreAttrs = false;
			continue;
		}
		
		outputStr += newline;
		for ( XMP_Index level = indent; level > 0; --level ) outputStr += indentStr;
		outputStr += currProp->name;
		outputStr += "=\"";
		AppendNodeValue ( outputStr, currProp->value, kForAttribute );
		outputStr += '"';

	}
	
	return allAreAttrs;

}	// SerializeCompactRDFAttrProps


// -------------------------------------------------------------------------------------------------
// SerializeCompactRDFElemProps
// ----------------------------
//
// Recursively handles the "value" for a node that must be written as an RDF property element. It
// does not matter if it is a top level property, a field of a struct, or an item of an array.  The
// indent is that for the property element. The patterns bwlow ignore attribute qualifiers such as
// xml:lang, they don't affect the output form.
//
//	<ns:UnqualifiedStructProperty-1
//		... The fields as attributes, if all are simple and unqualified
//	/>
//
//	<ns:UnqualifiedStructProperty-2 rdf:parseType="Resource">
//		... The fields as elements, if none are simple and unqualified
//	</ns:UnqualifiedStructProperty-2>
//
//	<ns:UnqualifiedStructProperty-3>
//		<rdf:Description
//			... The simple and unqualified fields as attributes
//		>
//			... The compound or qualified fields as elements
//		</rdf:Description>
//	</ns:UnqualifiedStructProperty-3>
//
//	<ns:UnqualifiedArrayProperty>
//		<rdf:Bag> or Seq or Alt
//			... Array items as rdf:li elements, same forms as top level properties
//		</rdf:Bag>
//	</ns:UnqualifiedArrayProperty>
//
//	<ns:QualifiedProperty rdf:parseType="Resource">
//		<rdf:value> ... Property "value" following the unqualified forms ... </rdf:value>
//		... Qualifiers looking like named struct fields
//	</ns:QualifiedProperty>

// *** Consider numbered array items, but has compatibility problems.
// *** Consider qualified form with rdf:Description and attributes.

static void
SerializeCompactRDFElemProps ( const XMP_Node *	parentNode,
							   XMP_VarString &	outputStr,
							   XMP_StringPtr	newline,
							   XMP_StringPtr	indentStr,
							   XMP_Index		indent )
{
	XMP_Index level;

	for ( size_t prop = 0, propLim = parentNode->children.size(); prop != propLim; ++prop ) {

		const XMP_Node * propNode = parentNode->children[prop];
		if ( CanBeRDFAttrProp ( propNode ) ) continue;

		bool emitEndTag = true;
		bool indentEndTag = true;

		XMP_OptionBits propForm = propNode->options & kXMP_PropCompositeMask;

		// -----------------------------------------------------------------------------------
		// Determine the XML element name, write the name part of the start tag. Look over the
		// qualifiers to decide on "normal" versus "rdf:value" form. Emit the attribute
		// qualifiers at the same time.
		
		XMP_StringPtr elemName = propNode->name.c_str();
		if ( *elemName == '[' ) elemName = "rdf:li";

		for ( level = indent; level > 0; --level ) outputStr += indentStr;
		outputStr += '<';
		outputStr += elemName;
	
		bool hasGeneralQualifiers = false;
		bool hasRDFResourceQual   = false;

		for ( size_t qualNum = 0, qualLim = propNode->qualifiers.size(); qualNum < qualLim; ++qualNum ) {
			const XMP_Node * currQual = propNode->qualifiers[qualNum];
			if ( ! IsRDFAttrQualifier ( currQual->name ) ) {
				hasGeneralQualifiers = true;
			} else {
				if ( currQual->name == "rdf:resource" ) hasRDFResourceQual = true;
				outputStr += ' ';
				outputStr += currQual->name;
				outputStr += "=\"";
				AppendNodeValue ( outputStr, currQual->value, kForAttribute );
				outputStr += '"';
			}
		}
		
		// --------------------------------------------------------
		// Process the property according to the standard patterns.
	
		if ( hasGeneralQualifiers ) {
		
			// -------------------------------------------------------------------------------------
			// The node has general qualifiers, ones that can't be attributes on a property element.
			// Emit using the qualified property pseudo-struct form. The value is output by a call
			// to SerializeCanonicalRDFProperty with emitAsRDFValue set.
			
			// *** We're losing compactness in the calls to SerializeCanonicalRDFProperty.
			// *** Should refactor to have SerializeCompactRDFProperty that does one node.

			outputStr += " rdf:parseType=\"Resource\">";
			outputStr += newline;

			SerializeCanonicalRDFProperty ( propNode, outputStr, newline, indentStr, indent+1,
											kUseAdobeVerboseRDF, kEmitAsRDFValue );

			size_t qualNum = 0;
			size_t qualLim = propNode->qualifiers.size();
			if ( propNode->options & kXMP_PropHasLang ) ++qualNum;
			
			for ( ; qualNum < qualLim; ++qualNum ) {
				const XMP_Node * currQual = propNode->qualifiers[qualNum];
				SerializeCanonicalRDFProperty ( currQual, outputStr, newline, indentStr, indent+1,
												kUseAdobeVerboseRDF, kEmitAsNormalValue );
			}
			
		} else {

			// --------------------------------------------------------------------
			// This node has only attribute qualifiers. Emit as a property element.
			
			if ( propForm == 0 ) {
			
				// --------------------------
				// This is a simple property.
				
				if ( propNode->options & kXMP_PropValueIsURI ) {
					outputStr += " rdf:resource=\"";
					AppendNodeValue ( outputStr, propNode->value, kForAttribute );
					outputStr += "\"/>";
					outputStr += newline;
					emitEndTag = false;
				} else if ( propNode->value.empty() ) {
					outputStr += "/>";
					outputStr += newline;
					emitEndTag = false;
				} else {
					outputStr += '>';
					AppendNodeValue ( outputStr, propNode->value, kForElement );
					indentEndTag = false;
				}
				
			} else if ( propForm & kXMP_PropValueIsArray ) {

				// -----------------
				// This is an array.
				
				outputStr += '>';
				outputStr += newline;
				EmitRDFArrayTag ( propForm, outputStr, newline, indentStr, indent+1, propNode->children.size(), kIsStartTag );
			
				if ( XMP_ArrayIsAltText(propNode->options) ) NormalizeLangArray ( (XMP_Node*)propNode );
				SerializeCompactRDFElemProps ( propNode, outputStr, newline, indentStr, indent+2 );

				EmitRDFArrayTag ( propForm, outputStr, newline, indentStr, indent+1, propNode->children.size(), kIsEndTag );

			} else {

				// ----------------------
				// This must be a struct.
				
				XMP_Assert ( propForm & kXMP_PropValueIsStruct );

				bool hasAttrFields = false;
				bool hasElemFields = false;
			
				size_t field, fieldLim;
				for ( field = 0, fieldLim = propNode->children.size(); field != fieldLim; ++field ) {
					XMP_Node * currField = propNode->children[field];
					if ( CanBeRDFAttrProp ( currField ) ) {
						hasAttrFields = true;
						if ( hasElemFields ) break;	// No sense looking further.
					} else {
						hasElemFields = true;
						if ( hasAttrFields ) break;	// No sense looking further.
					}
				}
				
				if ( hasRDFResourceQual && hasElemFields ) {
					XMP_Throw ( "Can't mix rdf:resource qualifier and element fields", kXMPErr_BadRDF );
				}
				
				if ( propNode->children.size() == 0 ) {
				
					// Catch an empty struct as a special case. The case below would emit an empty
					// XML element, which gets reparsed as a simple property with an empty value.
					outputStr += " rdf:parseType=\"Resource\"/>";
					outputStr += newline;
					emitEndTag = false;
				
				} else if ( ! hasElemFields ) {

					// All fields can be attributes, use the emptyPropertyElt form.
					SerializeCompactRDFAttrProps ( propNode, outputStr, newline, indentStr, indent+1 );
					outputStr += "/>";
					outputStr += newline;
					emitEndTag = false;

				} else if ( ! hasAttrFields ) {
				
					// All fields must be elements, use the parseTypeResourcePropertyElt form.
					outputStr += " rdf:parseType=\"Resource\">";
					outputStr += newline;
					SerializeCompactRDFElemProps ( propNode, outputStr, newline, indentStr, indent+1 );
				
				} else {
				
					// Have a mix of attributes and elements, use an inner rdf:Description.
					outputStr += '>';
					outputStr += newline;
					for ( level = indent+1; level > 0; --level ) outputStr += indentStr;
					outputStr += "<rdf:Description";
					SerializeCompactRDFAttrProps ( propNode, outputStr, newline, indentStr, indent+2 );
					outputStr += ">";
					outputStr += newline;
					SerializeCompactRDFElemProps ( propNode, outputStr, newline, indentStr, indent+1 );
					for ( level = indent+1; level > 0; --level ) outputStr += indentStr;
					outputStr += kRDF_StructEnd;
					outputStr += newline;

				}

			}

		}
		
		// ----------------------------------
		// Emit the property element end tag.
		
		if ( emitEndTag ) {
			if ( indentEndTag ) for ( level = indent; level > 0; --level ) outputStr += indentStr;
			outputStr += "</";
			outputStr += elemName;
			outputStr += '>';
			outputStr += newline;
		}

	}
	
}	// SerializeCompactRDFElemProps


// -------------------------------------------------------------------------------------------------
// SerializeCompactRDFSchemas
// --------------------------
//
// All properties from all schema are written in a single rdf:Description element, as are all of the
// necessary namespace declarations. The baseIndent is the base level for the entire serialization,
// that of the x:xmpmeta element. The x:xmpmeta and rdf:RDF elements have already been written.
//
// Top level simple unqualified properties are written as attributes of the (only) rdf:Description
// element. Structs, arrays, and qualified properties are written by SerializeCompactRDFElemProp. An
// xml:lang qualifier on a simple property prevents the attribute form.
//
//	<rdf:Description rdf:about="TreeName"
//			xmlns:ns="URI" ...
//		ns:UnqualifiedSimpleProperty="value" ... >
//		... The remaining properties of the schema, see SerializeCompactRDFElemProps
//	</rdf:Description>

static void
SerializeCompactRDFSchemas ( const XMP_Node & xmpTree,
							 XMP_VarString &  outputStr,
							 XMP_StringPtr	  newline,
							 XMP_StringPtr	  indentStr,
							 XMP_Index		  baseIndent )
{
	XMP_Index level;
	size_t schema, schemaLim;
	
	StartOuterRDFDescription ( xmpTree, outputStr, newline, indentStr, baseIndent );
	
	// Write the top level "attrProps" and close the rdf:Description start tag.
	bool allAreAttrs = true;
	for ( schema = 0, schemaLim = xmpTree.children.size(); schema != schemaLim; ++schema ) {
		const XMP_Node * currSchema = xmpTree.children[schema];
		allAreAttrs &= SerializeCompactRDFAttrProps ( currSchema, outputStr, newline, indentStr, baseIndent+3 );
	}
	if ( ! allAreAttrs ) {
		outputStr += ">";
		outputStr += newline;
	} else {
		outputStr += "/>";
		outputStr += newline;
		return;	// ! Done if all properties in all schema are written as attributes.
	}

	// Write the remaining properties for each schema.
	for ( schema = 0, schemaLim = xmpTree.children.size(); schema != schemaLim; ++schema ) {
		const XMP_Node * currSchema = xmpTree.children[schema];
		SerializeCompactRDFElemProps ( currSchema, outputStr, newline, indentStr, baseIndent+3 );
	}
	
	// Write the rdf:Description end tag.
	for ( level = baseIndent+2; level > 0; --level ) outputStr += indentStr;
	outputStr += kRDF_SchemaEnd;
	outputStr += newline;

}	// SerializeCompactRDFSchemas


// -------------------------------------------------------------------------------------------------
// SerializeAsRDF
// --------------
//
//	<?xpacket begin... ?>
//	<x:xmpmeta xmlns:x=... >
//		<rdf:RDF xmlns:rdf=... >
//
//			... The properties, see SerializeCanonicalRDFSchema or SerializeCompactRDFSchemas
//
//		</rdf:RDF>
//	</x:xmpmeta>
//	<?xpacket end... ?>

// *** Need to strip empty arrays?
// *** Option to strip/keep empty structs?
// *** Need to verify handling of rdf:type qualifiers in canonical and compact.
// *** Need to verify round tripping of rdf:ID and similar qualifiers, see RDF 7.2.21.
// *** Check cases of rdf:resource plus explicit attr qualifiers (like xml:lang).

static void
SerializeAsRDF ( const XMPMeta & xmpObj,
				 XMP_VarString & headStr,	// Everything up to the padding.
				 XMP_VarString & tailStr,	// Everything after the padding.
				 XMP_OptionBits	 options,
				 XMP_StringPtr	 newline,
				 XMP_StringPtr	 indentStr,
				 XMP_Index		 baseIndent )
{
	const size_t treeNameLen = xmpObj.tree.name.size();
	const size_t indentLen   = strlen ( indentStr );

	// First estimate the worst case space and reserve room in the output string. This optimization
	// avoids reallocating and copying the output as it grows. The initial count does not look at
	// the values of properties, so it does not account for character entities, e.g. &#xA; for newline.
	// Since there can be a lot of these in things like the base 64 encoding of a large thumbnail,
	// inflate the count by 1/4 (easy to do) to accommodate.
	
	// *** Need to include estimate for alias comments.
	
	size_t outputLen = 2 * (strlen(kPacketHeader) + strlen(kRDF_XMPMetaStart) + strlen(kRDF_RDFStart) + 3*baseIndent*indentLen);
	
	for ( size_t schemaNum = 0, schemaLim = xmpObj.tree.children.size(); schemaNum < schemaLim; ++schemaNum ) {
		const XMP_Node * currSchema = xmpObj.tree.children[schemaNum];
		outputLen += 2*(baseIndent+2)*indentLen + strlen(kRDF_SchemaStart) + treeNameLen + strlen(kRDF_SchemaEnd) + 2;
		outputLen += EstimateRDFSize ( currSchema, baseIndent+2, indentLen );
	}
	
	outputLen += (outputLen >> 2);	// Inflate by 1/4, an empirical fudge factor.
	
	// Now generate the RDF into the head string as UTF-8.
	
	XMP_Index level;
	
	headStr.erase();
	headStr.reserve ( outputLen );
	
	// Write the packet header PI.
	if ( ! (options & kXMP_OmitPacketWrapper) ) {
		for ( level = baseIndent; level > 0; --level ) headStr += indentStr;
		headStr += kPacketHeader;
		headStr += newline;
	}

	// Write the xmpmeta element's start tag.
	if ( ! (options & kXMP_OmitXMPMetaElement) ) {
		for ( level = baseIndent; level > 0; --level ) headStr += indentStr;
		headStr += kRDF_XMPMetaStart;
		headStr += kXMPCore_VersionMessage "\">";
		headStr += newline;
	}

	// Write the rdf:RDF start tag.
	for ( level = baseIndent+1; level > 0; --level ) headStr += indentStr;
	headStr += kRDF_RDFStart;
	headStr += newline;
	
	// Write all of the properties.
	if ( options & kXMP_UseCompactFormat ) {
		SerializeCompactRDFSchemas ( xmpObj.tree, headStr, newline, indentStr, baseIndent );
	} else {
		bool useCanonicalRDF = XMP_OptionIsSet ( options, kXMP_UseCanonicalFormat );
		SerializeCanonicalRDFSchemas ( xmpObj.tree, headStr, newline, indentStr, baseIndent, useCanonicalRDF );
	}

	// Write the rdf:RDF end tag.
	for ( level = baseIndent+1; level > 0; --level ) headStr += indentStr;
	headStr += kRDF_RDFEnd;
	headStr += newline;

	// Write the xmpmeta end tag.
	if ( ! (options & kXMP_OmitXMPMetaElement) ) {
		for ( level = baseIndent; level > 0; --level ) headStr += indentStr;
		headStr += kRDF_XMPMetaEnd;
		headStr += newline;
	}
	
	// Write the packet trailer PI into the tail string as UTF-8.
	tailStr.erase();
	if ( ! (options & kXMP_OmitPacketWrapper) ) {
		tailStr.reserve ( strlen(kPacketTrailer) + (strlen(indentStr) * baseIndent) );
		for ( level = baseIndent; level > 0; --level ) tailStr += indentStr;
		tailStr += kPacketTrailer;
		if ( options & kXMP_ReadOnlyPacket ) tailStr[tailStr.size()-4] = 'r';
	}
	
}	// SerializeAsRDF


// -------------------------------------------------------------------------------------------------
// SerializeToBuffer
// -----------------

void
XMPMeta::SerializeToBuffer ( XMP_VarString * rdfString,
							 XMP_OptionBits	 options,
							 XMP_StringLen	 padding,
							 XMP_StringPtr	 newline,
							 XMP_StringPtr	 indentStr,
							 XMP_Index		 baseIndent ) const
{
	XMP_Enforce( rdfString != 0 );
	XMP_Assert ( (newline != 0) && (indentStr != 0) );
	rdfString->erase();
	
	// Fix up some default parameters.
	
	enum { kDefaultPad = 2048 };
	size_t unicodeUnitSize = 1;
	XMP_OptionBits charEncoding = options & kXMP_EncodingMask;

	if ( charEncoding != kXMP_EncodeUTF8 ) {
		if ( options & _XMP_UTF16_Bit ) {
			if ( options & _XMP_UTF32_Bit ) XMP_Throw ( "Can't use both _XMP_UTF16_Bit and _XMP_UTF32_Bit", kXMPErr_BadOptions );
			unicodeUnitSize = 2;
		} else if ( options & _XMP_UTF32_Bit ) {
			unicodeUnitSize = 4;
		} else {
			XMP_Throw ( "Can't use _XMP_LittleEndian_Bit by itself", kXMPErr_BadOptions );
		}
	}
	
	if ( options & kXMP_OmitAllFormatting ) {
		newline = " ";	// ! Yes, a space for "newline". This ensures token separation.
		indentStr = "";
	} else {
		if ( *newline == 0 ) newline = "\xA";	// Linefeed
		if ( *indentStr == 0 ) {
			indentStr = " ";
			if ( ! (options & kXMP_UseCompactFormat) ) indentStr  = "   ";
		}
	}
	
	if ( options & kXMP_ExactPacketLength ) {
		if ( options & (kXMP_OmitPacketWrapper | kXMP_IncludeThumbnailPad) ) {
			XMP_Throw ( "Inconsistent options for exact size serialize", kXMPErr_BadOptions );
		}
		if ( (padding & (unicodeUnitSize-1)) != 0 ) {
			XMP_Throw ( "Exact size must be a multiple of the Unicode element", kXMPErr_BadOptions );
		}
	} else if ( options & kXMP_ReadOnlyPacket ) {
		if ( options & (kXMP_OmitPacketWrapper | kXMP_IncludeThumbnailPad) ) {
			XMP_Throw ( "Inconsistent options for read-only packet", kXMPErr_BadOptions );
		}
		padding = 0;
	} else if ( options & kXMP_OmitPacketWrapper ) {
		if ( options & kXMP_IncludeThumbnailPad ) {
			XMP_Throw ( "Inconsistent options for non-packet serialize", kXMPErr_BadOptions );
		}
		padding = 0;
	} else {
		if ( padding == 0 ) {
			padding = kDefaultPad * unicodeUnitSize;
		} else if ( (padding >> 28) != 0 ) {
			XMP_Throw ( "Outrageously large padding size", kXMPErr_BadOptions );	// Bigger than 256 MB.
		}
		if ( options & kXMP_IncludeThumbnailPad ) {
			if ( ! this->DoesPropertyExist ( kXMP_NS_XMP, "Thumbnails" ) ) padding += (10000 * unicodeUnitSize);	// *** Need a better estimate.
		}
	}

	// Serialize as UTF-8, then convert to UTF-16 or UTF-32 if necessary, and assemble with the padding and tail.
	
	std::string tailStr;

	SerializeAsRDF ( *this, *rdfString, tailStr, options, newline, indentStr, baseIndent );

	if ( charEncoding == kXMP_EncodeUTF8 ) {

		if ( options & kXMP_ExactPacketLength ) {
			size_t minSize = rdfString->size() + tailStr.size();
			if ( minSize > padding ) XMP_Throw ( "Can't fit into specified packet size", kXMPErr_BadSerialize );
			padding -= minSize;	// Now the actual amount of padding to add.
		}
		
		size_t newlineLen = strlen ( newline );
	
		if ( padding < newlineLen ) {
			rdfString->append ( padding, ' ' );
		} else {
			padding -= newlineLen;	// Write this newline last.
			while ( padding >= (100 + newlineLen) ) {
				rdfString->append ( 100, ' ' );
				*rdfString += newline;
				padding -= (100 + newlineLen);
			}
			rdfString->append ( padding, ' ' );
			*rdfString += newline;
		}

		*rdfString += tailStr;
	
	} else {
	
		// Need to convert the encoding. Swap the UTF-8 into a local string and convert back. Assemble everything.
		
		XMP_VarString utf8Str, newlineStr;
		bool bigEndian = ((charEncoding & _XMP_LittleEndian_Bit) == 0);
		
		if ( charEncoding & _XMP_UTF16_Bit ) {

			std::string padStr ( "  " );  padStr[0] = 0;	// Assume big endian.
			
			utf8Str.swap ( *rdfString );
			ToUTF16 ( (UTF8Unit*)utf8Str.c_str(), utf8Str.size(), rdfString, bigEndian );
			utf8Str.swap ( tailStr );
			ToUTF16 ( (UTF8Unit*)utf8Str.c_str(), utf8Str.size(), &tailStr, bigEndian );

			if ( options & kXMP_ExactPacketLength ) {
				size_t minSize = rdfString->size() + tailStr.size();
				if ( minSize > padding ) XMP_Throw ( "Can't fit into specified packet size", kXMPErr_BadSerialize );
				padding -= minSize;	// Now the actual amount of padding to add (in bytes).
			}

			utf8Str.assign ( newline );
			ToUTF16 ( (UTF8Unit*)utf8Str.c_str(), utf8Str.size(), &newlineStr, bigEndian );
			size_t newlineLen = newlineStr.size();
	
			if ( padding < newlineLen ) {
				for ( int i = padding/2; i > 0; --i ) *rdfString += padStr;
			} else {
				padding -= newlineLen;	// Write this newline last.
				while ( padding >= (200 + newlineLen) ) {
					for ( int i = 100; i > 0; --i ) *rdfString += padStr;
					*rdfString += newlineStr;
					padding -= (200 + newlineLen);
				}
				for ( int i = padding/2; i > 0; --i ) *rdfString += padStr;
				*rdfString += newlineStr;
			}

			*rdfString += tailStr;

		} else {

			std::string padStr ( "    " );  padStr[0] = padStr[1] = padStr[2] = 0;	// Assume big endian.
			UTF8_to_UTF32_Proc Converter = UTF8_to_UTF32BE;

			if ( charEncoding & _XMP_LittleEndian_Bit ) {
				padStr[0] = ' '; padStr[1] = padStr[2] = padStr[3] = 0;
				Converter = UTF8_to_UTF32LE;
			}
			
			utf8Str.swap ( *rdfString );
			ToUTF32 ( (UTF8Unit*)utf8Str.c_str(), utf8Str.size(), rdfString, bigEndian );
			utf8Str.swap ( tailStr );
			ToUTF32 ( (UTF8Unit*)utf8Str.c_str(), utf8Str.size(), &tailStr, bigEndian );

			if ( options & kXMP_ExactPacketLength ) {
				size_t minSize = rdfString->size() + tailStr.size();
				if ( minSize > padding ) XMP_Throw ( "Can't fit into specified packet size", kXMPErr_BadSerialize );
				padding -= minSize;	// Now the actual amount of padding to add (in bytes).
			}

			utf8Str.assign ( newline );
			ToUTF32 ( (UTF8Unit*)utf8Str.c_str(), utf8Str.size(), &newlineStr, bigEndian );
			size_t newlineLen = newlineStr.size();
	
			if ( padding < newlineLen ) {
				for ( int i = padding/4; i > 0; --i ) *rdfString += padStr;
			} else {
				padding -= newlineLen;	// Write this newline last.
				while ( padding >= (400 + newlineLen) ) {
					for ( int i = 100; i > 0; --i ) *rdfString += padStr;
					*rdfString += newlineStr;
					padding -= (400 + newlineLen);
				}
				for ( int i = padding/4; i > 0; --i ) *rdfString += padStr;
				*rdfString += newlineStr;
			}

			*rdfString += tailStr;

		}
	
	}

}	// SerializeToBuffer

// =================================================================================================