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 the video and the audio data.
26 public class MediaCodec : IDisposable
28 private const int CodecTypeMask = 0xFFFF;
29 private const int CodecKindMask = 0x3000;
30 // private const int CodecKindAudio = 0x1000; // Not used
31 private const int CodecKindVideo = 0x2000;
33 private IntPtr _handle;
36 /// Initializes 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 initialize a new media codec.");
47 MultimediaDebug.AssertNoError(ret);
49 RegisterInputProcessed();
50 RegisterErrorOccurred();
53 #region IDisposable-support
54 private bool _isDisposed = false;
57 /// Releases the resources used by the <see cref="MediaCodec"/> object.
59 /// <param name="disposing">
60 /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
62 protected virtual void Dispose(bool disposing)
66 if (_handle != IntPtr.Zero)
68 Interop.MediaCodec.Destroy(_handle);
69 _handle = IntPtr.Zero;
82 /// Releases all resources used by the <see cref="MediaCodec"/> object.
88 GC.SuppressFinalize(this);
93 /// Validates if the object has already been disposed of.
95 /// <exception cref="ObjectDisposedException">The current object has been disposed of.</exception>
96 private void ValidateNotDisposed()
100 throw new ObjectDisposedException(nameof(MediaCodec));
104 private static IEnumerable<MediaFormatVideoMimeType> _supportedVideoCodecs;
107 /// Gets the audio codec list that the current device supports.
109 public static IEnumerable<MediaFormatVideoMimeType> SupportedVideoCodecs
113 if (_supportedVideoCodecs == null)
115 LoadSupportedCodec();
118 return _supportedVideoCodecs;
122 private static IEnumerable<MediaFormatAudioMimeType> _supportedAudioCodecs;
126 /// Gets the audio codec list that the current device supports.
128 public static IEnumerable<MediaFormatAudioMimeType> SupportedAudioCodecs
132 if (_supportedAudioCodecs == null)
134 LoadSupportedCodec();
137 return _supportedAudioCodecs;
141 private static bool TryGetMimeTypeFromCodecType<T>(int codecType, ref T result)
148 foreach (T value in Enum.GetValues(typeof(T)))
150 if ((Convert.ToInt32(value) & CodecTypeMask) == codecType)
157 Debug.Fail($"Unknown codec : { codecType }.");
161 private static void LoadSupportedCodec()
163 var videoCodecList = new List<MediaFormatVideoMimeType>();
164 var audioCodecList = new List<MediaFormatAudioMimeType>();
166 Interop.MediaCodec.SupportedCodecCallback cb = (codecType, _) =>
168 if ((codecType & CodecKindMask) == CodecKindVideo)
170 MediaFormatVideoMimeType mimeType = 0;
171 if (TryGetMimeTypeFromCodecType(codecType, ref mimeType))
173 videoCodecList.Add(mimeType);
178 MediaFormatAudioMimeType mimeType = 0;
179 if (TryGetMimeTypeFromCodecType(codecType, ref mimeType))
181 audioCodecList.Add(mimeType);
188 int ret = Interop.MediaCodec.ForeachSupportedCodec(cb, IntPtr.Zero);
190 MultimediaDebug.AssertNoError(ret);
192 _supportedVideoCodecs = videoCodecList.AsReadOnly();
193 _supportedAudioCodecs = audioCodecList.AsReadOnly();
197 /// Prepares the MediaCodec for encoding or decoding.
199 /// <exception cref="InvalidOperationException">
200 /// The codec is not configured yet.\n
204 public void Prepare()
206 ValidateNotDisposed();
208 int ret = Interop.MediaCodec.Prepare(_handle);
210 if (ret == (int)MediaCodecErrorCode.NotInitialized)
212 throw new InvalidOperationException("The codec is not configured.");
214 if (ret != (int)MediaCodecErrorCode.None)
216 throw new InvalidOperationException("Operation failed.");
219 MultimediaDebug.AssertNoError(ret);
223 /// Unprepares the MediaCodec.
225 public void Unprepare()
227 ValidateNotDisposed();
229 int ret = Interop.MediaCodec.Unprepare(_handle);
231 MultimediaDebug.AssertNoError(ret);
235 /// Configures the MediaCodec.
237 /// <param name="format">The <see cref="MediaFormat"/> for properties of media data to decode or encode.</param>
238 /// <param name="encoder">The value indicating whether the codec works as an encoder or a decoder.</param>
239 /// <param name="codecType">The value indicating whether the codec uses hardware acceleration.</param>
240 /// <exception cref="ArgumentNullException"><paramref name="format"/> is null.</exception>
241 /// <exception cref="ArgumentException">
242 /// <paramref name="codecType"/> is invalid.\n
244 /// <paramref name="format"/> is neither audio type nor video type.
246 /// <exception cref="NotSupportedException">The mime type of the format is not supported.</exception>
247 /// <see cref="SupportedAudioCodecs"/>
248 /// <see cref="SupportedVideoCodecs"/>
249 public void Configure(MediaFormat format, bool encoder, MediaCodecTypes codecType)
251 ValidateNotDisposed();
255 throw new ArgumentNullException(nameof(format));
258 if (codecType != MediaCodecTypes.Hardware && codecType != MediaCodecTypes.Software)
260 throw new ArgumentException("codecType is invalid.");
263 if (format.Type == MediaFormatType.Audio)
265 ConfigureAudio((AudioMediaFormat)format, encoder, codecType);
267 else if (format.Type == MediaFormatType.Video)
269 ConfigureVideo((VideoMediaFormat)format, encoder, codecType);
273 throw new ArgumentException("Only video and audio formats are allowed.");
277 private void ConfigureAudio(AudioMediaFormat format, bool encoder,
278 MediaCodecTypes supportType)
280 int codecType = (int)format.MimeType & CodecTypeMask;
282 if (!Enum.IsDefined(typeof(SupportedCodecType), codecType))
284 throw new NotSupportedException("The format is not supported " +
285 $"mime type : { Enum.GetName(typeof(MediaFormatAudioMimeType), format.MimeType) }");
288 DoConfigure(codecType, encoder, supportType);
292 int ret = Interop.MediaCodec.SetAudioEncoderInfo(_handle, format.SampleRate,
293 format.Channel, format.Bit, format.BitRate);
295 MultimediaDebug.AssertNoError(ret);
299 int ret = Interop.MediaCodec.SetAudioDecoderInfo(_handle, format.SampleRate,
300 format.Channel, format.Bit);
302 MultimediaDebug.AssertNoError(ret);
306 private void ConfigureVideo(VideoMediaFormat format, bool encoder,
307 MediaCodecTypes supportType)
309 int codecType = (int)format.MimeType & CodecTypeMask;
311 if (!Enum.IsDefined(typeof(SupportedCodecType), codecType))
313 throw new NotSupportedException("The format is not supported." +
314 $"mime type : { Enum.GetName(typeof(MediaFormatVideoMimeType), format.MimeType) }");
317 DoConfigure(codecType, encoder, supportType);
321 int ret = Interop.MediaCodec.SetVideoEncoderInfo(_handle, format.Size.Width,
322 format.Size.Height, format.FrameRate, format.BitRate / 1000);
324 MultimediaDebug.AssertNoError(ret);
328 int ret = Interop.MediaCodec.SetVideoDecoderInfo(_handle, format.Size.Width, format.Size.Height);
330 MultimediaDebug.AssertNoError(ret);
334 private void DoConfigure(int codecType, bool encoder, MediaCodecTypes supportType)
336 Debug.Assert(Enum.IsDefined(typeof(SupportedCodecType), codecType));
338 int flags = (int)(encoder ? MediaCodecCodingType.Encoder : MediaCodecCodingType.Decoder);
340 flags |= (int)supportType;
342 int ret = Interop.MediaCodec.Configure(_handle, codecType, flags);
344 if (ret == (int)MediaCodecErrorCode.NotSupportedOnDevice)
346 throw new NotSupportedException("The format is not supported.");
348 MultimediaDebug.AssertNoError(ret);
352 /// Adds the packet to the internal queue of the codec.
354 /// <param name="packet">The packet to be encoded or decoded.</param>
355 /// <exception cref="ArgumentNullException"><paramref name="packet"/> is null.</exception>
356 /// <exception cref="InvalidOperationException">The current codec is not prepared yet.</exception>
357 /// <remarks>Any attempts to modify the packet will fail until the <see cref="InputProcessed"/> event for the packet is invoked.</remarks>
358 public void ProcessInput(MediaPacket packet)
360 ValidateNotDisposed();
364 throw new ArgumentNullException(nameof(packet));
367 MediaPacket.Lock packetLock = MediaPacket.Lock.Get(packet);
369 int ret = Interop.MediaCodec.Process(_handle, packetLock.GetHandle(), 0);
371 if (ret == (int)MediaCodecErrorCode.InvalidState)
373 throw new InvalidOperationException("The codec is in invalid state.");
376 MultimediaDebug.AssertNoError(ret);
380 /// Flushes both input and output buffers.
382 public void FlushBuffers()
384 ValidateNotDisposed();
386 int ret = Interop.MediaCodec.FlushBuffers(_handle);
388 MultimediaDebug.AssertNoError(ret);
392 /// Retrieves supported codec types for the specified params.
394 /// <param name="encoder">The value indicating encoder or decoder.</param>
395 /// <param name="type">The mime type to query.</param>
396 /// <returns>The values indicating which codec types are supported on the current device.</returns>
397 /// <exception cref="ArgumentException"><paramref name="type"/> is invalid.</exception>
398 public MediaCodecTypes GetCodecType(bool encoder, MediaFormatVideoMimeType type)
400 ValidateNotDisposed();
402 if (CheckMimeType(typeof(MediaFormatVideoMimeType), (int)type) == false)
407 return GetCodecType((int)type, encoder);
411 /// Retrieves supported codec types for the specified params.
413 /// <param name="encoder">The value indicating encoder or decoder.</param>
414 /// <param name="type">The mime type to query.</param>
415 /// <returns>The values indicating which codec types are supported on the current device.</returns>
416 /// <exception cref="ArgumentException"><paramref name="type"/> is invalid.</exception>
417 public MediaCodecTypes GetCodecType(bool encoder, MediaFormatAudioMimeType type)
419 ValidateNotDisposed();
421 if (CheckMimeType(typeof(MediaFormatAudioMimeType), (int)type) == false)
426 return GetCodecType((int)type, encoder);
429 private MediaCodecTypes GetCodecType(int mimeType, bool isEncoder)
431 int codecType = mimeType & CodecTypeMask;
434 int ret = Interop.MediaCodec.GetSupportedType(_handle, codecType, isEncoder, out value);
436 MultimediaDebug.AssertNoError(ret);
438 return (MediaCodecTypes)value;
441 private bool CheckMimeType(Type type, int value)
443 int codecType = value & CodecTypeMask;
445 if (!Enum.IsDefined(type, value))
447 throw new ArgumentException($"The mime type value is invalid : { value }.");
450 return Enum.IsDefined(typeof(SupportedCodecType), codecType);
453 #region OutputAvailable event
454 private EventHandler<OutputAvailableEventArgs> _outputAvailable;
455 private Interop.MediaCodec.OutputBufferAvailableCallback _outputBufferAvailableCb;
456 private object _outputAvailableLock = new object();
459 /// Occurs when an output buffer is available.
461 /// <remarks>The output packet needs to be disposed after it is used to clean up unmanaged resources.</remarks>
462 public event EventHandler<OutputAvailableEventArgs> OutputAvailable
466 ValidateNotDisposed();
468 lock (_outputAvailableLock)
470 if (_outputAvailable == null)
472 RegisterOutputAvailableCallback();
474 _outputAvailable += value;
479 ValidateNotDisposed();
481 lock (_outputAvailableLock)
483 _outputAvailable -= value;
484 if (_outputAvailable == null)
486 // We can remove handler first, because we know the method that unregisters callback does not throw.
487 UnregisterOutputAvailableCallback();
493 private void RegisterOutputAvailableCallback()
495 _outputBufferAvailableCb = (packetHandle, _) =>
497 if (_outputAvailable == null)
499 Interop.MediaPacket.Destroy(packetHandle);
503 OutputAvailableEventArgs args = null;
506 args = new OutputAvailableEventArgs(packetHandle);
510 Interop.MediaPacket.Destroy(packetHandle);
512 MultimediaLog.Error(typeof(MediaCodec).FullName, "Failed to raise OutputAvailable event", e);
517 _outputAvailable?.Invoke(this, args);
521 int ret = Interop.MediaCodec.SetOutputBufferAvailableCb(_handle, _outputBufferAvailableCb);
523 MultimediaDebug.AssertNoError(ret);
526 private void UnregisterOutputAvailableCallback()
528 int ret = Interop.MediaCodec.UnsetOutputBufferAvailableCb(_handle);
530 MultimediaDebug.AssertNoError(ret);
534 #region InputProcessed event
535 private Interop.MediaCodec.InputBufferUsedCallback _inputBufferUsedCb;
538 /// Occurs when an input packet is processed.
540 /// <see cref="ProcessInput(MediaPacket)"/>
541 public event EventHandler<InputProcessedEventArgs> InputProcessed;
543 private void RegisterInputProcessed()
545 _inputBufferUsedCb = (lockedPacketHandle, _) =>
547 MediaPacket packet = null;
549 // Lock must be disposed here, note that the packet won't be disposed.
550 using (MediaPacket.Lock packetLock =
551 MediaPacket.Lock.FromHandle(lockedPacketHandle))
553 Debug.Assert(packetLock != null);
555 packet = packetLock.MediaPacket;
557 Debug.Assert(packet != null);
559 InputProcessed?.Invoke(this, new InputProcessedEventArgs(packet));
562 int ret = Interop.MediaCodec.SetInputBufferUsedCb(_handle, _inputBufferUsedCb);
564 MultimediaDebug.AssertNoError(ret);
568 #region ErrorOccurred event
569 private Interop.MediaCodec.ErrorCallback _errorCb;
572 /// Occurs whenever an error is produced in the codec.
574 public event EventHandler<MediaCodecErrorOccurredEventArgs> ErrorOccurred;
576 private void RegisterErrorOccurred()
578 _errorCb = (errorCode, _) =>
580 MediaCodecError error = (Enum.IsDefined(typeof(MediaCodecError), errorCode)) ?
581 (MediaCodecError)errorCode : MediaCodecError.InternalError;
583 ErrorOccurred?.Invoke(this, new MediaCodecErrorOccurredEventArgs(error));
585 int ret = Interop.MediaCodec.SetErrorCb(_handle, _errorCb);
587 MultimediaDebug.AssertNoError(ret);
591 #region EosReached event
592 private Interop.MediaCodec.EosCallback _eosCb;
595 /// Occurs when the codec processes all input data.
597 public event EventHandler<EventArgs> EosReached;
599 private void RegisterEosReached()
601 _eosCb = _ => EosReached?.Invoke(this, EventArgs.Empty);
603 int ret = Interop.MediaCodec.SetEosCb(_handle, _eosCb);
605 MultimediaDebug.AssertNoError(ret);
610 #region BufferStatusChanged event
611 private Interop.MediaCodec.BufferStatusCallback _bufferStatusCb;
614 /// Occurs when the codec needs more data or has enough data.
616 public event EventHandler<BufferStatusChangedEventArgs> BufferStatusChanged;
618 private void RegisterBufferStatusChanged()
620 _bufferStatusCb = (statusCode, _) =>
622 Debug.Assert(Enum.IsDefined(typeof(MediaCodecStatus), statusCode),
623 $"{ statusCode } is not defined in MediaCodecStatus!");
625 BufferStatusChanged?.Invoke(this,
626 new BufferStatusChangedEventArgs((MediaCodecStatus)statusCode));
629 int ret = Interop.MediaCodec.SetBufferStatusCb(_handle, _bufferStatusCb);
631 MultimediaDebug.AssertNoError(ret);