/
ImageEncoder.cs
479 lines (421 loc) · 17.3 KB
/
ImageEncoder.cs
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
/*
* Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using static Interop;
using NativeEncoder = Interop.ImageUtil.Encode;
namespace Tizen.Multimedia.Util
{
/// <summary>
/// This is a base class for image encoders.
/// </summary>
/// <since_tizen> 4 </since_tizen>
public abstract class ImageEncoder : IDisposable
{
private ImageEncoderHandle _handle;
private bool _hasResolution;
internal ImageEncoder(ImageFormat format)
{
NativeEncoder.Create(format, out _handle).ThrowIfFailed("Failed to create ImageEncoder");
Debug.Assert(_handle != null);
OutputFormat = format;
}
private ImageEncoderHandle Handle
{
get
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return _handle;
}
}
/// <summary>
/// Gets the image format of this encoder.
/// </summary>
/// <since_tizen> 4 </since_tizen>
public ImageFormat OutputFormat { get; }
/// <summary>
/// Sets the resolution of the output image.
/// </summary>
/// <param name="resolution">The target resolution.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// The width of <paramref name="resolution"/> is less than or equal to zero.<br/>
/// -or-<br/>
/// The height of <paramref name="resolution"/> is less than or equal to zero.
/// </exception>
/// <since_tizen> 4 </since_tizen>
public void SetResolution(Size resolution)
{
if (resolution.Width <= 0)
{
throw new ArgumentOutOfRangeException(nameof(resolution), resolution.Width,
"The width of resolution can't be less than or equal to zero.");
}
if (resolution.Height <= 0)
{
throw new ArgumentOutOfRangeException(nameof(resolution), resolution.Height,
"The height of resolution can't be less than or equal to zero.");
}
NativeEncoder.SetResolution(Handle, (uint)resolution.Width, (uint)resolution.Height).
ThrowIfFailed("Failed to set the resolution");
_hasResolution = true;
}
/// <summary>
/// Sets the color-space of the output image.
/// </summary>
/// <param name="colorSpace">The target color-space.</param>
/// <exception cref="ArgumentException"><paramref name="colorSpace"/> is invalid.</exception>
/// <exception cref="NotSupportedException"><paramref name="colorSpace"/> is not supported by the encoder.</exception>
/// <seealso cref="ImageUtil.GetSupportedColorSpaces(ImageFormat)"/>
/// <since_tizen> 4 </since_tizen>
public void SetColorSpace(ColorSpace colorSpace)
{
ValidationUtil.ValidateEnum(typeof(ColorSpace), colorSpace, nameof(colorSpace));
if (ImageUtil.GetSupportedColorSpaces(OutputFormat).Contains(colorSpace) == false)
{
throw new NotSupportedException($"{colorSpace.ToString()} is not supported for {OutputFormat}.");
}
NativeEncoder.SetColorspace(Handle, colorSpace.ToImageColorSpace()).
ThrowIfFailed("Failed to set the color space");
}
private void RunEncoding(object outStream)
{
IntPtr outBuffer = IntPtr.Zero;
try
{
NativeEncoder.SetOutputBuffer(Handle, out outBuffer).ThrowIfFailed("Failed to initialize encoder");
NativeEncoder.Run(Handle, out var size).ThrowIfFailed("Failed to encode given image");
byte[] buf = new byte[size];
Marshal.Copy(outBuffer, buf, 0, (int)size);
(outStream as Stream).Write(buf, 0, (int)size);
}
finally
{
Interop.Libc.Free(outBuffer);
}
}
private Task Run(Stream outStream)
{
return Task.Factory.StartNew(RunEncoding, outStream, CancellationToken.None,
TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning,
TaskScheduler.Default);
}
internal Task EncodeAsync(Action<ImageEncoderHandle> settingInputAction, Stream outStream)
{
Debug.Assert(settingInputAction != null);
if (outStream == null)
{
throw new ArgumentNullException(nameof(outStream));
}
if (outStream.CanWrite == false)
{
throw new ArgumentException("The stream is not writable.", nameof(outStream));
}
Initialize();
settingInputAction(Handle);
return Run(outStream);
}
/// <summary>
/// Encodes an image from a raw image buffer to a specified <see cref="Stream"/>.
/// </summary>
/// <param name="inputBuffer">The image buffer to encode.</param>
/// <param name="outStream">The stream that the image is encoded to.</param>
/// <returns>A task that represents the asynchronous encoding operation.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="inputBuffer"/> is null.<br/>
/// -or-<br/>
/// <paramref name="outStream"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="inputBuffer"/> is an empty array.<br/>
/// -or-<br/>
/// <paramref name="outStream"/> is not writable.
/// </exception>
/// <exception cref="InvalidOperationException">The resolution is not set.</exception>
/// <exception cref="ObjectDisposedException">The <see cref="ImageEncoder"/> has already been disposed of.</exception>
/// <seealso cref="SetResolution"/>
/// <since_tizen> 4 </since_tizen>
public Task EncodeAsync(byte[] inputBuffer, Stream outStream)
{
if (inputBuffer == null)
{
throw new ArgumentNullException(nameof(inputBuffer));
}
if (inputBuffer.Length == 0)
{
throw new ArgumentException("buffer is empty.", nameof(inputBuffer));
}
return EncodeAsync(handle =>
{
NativeEncoder.SetInputBuffer(handle, inputBuffer).
ThrowIfFailed("Failed to configure encoder; InputBuffer");
}, outStream);
}
internal void Initialize()
{
Configure(Handle);
if (_hasResolution == false)
{
throw new InvalidOperationException("Resolution is not set.");
}
}
internal abstract void Configure(ImageEncoderHandle handle);
#region IDisposable Support
private bool _disposed = false;
/// <summary>
/// Releases the unmanaged resources used by the ImageEncoder.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
/// <since_tizen> 4 </since_tizen>
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (_handle != null)
{
_handle.Dispose();
}
_disposed = true;
}
}
/// <summary>
/// Releases all resources used by the ImageEncoder.
/// </summary>
/// <since_tizen> 4 </since_tizen>
public void Dispose()
{
Dispose(true);
}
#endregion
}
/// <summary>
/// Provides the ability to encode the Bitmap (BMP) format images.
/// </summary>
/// <since_tizen> 4 </since_tizen>
public class BmpEncoder : ImageEncoder
{
/// <summary>
/// Initializes a new instance of the <see cref="BmpEncoder"/> class.
/// </summary>
/// <remarks><see cref="ImageEncoder.OutputFormat"/> will be the <see cref="ImageFormat.Bmp"/>.</remarks>
/// <since_tizen> 4 </since_tizen>
public BmpEncoder() : base(ImageFormat.Bmp)
{
}
internal override void Configure(ImageEncoderHandle handle)
{
}
}
/// <summary>
/// Provides the ability to encode the Portable Network Graphics (PNG) format images.
/// </summary>
/// <since_tizen> 4 </since_tizen>
public class PngEncoder : ImageEncoder
{
/// <summary>
/// A read-only field that represents the default value of <see cref="Compression"/>.
/// </summary>
/// <since_tizen> 4 </since_tizen>
public static readonly PngCompression DefaultCompression = PngCompression.Level6;
private PngCompression? _compression;
/// <summary>
/// Initializes a new instance of the <see cref="PngEncoder"/> class.
/// </summary>
/// <remarks><see cref="ImageEncoder.OutputFormat"/> will be the <see cref="ImageFormat.Png"/>.</remarks>
/// <since_tizen> 4 </since_tizen>
public PngEncoder() :
base(ImageFormat.Png)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PngEncoder"/> class with <see cref="PngCompression"/>.
/// </summary>
/// <remarks><see cref="ImageEncoder.OutputFormat"/> will be the <see cref="ImageFormat.Png"/>.</remarks>
/// <param name="compression">The compression level of the encoder.</param>
/// <exception cref="ArgumentException"><paramref name="compression"/> is invalid.</exception>
/// <since_tizen> 4 </since_tizen>
public PngEncoder(PngCompression compression) :
base(ImageFormat.Png)
{
Compression = compression;
}
/// <summary>
/// Gets or sets the compression level of the png image.
/// </summary>
/// <value>The compression level. The default is <see cref="PngCompression.Level6"/>.</value>
/// <exception cref="ArgumentException"><paramref name="value"/> is invalid.</exception>
/// <since_tizen> 4 </since_tizen>
public PngCompression Compression
{
get { return _compression ?? DefaultCompression; }
set
{
ValidationUtil.ValidateEnum(typeof(PngCompression), value, nameof(Compression));
_compression = value;
}
}
internal override void Configure(ImageEncoderHandle handle)
{
if (_compression.HasValue)
{
NativeEncoder.SetPngCompression(handle, _compression.Value).
ThrowIfFailed("Failed to configure encoder; PngCompression");
}
}
}
/// <summary>
/// Provides the ability to encode the Joint Photographic Experts Group (JPEG) format images.
/// </summary>
/// <since_tizen> 4 </since_tizen>
public class JpegEncoder : ImageEncoder
{
/// <summary>
/// A read-only field that represents the default value of <see cref="Quality"/>.
/// </summary>
/// <since_tizen> 4 </since_tizen>
public static readonly int DefaultQuality = 75;
private int? _quality;
/// <summary>
/// Initializes a new instance of the <see cref="JpegEncoder"/> class.
/// </summary>
/// <remarks><see cref="ImageEncoder.OutputFormat"/> will be the <see cref="ImageFormat.Jpeg"/>.</remarks>
/// <since_tizen> 4 </since_tizen>
public JpegEncoder() : base(ImageFormat.Jpeg)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JpegEncoder"/> class with initial quality value.
/// </summary>
/// <param name="quality">The quality for JPEG image encoding; from 1(lowest quality) to 100(highest quality).</param>
/// <remarks><see cref="ImageEncoder.OutputFormat"/> will be the <see cref="ImageFormat.Jpeg"/>.</remarks>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="quality"/> is less than or equal to 0.<br/>
/// -or-<br/>
/// <paramref name="quality"/> is greater than 100.
/// </exception>
/// <since_tizen> 4 </since_tizen>
public JpegEncoder(int quality) :
base(ImageFormat.Jpeg)
{
Quality = quality;
}
/// <summary>
/// Gets or sets the quality of the encoded image.
/// </summary>
/// <value>
/// The quality of the output image. The default is 75.<br/>
/// Valid value is from 1(lowest quality) to 100(highest quality).
/// </value>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="value"/> is less than or equal to 0.<br/>
/// -or-<br/>
/// <paramref name="value"/> is greater than 100.
/// </exception>
/// <since_tizen> 4 </since_tizen>
public int Quality
{
get { return _quality ?? DefaultQuality; }
set
{
if (value <= 0 || value > 100)
{
throw new ArgumentOutOfRangeException(nameof(Quality), value,
"Valid range is from 1 to 100, inclusive.");
}
_quality = value;
}
}
internal override void Configure(ImageEncoderHandle handle)
{
if (_quality.HasValue)
{
NativeEncoder.SetQuality(handle, _quality.Value).
ThrowIfFailed("Failed to configure encoder; Quality");
}
}
}
/// <summary>
/// Provides the ability to encode the Graphics Interchange Format (GIF) format images.
/// </summary>
/// <since_tizen> 4 </since_tizen>
public class GifEncoder : ImageEncoder
{
/// <summary>
/// Initializes a new instance of the <see cref="GifEncoder"/> class.
/// </summary>
/// <remarks><see cref="ImageEncoder.OutputFormat"/> will be the <see cref="ImageFormat.Gif"/>.</remarks>
/// <since_tizen> 4 </since_tizen>
public GifEncoder() : base(ImageFormat.Gif)
{
}
internal override void Configure(ImageEncoderHandle handle)
{
}
/// <summary>
/// Encodes a Graphics Interchange Format (GIF) image from multiple raw image buffers to a specified <see cref="Stream"/>.
/// </summary>
/// <param name="frames">The image frames to encode.</param>
/// <param name="outStream">The stream that the image is encoded to.</param>
/// <returns>A task that represents the asynchronous encoding operation.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="frames"/> is null.<br/>
/// -or-<br/>
/// <paramref name="outStream"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="frames"/> has no element(empty).<br/>
/// -or-<br/>
/// <paramref name="outStream"/> is not writable.
/// </exception>
/// <exception cref="InvalidOperationException">The resolution is not set.</exception>
/// <exception cref="ObjectDisposedException">The <see cref="ImageEncoder"/> has already been disposed of.</exception>
/// <seealso cref="ImageEncoder.SetResolution"/>
/// <since_tizen> 4 </since_tizen>
public Task EncodeAsync(IEnumerable<GifFrame> frames, Stream outStream)
{
if (frames == null)
{
throw new ArgumentNullException(nameof(frames));
}
if (frames.Count() == 0)
{
throw new ArgumentException("frames is a empty collection", nameof(frames));
}
return EncodeAsync(handle =>
{
foreach (GifFrame frame in frames)
{
if (frame == null)
{
throw new ArgumentNullException(nameof(frames));
}
NativeEncoder.SetInputBuffer(handle, frame.Buffer).
ThrowIfFailed("Failed to configure encoder; Buffer");
NativeEncoder.SetGifFrameDelayTime(handle, (ulong)frame.Delay).
ThrowIfFailed("Failed to configure encoder; Delay");
}
}, outStream);
}
}
}