summaryrefslogtreecommitdiff
path: root/Tizen.Multimedia/AudioManager/AudioStreamPolicy.cs
blob: 9e260b2455de148535b7807216f9ced60d528104 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/*
 * 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
{
    /// <summary>
    /// Provides the ability to control a sound stream.
    /// </summary>
    public class AudioStreamPolicy : IDisposable
    {
        private AudioStreamPolicyHandle _handle;
        private bool _disposed = false;
        private Interop.AudioStreamPolicy.FocusStateChangedCallback _focusStateChangedCallback;

        /// <summary>
        ///  Initializes a new instance of the <see cref="AudioStreamPolicy"/> class with <see cref="AudioStreamType"/>
        /// </summary>
        /// <remarks>
        /// To apply the stream policy according to this stream information, the AudioStreamPolicy should
        /// be passed to other APIs related to playback or recording. (e.g., <see cref="Player"/>, <see cref="WavPlayer"/> , etc.)
        /// </remarks>
        /// <param name="streamType">Type of sound stream for which policy needs to be created.</param>
        public AudioStreamPolicy(AudioStreamType streamType)
        {
            ValidationUtil.ValidateEnum(typeof(AudioStreamType), streamType, nameof(streamType));

            _focusStateChangedCallback = (IntPtr streamInfo, AudioStreamFocusOptions focusMask,
                AudioStreamFocusState state, AudioStreamFocusChangedReason reason, AudioStreamBehaviors behaviors,
                string extraInfo, IntPtr userData) =>
            {
                FocusStateChanged?.Invoke(this,
                    new AudioStreamPolicyFocusStateChangedEventArgs(focusMask, state, reason, behaviors, extraInfo));
            };

            Interop.AudioStreamPolicy.Create(streamType, _focusStateChangedCallback,
                IntPtr.Zero, out _handle).Validate("Unable to create stream information");

            Debug.Assert(_handle != null);
        }

        /// <summary>
        /// Occurs when the state of focus that belongs to the current AudioStreamPolicy is changed.
        /// </summary>
        /// <remarks>
        /// The event is raised in the internal thread.
        /// </remarks>
        public event EventHandler<AudioStreamPolicyFocusStateChangedEventArgs> FocusStateChanged;

        /// <summary>
        /// Gets the <see cref="AudioVolumeType"/>.
        /// </summary>
        /// <remarks>
        /// If the <see cref="AudioStreamType"/> of the current AudioStreamPolicy is <see cref="AudioStreamType.Emergency"/>,
        /// it returns <see cref="AudioVolumeType.None"/>.
        /// </remarks>
        /// <value>The <see cref="AudioVolumeType"/> of the policy instance.</value>
        public AudioVolumeType VolumeType
        {
            get
            {
                AudioVolumeType type;
                var ret = Interop.AudioStreamPolicy.GetSoundType(Handle, out type);
                if (ret == AudioManagerError.NoData)
                {
                    return AudioVolumeType.None;
                }

                ret.Validate("Failed to get volume type");

                return type;
            }
        }

        private AudioStreamFocusState GetFocusState(bool playback)
        {
            int ret = Interop.AudioStreamPolicy.GetFocusState(Handle, out var stateForPlayback, out var stateForRecording);
            MultimediaDebug.AssertNoError(ret);

            return playback ? stateForPlayback : stateForRecording;
        }

        /// <summary>
        /// Gets the state of focus for playback.
        /// </summary>
        /// <value>The state of focus for playback.</value>
        public AudioStreamFocusState PlaybackFocusState => GetFocusState(true);

        /// <summary>
        /// Gets the state of focus for recording.
        /// </summary>
        /// <value>The state of focus for recording.</value>
        public AudioStreamFocusState RecordingFocusState => GetFocusState(false);

        /// <summary>
        /// Gets or sets the auto focus reacquisition.
        /// </summary>
        /// <value>
        /// true if the auto focus reacquisition is enabled; otherwise, false.\n
        /// The default is true.
        /// </value>
        /// <remarks>
        /// If you don't want to reacquire the focus you've lost automatically,
        /// disable the focus reacquisition.
        /// </remarks>
        public bool FocusReacquisitionEnabled
        {
            get
            {
                Interop.AudioStreamPolicy.GetFocusReacquisition(Handle, out var enabled).
                    Validate("Failed to get focus reacquisition state");

                return enabled;
            }
            set
            {
                Interop.AudioStreamPolicy.SetFocusReacquisition(Handle, value).
                    Validate("Failed to set focus reacquisition");
            }
        }

        internal AudioStreamPolicyHandle Handle
        {
            get
            {
                if (_disposed)
                {
                    throw new ObjectDisposedException(nameof(AudioStreamPolicy));
                }
                return _handle;
            }
        }

        /// <summary>
        /// Acquires the stream focus.
        /// </summary>
        /// <param name="options">The focuses that you want to acquire.</param>
        /// <param name="behaviors">The requesting behaviors.</param>
        /// <param name="extraInfo">The extra information for this request. This value can be null.</param>
        public void AcquireFocus(AudioStreamFocusOptions options, AudioStreamBehaviors behaviors, string extraInfo)
        {
            if (options == 0)
            {
                throw new ArgumentException("options can't be zero.", nameof(options));
            }

            if (options.IsValid() == false)
            {
                throw new ArgumentOutOfRangeException(nameof(options), options, "options contains a invalid bit.");
            }

            if (behaviors.IsValid() == false)
            {
                throw new ArgumentOutOfRangeException(nameof(behaviors), behaviors, "behaviors contains a invalid bit.");
            }

            Interop.AudioStreamPolicy.AcquireFocus(Handle, options, behaviors, extraInfo).
                Validate("Failed to acquire focus");
        }

        /// <summary>
        /// Releases the acquired focus.
        /// </summary>
        /// <param name="options">The focus mask that you want to release.</param>
        /// <param name="behaviors">The requesting behaviors.</param>
        /// <param name="extraInfo">The extra information for this request. This value can be null.</param>
        public void ReleaseFocus(AudioStreamFocusOptions options, AudioStreamBehaviors behaviors, string extraInfo)
        {
            if (options == 0)
            {
                throw new ArgumentException("options can't be zero.", nameof(options));
            }

            if (options.IsValid() == false)
            {
                throw new ArgumentOutOfRangeException(nameof(options), options, "options contains a invalid bit.");
            }

            if (behaviors.IsValid() == false)
            {
                throw new ArgumentOutOfRangeException(nameof(behaviors), behaviors, "behaviors contains a invalid bit.");
            }

            Interop.AudioStreamPolicy.ReleaseFocus(Handle, options, behaviors, extraInfo).
                Validate("Failed to release focus");
        }

        /// <summary>
        /// Applies the stream routing.
        /// </summary>
        /// <remarks>
        /// If the stream has not been made yet, this will be applied when the stream starts to play.
        /// </remarks>
        /// <seealso cref="AddDeviceForStreamRouting(AudioDevice)"/>
        /// <seealso cref="RemoveDeviceForStreamRouting(AudioDevice)"/>
        public void ApplyStreamRouting()
        {
            Interop.AudioStreamPolicy.ApplyStreamRouting(Handle).Validate("Failed to apply stream routing");
        }

        /// <summary>
        /// Adds a device for the stream routing.
        /// </summary>
        /// <param name="device">The device to add.</param>
        /// <remarks>
        /// The available <see cref="AudioStreamType"/> is <see cref="AudioStreamType.Voip"/> and <see cref="AudioStreamType.MediaExternalOnly"/>.
        /// </remarks>
        /// <seealso cref="AudioManager.GetConnectedDevices(AudioDeviceOptions)"/>
        /// <seealso cref="ApplyStreamRouting"/>
        public void AddDeviceForStreamRouting(AudioDevice device)
        {
            if (device == null)
            {
                throw new ArgumentNullException(nameof(device));
            }
            var ret = Interop.AudioStreamPolicy.AddDeviceForStreamRouting(Handle, device.Id);

            if (ret == AudioManagerError.NoData)
            {
                throw new ArgumentException("The device seems not connected.", nameof(device));
            }

            ret.Validate("Failed to add device for stream routing");
        }

        /// <summary>
        /// Removes the device for the stream routing.
        /// </summary>
        /// <param name="device">The device to remove.</param>
        /// <remarks>
        /// The available <see cref="AudioStreamType"/> is <see cref="AudioStreamType.Voip"/> and <see cref="AudioStreamType.MediaExternalOnly"/>.
        /// </remarks>
        public void RemoveDeviceForStreamRouting(AudioDevice device)
        {
            if (device == null)
            {
                throw new ArgumentNullException(nameof(device));
            }

            Interop.AudioStreamPolicy.RemoveDeviceForStreamRouting(Handle, device.Id).
                Validate("Failed to remove device for stream routing");
        }

        /// <summary>
        /// Releases all resources used by the <see cref="AudioStreamPolicy"/>.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
        }

        /// <summary>
        /// Releases the unmanaged resources used by the <see cref="AudioStreamPolicy"/>.
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (_handle != null)
                {
                    _handle.Dispose();
                }
                _disposed = true;
            }
        }

        #region Static events

        private static bool _isWatchCallbackRegistered;
        private static EventHandler<StreamFocusStateChangedEventArgs> _streamFocusStateChanged;
        private static Interop.AudioStreamPolicy.FocusStateWatchCallback _focusStateWatchCallback;
        private static object _streamFocusEventLock = new object();

        /// <summary>
        /// Occurs when the focus state for stream types is changed regardless of the process.
        /// </summary>
        public static event EventHandler<StreamFocusStateChangedEventArgs> StreamFocusStateChanged
        {
            add
            {
                lock (_streamFocusEventLock)
                {
                    if (_isWatchCallbackRegistered == false)
                    {
                        RegisterFocusStateWatch();
                        _isWatchCallbackRegistered = true;
                    }
                    _streamFocusStateChanged += value;
                }
            }
            remove
            {
                lock (_streamFocusEventLock)
                {
                    _streamFocusStateChanged -= value;
                }
            }
        }

        private static void RegisterFocusStateWatch()
        {
            _focusStateWatchCallback = (int id, AudioStreamFocusOptions options, AudioStreamFocusState focusState,
                AudioStreamFocusChangedReason reason, string extraInfo, IntPtr userData) =>
            {
                _streamFocusStateChanged?.Invoke(null,
                    new StreamFocusStateChangedEventArgs(options, focusState, reason, extraInfo));
            };

            Interop.AudioStreamPolicy.AddFocusStateWatchCallback(
                AudioStreamFocusOptions.Playback | AudioStreamFocusOptions.Recording,
                _focusStateWatchCallback, IntPtr.Zero, out var cbId).
                Validate("Failed to initialize focus state event");
        }
        #endregion
    }
}