native_video_view.m 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. /**************************************************************************/
  2. /* native_video_view.m */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #import "native_video_view.h"
  31. #import <AVFoundation/AVFoundation.h>
  32. @interface GodotNativeVideoView ()
  33. @property(strong, nonatomic) AVAsset *avAsset;
  34. @property(strong, nonatomic) AVPlayerItem *avPlayerItem;
  35. @property(strong, nonatomic) AVPlayer *avPlayer;
  36. @property(strong, nonatomic) AVPlayerLayer *avPlayerLayer;
  37. @property(assign, nonatomic) CMTime videoCurrentTime;
  38. @property(assign, nonatomic) BOOL isVideoCurrentlyPlaying;
  39. @end
  40. @implementation GodotNativeVideoView
  41. - (instancetype)initWithFrame:(CGRect)frame {
  42. self = [super initWithFrame:frame];
  43. if (self) {
  44. [self godot_commonInit];
  45. }
  46. return self;
  47. }
  48. - (instancetype)initWithCoder:(NSCoder *)coder {
  49. self = [super initWithCoder:coder];
  50. if (self) {
  51. [self godot_commonInit];
  52. }
  53. return self;
  54. }
  55. - (void)godot_commonInit {
  56. self.isVideoCurrentlyPlaying = NO;
  57. self.videoCurrentTime = kCMTimeZero;
  58. [self observeVideoAudio];
  59. }
  60. - (void)layoutSubviews {
  61. [super layoutSubviews];
  62. self.avPlayerLayer.frame = self.bounds;
  63. }
  64. - (void)observeVideoAudio {
  65. printf("******** adding observer for sound routing changes\n");
  66. [[NSNotificationCenter defaultCenter]
  67. addObserver:self
  68. selector:@selector(audioRouteChangeListenerCallback:)
  69. name:AVAudioSessionRouteChangeNotification
  70. object:nil];
  71. }
  72. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  73. if (object == self.avPlayerItem && [keyPath isEqualToString:@"status"]) {
  74. [self handleVideoOrPlayerStatus];
  75. }
  76. if (object == self.avPlayer && [keyPath isEqualToString:@"rate"]) {
  77. [self handleVideoPlayRate];
  78. }
  79. }
  80. // MARK: Video Audio
  81. - (void)audioRouteChangeListenerCallback:(NSNotification *)notification {
  82. printf("*********** route changed!\n");
  83. NSDictionary *interuptionDict = notification.userInfo;
  84. NSInteger routeChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
  85. switch (routeChangeReason) {
  86. case AVAudioSessionRouteChangeReasonNewDeviceAvailable: {
  87. NSLog(@"AVAudioSessionRouteChangeReasonNewDeviceAvailable");
  88. NSLog(@"Headphone/Line plugged in");
  89. } break;
  90. case AVAudioSessionRouteChangeReasonOldDeviceUnavailable: {
  91. NSLog(@"AVAudioSessionRouteChangeReasonOldDeviceUnavailable");
  92. NSLog(@"Headphone/Line was pulled. Resuming video play....");
  93. if ([self isVideoPlaying]) {
  94. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5f * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  95. [self.avPlayer play]; // NOTE: change this line according your current player implementation
  96. NSLog(@"resumed play");
  97. });
  98. }
  99. } break;
  100. case AVAudioSessionRouteChangeReasonCategoryChange: {
  101. // called at start - also when other audio wants to play
  102. NSLog(@"AVAudioSessionRouteChangeReasonCategoryChange");
  103. } break;
  104. }
  105. }
  106. // MARK: Native Video Player
  107. - (void)handleVideoOrPlayerStatus {
  108. if (self.avPlayerItem.status == AVPlayerItemStatusFailed || self.avPlayer.status == AVPlayerStatusFailed) {
  109. [self stopVideo];
  110. }
  111. if (self.avPlayer.status == AVPlayerStatusReadyToPlay && self.avPlayerItem.status == AVPlayerItemStatusReadyToPlay && CMTimeCompare(self.videoCurrentTime, kCMTimeZero) == 0) {
  112. // NSLog(@"time: %@", self.video_current_time);
  113. [self.avPlayer seekToTime:self.videoCurrentTime];
  114. self.videoCurrentTime = kCMTimeZero;
  115. }
  116. }
  117. - (void)handleVideoPlayRate {
  118. NSLog(@"Player playback rate changed: %.5f", self.avPlayer.rate);
  119. if ([self isVideoPlaying] && self.avPlayer.rate == 0.0 && !self.avPlayer.error) {
  120. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5f * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  121. [self.avPlayer play]; // NOTE: change this line according your current player implementation
  122. NSLog(@"resumed play");
  123. });
  124. NSLog(@" . . . PAUSED (or just started)");
  125. }
  126. }
  127. - (BOOL)playVideoAtPath:(NSString *)filePath volume:(float)videoVolume audio:(NSString *)audioTrack subtitle:(NSString *)subtitleTrack {
  128. self.avAsset = [AVAsset assetWithURL:[NSURL fileURLWithPath:filePath]];
  129. self.avPlayerItem = [AVPlayerItem playerItemWithAsset:self.avAsset];
  130. [self.avPlayerItem addObserver:self forKeyPath:@"status" options:0 context:nil];
  131. self.avPlayer = [AVPlayer playerWithPlayerItem:self.avPlayerItem];
  132. self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
  133. [self.avPlayer addObserver:self forKeyPath:@"status" options:0 context:nil];
  134. [[NSNotificationCenter defaultCenter]
  135. addObserver:self
  136. selector:@selector(playerItemDidReachEnd:)
  137. name:AVPlayerItemDidPlayToEndTimeNotification
  138. object:[self.avPlayer currentItem]];
  139. [self.avPlayer addObserver:self forKeyPath:@"rate" options:NSKeyValueObservingOptionNew context:0];
  140. [self.avPlayerLayer setFrame:self.bounds];
  141. [self.layer addSublayer:self.avPlayerLayer];
  142. [self.avPlayer play];
  143. AVMediaSelectionGroup *audioGroup = [self.avAsset mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicAudible];
  144. NSMutableArray *allAudioParams = [NSMutableArray array];
  145. for (id track in audioGroup.options) {
  146. NSString *language = [[track locale] localeIdentifier];
  147. NSLog(@"subtitle lang: %@", language);
  148. if ([language isEqualToString:audioTrack]) {
  149. AVMutableAudioMixInputParameters *audioInputParams = [AVMutableAudioMixInputParameters audioMixInputParameters];
  150. [audioInputParams setVolume:videoVolume atTime:kCMTimeZero];
  151. [audioInputParams setTrackID:[track trackID]];
  152. [allAudioParams addObject:audioInputParams];
  153. AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
  154. [audioMix setInputParameters:allAudioParams];
  155. [self.avPlayer.currentItem selectMediaOption:track inMediaSelectionGroup:audioGroup];
  156. [self.avPlayer.currentItem setAudioMix:audioMix];
  157. break;
  158. }
  159. }
  160. AVMediaSelectionGroup *subtitlesGroup = [self.avAsset mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicLegible];
  161. NSArray *useableTracks = [AVMediaSelectionGroup mediaSelectionOptionsFromArray:subtitlesGroup.options withoutMediaCharacteristics:[NSArray arrayWithObject:AVMediaCharacteristicContainsOnlyForcedSubtitles]];
  162. for (id track in useableTracks) {
  163. NSString *language = [[track locale] localeIdentifier];
  164. NSLog(@"subtitle lang: %@", language);
  165. if ([language isEqualToString:subtitleTrack]) {
  166. [self.avPlayer.currentItem selectMediaOption:track inMediaSelectionGroup:subtitlesGroup];
  167. break;
  168. }
  169. }
  170. self.isVideoCurrentlyPlaying = YES;
  171. return true;
  172. }
  173. - (BOOL)isVideoPlaying {
  174. if (self.avPlayer.error) {
  175. printf("Error during playback\n");
  176. }
  177. return (self.avPlayer.rate > 0 && !self.avPlayer.error);
  178. }
  179. - (void)pauseVideo {
  180. self.videoCurrentTime = self.avPlayer.currentTime;
  181. [self.avPlayer pause];
  182. self.isVideoCurrentlyPlaying = NO;
  183. }
  184. - (void)unfocusVideo {
  185. [self.avPlayer pause];
  186. }
  187. - (void)unpauseVideo {
  188. [self.avPlayer play];
  189. self.isVideoCurrentlyPlaying = YES;
  190. }
  191. - (void)playerItemDidReachEnd:(NSNotification *)notification {
  192. [self stopVideo];
  193. }
  194. - (void)finishPlayingVideo {
  195. [self.avPlayer pause];
  196. [self.avPlayerLayer removeFromSuperlayer];
  197. self.avPlayerLayer = nil;
  198. if (self.avPlayerItem) {
  199. [self.avPlayerItem removeObserver:self forKeyPath:@"status"];
  200. self.avPlayerItem = nil;
  201. }
  202. if (self.avPlayer) {
  203. [self.avPlayer removeObserver:self forKeyPath:@"status"];
  204. self.avPlayer = nil;
  205. }
  206. self.avAsset = nil;
  207. self.isVideoCurrentlyPlaying = NO;
  208. }
  209. - (void)stopVideo {
  210. [self finishPlayingVideo];
  211. [self removeFromSuperview];
  212. }
  213. @end