Files
SabreTools/SabreTools.FileTypes/CHD/CHDFile.cs

103 lines
3.1 KiB
C#
Raw Normal View History

using System;
using System.IO;
using System.Text;
2024-04-24 13:45:38 -04:00
using SabreTools.IO.Extensions;
2017-10-31 01:06:56 -07:00
2020-12-10 22:31:23 -08:00
namespace SabreTools.FileTypes.CHD
2017-10-31 01:06:56 -07:00
{
/// <summary>
/// This is code adapted from chd.h and chd.cpp in MAME
/// Additional archival code from https://github.com/rtissera/libchdr/blob/master/src/chd.h
/// </summary>
public abstract class CHDFile : BaseFile
{
#region Private instance variables
2024-10-20 00:03:29 -04:00
protected const string Signature = "MComprHD";
/// <summary>
/// Model representing the correct CHD header
/// </summary>
protected Models.CHD.Header? _header;
#endregion
#region Constructors
/// <summary>
/// Create a new CHDFile from an input file
/// </summary>
/// <param name="filename">Filename respresenting the CHD file</param>
2024-02-28 19:19:50 -05:00
public static CHDFile? Create(string filename)
{
2024-10-20 00:06:40 -04:00
using var fs = File.OpenRead(filename);
return Create(fs);
}
/// <summary>
/// Create a new CHDFile from an input stream
/// </summary>
2024-10-20 00:06:40 -04:00
/// <param name="stream">Stream representing the CHD file</param>
public static CHDFile? Create(Stream stream)
{
2020-07-19 21:59:34 -07:00
try
{
2024-10-20 00:06:40 -04:00
// Get the detected CHD version
uint version = GetVersion(stream);
2024-07-19 15:35:23 -04:00
// Read and return the current CHD
2024-10-20 00:06:40 -04:00
return version switch
{
1 => CHDFileV1.Deserialize(stream),
2 => CHDFileV2.Deserialize(stream),
3 => CHDFileV3.Deserialize(stream),
4 => CHDFileV4.Deserialize(stream),
5 => CHDFileV5.Deserialize(stream),
_ => null,
};
2020-07-19 21:59:34 -07:00
}
catch
{
return null;
}
}
#endregion
2024-10-20 00:06:40 -04:00
#region Helpers
/// <summary>
2024-10-20 00:06:40 -04:00
/// Get the matching CHD version, if possible
/// </summary>
/// <returns>Matching version, 0 if none</returns>
2024-10-20 00:06:40 -04:00
private static uint GetVersion(Stream stream)
{
2024-10-20 00:03:29 -04:00
// Read the header values
byte[] tagBytes = stream.ReadBytes(8);
string tag = Encoding.ASCII.GetString(tagBytes);
uint length = stream.ReadUInt32BigEndian();
uint version = stream.ReadUInt32BigEndian();
// Seek back to start
stream.SeekIfPossible();
// Check the signature
if (!string.Equals(tag, Signature, StringComparison.Ordinal))
return 0;
2024-10-20 00:03:29 -04:00
// Match the version to header length
return version switch
{
1 => length == CHDFileV1.HeaderSize ? version : 0,
2 => length == CHDFileV2.HeaderSize ? version : 0,
3 => length == CHDFileV3.HeaderSize ? version : 0,
4 => length == CHDFileV4.HeaderSize ? version : 0,
5 => length == CHDFileV5.HeaderSize ? version : 0,
_ => 0,
};
}
#endregion
}
2017-10-31 01:06:56 -07:00
}