using System;
using System.Runtime.InteropServices;
+using static Interop.AudioIO;
namespace Tizen.Multimedia
{
/// <summary>
/// Provides the ability to directly manage the system audio input devices.
/// </summary>
- /// <remarks>The recorder privilege(http://tizen.org/privilege/recorder) is required.</remarks>
+ /// <privilege>http://tizen.org/privilege/recorder</privilege>
public abstract class AudioCaptureBase : IDisposable
{
/// <summary>
- /// Specifies the minimum value allowed for the audio capture.
+ /// Specifies the minimum value allowed for the audio capture, in Hertz (Hz).
/// </summary>
+ /// <seealso cref="SampleRate"/>
public static readonly int MinSampleRate = 8000;
/// <summary>
- /// Specifies the maximum value allowed for the audio capture.
+ /// Specifies the maximum value allowed for the audio capture, in Hertz (Hz).
/// </summary>
+ /// <seealso cref="SampleRate"/>
public static readonly int MaxSampleRate = 48000;
internal IntPtr _handle = IntPtr.Zero;
SampleType = sampleType;
AudioIOUtil.ThrowIfError(
- Interop.AudioIO.AudioInput.Create(SampleRate, (int)Channel, (int)SampleType, out _handle));
+ AudioInput.Create(SampleRate, (int)Channel, (int)SampleType, out _handle));
RegisterStateChangedCallback();
}
/// </summary>
public event EventHandler<AudioIOStateChangedEventArgs> StateChanged;
- private Interop.AudioIO.AudioStateChangedCallback _stateChangedCallback;
+ private AudioStateChangedCallback _stateChangedCallback;
private void RegisterStateChangedCallback()
{
};
AudioIOUtil.ThrowIfError(
- Interop.AudioIO.AudioInput.SetStateChangedCallback(_handle, _stateChangedCallback, IntPtr.Zero));
+ AudioInput.SetStateChangedCallback(_handle, _stateChangedCallback, IntPtr.Zero));
}
#region Dispose support
}
}
- Interop.AudioIO.AudioInput.Destroy(_handle);
+ AudioInput.Destroy(_handle);
_handle = IntPtr.Zero;
_isDisposed = true;
}
}
/// <summary>
- /// Gets the sample rate of the audio input data stream.
+ /// Gets the sample rate of the audio input data stream, in Hertz (Hz).
/// </summary>
public int SampleRate { get; }
/// <exception cref="ObjectDisposedException">The AudioPlayback has already been disposed.</exception>
public int GetBufferSize()
{
- AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioInput.GetBufferSize(_handle, out var size));
+ AudioIOUtil.ThrowIfError(AudioInput.GetBufferSize(_handle, out var size));
return size;
}
{
ValidateState(AudioIOState.Idle);
- AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioInput.Prepare(_handle),
+ AudioIOUtil.ThrowIfError(AudioInput.Prepare(_handle),
"Failed to prepare the AudioCapture");
}
/// </summary>
/// <exception cref="InvalidOperationException">
/// Operation failed due to internal error.\n
- /// \n
+ /// -or-\n
/// The current state is <see cref="AudioIOState.Idle"/>.
/// </exception>
/// <seealso cref="Prepare"/>
{
ValidateState(AudioIOState.Running, AudioIOState.Paused);
- AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioInput.Unprepare(_handle),
+ AudioIOUtil.ThrowIfError(AudioInput.Unprepare(_handle),
"Failed to unprepare the AudioCapture");
}
/// Pauses buffering of audio data from the device.
/// </summary>
/// <exception cref="InvalidOperationException">
- /// The current state is <see cref="AudioState.Idle"/>.\n
+ /// The current state is <see cref="AudioIOState.Idle"/>.\n
/// -or-\n
/// The method is called in the <see cref="AsyncAudioCapture.DataAvailable"/> event handler.
/// </exception>
}
ValidateState(AudioIOState.Running);
- AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioInput.Pause(_handle));
+ AudioIOUtil.ThrowIfError(AudioInput.Pause(_handle));
}
/// <summary>
/// Resumes buffering audio data from the device.
/// </summary>
/// <exception cref="InvalidOperationException">
- /// The current state is <see cref="AudioState.Idle"/>.\n
+ /// The current state is <see cref="AudioIOState.Idle"/>.\n
/// -or-\n
/// The method is called in the <see cref="AsyncAudioCapture.DataAvailable"/> event handler.
/// </exception>
}
ValidateState(AudioIOState.Paused);
- AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioInput.Resume(_handle));
+ AudioIOUtil.ThrowIfError(AudioInput.Resume(_handle));
}
/// <summary>
/// Flushes and discards buffered audio data from the input stream.
/// </summary>
- /// <exception cref="InvalidOperationException">The current state is <see cref="AudioState.Idle"/>.</exception>
+ /// <exception cref="InvalidOperationException">The current state is <see cref="AudioIOState.Idle"/>.</exception>
public void Flush()
{
ValidateState(AudioIOState.Running, AudioIOState.Paused);
- int ret = Interop.AudioIO.AudioInput.Flush(_handle);
+ int ret = AudioInput.Flush(_handle);
MultimediaDebug.AssertNoError(ret);
}
throw new ArgumentNullException(nameof(streamPolicy));
}
- if (streamPolicy.Handle == IntPtr.Zero)
- {
- throw new ObjectDisposedException(nameof(streamPolicy));
- }
-
ValidateNotDisposed();
- AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioInput.SetStreamInfo(_handle, streamPolicy.Handle));
+ AudioIOUtil.ThrowIfError(AudioInput.SetStreamInfo(_handle, streamPolicy.Handle));
}
}
/// <param name="channel">The audio channel type.</param>
/// <param name="sampleType">The audio sample type.</param>
/// <exception cref="ArgumentOutOfRangeException">
- /// <paramref name="sampleRate"/> is less than <see cref="MinSampleRate"/>.\n
+ /// <paramref name="sampleRate"/> is less than <see cref="AudioCaptureBase.MinSampleRate"/>.\n
/// -or-\n
- /// <paramref name="sampleRate"/> is greater than <see cref="MaxSampleRate"/>.
+ /// <paramref name="sampleRate"/> is greater than <see cref="AudioCaptureBase.MaxSampleRate"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="channel"/> is invalid.\n
byte[] buffer = new byte[count];
- AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioInput.Read(_handle, buffer, count),
+ AudioIOUtil.ThrowIfError(AudioInput.Read(_handle, buffer, count),
"Failed to read");
return buffer;
/// <param name="channel">The audio channel type.</param>
/// <param name="sampleType">The audio sample type.</param>
/// <exception cref="ArgumentOutOfRangeException">
- /// <paramref name="sampleRate"/> is less than <see cref="MinSampleRate"/>.\n
+ /// <paramref name="sampleRate"/> is less than <see cref="AudioCaptureBase.MinSampleRate"/>.\n
/// -or-\n
- /// <paramref name="sampleRate"/> is greater than <see cref="MaxSampleRate"/>.
+ /// <paramref name="sampleRate"/> is greater than <see cref="AudioCaptureBase.MaxSampleRate"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="channel"/> is invalid.\n
_streamCallback = (IntPtr handle, uint length, IntPtr _) => { OnInputDataAvailable(handle, length); };
AudioIOUtil.ThrowIfError(
- Interop.AudioIO.AudioInput.SetStreamCallback(_handle, _streamCallback, IntPtr.Zero),
+ AudioInput.SetStreamCallback(_handle, _streamCallback, IntPtr.Zero),
$"Failed to initialize a { nameof(AsyncAudioCapture) }");
}
- private Interop.AudioIO.AudioStreamCallback _streamCallback;
+ private AudioStreamCallback _streamCallback;
private void OnInputDataAvailable(IntPtr handle, uint length)
{
IntPtr ptr = IntPtr.Zero;
try
{
- AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioInput.Peek(_handle, out ptr, ref length));
+ AudioIOUtil.ThrowIfError(AudioInput.Peek(_handle, out ptr, ref length));
byte[] buffer = new byte[length];
Marshal.Copy(ptr, buffer, 0, (int)length);
- Interop.AudioIO.AudioInput.Drop(_handle);
+ AudioInput.Drop(_handle);
DataAvailable?.Invoke(this, new AudioDataAvailableEventArgs(buffer));
}
*/
using System;
+using static Interop.AudioIO;
namespace Tizen.Multimedia
{
/// </summary>
public class AudioPlayback : IDisposable
{
+ /// <summary>
+ /// Specifies the minimum value allowed for the audio capture, in Hertz (Hz).
+ /// </summary>
+ /// <seealso cref="SampleRate"/>
public static readonly int MinSampleRate = 8000;
+
+ /// <summary>
+ /// Specifies the maximum value allowed for the audio capture, in Hertz (Hz).
+ /// </summary>
+ /// <seealso cref="SampleRate"/>
public static readonly int MaxSampleRate = 48000;
private IntPtr _handle = IntPtr.Zero;
/// <seealso cref="Write(byte[])"/>
public event EventHandler<AudioPlaybackBufferAvailableEventArgs> BufferAvailable;
- private Interop.AudioIO.AudioStreamCallback _streamCallback;
+ private AudioStreamCallback _streamCallback;
private void RegisterStreamCallback()
{
};
AudioIOUtil.ThrowIfError(
- Interop.AudioIO.AudioOutput.SetStreamChangedCallback(_handle, _streamCallback, IntPtr.Zero),
+ AudioOutput.SetStreamChangedCallback(_handle, _streamCallback, IntPtr.Zero),
$"Failed to create {nameof(AudioPlayback)}");
}
/// </summary>
public event EventHandler<AudioIOStateChangedEventArgs> StateChanged;
- private Interop.AudioIO.AudioStateChangedCallback _stateChangedCallback;
+ private AudioStateChangedCallback _stateChangedCallback;
private void RegisterStateChangedCallback()
{
};
AudioIOUtil.ThrowIfError(
- Interop.AudioIO.AudioOutput.SetStateChangedCallback(_handle, _stateChangedCallback, IntPtr.Zero),
+ AudioOutput.SetStateChangedCallback(_handle, _stateChangedCallback, IntPtr.Zero),
$"Failed to create {nameof(AudioPlayback)}");
}
#endregion
SampleType = sampleType;
AudioIOUtil.ThrowIfError(
- Interop.AudioIO.AudioOutput.Create(SampleRate, (int)Channel, (int)SampleType, out _handle),
+ AudioOutput.Create(SampleRate, (int)Channel, (int)SampleType, out _handle),
$"Failed to create {nameof(AudioPlayback)}");
RegisterStreamCallback();
}
}
- Interop.AudioIO.AudioOutput.Destroy(_handle);
+ AudioOutput.Destroy(_handle);
_handle = IntPtr.Zero;
_isDisposed = true;
}
}
/// <summary>
- /// Gets the sample rate of the audio output data stream.
+ /// Gets the sample rate of the audio output data stream, in Hertz (Hz).
/// </summary>
public int SampleRate { get; }
ValidateNotDisposed();
int audioType = 0;
- int ret = Interop.AudioIO.AudioOutput.GetSoundType(_handle, out audioType);
+ int ret = AudioOutput.GetSoundType(_handle, out audioType);
MultimediaDebug.AssertNoError(ret);
return (AudioStreamType)audioType;
/// <exception cref="ObjectDisposedException">The AudioPlayback has already been disposed.</exception>
public int GetBufferSize()
{
- AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioOutput.GetBufferSize(_handle, out var size));
+ AudioIOUtil.ThrowIfError(AudioOutput.GetBufferSize(_handle, out var size));
return size;
}
/// <summary>
/// Drains buffered audio data from the output stream.
- /// It blocks the calling thread until draining the stream buffer completely. (e.g end of playback)
+ /// It blocks the calling thread until draining the stream buffer completely. (e.g. end of playback)
/// </summary>
/// <exception cref="ObjectDisposedException">The AudioPlayback has already been disposed.</exception>
/// <exception cref="InvalidOperationException">The current state is <see cref="AudioIOState.Idle"/>.</exception>
{
ValidateState(AudioIOState.Running, AudioIOState.Paused);
- int ret = Interop.AudioIO.AudioOutput.Drain(_handle);
+ int ret = AudioOutput.Drain(_handle);
MultimediaDebug.AssertNoError(ret);
}
throw new ArgumentException("buffer has no data.(the Length is zero.)", nameof(buffer));
}
- int ret = Interop.AudioIO.AudioOutput.Write(_handle, buffer, (uint)buffer.Length);
+ int ret = AudioOutput.Write(_handle, buffer, (uint)buffer.Length);
AudioIOUtil.ThrowIfError(ret, "Failed to write buffer");
{
ValidateState(AudioIOState.Idle);
- AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioOutput.Prepare(_handle),
+ AudioIOUtil.ThrowIfError(AudioOutput.Prepare(_handle),
$"Failed to prepare the {nameof(AudioPlayback)}");
}
{
ValidateState(AudioIOState.Running, AudioIOState.Paused);
- AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioOutput.Unprepare(_handle),
+ AudioIOUtil.ThrowIfError(AudioOutput.Unprepare(_handle),
$"Failed to unprepare the {nameof(AudioPlayback)}");
}
}
ValidateState(AudioIOState.Running);
- AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioOutput.Pause(_handle));
+ AudioIOUtil.ThrowIfError(AudioOutput.Pause(_handle));
}
/// <summary>
}
ValidateState(AudioIOState.Paused);
- AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioOutput.Resume(_handle));
+ AudioIOUtil.ThrowIfError(AudioOutput.Resume(_handle));
}
/// <summary>
{
ValidateState(AudioIOState.Running, AudioIOState.Paused);
- int ret = Interop.AudioIO.AudioOutput.Flush(_handle);
+ int ret = AudioOutput.Flush(_handle);
MultimediaDebug.AssertNoError(ret);
}
throw new ArgumentNullException(nameof(streamPolicy));
}
- if (streamPolicy.Handle == IntPtr.Zero)
- {
- throw new ObjectDisposedException(nameof(streamPolicy));
- }
-
ValidateNotDisposed();
- AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioOutput.SetStreamInfo(_handle, streamPolicy.Handle));
+ AudioIOUtil.ThrowIfError(AudioOutput.SetStreamInfo(_handle, streamPolicy.Handle));
}
}
}
using System;
using System.Runtime.InteropServices;
+using Tizen.Multimedia;
internal static partial class Interop
{
internal static extern int Destroy(IntPtr handle);
[DllImport(Libraries.AudioIO, EntryPoint = "audio_in_set_sound_stream_info")]
- internal static extern int SetStreamInfo(IntPtr handle, IntPtr streamInfoHandle);
+ internal static extern int SetStreamInfo(IntPtr handle, AudioStreamPolicyHandle streamInfoHandle);
[DllImport(Libraries.AudioIO, EntryPoint = "audio_in_prepare")]
internal static extern int Prepare(IntPtr handle);
internal static extern int Resume(IntPtr handle);
[DllImport(Libraries.AudioIO, EntryPoint = "audio_out_set_sound_stream_info")]
- internal static extern int SetStreamInfo(IntPtr handle, IntPtr streamInfoHandle);
+ internal static extern int SetStreamInfo(IntPtr handle, AudioStreamPolicyHandle streamInfoHandle);
[DllImport(Libraries.AudioIO, EntryPoint = "audio_out_unprepare")]
internal static extern int Unprepare(IntPtr handle);
* limitations under the License.
*/
-using System;
using System.Runtime.InteropServices;
using Tizen.Multimedia;
internal static partial class TonePlayer
{
[DllImport(Libraries.TonePlayer, EntryPoint = "tone_player_start_new")]
- internal static extern TonePlayerError Start(ToneType tone, IntPtr streamInfoHandle,
+ internal static extern TonePlayerError Start(ToneType tone, AudioStreamPolicyHandle streamInfoHandle,
int durationMs, out int id);
[DllImport(Libraries.TonePlayer, EntryPoint = "tone_player_stop")]
internal delegate void WavPlayerCompletedCallback(int playerId, IntPtr userData);
[DllImport(Libraries.WavPlayer, EntryPoint = "wav_player_start_new")]
- internal static extern WavPlayerError Start(string filePath, IntPtr streamInfoHandle,
+ internal static extern WavPlayerError Start(string filePath, AudioStreamPolicyHandle streamInfoHandle,
WavPlayerCompletedCallback completedCallback, IntPtr userData, out int id);
[DllImport(Libraries.WavPlayer, EntryPoint = "wav_player_stop")]
using System;
using System.Threading;
using System.Threading.Tasks;
+using Native = Interop.TonePlayer;
namespace Tizen.Multimedia
{
var tcs = new TaskCompletionSource<bool>();
- Interop.TonePlayer.Start(tone, streamPolicy.Handle, durationMilliseconds, out var id).
+ Native.Start(tone, streamPolicy.Handle, durationMilliseconds, out var id).
Validate("Failed to play tone.");
using (RegisterCancellationAction(tcs, cancellationToken, id))
return cancellationToken.Register(() =>
{
- Interop.TonePlayer.Stop(id).Validate("Failed to cancel");
+ Native.Stop(id).Validate("Failed to cancel");
tcs.TrySetCanceled();
});
}
using System.IO;
using System.Threading;
using System.Threading.Tasks;
+using Native = Interop.WavPlayer;
namespace Tizen.Multimedia
{
/// </exception>
/// <exception cref="InvalidOperationException">An internal error occurs.</exception>
/// <exception cref="FileNotFoundException"><paramref name="path"/> does not exists.</exception>
- /// <exception cref="FileFormatException">The format of <paramref name=""/> is not supported.</exception>
+ /// <exception cref="FileFormatException">The format of <paramref name="path"/> is not supported.</exception>
/// <exception cref="ObjectDisposedException"><paramref name="streamPolicy"/> has already been disposed of.</exception>
public static Task StartAsync(string path, AudioStreamPolicy streamPolicy)
{
/// </exception>
/// <exception cref="InvalidOperationException">An internal error occurs.</exception>
/// <exception cref="FileNotFoundException"><paramref name="path"/> does not exists.</exception>
- /// <exception cref="FileFormatException">The format of <paramref name=""/> is not supported.</exception>
+ /// <exception cref="FileFormatException">The format of <paramref name="path"/> is not supported.</exception>
/// <exception cref="ObjectDisposedException"><paramref name="streamPolicy"/> has already been disposed.</exception>
public static Task StartAsync(string path, AudioStreamPolicy streamPolicy,
CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
- Interop.WavPlayer.WavPlayerCompletedCallback cb = (id_, _) => tcs.TrySetResult(true);
+ Native.WavPlayerCompletedCallback cb = (id_, _) => tcs.TrySetResult(true);
- Interop.WavPlayer.Start(path, streamPolicy.Handle, cb, IntPtr.Zero, out var id).
- Validate("Failed to play.");
-
- using (RegisterCancellationAction(tcs, cancellationToken, id))
+ using (ObjectKeeper.Get(cb))
{
- await tcs.Task;
+ Native.Start(path, streamPolicy.Handle, cb, IntPtr.Zero, out var id).
+ Validate("Failed to play.");
+
+ using (RegisterCancellationAction(tcs, cancellationToken, id))
+ {
+ await tcs.Task;
+ }
}
}
return cancellationToken.Register(() =>
{
- Interop.WavPlayer.Stop(id).Validate("Failed to cancel");
+ Native.Stop(id).Validate("Failed to cancel");
tcs.TrySetCanceled();
});
}
/// Retrieves all the fps by resolution supported by the camera.
/// </summary>
/// <since_tizen> 3 </since_tizen>
+ /// <param name="width">The width of required preview resolution.</param>
+ /// <param name="height">The height of required preview resolution.</param>
/// <returns>
/// It returns a list containing all the supported <see cref="CameraFps"/> by resolution.
/// </returns>
/// Retrieves all the fps by resolution supported by the camera.
/// </summary>
/// <since_tizen> 3 </since_tizen>
+ /// <param name="size">The size of required preview resolution.</param>
/// <returns>
/// It returns a list containing all the supported <see cref="CameraFps"/> by resolution.
/// </returns>
{
throw new NotSupportedException("Pan is not supported.");
}
+
return _panRange.Value;
}
}
{
throw new NotSupportedException("Tilt is not supported.");
}
+
return _tiltRange.Value;
}
}
[DllImport(Libraries.MediaCodec, EntryPoint = "mediacodec_set_input_buffer_used_cb")]
internal static extern int SetInputBufferUsedCb(IntPtr handle,
- InputBufferUsedCallback cb, IntPtr arg);
+ InputBufferUsedCallback cb, IntPtr arg = default(IntPtr));
[DllImport(Libraries.MediaCodec, EntryPoint = "mediacodec_unset_input_buffer_used_cb")]
internal static extern int UnsetInputBufferUsedCb(IntPtr handle);
[DllImport(Libraries.MediaCodec, EntryPoint = "mediacodec_set_output_buffer_available_cb")]
internal static extern int SetOutputBufferAvailableCb(IntPtr handle,
- OutputBufferAvailableCallback cb, IntPtr arg);
+ OutputBufferAvailableCallback cb, IntPtr arg = default(IntPtr));
[DllImport(Libraries.MediaCodec, EntryPoint = "mediacodec_unset_output_buffer_available_cb")]
internal static extern int UnsetOutputBufferAvailableCb(IntPtr handle);
[DllImport(Libraries.MediaCodec, EntryPoint = "mediacodec_set_error_cb")]
- internal static extern int SetErrorCb(IntPtr handle, ErrorCallback cb, IntPtr arg);
+ internal static extern int SetErrorCb(IntPtr handle, ErrorCallback cb, IntPtr arg = default(IntPtr));
[DllImport(Libraries.MediaCodec, EntryPoint = "mediacodec_unset_error_cb")]
internal static extern int UnsetErrorCb(IntPtr handle);
[DllImport(Libraries.MediaCodec, EntryPoint = "mediacodec_set_eos_cb")]
- internal static extern int SetEosCb(IntPtr handle, EosCallback cb, IntPtr arg);
+ internal static extern int SetEosCb(IntPtr handle, EosCallback cb, IntPtr arg = default(IntPtr));
[DllImport(Libraries.MediaCodec, EntryPoint = "mediacodec_unset_eos_cb")]
internal static extern int UnsetEosCb(IntPtr handle);
[DllImport(Libraries.MediaCodec, EntryPoint = "mediacodec_set_buffer_status_cb")]
internal static extern int SetBufferStatusCb(IntPtr handle, BufferStatusCallback cb,
- IntPtr arg);
+ IntPtr arg = default(IntPtr));
[DllImport(Libraries.MediaCodec, EntryPoint = "mediacodec_unset_buffer_status_cb")]
internal static extern int UnsetBufferStatusCb(IntPtr handle);
+/*
+ * 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.Runtime.InteropServices;
{
private const int CodecTypeMask = 0xFFFF;
private const int CodecKindMask = 0x3000;
-// private const int CodecKindAudio = 0x1000; // Not used
+ // private const int CodecKindAudio = 0x1000; // Not used
private const int CodecKindVideo = 0x2000;
private IntPtr _handle;
#region OutputAvailable event
private EventHandler<OutputAvailableEventArgs> _outputAvailable;
private Interop.MediaCodec.OutputBufferAvailableCallback _outputBufferAvailableCb;
+ private object _outputAvailableLock = new object();
/// <summary>
/// Occurs when an output buffer is available.
{
ValidateNotDisposed();
- if (_outputAvailable == null)
+ lock (_outputAvailableLock)
{
- RegisterOutputAvailableCallback();
+ if (_outputAvailable == null)
+ {
+ RegisterOutputAvailableCallback();
+ }
+ _outputAvailable += value;
}
- _outputAvailable += value;
-
}
remove
{
ValidateNotDisposed();
- _outputAvailable -= value;
- if (_outputAvailable == null)
+ lock (_outputAvailableLock)
{
- UnregisterOutputAvailableCallback();
+ _outputAvailable -= value;
+ if (_outputAvailable == null)
+ {
+ // We can remove handler first, because we know the method that unregisters callback does not throw.
+ UnregisterOutputAvailableCallback();
+ }
}
}
}
{
_outputBufferAvailableCb = (packetHandle, _) =>
{
- OutputAvailableEventArgs args = null;
+ if (_outputAvailable == null)
+ {
+ Interop.MediaPacket.Destroy(packetHandle);
+ return;
+ }
+ OutputAvailableEventArgs args = null;
try
{
args = new OutputAvailableEventArgs(packetHandle);
}
- catch (Exception)
+ catch (Exception e)
{
Interop.MediaPacket.Destroy(packetHandle);
- // TODO should we throw it to unmanaged code?
- throw;
+ MultimediaLog.Error(typeof(MediaCodec).FullName, "Failed to raise OutputAvailable event", e);
}
- //TODO dispose if no event handler registered
- _outputAvailable?.Invoke(this, args);
+ if (args != null)
+ {
+ _outputAvailable?.Invoke(this, args);
+ }
};
- int ret = Interop.MediaCodec.SetOutputBufferAvailableCb(_handle,
- _outputBufferAvailableCb, IntPtr.Zero);
+ int ret = Interop.MediaCodec.SetOutputBufferAvailableCb(_handle, _outputBufferAvailableCb);
MultimediaDebug.AssertNoError(ret);
}
InputProcessed?.Invoke(this, new InputProcessedEventArgs(packet));
};
- int ret = Interop.MediaCodec.SetInputBufferUsedCb(_handle,
- _inputBufferUsedCb, IntPtr.Zero);
-
- MultimediaDebug.AssertNoError(ret);
- }
-
- private void UnregisterInputProcessed()
- {
- int ret = Interop.MediaCodec.UnsetInputBufferUsedCb(_handle);
+ int ret = Interop.MediaCodec.SetInputBufferUsedCb(_handle, _inputBufferUsedCb);
MultimediaDebug.AssertNoError(ret);
}
ErrorOccurred?.Invoke(this, new MediaCodecErrorOccurredEventArgs(error));
};
- int ret = Interop.MediaCodec.SetErrorCb(_handle, _errorCb, IntPtr.Zero);
-
- MultimediaDebug.AssertNoError(ret);
- }
-
- private void UnregisterErrorOccurred()
- {
- int ret = Interop.MediaCodec.UnsetErrorCb(_handle);
+ int ret = Interop.MediaCodec.SetErrorCb(_handle, _errorCb);
MultimediaDebug.AssertNoError(ret);
}
#endregion
#region EosReached event
- private EventHandler<EventArgs> _eosReached;
private Interop.MediaCodec.EosCallback _eosCb;
- // TODO replace
/// <summary>
/// Occurs when the codec processes all input data.
/// </summary>
- public event EventHandler<EventArgs> EosReached
- {
- add
- {
- ValidateNotDisposed();
-
- if (_eosReached == null)
- {
- RegisterEosReached();
- }
- _eosReached += value;
-
- }
- remove
- {
- ValidateNotDisposed();
-
- _eosReached -= value;
- if (_eosReached == null)
- {
- UnregisterEosReached();
- }
- }
- }
+ public event EventHandler<EventArgs> EosReached;
private void RegisterEosReached()
{
- _eosCb = _ => _eosReached?.Invoke(this, EventArgs.Empty);
+ _eosCb = _ => EosReached?.Invoke(this, EventArgs.Empty);
- int ret = Interop.MediaCodec.SetEosCb(_handle, _eosCb, IntPtr.Zero);
+ int ret = Interop.MediaCodec.SetEosCb(_handle, _eosCb);
MultimediaDebug.AssertNoError(ret);
}
- private void UnregisterEosReached()
- {
- int ret = Interop.MediaCodec.UnsetEosCb(_handle);
-
- MultimediaDebug.AssertNoError(ret);
- }
#endregion
#region BufferStatusChanged event
- private EventHandler<BufferStatusChangedEventArgs> _bufferStatusChanged;
private Interop.MediaCodec.BufferStatusCallback _bufferStatusCb;
/// <summary>
/// Occurs when the codec needs more data or has enough data.
/// </summary>
- public event EventHandler<BufferStatusChangedEventArgs> BufferStatusChanged
- {
- add
- {
- ValidateNotDisposed();
-
- if (_bufferStatusChanged == null)
- {
- RegisterBufferStatusChanged();
- }
- _bufferStatusChanged += value;
-
- }
- remove
- {
- ValidateNotDisposed();
-
- _bufferStatusChanged -= value;
- if (_bufferStatusChanged == null)
- {
- UnregisterBufferStatusChanged();
- }
- }
- }
+ public event EventHandler<BufferStatusChangedEventArgs> BufferStatusChanged;
private void RegisterBufferStatusChanged()
{
Debug.Assert(Enum.IsDefined(typeof(MediaCodecStatus), statusCode),
$"{ statusCode } is not defined in MediaCodecStatus!");
- _bufferStatusChanged?.Invoke(this,
+ BufferStatusChanged?.Invoke(this,
new BufferStatusChangedEventArgs((MediaCodecStatus)statusCode));
};
- int ret = Interop.MediaCodec.SetBufferStatusCb(_handle, _bufferStatusCb, IntPtr.Zero);
-
- MultimediaDebug.AssertNoError(ret);
- }
-
- private void UnregisterBufferStatusChanged()
- {
- int ret = Interop.MediaCodec.UnsetBufferStatusCb(_handle);
+ int ret = Interop.MediaCodec.SetBufferStatusCb(_handle, _bufferStatusCb);
MultimediaDebug.AssertNoError(ret);
}
[DllImport(Libraries.Player, EntryPoint = "player_audio_effect_equalizer_is_available")]
internal static extern PlayerErrorCode EqualizerIsAvailable(IntPtr player, out bool available);
}
-
}
internal static extern PlayerErrorCode GetVolume(IntPtr player, out float left, out float right);
[DllImport(Libraries.Player, EntryPoint = "player_set_sound_stream_info")]
- internal static extern PlayerErrorCode SetAudioPolicyInfo(IntPtr player, IntPtr streamInfo);
+ internal static extern PlayerErrorCode SetAudioPolicyInfo(IntPtr player, AudioStreamPolicyHandle streamInfo);
[DllImport(Libraries.Player, EntryPoint = "player_set_audio_latency_mode")]
internal static extern PlayerErrorCode SetAudioLatencyMode(IntPtr player, AudioLatencyMode latencyMode);
/// <value>The percentage of the buffering.</value>
public int Percent { get; }
+ /// <summary>
+ /// Returns a string that represents the current object.
+ /// </summary>
+ /// <returns>A string that represents the current object.</returns>
public override string ToString()
{
return $"Percent={ Percent.ToString() }";
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
namespace Tizen.Multimedia
{
set;
}
+ /// <summary>
+ /// Returns a string that represents the current object.
+ /// </summary>
+ /// <returns>A string that represents the current object.</returns>
public override string ToString()
{
return $"Start={ Start.ToString() }, Current={ Current.ToString() }";
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
using System;
using System.Diagnostics;
using Native = Interop.AudioEffect;
/// <param name="value">The value indicating new gain in decibel(dB).</param>
/// <exception cref="ObjectDisposedException">The player that this EqualizerBand belongs to has already been disposed of.</exception>
/// <exception cref="ArgumentOutOfRangeException">
- /// <paramref name="value"/> is less than <see cref="AudioEffect.MinBandLevel"/>.\n
- /// -or-\n
- /// <paramref name="value"/> is greater than <see cref="AudioEffect.MaxBandLevel"/>.
+ /// <paramref name="value"/> is not inside of <see cref="AudioEffect.BandLevelRange"/>.
/// </exception>
public int Level
{
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
using System;
using static Interop;
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
namespace Tizen.Multimedia
{
/// <summary>
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
using System;
namespace Tizen.Multimedia
/// </summary>
public MediaStreamBufferStatus Status { get; }
+ /// <summary>
+ /// Returns a string that represents the current object.
+ /// </summary>
+ /// <returns>A string that represents the current object.</returns>
public override string ToString()
{
return $"Status : { Status.ToString() }";
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
using System;
using System.Diagnostics;
using static Interop;
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
using System;
namespace Tizen.Multimedia
/// </summary>
public class MediaStreamSeekingOccurredEventArgs : EventArgs
{
- /// <summary>
+ /// <summary>
/// Initializes a new instance of the MediaStreamSeekingOccurredEventArgs class.
/// </summary>
/// <param name="offset">The value indicating the new position to seek.</param>
public MediaStreamSeekingOccurredEventArgs(ulong offset)
{
- Offset = offset;
+ Offset = offset;
}
/// <summary>
/// </summary>
public ulong Offset { get; }
+ /// <summary>
+ /// Returns a string that represents the current object.
+ /// </summary>
+ /// <returns>A string that represents the current object.</returns>
public override string ToString() => $"Offset : { Offset.ToString() }";
}
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
using System;
using System.Collections.Generic;
using System.Diagnostics;
private MediaStreamConfiguration CreateAudioConfiguration(AudioMediaFormat format)
{
- if( format == null )
+ if (format == null)
{
return null;
}
-/// Media Uri source
/*
* Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
using System;
using static Interop;
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
using System;
namespace Tizen.Multimedia
/// </summary>
public PlaybackInterruptionReason Reason { get; }
+ /// <summary>
+ /// Returns a string that represents the current object.
+ /// </summary>
+ /// <returns>A string that represents the current object.</returns>
public override string ToString()
{
return $"Reason : { Reason.ToString() }";
--- /dev/null
+/*
+ * 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.Threading.Tasks;
+using System.Runtime.InteropServices;
+using System.Diagnostics;
+using System.IO;
+using System.Threading;
+using static Interop;
+
+namespace Tizen.Multimedia
+{
+ public partial class Player
+ {
+ /// <summary>
+ /// Occurs when playback of a media is finished.
+ /// </summary>
+ public event EventHandler<EventArgs> PlaybackCompleted;
+ private NativePlayer.PlaybackCompletedCallback _playbackCompletedCallback;
+
+ /// <summary>
+ /// Occurs when playback of a media is interrupted.
+ /// </summary>
+ public event EventHandler<PlaybackInterruptedEventArgs> PlaybackInterrupted;
+ private NativePlayer.PlaybackInterruptedCallback _playbackInterruptedCallback;
+
+ /// <summary>
+ /// Occurs when any error occurs.
+ /// </summary>
+ /// <remarks>The event handler will be executed on an internal thread.</remarks>
+ public event EventHandler<PlayerErrorOccurredEventArgs> ErrorOccurred;
+ private NativePlayer.PlaybackErrorCallback _playbackErrorCallback;
+
+ /// <summary>
+ /// Occurs when the video stream changed.
+ /// </summary>
+ /// <remarks>The event handler will be executed on an internal thread.</remarks>
+ public event EventHandler<VideoStreamChangedEventArgs> VideoStreamChanged;
+ private NativePlayer.VideoStreamChangedCallback _videoStreamChangedCallback;
+
+ /// <summary>
+ /// Occurs when the subtitle is updated.
+ /// </summary>
+ /// <remarks>The event handler will be executed on an internal thread.</remarks>
+ public event EventHandler<SubtitleUpdatedEventArgs> SubtitleUpdated;
+ private NativePlayer.SubtitleUpdatedCallback _subtitleUpdatedCallback;
+
+ /// <summary>
+ /// Occurs when there is a change in the buffering status of streaming.
+ /// </summary>
+ public event EventHandler<BufferingProgressChangedEventArgs> BufferingProgressChanged;
+ private NativePlayer.BufferingProgressCallback _bufferingProgressCallback;
+
+ internal event EventHandler<MediaStreamBufferStatusChangedEventArgs> MediaStreamAudioBufferStatusChanged;
+ private NativePlayer.MediaStreamBufferStatusCallback _mediaStreamAudioBufferStatusChangedCallback;
+
+ internal event EventHandler<MediaStreamBufferStatusChangedEventArgs> MediaStreamVideoBufferStatusChanged;
+ private NativePlayer.MediaStreamBufferStatusCallback _mediaStreamVideoBufferStatusChangedCallback;
+
+ internal event EventHandler<MediaStreamSeekingOccurredEventArgs> MediaStreamAudioSeekingOccurred;
+ private NativePlayer.MediaStreamSeekCallback _mediaStreamAudioSeekCallback;
+
+ internal event EventHandler<MediaStreamSeekingOccurredEventArgs> MediaStreamVideoSeekingOccurred;
+ private NativePlayer.MediaStreamSeekCallback _mediaStreamVideoSeekCallback;
+
+ private bool _callbackRegistered;
+
+ private void RegisterEvents()
+ {
+ if (_callbackRegistered)
+ {
+ return;
+ }
+ RegisterSubtitleUpdatedCallback();
+ RegisterErrorOccurredCallback();
+ RegisterPlaybackInterruptedCallback();
+ RegisterVideoStreamChangedCallback();
+ RegisterBufferingCallback();
+ RegisterMediaStreamBufferStatusCallback();
+ RegisterMediaStreamSeekCallback();
+ RegisterPlaybackCompletedCallback();
+
+ _callbackRegistered = true;
+ }
+
+ private void RegisterSubtitleUpdatedCallback()
+ {
+ _subtitleUpdatedCallback = (duration, text, _) =>
+ {
+ Log.Debug(PlayerLog.Tag, "duration : " + duration + ", text : " + text);
+ SubtitleUpdated?.Invoke(this, new SubtitleUpdatedEventArgs(duration, text));
+ };
+
+ NativePlayer.SetSubtitleUpdatedCb(Handle, _subtitleUpdatedCallback).
+ ThrowIfFailed("Failed to initialize the player");
+ }
+
+ private void RegisterPlaybackCompletedCallback()
+ {
+ _playbackCompletedCallback = _ =>
+ {
+ Log.Debug(PlayerLog.Tag, "completed callback");
+ PlaybackCompleted?.Invoke(this, EventArgs.Empty);
+ };
+ NativePlayer.SetCompletedCb(Handle, _playbackCompletedCallback).
+ ThrowIfFailed("Failed to set PlaybackCompleted");
+ }
+
+ private void RegisterPlaybackInterruptedCallback()
+ {
+ _playbackInterruptedCallback = (code, _) =>
+ {
+ if (!Enum.IsDefined(typeof(PlaybackInterruptionReason), code))
+ {
+ return;
+ }
+
+ if (code == PlaybackInterruptionReason.ResourceConflict)
+ {
+ OnUnprepared();
+ }
+
+ Log.Warn(PlayerLog.Tag, "interrupted reason : " + code);
+ PlaybackInterrupted?.Invoke(this, new PlaybackInterruptedEventArgs(code));
+ };
+
+ NativePlayer.SetInterruptedCb(Handle, _playbackInterruptedCallback).
+ ThrowIfFailed("Failed to set PlaybackInterrupted");
+ }
+
+ private void RegisterErrorOccurredCallback()
+ {
+ _playbackErrorCallback = (code, _) =>
+ {
+ //TODO handle service disconnected error.
+ Log.Warn(PlayerLog.Tag, "error code : " + code);
+ ErrorOccurred?.Invoke(this, new PlayerErrorOccurredEventArgs((PlayerError)code));
+ };
+
+ NativePlayer.SetErrorCb(Handle, _playbackErrorCallback).
+ ThrowIfFailed("Failed to set PlaybackError");
+ }
+
+ #region VideoFrameDecoded event
+
+ private EventHandler<VideoFrameDecodedEventArgs> _videoFrameDecoded;
+
+ private NativePlayer.VideoFrameDecodedCallback _videoFrameDecodedCallback;
+
+ /// <summary>
+ /// Occurs when a video frame is decoded.
+ /// </summary>
+ /// <remarks>
+ /// <para>The event handler will be executed on an internal thread.</para>
+ /// <para>The <see cref="VideoFrameDecodedEventArgs.Packet"/> in event args should be disposed after use.</para>
+ /// </remarks>
+ /// <feature>http://tizen.org/feature/multimedia.raw_video</feature>
+ /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
+ /// <seealso cref="VideoFrameDecodedEventArgs.Packet"/>
+ public event EventHandler<VideoFrameDecodedEventArgs> VideoFrameDecoded
+ {
+ add
+ {
+ ValidationUtil.ValidateFeatureSupported(Features.RawVideo);
+
+ _videoFrameDecoded += value;
+ }
+ remove
+ {
+ ValidationUtil.ValidateFeatureSupported(Features.RawVideo);
+
+ _videoFrameDecoded -= value;
+ }
+ }
+
+ private void RegisterVideoFrameDecodedCallback()
+ {
+ _videoFrameDecodedCallback = (packetHandle, _) =>
+ {
+ var handler = _videoFrameDecoded;
+ if (handler != null)
+ {
+ Log.Debug(PlayerLog.Tag, "packet : " + packetHandle);
+ handler.Invoke(this,
+ new VideoFrameDecodedEventArgs(MediaPacket.From(packetHandle)));
+ }
+ else
+ {
+ MediaPacket.From(packetHandle).Dispose();
+ }
+ };
+
+ NativePlayer.SetVideoFrameDecodedCb(Handle, _videoFrameDecodedCallback).
+ ThrowIfFailed("Failed to register the VideoFrameDecoded");
+ }
+ #endregion
+
+ private void RegisterVideoStreamChangedCallback()
+ {
+ ValidatePlayerState(PlayerState.Idle);
+
+ _videoStreamChangedCallback = (width, height, fps, bitrate, _) =>
+ {
+ Log.Debug(PlayerLog.Tag, "height : " + height + ", width : " + width
+ + ", fps : " + fps + ", bitrate : " + bitrate);
+
+ VideoStreamChanged?.Invoke(this, new VideoStreamChangedEventArgs(height, width, fps, bitrate));
+ };
+
+ NativePlayer.SetVideoStreamChangedCb(Handle, _videoStreamChangedCallback).
+ ThrowIfFailed("Failed to set the video stream changed callback");
+ }
+
+ private void RegisterBufferingCallback()
+ {
+ _bufferingProgressCallback = (percent, _) =>
+ {
+ Log.Debug(PlayerLog.Tag, $"Buffering callback with percent { percent }");
+ BufferingProgressChanged?.Invoke(this, new BufferingProgressChangedEventArgs(percent));
+ };
+
+ NativePlayer.SetBufferingCb(Handle, _bufferingProgressCallback).
+ ThrowIfFailed("Failed to set BufferingProgress");
+ }
+
+ private void RegisterMediaStreamBufferStatusCallback()
+ {
+ _mediaStreamAudioBufferStatusChangedCallback = (status, _) =>
+ {
+ Debug.Assert(Enum.IsDefined(typeof(MediaStreamBufferStatus), status));
+ Log.Debug(PlayerLog.Tag, "audio buffer status : " + status);
+ MediaStreamAudioBufferStatusChanged?.Invoke(this,
+ new MediaStreamBufferStatusChangedEventArgs(status));
+ };
+ _mediaStreamVideoBufferStatusChangedCallback = (status, _) =>
+ {
+ Debug.Assert(Enum.IsDefined(typeof(MediaStreamBufferStatus), status));
+ Log.Debug(PlayerLog.Tag, "video buffer status : " + status);
+ MediaStreamVideoBufferStatusChanged?.Invoke(this,
+ new MediaStreamBufferStatusChangedEventArgs(status));
+ };
+
+ RegisterMediaStreamBufferStatusCallback(StreamType.Audio, _mediaStreamAudioBufferStatusChangedCallback);
+ RegisterMediaStreamBufferStatusCallback(StreamType.Video, _mediaStreamVideoBufferStatusChangedCallback);
+ }
+
+ private void RegisterMediaStreamBufferStatusCallback(StreamType streamType,
+ NativePlayer.MediaStreamBufferStatusCallback cb)
+ {
+ NativePlayer.SetMediaStreamBufferStatusCb(Handle, streamType, cb).
+ ThrowIfFailed("Failed to SetMediaStreamBufferStatus");
+ }
+
+ private void RegisterMediaStreamSeekCallback()
+ {
+ _mediaStreamAudioSeekCallback = (offset, _) =>
+ {
+ Log.Debug(PlayerLog.Tag, "audio seeking offset : " + offset);
+ MediaStreamAudioSeekingOccurred?.Invoke(this, new MediaStreamSeekingOccurredEventArgs(offset));
+ };
+ _mediaStreamVideoSeekCallback = (offset, _) =>
+ {
+ Log.Debug(PlayerLog.Tag, "video seeking offset : " + offset);
+ MediaStreamVideoSeekingOccurred?.Invoke(this, new MediaStreamSeekingOccurredEventArgs(offset));
+ };
+
+ RegisterMediaStreamSeekCallback(StreamType.Audio, _mediaStreamAudioSeekCallback);
+ RegisterMediaStreamSeekCallback(StreamType.Video, _mediaStreamVideoSeekCallback);
+ }
+
+ private void RegisterMediaStreamSeekCallback(StreamType streamType, NativePlayer.MediaStreamSeekCallback cb)
+ {
+ NativePlayer.SetMediaStreamSeekCb(Handle, streamType, cb).
+ ThrowIfFailed("Failed to SetMediaStreamSeek");
+ }
+ }
+}
--- /dev/null
+/*
+ * 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.Threading.Tasks;
+using System.Runtime.InteropServices;
+using System.Diagnostics;
+using System.IO;
+using System.Threading;
+using static Interop;
+
+namespace Tizen.Multimedia
+{
+ public partial class Player
+ {
+ private void RetrieveProperties()
+ {
+ NativePlayer.GetAudioLatencyMode(Handle, out _audioLatencyMode).
+ ThrowIfFailed("Failed to initialize the player");
+
+ NativePlayer.IsLooping(Handle, out _isLooping).ThrowIfFailed("Failed to initialize the player");
+ }
+
+ /// <summary>
+ /// Gets the native handle of the player.
+ /// </summary>
+ /// <value>An IntPtr that contains the native handle of the player.</value>
+ /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
+ public IntPtr Handle
+ {
+ get
+ {
+ ValidateNotDisposed();
+ return _handle.DangerousGetHandle();
+ }
+ }
+
+ #region Network configuration
+ private string _cookie = "";
+ private string _userAgent = "";
+
+ /// <summary>
+ /// Gets or Sets the cookie for streaming playback.
+ /// </summary>
+ /// <remarks>To set, the player must be in the <see cref="PlayerState.Idle"/> state.</remarks>
+ /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
+ /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
+ /// <exception cref="ArgumentNullException">The value to set is null.</exception>
+ public string Cookie
+ {
+ get
+ {
+ Log.Info(PlayerLog.Tag, "get cookie : " + _cookie);
+ return _cookie;
+ }
+ set
+ {
+ ValidatePlayerState(PlayerState.Idle);
+
+ if (value == null)
+ {
+ throw new ArgumentNullException(nameof(value), "Cookie can't be null.");
+ }
+
+ NativePlayer.SetStreamingCookie(Handle, value, value.Length).
+ ThrowIfFailed("Failed to set the cookie to the player");
+
+ _cookie = value;
+ }
+ }
+
+ /// <summary>
+ /// Gets or Sets the user agent for streaming playback.
+ /// </summary>
+ /// <remarks>To set, the player must be in the <see cref="PlayerState.Idle"/> state.</remarks>
+ /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
+ /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
+ /// <exception cref="ArgumentNullException">The value to set is null.</exception>
+ public string UserAgent
+ {
+ get
+ {
+ Log.Info(PlayerLog.Tag, "get useragent : " + _userAgent);
+ return _userAgent;
+ }
+ set
+ {
+ ValidatePlayerState(PlayerState.Idle);
+
+ if (value == null)
+ {
+ throw new ArgumentNullException(nameof(value), "UserAgent can't be null.");
+ }
+
+ NativePlayer.SetStreamingUserAgent(Handle, value, value.Length).
+ ThrowIfFailed("Failed to set the user agent to the player");
+
+ _userAgent = value;
+ }
+ }
+ #endregion
+
+ /// <summary>
+ /// Gets the state of the player.
+ /// </summary>
+ /// <value>The current state of the player.</value>
+ /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
+ public PlayerState State
+ {
+ get
+ {
+ ValidateNotDisposed();
+
+ if (IsPreparing())
+ {
+ return PlayerState.Preparing;
+ }
+
+ NativePlayer.GetState(Handle, out var state).ThrowIfFailed("Failed to retrieve the state of the player");
+
+ Debug.Assert(Enum.IsDefined(typeof(PlayerState), state));
+
+ return (PlayerState)state;
+ }
+ }
+
+ private AudioLatencyMode _audioLatencyMode;
+
+ /// <summary>
+ /// Gets or sets the audio latency mode.
+ /// </summary>
+ /// <value>A <see cref="AudioLatencyMode"/> that specifies the mode. The default is <see cref="AudioLatencyMode.Mid"/>.</value>
+ /// <remarks>
+ /// If the mode is <see cref="AudioLatencyMode.High"/>,
+ /// audio output interval can be increased so, it can keep more audio data to play.
+ /// But, state transition like pause or resume can be more slower than default(<see cref="AudioLatencyMode.Mid"/>).
+ /// </remarks>
+ /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
+ /// <exception cref="ArgumentException">The value is not valid.</exception>
+ public AudioLatencyMode AudioLatencyMode
+ {
+ get
+ {
+ Log.Info(PlayerLog.Tag, "get audio latency mode : " + _audioLatencyMode);
+ return _audioLatencyMode;
+ }
+ set
+ {
+ ValidateNotDisposed();
+
+ if (_audioLatencyMode == value)
+ {
+ return;
+ }
+ ValidationUtil.ValidateEnum(typeof(AudioLatencyMode), value);
+
+ NativePlayer.SetAudioLatencyMode(Handle, value).
+ ThrowIfFailed("Failed to set the audio latency mode of the player");
+
+ _audioLatencyMode = value;
+ }
+ }
+
+ private bool _isLooping;
+
+ /// <summary>
+ /// Gets or sets the looping state.
+ /// </summary>
+ /// <value>true if the playback is looping; otherwise, false. The default value is false.</value>
+ /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
+ public bool IsLooping
+ {
+ get
+ {
+ Log.Info(PlayerLog.Tag, "get looping : " + _isLooping);
+ return _isLooping;
+ }
+ set
+ {
+ ValidateNotDisposed();
+
+ if (_isLooping == value)
+ {
+ return;
+ }
+
+ NativePlayer.SetLooping(Handle, value).ThrowIfFailed("Failed to set the looping state of the player");
+
+ _isLooping = value;
+ }
+ }
+
+ #region Display methods
+ /// <summary>
+ /// Gets the display settings.
+ /// </summary>
+ /// <value>A <see cref="PlayerDisplaySettings"/> that specifies the display settings.</value>
+ public PlayerDisplaySettings DisplaySettings { get; }
+
+ private Display _display;
+
+ private PlayerErrorCode SetDisplay(Display display)
+ {
+ if (display == null)
+ {
+ Log.Info(PlayerLog.Tag, "set display to none");
+ return NativePlayer.SetDisplay(Handle, DisplayType.None, IntPtr.Zero);
+ }
+
+ return display.ApplyTo(this);
+ }
+
+ private void ReplaceDisplay(Display newDisplay)
+ {
+ _display?.SetOwner(null);
+ _display = newDisplay;
+ _display?.SetOwner(this);
+ }
+
+ /// <summary>
+ /// Gets or sets the display.
+ /// </summary>
+ /// <value>A <see cref="Multimedia.Display"/> that specifies the display.</value>
+ /// <remarks>The player must be in the <see cref="PlayerState.Idle"/> state.</remarks>
+ /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
+ /// <exception cref="ArgumentException">The value has already been assigned to another player.</exception>
+ /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
+ public Display Display
+ {
+ get
+ {
+ return _display;
+ }
+ set
+ {
+ ValidatePlayerState(PlayerState.Idle);
+
+ if (value?.Owner != null)
+ {
+ if (ReferenceEquals(this, value.Owner))
+ {
+ return;
+ }
+
+ throw new ArgumentException("The display has already been assigned to another.");
+ }
+ SetDisplay(value).ThrowIfFailed("Failed to set the display to the player");
+
+ ReplaceDisplay(value);
+ }
+ }
+
+ PlayerErrorCode IDisplayable<PlayerErrorCode>.ApplyEvasDisplay(DisplayType type, ElmSharp.EvasObject evasObject)
+ {
+ Debug.Assert(IsDisposed == false);
+
+ Debug.Assert(Enum.IsDefined(typeof(DisplayType), type));
+
+ return NativePlayer.SetDisplay(Handle, type, evasObject);
+ }
+ #endregion
+
+ private PlayerTrackInfo _audioTrack;
+
+ /// <summary>
+ /// Gets the track info for audio.
+ /// </summary>
+ /// <value>A <see cref="PlayerTrackInfo"/> for audio.</value>
+ public PlayerTrackInfo AudioTrackInfo
+ {
+ get
+ {
+ if (_audioTrack == null)
+ {
+ _audioTrack = new PlayerTrackInfo(this, StreamType.Audio);
+ }
+ return _audioTrack;
+ }
+ }
+
+ private PlayerTrackInfo _subtitleTrackInfo;
+
+ /// <summary>
+ /// Gets the track info for subtitle.
+ /// </summary>
+ /// <value>A <see cref="PlayerTrackInfo"/> for subtitle.</value>
+ public PlayerTrackInfo SubtitleTrackInfo
+ {
+ get
+ {
+ if (_subtitleTrackInfo == null)
+ {
+ _subtitleTrackInfo = new PlayerTrackInfo(this, StreamType.Text);
+ }
+ return _subtitleTrackInfo;
+ }
+ }
+
+ private StreamInfo _streamInfo;
+
+ /// <summary>
+ /// Gets the stream information.
+ /// </summary>
+ /// <value>A <see cref="StreamInfo"/> for this player.</value>
+ public StreamInfo StreamInfo
+ {
+ get
+ {
+ if (_streamInfo == null)
+ {
+ _streamInfo = new StreamInfo(this);
+ }
+ return _streamInfo;
+ }
+ }
+
+ private readonly AudioEffect _audioEffect;
+
+ /// <summary>
+ /// Gets the audio effect.
+ /// </summary>
+ /// <feature>http://tizen.org/feature/multimedia.custom_audio_effect</feature>
+ /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
+ public AudioEffect AudioEffect
+ {
+ get
+ {
+ if (_audioEffect == null)
+ {
+ throw new NotSupportedException($"The feature({Features.AudioEffect}) is not supported.");
+ }
+
+ return _audioEffect;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the mute state.
+ /// </summary>
+ /// <value>true if the player is muted; otherwise, false.</value>
+ /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
+ public bool Muted
+ {
+ get
+ {
+ bool value = false;
+ NativePlayer.IsMuted(Handle, out value).ThrowIfFailed("Failed to get the mute state of the player");
+
+ Log.Info(PlayerLog.Tag, "get mute : " + value);
+
+ return value;
+ }
+ set
+ {
+ NativePlayer.SetMute(Handle, value).ThrowIfFailed("Failed to set the mute state of the player");
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the current volume.
+ /// </summary>
+ /// <remarks>Valid volume range is from 0 to 1.0, inclusive.</remarks>
+ /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
+ /// <exception cref="ArgumentOutOfRangeException">
+ /// <paramref name="value"/> is less than zero.\n
+ /// -or-\n
+ /// <paramref name="value"/> is greater than 1.0.
+ /// </exception>
+ public float Volume
+ {
+ get
+ {
+ float value = 0.0F;
+ NativePlayer.GetVolume(Handle, out value, out value).
+ ThrowIfFailed("Failed to get the volume of the player");
+ return value;
+ }
+ set
+ {
+ if (value < 0F || 1.0F < value)
+ {
+ throw new ArgumentOutOfRangeException(nameof(value), value,
+ $"Valid volume range is 0 <= value <= 1.0, but got { value }.");
+ }
+
+ NativePlayer.SetVolume(Handle, value, value).
+ ThrowIfFailed("Failed to set the volume of the player");
+ }
+ }
+ }
+}
/// It also provides functions to adjust the configurations of the player such as playback rate, volume, looping etc.
/// Note that only one video player can be played at one time.
/// </remarks>
- public class Player : IDisposable, IDisplayable<PlayerErrorCode>
+ public partial class Player : IDisposable, IDisplayable<PlayerErrorCode>
{
private PlayerHandle _handle;
/// <summary>
- /// Occurs when playback of a media is finished.
- /// </summary>
- public event EventHandler<EventArgs> PlaybackCompleted;
- private NativePlayer.PlaybackCompletedCallback _playbackCompletedCallback;
-
- /// <summary>
- /// Occurs when playback of a media is interrupted.
- /// </summary>
- public event EventHandler<PlaybackInterruptedEventArgs> PlaybackInterrupted;
- private NativePlayer.PlaybackInterruptedCallback _playbackInterruptedCallback;
-
- /// <summary>
- /// Occurs when any error occurs.
- /// </summary>
- /// <remarks>The event handler will be executed on an internal thread.</remarks>
- public event EventHandler<PlayerErrorOccurredEventArgs> ErrorOccurred;
- private NativePlayer.PlaybackErrorCallback _playbackErrorCallback;
-
- /// <summary>
- /// Occurs when the video stream changed.
- /// </summary>
- /// <remarks>The event handler will be executed on an internal thread.</remarks>
- public event EventHandler<VideoStreamChangedEventArgs> VideoStreamChanged;
- private NativePlayer.VideoStreamChangedCallback _videoStreamChangedCallback;
-
- /// <summary>
- /// Occurs when the subtitle is updated.
- /// </summary>
- /// <remarks>The event handler will be executed on an internal thread.</remarks>
- public event EventHandler<SubtitleUpdatedEventArgs> SubtitleUpdated;
- private NativePlayer.SubtitleUpdatedCallback _subtitleUpdatedCallback;
-
- /// <summary>
- /// Occurs when there is a change in the buffering status of streaming.
- /// </summary>
- public event EventHandler<BufferingProgressChangedEventArgs> BufferingProgressChanged;
- private NativePlayer.BufferingProgressCallback _bufferingProgressCallback;
-
- internal event EventHandler<MediaStreamBufferStatusChangedEventArgs> MediaStreamAudioBufferStatusChanged;
- private NativePlayer.MediaStreamBufferStatusCallback _mediaStreamAudioBufferStatusChangedCallback;
-
- internal event EventHandler<MediaStreamBufferStatusChangedEventArgs> MediaStreamVideoBufferStatusChanged;
- private NativePlayer.MediaStreamBufferStatusCallback _mediaStreamVideoBufferStatusChangedCallback;
-
- internal event EventHandler<MediaStreamSeekingOccurredEventArgs> MediaStreamAudioSeekingOccurred;
- private NativePlayer.MediaStreamSeekCallback _mediaStreamAudioSeekCallback;
-
- internal event EventHandler<MediaStreamSeekingOccurredEventArgs> MediaStreamVideoSeekingOccurred;
- private NativePlayer.MediaStreamSeekCallback _mediaStreamVideoSeekCallback;
-
- /// <summary>
/// Initialize a new instance of the Player class.
/// </summary>
public Player()
{
- Log.Debug(PlayerLog.Tag, PlayerLog.Enter);
-
NativePlayer.Create(out _handle).ThrowIfFailed("Failed to create player");
Debug.Assert(_handle != null);
DisplaySettings = PlayerDisplaySettings.Create(this);
}
- private void RetrieveProperties()
- {
- Log.Debug(PlayerLog.Tag, PlayerLog.Enter);
-
- NativePlayer.GetAudioLatencyMode(Handle, out _audioLatencyMode).
- ThrowIfFailed("Failed to initialize the player");
-
- NativePlayer.IsLooping(Handle, out _isLooping).ThrowIfFailed("Failed to initialize the player");
-
- Log.Debug(PlayerLog.Tag, PlayerLog.Leave);
- }
-
- private bool _callbackRegistered;
-
- private void RegisterCallbacks()
- {
- Log.Debug(PlayerLog.Tag, PlayerLog.Enter);
-
- if (_callbackRegistered)
- {
- return;
- }
- RegisterSubtitleUpdatedCallback();
- RegisterErrorOccurredCallback();
- RegisterPlaybackInterruptedCallback();
- RegisterVideoStreamChangedCallback();
- RegisterBufferingCallback();
- RegisterMediaStreamBufferStatusCallback();
- RegisterMediaStreamSeekCallback();
- RegisterPlaybackCompletedCallback();
-
- _callbackRegistered = true;
- }
-
- /// <summary>
- /// Gets the native handle of the player.
- /// </summary>
- /// <value>An IntPtr that contains the native handle of the player.</value>
- /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
- public IntPtr Handle
- {
- get
- {
- ValidateNotDisposed();
- return _handle.DangerousGetHandle();
- }
- }
-
internal void ValidatePlayerState(params PlayerState[] desiredStates)
{
Debug.Assert(desiredStates.Length > 0);
$"Current State : { curState }, Valid State : { string.Join(", ", desiredStates) }.");
}
- #region Properties
- #region Network configuration
- private string _cookie = "";
- private string _userAgent = "";
-
- /// <summary>
- /// Gets or Sets the cookie for streaming playback.
- /// </summary>
- /// <remarks>To set, the player must be in the <see cref="PlayerState.Idle"/> state.</remarks>
- /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
- /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
- /// <exception cref="ArgumentNullException">The value to set is null.</exception>
- public string Cookie
- {
- get
- {
- Log.Info(PlayerLog.Tag, "get cookie : " + _cookie);
- return _cookie;
- }
- set
- {
- Log.Debug(PlayerLog.Tag, PlayerLog.Enter);
- ValidatePlayerState(PlayerState.Idle);
-
- if (value == null)
- {
- Log.Error(PlayerLog.Tag, "cookie can't be null");
- throw new ArgumentNullException(nameof(value), "Cookie can't be null.");
- }
-
- NativePlayer.SetStreamingCookie(Handle, value, value.Length).
- ThrowIfFailed("Failed to set the cookie to the player");
-
- _cookie = value;
- Log.Debug(PlayerLog.Tag, PlayerLog.Leave);
- }
- }
-
- /// <summary>
- /// Gets or Sets the user agent for streaming playback.
- /// </summary>
- /// <remarks>To set, the player must be in the <see cref="PlayerState.Idle"/> state.</remarks>
- /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
- /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
- /// <exception cref="ArgumentNullException">The value to set is null.</exception>
- public string UserAgent
- {
- get
- {
- Log.Info(PlayerLog.Tag, "get useragent : " + _userAgent);
- return _userAgent;
- }
- set
- {
- Log.Debug(PlayerLog.Tag, PlayerLog.Enter);
- ValidatePlayerState(PlayerState.Idle);
-
- if (value == null)
- {
- Log.Error(PlayerLog.Tag, "UserAgent can't be null");
- throw new ArgumentNullException(nameof(value), "UserAgent can't be null.");
- }
-
- NativePlayer.SetStreamingUserAgent(Handle, value, value.Length).
- ThrowIfFailed("Failed to set the user agent to the player");
-
- _userAgent = value;
- Log.Debug(PlayerLog.Tag, PlayerLog.Leave);
- }
- }
- #endregion
-
- /// <summary>
- /// Gets the state of the player.
- /// </summary>
- /// <value>The current state of the player.</value>
- /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
- public PlayerState State
- {
- get
- {
- ValidateNotDisposed();
-
- if (IsPreparing())
- {
- return PlayerState.Preparing;
- }
-
- int state = 0;
- NativePlayer.GetState(Handle, out state).ThrowIfFailed("Failed to retrieve the state of the player");
-
- Debug.Assert(Enum.IsDefined(typeof(PlayerState), state));
-
- return (PlayerState)state;
- }
- }
-
- private AudioLatencyMode _audioLatencyMode;
-
- /// <summary>
- /// Gets or sets the audio latency mode.
- /// </summary>
- /// <value>A <see cref="AudioLatencyMode"/> that specifies the mode. The default is <see cref="AudioLatencyMode.Mid"/>.</value>
- /// <remarks>
- /// If the mode is <see cref="AudioLatencyMode.High"/>,
- /// audio output interval can be increased so, it can keep more audio data to play.
- /// But, state transition like pause or resume can be more slower than default(<see cref="AudioLatencyMode.Mid"/>).
- /// </remarks>
- /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
- /// <exception cref="ArgumentException">The value is not valid.</exception>
- public AudioLatencyMode AudioLatencyMode
- {
- get
- {
- Log.Info(PlayerLog.Tag, "get audio latency mode : " + _audioLatencyMode);
- return _audioLatencyMode;
- }
- set
- {
- Log.Debug(PlayerLog.Tag, PlayerLog.Enter);
- ValidateNotDisposed();
-
- if (_audioLatencyMode == value)
- {
- return;
- }
- ValidationUtil.ValidateEnum(typeof(AudioLatencyMode), value);
-
- NativePlayer.SetAudioLatencyMode(Handle, value).
- ThrowIfFailed("Failed to set the audio latency mode of the player");
-
- _audioLatencyMode = value;
- }
- }
-
- private bool _isLooping;
-
- /// <summary>
- /// Gets or sets the looping state.
- /// </summary>
- /// <value>true if the playback is looping; otherwise, false. The default value is false.</value>
- /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
- public bool IsLooping
- {
- get
- {
- Log.Info(PlayerLog.Tag, "get looping : " + _isLooping);
- return _isLooping;
- }
- set
- {
- Log.Debug(PlayerLog.Tag, PlayerLog.Enter);
- ValidateNotDisposed();
-
- if (_isLooping == value)
- {
- return;
- }
-
- NativePlayer.SetLooping(Handle, value).ThrowIfFailed("Failed to set the looping state of the player");
-
- _isLooping = value;
- }
- }
-
- #region Display methods
- /// <summary>
- /// Gets the display settings.
- /// </summary>
- /// <value>A <see cref="PlayerDisplaySettings"/> that specifies the display settings.</value>
- public PlayerDisplaySettings DisplaySettings { get; }
-
- private Display _display;
-
- private PlayerErrorCode SetDisplay(Display display)
- {
- if (display == null)
- {
- Log.Info(PlayerLog.Tag, "set display to none");
- return NativePlayer.SetDisplay(Handle, DisplayType.None, IntPtr.Zero);
- }
-
- return display.ApplyTo(this);
- }
-
- private void ReplaceDisplay(Display newDisplay)
- {
- _display?.SetOwner(null);
- _display = newDisplay;
- _display?.SetOwner(this);
- }
-
- /// <summary>
- /// Gets or sets the display.
- /// </summary>
- /// <value>A <see cref="Multimedia.Display"/> that specifies the display.</value>
- /// <remarks>The player must be in the <see cref="PlayerState.Idle"/> state.</remarks>
- /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
- /// <exception cref="ArgumentException">The value has already been assigned to another player.</exception>
- /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
- public Display Display
- {
- get
- {
- return _display;
- }
- set
- {
- ValidatePlayerState(PlayerState.Idle);
-
- if (value?.Owner != null)
- {
- if (ReferenceEquals(this, value.Owner))
- {
- return;
- }
-
- throw new ArgumentException("The display has already been assigned to another.");
- }
- SetDisplay(value).ThrowIfFailed("Failed to set the display to the player");
-
- ReplaceDisplay(value);
- }
- }
-
- PlayerErrorCode IDisplayable<PlayerErrorCode>.ApplyEvasDisplay(DisplayType type, ElmSharp.EvasObject evasObject)
- {
- Debug.Assert(IsDisposed == false);
-
- Debug.Assert(Enum.IsDefined(typeof(DisplayType), type));
-
- return NativePlayer.SetDisplay(Handle, type, evasObject);
- }
- #endregion
-
- private PlayerTrackInfo _audioTrack;
-
- /// <summary>
- /// Gets the track info for audio.
- /// </summary>
- /// <value>A <see cref="PlayerTrackInfo"/> for audio.</value>
- public PlayerTrackInfo AudioTrackInfo
- {
- get
- {
- Log.Debug(PlayerLog.Tag, PlayerLog.Enter);
- if (_audioTrack == null)
- {
- _audioTrack = new PlayerTrackInfo(this, StreamType.Audio);
- }
- return _audioTrack;
- }
- }
-
- private PlayerTrackInfo _subtitleTrackInfo;
-
- /// <summary>
- /// Gets the track info for subtitle.
- /// </summary>
- /// <value>A <see cref="PlayerTrackInfo"/> for subtitle.</value>
- public PlayerTrackInfo SubtitleTrackInfo
- {
- get
- {
- Log.Debug(PlayerLog.Tag, PlayerLog.Enter);
- if (_subtitleTrackInfo == null)
- {
- _subtitleTrackInfo = new PlayerTrackInfo(this, StreamType.Text);
- }
- return _subtitleTrackInfo;
- }
- }
-
- private StreamInfo _streamInfo;
-
- /// <summary>
- /// Gets the stream information.
- /// </summary>
- /// <value>A <see cref="StreamInfo"/> for this player.</value>
- public StreamInfo StreamInfo
- {
- get
- {
- Log.Debug(PlayerLog.Tag, PlayerLog.Enter);
- if (_streamInfo == null)
- {
- _streamInfo = new StreamInfo(this);
- }
- return _streamInfo;
- }
- }
-
- private readonly AudioEffect _audioEffect;
-
- /// <summary>
- /// Gets the audio effect.
- /// </summary>
- /// <feature>http://tizen.org/feature/multimedia.custom_audio_effect</feature>
- /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
- public AudioEffect AudioEffect
- {
- get
- {
- if (_audioEffect == null)
- {
- throw new NotSupportedException($"The feature({Features.AudioEffect}) is not supported.");
- }
-
- return _audioEffect;
- }
- }
-
- #endregion
-
#region Dispose support
private bool _disposed;
/// </summary>
public void Dispose()
{
- Log.Debug(PlayerLog.Tag, PlayerLog.Enter);
Dispose(true);
}
#region Methods
/// <summary>
- /// Gets or sets the mute state.
- /// </summary>
- /// <value>true if the player is muted; otherwise, false.</value>
- /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
- public bool Muted
- {
- get
- {
- Log.Debug(PlayerLog.Tag, PlayerLog.Enter);
-
- bool value = false;
- NativePlayer.IsMuted(Handle, out value).ThrowIfFailed("Failed to get the mute state of the player");
-
- Log.Info(PlayerLog.Tag, "get mute : " + value);
-
- return value;
- }
- set
- {
- NativePlayer.SetMute(Handle, value).ThrowIfFailed("Failed to set the mute state of the player");
- }
- }
-
- /// <summary>
/// Gets the streaming download Progress.
/// </summary>
/// <returns>The <see cref="DownloadProgress"/> containing current download progress.</returns>
return new DownloadProgress(start, current);
}
- #region Volume
- /// <summary>
- /// Gets or sets the current volume.
- /// </summary>
- /// <remarks>Valid volume range is from 0 to 1.0, inclusive.</remarks>
- /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
- /// <exception cref="ArgumentOutOfRangeException">
- /// <paramref name="value"/> is less than zero.\n
- /// -or-\n
- /// <paramref name="value"/> is greater than 1.0.
- /// </exception>
- public float Volume
- {
- get
- {
- float value = 0.0F;
- NativePlayer.GetVolume(Handle, out value, out value).
- ThrowIfFailed("Failed to get the volume of the player");
- return value;
- }
- set
- {
- if (value < 0F || 1.0F < value)
- {
- throw new ArgumentOutOfRangeException(nameof(value), value,
- $"Valid volume range is 0 <= value <= 1.0, but got { value }.");
- }
-
- NativePlayer.SetVolume(Handle, value, value).
- ThrowIfFailed("Failed to set the volume of the player");
- }
- }
-
- #endregion
-
/// <summary>
/// Sets the subtitle path for playback.
/// </summary>
/// <seealso cref="SetSubtitle(string)"/>
public void SetSubtitleOffset(int offset)
{
- Log.Debug(PlayerLog.Tag, PlayerLog.Enter);
ValidatePlayerState(PlayerState.Playing, PlayerState.Paused);
var err = NativePlayer.SetSubtitlePositionOffset(Handle, offset);
private void Prepare()
{
- Log.Debug(PlayerLog.Tag, PlayerLog.Enter);
NativePlayer.Prepare(Handle).ThrowIfFailed("Failed to prepare the player");
}
+ /// <summary>
+ /// Called when the <see cref="Prepare"/> is invoked.
+ /// </summary>
protected virtual void OnPreparing()
{
- RegisterCallbacks();
+ RegisterEvents();
}
/// <summary>
OnUnprepared();
}
+ /// <summary>
+ /// Called after the <see cref="Player"/> is unprepared.
+ /// </summary>
+ /// <seealso cref="Unprepare"/>
protected virtual void OnUnprepared()
{
_source?.DetachFrom(this);
/// Applies the audio stream policy.
/// </summary>
/// <param name="policy">The <see cref="AudioStreamPolicy"/> to apply.</param>
- /// <remarks>The player must be in the <see cref="PlayerState.Idle"/> state.</remarks>
+ /// <remarks>
+ /// The player must be in the <see cref="PlayerState.Idle"/> state.\n
+ /// \n
+ /// <see cref="Player"/> does not support all <see cref="AudioStreamType"/>.\n
+ /// Supported types are <see cref="AudioStreamType.Media"/>, <see cref="AudioStreamType.System"/>,
+ /// <see cref="AudioStreamType.Alarm"/>, <see cref="AudioStreamType.Notification"/>,
+ /// <see cref="AudioStreamType.Emergency"/>, <see cref="AudioStreamType.VoiceInformation"/>,
+ /// <see cref="AudioStreamType.RingtoneVoip"/> and <see cref="AudioStreamType.MediaExternalOnly"/>.
+ /// </remarks>
/// <exception cref="ObjectDisposedException">
/// The player has already been disposed of.\n
/// -or-\n
/// </exception>
/// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
/// <exception cref="ArgumentNullException"><paramref name="policy"/> is null.</exception>
+ /// <exception cref="NotSupportedException">
+ /// <see cref="AudioStreamType"/> of <paramref name="policy"/> is not supported by <see cref="Player"/>.
+ /// </exception>
+ /// <seealso cref="AudioStreamPolicy"/>
public void ApplyAudioStreamPolicy(AudioStreamPolicy policy)
{
- Log.Debug(PlayerLog.Tag, PlayerLog.Enter);
if (policy == null)
{
throw new ArgumentNullException(nameof(policy));
}
- if (policy.Handle == IntPtr.Zero)
- {
- throw new ObjectDisposedException(nameof(policy));
- }
-
ValidatePlayerState(PlayerState.Idle);
NativePlayer.SetAudioPolicyInfo(Handle, policy.Handle).
}
#endregion
- #region Callback registrations
- private void RegisterSubtitleUpdatedCallback()
- {
- _subtitleUpdatedCallback = (duration, text, _) =>
- {
- Log.Debug(PlayerLog.Tag, "duration : " + duration + ", text : " + text);
- SubtitleUpdated?.Invoke(this, new SubtitleUpdatedEventArgs(duration, text));
- };
-
- NativePlayer.SetSubtitleUpdatedCb(Handle, _subtitleUpdatedCallback).
- ThrowIfFailed("Failed to initialize the player");
- }
-
- private void RegisterPlaybackCompletedCallback()
- {
- _playbackCompletedCallback = _ =>
- {
- Log.Debug(PlayerLog.Tag, "completed callback");
- PlaybackCompleted?.Invoke(this, EventArgs.Empty);
- };
- NativePlayer.SetCompletedCb(Handle, _playbackCompletedCallback).
- ThrowIfFailed("Failed to set PlaybackCompleted");
- }
-
- private void RegisterPlaybackInterruptedCallback()
- {
- _playbackInterruptedCallback = (code, _) =>
- {
- if (!Enum.IsDefined(typeof(PlaybackInterruptionReason), code))
- {
- return;
- }
-
- if (code == PlaybackInterruptionReason.ResourceConflict)
- {
- OnUnprepared();
- }
-
- Log.Warn(PlayerLog.Tag, "interrupted reason : " + code);
- PlaybackInterrupted?.Invoke(this, new PlaybackInterruptedEventArgs(code));
- };
-
- NativePlayer.SetInterruptedCb(Handle, _playbackInterruptedCallback).
- ThrowIfFailed("Failed to set PlaybackInterrupted");
- }
-
- private void RegisterErrorOccurredCallback()
- {
- _playbackErrorCallback = (code, _) =>
- {
- //TODO handle service disconnected error.
- Log.Warn(PlayerLog.Tag, "error code : " + code);
- ErrorOccurred?.Invoke(this, new PlayerErrorOccurredEventArgs((PlayerError)code));
- };
-
- NativePlayer.SetErrorCb(Handle, _playbackErrorCallback).
- ThrowIfFailed("Failed to set PlaybackError");
- }
-
- #region VideoFrameDecoded event
-
- private EventHandler<VideoFrameDecodedEventArgs> _videoFrameDecoded;
-
- private NativePlayer.VideoFrameDecodedCallback _videoFrameDecodedCallback;
-
- /// <summary>
- /// Occurs when a video frame is decoded.
- /// </summary>
- /// <remarks>
- /// <para>The event handler will be executed on an internal thread.</para>
- /// <para>The <see cref="VideoFrameDecodedEventArgs.Packet"/> in event args should be disposed after use.</para>
- /// </remarks>
- /// <feature>http://tizen.org/feature/multimedia.raw_video</feature>
- /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
- /// <seealso cref="VideoFrameDecodedEventArgs.Packet"/>
- public event EventHandler<VideoFrameDecodedEventArgs> VideoFrameDecoded
- {
- add
- {
- ValidationUtil.ValidateFeatureSupported(Features.RawVideo);
-
- _videoFrameDecoded += value;
- }
- remove
- {
- ValidationUtil.ValidateFeatureSupported(Features.RawVideo);
-
- _videoFrameDecoded -= value;
- }
- }
-
- private void RegisterVideoFrameDecodedCallback()
- {
- _videoFrameDecodedCallback = (packetHandle, _) =>
- {
- var handler = _videoFrameDecoded;
- if (handler != null)
- {
- Log.Debug(PlayerLog.Tag, "packet : " + packetHandle);
- handler.Invoke(this,
- new VideoFrameDecodedEventArgs(MediaPacket.From(packetHandle)));
- }
- else
- {
- MediaPacket.From(packetHandle).Dispose();
- }
- };
-
- NativePlayer.SetVideoFrameDecodedCb(Handle, _videoFrameDecodedCallback).
- ThrowIfFailed("Failed to register the VideoFrameDecoded");
- }
- #endregion
-
- private void RegisterVideoStreamChangedCallback()
- {
- ValidatePlayerState(PlayerState.Idle);
-
- _videoStreamChangedCallback = (width, height, fps, bitrate, _) =>
- {
- Log.Debug(PlayerLog.Tag, "height : " + height + ", width : " + width
- + ", fps : " + fps + ", bitrate : " + bitrate);
-
- VideoStreamChanged?.Invoke(this, new VideoStreamChangedEventArgs(height, width, fps, bitrate));
- };
-
- NativePlayer.SetVideoStreamChangedCb(Handle, _videoStreamChangedCallback).
- ThrowIfFailed("Failed to set the video stream changed callback");
- }
-
- private void RegisterBufferingCallback()
- {
- _bufferingProgressCallback = (percent, _) =>
- {
- Log.Debug(PlayerLog.Tag, $"Buffering callback with percent { percent }");
- BufferingProgressChanged?.Invoke(this, new BufferingProgressChangedEventArgs(percent));
- };
-
- NativePlayer.SetBufferingCb(Handle, _bufferingProgressCallback).
- ThrowIfFailed("Failed to set BufferingProgress");
- }
-
- private void RegisterMediaStreamBufferStatusCallback()
- {
- _mediaStreamAudioBufferStatusChangedCallback = (status, _) =>
- {
- Debug.Assert(Enum.IsDefined(typeof(MediaStreamBufferStatus), status));
- Log.Debug(PlayerLog.Tag, "audio buffer status : " + status);
- MediaStreamAudioBufferStatusChanged?.Invoke(this,
- new MediaStreamBufferStatusChangedEventArgs(status));
- };
- _mediaStreamVideoBufferStatusChangedCallback = (status, _) =>
- {
- Debug.Assert(Enum.IsDefined(typeof(MediaStreamBufferStatus), status));
- Log.Debug(PlayerLog.Tag, "video buffer status : " + status);
- MediaStreamVideoBufferStatusChanged?.Invoke(this,
- new MediaStreamBufferStatusChangedEventArgs(status));
- };
-
- RegisterMediaStreamBufferStatusCallback(StreamType.Audio, _mediaStreamAudioBufferStatusChangedCallback);
- RegisterMediaStreamBufferStatusCallback(StreamType.Video, _mediaStreamVideoBufferStatusChangedCallback);
- }
-
- private void RegisterMediaStreamBufferStatusCallback(StreamType streamType,
- NativePlayer.MediaStreamBufferStatusCallback cb)
- {
- NativePlayer.SetMediaStreamBufferStatusCb(Handle, streamType, cb).
- ThrowIfFailed("Failed to SetMediaStreamBufferStatus");
- }
-
- private void RegisterMediaStreamSeekCallback()
- {
- _mediaStreamAudioSeekCallback = (offset, _) =>
- {
- Log.Debug(PlayerLog.Tag, "audio seeking offset : " + offset);
- MediaStreamAudioSeekingOccurred?.Invoke(this, new MediaStreamSeekingOccurredEventArgs(offset));
- };
- _mediaStreamVideoSeekCallback = (offset, _) =>
- {
- Log.Debug(PlayerLog.Tag, "video seeking offset : " + offset);
- MediaStreamVideoSeekingOccurred?.Invoke(this, new MediaStreamSeekingOccurredEventArgs(offset));
- };
-
- RegisterMediaStreamSeekCallback(StreamType.Audio, _mediaStreamAudioSeekCallback);
- RegisterMediaStreamSeekCallback(StreamType.Video, _mediaStreamVideoSeekCallback);
- }
-
- private void RegisterMediaStreamSeekCallback(StreamType streamType, NativePlayer.MediaStreamSeekCallback cb)
- {
- NativePlayer.SetMediaStreamSeekCb(Handle, streamType, cb).
- ThrowIfFailed("Failed to SetMediaStreamSeek");
- }
- #endregion
-
#region Preparing state
private int _isPreparing;
/// This method supports the product infrastructure and is not intended to be used directly from application code.
/// </summary>
protected static Exception GetException(int errorCode, string message) =>
- ((PlayerErrorCode) errorCode).GetException(message);
+ ((PlayerErrorCode)errorCode).GetException(message);
}
}
/// </summary>
public class PlayerDisplaySettings
{
+ /// <summary>
+ /// This constructor supports the product infrastructure and is not intended to be used directly from application code.
+ /// </summary>
protected PlayerDisplaySettings(Player player)
{
if (player == null)
internal static PlayerDisplaySettings Create(Player player) => new PlayerDisplaySettings(player);
+ /// <summary>
+ /// Gets the player of this instance.
+ /// </summary>
+ /// <value>The <see cref="Player"/> of this <see cref="PlayerDisplaySettings"/> instance.</value>
protected Player Player { get; }
/// <summary>
/// <summary>
/// Specifies display modes for <see cref="Player"/>
/// </summary>
- /// <seealso cref="Display.Mode"/>
+ /// <seealso cref="PlayerDisplaySettings.Mode"/>
public enum PlayerDisplayMode
{
/// <summary>
OriginalOrFull,
/// <summary>
- /// Region of interest, See <see cref="Display.SetRoi(Rectangle)"/>.
+ /// Region of interest, See <see cref="PlayerDisplaySettings.SetRoi(Rectangle)"/>.
/// </summary>
Roi
}
/// </summary>
public PlayerError Error { get; }
+ /// <summary>
+ /// Returns a string that represents the current object.
+ /// </summary>
+ /// <returns>A string that represents the current object.</returns>
public override string ToString()
{
return $"Error={ Error.ToString() }";
set;
}
+ /// <summary>
+ /// Returns a string that represents the current object.
+ /// </summary>
+ /// <returns>A string that represents the current object.</returns>
public override string ToString() =>
$"SampleRate={ SampleRate.ToString() }, Channels={ Channels.ToString() }, BitRate={ BitRate.ToString() }";
}
set;
}
+ /// <summary>
+ /// Returns a string that represents the current object.
+ /// </summary>
+ /// <returns>A string that represents the current object.</returns>
public override string ToString()
{
return $"Fps={ Fps.ToString() }, BitRate={ BitRate.ToString() }, Size=[{ Size.ToString() }]";
/// </summary>
public string Text { get; }
+ /// <summary>
+ /// Returns a string that represents the current object.
+ /// </summary>
+ /// <returns>A string that represents the current object.</returns>
public override string ToString()
{
return $"Duration={ Duration.ToString() }, Text={ Text }";
-/// This File contains VideoStreamEventArgs class
-///
-/// Copyright 2016 by Samsung Electronics, Inc.,
/*
* Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
*
/// </summary>
public class VideoStreamChangedEventArgs : EventArgs
{
-
/// <summary>
/// Initializes a new instance of the VideoStreamChangedEventArgs class.
/// </summary>
/// </summary>
public int BitRate { get; }
+ /// <summary>
+ /// Returns a string that represents the current object.
+ /// </summary>
+ /// <returns>A string that represents the current object.</returns>
public override string ToString()
{
return $"Size=({ Size.ToString() }), Fps={ Fps.ToString() }, BitRate={ BitRate.ToString() }";
-using System;
+/*
+ * 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.Runtime.InteropServices;
internal static partial class Interop
-using System;
+/*
+ * 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.Runtime.InteropServices;
using Tizen.Multimedia;
+/*
+ * 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.Runtime.InteropServices;
using Tizen.Multimedia;
internal static extern RecorderError GetState(IntPtr handle, out RecorderState state);
[DllImport(Libraries.Recorder, EntryPoint = "recorder_set_sound_stream_info")]
- internal static extern RecorderError SetAudioStreamPolicy(IntPtr handle, IntPtr streamInfoHandle);
+ internal static extern RecorderError SetAudioStreamPolicy(IntPtr handle, AudioStreamPolicyHandle streamInfoHandle);
[DllImport(Libraries.Recorder, EntryPoint = "recorder_set_error_cb")]
internal static extern RecorderError SetErrorCallback(IntPtr handle, RecorderErrorCallback callback, IntPtr userData);
using System;
using System.Runtime.InteropServices;
-using Tizen.Multimedia;
+using Tizen.Multimedia.Remoting;
internal static partial class Interop
{
* limitations under the License.
*/
-using System;
-
-namespace Tizen.Multimedia
+/// <summary>
+/// The System.Runtime.Remoting namespace provides classes and interfaces that work with remote process or device.
+/// </summary>
+namespace Tizen.Multimedia.Remoting
{
- internal static class ValidationUtil
- {
- internal static void ValidateEnum(Type enumType, object value, string paramName)
- {
- if (!Enum.IsDefined(enumType, value))
- {
- throw new ArgumentException($"Invalid { enumType.Name } value : { value }", paramName);
- }
- }
- }
-}
+}
\ No newline at end of file
using System;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Remoting
{
/// <summary>
/// Provides data for the <see cref="ScreenMirroring.StateChanged"/> event.
using System;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Remoting
{
internal static class InteropHelper
{
using System.Threading.Tasks;
using Native = Interop.ScreenMirroring;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Remoting
{
/// <summary>
/// Provides the ability to connect to and disconnect from a screen mirroring source,
*/
using System;
-using static Tizen.Multimedia.InteropHelper;
+using static Tizen.Multimedia.Remoting.InteropHelper;
using Native = Interop.ScreenMirroring;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Remoting
{
/// <summary>
/// Provides a means to retrieve the audio information which is negotiated with the source device.
using System;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Remoting
{
/// <summary>
/// Specifies audio codecs for <see cref="ScreenMirroring"/>.
using System;
using Tizen.Internals.Errors;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Remoting
{
internal enum ScreenMirroringErrorCode
{
*/
using System;
-using static Tizen.Multimedia.InteropHelper;
+using static Tizen.Multimedia.Remoting.InteropHelper;
using Native = Interop.ScreenMirroring;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Remoting
{
/// <summary>
/// Provides a means to retrieve the video information which is negotiated with the source device.
internal static void ThrowException(int errorCode, string errorMessage = null, string paramName = null)
{
StreamRecorderError err = (StreamRecorderError)errorCode;
- if(string.IsNullOrEmpty(errorMessage)) {
+ if (string.IsNullOrEmpty(errorMessage))
+ {
errorMessage = err.ToString();
}
- switch((StreamRecorderError)errorCode) {
- case StreamRecorderError.InvalidParameter:
- throw new ArgumentException(errorMessage, paramName);
- case StreamRecorderError.OutOfMemory:
- throw new OutOfMemoryException(errorMessage);
- case StreamRecorderError.PermissionDenied:
- throw new UnauthorizedAccessException(errorMessage);
- case StreamRecorderError.NotSupported:
- throw new NotSupportedException(errorMessage);
- case StreamRecorderError.InvalidState:
- case StreamRecorderError.InvalidOperation:
- case StreamRecorderError.OutOfStorage:
- throw new InvalidOperationException(errorMessage);
+ switch ((StreamRecorderError)errorCode)
+ {
+ case StreamRecorderError.InvalidParameter:
+ throw new ArgumentException(errorMessage, paramName);
+ case StreamRecorderError.OutOfMemory:
+ throw new OutOfMemoryException(errorMessage);
+ case StreamRecorderError.PermissionDenied:
+ throw new UnauthorizedAccessException(errorMessage);
+ case StreamRecorderError.NotSupported:
+ throw new NotSupportedException(errorMessage);
+ case StreamRecorderError.InvalidState:
+ case StreamRecorderError.InvalidOperation:
+ case StreamRecorderError.OutOfStorage:
+ throw new InvalidOperationException(errorMessage);
}
}
}
+/*
+ * 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.Runtime.InteropServices;
using Tizen;
using System;
using System.Runtime.InteropServices;
-using Tizen.Multimedia;
+using Tizen.Multimedia.Vision;
/// <summary>
/// Interop APIs
using System;
using System.Runtime.InteropServices;
-using Tizen.Multimedia;
+using Tizen.Multimedia.Vision;
/// <summary>
/// Interop APIs
}
- internal static Tizen.Multimedia.Quadrangle ToApiStruct(this MediaVision.Quadrangle quadrangle)
+ internal static Quadrangle ToApiStruct(this MediaVision.Quadrangle quadrangle)
{
Tizen.Multimedia.Point[] points = new Tizen.Multimedia.Point[4];
for (int i = 0; i < 4; ++i)
{
points[i] = quadrangle.points[i].ToApiStruct();
}
- return new Tizen.Multimedia.Quadrangle(points);
+ return new Quadrangle(points);
}
- internal static MediaVision.Quadrangle ToMarshalable(this Tizen.Multimedia.Quadrangle quadrangle)
+ internal static MediaVision.Quadrangle ToMarshalable(this Quadrangle quadrangle)
{
MediaVision.Point[] points = new MediaVision.Point[4];
for (int i = 0; i < 4; ++i)
internal static extern int GetWidth(IntPtr source, out uint imageWidth);
[DllImport(Libraries.MediaVision, EntryPoint = "mv_source_get_colorspace")]
- internal static extern int GetColorspace(IntPtr /* mv_source_h */ source, out Tizen.Multimedia.Colorspace colorspace);
+ internal static extern int GetColorspace(IntPtr /* mv_source_h */ source, out Colorspace colorspace);
}
/// <summary>
internal static extern int Destroy(IntPtr handle);
[DllImport(Libraries.MediaVision, EntryPoint = "mv_engine_config_set_double_attribute")]
- internal static extern Tizen.Multimedia.MediaVisionError SetDouble(IntPtr handle, string name, double value);
+ internal static extern MediaVisionError SetDouble(IntPtr handle, string name, double value);
[DllImport(Libraries.MediaVision, EntryPoint = "mv_engine_config_set_int_attribute")]
- internal static extern Tizen.Multimedia.MediaVisionError SetInt(IntPtr handle, string name, int value);
+ internal static extern MediaVisionError SetInt(IntPtr handle, string name, int value);
[DllImport(Libraries.MediaVision, EntryPoint = "mv_engine_config_set_bool_attribute")]
- internal static extern Tizen.Multimedia.MediaVisionError SetBool(IntPtr handle, string name, bool value);
+ internal static extern MediaVisionError SetBool(IntPtr handle, string name, bool value);
[DllImport(Libraries.MediaVision, EntryPoint = "mv_engine_config_set_string_attribute")]
- internal static extern Tizen.Multimedia.MediaVisionError SetString(IntPtr handle, string name, string value);
+ internal static extern MediaVisionError SetString(IntPtr handle, string name, string value);
[DllImport(Libraries.MediaVision, EntryPoint = "mv_engine_config_get_double_attribute")]
- internal static extern Tizen.Multimedia.MediaVisionError GetDouble(IntPtr handle, string name, out double value);
+ internal static extern MediaVisionError GetDouble(IntPtr handle, string name, out double value);
[DllImport(Libraries.MediaVision, EntryPoint = "mv_engine_config_get_int_attribute")]
- internal static extern Tizen.Multimedia.MediaVisionError GetInt(IntPtr handle, string name, out int value);
+ internal static extern MediaVisionError GetInt(IntPtr handle, string name, out int value);
[DllImport(Libraries.MediaVision, EntryPoint = "mv_engine_config_get_bool_attribute")]
- internal static extern Tizen.Multimedia.MediaVisionError GetBool(IntPtr handle, string name, out bool value);
+ internal static extern MediaVisionError GetBool(IntPtr handle, string name, out bool value);
[DllImport(Libraries.MediaVision, EntryPoint = "mv_engine_config_get_string_attribute")]
- internal static extern Tizen.Multimedia.MediaVisionError GetString(IntPtr handle, string name, out IntPtr value);
+ internal static extern MediaVisionError GetString(IntPtr handle, string name, out IntPtr value);
}
}
}
using System;
using System.Runtime.InteropServices;
-using Tizen.Multimedia;
+using Tizen.Multimedia.Vision;
/// <summary>
/// Interop APIs
using System;
using System.Runtime.InteropServices;
-using Tizen.Multimedia;
+using Tizen.Multimedia.Vision;
/// <summary>
/// Interop APIs
using System;
using System.Runtime.InteropServices;
-using Tizen.Multimedia;
+using Tizen.Multimedia.Vision;
/// <summary>
/// Interop APIs
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents a detected barcode.
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents a configuration of <see cref="BarcodeDetector"/>.
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Specifies the target of <see cref="BarcodeDetector"/>.
using InteropBarcode = Interop.MediaVision.BarcodeDetector;
using Unmanaged = Interop.MediaVision;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Provides the ability to detect barcodes on image sources.
using Tizen.Common;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents a configuration of <see cref="BarcodeGenerator"/> instances.
using System;
using InteropBarcode = Interop.MediaVision.BarcodeGenerator;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Provides the ability to generate barcodes and QR codes.
using System;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents a configuration for the image to be generated by <see cref="BarcodeGenerator"/>.
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Specifies supported image formats for <see cref="BarcodeGenerator"/>
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Specifies the supported barcode types.
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Specifies colorspaces for MediaVision.
using System.Runtime.InteropServices;
using static Interop.MediaVision;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// A base class for configuration classes.
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Specifies the supported QR code error correction level.
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Specifies the eyes state types.
using System;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents a configuration of <see cref="FaceDetector"/> instances.
using System.Threading.Tasks;
using InteropFace = Interop.MediaVision.Face;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Provides the ability to detect faces on image sources.
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents a configuration of <see cref="FaceRecognizer"/> instances.
using System.Runtime.InteropServices;
using InteropModel = Interop.MediaVision.FaceRecognitionModel;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents the face recognition model interface.
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Specifies the face recognition model learning algorithms.
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents result of <see cref="FaceRecognizer"/> operations.
using System.Threading.Tasks;
using InteropFace = Interop.MediaVision.Face;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Provides the ability to recognize faces, face expressions and eye condition on image sources.
TaskCompletionSource<FacialExpression> tcsResult = new TaskCompletionSource<FacialExpression>();
- InteropFace.MvFaceFacialExpressionRecognizedCallback cb = (IntPtr sourceHandle, IntPtr engineCfgHandle,
- global::Interop.MediaVision.Rectangle faceLocation, FacialExpression facialExpression, IntPtr _) =>
- {
- Log.Info(MediaVisionLog.Tag, $"Facial expression recognized, expression : {facialExpression}");
- if (!tcsResult.TrySetResult(facialExpression))
- {
- Log.Error(MediaVisionLog.Tag, "Failed to set facial result");
- }
- };
+ InteropFace.MvFaceFacialExpressionRecognizedCallback cb = (IntPtr sourceHandle, IntPtr engineCfgHandle,
+ global::Interop.MediaVision.Rectangle faceLocation, FacialExpression facialExpression, IntPtr _) =>
+ {
+ Log.Info(MediaVisionLog.Tag, $"Facial expression recognized, expression : {facialExpression}");
+ if (!tcsResult.TrySetResult(facialExpression))
+ {
+ Log.Error(MediaVisionLog.Tag, "Failed to set facial result");
+ }
+ };
using (var cbKeeper = ObjectKeeper.Get(cb))
{
using System.Threading.Tasks;
using InteropFace = Interop.MediaVision.Face;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Provides the ability to track faces on image sources.
using System.IO;
using InteropModel = Interop.MediaVision.FaceTrackingModel;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents face tracking model.
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents result of face tracking operation.
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Specifies the expression types for faces.
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents a configuration of fill operations of <see cref="ImageObject"/> instances.
using System.IO;
using InteropImage = Interop.MediaVision.Image;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents an image object.
/// Initializes a new instance of the <see cref="ImageObject"/> class from the specified file.
/// </summary>
/// <remarks>
- /// ImageObject has been saved by <see cref="Save()"/> can be loaded.
+ /// ImageObject has been saved by <see cref="Save(string)"/> can be loaded.
/// </remarks>
/// <param name="path">Path to the image object to load.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
using System;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents a configuration of <see cref="ImageRecognizer"/>.
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents a result of RecognizeAsync operations of <see cref="ImageRecognizer"/>.
using System.Threading.Tasks;
using InteropImage = Interop.MediaVision.Image;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Provides the ability to recognize images on image sources.
using System.Threading.Tasks;
using InteropImage = Interop.MediaVision.Image;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Provides the ability to track images on image sources.
using System;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents a configuration of <see cref="ImageTracker"/>.
using System.IO;
using InteropModel = Interop.MediaVision.ImageTrackingModel;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents the image tracking model interface.
using System.IO;
using Tizen.Internals.Errors;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
internal static class MediaVisionLog
{
using System.Diagnostics;
using InteropSource = Interop.MediaVision.MediaSource;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents the media vision source to keep information on image or video frame data as raw buffer.
{
fillAction(_handle);
}
- catch(Exception)
+ catch (Exception)
{
InteropSource.Destroy(_handle);
_disposed = true;
using System;
using System.Collections.Generic;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Provides data for the <see cref="MovementDetector.Detected"/> event.
using System;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents a configuration of <see cref="MovementDetector"/>.
using System;
using static Interop.MediaVision.Surveillance;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Provides the ability to detect movement on image sources.
using System;
using System.Collections.Generic;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Provides data for the <see cref="PersonAppearanceDetector.Detected"/> event.
using System;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents a configuration of <see cref="PersonAppearanceDetector"/> instances.
using System;
using static Interop.MediaVision.Surveillance;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Provides the ability to detect person appearance changes on image sources.
using System;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents a configuration of <see cref="PersonRecognizer"/> instances.
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents a result of <see cref="PersonRecognizer"/> instances.
using System;
using System.Collections.Generic;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Provides data for the <see cref="PersonRecognizer.Recognized"/> event.
using System;
using static Interop.MediaVision.Surveillance;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Provides the ability to recognize person on image sources.
using System;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents a QR configuration of <see cref="BarcodeGenerator"/>.
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Specifies the supported QR code encoding mode.
using System;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Represents a region with 4 <see cref="Point"/>s.
* limitations under the License.
*/
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// SurveillanceEngineConfiguration is a base class for surveillance configurations.
using System.Runtime.InteropServices;
using static Interop.MediaVision.Surveillance;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// SurveillanceEngine is a base class for surveillance event triggers.
using System;
using static Interop.MediaVision.Surveillance;
-namespace Tizen.Multimedia
+namespace Tizen.Multimedia.Vision
{
/// <summary>
/// Provides the ability to push source to surveillance engines.
* limitations under the License.
*/
-using System.Diagnostics;
-
-namespace Tizen.Multimedia
+/// <summary>
+/// The Tizen.Multimedia.Vision namespace contains classes and interfaces that support vision processing including
+/// face detection, face recognition, face tracking, barcode detection, barcode generation, flat image detection,
+/// flat image recognition, flat image tracking, flat image features extraction, movement detection,
+/// person appearance/disappearance detection and person recognition.
+/// </summary>
+namespace Tizen.Multimedia.Vision
{
- internal class MultimediaDebug
- {
- [Conditional("DEBUG")]
- internal static void AssertNoError(int errorCode)
- {
- Debug.Assert(errorCode == (int)Internals.Errors.ErrorCode.None,
- $"The API is supposed not to return an error! But it returns error({ errorCode }).",
- "Implementation of core may have been changed, modify the call to throw if the return code is not ok.");
- }
- }
}
* limitations under the License.
*/
- // This file specifies any assembly atrributes.
- // Note that InternalsVisibleToAttribute can be removed or added and needs to be only Multimedia packages only.
+// This file specifies any assembly attributes.
+// Note that InternalsVisibleToAttribute can be removed or added and needs to be Multimedia packages only.
using System.Runtime.CompilerServices;
+[assembly: InternalsVisibleTo("Tizen.Multimedia.AudioIO, " +
+ "PublicKey=0024000004800000940000000602000000240000525341310004000001000100d115b100424841" +
+ "6b12d21b626cfb17149c9303fe394693fd3b32d7872e89559a4fa96c98110c2e62eea48aca693b" +
+ "ddbe17094ca8ea2e2cd79970ca590fb672b9b371b5d7002076817321f62d6483ea50c56dbd1f37" +
+ "b185a4c24c47718876e6ae6d266508c551170d4cbdda3f82edaff9405ee3d7857282d8269e8e518d2f0fb2")]
+
[assembly: InternalsVisibleTo("Tizen.Multimedia.Camera, " +
"PublicKey=0024000004800000940000000602000000240000525341310004000001000100d115b100424841" +
"6b12d21b626cfb17149c9303fe394693fd3b32d7872e89559a4fa96c98110c2e62eea48aca693b" +
- /*
+/*
* Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the License);
namespace Tizen.Multimedia
{
- internal static class AudioDeviceLog
- {
- internal const string Tag = "Tizen.Multimedia.AudioDevice";
- }
-
/// <summary>
/// The Device API provides functions to query the information of sound devices.
/// </summary>
public class AudioDevice
{
private readonly int _id;
- private readonly string _name;
private readonly AudioDeviceType _type;
private readonly AudioDeviceIoDirection _ioDirection;
- private readonly AudioDeviceState _state;
- private readonly IntPtr _handle;
internal AudioDevice(IntPtr deviceHandle)
{
- _handle = deviceHandle;
- int ret;
-
- ret = Interop.AudioDevice.GetDeviceId(_handle, out _id);
- if (ret != 0)
- {
- Tizen.Log.Error(AudioDeviceLog.Tag, "Unable to get device Id: " + (AudioManagerError)ret);
- }
- AudioManagerErrorFactory.CheckAndThrowException(ret, _handle, "Unable to get device Id");
-
- IntPtr name;
- ret = Interop.AudioDevice.GetDeviceName(_handle, out name);
- if (ret != 0)
- {
- Tizen.Log.Error(AudioDeviceLog.Tag, "Unable to get device name" + (AudioManagerError)ret);
- }
- AudioManagerErrorFactory.CheckAndThrowException(ret, _handle, "Unable to get device name");
+ int ret = Interop.AudioDevice.GetDeviceId(deviceHandle, out _id);
+ MultimediaDebug.AssertNoError(ret);
- _name = Marshal.PtrToStringAnsi(name);
+ ret = Interop.AudioDevice.GetDeviceName(deviceHandle, out var name);
+ MultimediaDebug.AssertNoError(ret);
- ret = Interop.AudioDevice.GetDeviceType(_handle, out _type);
- if (ret != 0)
- {
- Tizen.Log.Error(AudioDeviceLog.Tag, "Unable to get device type" + (AudioManagerError)ret);
- }
- AudioManagerErrorFactory.CheckAndThrowException(ret, _handle, "Unable to get device type");
+ Name = Marshal.PtrToStringAnsi(name);
- ret = Interop.AudioDevice.GetDeviceIoDirection(_handle, out _ioDirection);
- if (ret != 0)
- {
- Tizen.Log.Error(AudioDeviceLog.Tag, "Unable to get device IoDirection" + (AudioManagerError)ret);
- }
- AudioManagerErrorFactory.CheckAndThrowException(ret, _handle, "Unable to get device IO Direction");
+ ret = Interop.AudioDevice.GetDeviceType(deviceHandle, out _type);
+ MultimediaDebug.AssertNoError(ret);
- ret = Interop.AudioDevice.GetDeviceState(_handle, out _state);
- if (ret != 0)
- {
- Tizen.Log.Error(AudioDeviceLog.Tag, "Unable to get device state" + (AudioManagerError)ret);
- }
- AudioManagerErrorFactory.CheckAndThrowException(ret, _handle, "Unable to get device state");
+ ret = (int)Interop.AudioDevice.GetDeviceIoDirection(deviceHandle, out _ioDirection);
+ MultimediaDebug.AssertNoError(ret);
}
/// <summary>
- /// The id of the device.
+ /// Gets the id of the device.
/// </summary>
+ /// <value>The id of the device.</value>
public int Id => _id;
/// <summary>
- /// The name of the device.
+ /// Gets the name of the device.
/// </summary>
- public string Name => _name;
+ /// <value>The name of the device.</value>
+ public string Name { get; }
/// <summary>
- /// The type of the device.
+ /// Gets the type of the device.
/// </summary>
+ /// <value>The <see cref="AudioDeviceType"/> of the device.</value>
public AudioDeviceType Type => _type;
/// <summary>
- /// The io direction of the device.
+ /// Gets the IO direction of the device.
/// </summary>
+ /// <value>The IO direction of the device.</value>
public AudioDeviceIoDirection IoDirection => _ioDirection;
/// <summary>
- /// The state of the device.
+ /// Gets the state of the device.
+ /// </summary>
+ /// <value>The <see cref="AudioDeviceState"/> of the device.</value>
+ public AudioDeviceState State
+ {
+ get
+ {
+ Interop.AudioDevice.GetDeviceState(Id, out var state).
+ Validate("Failed to get the state of the device");
+
+ return state;
+ }
+ }
+
+ /// <summary>
+ /// Returns a string that represents the current object.
/// </summary>
- public AudioDeviceState State => _state;
+ /// <returns>A string that represents the current object.</returns>
+ public override string ToString() =>
+ $"Id={Id}, Name={Name}, Type={Type}, IoDirection={IoDirection}, State={State}";
+
+ /// <summary>
+ /// Compares an object to an instance of <see cref="AudioDevice"/> for equality.
+ /// </summary>
+ /// <param name="obj">A <see cref="Object"/> to compare.</param>
+ /// <returns>true if the two devices are equal; otherwise, false.</returns>
+ public override bool Equals(object obj)
+ {
+ var rhs = obj as AudioDevice;
+ if (rhs == null)
+ {
+ return false;
+ }
+
+ return Id == rhs.Id;
+ }
+
- internal IntPtr Handle => _handle;
+ /// <summary>
+ /// Gets the hash code for this instance of <see cref="AudioDevice"/>.
+ /// </summary>
+ /// <returns>The hash code for this instance of <see cref="AudioDevice"/>.</returns>
+ public override int GetHashCode()
+ {
+ return Id.GetHashCode();
+ }
}
}
- /*
+/*
* Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the License);
namespace Tizen.Multimedia
{
/// <summary>
- /// Class extending EventArgs which contains parameters to be passed to event handler of DeviceConnected event
+ /// Provides data for the <see cref="AudioManager.DeviceConnectionChanged"/> event.
/// </summary>
public class AudioDeviceConnectionChangedEventArgs : EventArgs
{
}
/// <summary>
- /// The object of sound device
+ /// Gets the device.
/// </summary>
+ /// <value>The <see cref="AudioDevice"/>.</value>
public AudioDevice Device { get; }
/// <summary>
- /// The state of device connection: (true = connected, false = disconnected)
+ /// Gets the connection state of the device.
/// </summary>
+ /// <value>true if the device is connected; otherwise, false.</value>
public bool IsConnected { get; }
}
}
- /*
+/*
* Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the License);
namespace Tizen.Multimedia
{
/// <summary>
- /// Class extending EventArgs which contains parameters to be passed to event handler of DeviceInformationChanged event
+ /// Provides data for the <see cref="AudioManager.DeviceStateChanged"/> event.
/// </summary>
public class AudioDeviceStateChangedEventArgs : EventArgs
{
internal AudioDeviceStateChangedEventArgs(AudioDevice device, AudioDeviceState changedState)
{
Device = device;
- ChangedState = changedState;
+ State = changedState;
}
/// <summary>
- /// The object of sound device
+ /// Gets the device.
/// </summary>
+ /// <value>The <see cref="AudioDevice"/>.</value>
public AudioDevice Device { get; }
/// <summary>
- /// The entry of sound device state
+ /// Gets the state of the device.
/// </summary>
- public AudioDeviceState ChangedState { get; }
+ /// <value>The <see cref="AudioDeviceState"/> of the device.</value>
+ public AudioDeviceState State { get; }
}
}
- /*
+/*
* Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the License);
namespace Tizen.Multimedia
{
- internal static class AudioManagerLog
- {
- internal const string Tag = "Tizen.Multimedia.AudioManager";
- }
-
/// <summary>
- /// The Audio Manager class provides functions to get and set sound parameters like volume and devices.
+ /// Provides the ability to control volume levels and monitor audio devices.
/// </summary>
public static class AudioManager
{
- private static int _deviceConnectionChangedCallbackId = -1;
- private static int _deviceStateChangedCallbackId = -1;
-
- private static Interop.SoundDeviceConnectionChangedCallback _audioDeviceConnectionChangedCallback;
- private static Interop.SoundDeviceStateChangedCallback _audioDeviceStateChangedCallback;
-
- private static EventHandler<AudioDeviceConnectionChangedEventArgs> _audioDeviceConnectionChanged;
- private static EventHandler<AudioDeviceStateChangedEventArgs> _audioDeviceStateChanged;
-
- /// <summary>
- /// Constructor for AudioManager. Initializes the VolumeController property etc.
- /// </summary>
static AudioManager()
{
VolumeController = new AudioVolume();
}
/// <summary>
- /// Registers/Unregisters a function to be invoked when the state of connection of an Audio device was changed.
+ /// Gets the volume controller.
/// </summary>
- public static event EventHandler<AudioDeviceConnectionChangedEventArgs> DeviceConnectionChanged
+ /// <value>The <see cref="AudioVolume"/>.</value>
+ public static AudioVolume VolumeController { get; }
+
+ /// <summary>
+ /// Gets the all devices currently connected.
+ /// </summary>
+ /// <param name="options">The audio device options.</param>
+ /// <returns>An IEnumerable<AudioDevice> that contains connected devices.</returns>
+ public static IEnumerable<AudioDevice> GetConnectedDevices()
{
- add
+ IntPtr deviceListHandle = IntPtr.Zero;
+
+ try
{
- if (_audioDeviceConnectionChanged == null)
+ var ret = Interop.AudioDevice.GetDeviceList(AudioDeviceOptions.All, out deviceListHandle);
+
+ List<AudioDevice> result = new List<AudioDevice>();
+
+ if (ret == AudioManagerError.NoData)
{
- RegisterAudioDeviceEvent();
- Tizen.Log.Info(AudioManagerLog.Tag, "DeviceConnectionChanged event registered");
+ return result;
}
- _audioDeviceConnectionChanged += value;
- Tizen.Log.Info(AudioManagerLog.Tag, "DeviceConnectionChanged event added");
- }
- remove
- {
- if (_audioDeviceConnectionChanged?.GetInvocationList()?.GetLength(0) == 1)
+
+ ret.Validate("Failed to get connected devices");
+
+ while (ret == AudioManagerError.None)
{
- UnregisterDeviceConnectionChangedEvent();
+ ret = Interop.AudioDevice.GetNextDevice(deviceListHandle, out var deviceHandle);
+
+ if (ret == AudioManagerError.NoData)
+ {
+ break;
+ }
+
+ ret.Validate("Failed to get connected devices");
+
+ result.Add(new AudioDevice(deviceHandle));
}
- _audioDeviceConnectionChanged -= value;
- Tizen.Log.Info(AudioManagerLog.Tag, "DeviceConnectionChanged event removed");
+ return result;
+ }
+ finally
+ {
+ Interop.AudioDevice.FreeDeviceList(deviceListHandle);
}
}
+ #region DeviceConnectionChanged event
+ private static int _deviceConnectionChangedCallbackId = -1;
+
+ private static Interop.AudioDevice.ConnectionChangedCallback _audioDeviceConnectionChangedCallback;
+ private static EventHandler<AudioDeviceConnectionChangedEventArgs> _audioDeviceConnectionChanged;
+ private static object _audioDeviceConnectionLock = new object();
+
/// <summary>
- /// Registers/Unregisters a callback function to be invoked when the state of an Audio sound device was changed.
+ /// Occurs when the state of connection of an audio device changes.
/// </summary>
- public static event EventHandler<AudioDeviceStateChangedEventArgs> DeviceStateChanged
+ public static event EventHandler<AudioDeviceConnectionChangedEventArgs> DeviceConnectionChanged
{
add
{
- if (_audioDeviceStateChanged == null)
+ lock (_audioDeviceConnectionLock)
{
- RegisterDeviceStateChangedEvent();
+ if (_audioDeviceConnectionChanged == null)
+ {
+ RegisterAudioDeviceEvent();
+ }
+ _audioDeviceConnectionChanged += value;
}
- _audioDeviceStateChanged += value;
- Tizen.Log.Info(AudioManagerLog.Tag, "DeviceStateChanged event added");
}
remove
{
- if (_audioDeviceStateChanged?.GetInvocationList()?.GetLength(0) == 1)
+ if (value == null)
{
- UnregisterDeviceStateChangedEvent();
+ return;
+ }
+
+ lock (_audioDeviceConnectionLock)
+ {
+ if (_audioDeviceConnectionChanged == value)
+ {
+ UnregisterDeviceConnectionChangedEvent();
+ }
+ _audioDeviceConnectionChanged -= value;
}
- _audioDeviceStateChanged -= value;
- Tizen.Log.Info(AudioManagerLog.Tag, "DeviceStateChanged event removed");
}
}
- /// <summary>
- /// The VolumeController object (singleton) is-a part of SoundManager and its properties and methods are used via AudioManager
- /// </summary>
- public static AudioVolume VolumeController { get; }
+ private static void RegisterAudioDeviceEvent()
+ {
+ _audioDeviceConnectionChangedCallback = (IntPtr device, bool isConnected, IntPtr userData) =>
+ {
+ _audioDeviceConnectionChanged?.Invoke(null,
+ new AudioDeviceConnectionChangedEventArgs(new AudioDevice(device), isConnected));
+ };
+
+ Interop.AudioDevice.AddDeviceConnectionChangedCallback(AudioDeviceOptions.All,
+ _audioDeviceConnectionChangedCallback, IntPtr.Zero, out _deviceConnectionChangedCallbackId).
+ Validate("Unable to add device connection changed callback");
+ }
+
+ private static void UnregisterDeviceConnectionChangedEvent()
+ {
+ Interop.AudioDevice.RemoveDeviceConnectionChangedCallback(_deviceConnectionChangedCallbackId).
+ Validate("Unable to remove device connection changed callback");
+ }
+ #endregion
+
+ #region DeviceStateChanged event
+ private static int _deviceStateChangedCallbackId = -1;
+
+ private static Interop.AudioDevice.StateChangedCallback _audioDeviceStateChangedCallback;
+ private static EventHandler<AudioDeviceStateChangedEventArgs> _audioDeviceStateChanged;
+ private static object _audioDeviceStateLock = new object();
/// <summary>
- /// Gets the list consisting of all devices currently connected.
+ /// Occurs when the state of an audio device changes.
/// </summary>
- /// <param name="options">The audio device options</param>
- /// <returns>The list of connected devices: IEnumerable of Device objects</returns>
- public static IEnumerable<AudioDevice> GetCurrentDevices(AudioDeviceOptions options)
+ public static event EventHandler<AudioDeviceStateChangedEventArgs> DeviceStateChanged
{
- List<AudioDevice> audioDeviceList = new List<AudioDevice>();
- IntPtr deviceListHandle;
- IntPtr handlePosition;
- AudioDeviceIoDirection ioDirection;
-
- int ret = Interop.AudioDevice.GetCurrentDeviceList(options, out deviceListHandle);
- if (ret != (int)AudioManagerError.NoData)
- {
- AudioManagerErrorFactory.CheckAndThrowException(ret, "Unable to get next device");
- }
- while (ret == (int)AudioManagerError.None)
+ add
{
- ret = Interop.AudioDevice.GetNextDevice(deviceListHandle, out handlePosition);
- if (ret == (int)AudioManagerError.NoData)
+ lock (_audioDeviceStateLock)
{
- break;
+ if (_audioDeviceStateChanged == null)
+ {
+ RegisterDeviceStateChangedEvent();
+ }
+ _audioDeviceStateChanged += value;
}
- else if (ret != (int)AudioManagerError.None)
+ }
+ remove
+ {
+ if (value == null)
{
- AudioManagerErrorFactory.CheckAndThrowException(ret, "Unable to get next device");
+ return;
}
- if (options == AudioDeviceOptions.Input || (options == AudioDeviceOptions.Output))
+ lock (_audioDeviceStateLock)
{
- ret = Interop.AudioDevice.GetDeviceIoDirection(handlePosition, out ioDirection);
- if (ret != 0)
+ if (_audioDeviceStateChanged == value)
{
- Tizen.Log.Error(AudioManagerLog.Tag, "Unable to get device IoDirection" + (AudioManagerError)ret);
- AudioManagerErrorFactory.CheckAndThrowException(ret, handlePosition, "Unable to get device IO Direction");
- }
- else if (ioDirection == AudioDeviceIoDirection.InputAndOutput)
- {
- continue;
+ UnregisterDeviceStateChangedEvent();
}
+ _audioDeviceStateChanged -= value;
}
- audioDeviceList.Add(new AudioDevice(handlePosition));
}
- return audioDeviceList;
- }
-
- private static void RegisterAudioDeviceEvent()
- {
- _audioDeviceConnectionChangedCallback = (IntPtr device, bool isConnected, IntPtr userData) =>
- {
- AudioDeviceConnectionChangedEventArgs eventArgs = new AudioDeviceConnectionChangedEventArgs(new AudioDevice(device), isConnected);
- _audioDeviceConnectionChanged?.Invoke(null, eventArgs);
- };
- int ret = Interop.AudioDevice.AddDeviceConnectionChangedCallback(AudioDeviceOptions.All, _audioDeviceConnectionChangedCallback, IntPtr.Zero, out _deviceConnectionChangedCallbackId);
- AudioManagerErrorFactory.CheckAndThrowException(ret, "Unable to add device connection changed callback");
- Tizen.Log.Info(AudioManagerLog.Tag, "AudioDeviceConnectionChanged Event registered");
}
private static void RegisterDeviceStateChangedEvent()
{
_audioDeviceStateChangedCallback = (IntPtr device, AudioDeviceState changedState, IntPtr userData) =>
{
- AudioDeviceStateChangedEventArgs eventArgs = new AudioDeviceStateChangedEventArgs(new AudioDevice(device), changedState);
- _audioDeviceStateChanged?.Invoke(null, eventArgs);
+ _audioDeviceStateChanged?.Invoke(null,
+ new AudioDeviceStateChangedEventArgs(new AudioDevice(device), changedState));
};
- int ret = Interop.AudioDevice.AddDeviceStateChangedCallback(AudioDeviceOptions.All, _audioDeviceStateChangedCallback, IntPtr.Zero, out _deviceStateChangedCallbackId);
- AudioManagerErrorFactory.CheckAndThrowException(ret, "Unable to add device state changed callback");
- Tizen.Log.Info(AudioManagerLog.Tag, "AudioDeviceStateChangedEvent callback registered");
- }
- private static void UnregisterDeviceConnectionChangedEvent()
- {
- if (_deviceConnectionChangedCallbackId > 0)
- {
- int ret = Interop.AudioDevice.RemoveDeviceConnectionChangedCallback(_deviceConnectionChangedCallbackId);
- AudioManagerErrorFactory.CheckAndThrowException(ret, "Unable to remove device connection changed callback");
- Tizen.Log.Info(AudioManagerLog.Tag, "AudioDeviceConnectionChangedEvent callback unregistered");
- _deviceConnectionChangedCallbackId = -1;
- }
+ Interop.AudioDevice.AddDeviceStateChangedCallback(AudioDeviceOptions.All,
+ _audioDeviceStateChangedCallback, IntPtr.Zero, out _deviceStateChangedCallbackId).
+ Validate("Failed to add device state changed event");
}
private static void UnregisterDeviceStateChangedEvent()
{
- if (_deviceStateChangedCallbackId > 0)
- {
- int ret = Interop.AudioDevice.RemoveDeviceStateChangedCallback(_deviceStateChangedCallbackId);
- AudioManagerErrorFactory.CheckAndThrowException(ret, "Unable to remove device state changed callback");
- Tizen.Log.Info(AudioManagerLog.Tag, "AudioDeviceStateChanged callback unregistered");
- _deviceStateChangedCallbackId = -1;
- }
+ Interop.AudioDevice.RemoveDeviceStateChangedCallback(_deviceStateChangedCallbackId).
+ Validate("Failed to remove device state changed event");
}
+ #endregion
}
}
- /*
+/*
* Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the License);
*/
using System;
+
namespace Tizen.Multimedia
{
/// <summary>
- /// Enumeration for audio device options.
+ /// Specifies the flag for audio device options.
+ /// <para>
+ /// This enumeration has a <see cref="FlagsAttribute"/> attribute that allows a bitwise combination of its member values.
+ /// </para>
/// </summary>
- public enum AudioDeviceOptions
+ [Flags]
+ internal enum AudioDeviceOptions
{
/// <summary>
- /// Mask for input devices
+ /// Input devices.
/// </summary>
Input = 0x0001,
/// <summary>
- /// Mask for output devices
+ /// Output devices.
/// </summary>
Output = 0x0002,
/// <summary>
- /// Mask for input/output devices (both directions are available)
+ /// Input and output devices (both directions are available).
/// </summary>
InputAndOutput = 0x0004,
/// <summary>
- /// Mask for built-in devices
+ /// Built-in devices.
/// </summary>
Internal = 0x00010,
/// <summary>
- /// Mask for external devices
+ /// External devices.
/// </summary>
External = 0x0020,
/// <summary>
- /// Mask for deactivated devices
+ /// Deactivated devices.
/// </summary>
Deactivated = 0x1000,
/// <summary>
- /// Mask for activated devices
+ /// Activated devices.
/// </summary>
Activated = 0x2000,
+
/// <summary>
- /// Mask for all devices
+ /// All devices.
/// </summary>
All = 0xFFFF
}
/// <summary>
- /// Enumeration for audio device type.
+ /// Specifies audio device type.
/// </summary>
public enum AudioDeviceType
{
/// <summary>
- /// Built-in speaker
+ /// Built-in speaker.
/// </summary>
BuiltinSpeaker,
/// <summary>
- /// Built-in receiver
+ /// Built-in receiver.
/// </summary>
BuiltinReceiver,
/// <summary>
- /// Built-in mic
+ /// Built-in microphone.
/// </summary>
BuiltinMic,
/// <summary>
- /// Audio jack that can be connected to wired accessory such as headphones and headsets
+ /// Audio jack that can be connected to wired accessory such as headphones and headsets.
/// </summary>
AudioJack,
/// <summary>
- /// Bluetooth Media (A2DP)
+ /// Bluetooth Media (A2DP).
/// </summary>
BluetoothMedia,
/// <summary>
- /// HDMI
+ /// HDMI.
/// </summary>
Hdmi,
/// <summary>
- /// Device for forwarding
+ /// Device for forwarding.
/// </summary>
Forwarding,
/// <summary>
- /// USB Audio
+ /// USB Audio.
/// </summary>
UsbAudio,
/// <summary>
- /// Bluetooth Voice (SCO)
+ /// Bluetooth Voice (SCO).
/// </summary>
BluetoothVoice
}
/// <summary>
- /// Enumeration for audio device direction.
+ /// Specifies audio device direction.
/// </summary>
public enum AudioDeviceIoDirection
{
/// <summary>
- /// Input device
+ /// Input device.
/// </summary>
Input,
/// <summary>
- /// Output device
+ /// Output device.
/// </summary>
Output,
/// <summary>
- /// Input/output device (both directions are available)
+ /// Input/output device (both directions are available).
/// </summary>
InputAndOutput
}
/// <summary>
- /// Enumeration for audio device state.
+ /// Specifies audio device state.
/// </summary>
public enum AudioDeviceState
{
/// <summary>
- /// Deactivated state
+ /// Deactivated state.
/// </summary>
Deactivated,
/// <summary>
- /// Activated state
+ /// Activated state.
/// </summary>
Activated
}
/// <summary>
- /// Enumeration for audio volume type.
+ /// Specifies audio volume type.
/// </summary>
public enum AudioVolumeType
{
/// <summary>
- /// Volume type for system
+ /// System.
/// </summary>
System,
/// <summary>
- /// Volume type for notification
+ /// Notification.
/// </summary>
Notification,
/// <summary>
- /// Volume type for alarm
+ /// Alarm.
/// </summary>
Alarm,
/// <summary>
- /// Volume type for ringtone
+ /// Ringtone.
/// </summary>
Ringtone,
/// <summary>
- /// Volume type for media
+ /// Media.
/// </summary>
Media,
/// <summary>
- /// Volume type for call
+ /// Call.
/// </summary>
Call,
/// <summary>
- /// Volume type for voip
+ /// VoIP.
/// </summary>
Voip,
/// <summary>
- /// Volume type for voice
+ /// Voice.
/// </summary>
Voice,
/// <summary>
- /// Volume type None
+ /// No volume exists.
/// </summary>
+ /// <seealso cref="AudioStreamPolicy.VolumeType"/>
None
}
/// <summary>
- /// Enumeration for audio stream type.
+ /// Specifies audio stream type.
/// </summary>
public enum AudioStreamType
{
/// <summary>
- /// Audio stream type for media
+ /// Media.
/// </summary>
Media,
/// <summary>
- /// Audio stream type for system
+ /// System.
/// </summary>
System,
/// <summary>
- /// Audio stream type for alarm
+ /// Alarm.
/// </summary>
Alarm,
/// <summary>
- /// Audio stream type for notification
+ /// Notification.
/// </summary>
Notification,
/// <summary>
- /// Audio stream type for emergency
+ /// Emergency.
/// </summary>
Emergency,
/// <summary>
- /// Audio stream type for voice information
+ /// Voice information.
/// </summary>
VoiceInformation,
/// <summary>
- /// Audio stream type for voice recognition
+ /// Voice recognition.
/// </summary>
VoiceRecognition,
/// <summary>
- /// Audio stream type for ringtone for VoIP
+ /// Ringtone for VoIP.
/// </summary>
RingtoneVoip,
/// <summary>
- /// Audio stream type for VoIP
+ /// VoIP.
/// </summary>
Voip,
/// <summary>
- /// Audio stream type for media only for external devices
+ /// Media only for external devices.
/// </summary>
MediaExternalOnly
}
/// <summary>
- /// Enumeration for change reason of audio stream focus state.
+ /// Specifies change reason of audio stream focus state.
/// </summary>
public enum AudioStreamFocusChangedReason
{
/// <summary>
- /// Changed by the stream type for media
+ /// Media.
/// </summary>
Media,
/// <summary>
- /// Changed by the stream type for system
+ /// System.
/// </summary>
System,
/// <summary>
- /// Changed by the stream type for alarm
+ /// Alarm.
/// </summary>
Alarm,
/// <summary>
- /// Changed by the stream type for notification
+ /// Notification.
/// </summary>
Notification,
/// <summary>
- /// Changed by the stream type for emergency
+ /// Emergency.
/// </summary>
Emergency,
/// <summary>
- /// Changed by the stream type for voice information
+ /// Voice information.
/// </summary>
VoiceInformation,
/// <summary>
- /// Changed by the stream type for voice recognition
+ /// Voice recognition.
/// </summary>
VoiceRecognition,
/// <summary>
- /// Changed by the stream type for ringtone
+ /// Ringtone.
/// </summary>
RingtoneVoip,
/// <summary>
- /// Changed by the stream type for VoIP
+ /// VoIP.
/// </summary>
Voip,
/// <summary>
- /// Changed by the stream type for voice-call or video-call
+ /// Voice-call or video-call.
/// </summary>
Call,
/// <summary>
- /// Changed by the stream type for media only for external devices
+ /// Media only for external devices.
/// </summary>
MediaExternalOnly
}
/// <summary>
- /// Enumeration for audio stream focus options.
+ /// Specifies the flag for audio stream focus options.
+ /// <para>
+ /// This enumeration has a <see cref="FlagsAttribute"/> attribute that allows a bitwise combination of its member values.
+ /// </para>
/// </summary>
+ [Flags]
public enum AudioStreamFocusOptions
{
/// <summary>
- /// Mask for playback focus
+ /// Playback focus.
/// </summary>
Playback = 0x0001,
/// <summary>
- /// Mask for recording focus
+ /// Recording focus.
/// </summary>
Recording = 0x0002
}
/// <summary>
- /// Enumeration for audio stream focus state.
+ /// Specifies audio stream focus state.
/// </summary>
public enum AudioStreamFocusState
{
/// <summary>
- /// Focus state for release
+ /// Focus state for release.
/// </summary>
Released,
/// <summary>
- ///Focus state for acquisition
+ /// Focus state for acquisition.
/// </summary>
Acquired
}
/// <summary>
- /// Enumeration for audio stream behavior
+ /// Specifies the flag for audio stream behaviors.
+ /// <para>
+ /// This enumeration has a <see cref="FlagsAttribute"/> attribute that allows a bitwise combination of its member values.
+ /// </para>
/// </summary>
[Flags]
- public enum AudioStreamBehavior
+ public enum AudioStreamBehaviors
{
/// <summary>
- /// Audio Stream Behavior NONE
- /// </summary>
- None = 0x0000,
- /// <summary>
- /// Audio Stream Behavior No Resume
+ /// No Resume.
/// </summary>
NoResume = 0x0001,
/// <summary>
- /// Audio Stream Behavior Fading
+ /// Fading.
/// </summary>
Fading = 0x0002
}
+
+
+ internal static class AudioManagerEnumExtensions
+ {
+ internal static bool IsValid(this AudioStreamFocusOptions value)
+ {
+ int mask = (int)(AudioStreamFocusOptions.Playback | AudioStreamFocusOptions.Recording);
+
+ return (mask & (int)value) != 0;
+ }
+
+ internal static bool IsValid(this AudioStreamBehaviors value)
+ {
+ int mask = (int)(AudioStreamBehaviors.NoResume | AudioStreamBehaviors.Fading);
+
+ return ((~mask) & (int)value) == 0;
+ }
+ }
+
}
- /*
+/*
* Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the License);
namespace Tizen.Multimedia
{
- /// <summary>
- /// Enumeration for sound manager's error codes.
- /// </summary>
- internal enum AudioManagerError{
-
+ internal enum AudioManagerError
+ {
SoundManagerError = -0x01960000,
/// <summary>
/// Successful
InvalidState = SoundManagerError | 04
}
- internal static class AudioManagerErrorFactory
+ internal static class AudioManagerErrorExtensions
{
- static internal void CheckAndThrowException(int error, string msg)
+ internal static void Validate(this AudioManagerError err, string msg)
{
- AudioManagerError e = (AudioManagerError) error;
- switch (e)
+ if (err == AudioManagerError.None)
+ {
+ return;
+ }
+
+ msg = msg ?? "";
+ msg += $" : {err}.";
+
+ switch (err)
{
- case AudioManagerError.None:
- return;
case AudioManagerError.OutOfMemory:
- throw new InvalidOperationException("Out of Memory: " + msg);
+ throw new OutOfMemoryException(msg);
+
case AudioManagerError.InvalidParameter:
- throw new ArgumentException("Invalid Parameter: " + msg);
- case AudioManagerError.InvalidOperation:
- throw new InvalidOperationException("Invalid Opertation: " + msg);
+ throw new ArgumentException(msg);
+
case AudioManagerError.PermissionDenied:
- throw new InvalidOperationException("Permission Denied: " + msg);
+ throw new UnauthorizedAccessException(msg);
+
case AudioManagerError.NotSupported:
- throw new InvalidOperationException("Not Supported: " + msg);
+ throw new NotSupportedException(msg);
+
+ case AudioManagerError.Policy:
+ throw new AudioPolicyException(msg);
+
case AudioManagerError.NoData:
- throw new InvalidOperationException("No Data: " + msg);
+ // TODO check when it is thrown
+ throw new InvalidOperationException(msg);
+
case AudioManagerError.Internal:
- throw new InvalidOperationException("Internal Error: " + msg);
- case AudioManagerError.Policy:
- throw new InvalidOperationException("Noncomplaince with System Sound Policy error: " + msg);
+ case AudioManagerError.InvalidOperation:
case AudioManagerError.NoPlayingSound:
- throw new InvalidOperationException("No playing sound: " + msg);
case AudioManagerError.InvalidState:
- throw new InvalidOperationException("Invalid State: " + msg);
- default:
- throw new InvalidOperationException("Unknown Error Code: " + msg);
- }
- }
+ throw new InvalidOperationException(msg);
- static internal void CheckAndThrowException(int error, IntPtr handle, string msg)
- {
- if (handle == IntPtr.Zero)
- {
- throw new InvalidOperationException("Invalid instance (object may have been disposed or released)");
- }
- else
- {
- CheckAndThrowException(error, msg);
+ default:
+ throw new InvalidOperationException("Unknown Error : " + msg);
}
}
}
--- /dev/null
+/*
+ * 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;
+
+namespace Tizen.Multimedia
+{
+ /// <summary>
+ /// The exception that is thrown when noncompliance with the sound system policy happens.
+ /// </summary>
+ public class AudioPolicyException : InvalidOperationException
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AudioPolicyException"/> class.
+ /// </summary>
+ public AudioPolicyException()
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AudioPolicyException"/> class with a specified error message.
+ /// </summary>
+ /// <param name="message">The error message that explains the reason for the exception.</param>
+ public AudioPolicyException(string message) : base(message)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AudioPolicyException"/> class with a specified error message and inner exception.
+ /// </summary>
+ /// <param name="message">The error message that explains the reason for the exception.</param>
+ /// <param name="innerException">The exception that is the cause of the current exception..</param>
+ public AudioPolicyException(string message, Exception innerException) : base(message, innerException)
+ {
+ }
+ }
+}
- /*
+/*
* Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the License);
*/
using System;
+using System.Diagnostics;
namespace Tizen.Multimedia
{
- internal static class AudioStreamPolicyLog
- {
- internal const string Tag = "Tizen.Multimedia.AudioStreamPolicy";
- }
-
/// <summary>
- /// The Stream Policy API provides functions to control a sound stream.
+ /// Provides the ability to control a sound stream.
/// </summary>
public class AudioStreamPolicy : IDisposable
{
- private static int _focusStateWatchCounter = 0;
- private static EventHandler<FocusStateChangedEventArgs> _focusStateWatchForPlayback;
- private static EventHandler<FocusStateChangedEventArgs> _focusStateWatchForRecording;
- private static Interop.SoundStreamFocusStateWatchCallback _focusStateWatchCallback;
- private static int _focusWatchCbId;
-
- private IntPtr _streamInfo;
- private AudioStreamType _streamType;
+ private AudioStreamPolicyHandle _handle;
private bool _disposed = false;
- private EventHandler<StreamFocusStateChangedEventArgs> _focusStateChanged;
- private Interop.SoundStreamFocusStateChangedCallback _focusStateChangedCallback;
+ private Interop.AudioStreamPolicy.FocusStateChangedCallback _focusStateChangedCallback;
/// <summary>
- /// Creates and returns an AudioStreamPolicy object
+ /// Initializes a new instance of the <see cref="AudioStreamPolicy"/> class with <see cref="AudioStreamType"/>
/// </summary>
/// <remarks>
- /// To apply the stream policy according to this stream information, this object should be passed to other APIs
- /// related to playback or recording. (e.g., player, wav-player, audio-io, etc.)
+ /// To apply the stream policy according to this stream information, the AudioStreamPolicy should
+ /// be passed to other APIs related to playback or recording. (e.g., <see cref="Player"/>, <see cref="WavPlayer"/> , etc.)
/// </remarks>
- /// <param name="streamType">Type of sound stream for which policy needs to be created</param>
- /// <returns>StreamPolicy object</returns>
+ /// <param name="streamType">Type of sound stream for which policy needs to be created.</param>
public AudioStreamPolicy(AudioStreamType streamType)
{
- _streamType = streamType;
+ ValidationUtil.ValidateEnum(typeof(AudioStreamType), streamType, nameof(streamType));
- _focusStateChangedCallback = (IntPtr streamInfo, AudioStreamFocusOptions focusMask, AudioStreamFocusState focusState, int reason, int audioStreamBehavior, string extraInfo, IntPtr userData) => {
- StreamFocusStateChangedEventArgs eventArgs = new StreamFocusStateChangedEventArgs((AudioStreamFocusChangedReason)reason, extraInfo);
- _focusStateChanged?.Invoke(this, eventArgs);
+ _focusStateChangedCallback = (IntPtr streamInfo, AudioStreamFocusOptions focusMask,
+ AudioStreamFocusState state, AudioStreamFocusChangedReason reason, AudioStreamBehaviors behaviors,
+ string extraInfo, IntPtr userData) =>
+ {
+ FocusStateChanged?.Invoke(this,
+ new AudioStreamPolicyFocusStateChangedEventArgs(focusMask, state, reason, behaviors, extraInfo));
};
- int ret = Interop.AudioStreamPolicy.CreateStreamInformation((int)streamType, _focusStateChangedCallback, IntPtr.Zero, out _streamInfo);
- AudioManagerErrorFactory.CheckAndThrowException(ret, "Unable to create stream information");
- }
- ~AudioStreamPolicy()
- {
- Dispose(false);
- }
+ Interop.AudioStreamPolicy.Create(streamType, _focusStateChangedCallback,
+ IntPtr.Zero, out _handle).Validate("Unable to create stream information");
- /// <summary>
- /// Registers the watch function to be invoked when the focus state for each sound stream type is changed regardless of the process.
- /// <remarks>
- /// Remarks: You can set this only once per process.
- /// </remarks>
- /// </summary>
- public static event EventHandler<FocusStateChangedEventArgs> PlaybackFocusStateWatch {
- add {
- Tizen.Log.Info(AudioStreamPolicyLog.Tag, "############# _focusStateWatchCounter" + _focusStateWatchCounter);
- if(_focusStateWatchCounter == 0) {
- RegisterFocusStateWatchEvent();
- }
- _focusStateWatchCounter++;
- _focusStateWatchForPlayback += value;
- }
- remove {
- Tizen.Log.Info(AudioStreamPolicyLog.Tag, "############# _focusStateWatchCounter" + _focusStateWatchCounter);
- _focusStateWatchForPlayback -= value;
- _focusStateWatchCounter--;
- if(_focusStateWatchCounter == 0) {
- UnregisterFocusStateWatch();
- }
- }
+ Debug.Assert(_handle != null);
}
/// <summary>
- /// Registers the watch function to be invoked when the focus state for each sound stream type is changed regardless of the process.
+ /// Occurs when the state of focus that belongs to the current AudioStreamPolicy is changed.
+ /// </summary>
/// <remarks>
- /// Remarks: You can set this only once per process.
+ /// The event is raised in the internal thread.
/// </remarks>
- /// </summary>
- public static event EventHandler<FocusStateChangedEventArgs> RecordingFocusStateWatch {
- add {
- if(_focusStateWatchCounter == 0) {
- RegisterFocusStateWatchEvent();
- }
- _focusStateWatchCounter++;
- _focusStateWatchForRecording += value;
- }
- remove {
- _focusStateWatchForRecording -= value;
- _focusStateWatchCounter--;
- if(_focusStateWatchCounter == 0) {
- UnregisterFocusStateWatch();
- }
- }
- }
+ public event EventHandler<AudioStreamPolicyFocusStateChangedEventArgs> FocusStateChanged;
/// <summary>
- /// Registers function to be called when the state of focus that belongs to the current
- /// streamInfo is changed.
+ /// Gets the <see cref="AudioVolumeType"/>.
/// </summary>
/// <remarks>
- /// Remarks: This function is issued in the internal thread of the sound manager. Therefore it is recommended not to call UI update function in this function.
- /// Postcondition : Check PlaybackFocusState and RecordingFocusState in the registered event handler to figure out how the focus state of the StreamInfo has been changed.
+ /// If the <see cref="AudioStreamType"/> of the current AudioStreamPolicy is <see cref="AudioStreamType.Emergency"/>,
+ /// it returns <see cref="AudioVolumeType.None"/>.
/// </remarks>
- public event EventHandler<StreamFocusStateChangedEventArgs> StreamFocusStateChanged {
- add {
- _focusStateChanged += value;
- }
- remove {
- _focusStateChanged -= value;
- }
- }
-
- /// <summary>
- /// The sound type of the stream information.
- /// </summary>
- public AudioVolumeType VolumeType {
- get {
- AudioVolumeType soundType;
- int ret = Interop.AudioStreamPolicy.GetSoundType(_streamInfo, out soundType);
- if(ret != 0) {
- Tizen.Log.Info(AudioStreamPolicyLog.Tag, "Unable to get sound type:" + (AudioManagerError)ret);
+ /// <value>The <see cref="AudioVolumeType"/> of the policy instance.</value>
+ public AudioVolumeType VolumeType
+ {
+ get
+ {
+ AudioVolumeType type;
+ var ret = Interop.AudioStreamPolicy.GetSoundType(Handle, out type);
+ if (ret == AudioManagerError.NoData)
+ {
return AudioVolumeType.None;
}
- return soundType;
+
+ ret.Validate("Failed to get volume type");
+
+ return type;
}
}
+ private AudioStreamFocusState GetFocusState(bool playback)
+ {
+ int ret = Interop.AudioStreamPolicy.GetFocusState(Handle, out var stateForPlayback, out var stateForRecording);
+ MultimediaDebug.AssertNoError(ret);
+
+ return playback ? stateForPlayback : stateForRecording;
+ }
+
/// <summary>
- /// The state of focus for playback.
+ /// Gets the state of focus for playback.
/// </summary>
- public AudioStreamFocusState PlaybackFocusState {
- get {
- AudioStreamFocusState stateForPlayback;
- AudioStreamFocusState stateForRecording;
- int ret = Interop.AudioStreamPolicy.GetFocusState(_streamInfo, out stateForPlayback, out stateForRecording);
- if(ret != 0) {
- Tizen.Log.Info(AudioStreamPolicyLog.Tag, "Unable to get focus state" + (AudioManagerError)ret);
- return AudioStreamFocusState.Released;
- }
- return stateForPlayback;
- }
- }
+ /// <value>The state of focus for playback.</value>
+ public AudioStreamFocusState PlaybackFocusState => GetFocusState(true);
/// <summary>
- /// The state of focus for recording.
+ /// Gets the state of focus for recording.
/// </summary>
- public AudioStreamFocusState RecordingFocusState {
- get {
- AudioStreamFocusState stateForPlayback;
- AudioStreamFocusState stateForRecording;
- int ret = Interop.AudioStreamPolicy.GetFocusState(_streamInfo, out stateForPlayback, out stateForRecording);
- if(ret != 0) {
- Tizen.Log.Info(AudioStreamPolicyLog.Tag, "Unable to get focus state" + (AudioManagerError)ret);
- return AudioStreamFocusState.Released;
- }
- return stateForRecording;
- }
- }
+ /// <value>The state of focus for recording.</value>
+ public AudioStreamFocusState RecordingFocusState => GetFocusState(false);
/// <summary>
- /// Auto focus reacquisition property
+ /// Gets or sets the auto focus reacquisition.
/// </summary>
+ /// <value>
+ /// true if the auto focus reacquisition is enabled; otherwise, false.\n
+ /// The default is true.
+ /// </value>
/// <remarks>
- /// The focus reacquistion is set as default. If you don't want to reacquire the focus you've lost automatically, disable the focus reacqusition setting by using this API and vice versa.
+ /// If you don't want to reacquire the focus you've lost automatically,
+ /// disable the focus reacquisition.
/// </remarks>
- public bool FocusReacquisitionEnabled {
- get {
- bool enabled;
- int ret = Interop.AudioStreamPolicy.GetFocusReacquisition(_streamInfo, out enabled);
- if(ret != 0) {
- Tizen.Log.Info(AudioStreamPolicyLog.Tag, "Unable to get focus reacquisition" + (AudioManagerError)ret);
- return true;
- }
+ public bool FocusReacquisitionEnabled
+ {
+ get
+ {
+ Interop.AudioStreamPolicy.GetFocusReacquisition(Handle, out var enabled).
+ Validate("Failed to get focus reacquisition state");
+
return enabled;
}
- set {
- int ret = Interop.AudioStreamPolicy.SetFocusReacquisition(_streamInfo, value);
- AudioManagerErrorFactory.CheckAndThrowException(ret, "Unable to set focus reacquisition");
+ set
+ {
+ Interop.AudioStreamPolicy.SetFocusReacquisition(Handle, value).
+ Validate("Failed to set focus reacquisition");
}
}
- public IntPtr Handle {
- get {
- return _streamInfo;
+ internal AudioStreamPolicyHandle Handle
+ {
+ get
+ {
+ if (_disposed)
+ {
+ throw new ObjectDisposedException(nameof(AudioStreamPolicy));
+ }
+ return _handle;
}
}
/// <summary>
/// Acquires the stream focus.
/// </summary>
- /// <param name="options">The focus mask that user wants to acquire</param>
- /// <param name="audioStreamBehavior">The required action for releaser</param>
- /// <param name="extraInformation">The Extra information for this request (optional, this can be null)</param>
- /// <remarks>
- /// Do not call this API within event handlers of FocuStateChanged and StreamFocusStateWatch else it will throw and exception
- /// </remarks>
- public void AcquireFocus(AudioStreamFocusOptions options, AudioStreamBehavior audioStreamBehavior, string extraInformation)
+ /// <param name="options">The focuses that you want to acquire.</param>
+ /// <param name="behaviors">The requesting behaviors.</param>
+ /// <param name="extraInfo">The extra information for this request. This value can be null.</param>
+ public void AcquireFocus(AudioStreamFocusOptions options, AudioStreamBehaviors behaviors, string extraInfo)
{
- int ret = Interop.AudioStreamPolicy.AcquireFocus(_streamInfo, options, (int)audioStreamBehavior, extraInformation);
- Tizen.Log.Info(AudioStreamPolicyLog.Tag, "Acquire focus return: " + ret);
- AudioManagerErrorFactory.CheckAndThrowException(ret, "Unable to acquire focus");
+ if (options == 0)
+ {
+ throw new ArgumentException("options can't be zero.", nameof(options));
+ }
+
+ if (options.IsValid() == false)
+ {
+ throw new ArgumentOutOfRangeException(nameof(options), options, "options contains a invalid bit.");
+ }
+
+ if (behaviors.IsValid() == false)
+ {
+ throw new ArgumentOutOfRangeException(nameof(behaviors), behaviors, "behaviors contains a invalid bit.");
+ }
+
+ Interop.AudioStreamPolicy.AcquireFocus(Handle, options, behaviors, extraInfo).
+ Validate("Failed to acquire focus");
}
/// <summary>
/// Releases the acquired focus.
/// </summary>
- /// <param name="options">The focus mask that user wants to release</param>
- /// <param name="audioStreamBehavior">The required action for acquirer</param>
- /// <param name="extraInformation">he Extra information for this request (optional, this can be null)</param>
- /// <remarks>
- /// Do not call this API within event handlers of FocuStateChanged and StreamFocusStateWatch else it will throw and exception
- /// </remarks>
- public void ReleaseFocus(AudioStreamFocusOptions options, AudioStreamBehavior audioStreamBehavior, string extraInformation)
+ /// <param name="options">The focus mask that you want to release.</param>
+ /// <param name="behaviors">The requesting behaviors.</param>
+ /// <param name="extraInfo">The extra information for this request. This value can be null.</param>
+ public void ReleaseFocus(AudioStreamFocusOptions options, AudioStreamBehaviors behaviors, string extraInfo)
{
- int ret = Interop.AudioStreamPolicy.ReleaseFocus(_streamInfo, options, (int)audioStreamBehavior, extraInformation);
- Tizen.Log.Info(AudioStreamPolicyLog.Tag, "Release focus return: " + ret);
- AudioManagerErrorFactory.CheckAndThrowException(ret, "Unable to release focus");
+ if (options == 0)
+ {
+ throw new ArgumentException("options can't be zero.", nameof(options));
+ }
+
+ if (options.IsValid() == false)
+ {
+ throw new ArgumentOutOfRangeException(nameof(options), options, "options contains a invalid bit.");
+ }
+
+ if (behaviors.IsValid() == false)
+ {
+ throw new ArgumentOutOfRangeException(nameof(behaviors), behaviors, "behaviors contains a invalid bit.");
+ }
+
+ Interop.AudioStreamPolicy.ReleaseFocus(Handle, options, behaviors, extraInfo).
+ Validate("Failed to release focus");
}
/// <summary>
/// Applies the stream routing.
/// </summary>
/// <remarks>
- /// If the stream has not been made yet, this setting will be applied when the stream starts to play.
- /// Precondition: Call AddDeviceForStreamRouting() before calling this function.
+ /// If the stream has not been made yet, this will be applied when the stream starts to play.
/// </remarks>
+ /// <seealso cref="AddDeviceForStreamRouting(AudioDevice)"/>
+ /// <seealso cref="RemoveDeviceForStreamRouting(AudioDevice)"/>
public void ApplyStreamRouting()
{
- int ret = Interop.AudioStreamPolicy.ApplyStreamRouting(_streamInfo);
- Tizen.Log.Info(AudioStreamPolicyLog.Tag, "Apply Routing: " + (AudioManagerError)ret);
- AudioManagerErrorFactory.CheckAndThrowException(ret, "Unable to apply stream routing");
+ Interop.AudioStreamPolicy.ApplyStreamRouting(Handle).Validate("Failed to apply stream routing");
}
/// <summary>
- /// Adds the device to the stream information for the stream routing.
+ /// Adds a device for the stream routing.
/// </summary>
+ /// <param name="device">The device to add.</param>
/// <remarks>
- /// Remarks: Use SoundManager.GetCurrentDeviceList() to get the device.
- /// The available types of the StreamInfo for this API are SoundStreamTypeVoip and SoundStreamTypeMediaExternalOnly.
- /// Postcondition: You can apply this setting by calling ApplyStreamRouting().
+ /// The available <see cref="AudioStreamType"/> is <see cref="AudioStreamType.Voip"/> and <see cref="AudioStreamType.MediaExternalOnly"/>.
/// </remarks>
- /// <param name="soundDevice">The device item from the current sound devices list.</param>
- public void AddDeviceForStreamRouting(AudioDevice soundDevice)
+ /// <seealso cref="AudioManager.GetConnectedDevices()"/>
+ /// <seealso cref="ApplyStreamRouting"/>
+ public void AddDeviceForStreamRouting(AudioDevice device)
{
- int ret = Interop.AudioStreamPolicy.AddDeviceForStreamRouting(_streamInfo, soundDevice.Handle);
- Tizen.Log.Info(AudioStreamPolicyLog.Tag, "Add stream routing: " + (AudioManagerError)ret);
+ if (device == null)
+ {
+ throw new ArgumentNullException(nameof(device));
+ }
+ var ret = Interop.AudioStreamPolicy.AddDeviceForStreamRouting(Handle, device.Id);
+
+ if (ret == AudioManagerError.NoData)
+ {
+ throw new ArgumentException("The device seems not connected.", nameof(device));
+ }
- AudioManagerErrorFactory.CheckAndThrowException(ret, "Unable to add device for stream routing");
+ ret.Validate("Failed to add device for stream routing");
}
/// <summary>
- /// Removes the device to the stream information for the stream routing.
+ /// Removes the device for the stream routing.
/// </summary>
+ /// <param name="device">The device to remove.</param>
/// <remarks>
- /// Remarks: Use SoundManager.GetCurrentDeviceList() to get the device.
- /// The available types of the StreamInfo for this API are SoundStreamTypeVoip and SoundStreamTypeMediaExternalOnly.
- /// Postcondition: You can apply this setting by calling ApplyStreamRouting().
+ /// The available <see cref="AudioStreamType"/> is <see cref="AudioStreamType.Voip"/> and <see cref="AudioStreamType.MediaExternalOnly"/>.
/// </remarks>
- /// <param name="soundDevice">The device item from the current sound devices list.</param>
- public void RemoveDeviceForStreamRouting(AudioDevice soundDevice)
+ public void RemoveDeviceForStreamRouting(AudioDevice device)
{
- int ret = Interop.AudioStreamPolicy.RemoveDeviceForStreamRouting(_streamInfo, soundDevice.Handle);
- Tizen.Log.Info(AudioStreamPolicyLog.Tag, "Remove stream routing: " + (AudioManagerError)ret);
- AudioManagerErrorFactory.CheckAndThrowException(ret, "Unable to remove device for stream routing");
+ if (device == null)
+ {
+ throw new ArgumentNullException(nameof(device));
+ }
+
+ Interop.AudioStreamPolicy.RemoveDeviceForStreamRouting(Handle, device.Id).
+ Validate("Failed to remove device for stream routing");
}
+ /// <summary>
+ /// Releases all resources used by the <see cref="AudioStreamPolicy"/>.
+ /// </summary>
public void Dispose()
{
Dispose(true);
- GC.SuppressFinalize(this);
}
+ /// <summary>
+ /// Releases the unmanaged resources used by the <see cref="AudioStreamPolicy"/>.
+ /// </summary>
+ /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
- if(!_disposed) {
- if(disposing) {
- // to be used if there are any other disposable objects
- }
- if(_streamInfo != IntPtr.Zero) {
- Interop.AudioStreamPolicy.DestroyStreamInformation(_streamInfo); // Destroy the handle
- _streamInfo = IntPtr.Zero;
+ if (!_disposed)
+ {
+ if (_handle != null)
+ {
+ _handle.Dispose();
}
_disposed = true;
}
}
- private static void RegisterFocusStateWatchEvent()
+ #region Static events
+
+ private static bool _isWatchCallbackRegistered;
+ private static EventHandler<StreamFocusStateChangedEventArgs> _streamFocusStateChanged;
+ private static Interop.AudioStreamPolicy.FocusStateWatchCallback _focusStateWatchCallback;
+ private static object _streamFocusEventLock = new object();
+
+ /// <summary>
+ /// Occurs when the focus state for stream types is changed regardless of the process.
+ /// </summary>
+ public static event EventHandler<StreamFocusStateChangedEventArgs> StreamFocusStateChanged
{
- _focusStateWatchCallback = (int id, AudioStreamFocusOptions options, AudioStreamFocusState focusState, AudioStreamFocusChangedReason reason, string extraInfo, IntPtr userData) => {
- Tizen.Log.Info(AudioStreamPolicyLog.Tag, "############# _Inside _focusStateWatchCallback : id = " + id + "options = " + options);
- FocusStateChangedEventArgs eventArgs = new FocusStateChangedEventArgs(focusState, reason, extraInfo);
- if(options == AudioStreamFocusOptions.Playback) {
- Tizen.Log.Info(AudioStreamPolicyLog.Tag, "############# _eventArgs = " + eventArgs);
- _focusStateWatchForPlayback?.Invoke(null, eventArgs);
- } else if(options == AudioStreamFocusOptions.Recording) {
- _focusStateWatchForRecording?.Invoke(null, eventArgs);
- } else if(options == (AudioStreamFocusOptions.Playback | AudioStreamFocusOptions.Recording)) {
- _focusStateWatchForPlayback?.Invoke(null, eventArgs);
- _focusStateWatchForRecording?.Invoke(null, eventArgs);
+ add
+ {
+ lock (_streamFocusEventLock)
+ {
+ if (_isWatchCallbackRegistered == false)
+ {
+ RegisterFocusStateWatch();
+ _isWatchCallbackRegistered = true;
+ }
+ _streamFocusStateChanged += value;
}
- };
- int ret = Interop.AudioStreamPolicy.AddFocusStateWatchCallback(AudioStreamFocusOptions.Playback | AudioStreamFocusOptions.Recording, _focusStateWatchCallback, IntPtr.Zero, out _focusWatchCbId);
- Tizen.Log.Info(AudioStreamPolicyLog.Tag, "############# _AddFocusStateWatchCallback : ret = " + ret + " ID = " + _focusWatchCbId);
- AudioManagerErrorFactory.CheckAndThrowException(ret, "Unable to set focus state watch callback");
+ }
+ remove
+ {
+ lock (_streamFocusEventLock)
+ {
+ _streamFocusStateChanged -= value;
+ }
+ }
}
- private static void UnregisterFocusStateWatch()
+ private static void RegisterFocusStateWatch()
{
- int ret = Interop.AudioStreamPolicy.RemoveFocusStateWatchCallback(_focusWatchCbId);
- AudioManagerErrorFactory.CheckAndThrowException(ret, "Unable to unset focus state watch callback");
+ _focusStateWatchCallback = (int id, AudioStreamFocusOptions options, AudioStreamFocusState focusState,
+ AudioStreamFocusChangedReason reason, string extraInfo, IntPtr userData) =>
+ {
+ _streamFocusStateChanged?.Invoke(null,
+ new StreamFocusStateChangedEventArgs(options, focusState, reason, extraInfo));
+ };
+
+ Interop.AudioStreamPolicy.AddFocusStateWatchCallback(
+ AudioStreamFocusOptions.Playback | AudioStreamFocusOptions.Recording,
+ _focusStateWatchCallback, IntPtr.Zero, out var cbId).
+ Validate("Failed to initialize focus state event");
}
+ #endregion
}
}
--- /dev/null
+/*
+ * 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;
+
+namespace Tizen.Multimedia
+{
+ /// <summary>
+ /// Provides data for the <see cref="AudioStreamPolicy.FocusStateChanged"/> event.
+ /// </summary>
+ public class AudioStreamPolicyFocusStateChangedEventArgs : EventArgs
+ {
+ internal AudioStreamPolicyFocusStateChangedEventArgs(AudioStreamFocusOptions options,
+ AudioStreamFocusState state, AudioStreamFocusChangedReason reason,
+ AudioStreamBehaviors behaviors, string extraInfo)
+ {
+ FocusOptions = options;
+ FocusState = state;
+ Reason = reason;
+ Behaviors = behaviors;
+ ExtraInfo = extraInfo;
+ }
+
+ /// <summary>
+ /// Gets the focus options.
+ /// </summary>
+ /// <value>The focus options.</value>
+ public AudioStreamFocusOptions FocusOptions { get; }
+
+ /// <summary>
+ /// Gets the focus state.
+ /// </summary>
+ /// <value>The focus state.</value>
+ public AudioStreamFocusState FocusState { get; }
+
+ /// <summary>
+ /// Gets the reason for state change of the focus.
+ /// </summary>
+ /// <value>The reason for state change of the focus.</value>
+ public AudioStreamFocusChangedReason Reason { get; }
+
+ /// <summary>
+ /// Gets the requested behaviors that should be followed
+ /// </summary>
+ /// <value>The requested behaviors that should be followed.</value>
+ public AudioStreamBehaviors Behaviors { get; }
+
+ /// <summary>
+ /// Gets the extra information.
+ /// </summary>
+ /// <value>
+ /// The extra information specified in <see cref="AudioStreamPolicy.AcquireFocus(AudioStreamFocusOptions, AudioStreamBehaviors, string)"/> or
+ /// <see cref="AudioStreamPolicy.ReleaseFocus(AudioStreamFocusOptions, AudioStreamBehaviors, string)"/>.
+ /// </value>
+ /// <seealso cref="AudioStreamPolicy.AcquireFocus(AudioStreamFocusOptions, AudioStreamBehaviors, string)"/>
+ /// <seealso cref="AudioStreamPolicy.ReleaseFocus(AudioStreamFocusOptions, AudioStreamBehaviors, string)"/>
+ public string ExtraInfo { get; }
+ }
+}
- /*
- * 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.
- */
+/*
+* 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;
namespace Tizen.Multimedia
{
- internal static class AudioVolumeLog
- {
- internal const string Tag = "Tizen.Multimedia.AudioVolume";
- }
-
/// <summary>
- /// The AudioVolume API provides functions to check and control volumes.
+ /// Provides the ability to control the volume levels.
/// </summary>
+ /// <seealso cref="AudioManager"/>
public class AudioVolume
{
- private static int _volumeChangedCallbackId = -1;
+ private const string Tag = "Tizen.Multimedia.AudioVolume";
+
+ private int _volumeChangedCallbackId = -1;
private EventHandler<VolumeChangedEventArgs> _volumeChanged;
- private Interop.SoundManagerVolumeChangedCallback _volumeChangedCallback;
+ private Interop.AudioVolume.VolumeChangedCallback _volumeChangedCallback;
+
+ private object _eventLock = new object();
internal AudioVolume()
{
}
/// <summary>
- /// Registers a function to be invoked when the volume level is changed.
+ /// Occurs when the volume level is changed.
/// </summary>
- public event EventHandler<VolumeChangedEventArgs> Changed {
- add {
- Tizen.Log.Info(AudioVolumeLog.Tag, "VolumeController Changed Event added....");
- if(_volumeChanged == null) {
- RegisterVolumeChangedEvent();
+ public event EventHandler<VolumeChangedEventArgs> Changed
+ {
+ add
+ {
+ lock (_eventLock)
+ {
+ if (_volumeChanged == null)
+ {
+ RegisterVolumeChangedEvent();
+ }
+ _volumeChanged += value;
}
- _volumeChanged += value;
}
- remove {
- Tizen.Log.Info(AudioVolumeLog.Tag, "VolumeController Changed Event removed....");
- if(_volumeChanged?.GetInvocationList()?.GetLength(0) == 1) {
- UnregisterVolumeChangedEvent();
+ remove
+ {
+ if (value == null)
+ {
+ return;
+ }
+
+ lock (_eventLock)
+ {
+ if (_volumeChanged == value)
+ {
+ UnregisterVolumeChangedEvent();
+ }
+ _volumeChanged -= value;
}
- _volumeChanged -= value;
}
}
/// <summary>
- /// The Audio Manager has predefined volume types.(system, notification, alarm, ringtone, media, call, voip, voice).
- /// The volume type of the sound being currently played.
+ /// Gets the volume type of the sound being currently played.
/// </summary>
- public AudioVolumeType CurrentPlaybackType {
- get {
- AudioVolumeType currentType;
- int ret = Interop.AudioVolume.GetCurrentSoundType(out currentType);
- if(ret != 0) {
- Tizen.Log.Info(AudioVolumeLog.Tag, "Unable to get current playback sound type" + (AudioManagerError)ret);
+ /// <value>The volume type of the sound being currently played.</value>
+ public AudioVolumeType CurrentPlaybackType
+ {
+ get
+ {
+ var ret = Interop.AudioVolume.GetCurrentSoundType(out var currentType);
+ if (ret == AudioManagerError.NoPlayingSound)
+ {
return AudioVolumeType.None;
}
+ ret.Validate("Failed to get current volume type");
+
return currentType;
}
}
/// <summary>
- /// The indexer class which is used to get/set volume level specified for a particular sound type.
+ /// Gets the <see cref="VolumeLevel"/>.
/// </summary>
- public VolumeLevel Level;
+ /// <value>The <see cref="VolumeLevel"/>.</value>
+ public VolumeLevel Level { get; }
/// <summary>
- /// The indexer class which is used to get maximum volume level supported for a particular sound type.
+ /// Gets the <see cref="MaxVolumeLevel"/>.
/// </summary>
- public MaxVolumeLevel MaxLevel;
+ /// <value>The <see cref="MaxVolumeLevel"/>.</value>
+ public MaxVolumeLevel MaxLevel { get; }
private void RegisterVolumeChangedEvent()
{
- _volumeChangedCallback = (AudioVolumeType type, uint volume, IntPtr userData) => {
- VolumeChangedEventArgs eventArgs = new VolumeChangedEventArgs(type, volume);
- _volumeChanged.Invoke(this, eventArgs);
+ _volumeChangedCallback = (AudioVolumeType type, uint volume, IntPtr userData) =>
+ {
+ _volumeChanged?.Invoke(this, new VolumeChangedEventArgs(type, volume));
};
- int error = Interop.AudioVolume.AddVolumeChangedCallback(_volumeChangedCallback, IntPtr.Zero, out _volumeChangedCallbackId);
- Tizen.Log.Info(AudioVolumeLog.Tag, "VolumeController Add Changed Event return id:" + _volumeChangedCallbackId + "error:" + error);
- AudioManagerErrorFactory.CheckAndThrowException(error, "unable to add level changed callback");
+ var error = Interop.AudioVolume.AddVolumeChangedCallback(_volumeChangedCallback, IntPtr.Zero,
+ out _volumeChangedCallbackId);
+ Log.Info(Tag, $"VolumeController callback id:{_volumeChangedCallbackId}");
+
+ error.Validate("Failed to add volume changed event");
}
private void UnregisterVolumeChangedEvent()
{
- if (_volumeChangedCallbackId > 0) {
- int error = Interop.AudioVolume.RemoveVolumeChangedCallback(_volumeChangedCallbackId);
- Tizen.Log.Info(AudioVolumeLog.Tag, "VolumeController Remove Changed Event(id:" + _volumeChangedCallbackId + ") return error: " + error);
- AudioManagerErrorFactory.CheckAndThrowException(error, "unable to remove level changed callback");
- }
+ Interop.AudioVolume.RemoveVolumeChangedCallback(_volumeChangedCallbackId).
+ Validate("Failed to remove volume changed event");
}
}
}
+++ /dev/null
- /*
- * 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;
-
-namespace Tizen.Multimedia
-{
- /// <summary>
- /// Class extending EventArgs and contains the necessary parameters to passed to FocusStateWatch event handler
- /// </summary>
- public class FocusStateChangedEventArgs : EventArgs
- {
- internal FocusStateChangedEventArgs(AudioStreamFocusState focusState, AudioStreamFocusChangedReason reason, string extraInformation)
- {
- FocusState = focusState;
- FocusChangedReason = reason;
- ExtraInformation = extraInformation;
- }
-
- /// <summary>
- /// The changed focus state
- /// </summary>
- public AudioStreamFocusState FocusState { get; }
-
- /// <summary>
- /// The reason for state change of the focus
- /// </summary>
- public AudioStreamFocusChangedReason FocusChangedReason { get; }
-
- /// <summary>
- /// The extra information
- /// </summary>
- public string ExtraInformation { get; }
- }
-}
- /*
+/*
* Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the License);
namespace Tizen.Multimedia
{
- internal static class MaxVolumeLog
- {
- internal const string Tag = "Tizen.Multimedia.MaxVolume";
- }
-
/// <summary>
- /// This is a indexer class which is used to get the maximum volume level
- /// supported for a particular sound type.
+ /// Provides a means to get max volume levels.
/// </summary>
public class MaxVolumeLevel
{
- public int this [AudioVolumeType type] {
- get {
- if(type == AudioVolumeType.None)
- throw new ArgumentException("Wrong Audio volume type. Cannot get max volume level for AudioVolumeType.None");
- int maxVolume;
- int ret = Interop.AudioVolume.GetMaxVolume(type, out maxVolume);
- if(ret != 0) {
- Tizen.Log.Info(MaxVolumeLog.Tag, "Max Level Error: " + (AudioManagerError)ret);
- return -1;
+ internal MaxVolumeLevel()
+ {
+ }
+
+ /// <summary>
+ /// Gets the max volume level of the specified <see cref="AudioVolumeType"/>
+ /// </summary>
+ /// <param name="type">The <see cref="AudioVolumeType"/> to query.</param>
+ /// <value>The maximum volume level.</value>
+ /// <exception cref="ArgumentException"><paramref name="type"/> is invalid.</exception>
+ /// <exception cref="ArgumentOutOfRangeException"><paramref name="type"/> is <see cref="AudioVolumeType.None"/>.</exception>
+ public int this[AudioVolumeType type]
+ {
+ get
+ {
+ ValidationUtil.ValidateEnum(typeof(AudioVolumeType), type, nameof(type));
+
+ if (type == AudioVolumeType.None)
+ {
+ throw new ArgumentOutOfRangeException(nameof(type),
+ "Cannot get max volume level for AudioVolumeType.None");
}
+
+ Interop.AudioVolume.GetMaxVolume(type, out var maxVolume).
+ Validate("Failed to get the max volume level");
+
return maxVolume;
}
}
}
-}
\ No newline at end of file
+}
- /*
+/*
* Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the License);
namespace Tizen.Multimedia
{
/// <summary>
- /// Class extending EventArgs and contains the necessary parameters to passed to FocusStateChanged event handler
+ /// Provides data for the <see cref="AudioStreamPolicy.StreamFocusStateChanged"/> event.
/// </summary>
public class StreamFocusStateChangedEventArgs : EventArgs
{
- /* FIXME */
- internal StreamFocusStateChangedEventArgs(AudioStreamFocusChangedReason reason, string extraInformation)
+ internal StreamFocusStateChangedEventArgs(AudioStreamFocusOptions options,
+ AudioStreamFocusState focusState, AudioStreamFocusChangedReason reason, string extraInfo)
{
- FocusChangedReason = reason;
- ExtraInformation = extraInformation;
+ FocusOptions = options;
+ FocusState = focusState;
+ Reason = reason;
+ ExtraInfo = extraInfo;
}
/// <summary>
- /// The reason for state change of the focus
+ /// Gets the focus options.
/// </summary>
- public AudioStreamFocusChangedReason FocusChangedReason { get; }
+ /// <value>The focus options.</value>
+ public AudioStreamFocusOptions FocusOptions { get; }
/// <summary>
- /// The extra information
+ /// Gets the changed focus state.
/// </summary>
- public string ExtraInformation { get; }
+ /// <value>The focus state.</value>
+ public AudioStreamFocusState FocusState { get; }
+
+ /// <summary>
+ /// Gets the reason for state change of the focus.
+ /// </summary>
+ /// <value>The reason for state change of the focus.</value>
+ public AudioStreamFocusChangedReason Reason { get; }
+
+ /// <summary>
+ /// Gets the extra information.
+ /// </summary>
+ /// <value>
+ /// The extra information specified in <see cref="AudioStreamPolicy.AcquireFocus(AudioStreamFocusOptions, AudioStreamBehaviors, string)"/> or
+ /// <see cref="AudioStreamPolicy.ReleaseFocus(AudioStreamFocusOptions, AudioStreamBehaviors, string)"/>.
+ /// </value>
+ /// <seealso cref="AudioStreamPolicy.AcquireFocus(AudioStreamFocusOptions, AudioStreamBehaviors, string)"/>
+ /// <seealso cref="AudioStreamPolicy.ReleaseFocus(AudioStreamFocusOptions, AudioStreamBehaviors, string)"/>
+ public string ExtraInfo { get; }
}
}
- /*
+/*
* Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the License);
namespace Tizen.Multimedia
{
/// <summary>
- /// Extnded EventArgs which contains the parameteres to be passed to the AudioVolume Changed event
+ /// Provides data for the <see cref="AudioVolume.Changed"/> event.
/// </summary>
public class VolumeChangedEventArgs : EventArgs
{
internal VolumeChangedEventArgs(AudioVolumeType type, uint level)
{
Type = type;
- Level = level;
+ Level = (int)level;
}
/// <summary>
- /// The sound type of the changed volume
+ /// Gets the sound type that volume is changed.
/// </summary>
+ /// <value>The sound type that volume is changed.</value>
public AudioVolumeType Type { get; }
/// <summary>
- /// The new volume value
+ /// Gets the new volume.
/// </summary>
- public uint Level { get; }
+ /// <value>The new volume level.</value>
+ public int Level { get; }
}
}
- /*
+/*
* Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the License);
namespace Tizen.Multimedia
{
- internal static class VolumeLevelLog
- {
- internal const string Tag = "Tizen.Multimedia.VolumeLevel";
- }
/// <summary>
- /// This is a indexer class which is used to get/set the volume level
- /// specified for a particular sound type.
+ /// Provides a means to control volume levels.
/// </summary>
public class VolumeLevel
{
- public int this [AudioVolumeType type] {
- get {
- if(type == AudioVolumeType.None)
- throw new ArgumentException("Wrong Audio volume type. Cannot get volume level for AudioVolumeType.None");
- int volume;
- int ret = Interop.AudioVolume.GetVolume(type, out volume);
- if(ret != 0) {
- Tizen.Log.Info(VolumeLevelLog.Tag, "Get Level Error: " + (AudioManagerError)ret);
- return -1;
+ internal VolumeLevel()
+ {
+ }
+
+ /// <summary>
+ /// Gets or sets the volume level of the specified <see cref="AudioVolumeType"/>
+ /// </summary>
+ /// <param name="type">The <see cref="AudioVolumeType"/> to control.</param>
+ /// <value>The current volume level.</value>
+ /// <remarks>To set volumes, the specified privilege is required.</remarks>
+ /// <privilege>http://tizen.org/privilege/volume.set</privilege>
+ /// <exception cref="ArgumentException"><paramref name="type"/> is invalid.</exception>
+ /// <exception cref="ArgumentOutOfRangeException">
+ /// <paramref name="type"/> is <see cref="AudioVolumeType.None"/>.
+ /// -or-
+ /// <paramref name="value"/> is less than zero.
+ /// -or-
+ /// <paramref name="value"/> is greater than <see cref="MaxVolumeLevel.this[AudioVolumeType]"/>.
+ /// </exception>
+ /// <exception cref="UnauthorizedAccessException">Caller does not have required privilege to set volume.</exception>
+ public int this[AudioVolumeType type]
+ {
+ get
+ {
+ ValidationUtil.ValidateEnum(typeof(AudioVolumeType), type, nameof(type));
+
+ if (type == AudioVolumeType.None)
+ {
+ throw new ArgumentOutOfRangeException(nameof(type),
+ "Cannot get volume level for AudioVolumeType.None");
}
+
+ Interop.AudioVolume.GetVolume(type, out var volume).Validate("Failed to get the volume level");
+
return volume;
}
- set {
- if(type == AudioVolumeType.None)
- throw new ArgumentException("Wrong Audio volume type. Cannot set volume level for AudioVolumeType.None");
- int ret = Interop.AudioVolume.SetVolume(type, value);
- if(ret != 0) {
- Tizen.Log.Info(VolumeLevelLog.Tag, "Set Level Error: " + (AudioManagerError)ret);
- AudioManagerErrorFactory.CheckAndThrowException(ret, "Unable to set level");
+ set
+ {
+ ValidationUtil.ValidateEnum(typeof(AudioVolumeType), type, nameof(value));
+
+ if (type == AudioVolumeType.None)
+ {
+ throw new ArgumentOutOfRangeException(nameof(type),
+ "Cannot set volume level for AudioVolumeType.None");
+ }
+
+ var ret = Interop.AudioVolume.SetVolume(type, value);
+
+ if (ret == AudioManagerError.InvalidParameter)
+ {
+ throw new ArgumentOutOfRangeException(nameof(value), value,
+ $"valid volume level range is 0 <= x <= {nameof(MaxVolumeLevel)}[{nameof(AudioVolumeType)}]");
}
+
+ ret.Validate("Failed to set the volume level");
}
}
}
-}
\ No newline at end of file
+}
-
+/*
+ * 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;
namespace Tizen.Multimedia
--- /dev/null
+/*
+ * 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.Runtime.InteropServices;
+
+namespace Tizen.Multimedia
+{
+ internal class AudioStreamPolicyHandle : SafeHandle
+ {
+ protected AudioStreamPolicyHandle() : base(IntPtr.Zero, true)
+ {
+ }
+
+ public override bool IsInvalid => handle == IntPtr.Zero;
+
+ protected override bool ReleaseHandle()
+ {
+ var ret = Interop.AudioStreamPolicy.Destroy(handle);
+ if (ret != AudioManagerError.None)
+ {
+ Log.Debug(GetType().FullName, $"Failed to release native {GetType()}");
+ return false;
+ }
+
+ return true;
+ }
+ }
+}
-using System;
+/*
+ * 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.Runtime.InteropServices;
namespace Tizen.Multimedia
{
internal static partial class Interop
{
- [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
- internal delegate void SoundDeviceConnectionChangedCallback(IntPtr device, bool isConnected, IntPtr userData);
-
- [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
- internal delegate void SoundDeviceStateChangedCallback(IntPtr device, AudioDeviceState changedState, IntPtr userData);
-
internal static partial class AudioDevice
{
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_get_device_list")]
- internal static extern int GetCurrentDeviceList(AudioDeviceOptions deviceMask, out IntPtr deviceList);
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ internal delegate void ConnectionChangedCallback(IntPtr device, bool isConnected, IntPtr userData);
+
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ internal delegate void StateChangedCallback(IntPtr device, AudioDeviceState changedState, IntPtr userData);
+
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_get_device_list")]
+ internal static extern AudioManagerError GetDeviceList(AudioDeviceOptions deviceMask, out IntPtr deviceList);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_free_device_list")]
- internal static extern int FreeDeviceList(IntPtr deviceList);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_free_device_list")]
+ internal static extern AudioManagerError FreeDeviceList(IntPtr deviceList);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_get_next_device")]
- internal static extern int GetNextDevice(IntPtr deviceList, out IntPtr device);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_get_next_device")]
+ internal static extern AudioManagerError GetNextDevice(IntPtr deviceList, out IntPtr device);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_get_device_type")]
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_get_device_type")]
internal static extern int GetDeviceType(IntPtr device, out AudioDeviceType type);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_get_device_io_direction")]
- internal static extern int GetDeviceIoDirection(IntPtr device, out AudioDeviceIoDirection ioDirection);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_get_device_io_direction")]
+ internal static extern AudioManagerError GetDeviceIoDirection(IntPtr device, out AudioDeviceIoDirection ioDirection);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_get_device_id")]
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_get_device_id")]
internal static extern int GetDeviceId(IntPtr device, out int id);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_get_device_name")]
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_get_device_name")]
internal static extern int GetDeviceName(IntPtr device, out IntPtr name);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_get_device_state")]
- internal static extern int GetDeviceState(IntPtr device, out AudioDeviceState state);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_get_device_state_by_id")]
+ internal static extern AudioManagerError GetDeviceState(int deviceId, out AudioDeviceState state);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_add_device_connection_changed_cb")]
- internal static extern int AddDeviceConnectionChangedCallback(AudioDeviceOptions deviceMask, SoundDeviceConnectionChangedCallback callback, IntPtr userData, out int id);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_add_device_connection_changed_cb")]
+ internal static extern AudioManagerError AddDeviceConnectionChangedCallback(
+ AudioDeviceOptions deviceMask, ConnectionChangedCallback callback, IntPtr userData, out int id);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_remove_device_connection_changed_cb")]
- internal static extern int RemoveDeviceConnectionChangedCallback(int id);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_remove_device_connection_changed_cb")]
+ internal static extern AudioManagerError RemoveDeviceConnectionChangedCallback(int id);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_add_device_state_changed_cb")]
- internal static extern int AddDeviceStateChangedCallback(AudioDeviceOptions deviceMask, SoundDeviceStateChangedCallback callback, IntPtr userData, out int id);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_add_device_state_changed_cb")]
+ internal static extern AudioManagerError AddDeviceStateChangedCallback(AudioDeviceOptions deviceMask,
+ StateChangedCallback callback, IntPtr userData, out int id);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_remove_device_state_changed_cb")]
- internal static extern int RemoveDeviceStateChangedCallback(int id);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_remove_device_state_changed_cb")]
+ internal static extern AudioManagerError RemoveDeviceStateChangedCallback(int id);
}
}
}
\ No newline at end of file
-using System;
+/*
+ * 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.Runtime.InteropServices;
namespace Tizen.Multimedia
-using System;
+/*
+ * 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.Runtime.InteropServices;
namespace Tizen.Multimedia
+/*
+ * 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.Runtime.InteropServices;
[DllImport(Libraries.MediaTool, EntryPoint = "media_packet_set_buffer_size")]
internal static extern int SetBufferSize(IntPtr handle, ulong size);
-
[DllImport(Libraries.MediaTool, EntryPoint = "media_packet_get_allocated_buffer_size")]
internal static extern int GetAllocatedBufferSize(IntPtr handle, out int size);
-using System;
+/*
+ * 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.Runtime.InteropServices;
namespace Tizen.Multimedia
{
internal static partial class Interop
{
- [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
- internal delegate void SoundStreamFocusStateChangedCallback(IntPtr streamInfo, AudioStreamFocusOptions focusMask, AudioStreamFocusState focusState, int reason, int audioStreamBehavior, string extraInfo, IntPtr userData);
-
- [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
- internal delegate void SoundStreamFocusStateWatchCallback(int id, AudioStreamFocusOptions focusMask, AudioStreamFocusState focusState, AudioStreamFocusChangedReason reason, string extraInfo, IntPtr userData);
-
internal static partial class AudioStreamPolicy
{
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_create_stream_information")]
- internal static extern int CreateStreamInformation(int streamType, SoundStreamFocusStateChangedCallback callback, IntPtr userData, out IntPtr streamInfo);
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ internal delegate void FocusStateChangedCallback(IntPtr streamInfo, AudioStreamFocusOptions focusMask,
+ AudioStreamFocusState focusState, AudioStreamFocusChangedReason reason,
+ AudioStreamBehaviors audioStreamBehavior, string extraInfo, IntPtr userData);
+
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ internal delegate void FocusStateWatchCallback(int id, AudioStreamFocusOptions focusMask,
+ AudioStreamFocusState focusState, AudioStreamFocusChangedReason reason, string extraInfo,
+ IntPtr userData);
+
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_create_stream_information")]
+ internal static extern AudioManagerError Create(AudioStreamType streamType,
+ FocusStateChangedCallback callback, IntPtr userData, out AudioStreamPolicyHandle streamInfo);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_destroy_stream_information")]
- internal static extern int DestroyStreamInformation(IntPtr streamInfo);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_destroy_stream_information")]
+ internal static extern AudioManagerError Destroy(IntPtr streamInfo);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_add_device_for_stream_routing")]
- internal static extern int AddDeviceForStreamRouting(IntPtr streamInfo, IntPtr device);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_add_device_id_for_stream_routing")]
+ internal static extern AudioManagerError AddDeviceForStreamRouting(
+ AudioStreamPolicyHandle streamInfo, int deviceId);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_remove_device_for_stream_routing")]
- internal static extern int RemoveDeviceForStreamRouting(IntPtr streamInfo, IntPtr device);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_remove_device_id_for_stream_routing")]
+ internal static extern AudioManagerError RemoveDeviceForStreamRouting(
+ AudioStreamPolicyHandle streamInfo, int device);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_apply_stream_routing")]
- internal static extern int ApplyStreamRouting(IntPtr streamInfo);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_apply_stream_routing")]
+ internal static extern AudioManagerError ApplyStreamRouting(AudioStreamPolicyHandle streamInfo);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_acquire_focus")]
- internal static extern int AcquireFocus(IntPtr streamInfo, AudioStreamFocusOptions focusMask, int audioStreamBehavior, string extraInfo);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_acquire_focus")]
+ internal static extern AudioManagerError AcquireFocus(AudioStreamPolicyHandle streamInfo,
+ AudioStreamFocusOptions focusMask, AudioStreamBehaviors audioStreamBehavior, string extraInfo);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_release_focus")]
- internal static extern int ReleaseFocus(IntPtr streamInfo, AudioStreamFocusOptions focusMask, int audioStreamBehavior, string extraInfo);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_release_focus")]
+ internal static extern AudioManagerError ReleaseFocus(AudioStreamPolicyHandle streamInfo,
+ AudioStreamFocusOptions focusMask, AudioStreamBehaviors audioStreamBehavior, string extraInfo);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_get_focus_state")]
- internal static extern int GetFocusState(IntPtr streaInfo, out AudioStreamFocusState stateForPlayback, out AudioStreamFocusState stateForRecording);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_get_focus_state")]
+ internal static extern int GetFocusState(AudioStreamPolicyHandle streamInfo,
+ out AudioStreamFocusState stateForPlayback, out AudioStreamFocusState stateForRecording);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_set_focus_reacquisition")]
- internal static extern int SetFocusReacquisition(IntPtr streamInfo, bool enable);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_set_focus_reacquisition")]
+ internal static extern AudioManagerError SetFocusReacquisition(AudioStreamPolicyHandle streamInfo,
+ bool enable);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_get_focus_reacquisition")]
- internal static extern int GetFocusReacquisition(IntPtr streamInfo, out bool enabled);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_get_focus_reacquisition")]
+ internal static extern AudioManagerError GetFocusReacquisition(AudioStreamPolicyHandle streamInfo,
+ out bool enabled);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_get_sound_type")]
- internal static extern int GetSoundType(IntPtr streamInfo, out AudioVolumeType soundType);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_get_sound_type")]
+ internal static extern AudioManagerError GetSoundType(AudioStreamPolicyHandle streamInfo,
+ out AudioVolumeType soundType);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_add_focus_state_watch_cb")]
- internal static extern int AddFocusStateWatchCallback(AudioStreamFocusOptions focusMask, SoundStreamFocusStateWatchCallback callback, IntPtr userData, out int id);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_add_focus_state_watch_cb")]
+ internal static extern AudioManagerError AddFocusStateWatchCallback(AudioStreamFocusOptions focusMask,
+ FocusStateWatchCallback callback, IntPtr userData, out int id);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_remove_focus_state_watch_cb")]
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_remove_focus_state_watch_cb")]
internal static extern int RemoveFocusStateWatchCallback(int id);
}
}
-using System;
+/*
+ * 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.Runtime.InteropServices;
namespace Tizen.Multimedia
{
internal static partial class Interop
{
- [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
- internal delegate void SoundManagerVolumeChangedCallback(AudioVolumeType type, uint volume, IntPtr userData);
-
internal static partial class AudioVolume
{
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_get_max_volume")]
- internal static extern int GetMaxVolume(AudioVolumeType type, out int max);
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ internal delegate void VolumeChangedCallback(AudioVolumeType type, uint volume, IntPtr userData);
+
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_get_max_volume")]
+ internal static extern AudioManagerError GetMaxVolume(AudioVolumeType type, out int max);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_set_volume")]
- internal static extern int SetVolume(AudioVolumeType type, int volume);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_set_volume")]
+ internal static extern AudioManagerError SetVolume(AudioVolumeType type, int volume);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_get_volume")]
- internal static extern int GetVolume(AudioVolumeType type, out int volume);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_get_volume")]
+ internal static extern AudioManagerError GetVolume(AudioVolumeType type, out int volume);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_get_current_sound_type")]
- internal static extern int GetCurrentSoundType(out AudioVolumeType type);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_get_current_sound_type")]
+ internal static extern AudioManagerError GetCurrentSoundType(out AudioVolumeType type);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_add_volume_changed_cb")]
- internal static extern int AddVolumeChangedCallback(SoundManagerVolumeChangedCallback callback, IntPtr userData, out int id);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_add_volume_changed_cb")]
+ internal static extern AudioManagerError AddVolumeChangedCallback(VolumeChangedCallback callback,
+ IntPtr userData, out int id);
- [DllImportAttribute(Libraries.SoundManager, EntryPoint = "sound_manager_remove_volume_changed_cb")]
- internal static extern int RemoveVolumeChangedCallback(int id);
+ [DllImport(Libraries.SoundManager, EntryPoint = "sound_manager_remove_volume_changed_cb")]
+ internal static extern AudioManagerError RemoveVolumeChangedCallback(int id);
}
}
}
\ No newline at end of file
--- /dev/null
+/*
+ * 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.Diagnostics;
+using Tizen.Internals.Errors;
+
+namespace Tizen.Multimedia
+{
+ /// <summary>
+ /// Represents an audio media format. This class cannot be inherited.
+ /// </summary>
+ public sealed class AudioMediaFormat : MediaFormat
+ {
+
+ /// <summary>
+ /// Initializes a new instance of the AudioMediaFormat class with the specified mime type,
+ /// channel, sample rate, bit and bit rate.
+ /// </summary>
+ /// <param name="mimeType">The mime type of the format.</param>
+ /// <param name="channel">The channel value of the format.</param>
+ /// <param name="sampleRate">The sample rate value of the format.</param>
+ /// <param name="bit">The bit value of the format.</param>
+ /// <param name="bitRate">The bit rate value of the format.</param>
+ /// <exception cref="ArgumentException"><paramref name="mimeType"/> is invalid(i.e. undefined value).</exception>
+ /// <exception cref="ArgumentOutOfRangeException">
+ /// <paramref name="channel"/>, <paramref name="sampleRate"/>, <paramref name="bit"/> or <paramref name="bitRate"/> is less than zero.
+ /// </exception>
+ public AudioMediaFormat(MediaFormatAudioMimeType mimeType,
+ int channel, int sampleRate, int bit, int bitRate)
+ : this(mimeType, channel, sampleRate, bit, bitRate, MediaFormatAacType.None)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the AudioMediaFormat class with the specified mime type,
+ /// channel, sample rate, bit, bit rate and aac type.
+ /// </summary>
+ /// <param name="mimeType">The mime type of the format.</param>
+ /// <param name="channel">The channel value of the format.</param>
+ /// <param name="sampleRate">The sample rate value of the format.</param>
+ /// <param name="bit">The bit value of the format.</param>
+ /// <param name="bitRate">The bit rate value of the format.</param>
+ /// <param name="aacType">The AAC bitstream format(ADIF or ADTS).</param>
+ /// <exception cref="ArgumentException">
+ /// <paramref name="mimeType"/> or <paramref name="aacType"/> is invalid(i.e. undefined value).\n
+ /// -or-\n
+ /// <paramref name="aacType"/> is not <see cref="MediaFormatAacType.None"/>, but <paramref name="mimeType"/> is one of aac types.
+ /// </exception>
+ /// <exception cref="ArgumentOutOfRangeException">
+ /// <paramref name="channel"/>, <paramref name="sampleRate"/>, <paramref name="bit"/> or <paramref name="bitRate"/> is less than zero.
+ /// </exception>
+ public AudioMediaFormat(MediaFormatAudioMimeType mimeType,
+ int channel, int sampleRate, int bit, int bitRate, MediaFormatAacType aacType)
+ : base(MediaFormatType.Audio)
+ {
+ if (!Enum.IsDefined(typeof(MediaFormatAudioMimeType), mimeType))
+ {
+ throw new ArgumentException($"Invalid mime type value : { (int)mimeType }");
+ }
+ if (channel < 0)
+ {
+ throw new ArgumentOutOfRangeException("Channel value can't be negative.");
+ }
+ if (sampleRate < 0)
+ {
+ throw new ArgumentOutOfRangeException("Sample rate value can't be negative.");
+ }
+ if (bit < 0)
+ {
+ throw new ArgumentOutOfRangeException("Bit value can't be negative.");
+ }
+ if (bitRate < 0)
+ {
+ throw new ArgumentOutOfRangeException("Bit rate value can't be negative.");
+ }
+ if (!Enum.IsDefined(typeof(MediaFormatAacType), aacType))
+ {
+ throw new ArgumentException($"Invalid aac type value : { (int)aacType }");
+ }
+ if (!IsAacSupportedMimeType(mimeType) && aacType != MediaFormatAacType.None)
+ {
+ throw new ArgumentException("Aac is supported only with aac mime types.");
+ }
+
+ MimeType = mimeType;
+ Channel = channel;
+ SampleRate = sampleRate;
+ Bit = bit;
+ BitRate = bitRate;
+ AacType = aacType;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the AudioMediaFormat class from a native handle.
+ /// </summary>
+ /// <param name="handle">A native handle.</param>
+ internal AudioMediaFormat(IntPtr handle)
+ : base(MediaFormatType.Audio)
+ {
+ Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!");
+
+ MediaFormatAudioMimeType mimeType;
+ int channel = 0;
+ int sampleRate = 0;
+ int bit = 0;
+ int bitRate = 0;
+ MediaFormatAacType aacType;
+ GetInfo(handle, out mimeType, out channel, out sampleRate, out bit, out bitRate);
+
+ if (IsAacSupportedMimeType(mimeType))
+ {
+ GetAacType(handle, out aacType);
+ }
+ else
+ {
+ aacType = MediaFormatAacType.None;
+ }
+
+ MimeType = mimeType;
+ Channel = channel;
+ SampleRate = sampleRate;
+ Bit = bit;
+ BitRate = bitRate;
+ AacType = aacType;
+ }
+
+ /// <summary>
+ /// Returns an indication whether a specified mime type is a aac type.
+ /// </summary>
+ /// <param name="mimeType">A mime type.</param>
+ private static bool IsAacSupportedMimeType(MediaFormatAudioMimeType mimeType)
+ {
+ return mimeType == MediaFormatAudioMimeType.AacLC ||
+ mimeType == MediaFormatAudioMimeType.AacHE ||
+ mimeType == MediaFormatAudioMimeType.AacHEPS;
+ }
+
+ /// <summary>
+ /// Retrieves audio properties of media format from a native handle.
+ /// </summary>
+ /// <param name="handle">A native handle that properties are retrieved from.</param>
+ /// <param name="mimeType">An out parameter for mime type.</param>
+ /// <param name="channel">An out parameter for channel.</param>
+ /// <param name="sampleRate">An out parameter for sample rate.</param>
+ /// <param name="bit">An out parameter for bit.</param>
+ /// <param name="bitRate">An out parameter for bit rate.</param>
+ private static void GetInfo(IntPtr handle, out MediaFormatAudioMimeType mimeType,
+ out int channel, out int sampleRate, out int bit, out int bitRate)
+ {
+ Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!");
+
+ int mimeTypeValue = 0;
+
+ int ret = Interop.MediaFormat.GetAudioInfo(handle,
+ out mimeTypeValue, out channel, out sampleRate, out bit, out bitRate);
+
+ mimeType = (MediaFormatAudioMimeType)mimeTypeValue;
+
+ MultimediaDebug.AssertNoError(ret);
+
+ Debug.Assert(Enum.IsDefined(typeof(MediaFormatAudioMimeType), mimeType),
+ "Invalid audio mime type!");
+ }
+
+ /// <summary>
+ /// Retrieves aac type value from a native handle.
+ /// </summary>
+ /// <param name="handle">A native handle that properties are retrieved from.</param>
+ /// <param name="aacType">An out parameter for aac type.</param>
+ private static void GetAacType(IntPtr handle, out MediaFormatAacType aacType)
+ {
+ Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!");
+
+ int aacTypeValue = 0;
+
+ int ret = Interop.MediaFormat.GetAudioAacType(handle, out aacTypeValue);
+
+ MultimediaDebug.AssertNoError(ret);
+
+ aacType = (MediaFormatAacType)aacTypeValue;
+
+ Debug.Assert(Enum.IsDefined(typeof(MediaFormatAacType), aacType), "Invalid aac type!");
+ }
+
+ internal override void AsNativeHandle(IntPtr handle)
+ {
+ Debug.Assert(Type == MediaFormatType.Audio);
+
+ int ret = Interop.MediaFormat.SetAudioMimeType(handle, (int)MimeType);
+ MultimediaDebug.AssertNoError(ret);
+
+ ret = Interop.MediaFormat.SetAudioChannel(handle, Channel);
+ MultimediaDebug.AssertNoError(ret);
+
+ ret = Interop.MediaFormat.SetAudioSampleRate(handle, SampleRate);
+ MultimediaDebug.AssertNoError(ret);
+
+ ret = Interop.MediaFormat.SetAudioBit(handle, Bit);
+ MultimediaDebug.AssertNoError(ret);
+
+ ret = Interop.MediaFormat.SetAudioAverageBps(handle, BitRate);
+ MultimediaDebug.AssertNoError(ret);
+
+ ret = Interop.MediaFormat.SetAudioAacType(handle, (int)AacType);
+ MultimediaDebug.AssertNoError(ret);
+ }
+
+ /// <summary>
+ /// Gets the mime type of the current format.
+ /// </summary>
+ public MediaFormatAudioMimeType MimeType { get; }
+
+ /// <summary>
+ /// Gets the channel value of the current format.
+ /// </summary>
+ public int Channel { get; }
+
+ /// <summary>
+ /// Gets the sample rate value of the current format.
+ /// </summary>
+ public int SampleRate { get; }
+
+ /// <summary>
+ /// Gets the bit value of the current format.
+ /// </summary>
+ public int Bit { get; }
+
+ /// <summary>
+ /// Gets the bit rate value of the current format.
+ /// </summary>
+ public int BitRate { get; }
+
+ /// <summary>
+ /// Gets the aac type of the current format.
+ /// </summary>
+ public MediaFormatAacType AacType { get; }
+
+ public override string ToString()
+ {
+ return $@"MimeTyp={ MimeType.ToString() }, Channel={ Channel.ToString() }, SampleRate=
+ { SampleRate }, Bit={ Bit.ToString() }, BitRate={ BitRate.ToString() }, AacType={ AacType.ToString() }";
+ }
+
+ public override bool Equals(object obj)
+ {
+ var rhs = obj as AudioMediaFormat;
+ if (rhs == null)
+ {
+ return false;
+ }
+
+ return MimeType == rhs.MimeType && Channel == rhs.Channel && SampleRate == rhs.SampleRate &&
+ Bit == rhs.Bit && BitRate == rhs.BitRate;
+ }
+
+ public override int GetHashCode()
+ {
+ return new { MimeType, Channel, SampleRate, Bit, BitRate }.GetHashCode();
+ }
+ }
+}
--- /dev/null
+/*
+ * 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.Diagnostics;
+using Tizen.Internals.Errors;
+
+namespace Tizen.Multimedia
+{
+ /// <summary>
+ /// Represents a container media format. This class cannot be inherited.
+ /// </summary>
+ public sealed class ContainerMediaFormat : MediaFormat
+ {
+ /// <summary>
+ /// Initializes a new instance of the ContainerMediaFormat class.
+ /// </summary>
+ /// <param name="mimeType">The mime type of the container format.</param>
+ /// <exception cref="ArgumentException">mimeType is invalid(i.e. undefined value).</exception>
+ public ContainerMediaFormat(MediaFormatContainerMimeType mimeType)
+ : base(MediaFormatType.Container)
+ {
+ if (!Enum.IsDefined(typeof(MediaFormatContainerMimeType), mimeType))
+ {
+ throw new ArgumentException($"Invalid mime type value : { (int)mimeType }");
+ }
+ MimeType = mimeType;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the ContainerMediaFormat class from a native handle.
+ /// </summary>
+ /// <param name="handle">A native media format handle.</param>
+ internal ContainerMediaFormat(IntPtr handle)
+ : base(MediaFormatType.Container)
+ {
+ Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!");
+
+ int mimeType = 0;
+
+ int ret = Interop.MediaFormat.GetContainerMimeType(handle, out mimeType);
+
+ MultimediaDebug.AssertNoError(ret);
+
+ Debug.Assert(Enum.IsDefined(typeof(MediaFormatContainerMimeType), mimeType),
+ "Invalid container mime type!");
+
+ MimeType = (MediaFormatContainerMimeType)mimeType;
+ }
+
+ /// <summary>
+ /// Gets the mime type of the current format.
+ /// </summary>
+ public MediaFormatContainerMimeType MimeType
+ {
+ get;
+ }
+
+ internal override void AsNativeHandle(IntPtr handle)
+ {
+ Debug.Assert(Type == MediaFormatType.Container);
+
+ int ret = Interop.MediaFormat.SetContainerMimeType(handle, (int)MimeType);
+
+ MultimediaDebug.AssertNoError(ret);
+ }
+
+ public override string ToString()
+ {
+ return $"MimeType={ MimeType.ToString() }";
+ }
+
+ public override bool Equals(object obj)
+ {
+ var rhs = obj as ContainerMediaFormat;
+ if (rhs == null)
+ {
+ return false;
+ }
+
+ return MimeType == rhs.MimeType;
+ }
+
+ public override int GetHashCode()
+ {
+ return (int)MimeType;
+ }
+ }
+}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
using System;
using System.Diagnostics;
using Tizen.Internals.Errors;
/// <param name="handle">A native handle to be written.</param>
internal abstract void AsNativeHandle(IntPtr handle);
}
-
- /// <summary>
- /// Represents a container media format. This class cannot be inherited.
- /// </summary>
- public sealed class ContainerMediaFormat : MediaFormat
- {
- /// <summary>
- /// Initializes a new instance of the ContainerMediaFormat class.
- /// </summary>
- /// <param name="mimeType">The mime type of the container format.</param>
- /// <exception cref="ArgumentException">mimeType is invalid(i.e. undefined value).</exception>
- public ContainerMediaFormat(MediaFormatContainerMimeType mimeType)
- : base(MediaFormatType.Container)
- {
- if (!Enum.IsDefined(typeof(MediaFormatContainerMimeType), mimeType))
- {
- throw new ArgumentException($"Invalid mime type value : { (int)mimeType }");
- }
- MimeType = mimeType;
- }
-
- /// <summary>
- /// Initializes a new instance of the ContainerMediaFormat class from a native handle.
- /// </summary>
- /// <param name="handle">A native media format handle.</param>
- internal ContainerMediaFormat(IntPtr handle)
- : base(MediaFormatType.Container)
- {
- Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!");
-
- int mimeType = 0;
-
- int ret = Interop.MediaFormat.GetContainerMimeType(handle, out mimeType);
-
- MultimediaDebug.AssertNoError(ret);
-
- Debug.Assert(Enum.IsDefined(typeof(MediaFormatContainerMimeType), mimeType),
- "Invalid container mime type!");
-
- MimeType = (MediaFormatContainerMimeType)mimeType;
- }
-
- /// <summary>
- /// Gets the mime type of the current format.
- /// </summary>
- public MediaFormatContainerMimeType MimeType
- {
- get;
- }
-
- internal override void AsNativeHandle(IntPtr handle)
- {
- Debug.Assert(Type == MediaFormatType.Container);
-
- int ret = Interop.MediaFormat.SetContainerMimeType(handle, (int)MimeType);
-
- MultimediaDebug.AssertNoError(ret);
- }
-
- public override string ToString()
- {
- return $"MimeType={ MimeType.ToString() }";
- }
-
- public override bool Equals(object obj)
- {
- var rhs = obj as ContainerMediaFormat;
- if (rhs == null)
- {
- return false;
- }
-
- return MimeType == rhs.MimeType;
- }
-
- public override int GetHashCode()
- {
- return (int)MimeType;
- }
- }
-
- /// <summary>
- /// Represents a video media format. This class cannot be inherited.
- /// </summary>
- public sealed class VideoMediaFormat : MediaFormat
- {
- private const int DefaultFrameRate = 0;
- private const int DefaultBitRate = 0;
-
- /// <summary>
- /// Initializes a new instance of the VideoMediaFormat class with the specified mime type, width and height.
- /// </summary>
- /// <param name="mimeType">The mime type of the format.</param>
- /// <param name="width">The width value of the format.</param>
- /// <param name="height">The height value of the format</param>
- /// <exception cref="ArgumentException">mimeType is invalid(i.e. undefined value).</exception>
- /// <exception cref="ArgumentOutOfRangeException">width, or height is less than zero.</exception>
- public VideoMediaFormat(MediaFormatVideoMimeType mimeType, int width, int height)
- : this(mimeType, width, height, DefaultFrameRate)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the VideoMediaFormat class with the specified mime type and size.
- /// </summary>
- /// <param name="mimeType">The mime type of the format.</param>
- /// <param name="size">The size of the format.</param>
- /// <exception cref="ArgumentException">mimeType is invalid(i.e. undefined value).</exception>
- /// <exception cref="ArgumentOutOfRangeException">width, or height is less than zero.</exception>
- public VideoMediaFormat(MediaFormatVideoMimeType mimeType, Size size)
- : this(mimeType, size, DefaultFrameRate)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the VideoMediaFormat class with the specified mime type,
- /// width, height and frame rate.
- /// </summary>
- /// <param name="mimeType">The mime type of the format.</param>
- /// <param name="width">The width value of the format.</param>
- /// <param name="height">The height value of the format</param>
- /// <param name="frameRate">The frame rate of the format.</param>
- /// <exception cref="ArgumentException">mimeType is invalid(i.e. undefined value).</exception>
- /// <exception cref="ArgumentOutOfRangeException">width, height or frameRate is less than zero.</exception>
- public VideoMediaFormat(MediaFormatVideoMimeType mimeType, int width, int height,
- int frameRate)
- : this(mimeType, width, height, frameRate, DefaultBitRate)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the VideoMediaFormat class with the specified mime type,
- /// width, height and frame rate.
- /// </summary>
- /// <param name="mimeType">The mime type of the format.</param>
- /// <param name="size">The video size of the format.</param>
- /// <param name="frameRate">The frame rate of the format.</param>
- /// <exception cref="ArgumentException">mimeType is invalid(i.e. undefined value).</exception>
- /// <exception cref="ArgumentOutOfRangeException">width, height or frameRate is less than zero.</exception>
- public VideoMediaFormat(MediaFormatVideoMimeType mimeType, Size size,
- int frameRate)
- : this(mimeType, size, frameRate, DefaultBitRate)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the VideoMediaFormat class with the specified mime type,
- /// width, height, frame rate and bit rate.
- /// </summary>
- /// <param name="mimeType">The mime type of the format.</param>
- /// <param name="width">The width value of the format.</param>
- /// <param name="height">The height value of the format</param>
- /// <param name="frameRate">The frame rate of the format.</param>
- /// <param name="bitRate">The bit rate of the format.</param>
- /// <exception cref="ArgumentException">mimeType is invalid(i.e. undefined value).</exception>
- /// <exception cref="ArgumentOutOfRangeException">width, height, frameRate or bitRate is less than zero.</exception>
- public VideoMediaFormat(MediaFormatVideoMimeType mimeType, int width, int height,
- int frameRate, int bitRate)
- : this(mimeType, new Size(width, height), frameRate, bitRate)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the VideoMediaFormat class with the specified mime type,
- /// size, frame rate and bit rate.
- /// </summary>
- /// <param name="mimeType">The mime type of the format.</param>
- /// <param name="size">The size of the format.</param>
- /// <param name="frameRate">The frame rate of the format.</param>
- /// <param name="bitRate">The bit rate of the format.</param>
- /// <exception cref="ArgumentException">mimeType is invalid(i.e. undefined value).</exception>
- /// <exception cref="ArgumentOutOfRangeException">width, height, frameRate or bitRate is less than zero.</exception>
- public VideoMediaFormat(MediaFormatVideoMimeType mimeType, Size size,
- int frameRate, int bitRate)
- : base(MediaFormatType.Video)
- {
- if (!Enum.IsDefined(typeof(MediaFormatVideoMimeType), mimeType))
- {
- throw new ArgumentException($"Invalid mime type value : { (int)mimeType }");
- }
- if (size.Width < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(size), size.Width, "Size.Width value can't be less than zero.");
- }
- if (size.Height < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(size), size.Height, "Size.Height value can't be less than zero.");
- }
- if (frameRate < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(frameRate), frameRate, "Frame rate can't be less than zero.");
- }
- if (bitRate < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(bitRate), bitRate, "Bit rate value can't be less than zero.");
- }
-
- MimeType = mimeType;
- Size = size;
- FrameRate = frameRate;
- BitRate = bitRate;
- }
-
- /// <summary>
- /// Initializes a new instance of the VideoMediaForma class from a native handle.
- /// </summary>
- /// <param name="handle">A native handle.</param>
- internal VideoMediaFormat(IntPtr handle)
- : base(MediaFormatType.Video)
- {
- Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!");
-
- int width = 0;
- int height = 0;
- int bitRate = 0;
- int frameRate = 0;
- MediaFormatVideoMimeType mimeType;
- GetInfo(handle, out width, out height, out bitRate, out mimeType);
-
- GetFrameRate(handle, out frameRate);
-
- MimeType = mimeType;
- Size = new Size(width, height);
- FrameRate = frameRate;
- BitRate = bitRate;
- }
-
- /// <summary>
- /// Retrieves video properties of media format from a native handle.
- /// </summary>
- /// <param name="handle">A native handle that properties are retrieved from.</param>
- /// <param name="width">An out parameter for width.</param>
- /// <param name="height">An out parameter for height.</param>
- /// <param name="bitRate">An out parameter for bit rate.</param>
- /// <param name="mimeType">An out parameter for mime type.</param>
- private static void GetInfo(IntPtr handle, out int width, out int height, out int bitRate,
- out MediaFormatVideoMimeType mimeType)
- {
- Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!");
-
- int mimeTypeValue = 0;
- int maxBps = 0;
-
- int ret = Interop.MediaFormat.GetVideoInfo(handle,
- out mimeTypeValue, out width, out height, out bitRate, out maxBps);
-
- MultimediaDebug.AssertNoError(ret);
-
- mimeType = (MediaFormatVideoMimeType)mimeTypeValue;
-
- Debug.Assert(Enum.IsDefined(typeof(MediaFormatVideoMimeType), mimeType),
- "Invalid video mime type!");
- }
-
- /// <summary>
- /// Retrieves frame rate from a native handle.
- /// </summary>
- /// <param name="handle">A native handle that properties are retrieved from.</param>
- /// <param name="frameRate">An out parameter for frame rate.</param>
- private static void GetFrameRate(IntPtr handle, out int frameRate)
- {
- Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!");
-
- int ret = Interop.MediaFormat.GetVideoFrameRate(handle, out frameRate);
-
- MultimediaDebug.AssertNoError(ret);
- }
-
- internal override void AsNativeHandle(IntPtr handle)
- {
- Debug.Assert(Type == MediaFormatType.Video);
-
- int ret = Interop.MediaFormat.SetVideoMimeType(handle, (int)MimeType);
- MultimediaDebug.AssertNoError(ret);
-
- ret = Interop.MediaFormat.SetVideoWidth(handle, Size.Width);
- MultimediaDebug.AssertNoError(ret);
-
- ret = Interop.MediaFormat.SetVideoHeight(handle, Size.Height);
- MultimediaDebug.AssertNoError(ret);
-
- ret = Interop.MediaFormat.SetVideoAverageBps(handle, BitRate);
- MultimediaDebug.AssertNoError(ret);
-
- ret = Interop.MediaFormat.SetVideoFrameRate(handle, FrameRate);
- MultimediaDebug.AssertNoError(ret);
- }
-
- /// <summary>
- /// Gets the mime type of the current format.
- /// </summary>
- public MediaFormatVideoMimeType MimeType { get; }
-
- /// <summary>
- /// Gets the size of the current format.
- /// </summary>
- public Size Size { get; }
-
- /// <summary>
- /// Gets the frame rate value of the current format.
- /// </summary>
- public int FrameRate { get; }
-
- /// <summary>
- /// Gets the bit rate value of the current format.
- /// </summary>
- public int BitRate { get; }
-
- public override string ToString()
- {
- return $@"MimeType={ MimeType.ToString() }, Size=({ Size.ToString() }), FrameRate=
- { FrameRate.ToString() }, BitRate={ BitRate.ToString() }";
- }
-
- public override bool Equals(object obj)
- {
- var rhs = obj as VideoMediaFormat;
- if (rhs == null)
- {
- return false;
- }
-
- return MimeType == rhs.MimeType && Size == rhs.Size &&
- FrameRate == rhs.FrameRate && BitRate == rhs.BitRate;
- }
-
- public override int GetHashCode()
- {
- return new { MimeType, Size, FrameRate, BitRate }.GetHashCode();
- }
- }
-
- /// <summary>
- /// Represents an audio media format. This class cannot be inherited.
- /// </summary>
- public sealed class AudioMediaFormat : MediaFormat
- {
-
- /// <summary>
- /// Initializes a new instance of the AudioMediaFormat class with the specified mime type,
- /// channel, sample rate, bit and bit rate.
- /// </summary>
- /// <param name="mimeType">The mime type of the format.</param>
- /// <param name="channel">The channel value of the format.</param>
- /// <param name="sampleRate">The sample rate value of the format.</param>
- /// <param name="bit">The bit value of the format.</param>
- /// <param name="bitRate">The bit rate value of the format.</param>
- /// <exception cref="ArgumentException"><paramref name="mimeType"/> is invalid(i.e. undefined value).</exception>
- /// <exception cref="ArgumentOutOfRangeException">
- /// <paramref name="channel"/>, <paramref name="sampleRate"/>, <paramref name="bit"/> or <paramref name="bitRate"/> is less than zero.
- /// </exception>
- public AudioMediaFormat(MediaFormatAudioMimeType mimeType,
- int channel, int sampleRate, int bit, int bitRate)
- : this(mimeType, channel, sampleRate, bit, bitRate, MediaFormatAacType.None)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the AudioMediaFormat class with the specified mime type,
- /// channel, sample rate, bit, bit rate and aac type.
- /// </summary>
- /// <param name="mimeType">The mime type of the format.</param>
- /// <param name="channel">The channel value of the format.</param>
- /// <param name="sampleRate">The sample rate value of the format.</param>
- /// <param name="bit">The bit value of the format.</param>
- /// <param name="bitRate">The bit rate value of the format.</param>
- /// <param name="aacType">The AAC bitstream format(ADIF or ADTS).</param>
- /// <exception cref="ArgumentException">
- /// <paramref name="mimeType"/> or <paramref name="aacType"/> is invalid(i.e. undefined value).\n
- /// -or-\n
- /// <paramref name="aacType"/> is not <see cref="MediaFormatAacType.None"/>, but <paramref name="mimeType"/> is one of aac types.
- /// </exception>
- /// <exception cref="ArgumentOutOfRangeException">
- /// <paramref name="channel"/>, <paramref name="sampleRate"/>, <paramref name="bit"/> or <paramref name="bitRate"/> is less than zero.
- /// </exception>
- public AudioMediaFormat(MediaFormatAudioMimeType mimeType,
- int channel, int sampleRate, int bit, int bitRate, MediaFormatAacType aacType)
- : base(MediaFormatType.Audio)
- {
- if (!Enum.IsDefined(typeof(MediaFormatAudioMimeType), mimeType))
- {
- throw new ArgumentException($"Invalid mime type value : { (int)mimeType }");
- }
- if (channel < 0)
- {
- throw new ArgumentOutOfRangeException("Channel value can't be negative.");
- }
- if (sampleRate < 0)
- {
- throw new ArgumentOutOfRangeException("Sample rate value can't be negative.");
- }
- if (bit < 0)
- {
- throw new ArgumentOutOfRangeException("Bit value can't be negative.");
- }
- if (bitRate < 0)
- {
- throw new ArgumentOutOfRangeException("Bit rate value can't be negative.");
- }
- if (!Enum.IsDefined(typeof(MediaFormatAacType), aacType))
- {
- throw new ArgumentException($"Invalid aac type value : { (int)aacType }");
- }
- if (!IsAacSupportedMimeType(mimeType) && aacType != MediaFormatAacType.None)
- {
- throw new ArgumentException("Aac is supported only with aac mime types.");
- }
-
- MimeType = mimeType;
- Channel = channel;
- SampleRate = sampleRate;
- Bit = bit;
- BitRate = bitRate;
- AacType = aacType;
- }
-
- /// <summary>
- /// Initializes a new instance of the AudioMediaFormat class from a native handle.
- /// </summary>
- /// <param name="handle">A native handle.</param>
- internal AudioMediaFormat(IntPtr handle)
- : base(MediaFormatType.Audio)
- {
- Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!");
-
- MediaFormatAudioMimeType mimeType;
- int channel = 0;
- int sampleRate = 0;
- int bit = 0;
- int bitRate = 0;
- MediaFormatAacType aacType;
- GetInfo(handle, out mimeType, out channel, out sampleRate, out bit, out bitRate);
-
- if (IsAacSupportedMimeType(mimeType))
- {
- GetAacType(handle, out aacType);
- }
- else
- {
- aacType = MediaFormatAacType.None;
- }
-
- MimeType = mimeType;
- Channel = channel;
- SampleRate = sampleRate;
- Bit = bit;
- BitRate = bitRate;
- AacType = aacType;
- }
-
- /// <summary>
- /// Returns an indication whether a specified mime type is a aac type.
- /// </summary>
- /// <param name="mimeType">A mime type.</param>
- private static bool IsAacSupportedMimeType(MediaFormatAudioMimeType mimeType)
- {
- return mimeType == MediaFormatAudioMimeType.AacLC ||
- mimeType == MediaFormatAudioMimeType.AacHE ||
- mimeType == MediaFormatAudioMimeType.AacHEPS;
- }
-
- /// <summary>
- /// Retrieves audio properties of media format from a native handle.
- /// </summary>
- /// <param name="handle">A native handle that properties are retrieved from.</param>
- /// <param name="mimeType">An out parameter for mime type.</param>
- /// <param name="channel">An out parameter for channel.</param>
- /// <param name="sampleRate">An out parameter for sample rate.</param>
- /// <param name="bit">An out parameter for bit.</param>
- /// <param name="bitRate">An out parameter for bit rate.</param>
- private static void GetInfo(IntPtr handle, out MediaFormatAudioMimeType mimeType,
- out int channel, out int sampleRate, out int bit, out int bitRate)
- {
- Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!");
-
- int mimeTypeValue = 0;
-
- int ret = Interop.MediaFormat.GetAudioInfo(handle,
- out mimeTypeValue, out channel, out sampleRate, out bit, out bitRate);
-
- mimeType = (MediaFormatAudioMimeType)mimeTypeValue;
-
- MultimediaDebug.AssertNoError(ret);
-
- Debug.Assert(Enum.IsDefined(typeof(MediaFormatAudioMimeType), mimeType),
- "Invalid audio mime type!");
- }
-
- /// <summary>
- /// Retrieves aac type value from a native handle.
- /// </summary>
- /// <param name="handle">A native handle that properties are retrieved from.</param>
- /// <param name="aacType">An out parameter for aac type.</param>
- private static void GetAacType(IntPtr handle, out MediaFormatAacType aacType)
- {
- Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!");
-
- int aacTypeValue = 0;
-
- int ret = Interop.MediaFormat.GetAudioAacType(handle, out aacTypeValue);
-
- MultimediaDebug.AssertNoError(ret);
-
- aacType = (MediaFormatAacType)aacTypeValue;
-
- Debug.Assert(Enum.IsDefined(typeof(MediaFormatAacType), aacType), "Invalid aac type!");
- }
-
- internal override void AsNativeHandle(IntPtr handle)
- {
- Debug.Assert(Type == MediaFormatType.Audio);
-
- int ret = Interop.MediaFormat.SetAudioMimeType(handle, (int)MimeType);
- MultimediaDebug.AssertNoError(ret);
-
- ret = Interop.MediaFormat.SetAudioChannel(handle, Channel);
- MultimediaDebug.AssertNoError(ret);
-
- ret = Interop.MediaFormat.SetAudioSampleRate(handle, SampleRate);
- MultimediaDebug.AssertNoError(ret);
-
- ret = Interop.MediaFormat.SetAudioBit(handle, Bit);
- MultimediaDebug.AssertNoError(ret);
-
- ret = Interop.MediaFormat.SetAudioAverageBps(handle, BitRate);
- MultimediaDebug.AssertNoError(ret);
-
- ret = Interop.MediaFormat.SetAudioAacType(handle, (int)AacType);
- MultimediaDebug.AssertNoError(ret);
- }
-
- /// <summary>
- /// Gets the mime type of the current format.
- /// </summary>
- public MediaFormatAudioMimeType MimeType { get; }
-
- /// <summary>
- /// Gets the channel value of the current format.
- /// </summary>
- public int Channel { get; }
-
- /// <summary>
- /// Gets the sample rate value of the current format.
- /// </summary>
- public int SampleRate { get; }
-
- /// <summary>
- /// Gets the bit value of the current format.
- /// </summary>
- public int Bit { get; }
-
- /// <summary>
- /// Gets the bit rate value of the current format.
- /// </summary>
- public int BitRate { get; }
-
- /// <summary>
- /// Gets the aac type of the current format.
- /// </summary>
- public MediaFormatAacType AacType { get; }
-
- public override string ToString()
- {
- return $@"MimeTyp={ MimeType.ToString() }, Channel={ Channel.ToString() }, SampleRate=
- { SampleRate }, Bit={ Bit.ToString() }, BitRate={ BitRate.ToString() }, AacType={ AacType.ToString() }";
- }
-
- public override bool Equals(object obj)
- {
- var rhs = obj as AudioMediaFormat;
- if (rhs == null)
- {
- return false;
- }
-
- return MimeType == rhs.MimeType && Channel == rhs.Channel && SampleRate == rhs.SampleRate &&
- Bit == rhs.Bit && BitRate == rhs.BitRate;
- }
-
- public override int GetHashCode()
- {
- return new { MimeType, Channel, SampleRate, Bit, BitRate }.GetHashCode();
- }
- }
-
- /// <summary>
- /// Represents a text media format. This class cannot be inherited.
- /// </summary>
- public sealed class TextMediaFormat : MediaFormat
- {
- /// <summary>
- /// Initializes a new instance of the TextMediaFormat class with the specified mime type
- /// and text type.
- /// </summary>
- /// <param name="mimeType">The mime type of the format.</param>
- /// <param name="textType">The text type of the format.</param>
- /// <exception cref="ArgumentException">
- /// mimeType or textType is invalid(i.e. undefined value).</exception>
- public TextMediaFormat(MediaFormatTextMimeType mimeType, MediaFormatTextType textType)
- : base(MediaFormatType.Text)
- {
- if (!Enum.IsDefined(typeof(MediaFormatTextMimeType), mimeType))
- {
- throw new ArgumentException($"Invalid mime type value : { (int)mimeType }");
- }
- if (!Enum.IsDefined(typeof(MediaFormatTextType), textType))
- {
- throw new ArgumentException($"Invalid text type value : { (int)textType }");
- }
- MimeType = mimeType;
- TextType = textType;
- }
-
- /// <summary>
- /// Initializes a new instance of the TextMediaFormat class from a native handle.
- /// </summary>
- /// <param name="handle">A native handle.</param>
- internal TextMediaFormat(IntPtr handle)
- : base(MediaFormatType.Text)
- {
- Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!");
-
- MediaFormatTextMimeType mimeType;
- MediaFormatTextType textType;
-
- GetInfo(handle, out mimeType, out textType);
-
- MimeType = mimeType;
- TextType = textType;
- }
-
- /// <summary>
- /// Retrieves text properties of media format from a native handle.
- /// </summary>
- /// <param name="handle">A native handle that properties are retrieved from.</param>
- /// <param name="mimeType">An out parameter for mime type.</param>
- /// <param name="textType">An out parameter for text type.</param>
- private static void GetInfo(IntPtr handle, out MediaFormatTextMimeType mimeType,
- out MediaFormatTextType textType)
- {
- int mimeTypeValue = 0;
- int textTypeValue = 0;
-
- int ret = Interop.MediaFormat.GetTextInfo(handle, out mimeTypeValue, out textTypeValue);
-
- MultimediaDebug.AssertNoError(ret);
-
- mimeType = (MediaFormatTextMimeType)mimeTypeValue;
- textType = (MediaFormatTextType)textTypeValue;
-
- Debug.Assert(Enum.IsDefined(typeof(MediaFormatTextMimeType), mimeType),
- "Invalid text mime type!");
- Debug.Assert(Enum.IsDefined(typeof(MediaFormatTextType), textType),
- "Invalid text type!");
- }
-
- internal override void AsNativeHandle(IntPtr handle)
- {
- Debug.Assert(Type == MediaFormatType.Text);
-
- int ret = Interop.MediaFormat.SetTextMimeType(handle, (int)MimeType);
- MultimediaDebug.AssertNoError(ret);
-
- ret = Interop.MediaFormat.SetTextType(handle, (int)TextType);
- MultimediaDebug.AssertNoError(ret);
- }
-
- /// <summary>
- /// Gets the mime type of the current format.
- /// </summary>
- public MediaFormatTextMimeType MimeType { get; }
-
- /// <summary>
- /// Gets the text type of the current format.
- /// </summary>
- public MediaFormatTextType TextType { get; }
-
- public override string ToString()
- {
- return $"MimeType={ MimeType.ToString() }, TextType={ TextType.ToString() }";
- }
-
- public override bool Equals(object obj)
- {
- var rhs = obj as TextMediaFormat;
- if (rhs == null)
- {
- return false;
- }
-
- return MimeType == rhs.MimeType && TextType == rhs.TextType;
- }
-
- public override int GetHashCode()
- {
- return new { MimeType, TextType }.GetHashCode();
- }
- }
}
--- /dev/null
+/*
+ * 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.Diagnostics;
+using System.Runtime.InteropServices;
+using System.Threading;
+using Tizen.Internals.Errors;
+
+namespace Tizen.Multimedia
+{
+ /// <summary>
+ /// Represents a packet for multimedia.
+ /// </summary>
+ public abstract partial class MediaPacket : IDisposable
+ {
+ private readonly LockState _lock = new LockState();
+
+ /// <summary>
+ /// Validate the current object is not locked.
+ /// </summary>
+ /// <exception cref="ObjectDisposedException">The MediaPacket has already been disposed of.</exception>
+ /// <exception cref="InvalidOperationException">The MediaPacket is in use by another module.</exception>
+ private void ValidateNotLocked()
+ {
+ ValidateNotDisposed();
+
+ if (_lock.IsLocked)
+ {
+ throw new InvalidOperationException("Can't perform any writing operation." +
+ "The packet is in use, internally.");
+ }
+ }
+
+ /// <summary>
+ /// Provides a thread-safe lock state controller.
+ /// </summary>
+ private sealed class LockState
+ {
+ const int LOCKED = 1;
+ const int UNLOCKED = 0;
+
+ private int _locked = UNLOCKED;
+
+ internal void SetLock()
+ {
+ if (Interlocked.CompareExchange(ref _locked, LOCKED, UNLOCKED) == LOCKED)
+ {
+ throw new InvalidOperationException("The packet is already locked.");
+ }
+ }
+
+ internal void SetUnlock()
+ {
+ if (Interlocked.CompareExchange(ref _locked, UNLOCKED, LOCKED) == UNLOCKED)
+ {
+ Debug.Fail("The packet to unlock is not locked. " +
+ "There must be an error somewhere that a lock isn't disposed correctly.");
+ }
+ }
+
+ internal bool IsLocked
+ {
+ get
+ {
+ return Interlocked.CompareExchange(ref _locked, 0, 0) == LOCKED;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Provides a thread-safe lock controller.
+ /// </summary>
+ /// <example>
+ /// using (var lock = BaseMediaPacket.Lock(mediaPacket))
+ /// {
+ /// ....
+ /// }
+ /// </example>
+ internal sealed class Lock : IDisposable
+ {
+ private readonly MediaPacket _packet;
+ private readonly GCHandle _gcHandle;
+ private int _lockCount;
+
+ internal static Lock Get(MediaPacket packet)
+ {
+ Debug.Assert(packet != null);
+
+ lock (packet)
+ {
+ Lock lck = FromHandle(packet._handle);
+
+ if (lck == null)
+ {
+ lck = new Lock(packet);
+ }
+
+ lck._lockCount++;
+
+ return lck;
+ }
+ }
+
+ private Lock(MediaPacket packet)
+ {
+ Debug.Assert(packet != null, "The packet is null!");
+
+ packet.ValidateNotDisposed();
+
+ _packet = packet;
+
+ _packet._lock.SetLock();
+
+ _gcHandle = GCHandle.Alloc(this);
+
+ SetExtra(GCHandle.ToIntPtr(_gcHandle));
+ }
+
+ internal static Lock FromHandle(IntPtr handle)
+ {
+ Debug.Assert(handle != IntPtr.Zero);
+
+ IntPtr extra = GetExtra(handle);
+
+ if (extra == IntPtr.Zero)
+ {
+ return null;
+ }
+
+ return (Lock)GCHandle.FromIntPtr(extra).Target;
+ }
+
+ private void SetExtra(IntPtr ptr)
+ {
+ int ret = Interop.MediaPacket.SetExtra(_packet._handle, ptr);
+
+ MultimediaDebug.AssertNoError(ret);
+ }
+
+ private static IntPtr GetExtra(IntPtr handle)
+ {
+ IntPtr value;
+
+ int ret = Interop.MediaPacket.GetExtra(handle, out value);
+
+ MultimediaDebug.AssertNoError(ret);
+
+ return value;
+ }
+
+ internal IntPtr GetHandle()
+ {
+ return _packet.GetHandle();
+ }
+
+ internal MediaPacket MediaPacket
+ {
+ get
+ {
+ return _packet;
+ }
+ }
+
+ private bool _isDisposed = false;
+
+ public void Dispose()
+ {
+ if (!_isDisposed)
+ {
+ lock (_packet)
+ {
+ _lockCount--;
+
+ if (_lockCount == 0)
+ {
+ SetExtra(IntPtr.Zero);
+
+ if (_gcHandle.IsAllocated)
+ {
+ _gcHandle.Free();
+ }
+
+ //We can assure that at this point '_packet' is always locked by this lock.
+ _packet._lock.SetUnlock();
+ }
+ }
+
+ _isDisposed = true;
+ }
+ }
+ }
+ }
+}
/// <summary>
/// Represents a packet for multimedia.
/// </summary>
- public abstract class MediaPacket : IDisposable
+ public abstract partial class MediaPacket : IDisposable
{
private IntPtr _handle = IntPtr.Zero;
}
/// <summary>
- /// Validate the current object is not locked.
- /// </summary>
- /// <exception cref="ObjectDisposedException">The MediaPacket has already been disposed of.</exception>
- /// <exception cref="InvalidOperationException">The MediaPacket is in use by another module.</exception>
- private void ValidateNotLocked()
- {
- ValidateNotDisposed();
-
- if (_lock.IsLocked)
- {
- throw new InvalidOperationException("Can't perform any writing operation." +
- "The packet is in use, internally.");
- }
- }
- /// <summary>
/// Ensures whether the packet is writable.
/// </summary>
/// <exception cref="ObjectDisposedException">The MediaPacket already has been disposed of.</exception>
return new MediaPacketBuffer(this, dataHandle, size);
}
- #region Lock operations
- private readonly LockState _lock = new LockState();
-
- /// <summary>
- /// Provides a thread-safe lock state controller.
- /// </summary>
- private sealed class LockState
- {
- const int LOCKED = 1;
- const int UNLOCKED = 0;
-
- private int _locked = UNLOCKED;
-
- internal void SetLock()
- {
- if (Interlocked.CompareExchange(ref _locked, LOCKED, UNLOCKED) == LOCKED)
- {
- throw new InvalidOperationException("The packet is already locked.");
- }
- }
-
- internal void SetUnlock()
- {
- if (Interlocked.CompareExchange(ref _locked, UNLOCKED, LOCKED) == UNLOCKED)
- {
- Debug.Fail("The packet to unlock is not locked. " +
- "There must be an error somewhere that a lock isn't disposed correctly.");
- }
- }
-
- internal bool IsLocked
- {
- get
- {
- return Interlocked.CompareExchange(ref _locked, 0, 0) == LOCKED;
- }
- }
- }
-
- /// <summary>
- /// Provides a thread-safe lock controller.
- /// </summary>
- /// <example>
- /// using (var lock = BaseMediaPacket.Lock(mediaPacket))
- /// {
- /// ....
- /// }
- /// </example>
- internal sealed class Lock : IDisposable
- {
- private readonly MediaPacket _packet;
- private readonly GCHandle _gcHandle;
- private int _lockCount;
-
- internal static Lock Get(MediaPacket packet)
- {
- Debug.Assert(packet != null);
-
- lock (packet)
- {
- Lock lck = FromHandle(packet._handle);
-
- if (lck == null)
- {
- lck = new Lock(packet);
- }
-
- lck._lockCount++;
-
- return lck;
- }
- }
-
- private Lock(MediaPacket packet)
- {
- Debug.Assert(packet != null, "The packet is null!");
-
- packet.ValidateNotDisposed();
-
- _packet = packet;
-
- _packet._lock.SetLock();
-
- _gcHandle = GCHandle.Alloc(this);
-
- SetExtra(GCHandle.ToIntPtr(_gcHandle));
- }
-
- internal static Lock FromHandle(IntPtr handle)
- {
- Debug.Assert(handle != IntPtr.Zero);
-
- IntPtr extra = GetExtra(handle);
-
- if (extra == IntPtr.Zero)
- {
- return null;
- }
-
- return (Lock)GCHandle.FromIntPtr(extra).Target;
- }
-
- private void SetExtra(IntPtr ptr)
- {
- int ret = Interop.MediaPacket.SetExtra(_packet._handle, ptr);
-
- MultimediaDebug.AssertNoError(ret);
- }
-
- private static IntPtr GetExtra(IntPtr handle)
- {
- IntPtr value;
-
- int ret = Interop.MediaPacket.GetExtra(handle, out value);
-
- MultimediaDebug.AssertNoError(ret);
-
- return value;
- }
-
- internal IntPtr GetHandle()
- {
- return _packet.GetHandle();
- }
-
- internal MediaPacket MediaPacket
- {
- get
- {
- return _packet;
- }
- }
-
- private bool _isDisposed = false;
-
- public void Dispose()
- {
- if (!_isDisposed)
- {
- lock (_packet)
- {
- _lockCount--;
-
- if (_lockCount == 0)
- {
- SetExtra(IntPtr.Zero);
-
- if (_gcHandle.IsAllocated)
- {
- _gcHandle.Free();
- }
-
- //We can assure that at this point '_packet' is always locked by this lock.
- _packet._lock.SetUnlock();
- }
- }
-
- _isDisposed = true;
- }
- }
- }
- #endregion
-
/// <summary>
/// Creates an object of the MediaPacket with the specified <see cref="MediaFormat"/>.
/// </summary>
--- /dev/null
+/*
+ * 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.Diagnostics;
+using Tizen.Internals.Errors;
+
+namespace Tizen.Multimedia
+{
+ /// <summary>
+ /// Represents a text media format. This class cannot be inherited.
+ /// </summary>
+ public sealed class TextMediaFormat : MediaFormat
+ {
+ /// <summary>
+ /// Initializes a new instance of the TextMediaFormat class with the specified mime type
+ /// and text type.
+ /// </summary>
+ /// <param name="mimeType">The mime type of the format.</param>
+ /// <param name="textType">The text type of the format.</param>
+ /// <exception cref="ArgumentException">
+ /// mimeType or textType is invalid(i.e. undefined value).</exception>
+ public TextMediaFormat(MediaFormatTextMimeType mimeType, MediaFormatTextType textType)
+ : base(MediaFormatType.Text)
+ {
+ if (!Enum.IsDefined(typeof(MediaFormatTextMimeType), mimeType))
+ {
+ throw new ArgumentException($"Invalid mime type value : { (int)mimeType }");
+ }
+ if (!Enum.IsDefined(typeof(MediaFormatTextType), textType))
+ {
+ throw new ArgumentException($"Invalid text type value : { (int)textType }");
+ }
+ MimeType = mimeType;
+ TextType = textType;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the TextMediaFormat class from a native handle.
+ /// </summary>
+ /// <param name="handle">A native handle.</param>
+ internal TextMediaFormat(IntPtr handle)
+ : base(MediaFormatType.Text)
+ {
+ Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!");
+
+ MediaFormatTextMimeType mimeType;
+ MediaFormatTextType textType;
+
+ GetInfo(handle, out mimeType, out textType);
+
+ MimeType = mimeType;
+ TextType = textType;
+ }
+
+ /// <summary>
+ /// Retrieves text properties of media format from a native handle.
+ /// </summary>
+ /// <param name="handle">A native handle that properties are retrieved from.</param>
+ /// <param name="mimeType">An out parameter for mime type.</param>
+ /// <param name="textType">An out parameter for text type.</param>
+ private static void GetInfo(IntPtr handle, out MediaFormatTextMimeType mimeType,
+ out MediaFormatTextType textType)
+ {
+ int mimeTypeValue = 0;
+ int textTypeValue = 0;
+
+ int ret = Interop.MediaFormat.GetTextInfo(handle, out mimeTypeValue, out textTypeValue);
+
+ MultimediaDebug.AssertNoError(ret);
+
+ mimeType = (MediaFormatTextMimeType)mimeTypeValue;
+ textType = (MediaFormatTextType)textTypeValue;
+
+ Debug.Assert(Enum.IsDefined(typeof(MediaFormatTextMimeType), mimeType),
+ "Invalid text mime type!");
+ Debug.Assert(Enum.IsDefined(typeof(MediaFormatTextType), textType),
+ "Invalid text type!");
+ }
+
+ internal override void AsNativeHandle(IntPtr handle)
+ {
+ Debug.Assert(Type == MediaFormatType.Text);
+
+ int ret = Interop.MediaFormat.SetTextMimeType(handle, (int)MimeType);
+ MultimediaDebug.AssertNoError(ret);
+
+ ret = Interop.MediaFormat.SetTextType(handle, (int)TextType);
+ MultimediaDebug.AssertNoError(ret);
+ }
+
+ /// <summary>
+ /// Gets the mime type of the current format.
+ /// </summary>
+ public MediaFormatTextMimeType MimeType { get; }
+
+ /// <summary>
+ /// Gets the text type of the current format.
+ /// </summary>
+ public MediaFormatTextType TextType { get; }
+
+ public override string ToString()
+ {
+ return $"MimeType={ MimeType.ToString() }, TextType={ TextType.ToString() }";
+ }
+
+ public override bool Equals(object obj)
+ {
+ var rhs = obj as TextMediaFormat;
+ if (rhs == null)
+ {
+ return false;
+ }
+
+ return MimeType == rhs.MimeType && TextType == rhs.TextType;
+ }
+
+ public override int GetHashCode()
+ {
+ return new { MimeType, TextType }.GetHashCode();
+ }
+ }
+}
--- /dev/null
+/*
+ * 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.Diagnostics;
+using Tizen.Internals.Errors;
+
+namespace Tizen.Multimedia
+{
+ /// <summary>
+ /// Represents a video media format. This class cannot be inherited.
+ /// </summary>
+ public sealed class VideoMediaFormat : MediaFormat
+ {
+ private const int DefaultFrameRate = 0;
+ private const int DefaultBitRate = 0;
+
+ /// <summary>
+ /// Initializes a new instance of the VideoMediaFormat class with the specified mime type, width and height.
+ /// </summary>
+ /// <param name="mimeType">The mime type of the format.</param>
+ /// <param name="width">The width value of the format.</param>
+ /// <param name="height">The height value of the format</param>
+ /// <exception cref="ArgumentException">mimeType is invalid(i.e. undefined value).</exception>
+ /// <exception cref="ArgumentOutOfRangeException">width, or height is less than zero.</exception>
+ public VideoMediaFormat(MediaFormatVideoMimeType mimeType, int width, int height)
+ : this(mimeType, width, height, DefaultFrameRate)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the VideoMediaFormat class with the specified mime type and size.
+ /// </summary>
+ /// <param name="mimeType">The mime type of the format.</param>
+ /// <param name="size">The size of the format.</param>
+ /// <exception cref="ArgumentException">mimeType is invalid(i.e. undefined value).</exception>
+ /// <exception cref="ArgumentOutOfRangeException">width, or height is less than zero.</exception>
+ public VideoMediaFormat(MediaFormatVideoMimeType mimeType, Size size)
+ : this(mimeType, size, DefaultFrameRate)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the VideoMediaFormat class with the specified mime type,
+ /// width, height and frame rate.
+ /// </summary>
+ /// <param name="mimeType">The mime type of the format.</param>
+ /// <param name="width">The width value of the format.</param>
+ /// <param name="height">The height value of the format</param>
+ /// <param name="frameRate">The frame rate of the format.</param>
+ /// <exception cref="ArgumentException">mimeType is invalid(i.e. undefined value).</exception>
+ /// <exception cref="ArgumentOutOfRangeException">width, height or frameRate is less than zero.</exception>
+ public VideoMediaFormat(MediaFormatVideoMimeType mimeType, int width, int height,
+ int frameRate)
+ : this(mimeType, width, height, frameRate, DefaultBitRate)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the VideoMediaFormat class with the specified mime type,
+ /// width, height and frame rate.
+ /// </summary>
+ /// <param name="mimeType">The mime type of the format.</param>
+ /// <param name="size">The video size of the format.</param>
+ /// <param name="frameRate">The frame rate of the format.</param>
+ /// <exception cref="ArgumentException">mimeType is invalid(i.e. undefined value).</exception>
+ /// <exception cref="ArgumentOutOfRangeException">width, height or frameRate is less than zero.</exception>
+ public VideoMediaFormat(MediaFormatVideoMimeType mimeType, Size size,
+ int frameRate)
+ : this(mimeType, size, frameRate, DefaultBitRate)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the VideoMediaFormat class with the specified mime type,
+ /// width, height, frame rate and bit rate.
+ /// </summary>
+ /// <param name="mimeType">The mime type of the format.</param>
+ /// <param name="width">The width value of the format.</param>
+ /// <param name="height">The height value of the format</param>
+ /// <param name="frameRate">The frame rate of the format.</param>
+ /// <param name="bitRate">The bit rate of the format.</param>
+ /// <exception cref="ArgumentException">mimeType is invalid(i.e. undefined value).</exception>
+ /// <exception cref="ArgumentOutOfRangeException">width, height, frameRate or bitRate is less than zero.</exception>
+ public VideoMediaFormat(MediaFormatVideoMimeType mimeType, int width, int height,
+ int frameRate, int bitRate)
+ : this(mimeType, new Size(width, height), frameRate, bitRate)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the VideoMediaFormat class with the specified mime type,
+ /// size, frame rate and bit rate.
+ /// </summary>
+ /// <param name="mimeType">The mime type of the format.</param>
+ /// <param name="size">The size of the format.</param>
+ /// <param name="frameRate">The frame rate of the format.</param>
+ /// <param name="bitRate">The bit rate of the format.</param>
+ /// <exception cref="ArgumentException">mimeType is invalid(i.e. undefined value).</exception>
+ /// <exception cref="ArgumentOutOfRangeException">width, height, frameRate or bitRate is less than zero.</exception>
+ public VideoMediaFormat(MediaFormatVideoMimeType mimeType, Size size,
+ int frameRate, int bitRate)
+ : base(MediaFormatType.Video)
+ {
+ if (!Enum.IsDefined(typeof(MediaFormatVideoMimeType), mimeType))
+ {
+ throw new ArgumentException($"Invalid mime type value : { (int)mimeType }");
+ }
+ if (size.Width < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(size), size.Width, "Size.Width value can't be less than zero.");
+ }
+ if (size.Height < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(size), size.Height, "Size.Height value can't be less than zero.");
+ }
+ if (frameRate < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(frameRate), frameRate, "Frame rate can't be less than zero.");
+ }
+ if (bitRate < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(bitRate), bitRate, "Bit rate value can't be less than zero.");
+ }
+
+ MimeType = mimeType;
+ Size = size;
+ FrameRate = frameRate;
+ BitRate = bitRate;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the VideoMediaForma class from a native handle.
+ /// </summary>
+ /// <param name="handle">A native handle.</param>
+ internal VideoMediaFormat(IntPtr handle)
+ : base(MediaFormatType.Video)
+ {
+ Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!");
+
+ int width = 0;
+ int height = 0;
+ int bitRate = 0;
+ int frameRate = 0;
+ MediaFormatVideoMimeType mimeType;
+ GetInfo(handle, out width, out height, out bitRate, out mimeType);
+
+ GetFrameRate(handle, out frameRate);
+
+ MimeType = mimeType;
+ Size = new Size(width, height);
+ FrameRate = frameRate;
+ BitRate = bitRate;
+ }
+
+ /// <summary>
+ /// Retrieves video properties of media format from a native handle.
+ /// </summary>
+ /// <param name="handle">A native handle that properties are retrieved from.</param>
+ /// <param name="width">An out parameter for width.</param>
+ /// <param name="height">An out parameter for height.</param>
+ /// <param name="bitRate">An out parameter for bit rate.</param>
+ /// <param name="mimeType">An out parameter for mime type.</param>
+ private static void GetInfo(IntPtr handle, out int width, out int height, out int bitRate,
+ out MediaFormatVideoMimeType mimeType)
+ {
+ Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!");
+
+ int mimeTypeValue = 0;
+ int maxBps = 0;
+
+ int ret = Interop.MediaFormat.GetVideoInfo(handle,
+ out mimeTypeValue, out width, out height, out bitRate, out maxBps);
+
+ MultimediaDebug.AssertNoError(ret);
+
+ mimeType = (MediaFormatVideoMimeType)mimeTypeValue;
+
+ Debug.Assert(Enum.IsDefined(typeof(MediaFormatVideoMimeType), mimeType),
+ "Invalid video mime type!");
+ }
+
+ /// <summary>
+ /// Retrieves frame rate from a native handle.
+ /// </summary>
+ /// <param name="handle">A native handle that properties are retrieved from.</param>
+ /// <param name="frameRate">An out parameter for frame rate.</param>
+ private static void GetFrameRate(IntPtr handle, out int frameRate)
+ {
+ Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!");
+
+ int ret = Interop.MediaFormat.GetVideoFrameRate(handle, out frameRate);
+
+ MultimediaDebug.AssertNoError(ret);
+ }
+
+ internal override void AsNativeHandle(IntPtr handle)
+ {
+ Debug.Assert(Type == MediaFormatType.Video);
+
+ int ret = Interop.MediaFormat.SetVideoMimeType(handle, (int)MimeType);
+ MultimediaDebug.AssertNoError(ret);
+
+ ret = Interop.MediaFormat.SetVideoWidth(handle, Size.Width);
+ MultimediaDebug.AssertNoError(ret);
+
+ ret = Interop.MediaFormat.SetVideoHeight(handle, Size.Height);
+ MultimediaDebug.AssertNoError(ret);
+
+ ret = Interop.MediaFormat.SetVideoAverageBps(handle, BitRate);
+ MultimediaDebug.AssertNoError(ret);
+
+ ret = Interop.MediaFormat.SetVideoFrameRate(handle, FrameRate);
+ MultimediaDebug.AssertNoError(ret);
+ }
+
+ /// <summary>
+ /// Gets the mime type of the current format.
+ /// </summary>
+ public MediaFormatVideoMimeType MimeType { get; }
+
+ /// <summary>
+ /// Gets the size of the current format.
+ /// </summary>
+ public Size Size { get; }
+
+ /// <summary>
+ /// Gets the frame rate value of the current format.
+ /// </summary>
+ public int FrameRate { get; }
+
+ /// <summary>
+ /// Gets the bit rate value of the current format.
+ /// </summary>
+ public int BitRate { get; }
+
+ public override string ToString()
+ {
+ return $@"MimeType={ MimeType.ToString() }, Size=({ Size.ToString() }), FrameRate=
+ { FrameRate.ToString() }, BitRate={ BitRate.ToString() }";
+ }
+
+ public override bool Equals(object obj)
+ {
+ var rhs = obj as VideoMediaFormat;
+ if (rhs == null)
+ {
+ return false;
+ }
+
+ return MimeType == rhs.MimeType && Size == rhs.Size &&
+ FrameRate == rhs.FrameRate && BitRate == rhs.BitRate;
+ }
+
+ public override int GetHashCode()
+ {
+ return new { MimeType, Size, FrameRate, BitRate }.GetHashCode();
+ }
+ }
+}
+/*
+ * 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 ElmSharp;