Add support and command for converting images, fixes #134

This commit is contained in:
2017-12-29 00:46:03 +00:00
parent d2036a3d16
commit 1aebaca9a9
11 changed files with 331 additions and 3 deletions

View File

@@ -22,6 +22,7 @@
<e p="Commands.cs" t="Include" />
<e p="Compare.cs" t="Include" />
<e p="Configure.cs" t="Include" />
<e p="ConvertImage.cs" t="Include" />
<e p="CreateSidecar.cs" t="Include" />
<e p="Decode.cs" t="Include" />
<e p="DeviceInfo.cs" t="Include" />

View File

@@ -351,6 +351,10 @@ namespace DiscImageChef.Core
AllStats.Commands.ListEncodings++;
CurrentStats.Commands.ListEncodings++;
break;
case "convert-image":
AllStats.Commands.ConvertImage++;
CurrentStats.Commands.ConvertImage++;
break;
}
}

View File

@@ -67,6 +67,7 @@ namespace DiscImageChef.Metadata
public long Checksum;
public long Compare;
public long CreateSidecar;
public long ConvertImage;
public long Decode;
public long DeviceInfo;
public long DeviceReport;

View File

@@ -109,6 +109,7 @@ namespace DiscImageChef.Server.Controllers
oldStats.Commands.ExtractFiles += newStats.Commands.ExtractFiles;
oldStats.Commands.ListDevices += newStats.Commands.ListDevices;
oldStats.Commands.ListEncodings += newStats.Commands.ListEncodings;
oldStats.Commands.ConvertImage += newStats.Commands.ConvertImage;
}
if(newStats.OperatingSystems != null)

View File

@@ -97,6 +97,7 @@
<i>benchmark</i> command has been run <asp:Label id="lblBenchmark" runat="server"/> times<br/>
<i>checksum</i> command has been run <asp:Label id="lblChecksum" runat="server"/> times<br/>
<i>compare</i> command has been run <asp:Label id="lblCompare" runat="server"/> times<br/>
<i>convert-image</i> command has been run <asp:Label id="lblConvertImage" runat="server"/> times<br/>
<i>create-sidecar</i> command has been run <asp:Label id="lblCreateSidecar" runat="server"/> times<br/>
<i>decode</i> command has been run <asp:Label id="lblDecode" runat="server"/> times<br/>
<i>device-info</i> command has been run <asp:Label id="lblDeviceInfo" runat="server"/> times<br/>

View File

@@ -136,6 +136,7 @@ namespace DiscImageChef.Server
lblExtractFiles.Text = statistics.Commands.ExtractFiles.ToString();
lblListDevices.Text = statistics.Commands.ListDevices.ToString();
lblListEncodings.Text = statistics.Commands.ListEncodings.ToString();
lblConvertImage.Text = statistics.Commands.ConvertImage.ToString();
}
else divCommands.Visible = false;

View File

@@ -40,6 +40,8 @@ namespace DiscImageChef.Server {
protected Label lblCompare;
protected Label lblConvertImage;
protected Label lblCreateSidecar;
protected Label lblDecode;

View File

@@ -0,0 +1,287 @@
// /***************************************************************************
// The Disc Image Chef
// ----------------------------------------------------------------------------
//
// Filename : ConvertImage.cs
// Author(s) : Natalia Portillo <claunia@claunia.com>
//
// Component : Verbs.
//
// --[ Description ] ----------------------------------------------------------
//
// Converts from one media image to another.
//
// --[ License ] --------------------------------------------------------------
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2018 Natalia Portillo
// ****************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DiscImageChef.Console;
using DiscImageChef.Core;
using DiscImageChef.DiscImages;
using DiscImageChef.Filters;
namespace DiscImageChef.Commands
{
public static class ConvertImage
{
public static void DoConvert(ConvertImageOptions options)
{
DicConsole.DebugWriteLine("Analyze command", "--debug={0}", options.Debug);
DicConsole.DebugWriteLine("Analyze command", "--verbose={0}", options.Verbose);
DicConsole.DebugWriteLine("Analyze command", "--input={0}", options.InputFile);
DicConsole.DebugWriteLine("Analyze command", "--output={0}", options.OutputFile);
DicConsole.DebugWriteLine("Analyze command", "--format={0}", options.OutputFormat);
DicConsole.DebugWriteLine("Analyze command", "--count={0}", options.Count);
DicConsole.DebugWriteLine("Analyze command", "--force={0}", options.Force);
if(options.Count == 0)
{
DicConsole.ErrorWriteLine("Need to specify more than 0 sectors to copy at once");
return;
}
FiltersList filtersList = new FiltersList();
IFilter inputFilter = filtersList.GetFilter(options.InputFile);
if(inputFilter == null)
{
DicConsole.ErrorWriteLine("Cannot open specified file.");
return;
}
PluginBase plugins = new PluginBase();
IMediaImage inputFormat = ImageFormat.Detect(inputFilter);
if(inputFormat == null)
{
DicConsole.WriteLine("Input image format not identified, not proceeding with conversion.");
return;
}
if(options.Verbose)
DicConsole.VerboseWriteLine("Input image format identified by {0} ({1}).", inputFormat.Name,
inputFormat.Id);
else DicConsole.WriteLine("Input image format identified by {0}.", inputFormat.Name);
try
{
if(!inputFormat.Open(inputFilter))
{
DicConsole.WriteLine("Unable to open image format");
DicConsole.WriteLine("No error given");
return;
}
DicConsole.DebugWriteLine("Convert-image command", "Correctly opened image file.");
DicConsole.DebugWriteLine("Convert-image command", "Image without headers is {0} bytes.",
inputFormat.Info.ImageSize);
DicConsole.DebugWriteLine("Convert-image command", "Image has {0} sectors.", inputFormat.Info.Sectors);
DicConsole.DebugWriteLine("Convert-image command", "Image identifies media type as {0}.",
inputFormat.Info.MediaType);
Core.Statistics.AddMediaFormat(inputFormat.Format);
Core.Statistics.AddMedia(inputFormat.Info.MediaType, false);
Core.Statistics.AddFilter(inputFilter.Name);
}
catch(Exception ex)
{
DicConsole.ErrorWriteLine("Unable to open image format");
DicConsole.ErrorWriteLine("Error: {0}", ex.Message);
DicConsole.DebugWriteLine("Convert-image command", "Stack trace: {0}", ex.StackTrace);
return;
}
List<IWritableImage> candidates = new List<IWritableImage>();
// Try extension
if(string.IsNullOrEmpty(options.OutputFormat))
candidates.AddRange(plugins.WritableImages.Values.Where(t =>
t.KnownExtensions
.Contains(Path.GetExtension(options
.OutputFile))));
// Try Id
else if(Guid.TryParse(options.OutputFormat, out Guid outId))
candidates.AddRange(plugins.WritableImages.Values.Where(t => t.Id.Equals(outId)));
// Try name
else
candidates.AddRange(plugins.WritableImages.Values.Where(t => string.Equals(t.Name, options.OutputFormat,
StringComparison
.InvariantCultureIgnoreCase)));
if(candidates.Count == 0)
{
DicConsole.WriteLine("No plugin supports requested format.");
return;
}
if(candidates.Count > 1)
{
DicConsole.WriteLine("More than one plugin supports requested format.");
return;
}
IWritableImage outputFormat = candidates[0];
if(!outputFormat.SupportedMediaTypes.Contains(inputFormat.Info.MediaType))
{
DicConsole.ErrorWriteLine("Output format does not support media type, cannot continue...");
return;
}
if(options.Verbose)
DicConsole.VerboseWriteLine("Output image format: {0} ({1}).", outputFormat.Name, outputFormat.Id);
else DicConsole.WriteLine("Output image format: {0}.", outputFormat.Name);
foreach(MediaTagType mediaTag in inputFormat.Info.ReadableMediaTags)
{
if(outputFormat.SupportedMediaTags.Contains(mediaTag) || options.Force) continue;
DicConsole.ErrorWriteLine("Converting image will lose media tag {0}, not continuing...");
DicConsole.ErrorWriteLine("If you don't care, use force option.");
return;
}
bool useLong = inputFormat.Info.ReadableSectorTags.Count != 0;
foreach(SectorTagType mediaTag in inputFormat.Info.ReadableSectorTags)
{
if(!outputFormat.SupportedSectorTags.Contains(mediaTag))
if(options.Force)
{
useLong = false;
continue;
}
DicConsole.ErrorWriteLine("Converting image will lose sector tag {0}, not continuing...");
DicConsole
.ErrorWriteLine("If you don't care, use force option. This will skip all sector tags converting only user data.");
return;
}
if(!outputFormat.Create(options.OutputFile, inputFormat.Info.MediaType, new Dictionary<string, string>(),
inputFormat.Info.Sectors))
{
DicConsole.ErrorWriteLine("Error {0} creating output image.", outputFormat.ErrorMessage);
return;
}
List<Track> tracks;
try { tracks = inputFormat.Tracks; }
catch(Exception) { tracks = null; }
if(tracks != null)
if(!outputFormat.SetTracks(tracks))
{
DicConsole.ErrorWriteLine("Error {0} sending tracks list to output image.",
outputFormat.ErrorMessage);
return;
}
foreach(MediaTagType mediaTag in inputFormat.Info.ReadableMediaTags)
{
DicConsole.WriteLine("Converting media tag {0}", mediaTag);
byte[] tag = inputFormat.ReadDiskTag(mediaTag);
if(outputFormat.WriteMediaTag(tag, mediaTag)) continue;
if(options.Force)
DicConsole.ErrorWriteLine("Error {0} writing media tag, continuing...", outputFormat.ErrorMessage);
else
{
DicConsole.ErrorWriteLine("Error {0} writing media tag, not continuing...",
outputFormat.ErrorMessage);
return;
}
}
DicConsole.WriteLine("{0} sectors to convert", inputFormat.Info.Sectors);
ulong doneSectors = 0;
while(doneSectors < inputFormat.Info.Sectors)
{
byte[] sector;
uint sectorsToDo;
if(inputFormat.Info.Sectors - doneSectors >= (ulong)options.Count) sectorsToDo = (uint)options.Count;
else
sectorsToDo =
(uint)(inputFormat.Info.Sectors - doneSectors);
DicConsole.Write("\rConverting sectors {0} to {1} ({2:P2} done)", doneSectors,
doneSectors + sectorsToDo, doneSectors / (double)inputFormat.Info.Sectors);
bool result;
if(useLong)
if(sectorsToDo == 1)
{
sector = inputFormat.ReadSectorLong(doneSectors);
result = outputFormat.WriteSectorLong(sector, doneSectors);
}
else
{
sector = inputFormat.ReadSectorsLong(doneSectors, sectorsToDo);
result = outputFormat.WriteSectorsLong(sector, doneSectors, sectorsToDo);
}
else
{
if(sectorsToDo == 1)
{
sector = inputFormat.ReadSector(doneSectors);
result = outputFormat.WriteSector(sector, doneSectors);
}
else
{
sector = inputFormat.ReadSectors(doneSectors, sectorsToDo);
result = outputFormat.WriteSectors(sector, doneSectors, sectorsToDo);
}
}
if(!result)
if(options.Force)
DicConsole.ErrorWriteLine("Error {0} writing sector {1}, continuing...",
outputFormat.ErrorMessage, doneSectors);
else
{
DicConsole.ErrorWriteLine("Error {0} writing sector {1}, not continuing...",
outputFormat.ErrorMessage, doneSectors);
return;
}
doneSectors += sectorsToDo;
}
DicConsole.Write("\rConverting sectors {0} to {1} ({2:P2} done)", inputFormat.Info.Sectors,
inputFormat.Info.Sectors, 1.0);
DicConsole.WriteLine();
DicConsole.WriteLine("Closing output image.");
if(!outputFormat.Close())
DicConsole.ErrorWriteLine("Error {0} closing output image... Contents are not correct.",
outputFormat.ErrorMessage);
DicConsole.WriteLine();
DicConsole.WriteLine("Conversion done.");
Core.Statistics.AddCommand("convert-image");
}
}
}

View File

@@ -51,6 +51,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Commands\ConvertImage.cs" />
<Compile Include="Commands\ListOptions.cs" />
<Compile Include="Main.cs" />
<Compile Include="AssemblyInfo.cs" />

View File

@@ -53,8 +53,8 @@ namespace DiscImageChef
Parser.Default.ParseArguments(args, typeof(AnalyzeOptions), typeof(BenchmarkOptions),
typeof(ChecksumOptions), typeof(CompareOptions), typeof(ConfigureOptions),
typeof(CreateSidecarOptions), typeof(DecodeOptions),
typeof(DeviceInfoOptions), typeof(DeviceReportOptions),
typeof(ConvertImageOptions), typeof(CreateSidecarOptions),
typeof(DecodeOptions), typeof(DeviceInfoOptions), typeof(DeviceReportOptions),
typeof(DumpMediaOptions), typeof(EntropyOptions), typeof(ExtractFilesOptions),
typeof(FormatsOptions), typeof(ListDevicesOptions),
typeof(ListEncodingsOptions), typeof(ListOptionsOptions), typeof(LsOptions),
@@ -180,6 +180,12 @@ namespace DiscImageChef
if(opts.Verbose) DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
PrintCopyright();
ListOptions.DoList();
}).WithParsed<ConvertImageOptions>(opts =>
{
if(opts.Debug) DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
if(opts.Verbose) DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
PrintCopyright();
ConvertImage.DoConvert(opts);
}).WithParsed<ConfigureOptions>(opts =>
{
PrintCopyright();

View File

@@ -353,4 +353,27 @@ namespace DiscImageChef
[Verb("list-options", HelpText = "Lists all options supported by read-only filesystems and writable media images.")]
public class ListOptionsOptions : CommonOptions { }
[Verb("convert-image", HelpText = "Converts one image to another format.")]
public class ConvertImageOptions : CommonOptions
{
[Option('i', "input", Required = true, HelpText = "Input image.")]
public string InputFile { get; set; }
[Option('o', "output", Required = true, HelpText = "Output image.")]
public string OutputFile { get; set; }
[Option('p', "format", Default = null,
HelpText =
"Format of the output image, as plugin name or plugin id. If not present, will try to detect it from output image extension.")]
public string OutputFormat { get; set; }
[Option('c', "count", Default = 64, HelpText = "How many sectors to convert at once.")]
public int Count { get; set; }
[Option('f', "force", Default = false,
HelpText =
"Continue conversion even if sector or media tags will be lost in the process.")]
public bool Force { get; set; }
}
}