summaryrefslogtreecommitdiff
path: root/XMPFiles/source/FileHandlers/SWF_Handler.cpp
blob: a0554ce5ca4e9ebff38438706c3347ddc561cb3d (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
// =================================================================================================
// ADOBE SYSTEMS INCORPORATED
// Copyright 2006 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.
// =================================================================================================

#include "public/include/XMP_Environment.h"	// ! XMP_Environment.h must be the first included header.

#include "public/include/XMP_Const.h"
#include "public/include/XMP_IO.hpp"

#include "XMPFiles/source/XMPFiles_Impl.hpp"
#include "source/XMPFiles_IO.hpp"
#include "source/XIO.hpp"

#include "XMPFiles/source/FileHandlers/SWF_Handler.hpp"
#include "XMPFiles/source/FormatSupport/SWF_Support.hpp"

using namespace std;

// =================================================================================================
/// \file SWF_Handler.hpp
/// \brief File format handler for SWF.
///
/// This handler ...
///
// =================================================================================================

// =================================================================================================
// SWF_MetaHandlerCTor
// ===================

XMPFileHandler * SWF_MetaHandlerCTor ( XMPFiles * parent )
{
	return new SWF_MetaHandler ( parent );

}	// SWF_MetaHandlerCTor

// =================================================================================================
// SWF_CheckFormat
// ===============

bool SWF_CheckFormat ( XMP_FileFormat format,
					   XMP_StringPtr  filePath,
                       XMP_IO *       fileRef,
                       XMPFiles *     parent )
{
	IgnoreParam(format); IgnoreParam(fileRef); IgnoreParam(parent);
	XMP_Assert ( format == kXMP_SWFFile );
	
	// Make sure the file is long enough for an empty SWF stream. Check the signature.

	if ( fileRef->Length() < SWF_IO::HeaderPrefixSize ) return false;

	fileRef->Rewind();
	XMP_Uns8 buffer [4];
	fileRef->ReadAll ( buffer, 4 );
	XMP_Uns32 signature = GetUns32LE ( &buffer[0] ) & 0xFFFFFF;	// Discard the version byte.
	
	return ( (signature == SWF_IO::CompressedSignature) || (signature == SWF_IO::ExpandedSignature) );

}	// SWF_CheckFormat

// =================================================================================================
// SWF_MetaHandler::SWF_MetaHandler
// ================================

SWF_MetaHandler::SWF_MetaHandler ( XMPFiles * _parent )
	: isCompressed(false), hasFileAttributes(false), hasMetadata(false), brokenSWF(false), expandedSize(0), firstTagOffset(0)
{
	this->parent = _parent;
	this->handlerFlags = kSWF_HandlerFlags;
	this->stdCharForm  = kXMP_Char8Bit;

}

// =================================================================================================
// SWF_MetaHandler::~SWF_MetaHandler
// =================================

SWF_MetaHandler::~SWF_MetaHandler()
{
	// Nothing to do at this time.
}

// =================================================================================================
// SWF_MetaHandler::CacheFileData
// ==============================
//
// SWF files are pretty small, have simple metadata, and often have ZIP compression. Because they
// are small and often compressed, we always cache the fully expanded SWF in memory. That is used
// for both reading and updating. Note that SWF_CheckFormat has already done basic checks on the
// size and signature, they don't need to be repeated here.
//
// Try to find the FileAttributes and Metadata tags, saving their offsets for later use if updating
// the file. We need to be tolerant when reading, allowing the FileAttributes tag to be anywhere and
// allowing Metadata without FileAttributes or with the HasMetadata flag clear. The SWF spec is not
// clear enough about the rules for SWF 7 and earlier, there are 3rd party tools that don't put
// FileAttributes first.

void SWF_MetaHandler::CacheFileData() {

	XMP_Assert ( (! this->processedXMP) && (! this->containsXMP) );
	XMP_Assert ( this->expandedSWF.empty() );

	XMP_IO * fileRef = this->parent->ioRef;
	XMP_Int64 fileLength = fileRef->Length();
	XMP_Enforce ( fileLength <= SWF_IO::MaxExpandedSize );

	// Get the uncompressed SWF stream into memory.
	
	fileRef->Rewind();
	XMP_Uns8 buffer [SWF_IO::HeaderPrefixSize];	// Read the uncompressed file header prefix.
	fileRef->ReadAll ( buffer, SWF_IO::HeaderPrefixSize );

	XMP_Uns32 signature = GetUns32LE ( &buffer[0] ) & 0xFFFFFF;	// Discard the version byte.
	this->expandedSize = GetUns32LE ( &buffer[4] );
	if ( signature == SWF_IO::CompressedSignature ) this->isCompressed = true;
	
	if ( this->isCompressed ) {
	
		// Expand the SWF file into memory.
		this->expandedSWF.reserve ( this->expandedSize );	// Try to avoid reallocations.
		SWF_IO::DecompressFileToMemory ( fileRef, &this->expandedSWF );
		this->expandedSize = this->expandedSWF.size();	// Use the true length.
	
	} else {
	
		// Read the entire uncompressed file into memory.
		this->expandedSize = (XMP_Uns32)fileLength;	// Use the true length.
		this->expandedSWF.insert ( this->expandedSWF.end(), (size_t)fileLength, 0 );
		fileRef->Rewind();
		fileRef->ReadAll ( &this->expandedSWF[0], (XMP_Uns32)fileLength );
	
	}
	
	// Look for the FileAttributes and Metadata tags.
	
	this->firstTagOffset = SWF_IO::FileHeaderSize ( this->expandedSWF[SWF_IO::HeaderPrefixSize] );
	
	XMP_Uns32 currOffset = this->firstTagOffset;
	SWF_IO::TagInfo currTag;
	
	for ( ; currOffset < this->expandedSize; currOffset = SWF_IO::NextTagOffset(currTag) ) {
	
		bool ok = SWF_IO::GetTagInfo ( this->expandedSWF, currOffset, &currTag );
		if ( ! ok ) {
			this->brokenSWF = true;	// Let the read finish, but refuse to update.
			break;
		}
		
		if ( currTag.tagID == SWF_IO::FileAttributesTagID ) {
			this->fileAttributesTag = currTag;
			this->hasFileAttributes = true;
			if ( this->hasMetadata ) break;	// Exit if we have both.
		}
		
		if ( currTag.tagID == SWF_IO::MetadataTagID ) {
			this->metadataTag = currTag;
			this->hasMetadata = true;
			if ( this->hasFileAttributes ) break;	// Exit if we have both.
		}
		
	}
	
	if ( this->hasMetadata ) {
		this->packetInfo.offset = SWF_IO::ContentOffset ( this->metadataTag );
		this->packetInfo.length = this->metadataTag.contentLength;
		this->xmpPacket.assign ( (char*)&this->expandedSWF[(size_t)this->packetInfo.offset], (size_t)this->packetInfo.length );
		FillPacketInfo ( this->xmpPacket, &this->packetInfo );
		this->containsXMP = true;
	}
	
}	// SWF_MetaHandler::CacheFileData

// =================================================================================================
// SWF_MetaHandler::ProcessXMP
// ===========================

void SWF_MetaHandler::ProcessXMP()
{

	this->processedXMP = true;	// Make sure we only come through here once.

	if ( ! this->xmpPacket.empty() ) {
		XMP_Assert ( this->containsXMP );
		XMP_StringPtr packetStr = this->xmpPacket.c_str();
		XMP_StringLen packetLen = (XMP_StringLen)this->xmpPacket.size();
		this->xmpObj.ParseFromBuffer ( packetStr, packetLen );
	}

}	// SWF_MetaHandler::ProcessXMP

// =================================================================================================
// XMPFileHandler::GetSerializeOptions
// ===================================
//
// Override default implementation to ensure omitting XMP wrapper.

XMP_OptionBits SWF_MetaHandler::GetSerializeOptions()
{

	return (kXMP_OmitPacketWrapper | kXMP_OmitAllFormatting | kXMP_OmitXMPMetaElement);

} // XMPFileHandler::GetSerializeOptions

// =================================================================================================
// SWF_MetaHandler::UpdateFile
// ===========================
//
// Update the expanded SWF in memory, then write it to the file.

void SWF_MetaHandler::UpdateFile ( bool doSafeUpdate )
{

	if ( doSafeUpdate ) XMP_Throw ( "SWF_MetaHandler::UpdateFile: Safe update not supported", kXMPErr_Unavailable );

	if ( ! this->needsUpdate ) return;
	this->needsUpdate = false; // Don't come through here twice, even if there are errors.
	
	if ( this->brokenSWF ) {
		XMP_Throw ( "SWF is broken, can't update.", kXMPErr_BadFileFormat );
	}
	
	// Make sure there is a FileAttributes tag at the front, with the HasMetadata flag set.
	
	if ( ! this->hasFileAttributes ) {
	
		// Insert a new FileAttributes tag as the first tag.
		
		XMP_Uns8 buffer [6];	// Two byte header plus four byte content.
		PutUns16LE ( ((SWF_IO::FileAttributesTagID << 6) | 4), &buffer[0] );
		PutUns32LE ( SWF_IO::HasMetadataMask, &buffer[2] );
		
		this->expandedSWF.insert ( (this->expandedSWF.begin() + this->firstTagOffset), 6, 0 );
		memcpy ( &this->expandedSWF[this->firstTagOffset], &buffer[0], 6 );

		this->hasFileAttributes = true;
		bool ok = SWF_IO::GetTagInfo ( this->expandedSWF, this->firstTagOffset, &this->fileAttributesTag );
		XMP_Assert ( ok );
		
		if ( this->hasMetadata ) this->metadataTag.tagOffset += 6;	// The Metadata tag is now further back.

	} else {
		
		// Make sure the HasMetadata flag is set.
		if ( this->fileAttributesTag.contentLength > 0 ) {
			XMP_Uns32 flagsOffset = SWF_IO::ContentOffset ( this->fileAttributesTag );
			this->expandedSWF[flagsOffset] |= SWF_IO::HasMetadataMask;
		}

		// Make sure the FileAttributes tag is the first tag.
		if ( this->fileAttributesTag.tagOffset != this->firstTagOffset ) {

			RawDataBlock attrTag;
			XMP_Uns32 attrTagLength = SWF_IO::FullTagLength ( this->fileAttributesTag );
			attrTag.assign ( attrTagLength, 0 );
			memcpy ( &attrTag[0], &this->expandedSWF[this->fileAttributesTag.tagOffset], attrTagLength );
			
			RawDataBlock::iterator attrTagPos = this->expandedSWF.begin() + this->fileAttributesTag.tagOffset;
			RawDataBlock::iterator attrTagEnd = attrTagPos + attrTagLength;
			this->expandedSWF.erase ( attrTagPos, attrTagEnd );	// Remove the old FileAttributes tag;
			
			if ( this->hasMetadata && (this->metadataTag.tagOffset < this->fileAttributesTag.tagOffset) ) {
				this->metadataTag.tagOffset += attrTagLength;	// The FileAttributes tag will become in front.
			}
			
			this->expandedSWF.insert ( (this->expandedSWF.begin() + this->firstTagOffset), attrTagLength, 0 );
			memcpy ( &this->expandedSWF[this->firstTagOffset], &attrTag[0], attrTagLength );
			
			this->fileAttributesTag.tagOffset = this->firstTagOffset;

		}

	}
	
	// Make sure the XMP is as small as possible. Write the XMP as the second tag.
	
	XMP_Assert ( this->hasFileAttributes );
	
	XMP_OptionBits smallOptions = kXMP_OmitPacketWrapper | kXMP_UseCompactFormat | kXMP_OmitAllFormatting | kXMP_OmitXMPMetaElement;
	this->xmpObj.SerializeToBuffer ( &this->xmpPacket, smallOptions );
	
	if ( this->hasMetadata ) {
		// Remove the old XMP, the size and location have probably changed.
		XMP_Uns32 oldMetaLength = SWF_IO::FullTagLength ( this->metadataTag );
		RawDataBlock::iterator oldMetaPos = this->expandedSWF.begin() + this->metadataTag.tagOffset;
		RawDataBlock::iterator oldMetaEnd = oldMetaPos + oldMetaLength;
		this->expandedSWF.erase ( oldMetaPos, oldMetaEnd );
	}
	
	this->metadataTag.hasLongHeader = true;
	this->metadataTag.tagID = SWF_IO::MetadataTagID;
	this->metadataTag.tagOffset = SWF_IO::NextTagOffset ( this->fileAttributesTag );
	this->metadataTag.contentLength = this->xmpPacket.size();

	XMP_Uns32 newMetaLength = 6 + this->metadataTag.contentLength;	// Always use a long tag header.
	this->expandedSWF.insert ( (this->expandedSWF.begin() + this->metadataTag.tagOffset), newMetaLength, 0 );

	PutUns16LE ( ((SWF_IO::MetadataTagID << 6) | SWF_IO::TagLengthMask), &this->expandedSWF[this->metadataTag.tagOffset] );
	PutUns32LE ( this->metadataTag.contentLength, &this->expandedSWF[this->metadataTag.tagOffset+2] );
	memcpy ( &this->expandedSWF[this->metadataTag.tagOffset+6], this->xmpPacket.c_str(), this->metadataTag.contentLength );

	this->hasMetadata = true;
	
	// Rewrite the file.
	
	XMP_IO * fileRef = this->parent->ioRef;
	fileRef->Rewind();
	fileRef->Truncate ( 0 );
	fileRef->Write ( &this->expandedSWF[0], this->expandedSWF.size() );

}	// SWF_MetaHandler::UpdateFile

// =================================================================================================
// SWF_MetaHandler::WriteTempFile
// ==============================

// ! See important notes in SWF_Handler.hpp about file handling.

void SWF_MetaHandler::WriteTempFile ( XMP_IO* tempRef )
{

	// ! WriteTempFile is not supposed to be called for SWF.
	XMP_Throw ( "SWF_MetaHandler::WriteTempFile should not be called", kXMPErr_InternalFailure );

}	// SWF_MetaHandler::WriteTempFile