Formats update.

(HG3): attempt to recognize swapped Red/Blue channels.
Fairytale BDT archives.
(XP3, VF): add 'exe' to extensions list.
(DXR): consolidated Macromedia Director archives.
(SND): support mp3 streams.
(QPK): PSP resource archive.
(GRC): support encrypted images.
This commit is contained in:
morkt
2023-09-14 19:17:31 +04:00
parent b73bd0fb4d
commit bfd81f9ec4
23 changed files with 1081 additions and 426 deletions

View File

@@ -198,10 +198,10 @@ namespace GameRes.Formats.Macromedia
if (t >= 0)
{
string ext = new string (type_buf, 0, t+1);
return string.Format ("{0:X8}.{1}", id, ext.ToLowerInvariant());
return string.Format ("{0:D8}.{1}", id, ext.ToLowerInvariant());
}
else
return id.ToString ("X8");
return id.ToString ("D8");
}
byte[] ZlibUnpack (long offset, uint size, out int actual_size, int unpacked_size_hint = 0)

View File

@@ -23,13 +23,13 @@
// IN THE SOFTWARE.
//
using GameRes.Compression;
using GameRes.Utility;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Media;
using System.Windows.Media.Imaging;
@@ -46,12 +46,12 @@ namespace GameRes.Formats.Macromedia
public DxrOpener ()
{
Extensions = new[] { "dxr", "cxt" };
Extensions = new[] { "dxr", "cxt", "cct", "dcr" };
Signatures = new[] { 0x52494658u, 0x58464952u };
}
internal static readonly HashSet<string> RawChunks = new HashSet<string> {
"RTE0", "RTE1", "FXmp", "VWFI", "VWSC", "Lscr", "STXT", "XMED", "snd "
"RTE0", "RTE1", "FXmp", "VWFI", "VWSC", "Lscr", "STXT", "XMED", //"snd "
};
internal bool ConvertText = true;
@@ -71,9 +71,9 @@ namespace GameRes.Formats.Macromedia
var dir = new List<Entry> ();
ImportMedia (dir_file, dir);
foreach (MemoryMapEntry entry in dir_file.MMap.Dir)
foreach (DirectorEntry entry in dir_file.Directory)
{
if (entry.Size != 0 && RawChunks.Contains (entry.FourCC))
if (entry.Size != 0 && entry.Offset != -1 && RawChunks.Contains (entry.FourCC))
{
entry.Name = string.Format ("{0:D6}.{1}", entry.Id, entry.FourCC.Trim());
if ("snd " == entry.FourCC)
@@ -90,19 +90,30 @@ namespace GameRes.Formats.Macromedia
var snd = entry as SoundEntry;
if (snd != null)
return OpenSound (arc, snd);
var ment = entry as MemoryMapEntry;
if (!ConvertText || null == ment || ment.FourCC != "STXT")
var pent = entry as PackedEntry;
if (null == pent)
return base.OpenEntry (arc, entry);
uint offset = Binary.BigEndian (arc.File.View.ReadUInt32 (entry.Offset));
uint length = Binary.BigEndian (arc.File.View.ReadUInt32 (entry.Offset + 4));
return arc.File.CreateStream (entry.Offset + offset, length);
var input = OpenChunkStream (arc.File, pent);
var ment = entry as DirectorEntry;
if (null == ment || !ConvertText || ment.FourCC != "STXT")
return input.AsStream;
using (input)
{
uint offset = Binary.BigEndian (input.ReadUInt32());
uint length = Binary.BigEndian (input.ReadUInt32());
input.Position = offset;
var text = input.ReadBytes ((int)length);
return new BinMemoryStream (text, entry.Name);
}
}
internal Stream OpenSound (ArcFile arc, SoundEntry entry)
{
if (null == entry.Header)
return base.OpenEntry (arc, entry);
var header = arc.File.View.ReadBytes (entry.Header.Offset, entry.Header.Size);
var header = new byte[entry.Header.UnpackedSize];
using (var input = OpenChunkStream (arc.File, entry.Header))
input.Read (header, 0, header.Length);
var format = entry.DeserializeHeader (header);
var riff = new MemoryStream (0x2C);
WaveAudio.WriteRiffHeader (riff, format, entry.Size);
@@ -110,12 +121,14 @@ namespace GameRes.Formats.Macromedia
{
using (riff)
{
var input = arc.File.CreateStream (entry.Offset, entry.Size);
var input = OpenChunkStream (arc.File, entry).AsStream;
return new PrefixStream (riff.ToArray(), input);
}
}
// samples are stored in big-endian format
var samples = arc.File.View.ReadBytes (entry.Offset, entry.Size);
var samples = new byte[entry.UnpackedSize];
using (var input = OpenChunkStream (arc.File, entry))
input.Read (samples, 0, samples.Length);
for (int i = 1; i < samples.Length; i += 2)
{
byte s = samples[i-1];
@@ -130,7 +143,6 @@ namespace GameRes.Formats.Macromedia
void ImportMedia (DirectorFile dir_file, List<Entry> dir)
{
var seen_ids = new HashSet<int>();
var mmap = dir_file.MMap;
foreach (var cast in dir_file.Casts)
{
foreach (var piece in cast.Members.Values)
@@ -157,17 +169,35 @@ namespace GameRes.Formats.Macromedia
{
if ("ediM" == elem.FourCC)
{
var ediM = dir_file.MMap[elem.Id];
if (string.IsNullOrEmpty (name))
name = ediM.Id.ToString ("D6");
return new Entry
var ediM = dir_file.Index[elem.Id];
name = SanitizeName(name, ediM.Id);
return new PackedEntry
{
Name = name + ".mp3",
Type = "audio",
Offset = ediM.Offset,
Size = ediM.Size,
Name = name + ".ediM",
Type = "audio",
Offset = ediM.Offset,
Size = ediM.Size,
UnpackedSize = ediM.UnpackedSize,
IsPacked = ediM.IsPacked
};
}
else if ("snd " == elem.FourCC)
{
var snd = dir_file.Index[elem.Id];
if (snd.Size != 0)
{
name = SanitizeName (name, snd.Id);
return new PackedEntry
{
Name = name + ".snd",
Type = "audio",
Offset = snd.Offset,
Size = snd.Size,
UnpackedSize = snd.Size,
IsPacked = false,
};
}
}
if (null == sndHrec && "sndH" == elem.FourCC)
sndHrec = elem;
else if (null == sndSrec && "sndS" == elem.FourCC)
@@ -175,65 +205,99 @@ namespace GameRes.Formats.Macromedia
}
if (sndHrec == null || sndSrec == null)
return null;
var sndH = dir_file.MMap[sndHrec.Id];
var sndS = dir_file.MMap[sndSrec.Id];
if (string.IsNullOrEmpty (name))
name = sndSrec.Id.ToString ("D6");
var sndH = dir_file.Index[sndHrec.Id];
var sndS = dir_file.Index[sndSrec.Id];
name = SanitizeName (name, sndSrec.Id);
return new SoundEntry
{
Name = name + ".snd",
Type = "audio",
Offset = sndS.Offset,
Size = sndS.Size,
UnpackedSize = sndS.UnpackedSize,
IsPacked = sndS.IsPacked,
Header = sndH,
};
}
Entry ImportBitmap (CastMember bitmap, DirectorFile dir_file, Cast cast)
{
// var bitd = dir_file.KeyTable.FindByCast (bitmap.Id, "BITD");
KeyTableEntry bitd = null, alfa = null;
KeyTableEntry bitd = null, edim = null, alfa = null;
foreach (var elem in dir_file.KeyTable.Table.Where (e => e.CastId == bitmap.Id))
{
if (null == bitd && "BITD" == elem.FourCC)
bitd = elem;
else if (null == edim && "ediM" == elem.FourCC)
edim = elem;
else if (null == alfa && "ALFA" == elem.FourCC)
alfa = elem;
}
if (bitd == null)
if (bitd == null && edim == null)
return null;
var entry = new BitmapEntry();
entry.DeserializeHeader (bitmap.SpecificData);
var name = bitmap.Info.Name;
if (string.IsNullOrEmpty (name))
name = bitd.Id.ToString ("D6");
var chunk = dir_file.MMap[bitd.Id];
entry.Name = name + ".BITD";
entry.Type = "image";
entry.Offset = chunk.Offset;
entry.Size = chunk.Size;
if (entry.Palette > 0)
if (bitd != null)
{
var cast_id = cast.Index[entry.Palette-1];
var clut = dir_file.KeyTable.FindByCast (cast_id, "CLUT");
if (clut != null)
entry.PaletteRef = dir_file.MMap[clut.Id];
entry.DeserializeHeader (bitmap.SpecificData);
var name = SanitizeName (bitmap.Info.Name, bitd.Id);
var chunk = dir_file.Index[bitd.Id];
entry.Name = name + ".BITD";
entry.Type = "image";
entry.Offset = chunk.Offset;
entry.Size = chunk.Size;
entry.IsPacked = chunk.IsPacked;
entry.UnpackedSize = chunk.UnpackedSize;
if (entry.Palette > 0)
{
var cast_id = cast.Index[entry.Palette-1];
var clut = dir_file.KeyTable.FindByCast (cast_id, "CLUT");
if (clut != null)
entry.PaletteRef = dir_file.Index[clut.Id];
}
}
else // if (edim != null)
{
var name = SanitizeName (bitmap.Info.Name, edim.Id);
var chunk = dir_file.Index[edim.Id];
entry.Name = name + ".jpg";
entry.Type = "image";
entry.Offset = chunk.Offset;
entry.Size = chunk.Size;
entry.IsPacked = false;
entry.UnpackedSize = entry.Size;
}
if (alfa != null)
entry.AlphaRef = dir_file.MMap[alfa.Id];
entry.AlphaRef = dir_file.Index[alfa.Id];
return entry;
}
static readonly Regex ForbiddenCharsRe = new Regex (@"[:?*<>/\\]");
string SanitizeName (string name, int id)
{
name = name?.Trim();
if (string.IsNullOrEmpty (name))
name = id.ToString ("D6");
else
name = ForbiddenCharsRe.Replace (name, "_");
return name;
}
public override IImageDecoder OpenImage (ArcFile arc, Entry entry)
{
var bent = entry as BitmapEntry;
if (null == bent)
return base.OpenImage (arc, entry);
return base.OpenImage(arc, entry);
if (entry.Name.HasExtension (".jpg"))
return OpenJpeg (arc, bent);
BitmapPalette palette = null;
if (bent.PaletteRef != null)
{
var pal_bytes = arc.File.View.ReadBytes (bent.PaletteRef.Offset, bent.PaletteRef.Size);
palette = ReadPalette (pal_bytes);
using (var pal = OpenChunkStream (arc.File, bent.PaletteRef))
{
var pal_bytes = pal.ReadBytes ((int)bent.PaletteRef.UnpackedSize);
palette = ReadPalette (pal_bytes);
}
}
else if (bent.BitDepth <= 8)
{
@@ -247,27 +311,53 @@ namespace GameRes.Formats.Macromedia
case -101: palette = Palettes.SystemWindows; break;
}
}
var info = new ImageMetaData {
var info = new BitdMetaData {
Width = (uint)(bent.Right - bent.Left),
Height = (uint)(bent.Bottom - bent.Top),
BPP = bent.BitDepth
BPP = bent.BitDepth,
DepthType = bent.DepthType,
};
byte[] alpha_channel = null;
if (bent.AlphaRef != null)
{
using (var alpha = arc.File.CreateStream (bent.AlphaRef.Offset, bent.AlphaRef.Size))
{
var alpha_info = new ImageMetaData {
Width = info.Width,
Height = info.Height,
BPP = 8,
};
var decoder = new BitdDecoder (alpha, alpha_info, null);
alpha_channel = decoder.Unpack8bpp();
}
}
alpha_channel = ReadAlphaChannel (arc.File, bent.AlphaRef, info);
var input = OpenChunkStream (arc.File, bent).AsStream;
return new BitdDecoder (input, info, palette) { AlphaChannel = alpha_channel };
}
IImageDecoder OpenJpeg (ArcFile arc, BitmapEntry entry)
{
if (null == entry.AlphaRef)
return base.OpenImage (arc, entry);
// jpeg with alpha-channel
var input = arc.File.CreateStream (entry.Offset, entry.Size);
return new BitdDecoder (input.AsStream, info, palette) { AlphaChannel = alpha_channel };
try
{
var info = ImageFormat.Jpeg.ReadMetaData (input);
if (null == info)
throw new InvalidFormatException ("Invalid 'ediM' chunk.");
var alpha_channel = ReadAlphaChannel (arc.File, entry.AlphaRef, info);
return BitdDecoder.FromJpeg (input, info, alpha_channel);
}
catch
{
input.Dispose();
throw;
}
}
byte[] ReadAlphaChannel (ArcView file, DirectorEntry entry, ImageMetaData info)
{
using (var alpha = OpenChunkStream (file, entry))
{
var alpha_info = new BitdMetaData {
Width = info.Width,
Height = info.Height,
BPP = 8,
DepthType = 0x80,
};
var decoder = new BitdDecoder (alpha.AsStream, alpha_info, null);
return decoder.Unpack8bpp();
}
}
BitmapPalette ReadPalette (byte[] data)
@@ -280,9 +370,20 @@ namespace GameRes.Formats.Macromedia
}
return new BitmapPalette (colors);
}
IBinaryStream OpenChunkStream (ArcView file, PackedEntry entry)
{
var input = file.CreateStream (entry.Offset, entry.Size);
if (!entry.IsPacked)
return input;
var data = new byte[entry.UnpackedSize];
using (var zstream = new ZLibStream (input, CompressionMode.Decompress))
zstream.Read (data, 0, data.Length);
return new BinMemoryStream (data, entry.Name);
}
}
internal class BitmapEntry : Entry
internal class BitmapEntry : PackedEntry
{
public byte Flags;
public byte DepthType;
@@ -292,8 +393,8 @@ namespace GameRes.Formats.Macromedia
public int Right;
public int BitDepth;
public int Palette;
public Entry PaletteRef;
public Entry AlphaRef;
public DirectorEntry PaletteRef;
public DirectorEntry AlphaRef;
public void DeserializeHeader (byte[] data)
{
@@ -314,9 +415,9 @@ namespace GameRes.Formats.Macromedia
}
}
internal class SoundEntry : Entry
internal class SoundEntry : PackedEntry
{
public Entry Header;
public DirectorEntry Header;
public WaveFormat DeserializeHeader (byte[] header)
{

View File

@@ -31,10 +31,12 @@ namespace GameRes.Formats.Macromedia
[Export(typeof(AudioFormat))]
public class SndAudio : AudioFormat
{
public override string Tag { get => "SND"; }
public override string Description { get => "Macromedia Director audio resource"; }
public override uint Signature { get => 0; }
public override bool CanWrite { get => false; }
public override string Tag => "SND";
public override string Description => "Macromedia Director audio resource";
public override uint Signature => 0;
public override bool CanWrite => false;
static readonly ResourceInstance<AudioFormat> Mp3 = new ResourceInstance<AudioFormat> ("MP3");
public override SoundInput TryOpen (IBinaryStream file)
{
@@ -83,6 +85,13 @@ namespace GameRes.Formats.Macromedia
if (bps != 16 && bps != 8)
return null;
// try mp3
var samples_stream = new StreamRegion (reader.Source, reader.Position);
var mp3_input = new BinaryStream (samples_stream, file.Name);
var mp3 = Mp3.Value.TryOpen (mp3_input);
if (mp3 != null)
return mp3;
var format = new WaveFormat {
FormatTag = 1,
Channels = channels,
@@ -93,8 +102,7 @@ namespace GameRes.Formats.Macromedia
format.SetBPS();
if (8 == bps)
{
var data = new StreamRegion (file.AsStream, file.Position);
return new RawPcmInput (data, format);
return new RawPcmInput (samples_stream, format);
}
int sample_count = frames_count * channels;
var samples = file.ReadBytes (sample_count);

View File

@@ -23,9 +23,11 @@
// IN THE SOFTWARE.
//
using GameRes.Compression;
using GameRes.Utility;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
@@ -66,24 +68,53 @@ namespace GameRes.Formats.Macromedia
internal class DirectorFile
{
List<DirectorEntry> m_dir;
Dictionary<int, DirectorEntry> m_index = new Dictionary<int, DirectorEntry>();
MemoryMap m_mmap = new MemoryMap();
KeyTable m_keyTable = new KeyTable();
DirectorConfig m_config = new DirectorConfig();
List<Cast> m_casts = new List<Cast>();
Dictionary<int, byte[]> m_ilsMap = new Dictionary<int, byte[]>();
public MemoryMap MMap => m_mmap;
public bool IsAfterBurned { get; private set; }
public MemoryMap MMap => m_mmap;
public KeyTable KeyTable => m_keyTable;
public DirectorConfig Config => m_config;
public List<Cast> Casts => m_casts;
public List<Cast> Casts => m_casts;
public List<DirectorEntry> Directory => m_dir;
public Dictionary<int, DirectorEntry> Index => m_index;
public DirectorEntry Find (string four_cc) => Directory.Find (e => e.FourCC == four_cc);
public DirectorEntry FindById (int id)
{
DirectorEntry entry;
m_index.TryGetValue (id, out entry);
return entry;
}
public bool Deserialize (SerializationContext context, Reader reader)
{
reader.Position = 8;
string codec = reader.ReadFourCC();
if (codec != "MV93" && codec != "MC95")
if (codec == "MV93" || codec == "MC95")
{
if (!ReadMMap (context, reader))
return false;
}
else if (codec == "FGDC" || codec == "FGDM")
{
IsAfterBurned = true;
if (!ReadAfterBurner (context, reader))
return false;
}
else
{
Trace.WriteLine (string.Format ("Unknown codec '{0}'", codec), "DXR");
return false;
return ReadMMap (context, reader)
&& ReadKeyTable (context, reader)
}
return ReadKeyTable (context, reader)
&& ReadConfig (context, reader)
&& ReadCasts (context, reader);
}
@@ -99,25 +130,129 @@ namespace GameRes.Formats.Macromedia
return false;
reader.Position = mmap_pos + 8;
MMap.Deserialize (context, reader);
m_dir = MMap.Dir;
for (int i = 0; i < m_dir.Count; ++i)
{
m_index[i] = m_dir[i];
}
return true;
}
bool ReadAfterBurner (SerializationContext context, Reader reader)
{
if (reader.ReadFourCC() != "Fver")
return false;
int length = reader.ReadVarInt();
long next_pos = reader.Position + length;
int version = reader.ReadVarInt();
if (version > 0x400)
{
reader.ReadVarInt(); // imap version
reader.ReadVarInt(); // director version
}
if (version > 0x500)
{
int str_len = reader.ReadU8();
reader.Skip (str_len); // version string
}
reader.Position = next_pos;
if (reader.ReadFourCC() != "Fcdr")
return false;
// skip compression table, assume everything is zlib-compressed
length = reader.ReadVarInt();
reader.Position += length;
if (reader.ReadFourCC() != "ABMP")
return false;
length = reader.ReadVarInt();
next_pos = reader.Position + length;
reader.ReadVarInt(); // compression type, index within 'Fcdr' compression table
int unpacked_size = reader.ReadVarInt();
using (var abmp = new ZLibStream (reader.Source, CompressionMode.Decompress, true))
{
var abmp_reader = new Reader (abmp, reader.ByteOrder);
if (!ReadABMap (context, abmp_reader))
return false;
}
reader.Position = next_pos;
if (reader.ReadFourCC() != "FGEI")
return false;
reader.ReadVarInt();
long base_offset = reader.Position;
foreach (var entry in m_dir)
{
m_index[entry.Id] = entry;
if (entry.Offset >= 0)
entry.Offset += base_offset;
}
var ils_chunk = FindById (2);
if (null == ils_chunk)
return false;
using (var ils = new ZLibStream (reader.Source, CompressionMode.Decompress, true))
{
uint pos = 0;
var ils_reader = new Reader (ils, reader.ByteOrder);
while (pos < ils_chunk.UnpackedSize)
{
int id = ils_reader.ReadVarInt();
var chunk = m_index[id];
m_ilsMap[id] = ils_reader.ReadBytes ((int)chunk.Size);
pos += ils_reader.GetVarIntLength ((uint)id) + chunk.Size;
}
}
return true;
}
bool ReadABMap (SerializationContext context, Reader reader)
{
reader.ReadVarInt();
reader.ReadVarInt();
int count = reader.ReadVarInt();
m_dir = new List<DirectorEntry> (count);
for (int i = 0; i < count; ++ i)
{
var entry = new AfterBurnerEntry();
entry.Deserialize (context, reader);
m_dir.Add (entry);
}
return true;
}
Reader GetChunkReader (DirectorEntry chunk, Reader reader)
{
if (-1 == chunk.Offset)
{
byte[] chunk_data;
if (!m_ilsMap.TryGetValue (chunk.Id, out chunk_data))
throw new InvalidFormatException (string.Format ("Can't find chunk {0} in ILS", chunk.FourCC));
var input = new BinMemoryStream (chunk_data, null);
reader = new Reader (input, reader.ByteOrder);
}
else
{
reader.Position = chunk.Offset;
}
return reader;
}
bool ReadKeyTable (SerializationContext context, Reader reader)
{
var key_chunk = MMap.Find ("KEY*");
var key_chunk = Find ("KEY*");
if (null == key_chunk)
return false;
reader.Position = key_chunk.Offset;
reader = GetChunkReader (key_chunk, reader);
KeyTable.Deserialize (context, reader);
return true;
}
bool ReadConfig (SerializationContext context, Reader reader)
{
var config_chunk = MMap.Find ("VWCF") ?? MMap.Find ("DRCF");
var config_chunk = Find ("VWCF") ?? Find ("DRCF");
if (null == config_chunk)
return false;
reader.Position = config_chunk.Offset;
reader = GetChunkReader (config_chunk, reader);
Config.Deserialize (context, reader);
context.Version = Config.Version;
return true;
@@ -125,21 +260,23 @@ namespace GameRes.Formats.Macromedia
bool ReadCasts (SerializationContext context, Reader reader)
{
Reader cas_reader;
if (context.Version > 1200)
{
var mcsl = MMap.Find ("MCsL");
var mcsl = Find ("MCsL");
if (mcsl != null)
{
reader.Position = mcsl.Offset;
var mcsl_reader = GetChunkReader (mcsl, reader);
var cast_list = new CastList();
cast_list.Deserialize (context, reader);
cast_list.Deserialize (context, mcsl_reader);
foreach (var entry in cast_list.Entries)
{
var key_entry = KeyTable.FindByCast (entry.Id, "CAS*");
if (key_entry != null)
{
var mmap_entry = MMap[key_entry.Id];
var cast = new Cast (context, reader, mmap_entry);
var cas_entry = Index[key_entry.Id];
cas_reader = GetChunkReader (cas_entry, reader);
var cast = new Cast (context, cas_reader, cas_entry);
if (!PopulateCast (cast, context, reader, entry))
return false;
Casts.Add (cast);
@@ -148,11 +285,12 @@ namespace GameRes.Formats.Macromedia
return true;
}
}
var cas_chunk = MMap.Find ("CAS*");
var cas_chunk = Find ("CAS*");
if (null == cas_chunk)
return false;
var new_entry = new CastListEntry { Name = "internal", Id = 0x400, MinMember = Config.MinMember };
var new_cast = new Cast (context, reader, cas_chunk);
cas_reader = GetChunkReader (cas_chunk, reader);
var new_cast = new Cast (context, cas_reader, cas_chunk);
if (!PopulateCast (new_cast, context, reader, new_entry))
return false;
Casts.Add (new_cast);
@@ -162,30 +300,16 @@ namespace GameRes.Formats.Macromedia
public bool PopulateCast (Cast cast, SerializationContext context, Reader reader, CastListEntry entry)
{
cast.Name = entry.Name;
/*
var lctx_ref = KeyTable.Table.Find (e => e.CastId == entry.Id && (e.FourCC == "Lctx" || e.FourCC == "LctX"));
MemoryMapEntry lctx_chunk = null;
if (lctx_ref != null)
lctx_chunk = MMap[lctx_ref.Id];
else
lctx_chunk = MMap.Dir.Find (e => e.FourCC == "Lctx" || e.FourCC == "LctX");
if (null == lctx_chunk)
return false;
reader.Position = lctx_chunk.Offset;
var lctx = new ScriptContext();
lctx.Deserialize (context, reader);
cast.Context = lctx;
*/
for (int i = 0; i < cast.Index.Length; ++i)
{
int chunk_id = cast.Index[i];
if (chunk_id > 0)
{
var chunk = MMap[chunk_id];
var chunk = this.Index[chunk_id];
var member = new CastMember();
member.Id = chunk_id;
reader.Position = chunk.Offset;
member.Deserialize (context, reader);
var cast_reader = GetChunkReader (chunk, reader);
member.Deserialize (context, cast_reader);
cast.Members[member.Id] = member;
}
}
@@ -293,11 +417,10 @@ namespace GameRes.Formats.Macromedia
public string Name;
public Dictionary<int, CastMember> Members = new Dictionary<int, CastMember>();
public Cast (SerializationContext context, Reader reader, MemoryMapEntry entry)
public Cast (SerializationContext context, Reader reader, DirectorEntry entry)
{
int count = (int)(entry.Size / 4);
Index = new int[count];
reader.Position = entry.Offset;
Deserialize (context, reader);
}
@@ -391,54 +514,6 @@ namespace GameRes.Formats.Macromedia
public int Id;
}
internal class ScriptContext
{
public int EntriesOffset;
public int LnamChunkId;
public int ValidCount;
public ushort Flags;
public short FreePtr;
public List<ScriptContextMap> ChunkMap = new List<ScriptContextMap>();
public void Deserialize (SerializationContext context, Reader reader)
{
long base_offset = reader.Position;
reader = reader.CloneUnless (ByteOrder.BigEndian);
reader.Skip (8);
int count = reader.ReadI32();
reader.Skip (4);
EntriesOffset = reader.ReadU16();
reader.Skip (14);
LnamChunkId = reader.ReadI32();
ValidCount = reader.ReadU16();
Flags = reader.ReadU16();
FreePtr = reader.ReadI16();
reader.Position = base_offset + EntriesOffset;
ChunkMap.Clear();
ChunkMap.Capacity = count;
for (int i = 0; i < count; ++i)
{
var entry = new ScriptContextMap();
entry.Deserialize (context, reader);
ChunkMap.Add (entry);
}
}
}
internal class ScriptContextMap
{
public int Key;
public int ChunkId;
public void Deserialize (SerializationContext context, Reader reader)
{
Key = reader.ReadI32();
ChunkId = reader.ReadI32();
reader.Skip (4);
}
}
internal class DirectorConfig
{
public short Length;
@@ -548,11 +623,9 @@ namespace GameRes.Formats.Macromedia
public int ChunkCountMax;
public int ChunkCountUsed;
public int FreeHead;
public readonly List<MemoryMapEntry> Dir = new List<MemoryMapEntry>();
public readonly List<DirectorEntry> Dir = new List<DirectorEntry>();
public MemoryMapEntry this[int index] => Dir[index];
public MemoryMapEntry Find (string four_cc) => Dir.Find (e => e.FourCC == four_cc);
public DirectorEntry this[int index] => Dir[index];
public void Deserialize (SerializationContext context, Reader reader)
{
@@ -582,10 +655,14 @@ namespace GameRes.Formats.Macromedia
}
}
internal class MemoryMapEntry : Entry
internal class DirectorEntry : PackedEntry
{
public int Id;
public string FourCC;
}
internal class MemoryMapEntry : DirectorEntry
{
public ushort Flags;
public MemoryMapEntry (int id = 0)
@@ -596,10 +673,28 @@ namespace GameRes.Formats.Macromedia
public void Deserialize (SerializationContext context, Reader reader)
{
FourCC = reader.ReadFourCC();
Size = reader.ReadU32();
Size = reader.ReadU32();
Offset = reader.ReadU32() + 8;
Flags = reader.ReadU16();
int Next = reader.ReadI32();
Flags = reader.ReadU16();
reader.ReadI32(); // next
UnpackedSize = Size;
IsPacked = false;
}
}
internal class AfterBurnerEntry : DirectorEntry
{
public int CompMethod;
public void Deserialize (SerializationContext context, Reader reader)
{
Id = reader.ReadVarInt();
Offset = reader.ReadVarInt();
Size = (uint)reader.ReadVarInt();
UnpackedSize = (uint)reader.ReadVarInt();
CompMethod = reader.ReadVarInt(); // assume zlib
FourCC = reader.ReadFourCC();
IsPacked = Size != UnpackedSize;
}
}
@@ -619,7 +714,7 @@ namespace GameRes.Formats.Macromedia
SetByteOrder (e);
}
public Stream Source { get => m_input; }
public Stream Source => m_input;
public ByteOrder ByteOrder { get; private set; }
@@ -701,6 +796,32 @@ namespace GameRes.Formats.Macromedia
return buffer;
}
public int ReadVarInt ()
{
int n = 0;
for (int i = 0; i < 5; ++i)
{
int bits = m_input.ReadByte();
if (-1 == bits)
throw new EndOfStreamException();
n = n << 7 | bits & 0x7F;
if (0 == (bits & 0x80))
return n;
}
throw new InvalidFormatException();
}
public uint GetVarIntLength (uint i)
{
uint n = 1;
while (i > 0x7F)
{
i >>= 7;
++n;
}
return n;
}
public Reader CloneUnless (ByteOrder order)
{
if (this.ByteOrder != order)

View File

@@ -1,8 +1,8 @@
//! \file ImageBITD.cs
//! \date Fri Jun 26 07:45:01 2015
//! \brief Selen image format.
//! \brief Macromedia Director image format.
//
// Copyright (C) 2015 by morkt
// Copyright (C) 2015-2023 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
@@ -34,174 +34,9 @@ using GameRes.Utility;
namespace GameRes.Formats.Macromedia
{
[Export(typeof(ImageFormat))]
public class BitdFormat : ImageFormat
internal class BitdMetaData : ImageMetaData
{
public override string Tag { get { return "BITD"; } }
public override string Description { get { return "Selen RLE-compressed bitmap"; } }
public override uint Signature { get { return 0; } }
public override ImageMetaData ReadMetaData (IBinaryStream stream)
{
if (stream.Length > 0xffffff)
return null;
var scanner = new BitdScanner (stream.AsStream);
return scanner.GetInfo();
}
public override ImageData Read (IBinaryStream stream, ImageMetaData info)
{
var reader = new BitdReader (stream.AsStream, info);
reader.Unpack();
return ImageData.Create (info, reader.Format, null, reader.Data);
}
public override void Write (Stream file, ImageData image)
{
throw new NotImplementedException ("BitdFormat.Write not implemented");
}
}
internal class BitdScanner
{
Stream m_input;
protected Stream Input { get { return m_input; } }
public BitdScanner (Stream input)
{
m_input = input;
}
const int MaxScanLine = 2048;
public ImageMetaData GetInfo ()
{
int total = 0;
var scan_lines = new Dictionary<int, int>();
var key_lines = new List<int>();
for (;;)
{
int b = m_input.ReadByte();
if (-1 == b)
break;
int count = b;
if (b > 0x7f)
count = (byte)-(sbyte)b;
++count;
if (count > 0x7f)
return null;
if (b > 0x7f)
{
if (-1 == m_input.ReadByte())
return null;
}
else
m_input.Seek (count, SeekOrigin.Current);
key_lines.Clear();
key_lines.AddRange (scan_lines.Keys);
foreach (var line in key_lines)
{
int width = scan_lines[line];
if (width < count)
scan_lines.Remove (line);
else if (width == count)
scan_lines[line] = line;
else
scan_lines[line] = width - count;
}
total += count;
if (total <= MaxScanLine && total >= 8)
scan_lines[total] = total;
if (total > MaxScanLine && !scan_lines.Any())
return null;
}
int rem;
total = Math.DivRem (total, 4, out rem);
if (rem != 0)
return null;
var valid_lines = from line in scan_lines where line.Key == line.Value
orderby line.Key
select line.Key;
bool is_eof = -1 == m_input.ReadByte();
foreach (var width in valid_lines)
{
int height = Math.DivRem (total, width, out rem);
if (0 == rem)
{
return new ImageMetaData
{
Width = (uint)width,
Height = (uint)height,
BPP = 32,
};
}
}
return null;
}
}
internal class BitdReader : BitdScanner
{
byte[] m_output;
int m_width;
int m_height;
public byte[] Data { get { return m_output; } }
public PixelFormat Format { get; private set; }
public BitdReader (Stream input, ImageMetaData info) : base (input)
{
m_width = (int)info.Width;
m_height = (int)info.Height;
m_output = new byte[m_width * m_height * 4];
Format = PixelFormats.Bgra32;
}
public void Unpack ()
{
int stride = m_width * 4;
var scan_line = new byte[stride];
for (int line = 0; line < m_output.Length; line += stride)
{
int dst = 0;
while (dst < stride)
{
int b = Input.ReadByte();
if (-1 == b)
throw new InvalidFormatException ("Unexpected end of file");
int count = b;
if (b > 0x7f)
count = (byte)-(sbyte)b;
++count;
if (dst + count > stride)
throw new InvalidFormatException();
if (b > 0x7f)
{
b = Input.ReadByte();
if (-1 == b)
throw new InvalidFormatException ("Unexpected end of file");
for (int i = 0; i < count; ++i)
scan_line[dst++] = (byte)b;
}
else
{
Input.Read (scan_line, dst, count);
dst += count;
}
}
dst = line;
for (int x = 0; x < m_width; ++x)
{
m_output[dst++] = scan_line[x+m_width*3];
m_output[dst++] = scan_line[x+m_width*2];
m_output[dst++] = scan_line[x+m_width];
m_output[dst++] = scan_line[x];
}
}
}
public byte DepthType;
}
internal class BitdDecoder : IImageDecoder
@@ -216,13 +51,13 @@ namespace GameRes.Formats.Macromedia
BitmapPalette m_palette;
public Stream Source => m_input;
public ImageFormat SourceFormat => null;
public ImageFormat SourceFormat { get; private set; }
public ImageMetaData Info => m_info;
public ImageData Image => m_image ?? (m_image = GetImageData());
public PixelFormat Format { get; private set; }
public byte[] AlphaChannel { get; set; }
public BitdDecoder (Stream input, ImageMetaData info, BitmapPalette palette)
public BitdDecoder (Stream input, BitdMetaData info, BitmapPalette palette)
{
m_input = input;
m_info = info;
@@ -235,23 +70,55 @@ namespace GameRes.Formats.Macromedia
: info.BPP == 4 ? PixelFormats.Indexed4
: info.BPP == 8 ? PixelFormats.Indexed8
: info.BPP == 16 ? PixelFormats.Bgr555
: PixelFormats.Bgr32;
: info.DepthType == 0x87 // i have no clue what this is
|| info.DepthType == 0x8A ? PixelFormats.Bgra32 // depth type 0x87/0x8A
: PixelFormats.Bgra32; // depth type 0x82/84/85/86/8C
m_palette = palette;
}
private BitdDecoder (Stream input, ImageMetaData info, byte[] alpha_channel)
{
m_input = input;
m_info = info;
m_width = info.iWidth;
m_height = info.iHeight;
m_stride = (m_width * m_info.BPP + 7) / 8;
Format = PixelFormats.Bgra32;
AlphaChannel = alpha_channel;
SourceFormat = ImageFormat.Jpeg;
}
public static IImageDecoder FromJpeg (Stream input, ImageMetaData info, byte[] alpha_channel)
{
return new BitdDecoder (input, info, alpha_channel);
}
protected ImageData GetImageData ()
{
BitmapSource bitmap = null;
m_input.Position = 0;
if (Info.BPP <= 8)
if (SourceFormat == ImageFormat.Jpeg)
{
var decoder = new JpegBitmapDecoder (m_input, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
bitmap = decoder.Frames[0];
if (null == AlphaChannel)
return new ImageData (bitmap, m_info);
}
else if (Info.BPP > 8)
UnpackChannels (Info.BPP / 8);
else if (m_output.Length != m_input.Length)
Unpack8bpp();
else
UnpackChannels (Info.BPP / 8);
m_input.Read (m_output, 0, m_output.Length);
if (AlphaChannel != null)
{
if (Info.BPP != 32)
if (Info.BPP != 32 || bitmap != null)
{
BitmapSource bitmap = BitmapSource.Create (Info.iWidth, Info.iHeight, ImageData.DefaultDpiX, ImageData.DefaultDpiY, Format, m_palette, m_output, m_stride);
bitmap = new FormatConvertedBitmap (bitmap, PixelFormats.Bgr32, null, 0);
if (bitmap == null)
bitmap = BitmapSource.Create (m_width, m_height, ImageData.DefaultDpiX, ImageData.DefaultDpiY, Format, m_palette, m_output, m_stride);
if (Info.BPP != 32)
bitmap = new FormatConvertedBitmap (bitmap, PixelFormats.Bgr32, null, 0);
m_stride = bitmap.PixelWidth * 4;
m_output = new byte[bitmap.PixelHeight * m_stride];
bitmap.CopyPixels (m_output, m_stride, 0);
@@ -324,7 +191,8 @@ namespace GameRes.Formats.Macromedia
{
int b = m_input.ReadByte();
if (-1 == b)
throw new InvalidFormatException ("Unexpected end of file");
break; // one in 5000 images somehow stumbles here
// throw new InvalidFormatException ("Unexpected end of file");
int count = b;
if (b > 0x7f)
count = (byte)-(sbyte)b;