This repository has been archived by the owner on May 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
MediaElementRenderer.cs
445 lines (374 loc) · 11.4 KB
/
MediaElementRenderer.cs
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
using AVFoundation;
using AVKit;
using CoreGraphics;
using CoreMedia;
using Foundation;
using System;
using System.IO;
using UIKit;
using Xamarin.Forms.Internals;
namespace Xamarin.Forms.Platform.iOS
{
public sealed class MediaElementRenderer : ViewRenderer<MediaElement, UIView>
{
IMediaElementController Controller => Element as IMediaElementController;
AVPlayerViewController _avPlayerViewController = new AVPlayerViewController();
NSObject _playedToEndObserver;
NSObject _statusObserver;
NSObject _rateObserver;
bool _idleTimerDisabled = false;
[Internals.Preserve(Conditional = true)]
public MediaElementRenderer()
{
Xamarin.Forms.MediaElement.VerifyMediaElementFlagEnabled(nameof(MediaElementRenderer));
_playedToEndObserver = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, PlayedToEnd);
}
void SetKeepScreenOn(bool value)
{
if (value)
{
if (!UIApplication.SharedApplication.IdleTimerDisabled)
{
_idleTimerDisabled = true;
UIApplication.SharedApplication.IdleTimerDisabled = true;
}
}
else if (_idleTimerDisabled)
{
_idleTimerDisabled = false;
UIApplication.SharedApplication.IdleTimerDisabled = false;
}
}
void UpdateSource()
{
if (Element.Source != null)
{
AVAsset asset = null;
var uriSource = Element.Source as UriMediaSource;
if (uriSource != null)
{
if (uriSource.Uri.Scheme == "ms-appx")
{
if (uriSource.Uri.LocalPath.Length <= 1)
return;
// used for a file embedded in the application package
asset = AVAsset.FromUrl(NSUrl.FromFilename(uriSource.Uri.LocalPath.Substring(1)));
}
else if (uriSource.Uri.Scheme == "ms-appdata")
{
string filePath = Platform.ResolveMsAppDataUri(uriSource.Uri);
if (string.IsNullOrEmpty(filePath))
throw new ArgumentException("Invalid Uri", "Source");
asset = AVAsset.FromUrl(NSUrl.FromFilename(filePath));
}
else
{
asset = AVUrlAsset.Create(NSUrl.FromString(uriSource.Uri.AbsoluteUri));
}
}
else
{
var fileSource = Element.Source as FileMediaSource;
if (fileSource != null)
{
asset = AVAsset.FromUrl(NSUrl.FromFilename(fileSource.File));
}
}
var item = new AVPlayerItem(asset);
RemoveStatusObserver();
_statusObserver = (NSObject)item.AddObserver("status", NSKeyValueObservingOptions.New, ObserveStatus);
if (_avPlayerViewController.Player != null)
{
_avPlayerViewController.Player.ReplaceCurrentItemWithPlayerItem(item);
}
else
{
_avPlayerViewController.Player = new AVPlayer(item);
_rateObserver = (NSObject)_avPlayerViewController.Player.AddObserver("rate", NSKeyValueObservingOptions.New, ObserveRate);
}
if (Element.AutoPlay)
Play();
}
else
{
if (Element.CurrentState == MediaElementState.Playing || Element.CurrentState == MediaElementState.Buffering)
{
_avPlayerViewController.Player.Pause();
Controller.CurrentState = MediaElementState.Stopped;
}
}
}
protected override void Dispose(bool disposing)
{
if(_playedToEndObserver != null)
{
NSNotificationCenter.DefaultCenter.RemoveObserver(_playedToEndObserver);
_playedToEndObserver = null;
}
if(_rateObserver != null)
{
_rateObserver.Dispose();
_rateObserver = null;
}
RemoveStatusObserver();
_avPlayerViewController?.Player?.Pause();
_avPlayerViewController?.Player?.ReplaceCurrentItemWithPlayerItem(null);
base.Dispose(disposing);
}
void RemoveStatusObserver()
{
if (_statusObserver != null)
{
try
{
_avPlayerViewController?.Player?.CurrentItem?.RemoveObserver(_statusObserver, "status");
}
finally
{
_statusObserver = null;
}
}
}
void ObserveRate(NSObservedChange e)
{
if (Controller is object)
{
switch (_avPlayerViewController.Player.Rate)
{
case 0.0f:
Controller.CurrentState = MediaElementState.Paused;
break;
case 1.0f:
Controller.CurrentState = MediaElementState.Playing;
break;
}
Controller.Position = Position;
}
}
void ObserveStatus(NSObservedChange e)
{
Controller.Volume = _avPlayerViewController.Player.Volume;
switch (_avPlayerViewController.Player.Status)
{
case AVPlayerStatus.Failed:
Controller.OnMediaFailed();
break;
case AVPlayerStatus.ReadyToPlay:
var duration = _avPlayerViewController.Player.CurrentItem.Duration;
if (duration.IsIndefinite)
Controller.Duration = TimeSpan.Zero;
else
Controller.Duration = TimeSpan.FromSeconds(duration.Seconds);
Controller.VideoHeight = (int)_avPlayerViewController.Player.CurrentItem.Asset.NaturalSize.Height;
Controller.VideoWidth = (int)_avPlayerViewController.Player.CurrentItem.Asset.NaturalSize.Width;
Controller.OnMediaOpened();
Controller.Position = Position;
break;
}
}
TimeSpan Position
{
get
{
if (_avPlayerViewController.Player.CurrentTime.IsInvalid)
return TimeSpan.Zero;
return TimeSpan.FromSeconds(_avPlayerViewController.Player.CurrentTime.Seconds);
}
}
void PlayedToEnd(NSNotification notification)
{
if (Element.IsLooping)
{
_avPlayerViewController.Player.Seek(CMTime.Zero);
Controller.Position = Position;
_avPlayerViewController.Player.Play();
}
else
{
SetKeepScreenOn(false);
Controller.Position = Position;
try
{
Device.BeginInvokeOnMainThread(Controller.OnMediaEnded);
}
catch { }
}
}
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case nameof(MediaElement.Aspect):
_avPlayerViewController.VideoGravity = AspectToGravity(Element.Aspect);
break;
case nameof(MediaElement.KeepScreenOn):
if (!Element.KeepScreenOn)
{
SetKeepScreenOn(false);
}
else if(Element.CurrentState == MediaElementState.Playing)
{
// only toggle this on if property is set while video is already running
SetKeepScreenOn(true);
}
break;
case nameof(MediaElement.ShowsPlaybackControls):
_avPlayerViewController.ShowsPlaybackControls = Element.ShowsPlaybackControls;
break;
case nameof(MediaElement.Source):
UpdateSource();
break;
case nameof(MediaElement.Volume):
_avPlayerViewController.Player.Volume = (float)Element.Volume;
break;
}
}
void MediaElementSeekRequested(object sender, SeekRequested e)
{
if (_avPlayerViewController.Player.Status != AVPlayerStatus.ReadyToPlay || _avPlayerViewController.Player.CurrentItem == null)
return;
NSValue[] ranges = _avPlayerViewController.Player.CurrentItem.SeekableTimeRanges;
CMTime seekTo = new CMTime(Convert.ToInt64(e.Position.TotalMilliseconds), 1000);
foreach (NSValue v in ranges)
{
if (seekTo >= v.CMTimeRangeValue.Start && seekTo < (v.CMTimeRangeValue.Start + v.CMTimeRangeValue.Duration))
{
_avPlayerViewController.Player.Seek(seekTo, SeekComplete);
break;
}
}
}
void Play()
{
var audioSession = AVAudioSession.SharedInstance();
NSError err = audioSession.SetCategory(AVAudioSession.CategoryPlayback);
if (!(err is null))
Log.Warning("MediaElement", "Failed to set AVAudioSession Category {0}", err.Code);
audioSession.SetMode(AVAudioSession.ModeMoviePlayback, out err);
if (!(err is null))
Log.Warning("MediaElement", "Failed to set AVAudioSession Mode {0}", err.Code);
err = audioSession.SetActive(true);
if (!(err is null))
Log.Warning("MediaElement", "Failed to set AVAudioSession Active {0}", err.Code);
if (_avPlayerViewController.Player != null)
{
_avPlayerViewController.Player.Play();
Controller.CurrentState = MediaElementState.Playing;
}
if (Element.KeepScreenOn)
{
SetKeepScreenOn(true);
}
}
void MediaElementStateRequested(object sender, StateRequested e)
{
MediaElementVolumeRequested(this, EventArgs.Empty);
switch (e.State)
{
case MediaElementState.Playing:
Play();
break;
case MediaElementState.Paused:
if (Element.KeepScreenOn)
{
SetKeepScreenOn(false);
}
if (_avPlayerViewController.Player != null)
{
_avPlayerViewController.Player.Pause();
Controller.CurrentState = MediaElementState.Paused;
}
break;
case MediaElementState.Stopped:
if (Element.KeepScreenOn)
{
SetKeepScreenOn(false);
}
//ios has no stop...
_avPlayerViewController?.Player.Pause();
_avPlayerViewController?.Player.Seek(CMTime.Zero);
Controller.CurrentState = MediaElementState.Stopped;
NSError err = AVAudioSession.SharedInstance().SetActive(false);
if (!(err is null))
Log.Warning("MediaElement", "Failed to set AVAudioSession Inactive {0}", err.Code);
break;
}
Controller.Position = Position;
}
static AVLayerVideoGravity AspectToGravity(Aspect aspect)
{
switch (aspect)
{
case Aspect.Fill:
return AVLayerVideoGravity.Resize;
case Aspect.AspectFill:
return AVLayerVideoGravity.ResizeAspectFill;
default:
return AVLayerVideoGravity.ResizeAspect;
}
}
void SeekComplete(bool finished)
{
if (finished)
{
Controller.OnSeekCompleted();
}
}
private void MediaElementVolumeRequested(object sender, EventArgs e)
{
Controller.Volume = _avPlayerViewController.Player.Volume;
}
void MediaElementPositionRequested(object sender, EventArgs e)
{
Controller.Position = Position;
}
protected override void OnElementChanged(ElementChangedEventArgs<MediaElement> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
e.OldElement.PropertyChanged -= OnElementPropertyChanged;
e.OldElement.SeekRequested -= MediaElementSeekRequested;
e.OldElement.StateRequested -= MediaElementStateRequested;
e.OldElement.PositionRequested -= MediaElementPositionRequested;
e.OldElement.VolumeRequested -= MediaElementVolumeRequested;
if (_playedToEndObserver != null)
{
NSNotificationCenter.DefaultCenter.RemoveObserver(_playedToEndObserver);
_playedToEndObserver = null;
}
// stop video if playing
if (_avPlayerViewController?.Player?.CurrentItem != null)
{
RemoveStatusObserver();
_avPlayerViewController.Player.Pause();
_avPlayerViewController.Player.Seek(CMTime.Zero);
_avPlayerViewController.Player.ReplaceCurrentItemWithPlayerItem(null);
AVAudioSession.SharedInstance().SetActive(false);
}
}
if (e.NewElement != null)
{
SetNativeControl(_avPlayerViewController.View);
Element.PropertyChanged += OnElementPropertyChanged;
Element.SeekRequested += MediaElementSeekRequested;
Element.StateRequested += MediaElementStateRequested;
Element.PositionRequested += MediaElementPositionRequested;
Element.VolumeRequested += MediaElementVolumeRequested;
_avPlayerViewController.ShowsPlaybackControls = Element.ShowsPlaybackControls;
_avPlayerViewController.VideoGravity = AspectToGravity(Element.Aspect);
if (Element.KeepScreenOn)
{
SetKeepScreenOn(true);
}
_playedToEndObserver = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, PlayedToEnd);
UpdateBackgroundColor();
UpdateSource();
}
}
void UpdateBackgroundColor()
{
BackgroundColor = Element.BackgroundColor.ToUIColor();
}
}
}