-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathProgram.cs
More file actions
436 lines (407 loc) · 15.5 KB
/
Program.cs
File metadata and controls
436 lines (407 loc) · 15.5 KB
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
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.PixelFormats;
using SixPix;
using System.Text;
#if SIXPIX_DEBUG
Console.WriteLine("Hello, SixPix!");
#endif
if (args.Length == 0)
{
PrintUsage();
Environment.Exit(1);
}
Transparency transp = Transparency.Default;
int w = -1, h = -1, f = -1, delay = -1;
Rgba32 bgColor = new();
bool getData = false, anim = false, animForever = false;
string infile = "", outfile = "";
const string MAP8_SIXEL = "Pq\"1;1;93;14#0;2;60;0;0#1;2;0;66;0#2;2;56;60;0#3;2;47;38;97#4;2;72;0;69#5;2;0;66;72#6;2;72;72;72#7;2;0;0;0#0!11~#1!12~#2!12~#3!12~#4!12~#5!12~#6!12~#7!10~-#0!11~#1!12~#2!12~#3!12~#4!12~#5!12~#6!12~#7!10~-#0!11B#1!12B#2!12B#3!12B#4!12B#5!12B#6!12B#7!10B\\";
foreach (var arg in args)
{
string param = "";
if (arg.StartsWith('-') || arg.StartsWith('/'))
{
param = arg.TrimStart('-', '/');
switch (param[0])
{
case 'a':
anim = true;
break;
case 'A':
anim = true;
animForever = true;
break;
case 'g':
case 'G':
getData = true;
break;
case 't':
transp = Transparency.None;
break;
case 'T':
transp = Transparency.TopLeft;
break;
case 'b':
case 'B':
transp = Transparency.Background;
break;
case 'c':
case 'C':
transp = Transparency.None;
var o = ' ';
if (param.Contains('='))
o = '=';
else if (param.Contains(':'))
o = ':';
else
break;
string s = param[(param.IndexOf(o) + 1)..];
if (s.StartsWith('#'))
s = s[1..];
else if (s.StartsWith("0x"))
s = s[2..];
if (s.Length is > 2 and < 9)
{
if (s.Length is 5 or 7)
s = '0' + s;
if (Rgba32.TryParseHex(s, out bgColor))
break;
}
Console.WriteLine("Error: Bad color value specified (must be in hexadecimal).");
break;
case 'w':
case 'W':
if (param.Contains('='))
_ = int.TryParse(param[(param.IndexOf('=') + 1)..], out w);
else if (param.Contains(':'))
_ = int.TryParse(param[(param.IndexOf(':') + 1)..], out w);
break;
case 'h':
case 'H':
if (param.Contains('='))
_ = int.TryParse(param[(param.IndexOf('=') + 1)..], out h);
else if (param.Contains(':'))
_ = int.TryParse(param[(param.IndexOf(':') + 1)..], out h);
break;
case 'f':
case 'F':
if (param.Contains('='))
_ = int.TryParse(param[(param.IndexOf('=') + 1)..], out f);
else if (param.Contains(':'))
_ = int.TryParse(param[(param.IndexOf(':') + 1)..], out f);
if (f < 0)
f = 0;
break;
case 'd':
case 'D':
if (param.Contains('='))
_ = int.TryParse(param[(param.IndexOf('=') + 1)..], out delay);
else if (param.Contains(':'))
_ = int.TryParse(param[(param.IndexOf(':') + 1)..], out delay);
break;
case 'o': // output filename (explicit instead of based on position)
case 'O':
if (param.Contains('='))
outfile = param[(param.IndexOf('=') + 1)..];
else if (param.Contains(':'))
outfile = param[(param.IndexOf(':') + 1)..];
break;
case 'i': // input filename (explicit instead of based on position)
case 'I':
if (param.Contains('='))
infile = param[(param.IndexOf('=') + 1)..];
else if (param.Contains(':'))
infile = param[(param.IndexOf(':') + 1)..];
break;
default:
Console.Error.WriteLine("Error: Unrecognized parameter '" + param + "'");
Environment.Exit(1);
break;
}
}
else if (string.IsNullOrEmpty(infile))
infile = arg;
else
outfile = arg;
// Don't allow file output forever
if (!string.IsNullOrEmpty(outfile))
animForever = false;
}
if (!Path.Exists(infile))
{
if (string.IsNullOrEmpty(infile))
Console.Error.WriteLine("Error: No input filename provided.");
else
Console.Error.WriteLine("Error: File not found: " + infile);
PrintUsage();
Environment.Exit(1);
}
var fileInfo = new FileInfo(infile);
if (IsBinary(infile))
{
var start = DateTime.Now;
try
{
using var fs = fileInfo.OpenRead();
using var image = Image.Load<Rgba32>(fs);
using var sixelEncoder = Sixel.CreateEncoder(image)
.Resize(width: w, height: h);
// Reverse /t logic when displaying animations if sync isn't supported
if (anim && sixelEncoder.ReverseTransparencyOnAnimate && !Sixel.IsSyncSupported())
{
if (transp == Transparency.None)
transp = Transparency.Default;
else if (transp == Transparency.Default)
transp = Transparency.None;
}
sixelEncoder.TransparencyMode = transp;
if (bgColor != default)
Sixel.BackgroundColor = Color.FromPixel(bgColor);
if (f >= sixelEncoder.FrameCount)
{
Console.Error.WriteLine("Error: Specified frame does not exist (index starts at 0).");
getData = true;
}
#if IMAGESHARP4
var best = Sixel.GetBestFrame(sixelEncoder.Image, null);
#endif
if (getData)
{
(var cw, var ch) = sixelEncoder.CanvasSize;
Console.WriteLine("Image Format: " + sixelEncoder.Format);
Console.WriteLine(" Image Size: " + cw + "x" + ch);
Console.WriteLine(" Num Frames: " + sixelEncoder.FrameCount);
#if IMAGESHARP4
Console.WriteLine(" Best Frame: " + best);
#endif
Console.WriteLine(" Num Repeats: " + sixelEncoder.RepeatCount);
Console.Write("Frame Delays: [ ");
for (var fr = 0; fr < sixelEncoder.FrameCount; fr++)
{
Console.Write(sixelEncoder.GetFrameDelay(fr) + " ");
}
Console.WriteLine("]");
Environment.Exit(sixelEncoder.FrameCount);
}
if (!string.IsNullOrEmpty(outfile))
{
if (!anim) // Write to one file
{
var sixelString = sixelEncoder.EncodeFrame(f);
#if SIXPIX_DEBUG
var elapsed = DateTime.Now - start;
Console.WriteLine($"Elapsed {elapsed.TotalMilliseconds} ms");
#endif
// Save image to Sixel text file
var thisOutfile = outfile;
if (!thisOutfile.Contains('.'))
thisOutfile += ".six";
using var wf = new FileStream(thisOutfile, FileMode.Create);
Console.WriteLine($"Writing to file {wf.Name} ...");
wf.Write(new UTF8Encoding(true).GetBytes(sixelString));
}
else // write each frame to a file
{
var frameIndex = 0;
foreach (var sixelString in sixelEncoder.EncodeFrames())
{
#if SIXPIX_DEBUG
var elapsed = DateTime.Now - start;
Console.WriteLine($"Elapsed {elapsed.TotalMilliseconds} ms");
#endif
// Save image to Sixel text file
var thisOutfile = outfile;
// Add frame number to filename if exporting multiple frames
if (anim)
thisOutfile += frameIndex;
if (!thisOutfile.Contains('.'))
thisOutfile += ".six";
using var wf = new FileStream(thisOutfile, FileMode.Create);
Console.WriteLine($"Writing to file {wf.Name} ...");
wf.Write(new UTF8Encoding(true).GetBytes(sixelString));
frameIndex++;
}
}
Environment.Exit(0);
}
if (!anim)
{
#if IMAGESHARP4
if (f < 0 && best >= 0)
f = best;
#endif
if (f < 0)
f = 0;
var sixelString = sixelEncoder.EncodeFrame(f);
#if SIXPIX_DEBUG
var elapsed = DateTime.Now - start;
Console.WriteLine($"Elapsed {elapsed.TotalMilliseconds} ms");
#endif
Console.WriteLine(sixelString);
Environment.Exit(0);
}
if (sixelEncoder.FrameCount < 2)
{
Console.Error.WriteLine("Error: Cannot animate a single-frame file.");
Environment.Exit(1);
}
// Disable cursor
Console.Write(Sixel.ESC + Sixel.CursorOff);
// Start animation
Console.WriteLine("Press 'Ctrl+c' or 'q' to stop.");
using var ct = new CancellationTokenSource();
sixelEncoder.SetFrameDelays(delay >= 0 ? delay : -1);
var t1 = sixelEncoder.Animate(animForever ? 0 : 1,
f < 0 ? 0 : f,
-1,
ct.Token);
var t2 = Task.Run(() =>
{
Console.TreatControlCAsInput = true;
ConsoleKeyInfo keyInfo;
do
{
keyInfo = Console.ReadKey(true);
if (keyInfo is { Key: ConsoleKey.C, Modifiers: ConsoleModifiers.Control }
or { KeyChar: 'q' })
{
ct.CancelAsync();
break;
}
}
while (true);
Console.TreatControlCAsInput = false;
});
t1.Wait();
}
catch (AggregateException e)
{
if (e.InnerException is TaskCanceledException ex)
Console.Error.WriteLine("Canceled.");
else
throw;
}
catch (Exception e)
{
Console.Error.WriteLine($"Error: {e.Message}");
#if SIXPIX_DEBUG
Console.Error.WriteLine(e.StackTrace);
#endif
}
// Re-enable cursor
Console.WriteLine(Sixel.ESC + Sixel.CursorOn);
}
else
{
if (fileInfo.Extension is not ".six" and not ".sixel" and not ".txt" and not ".out")
Console.WriteLine("Unknown filetype, attempting to decode from Sixel string ...");
if (string.IsNullOrEmpty(outfile))
{
Console.Error.WriteLine("Error: No output filename provided. Required for Sixel decoding.");
PrintUsage();
Environment.Exit(1);
}
if (!outfile.Contains('.'))
outfile += ".six";
var start = DateTime.Now;
// Decode: Sixel stream -> Image<Rgba32>
try
{
using var fs = fileInfo.OpenRead();
using var image = Sixel.Decode(fs);
#if SIXPIX_DEBUG
var elapsed = DateTime.Now - start;
Console.WriteLine($"Elapsed {elapsed.TotalMilliseconds} ms");
#endif
if (!string.IsNullOrEmpty(outfile))
{
// Save image to a file as png
if (!outfile.Contains('.'))
outfile += ".png";
using var wf = new FileStream(outfile, FileMode.Create);
Console.WriteLine($"Writing to file {wf.Name} ...");
image.Save(wf, new PngEncoder());
}
}
catch (Exception e)
{
Console.Error.WriteLine($"Error: {e.Message}");
#if SIXPIX_DEBUG
Console.Error.WriteLine(e.StackTrace);
#endif
}
}
Environment.Exit(0);
static bool IsBinary(string filePath)
{
int numNul = 0;
using var sr = new StreamReader(filePath);
for (var i = 0; i < 8000; i++)
{
if (sr.EndOfStream)
return false;
if ((char)sr.Read() == '\0')
{
numNul++;
if (numNul >= 1)
return true;
}
else
numNul = 0;
}
return false;
}
static void PrintUsage()
{
Console.WriteLine(MAP8_SIXEL);
if (Sixel.IsSupported())
{
var cellSize = Sixel.GetCellSize();
var windowCharSize = Sixel.GetWindowCharSize();
var windowPixelSize = Sixel.GetWindowPixelSize();
Console.WriteLine($"Sixel is supported!");
Console.WriteLine($"Background:#{Sixel.BackgroundColor}; " +
$"Sync Output:{Sixel.IsSyncSupported()}; " +
$"Cell Size:{cellSize.Width}x{cellSize.Height}; " +
$"Current Window:{windowPixelSize.Width}x{windowPixelSize.Height}px, " +
$"{windowCharSize.Width}x{windowCharSize.Height}ch");
}
else
Console.WriteLine("If you see colored bands above, your terminal supports Sixel.");
Console.WriteLine();
//----------------|---------10--------20--------30--------40--------50--------60--------70--------80
//----------------|123456789|123456789|123456789|123456789|123456789|123456789|123456789|123456789|
Console.WriteLine("Encoding usage:");
Console.WriteLine(" SixPix.exe [params] <in> [<out>]");
Console.WriteLine(" /t : Disable transparency, or enable when animating (optional)");
Console.WriteLine(" /T : Make color at top-left (x=0,y=0) transparent (optional)");
Console.WriteLine(" /b : Make GIF or WebP background color transparent (optional)");
Console.WriteLine(" /c:<Color> : Specify a background color in hexadecimal (RRGGBB) (optional)");
Console.WriteLine(" /w:<Width> : Width in pixels (optional)");
Console.WriteLine(" /h:<Height> : Height in pixels (optional)");
Console.WriteLine(" /a : Animate the frames of a multi-frame image (optional),");
Console.WriteLine(" With <out> specified, encode all frames and append frame number");
Console.WriteLine(" /A : Animate forever (optional), press 'Ctrl+c' or 'q' to stop");
Console.WriteLine(" /f:<Frame> : Display a single frame of a multi-frame image (optional)");
Console.WriteLine(" /d:<Delay> : Animation delay (in milliseconds)");
#if IMAGESHARP4 // ImageSharp v4.0 adds support for CUR and ICO files
Console.WriteLine(" <in> : Image filename to encode to Sixel (required), supports BMP, CUR,");
Console.WriteLine(" GIF, ICO, JPEG, PBM, PNG, QOI, TGA, TIFF, and WebP");
#else
Console.WriteLine(" <in> : Image filename to encode to Sixel (required), supports BMP, GIF,");
Console.WriteLine(" JPEG, PBM, PNG, QOI, TGA, TIFF, and WebP");
#endif
Console.WriteLine(" <out>[.six] : Output Sixel text filename (optional), otherwise display image(s)");
Console.WriteLine();
Console.WriteLine("Decoding usage:");
Console.WriteLine(" SixPix.exe <in> <out>");
Console.WriteLine(" <in> : Sixel text file to decode (required)");
Console.WriteLine(" <out>[.png] : Output PNG image filename (required)");
Console.WriteLine();
Console.WriteLine("Informational usage:");
Console.WriteLine(" SixPix.exe /g <in>");
Console.WriteLine(" /g : Get image data (required), return code is number of frames");
Console.WriteLine(" <in> : Image filename to read (required)");
Console.WriteLine();
}