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;
21 namespace Tizen.Multimedia.MediaCodec
24 /// Provides the means to encode and decode video and audio data.
26 public class MediaCodec : IDisposable
28 private static readonly int CodecTypeMask = 0xFFFF;
29 private static readonly int CodecKindMask = 0x3000;
30 private static readonly int CodecKindAudio = 0x1000;
31 private static readonly int CodecKindVideo = 0x2000;
33 private IntPtr _handle;
36 /// Initialize a new instance of the MediaCodec class.
40 int ret = Interop.MediaCodec.Create(out _handle);
42 if (ret == (int)MediaCodecErrorCode.InvalidOperation)
44 throw new InvalidOperationException("Not able to initiate a new media codec.");
47 MediaCodecDebug.AssertNoError(ret);
50 #region IDisposable-support
51 private bool _isDisposed = false;
53 protected virtual void Dispose(bool disposing)
57 if (_handle != IntPtr.Zero)
59 Interop.MediaCodec.Destroy(_handle);
60 _handle = IntPtr.Zero;
76 GC.SuppressFinalize(this);
81 /// Validates if the object already has been disposed of.
83 /// <exception cref="ObjectDisposedException">The current object has been disposed of.</exception>
84 private void ValidateNotDisposed()
88 throw new ObjectDisposedException(nameof(MediaCodec));
92 private static IEnumerable<MediaFormatVideoMimeType> _supportedVideoCodecs;
95 /// Gets the audio codec list that the current device supports.
97 public static IEnumerable<MediaFormatVideoMimeType> SupportedVideoCodecs
101 if (_supportedVideoCodecs == null)
103 LoadSupportedCodec();
106 return _supportedVideoCodecs;
110 private static IEnumerable<MediaFormatAudioMimeType> _supportedAudioCodecs;
114 /// Gets the audio codec list that the current device supports.
116 public static IEnumerable<MediaFormatAudioMimeType> SupportedAudioCodecs
120 if (_supportedAudioCodecs == null)
122 LoadSupportedCodec();
125 return _supportedAudioCodecs;
129 private static bool TryGetMimeTypeFromCodecType<T>(int codecType, ref T result)
131 foreach (T value in Enum.GetValues(typeof(T)))
133 if ((Convert.ToInt32(value) & CodecTypeMask) == codecType)
140 Debug.Fail($"Unknown codec : { codecType }.");
144 private static void LoadSupportedCodec()
146 var videoCodecList = new List<MediaFormatVideoMimeType>();
147 var audioCodecList = new List<MediaFormatAudioMimeType>();
149 Interop.MediaCodec.SupportedCodecCallback cb = (int codecType, IntPtr arg) =>
151 if ((codecType & CodecKindMask) == CodecKindVideo)
153 MediaFormatVideoMimeType mimeType = 0;
154 if (TryGetMimeTypeFromCodecType(codecType, ref mimeType))
156 videoCodecList.Add(mimeType);
161 MediaFormatAudioMimeType mimeType = 0;
162 if (TryGetMimeTypeFromCodecType(codecType, ref mimeType))
164 audioCodecList.Add(mimeType);
171 int ret = Interop.MediaCodec.ForeachSupportedCodec(cb, IntPtr.Zero);
173 MediaCodecDebug.AssertNoError(ret);
175 _supportedVideoCodecs = videoCodecList.AsReadOnly();
176 _supportedAudioCodecs = audioCodecList.AsReadOnly();
180 /// Prepares the MediaCodec for encoding or decoding.
182 /// <exception cref="InvalidOperationException">
183 /// The codec is not configured, yet.
184 /// <para>-or-</para>
187 public void Prepare()
189 ValidateNotDisposed();
191 int ret = Interop.MediaCodec.Prepare(_handle);
193 if (ret == (int)MediaCodecErrorCode.NotInitialized)
195 throw new InvalidOperationException("The codec is not configured.");
197 if (ret != (int)MediaCodecErrorCode.None)
199 throw new InvalidOperationException("Operation failed.");
202 MediaCodecDebug.AssertNoError(ret);
206 /// Unprepares the MediaCodec.
208 public void Unprepare()
210 ValidateNotDisposed();
212 int ret = Interop.MediaCodec.Unprepare(_handle);
214 MediaCodecDebug.AssertNoError(ret);
218 /// Configures the MediaCodec.
220 /// <param name="format">The <see cref="MediaFormat"/> for properties of media data to decode or encode.</param>
221 /// <param name="encoder">The value indicating whether the codec works as a encoder or a decoder.</param>
222 /// <param name="codecType">The value indicating whether the codec uses hardware acceleration.</param>
223 /// <exception cref="ArgumentNullException">format is null</exception>
224 /// <exception cref="ArgumentException">
225 /// codecType is invalid.
226 /// <para>-or-</para>
227 /// format is neither audio type or video type.
229 /// <exception cref="NotSupportedException">the mime type of the format is not supported.</exception>
230 /// <see cref="SupportedAudioCodecs"/>
231 /// <see cref="SupportedVideoCodecs"/>
232 public void Configure(MediaFormat format, bool encoder, MediaCodecTypes codecType)
234 ValidateNotDisposed();
238 throw new ArgumentNullException("Format can't be null.");
241 if (codecType != MediaCodecTypes.Hardware && codecType != MediaCodecTypes.Software)
243 throw new ArgumentException("codecType is invalid.");
246 if (format.Type == MediaFormatType.Audio)
248 ConfigureAudio((AudioMediaFormat)format, encoder, codecType);
250 else if (format.Type == MediaFormatType.Video)
252 ConfigureVideo((VideoMediaFormat)format, encoder, codecType);
256 throw new ArgumentException("Only video and audio formats are allowed.");
260 private void ConfigureAudio(AudioMediaFormat format, bool encoder,
261 MediaCodecTypes supportType)
263 int codecType = (int)format.MimeType & CodecTypeMask;
265 if (!Enum.IsDefined(typeof(SupportedCodecType), codecType))
267 throw new NotSupportedException("The format is not supported " +
268 $"mime type : { Enum.GetName(typeof(MediaFormatAudioMimeType), format.MimeType) }");
271 DoConfigure(codecType, encoder, supportType);
275 int ret = Interop.MediaCodec.SetAudioEncoderInfo(_handle, format.SampleRate,
276 format.Channel, format.Bit, format.BitRate);
278 MediaCodecDebug.AssertNoError(ret);
282 int ret = Interop.MediaCodec.SetAudioDecoderInfo(_handle, format.SampleRate,
283 format.Channel, format.Bit);
285 MediaCodecDebug.AssertNoError(ret);
289 private void ConfigureVideo(VideoMediaFormat format, bool encoder,
290 MediaCodecTypes supportType)
292 int codecType = (int)format.MimeType & CodecTypeMask;
294 if (!Enum.IsDefined(typeof(SupportedCodecType), codecType))
296 throw new NotSupportedException("The format is not supported." +
297 $"mime type : { Enum.GetName(typeof(MediaFormatVideoMimeType), format.MimeType) }");
300 DoConfigure(codecType, encoder, supportType);
304 int ret = Interop.MediaCodec.SetVideoEncoderInfo(_handle, format.Width,
305 format.Height, format.FrameRate, format.BitRate / 1000);
307 MediaCodecDebug.AssertNoError(ret);
311 int ret = Interop.MediaCodec.SetVideoDecoderInfo(_handle, format.Width, format.Height);
313 MediaCodecDebug.AssertNoError(ret);
317 private void DoConfigure(int codecType, bool encoder, MediaCodecTypes supportType)
319 Debug.Assert(Enum.IsDefined(typeof(SupportedCodecType), codecType));
321 int flags = (int)(encoder ? MediaCodecCodingType.Encoder : MediaCodecCodingType.Decoder);
323 flags |= (int)supportType;
325 int ret = Interop.MediaCodec.Configure(_handle, codecType, flags);
327 if (ret == (int)MediaCodecErrorCode.NotSupportedOnDevice)
329 throw new NotSupportedException("The format is not supported.");
331 MediaCodecDebug.AssertNoError(ret);
335 /// Add the packet to the internal queue of the codec.
337 /// <param name="packet">The packet to be encoded or decoded.</param>
338 /// <exception cref="ArgumentNullException">packet is null.</exception>
339 /// <exception cref="InvalidOperationException">the current codec is not prepared, yet.</exception>
340 /// <remarks>Any attempts to modify the packet will be failed until the <see cref="InputProcessed"/> event for the packet is invoked.</remarks>
341 public void ProcessInput(MediaPacket packet)
343 ValidateNotDisposed();
347 throw new ArgumentNullException("Packet can't be null");
350 MediaPacket.Lock packetLock = new MediaPacket.Lock(packet);
352 int ret = Interop.MediaCodec.Process(_handle, packetLock.GetHandle(), 0);
354 if (ret == (int)MediaCodecErrorCode.InvalidState)
356 throw new InvalidOperationException("The codec is in invalid state.");
359 MediaCodecDebug.AssertNoError(ret);
363 /// Flush both input and output buffers.
365 public void FlushBuffers()
367 ValidateNotDisposed();
369 int ret = Interop.MediaCodec.FlushBuffers(_handle);
371 MediaCodecDebug.AssertNoError(ret);
375 /// Retrieves supported codec types for the specified params.
377 /// <param name="encoder">The value indicating encoder or decoder.</param>
378 /// <param name="type">The mime type to query.</param>
379 /// <returns>The values indicating which codec types are supported on the current device.</returns>
380 /// <exception cref="ArgumentException">type is invalid.</exception>
381 public MediaCodecTypes GetCodecType(bool encoder, MediaFormatVideoMimeType type)
383 ValidateNotDisposed();
385 if (CheckMimeType(typeof(MediaFormatVideoMimeType), (int)type) == false)
390 return GetCodecType((int)type, encoder);
394 /// Retrieves supported codec types for the specified params.
396 /// <param name="encoder">The value indicating encoder or decoder.</param>
397 /// <param name="type">The mime type to query.</param>
398 /// <returns>The values indicating which codec types are supported on the current device.</returns>
399 /// <exception cref="ArgumentException">type is invalid.</exception>
400 public MediaCodecTypes GetCodecType(bool encoder, MediaFormatAudioMimeType type)
402 ValidateNotDisposed();
404 if (CheckMimeType(typeof(MediaFormatAudioMimeType), (int)type) == false)
409 return GetCodecType((int)type, encoder);
412 private MediaCodecTypes GetCodecType(int mimeType, bool isEncoder)
414 int codecType = mimeType & CodecTypeMask;
417 int ret = Interop.MediaCodec.GetSupportedType(_handle, codecType, isEncoder, out value);
419 MediaCodecDebug.AssertNoError(ret);
421 return (MediaCodecTypes)value;
424 private bool CheckMimeType(Type type, int value)
426 int codecType = value & CodecTypeMask;
428 if (!Enum.IsDefined(type, value))
430 throw new ArgumentException($"The mime type value is invalid : { value }.");
433 return Enum.IsDefined(typeof(SupportedCodecType), codecType);
436 #region OutputAvailable event
437 private EventHandler<OutputAvailableEventArgs> _outputAvailable;
438 private Interop.MediaCodec.OutputBufferAvailableCallback _outputBufferAvailableCb;
441 /// Occurs when an output buffer is available.
443 /// <remarks>The output packet needs to be disposed after it is used to clean up unmanaged resources.</remarks>
444 public event EventHandler<OutputAvailableEventArgs> OutputAvailable
448 ValidateNotDisposed();
450 if (_outputAvailable == null)
452 RegisterOutputAvailableCallback();
454 _outputAvailable += value;
459 ValidateNotDisposed();
461 _outputAvailable -= value;
462 if (_outputAvailable == null)
464 UnregisterOutputAvailableCallback();
469 private void RegisterOutputAvailableCallback()
471 _outputBufferAvailableCb = (IntPtr packetHandle, IntPtr arg) =>
473 OutputAvailableEventArgs args = null;
477 args = new OutputAvailableEventArgs(packetHandle);
481 Interop.MediaPacket.Destroy(packetHandle);
485 _outputAvailable?.Invoke(this, args);
488 int ret = Interop.MediaCodec.SetOutputBufferAvaiableCb(_handle,
489 _outputBufferAvailableCb, IntPtr.Zero);
491 MediaCodecDebug.AssertNoError(ret);
494 private void UnregisterOutputAvailableCallback()
496 int ret = Interop.MediaCodec.UnsetOutputBufferAvaiableCb(_handle);
498 MediaCodecDebug.AssertNoError(ret);
502 #region InputProcessed event
503 private EventHandler<InputProcessedEventArgs> _inputProcessed;
504 private Interop.MediaCodec.InputBufferUsedCallback _inputBufferUsedCb;
507 /// Occurs when an input packet is processed.
509 /// <see cref="ProcessInput(MediaPacket)"/>
510 public event EventHandler<InputProcessedEventArgs> InputProcessed
514 ValidateNotDisposed();
516 if (_inputProcessed == null)
518 RegisterInputProcessed();
520 _inputProcessed += value;
525 ValidateNotDisposed();
527 _inputProcessed -= value;
528 if (_inputProcessed == null)
530 UnregisterInputProcessed();
535 private void RegisterInputProcessed()
537 _inputBufferUsedCb = (IntPtr lockedPacketHandle, IntPtr arg) =>
539 MediaPacket packet = null;
541 // Lock must be disposed here, note that the packet won't be disposed.
542 using (MediaPacket.Lock packetLock =
543 MediaPacket.Lock.FromHandle(lockedPacketHandle))
545 packet = packetLock.MediaPacket;
547 Debug.Assert(packet != null);
549 _inputProcessed?.Invoke(this, new InputProcessedEventArgs(packet));
552 int ret = Interop.MediaCodec.SetInputBufferUsedCb(_handle,
553 _inputBufferUsedCb, IntPtr.Zero);
555 MediaCodecDebug.AssertNoError(ret);
558 private void UnregisterInputProcessed()
560 int ret = Interop.MediaCodec.UnsetInputBufferUsedCb(_handle);
562 MediaCodecDebug.AssertNoError(ret);
566 #region ErrorOccurred event
567 private EventHandler<ErrorOccurredEventArgs> _errorOccurred;
568 private Interop.MediaCodec.ErrorCallback _errorCb;
571 /// Occurs whenever an error is produced in the codec.
573 public event EventHandler<ErrorOccurredEventArgs> ErrorOccurred
577 ValidateNotDisposed();
579 if (_errorOccurred == null)
581 RegisterErrorOccurred();
583 _errorOccurred += value;
588 ValidateNotDisposed();
590 _errorOccurred -= value;
591 if (_errorOccurred == null)
593 UnregisterErrorOccurred();
598 private void RegisterErrorOccurred()
600 _errorCb = (int errorCode, IntPtr arg) =>
602 MediaCodecError error = (Enum.IsDefined(typeof(MediaCodecError), errorCode)) ?
603 (MediaCodecError)errorCode : MediaCodecError.InternalError;
605 _errorOccurred?.Invoke(this, new ErrorOccurredEventArgs(error));
607 int ret = Interop.MediaCodec.SetErrorCb(_handle, _errorCb, IntPtr.Zero);
609 MediaCodecDebug.AssertNoError(ret);
612 private void UnregisterErrorOccurred()
614 int ret = Interop.MediaCodec.UnsetErrorCb(_handle);
616 MediaCodecDebug.AssertNoError(ret);
620 #region EosReached event
621 private EventHandler<EosReachedEventArgs> _eosReached;
622 private Interop.MediaCodec.EosCallback _eosCb;
625 /// Occurs when the codec processes all input data.
627 public event EventHandler<EosReachedEventArgs> EosReached
631 ValidateNotDisposed();
633 if (_eosReached == null)
635 RegisterEosReached();
637 _eosReached += value;
642 ValidateNotDisposed();
644 _eosReached -= value;
645 if (_eosReached == null)
647 UnregisterEosReached();
652 private void RegisterEosReached()
654 _eosCb = (IntPtr arg) => _eosReached?.Invoke(this, new EosReachedEventArgs());
656 int ret = Interop.MediaCodec.SetEosCb(_handle, _eosCb, IntPtr.Zero);
658 MediaCodecDebug.AssertNoError(ret);
661 private void UnregisterEosReached()
663 int ret = Interop.MediaCodec.UnsetEosCb(_handle);
665 MediaCodecDebug.AssertNoError(ret);
669 #region BufferStatusChanged event
670 private EventHandler<BufferStatusChangedEventArgs> _bufferStatusChanged;
671 private Interop.MediaCodec.BufferStatusCallback _bufferStatusCb;
674 /// Occurs when the codec needs more data or has enough data.
676 public event EventHandler<BufferStatusChangedEventArgs> BufferStatusChanged
680 ValidateNotDisposed();
682 if (_bufferStatusChanged == null)
684 RegisterBufferStatusChanged();
686 _bufferStatusChanged += value;
691 ValidateNotDisposed();
693 _bufferStatusChanged -= value;
694 if (_bufferStatusChanged == null)
696 UnregisterBufferStatusChanged();
701 private void RegisterBufferStatusChanged()
703 _bufferStatusCb = (int statusCode, IntPtr arg) =>
705 Debug.Assert(Enum.IsDefined(typeof(MediaCodecStatus), statusCode),
706 $"{ statusCode } is not defined in MediaCodecStatus!");
708 _bufferStatusChanged?.Invoke(this,
709 new BufferStatusChangedEventArgs((MediaCodecStatus)statusCode));
712 int ret = Interop.MediaCodec.SetBufferStatusCb(_handle, _bufferStatusCb, IntPtr.Zero);
714 MediaCodecDebug.AssertNoError(ret);
717 private void UnregisterBufferStatusChanged()
719 int ret = Interop.MediaCodec.UnsetBufferStatusCb(_handle);
721 MediaCodecDebug.AssertNoError(ret);