@cometchat/chat-uikit-react-native 4.2.2 → 4.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/README.md +26 -67
  2. package/android/.gradle/7.4/checksums/checksums.lock +0 -0
  3. package/android/.gradle/7.4/fileHashes/fileHashes.lock +0 -0
  4. package/android/build.gradle +1 -1
  5. package/android/src/main/java/com/reactnativecometchatuikit/CometchatUiKitPackage.java +2 -1
  6. package/android/src/main/java/com/reactnativecometchatuikit/ReactVideoView.java +796 -0
  7. package/android/src/main/java/com/reactnativecometchatuikit/ReactVideoViewManager.java +172 -0
  8. package/android/src/main/java/com/scalablevideoview/BuildConfig.java +10 -0
  9. package/android/src/main/java/com/scalablevideoview/PivotPoint.java +13 -0
  10. package/android/src/main/java/com/scalablevideoview/ScalableType.java +34 -0
  11. package/android/src/main/java/com/scalablevideoview/ScalableVideoView.java +255 -0
  12. package/android/src/main/java/com/scalablevideoview/ScaleManager.java +188 -0
  13. package/android/src/main/java/com/scalablevideoview/Size.java +20 -0
  14. package/android/src/main/java/com/zipfile/APEZProvider.java +287 -0
  15. package/android/src/main/java/com/zipfile/APKExpansionSupport.java +81 -0
  16. package/android/src/main/java/com/zipfile/ZipResourceFile.java +428 -0
  17. package/android/src/main/res/values/attrs.xml +37 -0
  18. package/ios/FileManager.m +75 -5
  19. package/ios/Video/CCRCTVideo.h +67 -0
  20. package/ios/Video/CCRCTVideo.m +2031 -0
  21. package/ios/Video/CCRCTVideoManager.h +6 -0
  22. package/ios/Video/CCRCTVideoManager.m +133 -0
  23. package/ios/Video/CCRCTVideoPlayerViewController.h +20 -0
  24. package/ios/Video/CCRCTVideoPlayerViewController.m +43 -0
  25. package/ios/Video/CCRCTVideoPlayerViewControllerDelegate.h +7 -0
  26. package/ios/Video/UIView+FindUIViewController.h +15 -0
  27. package/ios/Video/UIView+FindUIViewController.m +21 -0
  28. package/ios/VideoCaching/RCTVideoCache.h +38 -0
  29. package/ios/VideoCaching/RCTVideoCache.m +174 -0
  30. package/ios/VideoPickerModule.h +7 -0
  31. package/ios/VideoPickerModule.mm +95 -0
  32. package/package.json +3 -4
  33. package/react-native-cometchat-ui-kit.podspec +24 -10
  34. package/src/CometChatContacts/CometChatContacts.tsx +12 -9
  35. package/src/CometChatConversations/CometChatConversations.tsx +84 -64
  36. package/src/CometChatDetails/CometChatDetails.tsx +14 -12
  37. package/src/CometChatGroupMembers/CometChatGroupMembers.tsx +8 -4
  38. package/src/CometChatGroupMembers/resources/check.png +0 -0
  39. package/src/CometChatGroupMembers/resources/index.ts +2 -0
  40. package/src/CometChatGroups/CometChatGroups.tsx +4 -4
  41. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +57 -15
  42. package/src/CometChatMessageHeader/CometChatMessageHeader.tsx +9 -2
  43. package/src/CometChatMessageInformation/CometChatMessageInformation.tsx +1 -1
  44. package/src/CometChatMessageList/CometChatMessageList.tsx +596 -181
  45. package/src/CometChatMessageList/MessageListConfiguration.ts +55 -4
  46. package/src/CometChatMessageList/resources/index.ts +5 -1
  47. package/src/CometChatMessageList/resources/leftarrowcurve.png +0 -0
  48. package/src/CometChatMessageList/resources/rightarrowcurve.png +0 -0
  49. package/src/CometChatMessages/CometChatMessages.tsx +1 -1
  50. package/src/CometChatThreadedMessages/CometChatThreadedMessages.tsx +4 -12
  51. package/src/CometChatThreadedMessages/style.ts +3 -1
  52. package/src/CometChatUsers/CometChatUsers.tsx +1 -1
  53. package/src/calls/CallUtils.ts +4 -8
  54. package/src/calls/CallingExtentionDecorator.tsx +5 -2
  55. package/src/calls/CometChatCallBubble/styles.ts +2 -1
  56. package/src/calls/CometChatCallButtons/CometChatCallButtons.tsx +14 -3
  57. package/src/calls/CometChatIncomingCall/CometChatIncomingCall.tsx +9 -9
  58. package/src/calls/CometChatOutgoingCall/CometChatOutgoingCall.tsx +80 -73
  59. package/src/extensions/CollaborativeBubble/styles.ts +2 -0
  60. package/src/extensions/SmartReplies/SmartRepliesDecorator.tsx +11 -0
  61. package/src/extensions/index.ts +0 -4
  62. package/src/index.ts +53 -8
  63. package/src/shared/CometChatUiKit/CometChatUIKit.ts +14 -2
  64. package/src/shared/constants/UIKitConstants.ts +1 -0
  65. package/src/shared/events/CometChatUIEventHandler/CometChatUIEventHandler.ts +6 -0
  66. package/src/shared/events/CometChatUIEventHandler/Listener.ts +8 -0
  67. package/src/shared/events/ListenerInitializer.ts +6 -0
  68. package/src/shared/events/messages.ts +2 -0
  69. package/src/shared/framework/MessageDataSource.tsx +29 -25
  70. package/src/shared/index.ts +49 -1
  71. package/src/shared/libs/VideoPlayer/DRMType.js +6 -0
  72. package/src/shared/libs/VideoPlayer/FilterType.js +18 -0
  73. package/src/shared/libs/VideoPlayer/TextTrackType.js +5 -0
  74. package/src/shared/libs/VideoPlayer/Video.js +519 -0
  75. package/src/shared/libs/VideoPlayer/VideoResizeMode.js +5 -0
  76. package/src/shared/libs/VideoPlayerControls/OSSupport/PlatformSupport.tsx +43 -0
  77. package/src/shared/libs/VideoPlayerControls/OSSupport/TVOSSupport.tsx +16 -0
  78. package/src/shared/libs/VideoPlayerControls/OSSupport/index.tsx +1 -0
  79. package/src/shared/libs/VideoPlayerControls/VideoPlayer.tsx +511 -0
  80. package/src/shared/libs/VideoPlayerControls/assets/img/back.png +0 -0
  81. package/src/shared/libs/VideoPlayerControls/assets/img/back@2x.png +0 -0
  82. package/src/shared/libs/VideoPlayerControls/assets/img/back@3x.png +0 -0
  83. package/src/shared/libs/VideoPlayerControls/assets/img/bottom-vignette.png +0 -0
  84. package/src/shared/libs/VideoPlayerControls/assets/img/bottom-vignette@2x.png +0 -0
  85. package/src/shared/libs/VideoPlayerControls/assets/img/bottom-vignette@3x.png +0 -0
  86. package/src/shared/libs/VideoPlayerControls/assets/img/error-icon.png +0 -0
  87. package/src/shared/libs/VideoPlayerControls/assets/img/error-icon@2x.png +0 -0
  88. package/src/shared/libs/VideoPlayerControls/assets/img/error-icon@3x.png +0 -0
  89. package/src/shared/libs/VideoPlayerControls/assets/img/expand.png +0 -0
  90. package/src/shared/libs/VideoPlayerControls/assets/img/expand@2x.png +0 -0
  91. package/src/shared/libs/VideoPlayerControls/assets/img/expand@3x.png +0 -0
  92. package/src/shared/libs/VideoPlayerControls/assets/img/forward.png +0 -0
  93. package/src/shared/libs/VideoPlayerControls/assets/img/forward@2x.png +0 -0
  94. package/src/shared/libs/VideoPlayerControls/assets/img/forward@3x.png +0 -0
  95. package/src/shared/libs/VideoPlayerControls/assets/img/loader-icon.png +0 -0
  96. package/src/shared/libs/VideoPlayerControls/assets/img/loader-icon@2x.png +0 -0
  97. package/src/shared/libs/VideoPlayerControls/assets/img/loader-icon@3x.png +0 -0
  98. package/src/shared/libs/VideoPlayerControls/assets/img/pause.png +0 -0
  99. package/src/shared/libs/VideoPlayerControls/assets/img/pause@2x.png +0 -0
  100. package/src/shared/libs/VideoPlayerControls/assets/img/pause@3x.png +0 -0
  101. package/src/shared/libs/VideoPlayerControls/assets/img/play.png +0 -0
  102. package/src/shared/libs/VideoPlayerControls/assets/img/play@2x.png +0 -0
  103. package/src/shared/libs/VideoPlayerControls/assets/img/play@3x.png +0 -0
  104. package/src/shared/libs/VideoPlayerControls/assets/img/rewind.png +0 -0
  105. package/src/shared/libs/VideoPlayerControls/assets/img/rewind@2x.png +0 -0
  106. package/src/shared/libs/VideoPlayerControls/assets/img/rewind@3x.png +0 -0
  107. package/src/shared/libs/VideoPlayerControls/assets/img/shrink.png +0 -0
  108. package/src/shared/libs/VideoPlayerControls/assets/img/shrink@2x.png +0 -0
  109. package/src/shared/libs/VideoPlayerControls/assets/img/shrink@3x.png +0 -0
  110. package/src/shared/libs/VideoPlayerControls/assets/img/top-vignette.png +0 -0
  111. package/src/shared/libs/VideoPlayerControls/assets/img/top-vignette@2x.png +0 -0
  112. package/src/shared/libs/VideoPlayerControls/assets/img/top-vignette@3x.png +0 -0
  113. package/src/shared/libs/VideoPlayerControls/assets/img/volume.png +0 -0
  114. package/src/shared/libs/VideoPlayerControls/assets/img/volume@2x.png +0 -0
  115. package/src/shared/libs/VideoPlayerControls/assets/img/volume@3x.png +0 -0
  116. package/src/shared/libs/VideoPlayerControls/components/Back/Back.tsx +28 -0
  117. package/src/shared/libs/VideoPlayerControls/components/Back/index.ts +1 -0
  118. package/src/shared/libs/VideoPlayerControls/components/BottomControls.tsx +142 -0
  119. package/src/shared/libs/VideoPlayerControls/components/Control.tsx +45 -0
  120. package/src/shared/libs/VideoPlayerControls/components/Error/Error.tsx +22 -0
  121. package/src/shared/libs/VideoPlayerControls/components/Error/index.ts +1 -0
  122. package/src/shared/libs/VideoPlayerControls/components/Error/styles.ts +21 -0
  123. package/src/shared/libs/VideoPlayerControls/components/Fullscreen.tsx +36 -0
  124. package/src/shared/libs/VideoPlayerControls/components/Loader/Loader.tsx +15 -0
  125. package/src/shared/libs/VideoPlayerControls/components/Loader/index.ts +1 -0
  126. package/src/shared/libs/VideoPlayerControls/components/Loader/styles.ts +16 -0
  127. package/src/shared/libs/VideoPlayerControls/components/NullControl.tsx +7 -0
  128. package/src/shared/libs/VideoPlayerControls/components/Overlay.tsx +23 -0
  129. package/src/shared/libs/VideoPlayerControls/components/PlayPause/PlayPause.tsx +109 -0
  130. package/src/shared/libs/VideoPlayerControls/components/PlayPause/index.ts +1 -0
  131. package/src/shared/libs/VideoPlayerControls/components/PlayPause/styles.ts +21 -0
  132. package/src/shared/libs/VideoPlayerControls/components/Seekbar/Seekbar.tsx +47 -0
  133. package/src/shared/libs/VideoPlayerControls/components/Seekbar/index.ts +1 -0
  134. package/src/shared/libs/VideoPlayerControls/components/Seekbar/styles.ts +37 -0
  135. package/src/shared/libs/VideoPlayerControls/components/Timer/Timer.tsx +28 -0
  136. package/src/shared/libs/VideoPlayerControls/components/Timer/index.ts +1 -0
  137. package/src/shared/libs/VideoPlayerControls/components/Timer/styles.ts +12 -0
  138. package/src/shared/libs/VideoPlayerControls/components/Title.tsx +35 -0
  139. package/src/shared/libs/VideoPlayerControls/components/TopControls.tsx +110 -0
  140. package/src/shared/libs/VideoPlayerControls/components/Volume/Volume.tsx +37 -0
  141. package/src/shared/libs/VideoPlayerControls/components/Volume/index.ts +1 -0
  142. package/src/shared/libs/VideoPlayerControls/components/Volume/styles.ts +31 -0
  143. package/src/shared/libs/VideoPlayerControls/components/index.ts +14 -0
  144. package/src/shared/libs/VideoPlayerControls/components/styles.ts +30 -0
  145. package/src/shared/libs/VideoPlayerControls/hooks/index.ts +3 -0
  146. package/src/shared/libs/VideoPlayerControls/hooks/useAnimations.ts +68 -0
  147. package/src/shared/libs/VideoPlayerControls/hooks/useControlTimeout.tsx +67 -0
  148. package/src/shared/libs/VideoPlayerControls/hooks/usePanResponders.tsx +96 -0
  149. package/src/shared/libs/VideoPlayerControls/index.ts +4 -0
  150. package/src/shared/libs/VideoPlayerControls/styles.ts +19 -0
  151. package/src/shared/libs/VideoPlayerControls/types.ts +290 -0
  152. package/src/shared/libs/VideoPlayerControls/utils.ts +76 -0
  153. package/src/shared/modals/CometChatMessageTemplate.ts +113 -9
  154. package/src/shared/modals/InteractiveData/InteractiveMessage/SchedulerMessage.ts +23 -21
  155. package/src/shared/resources/CometChatLocalize/resources/ar/translation.json +4 -1
  156. package/src/shared/resources/CometChatLocalize/resources/de/translation.json +4 -1
  157. package/src/shared/resources/CometChatLocalize/resources/en/translation.json +6 -3
  158. package/src/shared/resources/CometChatLocalize/resources/es/translation.json +4 -1
  159. package/src/shared/resources/CometChatLocalize/resources/fr/translation.json +4 -1
  160. package/src/shared/resources/CometChatLocalize/resources/hi/translation.json +4 -1
  161. package/src/shared/resources/CometChatLocalize/resources/lt/translation.json +4 -1
  162. package/src/shared/resources/CometChatLocalize/resources/ms/translation.json +4 -1
  163. package/src/shared/resources/CometChatLocalize/resources/pt/translation.json +4 -1
  164. package/src/shared/resources/CometChatLocalize/resources/ru/translation.json +4 -1
  165. package/src/shared/resources/CometChatLocalize/resources/sv/translation.json +4 -1
  166. package/src/shared/resources/CometChatLocalize/resources/zh/translation.json +4 -1
  167. package/src/shared/resources/CometChatLocalize/resources/zh-tw/translation.json +4 -1
  168. package/src/shared/resources/CometChatTheme/Palette.ts +79 -45
  169. package/src/shared/resources/CometChatTheme/Typography.ts +18 -0
  170. package/src/shared/utils/CommonUtils.ts +71 -0
  171. package/src/shared/utils/PermissionUtilIOS.ts +104 -0
  172. package/src/shared/views/CometChatActionSheet/ActionSheetStyle.ts +3 -1
  173. package/src/shared/views/CometChatActionSheet/CometChatActionSheet.tsx +6 -6
  174. package/src/shared/views/CometChatAudioBubble/CometChatAudioBubble.tsx +28 -5
  175. package/src/shared/views/CometChatAudioBubble/style.ts +4 -2
  176. package/src/shared/views/CometChatAvatar/AvatarStyle.ts +1 -1
  177. package/src/shared/views/CometChatBottomSheet/CometChatBottomSheet.tsx +4 -3
  178. package/src/shared/views/CometChatEmojiKeyboard/CometChatEmojiKeyboard.tsx +47 -31
  179. package/src/shared/views/CometChatEmojiKeyboard/EmojiKeyboardConfiguration.ts +5 -5
  180. package/src/shared/views/CometChatEmojiKeyboard/EmojiKeyboardStyle.ts +12 -13
  181. package/src/shared/views/CometChatFileBubble/CometChatFileBubble.tsx +52 -5
  182. package/src/shared/views/CometChatFileBubble/style.ts +4 -2
  183. package/src/shared/views/CometChatImageBubble/CometChatImageBubble.tsx +25 -2
  184. package/src/shared/views/CometChatList/CometChatList.tsx +2 -1
  185. package/src/shared/views/CometChatMessageBubble/CometChatMessageBubble.tsx +51 -2
  186. package/src/shared/views/CometChatQuickReactions/CometChatQuickReactions.tsx +76 -0
  187. package/src/shared/views/CometChatQuickReactions/QuickReactionsConfiguration.tsx +12 -0
  188. package/src/shared/views/CometChatQuickReactions/QuickReactionsStyle.tsx +35 -0
  189. package/src/shared/views/CometChatQuickReactions/index.ts +12 -0
  190. package/src/shared/views/CometChatReactions/CometChatReactions.tsx +166 -0
  191. package/src/shared/views/CometChatReactions/ReactionsConfiguration.tsx +12 -0
  192. package/src/shared/views/CometChatReactions/ReactionsStyle.tsx +43 -0
  193. package/src/shared/views/CometChatReactions/index.ts +12 -0
  194. package/src/{extensions/Reactions/CometChatMessageReactions → shared/views/CometChatReactions}/style.ts +7 -7
  195. package/src/shared/views/CometChatReactionsList/CometChatReactionsList.tsx +335 -0
  196. package/src/shared/views/CometChatReactionsList/ReactionsListConfiguration.tsx +14 -0
  197. package/src/shared/views/CometChatReactionsList/ReactionsListStyle.tsx +67 -0
  198. package/src/shared/views/CometChatReactionsList/index.ts +12 -0
  199. package/src/shared/views/CometChatReactionsList/resources/Spineer.png +0 -0
  200. package/src/shared/views/CometChatReactionsList/resources/index.ts +5 -0
  201. package/src/shared/views/CometChatReceipt/CometChatReceipt.tsx +21 -4
  202. package/src/shared/views/CometChatReceipt/MessageConfiguration.ts +12 -0
  203. package/src/shared/views/CometChatReceipt/resources/error.png +0 -0
  204. package/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx +1 -1
  205. package/src/shared/views/CometChatVideoBubble/CometChatVideoBubble.tsx +78 -12
  206. package/src/shared/views/CometChatVideoBubble/VideoBubbleStyle.ts +52 -2
  207. package/src/shared/views/CometChatVideoPlayer/CometChatVideoPlayer.tsx +134 -0
  208. package/src/shared/views/CometChatVideoPlayer/index.tsx +1 -0
  209. package/src/shared/views/index.ts +30 -0
  210. package/android/.gradle/7.4.2/checksums/checksums.lock +0 -0
  211. package/android/.gradle/7.4.2/fileChanges/last-build.bin +0 -0
  212. package/android/.gradle/7.4.2/fileHashes/fileHashes.lock +0 -0
  213. package/android/.gradle/7.4.2/gc.properties +0 -0
  214. package/android/.gradle/checksums/checksums.lock +0 -0
  215. package/android/.idea/gradle.xml +0 -13
  216. package/android/.idea/misc.xml +0 -8
  217. package/android/.idea/modules/android.iml +0 -18
  218. package/android/.idea/modules.xml +0 -8
  219. package/android/.idea/vcs.xml +0 -6
  220. package/android/local.properties +0 -8
  221. package/src/extensions/Reactions/CometChatMessageReactions/CometChatMessageReactions.tsx +0 -249
  222. package/src/extensions/Reactions/CometChatMessageReactions/index.ts +0 -3
  223. package/src/extensions/Reactions/ReactionsDecorator.tsx +0 -164
  224. package/src/extensions/Reactions/ReactionsExtension.tsx +0 -48
  225. package/src/extensions/Reactions/index.ts +0 -4
  226. /package/src/{extensions/Reactions → shared/views/CometChatQuickReactions}/resources/AddReactions.png +0 -0
  227. /package/src/{extensions/Reactions → shared/views/CometChatQuickReactions}/resources/index.ts +0 -0
@@ -0,0 +1,2031 @@
1
+ #import <React/RCTConvert.h>
2
+ #import "CCRCTVideo.h"
3
+ #import <React/RCTBridgeModule.h>
4
+ #import <React/RCTEventDispatcher.h>
5
+ #import <React/UIView+React.h>
6
+ #include <MediaAccessibility/MediaAccessibility.h>
7
+ #include <AVFoundation/AVFoundation.h>
8
+
9
+ static NSString *const statusKeyPath = @"status";
10
+ static NSString *const playbackLikelyToKeepUpKeyPath = @"playbackLikelyToKeepUp";
11
+ static NSString *const playbackBufferEmptyKeyPath = @"playbackBufferEmpty";
12
+ static NSString *const readyForDisplayKeyPath = @"readyForDisplay";
13
+ static NSString *const playbackRate = @"rate";
14
+ static NSString *const timedMetadata = @"timedMetadata";
15
+ static NSString *const externalPlaybackActive = @"externalPlaybackActive";
16
+
17
+ static int const RCTVideoUnset = -1;
18
+
19
+ #ifdef DEBUG
20
+ #define DebugLog(...) NSLog(__VA_ARGS__)
21
+ #else
22
+ #define DebugLog(...) (void)0
23
+ #endif
24
+
25
+ @implementation CCRCTVideo
26
+ {
27
+ AVPlayer *_player;
28
+ AVPlayerItem *_playerItem;
29
+ NSDictionary *_source;
30
+ BOOL _playerItemObserversSet;
31
+ BOOL _playerBufferEmpty;
32
+ AVPlayerLayer *_playerLayer;
33
+ BOOL _playerLayerObserverSet;
34
+ CCRCTVideoPlayerViewController *_playerViewController;
35
+ NSURL *_videoURL;
36
+ BOOL _requestingCertificate;
37
+ BOOL _requestingCertificateErrored;
38
+
39
+ /* DRM */
40
+ NSDictionary *_drm;
41
+ AVAssetResourceLoadingRequest *_loadingRequest;
42
+
43
+ /* Required to publish events */
44
+ RCTEventDispatcher *_eventDispatcher;
45
+ BOOL _playbackRateObserverRegistered;
46
+ BOOL _isExternalPlaybackActiveObserverRegistered;
47
+ BOOL _videoLoadStarted;
48
+
49
+ bool _pendingSeek;
50
+ float _pendingSeekTime;
51
+ float _lastSeekTime;
52
+
53
+ /* For sending videoProgress events */
54
+ Float64 _progressUpdateInterval;
55
+ BOOL _controls;
56
+ id _timeObserver;
57
+
58
+ /* Keep track of any modifiers, need to be applied after each play */
59
+ float _volume;
60
+ float _rate;
61
+ float _maxBitRate;
62
+
63
+ BOOL _automaticallyWaitsToMinimizeStalling;
64
+ BOOL _muted;
65
+ BOOL _paused;
66
+ BOOL _repeat;
67
+ BOOL _allowsExternalPlayback;
68
+ NSArray * _textTracks;
69
+ NSDictionary * _selectedTextTrack;
70
+ NSDictionary * _selectedAudioTrack;
71
+ BOOL _playbackStalled;
72
+ BOOL _playInBackground;
73
+ BOOL _preventsDisplaySleepDuringVideoPlayback;
74
+ float _preferredForwardBufferDuration;
75
+ BOOL _playWhenInactive;
76
+ BOOL _pictureInPicture;
77
+ NSString * _ignoreSilentSwitch;
78
+ NSString * _mixWithOthers;
79
+ NSString * _resizeMode;
80
+ BOOL _fullscreen;
81
+ BOOL _fullscreenAutorotate;
82
+ NSString * _fullscreenOrientation;
83
+ BOOL _fullscreenPlayerPresented;
84
+ NSString *_filterName;
85
+ BOOL _filterEnabled;
86
+ UIViewController * _presentingViewController;
87
+ #if __has_include(<react-native-cometchat-ui-kit/RCTVideoCache.h>)
88
+ RCTVideoCache * _videoCache;
89
+ #endif
90
+ #if TARGET_OS_IOS
91
+ void (^__strong _Nonnull _restoreUserInterfaceForPIPStopCompletionHandler)(BOOL);
92
+ AVPictureInPictureController *_pipController;
93
+ #endif
94
+ }
95
+
96
+ - (instancetype)initWithEventDispatcher:(RCTEventDispatcher *)eventDispatcher
97
+ {
98
+ if ((self = [super init])) {
99
+ _eventDispatcher = eventDispatcher;
100
+ _automaticallyWaitsToMinimizeStalling = YES;
101
+ _playbackRateObserverRegistered = NO;
102
+ _isExternalPlaybackActiveObserverRegistered = NO;
103
+ _playbackStalled = NO;
104
+ _rate = 1.0;
105
+ _volume = 1.0;
106
+ _resizeMode = @"AVLayerVideoGravityResizeAspectFill";
107
+ _fullscreenAutorotate = YES;
108
+ _fullscreenOrientation = @"all";
109
+ _pendingSeek = false;
110
+ _pendingSeekTime = 0.0f;
111
+ _lastSeekTime = 0.0f;
112
+ _progressUpdateInterval = 250;
113
+ _controls = NO;
114
+ _playerBufferEmpty = YES;
115
+ _playInBackground = false;
116
+ _preventsDisplaySleepDuringVideoPlayback = true;
117
+ _preferredForwardBufferDuration = 0.0f;
118
+ _allowsExternalPlayback = YES;
119
+ _playWhenInactive = false;
120
+ _pictureInPicture = false;
121
+ _ignoreSilentSwitch = @"inherit"; // inherit, ignore, obey
122
+ _mixWithOthers = @"inherit"; // inherit, mix, duck
123
+ #if TARGET_OS_IOS
124
+ _restoreUserInterfaceForPIPStopCompletionHandler = NULL;
125
+ #endif
126
+ #if __has_include(<react-native-cometchat-ui-kit/RCTVideoCache.h>)
127
+ _videoCache = [RCTVideoCache sharedInstance];
128
+ #endif
129
+ [[NSNotificationCenter defaultCenter] addObserver:self
130
+ selector:@selector(applicationWillResignActive:)
131
+ name:UIApplicationWillResignActiveNotification
132
+ object:nil];
133
+
134
+ [[NSNotificationCenter defaultCenter] addObserver:self
135
+ selector:@selector(applicationDidEnterBackground:)
136
+ name:UIApplicationDidEnterBackgroundNotification
137
+ object:nil];
138
+
139
+ [[NSNotificationCenter defaultCenter] addObserver:self
140
+ selector:@selector(applicationWillEnterForeground:)
141
+ name:UIApplicationWillEnterForegroundNotification
142
+ object:nil];
143
+
144
+ [[NSNotificationCenter defaultCenter] addObserver:self
145
+ selector:@selector(audioRouteChanged:)
146
+ name:AVAudioSessionRouteChangeNotification
147
+ object:nil];
148
+ }
149
+
150
+ return self;
151
+ }
152
+
153
+ - (CCRCTVideoPlayerViewController*)createPlayerViewController:(AVPlayer*)player
154
+ withPlayerItem:(AVPlayerItem*)playerItem {
155
+ CCRCTVideoPlayerViewController* viewController = [[CCRCTVideoPlayerViewController alloc] init];
156
+ viewController.showsPlaybackControls = YES;
157
+ viewController.rctDelegate = self;
158
+ viewController.preferredOrientation = _fullscreenOrientation;
159
+
160
+ viewController.view.frame = self.bounds;
161
+ viewController.player = player;
162
+ return viewController;
163
+ }
164
+
165
+ /* ---------------------------------------------------------
166
+ ** Get the duration for a AVPlayerItem.
167
+ ** ------------------------------------------------------- */
168
+
169
+ - (CMTime)playerItemDuration
170
+ {
171
+ AVPlayerItem *playerItem = [_player currentItem];
172
+ if (playerItem.status == AVPlayerItemStatusReadyToPlay)
173
+ {
174
+ return([playerItem duration]);
175
+ }
176
+
177
+ return(kCMTimeInvalid);
178
+ }
179
+
180
+ - (CMTimeRange)playerItemSeekableTimeRange
181
+ {
182
+ AVPlayerItem *playerItem = [_player currentItem];
183
+ if (playerItem.status == AVPlayerItemStatusReadyToPlay)
184
+ {
185
+ return [playerItem seekableTimeRanges].firstObject.CMTimeRangeValue;
186
+ }
187
+
188
+ return (kCMTimeRangeZero);
189
+ }
190
+
191
+ -(void)addPlayerTimeObserver
192
+ {
193
+ const Float64 progressUpdateIntervalMS = _progressUpdateInterval / 1000;
194
+ // @see endScrubbing in AVPlayerDemoPlaybackViewController.m
195
+ // of https://developer.apple.com/library/ios/samplecode/AVPlayerDemo/Introduction/Intro.html
196
+ __weak CCRCTVideo *weakSelf = self;
197
+ _timeObserver = [_player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(progressUpdateIntervalMS, NSEC_PER_SEC)
198
+ queue:NULL
199
+ usingBlock:^(CMTime time) { [weakSelf sendProgressUpdate]; }
200
+ ];
201
+ }
202
+
203
+ /* Cancels the previously registered time observer. */
204
+ -(void)removePlayerTimeObserver
205
+ {
206
+ if (_timeObserver)
207
+ {
208
+ [_player removeTimeObserver:_timeObserver];
209
+ _timeObserver = nil;
210
+ }
211
+ }
212
+
213
+ #pragma mark - Progress
214
+
215
+ - (void)dealloc
216
+ {
217
+ [[NSNotificationCenter defaultCenter] removeObserver:self];
218
+ [self removePlayerLayer];
219
+ [self removePlayerItemObservers];
220
+ [_player removeObserver:self forKeyPath:playbackRate context:nil];
221
+ [_player removeObserver:self forKeyPath:externalPlaybackActive context: nil];
222
+ }
223
+
224
+ #pragma mark - App lifecycle handlers
225
+
226
+ - (void)applicationWillResignActive:(NSNotification *)notification
227
+ {
228
+ if (_playInBackground || _playWhenInactive || _paused) return;
229
+
230
+ [_player pause];
231
+ [_player setRate:0.0];
232
+ }
233
+
234
+ - (void)applicationDidEnterBackground:(NSNotification *)notification
235
+ {
236
+ if (_playInBackground) {
237
+ // Needed to play sound in background. See https://developer.apple.com/library/ios/qa/qa1668/_index.html
238
+ [_playerLayer setPlayer:nil];
239
+ [_playerViewController setPlayer:nil];
240
+ }
241
+ }
242
+
243
+ - (void)applicationWillEnterForeground:(NSNotification *)notification
244
+ {
245
+ [self applyModifiers];
246
+ if (_playInBackground) {
247
+ [_playerLayer setPlayer:_player];
248
+ [_playerViewController setPlayer:_player];
249
+ }
250
+ }
251
+
252
+ #pragma mark - Audio events
253
+
254
+ - (void)audioRouteChanged:(NSNotification *)notification
255
+ {
256
+ NSNumber *reason = [[notification userInfo] objectForKey:AVAudioSessionRouteChangeReasonKey];
257
+ NSNumber *previousRoute = [[notification userInfo] objectForKey:AVAudioSessionRouteChangePreviousRouteKey];
258
+ if (reason.unsignedIntValue == AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
259
+ self.onVideoAudioBecomingNoisy(@{@"target": self.reactTag});
260
+ }
261
+ }
262
+
263
+ #pragma mark - Progress
264
+
265
+ - (void)sendProgressUpdate
266
+ {
267
+ AVPlayerItem *video = [_player currentItem];
268
+ if (video == nil || video.status != AVPlayerItemStatusReadyToPlay) {
269
+ return;
270
+ }
271
+
272
+ CMTime playerDuration = [self playerItemDuration];
273
+ if (CMTIME_IS_INVALID(playerDuration)) {
274
+ return;
275
+ }
276
+
277
+ CMTime currentTime = _player.currentTime;
278
+ NSDate *currentPlaybackTime = _player.currentItem.currentDate;
279
+ const Float64 duration = CMTimeGetSeconds(playerDuration);
280
+ const Float64 currentTimeSecs = CMTimeGetSeconds(currentTime);
281
+
282
+ [[NSNotificationCenter defaultCenter] postNotificationName:@"RCTVideo_progress" object:nil userInfo:@{@"progress": [NSNumber numberWithDouble: currentTimeSecs / duration]}];
283
+
284
+ if( currentTimeSecs >= 0 && self.onVideoProgress) {
285
+ self.onVideoProgress(@{
286
+ @"currentTime": [NSNumber numberWithFloat:CMTimeGetSeconds(currentTime)],
287
+ @"playableDuration": [self calculatePlayableDuration],
288
+ @"atValue": [NSNumber numberWithLongLong:currentTime.value],
289
+ @"atTimescale": [NSNumber numberWithInt:currentTime.timescale],
290
+ @"currentPlaybackTime": [NSNumber numberWithLongLong:[@(floor([currentPlaybackTime timeIntervalSince1970] * 1000)) longLongValue]],
291
+ @"target": self.reactTag,
292
+ @"seekableDuration": [self calculateSeekableDuration],
293
+ });
294
+ }
295
+ }
296
+
297
+ /*!
298
+ * Calculates and returns the playable duration of the current player item using its loaded time ranges.
299
+ *
300
+ * \returns The playable duration of the current player item in seconds.
301
+ */
302
+ - (NSNumber *)calculatePlayableDuration
303
+ {
304
+ AVPlayerItem *video = _player.currentItem;
305
+ if (video.status == AVPlayerItemStatusReadyToPlay) {
306
+ __block CMTimeRange effectiveTimeRange;
307
+ [video.loadedTimeRanges enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
308
+ CMTimeRange timeRange = [obj CMTimeRangeValue];
309
+ if (CMTimeRangeContainsTime(timeRange, video.currentTime)) {
310
+ effectiveTimeRange = timeRange;
311
+ *stop = YES;
312
+ }
313
+ }];
314
+ Float64 playableDuration = CMTimeGetSeconds(CMTimeRangeGetEnd(effectiveTimeRange));
315
+ if (playableDuration > 0) {
316
+ return [NSNumber numberWithFloat:playableDuration];
317
+ }
318
+ }
319
+ return [NSNumber numberWithInteger:0];
320
+ }
321
+
322
+ - (NSNumber *)calculateSeekableDuration
323
+ {
324
+ CMTimeRange timeRange = [self playerItemSeekableTimeRange];
325
+ if (CMTIME_IS_NUMERIC(timeRange.duration))
326
+ {
327
+ return [NSNumber numberWithFloat:CMTimeGetSeconds(timeRange.duration)];
328
+ }
329
+ return [NSNumber numberWithInteger:0];
330
+ }
331
+
332
+ - (void)addPlayerItemObservers
333
+ {
334
+ [_playerItem addObserver:self forKeyPath:statusKeyPath options:0 context:nil];
335
+ [_playerItem addObserver:self forKeyPath:playbackBufferEmptyKeyPath options:0 context:nil];
336
+ [_playerItem addObserver:self forKeyPath:playbackLikelyToKeepUpKeyPath options:0 context:nil];
337
+ [_playerItem addObserver:self forKeyPath:timedMetadata options:NSKeyValueObservingOptionNew context:nil];
338
+ _playerItemObserversSet = YES;
339
+ }
340
+
341
+ /* Fixes https://github.com/brentvatne/react-native-video/issues/43
342
+ * Crashes caused when trying to remove the observer when there is no
343
+ * observer set */
344
+ - (void)removePlayerItemObservers
345
+ {
346
+ if (_playerItemObserversSet) {
347
+ [_playerItem removeObserver:self forKeyPath:statusKeyPath];
348
+ [_playerItem removeObserver:self forKeyPath:playbackBufferEmptyKeyPath];
349
+ [_playerItem removeObserver:self forKeyPath:playbackLikelyToKeepUpKeyPath];
350
+ [_playerItem removeObserver:self forKeyPath:timedMetadata];
351
+ _playerItemObserversSet = NO;
352
+ }
353
+ }
354
+
355
+ #pragma mark - Player and source
356
+
357
+ - (void)setSrc:(NSDictionary *)source
358
+ {
359
+ _source = source;
360
+ [self removePlayerLayer];
361
+ [self removePlayerTimeObserver];
362
+ [self removePlayerItemObservers];
363
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) 0), dispatch_get_main_queue(), ^{
364
+
365
+ // perform on next run loop, otherwise other passed react-props may not be set
366
+ [self playerItemForSource:self->_source withCallback:^(AVPlayerItem * playerItem) {
367
+ self->_playerItem = playerItem;
368
+ _playerItem = playerItem;
369
+ [self setPreferredForwardBufferDuration:_preferredForwardBufferDuration];
370
+ [self addPlayerItemObservers];
371
+ [self setFilter:self->_filterName];
372
+ [self setMaxBitRate:self->_maxBitRate];
373
+
374
+ [_player pause];
375
+
376
+ if (_playbackRateObserverRegistered) {
377
+ [_player removeObserver:self forKeyPath:playbackRate context:nil];
378
+ _playbackRateObserverRegistered = NO;
379
+ }
380
+ if (self->_isExternalPlaybackActiveObserverRegistered) {
381
+ [self->_player removeObserver:self forKeyPath:externalPlaybackActive context:nil];
382
+ self->_isExternalPlaybackActiveObserverRegistered = NO;
383
+ }
384
+
385
+ self->_player = [AVPlayer playerWithPlayerItem:self->_playerItem];
386
+ self->_player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
387
+
388
+ [self->_player addObserver:self forKeyPath:playbackRate options:0 context:nil];
389
+ self->_playbackRateObserverRegistered = YES;
390
+
391
+ [self->_player addObserver:self forKeyPath:externalPlaybackActive options:0 context:nil];
392
+ self->_isExternalPlaybackActiveObserverRegistered = YES;
393
+
394
+ [self addPlayerTimeObserver];
395
+ if (@available(iOS 10.0, *)) {
396
+ [self setAutomaticallyWaitsToMinimizeStalling:_automaticallyWaitsToMinimizeStalling];
397
+ }
398
+
399
+ //Perform on next run loop, otherwise onVideoLoadStart is nil
400
+ if (self.onVideoLoadStart) {
401
+ id uri = [self->_source objectForKey:@"uri"];
402
+ id type = [self->_source objectForKey:@"type"];
403
+ self.onVideoLoadStart(@{@"src": @{
404
+ @"uri": uri ? uri : [NSNull null],
405
+ @"type": type ? type : [NSNull null],
406
+ @"isNetwork": [NSNumber numberWithBool:(bool)[self->_source objectForKey:@"isNetwork"]]},
407
+ @"drm": self->_drm ? self->_drm : [NSNull null],
408
+ @"target": self.reactTag
409
+ });
410
+ }
411
+ }];
412
+ });
413
+ _videoLoadStarted = YES;
414
+ }
415
+
416
+ - (void)setDrm:(NSDictionary *)drm {
417
+ _drm = drm;
418
+ }
419
+
420
+ - (NSURL*) urlFilePath:(NSString*) filepath {
421
+ if ([filepath containsString:@"file://"]) {
422
+ return [NSURL URLWithString:filepath];
423
+ }
424
+
425
+ // if no file found, check if the file exists in the Document directory
426
+ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
427
+ NSString* relativeFilePath = [filepath lastPathComponent];
428
+ // the file may be multiple levels below the documents directory
429
+ NSArray* fileComponents = [filepath componentsSeparatedByString:@"Documents/"];
430
+ if (fileComponents.count > 1) {
431
+ relativeFilePath = [fileComponents objectAtIndex:1];
432
+ }
433
+
434
+ NSString *path = [paths.firstObject stringByAppendingPathComponent:relativeFilePath];
435
+ if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
436
+ return [NSURL fileURLWithPath:path];
437
+ }
438
+ return nil;
439
+ }
440
+
441
+ - (void)playerItemPrepareText:(AVAsset *)asset assetOptions:(NSDictionary * __nullable)assetOptions withCallback:(void(^)(AVPlayerItem *))handler
442
+ {
443
+ if (!_textTracks || _textTracks.count==0) {
444
+ handler([AVPlayerItem playerItemWithAsset:asset]);
445
+ return;
446
+ }
447
+
448
+ // AVPlayer can't airplay AVMutableCompositions
449
+ _allowsExternalPlayback = NO;
450
+
451
+ // sideload text tracks
452
+ AVMutableComposition *mixComposition = [[AVMutableComposition alloc] init];
453
+
454
+ AVAssetTrack *videoAsset = [asset tracksWithMediaType:AVMediaTypeVideo].firstObject;
455
+ AVMutableCompositionTrack *videoCompTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
456
+ [videoCompTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.timeRange.duration)
457
+ ofTrack:videoAsset
458
+ atTime:kCMTimeZero
459
+ error:nil];
460
+
461
+ AVAssetTrack *audioAsset = [asset tracksWithMediaType:AVMediaTypeAudio].firstObject;
462
+ AVMutableCompositionTrack *audioCompTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
463
+ [audioCompTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.timeRange.duration)
464
+ ofTrack:audioAsset
465
+ atTime:kCMTimeZero
466
+ error:nil];
467
+
468
+ NSMutableArray* validTextTracks = [NSMutableArray array];
469
+ for (int i = 0; i < _textTracks.count; ++i) {
470
+ AVURLAsset *textURLAsset;
471
+ NSString *textUri = [_textTracks objectAtIndex:i][@"uri"];
472
+ if ([[textUri lowercaseString] hasPrefix:@"http"]) {
473
+ textURLAsset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:textUri] options:assetOptions];
474
+ } else {
475
+ textURLAsset = [AVURLAsset URLAssetWithURL:[self urlFilePath:textUri] options:nil];
476
+ }
477
+ AVAssetTrack *textTrackAsset = [textURLAsset tracksWithMediaType:AVMediaTypeText].firstObject;
478
+ if (!textTrackAsset) continue; // fix when there's no textTrackAsset
479
+ [validTextTracks addObject:[_textTracks objectAtIndex:i]];
480
+ AVMutableCompositionTrack *textCompTrack = [mixComposition
481
+ addMutableTrackWithMediaType:AVMediaTypeText
482
+ preferredTrackID:kCMPersistentTrackID_Invalid];
483
+ [textCompTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.timeRange.duration)
484
+ ofTrack:textTrackAsset
485
+ atTime:kCMTimeZero
486
+ error:nil];
487
+ }
488
+ if (validTextTracks.count != _textTracks.count) {
489
+ [self setTextTracks:validTextTracks];
490
+ }
491
+
492
+ handler([AVPlayerItem playerItemWithAsset:mixComposition]);
493
+ }
494
+
495
+ - (void)playerItemForSource:(NSDictionary *)source withCallback:(void(^)(AVPlayerItem *))handler
496
+ {
497
+ bool isNetwork = [RCTConvert BOOL:[source objectForKey:@"isNetwork"]];
498
+ bool isAsset = [RCTConvert BOOL:[source objectForKey:@"isAsset"]];
499
+ bool shouldCache = [RCTConvert BOOL:[source objectForKey:@"shouldCache"]];
500
+ NSString *uri = [source objectForKey:@"uri"];
501
+ NSString *type = [source objectForKey:@"type"];
502
+ AVURLAsset *asset;
503
+ if (!uri || [uri isEqualToString:@""]) {
504
+ DebugLog(@"Could not find video URL in source '%@'", source);
505
+ return;
506
+ }
507
+
508
+ NSURL *url = isNetwork || isAsset
509
+ ? [NSURL URLWithString:uri]
510
+ : [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:uri ofType:type]];
511
+ NSMutableDictionary *assetOptions = [[NSMutableDictionary alloc] init];
512
+
513
+ if (isNetwork) {
514
+ NSDictionary *headers = [source objectForKey:@"requestHeaders"];
515
+ if ([headers count] > 0) {
516
+ [assetOptions setObject:headers forKey:@"AVURLAssetHTTPHeaderFieldsKey"];
517
+ }
518
+ NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
519
+ [assetOptions setObject:cookies forKey:AVURLAssetHTTPCookiesKey];
520
+
521
+ #if __has_include(<react-native-cometchat-ui-kit/RCTVideoCache.h>)
522
+ if (shouldCache && (!_textTracks || !_textTracks.count)) {
523
+ /* The DVURLAsset created by cache doesn't have a tracksWithMediaType property, so trying
524
+ * to bring in the text track code will crash. I suspect this is because the asset hasn't fully loaded.
525
+ * Until this is fixed, we need to bypass caching when text tracks are specified.
526
+ */
527
+ DebugLog(@"Caching is not supported for uri '%@' because text tracks are not compatible with the cache. Checkout https://github.com/react-native-community/react-native-video/blob/master/docs/caching.md", uri);
528
+ [self playerItemForSourceUsingCache:uri assetOptions:assetOptions withCallback:handler];
529
+ return;
530
+ }
531
+ #endif
532
+
533
+ asset = [AVURLAsset URLAssetWithURL:url options:assetOptions];
534
+ } else if (isAsset) {
535
+ asset = [AVURLAsset URLAssetWithURL:url options:nil];
536
+ } else {
537
+ asset = [AVURLAsset URLAssetWithURL:[[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:uri ofType:type]] options:nil];
538
+ }
539
+ // Reset _loadingRequest
540
+ if (_loadingRequest != nil) {
541
+ [_loadingRequest finishLoading];
542
+ }
543
+ _requestingCertificate = NO;
544
+ _requestingCertificateErrored = NO;
545
+ // End Reset _loadingRequest
546
+ if (self->_drm != nil) {
547
+ dispatch_queue_t queue = dispatch_queue_create("assetQueue", nil);
548
+ [asset.resourceLoader setDelegate:self queue:queue];
549
+ }
550
+
551
+ [self playerItemPrepareText:asset assetOptions:assetOptions withCallback:handler];
552
+ }
553
+
554
+ #if __has_include(<react-native-cometchat-ui-kit/RCTVideoCache.h>)
555
+
556
+ - (void)playerItemForSourceUsingCache:(NSString *)uri assetOptions:(NSDictionary *)options withCallback:(void(^)(AVPlayerItem *))handler {
557
+ NSURL *url = [NSURL URLWithString:uri];
558
+ [_videoCache getItemForUri:uri withCallback:^(RCTVideoCacheStatus videoCacheStatus, AVAsset * _Nullable cachedAsset) {
559
+ switch (videoCacheStatus) {
560
+ case RCTVideoCacheStatusMissingFileExtension: {
561
+ DebugLog(@"Could not generate cache key for uri '%@'. It is currently not supported to cache urls that do not include a file extension. The video file will not be cached. Checkout https://github.com/react-native-community/react-native-video/blob/master/docs/caching.md", uri);
562
+ AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:options];
563
+ [self playerItemPrepareText:asset assetOptions:options withCallback:handler];
564
+ return;
565
+ }
566
+ case RCTVideoCacheStatusUnsupportedFileExtension: {
567
+ DebugLog(@"Could not generate cache key for uri '%@'. The file extension of that uri is currently not supported. The video file will not be cached. Checkout https://github.com/react-native-community/react-native-video/blob/master/docs/caching.md", uri);
568
+ AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:options];
569
+ [self playerItemPrepareText:asset assetOptions:options withCallback:handler];
570
+ return;
571
+ }
572
+ default:
573
+ if (cachedAsset) {
574
+ DebugLog(@"Playing back uri '%@' from cache", uri);
575
+ // See note in playerItemForSource about not being able to support text tracks & caching
576
+ handler([AVPlayerItem playerItemWithAsset:cachedAsset]);
577
+ return;
578
+ }
579
+ }
580
+
581
+ DVURLAsset *asset = [[DVURLAsset alloc] initWithURL:url options:options networkTimeout:10000];
582
+ asset.loaderDelegate = self;
583
+
584
+ /* More granular code to have control over the DVURLAsset
585
+ DVAssetLoaderDelegate *resourceLoaderDelegate = [[DVAssetLoaderDelegate alloc] initWithURL:url];
586
+ resourceLoaderDelegate.delegate = self;
587
+ NSURLComponents *components = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:NO];
588
+ components.scheme = [DVAssetLoaderDelegate scheme];
589
+ AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[components URL] options:options];
590
+ [asset.resourceLoader setDelegate:resourceLoaderDelegate queue:dispatch_get_main_queue()];
591
+ */
592
+
593
+ handler([AVPlayerItem playerItemWithAsset:asset]);
594
+ }];
595
+ }
596
+
597
+ #pragma mark - DVAssetLoaderDelegate
598
+
599
+ - (void)dvAssetLoaderDelegate:(DVAssetLoaderDelegate *)loaderDelegate
600
+ didLoadData:(NSData *)data
601
+ forURL:(NSURL *)url {
602
+ [_videoCache storeItem:data forUri:[url absoluteString] withCallback:^(BOOL success) {
603
+ DebugLog(@"Cache data stored successfully 🎉");
604
+ }];
605
+ }
606
+
607
+ #endif
608
+
609
+ - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
610
+ {
611
+
612
+ if([keyPath isEqualToString:readyForDisplayKeyPath] && [change objectForKey:NSKeyValueChangeNewKey] && self.onReadyForDisplay) {
613
+ self.onReadyForDisplay(@{@"target": self.reactTag});
614
+ return;
615
+ }
616
+ if (object == _playerItem) {
617
+ // When timeMetadata is read the event onTimedMetadata is triggered
618
+ if ([keyPath isEqualToString:timedMetadata]) {
619
+ NSArray<AVMetadataItem *> *items = [change objectForKey:@"new"];
620
+ if (items && ![items isEqual:[NSNull null]] && items.count > 0) {
621
+ NSMutableArray *array = [NSMutableArray new];
622
+ for (AVMetadataItem *item in items) {
623
+ NSString *value = (NSString *)item.value;
624
+ NSString *identifier = item.identifier;
625
+
626
+ if (![value isEqual: [NSNull null]]) {
627
+ NSDictionary *dictionary = [[NSDictionary alloc] initWithObjects:@[value, identifier] forKeys:@[@"value", @"identifier"]];
628
+
629
+ [array addObject:dictionary];
630
+ }
631
+ }
632
+
633
+ self.onTimedMetadata(@{
634
+ @"target": self.reactTag,
635
+ @"metadata": array
636
+ });
637
+ }
638
+ }
639
+
640
+ if ([keyPath isEqualToString:statusKeyPath]) {
641
+ // Handle player item status change.
642
+ if (_playerItem.status == AVPlayerItemStatusReadyToPlay) {
643
+ float duration = CMTimeGetSeconds(_playerItem.asset.duration);
644
+
645
+ if (isnan(duration)) {
646
+ duration = 0.0;
647
+ }
648
+
649
+ NSObject *width = @"undefined";
650
+ NSObject *height = @"undefined";
651
+ NSString *orientation = @"undefined";
652
+
653
+ if ([_playerItem.asset tracksWithMediaType:AVMediaTypeVideo].count > 0) {
654
+ AVAssetTrack *videoTrack = [[_playerItem.asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
655
+ width = [NSNumber numberWithFloat:videoTrack.naturalSize.width];
656
+ height = [NSNumber numberWithFloat:videoTrack.naturalSize.height];
657
+ CGAffineTransform preferredTransform = [videoTrack preferredTransform];
658
+
659
+ if ((videoTrack.naturalSize.width == preferredTransform.tx
660
+ && videoTrack.naturalSize.height == preferredTransform.ty)
661
+ || (preferredTransform.tx == 0 && preferredTransform.ty == 0))
662
+ {
663
+ orientation = @"landscape";
664
+ } else {
665
+ orientation = @"portrait";
666
+ }
667
+ } else if (_playerItem.presentationSize.height) {
668
+ width = [NSNumber numberWithFloat:_playerItem.presentationSize.width];
669
+ height = [NSNumber numberWithFloat:_playerItem.presentationSize.height];
670
+ orientation = _playerItem.presentationSize.width > _playerItem.presentationSize.height ? @"landscape" : @"portrait";
671
+ }
672
+
673
+ if (_pendingSeek) {
674
+ [self setCurrentTime:_pendingSeekTime];
675
+ _pendingSeek = false;
676
+ }
677
+
678
+ if (self.onVideoLoad && _videoLoadStarted) {
679
+ self.onVideoLoad(@{@"duration": [NSNumber numberWithFloat:duration],
680
+ @"currentTime": [NSNumber numberWithFloat:CMTimeGetSeconds(_playerItem.currentTime)],
681
+ @"canPlayReverse": [NSNumber numberWithBool:_playerItem.canPlayReverse],
682
+ @"canPlayFastForward": [NSNumber numberWithBool:_playerItem.canPlayFastForward],
683
+ @"canPlaySlowForward": [NSNumber numberWithBool:_playerItem.canPlaySlowForward],
684
+ @"canPlaySlowReverse": [NSNumber numberWithBool:_playerItem.canPlaySlowReverse],
685
+ @"canStepBackward": [NSNumber numberWithBool:_playerItem.canStepBackward],
686
+ @"canStepForward": [NSNumber numberWithBool:_playerItem.canStepForward],
687
+ @"naturalSize": @{
688
+ @"width": width,
689
+ @"height": height,
690
+ @"orientation": orientation
691
+ },
692
+ @"audioTracks": [self getAudioTrackInfo],
693
+ @"textTracks": [self getTextTrackInfo],
694
+ @"target": self.reactTag});
695
+ }
696
+ _videoLoadStarted = NO;
697
+
698
+ [self attachListeners];
699
+ [self applyModifiers];
700
+ } else if (_playerItem.status == AVPlayerItemStatusFailed && self.onVideoError) {
701
+ self.onVideoError(@{@"error": @{@"code": [NSNumber numberWithInteger: _playerItem.error.code],
702
+ @"localizedDescription": [_playerItem.error localizedDescription] == nil ? @"" : [_playerItem.error localizedDescription],
703
+ @"localizedFailureReason": [_playerItem.error localizedFailureReason] == nil ? @"" : [_playerItem.error localizedFailureReason],
704
+ @"localizedRecoverySuggestion": [_playerItem.error localizedRecoverySuggestion] == nil ? @"" : [_playerItem.error localizedRecoverySuggestion],
705
+ @"domain": _playerItem != nil && _playerItem.error != nil ? _playerItem.error.domain : @"RTCVideo"},
706
+ @"target": self.reactTag});
707
+ }
708
+ } else if ([keyPath isEqualToString:playbackBufferEmptyKeyPath]) {
709
+ _playerBufferEmpty = YES;
710
+ self.onVideoBuffer(@{@"isBuffering": @(YES), @"target": self.reactTag});
711
+ } else if ([keyPath isEqualToString:playbackLikelyToKeepUpKeyPath]) {
712
+ // Continue playing (or not if paused) after being paused due to hitting an unbuffered zone.
713
+ if ((!(_controls || _fullscreenPlayerPresented) || _playerBufferEmpty) && _playerItem.playbackLikelyToKeepUp) {
714
+ [self setPaused:_paused];
715
+ }
716
+ _playerBufferEmpty = NO;
717
+ self.onVideoBuffer(@{@"isBuffering": @(NO), @"target": self.reactTag});
718
+ }
719
+ } else if (object == _player) {
720
+ if([keyPath isEqualToString:playbackRate]) {
721
+ if (_player.rate > 0 && _rate > 0 && _player.rate != _rate) {
722
+ // Playback is resuming, apply rate modifer.
723
+ [_player setRate:_rate];
724
+ } else if(self.onPlaybackRateChange) {
725
+ self.onPlaybackRateChange(@{@"playbackRate": [NSNumber numberWithFloat:_player.rate],
726
+ @"target": self.reactTag});
727
+ }
728
+ if(_playbackStalled && _player.rate > 0) {
729
+ if(self.onPlaybackResume) {
730
+ self.onPlaybackResume(@{@"playbackRate": [NSNumber numberWithFloat:_player.rate],
731
+ @"target": self.reactTag});
732
+ }
733
+ _playbackStalled = NO;
734
+ }
735
+ }
736
+ else if([keyPath isEqualToString:externalPlaybackActive]) {
737
+ if(self.onVideoExternalPlaybackChange) {
738
+ self.onVideoExternalPlaybackChange(@{@"isExternalPlaybackActive": [NSNumber numberWithBool:_player.isExternalPlaybackActive],
739
+ @"target": self.reactTag});
740
+ }
741
+ }
742
+ } else if (object == _playerViewController.contentOverlayView) {
743
+ // when controls==true, this is a hack to reset the rootview when rotation happens in fullscreen
744
+ if ([keyPath isEqualToString:@"frame"]) {
745
+
746
+ CGRect oldRect = [change[NSKeyValueChangeOldKey] CGRectValue];
747
+ CGRect newRect = [change[NSKeyValueChangeNewKey] CGRectValue];
748
+
749
+ if (!CGRectEqualToRect(oldRect, newRect)) {
750
+ if (CGRectEqualToRect(newRect, [UIScreen mainScreen].bounds)) {
751
+ NSLog(@"in fullscreen");
752
+
753
+ [self.reactViewController.view setFrame:[UIScreen mainScreen].bounds];
754
+ [self.reactViewController.view setNeedsLayout];
755
+ } else NSLog(@"not fullscreen");
756
+ }
757
+
758
+ return;
759
+ }
760
+ }
761
+ }
762
+
763
+ - (void)attachListeners
764
+ {
765
+ // listen for end of file
766
+ [[NSNotificationCenter defaultCenter] removeObserver:self
767
+ name:AVPlayerItemDidPlayToEndTimeNotification
768
+ object:[_player currentItem]];
769
+ [[NSNotificationCenter defaultCenter] addObserver:self
770
+ selector:@selector(playerItemDidReachEnd:)
771
+ name:AVPlayerItemDidPlayToEndTimeNotification
772
+ object:[_player currentItem]];
773
+
774
+ [[NSNotificationCenter defaultCenter] removeObserver:self
775
+ name:AVPlayerItemPlaybackStalledNotification
776
+ object:nil];
777
+ [[NSNotificationCenter defaultCenter] addObserver:self
778
+ selector:@selector(playbackStalled:)
779
+ name:AVPlayerItemPlaybackStalledNotification
780
+ object:nil];
781
+
782
+ [[NSNotificationCenter defaultCenter] removeObserver:self
783
+ name:AVPlayerItemNewAccessLogEntryNotification
784
+ object:nil];
785
+ [[NSNotificationCenter defaultCenter] addObserver:self
786
+ selector:@selector(handleAVPlayerAccess:)
787
+ name:AVPlayerItemNewAccessLogEntryNotification
788
+ object:nil];
789
+ [[NSNotificationCenter defaultCenter] removeObserver:self
790
+ name: AVPlayerItemFailedToPlayToEndTimeNotification
791
+ object:nil];
792
+ [[NSNotificationCenter defaultCenter] addObserver:self
793
+ selector:@selector(didFailToFinishPlaying:)
794
+ name: AVPlayerItemFailedToPlayToEndTimeNotification
795
+ object:nil];
796
+
797
+ }
798
+
799
+ - (void)handleAVPlayerAccess:(NSNotification *)notification {
800
+ AVPlayerItemAccessLog *accessLog = [((AVPlayerItem *)notification.object) accessLog];
801
+ AVPlayerItemAccessLogEvent *lastEvent = accessLog.events.lastObject;
802
+
803
+ /* TODO: get this working
804
+ if (self.onBandwidthUpdate) {
805
+ self.onBandwidthUpdate(@{@"bitrate": [NSNumber numberWithFloat:lastEvent.observedBitrate]});
806
+ }
807
+ */
808
+ }
809
+
810
+ - (void)didFailToFinishPlaying:(NSNotification *)notification {
811
+ NSError *error = notification.userInfo[AVPlayerItemFailedToPlayToEndTimeErrorKey];
812
+ self.onVideoError(@{@"error": @{@"code": [NSNumber numberWithInteger: error.code],
813
+ @"localizedDescription": [error localizedDescription] == nil ? @"" : [error localizedDescription],
814
+ @"localizedFailureReason": [error localizedFailureReason] == nil ? @"" : [error localizedFailureReason],
815
+ @"localizedRecoverySuggestion": [error localizedRecoverySuggestion] == nil ? @"" : [error localizedRecoverySuggestion],
816
+ @"domain": error.domain},
817
+ @"target": self.reactTag});
818
+ }
819
+
820
+ - (void)playbackStalled:(NSNotification *)notification
821
+ {
822
+ if(self.onPlaybackStalled) {
823
+ self.onPlaybackStalled(@{@"target": self.reactTag});
824
+ }
825
+ _playbackStalled = YES;
826
+ }
827
+
828
+ - (void)playerItemDidReachEnd:(NSNotification *)notification
829
+ {
830
+ if(self.onVideoEnd) {
831
+ self.onVideoEnd(@{@"target": self.reactTag});
832
+ }
833
+
834
+ if (_repeat) {
835
+ AVPlayerItem *item = [notification object];
836
+ [item seekToTime:kCMTimeZero];
837
+ [self applyModifiers];
838
+ } else {
839
+ [self removePlayerTimeObserver];
840
+ }
841
+ }
842
+
843
+ #pragma mark - Prop setters
844
+
845
+ - (void)setResizeMode:(NSString*)mode
846
+ {
847
+ if( _controls )
848
+ {
849
+ _playerViewController.videoGravity = mode;
850
+ }
851
+ else
852
+ {
853
+ _playerLayer.videoGravity = mode;
854
+ }
855
+ _resizeMode = mode;
856
+ }
857
+
858
+ - (void)setPlayInBackground:(BOOL)playInBackground
859
+ {
860
+ _playInBackground = playInBackground;
861
+ }
862
+
863
+ - (void)setPreventsDisplaySleepDuringVideoPlayback:(BOOL)preventsDisplaySleepDuringVideoPlayback
864
+ {
865
+ _preventsDisplaySleepDuringVideoPlayback = preventsDisplaySleepDuringVideoPlayback;
866
+ [self applyModifiers];
867
+ }
868
+
869
+ - (void)setAllowsExternalPlayback:(BOOL)allowsExternalPlayback
870
+ {
871
+ _allowsExternalPlayback = allowsExternalPlayback;
872
+ _player.allowsExternalPlayback = _allowsExternalPlayback;
873
+ }
874
+
875
+ - (void)setPlayWhenInactive:(BOOL)playWhenInactive
876
+ {
877
+ _playWhenInactive = playWhenInactive;
878
+ }
879
+
880
+ - (void)setPictureInPicture:(BOOL)pictureInPicture
881
+ {
882
+ #if TARGET_OS_IOS
883
+ if (_pictureInPicture == pictureInPicture) {
884
+ return;
885
+ }
886
+
887
+ _pictureInPicture = pictureInPicture;
888
+ if (_pipController && _pictureInPicture && ![_pipController isPictureInPictureActive]) {
889
+ dispatch_async(dispatch_get_main_queue(), ^{
890
+ [_pipController startPictureInPicture];
891
+ });
892
+ } else if (_pipController && !_pictureInPicture && [_pipController isPictureInPictureActive]) {
893
+ dispatch_async(dispatch_get_main_queue(), ^{
894
+ [_pipController stopPictureInPicture];
895
+ });
896
+ }
897
+ #endif
898
+ }
899
+
900
+ #if TARGET_OS_IOS
901
+ - (void)setRestoreUserInterfaceForPIPStopCompletionHandler:(BOOL)restore
902
+ {
903
+ if (_restoreUserInterfaceForPIPStopCompletionHandler != NULL) {
904
+ _restoreUserInterfaceForPIPStopCompletionHandler(restore);
905
+ _restoreUserInterfaceForPIPStopCompletionHandler = NULL;
906
+ }
907
+ }
908
+
909
+ - (void)setupPipController {
910
+ if (!_pipController && _playerLayer && [AVPictureInPictureController isPictureInPictureSupported]) {
911
+ // Create new controller passing reference to the AVPlayerLayer
912
+ _pipController = [[AVPictureInPictureController alloc] initWithPlayerLayer:_playerLayer];
913
+ _pipController.delegate = self;
914
+ }
915
+ }
916
+ #endif
917
+
918
+ - (void)setIgnoreSilentSwitch:(NSString *)ignoreSilentSwitch
919
+ {
920
+ _ignoreSilentSwitch = ignoreSilentSwitch;
921
+ [self configureAudio];
922
+ [self applyModifiers];
923
+ }
924
+
925
+ - (void)setMixWithOthers:(NSString *)mixWithOthers
926
+ {
927
+ _mixWithOthers = mixWithOthers;
928
+ [self applyModifiers];
929
+ }
930
+
931
+ - (void)setPaused:(BOOL)paused
932
+ {
933
+ if (paused) {
934
+ [_player pause];
935
+ [_player setRate:0.0];
936
+ } else {
937
+
938
+ [self configureAudio];
939
+
940
+ if (@available(iOS 10.0, *) && !_automaticallyWaitsToMinimizeStalling) {
941
+ [_player playImmediatelyAtRate:_rate];
942
+ } else {
943
+ [_player play];
944
+ [_player setRate:_rate];
945
+ }
946
+ [_player setRate:_rate];
947
+ }
948
+
949
+ _paused = paused;
950
+ }
951
+
952
+ - (float)getCurrentTime
953
+ {
954
+ return _playerItem != NULL ? CMTimeGetSeconds(_playerItem.currentTime) : 0;
955
+ }
956
+
957
+ - (void)setCurrentTime:(float)currentTime
958
+ {
959
+ NSDictionary *info = @{
960
+ @"time": [NSNumber numberWithFloat:currentTime],
961
+ @"tolerance": [NSNumber numberWithInt:100]
962
+ };
963
+ [self setSeek:info];
964
+ }
965
+
966
+ - (void)setSeek:(NSDictionary *)info
967
+ {
968
+ NSNumber *seekTime = info[@"time"];
969
+ NSNumber *seekTolerance = info[@"tolerance"];
970
+
971
+ int timeScale = 1000;
972
+
973
+ AVPlayerItem *item = _player.currentItem;
974
+ if (item && item.status == AVPlayerItemStatusReadyToPlay) {
975
+ // TODO check loadedTimeRanges
976
+
977
+ CMTime cmSeekTime = CMTimeMakeWithSeconds([seekTime floatValue], timeScale);
978
+ CMTime current = item.currentTime;
979
+ // TODO figure out a good tolerance level
980
+ CMTime tolerance = CMTimeMake([seekTolerance floatValue], timeScale);
981
+ BOOL wasPaused = _paused;
982
+
983
+ if (CMTimeCompare(current, cmSeekTime) != 0) {
984
+ if (!wasPaused) [_player pause];
985
+ [_player seekToTime:cmSeekTime toleranceBefore:tolerance toleranceAfter:tolerance completionHandler:^(BOOL finished) {
986
+ if (!_timeObserver) {
987
+ [self addPlayerTimeObserver];
988
+ }
989
+ if (!wasPaused) {
990
+ [self setPaused:false];
991
+ }
992
+ if(self.onVideoSeek) {
993
+ self.onVideoSeek(@{@"currentTime": [NSNumber numberWithFloat:CMTimeGetSeconds(item.currentTime)],
994
+ @"seekTime": seekTime,
995
+ @"target": self.reactTag});
996
+ }
997
+ }];
998
+
999
+ _pendingSeek = false;
1000
+ }
1001
+
1002
+ } else {
1003
+ _pendingSeek = true;
1004
+ _pendingSeekTime = [seekTime floatValue];
1005
+ }
1006
+ }
1007
+
1008
+ - (void)setRate:(float)rate
1009
+ {
1010
+ _rate = rate;
1011
+ [self applyModifiers];
1012
+ }
1013
+
1014
+ - (void)setMuted:(BOOL)muted
1015
+ {
1016
+ _muted = muted;
1017
+ [self applyModifiers];
1018
+ }
1019
+
1020
+ - (void)setVolume:(float)volume
1021
+ {
1022
+ _volume = volume;
1023
+ [self applyModifiers];
1024
+ }
1025
+
1026
+ - (void)setMaxBitRate:(float) maxBitRate {
1027
+ _maxBitRate = maxBitRate;
1028
+ _playerItem.preferredPeakBitRate = maxBitRate;
1029
+ }
1030
+
1031
+ - (void)setPreferredForwardBufferDuration:(float) preferredForwardBufferDuration
1032
+ {
1033
+ _preferredForwardBufferDuration = preferredForwardBufferDuration;
1034
+ _playerItem.preferredForwardBufferDuration = preferredForwardBufferDuration;
1035
+ }
1036
+
1037
+ - (void)setAutomaticallyWaitsToMinimizeStalling:(BOOL)waits
1038
+ {
1039
+ _automaticallyWaitsToMinimizeStalling = waits;
1040
+ _player.automaticallyWaitsToMinimizeStalling = waits;
1041
+ }
1042
+
1043
+
1044
+ - (void)applyModifiers
1045
+ {
1046
+ if (_muted) {
1047
+ if (!_controls) {
1048
+ [_player setVolume:0];
1049
+ }
1050
+ [_player setMuted:YES];
1051
+ } else {
1052
+ [_player setVolume:_volume];
1053
+ [_player setMuted:NO];
1054
+ }
1055
+
1056
+ if (@available(iOS 12.0, *)) {
1057
+ self->_player.preventsDisplaySleepDuringVideoPlayback = _preventsDisplaySleepDuringVideoPlayback;
1058
+ } else {
1059
+ // Fallback on earlier versions
1060
+ }
1061
+
1062
+ [self setMaxBitRate:_maxBitRate];
1063
+ [self setSelectedAudioTrack:_selectedAudioTrack];
1064
+ [self setSelectedTextTrack:_selectedTextTrack];
1065
+ [self setResizeMode:_resizeMode];
1066
+ [self setRepeat:_repeat];
1067
+ [self setPaused:_paused];
1068
+ [self setControls:_controls];
1069
+ [self setAllowsExternalPlayback:_allowsExternalPlayback];
1070
+ }
1071
+
1072
+ - (void)configureAudio
1073
+ {
1074
+ AVAudioSession *session = [AVAudioSession sharedInstance];
1075
+ AVAudioSessionCategory category = nil;
1076
+ AVAudioSessionCategoryOptions options = nil;
1077
+
1078
+ if([_ignoreSilentSwitch isEqualToString:@"ignore"]) {
1079
+ category = AVAudioSessionCategoryPlayback;
1080
+ } else if([_ignoreSilentSwitch isEqualToString:@"obey"]) {
1081
+ category = AVAudioSessionCategoryAmbient;
1082
+ }
1083
+
1084
+ if([_mixWithOthers isEqualToString:@"mix"]) {
1085
+ options = AVAudioSessionCategoryOptionMixWithOthers;
1086
+ } else if([_mixWithOthers isEqualToString:@"duck"]) {
1087
+ options = AVAudioSessionCategoryOptionDuckOthers;
1088
+ }
1089
+
1090
+ if (category != nil && options != nil) {
1091
+ [session setCategory:category withOptions:options error:nil];
1092
+ } else if (category != nil && options == nil) {
1093
+ [session setCategory:category error:nil];
1094
+ } else if (category == nil && options != nil) {
1095
+ [session setCategory:session.category withOptions:options error:nil];
1096
+ }
1097
+ }
1098
+
1099
+ - (void)setRepeat:(BOOL)repeat {
1100
+ _repeat = repeat;
1101
+ }
1102
+
1103
+ - (void)setMediaSelectionTrackForCharacteristic:(AVMediaCharacteristic)characteristic
1104
+ withCriteria:(NSDictionary *)criteria
1105
+ {
1106
+ NSString *type = criteria[@"type"];
1107
+ AVMediaSelectionGroup *group = [_player.currentItem.asset
1108
+ mediaSelectionGroupForMediaCharacteristic:characteristic];
1109
+ AVMediaSelectionOption *mediaOption;
1110
+
1111
+ if ([type isEqualToString:@"disabled"]) {
1112
+ // Do nothing. We want to ensure option is nil
1113
+ } else if ([type isEqualToString:@"language"] || [type isEqualToString:@"title"]) {
1114
+ NSString *value = criteria[@"value"];
1115
+ for (int i = 0; i < group.options.count; ++i) {
1116
+ AVMediaSelectionOption *currentOption = [group.options objectAtIndex:i];
1117
+ NSString *optionValue;
1118
+ if ([type isEqualToString:@"language"]) {
1119
+ optionValue = [currentOption extendedLanguageTag];
1120
+ } else {
1121
+ optionValue = [[[currentOption commonMetadata]
1122
+ valueForKey:@"value"]
1123
+ objectAtIndex:0];
1124
+ }
1125
+ if ([value isEqualToString:optionValue]) {
1126
+ mediaOption = currentOption;
1127
+ break;
1128
+ }
1129
+ }
1130
+ //} else if ([type isEqualToString:@"default"]) {
1131
+ // option = group.defaultOption; */
1132
+ } else if ([type isEqualToString:@"index"]) {
1133
+ if ([criteria[@"value"] isKindOfClass:[NSNumber class]]) {
1134
+ int index = [criteria[@"value"] intValue];
1135
+ if (group.options.count > index) {
1136
+ mediaOption = [group.options objectAtIndex:index];
1137
+ }
1138
+ }
1139
+ } else { // default. invalid type or "system"
1140
+ #if TARGET_OS_TV
1141
+ // Do noting. Fix for tvOS native audio menu language selector
1142
+ #else
1143
+ [_player.currentItem selectMediaOptionAutomaticallyInMediaSelectionGroup:group];
1144
+ return;
1145
+ #endif
1146
+ }
1147
+
1148
+ #if TARGET_OS_TV
1149
+ // Do noting. Fix for tvOS native audio menu language selector
1150
+ #else
1151
+ // If a match isn't found, option will be nil and text tracks will be disabled
1152
+ [_player.currentItem selectMediaOption:mediaOption inMediaSelectionGroup:group];
1153
+ #endif
1154
+ }
1155
+
1156
+ - (void)setSelectedAudioTrack:(NSDictionary *)selectedAudioTrack {
1157
+ _selectedAudioTrack = selectedAudioTrack;
1158
+ [self setMediaSelectionTrackForCharacteristic:AVMediaCharacteristicAudible
1159
+ withCriteria:_selectedAudioTrack];
1160
+ }
1161
+
1162
+ - (void)setSelectedTextTrack:(NSDictionary *)selectedTextTrack {
1163
+ _selectedTextTrack = selectedTextTrack;
1164
+ if (_textTracks) { // sideloaded text tracks
1165
+ [self setSideloadedText];
1166
+ } else { // text tracks included in the HLS playlist
1167
+ [self setMediaSelectionTrackForCharacteristic:AVMediaCharacteristicLegible
1168
+ withCriteria:_selectedTextTrack];
1169
+ }
1170
+ }
1171
+
1172
+ - (void) setSideloadedText {
1173
+ NSString *type = _selectedTextTrack[@"type"];
1174
+ NSArray *textTracks = [self getTextTrackInfo];
1175
+
1176
+ // The first few tracks will be audio & video track
1177
+ int firstTextIndex = 0;
1178
+ for (firstTextIndex = 0; firstTextIndex < _player.currentItem.tracks.count; ++firstTextIndex) {
1179
+ if ([_player.currentItem.tracks[firstTextIndex].assetTrack hasMediaCharacteristic:AVMediaCharacteristicLegible]) {
1180
+ break;
1181
+ }
1182
+ }
1183
+
1184
+ int selectedTrackIndex = RCTVideoUnset;
1185
+
1186
+ if ([type isEqualToString:@"disabled"]) {
1187
+ // Do nothing. We want to ensure option is nil
1188
+ } else if ([type isEqualToString:@"language"]) {
1189
+ NSString *selectedValue = _selectedTextTrack[@"value"];
1190
+ for (int i = 0; i < textTracks.count; ++i) {
1191
+ NSDictionary *currentTextTrack = [textTracks objectAtIndex:i];
1192
+ if ([selectedValue isEqualToString:currentTextTrack[@"language"]]) {
1193
+ selectedTrackIndex = i;
1194
+ break;
1195
+ }
1196
+ }
1197
+ } else if ([type isEqualToString:@"title"]) {
1198
+ NSString *selectedValue = _selectedTextTrack[@"value"];
1199
+ for (int i = 0; i < textTracks.count; ++i) {
1200
+ NSDictionary *currentTextTrack = [textTracks objectAtIndex:i];
1201
+ if ([selectedValue isEqualToString:currentTextTrack[@"title"]]) {
1202
+ selectedTrackIndex = i;
1203
+ break;
1204
+ }
1205
+ }
1206
+ } else if ([type isEqualToString:@"index"]) {
1207
+ if ([_selectedTextTrack[@"value"] isKindOfClass:[NSNumber class]]) {
1208
+ int index = [_selectedTextTrack[@"value"] intValue];
1209
+ if (textTracks.count > index) {
1210
+ selectedTrackIndex = index;
1211
+ }
1212
+ }
1213
+ }
1214
+
1215
+ // in the situation that a selected text track is not available (eg. specifies a textTrack not available)
1216
+ if (![type isEqualToString:@"disabled"] && selectedTrackIndex == RCTVideoUnset) {
1217
+ CFArrayRef captioningMediaCharacteristics = MACaptionAppearanceCopyPreferredCaptioningMediaCharacteristics(kMACaptionAppearanceDomainUser);
1218
+ NSArray *captionSettings = (__bridge NSArray*)captioningMediaCharacteristics;
1219
+ if ([captionSettings containsObject:AVMediaCharacteristicTranscribesSpokenDialogForAccessibility]) {
1220
+ selectedTrackIndex = 0; // If we can't find a match, use the first available track
1221
+ NSString *systemLanguage = [[NSLocale preferredLanguages] firstObject];
1222
+ for (int i = 0; i < textTracks.count; ++i) {
1223
+ NSDictionary *currentTextTrack = [textTracks objectAtIndex:i];
1224
+ if ([systemLanguage isEqualToString:currentTextTrack[@"language"]]) {
1225
+ selectedTrackIndex = i;
1226
+ break;
1227
+ }
1228
+ }
1229
+ }
1230
+ }
1231
+
1232
+ for (int i = firstTextIndex; i < _player.currentItem.tracks.count; ++i) {
1233
+ BOOL isEnabled = NO;
1234
+ if (selectedTrackIndex != RCTVideoUnset) {
1235
+ isEnabled = i == selectedTrackIndex + firstTextIndex;
1236
+ }
1237
+ [_player.currentItem.tracks[i] setEnabled:isEnabled];
1238
+ }
1239
+ }
1240
+
1241
+ -(void) setStreamingText {
1242
+ NSString *type = _selectedTextTrack[@"type"];
1243
+ AVMediaSelectionGroup *group = [_player.currentItem.asset
1244
+ mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicLegible];
1245
+ AVMediaSelectionOption *mediaOption;
1246
+
1247
+ if ([type isEqualToString:@"disabled"]) {
1248
+ // Do nothing. We want to ensure option is nil
1249
+ } else if ([type isEqualToString:@"language"] || [type isEqualToString:@"title"]) {
1250
+ NSString *value = _selectedTextTrack[@"value"];
1251
+ for (int i = 0; i < group.options.count; ++i) {
1252
+ AVMediaSelectionOption *currentOption = [group.options objectAtIndex:i];
1253
+ NSString *optionValue;
1254
+ if ([type isEqualToString:@"language"]) {
1255
+ optionValue = [currentOption extendedLanguageTag];
1256
+ } else {
1257
+ optionValue = [[[currentOption commonMetadata]
1258
+ valueForKey:@"value"]
1259
+ objectAtIndex:0];
1260
+ }
1261
+ if ([value isEqualToString:optionValue]) {
1262
+ mediaOption = currentOption;
1263
+ break;
1264
+ }
1265
+ }
1266
+ //} else if ([type isEqualToString:@"default"]) {
1267
+ // option = group.defaultOption; */
1268
+ } else if ([type isEqualToString:@"index"]) {
1269
+ if ([_selectedTextTrack[@"value"] isKindOfClass:[NSNumber class]]) {
1270
+ int index = [_selectedTextTrack[@"value"] intValue];
1271
+ if (group.options.count > index) {
1272
+ mediaOption = [group.options objectAtIndex:index];
1273
+ }
1274
+ }
1275
+ } else { // default. invalid type or "system"
1276
+ [_player.currentItem selectMediaOptionAutomaticallyInMediaSelectionGroup:group];
1277
+ return;
1278
+ }
1279
+
1280
+ // If a match isn't found, option will be nil and text tracks will be disabled
1281
+ [_player.currentItem selectMediaOption:mediaOption inMediaSelectionGroup:group];
1282
+ }
1283
+
1284
+ - (void)setTextTracks:(NSArray*) textTracks;
1285
+ {
1286
+ _textTracks = textTracks;
1287
+
1288
+ // in case textTracks was set after selectedTextTrack
1289
+ if (_selectedTextTrack) [self setSelectedTextTrack:_selectedTextTrack];
1290
+ }
1291
+
1292
+ - (NSArray *)getAudioTrackInfo
1293
+ {
1294
+ NSMutableArray *audioTracks = [[NSMutableArray alloc] init];
1295
+ AVMediaSelectionGroup *group = [_player.currentItem.asset
1296
+ mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicAudible];
1297
+ for (int i = 0; i < group.options.count; ++i) {
1298
+ AVMediaSelectionOption *currentOption = [group.options objectAtIndex:i];
1299
+ NSString *title = @"";
1300
+ NSArray *values = [[currentOption commonMetadata] valueForKey:@"value"];
1301
+ if (values.count > 0) {
1302
+ title = [values objectAtIndex:0];
1303
+ }
1304
+ NSString *language = [currentOption extendedLanguageTag] ? [currentOption extendedLanguageTag] : @"";
1305
+ NSDictionary *audioTrack = @{
1306
+ @"index": [NSNumber numberWithInt:i],
1307
+ @"title": title,
1308
+ @"language": language
1309
+ };
1310
+ [audioTracks addObject:audioTrack];
1311
+ }
1312
+ return audioTracks;
1313
+ }
1314
+
1315
+ - (NSArray *)getTextTrackInfo
1316
+ {
1317
+ // if sideloaded, textTracks will already be set
1318
+ if (_textTracks) return _textTracks;
1319
+
1320
+ // if streaming video, we extract the text tracks
1321
+ NSMutableArray *textTracks = [[NSMutableArray alloc] init];
1322
+ AVMediaSelectionGroup *group = [_player.currentItem.asset
1323
+ mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicLegible];
1324
+ for (int i = 0; i < group.options.count; ++i) {
1325
+ AVMediaSelectionOption *currentOption = [group.options objectAtIndex:i];
1326
+ NSString *title = @"";
1327
+ NSArray *values = [[currentOption commonMetadata] valueForKey:@"value"];
1328
+ if (values.count > 0) {
1329
+ title = [values objectAtIndex:0];
1330
+ }
1331
+ NSString *language = [currentOption extendedLanguageTag] ? [currentOption extendedLanguageTag] : @"";
1332
+ NSDictionary *textTrack = @{
1333
+ @"index": [NSNumber numberWithInt:i],
1334
+ @"title": title,
1335
+ @"language": language
1336
+ };
1337
+ [textTracks addObject:textTrack];
1338
+ }
1339
+ return textTracks;
1340
+ }
1341
+
1342
+ - (BOOL)getFullscreen
1343
+ {
1344
+ return _fullscreenPlayerPresented;
1345
+ }
1346
+
1347
+ - (void)setFullscreen:(BOOL) fullscreen {
1348
+ if( fullscreen && !_fullscreenPlayerPresented && _player )
1349
+ {
1350
+ // Ensure player view controller is not null
1351
+ if( !_playerViewController )
1352
+ {
1353
+ [self usePlayerViewController];
1354
+ }
1355
+ // Set presentation style to fullscreen
1356
+ [_playerViewController setModalPresentationStyle:UIModalPresentationFullScreen];
1357
+
1358
+ // Find the nearest view controller
1359
+ UIViewController *viewController = [self firstAvailableUIViewController];
1360
+ if( !viewController )
1361
+ {
1362
+ UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
1363
+ viewController = keyWindow.rootViewController;
1364
+ if( viewController.childViewControllers.count > 0 )
1365
+ {
1366
+ viewController = viewController.childViewControllers.lastObject;
1367
+ }
1368
+ }
1369
+ if( viewController )
1370
+ {
1371
+ _presentingViewController = viewController;
1372
+ if(self.onVideoFullscreenPlayerWillPresent) {
1373
+ self.onVideoFullscreenPlayerWillPresent(@{@"target": self.reactTag});
1374
+ }
1375
+ [viewController presentViewController:_playerViewController animated:true completion:^{
1376
+ _playerViewController.showsPlaybackControls = YES;
1377
+ _fullscreenPlayerPresented = fullscreen;
1378
+ _playerViewController.autorotate = _fullscreenAutorotate;
1379
+ if(self.onVideoFullscreenPlayerDidPresent) {
1380
+ self.onVideoFullscreenPlayerDidPresent(@{@"target": self.reactTag});
1381
+ }
1382
+ }];
1383
+ }
1384
+ }
1385
+ else if ( !fullscreen && _fullscreenPlayerPresented )
1386
+ {
1387
+ [self videoPlayerViewControllerWillDismiss:_playerViewController];
1388
+ [_presentingViewController dismissViewControllerAnimated:true completion:^{
1389
+ [self videoPlayerViewControllerDidDismiss:_playerViewController];
1390
+ }];
1391
+ }
1392
+ }
1393
+
1394
+ - (void)setFullscreenAutorotate:(BOOL)autorotate {
1395
+ _fullscreenAutorotate = autorotate;
1396
+ if (_fullscreenPlayerPresented) {
1397
+ _playerViewController.autorotate = autorotate;
1398
+ }
1399
+ }
1400
+
1401
+ - (void)setFullscreenOrientation:(NSString *)orientation {
1402
+ _fullscreenOrientation = orientation;
1403
+ if (_fullscreenPlayerPresented) {
1404
+ _playerViewController.preferredOrientation = orientation;
1405
+ }
1406
+ }
1407
+
1408
+ - (void)usePlayerViewController
1409
+ {
1410
+ if( _player )
1411
+ {
1412
+ if (!_playerViewController) {
1413
+ _playerViewController = [self createPlayerViewController:_player withPlayerItem:_playerItem];
1414
+ }
1415
+ // to prevent video from being animated when resizeMode is 'cover'
1416
+ // resize mode must be set before subview is added
1417
+ [self setResizeMode:_resizeMode];
1418
+
1419
+ if (_controls) {
1420
+ UIViewController *viewController = [self reactViewController];
1421
+ [viewController addChildViewController:_playerViewController];
1422
+ [self addSubview:_playerViewController.view];
1423
+ }
1424
+
1425
+ [_playerViewController addObserver:self forKeyPath:readyForDisplayKeyPath options:NSKeyValueObservingOptionNew context:nil];
1426
+
1427
+ [_playerViewController.contentOverlayView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];
1428
+ }
1429
+ }
1430
+
1431
+ - (void)usePlayerLayer
1432
+ {
1433
+ if( _player )
1434
+ {
1435
+ _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
1436
+ _playerLayer.frame = self.bounds;
1437
+ _playerLayer.needsDisplayOnBoundsChange = YES;
1438
+
1439
+ // to prevent video from being animated when resizeMode is 'cover'
1440
+ // resize mode must be set before layer is added
1441
+ [self setResizeMode:_resizeMode];
1442
+ [_playerLayer addObserver:self forKeyPath:readyForDisplayKeyPath options:NSKeyValueObservingOptionNew context:nil];
1443
+ _playerLayerObserverSet = YES;
1444
+
1445
+ [self.layer addSublayer:_playerLayer];
1446
+ self.layer.needsDisplayOnBoundsChange = YES;
1447
+ #if TARGET_OS_IOS
1448
+ [self setupPipController];
1449
+ #endif
1450
+ }
1451
+ }
1452
+
1453
+ - (void)setControls:(BOOL)controls
1454
+ {
1455
+ if( _controls != controls || (!_playerLayer && !_playerViewController) )
1456
+ {
1457
+ _controls = controls;
1458
+ if( _controls )
1459
+ {
1460
+ [self removePlayerLayer];
1461
+ [self usePlayerViewController];
1462
+ }
1463
+ else
1464
+ {
1465
+ [_playerViewController.view removeFromSuperview];
1466
+ _playerViewController = nil;
1467
+ [self usePlayerLayer];
1468
+ }
1469
+ }
1470
+ }
1471
+
1472
+ - (void)setProgressUpdateInterval:(float)progressUpdateInterval
1473
+ {
1474
+ _progressUpdateInterval = progressUpdateInterval;
1475
+
1476
+ if (_timeObserver) {
1477
+ [self removePlayerTimeObserver];
1478
+ [self addPlayerTimeObserver];
1479
+ }
1480
+ }
1481
+
1482
+ - (void)removePlayerLayer
1483
+ {
1484
+ if (_loadingRequest != nil) {
1485
+ [_loadingRequest finishLoading];
1486
+ }
1487
+ _requestingCertificate = NO;
1488
+ _requestingCertificateErrored = NO;
1489
+ [_playerLayer removeFromSuperlayer];
1490
+ if (_playerLayerObserverSet) {
1491
+ [_playerLayer removeObserver:self forKeyPath:readyForDisplayKeyPath];
1492
+ _playerLayerObserverSet = NO;
1493
+ }
1494
+ _playerLayer = nil;
1495
+ }
1496
+
1497
+ #pragma mark - RCTVideoPlayerViewControllerDelegate
1498
+
1499
+ - (void)videoPlayerViewControllerWillDismiss:(AVPlayerViewController *)playerViewController
1500
+ {
1501
+ if (_playerViewController == playerViewController && _fullscreenPlayerPresented && self.onVideoFullscreenPlayerWillDismiss)
1502
+ {
1503
+ @try{
1504
+ [_playerViewController.contentOverlayView removeObserver:self forKeyPath:@"frame"];
1505
+ [_playerViewController removeObserver:self forKeyPath:readyForDisplayKeyPath];
1506
+ }@catch(id anException){
1507
+ }
1508
+ self.onVideoFullscreenPlayerWillDismiss(@{@"target": self.reactTag});
1509
+ }
1510
+ }
1511
+
1512
+ - (void)videoPlayerViewControllerDidDismiss:(AVPlayerViewController *)playerViewController
1513
+ {
1514
+ if (_playerViewController == playerViewController && _fullscreenPlayerPresented)
1515
+ {
1516
+ _fullscreenPlayerPresented = false;
1517
+ _presentingViewController = nil;
1518
+ _playerViewController = nil;
1519
+ [self applyModifiers];
1520
+ if(self.onVideoFullscreenPlayerDidDismiss) {
1521
+ self.onVideoFullscreenPlayerDidDismiss(@{@"target": self.reactTag});
1522
+ }
1523
+ }
1524
+ }
1525
+
1526
+ - (void)setFilter:(NSString *)filterName {
1527
+ _filterName = filterName;
1528
+
1529
+ if (!_filterEnabled) {
1530
+ return;
1531
+ } else if ([[_source objectForKey:@"uri"] rangeOfString:@"m3u8"].location != NSNotFound) {
1532
+ return; // filters don't work for HLS... return
1533
+ } else if (!_playerItem.asset) {
1534
+ return;
1535
+ }
1536
+
1537
+ CIFilter *filter = [CIFilter filterWithName:filterName];
1538
+ _playerItem.videoComposition = [AVVideoComposition
1539
+ videoCompositionWithAsset:_playerItem.asset
1540
+ applyingCIFiltersWithHandler:^(AVAsynchronousCIImageFilteringRequest *_Nonnull request) {
1541
+ if (filter == nil) {
1542
+ [request finishWithImage:request.sourceImage context:nil];
1543
+ } else {
1544
+ CIImage *image = request.sourceImage.imageByClampingToExtent;
1545
+ [filter setValue:image forKey:kCIInputImageKey];
1546
+ CIImage *output = [filter.outputImage imageByCroppingToRect:request.sourceImage.extent];
1547
+ [request finishWithImage:output context:nil];
1548
+ }
1549
+ }];
1550
+ }
1551
+
1552
+ - (void)setFilterEnabled:(BOOL)filterEnabled {
1553
+ _filterEnabled = filterEnabled;
1554
+ }
1555
+
1556
+ #pragma mark - React View Management
1557
+
1558
+ - (void)insertReactSubview:(UIView *)view atIndex:(NSInteger)atIndex
1559
+ {
1560
+ // We are early in the game and somebody wants to set a subview.
1561
+ // That can only be in the context of playerViewController.
1562
+ if( !_controls && !_playerLayer && !_playerViewController )
1563
+ {
1564
+ [self setControls:true];
1565
+ }
1566
+
1567
+ if( _controls )
1568
+ {
1569
+ view.frame = self.bounds;
1570
+ [_playerViewController.contentOverlayView insertSubview:view atIndex:atIndex];
1571
+ }
1572
+ else
1573
+ {
1574
+ RCTLogError(@"video cannot have any subviews");
1575
+ }
1576
+ return;
1577
+ }
1578
+
1579
+ - (void)removeReactSubview:(UIView *)subview
1580
+ {
1581
+ if( _controls )
1582
+ {
1583
+ [subview removeFromSuperview];
1584
+ }
1585
+ else
1586
+ {
1587
+ RCTLogError(@"video cannot have any subviews");
1588
+ }
1589
+ return;
1590
+ }
1591
+
1592
+ - (void)layoutSubviews
1593
+ {
1594
+ [super layoutSubviews];
1595
+ if( _controls )
1596
+ {
1597
+ _playerViewController.view.frame = self.bounds;
1598
+
1599
+ // also adjust all subviews of contentOverlayView
1600
+ for (UIView* subview in _playerViewController.contentOverlayView.subviews) {
1601
+ subview.frame = self.bounds;
1602
+ }
1603
+ }
1604
+ else
1605
+ {
1606
+ [CATransaction begin];
1607
+ [CATransaction setAnimationDuration:0];
1608
+ _playerLayer.frame = self.bounds;
1609
+ [CATransaction commit];
1610
+ }
1611
+ }
1612
+
1613
+ #pragma mark - Lifecycle
1614
+
1615
+ - (void)removeFromSuperview
1616
+ {
1617
+ [_player pause];
1618
+ if (_playbackRateObserverRegistered) {
1619
+ [_player removeObserver:self forKeyPath:playbackRate context:nil];
1620
+ _playbackRateObserverRegistered = NO;
1621
+ }
1622
+ if (_isExternalPlaybackActiveObserverRegistered) {
1623
+ [_player removeObserver:self forKeyPath:externalPlaybackActive context:nil];
1624
+ _isExternalPlaybackActiveObserverRegistered = NO;
1625
+ }
1626
+ _player = nil;
1627
+
1628
+ [self removePlayerLayer];
1629
+
1630
+ [_playerViewController.contentOverlayView removeObserver:self forKeyPath:@"frame"];
1631
+ [_playerViewController removeObserver:self forKeyPath:readyForDisplayKeyPath];
1632
+ [_playerViewController.view removeFromSuperview];
1633
+ _playerViewController.rctDelegate = nil;
1634
+ _playerViewController.player = nil;
1635
+ _playerViewController = nil;
1636
+
1637
+ [self removePlayerTimeObserver];
1638
+ [self removePlayerItemObservers];
1639
+
1640
+ _eventDispatcher = nil;
1641
+ [[NSNotificationCenter defaultCenter] removeObserver:self];
1642
+
1643
+ [super removeFromSuperview];
1644
+ }
1645
+
1646
+ #pragma mark - Export
1647
+
1648
+ - (void)save:(NSDictionary *)options resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
1649
+
1650
+ AVAsset *asset = _playerItem.asset;
1651
+
1652
+ if (asset != nil) {
1653
+
1654
+ AVAssetExportSession *exportSession = [AVAssetExportSession
1655
+ exportSessionWithAsset:asset presetName:AVAssetExportPresetHighestQuality];
1656
+
1657
+ if (exportSession != nil) {
1658
+ NSString *path = nil;
1659
+ NSArray *array = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
1660
+ path = [self generatePathInDirectory:[[self cacheDirectoryPath] stringByAppendingPathComponent:@"Videos"]
1661
+ withExtension:@".mp4"];
1662
+ NSURL *url = [NSURL fileURLWithPath:path];
1663
+ exportSession.outputFileType = AVFileTypeMPEG4;
1664
+ exportSession.outputURL = url;
1665
+ exportSession.videoComposition = _playerItem.videoComposition;
1666
+ exportSession.shouldOptimizeForNetworkUse = true;
1667
+ [exportSession exportAsynchronouslyWithCompletionHandler:^{
1668
+
1669
+ switch ([exportSession status]) {
1670
+ case AVAssetExportSessionStatusFailed:
1671
+ reject(@"ERROR_COULD_NOT_EXPORT_VIDEO", @"Could not export video", exportSession.error);
1672
+ break;
1673
+ case AVAssetExportSessionStatusCancelled:
1674
+ reject(@"ERROR_EXPORT_SESSION_CANCELLED", @"Export session was cancelled", exportSession.error);
1675
+ break;
1676
+ default:
1677
+ resolve(@{@"uri": url.absoluteString});
1678
+ break;
1679
+ }
1680
+
1681
+ }];
1682
+
1683
+ } else {
1684
+
1685
+ reject(@"ERROR_COULD_NOT_CREATE_EXPORT_SESSION", @"Could not create export session", nil);
1686
+
1687
+ }
1688
+
1689
+ } else {
1690
+
1691
+ reject(@"ERROR_ASSET_NIL", @"Asset is nil", nil);
1692
+
1693
+ }
1694
+ }
1695
+
1696
+ - (void)setLicenseResult:(NSString *)license {
1697
+ NSData *respondData = [self base64DataFromBase64String:license];
1698
+ if (_loadingRequest != nil && respondData != nil) {
1699
+ AVAssetResourceLoadingDataRequest *dataRequest = [_loadingRequest dataRequest];
1700
+ [dataRequest respondWithData:respondData];
1701
+ [_loadingRequest finishLoading];
1702
+ } else {
1703
+ [self setLicenseResultError:@"No data from JS license response"];
1704
+ }
1705
+ }
1706
+
1707
+ - (BOOL)setLicenseResultError:(NSString *)error {
1708
+ if (_loadingRequest != nil) {
1709
+ NSError *licenseError = [NSError errorWithDomain: @"RCTVideo"
1710
+ code: RCTVideoErrorFromJSPart
1711
+ userInfo: @{
1712
+ NSLocalizedDescriptionKey: error,
1713
+ NSLocalizedFailureReasonErrorKey: error,
1714
+ NSLocalizedRecoverySuggestionErrorKey: error
1715
+ }
1716
+ ];
1717
+ [self finishLoadingWithError:licenseError];
1718
+ }
1719
+ return NO;
1720
+ }
1721
+
1722
+ - (BOOL)finishLoadingWithError:(NSError *)error {
1723
+ if (_loadingRequest && error != nil) {
1724
+ NSError *licenseError = error;
1725
+ [_loadingRequest finishLoadingWithError:licenseError];
1726
+ if (self.onVideoError) {
1727
+ self.onVideoError(@{@"error": @{@"code": [NSNumber numberWithInteger: error.code],
1728
+ @"localizedDescription": [error localizedDescription] == nil ? @"" : [error localizedDescription],
1729
+ @"localizedFailureReason": [error localizedFailureReason] == nil ? @"" : [error localizedFailureReason],
1730
+ @"localizedRecoverySuggestion": [error localizedRecoverySuggestion] == nil ? @"" : [error localizedRecoverySuggestion],
1731
+ @"domain": _playerItem.error == nil ? @"RCTVideo" : _playerItem.error.domain},
1732
+ @"target": self.reactTag});
1733
+ }
1734
+ }
1735
+ return NO;
1736
+ }
1737
+
1738
+ - (BOOL)ensureDirExistsWithPath:(NSString *)path {
1739
+ BOOL isDir = NO;
1740
+ NSError *error;
1741
+ BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir];
1742
+ if (!(exists && isDir)) {
1743
+ [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
1744
+ if (error) {
1745
+ return NO;
1746
+ }
1747
+ }
1748
+ return YES;
1749
+ }
1750
+
1751
+ - (NSString *)generatePathInDirectory:(NSString *)directory withExtension:(NSString *)extension {
1752
+ NSString *fileName = [[[NSUUID UUID] UUIDString] stringByAppendingString:extension];
1753
+ [self ensureDirExistsWithPath:directory];
1754
+ return [directory stringByAppendingPathComponent:fileName];
1755
+ }
1756
+
1757
+ - (NSString *)cacheDirectoryPath {
1758
+ NSArray *array = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
1759
+ return array[0];
1760
+ }
1761
+
1762
+ #pragma mark - AVAssetResourceLoaderDelegate
1763
+
1764
+ - (BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader shouldWaitForRenewalOfRequestedResource:(AVAssetResourceRenewalRequest *)renewalRequest {
1765
+ return [self loadingRequestHandling:renewalRequest];
1766
+ }
1767
+
1768
+ - (BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader shouldWaitForLoadingOfRequestedResource:(AVAssetResourceLoadingRequest *)loadingRequest {
1769
+ return [self loadingRequestHandling:loadingRequest];
1770
+ }
1771
+
1772
+ - (void)resourceLoader:(AVAssetResourceLoader *)resourceLoader
1773
+ didCancelLoadingRequest:(AVAssetResourceLoadingRequest *)loadingRequest {
1774
+ NSLog(@"didCancelLoadingRequest");
1775
+ }
1776
+
1777
+ - (BOOL)loadingRequestHandling:(AVAssetResourceLoadingRequest *)loadingRequest {
1778
+ if (self->_requestingCertificate) {
1779
+ return YES;
1780
+ } else if (self->_requestingCertificateErrored) {
1781
+ return NO;
1782
+ }
1783
+ _loadingRequest = loadingRequest;
1784
+ NSURL *url = loadingRequest.request.URL;
1785
+ if (self->_drm != nil) {
1786
+ NSString *contentId;
1787
+ NSString *contentIdOverride = (NSString *)[self->_drm objectForKey:@"contentId"];
1788
+ if (contentIdOverride != nil) {
1789
+ contentId = contentIdOverride;
1790
+ } else if (self.onGetLicense) {
1791
+ contentId = url.host;
1792
+ } else {
1793
+ contentId = [url.absoluteString stringByReplacingOccurrencesOfString:@"skd://" withString:@""];
1794
+ }
1795
+ NSString *drmType = (NSString *)[self->_drm objectForKey:@"type"];
1796
+ if ([drmType isEqualToString:@"fairplay"]) {
1797
+ NSString *certificateStringUrl = (NSString *)[self->_drm objectForKey:@"certificateUrl"];
1798
+ if (certificateStringUrl != nil) {
1799
+ NSURL *certificateURL = [NSURL URLWithString:[certificateStringUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1800
+ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
1801
+ NSData *certificateData = [NSData dataWithContentsOfURL:certificateURL];
1802
+ if ([self->_drm objectForKey:@"base64Certificate"]) {
1803
+ certificateData = [[NSData alloc] initWithBase64EncodedData:certificateData options:NSDataBase64DecodingIgnoreUnknownCharacters];
1804
+ }
1805
+
1806
+ if (certificateData != nil) {
1807
+ NSData *contentIdData;
1808
+ if(self.onGetLicense) {
1809
+ contentIdData = [contentId dataUsingEncoding:NSUTF8StringEncoding];
1810
+ } else {
1811
+ contentIdData = [NSData dataWithBytes: [contentId cStringUsingEncoding:NSUTF8StringEncoding] length:[contentId lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
1812
+ }
1813
+ AVAssetResourceLoadingDataRequest *dataRequest = [loadingRequest dataRequest];
1814
+ if (dataRequest != nil) {
1815
+ NSError *spcError = nil;
1816
+ NSData *spcData = [loadingRequest streamingContentKeyRequestDataForApp:certificateData contentIdentifier:contentIdData options:nil error:&spcError];
1817
+ // Request CKC to the server
1818
+ NSString *licenseServer = (NSString *)[self->_drm objectForKey:@"licenseServer"];
1819
+ if (spcError != nil) {
1820
+ [self finishLoadingWithError:spcError];
1821
+ self->_requestingCertificateErrored = YES;
1822
+ }
1823
+ if (spcData != nil) {
1824
+ if(self.onGetLicense) {
1825
+ NSString *base64Encoded = [spcData base64EncodedStringWithOptions:0];
1826
+ self->_requestingCertificate = YES;
1827
+ if (licenseServer == nil) {
1828
+ licenseServer = @"";
1829
+ }
1830
+ self.onGetLicense(@{@"licenseUrl": licenseServer,
1831
+ @"contentId": contentId,
1832
+ @"spcBase64": base64Encoded,
1833
+ @"target": self.reactTag}
1834
+ );
1835
+ } else if(licenseServer != nil) {
1836
+ NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
1837
+ [request setHTTPMethod:@"POST"];
1838
+ [request setURL:[NSURL URLWithString:licenseServer]];
1839
+ // HEADERS
1840
+ NSDictionary *headers = (NSDictionary *)[self->_drm objectForKey:@"headers"];
1841
+ if (headers != nil) {
1842
+ for (NSString *key in headers) {
1843
+ NSString *value = headers[key];
1844
+ [request setValue:value forHTTPHeaderField:key];
1845
+ }
1846
+ }
1847
+
1848
+ if(self.onGetLicense) {
1849
+ [request setHTTPBody: spcData];
1850
+ } else {
1851
+ NSString *spcEncoded = [spcData base64EncodedStringWithOptions:0];
1852
+ NSString *spcUrlEncoded = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)spcEncoded, NULL, CFSTR("?=&+"), kCFStringEncodingUTF8));
1853
+ NSString *post = [NSString stringWithFormat:@"spc=%@&%@", spcUrlEncoded, contentId];
1854
+ NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
1855
+ [request setHTTPBody: postData];
1856
+ }
1857
+
1858
+ NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
1859
+ NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
1860
+ NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
1861
+ NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
1862
+ if (error != nil) {
1863
+ NSLog(@"Error getting license from %@, HTTP status code %li", url, (long)[httpResponse statusCode]);
1864
+ [self finishLoadingWithError:error];
1865
+ self->_requestingCertificateErrored = YES;
1866
+ } else {
1867
+ if([httpResponse statusCode] != 200){
1868
+ NSLog(@"Error getting license from %@, HTTP status code %li", url, (long)[httpResponse statusCode]);
1869
+ NSError *licenseError = [NSError errorWithDomain: @"RCTVideo"
1870
+ code: RCTVideoErrorLicenseRequestNotOk
1871
+ userInfo: @{
1872
+ NSLocalizedDescriptionKey: @"Error obtaining license.",
1873
+ NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"License server responded with status code %li", (long)[httpResponse statusCode]],
1874
+ NSLocalizedRecoverySuggestionErrorKey: @"Did you send the correct data to the license Server? Is the server ok?"
1875
+ }
1876
+ ];
1877
+ [self finishLoadingWithError:licenseError];
1878
+ self->_requestingCertificateErrored = YES;
1879
+ } else if (data != nil) {
1880
+ if(self.onGetLicense) {
1881
+ [dataRequest respondWithData:data];
1882
+ } else {
1883
+ NSData *decodedData = [[NSData alloc] initWithBase64EncodedData:data options:0];
1884
+ [dataRequest respondWithData:decodedData];
1885
+ }
1886
+ [loadingRequest finishLoading];
1887
+ } else {
1888
+ NSError *licenseError = [NSError errorWithDomain: @"RCTVideo"
1889
+ code: RCTVideoErrorNoDataFromLicenseRequest
1890
+ userInfo: @{
1891
+ NSLocalizedDescriptionKey: @"Error obtaining DRM license.",
1892
+ NSLocalizedFailureReasonErrorKey: @"No data received from the license server.",
1893
+ NSLocalizedRecoverySuggestionErrorKey: @"Is the licenseServer ok?."
1894
+ }
1895
+ ];
1896
+ [self finishLoadingWithError:licenseError];
1897
+ self->_requestingCertificateErrored = YES;
1898
+ }
1899
+
1900
+ }
1901
+ }];
1902
+ [postDataTask resume];
1903
+ }
1904
+
1905
+ } else {
1906
+ NSError *licenseError = [NSError errorWithDomain: @"RCTVideo"
1907
+ code: RCTVideoErrorNoSPC
1908
+ userInfo: @{
1909
+ NSLocalizedDescriptionKey: @"Error obtaining license.",
1910
+ NSLocalizedFailureReasonErrorKey: @"No spc received.",
1911
+ NSLocalizedRecoverySuggestionErrorKey: @"Check your DRM config."
1912
+ }
1913
+ ];
1914
+ [self finishLoadingWithError:licenseError];
1915
+ self->_requestingCertificateErrored = YES;
1916
+ }
1917
+
1918
+ } else {
1919
+ NSError *licenseError = [NSError errorWithDomain: @"RCTVideo"
1920
+ code: RCTVideoErrorNoDataRequest
1921
+ userInfo: @{
1922
+ NSLocalizedDescriptionKey: @"Error obtaining DRM license.",
1923
+ NSLocalizedFailureReasonErrorKey: @"No dataRequest found.",
1924
+ NSLocalizedRecoverySuggestionErrorKey: @"Check your DRM configuration."
1925
+ }
1926
+ ];
1927
+ [self finishLoadingWithError:licenseError];
1928
+ self->_requestingCertificateErrored = YES;
1929
+ }
1930
+ } else {
1931
+ NSError *licenseError = [NSError errorWithDomain: @"RCTVideo"
1932
+ code: RCTVideoErrorNoCertificateData
1933
+ userInfo: @{
1934
+ NSLocalizedDescriptionKey: @"Error obtaining DRM license.",
1935
+ NSLocalizedFailureReasonErrorKey: @"No certificate data obtained from the specificied url.",
1936
+ NSLocalizedRecoverySuggestionErrorKey: @"Have you specified a valid 'certificateUrl'?"
1937
+ }
1938
+ ];
1939
+ [self finishLoadingWithError:licenseError];
1940
+ self->_requestingCertificateErrored = YES;
1941
+ }
1942
+ });
1943
+ return YES;
1944
+ } else {
1945
+ NSError *licenseError = [NSError errorWithDomain: @"RCTVideo"
1946
+ code: RCTVideoErrorNoCertificateURL
1947
+ userInfo: @{
1948
+ NSLocalizedDescriptionKey: @"Error obtaining DRM License.",
1949
+ NSLocalizedFailureReasonErrorKey: @"No certificate URL has been found.",
1950
+ NSLocalizedRecoverySuggestionErrorKey: @"Did you specified the prop certificateUrl?"
1951
+ }
1952
+ ];
1953
+ return [self finishLoadingWithError:licenseError];
1954
+ }
1955
+ } else {
1956
+ NSError *licenseError = [NSError errorWithDomain: @"RCTVideo"
1957
+ code: RCTVideoErrorNoFairplayDRM
1958
+ userInfo: @{
1959
+ NSLocalizedDescriptionKey: @"Error obtaining DRM license.",
1960
+ NSLocalizedFailureReasonErrorKey: @"Not a valid DRM Scheme has found",
1961
+ NSLocalizedRecoverySuggestionErrorKey: @"Have you specified the 'drm' 'type' as fairplay?"
1962
+ }
1963
+ ];
1964
+ return [self finishLoadingWithError:licenseError];
1965
+ }
1966
+
1967
+ } else {
1968
+ NSError *licenseError = [NSError errorWithDomain: @"RCTVideo"
1969
+ code: RCTVideoErrorNoDRMData
1970
+ userInfo: @{
1971
+ NSLocalizedDescriptionKey: @"Error obtaining DRM license.",
1972
+ NSLocalizedFailureReasonErrorKey: @"No drm object found.",
1973
+ NSLocalizedRecoverySuggestionErrorKey: @"Have you specified the 'drm' prop?"
1974
+ }
1975
+ ];
1976
+ return [self finishLoadingWithError:licenseError];
1977
+ }
1978
+
1979
+
1980
+ return NO;
1981
+ }
1982
+
1983
+ - (NSData *)base64DataFromBase64String: (NSString *)base64String {
1984
+ if (base64String != nil) {
1985
+ // NSData from the Base64 encoded str
1986
+ NSData *base64Data = [[NSData alloc] initWithBase64EncodedString:base64String options:NSASCIIStringEncoding];
1987
+ return base64Data;
1988
+ }
1989
+ return nil;
1990
+ }
1991
+ #pragma mark - Picture in Picture
1992
+
1993
+ #if TARGET_OS_IOS
1994
+ - (void)pictureInPictureControllerDidStopPictureInPicture:(AVPictureInPictureController *)pictureInPictureController {
1995
+ if (self.onPictureInPictureStatusChanged) {
1996
+ self.onPictureInPictureStatusChanged(@{
1997
+ @"isActive": [NSNumber numberWithBool:false]
1998
+ });
1999
+ }
2000
+ }
2001
+
2002
+ - (void)pictureInPictureControllerDidStartPictureInPicture:(AVPictureInPictureController *)pictureInPictureController {
2003
+ if (self.onPictureInPictureStatusChanged) {
2004
+ self.onPictureInPictureStatusChanged(@{
2005
+ @"isActive": [NSNumber numberWithBool:true]
2006
+ });
2007
+ }
2008
+ }
2009
+
2010
+ - (void)pictureInPictureControllerWillStopPictureInPicture:(AVPictureInPictureController *)pictureInPictureController {
2011
+
2012
+ }
2013
+
2014
+ - (void)pictureInPictureControllerWillStartPictureInPicture:(AVPictureInPictureController *)pictureInPictureController {
2015
+
2016
+ }
2017
+
2018
+ - (void)pictureInPictureController:(AVPictureInPictureController *)pictureInPictureController failedToStartPictureInPictureWithError:(NSError *)error {
2019
+
2020
+ }
2021
+
2022
+ - (void)pictureInPictureController:(AVPictureInPictureController *)pictureInPictureController restoreUserInterfaceForPictureInPictureStopWithCompletionHandler:(void (^)(BOOL))completionHandler {
2023
+ NSAssert(_restoreUserInterfaceForPIPStopCompletionHandler == NULL, @"restoreUserInterfaceForPIPStopCompletionHandler was not called after picture in picture was exited.");
2024
+ if (self.onRestoreUserInterfaceForPictureInPictureStop) {
2025
+ self.onRestoreUserInterfaceForPictureInPictureStop(@{});
2026
+ }
2027
+ _restoreUserInterfaceForPIPStopCompletionHandler = completionHandler;
2028
+ }
2029
+ #endif
2030
+
2031
+ @end