43b69ad5384d2fb75947e6b9b5820330954a9094
[platform/core/csapi/tizenfx.git] / src / Tizen.Multimedia.Util / ImageUtil / ImageDecoder.cs
1 /*
2  * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 using System;
18 using System.Collections.Generic;
19 using System.Diagnostics;
20 using System.IO;
21 using System.Linq;
22 using System.Runtime.InteropServices;
23 using System.Threading.Tasks;
24 using static Interop;
25 using static Interop.Decode;
26
27 namespace Tizen.Multimedia.Util
28 {
29     /// <summary>
30     /// This is a base class for image decoders.
31     /// </summary>
32     /// <since_tizen> 4 </since_tizen>
33     public abstract class ImageDecoder : IDisposable
34     {
35         private ImageDecoderHandle _handle;
36
37         private ColorSpace? _colorSpace;
38
39         internal ImageDecoder(ImageFormat format)
40         {
41             Create(out _handle).ThrowIfFailed("Failed to create ImageDecoder");
42
43             Debug.Assert(_handle != null);
44
45             InputFormat = format;
46         }
47
48         /// <summary>
49         /// Gets the image format of this decoder.
50         /// </summary>
51         /// <since_tizen> 4 </since_tizen>
52         public ImageFormat InputFormat { get; }
53
54         private ImageDecoderHandle Handle
55         {
56             get
57             {
58                 if (_handle.IsInvalid)
59                 {
60                     throw new ObjectDisposedException(nameof(ImageDecoder));
61                 }
62                 return _handle;
63             }
64         }
65
66         /// <summary>
67         /// Sets the color-space to decode into. The default is <see cref="ColorSpace.Rgba8888"/>.
68         /// </summary>
69         /// <param name="colorSpace">The value indicating color-space to decode into.</param>
70         /// <exception cref="ArgumentException"><paramref name="colorSpace"/> is invalid.</exception>
71         /// <exception cref="NotSupportedException"><paramref name="colorSpace"/> is not supported by the decoder.</exception>
72         /// <seealso cref="ImageUtil.GetSupportedColorSpaces(ImageFormat)"/>
73         /// <since_tizen> 4 </since_tizen>
74         public void SetColorSpace(ColorSpace colorSpace)
75         {
76             ValidationUtil.ValidateEnum(typeof(ColorSpace), colorSpace, nameof(ColorSpace));
77
78             if (ImageUtil.GetSupportedColorSpaces(InputFormat).Contains(colorSpace) == false)
79             {
80                 throw new NotSupportedException($"{colorSpace.ToString()} is not supported for {InputFormat}.");
81             }
82
83             _colorSpace = colorSpace;
84         }
85
86         /// <summary>
87         /// Decodes an image from the specified file.
88         /// </summary>
89         /// <param name="inputFilePath">The input file path from which to decode.</param>
90         /// <returns>A task that represents the asynchronous decoding operation.</returns>
91         /// <remarks>
92         ///     Only Graphics Interchange Format(GIF) codec returns more than one frame.<br/>
93         ///     <br/>
94         ///     http://tizen.org/privilege/mediastorage is needed if <paramref name="inputFilePath"/> is relevant to the media storage.<br/>
95         ///     http://tizen.org/privilege/externalstorage is needed if <paramref name="inputFilePath"/> is relevant to the external storage.
96         /// </remarks>
97         /// <exception cref="ArgumentNullException"><paramref name="inputFilePath"/> is null.</exception>
98         /// <exception cref="ArgumentException">
99         ///     <paramref name="inputFilePath"/> is an empty string.<br/>
100         ///     -or-<br/>
101         ///     <paramref name="inputFilePath"/> is not a image file.
102         /// </exception>
103         /// <exception cref="FileNotFoundException"><paramref name="inputFilePath"/> does not exists.</exception>
104         /// <exception cref="UnauthorizedAccessException">The caller does not have required permission to access the path.</exception>
105         /// <exception cref="FileFormatException">The format of <paramref name="inputFilePath"/> is not <see cref="InputFormat"/>.</exception>
106         /// <exception cref="ObjectDisposedException">The <see cref="ImageDecoder"/> has already been disposed of.</exception>
107         /// <since_tizen> 4 </since_tizen>
108         public async Task<IEnumerable<BitmapFrame>> DecodeAsync(string inputFilePath)
109         {
110             if (inputFilePath == null)
111             {
112                 throw new ArgumentNullException(nameof(inputFilePath));
113             }
114
115             if (inputFilePath.Length == 0)
116             {
117                 throw new ArgumentException("path is empty.", nameof(inputFilePath));
118             }
119
120             if (CheckHeader(inputFilePath) == false)
121             {
122                 throw new FileFormatException("The file has an invalid header.");
123             }
124
125             var pathPtr = Marshal.StringToHGlobalAnsi(inputFilePath);
126             try
127             {
128
129                 SetInputPath(Handle, pathPtr).ThrowIfFailed("Failed to set input file path for decoding");
130                 return await DecodeAsync();
131             }
132             finally
133             {
134                 Marshal.FreeHGlobal(pathPtr);
135             }
136         }
137
138         /// <summary>
139         /// Decodes an image from the buffer.
140         /// </summary>
141         /// <param name="inputBuffer">The image buffer from which to decode.</param>
142         /// <returns>A task that represents the asynchronous decoding operation.</returns>
143         /// <remarks>Only Graphics Interchange Format(GIF) codec returns more than one frame.</remarks>
144         /// <exception cref="ArgumentNullException"><paramref name="inputBuffer"/> is null.</exception>
145         /// <exception cref="ArgumentException"><paramref name="inputBuffer"/> is an empty array.</exception>
146         /// <exception cref="FileFormatException">The format of <paramref name="inputBuffer"/> is not <see cref="InputFormat"/>.</exception>
147         /// <exception cref="ObjectDisposedException">The <see cref="ImageDecoder"/> has already been disposed of.</exception>
148         /// <since_tizen> 4 </since_tizen>
149         public Task<IEnumerable<BitmapFrame>> DecodeAsync(byte[] inputBuffer)
150         {
151             if (inputBuffer == null)
152             {
153                 throw new ArgumentNullException(nameof(inputBuffer));
154             }
155
156             if (inputBuffer.Length == 0)
157             {
158                 throw new ArgumentException("buffer is empty.", nameof(inputBuffer));
159             }
160
161             if (CheckHeader(inputBuffer) == false)
162             {
163                 throw new FileFormatException("buffer has an invalid header.");
164             }
165
166             SetInputBuffer(Handle, inputBuffer, (ulong)inputBuffer.Length).
167                 ThrowIfFailed("Failed to set input buffer for decoding");
168
169             return DecodeAsync();
170         }
171
172         private bool CheckHeader(byte[] input)
173         {
174             if (input.Length < Header.Length)
175             {
176                 return false;
177             }
178
179             for (int i = 0; i < Header.Length; ++i)
180             {
181                 if (input[i] != Header[i])
182                 {
183                     return false;
184                 }
185             }
186
187             return true;
188         }
189
190         private bool CheckHeader(string inputFile)
191         {
192             using (var fs = File.OpenRead(inputFile))
193             {
194                 byte[] fileHeader = new byte[Header.Length];
195
196                 if (fs.Read(fileHeader, 0, fileHeader.Length) < Header.Length)
197                 {
198                     return false;
199                 }
200                 return CheckHeader(fileHeader);
201             }
202         }
203
204         internal Task<IEnumerable<BitmapFrame>> DecodeAsync()
205         {
206             Initialize(Handle);
207
208             IntPtr outBuffer = IntPtr.Zero;
209             SetOutputBuffer(Handle, out outBuffer).ThrowIfFailed("Failed to decode given image");
210
211             var tcs = new TaskCompletionSource<IEnumerable<BitmapFrame>>();
212
213             Task.Run(() =>
214             {
215                 try
216                 {
217                     int width, height;
218                     ulong size;
219
220                     DecodeRun(Handle, out width, out height, out size).ThrowIfFailed("Failed to decode");
221
222                     tcs.SetResult(new[] { new BitmapFrame(outBuffer, width, height, (int)size) });
223                 }
224                 catch (Exception e)
225                 {
226                     tcs.TrySetException(e);
227                 }
228                 finally
229                 {
230                     LibcSupport.Free(outBuffer);
231                 }
232             });
233
234             return tcs.Task;
235         }
236
237         internal virtual void Initialize(ImageDecoderHandle handle)
238         {
239             if (_colorSpace.HasValue)
240             {
241                 SetColorspace(Handle, _colorSpace.Value.ToImageColorSpace()).ThrowIfFailed("Failed to set color space");
242             }
243         }
244
245         internal abstract byte[] Header { get; }
246
247         #region IDisposable Support
248         private bool _disposed = false;
249
250         /// <summary>
251         /// Releases the unmanaged resources used by the ImageDecoder.
252         /// </summary>
253         /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
254         /// <since_tizen> 4 </since_tizen>
255         protected virtual void Dispose(bool disposing)
256         {
257             if (!_disposed)
258             {
259                 if (_handle != null)
260                 {
261                     _handle.Dispose();
262                 }
263                 _disposed = true;
264             }
265         }
266
267         /// <summary>
268         /// Releases all resources used by the ImageDecoder.
269         /// </summary>
270         /// <since_tizen> 4 </since_tizen>
271         public void Dispose()
272         {
273             Dispose(true);
274         }
275         #endregion
276     }
277
278     /// <summary>
279     /// Provides the ability to decode Bitmap (BMP) encoded images.
280     /// </summary>
281     /// <since_tizen> 4 </since_tizen>
282     public class BmpDecoder : ImageDecoder
283     {
284         private static readonly byte[] _header = { (byte)'B', (byte)'M' };
285
286         /// <summary>
287         /// Initializes a new instance of the <see cref="BmpDecoder"/> class.
288         /// </summary>
289         /// <remarks><see cref="ImageDecoder.InputFormat"/> will be the <see cref="ImageFormat.Bmp"/>.</remarks>
290         /// <since_tizen> 4 </since_tizen>
291         public BmpDecoder() : base(ImageFormat.Bmp)
292         {
293         }
294
295         internal override byte[] Header => _header;
296     }
297
298     /// <summary>
299     /// Provides the ability to decode the Portable Network Graphics (PNG) encoded images.
300     /// </summary>
301     /// <since_tizen> 4 </since_tizen>
302     public class PngDecoder : ImageDecoder
303     {
304         private static readonly byte[] _header = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };
305
306         /// <summary>
307         /// Initializes a new instance of the <see cref="PngDecoder"/> class.
308         /// </summary>
309         /// <remarks><see cref="ImageDecoder.InputFormat"/> will be the <see cref="ImageFormat.Png"/>.</remarks>
310         /// <since_tizen> 4 </since_tizen>
311         public PngDecoder() : base(ImageFormat.Png)
312         {
313         }
314
315         internal override byte[] Header => _header;
316     }
317
318     /// <summary>
319     /// Provides the ability to decode the Joint Photographic Experts Group (JPEG) encoded images.
320     /// </summary>
321     /// <since_tizen> 4 </since_tizen>
322     public class JpegDecoder : ImageDecoder
323     {
324         private static readonly byte[] _header = { 0xFF, 0xD8 };
325
326         /// <summary>
327         /// A read-only field that represents the default value of <see cref="Downscale"/>.
328         /// </summary>
329         /// <since_tizen> 4 </since_tizen>
330         public static readonly JpegDownscale DefaultJpegDownscale = JpegDownscale.None;
331
332         private JpegDownscale _jpegDownscale = DefaultJpegDownscale;
333
334         /// <summary>
335         /// Initializes a new instance of the <see cref="JpegDecoder"/> class.
336         /// </summary>
337         /// <remarks><see cref="ImageDecoder.InputFormat"/> will be the <see cref="ImageFormat.Jpeg"/>.</remarks>
338         /// <since_tizen> 4 </since_tizen>
339         public JpegDecoder() : base(ImageFormat.Jpeg)
340         {
341         }
342
343         /// <summary>
344         /// Gets or sets the downscale at which the jpeg image should be decoded.
345         /// </summary>
346         /// <exception cref="ArgumentException"><paramref name="value"/> is invalid.</exception>
347         /// <since_tizen> 4 </since_tizen>
348         public JpegDownscale Downscale
349         {
350             get
351             {
352                 return _jpegDownscale;
353             }
354             set
355             {
356                 ValidationUtil.ValidateEnum(typeof(JpegDownscale), value, nameof(Downscale));
357
358                 _jpegDownscale = value;
359             }
360         }
361
362         internal override void Initialize(ImageDecoderHandle handle)
363         {
364             base.Initialize(handle);
365
366             SetJpegDownscale(handle, Downscale).ThrowIfFailed("Failed to set downscale for decoding");
367         }
368
369         internal override byte[] Header => _header;
370     }
371
372     /// <summary>
373     /// Provides the ability to decode the Graphics Interchange Format (GIF) encoded images.
374     /// </summary>
375     /// <since_tizen> 4 </since_tizen>
376     public class GifDecoder : ImageDecoder
377     {
378         private static readonly byte[] _header = { (byte)'G', (byte)'I', (byte)'F' };
379
380         /// <summary>
381         /// Initializes a new instance of the <see cref="GifDecoder"/> class.
382         /// </summary>
383         /// <remarks><see cref="ImageDecoder.InputFormat"/> will be the <see cref="ImageFormat.Gif"/>.</remarks>
384         /// <since_tizen> 4 </since_tizen>
385         public GifDecoder() : base(ImageFormat.Gif)
386         {
387         }
388
389         internal override byte[] Header => _header;
390     }
391 }