Repository navigation
Expand file tree
/
Copy pathJpegDecoderCore.cs
More file actions
1665 lines (1405 loc) · 60.9 KB
/
Copy pathJpegDecoderCore.cs
File metadata and controls
1665 lines (1405 loc) · 60.9 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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
#nullable disable
using System.Buffers;
using System.Buffers.Binary;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using SixLabors.ImageSharp.Common.Helpers;
using SixLabors.ImageSharp.Formats.Jpeg.Components;
using SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder;
using SixLabors.ImageSharp.IO;
using SixLabors.ImageSharp.Memory;
using SixLabors.ImageSharp.Metadata;
using SixLabors.ImageSharp.Metadata.Profiles.Exif;
using SixLabors.ImageSharp.Metadata.Profiles.Icc;
using SixLabors.ImageSharp.Metadata.Profiles.Iptc;
using SixLabors.ImageSharp.Metadata.Profiles.Xmp;
namespace SixLabors.ImageSharp.Formats.Jpeg;
/// <summary>
/// Performs the jpeg decoding operation.
/// Originally ported from <see href="https://github.com/mozilla/pdf.js/blob/master/src/core/jpg.js"/>
/// with additional fixes for both performance and common encoding errors.
/// </summary>
internal sealed class JpegDecoderCore : ImageDecoderCore, IRawJpegData
{
/// <summary>
/// Whether the image has an EXIF marker.
/// </summary>
private bool hasExif;
/// <summary>
/// Contains exif data.
/// </summary>
private byte[] exifData;
/// <summary>
/// Whether the image has an ICC marker.
/// </summary>
private bool hasIcc;
/// <summary>
/// Contains ICC data.
/// </summary>
private byte[] iccData;
/// <summary>
/// Whether the image has a IPTC data.
/// </summary>
private bool hasIptc;
/// <summary>
/// Contains IPTC data.
/// </summary>
private byte[] iptcData;
/// <summary>
/// Whether the image has a XMP data.
/// </summary>
private bool hasXmp;
/// <summary>
/// Contains XMP data.
/// </summary>
private byte[] xmpData;
/// <summary>
/// Whether the image has a APP14 adobe marker. This is needed to determine image encoded colorspace.
/// </summary>
private bool hasAdobeMarker;
/// <summary>
/// Whether the image has a SOS marker.
/// </summary>
private bool hasSOSMarker;
/// <summary>
/// Contains information about the JFIF marker.
/// </summary>
private JFifMarker jFif;
/// <summary>
/// Contains information about the Adobe marker.
/// </summary>
private AdobeMarker adobe;
/// <summary>
/// Scan decoder.
/// </summary>
private IJpegScanDecoder scanDecoder;
/// <summary>
/// The arithmetic decoding tables.
/// </summary>
private List<ArithmeticDecodingTable> arithmeticDecodingTables;
/// <summary>
/// The restart interval.
/// </summary>
private int? resetInterval;
/// <summary>
/// The global configuration.
/// </summary>
private readonly Configuration configuration;
/// <summary>
/// Whether to skip metadata during decode.
/// </summary>
private readonly bool skipMetadata;
/// <summary>
/// The jpeg specific resize options.
/// </summary>
private readonly JpegDecoderResizeMode resizeMode;
/// <summary>
/// Initializes a new instance of the <see cref="JpegDecoderCore"/> class.
/// </summary>
/// <param name="options">The decoder options.</param>
/// <param name="iccProfile">The ICC profile to use for color conversion.</param>
public JpegDecoderCore(JpegDecoderOptions options, IccProfile iccProfile = null)
: base(options.GeneralOptions)
{
this.resizeMode = options.ResizeMode;
this.configuration = options.GeneralOptions.Configuration;
this.skipMetadata = options.GeneralOptions.SkipMetadata;
this.SetIccMetadata(iccProfile);
}
/// <summary>
/// Gets the only supported precisions
/// </summary>
// Refers to assembly's static data segment, no allocation occurs.
private static ReadOnlySpan<byte> SupportedPrecisions => [8, 12];
/// <summary>
/// Gets the frame
/// </summary>
public JpegFrame Frame { get; private set; }
/// <summary>
/// Gets the <see cref="ImageMetadata"/> decoded by this decoder instance.
/// </summary>
public ImageMetadata Metadata { get; private set; }
/// <inheritdoc/>
public JpegColorSpace ColorSpace { get; private set; }
/// <summary>
/// Gets the components.
/// </summary>
public JpegComponent[] Components => this.Frame.Components;
/// <inheritdoc/>
JpegComponent[] IRawJpegData.Components => this.Components;
/// <inheritdoc/>
public Block8x8F[] QuantizationTables { get; private set; }
/// <summary>
/// Finds the next file marker within the byte stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <returns>The <see cref="JpegFileMarker"/>.</returns>
public static JpegFileMarker FindNextFileMarker(BufferedReadStream stream)
{
while (true)
{
int b = stream.ReadByte();
if (b == -1)
{
return new JpegFileMarker(JpegConstants.Markers.EOI, stream.Length - 2);
}
// Found a marker.
if (b == JpegConstants.Markers.XFF)
{
while (b == JpegConstants.Markers.XFF)
{
// Loop here to discard any padding FF bytes on terminating marker.
b = stream.ReadByte();
if (b == -1)
{
return new JpegFileMarker(JpegConstants.Markers.EOI, stream.Length - 2);
}
}
// FF 00 is a stuffed data byte. RSTn and TEM have no length field (ITU T.81, Table B.1).
// Skip these standalone markers so the next marker's bytes are not read as a length.
if (b is not 0 and not JpegConstants.Markers.TEM and (< JpegConstants.Markers.RST0 or > JpegConstants.Markers.RST7))
{
return new JpegFileMarker((byte)(uint)b, stream.Position - 2);
}
}
}
}
/// <inheritdoc/>
protected override Image<TPixel> Decode<TPixel>(BufferedReadStream stream, CancellationToken cancellationToken)
{
using SpectralConverter<TPixel> spectralConverter = new(this.configuration, this.resizeMode == JpegDecoderResizeMode.ScaleOnly ? null : this.Options.TargetSize);
this.ParseStream(stream, spectralConverter, cancellationToken);
if (!this.hasSOSMarker)
{
JpegThrowHelper.ThrowInvalidImageContentException("Missing SOS marker.");
}
this.InitializeMetadataProfiles();
_ = this.Options.TryGetIccProfileForColorConversion(this.Metadata.IccProfile, out IccProfile profile);
return new Image<TPixel>(
this.configuration,
spectralConverter.GetPixelBuffer(profile, cancellationToken),
this.Metadata);
}
/// <inheritdoc/>
protected override ImageInfo Identify(BufferedReadStream stream, CancellationToken cancellationToken)
{
this.ParseStream(stream, spectralConverter: null, cancellationToken);
if (!this.hasSOSMarker)
{
JpegThrowHelper.ThrowInvalidImageContentException("Missing SOS marker.");
}
this.InitializeMetadataProfiles();
Size pixelSize = this.Frame.PixelSize;
return new ImageInfo(new Size(pixelSize.Width, pixelSize.Height), this.Metadata);
}
/// <summary>
/// Load quantization and/or Huffman tables for subsequent use for jpeg's embedded in tiff's,
/// so those tables do not need to be duplicated with segmented tiff's (tiff's with multiple strips).
/// </summary>
/// <param name="tableBytes">The table bytes.</param>
/// <param name="scanDecoder">The scan decoder.</param>
public void LoadTables(byte[] tableBytes, IJpegScanDecoder scanDecoder)
{
this.Metadata ??= new ImageMetadata();
this.QuantizationTables = new Block8x8F[4];
this.scanDecoder = scanDecoder;
if (tableBytes.Length < 4)
{
JpegThrowHelper.ThrowInvalidImageContentException("Not enough data to read marker");
}
using MemoryStream ms = new(tableBytes);
using BufferedReadStream stream = new(this.configuration, ms);
Span<byte> markerBuffer = stackalloc byte[2];
// Check for the Start Of Image marker.
int bytesRead = stream.Read(markerBuffer);
JpegFileMarker fileMarker = new(markerBuffer[1], 0);
if (fileMarker.Marker != JpegConstants.Markers.SOI)
{
JpegThrowHelper.ThrowInvalidImageContentException("Missing SOI marker.");
}
// Read next marker.
bytesRead = stream.Read(markerBuffer);
fileMarker = new JpegFileMarker(markerBuffer[1], (int)stream.Position - 2);
while (fileMarker.Marker != JpegConstants.Markers.EOI || (fileMarker.Marker == JpegConstants.Markers.EOI && fileMarker.Invalid))
{
if (!fileMarker.Invalid)
{
// Get the marker length.
int markerContentByteSize = ReadUint16(stream, markerBuffer) - 2;
// Validate the entire segment before parsing it. Casting directly
// to ulong also rejects lengths smaller than the two-byte length field.
if (!stream.IsReadRangeValid(stream.Position, (ulong)markerContentByteSize))
{
JpegThrowHelper.ThrowNotEnoughBytesForMarker(fileMarker.Marker);
}
switch (fileMarker.Marker)
{
case JpegConstants.Markers.SOI:
case JpegConstants.Markers.RST0:
case JpegConstants.Markers.RST7:
break;
case JpegConstants.Markers.DHT:
this.ProcessDefineHuffmanTablesMarker(stream, markerContentByteSize);
break;
case JpegConstants.Markers.DQT:
this.ProcessDefineQuantizationTablesMarker(stream, markerContentByteSize);
break;
case JpegConstants.Markers.DRI:
this.ProcessDefineRestartIntervalMarker(stream, markerContentByteSize, markerBuffer);
break;
case JpegConstants.Markers.EOI:
return;
}
}
// Read next marker.
bytesRead = stream.Read(markerBuffer);
if (bytesRead != 2)
{
JpegThrowHelper.ThrowInvalidImageContentException("Not enough data to read marker");
}
fileMarker = new JpegFileMarker(markerBuffer[1], 0);
}
}
/// <summary>
/// Parses the input stream for file markers.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="spectralConverter">The spectral converter to use.</param>
/// <param name="cancellationToken">The token to monitor cancellation.</param>
internal void ParseStream(BufferedReadStream stream, SpectralConverter spectralConverter, CancellationToken cancellationToken)
{
bool metadataOnly = spectralConverter == null;
this.scanDecoder ??= new HuffmanScanDecoder(stream, spectralConverter, cancellationToken);
// Apply the image-data policy to the active decoder, including one supplied by TIFF.
this.scanDecoder.SegmentIntegrityHandling = this.Options.SegmentIntegrityHandling;
this.Metadata ??= new ImageMetadata();
Span<byte> markerBuffer = stackalloc byte[2];
// Check for the Start Of Image marker.
stream.Read(markerBuffer);
JpegFileMarker fileMarker = new(markerBuffer[1], 0);
if (fileMarker.Marker != JpegConstants.Markers.SOI)
{
JpegThrowHelper.ThrowInvalidImageContentException("Missing SOI marker.");
}
fileMarker = FindNextFileMarker(stream);
this.QuantizationTables ??= new Block8x8F[4];
// Break only when we discover a valid EOI marker.
// https://github.com/SixLabors/ImageSharp/issues/695
while (fileMarker.Marker != JpegConstants.Markers.EOI)
{
cancellationToken.ThrowIfCancellationRequested();
if (!fileMarker.Invalid)
{
// Get the marker length.
int markerContentByteSize = ReadUint16(stream, markerBuffer) - 2;
// Validate the entire segment before parsing it. Casting directly
// to ulong also rejects lengths smaller than the two-byte length field.
if (!stream.IsReadRangeValid(stream.Position, (ulong)markerContentByteSize))
{
if (metadataOnly && this.Metadata != null && this.Frame != null)
{
// We have enough data to decode the image, so we can stop parsing.
return;
}
if (this.Metadata != null && this.Frame != null && spectralConverter.HasPixelBuffer())
{
// We have enough data to decode the image, so we can stop parsing.
return;
}
JpegThrowHelper.ThrowNotEnoughBytesForMarker(fileMarker.Marker);
}
switch (fileMarker.Marker)
{
case JpegConstants.Markers.SOF0:
case JpegConstants.Markers.SOF1:
case JpegConstants.Markers.SOF2:
if (!this.ProcessStartOfFrameMarker(stream, markerContentByteSize, fileMarker, ComponentType.Huffman, metadataOnly))
{
return;
}
break;
case JpegConstants.Markers.SOF9:
case JpegConstants.Markers.SOF10:
case JpegConstants.Markers.SOF13:
case JpegConstants.Markers.SOF14:
this.scanDecoder = new ArithmeticScanDecoder(stream, spectralConverter, cancellationToken)
{
SegmentIntegrityHandling = this.Options.SegmentIntegrityHandling
};
if (this.resetInterval.HasValue)
{
this.scanDecoder.ResetInterval = this.resetInterval.Value;
}
if (!this.ProcessStartOfFrameMarker(stream, markerContentByteSize, fileMarker, ComponentType.Arithmetic, metadataOnly))
{
return;
}
break;
case JpegConstants.Markers.SOF5:
JpegThrowHelper.ThrowNotSupportedException("Decoding jpeg files with differential sequential DCT is not supported.");
break;
case JpegConstants.Markers.SOF6:
JpegThrowHelper.ThrowNotSupportedException("Decoding jpeg files with differential progressive DCT is not supported.");
break;
case JpegConstants.Markers.SOF3:
case JpegConstants.Markers.SOF7:
JpegThrowHelper.ThrowNotSupportedException("Decoding lossless jpeg files is not supported.");
break;
case JpegConstants.Markers.SOF11:
case JpegConstants.Markers.SOF15:
JpegThrowHelper.ThrowNotSupportedException("Decoding jpeg files with lossless arithmetic coding is not supported.");
break;
case JpegConstants.Markers.SOS:
this.hasSOSMarker = true;
if (!metadataOnly)
{
this.ProcessStartOfScanMarker(stream, markerContentByteSize);
break;
}
// It's highly unlikely that APPn related data will be found after the SOS marker
// So we can stop parsing here and return the metadata we have parsed so far, instead
// of trying to parse any APPn markers after the SOS marker and risking running out of
// memory or other exceptions.
return;
case JpegConstants.Markers.DHT:
if (metadataOnly)
{
stream.Skip(markerContentByteSize);
}
else
{
this.ProcessDefineHuffmanTablesMarker(stream, markerContentByteSize);
}
break;
case JpegConstants.Markers.DQT:
this.ProcessDefineQuantizationTablesMarker(stream, markerContentByteSize);
break;
case JpegConstants.Markers.DRI:
if (metadataOnly)
{
stream.Skip(markerContentByteSize);
}
else
{
this.ProcessDefineRestartIntervalMarker(stream, markerContentByteSize, markerBuffer);
}
break;
case JpegConstants.Markers.APP0:
this.ProcessApplicationHeaderMarker(stream, markerContentByteSize);
break;
case JpegConstants.Markers.APP1:
this.ProcessApp1Marker(stream, markerContentByteSize);
break;
case JpegConstants.Markers.APP2:
this.ProcessApp2Marker(stream, markerContentByteSize);
break;
case JpegConstants.Markers.APP3:
case JpegConstants.Markers.APP4:
case JpegConstants.Markers.APP5:
case JpegConstants.Markers.APP6:
case JpegConstants.Markers.APP7:
case JpegConstants.Markers.APP8:
case JpegConstants.Markers.APP9:
case JpegConstants.Markers.APP10:
case JpegConstants.Markers.APP11:
case JpegConstants.Markers.APP12:
stream.Skip(markerContentByteSize);
break;
case JpegConstants.Markers.APP13:
this.ProcessApp13Marker(stream, markerContentByteSize);
break;
case JpegConstants.Markers.APP14:
this.ProcessApp14Marker(stream, markerContentByteSize);
break;
case JpegConstants.Markers.APP15:
stream.Skip(markerContentByteSize);
break;
case JpegConstants.Markers.COM:
this.ProcessComMarker(stream, markerContentByteSize);
break;
case JpegConstants.Markers.DAC:
if (metadataOnly)
{
stream.Skip(markerContentByteSize);
}
else
{
this.ProcessArithmeticTable(stream, markerContentByteSize);
}
break;
}
}
// Read on.
fileMarker = FindNextFileMarker(stream);
}
if (!metadataOnly && this.Frame is null)
{
JpegThrowHelper.ThrowInvalidImageContentException("No readable SOFn (Start Of Frame) marker found.");
}
this.Metadata.GetJpegMetadata().Interleaved = this.Frame.Interleaved;
}
/// <inheritdoc/>
public void Dispose()
{
this.Frame?.Dispose();
// Set large fields to null.
this.Frame = null;
this.scanDecoder = null;
}
/// <summary>
/// Assigns COM marker bytes to comment property
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="markerContentByteSize">The remaining bytes in the segment block.</param>
private void ProcessComMarker(BufferedReadStream stream, int markerContentByteSize)
{
char[] chars = new char[markerContentByteSize];
JpegMetadata metadata = this.Metadata.GetFormatMetadata(JpegFormat.Instance);
for (int i = 0; i < markerContentByteSize; i++)
{
int read = stream.ReadByte();
chars[i] = (char)read;
}
metadata.Comments.Add(new JpegComData(chars));
}
/// <summary>
/// Returns encoded colorspace based on the adobe APP14 marker.
/// </summary>
/// <param name="componentCount">Number of components.</param>
/// <param name="adobeMarker">Parsed adobe APP14 marker.</param>
/// <returns>The <see cref="JpegColorSpace"/></returns>
internal static JpegColorSpace DeduceJpegColorSpace(byte componentCount, ref AdobeMarker adobeMarker)
{
if (componentCount == 1)
{
return JpegColorSpace.Grayscale;
}
if (componentCount == 3)
{
if (adobeMarker.ColorTransform == JpegConstants.Adobe.ColorTransformUnknown)
{
return JpegColorSpace.RGB;
}
return JpegColorSpace.YCbCr;
}
if (componentCount == 4)
{
if (adobeMarker.ColorTransform == JpegConstants.Adobe.ColorTransformYcck)
{
return JpegColorSpace.Ycck;
}
return JpegColorSpace.Cmyk;
}
JpegThrowHelper.ThrowNotSupportedComponentCount(componentCount);
return default;
}
/// <summary>
/// Returns encoded colorspace based on the component count.
/// </summary>
/// <param name="componentCount">Number of components.</param>
/// <returns>The <see cref="JpegColorSpace"/></returns>
internal static JpegColorSpace DeduceJpegColorSpace(byte componentCount)
{
if (componentCount == 1)
{
return JpegColorSpace.Grayscale;
}
if (componentCount == 3)
{
return JpegColorSpace.YCbCr;
}
if (componentCount == 4)
{
return JpegColorSpace.Cmyk;
}
JpegThrowHelper.ThrowNotSupportedComponentCount(componentCount);
return default;
}
/// <summary>
/// Returns the jpeg color type based on the colorspace and subsampling used.
/// </summary>
/// <returns>Jpeg color type.</returns>
private JpegColorType DeduceJpegColorType()
{
switch (this.ColorSpace)
{
case JpegColorSpace.Grayscale:
return JpegColorType.Luminance;
case JpegColorSpace.RGB:
return JpegColorType.Rgb;
case JpegColorSpace.YCbCr:
if (this.Frame.Components[0].HorizontalSamplingFactor == 1 && this.Frame.Components[0].VerticalSamplingFactor == 1 &&
this.Frame.Components[1].HorizontalSamplingFactor == 1 && this.Frame.Components[1].VerticalSamplingFactor == 1 &&
this.Frame.Components[2].HorizontalSamplingFactor == 1 && this.Frame.Components[2].VerticalSamplingFactor == 1)
{
return JpegColorType.YCbCrRatio444;
}
else if (this.Frame.Components[0].HorizontalSamplingFactor == 2 && this.Frame.Components[0].VerticalSamplingFactor == 1 &&
this.Frame.Components[1].HorizontalSamplingFactor == 1 && this.Frame.Components[1].VerticalSamplingFactor == 1 &&
this.Frame.Components[2].HorizontalSamplingFactor == 1 && this.Frame.Components[2].VerticalSamplingFactor == 1)
{
return JpegColorType.YCbCrRatio422;
}
else if (this.Frame.Components[0].HorizontalSamplingFactor == 2 && this.Frame.Components[0].VerticalSamplingFactor == 2 &&
this.Frame.Components[1].HorizontalSamplingFactor == 1 && this.Frame.Components[1].VerticalSamplingFactor == 1 &&
this.Frame.Components[2].HorizontalSamplingFactor == 1 && this.Frame.Components[2].VerticalSamplingFactor == 1)
{
return JpegColorType.YCbCrRatio420;
}
else if (this.Frame.Components[0].HorizontalSamplingFactor == 4 && this.Frame.Components[0].VerticalSamplingFactor == 1 &&
this.Frame.Components[1].HorizontalSamplingFactor == 1 && this.Frame.Components[1].VerticalSamplingFactor == 1 &&
this.Frame.Components[2].HorizontalSamplingFactor == 1 && this.Frame.Components[2].VerticalSamplingFactor == 1)
{
return JpegColorType.YCbCrRatio411;
}
else if (this.Frame.Components[0].HorizontalSamplingFactor == 4 && this.Frame.Components[0].VerticalSamplingFactor == 2 &&
this.Frame.Components[1].HorizontalSamplingFactor == 1 && this.Frame.Components[1].VerticalSamplingFactor == 1 &&
this.Frame.Components[2].HorizontalSamplingFactor == 1 && this.Frame.Components[2].VerticalSamplingFactor == 1)
{
return JpegColorType.YCbCrRatio410;
}
else
{
return JpegColorType.YCbCrRatio420;
}
case JpegColorSpace.Cmyk:
return JpegColorType.Cmyk;
case JpegColorSpace.Ycck:
return JpegColorType.Ycck;
default:
return JpegColorType.YCbCrRatio420;
}
}
/// <summary>
/// Initializes the EXIF profile.
/// </summary>
private void InitExifProfile()
{
if (this.hasExif)
{
this.Metadata.ExifProfile = new ExifProfile(this.exifData);
}
}
/// <summary>
/// Initializes the ICC profile.
/// </summary>
private void InitIccProfile()
{
if (this.hasIcc && this.Metadata.IccProfile == null)
{
IccProfile profile = new(this.iccData);
if (profile.CheckIsValid())
{
this.Metadata.IccProfile = profile;
}
else
{
throw new InvalidIccProfileException("Invalid ICC profile.");
}
}
}
private void SetIccMetadata(IccProfile profile)
{
if (!this.skipMetadata && profile?.CheckIsValid() == true)
{
this.hasIcc = true;
this.Metadata ??= new ImageMetadata();
this.Metadata.IccProfile = profile;
}
}
/// <summary>
/// Initializes the IPTC profile.
/// </summary>
private void InitIptcProfile()
{
if (this.hasIptc)
{
this.Metadata.IptcProfile = new IptcProfile(this.iptcData);
}
}
/// <summary>
/// Initializes the XMP profile.
/// </summary>
private void InitXmpProfile()
{
if (this.hasXmp)
{
this.Metadata.XmpProfile = new XmpProfile(this.xmpData);
}
}
/// <summary>
/// Assigns derived metadata properties to <see cref="Metadata"/>, eg. horizontal and vertical resolution if it has a JFIF header.
/// </summary>
private void InitDerivedMetadataProperties()
{
if (this.jFif.XDensity > 0 && this.jFif.YDensity > 0)
{
this.Metadata.HorizontalResolution = this.jFif.XDensity;
this.Metadata.VerticalResolution = this.jFif.YDensity;
this.Metadata.ResolutionUnits = this.jFif.DensityUnits;
}
else if (this.hasExif)
{
double horizontalValue = this.GetExifResolutionValue(ExifTag.XResolution);
double verticalValue = this.GetExifResolutionValue(ExifTag.YResolution);
if (horizontalValue > 0 && verticalValue > 0)
{
this.Metadata.HorizontalResolution = horizontalValue;
this.Metadata.VerticalResolution = verticalValue;
this.Metadata.ResolutionUnits = UnitConverter.ExifProfileToResolutionUnit(this.Metadata.ExifProfile);
}
}
}
private double GetExifResolutionValue(ExifTag<Rational> tag)
{
if (this.Metadata.ExifProfile.TryGetValue(tag, out IExifValue<Rational> resolution))
{
return resolution.Value.ToDouble();
}
return 0;
}
/// <summary>
/// Initializes decoded metadata profiles using the configured ancillary segment handling policy.
/// </summary>
private void InitializeMetadataProfiles()
{
this.ExecuteAncillarySegmentAction(this.InitExifProfile);
this.ExecuteAncillarySegmentAction(this.InitIccProfile);
this.ExecuteAncillarySegmentAction(this.InitIptcProfile);
this.ExecuteAncillarySegmentAction(this.InitXmpProfile);
this.ExecuteAncillarySegmentAction(this.InitDerivedMetadataProperties);
}
/// <summary>
/// Extends the profile with additional data.
/// </summary>
/// <param name="profile">The profile data array.</param>
/// <param name="extension">The array containing addition profile data.</param>
private static void ExtendProfile(ref byte[] profile, byte[] extension)
{
int currentLength = profile.Length;
Array.Resize(ref profile, currentLength + extension.Length);
Buffer.BlockCopy(extension, 0, profile, currentLength, extension.Length);
}
/// <summary>
/// Processes the application header containing the JFIF identifier plus extra data.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="remaining">The remaining bytes in the segment block.</param>
private void ProcessApplicationHeaderMarker(BufferedReadStream stream, int remaining)
{
// We can only decode JFif identifiers.
// Some images contain multiple JFIF markers (Issue 1932) so we check to see
// if it's already been read.
if (remaining < JFifMarker.Length)
{
this.ThrowOrIgnoreNonStrictSegmentError("Bad App0 Marker length.");
// Skip the application header length
stream.Skip(remaining);
return;
}
if (!this.jFif.Equals(default))
{
// Skip the application header length
stream.Skip(remaining);
return;
}
Span<byte> temp = stackalloc byte[2 * 16 * 4];
stream.Read(temp, 0, JFifMarker.Length);
if (!JFifMarker.TryParse(temp, out this.jFif))
{
this.ThrowOrIgnoreNonStrictSegmentError("Invalid App0 marker.");
}
remaining -= JFifMarker.Length;
// TODO: thumbnail
if (remaining > 0)
{
if (!stream.IsReadRangeValid(stream.Position, (ulong)remaining + 1))
{
this.ThrowOrIgnoreNonStrictSegmentError("Bad App0 Marker length.");
stream.Skip(remaining);
return;
}
stream.Skip(remaining);
}
}
/// <summary>
/// Processes the App1 marker retrieving any stored metadata.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="remaining">The remaining bytes in the segment block.</param>
private void ProcessApp1Marker(BufferedReadStream stream, int remaining)
{
const int exifMarkerLength = 6;
const int xmpMarkerLength = 29;
if (remaining < exifMarkerLength)
{
this.ThrowOrIgnoreNonStrictSegmentError("Bad App1 Marker length.");
// Skip the application header length.
stream.Skip(remaining);
return;
}
if (this.skipMetadata)
{
// Skip the application header length.
stream.Skip(remaining);
return;
}
if (!stream.IsReadRangeValid(stream.Position, (ulong)remaining + 1))
{
this.ThrowOrIgnoreNonStrictSegmentError("Bad App1 Marker length.");
stream.Skip(remaining);
return;
}
Span<byte> temp = stackalloc byte[2 * 16 * 4];
// XMP marker is the longer then the EXIF marker, so first try read the EXIF marker bytes.
stream.Read(temp, 0, exifMarkerLength);
remaining -= exifMarkerLength;
if (ProfileResolver.IsProfile(temp, ProfileResolver.ExifMarker))
{
this.hasExif = true;
byte[] profile = new byte[remaining];
stream.Read(profile, 0, remaining);
if (this.exifData is null)
{
this.exifData = profile;
}
else
{
// If the EXIF information exceeds 64K, it will be split over multiple APP1 markers.
ExtendProfile(ref this.exifData, profile);
}
remaining = 0;
}
if (ProfileResolver.IsProfile(temp, ProfileResolver.XmpMarker[..exifMarkerLength]))
{
const int remainingXmpMarkerBytes = xmpMarkerLength - exifMarkerLength;
if (remaining < remainingXmpMarkerBytes)
{
this.ThrowOrIgnoreNonStrictSegmentError("Bad App1 Marker length.");
// Skip the application header length.
stream.Skip(remaining);
return;
}
stream.Read(temp, exifMarkerLength, remainingXmpMarkerBytes);
remaining -= remainingXmpMarkerBytes;
if (ProfileResolver.IsProfile(temp, ProfileResolver.XmpMarker))
{
this.hasXmp = true;
byte[] profile = new byte[remaining];
stream.Read(profile, 0, remaining);
if (this.xmpData is null)
{
this.xmpData = profile;
}
else
{
// If the XMP information exceeds 64K, it will be split over multiple APP1 markers.
ExtendProfile(ref this.xmpData, profile);
}
remaining = 0;
}
else
{
this.ThrowOrIgnoreNonStrictSegmentError("Invalid App1 marker.");
}
}
// Skip over any remaining bytes of this header.
stream.Skip(remaining);
}
/// <summary>
/// Processes the App2 marker retrieving any stored ICC profile information
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="remaining">The remaining bytes in the segment block.</param>
private void ProcessApp2Marker(BufferedReadStream stream, int remaining)
{
// Length is 14 though we only need to check 12.
const int icclength = 14;
if (remaining < icclength)
{
this.ThrowOrIgnoreNonStrictSegmentError("Bad App2 Marker length.");
stream.Skip(remaining);
return;
}
if (this.skipMetadata)
{
stream.Skip(remaining);
return;
}
Span<byte> identifier = stackalloc byte[icclength];
stream.Read(identifier);
remaining -= icclength; // We have read it by this point
if (ProfileResolver.IsProfile(identifier, ProfileResolver.IccMarker))
{
this.hasIcc = true;
byte[] profile = new byte[remaining];
stream.Read(profile, 0, remaining);
if (this.iccData is null)
{
this.iccData = profile;
}
else
{
// If the ICC information exceeds 64K, it will be split over multiple APP2 markers
ExtendProfile(ref this.iccData, profile);