summaryrefslogtreecommitdiff
path: root/src/Tizen.Multimedia.Radio/Radio/Radio.cs
blob: 8851afb9f1a2b5359e47fbf02fd3291d46e239bb (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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/*
 * 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.Linq;
using System.Threading.Tasks;
using Tizen.System;
using static Tizen.Multimedia.Interop.Radio;

namespace Tizen.Multimedia
{
    /// <summary>
    /// Provides a means for using the radio feature.
    /// </summary>
    public class Radio : IDisposable
    {
        private Interop.RadioHandle _handle;

        private const string FeatureFmRadio = "http://tizen.org/feature/fmradio";

        /// <summary>
        /// Initialize a new instance of the Radio class.
        /// </summary>
        /// <exception cref="NotSupportedException">Radio feature is not supported</exception>
        public Radio()
        {
            ValidateFeatureSupported(FeatureFmRadio);

            Create(out _handle);

            try
            {
                SetScanCompletedCb(_handle, ScanCompleteCallback).ThrowIfFailed("Failed to initialize radio");
                SetInterruptedCb(_handle, InterruptedCallback).ThrowIfFailed("Failed to initialize radio");
            }
            catch (Exception)
            {
                _handle.Dispose();
                throw;
            }
        }

        private Interop.RadioHandle Handle
        {
            get
            {
                if (_disposed)
                {
                    throw new ObjectDisposedException(GetType().Name);
                }
                return _handle;
            }
        }

        /// <summary>
        /// Occurs when radio scan information is updated.
        /// </summary>
        public event EventHandler<ScanUpdatedEventArgs> ScanUpdated;

        /// <summary>
        /// Occurs when radio scanning stops.
        /// </summary>
        public event EventHandler ScanStopped;

        /// <summary>
        /// Occurs when radio scan is completed.
        /// </summary>
        public event EventHandler ScanCompleted;

        /// <summary>
        /// Occurs when radio is interrupted
        /// </summary>
        public event EventHandler<RadioInterruptedEventArgs> Interrupted;

        /// <summary>
        /// Gets the current state of the radio.
        /// </summary>
        public RadioState State
        {
            get
            {
                RadioState state;
                GetState(Handle, out state);
                return state;
            }
        }

        /// <summary>
        /// Gets or sets the radio frequency, in [87500 ~ 108000] (kHz).
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     <paramref name="value"/> is less than <see cref="Range.Min"/> of <see cref="FrequencyRange"/>.\n
        ///     - or - \n
        ///     <paramref name="value"/> is greater than <see cref="Range.Max"/> of <see cref="FrequencyRange"/>.\n
        /// </exception>
        public int Frequency
        {
            get
            {
                int value = 0;
                GetFrequency(Handle, out value).ThrowIfFailed("Failed to get frequency");
                return value;
            }
            set
            {
                if (value < FrequencyRange.Min || value > FrequencyRange.Max)
                {
                    throw new ArgumentOutOfRangeException(nameof(Frequency), value, "Frequency must be within FrequencyRange.");
                }

                SetFrequency(Handle, value).ThrowIfFailed("Failed to set frequency");
            }
        }

        /// <summary>
        /// Gets the current signal strength, in [-128 ~ 128] (dBm).
        /// </summary>
        public int SignalStrength
        {
            get
            {
                int value = 0;
                GetSignalStrength(Handle, out value).ThrowIfFailed("Failed to get signal strength");
                return value;
            }
        }

        /// <summary>
        /// Gets the value indicating if radio is muted.
        /// </summary>
        /// <value>
        /// true if the radio is muted; otherwise, false.
        /// The default is false.
        /// </value>
        public bool IsMuted
        {
            get
            {
                bool value;
                GetMuted(Handle, out value).ThrowIfFailed("Failed to get the mute state");
                return value;
            }
            set
            {
                SetMute(Handle, value).ThrowIfFailed("Failed to set the mute state");
            }
        }

        /// <summary>
        /// Gets the channel spacing for current region.
        /// </summary>
        public int ChannelSpacing
        {
            get
            {
                int value;
                GetChannelSpacing(Handle, out value).ThrowIfFailed("Failed to get channel spacing");
                return value;
            }
        }

        /// <summary>
        /// Gets or sets the radio volume level.
        /// </summary>
        /// <remarks>Valid volume range is from 0 to 1.0(100%), inclusive.</remarks>
        /// <value>The default is 1.0.</value>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     <paramref name="value"/> is less than zero.\n
        ///     - or -\n
        ///     <paramref name="value"/> is greater than 1.0.
        /// </exception>
        public float Volume
        {
            get
            {
                float value;
                GetVolume(Handle, out value).ThrowIfFailed("Failed to get volume level.");
                return value;
            }
            set
            {
                if (value < 0F || 1.0F < value)
                {
                    throw new ArgumentOutOfRangeException(nameof(value), value,
                        $"Valid volume range is 0 <= value <= 1.0, but got { value }.");
                }

                SetVolume(Handle, value).ThrowIfFailed("Failed to set volume level");
            }
        }

        /// <summary>
        /// Gets the frequency for the region, in [87500 ~ 108000] (kHz).
        /// </summary>
        public Range FrequencyRange
        {
            get
            {
                int min, max;

                GetFrequencyRange(Handle, out min, out max).ThrowIfFailed("Failed to get frequency range");

                return new Range(min, max);
            }
        }

        /// <summary>
        /// Starts the radio.
        /// </summary>
        /// <remarks>The radio must be in the <see cref="RadioState.Ready"/> state.</remarks>
        /// <exception cref="InvalidOperationException">The radio is not in the valid state.</exception>
        public void Start()
        {
            ValidateRadioState(RadioState.Ready);

            Interop.Radio.Start(Handle).ThrowIfFailed("Failed to start radio");
        }

        /// <summary>
        /// Stops the radio.
        /// </summary>
        /// <remarks>The radio must be in the <see cref="RadioState.Playing"/> state.</remarks>
        /// <exception cref="InvalidOperationException">The radio is not in the valid state.</exception>
        public void Stop()
        {
            ValidateRadioState(RadioState.Playing);

            Interop.Radio.Stop(Handle).ThrowIfFailed("Failed to stop radio");
        }

        /// <summary>
        /// Starts radio scan, will trigger ScanInformationUpdated event, when scan information is updated
        /// </summary>
        /// <remarks>The radio must be in the <see cref="RadioState.Ready"/> or <see cref="RadioState.Playing"/> state.</remarks>
        /// <exception cref="InvalidOperationException">The radio is not in the valid state.</exception>
        /// <seealso cref="ScanUpdated"/>
        /// <seealso cref="ScanCompleted"/>
        public void StartScan()
        {
            ValidateRadioState(RadioState.Ready, RadioState.Playing);

            ScanStart(Handle, ScanUpdatedCallback);
        }

        /// <summary>
        /// Stops radio scan.
        /// </summary>
        /// <remarks>The radio must be in the <see cref="RadioState.Scanning"/> state.</remarks>
        /// <exception cref="InvalidOperationException">The radio is not in the valid state.</exception>
        /// <seealso cref="ScanStopped"/>
        public void StopScan()
        {
            ValidateRadioState(RadioState.Scanning);

            ScanStop(Handle, ScanStoppedCallback);
        }

        /// <summary>
        /// Seeks up the effective frequency of the radio.
        /// </summary>
        /// <returns>
        /// A task that represents the asynchronous seeking operation.
        /// The result value is the current frequency, in range [87500 ~ 108000] (kHz).
        /// It can be -1 if the seeking operation has failed.
        /// </returns>
        /// <remarks>The radio must be in the <see cref="RadioState.Playing/> state.</remarks>
        /// <exception cref="InvalidOperationException">The radio is not in the valid state.</exception>
        public async Task<int> SeekUpAsync()
        {
            ValidateRadioState(RadioState.Playing);

            TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
            SeekCompletedCallback callback = (currentFrequency, _) =>
            {
                tcs.TrySetResult(currentFrequency);
            };

            SeekUp(Handle, callback);
            return await tcs.Task;
        }

        /// <summary>
        /// Seeks down the effective frequency of the radio.
        /// </summary>
        /// <returns>
        /// A task that represents the asynchronous seeking operation.
        /// The result value is the current frequency, in range [87500 ~ 108000] (kHz).
        /// It can be -1 if the seeking operation has failed.
        /// </returns>
        /// <remarks>The radio must be in the <see cref="RadioState.Playing/> state.</remarks>
        /// <exception cref="InvalidOperationException">The radio is not in the valid state.</exception>
        public async Task<int> SeekDownAsync()
        {
            ValidateRadioState(RadioState.Playing);

            TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
            SeekCompletedCallback callback = (currentFrequency, _) =>
            {
                tcs.TrySetResult(currentFrequency);
            };

            SeekDown(Handle, callback);
            return await tcs.Task;
        }

        private void ValidateFeatureSupported(string featurePath)
        {
            bool supported = false;
            SystemInfo.TryGetValue(featurePath, out supported);

            if (supported == false)
            {
                throw new NotSupportedException($"The feature({featurePath}) is not supported.");
            }

        }

        private void ScanUpdatedCallback(int frequency, IntPtr data)
        {
            ScanUpdated?.Invoke(this, new ScanUpdatedEventArgs(frequency));
        }

        private void ScanStoppedCallback(IntPtr data)
        {
            ScanStopped?.Invoke(this, EventArgs.Empty);
        }

        private void ScanCompleteCallback(IntPtr data)
        {
            ScanCompleted?.Invoke(this, EventArgs.Empty);
        }

        private void InterruptedCallback(RadioInterruptedReason reason, IntPtr data)
        {
            Interrupted?.Invoke(this, new RadioInterruptedEventArgs(reason));
        }

        private void ValidateRadioState(params RadioState[] required)
        {
            RadioState curState = State;

            if (required.Contains(curState) == false)
            {
                throw new InvalidOperationException($"{curState} is not valid state.");
            }
        }

        #region IDisposable Support
        private bool _disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (_handle != null)
                {
                    _handle.Dispose();
                }
                _disposed = true;
            }
        }

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