2 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the License);
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an AS IS BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 using System.Collections.Generic;
19 using System.Diagnostics;
22 using System.Runtime.InteropServices;
23 using System.Threading.Tasks;
25 using static Interop.Decode;
27 namespace Tizen.Multimedia.Util
30 /// This is a base class for image decoders.
32 public abstract class ImageDecoder : IDisposable
34 private ImageDecoderHandle _handle;
36 private ColorSpace? _colorSpace;
38 internal ImageDecoder(ImageFormat format)
40 Create(out _handle).ThrowIfFailed("Failed to create ImageDecoder");
42 Debug.Assert(_handle != null);
48 /// Gets the image format of this decoder.
50 public ImageFormat InputFormat { get; }
52 private ImageDecoderHandle Handle
56 if (_handle.IsInvalid)
58 throw new ObjectDisposedException(nameof(ImageDecoder));
65 /// Sets the color-space to decode into. The default is <see cref="ColorSpace.Rgba8888"/>.
67 /// <param name="colorSpace">The value indicating color-space to decode into.</param>
68 /// <exception cref="ArgumentException"><paramref name="colorSpace"/> is invalid.</exception>
69 /// <exception cref="NotSupportedException"><paramref name="colorSpace"/> is not supported by the decoder.</exception>
70 /// <seealso cref="ImageUtil.GetSupportedColorSpaces(ImageFormat)"/>
71 public void SetColorSpace(ColorSpace colorSpace)
73 ValidationUtil.ValidateEnum(typeof(ColorSpace), colorSpace, nameof(ColorSpace));
75 if (ImageUtil.GetSupportedColorSpaces(InputFormat).Contains(colorSpace) == false)
77 throw new NotSupportedException($"{colorSpace.ToString()} is not supported for {InputFormat}.");
80 _colorSpace = colorSpace;
84 /// Decodes an image from the specified file.
86 /// <param name="inputFilePath">The input file path from which to decode.</param>
87 /// <returns>A task that represents the asynchronous decoding operation.</returns>
89 /// Only Graphics Interchange Format(GIF) codec returns more than one frame.\n
91 /// http://tizen.org/privilege/mediastorage is needed if <paramref name="inputFilePath"/> is relevant to the media storage.\n
92 /// http://tizen.org/privilege/externalstorage is needed if <paramref name="inputFilePath"/> is relevant to the external storage.
94 /// <exception cref="ArgumentNullException"><paramref name="inputFilePath"/> is null.</exception>
95 /// <exception cref="ArgumentException">
96 /// <paramref name="inputFilePath"/> is an empty string.\n
98 /// <paramref name="inputFilePath"/> is not a image file.\n
100 /// The format of <paramref name="inputFilePath"/> is not <see cref="InputFormat"/>.
102 /// <exception cref="FileNotFoundException"><paramref name="inputFilePath"/> does not exists.</exception>
103 /// <exception cref="UnauthorizedAccessException">The caller does not have required permission to access the path.</exception>
104 /// <exception cref="FileFormatException">The format of <paramref name="inputFilePath"/> is not <see cref="InputFormat"/>.</exception>
105 /// <exception cref="ObjectDisposedException">The <see cref="ImageDecoder"/> has already been disposed of.</exception>
106 public async Task<IEnumerable<BitmapFrame>> DecodeAsync(string inputFilePath)
108 if (inputFilePath == null)
110 throw new ArgumentNullException(nameof(inputFilePath));
113 if (inputFilePath.Length == 0)
115 throw new ArgumentException("path is empty.", nameof(inputFilePath));
118 if (CheckHeader(inputFilePath) == false)
120 throw new FileFormatException("The file has an invalid header.");
123 var pathPtr = Marshal.StringToHGlobalAnsi(inputFilePath);
127 SetInputPath(Handle, pathPtr).ThrowIfFailed("Failed to set input file path for decoding");
128 return await DecodeAsync();
132 Marshal.FreeHGlobal(pathPtr);
137 /// Decodes an image from the buffer.
139 /// <param name="inputBuffer">The image buffer from which to decode.</param>
140 /// <returns>A task that represents the asynchronous decoding operation.</returns>
142 /// Only Graphics Interchange Format(GIF) codec returns more than one frame.\n
144 /// <exception cref="ArgumentNullException"><paramref name="inputBuffer"/> is null.</exception>
145 /// <exception cref="ArgumentException">
146 /// <paramref name="inputBuffer"/> is an empty array.\n
148 /// The format of <paramref name="inputBuffer"/> is not <see cref="InputFormat"/>.
150 /// <exception cref="FileFormatException">The format of <paramref name="inputBuffer"/> is not <see cref="InputFormat"/>.</exception>
151 /// <exception cref="ObjectDisposedException">The <see cref="ImageDecoder"/> has already been disposed of.</exception>
152 public Task<IEnumerable<BitmapFrame>> DecodeAsync(byte[] inputBuffer)
154 if (inputBuffer == null)
156 throw new ArgumentNullException(nameof(inputBuffer));
159 if (inputBuffer.Length == 0)
161 throw new ArgumentException("buffer is empty.", nameof(inputBuffer));
164 if (CheckHeader(inputBuffer) == false)
166 throw new FileFormatException("buffer has an invalid header.");
169 SetInputBuffer(Handle, inputBuffer, (ulong)inputBuffer.Length).
170 ThrowIfFailed("Failed to set input buffer for decoding");
172 return DecodeAsync();
175 private bool CheckHeader(byte[] input)
177 if (input.Length < Header.Length)
182 for (int i = 0; i < Header.Length; ++i)
184 if (input[i] != Header[i])
193 private bool CheckHeader(string inputFile)
195 using (var fs = File.OpenRead(inputFile))
197 byte[] fileHeader = new byte[Header.Length];
199 if (fs.Read(fileHeader, 0, fileHeader.Length) < Header.Length)
203 return CheckHeader(fileHeader);
207 internal Task<IEnumerable<BitmapFrame>> DecodeAsync()
211 IntPtr outBuffer = IntPtr.Zero;
212 SetOutputBuffer(Handle, out outBuffer).ThrowIfFailed("Failed to decode given image");
214 var tcs = new TaskCompletionSource<IEnumerable<BitmapFrame>>();
223 DecodeRun(Handle, out width, out height, out size).ThrowIfFailed("Failed to decode");
225 tcs.SetResult(new[] { new BitmapFrame(outBuffer, width, height, (int)size) });
229 tcs.TrySetException(e);
233 LibcSupport.Free(outBuffer);
240 internal virtual void Initialize(ImageDecoderHandle handle)
242 if (_colorSpace.HasValue)
244 SetColorspace(Handle, _colorSpace.Value.ToImageColorSpace()).ThrowIfFailed("Failed to set color space");
248 internal abstract byte[] Header { get; }
250 #region IDisposable Support
251 private bool _disposed = false;
254 /// Releases the unmanaged resources used by the ImageDecoder.
256 /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
257 protected virtual void Dispose(bool disposing)
270 /// Releases all resources used by the ImageDecoder.
272 public void Dispose()
280 /// Provides the ability to decode Bitmap (BMP) encoded images.
282 public class BmpDecoder : ImageDecoder
284 private static readonly byte[] _header = { (byte)'B', (byte)'M' };
287 /// Initializes a new instance of the <see cref="BmpDecoder"/> class.
289 /// <remarks><see cref="ImageDecoder.InputFormat"/> will be the <see cref="ImageFormat.Bmp"/>.</remarks>
290 public BmpDecoder() : base(ImageFormat.Bmp)
294 internal override byte[] Header => _header;
298 /// Provides the ability to decode the Portable Network Graphics (PNG) encoded images.
300 public class PngDecoder : ImageDecoder
302 private static readonly byte[] _header = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };
305 /// Initializes a new instance of the <see cref="PngDecoder"/> class.
307 /// <remarks><see cref="ImageDecoder.InputFormat"/> will be the <see cref="ImageFormat.Png"/>.</remarks>
308 public PngDecoder() : base(ImageFormat.Png)
312 internal override byte[] Header => _header;
316 /// Provides the ability to decode the Joint Photographic Experts Group (JPEG) encoded images.
318 public class JpegDecoder : ImageDecoder
320 private static readonly byte[] _header = { 0xFF, 0xD8 };
323 /// A read-only field that represents the default value of <see cref="Downscale"/>.
325 public static readonly JpegDownscale DefaultJpegDownscale = JpegDownscale.None;
327 private JpegDownscale _jpegDownscale = DefaultJpegDownscale;
330 /// Initializes a new instance of the <see cref="JpegDecoder"/> class.
332 /// <remarks><see cref="ImageDecoder.InputFormat"/> will be the <see cref="ImageFormat.Jpeg"/>.</remarks>
333 public JpegDecoder() : base(ImageFormat.Jpeg)
338 /// Gets or sets the downscale at which the jpeg image should be decoded.
340 /// <exception cref="ArgumentException"><paramref name="value"/> is invalid.</exception>
341 public JpegDownscale Downscale
345 return _jpegDownscale;
349 ValidationUtil.ValidateEnum(typeof(JpegDownscale), value, nameof(Downscale));
351 _jpegDownscale = value;
355 internal override void Initialize(ImageDecoderHandle handle)
357 base.Initialize(handle);
359 SetJpegDownscale(handle, Downscale).ThrowIfFailed("Failed to set downscale for decoding");
362 internal override byte[] Header => _header;
366 /// Provides the ability to decode the Graphics Interchange Format (GIF) encoded images.
368 public class GifDecoder : ImageDecoder
370 private static readonly byte[] _header = { (byte)'G', (byte)'I', (byte)'F' };
373 /// Initializes a new instance of the <see cref="GifDecoder"/> class.
375 /// <remarks><see cref="ImageDecoder.InputFormat"/> will be the <see cref="ImageFormat.Gif"/>.</remarks>
376 public GifDecoder() : base(ImageFormat.Gif)
380 internal override byte[] Header => _header;