From: WonYoung Choi Date: Tue, 15 Nov 2016 00:19:04 +0000 (+0900) Subject: Rebase Tizen.Multimedia to public X-Git-Tag: submit/trunk/20170823.075128~94^2~170 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=fec9a97aa203bbbea4871add578a12751598735a;p=platform%2Fcore%2Fcsapi%2Ftizenfx.git Rebase Tizen.Multimedia to public Fix .nuspec file to change authors and version dependencies MediaVision - Fixed review comments from previous commit Fixed the block issues of Surveillance EventHandler Modify several MediaController Class Name because Class name was conflicted with 'Tizen.Multimedia'. Fixed spec Fix crash Tizen.Multimedia.dll by double free when event handler is registered [Tizen.Multimedia.ScreenMirroring] Three classes modified : enums, error factory and Interop.Libraries [MediaController] Fix MediaController abnormal behavior Change elmsharp version to 1.1.0 on project.json Modify project & json to fix build error Add build requirement for media-controller (BuildRequires: csapi-application-nuget) Refactor AudioIO classes Refactor Player classes Fix ambiguous names and remove useless types Fixed EngineConfiguration bugs Sync csproj Fix .csproject to remove unused fils Change-Id: I6a8e75a037c95122e1ca48a95a9a4d34cab3a07c Signed-off-by: Jiyong Min --- diff --git a/packaging/csapi-multimedia.spec b/packaging/csapi-multimedia.spec index 9dfbd07..a712802 100644 --- a/packaging/csapi-multimedia.spec +++ b/packaging/csapi-multimedia.spec @@ -8,7 +8,7 @@ Name: csapi-multimedia Summary: Tizen Multimedia API for C# -Version: 1.0.14 +Version: 1.0.19 Release: 0 Group: Development/Libraries License: Apache-2.0 @@ -25,6 +25,7 @@ BuildRequires: dotnet-build-tools # C# API Requries BuildRequires: csapi-tizen-nuget +BuildRequires: csapi-application-nuget BuildRequires: elm-sharp-nuget %description diff --git a/src/Tizen.Multimedia/AudioIO/AudioCapture.cs b/src/Tizen.Multimedia/AudioIO/AudioCapture.cs new file mode 100644 index 0000000..f4128a7 --- /dev/null +++ b/src/Tizen.Multimedia/AudioIO/AudioCapture.cs @@ -0,0 +1,412 @@ +/* +* 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 +{ + /// + /// Provides the ability to directly manage the system audio input devices. + /// + /// The recorder privilege(http://tizen.org/privilege/recorder) is required. + public abstract class AudioCaptureBase : IDisposable + { + public const int MinSampleRate = 8000; + public const int MaxSampleRate = 48000; + + internal IntPtr _handle = IntPtr.Zero; + + private AudioIOState _state = AudioIOState.Idle; + + internal AudioCaptureBase(int sampleRate, AudioChannel channel, AudioSampleType sampleType) + { + if (sampleRate < MinSampleRate || MaxSampleRate < sampleRate) + { + throw new ArgumentOutOfRangeException(nameof(sampleRate), sampleRate, + $"Valid sampleRate range is { MinSampleRate } <= x <= { MaxSampleRate }."); + } + + ValidationUtil.ValidateEnum(typeof(AudioChannel), channel); + ValidationUtil.ValidateEnum(typeof(AudioSampleType), sampleType); + + SampleRate = sampleRate; + Channel = channel; + SampleType = sampleType; + + AudioIOUtil.ThrowIfError( + Interop.AudioIO.AudioInput.Create(SampleRate, (int)Channel, (int)SampleType, out _handle)); + + RegisterStateChangedCallback(); + } + + ~AudioCaptureBase() + { + Dispose(false); + } + + /// + /// Occurs when the state of the AudioCapture is changed. + /// + public event EventHandler StateChanged; + + private Interop.AudioIO.AudioStateChangedCallback _stateChangedCallback; + + private void RegisterStateChangedCallback() + { + _stateChangedCallback = (IntPtr handle, int previous, int current, bool byPolicy, IntPtr _) => + { + _state = (AudioIOState)current; + + StateChanged?.Invoke(this, + new AudioIOStateChangedEventArgs((AudioIOState)previous, _state, byPolicy)); + }; + + AudioIOUtil.ThrowIfError( + Interop.AudioIO.AudioInput.SetStateChangedCallback(_handle, _stateChangedCallback, IntPtr.Zero)); + } + + #region Dispose support + private bool _isDisposed = false; + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (_isDisposed) + { + return; + } + + if (_handle != IntPtr.Zero) + { + if (_state != AudioIOState.Idle) + { + try + { + Unprepare(); + } + catch (Exception) + { + } + } + + Interop.AudioIO.AudioInput.Destroy(_handle); + _handle = IntPtr.Zero; + _isDisposed = true; + } + } + + internal void ValidateNotDisposed() + { + if (_isDisposed) + { + throw new ObjectDisposedException(GetType().Name); + } + } + #endregion + + internal void ValidateState(params AudioIOState[] desiredStates) + { + ValidateNotDisposed(); + + AudioIOUtil.ValidateState(_state, desiredStates); + } + + /// + /// Gets the sample rate of the audio input data stream. + /// + public int SampleRate { get; } + + /// + /// Gets the channel type of the audio input data stream. + /// + public AudioChannel Channel { get; } + + /// + /// Gets the sample type of the audio input data stream. + /// + public AudioSampleType SampleType { get; } + + /// + /// Gets the size to be allocated for the audio input buffer. + /// + /// The AudioPlayback has already been disposed. + /// The current state is . + public int GetBufferSize() + { + ValidateState(AudioIOState.Running, AudioIOState.Paused); + + int size; + AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioInput.GetBufferSize(_handle, out size)); + return size; + } + + /// + /// Prepares the AudioCapture for reading audio data by starting buffering of audio data from the device. + /// + /// + /// Operation failed due to internal error. + /// -or- + /// The current state is not . + /// + /// + public void Prepare() + { + ValidateState(AudioIOState.Idle); + + AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioInput.Prepare(_handle), + "Failed to prepare the AudioCapture"); + } + + /// + /// Unprepares the AudioCapture. + /// + /// + /// Operation failed due to internal error. + /// -or- + /// The current state is . + /// + /// + public void Unprepare() + { + ValidateState(AudioIOState.Running, AudioIOState.Paused); + + AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioInput.Unprepare(_handle), + "Failed to unprepare the AudioCapture"); + } + + /// + /// Pauses buffering of audio data from the device. + /// + /// + /// The current state is . + /// -or- + /// The method is called in the event handler. + /// + /// + public void Pause() + { + if (_state == AudioIOState.Paused) + { + return; + } + ValidateState(AudioIOState.Running); + + int ret = Interop.AudioIO.AudioInput.Pause(_handle); + + // Here, we convert the not supported error into InvalidOperationException. + // It is because this exception is more appropriate in C# for this kind of situation. + if ((int)AudioIOError.NotSupported == ret) + { + throw new InvalidOperationException("Cannot change the state in event handlers."); + } + + MultimediaDebug.AssertNoError(ret); + } + /// + /// Resumes buffering audio data from the device. + /// + /// + /// The current state is . + /// -or- + /// The method is called in the event handler. + /// + /// + public void Resume() + { + if (_state == AudioIOState.Running) + { + return; + } + ValidateState(AudioIOState.Paused); + + int ret = Interop.AudioIO.AudioInput.Resume(_handle); + + // Here, we convert the not supported error into InvalidOperationException. + // It is because this exception is more appropriate in C# for this kind of situation. + if ((int)AudioIOError.NotSupported == ret) + { + throw new InvalidOperationException("Cannot change the state in event handlers."); + } + + MultimediaDebug.AssertNoError(ret); + } + /// + /// Flushes and discards buffered audio data from the input stream. + /// + /// The current state is . + public void Flush() + { + ValidateState(AudioIOState.Running, AudioIOState.Paused); + + int ret = Interop.AudioIO.AudioInput.Flush(_handle); + + MultimediaDebug.AssertNoError(ret); + } + + /// + /// Sets the sound stream information to the audio input. + /// + /// The to apply for the AudioCapture. + /// is null. + /// has already been disposed. + /// is not supported. + /// Not able to retrieve information from . + public void ApplyStreamPolicy(AudioStreamPolicy streamPolicy) + { + if (streamPolicy == null) + { + 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)); + } + } + + /// + /// Provides the ability to record audio from system audio input devices in synchronous way. + /// + /// The recorder privilege(http://tizen.org/privilege/recorder) is required. + public class AudioCapture : AudioCaptureBase + { + /// + /// Initializes a new instance of the AudioCapture class with the specified sample rate, channel and sampleType. + /// + /// The audio sample rate.(8000 ~ 48000Hz) + /// The audio channel type. + /// The audio sample type. + /// + /// is less than . + /// -or- + /// is greater than . + /// + /// + /// The value of is invalid. + /// -or- + /// The value of is invalid. + /// + /// The required privilege is not specified. + /// The system does not support microphone. + public AudioCapture(int sampleRate, AudioChannel channel, AudioSampleType sampleType) + : base(sampleRate, channel, sampleType) + { + } + + /// + /// Reads audio data from the audio input buffer. + /// + /// + /// The buffer of audio data receiving an input + /// The current state is not . + /// is equal to or less than zero. + public byte[] Read(int length) + { + if (length <= 0) + { + throw new ArgumentOutOfRangeException(nameof(length), length, + $"{ nameof(length) } can't be equal to or less than zero."); + } + ValidateState(AudioIOState.Running); + + byte[] buffer = new byte[length]; + + AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioInput.Read(_handle, buffer, length), + "Failed to read"); + + return buffer; + } + } + + /// + /// Provides the ability to record audio from system audio input devices in asynchronous way. + /// + /// The recorder privilege(http://tizen.org/privilege/recorder) is required. + public class AsyncAudioCapture : AudioCaptureBase + { + + /// + /// Occurs when audio data is available. + /// + public event EventHandler DataAvailable; + + /// + /// Initializes a new instance of the AsyncAudioCapture class with the specified sample rate, channel and sampleType. + /// + /// The audio sample rate.(8000 ~ 48000Hz) + /// The audio channel type. + /// The audio sample type. + /// + /// is less than . + /// -or- + /// is greater than . + /// + /// + /// The value of is invalid. + /// -or- + /// The value of is invalid. + /// + /// The required privilege is not specified. + /// The system does not support microphone. + public AsyncAudioCapture(int sampleRate, AudioChannel channel, AudioSampleType sampleType) + : base(sampleRate, channel, sampleType) + { + _streamCallback = (IntPtr handle, uint length, IntPtr _) => { OnInputDataAvailable(handle, length); }; + + AudioIOUtil.ThrowIfError( + Interop.AudioIO.AudioInput.SetStreamCallback(_handle, _streamCallback, IntPtr.Zero), + $"Failed to initialize a { nameof(AsyncAudioCapture) }"); + } + + private Interop.AudioIO.AudioStreamCallback _streamCallback; + + private void OnInputDataAvailable(IntPtr handle, uint length) + { + if (length == 0U) + { + return; + } + + IntPtr ptr = IntPtr.Zero; + try + { + AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioInput.Peek(_handle, out ptr, ref length)); + + byte[] buffer = new byte[length]; + Marshal.Copy(ptr, buffer, 0, (int)length); + + Interop.AudioIO.AudioInput.Drop(_handle); + + DataAvailable?.Invoke(this, new AudioDataAvailableEvetnArgs(buffer)); + } + catch (Exception e) + { + Log.Error(nameof(AsyncAudioCapture), e.Message); + } + } + } +} diff --git a/src/Tizen.Multimedia/AudioIO/AudioDataAvailableEvetnArgs.cs b/src/Tizen.Multimedia/AudioIO/AudioDataAvailableEvetnArgs.cs new file mode 100644 index 0000000..3a03e21 --- /dev/null +++ b/src/Tizen.Multimedia/AudioIO/AudioDataAvailableEvetnArgs.cs @@ -0,0 +1,33 @@ +/* +* 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 +{ + /// + /// Provides data for the event. + /// + public class AudioDataAvailableEvetnArgs : EventArgs + { + internal AudioDataAvailableEvetnArgs(byte[] data) + { + Data = data; + } + + public byte[] Data { get; } + } +} diff --git a/src/Tizen.Multimedia/AudioIO/AudioIOEnumerations.cs b/src/Tizen.Multimedia/AudioIO/AudioIOEnumerations.cs deleted file mode 100755 index 8a29422..0000000 --- a/src/Tizen.Multimedia/AudioIO/AudioIOEnumerations.cs +++ /dev/null @@ -1,50 +0,0 @@ - /* - * 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 Tizen.Internals.Errors; - -namespace Tizen.Multimedia -{ - public enum AudioChannel - { - Mono = 0x80, // 1 channel, mono - Stereo // 2 cahnnel, stereo - }; - - public enum AudioIOError - { - None = ErrorCode.None, // Successful - OutOfMemory = ErrorCode.OutOfMemory, //Out of memory - InvalidParameter = ErrorCode.InvalidParameter, //Invalid parameter - InvalidOperation = ErrorCode.InvalidOperation, //Invalid operation - PermissionDenied = ErrorCode.PermissionDenied, //Device open error by security - NotSupported = ErrorCode.NotSupported, //Not supported - DevicePolicyRestriction = (-2147483648 / 2) + 4, - DeviceNotOpened = -0x01900000 | 0x01, //Device open error - DeviceNotClosed = -0x01900000 | 0x02, //Device close error - InvalidBuffer = -0x01900000 | 0x03, //Invalid buffer pointer - SoundPolicy = -0x01900000 | 0x04, //Sound policy error - InvalidState = -0x01900000 | 0x05, //Invalid state (Since 3.0) - NotSupportedType = -0x01900000 | 0x06, //Not supported stream type (Since 3.0) - }; - - public enum AudioState - { - Idle = 0, /** Audio-io handle is created, but not prepared */ - Running = 1, /** Audio-io handle is ready and the stream is running */ - Paused = 2 /** Audio-io handle is ready and the stream is paused */ - }; -} diff --git a/src/Tizen.Multimedia/AudioIO/AudioIOEnums.cs b/src/Tizen.Multimedia/AudioIO/AudioIOEnums.cs new file mode 100644 index 0000000..ee20b45 --- /dev/null +++ b/src/Tizen.Multimedia/AudioIO/AudioIOEnums.cs @@ -0,0 +1,64 @@ +/* +* 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 Tizen.Internals.Errors; + +namespace Tizen.Multimedia +{ + public enum AudioChannel + { + Mono = 0x80, + Stereo + }; + + internal enum AudioIOError + { + None = ErrorCode.None, + OutOfMemory = ErrorCode.OutOfMemory, + InvalidParameter = ErrorCode.InvalidParameter, + InvalidOperation = ErrorCode.InvalidOperation, + PermissionDenied = ErrorCode.PermissionDenied, //Device open error by security + NotSupported = ErrorCode.NotSupported, //Not supported + DevicePolicyRestriction = (-2147483648 / 2) + 4, + DeviceNotOpened = -0x01900000 | 0x01, + DeviceNotClosed = -0x01900000 | 0x02, + InvalidBuffer = -0x01900000 | 0x03, + SoundPolicy = -0x01900000 | 0x04, + InvalidState = -0x01900000 | 0x05, + NotSupportedType = -0x01900000 | 0x06, + } + + /// + /// Specifies the states for the , and . + /// + public enum AudioIOState + { + /// + /// Not prepared. + /// + Idle = 0, + + /// + /// The stream is running. + /// + Running = 1, + + /// + /// The stream is paused. + /// + Paused = 2 + } +} diff --git a/src/Tizen.Multimedia/AudioIO/AudioIOStateChangedEventArgs.cs b/src/Tizen.Multimedia/AudioIO/AudioIOStateChangedEventArgs.cs new file mode 100644 index 0000000..e9cca42 --- /dev/null +++ b/src/Tizen.Multimedia/AudioIO/AudioIOStateChangedEventArgs.cs @@ -0,0 +1,45 @@ +/* +* 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 +{ + /// + /// Argument for the event that is Audio State Changed. + /// + public class AudioIOStateChangedEventArgs : EventArgs + { + /// + /// Initializes the instance of the AudioStateChangedEventArgs class. + /// + /// + /// + /// + internal AudioIOStateChangedEventArgs(AudioIOState previous, AudioIOState current, bool byPolicy) + { + Previous = previous; + Current = current; + ByPolicy = byPolicy; + } + + public AudioIOState Previous { get; } + + public AudioIOState Current { get; } + + public bool ByPolicy { get; } + } +} diff --git a/src/Tizen.Multimedia/AudioIO/AudioErrorHelper.cs b/src/Tizen.Multimedia/AudioIO/AudioIOUtil.cs old mode 100755 new mode 100644 similarity index 53% rename from src/Tizen.Multimedia/AudioIO/AudioErrorHelper.cs rename to src/Tizen.Multimedia/AudioIO/AudioIOUtil.cs index 078f599..d6a0c76 --- a/src/Tizen.Multimedia/AudioIO/AudioErrorHelper.cs +++ b/src/Tizen.Multimedia/AudioIO/AudioIOUtil.cs @@ -1,81 +1,95 @@ - /* - * 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 class AudioErrorHelper - { - public static void Try(int errorCode) - { - AudioIOError code = (AudioIOError)errorCode; - // 현재는 에러코드 최상위 exception으로 전달, 추후 상황에 맞게 케이스 처리해야 함. - - Log.Info("Audio", "Error code = " + code); - if (code > 0) - { - Log.Info("Audio", "Code > 0, no error!!!!"); - return; - } - - switch (code) - { - case AudioIOError.None: - break; - case AudioIOError.OutOfMemory: - Log.Info("Audio", "OutOfMemoryException"); - throw new OutOfMemoryException(); - case AudioIOError.InvalidParameter: - Log.Info("Audio", "ArgumentException"); - throw new ArgumentException(); - case AudioIOError.InvalidOperation: - Log.Info("Audio", "InvalidOperationException"); - throw new InvalidOperationException(); - case AudioIOError.PermissionDenied: - Log.Info("Audio", "Permission Denied Error"); - throw new Exception("Permission Denied Error"); - case AudioIOError.NotSupported: - Log.Info("Audio", "NotSupportedException"); - throw new NotSupportedException(); - case AudioIOError.DevicePolicyRestriction: - Log.Info("Audio", "Device_policy_restriction"); - throw new Exception("Device_policy_restriction"); - case AudioIOError.DeviceNotOpened: - Log.Info("Audio", "Device Not Opened Error"); - throw new Exception("Device Not Opened Error"); - case AudioIOError.DeviceNotClosed: - Log.Info("Audio", "Device Not Closed Error"); - throw new Exception("Device Not Closed Error"); - case AudioIOError.InvalidBuffer: - Log.Info("Audio", "Invalid Buffer Error"); - throw new InvalidOperationException("Invalid Buffer Error"); - case AudioIOError.SoundPolicy: - Log.Info("Audio", "Sound Policy Error"); - throw new Exception("Sound Policy Error"); - case AudioIOError.InvalidState: - Log.Info("Audio", "Invalid State Error"); - throw new Exception("Invalid State Error"); - case AudioIOError.NotSupportedType: - Log.Info("Audio", "Not supported stream type Error"); - throw new Exception("Not supported stream type Error"); - default: - Log.Info("Audio", "Unknown Exception" + code); - throw new Exception("Unknown Exception"); - } - } - } -} +/* +* 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.Linq; + +namespace Tizen.Multimedia +{ + internal static class AudioIOUtil + { + internal static void ThrowIfError(int errorCode, string msg = null) + { + AudioIOError code = (AudioIOError)errorCode; + // 현재는 에러코드 최상위 exception으로 전달, 추후 상황에 맞게 케이스 처리해야 함. + + msg = (msg == null ? "" : msg + " ") + $": { code }"; + + if (code > 0) + { + Log.Info("Audio", "Code > 0, no error!!!!"); + return; + } + + switch (code) + { + case AudioIOError.None: + break; + case AudioIOError.OutOfMemory: + Log.Info("Audio", "OutOfMemoryException"); + throw new OutOfMemoryException(); + case AudioIOError.InvalidParameter: + Log.Info("Audio", "ArgumentException"); + throw new ArgumentException(msg); + case AudioIOError.InvalidOperation: + throw new InvalidOperationException(msg); + case AudioIOError.PermissionDenied: + Log.Info("Audio", "Permission Denied Error"); + throw new InvalidOperationException(msg); + case AudioIOError.NotSupported: + throw new NotSupportedException(msg); + case AudioIOError.DevicePolicyRestriction: + Log.Info("Audio", "Device_policy_restriction"); + throw new Exception("Device_policy_restriction"); + case AudioIOError.DeviceNotOpened: + Log.Info("Audio", "Device Not Opened Error"); + throw new Exception("Device Not Opened Error"); + case AudioIOError.DeviceNotClosed: + Log.Info("Audio", "Device Not Closed Error"); + throw new Exception("Device Not Closed Error"); + case AudioIOError.InvalidBuffer: + Log.Info("Audio", "Invalid Buffer Error"); + throw new InvalidOperationException(msg); + case AudioIOError.SoundPolicy: + Log.Info("Audio", "Sound Policy Error"); + throw new Exception(msg); + case AudioIOError.InvalidState: + Log.Info("Audio", "Invalid State Error"); + throw new InvalidOperationException(msg); + case AudioIOError.NotSupportedType: + Log.Info("Audio", "Not supported stream type Error"); + throw new NotSupportedException(msg); + default: + Log.Info("Audio", "Unknown Exception" + code); + throw new Exception(msg); + } + } + + internal static void ValidateState(AudioIOState curState, params AudioIOState[] desiredStates) + { + Debug.Assert(desiredStates.Length > 0); + + if (desiredStates.Contains(curState)) + { + return; + } + + throw new InvalidOperationException($"The audio is not in a valid state. " + + $"Current State : { curState }, Valid State : { string.Join(", ", desiredStates) }."); + } + } +} diff --git a/src/Tizen.Multimedia/AudioIO/AudioInput.cs b/src/Tizen.Multimedia/AudioIO/AudioInput.cs deleted file mode 100755 index 4da40b0..0000000 --- a/src/Tizen.Multimedia/AudioIO/AudioInput.cs +++ /dev/null @@ -1,244 +0,0 @@ - /* - * 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 -{ - /// - /// The Audio Input class provides a set of functions to directly manage the system audio input devices. - /// - public class AudioInput : BaseAudio - { - /// - /// Gets the sample rate of the audio input data stream. - /// - public override int SampleRate - { - get - { - int sampleRate; - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.GetSampleRate(_handle, out sampleRate)); - return sampleRate; - } - } - - /// - /// Gets the channel type of the audio input data stream. - /// The audio channel type defines whether the audio is mono or stereo. - /// - public override AudioChannel Channel - { - get - { - int channel; - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.GetChannel(_handle, out channel)); - return (AudioChannel)channel; - } - } - /// - /// Gets the sample audio format (8-bit or 16-bit) of the audio input data stream. - /// - public override AudioSampleType SampleType - { - get - { - int type; - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.GetSampleType(_handle, out type)); - return (AudioSampleType)type; - } - } - - /// - /// Gets the size to be allocated for the audio input buffer. - /// - public override int BufferSize - { - get - { - int size; - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.GetBufferSize(_handle, out size)); - return size; - } - } - /// - /// Reads audio data from the audio input buffer. - /// - /// - /// The buffer of audio data receiving an input - public byte[] Read(int length) - { - byte[] dataArray = new byte[length]; - - if (dataArray.Length <= 0) - throw new IndexOutOfRangeException("Bed Buffer Length"); - - IntPtr ptrByteArray = Marshal.AllocHGlobal(length); - try - { - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.Read(_handle, ptrByteArray, length)); - Marshal.Copy(ptrByteArray, dataArray, 0, dataArray.Length); - } - catch (Exception e) - { - Log.Info("Audio", "Read Exception : " + e.ToString()); - Console.WriteLine("read error" + e.ToString()); - } - finally - { - if (ptrByteArray != IntPtr.Zero) - { - Marshal.FreeHGlobal(ptrByteArray); - ptrByteArray = IntPtr.Zero; - } - } - return dataArray; - } - /// - /// peek from audio in buffer - /// This function works correctly only with read, write callback.Otherwise it won't operate as intended. - /// - /// - /// The allocated buffer - byte[] - public byte[] Peek(uint length) - { - IntPtr ptrByteArray = IntPtr.Zero; - uint nBytes = 0; - try - { - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.Peek(_handle, out ptrByteArray, out nBytes)); - byte[] dataArray = new byte[nBytes]; - Marshal.Copy(ptrByteArray, dataArray, 0, (int)nBytes); - - return dataArray; - } - finally - { - if (ptrByteArray != IntPtr.Zero) - { - ptrByteArray = IntPtr.Zero; - } - } - } - /// - /// drop peeked audio buffer. - /// This function works correctly only with read, write callback.Otherwise it won't operate as intended. - /// - public void Drop() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.Drop(_handle)); - } - /// - /// Releases the audio input handle and all its resources associated with an audio stream. - /// - protected override void Destroy() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.Destroy(_handle)); - } - /// - /// Sets an asynchronous(event) callback function to handle recording PCM (pulse-code modulation) data. - /// - protected override void RegisterAudioStreamLengthChanged() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.SetAudioInputStreamChangedCallback(_handle, OnStream, IntPtr.Zero)); - } - /// - /// Unregisters the callback function. - /// - protected override void UnregisterAudioStreamLengthChanged() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.UnsetAudioInputStreamChangedCallback(_handle)); - } - /// - /// Sets the state changed callback function to the audio input handle. - /// - protected override void RegisterAudioStateChangedCallback() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.SetAudioInputStateChangedCallback(_handle, OnStateChanged, IntPtr.Zero)); - } - /// - /// Unregisters the state changed callback function of the audio input handle. - /// - protected override void UnregisterAudioStateChangedmCallback() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.UnsetAudioInputStateChangedCallback(_handle)); - } - /// - /// Prepares the audio input for reading audio data by starting buffering of audio data from the device. - /// - public override void Prepare() - { - if(_bReady == false) - { - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.Prepare(_handle)); - _bReady = true; - } - } - /// - /// Unprepares the audio input. - /// - public override void Unprepare() - { - if (_bReady) - { - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.Unprepare(_handle)); - _bReady = false; - } - } - /// - /// Pauses buffering of audio data from the device. - /// - public override void Pause() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.Pause(_handle)); - } - /// - /// Resumes buffering audio data from the device. - /// - public override void Resume() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.Resume(_handle)); - } - /// - /// Flushes and discards buffered audio data from the input stream. - /// - public override void Flush() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.Flush(_handle)); - } - /// - /// Sets the sound stream information to the audio input. - /// - /// - /// - public override void SetStreamInfo(AudioStreamPolicy streamPolicy) - { - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.SetStreamInfo(_handle, streamPolicy.Handle)); - } - /// - /// Initializes the instance of the AudioInput class with the SafeAudioInputHandle. - /// - /// - /// - /// - public AudioInput(int sample_rate, AudioChannel channel, AudioSampleType type) - { - AudioErrorHelper.Try(Interop.AudioIO.AudioInput.Create(sample_rate, (int)channel, (int)type, out _handle)); - } - private AudioInput() { } - } -} diff --git a/src/Tizen.Multimedia/AudioIO/AudioOutput.cs b/src/Tizen.Multimedia/AudioIO/AudioOutput.cs deleted file mode 100755 index c2153e7..0000000 --- a/src/Tizen.Multimedia/AudioIO/AudioOutput.cs +++ /dev/null @@ -1,223 +0,0 @@ - /* - * 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 -{ - /// - /// The Audio Output class provides a set of functions to directly manage the system audio output devices. - /// - public class AudioOutput : BaseAudio - { - /// - /// Gets the sample rate of the audio output data stream. - /// - public override int SampleRate - { - get - { - int sampleRate; - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.GetSampleRate(_handle, out sampleRate)); - return sampleRate; - } - } - /// - /// Gets the channel type of the audio output data stream. - /// The audio channel type defines whether the audio is mono or stereo. - /// - public override AudioChannel Channel - { - get - { - int channel; - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.GetChannel(_handle, out channel)); - return (AudioChannel)channel; - } - } - /// - /// Gets the sample audio format (8-bit or 16-bit) of the audio output data stream. - /// - public override AudioSampleType SampleType - { - get - { - int type; - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.GetSampleType(_handle, out type)); - return (AudioSampleType)type; - } - } - /// - /// Gets the size to be allocated for the audio output buffer. - /// - public override int BufferSize - { - get - { - int size = 0; - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.GetBufferSize(_handle, out size)); - return size; - } - } - /// - /// Gets the sound type supported by the audio output device. - /// - public AudioStreamType SoundStreamType - { - get - { - int audioType = 0; - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.GetSoundType(_handle, out audioType)); - return (AudioStreamType)audioType; - } - } - - /// - /// Drains buffered audio data from the output stream. - /// This function waits until drains stream buffer completely. (e.g end of playback) - /// - public void Drain() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.Drain(_handle)); - } - object _lock = new object(); - /// - /// Starts writing the audio data to the device. - /// - /// - public void Write(byte[] buffer) - { - if (buffer.Length <= 0) - { - throw new IndexOutOfRangeException("Bed File Length"); - } - IntPtr ptrByteArray = Marshal.AllocHGlobal(buffer.Length); - try - { - Marshal.Copy(buffer, 0, ptrByteArray, buffer.Length); - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.Write(_handle, ptrByteArray, (uint)buffer.Length)); - } - finally - { - if (ptrByteArray != IntPtr.Zero) - { - Marshal.FreeHGlobal(ptrByteArray); - ptrByteArray = IntPtr.Zero; - } - } - } - /// - /// Sets an asynchronous(event) callback function to handle playing PCM (pulse-code modulation) data. - /// - protected override void RegisterAudioStreamLengthChanged() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.SetAudioOutputStreamChangedCallback(_handle, OnStream, IntPtr.Zero)); - } - /// - /// Unregisters the callback function. - /// - protected override void UnregisterAudioStreamLengthChanged() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.UnsetAudioOutputStreamChangedCallback(_handle)); - } - /// - /// Sets the state changed callback function to the audio output handle. - /// - protected override void RegisterAudioStateChangedCallback() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.SetAudioOutputStateChangedCallback(_handle, OnStateChanged, IntPtr.Zero)); - } - /// - /// Unregisters the state changed callback function of the audio output handle. - /// - protected override void UnregisterAudioStateChangedmCallback() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.UnsetAudioOutputStateChangedCallback(_handle)); - } - /// - /// Releases the audio output handle, along with all its resources. - /// - protected override void Destroy() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.Destroy(_handle)); - } - /// - /// Prepares the audio output for playback, this must be called before audio_out_write(). - /// - public override void Prepare() - { - if (_bReady == false) - { - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.Prepare(_handle)); - _bReady = true; - } - } - /// - /// Unprepares the audio output. - /// - public override void Unprepare() - { - if (_bReady) - { - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.Unprepare(_handle)); - _bReady = false; - } - } - /// - /// Pauses feeding of audio data to the device. - /// - public override void Pause() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.Pause(_handle)); - - } - /// - /// Resumes feeding of audio data to the device. - /// - public override void Resume() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.Resume(_handle)); - } - /// - /// Flushes and discards buffered audio data from the output stream. - /// - public override void Flush() - { - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.Flush(_handle)); - } - /// - /// Sets the sound stream information to the audio output. - /// - /// - /// - public override void SetStreamInfo(AudioStreamPolicy streamPolicy) - { - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.SetStreamInfo(_handle, streamPolicy.Handle)); - } - /// - /// Initializes the instance of the AudioOutput class with the SafeAudioInputHandle. - /// - /// - /// - /// - public AudioOutput(int sample_rate, AudioChannel channel, AudioSampleType type) - { - AudioErrorHelper.Try(Interop.AudioIO.AudioOutput.Create(sample_rate, (int)channel, (int)type, out _handle)); - } - private AudioOutput() { } - } -} diff --git a/src/Tizen.Multimedia/AudioIO/AudioPlaybackBufferAvailableEventArgs.cs b/src/Tizen.Multimedia/AudioIO/AudioPlaybackBufferAvailableEventArgs.cs new file mode 100644 index 0000000..ac9a495 --- /dev/null +++ b/src/Tizen.Multimedia/AudioIO/AudioPlaybackBufferAvailableEventArgs.cs @@ -0,0 +1,30 @@ +/* +* 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 +{ + public class AudioPlaybackBufferAvailableEventArgs : EventArgs + { + internal AudioPlaybackBufferAvailableEventArgs(int length) + { + Length = length; + } + + public int Length { get; } + } +} diff --git a/src/Tizen.Multimedia/AudioIO/AudioPlyaback.cs b/src/Tizen.Multimedia/AudioIO/AudioPlyaback.cs new file mode 100644 index 0000000..e59aa0e --- /dev/null +++ b/src/Tizen.Multimedia/AudioIO/AudioPlyaback.cs @@ -0,0 +1,408 @@ +/* +* 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 +{ + /// + /// Provides the ability to directly manage the system audio output devices and play PCM (pulse-code modulation) data. + /// + public class AudioPlayback : IDisposable + { + public const int MinSampleRate = 8000; + public const int MaxSampleRate = 48000; + + private IntPtr _handle = IntPtr.Zero; + + private AudioIOState _state = AudioIOState.Idle; + + #region Event + /// + /// Occurs when audio playback data can be written. + /// + /// + public event EventHandler BufferAvailable; + + private Interop.AudioIO.AudioStreamCallback _streamCallback; + + private void RegisterStreamCallback() + { + _streamCallback = (IntPtr handle, uint bytes, IntPtr _) => + { + BufferAvailable?.Invoke(this, new AudioPlaybackBufferAvailableEventArgs((int)bytes)); + }; + + AudioIOUtil.ThrowIfError( + Interop.AudioIO.AudioOutput.SetStreamChangedCallback(_handle, _streamCallback, IntPtr.Zero), + $"Failed to create {nameof(AudioPlayback)}"); + } + + /// + /// Occurs when the state of the AudioPlayback is changed. + /// + public event EventHandler StateChanged; + + private Interop.AudioIO.AudioStateChangedCallback _stateChangedCallback; + + private void RegisterStateChangedCallback() + { + _stateChangedCallback = (IntPtr handle, int previous, int current, bool byPolicy, IntPtr _) => + { + _state = (AudioIOState)current; + + StateChanged?.Invoke(this, + new AudioIOStateChangedEventArgs((AudioIOState)previous, _state, byPolicy)); + }; + + AudioIOUtil.ThrowIfError( + Interop.AudioIO.AudioOutput.SetStateChangedCallback(_handle, _stateChangedCallback, IntPtr.Zero), + $"Failed to create {nameof(AudioPlayback)}"); + } + #endregion + + /// + /// Initializes a new instance of the AudioPlayback class with the specified sample rate, channel and sample type. + /// + /// The audio sample rate.(8000 ~ 48000Hz) + /// The audio channel type. + /// The audio sample type. + /// + /// is less than . + /// -or- + /// is greater than . + /// + /// + /// The value of is invalid. + /// -or- + /// The value of is invalid. + /// + public AudioPlayback(int sampleRate, AudioChannel channel, AudioSampleType sampleType) + { + if (sampleRate < MinSampleRate || MaxSampleRate < sampleRate) + { + throw new ArgumentOutOfRangeException(nameof(sampleRate), sampleRate, + $"Valid sampleRate range is { MinSampleRate } <= x <= { MaxSampleRate }."); + } + + ValidationUtil.ValidateEnum(typeof(AudioChannel), channel); + ValidationUtil.ValidateEnum(typeof(AudioSampleType), sampleType); + + SampleRate = sampleRate; + Channel = channel; + SampleType = sampleType; + + AudioIOUtil.ThrowIfError( + Interop.AudioIO.AudioOutput.Create(SampleRate, (int)Channel, (int)SampleType, out _handle), + $"Failed to create {nameof(AudioPlayback)}"); + + RegisterStreamCallback(); + RegisterStateChangedCallback(); + } + + ~AudioPlayback() + { + Dispose(false); + } + + #region Dispose support + private bool _isDisposed = false; + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (_isDisposed) + { + return; + } + + if (_handle != IntPtr.Zero) + { + if (_state != AudioIOState.Idle) + { + try + { + Unprepare(); + } + catch (Exception) + { + } + } + + Interop.AudioIO.AudioOutput.Destroy(_handle); + _handle = IntPtr.Zero; + _isDisposed = true; + } + } + + private void ValidateNotDisposed() + { + if (_isDisposed) + { + throw new ObjectDisposedException(GetType().Name); + } + } + #endregion + + private void ValidateState(params AudioIOState[] desiredStates) + { + ValidateNotDisposed(); + + AudioIOUtil.ValidateState(_state, desiredStates); + } + + /// + /// Gets the sample rate of the audio output data stream. + /// + public int SampleRate { get; } + + /// + /// Gets the channel type of the audio output data stream. + /// + public AudioChannel Channel { get; } + + /// + /// Gets the sample type of the audio output data stream. + /// + public AudioSampleType SampleType { get; } + + /// + /// Gets the sound type supported by the audio output device. + /// + /// The AudioPlayback has already been disposed. + public AudioStreamType StreamType + { + get + { + ValidateNotDisposed(); + + int audioType = 0; + int ret = Interop.AudioIO.AudioOutput.GetSoundType(_handle, out audioType); + MultimediaDebug.AssertNoError(ret); + + return (AudioStreamType)audioType; + } + } + + /// + /// Gets the size to be allocated for the audio output buffer. + /// + /// The AudioPlayback has already been disposed. + /// The current state is . + public int GetBufferSize() + { + ValidateState(AudioIOState.Running, AudioIOState.Paused); + + int size = 0; + AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioOutput.GetBufferSize(_handle, out size)); + return size; + } + + /// + /// Drains buffered audio data from the output stream. + /// It blocks the calling thread until draining the stream buffer completely. (e.g end of playback) + /// + /// The AudioPlayback has already been disposed. + /// The current state is . + public void Drain() + { + ValidateState(AudioIOState.Running, AudioIOState.Paused); + + int ret = Interop.AudioIO.AudioOutput.Drain(_handle); + + MultimediaDebug.AssertNoError(ret); + } + + /// + /// Starts writing the audio data to the device. + /// + /// The buffer to write. + /// The written size. + /// is null. + /// The length of is zero. + /// The current state is not . + /// The AudioPlayback has already been disposed. + public int Write(byte[] buffer) + { + ValidateState(AudioIOState.Running); + + if (buffer == null) + { + throw new ArgumentNullException(nameof(buffer)); + } + + if (buffer.Length == 0) + { + throw new ArgumentException("buffer has no data.(the Length is zero.)", nameof(buffer)); + } + + int ret = Interop.AudioIO.AudioOutput.Write(_handle, buffer, (uint)buffer.Length); + + AudioIOUtil.ThrowIfError(ret, "Failed to write buffer"); + + return ret; + } + + /// + /// Prepares the AudioPlayback. + /// + /// + /// This must be called before . + /// + /// + /// Operation failed due to internal error. + /// -or- + /// The current state is not . + /// + /// The AudioPlayback has already been disposed. + /// + public void Prepare() + { + ValidateState(AudioIOState.Idle); + + AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioOutput.Prepare(_handle), + $"Failed to prepare the {nameof(AudioPlayback)}"); + } + + /// + /// Unprepares the AudioPlayback. + /// + /// + /// Operation failed due to internal error. + /// -or- + /// The current state is . + /// + /// The AudioPlayback has already been disposed. + /// + public void Unprepare() + { + ValidateState(AudioIOState.Running, AudioIOState.Paused); + + AudioIOUtil.ThrowIfError(Interop.AudioIO.AudioOutput.Unprepare(_handle), + $"Failed to unprepare the {nameof(AudioPlayback)}"); + } + + /// + /// Pauses feeding of audio data to the device. + /// + /// It has no effect if the current is the . + /// + /// The current state is . + /// -or- + /// The method is called in the event handler. + /// + /// The AudioPlayback has already been disposed. + /// + public void Pause() + { + if (_state == AudioIOState.Paused) + { + return; + } + ValidateState(AudioIOState.Running); + + int ret = Interop.AudioIO.AudioOutput.Pause(_handle); + + // Here, we convert the not supported error into InvalidOperationException. + // It is because this exception is more appropriate in C# for this kind of situation. + if ((int)AudioIOError.NotSupported == ret) + { + throw new InvalidOperationException("Cannot change the state in event handlers."); + } + + MultimediaDebug.AssertNoError(ret); + } + + /// + /// Resumes feeding of audio data to the device. + /// + /// It has no effect if the current is the . + /// + /// The current state is . + /// -or- + /// The method is called in an event handler. + /// + /// The AudioPlayback has already been disposed. + /// + public void Resume() + { + if (_state == AudioIOState.Running) + { + return; + } + ValidateState(AudioIOState.Paused); + + int ret = Interop.AudioIO.AudioOutput.Resume(_handle); + + // Here, we convert the not supported error into InvalidOperationException. + // It is because this exception is more appropriate in C# for this kind of situation. + if ((int)AudioIOError.NotSupported == ret) + { + throw new InvalidOperationException("Cannot change the state in event handlers."); + } + + MultimediaDebug.AssertNoError(ret); + } + + /// + /// Flushes and discards buffered audio data from the output stream. + /// + /// The current state is . + /// The AudioPlayback has already been disposed. + public void Flush() + { + ValidateState(AudioIOState.Running, AudioIOState.Paused); + + int ret = Interop.AudioIO.AudioOutput.Flush(_handle); + + MultimediaDebug.AssertNoError(ret); + } + + /// + /// Applies the sound stream information to the AudioPlayback. + /// + /// The to apply for the AudioPlayback. + /// is null. + /// + /// has already been disposed. + /// -or- + /// The AudioPlayback has already been disposed. + /// + /// is not supported. + /// Not able to retrieve information from . + public void ApplyStreamPolicy(AudioStreamPolicy streamPolicy) + { + if (streamPolicy == null) + { + 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)); + } + } +} diff --git a/src/Tizen.Multimedia/AudioIO/AudioStateChangedEventArgs.cs b/src/Tizen.Multimedia/AudioIO/AudioStateChangedEventArgs.cs deleted file mode 100755 index e6972dd..0000000 --- a/src/Tizen.Multimedia/AudioIO/AudioStateChangedEventArgs.cs +++ /dev/null @@ -1,46 +0,0 @@ - /* - * 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 -{ - /// - /// Argument for the event that is Audio State Changed. - /// - public class AudioStateChangedEventArgs : EventArgs - { - private readonly AudioState _previous; - private readonly AudioState _current; - private readonly bool _by_policy; - /// - /// Initializes the instance of the AudioStateChangedEventArgs class. - /// - /// - /// - /// - internal AudioStateChangedEventArgs(AudioState previous, AudioState current, bool by_policy) - { - this._previous = previous; - this._current = current; - this._by_policy = by_policy; - } - - public AudioState Previous { get { return _previous; } } - public AudioState Current { get { return _current; } } - public bool Policy { get { return _by_policy; } } - } -} diff --git a/src/Tizen.Multimedia/AudioIO/BaseAudio.cs b/src/Tizen.Multimedia/AudioIO/BaseAudio.cs deleted file mode 100755 index ee1fff4..0000000 --- a/src/Tizen.Multimedia/AudioIO/BaseAudio.cs +++ /dev/null @@ -1,125 +0,0 @@ - /* - * 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 -{ - public abstract class BaseAudio : IDisposable - { - #region Event - private EventHandler streamCallback; - private EventHandler stateChanged; - - public event EventHandler StreamLengthChanged - { - add - { - if (streamCallback == null) - { - RegisterAudioStreamLengthChanged(); - } - streamCallback += value; - } - remove - { - streamCallback -= value; - if (streamCallback == null) - { - UnregisterAudioStreamLengthChanged(); - } - } - } - public event EventHandler StateChanged - { - add - { - if (streamCallback == null) - { - RegisterAudioStateChangedCallback(); - } - stateChanged += value; - } - remove - { - stateChanged -= value; - if (streamCallback == null) - { - UnregisterAudioStateChangedmCallback(); - } - } - } - - protected void OnStream(IntPtr handle, uint nbytes, IntPtr userdata) - { - if (streamCallback != null) - { - streamCallback(this, new AudioStreamLengthChangedEventArgs(nbytes)); - } - } - protected void OnStateChanged(IntPtr handle, int previous, int current, bool by_policy, IntPtr user_data) - { - if (streamCallback != null) - { - stateChanged(this, new AudioStateChangedEventArgs((AudioState)previous, (AudioState)current, by_policy)); - } - } - #endregion - protected IntPtr _handle = IntPtr.Zero; - protected bool _bReady = false; - - public abstract int SampleRate { get;} - public abstract AudioChannel Channel { get; } - public abstract AudioSampleType SampleType { get; } - public abstract int BufferSize{ get; } - - public abstract void Prepare(); - public abstract void Unprepare(); - public abstract void Pause(); - public abstract void Resume(); - public abstract void Flush(); - public abstract void SetStreamInfo(AudioStreamPolicy streamPolicy); // 현재는 임의의 타입으로 실제 AudioPolicy가 들어와야 함. - protected abstract void Destroy(); - protected abstract void RegisterAudioStreamLengthChanged(); - protected abstract void UnregisterAudioStreamLengthChanged(); - protected abstract void UnregisterAudioStateChangedmCallback(); - protected abstract void RegisterAudioStateChangedCallback(); - - public BaseAudio() { } - ~BaseAudio() - { - Dispose(false); - } - public void Dispose() - { - Dispose(true); - } - protected virtual void Dispose(bool _bDisposing) - { - if (_bDisposing) // // Free managed objects. - { - // to be used if there are any other disposable objects - } - // // Free Unmanaged objects. - if (_bReady) - Unprepare(); - if (_handle != IntPtr.Zero) - Destroy(); - - GC.SuppressFinalize(this); - } - } -} diff --git a/src/Tizen.Multimedia/MediaCodec/MediaCodecDebug.cs b/src/Tizen.Multimedia/Common/MultimediaDebug.cs similarity index 81% rename from src/Tizen.Multimedia/MediaCodec/MediaCodecDebug.cs rename to src/Tizen.Multimedia/Common/MultimediaDebug.cs index 75d409c..3e00569 100644 --- a/src/Tizen.Multimedia/MediaCodec/MediaCodecDebug.cs +++ b/src/Tizen.Multimedia/Common/MultimediaDebug.cs @@ -16,16 +16,15 @@ using System.Diagnostics; -namespace Tizen.Multimedia.MediaCodec +namespace Tizen.Multimedia { - internal class MediaCodecDebug + internal class MultimediaDebug { - - [ConditionalAttribute("DEBUG")] + [Conditional("DEBUG")] internal static void AssertNoError(int errorCode) { - Debug.Assert(errorCode == (int)MediaCodecErrorCode.None, - $"The API is supposed not to return an error! But it returns error({ 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."); } } diff --git a/src/Tizen.Multimedia/MediaTool/MediaToolDebug.cs b/src/Tizen.Multimedia/Common/Size.cs similarity index 62% rename from src/Tizen.Multimedia/MediaTool/MediaToolDebug.cs rename to src/Tizen.Multimedia/Common/Size.cs index 91ad531..7aa6792 100644 --- a/src/Tizen.Multimedia/MediaTool/MediaToolDebug.cs +++ b/src/Tizen.Multimedia/Common/Size.cs @@ -14,19 +14,32 @@ * limitations under the License. */ -using System.Diagnostics; -using Tizen.Internals.Errors; - namespace Tizen.Multimedia { - internal class MediaToolDebug + public struct Size { - [ConditionalAttribute("DEBUG")] - internal static void AssertNoError(int errorCode) + public Size(int width, int height) + { + Width = width; + Height = height; + } + + public int Width + { + get; + set; + } + + public int Height + { + get; + set; + } + + public override string ToString() { - Debug.Assert(errorCode == (int)ErrorCode.None, "The API is supposed not to return an error!", - "Implementation of core may have been changed, modify code to throw if the return code is not zero."); + return $"Width : { Width }, Height : { Height }"; } } } diff --git a/src/Tizen.Multimedia/AudioIO/AudioStreamLengthChangedEventArgs.cs b/src/Tizen.Multimedia/Common/ValdiationUtil.cs old mode 100755 new mode 100644 similarity index 70% rename from src/Tizen.Multimedia/AudioIO/AudioStreamLengthChangedEventArgs.cs rename to src/Tizen.Multimedia/Common/ValdiationUtil.cs index e2fd523..9e7dcfb --- a/src/Tizen.Multimedia/AudioIO/AudioStreamLengthChangedEventArgs.cs +++ b/src/Tizen.Multimedia/Common/ValdiationUtil.cs @@ -1,31 +1,31 @@ - /* - * 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 -{ - public class AudioStreamLengthChangedEventArgs : EventArgs - { - private readonly uint _length; - - internal AudioStreamLengthChangedEventArgs( uint length ) - { - this._length = length; - } - public uint Length { get { return _length; } } - } -} +/* + * 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 ValidationUtil + { + internal static void ValidateEnum(Type enumType, object value) + { + if (!Enum.IsDefined(enumType, value)) + { + throw new ArgumentException($"Invalid { enumType.Name } value : { value }"); + } + } + } +} diff --git a/src/Tizen.Multimedia/Interop/Interop.AudioIO.cs b/src/Tizen.Multimedia/Interop/Interop.AudioIO.cs index 36671a8..b72792d 100755 --- a/src/Tizen.Multimedia/Interop/Interop.AudioIO.cs +++ b/src/Tizen.Multimedia/Interop/Interop.AudioIO.cs @@ -1,132 +1,121 @@ -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class AudioIO - { - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate void AudioStreamCallback(IntPtr handle, uint nbytes, IntPtr userdata); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate void AudioStateChangedCallback(IntPtr handle, int previous, int current, bool byPolicy, IntPtr userData); - - internal static partial class AudioInput - { - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_set_state_changed_cb")] - internal static extern int SetAudioInputStateChangedCallback(IntPtr handle, AudioStateChangedCallback callback, IntPtr user_data); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_unset_state_changed_cb")] - internal static extern int UnsetAudioInputStateChangedCallback(IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_set_stream_cb")] - internal static extern int SetAudioInputStreamChangedCallback(IntPtr handle, AudioStreamCallback callback, IntPtr user_data); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_unset_stream_cb")] - internal static extern int UnsetAudioInputStreamChangedCallback(IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_create")] - internal static extern int Create(int sampleRate, int channel, int type, out IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_destroy")] - internal static extern int Destroy(IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_set_stream_info")] - internal static extern int SetStreamInfo(IntPtr handle, IntPtr streamInfoHandle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_prepare")] - internal static extern int Prepare(IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_unprepare")] - internal static extern int Unprepare(IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_pause")] - internal static extern int Pause(IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_resume")] - internal static extern int Resume(IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_flush")] - internal static extern int Flush(IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_read")] - internal static extern int Read(IntPtr handle, IntPtr buffer, int length); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_get_buffer_size")] - internal static extern int GetBufferSize(IntPtr handle, out int size); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_get_sample_rate")] - internal static extern int GetSampleRate(IntPtr handle, out int sampleRate); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_get_channel")] - internal static extern int GetChannel(IntPtr handle, out int channel); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_get_sample_type")] - internal static extern int GetSampleType(IntPtr handle, out int sampleType); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_peek")] - internal static extern int Peek(IntPtr handle, out IntPtr buffer, out uint length); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_drop")] - internal static extern int Drop(IntPtr handle); - } - internal static partial class AudioOutput - { - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_set_state_changed_cb")] - internal static extern int SetAudioOutputStateChangedCallback(IntPtr handle, AudioStateChangedCallback callback, IntPtr user_data); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_unset_state_changed_cb")] - internal static extern int UnsetAudioOutputStateChangedCallback(IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_set_stream_cb")] - internal static extern int SetAudioOutputStreamChangedCallback(IntPtr handle, AudioStreamCallback callback, IntPtr user_data); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_unset_stream_cb")] - internal static extern int UnsetAudioOutputStreamChangedCallback(IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_create_new")] - internal static extern int Create(int sampleRate, int channel, int type, out IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_destroy")] - internal static extern int Destroy(IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_drain")] - internal static extern int Drain(IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_flush")] - internal static extern int Flush(IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_get_buffer_size")] - internal static extern int GetBufferSize(IntPtr handle, out int size); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_get_channel")] - internal static extern int GetChannel(IntPtr handle, out int channel); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_get_sample_rate")] - internal static extern int GetSampleRate(IntPtr handle, out int sampleRate); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_get_sample_type")] - internal static extern int GetSampleType(IntPtr handle, out int sampleType); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_get_sound_type")] - internal static extern int GetSoundType(IntPtr handle, out int soundType); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_pause")] - internal static extern int Pause(IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_prepare")] - internal static extern int Prepare(IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_resume")] - internal static extern int Resume(IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_set_stream_info")] - internal static extern int SetStreamInfo(IntPtr handle, IntPtr streamInfoHandle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_unprepare")] - internal static extern int Unprepare(IntPtr handle); - - [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_write")] - internal static extern int Write(IntPtr handle, IntPtr buffer, uint length); - } - } -} +using System; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class AudioIO + { + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void AudioStreamCallback(IntPtr handle, uint nbytes, IntPtr userdata); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void AudioStateChangedCallback(IntPtr handle, int previous, int current, bool byPolicy, IntPtr userData); + + internal static partial class AudioInput + { + [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_set_state_changed_cb")] + internal static extern int SetStateChangedCallback(IntPtr handle, AudioStateChangedCallback callback, IntPtr user_data); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_set_stream_cb")] + internal static extern int SetStreamCallback(IntPtr handle, AudioStreamCallback callback, IntPtr user_data); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_create")] + internal static extern int Create(int sampleRate, int channel, int type, out IntPtr handle); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_destroy")] + internal static extern int Destroy(IntPtr handle); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_set_stream_info")] + internal static extern int SetStreamInfo(IntPtr handle, IntPtr streamInfoHandle); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_prepare")] + internal static extern int Prepare(IntPtr handle); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_unprepare")] + internal static extern int Unprepare(IntPtr handle); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_pause")] + internal static extern int Pause(IntPtr handle); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_resume")] + internal static extern int Resume(IntPtr handle); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_flush")] + internal static extern int Flush(IntPtr handle); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_read")] + internal static extern int Read(IntPtr handle, byte[] buffer, int length); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_get_buffer_size")] + internal static extern int GetBufferSize(IntPtr handle, out int size); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_get_sample_rate")] + internal static extern int GetSampleRate(IntPtr handle, out int sampleRate); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_get_channel")] + internal static extern int GetChannel(IntPtr handle, out int channel); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_get_sample_type")] + internal static extern int GetSampleType(IntPtr handle, out int sampleType); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_peek")] + internal static extern int Peek(IntPtr handle, out IntPtr buffer, ref uint length); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_in_drop")] + internal static extern int Drop(IntPtr handle); + } + internal static partial class AudioOutput + { + [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_set_state_changed_cb")] + internal static extern int SetStateChangedCallback(IntPtr handle, AudioStateChangedCallback callback, IntPtr user_data); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_set_stream_cb")] + internal static extern int SetStreamChangedCallback(IntPtr handle, AudioStreamCallback callback, IntPtr user_data); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_create_new")] + internal static extern int Create(int sampleRate, int channel, int type, out IntPtr handle); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_destroy")] + internal static extern int Destroy(IntPtr handle); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_drain")] + internal static extern int Drain(IntPtr handle); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_flush")] + internal static extern int Flush(IntPtr handle); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_get_buffer_size")] + internal static extern int GetBufferSize(IntPtr handle, out int size); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_get_channel")] + internal static extern int GetChannel(IntPtr handle, out int channel); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_get_sample_rate")] + internal static extern int GetSampleRate(IntPtr handle, out int sampleRate); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_get_sample_type")] + internal static extern int GetSampleType(IntPtr handle, out int sampleType); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_get_sound_type")] + internal static extern int GetSoundType(IntPtr handle, out int soundType); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_pause")] + internal static extern int Pause(IntPtr handle); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_prepare")] + internal static extern int Prepare(IntPtr handle); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_resume")] + internal static extern int Resume(IntPtr handle); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_set_stream_info")] + internal static extern int SetStreamInfo(IntPtr handle, IntPtr streamInfoHandle); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_unprepare")] + internal static extern int Unprepare(IntPtr handle); + + [DllImport(Libraries.AudioIO, EntryPoint = "audio_out_write")] + internal static extern int Write(IntPtr handle, byte[] buffer, uint length); + } + } +} diff --git a/src/Tizen.Multimedia/Interop/Interop.Libraries.cs b/src/Tizen.Multimedia/Interop/Interop.Libraries.cs index de88182..fc29184 100755 --- a/src/Tizen.Multimedia/Interop/Interop.Libraries.cs +++ b/src/Tizen.Multimedia/Interop/Interop.Libraries.cs @@ -22,7 +22,7 @@ internal static partial class Interop public const string Recorder = "libcapi-media-recorder.so.0"; public const string SoundManager = "libcapi-media-sound-manager.so.0"; public const string AudioIO = "libcapi-media-audio-io.so.0"; - public const string ScreenMirroring = "libcapi-screen-mirroring-io.so.0"; + public const string ScreenMirroring = "libcapi-media-screen-mirroring.so.0"; public const string MetadataExtractor = "libcapi-media-metadata-extractor.so"; public const string MediaController = "libcapi-media-controller.so.0"; public const string MediaTool = "libcapi-media-tool.so.0"; diff --git a/src/Tizen.Multimedia/Interop/Interop.MediaController.cs b/src/Tizen.Multimedia/Interop/Interop.MediaController.cs old mode 100644 new mode 100755 index 04998d4..c370e8a --- a/src/Tizen.Multimedia/Interop/Interop.MediaController.cs +++ b/src/Tizen.Multimedia/Interop/Interop.MediaController.cs @@ -1,5 +1,6 @@ using System; using System.Runtime.InteropServices; +using Tizen.Applications; internal static partial class Interop { @@ -21,7 +22,7 @@ internal static partial class Interop internal delegate void RepeatModeUpdatedCallback(string serverName, int repeatMode, IntPtr userData); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void CommandReplyRecievedCallback(string serverName, int result, IntPtr bundleData, IntPtr userData); + internal delegate void CommandReplyRecievedCallback(string serverName, int result, IntPtr bundle, IntPtr userData); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate bool SubscribedServerCallback(string serverName, IntPtr userData); @@ -105,7 +106,7 @@ internal static partial class Interop internal static extern int SendPlaybackStateCommand(IntPtr handle, string serverName, int state); [DllImport(Libraries.MediaController, EntryPoint = "mc_client_send_custom_command")] - internal static extern int SendCustomCommand(IntPtr handle, string serverName, string command, IntPtr bundle, CommandReplyRecievedCallback callback, IntPtr userData); + internal static extern int SendCustomCommand(IntPtr handle, string serverName, string command, SafeBundleHandle bundle, CommandReplyRecievedCallback callback, IntPtr userData); [DllImport(Libraries.MediaController, EntryPoint = "mc_client_foreach_server_subscribed")] internal static extern int ForeachSubscribedServer(IntPtr handle, int subscriptionType, SubscribedServerCallback callback, IntPtr userData); @@ -120,7 +121,7 @@ internal static partial class Interop internal delegate void PlaybackStateCommandRecievedCallback(string clientName, int state, IntPtr userData); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void CustomCommandRecievedCallback(string clientName, string command, IntPtr bundleData, IntPtr userData); + internal delegate void CustomCommandRecievedCallback(string clientName, string command, IntPtr bundle, IntPtr userData); [DllImport(Libraries.MediaController, EntryPoint = "mc_server_create")] internal static extern int Create(out IntPtr handle); @@ -155,13 +156,13 @@ internal static partial class Interop [DllImport(Libraries.MediaController, EntryPoint = "mc_server_unset_playback_state_command_received_cb")] internal static extern int UnsetPlaybackStateCmdRecvCb(IntPtr handle); - [DllImport(Libraries.MediaController, EntryPoint = "mc_server_set_custom_command_received_cb ")] + [DllImport(Libraries.MediaController, EntryPoint = "mc_server_set_custom_command_received_cb")] internal static extern int SetCustomCmdRecvCb(IntPtr handle, CustomCommandRecievedCallback callback, IntPtr userData); - [DllImport(Libraries.MediaController, EntryPoint = "mc_server_unset_custom_command_received_cb ")] + [DllImport(Libraries.MediaController, EntryPoint = "mc_server_unset_custom_command_received_cb")] internal static extern int UnsetCustomCmdRecvCb(IntPtr handle); - [DllImport(Libraries.MediaController, EntryPoint = "mc_server_send_command_reply ")] - internal static extern int SendCommandReply(IntPtr handle, string clientName, int result, IntPtr bundleData); + [DllImport(Libraries.MediaController, EntryPoint = "mc_server_send_command_reply")] + internal static extern int SendCommandReply(IntPtr handle, string clientName, int result, SafeBundleHandle bundle); } } diff --git a/src/Tizen.Multimedia/Interop/Interop.Player.cs b/src/Tizen.Multimedia/Interop/Interop.Player.cs index f648429..7ca6460 100644 --- a/src/Tizen.Multimedia/Interop/Interop.Player.cs +++ b/src/Tizen.Multimedia/Interop/Interop.Player.cs @@ -6,297 +6,282 @@ internal static partial class Interop internal static partial class Player { - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void PlaybackCompletedCallback(IntPtr userData); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void PlaybackCompletedCallback(IntPtr userData); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void PlaybackInterruptedCallback(int code, IntPtr userData); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void PlaybackInterruptedCallback(int code, IntPtr userData); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void PlaybackErrorCallback(int code, IntPtr userData); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void PlaybackErrorCallback(int code, IntPtr userData); - //[UnmanagedFunctionPointer(CallingConvention.Cdecl)] - //internal delegate void VideoFrameDecodedCallback(MediaPacket packet, IntPtr userData); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void VideoFrameDecodedCallback(IntPtr packetHandle, IntPtr userData); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void SubtitleUpdatedCallback(uint duration, string text, IntPtr userData); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void SubtitleUpdatedCallback(uint duration, string text, IntPtr userData); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void BufferingProgressCallback(int percent, IntPtr userData); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void BufferingProgressCallback(int percent, IntPtr userData); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void ProgressiveDownloadMessageCallback(int type, IntPtr userData); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void VideoStreamChangedCallback(int width, int height, int fps, int bitrate, IntPtr userData); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void VideoStreamChangedCallback(int width, int height, int fps, int bitrate, IntPtr userData); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void MediaStreamBufferStatusCallback(int status, IntPtr userData); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void BufferStatusCallback(int status, IntPtr userData); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void MediaStreamSeekCallback(ulong offset, IntPtr userData); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void SeekOffsetChangedCallback(UInt64 offset, IntPtr userData); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void VideoCaptureCallback(IntPtr data, int width, int height, uint size, IntPtr userData); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void VideoCaptureCallback(byte[] data, int width, int height, uint size, IntPtr userData); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void PrepareCallback(IntPtr userData); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void PrepareCallback(IntPtr userData); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void SeekCompletedCallback(IntPtr userData); - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void SeekCompletedCallback(IntPtr userData); + [DllImport(Libraries.Player, EntryPoint = "player_create")] + internal static extern int Create(out IntPtr player); - [DllImport(Libraries.Player, EntryPoint = "player_create")] - internal static extern int Create(out IntPtr player); + [DllImport(Libraries.Player, EntryPoint = "player_destroy")] + internal static extern int Destroy(IntPtr player); - [DllImport(Libraries.Player, EntryPoint = "player_destroy")] - internal static extern int Destroy(IntPtr player); + [DllImport(Libraries.Player, EntryPoint = "player_prepare")] + internal static extern int Prepare(IntPtr player); - [DllImport(Libraries.Player, EntryPoint = "player_prepare")] - internal static extern int Prepare(IntPtr player); + [DllImport(Libraries.Player, EntryPoint = "player_prepare_async")] + internal static extern int PrepareAsync(IntPtr player, PrepareCallback cb, IntPtr userData); - [DllImport(Libraries.Player, EntryPoint = "player_prepare_async")] - internal static extern int PrepareAsync(IntPtr player, PrepareCallback cb, IntPtr userData); + [DllImport(Libraries.Player, EntryPoint = "player_unprepare")] + internal static extern int Unprepare(IntPtr player); - [DllImport(Libraries.Player, EntryPoint = "player_unprepare")] - internal static extern int Unprepare(IntPtr player); + [DllImport(Libraries.Player, EntryPoint = "player_set_uri")] + internal static extern int SetUri(IntPtr player, string uri); - [DllImport(Libraries.Player, EntryPoint = "player_set_uri")] - internal static extern int SetUri(IntPtr player, string uri); + [DllImport(Libraries.Player, EntryPoint = "player_set_display")] + internal static extern int SetDisplay(IntPtr player, int type, IntPtr display); - [DllImport(Libraries.Player, EntryPoint = "player_set_display")] - internal static extern int SetDisplay(IntPtr player, int type, IntPtr display); + [DllImport(Libraries.Player, EntryPoint = "player_start")] + internal static extern int Start(IntPtr player); - [DllImport(Libraries.Player, EntryPoint = "player_start")] - internal static extern int Start(IntPtr player); + [DllImport(Libraries.Player, EntryPoint = "player_stop")] + internal static extern int Stop(IntPtr player); - [DllImport(Libraries.Player, EntryPoint = "player_stop")] - internal static extern int Stop(IntPtr player); + [DllImport(Libraries.Player, EntryPoint = "player_pause")] + internal static extern int Pause(IntPtr player); - [DllImport(Libraries.Player, EntryPoint = "player_pause")] - internal static extern int Pause(IntPtr player); + [DllImport(Libraries.Player, EntryPoint = "player_set_memory_buffer")] + internal static extern int SetMemoryBuffer(IntPtr player, byte[] data, int size); - [DllImport(Libraries.Player, EntryPoint = "player_set_memory_buffer")] - internal static extern int SetMemoryBuffer(IntPtr player, IntPtr data, int size); + [DllImport(Libraries.Player, EntryPoint = "player_get_state")] + internal static extern int GetState(IntPtr player, out int state); - [DllImport(Libraries.Player, EntryPoint = "player_get_state")] - internal static extern int GetState(IntPtr player, out int state); + [DllImport(Libraries.Player, EntryPoint = "player_set_volume")] + internal static extern int SetVolume(IntPtr player, float left, float right); - [DllImport(Libraries.Player, EntryPoint = "player_set_volume")] - internal static extern int SetVolume(IntPtr player, float left, float right); + [DllImport(Libraries.Player, EntryPoint = "player_get_volume")] + internal static extern int GetVolume(IntPtr player, out float left, out float right); - [DllImport(Libraries.Player, EntryPoint = "player_get_volume")] - internal static extern int GetVolume(IntPtr player, out float left, out float right); + [DllImport(Libraries.Player, EntryPoint = "player_set_audio_policy_info")] + internal static extern int SetAudioPolicyInfo(IntPtr player, IntPtr streamInfo); - [DllImport(Libraries.Player, EntryPoint = "player_set_audio_policy_info")] - internal static extern int SetAudioPolicyInfo(IntPtr player, IntPtr stream_info); + [DllImport(Libraries.Player, EntryPoint = "player_set_audio_latency_mode")] + internal static extern int SetAudioLatencyMode(IntPtr player, int latencyMode); - [DllImport(Libraries.Player, EntryPoint = "player_set_audio_latency_mode")] - internal static extern int SetAudioLatencyMode(IntPtr player, int latency_mode); + [DllImport(Libraries.Player, EntryPoint = "player_get_audio_latency_mode")] + internal static extern int GetAudioLatencyMode(IntPtr player, out int latencyMode); - [DllImport(Libraries.Player, EntryPoint = "player_get_audio_latency_mode")] - internal static extern int GetAudioLatencyMode(IntPtr player, out int latency_mode); + [DllImport(Libraries.Player, EntryPoint = "player_get_play_position")] + internal static extern int GetPlayPosition(IntPtr player, out int millisecond); - [DllImport(Libraries.Player, EntryPoint = "player_get_play_position")] - internal static extern int GetPlayPosition(IntPtr player, out int millisecond); + [DllImport(Libraries.Player, EntryPoint = "player_set_play_position")] + internal static extern int SetPlayPosition(IntPtr player, int millisecond, bool accurate, SeekCompletedCallback cb, IntPtr userData); - [DllImport(Libraries.Player, EntryPoint = "player_set_play_position")] - internal static extern int SetPlayPosition(IntPtr player, int millisecond, bool accurate, SeekCompletedCallback cb, IntPtr userData); + [DllImport(Libraries.Player, EntryPoint = "player_set_mute")] + internal static extern int SetMute(IntPtr player, bool muted); - [DllImport(Libraries.Player, EntryPoint = "player_set_mute")] - internal static extern int SetMute(IntPtr player, bool muted); + [DllImport(Libraries.Player, EntryPoint = "player_is_muted")] + internal static extern int IsMuted(IntPtr player, out bool muted); - [DllImport(Libraries.Player, EntryPoint = "player_is_muted")] - internal static extern int IsMuted(IntPtr player, out bool muted); + [DllImport(Libraries.Player, EntryPoint = "player_set_looping")] + internal static extern int SetLooping(IntPtr player, bool looping); - [DllImport(Libraries.Player, EntryPoint = "player_set_looping")] - internal static extern int SetLooping(IntPtr player, bool looping); + [DllImport(Libraries.Player, EntryPoint = "player_is_looping")] + internal static extern int IsLooping(IntPtr player, out bool looping); - [DllImport(Libraries.Player, EntryPoint = "player_is_looping")] - internal static extern int IsLooping(IntPtr player, out bool looping); + [DllImport(Libraries.Player, EntryPoint = "player_set_completed_cb")] + internal static extern int SetCompletedCb(IntPtr player, PlaybackCompletedCallback callback, IntPtr userData); - [DllImport(Libraries.Player, EntryPoint = "player_set_completed_cb")] - internal static extern int SetCompletedCb(IntPtr player, PlaybackCompletedCallback callback, IntPtr user_data); + [DllImport(Libraries.Player, EntryPoint = "player_unset_completed_cb")] + internal static extern int UnsetCompletedCb(IntPtr player); - [DllImport(Libraries.Player, EntryPoint = "player_unset_completed_cb")] - internal static extern int UnsetCompletedCb(IntPtr player); + [DllImport(Libraries.Player, EntryPoint = "player_set_interrupted_cb")] + internal static extern int SetInterruptedCb(IntPtr player, PlaybackInterruptedCallback callback, IntPtr userData); - [DllImport(Libraries.Player, EntryPoint = "player_set_interrupted_cb")] - internal static extern int SetInterruptedCb(IntPtr player, PlaybackInterruptedCallback callback, IntPtr user_data); + [DllImport(Libraries.Player, EntryPoint = "player_unset_interrupted_cb")] + internal static extern int UnsetInterruptedCb(IntPtr player); - [DllImport(Libraries.Player, EntryPoint = "player_unset_interrupted_cb")] - internal static extern int UnsetInterruptedCb(IntPtr player); + [DllImport(Libraries.Player, EntryPoint = "player_set_error_cb")] + internal static extern int SetErrorCb(IntPtr player, PlaybackErrorCallback callback, IntPtr userData); - [DllImport(Libraries.Player, EntryPoint = "player_set_error_cb")] - internal static extern int SetErrorCb(IntPtr player, PlaybackErrorCallback callback, IntPtr user_data); + [DllImport(Libraries.Player, EntryPoint = "player_unset_error_cb")] + internal static extern int UnsetErrorCb(IntPtr player); - [DllImport(Libraries.Player, EntryPoint = "player_unset_error_cb")] - internal static extern int UnsetErrorCb(IntPtr player); + [DllImport(Libraries.Player, EntryPoint = "player_capture_video")] + internal static extern int CaptureVideo(IntPtr player, VideoCaptureCallback callback, IntPtr userData); - [DllImport(Libraries.Player, EntryPoint = "player_capture_video")] - internal static extern int CaptureVideo(IntPtr player, VideoCaptureCallback callback, IntPtr user_data); + [DllImport(Libraries.Player, EntryPoint = "player_set_media_packet_video_frame_decoded_cb")] + internal static extern int SetVideoFrameDecodedCb(IntPtr player, VideoFrameDecodedCallback callback, IntPtr userData); - //[DllImport(Libraries.Player, EntryPoint = "player_set_media_packet_video_frame_decoded_cb")] - //internal static extern int SetMediaPacketVideoFrameDecodedCb(IntPtr player, _videoFrameDecodedCallback callback, IntPtr user_data); + [DllImport(Libraries.Player, EntryPoint = "player_unset_media_packet_video_frame_decoded_cb")] + internal static extern int UnsetVideoFrameDecodedCb(IntPtr player); - [DllImport(Libraries.Player, EntryPoint = "player_unset_media_packet_video_frame_decoded_cb")] - internal static extern int UnsetMediaPacketVideoFrameDecodedCb(IntPtr player); + [DllImport(Libraries.Player, EntryPoint = "player_set_streaming_cookie")] + internal static extern int SetStreamingCookie(IntPtr player, string cookie, int size); - [DllImport(Libraries.Player, EntryPoint = "player_set_streaming_cookie")] - internal static extern int SetStreamingCookie(IntPtr player, string cookie, int size); + [DllImport(Libraries.Player, EntryPoint = "player_set_streaming_user_agent")] + internal static extern int SetStreamingUserAgent(IntPtr player, string userAgent, int size); - [DllImport(Libraries.Player, EntryPoint = "player_set_streaming_user_agent")] - internal static extern int SetStreamingUserAgent(IntPtr player, string user_agent, int size); + [DllImport(Libraries.Player, EntryPoint = "player_get_streaming_download_progress")] + internal static extern int GetStreamingDownloadProgress(IntPtr player, out int start, out int current); - [DllImport(Libraries.Player, EntryPoint = "player_get_streaming_download_progress")] - internal static extern int GetStreamingDownloadProgress(IntPtr player, out int start, out int current); + [DllImport(Libraries.Player, EntryPoint = "player_set_buffering_cb")] + internal static extern int SetBufferingCb(IntPtr player, BufferingProgressCallback callback, IntPtr userData); - [DllImport(Libraries.Player, EntryPoint = "player_set_buffering_cb")] - internal static extern int SetBufferingCb(IntPtr player, BufferingProgressCallback callback, IntPtr user_data); + [DllImport(Libraries.Player, EntryPoint = "player_unset_buffering_cb")] + internal static extern int UnsetBufferingCb(IntPtr player); - [DllImport(Libraries.Player, EntryPoint = "player_unset_buffering_cb")] - internal static extern int UnsetBufferingCb(IntPtr player); + [DllImport(Libraries.Player, EntryPoint = "player_set_playback_rate")] + internal static extern int SetPlaybackRate(IntPtr player, float rate); - [DllImport(Libraries.Player, EntryPoint = "player_set_progressive_download_path")] - internal static extern int SetProgressiveDownloadPath(IntPtr player, string path); + [DllImport(Libraries.Player, EntryPoint = "player_push_media_stream")] + internal static extern int PushMediaStream(IntPtr player, IntPtr packet); - [DllImport(Libraries.Player, EntryPoint = "player_get_progressive_download_status")] - internal static extern int GetProgressiveDownloadStatus(IntPtr player, out ulong current, out ulong total_size); + [DllImport(Libraries.Player, EntryPoint = "player_set_media_stream_info")] + internal static extern int SetMediaStreamInfo(IntPtr player, int type, IntPtr format); - [DllImport(Libraries.Player, EntryPoint = "player_set_progressive_download_message_cb")] - internal static extern int SetProgressiveDownloadMessageCb(IntPtr player, ProgressiveDownloadMessageCallback callback, IntPtr user_data); + [DllImport(Libraries.Player, EntryPoint = "player_set_media_stream_buffer_status_cb")] + internal static extern int SetMediaStreamBufferStatusCb(IntPtr player, int type, MediaStreamBufferStatusCallback callback, IntPtr userData); - [DllImport(Libraries.Player, EntryPoint = "player_unset_progressive_download_message_cb")] - internal static extern int UnsetProgressiveDownloadMessageCb(IntPtr player); + [DllImport(Libraries.Player, EntryPoint = "player_unset_media_stream_buffer_status_cb")] + internal static extern int UnsetMediaStreamBufferStatusCb(IntPtr player, int type); - [DllImport(Libraries.Player, EntryPoint = "player_set_playback_rate")] - internal static extern int SetPlaybackRate(IntPtr player, float rate); + [DllImport(Libraries.Player, EntryPoint = "player_set_media_stream_seek_cb")] + internal static extern int SetMediaStreamSeekCb(IntPtr player, int type, MediaStreamSeekCallback callback, IntPtr userData); - [DllImport(Libraries.Player, EntryPoint = "player_push_media_stream")] - internal static extern int PushMediaStream(IntPtr player, IntPtr packet); + [DllImport(Libraries.Player, EntryPoint = "player_unset_media_stream_seek_cb")] + internal static extern int UnsetMediaStreamSeekCb(IntPtr player, int type); - [DllImport(Libraries.Player, EntryPoint = "player_set_media_stream_info")] - internal static extern int SetMediaStreamInfo(IntPtr player, int type, IntPtr format); + [DllImport(Libraries.Player, EntryPoint = "player_set_media_stream_buffer_max_size")] + internal static extern int SetMediaStreamBufferMaxSize(IntPtr player, int type, ulong maxSize); - [DllImport(Libraries.Player, EntryPoint = "player_set_media_stream_buffer_status_cb")] - internal static extern int SetMediaStreamBufferStatusCb(IntPtr player, int type, BufferStatusCallback callback, IntPtr user_data); + [DllImport(Libraries.Player, EntryPoint = "player_get_media_stream_buffer_max_size")] + internal static extern int GetMediaStreamBufferMaxSize(IntPtr player, int type, out ulong maxSize); - [DllImport(Libraries.Player, EntryPoint = "player_unset_media_stream_buffer_status_cb")] - internal static extern int UnsetMediaStreamBufferStatusCb(IntPtr player, int type); + [DllImport(Libraries.Player, EntryPoint = "player_set_media_stream_buffer_min_threshold")] + internal static extern int SetMediaStreamBufferMinThreshold(IntPtr player, int type, uint percent); - [DllImport(Libraries.Player, EntryPoint = "player_set_media_stream_seek_cb")] - internal static extern int SetMediaStreamSeekCb(IntPtr player, int type, SeekOffsetChangedCallback callback, IntPtr user_data); + [DllImport(Libraries.Player, EntryPoint = "player_get_media_stream_buffer_min_threshold")] + internal static extern int GetMediaStreamBufferMinThreshold(IntPtr player, int type, out uint percent); - [DllImport(Libraries.Player, EntryPoint = "player_unset_media_stream_seek_cb")] - internal static extern int UnsetMediaStreamSeekCb(IntPtr player, int type); + [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_get_equalizer_bands_count")] + internal static extern int AudioEffectGetEqualizerBandsCount(IntPtr player, out int count); - [DllImport(Libraries.Player, EntryPoint = "player_set_media_stream_buffer_max_size")] - internal static extern int SetMediaStreamBufferMaxSize(IntPtr player, int type, ulong max_size); + [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_set_equalizer_band_level")] + internal static extern int AudioEffectSetEqualizerBandLevel(IntPtr player, int index, int level); - [DllImport(Libraries.Player, EntryPoint = "player_get_media_stream_buffer_max_size")] - internal static extern int GetMediaStreamBufferMaxSize(IntPtr player, int type, out ulong max_size); + [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_get_equalizer_band_level")] + internal static extern int AudioEffectGetEqualizerBandLevel(IntPtr player, int index, out int level); - [DllImport(Libraries.Player, EntryPoint = "player_set_media_stream_buffer_min_threshold")] - internal static extern int SetMediaStreamBufferMinThreshold(IntPtr player, int type, uint percent); + [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_set_equalizer_all_bands")] + internal static extern int AudioEffectSetEqualizerAllBands(IntPtr player, out int band_levels, int length); - [DllImport(Libraries.Player, EntryPoint = "player_get_media_stream_buffer_min_threshold")] - internal static extern int GetMediaStreamBufferMinThreshold(IntPtr player, int type, out uint percent); + [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_get_equalizer_level_range")] + internal static extern int AudioEffectGetEqualizerLevelRange(IntPtr player, out int min, out int max); - [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_get_equalizer_bands_count")] - internal static extern int AudioEffectGetEqualizerBandsCount(IntPtr player, out int count); + [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_get_equalizer_band_frequency")] + internal static extern int AudioEffectGetEqualizerBandFrequency(IntPtr player, int index, out int frequency); - [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_set_equalizer_band_level")] - internal static extern int AudioEffectSetEqualizerBandLevel(IntPtr player, int index, int level); + [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_get_equalizer_band_frequency_range")] + internal static extern int AudioEffectGetEqualizerBandFrequencyRange(IntPtr player, int index, out int range); - [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_get_equalizer_band_level")] - internal static extern int AudioEffectGetEqualizerBandLevel(IntPtr player, int index, out int level); + [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_equalizer_clear")] + internal static extern int AudioEffectEqualizerClear(IntPtr player); - [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_set_equalizer_all_bands")] - internal static extern int AudioEffectSetEqualizerAllBands(IntPtr player, out int band_levels, int length); + [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_equalizer_is_available")] + internal static extern int AudioEffectEqualizerIsAvailable(IntPtr player, out bool available); - [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_get_equalizer_level_range")] - internal static extern int AudioEffectGetEqualizerLevelRange(IntPtr player, out int min, out int max); + [DllImport(Libraries.Player, EntryPoint = "player_set_display_mode")] + internal static extern int SetDisplayMode(IntPtr player, int mode); - [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_get_equalizer_band_frequency")] - internal static extern int AudioEffectGetEqualizerBandFrequency(IntPtr player, int index, out int frequency); + [DllImport(Libraries.Player, EntryPoint = "player_get_display_mode")] + internal static extern int GetDisplayMode(IntPtr player, out int mode); - [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_get_equalizer_band_frequency_range")] - internal static extern int AudioEffectGetEqualizerBandFrequencyRange(IntPtr player, int index, out int range); + [DllImport(Libraries.Player, EntryPoint = "player_set_display_visible")] + internal static extern int SetDisplayVisible(IntPtr player, bool visible); - [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_equalizer_clear")] - internal static extern int AudioEffectEqualizerClear(IntPtr player); + [DllImport(Libraries.Player, EntryPoint = "player_is_display_visible")] + internal static extern int IsDisplayVisible(IntPtr player, out bool visible); - [DllImport(Libraries.Player, EntryPoint = "player_audio_effect_equalizer_is_available")] - internal static extern int AudioEffectEqualizerIsAvailable(IntPtr player, out bool available); + [DllImport(Libraries.Player, EntryPoint = "player_set_display_rotation")] + internal static extern int SetDisplayRotation(IntPtr player, int rotation); - [DllImport(Libraries.Player, EntryPoint = "player_set_display_mode")] - internal static extern int SetDisplayMode(IntPtr player, int mode); + [DllImport(Libraries.Player, EntryPoint = "player_get_display_rotation")] + internal static extern int GetDisplayRotation(IntPtr player, out int rotation); - [DllImport(Libraries.Player, EntryPoint = "player_get_display_mode")] - internal static extern int GetDisplayMode(IntPtr player, out int mode); + [DllImport(Libraries.Player, EntryPoint = "player_get_content_info")] + internal static extern int GetContentInfo(IntPtr player, int key, out IntPtr value); - [DllImport(Libraries.Player, EntryPoint = "player_set_display_visible")] - internal static extern int SetDisplayVisible(IntPtr player, bool visible); + [DllImport(Libraries.Player, EntryPoint = "player_get_codec_info")] + internal static extern int GetCodecInfo(IntPtr player, out IntPtr audioCodec, out IntPtr videoCodec); - [DllImport(Libraries.Player, EntryPoint = "player_is_display_visible")] - internal static extern int IsDisplayVisible(IntPtr player, out bool visible); + [DllImport(Libraries.Player, EntryPoint = "player_get_audio_stream_info")] + internal static extern int GetAudioStreamInfo(IntPtr player, out int sampleRate, out int channel, out int bitRate); - [DllImport(Libraries.Player, EntryPoint = "player_set_display_rotation")] - internal static extern int SetDisplayRotation(IntPtr player, int rotation); + [DllImport(Libraries.Player, EntryPoint = "player_get_video_stream_info")] + internal static extern int GetVideoStreamInfo(IntPtr player, out int fps, out int bitRate); - [DllImport(Libraries.Player, EntryPoint = "player_get_display_rotation")] - internal static extern int GetDisplayRotation(IntPtr player, out int rotation); + [DllImport(Libraries.Player, EntryPoint = "player_get_album_art")] + internal static extern int GetAlbumArt(IntPtr player, out IntPtr albumArt, out int size); - [DllImport(Libraries.Player, EntryPoint = "player_get_content_info")] - internal static extern int GetContentInfo(IntPtr player, int key, out IntPtr value); + [DllImport(Libraries.Player, EntryPoint = "player_get_video_size")] + internal static extern int GetVideoSize(IntPtr player, out int width, out int height); - [DllImport(Libraries.Player, EntryPoint = "player_get_codec_info")] - internal static extern int GetCodecInfo(IntPtr player, out IntPtr audio_codec, out IntPtr video_codec); + [DllImport(Libraries.Player, EntryPoint = "player_get_duration")] + internal static extern int GetDuration(IntPtr player, out int duration); - [DllImport(Libraries.Player, EntryPoint = "player_get_audio_stream_info")] - internal static extern int GetAudioStreamInfo(IntPtr player, out int sample_rate, out int channel, out int bit_rate); + [DllImport(Libraries.Player, EntryPoint = "player_set_subtitle_path")] + internal static extern int SetSubtitlePath(IntPtr player, string path); - [DllImport(Libraries.Player, EntryPoint = "player_get_video_stream_info")] - internal static extern int GetVideoStreamInfo(IntPtr player, out int fps, out int bit_rate); + [DllImport(Libraries.Player, EntryPoint = "player_set_subtitle_updated_cb")] + internal static extern int SetSubtitleUpdatedCb(IntPtr player, SubtitleUpdatedCallback callback, IntPtr userData); - [DllImport(Libraries.Player, EntryPoint = "player_get_album_art")] - internal static extern int GetAlbumArt(IntPtr player, out IntPtr album_art, out int size); + [DllImport(Libraries.Player, EntryPoint = "player_unset_subtitle_updated_cb")] + internal static extern int UnsetSubtitleUpdatedCb(IntPtr player); - [DllImport(Libraries.Player, EntryPoint = "player_get_video_size")] - internal static extern int GetVideoSize(IntPtr player, out int width, out int height); + [DllImport(Libraries.Player, EntryPoint = "player_set_subtitle_position_offset")] + internal static extern int SetSubtitlePositionOffset(IntPtr player, int millisecond); - [DllImport(Libraries.Player, EntryPoint = "player_get_duration")] - internal static extern int GetDuration(IntPtr player, out int duration); + [DllImport(Libraries.Player, EntryPoint = "player_set_video_stream_changed_cb")] + internal static extern int SetVideoStreamChangedCb(IntPtr player, VideoStreamChangedCallback callback, IntPtr userData); - [DllImport(Libraries.Player, EntryPoint = "player_set_subtitle_path")] - internal static extern int SetSubtitlePath(IntPtr player, string path); + [DllImport(Libraries.Player, EntryPoint = "player_unset_video_stream_changed_cb")] + internal static extern int UnsetVideoStreamChangedCb(IntPtr player); - [DllImport(Libraries.Player, EntryPoint = "player_set_subtitle_updated_cb")] - internal static extern int SetSubtitleUpdatedCb(IntPtr player, SubtitleUpdatedCallback callback, IntPtr user_data); + [DllImport(Libraries.Player, EntryPoint = "player_get_track_count")] + internal static extern int GetTrackCount(IntPtr player, int type, out int count); - [DllImport(Libraries.Player, EntryPoint = "player_unset_subtitle_updated_cb")] - internal static extern int UnsetSubtitleUpdatedCb(IntPtr player); + [DllImport(Libraries.Player, EntryPoint = "player_select_track")] + internal static extern int SelectTrack(IntPtr player, int type, int index); - [DllImport(Libraries.Player, EntryPoint = "player_set_subtitle_position_offset")] - internal static extern int SetSubtitlePositionOffset(IntPtr player, int millisecond); + [DllImport(Libraries.Player, EntryPoint = "player_get_current_track")] + internal static extern int GetCurrentTrack(IntPtr player, int type, out int index); - [DllImport(Libraries.Player, EntryPoint = "player_set_video_stream_changed_cb")] - internal static extern int SetVideoStreamChangedCb(IntPtr player, VideoStreamChangedCallback callback, IntPtr user_data); - - [DllImport(Libraries.Player, EntryPoint = "player_unset_video_stream_changed_cb")] - internal static extern int UnsetVideoStreamChangedCb(IntPtr player); - - [DllImport(Libraries.Player, EntryPoint = "player_get_track_count")] - internal static extern int GetTrackCount(IntPtr player, int type, out int count); - - [DllImport(Libraries.Player, EntryPoint = "player_select_track")] - internal static extern int SelectTrack(IntPtr player, int type, int index); - - [DllImport(Libraries.Player, EntryPoint = "player_get_current_track")] - internal static extern int GetCurrentTrack(IntPtr player, int type, out int index); - - [DllImport(Libraries.Player, EntryPoint = "player_get_track_language_code")] - internal static extern int GetTrackLanguageCode(IntPtr player, int type, int index, out string code); + [DllImport(Libraries.Player, EntryPoint = "player_get_track_language_code")] + internal static extern int GetTrackLanguageCode(IntPtr player, int type, int index, out IntPtr code); } } diff --git a/src/Tizen.Multimedia/MediaCodec/BufferStatusChangedEventArgs.cs b/src/Tizen.Multimedia/MediaCodec/BufferStatusChangedEventArgs.cs index ebbf589..6beac7c 100644 --- a/src/Tizen.Multimedia/MediaCodec/BufferStatusChangedEventArgs.cs +++ b/src/Tizen.Multimedia/MediaCodec/BufferStatusChangedEventArgs.cs @@ -23,27 +23,19 @@ namespace Tizen.Multimedia.MediaCodec /// public class BufferStatusChangedEventArgs : EventArgs { - private readonly MediaCodecStatus _status; - /// /// Initializes a new instance of the BufferStatusChangedEventArgs class. /// /// The value representing new status of the codec. public BufferStatusChangedEventArgs(MediaCodecStatus status) { - _status = status; + Status = status; } /// /// Gets the value indicating new status of the codec. /// - public MediaCodecStatus Status - { - get - { - return _status; - } - } + public MediaCodecStatus Status { get; } } } diff --git a/src/Tizen.Multimedia/MediaCodec/InputProcessedEventArgs.cs b/src/Tizen.Multimedia/MediaCodec/InputProcessedEventArgs.cs index 95fffb9..1883d95 100644 --- a/src/Tizen.Multimedia/MediaCodec/InputProcessedEventArgs.cs +++ b/src/Tizen.Multimedia/MediaCodec/InputProcessedEventArgs.cs @@ -24,28 +24,20 @@ namespace Tizen.Multimedia.MediaCodec /// public class InputProcessedEventArgs : EventArgs { - private readonly MediaPacket _packet; - /// /// Initializes a new instance of the InputProcessedEventArgs class. /// /// The packet that the codec has processed. - public InputProcessedEventArgs(MediaPacket packet) + internal InputProcessedEventArgs(MediaPacket packet) { Debug.Assert(packet != null); - _packet = packet; + Packet = packet; } /// /// Gets the packet that the codec has processed. /// - public MediaPacket Packet - { - get - { - return _packet; - } - } + public MediaPacket Packet { get; } } } diff --git a/src/Tizen.Multimedia/MediaCodec/MediaCodec.cs b/src/Tizen.Multimedia/MediaCodec/MediaCodec.cs index 03e6f83..c715d95 100644 --- a/src/Tizen.Multimedia/MediaCodec/MediaCodec.cs +++ b/src/Tizen.Multimedia/MediaCodec/MediaCodec.cs @@ -44,7 +44,7 @@ namespace Tizen.Multimedia.MediaCodec throw new InvalidOperationException("Not able to initialize a new media codec."); } - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } #region IDisposable-support @@ -151,7 +151,7 @@ namespace Tizen.Multimedia.MediaCodec var videoCodecList = new List(); var audioCodecList = new List(); - Interop.MediaCodec.SupportedCodecCallback cb = (int codecType, IntPtr arg) => + Interop.MediaCodec.SupportedCodecCallback cb = (codecType, _) => { if ((codecType & CodecKindMask) == CodecKindVideo) { @@ -175,7 +175,7 @@ namespace Tizen.Multimedia.MediaCodec int ret = Interop.MediaCodec.ForeachSupportedCodec(cb, IntPtr.Zero); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); _supportedVideoCodecs = videoCodecList.AsReadOnly(); _supportedAudioCodecs = audioCodecList.AsReadOnly(); @@ -204,7 +204,7 @@ namespace Tizen.Multimedia.MediaCodec throw new InvalidOperationException("Operation failed."); } - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } /// @@ -216,7 +216,7 @@ namespace Tizen.Multimedia.MediaCodec int ret = Interop.MediaCodec.Unprepare(_handle); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } /// @@ -280,14 +280,14 @@ namespace Tizen.Multimedia.MediaCodec int ret = Interop.MediaCodec.SetAudioEncoderInfo(_handle, format.SampleRate, format.Channel, format.Bit, format.BitRate); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } else { int ret = Interop.MediaCodec.SetAudioDecoderInfo(_handle, format.SampleRate, format.Channel, format.Bit); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } } @@ -309,13 +309,13 @@ namespace Tizen.Multimedia.MediaCodec int ret = Interop.MediaCodec.SetVideoEncoderInfo(_handle, format.Width, format.Height, format.FrameRate, format.BitRate / 1000); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } else { int ret = Interop.MediaCodec.SetVideoDecoderInfo(_handle, format.Width, format.Height); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } } @@ -333,7 +333,7 @@ namespace Tizen.Multimedia.MediaCodec { throw new NotSupportedException("The format is not supported."); } - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } /// @@ -361,7 +361,7 @@ namespace Tizen.Multimedia.MediaCodec throw new InvalidOperationException("The codec is in invalid state."); } - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } /// @@ -373,7 +373,7 @@ namespace Tizen.Multimedia.MediaCodec int ret = Interop.MediaCodec.FlushBuffers(_handle); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } /// @@ -421,7 +421,7 @@ namespace Tizen.Multimedia.MediaCodec int ret = Interop.MediaCodec.GetSupportedType(_handle, codecType, isEncoder, out value); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); return (MediaCodecTypes)value; } @@ -473,7 +473,7 @@ namespace Tizen.Multimedia.MediaCodec private void RegisterOutputAvailableCallback() { - _outputBufferAvailableCb = (IntPtr packetHandle, IntPtr arg) => + _outputBufferAvailableCb = (packetHandle, _) => { OutputAvailableEventArgs args = null; @@ -496,14 +496,14 @@ namespace Tizen.Multimedia.MediaCodec int ret = Interop.MediaCodec.SetOutputBufferAvaiableCb(_handle, _outputBufferAvailableCb, IntPtr.Zero); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } private void UnregisterOutputAvailableCallback() { int ret = Interop.MediaCodec.UnsetOutputBufferAvaiableCb(_handle); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } #endregion @@ -542,7 +542,7 @@ namespace Tizen.Multimedia.MediaCodec private void RegisterInputProcessed() { - _inputBufferUsedCb = (IntPtr lockedPacketHandle, IntPtr arg) => + _inputBufferUsedCb = (lockedPacketHandle, _) => { MediaPacket packet = null; @@ -560,25 +560,26 @@ namespace Tizen.Multimedia.MediaCodec int ret = Interop.MediaCodec.SetInputBufferUsedCb(_handle, _inputBufferUsedCb, IntPtr.Zero); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } private void UnregisterInputProcessed() { int ret = Interop.MediaCodec.UnsetInputBufferUsedCb(_handle); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } #endregion #region ErrorOccurred event - private EventHandler _errorOccurred; + private EventHandler _errorOccurred; private Interop.MediaCodec.ErrorCallback _errorCb; + // TODO replace /// /// Occurs whenever an error is produced in the codec. /// - public event EventHandler ErrorOccurred + public event EventHandler ErrorOccurred { add { @@ -605,34 +606,35 @@ namespace Tizen.Multimedia.MediaCodec private void RegisterErrorOccurred() { - _errorCb = (int errorCode, IntPtr arg) => + _errorCb = (errorCode, _) => { MediaCodecError error = (Enum.IsDefined(typeof(MediaCodecError), errorCode)) ? (MediaCodecError)errorCode : MediaCodecError.InternalError; - _errorOccurred?.Invoke(this, new ErrorOccurredEventArgs(error)); + _errorOccurred?.Invoke(this, new MediaCodecErrorOccurredEventArgs(error)); }; int ret = Interop.MediaCodec.SetErrorCb(_handle, _errorCb, IntPtr.Zero); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } private void UnregisterErrorOccurred() { int ret = Interop.MediaCodec.UnsetErrorCb(_handle); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } #endregion #region EosReached event - private EventHandler _eosReached; + private EventHandler _eosReached; private Interop.MediaCodec.EosCallback _eosCb; + // TODO replace /// /// Occurs when the codec processes all input data. /// - public event EventHandler EosReached + public event EventHandler EosReached { add { @@ -659,18 +661,18 @@ namespace Tizen.Multimedia.MediaCodec private void RegisterEosReached() { - _eosCb = (IntPtr arg) => _eosReached?.Invoke(this, new EosReachedEventArgs()); + _eosCb = _ => _eosReached?.Invoke(this, EventArgs.Empty); int ret = Interop.MediaCodec.SetEosCb(_handle, _eosCb, IntPtr.Zero); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } private void UnregisterEosReached() { int ret = Interop.MediaCodec.UnsetEosCb(_handle); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } #endregion @@ -708,7 +710,7 @@ namespace Tizen.Multimedia.MediaCodec private void RegisterBufferStatusChanged() { - _bufferStatusCb = (int statusCode, IntPtr arg) => + _bufferStatusCb = (statusCode, _) => { Debug.Assert(Enum.IsDefined(typeof(MediaCodecStatus), statusCode), $"{ statusCode } is not defined in MediaCodecStatus!"); @@ -719,14 +721,14 @@ namespace Tizen.Multimedia.MediaCodec int ret = Interop.MediaCodec.SetBufferStatusCb(_handle, _bufferStatusCb, IntPtr.Zero); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } private void UnregisterBufferStatusChanged() { int ret = Interop.MediaCodec.UnsetBufferStatusCb(_handle); - MediaCodecDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } #endregion } diff --git a/src/Tizen.Multimedia/MediaCodec/ErrorOccurredEventArgs.cs b/src/Tizen.Multimedia/MediaCodec/MediaCodecErrorOccurredEventArgs.cs similarity index 77% rename from src/Tizen.Multimedia/MediaCodec/ErrorOccurredEventArgs.cs rename to src/Tizen.Multimedia/MediaCodec/MediaCodecErrorOccurredEventArgs.cs index db54681..8311200 100644 --- a/src/Tizen.Multimedia/MediaCodec/ErrorOccurredEventArgs.cs +++ b/src/Tizen.Multimedia/MediaCodec/MediaCodecErrorOccurredEventArgs.cs @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - using System; namespace Tizen.Multimedia.MediaCodec @@ -21,28 +20,20 @@ namespace Tizen.Multimedia.MediaCodec /// /// Provides data for the event. /// - public class ErrorOccurredEventArgs : EventArgs + public class MediaCodecErrorOccurredEventArgs : EventArgs { - private readonly MediaCodecError _error; - /// /// Initializes a new instance of the ErrorOccurredEventArgs class. /// /// The value representing the type of the error. - public ErrorOccurredEventArgs(MediaCodecError error) + public MediaCodecErrorOccurredEventArgs(MediaCodecError error) { - _error = error; + Error = error; } /// /// Gets the value indicating what kind of the error. /// - public MediaCodecError Error - { - get - { - return _error; - } - } + public MediaCodecError Error { get; } } } diff --git a/src/Tizen.Multimedia/MediaCodec/OutputAvailableEventArgs.cs b/src/Tizen.Multimedia/MediaCodec/OutputAvailableEventArgs.cs index 2afd587..9c84828 100644 --- a/src/Tizen.Multimedia/MediaCodec/OutputAvailableEventArgs.cs +++ b/src/Tizen.Multimedia/MediaCodec/OutputAvailableEventArgs.cs @@ -24,22 +24,14 @@ namespace Tizen.Multimedia.MediaCodec /// The output packet needs to be disposed after it is used to clean up unmanaged resources. public class OutputAvailableEventArgs : EventArgs { - private readonly MediaPacket _packet; - internal OutputAvailableEventArgs(IntPtr packetHandle) { - _packet = MediaPacket.From(packetHandle); + Packet = MediaPacket.From(packetHandle); } /// /// Gets the result packet. /// - public MediaPacket Packet - { - get - { - return _packet; - } - } + public MediaPacket Packet { get; } } } diff --git a/src/Tizen.Multimedia/MediaController/CustomCommandEventArgs.cs b/src/Tizen.Multimedia/MediaController/CustomCommandEventArgs.cs index aace46f..80724d2 100755 --- a/src/Tizen.Multimedia/MediaController/CustomCommandEventArgs.cs +++ b/src/Tizen.Multimedia/MediaController/CustomCommandEventArgs.cs @@ -15,6 +15,7 @@ */ using System; +using Tizen.Applications; namespace Tizen.Multimedia.MediaController { @@ -29,15 +30,13 @@ namespace Tizen.Multimedia.MediaController { internal string _clientName; internal string _command; - internal IntPtr _bundle; - internal IntPtr _userData; + internal Bundle _bundle; - public CustomCommandEventArgs (string name, string command, IntPtr bundle, IntPtr userData) + public CustomCommandEventArgs (string name, string command, Bundle bundle) { _clientName = name; _command = command; _bundle = bundle; - _userData = userData; } /// @@ -68,25 +67,13 @@ namespace Tizen.Multimedia.MediaController /// Get bundle data. /// /// 0 - 100 - public IntPtr BundleData + public Bundle BundleData { get { return _bundle; } } - - /// - /// Get user data. - /// - /// 0 - 100 - public IntPtr UserData - { - get - { - return _userData; - } - } } } diff --git a/src/Tizen.Multimedia/MediaController/CommandReplyEventArgs.cs b/src/Tizen.Multimedia/MediaController/CustomCommandReplyEventArgs.cs similarity index 77% rename from src/Tizen.Multimedia/MediaController/CommandReplyEventArgs.cs rename to src/Tizen.Multimedia/MediaController/CustomCommandReplyEventArgs.cs index e9bdb1d..80e9344 100755 --- a/src/Tizen.Multimedia/MediaController/CommandReplyEventArgs.cs +++ b/src/Tizen.Multimedia/MediaController/CustomCommandReplyEventArgs.cs @@ -16,6 +16,7 @@ using System; +using Tizen.Applications; namespace Tizen.Multimedia.MediaController { @@ -26,19 +27,17 @@ namespace Tizen.Multimedia.MediaController /// /// CustomCommandRecieved event arguments /// - public class CommandReplyEventArgs : EventArgs + public class CustomCommandReplyEventArgs : EventArgs { internal string _serverName; internal int _result; - internal IntPtr _bundle; - internal IntPtr _userData; + internal Bundle _bundle; - public CommandReplyEventArgs (string serverName, int result, IntPtr bundle, IntPtr userData) + public CustomCommandReplyEventArgs (string serverName, int result, Bundle bundle) { _serverName = serverName; _result = result; _bundle = bundle; - _userData = userData; } /// @@ -69,25 +68,13 @@ namespace Tizen.Multimedia.MediaController /// Get bundle data. /// /// 0 - 100 - public IntPtr BundleData + public Bundle BundleData { get { return _bundle; } } - - /// - /// Get user data. - /// - /// 0 - 100 - public IntPtr UserData - { - get - { - return _userData; - } - } } } diff --git a/src/Tizen.Multimedia/MediaController/Client.cs b/src/Tizen.Multimedia/MediaController/MediaControllerClient.cs similarity index 87% rename from src/Tizen.Multimedia/MediaController/Client.cs rename to src/Tizen.Multimedia/MediaController/MediaControllerClient.cs index 7f7f809..fb7b47e 100755 --- a/src/Tizen.Multimedia/MediaController/Client.cs +++ b/src/Tizen.Multimedia/MediaController/MediaControllerClient.cs @@ -16,8 +16,9 @@ using System; using System.Collections.Generic; -using System.Threading; +using System.Runtime.InteropServices; using System.Threading.Tasks; +using Tizen.Applications; namespace Tizen.Multimedia.MediaController { @@ -43,8 +44,8 @@ namespace Tizen.Multimedia.MediaController private Interop.MediaControllerClient.ShuffleModeUpdatedCallback _shufflemodeUpdatedCallback; private EventHandler _repeatmodeUpdated; private Interop.MediaControllerClient.RepeatModeUpdatedCallback _repeatmodeUpdatedCallback; - private EventHandler _commandReply; - private Interop.MediaControllerClient.CommandReplyRecievedCallback _commandReplyCallback; + private EventHandler _customcommandReply; + private Interop.MediaControllerClient.CommandReplyRecievedCallback _customcommandReplyCallback; public MediaControllerClient () { @@ -202,27 +203,29 @@ namespace Tizen.Multimedia.MediaController /// /// CommandReply event is raised when reply for command is recieved /// - public event EventHandler CommandReply + public event EventHandler CustomCommandReply { add { - if(_commandReply == null) + if(_customcommandReply == null) { - _commandReplyCallback = (string serverName, int result, IntPtr bundle, IntPtr userData) => + _customcommandReplyCallback = (string serverName, int result, IntPtr bundle, IntPtr userData) => { - CommandReplyEventArgs eventArgs = new CommandReplyEventArgs(serverName, result, bundle, userData); - _commandReply?.Invoke(this, eventArgs); + SafeBundleHandle bundleHandle = new SafeBundleHandle(bundle, true); + Applications.Bundle _bundle = new Bundle(bundleHandle); + CustomCommandReplyEventArgs eventArgs = new CustomCommandReplyEventArgs(serverName, result, _bundle); + _customcommandReply?.Invoke(this, eventArgs); }; } - _commandReply += value; + _customcommandReply += value; } remove { - _commandReply -= value; - if(_commandReply == null) + _customcommandReply -= value; + if(_customcommandReply == null) { - _commandReplyCallback = null; + _customcommandReplyCallback = null; } } } @@ -242,14 +245,14 @@ namespace Tizen.Multimedia.MediaController MediaControllerErrorFactory.ThrowException(res, "Get Latest server failed"); } - ServerInformation _serverInfo = new ServerInformation (_name, (ServerState)_state); + ServerInformation _serverInfo = new ServerInformation (_name, (MediaControllerServerState)_state); return _serverInfo; } /// /// gets playback information for specific server /// Server Name - public Playback GetPlayback(String serverName) + public MediaControllerPlayback GetPlayback(String serverName) { MediaControllerError res = MediaControllerError.None; IntPtr _playbackHandle = IntPtr.Zero; @@ -261,14 +264,14 @@ namespace Tizen.Multimedia.MediaController MediaControllerErrorFactory.ThrowException(res, "Get Playback handle failed"); } - Playback _playback = new Playback (_playbackHandle); + MediaControllerPlayback _playback = new MediaControllerPlayback (_playbackHandle); return _playback; } /// /// gets metadata information for specific server /// Server Name - public Metadata GetMetadata(String serverName) + public MediaControllerMetadata GetMetadata(String serverName) { MediaControllerError res = MediaControllerError.None; IntPtr _metadataHandle = IntPtr.Zero; @@ -280,14 +283,14 @@ namespace Tizen.Multimedia.MediaController MediaControllerErrorFactory.ThrowException(res, "Get Playback handle failed"); } - Metadata _metadata = new Metadata (_metadataHandle); + MediaControllerMetadata _metadata = new MediaControllerMetadata (_metadataHandle); return _metadata; } /// /// gets shuffle mode for specific server /// Server Name - public ShuffleMode GetShuffleMode(String serverName) + public MediaControllerShuffleMode GetShuffleMode(String serverName) { MediaControllerError res = MediaControllerError.None; int _shuffleMode; @@ -298,13 +301,13 @@ namespace Tizen.Multimedia.MediaController MediaControllerErrorFactory.ThrowException(res, "Get Playback handle failed"); } - return (ShuffleMode)_shuffleMode; + return (MediaControllerShuffleMode)_shuffleMode; } /// /// gets repeat mode for specific server /// Server Name - public RepeatMode GetRepeatMode(String serverName) + public MediaControllerRepeatMode GetRepeatMode(String serverName) { MediaControllerError res = MediaControllerError.None; int _repeatMode; @@ -315,14 +318,14 @@ namespace Tizen.Multimedia.MediaController MediaControllerErrorFactory.ThrowException(res, "Get Playback handle failed"); } - return (RepeatMode)_repeatMode; + return (MediaControllerRepeatMode)_repeatMode; } /// /// Send command of playback state to server application /// Server Name /// Playback State - public void SendPlaybackStateCommand(string serverName, PlaybackState state) + public void SendPlaybackStateCommand(string serverName, MediaControllerPlaybackState state) { MediaControllerError res = MediaControllerError.None; res = (MediaControllerError)Interop.MediaControllerClient.SendPlaybackStateCommand(_handle, serverName, (int)state); @@ -339,14 +342,10 @@ namespace Tizen.Multimedia.MediaController /// Command /// Bundle data /// User Data - public void SendCustomCommand(string serverName, string command, IntPtr bundle, IntPtr userData) + public void SendCustomCommand(string serverName, string command, Bundle bundle) { MediaControllerError res = MediaControllerError.None; - if (_commandReply == null) { - res = (MediaControllerError)Interop.MediaControllerClient.SendCustomCommand(_handle, serverName, command, bundle, _commandReplyCallback, IntPtr.Zero); - } else { - res = (MediaControllerError)Interop.MediaControllerClient.SendCustomCommand(_handle, serverName, command, bundle, _commandReplyCallback, userData); - } + res = (MediaControllerError)Interop.MediaControllerClient.SendCustomCommand(_handle, serverName, command, bundle.SafeBundleHandle, _customcommandReplyCallback, IntPtr.Zero); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Send custom command failed" + res); @@ -358,7 +357,7 @@ namespace Tizen.Multimedia.MediaController /// Subscribe subscription type from specific server application /// Subscription Type /// Server Name - public void Subscribe(SubscriptionType type, string serverName) + public void Subscribe(MediaControllerSubscriptionType type, string serverName) { MediaControllerError res = MediaControllerError.None; res = (MediaControllerError)Interop.MediaControllerClient.Subscribe(_handle, (int)type, serverName); @@ -373,7 +372,7 @@ namespace Tizen.Multimedia.MediaController /// Subscribe subscription type from specific server application /// Subscription Type /// Server Name - public void Unsubscribe(SubscriptionType type, string serverName) + public void Unsubscribe(MediaControllerSubscriptionType type, string serverName) { MediaControllerError res = MediaControllerError.None; res = (MediaControllerError)Interop.MediaControllerClient.Unsubscribe(_handle, (int)type, serverName); @@ -399,7 +398,7 @@ namespace Tizen.Multimedia.MediaController /// /// gets subscribed server list /// Subscription Type - public Task> GetSubscribedServerList(SubscriptionType subscriptionType) + public Task> GetSubscribedServerList(MediaControllerSubscriptionType subscriptionType) { var task = new TaskCompletionSource>(); @@ -413,7 +412,7 @@ namespace Tizen.Multimedia.MediaController { _serverUpdatedCallback = (string serverName, int serverState, IntPtr userData) => { - ServerUpdatedEventArgs eventArgs = new ServerUpdatedEventArgs(serverName, (ServerState)serverState, userData); + ServerUpdatedEventArgs eventArgs = new ServerUpdatedEventArgs(serverName, (MediaControllerServerState)serverState); _serverUpdated?.Invoke(this, eventArgs); }; Interop.MediaControllerClient.SetServerUpdatedCb(_handle, _serverUpdatedCallback, IntPtr.Zero); @@ -428,7 +427,7 @@ namespace Tizen.Multimedia.MediaController { _playbackUpdatedCallback = (string serverName, IntPtr playback, IntPtr userData) => { - PlaybackUpdatedEventArgs eventArgs = new PlaybackUpdatedEventArgs(serverName, playback, userData); + PlaybackUpdatedEventArgs eventArgs = new PlaybackUpdatedEventArgs(serverName, playback); _playbackUpdated?.Invoke(this, eventArgs); }; Interop.MediaControllerClient.SetPlaybackUpdatedCb(_handle, _playbackUpdatedCallback, IntPtr.Zero); @@ -443,7 +442,7 @@ namespace Tizen.Multimedia.MediaController { _metadataUpdatedCallback = (string serverName, IntPtr metadata, IntPtr userData) => { - MetadataUpdatedEventArgs eventArgs = new MetadataUpdatedEventArgs(serverName, metadata, userData); + MetadataUpdatedEventArgs eventArgs = new MetadataUpdatedEventArgs(serverName, metadata); _metadataUpdated?.Invoke(this, eventArgs); }; Interop.MediaControllerClient.SetMetadataUpdatedCb(_handle, _metadataUpdatedCallback, IntPtr.Zero); @@ -459,7 +458,7 @@ namespace Tizen.Multimedia.MediaController MediaControllerError res = MediaControllerError.None; _shufflemodeUpdatedCallback = (string serverName, int shuffleMode, IntPtr userData) => { - ShuffleModeUpdatedEventArgs eventArgs = new ShuffleModeUpdatedEventArgs(serverName, (ShuffleMode)shuffleMode, userData); + ShuffleModeUpdatedEventArgs eventArgs = new ShuffleModeUpdatedEventArgs(serverName, (MediaControllerShuffleMode)shuffleMode); _shufflemodeUpdated?.Invoke(this, eventArgs); }; res = (MediaControllerError)Interop.MediaControllerClient.SetShuffleModeUpdatedCb(_handle, _shufflemodeUpdatedCallback, IntPtr.Zero); @@ -480,7 +479,7 @@ namespace Tizen.Multimedia.MediaController MediaControllerError res = MediaControllerError.None; _repeatmodeUpdatedCallback = (string serverName, int repeatMode, IntPtr userData) => { - RepeatModeUpdatedEventArgs eventArgs = new RepeatModeUpdatedEventArgs(serverName, (RepeatMode)repeatMode, userData); + RepeatModeUpdatedEventArgs eventArgs = new RepeatModeUpdatedEventArgs(serverName, (MediaControllerRepeatMode)repeatMode); _repeatmodeUpdated?.Invoke(this, eventArgs); }; res = (MediaControllerError)Interop.MediaControllerClient.SetRepeatModeUpdatedCb(_handle, _repeatmodeUpdatedCallback, IntPtr.Zero); diff --git a/src/Tizen.Multimedia/MediaController/MediaControllerEnums.cs b/src/Tizen.Multimedia/MediaController/MediaControllerEnums.cs index 117a284..d62fc67 100755 --- a/src/Tizen.Multimedia/MediaController/MediaControllerEnums.cs +++ b/src/Tizen.Multimedia/MediaController/MediaControllerEnums.cs @@ -22,7 +22,7 @@ namespace Tizen.Multimedia.MediaController /// /// Enumeration for server state /// - public enum ServerState + public enum MediaControllerServerState { /// /// Server state is unknown @@ -43,7 +43,7 @@ namespace Tizen.Multimedia.MediaController /// /// Enumeration for playback state /// - public enum PlaybackState + public enum MediaControllerPlaybackState { /// /// Playback state is unknown @@ -84,7 +84,7 @@ namespace Tizen.Multimedia.MediaController /// /// Enumeration for shuffle mode /// - public enum ShuffleMode + public enum MediaControllerShuffleMode { /// /// Shuffle mode is On @@ -100,7 +100,7 @@ namespace Tizen.Multimedia.MediaController /// /// Enumeration for repeat mode /// - public enum RepeatMode + public enum MediaControllerRepeatMode { /// /// Repeat mode is On @@ -116,7 +116,7 @@ namespace Tizen.Multimedia.MediaController /// /// Enumeration for repeat mode /// - public enum SubscriptionType + public enum MediaControllerSubscriptionType { /// /// Repeat mode is Off @@ -147,7 +147,7 @@ namespace Tizen.Multimedia.MediaController /// /// Enumeration for metadata attributes /// - internal enum Attributes + internal enum MediaControllerAttributes { /// /// Attribute is title @@ -170,6 +170,11 @@ namespace Tizen.Multimedia.MediaController Author, /// + /// Attribute is genre + /// + Genre, + + /// /// Attribute is duration /// Duration, diff --git a/src/Tizen.Multimedia/MediaController/Metadata.cs b/src/Tizen.Multimedia/MediaController/MediaControllerMetadata.cs similarity index 73% rename from src/Tizen.Multimedia/MediaController/Metadata.cs rename to src/Tizen.Multimedia/MediaController/MediaControllerMetadata.cs index 5898eaa..22fbab2 100755 --- a/src/Tizen.Multimedia/MediaController/Metadata.cs +++ b/src/Tizen.Multimedia/MediaController/MediaControllerMetadata.cs @@ -24,7 +24,7 @@ namespace Tizen.Multimedia.MediaController /// /// Metadata represents a metadata of media for server application to play /// - public class Metadata + public class MediaControllerMetadata { /// /// The title of media @@ -47,6 +47,11 @@ namespace Tizen.Multimedia.MediaController public string Author; /// + /// The genre of media + /// + public string Genre; + + /// /// The duration of media /// public string Duration; @@ -76,85 +81,90 @@ namespace Tizen.Multimedia.MediaController /// public string Picture; - internal Metadata(IntPtr _metadataHandle) { + public MediaControllerMetadata() + { + + } + + internal MediaControllerMetadata(IntPtr _metadataHandle) { MediaControllerError res = MediaControllerError.None; - res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)Attributes.Title, out Title); + res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)MediaControllerAttributes.Title, out Title); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Get Metadata failed" + res); MediaControllerErrorFactory.ThrowException(res, "Get Metadata failed"); } - res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)Attributes.Artist, out Artist); + res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)MediaControllerAttributes.Artist, out Artist); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Get Metadata failed" + res); MediaControllerErrorFactory.ThrowException(res, "Get Metadata failed"); } - res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)Attributes.Album, out Album); + res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)MediaControllerAttributes.Album, out Album); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Get Metadata failed" + res); MediaControllerErrorFactory.ThrowException(res, "Get Metadata failed"); } - res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)Attributes.Author, out Author); + res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)MediaControllerAttributes.Author, out Author); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Get Metadata failed" + res); MediaControllerErrorFactory.ThrowException(res, "Get Metadata failed"); } - res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)Attributes.Duration, out Duration); + res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)MediaControllerAttributes.Genre, out Genre); + if (res != MediaControllerError.None) + { + Log.Error(MediaControllerLog.LogTag, "Get Metadata failed" + res); + MediaControllerErrorFactory.ThrowException(res, "Get Metadata failed"); + } + + res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)MediaControllerAttributes.Duration, out Duration); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Get Metadata failed" + res); MediaControllerErrorFactory.ThrowException(res, "Get Metadata failed"); } - res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)Attributes.Date, out Date); + res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)MediaControllerAttributes.Date, out Date); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Get Metadata failed" + res); MediaControllerErrorFactory.ThrowException(res, "Get Metadata failed"); } - res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)Attributes.Copyright, out Copyright); + res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)MediaControllerAttributes.Copyright, out Copyright); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Get Metadata failed" + res); MediaControllerErrorFactory.ThrowException(res, "Get Metadata failed"); } - res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)Attributes.Description, out Description); + res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)MediaControllerAttributes.Description, out Description); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Get Metadata failed" + res); MediaControllerErrorFactory.ThrowException(res, "Get Metadata failed"); } - res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)Attributes.TrackNumber, out TrackNumber); + res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)MediaControllerAttributes.TrackNumber, out TrackNumber); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Get Metadata failed" + res); MediaControllerErrorFactory.ThrowException(res, "Get Metadata failed"); } - res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)Attributes.Picture, out Picture); + res = (MediaControllerError)Interop.MediaControllerClient.GetMetadata(_metadataHandle, (int)MediaControllerAttributes.Picture, out Picture); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Get Metadata failed" + res); MediaControllerErrorFactory.ThrowException(res, "Get Metadata failed"); } - - res = (MediaControllerError)Interop.MediaControllerClient.DestroyMetadata(_metadataHandle); - if(res != MediaControllerError.None) - { - Log.Error(MediaControllerLog.LogTag, "Destroy Metadata handle failed" + res); - MediaControllerErrorFactory.ThrowException(res, "Destroy Metadata handle failed"); - } } } } diff --git a/src/Tizen.Multimedia/MediaController/Playback.cs b/src/Tizen.Multimedia/MediaController/MediaControllerPlayback.cs similarity index 78% rename from src/Tizen.Multimedia/MediaController/Playback.cs rename to src/Tizen.Multimedia/MediaController/MediaControllerPlayback.cs index db6fc65..27e82d2 100755 --- a/src/Tizen.Multimedia/MediaController/Playback.cs +++ b/src/Tizen.Multimedia/MediaController/MediaControllerPlayback.cs @@ -22,14 +22,14 @@ namespace Tizen.Multimedia.MediaController /// /// Playback represents a playback state and playback position. /// - public class Playback + public class MediaControllerPlayback { - public Playback(PlaybackState state, ulong position) { + public MediaControllerPlayback(MediaControllerPlaybackState state, ulong position) { State = state; Position = position; } - internal Playback(IntPtr _playbackHandle) { + internal MediaControllerPlayback(IntPtr _playbackHandle) { MediaControllerError res = MediaControllerError.None; int _state = 0; ulong _position = 0L; @@ -48,20 +48,14 @@ namespace Tizen.Multimedia.MediaController MediaControllerErrorFactory.ThrowException(res, "Get Playback position failed"); } - res = (MediaControllerError)Interop.MediaControllerClient.DestroyPlayback(_playbackHandle); - if(res != MediaControllerError.None) - { - Log.Error(MediaControllerLog.LogTag, "Destroy Playback handle failed" + res); - MediaControllerErrorFactory.ThrowException(res, "Destroy Playback handle failed"); - } - State = (PlaybackState)_state; + State = (MediaControllerPlaybackState)_state; Position = _position; } /// /// The state of playback of media application /// - public PlaybackState State; + public MediaControllerPlaybackState State; /// /// The position of playback of media application diff --git a/src/Tizen.Multimedia/MediaController/Server.cs b/src/Tizen.Multimedia/MediaController/MediaControllerServer.cs similarity index 82% rename from src/Tizen.Multimedia/MediaController/Server.cs rename to src/Tizen.Multimedia/MediaController/MediaControllerServer.cs index 746893c..812b829 100755 --- a/src/Tizen.Multimedia/MediaController/Server.cs +++ b/src/Tizen.Multimedia/MediaController/MediaControllerServer.cs @@ -16,6 +16,8 @@ using System; +using System.Runtime.InteropServices; +using Tizen.Applications; namespace Tizen.Multimedia.MediaController { @@ -126,7 +128,7 @@ namespace Tizen.Multimedia.MediaController /// /// Update playback state and playback position /// playback state and playback position - public void UpdatePlayback(Playback playback) + public void UpdatePlayback(MediaControllerPlayback playback) { MediaControllerError res = MediaControllerError.None; res = (MediaControllerError)Interop.MediaControllerServer.SetPlaybackState(_handle, (int)playback.State); @@ -154,73 +156,80 @@ namespace Tizen.Multimedia.MediaController /// /// Update metadata information /// metadata information - public void UpdateMetadata(Metadata metadata) + public void UpdateMetadata(MediaControllerMetadata metadata) { MediaControllerError res = MediaControllerError.None; - res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)Attributes.Title, metadata.Title); + res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)MediaControllerAttributes.Title, metadata.Title); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Set Title failed" + res); MediaControllerErrorFactory.ThrowException(res, "Set Title failed"); } - res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)Attributes.Artist, metadata.Artist); + res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)MediaControllerAttributes.Artist, metadata.Artist); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Set Title failed" + res); MediaControllerErrorFactory.ThrowException(res, "Set Title failed"); } - res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)Attributes.Album, metadata.Album); + res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)MediaControllerAttributes.Album, metadata.Album); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Set Title failed" + res); MediaControllerErrorFactory.ThrowException(res, "Set Title failed"); } - res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)Attributes.Author, metadata.Author); + res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)MediaControllerAttributes.Author, metadata.Author); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Set Title failed" + res); MediaControllerErrorFactory.ThrowException(res, "Set Title failed"); - } - - res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)Attributes.Duration, metadata.Duration); + } + + res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)MediaControllerAttributes.Genre, metadata.Genre); + if (res != MediaControllerError.None) + { + Log.Error(MediaControllerLog.LogTag, "Set Title failed" + res); + MediaControllerErrorFactory.ThrowException(res, "Set Title failed"); + } + + res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)MediaControllerAttributes.Duration, metadata.Duration); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Set Title failed" + res); MediaControllerErrorFactory.ThrowException(res, "Set Title failed"); } - res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)Attributes.Date, metadata.Date); + res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)MediaControllerAttributes.Date, metadata.Date); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Set Title failed" + res); MediaControllerErrorFactory.ThrowException(res, "Set Title failed"); } - res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)Attributes.Copyright, metadata.Copyright); + res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)MediaControllerAttributes.Copyright, metadata.Copyright); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Set Title failed" + res); MediaControllerErrorFactory.ThrowException(res, "Set Title failed"); } - res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)Attributes.Description, metadata.Description); + res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)MediaControllerAttributes.Description, metadata.Description); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Set Title failed" + res); MediaControllerErrorFactory.ThrowException(res, "Set Title failed"); } - res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)Attributes.TrackNumber, metadata.TrackNumber); + res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)MediaControllerAttributes.TrackNumber, metadata.TrackNumber); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Set Title failed" + res); MediaControllerErrorFactory.ThrowException(res, "Set Title failed"); } - res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)Attributes.Picture, metadata.Picture); + res = (MediaControllerError)Interop.MediaControllerServer.SetMetadata(_handle, (int)MediaControllerAttributes.Picture, metadata.Picture); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Set Title failed" + res); @@ -238,7 +247,7 @@ namespace Tizen.Multimedia.MediaController /// /// Update shuffle mode /// shuffle mode - public void UpdateShuffleMode(ShuffleMode mode) + public void UpdateShuffleMode(MediaControllerShuffleMode mode) { MediaControllerError res = MediaControllerError.None; res = (MediaControllerError)Interop.MediaControllerServer.UpdateShuffleMode(_handle, (int)mode); @@ -252,14 +261,14 @@ namespace Tizen.Multimedia.MediaController /// /// Update repeat mode /// repeat mode - public void UpdateRepeatMode(RepeatMode mode) + public void UpdateRepeatMode(MediaControllerRepeatMode mode) { MediaControllerError res = MediaControllerError.None; - res = (MediaControllerError)Interop.MediaControllerServer.UpdateShuffleMode(_handle, (int)mode); + res = (MediaControllerError)Interop.MediaControllerServer.UpdateRepeatMode(_handle, (int)mode); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Update Repeat Mode failed" + res); - MediaControllerErrorFactory.ThrowException(res, "Repeat Shuffle Mode failed"); + MediaControllerErrorFactory.ThrowException(res, "Update Repeat Mode failed"); } } @@ -268,10 +277,10 @@ namespace Tizen.Multimedia.MediaController /// client name to recieve reply /// result to run command /// Bundle data - public void SendCommandReply(string clientName, int result, IntPtr bundle) + public void SendCustomCommandReply(string clientName, int result, Bundle bundle) { MediaControllerError res = MediaControllerError.None; - res = (MediaControllerError)Interop.MediaControllerServer.SendCommandReply (_handle, clientName, result, (IntPtr)bundle); + res = (MediaControllerError)Interop.MediaControllerServer.SendCommandReply (_handle, clientName, result, bundle.SafeBundleHandle); if(res != MediaControllerError.None) { Log.Error(MediaControllerLog.LogTag, "Send reply for command failed" + res); @@ -283,7 +292,7 @@ namespace Tizen.Multimedia.MediaController { _playbackCommandCallback = (string clientName, int state, IntPtr userData) => { - PlaybackStateCommandEventArgs eventArgs = new PlaybackStateCommandEventArgs(clientName, (PlaybackState)state, userData); + PlaybackStateCommandEventArgs eventArgs = new PlaybackStateCommandEventArgs(clientName, (MediaControllerPlaybackState)state); _playbackCommand?.Invoke(this, eventArgs); }; Interop.MediaControllerServer.SetPlaybackStateCmdRecvCb(_handle, _playbackCommandCallback, IntPtr.Zero); @@ -296,9 +305,11 @@ namespace Tizen.Multimedia.MediaController private void RegisterCustomCommandEvent() { - _customCommandCallback = (string clientName, string command, IntPtr bundleData, IntPtr userData) => + _customCommandCallback = (string clientName, string command, IntPtr bundle, IntPtr userData) => { - CustomCommandEventArgs eventArgs = new CustomCommandEventArgs(clientName, command, bundleData, userData); + SafeBundleHandle bundleHandle = new SafeBundleHandle(bundle, true); + Applications.Bundle _bundle = new Bundle(bundleHandle); + CustomCommandEventArgs eventArgs = new CustomCommandEventArgs(clientName, command, _bundle); _customCommand?.Invoke(this, eventArgs); }; Interop.MediaControllerServer.SetCustomCmdRecvCb(_handle, _customCommandCallback, IntPtr.Zero); diff --git a/src/Tizen.Multimedia/MediaController/MetadataUpdatedEventArgs.cs b/src/Tizen.Multimedia/MediaController/MetadataUpdatedEventArgs.cs index b4f8313..7706026 100755 --- a/src/Tizen.Multimedia/MediaController/MetadataUpdatedEventArgs.cs +++ b/src/Tizen.Multimedia/MediaController/MetadataUpdatedEventArgs.cs @@ -29,14 +29,12 @@ namespace Tizen.Multimedia.MediaController public class MetadataUpdatedEventArgs : EventArgs { internal string _serverName; - internal Metadata _metadata; - internal IntPtr _userData; + internal MediaControllerMetadata _metadata; - public MetadataUpdatedEventArgs (string name, IntPtr handle, IntPtr userData) + public MetadataUpdatedEventArgs (string name, IntPtr handle) { _serverName = name; - _metadata = new Metadata (handle); - _userData = userData; + _metadata = new MediaControllerMetadata (handle); } /// @@ -55,25 +53,13 @@ namespace Tizen.Multimedia.MediaController /// Get playback information. /// /// 0 - 100 - public Metadata Metadata + public MediaControllerMetadata Metadata { get { return _metadata; } } - - /// - /// Get user data. - /// - /// 0 - 100 - public IntPtr UserData - { - get - { - return _userData; - } - } } } diff --git a/src/Tizen.Multimedia/MediaController/PlaybackStateCommandEventArgs.cs b/src/Tizen.Multimedia/MediaController/PlaybackStateCommandEventArgs.cs index df8380e..d0f7e5d 100755 --- a/src/Tizen.Multimedia/MediaController/PlaybackStateCommandEventArgs.cs +++ b/src/Tizen.Multimedia/MediaController/PlaybackStateCommandEventArgs.cs @@ -29,14 +29,12 @@ namespace Tizen.Multimedia.MediaController public class PlaybackStateCommandEventArgs : EventArgs { internal string _clientName; - internal PlaybackState _state; - internal IntPtr _userData; + internal MediaControllerPlaybackState _state; - public PlaybackStateCommandEventArgs (string name, PlaybackState state, IntPtr userData) + public PlaybackStateCommandEventArgs (string name, MediaControllerPlaybackState state) { _clientName = name; _state = state; - _userData = userData; } /// @@ -55,25 +53,13 @@ namespace Tizen.Multimedia.MediaController /// Get playback state. /// /// 0 - 100 - public PlaybackState State + public MediaControllerPlaybackState State { get { return _state; } } - - /// - /// Get user data. - /// - /// 0 - 100 - public IntPtr UserData - { - get - { - return _userData; - } - } } } diff --git a/src/Tizen.Multimedia/MediaController/PlaybackUpdatedEventArgs.cs b/src/Tizen.Multimedia/MediaController/PlaybackUpdatedEventArgs.cs index de2f6c4..a1d3a9d 100755 --- a/src/Tizen.Multimedia/MediaController/PlaybackUpdatedEventArgs.cs +++ b/src/Tizen.Multimedia/MediaController/PlaybackUpdatedEventArgs.cs @@ -29,14 +29,12 @@ namespace Tizen.Multimedia.MediaController public class PlaybackUpdatedEventArgs : EventArgs { internal string _serverName; - internal Playback _playback; - internal IntPtr _userData; + internal MediaControllerPlayback _playback; - public PlaybackUpdatedEventArgs (string name, IntPtr handle, IntPtr userData) + public PlaybackUpdatedEventArgs (string name, IntPtr handle) { _serverName = name; - _playback = new Playback (handle); - _userData = userData; + _playback = new MediaControllerPlayback (handle); } /// @@ -55,25 +53,13 @@ namespace Tizen.Multimedia.MediaController /// Get playback information. /// /// 0 - 100 - public Playback PlaybackInfo + public MediaControllerPlayback PlaybackInfo { get { return _playback; } } - - /// - /// Get user data. - /// - /// 0 - 100 - public IntPtr UserData - { - get - { - return _userData; - } - } } } diff --git a/src/Tizen.Multimedia/MediaController/RepeatModeUpdatedEventArgs.cs b/src/Tizen.Multimedia/MediaController/RepeatModeUpdatedEventArgs.cs index 4c94283..ce784a7 100755 --- a/src/Tizen.Multimedia/MediaController/RepeatModeUpdatedEventArgs.cs +++ b/src/Tizen.Multimedia/MediaController/RepeatModeUpdatedEventArgs.cs @@ -29,14 +29,12 @@ namespace Tizen.Multimedia.MediaController public class RepeatModeUpdatedEventArgs : EventArgs { internal string _serverName; - internal RepeatMode _mode; - internal IntPtr _userData; + internal MediaControllerRepeatMode _mode; - public RepeatModeUpdatedEventArgs (string name, RepeatMode mode, IntPtr userData) + public RepeatModeUpdatedEventArgs (string name, MediaControllerRepeatMode mode) { _serverName = name; _mode = mode; - _userData = userData; } /// @@ -55,25 +53,13 @@ namespace Tizen.Multimedia.MediaController /// Get repeat mode. /// /// 0 - 100 - public RepeatMode RepeatMode + public MediaControllerRepeatMode RepeatMode { get { return _mode; } } - - /// - /// Get user data. - /// - /// 0 - 100 - public IntPtr UserData - { - get - { - return _userData; - } - } } } diff --git a/src/Tizen.Multimedia/MediaController/ServerInformation.cs b/src/Tizen.Multimedia/MediaController/ServerInformation.cs index c0aaa1b..37903b3 100755 --- a/src/Tizen.Multimedia/MediaController/ServerInformation.cs +++ b/src/Tizen.Multimedia/MediaController/ServerInformation.cs @@ -25,7 +25,7 @@ namespace Tizen.Multimedia.MediaController /// public class ServerInformation { - internal ServerInformation(string _name, ServerState _state) + internal ServerInformation(string _name, MediaControllerServerState _state) { Name = _name; State = _state; @@ -39,7 +39,7 @@ namespace Tizen.Multimedia.MediaController /// /// The state of server /// - public readonly ServerState State; + public readonly MediaControllerServerState State; } } diff --git a/src/Tizen.Multimedia/MediaController/ServerUpdatedEventArgs.cs b/src/Tizen.Multimedia/MediaController/ServerUpdatedEventArgs.cs index 7694182..e33de6b 100755 --- a/src/Tizen.Multimedia/MediaController/ServerUpdatedEventArgs.cs +++ b/src/Tizen.Multimedia/MediaController/ServerUpdatedEventArgs.cs @@ -28,16 +28,13 @@ namespace Tizen.Multimedia.MediaController public class ServerUpdatedEventArgs : EventArgs { internal ServerInformation _serverInfo; - internal ServerState _serverState; - internal IntPtr _userData; /// /// Constructor. /// - internal ServerUpdatedEventArgs(string name, ServerState state, IntPtr userData) + internal ServerUpdatedEventArgs(string name, MediaControllerServerState state) { _serverInfo = new ServerInformation (name, state); - _userData = userData; } /// @@ -51,18 +48,6 @@ namespace Tizen.Multimedia.MediaController return _serverInfo; } } - - /// - /// Get userData. - /// - /// 0 - 100 - public IntPtr userData - { - get - { - return _userData; - } - } } } diff --git a/src/Tizen.Multimedia/MediaController/ShuffleModeUpdatedEventArgs.cs b/src/Tizen.Multimedia/MediaController/ShuffleModeUpdatedEventArgs.cs index 4cb677a..5127a28 100755 --- a/src/Tizen.Multimedia/MediaController/ShuffleModeUpdatedEventArgs.cs +++ b/src/Tizen.Multimedia/MediaController/ShuffleModeUpdatedEventArgs.cs @@ -29,14 +29,12 @@ namespace Tizen.Multimedia.MediaController public class ShuffleModeUpdatedEventArgs : EventArgs { internal string _serverName; - internal ShuffleMode _mode; - internal IntPtr _userData; + internal MediaControllerShuffleMode _mode; - public ShuffleModeUpdatedEventArgs (string name, ShuffleMode mode, IntPtr userData) + public ShuffleModeUpdatedEventArgs (string name, MediaControllerShuffleMode mode) { _serverName = name; _mode = mode; - _userData = userData; } /// @@ -55,25 +53,13 @@ namespace Tizen.Multimedia.MediaController /// Get shuffle mode. /// /// 0 - 100 - public ShuffleMode ShuffleMode + public MediaControllerShuffleMode ShuffleMode { get { return _mode; } } - - /// - /// Get user data. - /// - /// 0 - 100 - public IntPtr UserData - { - get - { - return _userData; - } - } } } diff --git a/src/Tizen.Multimedia/MediaTool/MediaFormat.cs b/src/Tizen.Multimedia/MediaTool/MediaFormat.cs old mode 100644 new mode 100755 index 817d339..535662a --- a/src/Tizen.Multimedia/MediaTool/MediaFormat.cs +++ b/src/Tizen.Multimedia/MediaTool/MediaFormat.cs @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - using System; using System.Diagnostics; using Tizen.Internals.Errors; @@ -31,20 +30,15 @@ namespace Tizen.Multimedia /// A type for the format. internal MediaFormat(MediaFormatType type) { - _type = type; + Type = type; } - private readonly MediaFormatType _type; - /// /// Gets the type of the current format. /// public MediaFormatType Type { - get - { - return _type; - } + get; } /// @@ -64,7 +58,7 @@ namespace Tizen.Multimedia if (ret != (int)ErrorCode.InvalidOperation) { - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); switch ((MediaFormatType)type) { @@ -95,7 +89,7 @@ namespace Tizen.Multimedia IntPtr handle; int ret = Interop.MediaFormat.Create(out handle); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); AsNativeHandle(handle); @@ -131,7 +125,7 @@ namespace Tizen.Multimedia { throw new ArgumentException($"Invalid mime type value : { (int)mimeType }"); } - _mimeType = mimeType; + MimeType = mimeType; } /// @@ -147,41 +141,51 @@ namespace Tizen.Multimedia int ret = Interop.MediaFormat.GetContainerMimeType(handle, out mimeType); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); Debug.Assert(Enum.IsDefined(typeof(MediaFormatContainerMimeType), mimeType), "Invalid container mime type!"); - _mimeType = (MediaFormatContainerMimeType)mimeType; + MimeType = (MediaFormatContainerMimeType)mimeType; } - private readonly MediaFormatContainerMimeType _mimeType; - /// /// Gets the mime type of the current format. /// public MediaFormatContainerMimeType MimeType { - get - { - return _mimeType; - } + get; } protected override void AsNativeHandle(IntPtr handle) { Debug.Assert(Type == MediaFormatType.Container); - int ret = Interop.MediaFormat.SetContainerMimeType(handle, (int)_mimeType); + int ret = Interop.MediaFormat.SetContainerMimeType(handle, (int)MimeType); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } public override string ToString() { - return $"[{ nameof(ContainerMediaFormat) }] MimeType : { _mimeType }"; + return $"[{ nameof(ContainerMediaFormat) }] MimeType : { MimeType }"; } + 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; + } } /// @@ -258,11 +262,11 @@ namespace Tizen.Multimedia throw new ArgumentOutOfRangeException("Bit rate value can't be less than zero."); } - _mimeType = mimeType; - _width = width; - _height = height; - _frameRate = frameRate; - _bitRate = bitRate; + MimeType = mimeType; + Width = width; + Height = height; + FrameRate = frameRate; + BitRate = bitRate; } /// @@ -274,9 +278,20 @@ namespace Tizen.Multimedia { Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!"); - GetInfo(handle, out _width, out _height, out _bitRate, out _mimeType); + 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); + GetFrameRate(handle, out frameRate); + + MimeType = mimeType; + Width = width; + Height = height; + FrameRate = frameRate; + BitRate = bitRate; } /// @@ -298,7 +313,7 @@ namespace Tizen.Multimedia int ret = Interop.MediaFormat.GetVideoInfo(handle, out mimeTypeValue, out width, out height, out bitRate, out maxBps); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); mimeType = (MediaFormatVideoMimeType)mimeTypeValue; @@ -317,98 +332,75 @@ namespace Tizen.Multimedia int ret = Interop.MediaFormat.GetVideoFrameRate(handle, out frameRate); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } protected override void AsNativeHandle(IntPtr handle) { Debug.Assert(Type == MediaFormatType.Video); - int ret = Interop.MediaFormat.SetVideoMimeType(handle, (int)_mimeType); - MediaToolDebug.AssertNoError(ret); + int ret = Interop.MediaFormat.SetVideoMimeType(handle, (int)MimeType); + MultimediaDebug.AssertNoError(ret); - ret = Interop.MediaFormat.SetVideoWidth(handle, _width); - MediaToolDebug.AssertNoError(ret); + ret = Interop.MediaFormat.SetVideoWidth(handle, Width); + MultimediaDebug.AssertNoError(ret); - ret = Interop.MediaFormat.SetVideoHeight(handle, _height); - MediaToolDebug.AssertNoError(ret); + ret = Interop.MediaFormat.SetVideoHeight(handle, Height); + MultimediaDebug.AssertNoError(ret); - ret = Interop.MediaFormat.SetVideoAverageBps(handle, _bitRate); - MediaToolDebug.AssertNoError(ret); + ret = Interop.MediaFormat.SetVideoAverageBps(handle, BitRate); + MultimediaDebug.AssertNoError(ret); - ret = Interop.MediaFormat.SetVideoFrameRate(handle, _frameRate); - MediaToolDebug.AssertNoError(ret); + ret = Interop.MediaFormat.SetVideoFrameRate(handle, FrameRate); + MultimediaDebug.AssertNoError(ret); } - private readonly MediaFormatVideoMimeType _mimeType; - /// /// Gets the mime type of the current format. /// - public MediaFormatVideoMimeType MimeType - { - get - { - return _mimeType; - } - } - - private readonly int _width; + public MediaFormatVideoMimeType MimeType { get; } /// /// Gets the width value of the current format. /// - public int Width - { - get - { - return _width; - } - } - - private readonly int _height; + public int Width { get; } /// /// Gets the width value of the current format. /// - public int Height - { - get - { - return _height; - } - } - - private readonly int _frameRate; + public int Height { get; } /// /// Gets the frame rate value of the current format. /// - public int FrameRate - { - get - { - return _frameRate; - } - } - - private readonly int _bitRate; + public int FrameRate { get; } /// /// Gets the bit rate value of the current format. /// - public int BitRate + public int BitRate { get; } + + public override string ToString() { - get + return $"MimeType : { MimeType }, Width : { Width }, " + + $"Height : { Height }, FrameRate : { FrameRate }, BitRate : { BitRate }"; + } + + public override bool Equals(object obj) + { + var rhs = obj as VideoMediaFormat; + if (rhs == null) { - return _bitRate; + return false; } + + return MimeType == rhs.MimeType && Width == rhs.Width && Height == rhs.Height && + FrameRate == rhs.FrameRate && BitRate == rhs.BitRate; } - public override string ToString() + public override int GetHashCode() { - return $"[{ nameof(VideoMediaFormat) }] MimeType : { _mimeType }, Width : { _width }, " - + $"Height : { _height }, FrameRate : { _frameRate }, BitRate : { _bitRate }"; + return new { MimeType, Width, Height, FrameRate, BitRate }.GetHashCode(); } } @@ -485,12 +477,12 @@ namespace Tizen.Multimedia throw new ArgumentException("Aac is supported only with aac mime types."); } - _mimeType = mimeType; - _channel = channel; - _sampleRate = sampleRate; - _bit = bit; - _bitRate = bitRate; - _aacType = aacType; + MimeType = mimeType; + Channel = channel; + SampleRate = sampleRate; + Bit = bit; + BitRate = bitRate; + AacType = aacType; } /// @@ -502,17 +494,29 @@ namespace Tizen.Multimedia { Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!"); - GetInfo(handle, out _mimeType, out _channel, out _sampleRate, out _bit, out _bitRate); + 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)) + if (IsAacSupportedMimeType(mimeType)) { - GetAacType(handle, out _aacType); + GetAacType(handle, out aacType); } else { - _aacType = MediaFormatAacType.None; + aacType = MediaFormatAacType.None; } + MimeType = mimeType; + Channel = channel; + SampleRate = sampleRate; + Bit = bit; + BitRate = bitRate; + AacType = aacType; } /// @@ -547,7 +551,7 @@ namespace Tizen.Multimedia mimeType = (MediaFormatAudioMimeType)mimeTypeValue; - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); Debug.Assert(Enum.IsDefined(typeof(MediaFormatAudioMimeType), mimeType), "Invalid audio mime type!"); @@ -566,7 +570,7 @@ namespace Tizen.Multimedia int ret = Interop.MediaFormat.GetAudioAacType(handle, out aacTypeValue); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); aacType = (MediaFormatAacType)aacTypeValue; @@ -577,107 +581,75 @@ namespace Tizen.Multimedia { Debug.Assert(Type == MediaFormatType.Audio); - int ret = Interop.MediaFormat.SetAudioMimeType(handle, (int)_mimeType); - MediaToolDebug.AssertNoError(ret); + int ret = Interop.MediaFormat.SetAudioMimeType(handle, (int)MimeType); + MultimediaDebug.AssertNoError(ret); - ret = Interop.MediaFormat.SetAudioChannel(handle, _channel); - MediaToolDebug.AssertNoError(ret); + ret = Interop.MediaFormat.SetAudioChannel(handle, Channel); + MultimediaDebug.AssertNoError(ret); - ret = Interop.MediaFormat.SetAudioSampleRate(handle, _sampleRate); - MediaToolDebug.AssertNoError(ret); + ret = Interop.MediaFormat.SetAudioSampleRate(handle, SampleRate); + MultimediaDebug.AssertNoError(ret); - ret = Interop.MediaFormat.SetAudioBit(handle, _bit); - MediaToolDebug.AssertNoError(ret); + ret = Interop.MediaFormat.SetAudioBit(handle, Bit); + MultimediaDebug.AssertNoError(ret); - ret = Interop.MediaFormat.SetAudioAverageBps(handle, _bitRate); - MediaToolDebug.AssertNoError(ret); + ret = Interop.MediaFormat.SetAudioAverageBps(handle, BitRate); + MultimediaDebug.AssertNoError(ret); - ret = Interop.MediaFormat.SetAudioAacType(handle, (int)_aacType); - MediaToolDebug.AssertNoError(ret); + ret = Interop.MediaFormat.SetAudioAacType(handle, (int)AacType); + MultimediaDebug.AssertNoError(ret); } - private readonly MediaFormatAudioMimeType _mimeType; - /// /// Gets the mime type of the current format. /// - public MediaFormatAudioMimeType MimeType - { - get - { - return _mimeType; - } - } - - private readonly int _channel; + public MediaFormatAudioMimeType MimeType { get; } /// /// Gets the channel value of the current format. /// - public int Channel - { - get - { - return _channel; - } - } - - private readonly int _sampleRate; + public int Channel { get; } /// /// Gets the sample rate value of the current format. /// - public int SampleRate - { - get - { - return _sampleRate; - } - } - - private readonly int _bit; + public int SampleRate { get; } /// /// Gets the bit value of the current format. /// - public int Bit - { - get - { - return _bit; - } - } - - private readonly int _bitRate; + public int Bit { get; } /// /// Gets the bit rate value of the current format. /// - public int BitRate - { - get - { - return _bitRate; - } - } - - private readonly MediaFormatAacType _aacType; + public int BitRate { get; } /// /// Gets the aac type of the current format. /// - public MediaFormatAacType AacType + public MediaFormatAacType AacType { get; } + public override string ToString() + { + return $"MimeType : {MimeType }, Channel : { Channel }, SampleRate : { SampleRate }, " + + $"Bit : { Bit }, BitRate : { BitRate }, AacType : { AacType }"; + } + + public override bool Equals(object obj) { - get + var rhs = obj as AudioMediaFormat; + if (rhs == null) { - return _aacType; + return false; } + + return MimeType == rhs.MimeType && Channel == rhs.Channel && SampleRate == rhs.SampleRate && + Bit == rhs.Bit && BitRate == rhs.BitRate; } - public override string ToString() + public override int GetHashCode() { - return $"[{ nameof(AudioMediaFormat) }] MimeType : { _mimeType }, Channel : { _channel }, " - + $"SampleRate : { _sampleRate }, Bit : { _bit }, BitRate : { _bitRate }, AacType : { _aacType }"; + return new { MimeType, Channel, SampleRate, Bit, BitRate }.GetHashCode(); } } @@ -705,8 +677,8 @@ namespace Tizen.Multimedia { throw new ArgumentException($"Invalid text type value : { (int)textType }"); } - _mimeType = mimeType; - _textType = textType; + MimeType = mimeType; + TextType = textType; } /// @@ -718,7 +690,13 @@ namespace Tizen.Multimedia { Debug.Assert(handle != IntPtr.Zero, "The handle is invalid!"); - GetInfo(handle, out _mimeType, out _textType); + MediaFormatTextMimeType mimeType; + MediaFormatTextType textType; + + GetInfo(handle, out mimeType, out textType); + + MimeType = mimeType; + TextType = textType; } /// @@ -735,7 +713,7 @@ namespace Tizen.Multimedia int ret = Interop.MediaFormat.GetTextInfo(handle, out mimeTypeValue, out textTypeValue); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); mimeType = (MediaFormatTextMimeType)mimeTypeValue; textType = (MediaFormatTextType)textTypeValue; @@ -750,42 +728,42 @@ namespace Tizen.Multimedia { Debug.Assert(Type == MediaFormatType.Text); - int ret = Interop.MediaFormat.SetTextMimeType(handle, (int)_mimeType); - MediaToolDebug.AssertNoError(ret); + int ret = Interop.MediaFormat.SetTextMimeType(handle, (int)MimeType); + MultimediaDebug.AssertNoError(ret); - ret = Interop.MediaFormat.SetTextType(handle, (int)_textType); - MediaToolDebug.AssertNoError(ret); + ret = Interop.MediaFormat.SetTextType(handle, (int)TextType); + MultimediaDebug.AssertNoError(ret); } - private readonly MediaFormatTextMimeType _mimeType; - /// /// Gets the mime type of the current format. /// - public MediaFormatTextMimeType MimeType - { - get - { - return _mimeType; - } - } - - private readonly MediaFormatTextType _textType; + public MediaFormatTextMimeType MimeType { get; } /// /// Gets the text type of the current format. /// - public MediaFormatTextType TextType + public MediaFormatTextType TextType { get; } + + public override string ToString() { - get + return $"[{ nameof(TextMediaFormat) }] MimeType : { MimeType }, TextType : { TextType }"; + } + + public override bool Equals(object obj) + { + var rhs = obj as TextMediaFormat; + if (rhs == null) { - return _textType; + return false; } + + return MimeType == rhs.MimeType && TextType == rhs.TextType; } - public override string ToString() + public override int GetHashCode() { - return $"[{ nameof(TextMediaFormat) }] MimeType : { _mimeType }, TextType : { _textType }"; + return new { MimeType, TextType }.GetHashCode(); } } } diff --git a/src/Tizen.Multimedia/MediaTool/MediaFormatAacType.cs b/src/Tizen.Multimedia/MediaTool/MediaFormatAacType.cs index 05f37cd..2d34a9b 100644 --- a/src/Tizen.Multimedia/MediaTool/MediaFormatAacType.cs +++ b/src/Tizen.Multimedia/MediaTool/MediaFormatAacType.cs @@ -16,6 +16,9 @@ namespace Tizen.Multimedia { + /// + /// Specifies aac types for . + /// public enum MediaFormatAacType { None, diff --git a/src/Tizen.Multimedia/MediaTool/MediaFormatTextType.cs b/src/Tizen.Multimedia/MediaTool/MediaFormatTextType.cs index 9c1a2dc..d816e88 100644 --- a/src/Tizen.Multimedia/MediaTool/MediaFormatTextType.cs +++ b/src/Tizen.Multimedia/MediaTool/MediaFormatTextType.cs @@ -29,7 +29,7 @@ namespace Tizen.Multimedia /// /// The mp4 type. /// - Mp4, + MP4, /// /// The 3gp type. diff --git a/src/Tizen.Multimedia/MediaTool/MediaPacket.cs b/src/Tizen.Multimedia/MediaTool/MediaPacket.cs index 11f5f53..c31f541 100644 --- a/src/Tizen.Multimedia/MediaTool/MediaPacket.cs +++ b/src/Tizen.Multimedia/MediaTool/MediaPacket.cs @@ -36,7 +36,6 @@ namespace Tizen.Multimedia /// format is null. /// /// of the specified format is . - /// Out of memory. /// Operation failed. internal MediaPacket(MediaFormat format) { @@ -62,10 +61,10 @@ namespace Tizen.Multimedia { _handle = handle; - IntPtr formatHandle = IntPtr.Zero; + IntPtr formatHandle; int ret = Interop.MediaPacket.GetFormat(handle, out formatHandle); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); try { @@ -89,23 +88,22 @@ namespace Tizen.Multimedia /// Creates and initializes a native handle for the current object. /// /// The format to be set to the media format. - /// Out of memory. /// Operation failed. private void Initialize(MediaFormat format) { - IntPtr formatHandle = IntPtr.Zero; - if (format.Type == MediaFormatType.Container) { throw new ArgumentException("Creating a packet for container is not supported."); } + IntPtr formatHandle = IntPtr.Zero; + try { formatHandle = format.AsNativeHandle(); int ret = Interop.MediaPacket.Create(formatHandle, IntPtr.Zero, IntPtr.Zero, out _handle); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); Debug.Assert(_handle != IntPtr.Zero, "Created handle must not be null"); @@ -133,7 +131,6 @@ namespace Tizen.Multimedia /// /// Allocates internal buffer. /// - /// Out of memory. /// Operation failed. private void Alloc() { @@ -146,7 +143,7 @@ namespace Tizen.Multimedia switch (ret) { case ErrorCode.OutOfMemory: - throw new NotEnoughMemoryException("Failed to allocate buffer for the packet."); + throw new OutOfMemoryException("Failed to allocate buffer for the packet."); default: throw new InvalidOperationException("Failed to create a packet."); @@ -183,7 +180,7 @@ namespace Tizen.Multimedia ulong value = 0; int ret = Interop.MediaPacket.GetPts(_handle, out value); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); return value; } @@ -194,7 +191,7 @@ namespace Tizen.Multimedia int ret = Interop.MediaPacket.SetPts(_handle, value); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } } @@ -213,7 +210,7 @@ namespace Tizen.Multimedia ulong value = 0; int ret = Interop.MediaPacket.GetDts(_handle, out value); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); return value; } @@ -224,7 +221,7 @@ namespace Tizen.Multimedia int ret = Interop.MediaPacket.SetDts(_handle, value); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } } @@ -242,7 +239,7 @@ namespace Tizen.Multimedia bool value = false; int ret = Interop.MediaPacket.IsEncoded(_handle, out value); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); return value; } @@ -297,7 +294,7 @@ namespace Tizen.Multimedia ulong value = 0; int ret = Interop.MediaPacket.GetBufferSize(_handle, out value); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); Debug.Assert(value < int.MaxValue); @@ -322,7 +319,7 @@ namespace Tizen.Multimedia } int ret = Interop.MediaPacket.SetBufferSize(_handle, (ulong)value); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } } @@ -373,7 +370,7 @@ namespace Tizen.Multimedia int ret = Interop.MediaPacket.GetBufferFlags(_handle, out value); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); return (MediaPacketBufferFlags)value; } @@ -385,11 +382,11 @@ namespace Tizen.Multimedia int ret = Interop.MediaPacket.ResetBufferFlags(_handle); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); ret = Interop.MediaPacket.SetBufferFlags(_handle, (int)value); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } } @@ -520,7 +517,7 @@ namespace Tizen.Multimedia uint numberOfPlanes = 0; int ret = Interop.MediaPacket.GetNumberOfVideoPlanes(_handle, out numberOfPlanes); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); MediaPacketVideoPlane[] planes = new MediaPacketVideoPlane[numberOfPlanes]; @@ -540,16 +537,16 @@ namespace Tizen.Multimedia { Debug.Assert(_handle != IntPtr.Zero, "The handle is invalid!"); - IntPtr dataHandle = IntPtr.Zero; + IntPtr dataHandle; int ret = Interop.MediaPacket.GetBufferData(_handle, out dataHandle); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); Debug.Assert(dataHandle != IntPtr.Zero, "Data handle is invalid!"); int size = 0; ret = Interop.MediaPacket.GetAllocatedBufferSize(_handle, out size); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); return new MediaPacketBuffer(this, dataHandle, size); } @@ -637,16 +634,16 @@ namespace Tizen.Multimedia { int ret = Interop.MediaPacket.SetExtra(_packet._handle, ptr); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); } private static IntPtr GetExtra(IntPtr handle) { - IntPtr value = IntPtr.Zero; + IntPtr value; int ret = Interop.MediaPacket.GetExtra(handle, out value); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); return value; } diff --git a/src/Tizen.Multimedia/MediaTool/MediaPacketVideoPlane.cs b/src/Tizen.Multimedia/MediaTool/MediaPacketVideoPlane.cs index f386bef..3291221 100644 --- a/src/Tizen.Multimedia/MediaTool/MediaPacketVideoPlane.cs +++ b/src/Tizen.Multimedia/MediaTool/MediaPacketVideoPlane.cs @@ -39,14 +39,14 @@ namespace Tizen.Multimedia _packet = packet; int ret = Interop.MediaPacket.GetVideoStrideWidth(packet.GetHandle(), index, out _strideWidth); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); ret = Interop.MediaPacket.GetVideoStrideWidth(packet.GetHandle(), index, out _strideHeight); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); - IntPtr dataHandle = IntPtr.Zero; + IntPtr dataHandle; ret = Interop.MediaPacket.GetVideoPlaneData(packet.GetHandle(), index, out dataHandle); - MediaToolDebug.AssertNoError(ret); + MultimediaDebug.AssertNoError(ret); _buffer = new MediaPacketBuffer(packet, dataHandle, _strideWidth * _strideHeight); } diff --git a/src/Tizen.Multimedia/MediaVision/BarcodeDetectorEngineConfiguration.cs b/src/Tizen.Multimedia/MediaVision/BarcodeDetectorEngineConfiguration.cs index 130754b..2c54e76 100755 --- a/src/Tizen.Multimedia/MediaVision/BarcodeDetectorEngineConfiguration.cs +++ b/src/Tizen.Multimedia/MediaVision/BarcodeDetectorEngineConfiguration.cs @@ -35,6 +35,7 @@ namespace Tizen.Multimedia public BarcodeDetectorEngineConfiguration() : base() { + TargetAttribute = _targetAttr; } /// diff --git a/src/Tizen.Multimedia/MediaVision/BarcodeGeneratorEngineConfiguration.cs b/src/Tizen.Multimedia/MediaVision/BarcodeGeneratorEngineConfiguration.cs index cb861bf..b90c645 100755 --- a/src/Tizen.Multimedia/MediaVision/BarcodeGeneratorEngineConfiguration.cs +++ b/src/Tizen.Multimedia/MediaVision/BarcodeGeneratorEngineConfiguration.cs @@ -39,6 +39,9 @@ namespace Tizen.Multimedia public BarcodeGeneratorEngineConfiguration() : base() { + TextAttribute = _textAttr; + FrontColor = _frontColor; + BackColor = _backColor; } /// diff --git a/src/Tizen.Multimedia/MediaVision/EngineConfiguration.cs b/src/Tizen.Multimedia/MediaVision/EngineConfiguration.cs index f4a44bb..18b7e39 100755 --- a/src/Tizen.Multimedia/MediaVision/EngineConfiguration.cs +++ b/src/Tizen.Multimedia/MediaVision/EngineConfiguration.cs @@ -51,27 +51,35 @@ namespace Tizen.Multimedia internal void Add(string key, T value) { - int ret = 0; object val = (object)value; - if (typeof(T) == typeof(double)) - { - ret = Interop.MediaVision.EngineConfig.SetDouble(_engineHandle, key, (double)val); - } - else if (typeof(T) == typeof(int)) - { - ret = Interop.MediaVision.EngineConfig.SetInt(_engineHandle, key, (int)val); - } - else if (typeof(T) == typeof(bool)) + + if (!_config.ContainsKey(key)) { - ret = Interop.MediaVision.EngineConfig.SetBool(_engineHandle, key, (bool)val); + _config.Add(key, val); } - else if (typeof(T) == typeof(string)) + else { - ret = Interop.MediaVision.EngineConfig.SetString(_engineHandle, key, (string)val); - } + int ret = 0; + if (typeof(T) == typeof(double)) + { + ret = Interop.MediaVision.EngineConfig.SetDouble(_engineHandle, key, (double)val); + } + else if (typeof(T) == typeof(int)) + { + ret = Interop.MediaVision.EngineConfig.SetInt(_engineHandle, key, (int)val); + } + else if (typeof(T) == typeof(bool)) + { + ret = Interop.MediaVision.EngineConfig.SetBool(_engineHandle, key, (bool)val); + } + else if (typeof(T) == typeof(string)) + { + ret = Interop.MediaVision.EngineConfig.SetString(_engineHandle, key, (string)val); + } - MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to add attribute"); - _config.Add(key, val); + MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to add attribute"); + _config[key] = val; + } } internal object Get(string key) @@ -87,19 +95,12 @@ namespace Tizen.Multimedia } } - /// - /// Releases any unmanaged resources used by this object. - /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } - /// - /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects. - /// - /// If true, disposes any disposable objects. If false, does not dispose disposable objects. protected virtual void Dispose(bool disposing) { if (_disposed) diff --git a/src/Tizen.Multimedia/MediaVision/FaceEngineConfiguration.cs b/src/Tizen.Multimedia/MediaVision/FaceEngineConfiguration.cs index e95438f..b5b4b66 100755 --- a/src/Tizen.Multimedia/MediaVision/FaceEngineConfiguration.cs +++ b/src/Tizen.Multimedia/MediaVision/FaceEngineConfiguration.cs @@ -51,6 +51,14 @@ namespace Tizen.Multimedia public FaceEngineConfiguration() : base() { + ModelFilePath = _faceDetectionModelFilePathValue; + ModelType = _faceRecognitionModelTypeValue; ; + MinimumHeight = _faceDetectionMinHeightValue; + MinimumWidth = _faceDetectionMinWidthValue; + RoiHeight = _faceDetectionRoiHeightValue; + RoiWidth = _faceDetectionRoiWidthValue; + RoiX = _faceDetectionRoiXValue; + RoiY = _faceDetectionRoiYValue; } /// diff --git a/src/Tizen.Multimedia/MediaVision/FaceRecognitionModel.cs b/src/Tizen.Multimedia/MediaVision/FaceRecognitionModel.cs index 3b487cd..8fd9c72 100755 --- a/src/Tizen.Multimedia/MediaVision/FaceRecognitionModel.cs +++ b/src/Tizen.Multimedia/MediaVision/FaceRecognitionModel.cs @@ -188,19 +188,12 @@ namespace Tizen.Multimedia MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to learn"); } - /// - /// Releases any unmanaged resources used by this object. - /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } - /// - /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects. - /// - /// If true, disposes any disposable objects. If false, does not dispose disposable objects. protected virtual void Dispose(bool disposing) { if (_disposed) diff --git a/src/Tizen.Multimedia/MediaVision/FaceRecognizer.cs b/src/Tizen.Multimedia/MediaVision/FaceRecognizer.cs index ed3bdcc..e793bfb 100755 --- a/src/Tizen.Multimedia/MediaVision/FaceRecognizer.cs +++ b/src/Tizen.Multimedia/MediaVision/FaceRecognizer.cs @@ -66,6 +66,12 @@ namespace Tizen.Multimedia { try { + int faceLabel = 0; + if (faceLabelPtr != IntPtr.Zero) + { + faceLabel = Marshal.ReadInt32(faceLabelPtr); + } + Rectangle faceLocation = null; if (faceLocationPtr != IntPtr.Zero) { @@ -76,15 +82,9 @@ namespace Tizen.Multimedia Height = loc.height, Point = new Point(loc.x, loc.y) }; + Log.Info(MediaVisionLog.Tag, String.Format("Face label {0} recognized at : ({1}, {2}), Width : {3}, Height : {4}, confidence : {5}", faceLabel, faceLocation.Point.X, faceLocation.Point.Y, faceLocation.Width, faceLocation.Height, confidence)); } - int faceLabel = 0; - if (faceLabelPtr != IntPtr.Zero) - { - faceLabel = Marshal.ReadInt32(faceLabelPtr); - } - - Log.Info(MediaVisionLog.Tag, String.Format("Face label {0} recognized at : ({1}, {2}), Width : {3}, Height : {4}, confidence : {5}", faceLabel, faceLocation.Point.X, faceLocation.Point.Y, faceLocation.Width, faceLocation.Height, confidence)); FaceRecognitionResult result = new FaceRecognitionResult() { Location = faceLocation, diff --git a/src/Tizen.Multimedia/MediaVision/FaceTrackingModel.cs b/src/Tizen.Multimedia/MediaVision/FaceTrackingModel.cs index 93adb76..6efe545 100755 --- a/src/Tizen.Multimedia/MediaVision/FaceTrackingModel.cs +++ b/src/Tizen.Multimedia/MediaVision/FaceTrackingModel.cs @@ -118,19 +118,12 @@ namespace Tizen.Multimedia MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to save tracking model to file"); } - /// - /// Releases any unmanaged resources used by this object. - /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } - /// - /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects. - /// - /// If true, disposes any disposable objects. If false, does not dispose disposable objects. protected virtual void Dispose(bool disposing) { if (_disposed) diff --git a/src/Tizen.Multimedia/MediaVision/Image.cs b/src/Tizen.Multimedia/MediaVision/Image.cs index 8355906..0d0200c 100755 --- a/src/Tizen.Multimedia/MediaVision/Image.cs +++ b/src/Tizen.Multimedia/MediaVision/Image.cs @@ -147,19 +147,12 @@ namespace Tizen.Multimedia MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to save the image object"); } - /// - /// Releases any unmanaged resources used by this object. - /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } - /// - /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects. - /// - /// If true, disposes any disposable objects. If false, does not dispose disposable objects. protected virtual void Dispose(bool disposing) { if (_disposed) diff --git a/src/Tizen.Multimedia/MediaVision/ImageEngineConfiguration.cs b/src/Tizen.Multimedia/MediaVision/ImageEngineConfiguration.cs index 9d48821..e0c058f 100755 --- a/src/Tizen.Multimedia/MediaVision/ImageEngineConfiguration.cs +++ b/src/Tizen.Multimedia/MediaVision/ImageEngineConfiguration.cs @@ -49,7 +49,7 @@ namespace Tizen.Multimedia private int _imageTrackingHistoryAmountValue = 3; private double _imageTrackingExpectedOffsetValue = 0; private bool _imageTrackingUseStabilizationValue = true; - private double _imageTrackingStabilizationTolerantShiftValue; + private double _imageTrackingStabilizationTolerantShiftValue = 0.00006; private double _imageTrackingStabilizationSpeedValue = 0.3; private double _imageTrackingStabilizationAccelarationValue = 0.1; @@ -62,6 +62,19 @@ namespace Tizen.Multimedia public ImageEngineConfiguration() : base() { + ObjectScaleFactor = _imageRecognitionObjectScaleFactorValue; + ObjectMaxKeyPoints = _imageRecognitionObjectMaxKeypointsValue; + SceneScaleFactor = _imageRecognitionSceneScaleFactorValue; + SceneMaxKeyPoints = _imageRecognitionSceneMaxKeypointsValue; + MinKeyPointsMatches = _imageRecognitionMinKeypointsMatchValue; + RequiredMatchingPart = _imageRecognitionReqMatchPartValue; + TolerantPartMatchingError = _imageRecognitionTolerantPartMatchingErrorValue; + TrackingHistoryAmount = _imageTrackingHistoryAmountValue; + ExpectedTrackingOffset = _imageTrackingExpectedOffsetValue; + UseTrackingStabilization = _imageTrackingUseStabilizationValue; + TrackingStabilizationTolerantShift = _imageTrackingStabilizationTolerantShiftValue; + TrackingStabilizationSpeed = _imageTrackingStabilizationSpeedValue; + TrackingStabilizationAccelaration = _imageTrackingStabilizationAccelarationValue; } /// diff --git a/src/Tizen.Multimedia/MediaVision/ImageRecognitionResult.cs b/src/Tizen.Multimedia/MediaVision/ImageRecognitionResult.cs index 4668ce7..2bca0e7 100755 --- a/src/Tizen.Multimedia/MediaVision/ImageRecognitionResult.cs +++ b/src/Tizen.Multimedia/MediaVision/ImageRecognitionResult.cs @@ -14,22 +14,23 @@ * limitations under the License. */ +using System; using System.Collections.Generic; namespace Tizen.Multimedia { + /// + /// This class represents result of image recognition. + /// public class ImageRecognitionResult { - /// - /// This class represents result of image recognition operation. - /// internal ImageRecognitionResult() { } /// - /// The locations of image objects on the source image. + /// The indexes of recognized image objects and their locations on the source image. /// - public List Locations { get; internal set; } + public List> Results { get; internal set; } } } diff --git a/src/Tizen.Multimedia/MediaVision/ImageRecognizer.cs b/src/Tizen.Multimedia/MediaVision/ImageRecognizer.cs index 863c168..8a6042f 100755 --- a/src/Tizen.Multimedia/MediaVision/ImageRecognizer.cs +++ b/src/Tizen.Multimedia/MediaVision/ImageRecognizer.cs @@ -64,15 +64,20 @@ namespace Tizen.Multimedia { try { - List locations = new List(); + List> recognitionResults = new List>(); if (numberOfObjects > 0) { IntPtr[] imageLocationsPtr = new IntPtr[numberOfObjects]; Marshal.Copy(locationsPtr, imageLocationsPtr, 0, (int)numberOfObjects); - // Prepare list of locations + // Prepare list of locations and its indexes for (int i = 0; i < numberOfObjects; i++) { + if (imageLocationsPtr[i] == null) + { + continue; + } + Interop.MediaVision.Quadrangle location = (Interop.MediaVision.Quadrangle)Marshal.PtrToStructure(imageLocationsPtr[i], typeof(Interop.MediaVision.Quadrangle)); Quadrangle quadrangle = new Quadrangle() { @@ -85,13 +90,13 @@ namespace Tizen.Multimedia } }; Log.Info(MediaVisionLog.Tag, String.Format("Image recognized, Location : {0}", quadrangle.ToString())); - locations.Add(quadrangle); + recognitionResults.Add(Tuple.Create(i, quadrangle)); } } ImageRecognitionResult result = new ImageRecognitionResult() { - Locations = locations + Results = recognitionResults }; if (!tcsResult.TrySetResult(result)) diff --git a/src/Tizen.Multimedia/MediaVision/ImageTrackingModel.cs b/src/Tizen.Multimedia/MediaVision/ImageTrackingModel.cs index c59eed4..3cd6f53 100755 --- a/src/Tizen.Multimedia/MediaVision/ImageTrackingModel.cs +++ b/src/Tizen.Multimedia/MediaVision/ImageTrackingModel.cs @@ -110,19 +110,12 @@ namespace Tizen.Multimedia MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to save tracking model to file"); } - /// - /// Releases any unmanaged resources used by this object. - /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } - /// - /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects. - /// - /// If true, disposes any disposable objects. If false, does not dispose disposable objects. protected virtual void Dispose(bool disposing) { if (_disposed) diff --git a/src/Tizen.Multimedia/MediaVision/MediaVisionSource.cs b/src/Tizen.Multimedia/MediaVision/MediaVisionSource.cs index 8e3bdc5..44ca0e3 100755 --- a/src/Tizen.Multimedia/MediaVision/MediaVisionSource.cs +++ b/src/Tizen.Multimedia/MediaVision/MediaVisionSource.cs @@ -186,19 +186,12 @@ namespace Tizen.Multimedia MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to clear media source buffer"); } - /// - /// Releases any unmanaged resources used by this object. - /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } - /// - /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects. - /// - /// If true, disposes any disposable objects. If false, does not dispose disposable objects. protected virtual void Dispose(bool disposing) { if (_disposed) diff --git a/src/Tizen.Multimedia/MediaVision/SurveillanceEngineConfiguration.cs b/src/Tizen.Multimedia/MediaVision/SurveillanceEngineConfiguration.cs index 05b09dc..f167cac 100755 --- a/src/Tizen.Multimedia/MediaVision/SurveillanceEngineConfiguration.cs +++ b/src/Tizen.Multimedia/MediaVision/SurveillanceEngineConfiguration.cs @@ -39,6 +39,9 @@ namespace Tizen.Multimedia public SurveillanceEngineConfiguration() : base() { + FaceRecognitionModelFilePath = _faceRecognitionModelFilePathValue; + MovementDetectionThreshold = _movementDetectionThresholdValue; + SkipFramesCount = _skipFramesCountValue; } /// diff --git a/src/Tizen.Multimedia/MediaVision/SurveillanceEventTrigger.cs b/src/Tizen.Multimedia/MediaVision/SurveillanceEventTrigger.cs index 47e570a..e07ea01 100755 --- a/src/Tizen.Multimedia/MediaVision/SurveillanceEventTrigger.cs +++ b/src/Tizen.Multimedia/MediaVision/SurveillanceEventTrigger.cs @@ -56,6 +56,8 @@ namespace Tizen.Multimedia internal event EventHandler PersonAppearanceChangedEvent; internal event EventHandler MovementDetectedEvent; + private Interop.MediaVision.Surveillance.MvSurveillanceEventOccurredCallback eventOccurredCb; + /// /// Constructor of the SurveillanceEventTrigger class. /// @@ -153,7 +155,7 @@ namespace Tizen.Multimedia /// public void Subscribe(int videoStreamId, SurveillanceEngineConfiguration config = null) { - Interop.MediaVision.Surveillance.MvSurveillanceEventOccurredCallback eventOccurredCb = (IntPtr trigger, IntPtr source, int streamId, IntPtr eventResult, IntPtr userData) => + eventOccurredCb = (IntPtr trigger, IntPtr source, int streamId, IntPtr eventResult, IntPtr userData) => { Tizen.Log.Info(MediaVisionLog.Tag, string.Format("Surveillance event occurred, video stream id : {0}", streamId)); if (eventResult != null) @@ -212,19 +214,12 @@ namespace Tizen.Multimedia MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to push source"); } - /// - /// Releases any unmanaged resources used by this object. - /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } - /// - /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects. - /// - /// If true, disposes any disposable objects. If false, does not dispose disposable objects. protected virtual void Dispose(bool disposing) { if (_disposed) @@ -250,24 +245,27 @@ namespace Tizen.Multimedia int ret = Interop.MediaVision.Surveillance.GetResultCount(handle, _movementNumberOfRegionsKey, out count); MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get result count"); - resultPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle)) * count); - ret = Interop.MediaVision.Surveillance.GetResultValue(handle, _movementRegionsKey, resultPtr); - MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get result"); - - for (int i = 0; i < count; i++) + if (count > 0) { - Interop.MediaVision.Rectangle rect = (Interop.MediaVision.Rectangle)Marshal.PtrToStructure(resultPtr, typeof(Interop.MediaVision.Rectangle)); - regions.Add(new Rectangle() + resultPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle)) * count); + ret = Interop.MediaVision.Surveillance.GetResultValue(handle, _movementRegionsKey, resultPtr); + MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get result"); + + for (int i = 0; i < count; i++) { - Point = new Point() + Interop.MediaVision.Rectangle rect = (Interop.MediaVision.Rectangle)Marshal.PtrToStructure(resultPtr, typeof(Interop.MediaVision.Rectangle)); + regions.Add(new Rectangle() { - X = rect.x, - Y = rect.y - }, - Width = rect.width, - Height = rect.height - }); - resultPtr = IntPtr.Add(resultPtr, Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle))); + Point = new Point() + { + X = rect.x, + Y = rect.y + }, + Width = rect.width, + Height = rect.height + }); + resultPtr = IntPtr.Add(resultPtr, Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle))); + } } MovementDetectedEventArgs e = new MovementDetectedEventArgs() @@ -287,44 +285,47 @@ namespace Tizen.Multimedia int ret = Interop.MediaVision.Surveillance.GetResultCount(handle, _personsRecognizedNumberKey, out count); MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get result count"); - IntPtr locationPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle)) * count); - ret = Interop.MediaVision.Surveillance.GetResultValue(handle, _personsRecognizedLocationsKey, locationPtr); - MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get location"); - - IntPtr labelPtr = Marshal.AllocHGlobal(sizeof(int) * count); - ret = Interop.MediaVision.Surveillance.GetResultValue(handle, _personsRecognizedLabelsKey, labelPtr); - MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get label"); - int[] labelsArray = new int[count]; - Marshal.Copy(labelPtr, labelsArray, 0, count); - - IntPtr confidencePtr = Marshal.AllocHGlobal(sizeof(double) * count); - ret = Interop.MediaVision.Surveillance.GetResultValue(handle, _personsRecognizedConfidencesKey, confidencePtr); - MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get confidence"); - double[] confidencesArray = new double[count]; - Marshal.Copy(confidencePtr, confidencesArray, 0, count); - - for (int i = 0; i < count; i++) + if (count > 0) { - Interop.MediaVision.Rectangle rect = (Interop.MediaVision.Rectangle)Marshal.PtrToStructure(locationPtr, typeof(Interop.MediaVision.Rectangle)); - Rectangle location = new Rectangle() + IntPtr locationPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle)) * count); + ret = Interop.MediaVision.Surveillance.GetResultValue(handle, _personsRecognizedLocationsKey, locationPtr); + MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get location"); + + IntPtr labelPtr = Marshal.AllocHGlobal(sizeof(int) * count); + ret = Interop.MediaVision.Surveillance.GetResultValue(handle, _personsRecognizedLabelsKey, labelPtr); + MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get label"); + int[] labelsArray = new int[count]; + Marshal.Copy(labelPtr, labelsArray, 0, count); + + IntPtr confidencePtr = Marshal.AllocHGlobal(sizeof(double) * count); + ret = Interop.MediaVision.Surveillance.GetResultValue(handle, _personsRecognizedConfidencesKey, confidencePtr); + MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get confidence"); + double[] confidencesArray = new double[count]; + Marshal.Copy(confidencePtr, confidencesArray, 0, count); + + for (int i = 0; i < count; i++) { - Point = new Point() + Interop.MediaVision.Rectangle rect = (Interop.MediaVision.Rectangle)Marshal.PtrToStructure(locationPtr, typeof(Interop.MediaVision.Rectangle)); + Rectangle location = new Rectangle() { - X = rect.x, - Y = rect.y - }, - Width = rect.width, - Height = rect.height - }; - - result.Add(new PersonRecognitionResult() - { - Location = location, - Label = labelsArray[i], - Confidence = confidencesArray[i] - }); + Point = new Point() + { + X = rect.x, + Y = rect.y + }, + Width = rect.width, + Height = rect.height + }; + + result.Add(new PersonRecognitionResult() + { + Location = location, + Label = labelsArray[i], + Confidence = confidencesArray[i] + }); - locationPtr = IntPtr.Add(locationPtr, Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle))); + locationPtr = IntPtr.Add(locationPtr, Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle))); + } } PersonRecognizedEventArgs e = new PersonRecognizedEventArgs() @@ -347,73 +348,82 @@ namespace Tizen.Multimedia int ret = Interop.MediaVision.Surveillance.GetResultCount(handle, _personsAppearedNumber, out numOfAppearedPersons); MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get result"); - IntPtr appearedLocationPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle)) * numOfAppearedPersons); - ret = Interop.MediaVision.Surveillance.GetResultValue(handle, _personsAppearedLocations, appearedLocationPtr); - MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get result"); - - for (int i = 0; i < numOfAppearedPersons; i++) + if (numOfAppearedPersons > 0) { - Interop.MediaVision.Rectangle rect = (Interop.MediaVision.Rectangle)Marshal.PtrToStructure(appearedLocationPtr, typeof(Interop.MediaVision.Rectangle)); - appearedLocations.Add(new Rectangle() + IntPtr appearedLocationPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle)) * numOfAppearedPersons); + ret = Interop.MediaVision.Surveillance.GetResultValue(handle, _personsAppearedLocations, appearedLocationPtr); + MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get result"); + + for (int i = 0; i < numOfAppearedPersons; i++) { - Point = new Point() + Interop.MediaVision.Rectangle rect = (Interop.MediaVision.Rectangle)Marshal.PtrToStructure(appearedLocationPtr, typeof(Interop.MediaVision.Rectangle)); + appearedLocations.Add(new Rectangle() { - X = rect.x, - Y = rect.y - }, - Width = rect.width, - Height = rect.height - }); - - appearedLocationPtr = IntPtr.Add(appearedLocationPtr, Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle))); + Point = new Point() + { + X = rect.x, + Y = rect.y + }, + Width = rect.width, + Height = rect.height + }); + + appearedLocationPtr = IntPtr.Add(appearedLocationPtr, Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle))); + } } ret = Interop.MediaVision.Surveillance.GetResultCount(handle, _personsDisappearedNumber, out numOfDisappearedPersons); MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get result"); - IntPtr disAppearedLocationPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle)) * numOfDisappearedPersons); - ret = Interop.MediaVision.Surveillance.GetResultValue(handle, _personsDisappearedLocations, disAppearedLocationPtr); - MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get result"); - - for (int i = 0; i < numOfDisappearedPersons; i++) + if (numOfDisappearedPersons > 0) { - Interop.MediaVision.Rectangle rect = (Interop.MediaVision.Rectangle)Marshal.PtrToStructure(disAppearedLocationPtr, typeof(Interop.MediaVision.Rectangle)); - disappearedLocations.Add(new Rectangle() + IntPtr disAppearedLocationPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle)) * numOfDisappearedPersons); + ret = Interop.MediaVision.Surveillance.GetResultValue(handle, _personsDisappearedLocations, disAppearedLocationPtr); + MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get result"); + + for (int i = 0; i < numOfDisappearedPersons; i++) { - Point = new Point() + Interop.MediaVision.Rectangle rect = (Interop.MediaVision.Rectangle)Marshal.PtrToStructure(disAppearedLocationPtr, typeof(Interop.MediaVision.Rectangle)); + disappearedLocations.Add(new Rectangle() { - X = rect.x, - Y = rect.y - }, - Width = rect.width, - Height = rect.height - }); - - disAppearedLocationPtr = IntPtr.Add(disAppearedLocationPtr, Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle))); + Point = new Point() + { + X = rect.x, + Y = rect.y + }, + Width = rect.width, + Height = rect.height + }); + + disAppearedLocationPtr = IntPtr.Add(disAppearedLocationPtr, Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle))); + } } ret = Interop.MediaVision.Surveillance.GetResultCount(handle, _personsTrackedNumber, out numOfTrackedPersons); MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get result"); - IntPtr trackedLocationPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle)) * numOfTrackedPersons); - ret = Interop.MediaVision.Surveillance.GetResultValue(handle, _personsTrackedLocations, trackedLocationPtr); - MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get result"); - - for (int i = 0; i < numOfTrackedPersons; i++) + if (numOfTrackedPersons > 0) { - Interop.MediaVision.Rectangle rect = (Interop.MediaVision.Rectangle)Marshal.PtrToStructure(trackedLocationPtr, typeof(Interop.MediaVision.Rectangle)); - trackedLocations.Add(new Rectangle() + IntPtr trackedLocationPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle)) * numOfTrackedPersons); + ret = Interop.MediaVision.Surveillance.GetResultValue(handle, _personsTrackedLocations, trackedLocationPtr); + MediaVisionErrorFactory.CheckAndThrowException(ret, "Failed to get result"); + + for (int i = 0; i < numOfTrackedPersons; i++) { - Point = new Point() + Interop.MediaVision.Rectangle rect = (Interop.MediaVision.Rectangle)Marshal.PtrToStructure(trackedLocationPtr, typeof(Interop.MediaVision.Rectangle)); + trackedLocations.Add(new Rectangle() { - X = rect.x, - Y = rect.y - }, - Width = rect.width, - Height = rect.height - }); - - trackedLocationPtr = IntPtr.Add(trackedLocationPtr, Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle))); + Point = new Point() + { + X = rect.x, + Y = rect.y + }, + Width = rect.width, + Height = rect.height + }); + + trackedLocationPtr = IntPtr.Add(trackedLocationPtr, Marshal.SizeOf(typeof(Interop.MediaVision.Rectangle))); + } } PersonAppearanceChangedEventArgs e = new PersonAppearanceChangedEventArgs() diff --git a/src/Tizen.Multimedia/Player/AudioEffect.cs b/src/Tizen.Multimedia/Player/AudioEffect.cs index 09db778..a25cc67 100644 --- a/src/Tizen.Multimedia/Player/AudioEffect.cs +++ b/src/Tizen.Multimedia/Player/AudioEffect.cs @@ -1,158 +1,117 @@ -/// Audio effect -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ using System; -using System.Collections.Generic; -using System.Linq; - namespace Tizen.Multimedia { /// - /// Audio effect + /// Provides the ability to control the audio effects for . /// - /// - /// This class provides properties and API that are required for setting/getting - /// audio effects of a player. - /// public class AudioEffect { - internal IntPtr _playerHandle; - private List _bands; + private readonly EqualizerBand[] _bands; - internal AudioEffect() + internal AudioEffect(Player owner) { + Player = owner; + + bool available = false; + int ret = Interop.Player.AudioEffectEqualizerIsAvailable(Player.GetHandle(), out available); + PlayerErrorConverter.ThrowIfError(ret, "Failed to initialize the AudioEffect"); + + int count = 0; + ret = Interop.Player.AudioEffectGetEqualizerBandsCount(Player.GetHandle(), out count); + PlayerErrorConverter.ThrowIfError(ret, "Failed to initialize the AudioEffect"); + + int min = 0; + int max = 0; + ret = Interop.Player.AudioEffectGetEqualizerLevelRange(Player.GetHandle(), out min, out max); + PlayerErrorConverter.ThrowIfError(ret, "Failed to initialize the AudioEffect"); + + IsAvailable = available; + Count = count; + MinBandLevel = min; + MaxBandLevel = max; + + _bands = new EqualizerBand[count]; } /// - /// Set/Get Equalizer band level. - /// Get frequency and range. + /// Gets a at the specified index. /// - /// EqualizerBand - public IEnumerable EqualizerBands + /// The index of the band to get + /// The has already been disposed of. + /// + /// index is less than zero. + /// -or- + /// index is equal to or greater than . + /// + public EqualizerBand this[int index] { - set - { - int ret; - _bands = value.ToList(); - foreach(EqualizerBand band in _bands) - { - ret = Interop.Player.AudioEffectSetEqualizerBandLevel(_playerHandle, _bands.IndexOf(band), band.Level); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to set equalizer band" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Failed to set equalizer band"); - } - } - } get { - int ret; - int count = 0, level = 0, frequency = 0, range = 0; + Player.ValidateNotDisposed(); - if(_bands == null) - { - _bands = new List(); - } else + if (index < 0 || Count <= index) { - _bands.Clear(); + throw new ArgumentOutOfRangeException(nameof(index), index, + $"Valid index is 0 <= x < { nameof(Count) } "); } - ret = Interop.Player.AudioEffectGetEqualizerBandsCount(_playerHandle, out count); - if(ret == (int)PlayerError.None) - { - for(int idx = 0; idx < count; idx++) - { - ret = Interop.Player.AudioEffectGetEqualizerBandLevel(_playerHandle, idx, out level); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get equalizer band level"); - } - - ret = Interop.Player.AudioEffectGetEqualizerBandFrequency(_playerHandle, idx, out frequency); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get equalizer band frequency"); - } - - ret = Interop.Player.AudioEffectGetEqualizerBandFrequencyRange(_playerHandle, idx, out range); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get equalizer band frequency range"); - } - - EqualizerBand band = new EqualizerBand(level, frequency, range); - _bands.Add(band); - } - } else + if (_bands[index] == null) { - Log.Error(PlayerLog.LogTag, "Failed to get equalizer band count"); + _bands[index] = new EqualizerBand(this, index); } - - return _bands; + return _bands[index]; } } /// - /// Get Minimum Level of the bands in dB. + /// Clears the equalizer effect. /// - /// Minimum level - public int MinLevel + /// The has already been disposed of. + public void Clear() { - get - { - int min, max, ret; - ret = Interop.Player.AudioEffectGetEqualizerLevelRange(_playerHandle, out min, out max); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get min level" + (PlayerError)ret); - } - return min; - } + Player.ValidateNotDisposed(); + + PlayerErrorConverter.ThrowIfError(Interop.Player.AudioEffectEqualizerClear(Player.GetHandle()), + "Failed to clear equalizer effect"); } + public int Count{ get; } + + // TODO replace with range struct /// - /// Get Maximum Level of the bands in dB. + /// Get the minimum band level of the bands in dB. /// - /// Maximum level - public int MaxLevel - { - get - { - int min, max, ret; - ret = Interop.Player.AudioEffectGetEqualizerLevelRange(_playerHandle, out min, out max); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get max level" + (PlayerError)ret); - } - return max; - } - } + public int MinBandLevel { get; } /// - /// Get Equalizer Avaialbility. + /// Gets the maximum band level of the bands in dB. /// - /// true, false - public bool Available - { - get - { - bool available = false; - int ret = Interop.Player.AudioEffectEqualizerIsAvailable(_playerHandle, out available); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get equalizer availability" + (PlayerError)ret); - } - return available; - } - } + public int MaxBandLevel { get; } + + /// + /// Gets the value whether the AudioEffect is available or not. + /// + public bool IsAvailable { get; } + + /// + /// Gets the player that this AudioEffect belongs to. + /// + public Player Player { get; } } -} \ No newline at end of file +} diff --git a/src/Tizen.Multimedia/Player/BufferStatusEventArgs.cs b/src/Tizen.Multimedia/Player/BufferStatusEventArgs.cs deleted file mode 100644 index 86e6920..0000000 --- a/src/Tizen.Multimedia/Player/BufferStatusEventArgs.cs +++ /dev/null @@ -1,61 +0,0 @@ -/// This File contains BufferStatusEventArgs class -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - -using System; - -namespace Tizen.Multimedia -{ - - /// - /// BufferStatus event arguments - /// - /// - /// BufferStatus event arguments - /// - public class BufferStatusEventArgs : EventArgs - { - internal StreamingBufferStatus _status; - internal StreamType _streamType; - - /// - /// Constructor. - /// - internal BufferStatusEventArgs(StreamingBufferStatus status, StreamType type) - { - _status = status; - _streamType = type; - } - - /// - /// Get stream type. - /// - /// Audio, Video, Text - public StreamType StreamType - { - get - { - return _streamType; - } - } - - /// - /// Get buffering status. - /// - /// Underrun, Overflow - public StreamingBufferStatus Status - { - get - { - return _status; - } - } - } -} \ No newline at end of file diff --git a/src/Tizen.Multimedia/Player/BufferingProgressChangedEventArgs.cs b/src/Tizen.Multimedia/Player/BufferingProgressChangedEventArgs.cs index b52a01a..3203178 100644 --- a/src/Tizen.Multimedia/Player/BufferingProgressChangedEventArgs.cs +++ b/src/Tizen.Multimedia/Player/BufferingProgressChangedEventArgs.cs @@ -1,46 +1,41 @@ -/// This File contains BufferingProgressChangedEventArgs class -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - +/* + * 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 { - /// - /// BufferingProgress event arguments + /// Provides data for the event. /// - /// - /// BufferingProgress event arguments - /// - public class BufferingProgressEventArgs : EventArgs + public class BufferingProgressChangedEventArgs : EventArgs { - internal int _percent; - - /// - /// constructor - internal BufferingProgressEventArgs(int percent) - { - _percent = percent; - } + public BufferingProgressChangedEventArgs(int percent) + { + Percent = percent; + } - /// - /// Get buffering percentage. + /// + /// Gets the value indicating the buffering percentage. /// - /// 0 - 100 - public int Percent + /// The percentage of the buffering. + public int Percent { get; } + + public override string ToString() { - get - { - return _percent; - } + return $"Percent : { Percent }"; } } -} \ No newline at end of file +} diff --git a/src/Tizen.Multimedia/Player/CapturedFrame.cs b/src/Tizen.Multimedia/Player/CapturedFrame.cs new file mode 100644 index 0000000..b74bf32 --- /dev/null +++ b/src/Tizen.Multimedia/Player/CapturedFrame.cs @@ -0,0 +1,47 @@ +/* + * 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.Diagnostics; + +namespace Tizen.Multimedia +{ + //TODO we need a better name. + /// + /// Represents data for a video frame captured. + /// + public class CapturedFrame + { + internal CapturedFrame(byte[] imageBuffer, int width, int height) + { + Debug.Assert(imageBuffer != null, "imageBuffer is null!"); + Debug.Assert(width > 0, $"Width is invalid : {width}!"); + Debug.Assert(height > 0, $"height is invalid : {height}!"); + + Buffer = imageBuffer; + Size = new Size(width, height); + } + + /// + /// Gets the raw buffer of the captured image. + /// + /// The color space format is RGB888. + public byte[] Buffer { get; } + + /// + /// Gets the size. + /// + public Size Size { get; } + } +} diff --git a/src/Tizen.Multimedia/Player/Display.cs b/src/Tizen.Multimedia/Player/Display.cs deleted file mode 100644 index 0954b38..0000000 --- a/src/Tizen.Multimedia/Player/Display.cs +++ /dev/null @@ -1,112 +0,0 @@ -/// Display -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - -using System; - - -namespace Tizen.Multimedia -{ - /// - /// Display - /// - /// - /// This class provides properties and API that are required for setting - /// display configurations of a player. - /// - public class Display - { - internal IntPtr _playerHandle; - internal bool _isVisible; - internal DisplayMode _displayMode; - internal DisplayRotation _rotation; - - /// - /// Constructor - sets video display - /// display type - public Display(DisplayType displayType) - { - } - - /// - /// Set/Get Display mode. - /// - /// LetterBox, OriginalSize, FullScreen, CroppedFull, OriginalOrFull, DstRoi - public DisplayMode Mode - { - set - { - int ret = Interop.Player.SetDisplayMode(_playerHandle, (int)value); - if( ret == (int)PlayerError.None) - { - _displayMode = value; - } - else - { - Log.Error(PlayerLog.LogTag, "Setting display mode failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Setting display mode failed"); - } - } - get - { - return _displayMode; - } - } - - /// - /// Set/Get IsVisible. - /// - /// true, false - public bool IsVisible - { - set - { - int ret = Interop.Player.SetDisplayVisible(_playerHandle, value); - if(ret == (int)PlayerError.None) - { - _isVisible = value; - } - else - { - Log.Error(PlayerLog.LogTag, "Setting display visible failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Setting display visible failed"); - } - } - get - { - return _isVisible; - } - } - - /// - /// Set/Get Display rotation. - /// - /// RotationNone, Rotation90, Rotation180, Rotation270 - public DisplayRotation Rotation - { - set - { - int ret = Interop.Player.SetDisplayRotation(_playerHandle, (int)value); - if(ret == (int)PlayerError.None) - { - _rotation = value; - } else - { - Log.Error(PlayerLog.LogTag, "Setting display rotation failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Setting display rotation failed"); - } - } - get - { - return _rotation; - } - } - } -} \ No newline at end of file diff --git a/src/Tizen.Multimedia/Player/DownloadProgress.cs b/src/Tizen.Multimedia/Player/DownloadProgress.cs index a3793cd..1b25f30 100644 --- a/src/Tizen.Multimedia/Player/DownloadProgress.cs +++ b/src/Tizen.Multimedia/Player/DownloadProgress.cs @@ -1,59 +1,60 @@ -/// Download progress -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - -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. + */ namespace Tizen.Multimedia { /// - /// DownloadProgress + /// Represents data for a downloading status. /// - /// - /// Contains DownloadProgress of streaming playback. DownloadProgress object is null initially. - /// It is created only when playback starts. - /// - public class DownloadProgress + public struct DownloadProgress { - internal int _start; - internal int _current; - - internal DownloadProgress(int start, int current) + /// + /// Initialize a new instance of the DownloadProgress struct. + /// + /// The position that downloading started in percentage. + /// The position indicating the current downloading progress in percentage. + public DownloadProgress(int start, int current) { - _start = start; - _current = current; + Start = start; + Current = current; } /// - /// Get Start position in percentage. + /// Gets or sets the start position. /// - /// 0 to 100 + /// The position that downloading started in percentage. public int Start { - get - { - return _start; - } + get; + set; } /// - /// Get Current position in percentage. + /// Gets or sets the current position. /// - /// 0 to 100 + /// The position indicating the current downloading progress in percentage. public int Current { - get - { - return _current; - } + get; + set; + } + + public override string ToString() + { + return $"Start : { Start }, Current: { Current }"; } } -} \ No newline at end of file +} diff --git a/src/Tizen.Multimedia/Player/EqualizerBand.cs b/src/Tizen.Multimedia/Player/EqualizerBand.cs index 4635632..e64c87d 100644 --- a/src/Tizen.Multimedia/Player/EqualizerBand.cs +++ b/src/Tizen.Multimedia/Player/EqualizerBand.cs @@ -1,76 +1,102 @@ -/// Equalizer Band -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - +/* + * 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; namespace Tizen.Multimedia { /// - /// Equalizer band + /// Represents a equalizer band of . /// - /// - /// Contains Equalizer properties - /// public class EqualizerBand { - internal int _level; - internal int _frequency; - internal int _range; + private readonly AudioEffect _owner; + private readonly int _index; - internal EqualizerBand(int level, int frequency, int range) + internal EqualizerBand(AudioEffect owner, int index) { - _level = level; - _frequency = frequency; - _range = range; + Debug.Assert(owner != null); + + _owner = owner; + _index = index; + + int frequency = 0; + int range = 0; + + int ret = Interop.Player.AudioEffectGetEqualizerBandFrequency(_owner.Player.GetHandle(), _index, out frequency); + PlayerErrorConverter.ThrowIfError(ret, "Failed to initialize equalizer band"); + + ret = Interop.Player.AudioEffectGetEqualizerBandFrequencyRange(_owner.Player.GetHandle(), _index, out range); + PlayerErrorConverter.ThrowIfError(ret, "Failed to initialize equalizer band"); + + Frequency = frequency; + FrequencyRange = range; } /// - /// Set/Get new gain in decibel that is set to the given band [dB] + /// Sets the gain for the equalizer band. /// - /// int level - public int Level + /// The value indicating new gain in decibel(dB). + /// The player that this EqualuzerBand belongs to has already been disposed of. + /// + /// value is less than . + /// -or- + /// value is greater than . + /// + public void SetLevel(int value) { - set - { - _level = value; - } - get + _owner.Player.ValidateNotDisposed(); + + if (value < _owner.MinBandLevel || _owner.MaxBandLevel < value) { - return _level; + throw new ArgumentOutOfRangeException(nameof(value), value, + $"valid value range is { nameof(AudioEffect.MinBandLevel) } <= level <= { nameof(AudioEffect.MaxBandLevel) }. " + + $"but got {value}."); } + + int ret = Interop.Player.AudioEffectSetEqualizerBandLevel(_owner.Player.GetHandle(), _index, value); + PlayerErrorConverter.ThrowIfError(ret, "Failed to set the level of the equalizer band"); } /// - /// Get frequency of the given band [dB] . + /// Gets the gain for the equalizer band. /// - /// int frequency - public int Frequency + /// The player that this EqualuzerBand belongs to has already been disposed of. + public int GetLevel() { - get - { - return _frequency; - } + _owner.Player.ValidateNotDisposed(); + + int value = 0; + int ret = Interop.Player.AudioEffectGetEqualizerBandLevel(_owner.Player.GetHandle(), + _index, out value); + PlayerErrorConverter.ThrowIfError(ret, "Failed to initialize equalizer band"); + + return value; } /// - /// Get frequency range of the given band [dB]. + /// Gets the frequency in dB. /// - /// int range - public int Range - { - get - { - return _range; - } - } + public int Frequency { get; } + + /// + /// Gets the frequency range oin dB. + /// + public int FrequencyRange { get; } + } -} \ No newline at end of file +} diff --git a/src/Tizen.Multimedia/Player/MediaBufferSource.cs b/src/Tizen.Multimedia/Player/MediaBufferSource.cs index b19c929..f6329bc 100644 --- a/src/Tizen.Multimedia/Player/MediaBufferSource.cs +++ b/src/Tizen.Multimedia/Player/MediaBufferSource.cs @@ -1,36 +1,133 @@ -/// Media buffer source -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - +/* + * 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 { /// - /// The MediaBufferSource class used to set source to the player. + /// Represents a media source using memory. /// /// - /// MediaBufferSource object is created using buffer containing - /// media content. Then the object is set to the player as source. + /// The buffer has to be filled with appropriate data which means it must be well-formatted. + /// If you provide invalid data, you won't receive an error until is called. /// - public class MediaBufferSource : MediaSource + /// + public sealed class MediaBufferSource : MediaSource { - internal byte[] _buffer; + private byte[] _buffer; + + /// + /// Initialize a new instance of the MediaBufferSource class with an allocated buffer. + /// + /// The value indicating the size of the buffer. + /// + /// length is zero. + /// -or- + /// length is less than zero. + /// + public MediaBufferSource(int length) + { + if (length <= 0) + { + throw new ArgumentOutOfRangeException(nameof(length), length, + "length can't be equal to or less than zero."); + } + _buffer = new byte[length]; + } + + /// + /// Initialize a new instance of the MediaBufferSource class from the buffer. + /// + /// The source array to be copied into the buffer. + /// buffer is null. + public MediaBufferSource(byte[] buffer) : this(buffer, buffer == null ? 0 : buffer.Length) + { + } /// - /// Constructor - sets media buffer - /// source buffer - public MediaBufferSource(byte[] buffer) + /// Initialize a new instance of the MediaBufferSource class from the buffer + /// with the specified length and the specified offset. + /// + /// The source array to be copied into the buffer. + /// The value indicating the number of bytes to copy from the buffer. + /// The value indicating the offset in the buffer of the first byte to copy. + /// buffer is null. + /// + /// offset is less than zero. + /// -or- + /// length is equal to or less than zero. + /// -or- + /// offset+length is greater than buffer.Length. + /// + public MediaBufferSource(byte[] buffer, int length, int offset = 0) { - _buffer = buffer; + if (buffer == null) + { + throw new ArgumentNullException(nameof(buffer)); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException(nameof(offset), offset, "offset can't be less than zero."); + } + if (length <= 0) + { + throw new ArgumentOutOfRangeException(nameof(length), length, "length can't be equal to or less than zero."); + } + if (length + offset > buffer.Length) + { + throw new ArgumentOutOfRangeException($"length + offset can't be greater than the length of the { nameof(buffer) }."); + } + + _buffer = new byte[length]; + + Array.Copy(buffer, offset, _buffer, 0, length); } + private MediaBufferSource() + { + } + + /// + /// Create a MediaBufferSource that wraps a byte array. + /// + /// The array to be wrapped. + /// A MediaBufferSource wrapping the byte array. + public static MediaBufferSource Wrap(byte[] buffer) + { + if (buffer == null) + { + throw new ArgumentNullException(nameof(buffer)); + } + + MediaBufferSource source = new MediaBufferSource(); + source._buffer = buffer; + return source; + } + + /// + /// Gets the byte array of this buffer. + /// + public byte[] Buffer => _buffer; + + internal override void OnAttached(Player player) + { + // TODO test buffer if we need to use GCHandle + int ret = Interop.Player.SetMemoryBuffer(player.GetHandle(), _buffer, _buffer.Length); + PlayerErrorConverter.ThrowIfError(ret, "Failed to set the memory buffer"); + } } } diff --git a/src/Tizen.Multimedia/Player/MediaSource.cs b/src/Tizen.Multimedia/Player/MediaSource.cs index 2dc273e..b6ce203 100644 --- a/src/Tizen.Multimedia/Player/MediaSource.cs +++ b/src/Tizen.Multimedia/Player/MediaSource.cs @@ -1,28 +1,44 @@ -/// Mediasource -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - -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. + */ namespace Tizen.Multimedia { /// - /// The MediaSource class used to set source to the player. + /// MediaSource is a base class for sources. /// - /// - /// This is abstract class. Actual source classes - /// should inherit this class. - /// public abstract class MediaSource { + internal MediaSource() + { + } + + internal void AttachTo(Player player) + { + OnAttached(player); + } + + internal void DetachFrom(Player player) + { + OnDetached(player); + } + + internal abstract void OnAttached(Player player); + + internal virtual void OnDetached(Player player) + { + } } } diff --git a/src/Tizen.Multimedia/Player/MediaStreamBufferStatusChangedEventArgs.cs b/src/Tizen.Multimedia/Player/MediaStreamBufferStatusChangedEventArgs.cs new file mode 100644 index 0000000..7ce3130 --- /dev/null +++ b/src/Tizen.Multimedia/Player/MediaStreamBufferStatusChangedEventArgs.cs @@ -0,0 +1,45 @@ +/* + * 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 +{ + + /// + /// Provides data for the event. + /// + public class MediaStreamBufferStatusChangedEventArgs : EventArgs + { + /// + /// Initialize a new instance of the MediaStreamBufferStatusChangedEventArgs class. + /// + /// The value indicating the status of the stream. + public MediaStreamBufferStatusChangedEventArgs(MediaStreamBufferStatus status) + { + Status = status; + } + + /// + /// Gets the status. + /// + public MediaStreamBufferStatus Status { get; } + + public override string ToString() + { + return $"Status : { Status }"; + } + } +} diff --git a/src/Tizen.Multimedia/Player/MediaStreamConfiguration.cs b/src/Tizen.Multimedia/Player/MediaStreamConfiguration.cs index 451819d..2c301b6 100644 --- a/src/Tizen.Multimedia/Player/MediaStreamConfiguration.cs +++ b/src/Tizen.Multimedia/Player/MediaStreamConfiguration.cs @@ -1,176 +1,172 @@ -/// Media Stream configuration -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - +/* + * 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; namespace Tizen.Multimedia { /// - /// MediaStream configuration + /// Provides means to configure properties and handle events for . /// - /// - /// MediaStreamConfiguration class for media stream configuration. - /// - + /// public class MediaStreamConfiguration { - internal IntPtr _playerHandle; - internal StreamType _streamType; - #if _MEDIA_FORMAT_ - TODO: Uncomment this when MediaFormat is implemented. - private EventHandler _bufferStatusChanged; - private Interop.Player.BufferStatusCallback _bufferStatusChangedCallback; - private EventHandler _seekOffsetChanged; - private Interop.Player.SeekOffsetChangedCallback _seekOffsetChangedCallback; - #endif - - internal MediaStreamConfiguration() - { - } - - #if _MEDIA_FORMAT_ - TODO: Uncomment this when MediaFormat is implemented. + private const ulong DefaultBufferMaxSize = 200000; + private const uint DefaultBufferMinThreshold = 0; + + private readonly MediaStreamSource _owner; + private readonly StreamType _streamType; + + private ulong _bufferMaxSize = DefaultBufferMaxSize; + private uint _threshold = DefaultBufferMinThreshold; + + internal MediaStreamConfiguration(MediaStreamSource owner, StreamType streamType) + { + _owner = owner; + _streamType = streamType; + } + /// - /// BufferStatusChanged event is raised when buffer underrun or overflow occurs. + /// Occurs when the buffer underrun or overflow. /// - public event EventHandler BufferStatusChanged - { - add - { - if(_bufferStatusChanged == null) { - RegisterBufferStatusEvent(); - } - _bufferStatusChanged += value; - } - remove - { - _bufferStatusChanged -= value; - if(_bufferStatusChanged == null) { - UnregisterBufferStatusEvent(); - } - } - } + /// The event handler will be executed on an internal thread. + /// + /// + public event EventHandler BufferStatusChanged; /// - /// SeekOffsetChanged event is raised when seeking occurs. + /// Occurs when the seeking is requested. /// - public event EventHandler SeekOffsetChanged - { - add - { - if(_seekOffsetChanged == null) { - RegisterSeekOffsetChangedEvent(); - } - _seekOffsetChanged += value; - } - remove - { - _seekOffsetChanged -= value; - if(_seekOffsetChanged == null) { - UnregisterSeekOffsetChangedEvent(); - } - } - } - #endif + /// The event handler will be executed on an internal thread. + public event EventHandler SeekingOccurred; /// - /// max size bytes of buffer - /// Max size in bytes - public ulong BufferMaxSize - { - set - { - int ret = Interop.Player.SetMediaStreamBufferMaxSize(_playerHandle, (int)_streamType, value); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Set Buffer Max size failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Set Buffer Max size failed"); - } - - } - get - { - ulong size; - int ret = Interop.Player.GetMediaStreamBufferMaxSize(_playerHandle, (int)_streamType, out size); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Set Buffer Max size failed" + (PlayerError)ret); - } - return size; - } - } + /// Gets the max size of the buffer. + /// + /// The max size of the buffer. The default is 200000. + /// If the buffer level over the max size, will be raised with . + /// The is not assigned to a player. + /// value is zero. + /// + public ulong BufferMaxSize + { + get + { + return _bufferMaxSize; + } + set + { + if (_owner.Player == null) + { + throw new InvalidOperationException("The source is not assigned to a player yet."); + } + + Debug.Assert(_owner.Player.IsDisposed == false); + + if (value == 0UL) + { + throw new ArgumentOutOfRangeException(nameof(value), value, "the buffer max size can't be zero."); + } + + int ret = Interop.Player.SetMediaStreamBufferMaxSize(_owner.Player.GetHandle(), (int)_streamType, value); + + PlayerErrorConverter.ThrowIfError(ret, "Failed to set the buffer max size"); + + _bufferMaxSize = value; + } + } /// - /// Min threshold - /// min threshold in percent - public uint BufferMinThreshold - { - set - { - int ret = Interop.Player.SetMediaStreamBufferMinThreshold(_playerHandle, (int)_streamType, value); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Set Buffer Min threshold failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Set Buffer Min threshold failed"); - } - - } - get - { - uint percent; - int ret = Interop.Player.GetMediaStreamBufferMinThreshold(_playerHandle, (int)_streamType, out percent); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Get Buffer Min threshold failed" + (PlayerError)ret); - } - return percent; - } - } - - internal void SetHandle(IntPtr handle) - { - _playerHandle = handle; - } - - #if _MEDIA_FORMAT_ - TODO: Uncomment this when MediaFormat is implemented. - private void RegisterBufferStatusEvent() - { - _bufferStatusChangedCallback = (int status, IntPtr userData) => - { - BufferStatusEventArgs eventArgs = new BufferStatusEventArgs(); - _bufferStatusChanged?.Invoke(this, eventArgs); - }; - Interop.Player.SetMediaStreamBufferStatusCb(_playerHandle, _bufferStatusChangedCallback, IntPtr.Zero); - } - - private void UnregisterBufferStatusEvent() - { - Interop.Player.UnsetMediaStreamBufferStatusCb(_playerHandle); - } - - private void RegisterSeekOffsetChangedEvent() - { - _seekOffsetChangedCallback = (UInt64 offset, IntPtr userData) => - { - SeekOffsetEventArgs eventArgs = new SeekOffsetEventArgs(); - _seekOffsetChanged?.Invoke(this, eventArgs); - }; - Interop.Player.SetMediaStreamSeekCb(_playerHandle, _seekOffsetChangedCallback, IntPtr.Zero); - } - - private void UnregisterSeekOffsetChangedEvent() - { - Interop.Player.UnsetMediaStreamSeekCb(_playerHandle); - } - #endif - + /// Gets the min threshold of the buffer or zero if the is not assigned to a player. + /// + /// The minimum threshold of the buffer in percentage. The default is zero. + /// If the buffer level drops below the threshold value, will be raised with . + /// The is not assigned to a player. + /// value is greater than 100. + /// + public uint BufferMinThreshold + { + get + { + return _threshold; + } + set + { + if (_owner.Player == null) + { + throw new InvalidOperationException("The source is not assigned to a player yet."); + } + + Debug.Assert(_owner.Player.IsDisposed == false); + + if (100 < value) + { + throw new ArgumentOutOfRangeException(nameof(value), value, + $"The threshold can't be greater than 100, but got { value }."); + } + + int ret = Interop.Player.SetMediaStreamBufferMinThreshold(_owner.Player.GetHandle(), (int)_streamType, value); + PlayerErrorConverter.ThrowIfError(ret, "Failed to set the buffer minimum threshold"); + + _threshold = value; + } + } + + internal void OnPlayerSet(Player player) + { + if (_streamType == StreamType.Audio) + { + player.MediaStreamAudioSeekingOccurred += MediaStreamSeekingOccurred; + player.MediaStreamAudioBufferStatusChanged += MediaStreamBufferStatusChanged; + } + else + { + player.MediaStreamVideoSeekingOccurred += MediaStreamSeekingOccurred; + player.MediaStreamVideoBufferStatusChanged += MediaStreamBufferStatusChanged; + } + + int ret = Interop.Player.SetMediaStreamBufferMaxSize(player.GetHandle(), (int)_streamType, _bufferMaxSize); + PlayerErrorConverter.ThrowIfError(ret, "Failed to initialize the media stream configuration"); + + ret = Interop.Player.SetMediaStreamBufferMinThreshold(player.GetHandle(), (int)_streamType, _threshold); + PlayerErrorConverter.ThrowIfError(ret, "Failed to initialize the media stream configuration"); + } + + internal void OnPlayerUnset(Player player) + { + if (_streamType == StreamType.Audio) + { + player.MediaStreamAudioSeekingOccurred -= MediaStreamSeekingOccurred; + player.MediaStreamAudioBufferStatusChanged -= MediaStreamBufferStatusChanged; + } + else + { + player.MediaStreamVideoSeekingOccurred -= MediaStreamSeekingOccurred; + player.MediaStreamVideoBufferStatusChanged -= MediaStreamBufferStatusChanged; + } + } + + private void MediaStreamBufferStatusChanged(object sender, MediaStreamBufferStatusChangedEventArgs e) + { + BufferStatusChanged?.Invoke(this, e); + } + + private void MediaStreamSeekingOccurred(object sender, MediaStreamSeekingOccurredEventArgs e) + { + SeekingOccurred?.Invoke(this, e); + } } } diff --git a/src/Tizen.Multimedia/MediaTool/NotEnoughMemoryException.cs b/src/Tizen.Multimedia/Player/MediaStreamSeekingOccurredEventArgs.cs similarity index 56% rename from src/Tizen.Multimedia/MediaTool/NotEnoughMemoryException.cs rename to src/Tizen.Multimedia/Player/MediaStreamSeekingOccurredEventArgs.cs index 1a1870b..9e857e0 100644 --- a/src/Tizen.Multimedia/MediaTool/NotEnoughMemoryException.cs +++ b/src/Tizen.Multimedia/Player/MediaStreamSeekingOccurredEventArgs.cs @@ -13,22 +13,29 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - using System; namespace Tizen.Multimedia { /// - /// The exception that is thrown when there is no memory to allocate a new buffer for the packet. + /// Provides data for the event. /// - public class NotEnoughMemoryException : Exception + public class MediaStreamSeekingOccurredEventArgs : EventArgs { - /// - /// Initializes a new instance of the NotEnoughMemoryException class with a specified error message. + /// + /// Initialize a new instance of the MediaStreamSeekingOccurredEventArgs class. /// - /// Error description. - public NotEnoughMemoryException(string message) : base(message) + /// The value indicating the new position to seek. + public MediaStreamSeekingOccurredEventArgs(ulong offset) { + Offset = offset; } + + /// + /// Gets the offset. + /// + public ulong Offset { get; } + + public override string ToString() => $"Offset : { Offset }"; } } diff --git a/src/Tizen.Multimedia/Player/MediaStreamSource.cs b/src/Tizen.Multimedia/Player/MediaStreamSource.cs index 26a37f6..8cf472e 100644 --- a/src/Tizen.Multimedia/Player/MediaStreamSource.cs +++ b/src/Tizen.Multimedia/Player/MediaStreamSource.cs @@ -1,92 +1,281 @@ -/// Media Stream source -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; namespace Tizen.Multimedia { - /// - /// MediaStreamSource - /// - /// - /// MediaStreamSource class for media stream configuration. - /// - - public class MediaStreamSource : MediaSource - { - internal MediaStreamConfiguration _audioConfiguration; - internal MediaStreamConfiguration _videoConfiguration; - - /// - /// Constructor - public MediaStreamSource() - { - _audioConfiguration = new MediaStreamConfiguration(); - _videoConfiguration = new MediaStreamConfiguration(); - _audioConfiguration._streamType = StreamType.Audio; - _videoConfiguration._streamType = StreamType.Video; - } - - #if _MEDIA_FORMAT_ - TODO: Uncomment this when MediaFormat is implemented - /// - /// Get/Set Audio Media format. - /// - /// MediaFormat - //public MediaFormat AudioMediaFormat { get; set; } - - /// - /// Get/Set Video Media format. - /// - /// MediaFormat - //public MediaFormat VideoMediaFormat { get; set; } - #endif - - /// - /// Get/Set Audio configuration. - /// - /// MediaStreamConfiguration - public MediaStreamConfiguration AudioConfiguration - { - get - { - return _audioConfiguration; - } - } - - /// - /// Get/Set Video configuration. - /// - /// MediaStreamConfiguration - public MediaStreamConfiguration VideoConfiguration - { - get - { - return _videoConfiguration; - } - } - - #if _MEDIA_PACKET_ - /// - /// Push Media stream - /// media packet - /// TODO: Implement this when MediaPacket is ready - public void PushMediaStream(MediaPacket packet) - { - } - #endif - - internal void SetHandle(IntPtr handle) - { - _audioConfiguration.SetHandle(handle); - _videoConfiguration.SetHandle(handle); - } - } + + /// + /// Provides the ability to push packets as the source of + /// + /// The source must be set as a source to a player before pushing. + /// + // TODO is this name appropriate? + public sealed class MediaStreamSource : MediaSource + { + private readonly MediaFormat _audioMediaFormat; + private readonly MediaFormat _videoMediaFormat; + + public static IEnumerable SupportedAudioTypes + { + get + { + yield return MediaFormatAudioMimeType.Aac; + } + } + + public static IEnumerable SupportedVideoTypes + { + get + { + yield return MediaFormatVideoMimeType.H264SP; + } + } + + private Player _player; + + private MediaStreamConfiguration CreateAudioConfiguration(AudioMediaFormat format) + { + if( format == null ) + { + return null; + } + + if (!SupportedAudioTypes.Contains(format.MimeType)) + { + throw new ArgumentException($"The audio format is not supported, Type : {format.MimeType}."); + } + + return new MediaStreamConfiguration(this, StreamType.Audio); + } + + private MediaStreamConfiguration CreateVideoConfiguration(VideoMediaFormat format) + { + if (format == null) + { + return null; + } + + if (!SupportedVideoTypes.Contains(format.MimeType)) + { + throw new ArgumentException($"The video format is not supported, Type : {format.MimeType}."); + } + + return new MediaStreamConfiguration(this, StreamType.Video); + } + + + /// + /// Initialize a new instance of the MediaStreamSource class + /// with the specified and . + /// + /// The for this source. + /// The for this source. + /// AAC and H.264 are supported. + /// both and are null. + /// + /// is not supported. + /// -or- + /// is not supported. + /// + /// + /// + public MediaStreamSource(AudioMediaFormat audioMediaFormat, VideoMediaFormat videoMediaFormat) + { + if (audioMediaFormat == null && videoMediaFormat == null) + { + throw new ArgumentNullException(nameof(audioMediaFormat) + " and " + nameof(videoMediaFormat)); + } + + _audioMediaFormat = audioMediaFormat; + _videoMediaFormat = videoMediaFormat; + + AudioConfiguration = CreateAudioConfiguration(audioMediaFormat); + VideoConfiguration = CreateVideoConfiguration(videoMediaFormat); + } + + /// + /// Initialize a new instance of the MediaStreamSource class with the specified . + /// + /// The for this source. + /// AAC is supported. + /// is null. + /// is not supported. + /// + public MediaStreamSource(AudioMediaFormat audioMediaFormat) + { + if (audioMediaFormat == null) + { + throw new ArgumentNullException(nameof(audioMediaFormat)); + } + + _audioMediaFormat = audioMediaFormat; + + AudioConfiguration = CreateAudioConfiguration(audioMediaFormat); + } + /// + /// Initialize a new instance of the MediaStreamSource class with the specified . + /// + /// H.264 can is supported. + /// The for this source. + /// is null. + /// is not supported. + /// + public MediaStreamSource(VideoMediaFormat videoMediaFormat) + { + if (videoMediaFormat == null) + { + throw new ArgumentNullException(nameof(videoMediaFormat)); + } + + _videoMediaFormat = videoMediaFormat; + + VideoConfiguration = CreateVideoConfiguration(videoMediaFormat); + } + + /// + /// Gets the audio configuration or null if no AudioMediaFormat is specified in the constructor. + /// + public MediaStreamConfiguration AudioConfiguration { get; } + + /// + /// Gets the video configuration or null if no VideoMediaFormat is specified in the constructor. + /// + public MediaStreamConfiguration VideoConfiguration { get; } + + /// + /// Pushes elementary stream to decode audio or video. + /// + /// This source must be set as a source to a player and the player must be in the , or state. + /// The to decode. + /// + /// This source is not set as a source to a player. + /// -or- + /// The player is not in the valid state. + /// + /// packet is null. + /// packet has been disposed. + /// + /// is neither video nor audio type. + /// -or- + /// The format of packet is not matched with the specified format in the constructor. + /// + /// the internal buffer reaches limits. + /// + /// + /// + public void Push(MediaPacket packet) + { + if (_player == null) + { + throw new InvalidOperationException("The source is not set as a source to a player yet."); + } + if (packet == null) + { + throw new ArgumentNullException(nameof(packet)); + } + if (packet.IsDisposed) + { + throw new ObjectDisposedException(nameof(packet)); + } + + if (packet.Format.Type == MediaFormatType.Text || packet.Format.Type == MediaFormatType.Container) + { + throw new ArgumentException($"The format of the packet is invalid : { packet.Format.Type }."); + } + + if (!packet.Format.Equals(_audioMediaFormat) && !packet.Format.Equals(_videoMediaFormat)) + { + throw new ArgumentException($"The format of the packet is invalid : Unmatched format."); + } + + if (packet.Format.Type == MediaFormatType.Video && _videoMediaFormat == null) + { + throw new ArgumentException("Video is not configured with the current source."); + } + if (packet.Format.Type == MediaFormatType.Audio && _audioMediaFormat == null) + { + throw new ArgumentException("Audio is not configured with the current source."); + } + + _player.ValidatePlayerState(PlayerState.Paused, PlayerState.Playing, PlayerState.Ready); + + int ret = Interop.Player.PushMediaStream(_player.GetHandle(), packet.GetHandle()); + + PlayerErrorConverter.ThrowIfError(ret, "Failed to push the packet to the player"); + } + + private void SetMediaStreamInfo(StreamType streamType, MediaFormat mediaFormat) + { + if (mediaFormat == null) + { + return; + } + + IntPtr ptr = IntPtr.Zero; + + try + { + ptr = mediaFormat.AsNativeHandle(); + int ret = Interop.Player.SetMediaStreamInfo(_player.GetHandle(), (int)streamType, ptr); + + PlayerErrorConverter.ThrowIfError(ret, "Failed to set the media stream info"); + } + finally + { + MediaFormat.ReleaseNativeHandle(ptr); + } + } + + internal override void OnAttached(Player player) + { + Debug.Assert(player != null); + + if (_player != null) + { + throw new InvalidOperationException("The source is has already been assigned to another player."); + } + + AudioConfiguration?.OnPlayerSet(player); + VideoConfiguration?.OnPlayerSet(player); + + _player = player; + + SetMediaStreamInfo(StreamType.Audio, _audioMediaFormat); + SetMediaStreamInfo(StreamType.Video, _videoMediaFormat); + } + + internal override void OnDetached(Player player) + { + base.OnDetached(player); + + AudioConfiguration?.OnPlayerUnset(player); + VideoConfiguration?.OnPlayerUnset(player); + + _player = null; + } + + /// + /// Gets the that this source is assigned to as a source or null if this source is not assigned. + /// + /// + public Player Player => _player; + + } } diff --git a/src/Tizen.Multimedia/Player/MediaUriSource.cs b/src/Tizen.Multimedia/Player/MediaUriSource.cs index 331f362..d858a74 100644 --- a/src/Tizen.Multimedia/Player/MediaUriSource.cs +++ b/src/Tizen.Multimedia/Player/MediaUriSource.cs @@ -1,41 +1,59 @@ -/// Media Uri source -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - +/// Media Uri source +/* + * 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 { /// - /// The MediaUriSource class used to set source to the player. + /// Represents a media source with a uri. /// /// - /// MediaUriSource object is created using url string of the media - /// Then the object is set to the player as source. + /// The internet privilege(http://tizen.org/privilege/internet) must be added if any URLs are used to play from network. + /// The mediastorage privilege(http://tizen.org/privilege/mediastorage) must be added if any video/audio files are used to play located in the internal storage. + /// The externalstorage privilege(http://tizen.org/privilege/externalstorage) must be added if any video/audio files are used to play located in the external storage. /// - public class MediaUriSource : MediaSource + /// + public sealed class MediaUriSource : MediaSource { - private string _uri; - /// - /// Constructor - /// uri string + /// Initialize a new instance of the MediaUriSource class with the specified uri. + /// The uri string. + /// For HTTP or RSTP, uri should start with "http://" or "rtsp://". + /// The default protocol is "file://". + /// If you provide an invalid uri, you won't receive an error until is called. public MediaUriSource(string uri) { - _uri = uri; + if (uri == null) + { + throw new ArgumentNullException(nameof(uri)); + } + Uri = uri; } - internal string GetUri() + /// + /// Gets the uri. + /// + public string Uri { get; } + + internal override void OnAttached(Player player) { - return _uri; + PlayerErrorConverter.ThrowIfError(Interop.Player.SetUri(player.GetHandle(), Uri), + "Failed to set the source with specified uri"); } - } } diff --git a/src/Tizen.Multimedia/Player/PlaybackCompletedEventArgs.cs b/src/Tizen.Multimedia/Player/PlaybackCompletedEventArgs.cs deleted file mode 100644 index 1a7d8dc..0000000 --- a/src/Tizen.Multimedia/Player/PlaybackCompletedEventArgs.cs +++ /dev/null @@ -1,29 +0,0 @@ -/// This File contains PlaybackCompletedEventArgs class -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - -using System; - -namespace Tizen.Multimedia -{ - - /// - /// PlaybackCompleted event arguments - /// - /// - /// PlaybackCompleted event arguments - /// - public class PlaybackCompletedEventArgs : EventArgs - { - internal PlaybackCompletedEventArgs() - { - } - } -} \ No newline at end of file diff --git a/src/Tizen.Multimedia/Player/PlaybackErrorEventArgs.cs b/src/Tizen.Multimedia/Player/PlaybackErrorEventArgs.cs deleted file mode 100644 index 975ae05..0000000 --- a/src/Tizen.Multimedia/Player/PlaybackErrorEventArgs.cs +++ /dev/null @@ -1,48 +0,0 @@ -/// This File contains PlaybackErrorEventArgs class -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - -using System; - -namespace Tizen.Multimedia -{ - - /// - /// PlaybackError event arguments - /// - /// - /// PlaybackError event arguments - /// - public class PlaybackErrorEventArgs : EventArgs - { - internal int _errorCode; - - /// - /// Constructor. - /// - /// Playback error code - internal PlaybackErrorEventArgs(int errorCode) - { - _errorCode = errorCode; - } - - /// - /// Get the error code. - /// - /// integer error code - public int ErrorCode - { - get - { - return _errorCode; - } - } - } -} \ No newline at end of file diff --git a/src/Tizen.Multimedia/Player/PlaybackInterruptedEventArgs.cs b/src/Tizen.Multimedia/Player/PlaybackInterruptedEventArgs.cs index 2b9b3be..3369a27 100644 --- a/src/Tizen.Multimedia/Player/PlaybackInterruptedEventArgs.cs +++ b/src/Tizen.Multimedia/Player/PlaybackInterruptedEventArgs.cs @@ -1,48 +1,44 @@ -/// This File contains PlaybackInterruptedEventArgs class -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - +/* + * 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 { - /// - /// PlaybackInterrupted event arguments + /// Provides data for the event. /// - /// - /// PlaybackInterrupted event arguments - /// public class PlaybackInterruptedEventArgs : EventArgs { - internal int _interruptedCode; - - /// - /// Constructor - /// - /// Playback interrupted code - internal PlaybackInterruptedEventArgs(int interruptedCode) - { - _interruptedCode = interruptedCode; - } + /// + /// Initialize a new instance of the PlaybackInterruptedEventArgs class. + /// + /// The enum value indicating the reason. + public PlaybackInterruptedEventArgs(PlaybackIntrruptionReason reason) + { + Reason = reason; + } /// - /// Get the error code. + /// Gets the reason. /// - /// integer error code - public int InterruptedCode + public PlaybackIntrruptionReason Reason { get; } + + public override string ToString() { - get - { - return _interruptedCode; - } + return $"Reason : { Reason }"; } } -} \ No newline at end of file +} diff --git a/src/Tizen.Multimedia/Player/Player.cs b/src/Tizen.Multimedia/Player/Player.cs index 0e71221..356ee7f 100755 --- a/src/Tizen.Multimedia/Player/Player.cs +++ b/src/Tizen.Multimedia/Player/Player.cs @@ -1,784 +1,1184 @@ -/// Player -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - +/* + * 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; namespace Tizen.Multimedia { - static internal class PlayerLog - { - internal const string LogTag = "Tizen.Multimedia.Player"; - } - /// - /// The Player class provides APIs required for playback. + /// Provides the ability to control media playback. /// /// - /// The Player APIs provides functions to create a player, set media filename/url - /// and play the media content. It also provides APIs to adjust the configurations - /// of the player such as playback rate, volume, looping etc. And, event handlers - /// handles are provided to handle various playback events (like playback error/completion) + /// The Player provides functions to play a media content. + /// 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. /// - public class Player : IDisposable + public sealed class Player : IDisposable { - internal PlayerState _state; - internal float _leftVolume; - internal float _rightVolume; - internal int _audioLatencyMode; - internal bool _mute; - internal bool _isLooping; - internal Display _display; - internal Subtitle _subtitle; - internal AudioEffect _audioEffect; - internal StreamInformation _streamInformation; - internal StreamingConfiguration _streamingConfiguration; - internal IntPtr _playerHandle; - - private bool _disposed = false; - private EventHandler _playbackCompleted; + private IntPtr _handle = IntPtr.Zero; + + /// + /// Occurs when playback of a media is finished. + /// + public event EventHandler PlaybackCompleted; private Interop.Player.PlaybackCompletedCallback _playbackCompletedCallback; - private EventHandler _playbackInterrupted; + + /// + /// Occurs when playback of a media is interrupted. + /// + public event EventHandler PlaybackInterrupted; private Interop.Player.PlaybackInterruptedCallback _playbackInterruptedCallback; - private EventHandler _playbackError; + + /// + /// Occurs when any error occurs. + /// + /// The event handler will be executed on an internal thread. + public event EventHandler ErrorOccurred; private Interop.Player.PlaybackErrorCallback _playbackErrorCallback; - //TODO: Uncomment this after MediaPacket is implemented. - //private EventHandler _videoFrameDecoded; - //private Interop.Player.VideoFrameDecodedCallback _videoFrameDecodedCallback; + /// + /// Occurs when a video frame is decoded + /// + /// + /// The event handler will be executed on an internal thread. + /// The in event args should be disposed after use. + /// + /// + public event EventHandler VideoFrameDecoded; + private Interop.Player.VideoFrameDecodedCallback _videoFrameDecodedCallback; + /// + /// Occurs when the video stream changed. + /// + /// The event handler will be executed on an internal thread. + public event EventHandler VideoStreamChanged; + private Interop.Player.VideoStreamChangedCallback _videoStreamChangedCallback; /// - /// Player constructor. - public Player() - { - int ret; + /// Occurs when the subtitle is updated. + /// + /// The event handler will be executed on an internal thread. + public EventHandler SubtitleUpdated; + private Interop.Player.SubtitleUpdatedCallback _subtitleUpdatedCallback; - ret = Interop.Player.Create(out _playerHandle); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to create player" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Failed to create player"); - } + /// + /// Occurs when there is a change in the buffering status of streaming. + /// + public event EventHandler BufferingProgressChanged; + private Interop.Player.BufferingProgressCallback _bufferingProgressCallback; - // Initial get values - ret = Interop.Player.GetVolume(_playerHandle, out _leftVolume, out _rightVolume); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get volume levels" + ret); - } + internal event EventHandler MediaStreamAudioBufferStatusChanged; + private Interop.Player.MediaStreamBufferStatusCallback _mediaStreamAudioBufferStatusChangedCallback; - ret = Interop.Player.GetAudioLatencyMode(_playerHandle, out _audioLatencyMode); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get Audio latency mode" + ret); - } + internal event EventHandler MediaStreamVideoBufferStatusChanged; + private Interop.Player.MediaStreamBufferStatusCallback _mediaStreamVideoBufferStatusChangedCallback; - ret = Interop.Player.IsMuted(_playerHandle, out _mute); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get mute status" + ret); - } + internal event EventHandler MediaStreamAudioSeekingOccurred; + private Interop.Player.MediaStreamSeekCallback _mediaStreamAudioSeekCallback; - ret = Interop.Player.IsLooping(_playerHandle, out _isLooping); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get loop status" + ret); - } + internal event EventHandler MediaStreamVideoSeekingOccurred; + private Interop.Player.MediaStreamSeekCallback _mediaStreamVideoSeekCallback; + /// + /// Initialize a new instance of the Player class. + /// + public Player() + { + try + { + int ret = Interop.Player.Create(out _handle); + PlayerErrorConverter.ThrowIfError(ret, "Failed to create player"); - // AudioEffect - _audioEffect = new AudioEffect(); - _audioEffect._playerHandle = _playerHandle; + RetrieveProperties(); + RegisterCallbacks(); - // Display - _display = new Display(DisplayType.Evas /* Default value? */); - _display._playerHandle = _playerHandle; + AudioEffect = new AudioEffect(this); + } + catch (Exception) + { + if (_handle != IntPtr.Zero) + { + Interop.Player.Destroy(_handle); + } + throw; + } + } - // StreamingConfiguration - _streamingConfiguration = new StreamingConfiguration(_playerHandle); + private void RetrieveProperties() + { + PlayerErrorConverter.ThrowIfError(Interop.Player.GetVolume(_handle, out _volume, out _volume), + "Failed to initialize the player"); - // StreamInformation - _streamInformation = new StreamInformation(); - _streamInformation._playerHandle = _playerHandle; - _streamInformation._contentInfo = new PlayerContentInfo(); - _streamInformation._contentInfo._playerHandle = _playerHandle; + int value = 0; + PlayerErrorConverter.ThrowIfError(Interop.Player.GetAudioLatencyMode(_handle, out value), + "Failed to initialize the player"); + _audioLatencyMode = (AudioLatencyMode)value; + PlayerErrorConverter.ThrowIfError(Interop.Player.IsLooping(_handle, out _isLooping), + "Failed to initialize the player"); + } - Log.Debug(PlayerLog.LogTag, "player created : " + _playerHandle); + private void RegisterCallbacks() + { + RegisterSubtitleUpdatedCallback(); + RegisterErrorOccuuredCallback(); + RegisterPlaybackInterruptedCallback(); + RegisterVideoStreamChangedCallback(); + RegisterBufferingCallback(); + RegisterMediaStreamBufferStatusCallback(); + RegisterMediaStreamSeekCallback(); + RegisterPlaybackCompletedCallback(); + RegisterVideoFrameDecodedCallback(); } - /// - /// Player destructor - /// ~Player() { Dispose(false); } + internal IntPtr GetHandle() + { + ValidateNotDisposed(); + return _handle; + } - /// - /// PlaybackCompleted event is raised when playback of a media is finished - /// - public event EventHandler PlaybackCompleted + internal void ValidatePlayerState(params PlayerState[] desiredStates) { - add - { - if (_playbackCompleted == null) - { - RegisterPlaybackCompletedEvent(); - } - _playbackCompleted += value; + Debug.Assert(desiredStates.Length > 0); - } - remove + ValidateNotDisposed(); + + var curState = State; + if (curState.IsAnyOf(desiredStates)) { - _playbackCompleted -= value; - if (_playbackCompleted == null) - { - UnregisterPlaybackCompletedEvent(); - } + return; } + + throw new InvalidOperationException($"The player is not in a valid state. " + + $"Current State : { curState }, Valid State : { string.Join(", ", desiredStates) }."); } + #region Properties + #region Network configuration + private string _cookie = ""; + private string _userAgent = ""; + /// - /// PlaybackInterruped event is raised when playback of a media is interrupted + /// Gets or Sets the cookie for streaming playback. /// - public event EventHandler PlaybackInterruped + /// To set, the player must be in the state. + /// The player is not in the valid state. + /// The player has already been disposed of. + /// The value to set is null. + public string Cookie { - add + get { - if (_playbackInterrupted == null) - { - RegisterPlaybackInterruptedEvent(); - } - _playbackInterrupted += value; + return _cookie; } - remove + set { - _playbackInterrupted -= value; - if (_playbackInterrupted == null) + ValidatePlayerState(PlayerState.Idle); + + if (value == null) { - UnregisterPlaybackInterruptedEvent(); + throw new ArgumentNullException(nameof(value), "Cookie can't be null."); } + + int ret = Interop.Player.SetStreamingCookie(_handle, value, value.Length); + PlayerErrorConverter.ThrowIfError(ret, "Failed to set the cookie to the player"); + + _cookie = value; } } /// - /// PlaybackErrorOccured event is raised when any error occurs + /// Gets or Sets the user agent for streaming playback. /// - public event EventHandler PlaybackErrorOccured + /// To set, the player must be in the state. + /// The player is not in the valid state. + /// The player has already been disposed of. + /// The value to set is null. + public string UserAgent { - add + get { - if (_playbackError == null) - { - RegisterPlaybackErrorEvent(); - } - _playbackError += value; + return _userAgent; } - remove + set { - _playbackError -= value; - if (_playbackError == null) + ValidatePlayerState(PlayerState.Idle); + + if (value == null) { - UnregisterPlaybackErrorEvent(); + throw new ArgumentNullException(nameof(value), "UserAgent can't be null."); } - } - } + int ret = Interop.Player.SetStreamingUserAgent(_handle, value, value.Length); + PlayerErrorConverter.ThrowIfError(ret, "Failed to set the user agent to the player"); -#if _MEDIA_PACKET_ - TODO: Uncomment this after MediaPacket is implemented. - /// - /// VideoFrameCaptured event is raised when a video frame is decoded - /// - public event EventHandler VideoFrameDecoded - { - add - { - if(_videoFrameDecoded == null) { - RegisterVideoFrameDecodedEvent(); - } - _videoFrameDecoded += value; - } - remove - { - _videoFrameDecoded -= value; - if(_videoFrameDecoded == null) { - UnregisterVideoFrameDecodedEvent(); - } - } - } -#endif - + _userAgent = value; + } + } + #endregion /// - /// Get Player state. + /// Gets the state of the player. /// - /// PlayerState + /// The current state of the player. + /// The player has already been disposed of. public PlayerState State { get { - int state; - int ret = Interop.Player.GetState(_playerHandle, out state); + ValidateNotDisposed(); - if (ret != (int)PlayerError.None) - PlayerErrorFactory.ThrowException(ret, "Get player state failed"); + //TODO is this needed? + if (IsPreparing()) + { + return PlayerState.Preparing; + } + + int state = 0; + int ret = Interop.Player.GetState(_handle, out state); + PlayerErrorConverter.ThrowIfError(ret, "Failed to retrieve the state of the player"); + + Debug.Assert(Enum.IsDefined(typeof(PlayerState), state)); return (PlayerState)state; } } + private AudioLatencyMode _audioLatencyMode; + /// - /// Set/Get the left volume level. + /// Gets or sets the audio latency mode. /// - /// 0 to 1.0 that indicates left volume level - public float LeftVolume + /// A that specifies the mode. The default is . + /// + /// If the mode is , + /// 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() mode. + /// + /// The player has already been disposed of. + /// The value is not valid. + public AudioLatencyMode AudioLatencyMode { + get + { + return _audioLatencyMode; + } set { - int ret = Interop.Player.SetVolume(_playerHandle, value, value); + ValidateNotDisposed(); - if (ret == (int)PlayerError.None) - { - _leftVolume = value; - } - else + if (_audioLatencyMode == value) { - Log.Error(PlayerLog.LogTag, "Set volume failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "set volume failed"); + return; } - } - get - { - //Interop.Player.GetVolume(_playerHandle, out _leftVolume, out _rightVolume); - return _leftVolume; + ValidationUtil.ValidateEnum(typeof(AudioLatencyMode), value); + + int ret = Interop.Player.SetAudioLatencyMode(_handle, (int)value); + PlayerErrorConverter.ThrowIfError(ret, "Failed to set the audio latency mode of the player"); + + _audioLatencyMode = value; } } + private bool _isLooping; + /// - /// Set/Get the right volume level. + /// Gets or sets the looping state. /// - /// 0 to 1.0 that indicates right volume level - public float RightVolume + /// true if the playback is looping; otherwise, false. The default value is false. + /// The player has already been disposed of. + public bool IsLooping { + get + { + return _isLooping; + } set { - int ret = Interop.Player.SetVolume(_playerHandle, value, value); + ValidateNotDisposed(); - if (ret == (int)PlayerError.None) + if (_isLooping == value) { - _rightVolume = value; - } - else - { - Log.Error(PlayerLog.LogTag, "Set volume failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "set volume failed"); + return; } + + int ret = Interop.Player.SetLooping(_handle, value); + PlayerErrorConverter.ThrowIfError(ret, "Failed to set the mute state of the player"); + + _isLooping = value; + } - get + } + + #region Display methods + private PlayerDisplay _display; + + private int SetDisplay(PlayerDisplay display) + { + if (display == null) + { + return Interop.Player.SetDisplay(_handle, (int)PlayerDisplayType.None, IntPtr.Zero); + } + + Debug.Assert(Enum.IsDefined(typeof(PlayerDisplayType), display.Type)); + Debug.Assert(display.EvasObject != null); + + return Interop.Player.SetDisplay(_handle, (int)display.Type, display.EvasObject); + } + + private void ReplaceDisplay(PlayerDisplay newDisplay) + { + if (_display != null) { - //Interop.Player.GetVolume(_playerHandle, out _leftVolume, out _rightVolume); - return _rightVolume; + _display.Player = null; } + + _display = newDisplay; + _display.Player = this; } /// - /// Set/Get the Audio Latency Mode. + /// Gets or sets the display. /// - /// Low, Mid, High - public AudioLatencyMode AudioLatencyMode + /// A that specifies the display configurations. + /// The player must be in the state. + /// The player has already been disposed of. + /// The value has already been assigned to another player. + /// The player is not in the valid state. + public PlayerDisplay Display { + get + { + return _display; + } set { - if (_audioLatencyMode != (int)value) + ValidatePlayerState(PlayerState.Idle); + + if (value != null && value.Player != null) { - int ret = Interop.Player.SetAudioLatencyMode(_playerHandle, (int)value); - if (ret != (int)PlayerError.None) + if (ReferenceEquals(this, value.Player)) { - Log.Error(PlayerLog.LogTag, "Set audio latency mode failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "set audio latency mode failed"); + return; } else { - _audioLatencyMode = (int)value; + throw new ArgumentException("The display has already been assigned to another player."); } } + + PlayerErrorConverter.ThrowIfError(SetDisplay(value), "Failed to set the display to the player"); + + ReplaceDisplay(value); } + } + #endregion + private PlayerTrackInfo _audioTrack; + + /// + /// Gets the track info for audio. + /// + /// A for audio. + public PlayerTrackInfo AudioTrackInfo + { get { - return (AudioLatencyMode)_audioLatencyMode; + if (_audioTrack == null) + { + _audioTrack = new PlayerTrackInfo(this, StreamType.Audio); + } + return _audioTrack; } } + private PlayerTrackInfo _subtitleTrackInfo; + /// - /// Set/Get mute. + /// Gets the track info for subtitle. /// - /// true, false - public bool Mute + /// A for subtitle. + public PlayerTrackInfo SubtitleTrackInfo { - set + get { - if (_mute != value) + if (_subtitleTrackInfo == null) { - int ret = Interop.Player.SetMute(_playerHandle, value); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Set mute failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "set mute failed"); - } - else - { - _mute = value; - } + _subtitleTrackInfo = new PlayerTrackInfo(this, StreamType.Text); } + return _subtitleTrackInfo; } + } + + private StreamInfo _streamInfo; + + /// + /// Gets the stream information. + /// + /// A for this player. + public StreamInfo StreamInfo + { get { - //Interop.Player.IsMuted(_playerHandle, out _mute); - return _mute; + if (_streamInfo == null) + { + _streamInfo = new StreamInfo(this); + } + return _streamInfo; } } /// - /// Set/Get Loop play. + /// Gets audio effect. /// - /// true, false - public bool IsLooping + public AudioEffect AudioEffect { get; } + + #endregion + + #region Dispose support + private bool _disposed; + + public void Dispose() { - set + Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + if (!_disposed) { - if (_isLooping != value) + if (_source != null) { - int ret = Interop.Player.SetLooping(_playerHandle, value); - if (ret != (int)PlayerError.None) + try { - Log.Error(PlayerLog.LogTag, "Set loop failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "set loop failed"); + _source.DetachFrom(this); } - else + catch (Exception e) { - _isLooping = value; + Log.Error(nameof(Player), e.ToString()); } } + _source = null; + + if (_handle != IntPtr.Zero) + { + Interop.Player.Destroy(_handle); + _handle = IntPtr.Zero; + } + _disposed = true; } - get + } + + internal void ValidateNotDisposed() + { + if (_disposed) { - //Interop.Player.IsLooping(_playerHandle, out _isLooping); - return _isLooping; + throw new ObjectDisposedException(nameof(Player)); } } - /// - /// Get play position. - /// - /// play position in milli seconds - public int PlayPosition + internal bool IsDisposed { get { - int playPosition; - int ret = Interop.Player.GetPlayPosition(_playerHandle, out playPosition); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get play position, " + (PlayerError)ret); - } - return playPosition; + return _disposed; } } + #endregion + + #region Methods /// - /// Set/Get Display. + /// Gets the mute state. /// - /// Display configuration - public Display Display + /// The player has already been disposed of. + public bool IsMuted() { - set - { - _display = value; - _display._playerHandle = _playerHandle; - } - get - { - return _display; - } + ValidateNotDisposed(); + + bool value = false; + PlayerErrorConverter.ThrowIfError(Interop.Player.IsMuted(_handle, out value), + "Failed to get the mute state of the player"); + return value; } /// - /// Set/Get Subtitle. + /// Sets the mute state. /// - /// Subtitle configuration - public Subtitle Subtitle + /// true to mute the player; otherwise, false. + /// The player has already been disposed of. + public void SetMute(bool mute) { - set - { - _subtitle = value; - _subtitle._playerHandle = _playerHandle; - _subtitle._subPath = _subtitle._path; - } - get - { - return _subtitle; - } + ValidateNotDisposed(); + + int ret = Interop.Player.SetMute(_handle, mute); + PlayerErrorConverter.ThrowIfError(ret, "Failed to set the mute state of the player"); } + /// + /// Get Streaming download Progress. + /// + /// The player must be in the or state. + /// + /// The player is not streaming. + /// -or- + /// The player is not in the valid state. + /// + /// The player has already been disposed of. + public DownloadProgress GetDownloadProgress() + { + ValidatePlayerState(PlayerState.Playing, PlayerState.Paused); + + int start = 0; + int current = 0; + int ret = Interop.Player.GetStreamingDownloadProgress(_handle, out start, out current); + PlayerErrorConverter.ThrowIfError(ret, "Failed to get download progress"); + + return new DownloadProgress(start, current); + } + + #region Volume + private float _volume; /// - /// Get AudioEffect. + /// Sets the current volume. /// - /// AudioEffect object - public AudioEffect AudioEffect + /// Valid volume range is from 0 to 1.0, inclusive. + /// The player has already been disposed of. + /// + /// value is less than zero. + /// -or- + /// value is greater than 1.0. + /// + public void SetVolume(float value) { - get + ValidateNotDisposed(); + + if (value < 0F || 1.0F < value) { - return _audioEffect; + throw new ArgumentOutOfRangeException(nameof(value), value, + $"Valid volume range is 0 <= value <= 1.0, but got { value }."); } + + int ret = Interop.Player.SetVolume(_handle, value, value); + PlayerErrorConverter.ThrowIfError(ret, "Failed to set the volume of the player"); } /// - /// Get stream information. + /// Gets the current volume. /// - /// StreamInformation object - public StreamInformation StreamInformation + /// the volume range is from 0 to 1.0, inclusive. + /// The player has already been disposed of. + public float GetVolume() { - get - { - return _streamInformation; - } + ValidateNotDisposed(); + + float value = 0.0F; + int ret = Interop.Player.GetVolume(_handle, out value, out value); + PlayerErrorConverter.ThrowIfError(ret, "Failed to get the volume of the player"); + return value; } + #endregion /// - /// Get StreamingConfiguration. + /// Sets the subtitle path for playback. /// - /// StreamingConfiguration object - public StreamingConfiguration StreamingConfiguration + /// Only MicroDVD/SubViewer(*.sub), SAMI(*.smi), and SubRip(*.srt) subtitle formats are supported. + /// The mediastorage privilege(http://tizen.org/privilege/mediastorage) must be added if any files are used to play located in the internal storage. + /// The externalstorage privilege(http://tizen.org/privilege/externalstorage) must be added if any files are used to play located in the external storage. + /// + /// The player has already been disposed of. + /// The specified path does not exist. + /// The path is null. + public void SetSubtitle(string path) { - get + ValidateNotDisposed(); + + if (path == null) + { + throw new ArgumentNullException(nameof(path)); + } + + if (!File.Exists(path)) { - return _streamingConfiguration; + throw new ArgumentException($"The specified file does not exist : { path }."); } + + PlayerErrorConverter.ThrowIfError(Interop.Player.SetSubtitlePath(_handle, path), + "Failed to set the subtitle path to the player"); } + /// + /// Removes the subtitle path. + /// + /// The player must be in the state. + /// The player has already been disposed of. + /// The player is not in the valid state. + public void ClearSubtitle() + { + ValidatePlayerState(PlayerState.Idle); - public void Dispose() + PlayerErrorConverter.ThrowIfError(Interop.Player.SetSubtitlePath(_handle, null), + "Failed to clear the subtitle of the player"); + } + + /// + /// Sets the offset for the subtitle. + /// + /// The player must be in the or state. + /// The player has already been disposed of. + /// The player is not in the valid state. + public void SetSubtitleOffset(int offset) { - Dispose(true); - GC.SuppressFinalize(this); + ValidatePlayerState(PlayerState.Playing, PlayerState.Paused); + + PlayerErrorConverter.ThrowIfError(Interop.Player.SetSubtitlePositionOffset(_handle, offset), + "Failed to the subtitle offset of the player"); + } + + private void Prepare() + { + int ret = Interop.Player.Prepare(_handle); + PlayerErrorConverter.ThrowIfError(ret, "Failed to prepare the player"); } /// - /// Prepares the media player for playback. - public Task PrepareAsync() + /// Prepares the media player for playback, asynchronously. + /// + /// To prepare the player, the player must be in the state, + /// and a source must be set. + /// No source is set. + /// The player has already been disposed of. + /// The player is not in the valid state. + public Task PrepareAsync() { - int ret; - var task = new TaskCompletionSource(); + if (_source == null) + { + throw new InvalidOperationException("No source is set."); + } + + ValidatePlayerState(PlayerState.Idle); - Task.Factory.StartNew(() => + var completionSource = new TaskCompletionSource(); + + SetPreparing(); + + Task.Run(() => { - Interop.Player.PrepareCallback cb = (IntPtr userData) => + try { - task.SetResult(true); - return; - }; - ret = Interop.Player.PrepareAsync(_playerHandle, cb, IntPtr.Zero); - if (ret != (int)PlayerError.None) + Prepare(); + ClearPreparing(); + completionSource.SetResult(true); + } + catch (Exception e) { - task.SetResult(false); - Log.Error(PlayerLog.LogTag, "Failed to prepare player" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Failed to prepare player"); + ClearPreparing(); + completionSource.TrySetException(e); } }); - return task.Task; + return completionSource.Task; } /// - /// The most recently used media is reset and no longer associated with the player. Playback is no longer possible. - /// If you want to use the player again, you will have to set the data URI and call prepare() again. + /// Unprepares the player. + /// + /// + /// The most recently used source is reset and no longer associated with the player. Playback is no longer possible. + /// If you want to use the player again, you have to set a source and call again. + /// + /// The player must be in the , or state. + /// It has no effect if the player is already in the state. + /// + /// + /// The player has already been disposed of. + /// The player is not in the valid state. public void Unprepare() { - int ret = Interop.Player.Unprepare(_playerHandle); - if (ret != (int)PlayerError.None) + if (State == PlayerState.Idle) { - Log.Error(PlayerLog.LogTag, "Failed to unprepare player" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Failed to unprepare player"); + return; } + ValidatePlayerState(PlayerState.Ready, PlayerState.Paused, PlayerState.Playing); + + PlayerErrorConverter.ThrowIfError(Interop.Player.Unprepare(_handle), + "Failed to unprepare the player"); + + if (_source != null) + { + _source.DetachFrom(this); + } + _source = null; } + + //TODO remarks needs to be updated. see the native reference. /// - /// Starts or resumes playback. + /// Starts or resumes playback. + /// + /// + /// The player must be in the or state. + /// It has no effect if the player is already in the state. + /// + /// The player has already been disposed of. + /// The player is not in the valid state. + /// + /// + /// + /// public void Start() { - int ret = Interop.Player.Start(_playerHandle); - if (ret != (int)PlayerError.None) + if (State == PlayerState.Playing) { - Log.Error(PlayerLog.LogTag, "Failed to start player" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Failed to start player"); + return; } + ValidatePlayerState(PlayerState.Ready, PlayerState.Paused); + + PlayerErrorConverter.ThrowIfError(Interop.Player.Start(_handle), "Failed to start the player"); } /// - /// Stops playing media content. + /// Stops playing media content. + /// + /// + /// The player must be in the or state. + /// It has no effect if the player is already in the state. + /// + /// The player has already been disposed of. + /// The player is not in the valid state. + /// + /// public void Stop() { - int ret = Interop.Player.Stop(_playerHandle); - if (ret != (int)PlayerError.None) + if (State == PlayerState.Ready) { - Log.Error(PlayerLog.LogTag, "Failed to stop player" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Failed to stop player"); + return; } + ValidatePlayerState(PlayerState.Paused, PlayerState.Playing); + + PlayerErrorConverter.ThrowIfError(Interop.Player.Stop(_handle), "Failed to stop the player"); } /// - /// Pauses the player. + /// Pauses the player. + /// + /// + /// The player must be in the state. + /// It has no effect if the player is already in the state. + /// + /// The player has already been disposed of. + /// The player is not in the valid state. + /// public void Pause() { - int ret = Interop.Player.Pause(_playerHandle); - if (ret != (int)PlayerError.None) + if (State == PlayerState.Paused) { - Log.Error(PlayerLog.LogTag, "Failed to pause player" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Failed to pause player"); + return; } + + ValidatePlayerState(PlayerState.Playing); + + PlayerErrorConverter.ThrowIfError(Interop.Player.Pause(_handle), "Failed to pause the player"); } + private MediaSource _source; + /// - /// sets media source for the player. - /// Mediasource + /// Sets a media source for the player. + /// + /// A that specifies the source for playback. + /// The player must be in the state. + /// The player has already been disposed of. + /// + /// The player is not in the valid state. + /// -or- + /// It is not able to assign the source to the player. + /// + /// public void SetSource(MediaSource source) { - int ret; - if (source.GetType() == typeof(MediaUriSource)) + ValidatePlayerState(PlayerState.Idle); + + if (source != null) { - ret = Interop.Player.SetUri(_playerHandle, ((MediaUriSource)source).GetUri()); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to seturi" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Failed to set uri"); - } + source.AttachTo(this); } - else if (source.GetType() == typeof(MediaBufferSource)) + + if (_source != null) { - GCHandle pinnedArray = GCHandle.Alloc(((MediaBufferSource)source)._buffer, GCHandleType.Pinned); - IntPtr mem = pinnedArray.AddrOfPinnedObject(); - ret = Interop.Player.SetMemoryBuffer(_playerHandle, mem, ((MediaBufferSource)source)._buffer.Length); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to set memory buffer" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Failed to set memory buffer"); - } + _source.DetachFrom(this); + } + + _source = source; + } + + /// + /// Captures a video frame asynchronously. + /// + /// The player must be in the or state. + /// The player has already been disposed of. + /// The player is not in the valid state. + public Task CaptureVideoAsync() + { + ValidatePlayerState(PlayerState.Playing, PlayerState.Paused); + + TaskCompletionSource t = new TaskCompletionSource(); + + Interop.Player.VideoCaptureCallback cb = (data, width, height, size, gchPtr) => + { + Debug.Assert(size <= int.MaxValue); + + byte[] buf = new byte[size]; + Marshal.Copy(data, buf, 0, (int)size); + + t.TrySetResult(new CapturedFrame(buf, width, height)); + + GCHandle.FromIntPtr(gchPtr).Free(); + }; + + var gch = GCHandle.Alloc(cb); + try + { + PlayerErrorConverter.ThrowIfError( + Interop.Player.CaptureVideo(_handle, cb, GCHandle.ToIntPtr(gch)), + "Failed to capture the video"); } - else if (source.GetType() == typeof(MediaStreamSource)) + catch(Exception) { - // TODO: Handle MediaStream source after implementing MediaPacket module - ((MediaStreamSource)source).SetHandle(_playerHandle); + gch.Free(); + throw; } - } + return t.Task; + } /// - /// Captures a video frame asynchronously. - public Task CaptureVideoAsync() + /// Gets the play position in milliseconds. + /// + /// The player must be in the , or state. + /// The player has already been disposed of. + /// The player is not in the valid state. + /// + public int GetPlayPosition() { - return Task.Factory.StartNew(() => CaptureVideoAsyncTask()).Result; + ValidatePlayerState(PlayerState.Ready, PlayerState.Paused, PlayerState.Playing); + + int playPosition = 0; + + PlayerErrorConverter.ThrowIfError(Interop.Player.GetPlayPosition(_handle, out playPosition), + "Failed to get the play position of the player"); + + return playPosition; + } + + private void SetPlayPosition(int milliseconds, bool accurate, + Interop.Player.SeekCompletedCallback cb) + { + int ret = Interop.Player.SetPlayPosition(_handle, milliseconds, accurate, cb, IntPtr.Zero); + + //Note that we assume invalid param error is returned only when the position value is invalid. + if (ret == (int)PlayerErrorCode.InvalidArgument) + { + throw new ArgumentOutOfRangeException(nameof(milliseconds), milliseconds, + "The position is not valid."); + } + + PlayerErrorConverter.ThrowIfError(ret, "Failed to set play position"); } /// - ///Sets the seek position for playback, asynchronously. - /// Position to be set in milliseconds - /// accurate seek or not - public Task SetPlayPositionAsync(int milliseconds, bool accurate) + /// Sets the seek position for playback, asynchronously. + /// + /// The value indicating a desired position in milliseconds. + /// The value indicating whether the operation performs with accuracy. + /// + /// The player must be in the , or state. + /// If the is true, the play position will be adjusted as the specified value, + /// but this might be considerably slow. If false, the play position will be a nearest keyframe position. + /// + /// The player has already been disposed of. + /// The player is not in the valid state. + /// The specified position is not valid. + /// + public Task SetPlayPositionAsync(int position, bool accurate) { - var task = new TaskCompletionSource(); + ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused); + + var taskCompletionSource = new TaskCompletionSource(); - Task.Factory.StartNew(() => + bool immediateResult = _source is MediaStreamSource; + + Interop.Player.SeekCompletedCallback cb = _ => taskCompletionSource.TrySetResult(true); + + SetPlayPosition(position, accurate, cb); + if (immediateResult) { - Interop.Player.SeekCompletedCallback cb = (IntPtr userData) => - { - task.SetResult(true); - return; - }; - int ret = Interop.Player.SetPlayPosition(_playerHandle, milliseconds, accurate, cb, IntPtr.Zero); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to set playposition" + (PlayerError)ret); - task.SetResult(false); - PlayerErrorFactory.ThrowException(ret, "Failed to set playposition"); - } - }); + taskCompletionSource.TrySetResult(true); + } - return task.Task; + return taskCompletionSource.Task; } /// - /// sets playback rate - /// playback rate -5.0x to 5.0x + /// Sets playback rate. + /// + /// The value for the playback rate. Valid range is -5.0 to 5.0, inclusive. + /// + /// The player must be in the , or state. + /// The sound will be muted, when the playback rate is under 0.0 or over 2.0. + /// + /// The player has already been disposed of. + /// + /// The player is not in the valid state. + /// -or- + /// Streaming playback. + /// + /// + /// is less than 5.0. + /// -or- + /// is greater than 5.0. + /// -or- + /// is zero. + /// public void SetPlaybackRate(float rate) { - int ret = Interop.Player.SetPlaybackRate(_playerHandle, rate); - if (ret != (int)PlayerError.None) + if (rate < -5.0F || 5.0F < rate || rate == 0.0F) { - Log.Error(PlayerLog.LogTag, "Set playback rate failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "set playback rate failed"); + throw new ArgumentOutOfRangeException(nameof(rate), rate, "Valid range is -5.0 to 5.0 (except 0.0)"); } + + ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused); + + PlayerErrorConverter.ThrowIfError(Interop.Player.SetPlaybackRate(_handle, rate), + "Failed to set the playback rate."); } /// - /// sets audio stream policy - /// Audio Stream Policy - public void SetAudioStreamPolicy(AudioStreamPolicy policy) + /// Applies the audio stream policy. + /// + /// The to apply. + /// The player must be in the state. + /// + /// The player has already been disposed of. + /// -or- + /// has already been disposed of. + /// + /// The player is not in the valid state. + /// is null. + public void ApplyAudioStreamPolicy(AudioStreamPolicy policy) { - int ret = Interop.Player.SetAudioPolicyInfo(_playerHandle, policy.Handle); - if (ret != (int)PlayerError.None) + if (policy == null) + { + throw new ArgumentNullException(nameof(policy)); + } + + if (policy.Handle == IntPtr.Zero) { - Log.Error(PlayerLog.LogTag, "Set Audio stream policy failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Set Audio stream policy failed"); + throw new ObjectDisposedException(nameof(policy)); } + + ValidatePlayerState(PlayerState.Idle); + + PlayerErrorConverter.ThrowIfError(Interop.Player.SetAudioPolicyInfo(_handle, policy.Handle), + "Failed to set the audio stream policy to the player"); } + #endregion - protected virtual void Dispose(bool disposing) + #region Callback registrations + private void RegisterSubtitleUpdatedCallback() { - if (!_disposed) + _subtitleUpdatedCallback = (duration, text, _) => { - if (disposing) - { - // To be used if there are any other disposable objects - } - if (_playerHandle != IntPtr.Zero) - { - Interop.Player.Destroy(_playerHandle); - _playerHandle = IntPtr.Zero; - } - _disposed = true; - } + SubtitleUpdated?.Invoke(this, new SubtitleUpdatedEventArgs(duration, text)); + }; + + int ret = Interop.Player.SetSubtitleUpdatedCb(_handle, _subtitleUpdatedCallback, IntPtr.Zero); + PlayerErrorConverter.ThrowIfError(ret, "Failed to initialize the player"); } - private void RegisterPlaybackCompletedEvent() + private void RegisterPlaybackCompletedCallback() { - _playbackCompletedCallback = (IntPtr userData) => + _playbackCompletedCallback = _ => { - PlaybackCompletedEventArgs eventArgs = new PlaybackCompletedEventArgs(); - _playbackCompleted?.Invoke(this, eventArgs); + PlaybackCompleted?.Invoke(this, EventArgs.Empty); }; - int ret = Interop.Player.SetCompletedCb(_playerHandle, _playbackCompletedCallback, IntPtr.Zero); - if (ret != (int)PlayerError.None) + int ret = Interop.Player.SetCompletedCb(_handle, _playbackCompletedCallback, IntPtr.Zero); + PlayerErrorConverter.ThrowIfError(ret, "Failed to set PlaybackCompleted"); + } + + private void RegisterPlaybackInterruptedCallback() + { + _playbackInterruptedCallback = (code, _) => { - Log.Error(PlayerLog.LogTag, "Setting PlaybackCompleted callback failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Setting PlaybackCompleted callback failed"); - } + if (!Enum.IsDefined(typeof(PlaybackIntrruptionReason), code)) + { + return; + } + PlaybackInterrupted?.Invoke(this, + new PlaybackInterruptedEventArgs((PlaybackIntrruptionReason)code)); + }; + int ret = Interop.Player.SetInterruptedCb(_handle, _playbackInterruptedCallback, IntPtr.Zero); + PlayerErrorConverter.ThrowIfError(ret, "Failed to set PlaybackInterrupted"); } - private void UnregisterPlaybackCompletedEvent() + private void RegisterErrorOccuuredCallback() { - int ret = Interop.Player.UnsetCompletedCb(_playerHandle); - if (ret != (int)PlayerError.None) + _playbackErrorCallback = (code, _) => { - Log.Error(PlayerLog.LogTag, "Unsetting PlaybackCompleted callback failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Unsetting PlaybackCompleted callback failed"); - } + if (!Enum.IsDefined(typeof(PlayerError), code)) + { + return; + } + //TODO handle service disconnected error. + ErrorOccurred?.Invoke(this, new PlayerErrorOccurredEventArgs((PlayerError)code)); + }; + int ret = Interop.Player.SetErrorCb(_handle, _playbackErrorCallback, IntPtr.Zero); + PlayerErrorConverter.ThrowIfError(ret, "Setting PlaybackError callback failed"); } - private void RegisterPlaybackInterruptedEvent() + private void RegisterVideoFrameDecodedCallback() { - _playbackInterruptedCallback = (int code, IntPtr userData) => + _videoFrameDecodedCallback = (packetHandle,_) => { - PlaybackInterruptedEventArgs eventArgs = new PlaybackInterruptedEventArgs(code); - _playbackInterrupted?.Invoke(this, eventArgs); + var handler = VideoFrameDecoded; + if (handler != null) + { + handler.Invoke(this, + new VideoFrameDecodedEventArgs(MediaPacket.From(packetHandle))); + } + else + { + MediaPacket.From(packetHandle).Dispose(); + } }; - int ret = Interop.Player.SetInterruptedCb(_playerHandle, _playbackInterruptedCallback, IntPtr.Zero); - if (ret != (int)PlayerError.None) + + int ret = Interop.Player.SetVideoFrameDecodedCb(_handle, _videoFrameDecodedCallback, IntPtr.Zero); + PlayerErrorConverter.ThrowIfError(ret, "Failed to register the VideoFrameDecoded"); + } + + private void RegisterVideoStreamChangedCallback() + { + ValidatePlayerState(PlayerState.Idle); + + _videoStreamChangedCallback = (width, height, fps, bitrate, _) => { - Log.Error(PlayerLog.LogTag, "Setting PlaybackInterrupted callback failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Setting PlaybackInterrupted callback failed"); - } + VideoStreamChangedEventArgs eventArgs = new VideoStreamChangedEventArgs(height, width, fps, bitrate); + VideoStreamChanged?.Invoke(this, eventArgs); + }; + int ret = Interop.Player.SetVideoStreamChangedCb(GetHandle(), _videoStreamChangedCallback, IntPtr.Zero); + PlayerErrorConverter.ThrowIfError(ret, "Failed to set the video stream changed callback"); } - private void UnregisterPlaybackInterruptedEvent() + private void RegisterBufferingCallback() { - int ret = Interop.Player.UnsetInterruptedCb(_playerHandle); - if (ret != (int)PlayerError.None) + _bufferingProgressCallback = (percent, _) => { - Log.Error(PlayerLog.LogTag, "Unsetting PlaybackInterrupted callback failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Unsetting PlaybackInterrupted callback failed"); - } + Log.Debug(nameof(Player), $"Buffering callback with percent { percent }"); + BufferingProgressChanged?.Invoke(this, new BufferingProgressChangedEventArgs(percent)); + }; + + int ret = Interop.Player.SetBufferingCb(_handle, _bufferingProgressCallback, IntPtr.Zero); + PlayerErrorConverter.ThrowIfError(ret, "Failed to set BufferingProgress"); } - private void RegisterPlaybackErrorEvent() + private void RegisterMediaStreamBufferStatusCallback() { - _playbackErrorCallback = (int code, IntPtr userData) => + _mediaStreamAudioBufferStatusChangedCallback = (status, _) => { - PlaybackErrorEventArgs eventArgs = new PlaybackErrorEventArgs(code); - _playbackError?.Invoke(this, eventArgs); + Debug.Assert(Enum.IsDefined(typeof(MediaStreamBufferStatus), status)); + + MediaStreamAudioBufferStatusChanged?.Invoke(this, + new MediaStreamBufferStatusChangedEventArgs((MediaStreamBufferStatus)status)); }; - int ret = Interop.Player.SetErrorCb(_playerHandle, _playbackErrorCallback, IntPtr.Zero); - if (ret != (int)PlayerError.None) + _mediaStreamVideoBufferStatusChangedCallback = (status, _) => { - Log.Error(PlayerLog.LogTag, "Setting PlaybackError callback failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Setting PlaybackError callback failed"); - } + Debug.Assert(Enum.IsDefined(typeof(MediaStreamBufferStatus), status)); + MediaStreamVideoBufferStatusChanged?.Invoke(this, + new MediaStreamBufferStatusChangedEventArgs((MediaStreamBufferStatus)status)); + }; + + RegisterMediaStreamBufferStatusCallback(StreamType.Audio, _mediaStreamAudioBufferStatusChangedCallback); + RegisterMediaStreamBufferStatusCallback(StreamType.Video, _mediaStreamVideoBufferStatusChangedCallback); } - private void UnregisterPlaybackErrorEvent() + private void RegisterMediaStreamBufferStatusCallback(StreamType streamType, + Interop.Player.MediaStreamBufferStatusCallback cb) { - int ret = Interop.Player.UnsetErrorCb(_playerHandle); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Unsetting PlaybackError callback failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Unsetting PlaybackError callback failed"); - } + int ret = Interop.Player.SetMediaStreamBufferStatusCb(_handle, (int)streamType, + cb, IntPtr.Zero); + PlayerErrorConverter.ThrowIfError(ret, "Failed to initialize the player"); } - private Task CaptureVideoAsyncTask() + private void RegisterMediaStreamSeekCallback() { - TaskCompletionSource t = new TaskCompletionSource(); - Interop.Player.VideoCaptureCallback cb = (byte[] data, int width, int height, uint size, IntPtr userData) => + _mediaStreamAudioSeekCallback = (offset, _) => { - VideoFrameCapture v = new VideoFrameCapture(data, width, height, size); - t.SetResult(v); + MediaStreamAudioSeekingOccurred?.Invoke(this, new MediaStreamSeekingOccurredEventArgs(offset)); }; - - int ret = Interop.Player.CaptureVideo(_playerHandle, cb, IntPtr.Zero); - if (ret != (int)PlayerError.None) + _mediaStreamVideoSeekCallback = (offset, _) => { - Log.Error(PlayerLog.LogTag, "Failed to capture video" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Failed to capture video"); - } - return t.Task; + MediaStreamVideoSeekingOccurred?.Invoke(this, new MediaStreamSeekingOccurredEventArgs(offset)); + }; + + RegisterMediaStreamSeekCallback(StreamType.Audio, _mediaStreamAudioSeekCallback); + RegisterMediaStreamSeekCallback(StreamType.Video, _mediaStreamVideoSeekCallback); } + private void RegisterMediaStreamSeekCallback(StreamType streamType, Interop.Player.MediaStreamSeekCallback cb) + { + int ret = Interop.Player.SetMediaStreamSeekCb(_handle, (int)streamType, + cb, IntPtr.Zero); + + PlayerErrorConverter.ThrowIfError(ret, "Failed to initialize the player"); + } + #endregion + #region Preparing state -#if _MEDIA_PACKET_ - //TODO: Uncomment this when MediaPacket is implemented - private void RegisterVideoFrameDecodedEvent() + private int _isPreparing; + + private bool IsPreparing() { - _videoFrameDecoded = (MediaPacket packet, IntPtr userData) => - { - VideoFrameDecodedEventArgs eventArgs = new VideoFrameDecodedEventArgs(); - _videoFrameDecoded?.Invoke(this, eventArgs); - }; - Interop.Player.SetErrorCb(_playerHandle, _videoFrameDecodedCallback, IntPtr.Zero); + return Interlocked.CompareExchange(ref _isPreparing, 1, 1) == 1; } - private void UnregisterVideoFrameDecodedEvent() + private void SetPreparing() { - Interop.Player.UnsetMediaPacketVideoFrameDecodedCb(_playerHandle); + Interlocked.Exchange(ref _isPreparing, 1); } -#endif + private void ClearPreparing() + { + Interlocked.Exchange(ref _isPreparing, 0); + } + #endregion } } diff --git a/src/Tizen.Multimedia/Player/PlayerContentInfo.cs b/src/Tizen.Multimedia/Player/PlayerContentInfo.cs deleted file mode 100644 index 6dd285f..0000000 --- a/src/Tizen.Multimedia/Player/PlayerContentInfo.cs +++ /dev/null @@ -1,125 +0,0 @@ -/// PlayerContentInfo -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - -using System; -using System.Runtime.InteropServices; - -namespace Tizen.Multimedia -{ - /// - /// PlayerContentInfo - /// - /// - /// This class provides properties for metadata information of media file. - /// - - public class PlayerContentInfo - { - internal IntPtr _playerHandle; - - internal PlayerContentInfo() - { - } - - private string GetContentInfo(ContentInfoKey key) - { - IntPtr ptr = IntPtr.Zero; - - try - { - int ret = Interop.Player.GetContentInfo(_playerHandle, (int)key, out ptr); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get album info" + (PlayerError)ret); - return ""; - } - - return Marshal.PtrToStringAnsi(ptr); - } - finally - { - Interop.Libc.Free(ptr); - } - } - - /// - /// Metadata - Album - /// - /// album string - public string Album - { - get - { - return GetContentInfo(ContentInfoKey.Album); - } - } - - /// - /// Metadata - Artist - /// - /// artist string - public string Artist - { - get - { - return GetContentInfo(ContentInfoKey.Artist); - } - } - - /// - /// Metadata - Author - /// - /// Author string - public string Author - { - get - { - return GetContentInfo(ContentInfoKey.Author); - } - } - - /// - /// Metadata - Genre - /// - /// genre string - public string Genre - { - get - { - return GetContentInfo(ContentInfoKey.Genre); - } - } - - /// - /// Metadata - Title - /// - /// title string - public string Title - { - get - { - return GetContentInfo(ContentInfoKey.Title); - } - } - - /// - /// Metadata - Year - /// - /// year string - public string Year - { - get - { - return GetContentInfo(ContentInfoKey.Year); - } - } - - } -} diff --git a/src/Tizen.Multimedia/Player/PlayerDisplay.cs b/src/Tizen.Multimedia/Player/PlayerDisplay.cs new file mode 100644 index 0000000..088d005 --- /dev/null +++ b/src/Tizen.Multimedia/Player/PlayerDisplay.cs @@ -0,0 +1,190 @@ +/* + * 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; + +namespace Tizen.Multimedia +{ + //TODO reimplementation needed + /// + /// Provides means to configure display settings for video . + /// + public class PlayerDisplay + { + private readonly EvasObject _evasObject; + + private PlayerDisplay(PlayerDisplayType type, EvasObject evasObject) + { + if (evasObject == null) + { + throw new ArgumentNullException(nameof(evasObject)); + } + + if (evasObject == IntPtr.Zero) + { + throw new ArgumentException("The evas object is not realized."); + } + + Type = type; + _evasObject = evasObject; + } + + public PlayerDisplay(Window window) : this(PlayerDisplayType.Overlay, window) + { + } + + public PlayerDisplay(ElmSharp.Image image) : this(PlayerDisplayType.Surface, image) + { + } + + public EvasObject EvasObject + { + get + { + return _evasObject; + } + } + + internal PlayerDisplayType Type { get; } + + /// + /// Gets the player that the display is assigned to. + /// + public Player Player + { + get; + internal set; + } + + private void ValidatePlayer() + { + if (Player == null) + { + throw new InvalidOperationException("The display is not assigned, yet."); + } + + Player.ValidateNotDisposed(); + } + + private PlayerDisplayMode _displayMode = PlayerDisplayMode.LetterBox; + + /// + /// Set/Get Display mode. + /// + /// LetterBox, OriginalSize, FullScreen, CroppedFull, OriginalOrFull, DstRoi + /// + /// The display is not assigned. + /// -or- + /// Operation failed; internal error. + /// + /// The player already has been disposed of. + /// The specified value to set is invalid. + public PlayerDisplayMode Mode + { + get + { + return _displayMode; + } + set + { + ValidatePlayer(); + + if (_displayMode == value) + { + return; + } + + ValidationUtil.ValidateEnum(typeof(PlayerDisplayMode), value); + + int ret = Interop.Player.SetDisplayMode(Player.GetHandle(), (int)value); + PlayerErrorConverter.ThrowIfError(ret, "Failed to set display mode"); + + _displayMode = value; + } + } + + private bool _isVisible = true; + + /// + /// + /// + /// + /// + /// The display is not assigned. + /// -or- + /// Operation failed; internal error. + /// + /// The player already has been disposed of. + public bool IsVisible + { + get + { + return _isVisible; + } + set + { + ValidatePlayer(); + + if (_isVisible == value) + { + return; + } + + int ret = Interop.Player.SetDisplayVisible(Player.GetHandle(), value); + PlayerErrorConverter.ThrowIfError(ret, "Failed to set the visible state of the display"); + + _isVisible = value; + } + } + + private PlayerDisplayRotation _rotation = PlayerDisplayRotation.RotationNone; + + /// + /// Set/Get Display rotation. + /// + /// RotationNone, Rotation90, Rotation180, Rotation270 + /// + /// The display is not assigned. + /// -or- + /// Operation failed; internal error. + /// + /// The player already has been disposed of. + /// The specified value to set is invalid. + public PlayerDisplayRotation Rotation + { + get + { + return _rotation; + } + set + { + ValidatePlayer(); + + if (_rotation == value) + { + return; + } + + ValidationUtil.ValidateEnum(typeof(PlayerDisplayRotation), value); + + int ret = Interop.Player.SetDisplayRotation(Player.GetHandle(), (int)value); + PlayerErrorConverter.ThrowIfError(ret, "Failed to set the rotation state of the display"); + + _rotation = value; + } + } + } +} diff --git a/src/Tizen.Multimedia/Player/PlayerEnums.cs b/src/Tizen.Multimedia/Player/PlayerEnums.cs index e8eab1f..12fc51b 100644 --- a/src/Tizen.Multimedia/Player/PlayerEnums.cs +++ b/src/Tizen.Multimedia/Player/PlayerEnums.cs @@ -1,237 +1,256 @@ -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 Tizen.Internals.Errors; namespace Tizen.Multimedia { /// - /// Enumeration for player state + /// Specifies errors. /// - public enum PlayerState + /// + /// + public enum PlayerError { - /// - /// Player is not created - /// - None, + NoSuchFile = ErrorCode.NoSuchFile, + InternalError = ErrorCode.InvalidOperation, + NoSpaceOnDevice = PlayerErrorCode.NoSpaceOnDevice, + FeatureNotSupported = ErrorCode.NotSupported, + PermissionDenied = ErrorCode.PermissionDenied, + BufferSpace = ErrorCode.BufferSpace, + SeekFailed = PlayerErrorCode.SeekFailed, + InvalidState = PlayerErrorCode.InvalidState, + NotSupportedFile = PlayerErrorCode.NotSupportedFile, + InvalidUri = PlayerErrorCode.InvalidUri, + SoundPolicy = PlayerErrorCode.SoundPolicyError, + ConnectionFailed = PlayerErrorCode.ConnectionFailed, + VideoCaptureFailed = PlayerErrorCode.VideoCaptureFailed, + DrmExpired = PlayerErrorCode.DrmExpired, + DrmNoLicense = PlayerErrorCode.DrmNoLicense, + DrmFutureUse = PlayerErrorCode.DrmFutureUse, + DrmNotPermitted = PlayerErrorCode.DrmNotPermitted, + ResourceLimit = PlayerErrorCode.ResourceLimit, + ServiceDisconnected = PlayerErrorCode.ServiceDisconnected + } + /// + /// Specifies states that a can have. + /// + public enum PlayerState + { /// - /// Player is created, but not prepared + /// Initial state, unprepared. /// - Idle, + /// + Idle = 1, /// - /// Player is ready to play media + /// Prepared. /// + /// Ready, /// - /// Player is playing media + /// Playing. /// + /// Playing, /// - /// Player is paused while playing media + /// Paused while playing media. /// + /// Paused, + + + //TODO is this needed? + /// + /// Preparing in progress. + /// + /// /> + Preparing, } - /// - /// Enumeration for player display type - /// - public enum DisplayType + internal static class PlayerStateExtensions + { + internal static bool IsAnyOf(this PlayerState thisState, params PlayerState[] states) + { + return Array.IndexOf(states, thisState) != -1; + } + } + + internal enum PlayerDisplayType { /// - /// Overlay surface display + /// Overlay surface display /// Overlay, /// - /// Evas image object surface display + /// Evas image object surface display /// - Evas, + Surface, /// - /// This disposes off buffers + /// This disposes off buffers /// None, } - /// - /// Enumeration for player audio latency mode + /// Specifies audio latency modes for . /// + /// public enum AudioLatencyMode { /// - /// Low audio latency mode + /// Low audio latency mode. /// Low, /// - /// Middle audio latency mode + /// Middle audio latency mode. /// Mid, /// - /// High audio latency mode + /// High audio latency mode. /// High, } /// - /// Enumeration for player display rotation + /// Specifies display rotation modes for . /// - public enum DisplayRotation + /// + public enum PlayerDisplayRotation { /// - /// Display is not rotated + /// Display is not rotated /// RotationNone, /// - /// Display is rotated 90 degrees + /// Display is rotated 90 degrees /// Rotation90, /// - /// Display is rotated 180 degrees + /// Display is rotated 180 degrees /// Rotation180, /// - /// Display is rotated 270 degrees + /// Display is rotated 270 degrees /// Rotation270 } /// - /// Enumeration for player display mode + /// Specifies display modes for /// - public enum DisplayMode + /// + public enum PlayerDisplayMode { /// - /// Letter box + /// Letter box. /// LetterBox, /// - /// Origin size + /// Original size. /// OriginalSize, /// - /// Full-screen + /// Full-screen. /// FullScreen, /// - /// Cropped full-screen + /// Cropped full-screen. /// CroppedFull, /// - /// Origin size (if surface size is larger than video size(width/height)) or - /// Letter box (if video size(width/height) is larger than surface size) + /// Origin size (if surface size is larger than video size(width/height)) or + /// Letter box (if video size(width/height) is larger than surface size). /// OriginalOrFull, } - - /// - /// Enumeration for player stream type - /// - public enum StreamType + internal enum StreamType { /// - /// Container type - /// - Default, - - /// - /// Audio element stream type + /// Audio element stream type /// - Audio, + Audio = 1, /// - /// Video element stream type + /// Video element stream type /// Video, /// - /// Text type + /// Text type /// Text } - - /// - /// Enumeration for Progressive download message + /// Specifies the streaming buffer status. /// - public enum ProgressiveDownloadMessage + /// + /// + public enum MediaStreamBufferStatus { /// - /// Progressive download is started + /// Underrun. /// - Started, + Underrun, /// - /// Progressive download is completed + /// Completed. /// - Completed, + Overflow, } /// - /// Streaming buffer status + /// Specifies the reason for the playback interruption. /// - public enum StreamingBufferStatus + /// + public enum PlaybackIntrruptionReason { - /// - /// Underrun - /// - Underrun, - - /// - /// Completed - /// - Overflow, + ResourceConflict = 4 } - /// - /// Enumeration for source type + /// Specifies keys for the metadata. /// - public enum PlayerSourceType + /// + public enum StreamMetadataKey { - /// - /// Uri source - /// - Uri, - - /// - /// memory buffer source - /// - Memory, - - /// - /// stream source - /// - Stream, + Album, + Artist, + Author, + Genre, + Title, + Year } - - /// - /// Enumeration for Content info - /// - internal enum ContentInfoKey - { - Album, - Artist, - Author, - Genre, - Title, - Year - } - - } diff --git a/src/Tizen.Multimedia/Player/PlayerError.cs b/src/Tizen.Multimedia/Player/PlayerError.cs new file mode 100644 index 0000000..fb41136 --- /dev/null +++ b/src/Tizen.Multimedia/Player/PlayerError.cs @@ -0,0 +1,124 @@ +/* + * 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 Tizen.Internals.Errors; + +namespace Tizen.Multimedia +{ + internal enum PlayerErrorCode + { + None = ErrorCode.None, + InvalidArgument = ErrorCode.InvalidParameter, + OutOfMemory = ErrorCode.OutOfMemory, + NoSuchFile = ErrorCode.NoSuchFile, + InvalidOperation = ErrorCode.InvalidOperation, + NoSpaceOnDevice = ErrorCode.FileNoSpaceOnDevice, + FeatureNotSupported = ErrorCode.NotSupported, + PermissionDenied = ErrorCode.PermissionDenied, + NoBufferSpace = ErrorCode.BufferSpace, + TizenPlayerError = -0x01940000, + PlayerErrorClass = TizenPlayerError | 0x20, + SeekFailed = PlayerErrorClass | 0x01, + InvalidState = PlayerErrorClass | 0x02, + NotSupportedFile = PlayerErrorClass | 0x03, + InvalidUri = PlayerErrorClass | 0x04, + SoundPolicyError = PlayerErrorClass | 0x05, + ConnectionFailed = PlayerErrorClass | 0x06, + VideoCaptureFailed = PlayerErrorClass | 0x07, + DrmExpired = PlayerErrorClass | 0x08, + DrmNoLicense = PlayerErrorClass | 0x09, + DrmFutureUse = PlayerErrorClass | 0x0a, + DrmNotPermitted = PlayerErrorClass | 0x0b, + ResourceLimit = PlayerErrorClass | 0x0c, + ServiceDisconnected = PlayerErrorClass | 0x0d + } + + internal static class PlayerErrorConverter + { + internal static void ThrowIfError(int errorCode, string errorMessage) + { + if (errorCode == (int)PlayerErrorCode.None) + { + return; + } + PlayerErrorCode err = (PlayerErrorCode)errorCode; + + string msg = $"{ (errorMessage ?? "Operation failed") } : { err.ToString() }."; + + switch ((PlayerErrorCode)errorCode) + { + case PlayerErrorCode.InvalidArgument: + case PlayerErrorCode.InvalidUri: + case PlayerErrorCode.NoSuchFile: + throw new ArgumentException(msg); + + case PlayerErrorCode.OutOfMemory: + case PlayerErrorCode.NoSpaceOnDevice: + throw new OutOfMemoryException(msg); + + case PlayerErrorCode.PermissionDenied: + case PlayerErrorCode.InvalidOperation: + case PlayerErrorCode.InvalidState: + case PlayerErrorCode.FeatureNotSupported: + case PlayerErrorCode.SeekFailed: + case PlayerErrorCode.NotSupportedFile: + case PlayerErrorCode.ConnectionFailed: + case PlayerErrorCode.VideoCaptureFailed: + case PlayerErrorCode.DrmExpired: + case PlayerErrorCode.DrmNoLicense: + case PlayerErrorCode.DrmFutureUse: + case PlayerErrorCode.DrmNotPermitted: + throw new InvalidOperationException(msg); + + case PlayerErrorCode.NoBufferSpace: + throw new NoBufferSpaceException(msg); + + case PlayerErrorCode.ResourceLimit: + throw new ResouceLimitException(msg); + } + + throw new Exception(msg); + } + } + /// + /// The exception that is thrown when there is no available space in a buffer. + /// + public class NoBufferSpaceException : InvalidOperationException + { + /// + /// Initializes a new instance of the NoBufferSpaceException class with a specified error message. + /// + /// Error description. + public NoBufferSpaceException(string message) : base(message) + { + } + } + + /// + /// The exception that is thrown when there is no available resource for internal use. + /// + public class ResouceLimitException : InvalidOperationException + { + /// + /// Initializes a new instance of the ResouceLimitException class with a specified error message. + /// + /// Error description. + public ResouceLimitException(string message) : base(message) + { + } + } +} + diff --git a/src/Tizen.Multimedia/Player/PlayerErrorFactory.cs b/src/Tizen.Multimedia/Player/PlayerErrorFactory.cs deleted file mode 100644 index a08c5fb..0000000 --- a/src/Tizen.Multimedia/Player/PlayerErrorFactory.cs +++ /dev/null @@ -1,82 +0,0 @@ -/// Player Error factory -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung.using System; -/// - -using System; -using Tizen.Internals.Errors; - -namespace Tizen.Multimedia -{ - internal enum PlayerError - { - None = ErrorCode.None, - InvalidParameter = ErrorCode.InvalidParameter, - OutOfMemory = ErrorCode.OutOfMemory, - NoSuchFile = ErrorCode.NoSuchFile, - InvalidOperation = ErrorCode.InvalidOperation, - NoSpaceOnDevice = ErrorCode.FileNoSpaceOnDevice, - FeatureNotSupported = ErrorCode.NotSupported, - PermissionDenied = ErrorCode.PermissionDenied, - BufferSpace = ErrorCode.BufferSpace, - TizenPlayerError = -0x01940000, - PlayerErrorClass = TizenPlayerError | 0x20, - SeekFailed = PlayerErrorClass | 0x01, - InvalidState = PlayerErrorClass | 0x02, - FileNotSupported = PlayerErrorClass | 0x03, - InvalidUri = PlayerErrorClass | 0x04, - SoundPolicyError = PlayerErrorClass | 0x05, - ConnectionFailed = PlayerErrorClass | 0x06, - VideoCaptureFailed = PlayerErrorClass | 0x07, - DrmExpired = PlayerErrorClass | 0x08, - DrmNoLicense = PlayerErrorClass | 0x09, - DrmFutureUse = PlayerErrorClass | 0x0a, - DrmNotPermitted = PlayerErrorClass | 0x0b, - ResourceLimit = PlayerErrorClass | 0x0c, - ServiceDisconnected = PlayerErrorClass | 0x0d - }; - - internal static class PlayerErrorFactory - { - internal static void ThrowException(int errorCode, string errorMessage = null, string paramName = null) - { - PlayerError err = (PlayerError) errorCode; - if(string.IsNullOrEmpty(errorMessage)) - { - errorMessage = err.ToString(); - } - switch((PlayerError)errorCode) - { - case PlayerError.InvalidParameter: - throw new ArgumentException(errorMessage, paramName); - - case PlayerError.InvalidState: - case PlayerError.OutOfMemory: - case PlayerError.NoSuchFile: - case PlayerError.InvalidOperation: - case PlayerError.NoSpaceOnDevice: - case PlayerError.FeatureNotSupported: - case PlayerError.SeekFailed: - case PlayerError.FileNotSupported: - case PlayerError.InvalidUri: - case PlayerError.SoundPolicyError: - case PlayerError.ConnectionFailed: - case PlayerError.VideoCaptureFailed: - case PlayerError.DrmExpired: - case PlayerError.DrmNoLicense: - case PlayerError.DrmFutureUse: - case PlayerError.DrmNotPermitted: - case PlayerError.ResourceLimit: - case PlayerError.PermissionDenied: - throw new InvalidOperationException(errorMessage); - } - } - } -} - diff --git a/src/Tizen.Multimedia/MediaCodec/EosReachedEventArgs.cs b/src/Tizen.Multimedia/Player/PlayerErrorOccurredEventArgs.cs similarity index 54% rename from src/Tizen.Multimedia/MediaCodec/EosReachedEventArgs.cs rename to src/Tizen.Multimedia/Player/PlayerErrorOccurredEventArgs.cs index a5d5c0e..fb104b2 100644 --- a/src/Tizen.Multimedia/MediaCodec/EosReachedEventArgs.cs +++ b/src/Tizen.Multimedia/Player/PlayerErrorOccurredEventArgs.cs @@ -13,21 +13,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - using System; -namespace Tizen.Multimedia.MediaCodec +namespace Tizen.Multimedia { /// - /// Provides data for the event. + /// Provides data for the event. /// - public class EosReachedEventArgs : EventArgs + public class PlayerErrorOccurredEventArgs : EventArgs { /// - /// Initializes a new instance of the EosReachedEventArgs class. + /// Initialize a new instance of the PlayerErrorOccurredEventArgs class. /// - public EosReachedEventArgs() + /// The value indicating what kind of error occurred. + public PlayerErrorOccurredEventArgs(PlayerError error) + { + Error = error; + } + + /// + /// Gets the error. + /// + public PlayerError Error { get; } + + public override string ToString() { + return $"Error : { Error }"; } } } diff --git a/src/Tizen.Multimedia/Player/PlayerTrackInfo.cs b/src/Tizen.Multimedia/Player/PlayerTrackInfo.cs new file mode 100644 index 0000000..6ca50a1 --- /dev/null +++ b/src/Tizen.Multimedia/Player/PlayerTrackInfo.cs @@ -0,0 +1,152 @@ +/* + * 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; + +namespace Tizen.Multimedia +{ + /// + /// Provides means to retrieve track information. + /// + /// + /// + public class PlayerTrackInfo + { + private readonly int _streamType; + private readonly Player _owner; + + internal PlayerTrackInfo(Player player, StreamType streamType) + { + Debug.Assert(player != null); + + _streamType = (int)streamType; + _owner = player; + } + + /// + /// Gets the number of tracks. + /// + /// The number of tracks. + /// The that owns this instance must be in the , or state. + /// The that this instance belongs to has been disposed. + /// The that this instance belongs to is not in the valid state. + public int GetCount() + { + _owner.ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused); + + int count = 0; + int ret = Interop.Player.GetTrackCount(_owner.GetHandle(), _streamType, out count); + PlayerErrorConverter.ThrowIfError(ret, "Failed to initialize the track of the player"); + + return count; + } + + /// + /// Gets the language code for the specified index or null if the language is undefined. + /// + /// The number of tracks. + /// + /// The that owns this instance must be in the , or state. + /// The language codes are defined in ISO 639-1. + /// + /// The that this instance belongs to has been disposed. + /// The that this instance belongs to is not in the valid state. + /// + /// index is less than zero. + /// -or- + /// index is equal to or greater than + /// + public string GetLanguageCode(int index) + { + _owner.ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused); + + if (index < 0 || GetCount() <= index) + { + throw new ArgumentOutOfRangeException(nameof(index), index, + $"valid index range is 0 <= x < {nameof(GetCount)}(), but got { index }."); + } + + IntPtr code = IntPtr.Zero; + + try + { + int ret = Interop.Player.GetTrackLanguageCode( + _owner.GetHandle(), _streamType, index, out code); + + PlayerErrorConverter.ThrowIfError(ret, "Failed to get the selected index of the player"); + + string result = Marshal.PtrToStringAnsi(code); + + if (result == "und") + { + return null; + } + + return result; + } + finally + { + Interop.Libc.Free(code); + } + } + + /// + /// Gets the selected track index. + /// + /// The currently selected track index. + /// The that owns this instance must be in the , or state. + /// The that this instance belongs to has been disposed. + /// The that this instance belongs to is not in the valid state. + public int GetSelected() + { + _owner.ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused); + + int value = 0; + int ret = Interop.Player.GetCurrentTrack(_owner.GetHandle(), _streamType, out value); + PlayerErrorConverter.ThrowIfError(ret, "Failed to get the selected index of the player"); + + return value; + } + + /// + /// Selects the track. + /// + /// The index to select. + /// The that owns this instance must be in the , or state. + /// The that this instance belongs to has been disposed. + /// The that this instance belongs to is not in the valid state. + /// + /// index is less than zero. + /// -or- + /// index is equal to or greater than + /// + public void SetSelected(int index) + { + if (index < 0 || GetCount() <= index) + { + throw new ArgumentOutOfRangeException(nameof(index), index, + $"valid index range is 0 <= x < {nameof(GetCount)}(), but got { index }."); + } + + _owner.ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused); + + int ret = Interop.Player.SelectTrack(_owner.GetHandle(), _streamType, index); + PlayerErrorConverter.ThrowIfError(ret, "Failed to set the selected index of the player"); + } + + } +} diff --git a/src/Tizen.Multimedia/Player/ProgressiveDownloadMessageEventArgs.cs b/src/Tizen.Multimedia/Player/ProgressiveDownloadMessageEventArgs.cs deleted file mode 100644 index f140a8d..0000000 --- a/src/Tizen.Multimedia/Player/ProgressiveDownloadMessageEventArgs.cs +++ /dev/null @@ -1,47 +0,0 @@ -/// This File contains ProgressiveDownloadMessageEventArgs class -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - -using System; - -namespace Tizen.Multimedia -{ - - /// - /// ProgressiveDownloadMessage event arguments - /// - /// - /// ProgressiveDownloadMessage event arguments - /// - public class ProgressiveDownloadMessageEventArgs : EventArgs - { - internal ProgressiveDownloadMessage _message; - - /// - /// Constructor - /// - internal ProgressiveDownloadMessageEventArgs(ProgressiveDownloadMessage message) - { - _message = message; - } - - /// - /// Get Progressive download message. - /// - /// 0 - 100 - public ProgressiveDownloadMessage Message - { - get - { - return _message; - } - } - } -} \ No newline at end of file diff --git a/src/Tizen.Multimedia/Player/ProgressiveDownloadStatus.cs b/src/Tizen.Multimedia/Player/ProgressiveDownloadStatus.cs deleted file mode 100644 index 3970c16..0000000 --- a/src/Tizen.Multimedia/Player/ProgressiveDownloadStatus.cs +++ /dev/null @@ -1,59 +0,0 @@ -/// Progressive Download Status -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - -using System; - -namespace Tizen.Multimedia -{ - - /// - /// DownloadProgress - /// - /// - /// Contains Progressive download status. ProgressiveDownloadStatus object is null initially. - /// It is created only when playback starts. - /// - public class ProgressiveDownloadStatus - { - internal ulong _current; - internal ulong _totalSize; - - internal ProgressiveDownloadStatus(ulong current, ulong totalSize) - { - _current = current; - _totalSize = totalSize; - } - - /// - /// Get current download position (bytes) - /// - /// current download position - public ulong Current - { - get - { - return _current; - } - } - - /// - /// Get total size of the file (bytes) - /// - /// Total size of file (bytes) - public ulong TotalSize - { - get - { - return _totalSize; - } - } - } -} \ No newline at end of file diff --git a/src/Tizen.Multimedia/Player/SeekOffsetEventArgs.cs b/src/Tizen.Multimedia/Player/SeekOffsetEventArgs.cs deleted file mode 100644 index 2b146ad..0000000 --- a/src/Tizen.Multimedia/Player/SeekOffsetEventArgs.cs +++ /dev/null @@ -1,48 +0,0 @@ -/// This File contains SeekOffsetEventArgs class -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - -using System; - -namespace Tizen.Multimedia -{ - - /// - /// SeekOffset event arguments - /// - /// - /// SeekOffset event arguments - /// - public class SeekOffsetEventArgs : EventArgs - { - internal UInt64 _offset; - - /// - /// Constructor. - /// - internal SeekOffsetEventArgs(UInt64 offset) - { - _offset = offset; - } - - /// - /// Get seek offset. - /// - /// byte position to seek - public UInt64 Offset - { - get - { - return _offset; - } - } - - } -} \ No newline at end of file diff --git a/src/Tizen.Multimedia/Player/StreamInfo.cs b/src/Tizen.Multimedia/Player/StreamInfo.cs new file mode 100644 index 0000000..90754d6 --- /dev/null +++ b/src/Tizen.Multimedia/Player/StreamInfo.cs @@ -0,0 +1,314 @@ +/* + * 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 +{ + /// + /// Represents properties for audio stream. + /// + public struct AudioStreamProperties + { + /// + /// Initialize a new instance of the AudioStreamProperties struct with the specified sample rate, channels and bit rate. + /// + public AudioStreamProperties(int sampleRate, int channels, int bitRate) + { + SampleRate = sampleRate; + Channels = channels; + BitRate = bitRate; + } + + /// + /// Gets or sets the sample rate. + /// + /// The audio sample rate(Hz). + public int SampleRate + { + get; + set; + } + + /// + /// Gets or sets the channels. + /// + public int Channels + { + get; + set; + } + + /// + /// Gets or sets the bit rate. + /// + /// The audio bit rate(Hz). + public int BitRate + { + get; + set; + } + + public override string ToString() + { + return $"SampleRate : { SampleRate }, Channels : { Channels }, BitRate : { BitRate }"; + } + } + + /// + /// Represents properties for video stream. + /// + public struct VideoStreamProperties + { + /// + /// Initialize a new instance of the VideoStreamProperties struct with the specified fps, bit rate and size. + /// + public VideoStreamProperties(int fps, int bitRate, Size size) + { + Fps = fps; + BitRate = bitRate; + Size = size; + } + /// + /// Initialize a new instance of the VideoStreamProperties struct with the specified fps, bit rate, width and height. + /// + public VideoStreamProperties(int fps, int bitRate, int width, int height) + { + Fps = fps; + BitRate = bitRate; + Size = new Size(width, height); + } + + /// + /// Gets or sets the fps. + /// + public int Fps + { + get; + set; + } + /// + /// Gets or sets the bit rate. + /// + public int BitRate + { + get; + set; + } + + /// + /// Gets or sets the size. + /// + public Size Size + { + get; + set; + } + + public override string ToString() + { + return $"Fps : { Fps }, BitRate : { BitRate }, Size : [{ Size }]"; + } + } + + + /// + /// Provides means to retrieve stream information + /// + public class StreamInfo + { + internal StreamInfo(Player owner) + { + Player = owner; + } + + /// + /// Retrieves the album art of the stream or null if there is no album art data. + /// + /// The that owns this instance must be in the , or state. + /// The that this instance belongs to has been disposed. + /// The that this instance belongs to is not in the valid state. + public byte[] GetAlbumArt() + { + Player.ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused); + + int size; + IntPtr art; + int ret = Interop.Player.GetAlbumArt(Player.GetHandle(), out art, out size); + PlayerErrorConverter.ThrowIfError(ret, "Failed to get the album art"); + + if (art == IntPtr.Zero || size == 0) + { + return null; + } + + byte[] albumArt = new byte[size]; + Marshal.Copy(art, albumArt, 0, size); + return albumArt; + } + + private string GetCodecInfo(bool audioInfo) + { + Player.ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused); + + IntPtr audioPtr = IntPtr.Zero; + IntPtr videoPtr = IntPtr.Zero; + try + { + int ret = Interop.Player.GetCodecInfo(Player.GetHandle(), out audioPtr, out videoPtr); + PlayerErrorConverter.ThrowIfError(ret, "Failed to get codec info"); + + if (audioInfo) + { + return Marshal.PtrToStringAnsi(audioPtr); + } + else + { + return Marshal.PtrToStringAnsi(videoPtr); + } + } + finally + { + Interop.Libc.Free(audioPtr); + Interop.Libc.Free(videoPtr); + } + } + + /// + /// Retrieves the codec name of audio or null if there is no audio. + /// + public string GetAudioCodec() + { + return GetCodecInfo(true); + } + + /// + /// Retrieves the codec name of video or null if there is no video. + /// + public string GetVideoCodec() + { + return GetCodecInfo(false); + } + + + /// + /// Gets the duration. + /// + /// The that owns this instance must be in the , or state. + /// The that this instance belongs to has been disposed. + /// The that this instance belongs to is not in the valid state. + public int GetDuration() + { + Player.ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused); + + int duration = 0; + PlayerErrorConverter.ThrowIfError(Interop.Player.GetDuration(Player.GetHandle(), out duration), + "Failed to get the duration"); + return duration; + } + + /// + /// Gets the properties of audio. + /// + /// The that owns this instance must be in the , or state. + /// The that this instance belongs to has been disposed. + /// The that this instance belongs to is not in the valid state. + public AudioStreamProperties GetAudioProperies() + { + Player.ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused); + + int sampleRate = 0; + int channels = 0; + int bitRate = 0; + + int ret = Interop.Player.GetAudioStreamInfo(Player.GetHandle(), + out sampleRate, out channels, out bitRate); + PlayerErrorConverter.ThrowIfError(ret, "Failed to get audio stream info"); + + // TODO should we check value is zero and return null? + + return new AudioStreamProperties(sampleRate, channels, bitRate); + } + + /// + /// Gets the properties of video. + /// + /// The that owns this instance must be in the , or state. + /// The that this instance belongs to has been disposed. + /// The that this instance belongs to is not in the valid state. + public VideoStreamProperties GetVideoProperties() + { + Player.ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused); + + int fps = 0; + int bitRate = 0; + int ret = Interop.Player.GetVideoStreamInfo(Player.GetHandle(), out fps, out bitRate); + + PlayerErrorConverter.ThrowIfError(ret, "Failed to get the video info"); + + // TODO should we check value is zero and return null? + + return new VideoStreamProperties(fps, bitRate, GetVideoSize()); + } + + private Size GetVideoSize() + { + Player.ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused); + + int height = 0; + int width = 0; + int ret = Interop.Player.GetVideoSize(Player.GetHandle(), out width, out height); + + PlayerErrorConverter.ThrowIfError(ret, "Failed to get the video size"); + + return new Size(width, height); + } + + /// + /// Gets the metadata with the specified key. + /// + /// The key to query. + /// The that owns this instance must be in the , or state. + /// The that this instance belongs to has been disposed. + /// The that this instance belongs to is not in the valid state. + public string GetMetadata(StreamMetadataKey key) + { + Player.ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused); + + ValidationUtil.ValidateEnum(typeof(StreamMetadataKey), key); + + IntPtr ptr = IntPtr.Zero; + + try + { + int ret = Interop.Player.GetContentInfo(Player.GetHandle(), (int)key, out ptr); + PlayerErrorConverter.ThrowIfError(ret, $"Failed to get the meta data with the key '{ key }'"); + + + return Marshal.PtrToStringAnsi(ptr); + } + finally + { + Interop.Libc.Free(ptr); + } + } + + /// + /// Gets the that owns this instance. + /// + public Player Player { get; } + } +} diff --git a/src/Tizen.Multimedia/Player/StreamInformation.cs b/src/Tizen.Multimedia/Player/StreamInformation.cs deleted file mode 100644 index 38179c8..0000000 --- a/src/Tizen.Multimedia/Player/StreamInformation.cs +++ /dev/null @@ -1,272 +0,0 @@ -/// Audio Stream Information -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - -using System; -using System.Runtime.InteropServices; - - -namespace Tizen.Multimedia -{ - /// - /// Stream information - /// - /// - /// This class provides properties and API that are required for fetching - /// metadata of a media stream. - /// - public class StreamInformation - { - internal IntPtr _playerHandle; - internal PlayerContentInfo _contentInfo; - - internal StreamInformation() - { - } - - /// - /// Get album art. - /// - /// byte[] - public byte[] AlbumArt - { - get - { - int ret, size; - IntPtr art; - ret = Interop.Player.GetAlbumArt(_playerHandle, out art, out size); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get album art" + (PlayerError)ret); - Console.WriteLine("GetAlbumArt() failed " + ret); - } - else - { - byte[] albumArt; - albumArt = new byte[size]; - Marshal.Copy(art, albumArt, 0, size); - return albumArt; - } - return null; - } - } - - /// - /// Get AudioCodec. - /// - /// AudioCodec string - public string AudioCodec - { - get - { - IntPtr audioCodec = IntPtr.Zero, videoCodec = IntPtr.Zero; - try - { - int ret = Interop.Player.GetCodecInfo(_playerHandle, out audioCodec, out videoCodec); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get codec info" + (PlayerError)ret); - } - - return Marshal.PtrToStringAnsi(audioCodec); - } - finally - { - Interop.Libc.Free(audioCodec); - Interop.Libc.Free(videoCodec); - } - } - } - - /// - /// Get Duration. - /// - /// duration in milliseconds - public int Duration - { - get - { - int duration; - int ret = Interop.Player.GetDuration(_playerHandle, out duration); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get duration info" + (PlayerError)ret); - } - return duration; - } - } - - /// - /// Get Sample rate. - /// - /// The audio sample rate [Hz] - public int AudioSampleRate - { - get - { - int sampleRate, channels, bitRate; - int ret = Interop.Player.GetAudioStreamInfo(_playerHandle, out sampleRate, out channels, out bitRate); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get audio stream info" + (PlayerError)ret); - } - return sampleRate; - } - } - - /// - /// Channels - /// - /// The audio channels - public int AudioChannels - { - get - { - int sampleRate, channels, bitRate; - int ret = Interop.Player.GetAudioStreamInfo(_playerHandle, out sampleRate, out channels, out bitRate); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get audio channels info" + (PlayerError)ret); - } - return channels; - } - } - - /// - /// Audio bit rate. - /// - /// bit rate [Hz] - public int AudioBitRate - { - get - { - int sampleRate, channels, bitRate; - int ret = Interop.Player.GetAudioStreamInfo(_playerHandle, out sampleRate, out channels, out bitRate); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get audio bitrate info" + (PlayerError)ret); - } - return bitRate; - } - } - - - /// - /// VideoCodec - /// - /// video codec string - public string VideoCodec - { - get - { - IntPtr audioCodec = IntPtr.Zero, videoCodec = IntPtr.Zero; - try - { - int ret = Interop.Player.GetCodecInfo(_playerHandle, out audioCodec, out videoCodec); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get codec info" + (PlayerError)ret); - } - return Marshal.PtrToStringAnsi(videoCodec); - } - finally - { - Interop.Libc.Free(audioCodec); - Interop.Libc.Free(videoCodec); - } - } - } - - /// - /// FPS - /// - /// int Frames per second - public int VideoFps - { - get - { - int fps, bitRate; - int ret = Interop.Player.GetVideoStreamInfo(_playerHandle, out fps, out bitRate); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get video fps info" + (PlayerError)ret); - } - return fps; - } - } - - /// - /// Video bit rate. - /// - /// bit rate [Hz] - public int VideoBitRate - { - get - { - int fps, bitRate; - int ret = Interop.Player.GetVideoStreamInfo(_playerHandle, out fps, out bitRate); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get video bitrate info" + (PlayerError)ret); - } - return bitRate; - } - } - - /// - /// Get Video Height. - /// - /// video height - public int VideoHeight - { - get - { - int height, width; - int ret = Interop.Player.GetVideoSize(_playerHandle, out width, out height); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get video height" + (PlayerError)ret); - } - return height; - } - } - - /// - /// Get Video Width. - /// - /// video width - public int VideoWidth - { - get - { - int height, width; - int ret = Interop.Player.GetVideoSize(_playerHandle, out width, out height); - if (ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Failed to get video width" + (PlayerError)ret); - } - return width; - } - } - - /// - /// Get Player content info. - /// - /// metadata - public PlayerContentInfo ContentInfo - { - get - { - return _contentInfo; - } - } - - } -} diff --git a/src/Tizen.Multimedia/Player/StreamingConfiguration.cs b/src/Tizen.Multimedia/Player/StreamingConfiguration.cs deleted file mode 100644 index 7557a02..0000000 --- a/src/Tizen.Multimedia/Player/StreamingConfiguration.cs +++ /dev/null @@ -1,299 +0,0 @@ -/// Streaming configuration -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - -using System; - - -namespace Tizen.Multimedia -{ - /// - /// Streaming configuration - /// - /// - /// This class provides properties and API that are required for streaming - /// playback operations. - /// - public class StreamingConfiguration - { - internal IntPtr _playerHandle; - internal string _cookie; - internal string _userAgent; - internal string _progressiveDownloadPath; - private EventHandler _bufferingProgress; - private Interop.Player.BufferingProgressCallback _bufferingProgressCallback; - private EventHandler _pdMessage; - private Interop.Player.ProgressiveDownloadMessageCallback _pdMessageCallback; - private EventHandler _videoStreamChanged; - private Interop.Player.VideoStreamChangedCallback _videoStreamChangedCallback; - - - internal StreamingConfiguration(IntPtr handle) - { - _playerHandle = handle; - } - - - /// - /// BufferingProgressChanged event is raised when there is a change in the buffering status of a media stream - /// - public event EventHandler BufferingProgressChanged - { - add - { - if(_bufferingProgress == null) { - RegisterBufferingProgressEvent(); - } - _bufferingProgress += value; - } - remove - { - _bufferingProgress -= value; - if(_bufferingProgress == null) { - UnregisterBufferingProgressEvent(); - } - } - } - - /// - /// ProgressiveDownloadMessageChanged event is raised when progressive download is started or completed. - /// - public event EventHandler ProgressiveDownloadMessageChanged - { - add - { - if(_pdMessage == null) { - RegisterProgressiveDownloadMessageEvent(); - } - _pdMessage += value; - } - remove - { - _pdMessage -= value; - if(_pdMessage == null) { - UnregisterProgressiveDownloadMessageEvent(); - } - } - } - - /// - /// Video stream changed event is raised to notify the video stream changed. - /// - public event EventHandler VideoStreamChanged - { - add - { - if(_videoStreamChanged == null) { - RegisterVideoStreamChangedEvent(); - } - _videoStreamChanged += value; - } - remove - { - _videoStreamChanged -= value; - if(_videoStreamChanged == null) { - UnregisterVideoStreamChanged(); - } - } - } - - /// - /// Set/Get Progressive download path. - /// - /// path string - public string ProgressiveDownloadPath - { - set - { - int ret = Interop.Player.SetProgressiveDownloadPath(_playerHandle, value); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Setting progressive download path failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Setting progressive download path failed"); - } - _progressiveDownloadPath = value; - } - get - { - return _progressiveDownloadPath; - } - } - - /// - /// Get Streaming download Progress. - /// - /// download progress int start and current [0 to 100] - public DownloadProgress DownloadProgress - { - get - { - DownloadProgress progress = null; - int start, current; - int ret = Interop.Player.GetStreamingDownloadProgress(_playerHandle, out start, out current); - if(ret == (int)PlayerError.None) - { - progress = new DownloadProgress(start, current); - } - else - { - Log.Error(PlayerLog.LogTag, "Getting download progress failed" + (PlayerError)ret); - } - return progress; - } - } - - /// - /// Get progressive download status. - /// - /// progressive download status ulong current and total size - public ProgressiveDownloadStatus ProgressiveDownloadStatus - { - get - { - ProgressiveDownloadStatus status = null; - ulong current, totalSize; - int ret = Interop.Player.GetProgressiveDownloadStatus(_playerHandle, out current, out totalSize); - if(ret == (int)PlayerError.None) - { - status = new ProgressiveDownloadStatus(current, totalSize); - } - else - { - Log.Error(PlayerLog.LogTag, "Getting progressive download status failed" + (PlayerError)ret); - } - - return status; - } - } - - /// - /// Set/Get cookie. - /// - /// cookie string - public string Cookie - { - set - { - int ret = Interop.Player.SetStreamingCookie(_playerHandle, value, value.Length + 1); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Setting cookie failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Setting cookie failed"); - } - _cookie = value; - } - get - { - return _cookie; - } - } - - /// - /// Set/Get User agent. - /// - /// user agent string - public string UserAgent - { - set - { - int ret = Interop.Player.SetStreamingUserAgent(_playerHandle, value, value.Length + 1); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Setting user agent failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Setting user agent failed"); - } - _userAgent = value; - } - get - { - return _userAgent; - } - } - - - private void RegisterBufferingProgressEvent() - { - _bufferingProgressCallback = (int percent, IntPtr userData) => - { - BufferingProgressEventArgs eventArgs = new BufferingProgressEventArgs(percent); - _bufferingProgress?.Invoke(this, eventArgs); - }; - - int ret = Interop.Player.SetBufferingCb(_playerHandle, _bufferingProgressCallback, IntPtr.Zero); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Setting Buffering callback failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Setting Buffering callback failed"); - } - - } - - private void UnregisterBufferingProgressEvent() - { - int ret = Interop.Player.UnsetBufferingCb(_playerHandle); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Unsetting Buffering callback failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Unsetting Buffering callback failed"); - } - - } - private void RegisterProgressiveDownloadMessageEvent() - { - _pdMessageCallback = (int type, IntPtr userData) => - { - ProgressiveDownloadMessageEventArgs eventArgs = new ProgressiveDownloadMessageEventArgs((ProgressiveDownloadMessage)type); - _pdMessage?.Invoke(this, eventArgs); - }; - int ret = Interop.Player.SetProgressiveDownloadMessageCb(_playerHandle, _pdMessageCallback, IntPtr.Zero); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Setting progressive download callback failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Setting progressive download callback failed"); - } - } - - private void UnregisterProgressiveDownloadMessageEvent() - { - int ret = Interop.Player.UnsetProgressiveDownloadMessageCb(_playerHandle); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Unsetting progressive download callback failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Unsetting progressive download callback failed"); - } - - } - - private void RegisterVideoStreamChangedEvent() - { - _videoStreamChangedCallback = (int width, int height, int fps, int bitrate, IntPtr userData) => - { - VideoStreamEventArgs eventArgs = new VideoStreamEventArgs(height, width, fps, bitrate); - _videoStreamChanged?.Invoke(this, eventArgs); - }; - int ret = Interop.Player.SetVideoStreamChangedCb(_playerHandle, _videoStreamChangedCallback, IntPtr.Zero); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Setting video stream changed callback failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Setting video stream changed callback failed"); - } - } - - private void UnregisterVideoStreamChanged() - { - int ret = Interop.Player.UnsetVideoStreamChangedCb(_playerHandle); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Unsetting video stream changed callback failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Unsetting video stream changed callback failed"); - } - } - } -} diff --git a/src/Tizen.Multimedia/Player/Subtitle.cs b/src/Tizen.Multimedia/Player/Subtitle.cs deleted file mode 100644 index 852ded3..0000000 --- a/src/Tizen.Multimedia/Player/Subtitle.cs +++ /dev/null @@ -1,265 +0,0 @@ -/// Subtitle -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - -using System; -using System.Collections.Generic; - -namespace Tizen.Multimedia -{ - /// - /// Subtitle - /// - /// - /// This class provides properties and events that are required for subtitle - /// during playback. - /// - /// Note: Newly created subtitle has to be set to the 'Subtitle' property of the player object. - /// Else, operations on subtitle object do not work. - /// - public class Subtitle - { - internal IntPtr _playerHandle; - internal string _path; - - internal string _subPath - { - set - { - int ret = Interop.Player.SetSubtitlePath(_playerHandle, value); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Setting subtitle path failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Setting subtitle path failed"); - } - } - } - - - - private EventHandler _subtitleUpdated; - private Interop.Player.SubtitleUpdatedCallback _subtitleUpdatedCallback; - - /// - /// Subtitle Constructor. - /// Note: Newly created subtitle has to be set to the 'Subtitle' property of the player object. - /// Else, operations on subtitle object do not work. - /// subtitle path - public Subtitle(string path) - { - _path = path; - } - - /// - /// Subtitle event is raised when the subtitle is updated - /// - public event EventHandler Updated - { - add - { - if(_subtitleUpdated == null) - { - RegisterSubtitleUpdatedEvent(); - } - _subtitleUpdated += value; - } - remove - { - _subtitleUpdated -= value; - if(_subtitleUpdated == null) - { - UnregisterSubtitleUpdatedEvent(); - } - } - } - - /// - /// Set position offset. - /// - /// position in milli seconds - public int Position - { - set - { - int ret = Interop.Player.SetSubtitlePositionOffset(_playerHandle, value); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Setting position offset failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Setting position offset failed"); - } - } - } - - - /// - /// Get Text track. - /// - /// Text track list - public IEnumerable TextTrack - { - get - { - string langCode; - int curTrack; - int ret; - int tracks = 0; - List textTrack = new List(); - - ret = Interop.Player.GetTrackCount(_playerHandle, (int)StreamType.Text, out tracks); - if(ret == (int)PlayerError.None) - { - ret = Interop.Player.GetCurrentTrack(_playerHandle, (int)StreamType.Text, out curTrack); - if(ret == (int)PlayerError.None && tracks > 0) - { - for(int idx = 0; idx < tracks; idx++) - { - bool activated = (curTrack == idx ? true : false); - ret = Interop.Player.GetTrackLanguageCode(_playerHandle, (int)StreamType.Text, idx, out langCode); - if(ret == (int)PlayerError.None) - { - SubtitleTrack st = new SubtitleTrack(langCode, activated); - textTrack.Add(st); - } else - { - Log.Error(PlayerLog.LogTag, "Getting text track language code failed" + (PlayerError)ret); - } - } - } else - { - Log.Error(PlayerLog.LogTag, "Getting current track index failed" + (PlayerError)ret); - } - } else - { - Log.Error(PlayerLog.LogTag, "Getting track count failed" + (PlayerError)ret); - } - - return textTrack; - } - } - - /// - /// Get Audio track. - /// - /// Audio track list - public IEnumerable AudioTrack - { - get - { - string langCode; - int curTrack; - int ret; - int tracks = 0; - List audioTrack = new List(); - - ret = Interop.Player.GetTrackCount(_playerHandle, (int)StreamType.Audio, out tracks); - if(ret == (int)PlayerError.None) - { - ret = Interop.Player.GetCurrentTrack(_playerHandle, (int)StreamType.Audio, out curTrack); - if(ret == (int)PlayerError.None && tracks > 0) - { - for(int idx = 0; idx < tracks; idx++) - { - bool activated = (curTrack == idx ? true : false); - ret = Interop.Player.GetTrackLanguageCode(_playerHandle, (int)StreamType.Audio, idx, out langCode); - if(ret == (int)PlayerError.None) - { - SubtitleTrack st = new SubtitleTrack(langCode, activated); - audioTrack.Add(st); - } else - { - Log.Error(PlayerLog.LogTag, "Getting audio track language code failed" + (PlayerError)ret); - } - } - } else - { - Log.Error(PlayerLog.LogTag, "Getting audio track index failed" + (PlayerError)ret); - } - } else - { - Log.Error(PlayerLog.LogTag, "Getting audio track count failed" + (PlayerError)ret); - } - - return audioTrack; - } - } - - /// - /// Get video track. - /// - /// video track list - public IEnumerable VideoTrack - { - get - { - string langCode; - int curTrack; - int ret; - int tracks = 0; - List videoTrack = new List(); - - ret = Interop.Player.GetTrackCount(_playerHandle, (int)StreamType.Video, out tracks); - if(ret == (int)PlayerError.None) - { - ret = Interop.Player.GetCurrentTrack(_playerHandle, (int)StreamType.Video, out curTrack); - if(ret == (int)PlayerError.None && tracks > 0) - { - for(int idx = 0; idx < tracks; idx++) - { - bool activated = (curTrack == idx ? true : false); - ret = Interop.Player.GetTrackLanguageCode(_playerHandle, (int)StreamType.Video, idx, out langCode); - if(ret == (int)PlayerError.None) - { - SubtitleTrack st = new SubtitleTrack(langCode, activated); - videoTrack.Add(st); - } else - { - Log.Error(PlayerLog.LogTag, "Getting video track language code failed" + (PlayerError)ret); - } - } - } else - { - Log.Error(PlayerLog.LogTag, "Getting video track index failed" + (PlayerError)ret); - } - } else - { - Log.Error(PlayerLog.LogTag, "Getting video track count failed" + (PlayerError)ret); - } - - return videoTrack; - } - } - - private void RegisterSubtitleUpdatedEvent() - { - _subtitleUpdatedCallback = (uint duration, string text, IntPtr userData) => - { - SubtitleUpdatedEventArgs eventArgs = new SubtitleUpdatedEventArgs(duration, text); - _subtitleUpdated?.Invoke(this, eventArgs); - }; - int ret = Interop.Player.SetSubtitleUpdatedCb(_playerHandle, _subtitleUpdatedCallback, IntPtr.Zero); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Setting subtitle updated callback failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Setting subtitle updated callback failed"); - } - - } - - private void UnregisterSubtitleUpdatedEvent() - { - int ret = Interop.Player.UnsetSubtitleUpdatedCb(_playerHandle); - if(ret != (int)PlayerError.None) - { - Log.Error(PlayerLog.LogTag, "Unsetting subtitle updated callback failed" + (PlayerError)ret); - PlayerErrorFactory.ThrowException(ret, "Unsetting subtitle updated callback failed"); - } - } - } -} \ No newline at end of file diff --git a/src/Tizen.Multimedia/Player/SubtitleTrack.cs b/src/Tizen.Multimedia/Player/SubtitleTrack.cs deleted file mode 100644 index 4fb1767..0000000 --- a/src/Tizen.Multimedia/Player/SubtitleTrack.cs +++ /dev/null @@ -1,71 +0,0 @@ -/// Subtitle track -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - -using System; - -namespace Tizen.Multimedia -{ - /// - /// SubtitleTrack - /// - /// - /// This class provides properties for subtitle tracks. - /// - - public class SubtitleTrack - { - internal string _languageCode; - internal bool _activated; - - /// - /// SubtitleTrack Constructor. - /// - /// Language code string - /// subtitle activated true/false - public SubtitleTrack(string code, bool activated) - { - _languageCode = code; - _activated = activated; - } - - /// - /// Get/Set Language code. - /// - /// language code string - public string LanguageCode - { - set - { - _languageCode = value; - } - get - { - return _languageCode; - } - } - - /// - /// Get/Set activation status. - /// - /// true, false - public bool Activated - { - set - { - _activated = value; - } - get - { - return _activated; - } - } - - } -} diff --git a/src/Tizen.Multimedia/Player/SubtitleUpdatedEventArgs.cs b/src/Tizen.Multimedia/Player/SubtitleUpdatedEventArgs.cs index abb0662..4db7528 100644 --- a/src/Tizen.Multimedia/Player/SubtitleUpdatedEventArgs.cs +++ b/src/Tizen.Multimedia/Player/SubtitleUpdatedEventArgs.cs @@ -1,62 +1,47 @@ -/// This File contains SubtitleUpdatedEventArgs class -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - +/* + * 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 { - /// - /// SubtitleUpdated event arguments + /// Provides data for the event. /// - /// - /// SubtitleUpdated event arguments - /// public class SubtitleUpdatedEventArgs : EventArgs { - internal uint _duration; - internal string _text; - - /// - /// Constructor. - /// - internal SubtitleUpdatedEventArgs(uint duration, string text) - { - _duration = duration; - _text = text; - } + internal SubtitleUpdatedEventArgs(uint duration, string text) + { + Duration = duration; + Text = text; + } /// - /// The duration of the updated subtitle . + /// Gets the he duration of the updated subtitl . /// - /// ulong duration - public uint Duration - { - get - { - return _duration; - } - } + public uint Duration { get; } /// - /// The text of the updated subtitle . + /// Gets the text of the updated subtitle. /// /// string - public string Text + public string Text { get; } + + public override string ToString() { - get - { - return _text; - } + return $"Duration : { Duration }, Text : { Text }"; } - } -} \ No newline at end of file +} diff --git a/src/Tizen.Multimedia/Player/VideoFrameCapture.cs b/src/Tizen.Multimedia/Player/VideoFrameCapture.cs deleted file mode 100644 index 704f289..0000000 --- a/src/Tizen.Multimedia/Player/VideoFrameCapture.cs +++ /dev/null @@ -1,88 +0,0 @@ -/// VideoFrameCapture -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - -using System; - -namespace Tizen.Multimedia -{ - /// - /// VideoFrameCapture - /// - /// - /// VideoSize class provides properties of a captured video frame - /// - public class VideoFrameCapture - { - internal byte[] _imageBuffer; - internal int _width; - internal int _height; - internal uint _size; - - /// - /// Constructor - /// - internal VideoFrameCapture(byte[] imageBuffer, int width, int height, uint size) - { - _imageBuffer = imageBuffer; - _width = width; - _height = height; - _size = size; - } - - - /// - /// Get ImageBuffer. - /// - /// Image buffer - public byte[] ImageBuffer - { - get - { - return _imageBuffer; - } - } - - /// - /// Get width. - /// - /// Image width - public int Width - { - get - { - return _width; - } - } - - /// - /// Get height. - /// - /// Image Height - public int Height - { - get - { - return _height; - } - } - - /// - /// Get Size. - /// - /// Size of the image - public uint Size - { - get - { - return _size; - } - } - } -} diff --git a/src/Tizen.Multimedia/Player/VideoFrameDecodedEventArgs.cs b/src/Tizen.Multimedia/Player/VideoFrameDecodedEventArgs.cs index b8aef9b..a68e130 100644 --- a/src/Tizen.Multimedia/Player/VideoFrameDecodedEventArgs.cs +++ b/src/Tizen.Multimedia/Player/VideoFrameDecodedEventArgs.cs @@ -1,44 +1,39 @@ -/// This File contains VideoFrameDecodedEventArgs class -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - +/* + * 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 { - /// - /// VideoFrameDecoded event arguments + /// Provides data for the event. /// - /// - /// VideoFrameDecoded event arguments - /// public class VideoFrameDecodedEventArgs : EventArgs { - // TODO: uncomment when MediaPacket is implemented. - //internal MediaPacket _packet; + /// + /// Initialize a new instance of the VideoFrameDecodedEventArgs class. + /// + internal VideoFrameDecodedEventArgs(MediaPacket packet) + { + Packet = packet; + } - internal VideoFrameDecodedEventArgs() - { - } - /// - /// Get the Image buffer. + /// + /// Gets the packet containing the decoded frame. /// - /// integer error code - //public MediaPacket Packet - //{ - // get - // { - // return _packet; - // } - //} + public MediaPacket Packet { get; } } -} \ No newline at end of file +} diff --git a/src/Tizen.Multimedia/Player/VideoStreamChangedEventArgs.cs b/src/Tizen.Multimedia/Player/VideoStreamChangedEventArgs.cs new file mode 100644 index 0000000..b671ef8 --- /dev/null +++ b/src/Tizen.Multimedia/Player/VideoStreamChangedEventArgs.cs @@ -0,0 +1,59 @@ +/// This File contains VideoStreamEventArgs class +/// +/// Copyright 2016 by Samsung Electronics, Inc., +/* + * 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 +{ + /// + /// Provides data for the event. + /// + public class VideoStreamChangedEventArgs : EventArgs + { + + /// + /// Initialize a new instance of the VideoStreamChangedEventArgs class. + /// + internal VideoStreamChangedEventArgs(int height, int width, int fps, int bitrate) + { + Size = new Size(width, height); + Fps = fps; + BitRate = bitrate; + } + + /// + /// Gets the of new video. + /// + public Size Size { get; } + + /// + /// Gets the fps of new video + /// + public int Fps { get; } + + /// + /// Gets the bit rate of new video. + /// + public int BitRate { get; } + + public override string ToString() + { + return $"Size : ({ Size }), Fps : { Fps }, BitRate : { BitRate }"; + } + } +} diff --git a/src/Tizen.Multimedia/Player/VideoStreamEventArgs.cs b/src/Tizen.Multimedia/Player/VideoStreamEventArgs.cs deleted file mode 100644 index 8fa8a11..0000000 --- a/src/Tizen.Multimedia/Player/VideoStreamEventArgs.cs +++ /dev/null @@ -1,90 +0,0 @@ -/// This File contains VideoStreamEventArgs class -/// -/// Copyright 2016 by Samsung Electronics, Inc., -/// -/// This software is the confidential and proprietary information -/// of Samsung Electronics, Inc. ("Confidential Information"). You -/// shall not disclose such Confidential Information and shall use -/// it only in accordance with the terms of the license agreement -/// you entered into with Samsung. - - -using System; - -namespace Tizen.Multimedia -{ - - /// - /// VideoStreamEventArgs event arguments - /// - /// - /// VideoStreamEventArgs event arguments - /// - public class VideoStreamEventArgs : EventArgs - { - internal int _height; - internal int _width; - internal int _fps; - internal int _bitrate; - - /// - /// Constructor. - /// - internal VideoStreamEventArgs(int height, int width, int fps, int bitrate) - { - _height = height; - _width = width; - _fps = fps; - _bitrate = bitrate; - } - - /// - /// Get Video Height. - /// - /// video height - public int Height - { - get - { - return _height; - } - } - - /// - /// Get Video Width. - /// - /// video width - public int Width - { - get - { - return _width; - } - } - - /// - /// FPS - /// - /// int Frames per second - public int Fps - { - get - { - return _fps; - } - } - - /// - /// Bit rate. - /// - /// bit rate [Hz] - public int BitRate - { - get - { - return _bitrate; - } - } - - } -} \ No newline at end of file diff --git a/src/Tizen.Multimedia/ScreenMirroring/ScreenMirroringEnumerations.cs b/src/Tizen.Multimedia/ScreenMirroring/ScreenMirroringEnumerations.cs index 90d9ac4..82cce54 100755 --- a/src/Tizen.Multimedia/ScreenMirroring/ScreenMirroringEnumerations.cs +++ b/src/Tizen.Multimedia/ScreenMirroring/ScreenMirroringEnumerations.cs @@ -145,34 +145,14 @@ namespace Tizen.Multimedia /// /// Successful /// - None, + None = SCMirroringErrorCode.None, /// /// Invalid parameter /// - InvalidParameter, - /// - /// Out of memory - /// - OutOfMemory, + InvalidParameter = SCMirroringErrorCode.InvalidParameter, /// /// Invalid operation /// - InvalidOperation, - /// - /// Connection timeout - /// - ConnectionTimeOut, - /// - /// Permission denied - /// - PermissionDenied, - /// - /// Not supported - /// - NotSupported, - /// - /// Unknown error - /// - Unknown + InvalidOperation = SCMirroringErrorCode.InvalidOperation } -} \ No newline at end of file +} diff --git a/src/Tizen.Multimedia/ScreenMirroring/ScreenMirroringErrorFactory.cs b/src/Tizen.Multimedia/ScreenMirroring/ScreenMirroringErrorFactory.cs index 85af382..ed69588 100755 --- a/src/Tizen.Multimedia/ScreenMirroring/ScreenMirroringErrorFactory.cs +++ b/src/Tizen.Multimedia/ScreenMirroring/ScreenMirroringErrorFactory.cs @@ -14,31 +14,42 @@ * limitations under the License. */ -using System; - +using System; +using Tizen.Internals.Errors; namespace Tizen.Multimedia { + internal enum SCMirroringErrorCode + { + None = ErrorCode.None, + InvalidParameter = ErrorCode.InvalidParameter, + OutOfMemory = ErrorCode.OutOfMemory, + InvalidOperation = ErrorCode.InvalidOperation, + ConnectionTimeOut = ErrorCode.ConnectionTimeout, + PermissionDenied = ErrorCode.PermissionDenied, + NotSupported = ErrorCode.NotSupported, + Unknown = ErrorCode.Unknown + }; public class ScreenMirroringErrorFactory { internal static void ThrowException(int errorCode, string errorMessage = null, string paramName = null) { - SCMirroringError err = (SCMirroringError)errorCode; + SCMirroringErrorCode err = (SCMirroringErrorCode)errorCode; if (string.IsNullOrEmpty(errorMessage)) { errorMessage = err.ToString(); } - switch ((SCMirroringError)errorCode) + switch ((SCMirroringErrorCode)errorCode) { - case SCMirroringError.InvalidParameter: + case SCMirroringErrorCode.InvalidParameter: throw new ArgumentException(errorMessage, paramName); - case SCMirroringError.OutOfMemory: - case SCMirroringError.InvalidOperation: - case SCMirroringError.ConnectionTimeOut: - case SCMirroringError.PermissionDenied: - case SCMirroringError.NotSupported: - case SCMirroringError.Unknown: + case SCMirroringErrorCode.OutOfMemory: + case SCMirroringErrorCode.InvalidOperation: + case SCMirroringErrorCode.ConnectionTimeOut: + case SCMirroringErrorCode.PermissionDenied: + case SCMirroringErrorCode.NotSupported: + case SCMirroringErrorCode.Unknown: throw new InvalidOperationException(errorMessage); } } diff --git a/src/Tizen.Multimedia/Tizen.Multimedia.Net45.csproj b/src/Tizen.Multimedia/Tizen.Multimedia.Net45.csproj index eb2d90d..d36f713 100755 --- a/src/Tizen.Multimedia/Tizen.Multimedia.Net45.csproj +++ b/src/Tizen.Multimedia/Tizen.Multimedia.Net45.csproj @@ -45,13 +45,13 @@ - - - - - - - + + + + + + + @@ -78,6 +78,9 @@ + + + @@ -85,20 +88,18 @@ - - - - + + - + @@ -111,9 +112,6 @@ - - - @@ -161,37 +159,40 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - @@ -221,14 +222,31 @@ + + + + + + + + + + + + + + + + + - + diff --git a/src/Tizen.Multimedia/Tizen.Multimedia.Net45.project.json b/src/Tizen.Multimedia/Tizen.Multimedia.Net45.project.json index 8be2314..c3978a9 100755 --- a/src/Tizen.Multimedia/Tizen.Multimedia.Net45.project.json +++ b/src/Tizen.Multimedia/Tizen.Multimedia.Net45.project.json @@ -1,7 +1,8 @@ { "dependencies": { - "ElmSharp": "1.0.7", - "Tizen": "1.0.1" + "ElmSharp": "1.1.0-*", + "Tizen": "1.0.2", + "Tizen.Applications": "1.0.2" }, "frameworks": { "net45": {} @@ -9,4 +10,4 @@ "runtimes": { "win": {} } -} \ No newline at end of file +} diff --git a/src/Tizen.Multimedia/Tizen.Multimedia.csproj b/src/Tizen.Multimedia/Tizen.Multimedia.csproj index 6b65b67..fd2950a 100755 --- a/src/Tizen.Multimedia/Tizen.Multimedia.csproj +++ b/src/Tizen.Multimedia/Tizen.Multimedia.csproj @@ -1,280 +1,273 @@ - - - - Debug - AnyCPU - {0CE698B0-4849-4096-9D7F-30E611F50DAD} - Library - Properties - Tizen.Multimedia - Tizen.Multimedia - 512 - - - .NETStandard - v1.3 - .NETStandard,Version=v1.3 - false - true - $(NoWarn);1701;1702 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - true - - - Tizen.Multimedia.snk - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + Debug + AnyCPU + {0CE698B0-4849-4096-9D7F-30E611F50DAD} + Library + Properties + Tizen.Multimedia + Tizen.Multimedia + 512 + + + .NETStandard + v1.3 + .NETStandard,Version=v1.3 + false + true + $(NoWarn);1701;1702 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + + + Tizen.Multimedia.snk + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + --> + + --> - <_TargetFrameworkDirectories>$(MSBuildThisFileDirectory) - <_FullFrameworkReferenceAssemblyPaths>$(MSBuildThisFileDirectory) - true - - + --> + <_TargetFrameworkDirectories>$(MSBuildThisFileDirectory) + <_FullFrameworkReferenceAssemblyPaths>$(MSBuildThisFileDirectory) + true + + \ No newline at end of file diff --git a/src/Tizen.Multimedia/Tizen.Multimedia.nuspec b/src/Tizen.Multimedia/Tizen.Multimedia.nuspec old mode 100644 new mode 100755 index df54241..28c1b30 --- a/src/Tizen.Multimedia/Tizen.Multimedia.nuspec +++ b/src/Tizen.Multimedia/Tizen.Multimedia.nuspec @@ -3,10 +3,17 @@ Tizen.Multimedia $version$ - Tizen Developers - Multimedia API for Tizen.Net + Samsung Electronics + false + https://www.apache.org/licenses/LICENSE-2.0 + https://www.tizen.org/ + https://developer.tizen.org/sites/default/files/images/tizen-pinwheel-on-light-rgb_64_64.png + © Samsung Electronics Co., Ltd All Rights Reserved + Provides the Multimedia API for Tizen.Net - + + + diff --git a/src/Tizen.Multimedia/Tizen.Multimedia.project.json b/src/Tizen.Multimedia/Tizen.Multimedia.project.json index 124a18a..842b883 100755 --- a/src/Tizen.Multimedia/Tizen.Multimedia.project.json +++ b/src/Tizen.Multimedia/Tizen.Multimedia.project.json @@ -1,10 +1,11 @@ -{ - "dependencies": { - "ElmSharp": "1.0.7", - "NETStandard.Library": "1.6.0", - "Tizen": "1.0.1" - }, - "frameworks": { - "netstandard1.3": {} - } -} \ No newline at end of file +{ + "dependencies": { + "ElmSharp": "1.1.0-*", + "NETStandard.Library": "1.6.0", + "Tizen": "1.0.2", + "Tizen.Applications": "1.0.2" + }, + "frameworks": { + "netstandard1.3": {} + } +}