UnityReplayKit.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. #if UNITY_REPLAY_KIT_AVAILABLE
  2. #import "UnityReplayKit.h"
  3. #import "UnityAppController.h"
  4. #import "UI/UnityViewControllerBase.h"
  5. #import "UnityInterface.h"
  6. #import <UIKit/UIKit.h>
  7. extern "C" void UnityReplayKitTriggerBroadcastStatusCallback(void* callback, bool hasSucceeded, const char* errorMessage);
  8. static UnityReplayKit* _replayKit = nil;
  9. @protocol UnityReplayKit_RPScreenRecorder<NSObject>
  10. - (void)setMicrophoneEnabled:(BOOL)value;
  11. - (BOOL)isMicrophoneEnabled;
  12. - (void)setCameraEnabled:(BOOL)value;
  13. - (BOOL)isCameraEnabled;
  14. @property (nonatomic, setter = setMicrophoneEnabled:, getter = isMicrophoneEnabled) BOOL microphoneEnabled;
  15. @property (nonatomic, setter = setCameraEnabled:, getter = isCameraEnabled) BOOL cameraEnabled;
  16. @property (nonatomic, readonly) UIView* cameraPreviewView;
  17. @end
  18. @protocol UnityReplayKit_RPBroadcastController<NSObject>
  19. @property(nonatomic, readonly) NSURL *broadcastURL;
  20. @property(nonatomic, readonly, getter = isBroadcasting) BOOL broadcasting;
  21. @property(nonatomic, readonly) NSString *broadcastExtensionBundleID;
  22. //@property(nonatomic, weak) id<RPBroadcastControllerDelegate> delegate;
  23. @property(nonatomic, readonly, getter = isPaused) BOOL paused;
  24. @property(nonatomic, readonly) NSDictionary<NSString *, NSObject<NSCoding> *> *serviceInfo;
  25. - (BOOL)isBroadcasting;
  26. - (void)finishBroadcastWithHandler:(void (^)(NSError *error))handler;
  27. - (void)startBroadcastWithHandler:(void (^)(NSError *error))handler;
  28. - (void)pauseBroadcast;
  29. - (void)resumeBroadcast;
  30. @end
  31. @interface UnityReplayKit_RPBroadcastActivityViewController : UIViewController<NSObject>
  32. @property (nonatomic, weak) id delegate;
  33. @end
  34. // why do we care about orientation handling:
  35. // ReplayKit will disable top-window autorotation
  36. // as users keep asking to do autorotation during broadcast/record we create fake empty window with fake view controller
  37. // this window will have autorotation disabled instead of unity one
  38. // but this is not the end of the story: what fake view controller does is also important
  39. // now it is hard to speculate what *actually* happens but with setup like fake view controller takes over control over "supported orientations"
  40. // meaning that if we dont do anything suddenly all orientations become enabled.
  41. // to avoid that we create this monstrosity that pokes unity for orientation.
  42. #if PLATFORM_IOS
  43. @interface UnityReplayKitViewController : UnityViewControllerBase {}
  44. - (NSUInteger)supportedInterfaceOrientations;
  45. @end
  46. @implementation UnityReplayKitViewController
  47. - (NSUInteger)supportedInterfaceOrientations
  48. {
  49. NSUInteger ret = 0;
  50. if (UnityShouldAutorotate())
  51. {
  52. if (UnityIsOrientationEnabled(portrait))
  53. ret |= (1 << UIInterfaceOrientationPortrait);
  54. if (UnityIsOrientationEnabled(portraitUpsideDown))
  55. ret |= (1 << UIInterfaceOrientationPortraitUpsideDown);
  56. if (UnityIsOrientationEnabled(landscapeLeft))
  57. ret |= (1 << UIInterfaceOrientationLandscapeRight);
  58. if (UnityIsOrientationEnabled(landscapeRight))
  59. ret |= (1 << UIInterfaceOrientationLandscapeLeft);
  60. }
  61. else
  62. {
  63. switch (UnityRequestedScreenOrientation())
  64. {
  65. case portrait: ret = (1 << UIInterfaceOrientationPortrait); break;
  66. case portraitUpsideDown: ret = (1 << UIInterfaceOrientationPortraitUpsideDown); break;
  67. case landscapeLeft: ret = (1 << UIInterfaceOrientationLandscapeRight); break;
  68. case landscapeRight: ret = (1 << UIInterfaceOrientationLandscapeLeft); break;
  69. }
  70. }
  71. return ret;
  72. }
  73. @end
  74. #else
  75. #define UnityReplayKitViewController UnityViewControllerBase
  76. #endif
  77. @implementation UnityReplayKit
  78. {
  79. id<UnityReplayKit_RPBroadcastController> broadcastController;
  80. void* broadcastStartStatusCallback;
  81. UIView* currentCameraPreviewView;
  82. UIWindow* overlayWindow;
  83. }
  84. - (void)createOverlayWindow
  85. {
  86. UIWindow* wnd = self->overlayWindow = [[UIWindow alloc] initWithFrame: [UIScreen mainScreen].bounds];
  87. wnd.hidden = wnd.userInteractionEnabled = NO;
  88. wnd.backgroundColor = nil;
  89. wnd.rootViewController = [[UnityReplayKitViewController alloc] init];
  90. }
  91. + (UnityReplayKit*)sharedInstance
  92. {
  93. static dispatch_once_t onceToken;
  94. dispatch_once(&onceToken, ^{
  95. _replayKit = [[UnityReplayKit alloc] init];
  96. });
  97. return _replayKit;
  98. }
  99. - (BOOL)apiAvailable
  100. {
  101. return ([RPScreenRecorder class] != nil) && [RPScreenRecorder sharedRecorder].isAvailable;
  102. }
  103. - (BOOL)recordingPreviewAvailable
  104. {
  105. return _previewController != nil;
  106. }
  107. - (BOOL)startRecording:(BOOL)enableMicrophone
  108. {
  109. RPScreenRecorder* recorder = [RPScreenRecorder sharedRecorder];
  110. if (recorder == nil)
  111. {
  112. _lastError = [NSString stringWithUTF8String: "Failed to get Screen Recorder"];
  113. return NO;
  114. }
  115. recorder.delegate = self;
  116. __block BOOL success = YES;
  117. [recorder startRecordingWithMicrophoneEnabled: enableMicrophone handler:^(NSError* error) {
  118. if (error != nil)
  119. {
  120. _lastError = [error description];
  121. success = NO;
  122. }
  123. else
  124. {
  125. [self createOverlayWindow];
  126. }
  127. }];
  128. return success;
  129. }
  130. - (BOOL)isRecording
  131. {
  132. RPScreenRecorder* recorder = [RPScreenRecorder sharedRecorder];
  133. if (recorder == nil)
  134. {
  135. _lastError = [NSString stringWithUTF8String: "Failed to get Screen Recorder"];
  136. return NO;
  137. }
  138. return recorder.isRecording;
  139. }
  140. - (BOOL)stopRecording
  141. {
  142. RPScreenRecorder* recorder = [RPScreenRecorder sharedRecorder];
  143. if (recorder == nil)
  144. {
  145. _lastError = [NSString stringWithUTF8String: "Failed to get Screen Recorder"];
  146. return NO;
  147. }
  148. __block BOOL success = YES;
  149. [recorder stopRecordingWithHandler:^(RPPreviewViewController* previewViewController, NSError* error) {
  150. self->overlayWindow = nil;
  151. if (error != nil)
  152. {
  153. _lastError = [error description];
  154. success = NO;
  155. return;
  156. }
  157. if (previewViewController != nil)
  158. {
  159. [previewViewController setPreviewControllerDelegate: self];
  160. _previewController = previewViewController;
  161. }
  162. }];
  163. return success;
  164. }
  165. - (void)screenRecorder:(RPScreenRecorder*)screenRecorder didStopRecordingWithError:(NSError*)error previewViewController:(RPPreviewViewController*)previewViewController
  166. {
  167. if (error != nil)
  168. {
  169. _lastError = [error description];
  170. }
  171. self->overlayWindow = nil;
  172. _previewController = previewViewController;
  173. }
  174. - (BOOL)showPreview
  175. {
  176. if (_previewController == nil)
  177. {
  178. _lastError = [NSString stringWithUTF8String: "No recording available"];
  179. return NO;
  180. }
  181. [_previewController setModalPresentationStyle: UIModalPresentationFullScreen];
  182. [GetAppController().rootViewController presentViewController: _previewController animated: YES completion:^()
  183. {
  184. _previewController = nil;
  185. }];
  186. return YES;
  187. }
  188. - (BOOL)discardPreview
  189. {
  190. if (_previewController == nil)
  191. {
  192. return YES;
  193. }
  194. RPScreenRecorder* recorder = [RPScreenRecorder sharedRecorder];
  195. if (recorder == nil)
  196. {
  197. _lastError = [NSString stringWithUTF8String: "Failed to get Screen Recorder"];
  198. return NO;
  199. }
  200. [recorder discardRecordingWithHandler:^()
  201. {
  202. _previewController = nil;
  203. }];
  204. // TODO - the above callback doesn't seem to be working at the moment.
  205. _previewController = nil;
  206. return YES;
  207. }
  208. - (void)previewControllerDidFinish:(RPPreviewViewController*)previewController
  209. {
  210. if (previewController != nil)
  211. {
  212. [previewController dismissViewControllerAnimated: YES completion: nil];
  213. }
  214. }
  215. /****************************************
  216. * ReplayKit Broadcasting API *
  217. ****************************************/
  218. - (BOOL)broadcastingApiAvailable
  219. {
  220. return nil != NSClassFromString(@"RPBroadcastController")
  221. && nil != NSClassFromString(@"RPBroadcastActivityViewController");
  222. }
  223. - (NSURL*)broadcastURL
  224. {
  225. if (broadcastController == nil)
  226. {
  227. return nil;
  228. }
  229. return [broadcastController broadcastURL];
  230. }
  231. - (BOOL)isBroadcasting
  232. {
  233. if (broadcastController == nil)
  234. {
  235. return NO;
  236. }
  237. return [broadcastController isBroadcasting];
  238. }
  239. - (void)broadcastActivityViewController:(UnityReplayKit_RPBroadcastActivityViewController *)sBroadcastActivityViewController
  240. didFinishWithBroadcastController:(id<UnityReplayKit_RPBroadcastController>)sBroadcastController
  241. error:(NSError *)error
  242. {
  243. dispatch_sync(dispatch_get_main_queue(), ^{
  244. UnityPause(0);
  245. });
  246. if (sBroadcastController == nil)
  247. {
  248. _lastError = [error description];
  249. UnityReplayKitTriggerBroadcastStatusCallback(broadcastStartStatusCallback, false, [_lastError UTF8String]);
  250. broadcastStartStatusCallback = nullptr;
  251. [UnityGetGLViewController() dismissViewControllerAnimated: YES completion: nil];
  252. return;
  253. }
  254. broadcastController = sBroadcastController;
  255. [UnityGetGLViewController() dismissViewControllerAnimated: YES completion:^
  256. {
  257. [broadcastController startBroadcastWithHandler:^(NSError* error)
  258. {
  259. if (error != nil)
  260. {
  261. _lastError = [error description];
  262. UnityReplayKitTriggerBroadcastStatusCallback(broadcastStartStatusCallback, false, [_lastError UTF8String]);
  263. broadcastStartStatusCallback = nullptr;
  264. broadcastController = nil;
  265. return;
  266. }
  267. UnityReplayKitTriggerBroadcastStatusCallback(broadcastStartStatusCallback, true, "");
  268. broadcastStartStatusCallback = nullptr;
  269. _lastError = nil;
  270. }];
  271. }];
  272. }
  273. - (void)startBroadcastingWithCallback:(void *)callback
  274. {
  275. Class class_BroadcastActivityViewController = NSClassFromString(@"RPBroadcastActivityViewController");
  276. if (class_BroadcastActivityViewController == nil)
  277. {
  278. return;
  279. }
  280. if (broadcastController != nil && broadcastController.broadcasting)
  281. {
  282. _lastError = @"Broadcast already in progress";
  283. UnityReplayKitTriggerBroadcastStatusCallback(callback, false, [_lastError UTF8String]);
  284. return;
  285. }
  286. if (broadcastStartStatusCallback != nullptr)
  287. {
  288. _lastError = @"The last attempt to start a broadcast didn\'t finish yet.";
  289. UnityReplayKitTriggerBroadcastStatusCallback(callback, false, [_lastError UTF8String]);
  290. return;
  291. }
  292. [class_BroadcastActivityViewController performSelector: @selector(loadBroadcastActivityViewControllerWithHandler:) withObject:^(UnityReplayKit_RPBroadcastActivityViewController* vc, NSError* error)
  293. {
  294. if (vc == nil || error != nil)
  295. {
  296. _lastError = [error description];
  297. UnityReplayKitTriggerBroadcastStatusCallback(callback, false, [_lastError UTF8String]);
  298. return;
  299. }
  300. [self createOverlayWindow];
  301. UnityPause(1);
  302. vc.delegate = self;
  303. broadcastStartStatusCallback = callback;
  304. #if PLATFORM_TVOS
  305. vc.modalPresentationStyle = UIModalPresentationFullScreen;
  306. #else
  307. vc.modalPresentationStyle = UIModalPresentationPopover;
  308. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  309. {
  310. vc.popoverPresentationController.sourceRect = CGRectMake(GetAppController().rootView.bounds.size.width / 2, 0, 0, 0);
  311. vc.popoverPresentationController.sourceView = GetAppController().rootView;
  312. }
  313. #endif
  314. [UnityGetGLViewController() presentViewController: vc animated: YES completion: nil];
  315. }];
  316. return;
  317. }
  318. - (void)stopBroadcasting
  319. {
  320. self->overlayWindow = nil;
  321. if (broadcastController == nil || !broadcastController.broadcasting)
  322. {
  323. broadcastController = nil;
  324. return;
  325. }
  326. [broadcastController finishBroadcastWithHandler:^(NSError* error)
  327. {
  328. broadcastController = nil;
  329. if (error == nil)
  330. return;
  331. _lastError = [error description];
  332. }];
  333. }
  334. - (BOOL)isCameraEnabled
  335. {
  336. if (![self apiAvailable])
  337. {
  338. return NO;
  339. }
  340. id<UnityReplayKit_RPScreenRecorder> screenRecorder = (id)[RPScreenRecorder sharedRecorder];
  341. if (![screenRecorder respondsToSelector: @selector(isCameraEnabled)])
  342. {
  343. return NO;
  344. }
  345. return screenRecorder.cameraEnabled;
  346. }
  347. - (void)setCameraEnabled:(BOOL)cameraEnabled
  348. {
  349. if (![self apiAvailable])
  350. {
  351. return;
  352. }
  353. id<UnityReplayKit_RPScreenRecorder> screenRecorder = (id)[RPScreenRecorder sharedRecorder];
  354. if (![screenRecorder respondsToSelector: @selector(setCameraEnabled:)])
  355. {
  356. return;
  357. }
  358. screenRecorder.cameraEnabled = cameraEnabled;
  359. }
  360. - (BOOL)isMicrophoneEnabled
  361. {
  362. if (![self apiAvailable])
  363. {
  364. return NO;
  365. }
  366. id<UnityReplayKit_RPScreenRecorder> screenRecorder = (id)[RPScreenRecorder sharedRecorder];
  367. if (![screenRecorder respondsToSelector: @selector(isMicrophoneEnabled)])
  368. {
  369. return NO;
  370. }
  371. return screenRecorder.microphoneEnabled;
  372. }
  373. - (void)setMicrophoneEnabled:(BOOL)microphoneEnabled
  374. {
  375. if (![self apiAvailable])
  376. {
  377. return;
  378. }
  379. id<UnityReplayKit_RPScreenRecorder> screenRecorder = (id)[RPScreenRecorder sharedRecorder];
  380. if (![screenRecorder respondsToSelector: @selector(setMicrophoneEnabled:)])
  381. {
  382. return;
  383. }
  384. screenRecorder.microphoneEnabled = microphoneEnabled;
  385. }
  386. - (BOOL)showCameraPreviewAt:(CGPoint)position
  387. {
  388. if (currentCameraPreviewView == nil)
  389. {
  390. if (![self apiAvailable])
  391. {
  392. return NO;
  393. }
  394. id<UnityReplayKit_RPScreenRecorder> screenRecorder = (id)[RPScreenRecorder sharedRecorder];
  395. UIView* cameraPreviewView = screenRecorder.cameraPreviewView;
  396. if (cameraPreviewView == nil)
  397. {
  398. return NO;
  399. }
  400. [[UnityGetGLViewController() view] addSubview: cameraPreviewView];
  401. currentCameraPreviewView = cameraPreviewView;
  402. [cameraPreviewView setUserInteractionEnabled: NO];
  403. }
  404. int width = currentCameraPreviewView.frame.size.width;
  405. int height = currentCameraPreviewView.frame.size.height;
  406. [currentCameraPreviewView setFrame: CGRectMake(position.x, position.y, width, height)];
  407. return YES;
  408. }
  409. - (void)hideCameraPreview
  410. {
  411. if (currentCameraPreviewView != nil)
  412. {
  413. [currentCameraPreviewView removeFromSuperview];
  414. currentCameraPreviewView = nil;
  415. }
  416. }
  417. @end
  418. #endif // UNITY_REPLAY_KIT_AVAILABLE