/
StreamingMedia.m
executable file
·302 lines (263 loc) · 11.9 KB
/
StreamingMedia.m
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
#import "StreamingMedia.h"
#import <Cordova/CDV.h>
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
#import "LandscapeVideo.h"
#import "PortraitVideo.h"
@interface StreamingMedia()
- (void)parseOptions:(NSDictionary *) options type:(NSString *) type;
- (void)play:(CDVInvokedUrlCommand *) command type:(NSString *) type;
- (void)setBackgroundColor:(NSString *)color;
- (void)setImage:(NSString*)imagePath withScaleType:(NSString*)imageScaleType;
- (UIImage*)getImage: (NSString *)imageName;
- (void)startPlayer:(NSString*)uri;
- (void)moviePlayBackDidFinish:(NSNotification*)notification;
- (void)cleanup;
@end
@implementation StreamingMedia {
NSString* callbackId;
AVPlayerViewController *moviePlayer;
BOOL shouldAutoClose;
UIColor *backgroundColor;
UIImageView *imageView;
BOOL initFullscreen;
NSString *mOrientation;
NSString *videoType;
}
NSString * const TYPE_VIDEO = @"VIDEO";
NSString * const TYPE_AUDIO = @"AUDIO";
NSString * const DEFAULT_IMAGE_SCALE = @"center";
-(void)parseOptions:(NSDictionary *)options type:(NSString *) type {
// Common options
mOrientation = options[@"orientation"] ?: @"default";
if (![options isKindOfClass:[NSNull class]] && [options objectForKey:@"shouldAutoClose"]) {
shouldAutoClose = [[options objectForKey:@"shouldAutoClose"] boolValue];
} else {
shouldAutoClose = YES;
}
if (![options isKindOfClass:[NSNull class]] && [options objectForKey:@"bgColor"]) {
[self setBackgroundColor:[options objectForKey:@"bgColor"]];
} else {
backgroundColor = [UIColor blackColor];
}
if (![options isKindOfClass:[NSNull class]] && [options objectForKey:@"initFullscreen"]) {
initFullscreen = [[options objectForKey:@"initFullscreen"] boolValue];
} else {
initFullscreen = YES;
}
if ([type isEqualToString:TYPE_AUDIO]) {
videoType = TYPE_AUDIO;
// bgImage
// bgImageScale
if (![options isKindOfClass:[NSNull class]] && [options objectForKey:@"bgImage"]) {
NSString *imageScale = DEFAULT_IMAGE_SCALE;
if (![options isKindOfClass:[NSNull class]] && [options objectForKey:@"bgImageScale"]) {
imageScale = [options objectForKey:@"bgImageScale"];
}
[self setImage:[options objectForKey:@"bgImage"] withScaleType:imageScale];
}
// bgColor
if (![options isKindOfClass:[NSNull class]] && [options objectForKey:@"bgColor"]) {
NSLog(@"Found option for bgColor");
[self setBackgroundColor:[options objectForKey:@"bgColor"]];
} else {
backgroundColor = [UIColor blackColor];
}
}
// No specific options for video yet
}
-(void)play:(CDVInvokedUrlCommand *) command type:(NSString *) type {
callbackId = command.callbackId;
NSString *mediaUrl = [command.arguments objectAtIndex:0];
[self parseOptions:[command.arguments objectAtIndex:1] type:type];
[self startPlayer:mediaUrl];
}
-(void)stop:(CDVInvokedUrlCommand *) command type:(NSString *) type {
callbackId = command.callbackId;
if (moviePlayer.player) {
[moviePlayer.player pause];
}
}
-(void)playVideo:(CDVInvokedUrlCommand *) command {
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
[self play:command type:[NSString stringWithString:TYPE_VIDEO]];
}
-(void)playAudio:(CDVInvokedUrlCommand *) command {
[self play:command type:[NSString stringWithString:TYPE_AUDIO]];
}
-(void)stopAudio:(CDVInvokedUrlCommand *) command {
[self stop:command type:[NSString stringWithString:TYPE_AUDIO]];
}
-(void) setBackgroundColor:(NSString *)color {
if ([color hasPrefix:@"#"]) {
// HEX value
unsigned rgbValue = 0;
NSScanner *scanner = [NSScanner scannerWithString:color];
[scanner setScanLocation:1]; // bypass '#' character
[scanner scanHexInt:&rgbValue];
backgroundColor = [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0];
} else {
// Color name
NSString *selectorString = [[color lowercaseString] stringByAppendingString:@"Color"];
SEL selector = NSSelectorFromString(selectorString);
UIColor *colorObj = [UIColor blackColor];
if ([UIColor respondsToSelector:selector]) {
colorObj = [UIColor performSelector:selector];
}
backgroundColor = colorObj;
}
}
-(UIImage*)getImage: (NSString *)imageName {
UIImage *image = nil;
if (imageName != (id)[NSNull null]) {
if ([imageName hasPrefix:@"http"]) {
// Web image
image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageName]]];
} else if ([imageName hasPrefix:@"www/"]) {
// Asset image
image = [UIImage imageNamed:imageName];
} else if ([imageName hasPrefix:@"file://"]) {
// Stored image
image = [UIImage imageWithData:[NSData dataWithContentsOfFile:[[NSURL URLWithString:imageName] path]]];
} else if ([imageName hasPrefix:@"data:"]) {
// base64 encoded string
NSURL *imageURL = [NSURL URLWithString:imageName];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
image = [UIImage imageWithData:imageData];
} else {
// explicit path
image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageName]];
}
}
return image;
}
- (void)orientationChanged:(NSNotification *)notification {
if (imageView != nil) {
// adjust imageView for rotation
imageView.bounds = moviePlayer.contentOverlayView.bounds;
imageView.frame = moviePlayer.contentOverlayView.frame;
}
}
-(void)setImage:(NSString*)imagePath withScaleType:(NSString*)imageScaleType {
imageView = [[UIImageView alloc] initWithFrame:self.viewController.view.bounds];
if (imageScaleType == nil) {
NSLog(@"imagescaletype was NIL");
imageScaleType = DEFAULT_IMAGE_SCALE;
}
if ([imageScaleType isEqualToString:@"stretch"]){
// Stretches image to fill all available background space, disregarding aspect ratio
imageView.contentMode = UIViewContentModeScaleToFill;
} else if ([imageScaleType isEqualToString:@"fit"]) {
// fits entire image perfectly
imageView.contentMode = UIViewContentModeScaleAspectFit;
} else if ([imageScaleType isEqualToString:@"aspectStretch"]) {
// Stretches image to fill all possible space while retaining aspect ratio
imageView.contentMode = UIViewContentModeScaleAspectFill;
} else {
// Places image in the center of the screen
imageView.contentMode = UIViewContentModeCenter;
//moviePlayer.backgroundView.contentMode = UIViewContentModeCenter;
}
[imageView setImage:[self getImage:imagePath]];
}
-(void)startPlayer:(NSString*)uri {
NSURL *url = [NSURL URLWithString:uri];
AVPlayer *movie = [AVPlayer playerWithURL:url];
if ([mOrientation isEqualToString:@"landscape"]) {
moviePlayer = [[LandscapeAVPlayerViewController alloc] init];
} else if ([mOrientation isEqualToString:@"portrait"]) {
moviePlayer = [[PortraitAVPlayerViewController alloc] init];
} else {
moviePlayer = [[AVPlayerViewController alloc] init];
}
[moviePlayer setPlayer:movie];
[moviePlayer setShowsPlaybackControls:YES];
if(@available(iOS 11.0, *)) { [moviePlayer setEntersFullScreenWhenPlaybackBegins:YES]; }
//present modally so we get a close button
[self.viewController presentViewController:moviePlayer animated:YES completion:^(void){
//let's start this bitch.
[moviePlayer.player play];
}];
// Listen for playback finishing
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(moviePlayBackDidFinish:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:moviePlayer.player.currentItem];
// Listen for errors
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(moviePlayBackDidFinish:)
name:AVPlayerItemFailedToPlayToEndTimeNotification
object:moviePlayer.player.currentItem];
if ([videoType isEqualToString:TYPE_AUDIO]) {
if (imageView != nil) {
[moviePlayer.contentOverlayView setAutoresizesSubviews:YES];
[moviePlayer.contentOverlayView addSubview:imageView];
}
moviePlayer.contentOverlayView.backgroundColor = backgroundColor;
[self.viewController.view addSubview:moviePlayer.view];
}
// Listen for click on the "Done" button
// Deprecated.. AVPlayerController doesn't offer a "Done" listener... thanks apple. We'll listen for an error when playback finishes
// [[NSNotificationCenter defaultCenter] addObserver:self
// selector:@selector(doneButtonClick:)
// name:MPMoviePlayerWillExitFullscreenNotification
// object:nil];
// Listen for orientation change
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(orientationChanged:)
name:UIDeviceOrientationDidChangeNotification
object:nil];
}
- (void) moviePlayBackDidFinish:(NSNotification*)notification {
NSLog(@"Playback did finish with auto close being %d, and error message being %@", shouldAutoClose, notification.userInfo);
NSDictionary *notificationUserInfo = [notification userInfo];
NSNumber *errorValue = [notificationUserInfo objectForKey:AVPlayerItemFailedToPlayToEndTimeErrorKey];
NSString *errorMsg;
if (errorValue) {
NSError *mediaPlayerError = [notificationUserInfo objectForKey:@"error"];
if (mediaPlayerError) {
errorMsg = [mediaPlayerError localizedDescription];
} else {
errorMsg = @"Unknown error.";
}
NSLog(@"Playback failed: %@", errorMsg);
}
if (shouldAutoClose || [errorMsg length] != 0) {
[self cleanup];
CDVPluginResult* pluginResult;
if ([errorMsg length] != 0) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMsg];
} else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:true];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
}
}
- (void)cleanup {
NSLog(@"Clean up");
imageView = nil;
initFullscreen = false;
backgroundColor = nil;
// Remove playback finished listener
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:AVPlayerItemDidPlayToEndTimeNotification
object:moviePlayer.player.currentItem];
// Remove playback finished error listener
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:AVPlayerItemFailedToPlayToEndTimeNotification
object:moviePlayer.player.currentItem];
// Remove orientation change listener
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:UIDeviceOrientationDidChangeNotification
object:nil];
if (moviePlayer) {
[moviePlayer.player pause];
[moviePlayer dismissViewControllerAnimated:YES completion:nil];
moviePlayer = nil;
}
}
@end