/
ImageEncoder.cs
609 lines (538 loc) · 22.6 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
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
/*
* 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;
using NativeUtil = Interop.ImageUtil;
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;
internal IntPtr _imageUtilHandle;
internal IntPtr _animationHandle;
internal Size? _resolution;
internal ColorSpace? _colorSpace;
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.");
}
_resolution = resolution;
}
/// <summary>
/// Sets the color-space of the output image.
/// </summary>
/// <param name="colorSpace">The target color-space.</param>
/// <value>The default color space is <see cref="ColorSpace.Rgba8888"/>
/// <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}.");
}
_colorSpace = colorSpace;
}
internal virtual void RunEncoding(object outStream)
{
IntPtr outBuffer = IntPtr.Zero;
int size = 0;
try
{
NativeEncoder.RunToBuffer(Handle, _imageUtilHandle, out outBuffer, out 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
{
Marshal.FreeHGlobal(outBuffer);
NativeUtil.Destroy(_imageUtilHandle).ThrowIfFailed("Failed to destroy ImageUtil handle");
}
}
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 => {
NativeUtil.Create((uint)_resolution.Value.Width, (uint)_resolution.Value.Height, _colorSpace.Value.ToImageColorSpace(),
inputBuffer, inputBuffer.Length, out _imageUtilHandle).ThrowIfFailed("Failed to create ImageUtil handle");
}, outStream);
}
internal void Initialize()
{
Configure(Handle);
if (!_resolution.HasValue)
{
throw new InvalidOperationException("Resolution is not set.");
}
if (!_colorSpace.HasValue)
{
_colorSpace = ColorSpace.Rgba8888;
Log.Info("Tizen.Multimedia.Util", "ColorSpace was set to default value(Rgba8888).");
}
}
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
{
private IEnumerable<GifFrame> _frames;
/// <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.Any())
{
throw new ArgumentException("frames is a empty collection", nameof(frames));
}
_frames = frames;
return EncodeAsync(handle => {}, outStream);
}
internal override void RunEncoding(object outStream)
{
IntPtr outBuffer = IntPtr.Zero;
NativeEncoder.AnimationCreate(AnimationType.Gif, out _animationHandle).
ThrowIfFailed("Failed to create animation handle");
try
{
foreach (GifFrame frame in _frames)
{
if (frame == null)
{
throw new ArgumentNullException(nameof(frame));
}
NativeUtil.Create((uint)_resolution.Value.Width, (uint)_resolution.Value.Height, _colorSpace.Value.ToImageColorSpace(),
frame.Buffer, frame.Buffer.Length, out _imageUtilHandle).ThrowIfFailed("Failed to create ImageUtil handle");
NativeEncoder.AnimationAddFrame(_animationHandle, _imageUtilHandle, frame.Delay).
ThrowIfFailed("Failed to add frame");
NativeUtil.Destroy(_imageUtilHandle).ThrowIfFailed("Failed to destroy ImageUtil handle");
}
NativeEncoder.AnimationSaveToBuffer(_animationHandle, out outBuffer, out ulong 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
{
Marshal.FreeHGlobal(outBuffer);
if (_animationHandle != IntPtr.Zero)
{
NativeEncoder.AnimationDestroy(_animationHandle).ThrowIfFailed("Failed to destroy animation handle");
}
}
}
}
/// <summary>
/// Provides the ability to encode the WebP (Lossless and lossy compression for images on the web) format images.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public class WebPEncoder : ImageEncoder
{
/// <summary>
/// Initializes a new instance of the <see cref="WebPEncoder"/> class.
/// </summary>
/// <remarks><see cref="ImageEncoder.OutputFormat"/> will be the <see cref="ImageFormat.WebP"/>.</remarks>
/// <since_tizen> 8 </since_tizen>
public WebPEncoder() :
base(ImageFormat.WebP)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WebPEncoder"/> class with the information for lossless or lossy compression.
/// </summary>
/// <remarks><see cref="ImageEncoder.OutputFormat"/> will be the <see cref="ImageFormat.WebP"/>.</remarks>
/// <param name="lossless">
/// The flag determining whether the compression is lossless or lossy: true for lossless, false for lossy.<br/>
/// The default value is false.
/// </param>
/// <since_tizen> 8 </since_tizen>
public WebPEncoder(bool lossless) :
base(ImageFormat.WebP)
{
Lossless = lossless;
}
/// <summary>
/// Gets or sets the lossless or lossy WebP compression.
/// </summary>
/// <value>
/// The property determining whether the WebP compression is lossless or lossy.<br/>
/// The default is false(lossy).</value>
/// <since_tizen> 8 </since_tizen>
public bool Lossless { get; set; } = false;
internal override void Configure(ImageEncoderHandle handle)
{
NativeEncoder.SetLossless(handle, Lossless).
ThrowIfFailed("Failed to configure encoder; Lossless");
}
}
/// <summary>
/// Provides the ability to encode the JPEG(Joint Photographic Experts Group) XL format images.
/// </summary>
/// <since_tizen> 10 </since_tizen>
public class JpegXlEncoder : ImageEncoder
{
/// <summary>
/// Initializes a new instance of the <see cref="JpegXlEncoder"/> class.
/// </summary>
/// <remarks><see cref="ImageEncoder.OutputFormat"/> will be the <see cref="ImageFormat.JpegXl"/>.</remarks>
/// <since_tizen> 10 </since_tizen>
public JpegXlEncoder() :
base(ImageFormat.JpegXl)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JpegXlEncoder"/> class for lossless or lossy compression.
/// </summary>
/// <remarks><see cref="ImageEncoder.OutputFormat"/> will be the <see cref="ImageFormat.JpegXl"/>.</remarks>
/// <param name="lossless">
/// The flag determining whether the compression is lossless or lossy: true for lossless, false for lossy.<br/>
/// The default value is false.
/// </param>
/// <since_tizen> 10 </since_tizen>
public JpegXlEncoder(bool lossless) :
base(ImageFormat.JpegXl)
{
Lossless = lossless;
}
/// <summary>
/// Gets or sets the lossless or lossy JpegXl compression.
/// </summary>
/// <value>
/// The property determining whether the JpegXl compression is lossless or lossy.<br/>
/// The default is false(lossy).</value>
/// <since_tizen> 10 </since_tizen>
public bool Lossless { get; set; } = false;
internal override void Configure(ImageEncoderHandle handle)
{
NativeEncoder.SetLossless(handle, Lossless).
ThrowIfFailed($"Failed to configure encoder; Lossless={Lossless}");
}
}
}