The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1342 lines
59KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. #if (defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_10_0)
  19. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  20. #define JUCE_DEPRECATION_IGNORED 1
  21. #endif
  22. struct CameraDevice::Pimpl
  23. {
  24. using InternalOpenCameraResultCallback = std::function<void (const String& /*cameraId*/, const String& /*error*/)>;
  25. Pimpl (CameraDevice& ownerToUse, const String& cameraIdToUse, int /*index*/,
  26. int /*minWidth*/, int /*minHeight*/, int /*maxWidth*/, int /*maxHeight*/,
  27. bool useHighQuality)
  28. : owner (ownerToUse),
  29. cameraId (cameraIdToUse),
  30. captureSession (*this, useHighQuality)
  31. {
  32. }
  33. String getCameraId() const noexcept { return cameraId; }
  34. void open (InternalOpenCameraResultCallback cameraOpenCallbackToUse)
  35. {
  36. cameraOpenCallback = std::move (cameraOpenCallbackToUse);
  37. if (cameraOpenCallback == nullptr)
  38. {
  39. // A valid camera open callback must be passed.
  40. jassertfalse;
  41. return;
  42. }
  43. [AVCaptureDevice requestAccessForMediaType: AVMediaTypeVideo
  44. completionHandler: ^(BOOL granted)
  45. {
  46. // Access to video is required for camera to work,
  47. // black images will be produced otherwise!
  48. jassert (granted);
  49. ignoreUnused (granted);
  50. }];
  51. [AVCaptureDevice requestAccessForMediaType: AVMediaTypeAudio
  52. completionHandler: ^(BOOL granted)
  53. {
  54. // Access to audio is required for camera to work,
  55. // silence will be produced otherwise!
  56. jassert (granted);
  57. ignoreUnused (granted);
  58. }];
  59. captureSession.startSessionForDeviceWithId (cameraId);
  60. }
  61. bool openedOk() const noexcept { return captureSession.openedOk(); }
  62. void takeStillPicture (std::function<void (const Image&)> pictureTakenCallbackToUse)
  63. {
  64. if (pictureTakenCallbackToUse == nullptr)
  65. {
  66. jassertfalse;
  67. return;
  68. }
  69. pictureTakenCallback = std::move (pictureTakenCallbackToUse);
  70. triggerStillPictureCapture();
  71. }
  72. void startRecordingToFile (const File& file, int /*quality*/)
  73. {
  74. file.deleteFile();
  75. captureSession.startRecording (file);
  76. }
  77. void stopRecording()
  78. {
  79. captureSession.stopRecording();
  80. }
  81. Time getTimeOfFirstRecordedFrame() const
  82. {
  83. return captureSession.getTimeOfFirstRecordedFrame();
  84. }
  85. static StringArray getAvailableDevices()
  86. {
  87. StringArray results;
  88. JUCE_CAMERA_LOG ("Available camera devices: ");
  89. for (AVCaptureDevice* device in getDevices())
  90. {
  91. JUCE_CAMERA_LOG ("Device start----------------------------------");
  92. printDebugCameraInfo (device);
  93. JUCE_CAMERA_LOG ("Device end----------------------------------");
  94. results.add (nsStringToJuce (device.uniqueID));
  95. }
  96. return results;
  97. }
  98. void addListener (CameraDevice::Listener* listenerToAdd)
  99. {
  100. const ScopedLock sl (listenerLock);
  101. listeners.add (listenerToAdd);
  102. if (listeners.size() == 1)
  103. triggerStillPictureCapture();
  104. }
  105. void removeListener (CameraDevice::Listener* listenerToRemove)
  106. {
  107. const ScopedLock sl (listenerLock);
  108. listeners.remove (listenerToRemove);
  109. }
  110. private:
  111. static NSArray<AVCaptureDevice*>* getDevices()
  112. {
  113. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  114. if (iosVersion.major >= 10)
  115. {
  116. std::unique_ptr<NSMutableArray<AVCaptureDeviceType>, NSObjectDeleter> deviceTypes ([[NSMutableArray alloc] initWithCapacity: 2]);
  117. [deviceTypes.get() addObject: AVCaptureDeviceTypeBuiltInWideAngleCamera];
  118. [deviceTypes.get() addObject: AVCaptureDeviceTypeBuiltInTelephotoCamera];
  119. if ((iosVersion.major == 10 && iosVersion.minor >= 2) || iosVersion.major >= 11)
  120. [deviceTypes.get() addObject: AVCaptureDeviceTypeBuiltInDualCamera];
  121. if ((iosVersion.major == 11 && iosVersion.minor >= 1) || iosVersion.major >= 12)
  122. [deviceTypes.get() addObject: AVCaptureDeviceTypeBuiltInTrueDepthCamera];
  123. auto discoverySession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes: deviceTypes.get()
  124. mediaType: AVMediaTypeVideo
  125. position: AVCaptureDevicePositionUnspecified];
  126. return [discoverySession devices];
  127. }
  128. #endif
  129. return [AVCaptureDevice devicesWithMediaType: AVMediaTypeVideo];
  130. }
  131. //==============================================================================
  132. static void printDebugCameraInfo (AVCaptureDevice* device)
  133. {
  134. auto position = device.position;
  135. String positionString = position == AVCaptureDevicePositionBack
  136. ? "Back"
  137. : position == AVCaptureDevicePositionFront
  138. ? "Front"
  139. : "Unspecified";
  140. JUCE_CAMERA_LOG ("Position: " + positionString);
  141. JUCE_CAMERA_LOG ("Model ID: " + nsStringToJuce (device.modelID));
  142. JUCE_CAMERA_LOG ("Localized name: " + nsStringToJuce (device.localizedName));
  143. JUCE_CAMERA_LOG ("Unique ID: " + nsStringToJuce (device.uniqueID));
  144. JUCE_CAMERA_LOG ("Lens aperture: " + String (device.lensAperture));
  145. JUCE_CAMERA_LOG ("Has flash: " + String ((int)device.hasFlash));
  146. JUCE_CAMERA_LOG ("Supports flash always on: " + String ((int)[device isFlashModeSupported: AVCaptureFlashModeOn]));
  147. JUCE_CAMERA_LOG ("Supports auto flash: " + String ((int)[device isFlashModeSupported: AVCaptureFlashModeAuto]));
  148. JUCE_CAMERA_LOG ("Has torch: " + String ((int)device.hasTorch));
  149. JUCE_CAMERA_LOG ("Supports torch always on: " + String ((int)[device isTorchModeSupported: AVCaptureTorchModeOn]));
  150. JUCE_CAMERA_LOG ("Supports auto torch: " + String ((int)[device isTorchModeSupported: AVCaptureTorchModeAuto]));
  151. JUCE_CAMERA_LOG ("Low light boost supported: " + String ((int)device.lowLightBoostEnabled));
  152. JUCE_CAMERA_LOG ("Supports auto white balance: " + String ((int)[device isWhiteBalanceModeSupported: AVCaptureWhiteBalanceModeAutoWhiteBalance]));
  153. JUCE_CAMERA_LOG ("Supports continuous auto white balance: " + String ((int)[device isWhiteBalanceModeSupported: AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance]));
  154. JUCE_CAMERA_LOG ("Supports auto focus: " + String ((int)[device isFocusModeSupported: AVCaptureFocusModeAutoFocus]));
  155. JUCE_CAMERA_LOG ("Supports continuous auto focus: " + String ((int)[device isFocusModeSupported: AVCaptureFocusModeContinuousAutoFocus]));
  156. JUCE_CAMERA_LOG ("Supports point of interest focus: " + String ((int)device.focusPointOfInterestSupported));
  157. JUCE_CAMERA_LOG ("Smooth auto focus supported: " + String ((int)device.smoothAutoFocusSupported));
  158. JUCE_CAMERA_LOG ("Auto focus range restriction supported: " + String ((int)device.autoFocusRangeRestrictionSupported));
  159. JUCE_CAMERA_LOG ("Supports auto exposure: " + String ((int)[device isExposureModeSupported: AVCaptureExposureModeAutoExpose]));
  160. JUCE_CAMERA_LOG ("Supports continuous auto exposure: " + String ((int)[device isExposureModeSupported: AVCaptureExposureModeContinuousAutoExposure]));
  161. JUCE_CAMERA_LOG ("Supports custom exposure: " + String ((int)[device isExposureModeSupported: AVCaptureExposureModeCustom]));
  162. JUCE_CAMERA_LOG ("Supports point of interest exposure: " + String ((int)device.exposurePointOfInterestSupported));
  163. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  164. if (iosVersion.major >= 10)
  165. {
  166. JUCE_CAMERA_LOG ("Device type: " + nsStringToJuce (device.deviceType));
  167. JUCE_CAMERA_LOG ("Locking focus with custom lens position supported: " + String ((int)device.lockingFocusWithCustomLensPositionSupported));
  168. }
  169. #endif
  170. #if defined (__IPHONE_11_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_11_0
  171. if (iosVersion.major >= 11)
  172. {
  173. JUCE_CAMERA_LOG ("Min available video zoom factor: " + String (device.minAvailableVideoZoomFactor));
  174. JUCE_CAMERA_LOG ("Max available video zoom factor: " + String (device.maxAvailableVideoZoomFactor));
  175. JUCE_CAMERA_LOG ("Dual camera switch over video zoom factor: " + String (device.dualCameraSwitchOverVideoZoomFactor));
  176. }
  177. #endif
  178. JUCE_CAMERA_LOG ("Capture formats start-------------------");
  179. for (AVCaptureDeviceFormat* format in device.formats)
  180. {
  181. JUCE_CAMERA_LOG ("Capture format start------");
  182. printDebugCameraFormatInfo (format);
  183. JUCE_CAMERA_LOG ("Capture format end------");
  184. }
  185. JUCE_CAMERA_LOG ("Capture formats end-------------------");
  186. }
  187. static void printDebugCameraFormatInfo (AVCaptureDeviceFormat* format)
  188. {
  189. JUCE_CAMERA_LOG ("Media type: " + nsStringToJuce (format.mediaType));
  190. String colourSpaces;
  191. for (NSNumber* number in format.supportedColorSpaces)
  192. {
  193. switch ([number intValue])
  194. {
  195. case AVCaptureColorSpace_sRGB: colourSpaces << "sRGB "; break;
  196. case AVCaptureColorSpace_P3_D65: colourSpaces << "P3_D65 "; break;
  197. default: break;
  198. }
  199. }
  200. JUCE_CAMERA_LOG ("Supported colour spaces: " + colourSpaces);
  201. JUCE_CAMERA_LOG ("Video field of view: " + String (format.videoFieldOfView));
  202. JUCE_CAMERA_LOG ("Video max zoom factor: " + String (format.videoMaxZoomFactor));
  203. JUCE_CAMERA_LOG ("Video zoom factor upscale threshold: " + String (format.videoZoomFactorUpscaleThreshold));
  204. String videoFrameRateRangesString = "Video supported frame rate ranges: ";
  205. for (AVFrameRateRange* range in format.videoSupportedFrameRateRanges)
  206. videoFrameRateRangesString << frameRateRangeToString (range);
  207. JUCE_CAMERA_LOG (videoFrameRateRangesString);
  208. JUCE_CAMERA_LOG ("Video binned: " + String (int (format.videoBinned)));
  209. JUCE_CAMERA_LOG ("Video HDR supported: " + String (int (format.videoHDRSupported)));
  210. JUCE_CAMERA_LOG ("High resolution still image dimensions: " + getHighResStillImgDimensionsString (format.highResolutionStillImageDimensions));
  211. JUCE_CAMERA_LOG ("Min ISO: " + String (format.minISO));
  212. JUCE_CAMERA_LOG ("Max ISO: " + String (format.maxISO));
  213. JUCE_CAMERA_LOG ("Min exposure duration: " + cmTimeToString (format.minExposureDuration));
  214. String autoFocusSystemString;
  215. switch (format.autoFocusSystem)
  216. {
  217. case AVCaptureAutoFocusSystemPhaseDetection: autoFocusSystemString = "PhaseDetection"; break;
  218. case AVCaptureAutoFocusSystemContrastDetection: autoFocusSystemString = "ContrastDetection"; break;
  219. case AVCaptureAutoFocusSystemNone:
  220. default: autoFocusSystemString = "None";
  221. }
  222. JUCE_CAMERA_LOG ("Auto focus system: " + autoFocusSystemString);
  223. JUCE_CAMERA_LOG ("Standard (iOS 5.0) video stabilization supported: " + String ((int) [format isVideoStabilizationModeSupported: AVCaptureVideoStabilizationModeStandard]));
  224. JUCE_CAMERA_LOG ("Cinematic video stabilization supported: " + String ((int) [format isVideoStabilizationModeSupported: AVCaptureVideoStabilizationModeCinematic]));
  225. JUCE_CAMERA_LOG ("Auto video stabilization supported: " + String ((int) [format isVideoStabilizationModeSupported: AVCaptureVideoStabilizationModeAuto]));
  226. #if defined (__IPHONE_11_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_11_0
  227. if (iosVersion.major >= 11)
  228. {
  229. JUCE_CAMERA_LOG ("Min zoom factor for depth data delivery: " + String (format.videoMinZoomFactorForDepthDataDelivery));
  230. JUCE_CAMERA_LOG ("Max zoom factor for depth data delivery: " + String (format.videoMaxZoomFactorForDepthDataDelivery));
  231. }
  232. #endif
  233. }
  234. static String getHighResStillImgDimensionsString (CMVideoDimensions d)
  235. {
  236. return "[" + String (d.width) + " " + String (d.height) + "]";
  237. }
  238. static String cmTimeToString (CMTime time)
  239. {
  240. CFUniquePtr<CFStringRef> timeDesc (CMTimeCopyDescription (nullptr, time));
  241. return String::fromCFString (timeDesc.get());
  242. }
  243. static String frameRateRangeToString (AVFrameRateRange* range)
  244. {
  245. String result;
  246. result << "[minFrameDuration: " + cmTimeToString (range.minFrameDuration);
  247. result << " maxFrameDuration: " + cmTimeToString (range.maxFrameDuration);
  248. result << " minFrameRate: " + String (range.minFrameRate);
  249. result << " maxFrameRate: " + String (range.maxFrameRate) << "] ";
  250. return result;
  251. }
  252. //==============================================================================
  253. class CaptureSession
  254. {
  255. public:
  256. CaptureSession (Pimpl& ownerToUse, bool useHighQuality)
  257. : owner (ownerToUse),
  258. captureSessionQueue (dispatch_queue_create ("JuceCameraDeviceBackgroundDispatchQueue", DISPATCH_QUEUE_SERIAL)),
  259. captureSession ([[AVCaptureSession alloc] init]),
  260. delegate (nullptr),
  261. stillPictureTaker (*this),
  262. videoRecorder (*this)
  263. {
  264. static SessionDelegateClass cls;
  265. delegate.reset ([cls.createInstance() init]);
  266. SessionDelegateClass::setOwner (delegate.get(), this);
  267. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  268. [[NSNotificationCenter defaultCenter] addObserver: delegate.get()
  269. selector: @selector (sessionDidStartRunning:)
  270. name: AVCaptureSessionDidStartRunningNotification
  271. object: captureSession.get()];
  272. [[NSNotificationCenter defaultCenter] addObserver: delegate.get()
  273. selector: @selector (sessionDidStopRunning:)
  274. name: AVCaptureSessionDidStopRunningNotification
  275. object: captureSession.get()];
  276. [[NSNotificationCenter defaultCenter] addObserver: delegate.get()
  277. selector: @selector (sessionRuntimeError:)
  278. name: AVCaptureSessionRuntimeErrorNotification
  279. object: captureSession.get()];
  280. [[NSNotificationCenter defaultCenter] addObserver: delegate.get()
  281. selector: @selector (sessionWasInterrupted:)
  282. name: AVCaptureSessionWasInterruptedNotification
  283. object: captureSession.get()];
  284. [[NSNotificationCenter defaultCenter] addObserver: delegate.get()
  285. selector: @selector (sessionInterruptionEnded:)
  286. name: AVCaptureSessionInterruptionEndedNotification
  287. object: captureSession.get()];
  288. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  289. dispatch_async (captureSessionQueue,^
  290. {
  291. [captureSession.get() setSessionPreset: useHighQuality ? AVCaptureSessionPresetHigh
  292. : AVCaptureSessionPresetMedium];
  293. });
  294. ++numCaptureSessions;
  295. }
  296. ~CaptureSession()
  297. {
  298. [[NSNotificationCenter defaultCenter] removeObserver: delegate.get()];
  299. stopRecording();
  300. if (--numCaptureSessions == 0)
  301. {
  302. dispatch_async (captureSessionQueue, ^
  303. {
  304. if (captureSession.get().running)
  305. [captureSession.get() stopRunning];
  306. sessionClosedEvent.signal();
  307. });
  308. sessionClosedEvent.wait (-1);
  309. }
  310. }
  311. bool openedOk() const noexcept { return sessionStarted; }
  312. void startSessionForDeviceWithId (const String& cameraIdToUse)
  313. {
  314. dispatch_async (captureSessionQueue,^
  315. {
  316. cameraDevice = [AVCaptureDevice deviceWithUniqueID: juceStringToNS (cameraIdToUse)];
  317. auto audioDevice = [AVCaptureDevice defaultDeviceWithMediaType: AVMediaTypeAudio];
  318. [captureSession.get() beginConfiguration];
  319. // This will add just video...
  320. auto error = addInputToDevice (cameraDevice);
  321. if (error.isNotEmpty())
  322. {
  323. WeakReference<CaptureSession> weakRef (this);
  324. MessageManager::callAsync ([weakRef, error]() mutable
  325. {
  326. if (weakRef != nullptr)
  327. weakRef->owner.cameraOpenCallback ({}, error);
  328. });
  329. return;
  330. }
  331. // ... so add audio explicitly here
  332. error = addInputToDevice (audioDevice);
  333. if (error.isNotEmpty())
  334. {
  335. WeakReference<CaptureSession> weakRef (this);
  336. MessageManager::callAsync ([weakRef, error]() mutable
  337. {
  338. if (weakRef != nullptr)
  339. weakRef->owner.cameraOpenCallback ({}, error);
  340. });
  341. return;
  342. }
  343. [captureSession.get() commitConfiguration];
  344. if (! captureSession.get().running)
  345. [captureSession.get() startRunning];
  346. });
  347. }
  348. AVCaptureVideoPreviewLayer* createPreviewLayer()
  349. {
  350. if (! openedOk())
  351. {
  352. // A session must be started first!
  353. jassertfalse;
  354. return nullptr;
  355. }
  356. previewLayer = [AVCaptureVideoPreviewLayer layerWithSession: captureSession.get()];
  357. return previewLayer;
  358. }
  359. void takeStillPicture()
  360. {
  361. if (! openedOk())
  362. {
  363. // A session must be started first!
  364. jassert (openedOk());
  365. return;
  366. }
  367. stillPictureTaker.takePicture (previewLayer.connection.videoOrientation);
  368. }
  369. void startRecording (const File& file)
  370. {
  371. if (! openedOk())
  372. {
  373. // A session must be started first!
  374. jassertfalse;
  375. return;
  376. }
  377. if (file.existsAsFile())
  378. {
  379. // File overwriting is not supported by iOS video recorder, the target
  380. // file must not exist.
  381. jassertfalse;
  382. return;
  383. }
  384. videoRecorder.startRecording (file, previewLayer.connection.videoOrientation);
  385. }
  386. void stopRecording()
  387. {
  388. videoRecorder.stopRecording();
  389. }
  390. Time getTimeOfFirstRecordedFrame() const
  391. {
  392. return videoRecorder.getTimeOfFirstRecordedFrame();
  393. }
  394. JUCE_DECLARE_WEAK_REFERENCEABLE (CaptureSession)
  395. private:
  396. String addInputToDevice (AVCaptureDevice* device)
  397. {
  398. NSError* error = nil;
  399. auto input = [AVCaptureDeviceInput deviceInputWithDevice: device
  400. error: &error];
  401. if (error != nil)
  402. return nsStringToJuce (error.localizedDescription);
  403. if (! [captureSession.get() canAddInput: input])
  404. return "Could not add input to camera session.";
  405. [captureSession.get() addInput: input];
  406. return {};
  407. }
  408. //==============================================================================
  409. struct SessionDelegateClass : public ObjCClass<NSObject>
  410. {
  411. SessionDelegateClass() : ObjCClass<NSObject> ("SessionDelegateClass_")
  412. {
  413. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  414. addMethod (@selector (sessionDidStartRunning:), started, "v@:@");
  415. addMethod (@selector (sessionDidStopRunning:), stopped, "v@:@");
  416. addMethod (@selector (sessionRuntimeError:), runtimeError, "v@:@");
  417. addMethod (@selector (sessionWasInterrupted:), interrupted, "v@:@");
  418. addMethod (@selector (sessionInterruptionEnded:), interruptionEnded, "v@:@");
  419. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  420. addIvar<CaptureSession*> ("owner");
  421. registerClass();
  422. }
  423. //==============================================================================
  424. static CaptureSession& getOwner (id self) { return *getIvar<CaptureSession*> (self, "owner"); }
  425. static void setOwner (id self, CaptureSession* s) { object_setInstanceVariable (self, "owner", s); }
  426. private:
  427. //==============================================================================
  428. static void started (id self, SEL, NSNotification* notification)
  429. {
  430. JUCE_CAMERA_LOG (nsStringToJuce ([notification description]));
  431. ignoreUnused (notification);
  432. dispatch_async (dispatch_get_main_queue(),
  433. ^{
  434. getOwner (self).cameraSessionStarted();
  435. });
  436. }
  437. static void stopped (id, SEL, NSNotification* notification)
  438. {
  439. JUCE_CAMERA_LOG (nsStringToJuce ([notification description]));
  440. ignoreUnused (notification);
  441. }
  442. static void runtimeError (id self, SEL, NSNotification* notification)
  443. {
  444. JUCE_CAMERA_LOG (nsStringToJuce ([notification description]));
  445. dispatch_async (dispatch_get_main_queue(),
  446. ^{
  447. NSError* error = notification.userInfo[AVCaptureSessionErrorKey];
  448. auto errorString = error != nil ? nsStringToJuce (error.localizedDescription) : String();
  449. getOwner (self).cameraSessionRuntimeError (errorString);
  450. });
  451. }
  452. static void interrupted (id, SEL, NSNotification* notification)
  453. {
  454. JUCE_CAMERA_LOG (nsStringToJuce ([notification description]));
  455. ignoreUnused (notification);
  456. }
  457. static void interruptionEnded (id, SEL, NSNotification* notification)
  458. {
  459. JUCE_CAMERA_LOG (nsStringToJuce ([notification description]));
  460. ignoreUnused (notification);
  461. }
  462. };
  463. //==============================================================================
  464. class StillPictureTaker
  465. {
  466. public:
  467. StillPictureTaker (CaptureSession& cs)
  468. : captureSession (cs),
  469. captureOutput (createCaptureOutput()),
  470. photoOutputDelegate (nullptr)
  471. {
  472. if (Pimpl::getIOSVersion().major >= 10)
  473. {
  474. static PhotoOutputDelegateClass cls;
  475. photoOutputDelegate.reset ([cls.createInstance() init]);
  476. PhotoOutputDelegateClass::setOwner (photoOutputDelegate.get(), this);
  477. }
  478. captureSession.addOutputIfPossible (captureOutput);
  479. }
  480. void takePicture (AVCaptureVideoOrientation orientationToUse)
  481. {
  482. if (takingPicture)
  483. {
  484. // Picture taking already in progress!
  485. jassertfalse;
  486. return;
  487. }
  488. takingPicture = true;
  489. printImageOutputDebugInfo (captureOutput);
  490. if (auto* connection = findVideoConnection (captureOutput))
  491. {
  492. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  493. if (Pimpl::getIOSVersion().major >= 10 && [captureOutput isKindOfClass: [AVCapturePhotoOutput class]])
  494. {
  495. auto* photoOutput = (AVCapturePhotoOutput*) captureOutput;
  496. auto outputConnection = [photoOutput connectionWithMediaType: AVMediaTypeVideo];
  497. outputConnection.videoOrientation = orientationToUse;
  498. [photoOutput capturePhotoWithSettings: [AVCapturePhotoSettings photoSettings]
  499. delegate: id<AVCapturePhotoCaptureDelegate> (photoOutputDelegate.get())];
  500. return;
  501. }
  502. #endif
  503. auto* stillImageOutput = (AVCaptureStillImageOutput*) captureOutput;
  504. auto outputConnection = [stillImageOutput connectionWithMediaType: AVMediaTypeVideo];
  505. outputConnection.videoOrientation = orientationToUse;
  506. [stillImageOutput captureStillImageAsynchronouslyFromConnection: connection completionHandler:
  507. ^(CMSampleBufferRef imageSampleBuffer, NSError* error)
  508. {
  509. takingPicture = false;
  510. if (error != nil)
  511. {
  512. JUCE_CAMERA_LOG ("Still picture capture failed, error: " + nsStringToJuce (error.localizedDescription));
  513. jassertfalse;
  514. return;
  515. }
  516. NSData* imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation: imageSampleBuffer];
  517. auto image = ImageFileFormat::loadFrom (imageData.bytes, (size_t) imageData.length);
  518. callListeners (image);
  519. MessageManager::callAsync ([this, image] { notifyPictureTaken (image); });
  520. }];
  521. }
  522. else
  523. {
  524. // Could not find a connection of video type
  525. jassertfalse;
  526. }
  527. }
  528. private:
  529. static AVCaptureOutput* createCaptureOutput()
  530. {
  531. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  532. if (Pimpl::getIOSVersion().major >= 10)
  533. return [AVCapturePhotoOutput new];
  534. #endif
  535. return [AVCaptureStillImageOutput new];
  536. }
  537. static void printImageOutputDebugInfo (AVCaptureOutput* captureOutput)
  538. {
  539. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  540. if (Pimpl::getIOSVersion().major >= 10 && [captureOutput isKindOfClass: [AVCapturePhotoOutput class]])
  541. {
  542. auto* photoOutput = (AVCapturePhotoOutput*) captureOutput;
  543. String typesString;
  544. for (AVVideoCodecType type in photoOutput.availablePhotoCodecTypes)
  545. typesString << nsStringToJuce (type) << " ";
  546. JUCE_CAMERA_LOG ("Available image codec types: " + typesString);
  547. JUCE_CAMERA_LOG ("Still image stabilization supported: " + String ((int) photoOutput.stillImageStabilizationSupported));
  548. JUCE_CAMERA_LOG ("Dual camera fusion supported: " + String ((int) photoOutput.dualCameraFusionSupported));
  549. JUCE_CAMERA_LOG ("Supports flash: " + String ((int) [photoOutput.supportedFlashModes containsObject: @(AVCaptureFlashModeOn)]));
  550. JUCE_CAMERA_LOG ("Supports auto flash: " + String ((int) [photoOutput.supportedFlashModes containsObject: @(AVCaptureFlashModeAuto)]));
  551. JUCE_CAMERA_LOG ("Max bracketed photo count: " + String (photoOutput.maxBracketedCapturePhotoCount));
  552. JUCE_CAMERA_LOG ("Lens stabilization during bracketed capture supported: " + String ((int) photoOutput.lensStabilizationDuringBracketedCaptureSupported));
  553. JUCE_CAMERA_LOG ("Live photo capture supported: " + String ((int) photoOutput.livePhotoCaptureSupported));
  554. #if defined (__IPHONE_11_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_11_0
  555. if (Pimpl::getIOSVersion().major >= 11)
  556. {
  557. typesString.clear();
  558. for (AVFileType type in photoOutput.availablePhotoFileTypes)
  559. typesString << nsStringToJuce (type) << " ";
  560. JUCE_CAMERA_LOG ("Available photo file types: " + typesString);
  561. typesString.clear();
  562. for (AVFileType type in photoOutput.availableRawPhotoFileTypes)
  563. typesString << nsStringToJuce (type) << " ";
  564. JUCE_CAMERA_LOG ("Available RAW photo file types: " + typesString);
  565. typesString.clear();
  566. for (AVFileType type in photoOutput.availableLivePhotoVideoCodecTypes)
  567. typesString << nsStringToJuce (type) << " ";
  568. JUCE_CAMERA_LOG ("Available live photo video codec types: " + typesString);
  569. JUCE_CAMERA_LOG ("Dual camera dual photo delivery supported: " + String ((int) photoOutput.dualCameraDualPhotoDeliverySupported));
  570. JUCE_CAMERA_LOG ("Camera calibration data delivery supported: " + String ((int) photoOutput.cameraCalibrationDataDeliverySupported));
  571. JUCE_CAMERA_LOG ("Depth data delivery supported: " + String ((int) photoOutput.depthDataDeliverySupported));
  572. }
  573. #endif
  574. return;
  575. }
  576. #endif
  577. auto* stillImageOutput = (AVCaptureStillImageOutput*) captureOutput;
  578. String typesString;
  579. for (AVVideoCodecType type in stillImageOutput.availableImageDataCodecTypes)
  580. typesString << nsStringToJuce (type) << " ";
  581. JUCE_CAMERA_LOG ("Available image codec types: " + typesString);
  582. JUCE_CAMERA_LOG ("Still image stabilization supported: " + String ((int) stillImageOutput.stillImageStabilizationSupported));
  583. JUCE_CAMERA_LOG ("Automatically enables still image stabilization when available: " + String ((int) stillImageOutput.automaticallyEnablesStillImageStabilizationWhenAvailable));
  584. JUCE_CAMERA_LOG ("Output settings for image output: " + nsStringToJuce ([stillImageOutput.outputSettings description]));
  585. }
  586. //==============================================================================
  587. static AVCaptureConnection* findVideoConnection (AVCaptureOutput* output)
  588. {
  589. for (AVCaptureConnection* connection in output.connections)
  590. for (AVCaptureInputPort* port in connection.inputPorts)
  591. if ([port.mediaType isEqual: AVMediaTypeVideo])
  592. return connection;
  593. return nullptr;
  594. }
  595. //==============================================================================
  596. class PhotoOutputDelegateClass : public ObjCClass<NSObject>
  597. {
  598. public:
  599. PhotoOutputDelegateClass() : ObjCClass<NSObject> ("PhotoOutputDelegateClass_")
  600. {
  601. addMethod (@selector (captureOutput:willBeginCaptureForResolvedSettings:), willBeginCaptureForSettings, "v@:@@");
  602. addMethod (@selector (captureOutput:willCapturePhotoForResolvedSettings:), willCaptureForSettings, "v@:@@");
  603. addMethod (@selector (captureOutput:didCapturePhotoForResolvedSettings:), didCaptureForSettings, "v@:@@");
  604. addMethod (@selector (captureOutput:didFinishCaptureForResolvedSettings:error:), didFinishCaptureForSettings, "v@:@@@");
  605. if (Pimpl::getIOSVersion().major >= 11)
  606. addMethod (@selector (captureOutput:didFinishProcessingPhoto:error:), didFinishProcessingPhoto, "v@:@@@");
  607. else
  608. addMethod (@selector (captureOutput:didFinishProcessingPhotoSampleBuffer:previewPhotoSampleBuffer:resolvedSettings:bracketSettings:error:), didFinishProcessingPhotoSampleBuffer, "v@:@@@@@@");
  609. addIvar<StillPictureTaker*> ("owner");
  610. registerClass();
  611. }
  612. //==============================================================================
  613. static StillPictureTaker& getOwner (id self) { return *getIvar<StillPictureTaker*> (self, "owner"); }
  614. static void setOwner (id self, StillPictureTaker* t) { object_setInstanceVariable (self, "owner", t); }
  615. private:
  616. static void willBeginCaptureForSettings (id, SEL, AVCapturePhotoOutput*, AVCaptureResolvedPhotoSettings*)
  617. {
  618. JUCE_CAMERA_LOG ("willBeginCaptureForSettings()");
  619. }
  620. static void willCaptureForSettings (id, SEL, AVCapturePhotoOutput*, AVCaptureResolvedPhotoSettings*)
  621. {
  622. JUCE_CAMERA_LOG ("willCaptureForSettings()");
  623. }
  624. static void didCaptureForSettings (id, SEL, AVCapturePhotoOutput*, AVCaptureResolvedPhotoSettings*)
  625. {
  626. JUCE_CAMERA_LOG ("didCaptureForSettings()");
  627. }
  628. static void didFinishCaptureForSettings (id, SEL, AVCapturePhotoOutput*, AVCaptureResolvedPhotoSettings*, NSError* error)
  629. {
  630. String errorString = error != nil ? nsStringToJuce (error.localizedDescription) : String();
  631. ignoreUnused (errorString);
  632. JUCE_CAMERA_LOG ("didFinishCaptureForSettings(), error = " + errorString);
  633. }
  634. static void didFinishProcessingPhoto (id self, SEL, AVCapturePhotoOutput*, AVCapturePhoto* capturePhoto, NSError* error)
  635. {
  636. getOwner (self).takingPicture = false;
  637. String errorString = error != nil ? nsStringToJuce (error.localizedDescription) : String();
  638. ignoreUnused (errorString);
  639. JUCE_CAMERA_LOG ("didFinishProcessingPhoto(), error = " + errorString);
  640. if (error != nil)
  641. {
  642. JUCE_CAMERA_LOG ("Still picture capture failed, error: " + nsStringToJuce (error.localizedDescription));
  643. jassertfalse;
  644. return;
  645. }
  646. auto* imageOrientation = (NSNumber *) capturePhoto.metadata[(NSString*) kCGImagePropertyOrientation];
  647. auto* uiImage = getImageWithCorrectOrientation ((CGImagePropertyOrientation) imageOrientation.unsignedIntValue,
  648. [capturePhoto CGImageRepresentation]);
  649. auto* imageData = UIImageJPEGRepresentation (uiImage, 0.f);
  650. auto image = ImageFileFormat::loadFrom (imageData.bytes, (size_t) imageData.length);
  651. getOwner (self).callListeners (image);
  652. MessageManager::callAsync ([self, image]() { getOwner (self).notifyPictureTaken (image); });
  653. }
  654. static UIImage* getImageWithCorrectOrientation (CGImagePropertyOrientation imageOrientation,
  655. CGImageRef imageData)
  656. {
  657. auto origWidth = CGImageGetWidth (imageData);
  658. auto origHeight = CGImageGetHeight (imageData);
  659. auto targetSize = getTargetImageDimensionFor (imageOrientation, imageData);
  660. UIGraphicsBeginImageContext (targetSize);
  661. CGContextRef context = UIGraphicsGetCurrentContext();
  662. switch (imageOrientation)
  663. {
  664. case kCGImagePropertyOrientationUp:
  665. CGContextScaleCTM (context, 1.0, -1.0);
  666. CGContextTranslateCTM (context, 0.0, -targetSize.height);
  667. break;
  668. case kCGImagePropertyOrientationRight:
  669. CGContextRotateCTM (context, 90 * MathConstants<CGFloat>::pi / 180);
  670. CGContextScaleCTM (context, targetSize.height / origHeight, -targetSize.width / origWidth);
  671. break;
  672. case kCGImagePropertyOrientationDown:
  673. CGContextTranslateCTM (context, targetSize.width, 0.0);
  674. CGContextScaleCTM (context, -1.0, 1.0);
  675. break;
  676. case kCGImagePropertyOrientationLeft:
  677. CGContextRotateCTM (context, -90 * MathConstants<CGFloat>::pi / 180);
  678. CGContextScaleCTM (context, targetSize.height / origHeight, -targetSize.width / origWidth);
  679. CGContextTranslateCTM (context, -targetSize.width, -targetSize.height);
  680. break;
  681. case kCGImagePropertyOrientationUpMirrored:
  682. case kCGImagePropertyOrientationDownMirrored:
  683. case kCGImagePropertyOrientationLeftMirrored:
  684. case kCGImagePropertyOrientationRightMirrored:
  685. default:
  686. // Not implemented.
  687. jassertfalse;
  688. break;
  689. }
  690. CGContextDrawImage (context, CGRectMake (0, 0, targetSize.width, targetSize.height), imageData);
  691. UIImage* correctedImage = UIGraphicsGetImageFromCurrentImageContext();
  692. UIGraphicsEndImageContext();
  693. return correctedImage;
  694. }
  695. static CGSize getTargetImageDimensionFor (CGImagePropertyOrientation imageOrientation,
  696. CGImageRef imageData)
  697. {
  698. auto width = CGImageGetWidth (imageData);
  699. auto height = CGImageGetHeight (imageData);
  700. switch (imageOrientation)
  701. {
  702. case kCGImagePropertyOrientationUp:
  703. case kCGImagePropertyOrientationUpMirrored:
  704. case kCGImagePropertyOrientationDown:
  705. case kCGImagePropertyOrientationDownMirrored:
  706. return CGSizeMake ((CGFloat) width, (CGFloat) height);
  707. case kCGImagePropertyOrientationRight:
  708. case kCGImagePropertyOrientationRightMirrored:
  709. case kCGImagePropertyOrientationLeft:
  710. case kCGImagePropertyOrientationLeftMirrored:
  711. return CGSizeMake ((CGFloat) height, (CGFloat) width);
  712. }
  713. jassertfalse;
  714. return CGSizeMake ((CGFloat) width, (CGFloat) height);
  715. }
  716. static void didFinishProcessingPhotoSampleBuffer (id self, SEL, AVCapturePhotoOutput*,
  717. CMSampleBufferRef imageBuffer, CMSampleBufferRef imagePreviewBuffer,
  718. AVCaptureResolvedPhotoSettings*, AVCaptureBracketedStillImageSettings*,
  719. NSError* error)
  720. {
  721. getOwner (self).takingPicture = false;
  722. String errorString = error != nil ? nsStringToJuce (error.localizedDescription) : String();
  723. ignoreUnused (errorString);
  724. JUCE_CAMERA_LOG ("didFinishProcessingPhotoSampleBuffer(), error = " + errorString);
  725. if (error != nil)
  726. {
  727. JUCE_CAMERA_LOG ("Still picture capture failed, error: " + nsStringToJuce (error.localizedDescription));
  728. jassertfalse;
  729. return;
  730. }
  731. NSData* origImageData = [AVCapturePhotoOutput JPEGPhotoDataRepresentationForJPEGSampleBuffer: imageBuffer previewPhotoSampleBuffer: imagePreviewBuffer];
  732. auto origImage = [UIImage imageWithData: origImageData];
  733. auto imageOrientation = uiImageOrientationToCGImageOrientation (origImage.imageOrientation);
  734. auto* uiImage = getImageWithCorrectOrientation (imageOrientation, origImage.CGImage);
  735. auto* imageData = UIImageJPEGRepresentation (uiImage, 0.f);
  736. auto image = ImageFileFormat::loadFrom (imageData.bytes, (size_t) imageData.length);
  737. getOwner (self).callListeners (image);
  738. MessageManager::callAsync ([self, image]() { getOwner (self).notifyPictureTaken (image); });
  739. }
  740. static CGImagePropertyOrientation uiImageOrientationToCGImageOrientation (UIImageOrientation orientation)
  741. {
  742. switch (orientation)
  743. {
  744. case UIImageOrientationUp: return kCGImagePropertyOrientationUp;
  745. case UIImageOrientationDown: return kCGImagePropertyOrientationDown;
  746. case UIImageOrientationLeft: return kCGImagePropertyOrientationLeft;
  747. case UIImageOrientationRight: return kCGImagePropertyOrientationRight;
  748. case UIImageOrientationUpMirrored: return kCGImagePropertyOrientationUpMirrored;
  749. case UIImageOrientationDownMirrored: return kCGImagePropertyOrientationDownMirrored;
  750. case UIImageOrientationLeftMirrored: return kCGImagePropertyOrientationLeftMirrored;
  751. case UIImageOrientationRightMirrored: return kCGImagePropertyOrientationRightMirrored;
  752. }
  753. }
  754. };
  755. //==============================================================================
  756. void callListeners (const Image& image)
  757. {
  758. captureSession.callListeners (image);
  759. }
  760. void notifyPictureTaken (const Image& image)
  761. {
  762. captureSession.notifyPictureTaken (image);
  763. }
  764. CaptureSession& captureSession;
  765. AVCaptureOutput* captureOutput;
  766. std::unique_ptr<NSObject, NSObjectDeleter> photoOutputDelegate;
  767. bool takingPicture = false;
  768. };
  769. //==============================================================================
  770. // NB: FileOutputRecordingDelegateClass callbacks can be called from any thread (incl.
  771. // the message thread), so waiting for an event when stopping recording is not an
  772. // option and VideoRecorder must be alive at all times in order to get stopped
  773. // recording callback.
  774. class VideoRecorder
  775. {
  776. public:
  777. VideoRecorder (CaptureSession& session)
  778. : movieFileOutput ([AVCaptureMovieFileOutput new]),
  779. delegate (nullptr)
  780. {
  781. static FileOutputRecordingDelegateClass cls;
  782. delegate.reset ([cls.createInstance() init]);
  783. FileOutputRecordingDelegateClass::setOwner (delegate.get(), this);
  784. session.addOutputIfPossible (movieFileOutput);
  785. }
  786. ~VideoRecorder()
  787. {
  788. stopRecording();
  789. // Shutting down a device while recording will stop the recording
  790. // abruptly and the recording will be lost.
  791. jassert (! recordingInProgress);
  792. }
  793. void startRecording (const File& file, AVCaptureVideoOrientation orientationToUse)
  794. {
  795. if (Pimpl::getIOSVersion().major >= 10)
  796. printVideoOutputDebugInfo (movieFileOutput);
  797. auto url = [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())
  798. isDirectory: NO];
  799. auto outputConnection = [movieFileOutput connectionWithMediaType: AVMediaTypeVideo];
  800. outputConnection.videoOrientation = orientationToUse;
  801. [movieFileOutput startRecordingToOutputFileURL: url recordingDelegate: delegate.get()];
  802. }
  803. void stopRecording()
  804. {
  805. [movieFileOutput stopRecording];
  806. }
  807. Time getTimeOfFirstRecordedFrame() const
  808. {
  809. return Time (firstRecordedFrameTimeMs.get());
  810. }
  811. private:
  812. static void printVideoOutputDebugInfo (AVCaptureMovieFileOutput* output)
  813. {
  814. ignoreUnused (output);
  815. JUCE_CAMERA_LOG ("Available video codec types:");
  816. #if JUCE_CAMERA_LOG_ENABLED
  817. for (AVVideoCodecType type in output.availableVideoCodecTypes)
  818. JUCE_CAMERA_LOG (nsStringToJuce (type));
  819. #endif
  820. JUCE_CAMERA_LOG ("Output settings per video connection:");
  821. #if JUCE_CAMERA_LOG_ENABLED
  822. for (AVCaptureConnection* connection in output.connections)
  823. JUCE_CAMERA_LOG (nsStringToJuce ([[output outputSettingsForConnection: connection] description]));
  824. #endif
  825. }
  826. //==============================================================================
  827. struct FileOutputRecordingDelegateClass : public ObjCClass<NSObject<AVCaptureFileOutputRecordingDelegate>>
  828. {
  829. FileOutputRecordingDelegateClass() : ObjCClass<NSObject<AVCaptureFileOutputRecordingDelegate>> ("FileOutputRecordingDelegateClass_")
  830. {
  831. addMethod (@selector (captureOutput:didStartRecordingToOutputFileAtURL:fromConnections:), started, "v@:@@@");
  832. addMethod (@selector (captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:), stopped, "v@:@@@@");
  833. addIvar<VideoRecorder*> ("owner");
  834. registerClass();
  835. }
  836. //==============================================================================
  837. static VideoRecorder& getOwner (id self) { return *getIvar<VideoRecorder*> (self, "owner"); }
  838. static void setOwner (id self, VideoRecorder* r) { object_setInstanceVariable (self, "owner", r); }
  839. private:
  840. static void started (id self, SEL, AVCaptureFileOutput*, NSURL*, NSArray<AVCaptureConnection*>*)
  841. {
  842. JUCE_CAMERA_LOG ("Started recording");
  843. getOwner (self).firstRecordedFrameTimeMs.set (Time::getCurrentTime().toMilliseconds());
  844. getOwner (self).recordingInProgress = true;
  845. }
  846. static void stopped (id self, SEL, AVCaptureFileOutput*, NSURL*, NSArray<AVCaptureConnection*>*, NSError* error)
  847. {
  848. String errorString;
  849. bool recordingPlayable = true;
  850. // There might have been an error in the recording, yet there may be a playable file...
  851. if ([error code] != noErr)
  852. {
  853. id value = [[error userInfo] objectForKey: AVErrorRecordingSuccessfullyFinishedKey];
  854. if (value != nil && ! [value boolValue])
  855. recordingPlayable = false;
  856. errorString = nsStringToJuce (error.localizedDescription) + ", playable: " + String ((int) recordingPlayable);
  857. }
  858. JUCE_CAMERA_LOG ("Stopped recording, error = " + errorString);
  859. getOwner (self).recordingInProgress = false;
  860. }
  861. };
  862. AVCaptureMovieFileOutput* movieFileOutput;
  863. std::unique_ptr<NSObject<AVCaptureFileOutputRecordingDelegate>, NSObjectDeleter> delegate;
  864. bool recordingInProgress = false;
  865. Atomic<int64> firstRecordedFrameTimeMs { 0 };
  866. };
  867. //==============================================================================
  868. void addOutputIfPossible (AVCaptureOutput* output)
  869. {
  870. dispatch_async (captureSessionQueue,^
  871. {
  872. if ([captureSession.get() canAddOutput: output])
  873. {
  874. [captureSession.get() beginConfiguration];
  875. [captureSession.get() addOutput: output];
  876. [captureSession.get() commitConfiguration];
  877. return;
  878. }
  879. // Can't add output to camera session!
  880. jassertfalse;
  881. });
  882. }
  883. //==============================================================================
  884. void cameraSessionStarted()
  885. {
  886. sessionStarted = true;
  887. owner.cameraSessionStarted();
  888. }
  889. void cameraSessionRuntimeError (const String& error)
  890. {
  891. owner.cameraSessionRuntimeError (error);
  892. }
  893. void callListeners (const Image& image)
  894. {
  895. owner.callListeners (image);
  896. }
  897. void notifyPictureTaken (const Image& image)
  898. {
  899. owner.notifyPictureTaken (image);
  900. }
  901. Pimpl& owner;
  902. dispatch_queue_t captureSessionQueue;
  903. std::unique_ptr<AVCaptureSession, NSObjectDeleter> captureSession;
  904. std::unique_ptr<NSObject, NSObjectDeleter> delegate;
  905. StillPictureTaker stillPictureTaker;
  906. VideoRecorder videoRecorder;
  907. AVCaptureDevice* cameraDevice = nil;
  908. AVCaptureVideoPreviewLayer* previewLayer = nil;
  909. bool sessionStarted = false;
  910. WaitableEvent sessionClosedEvent;
  911. static int numCaptureSessions;
  912. };
  913. //==============================================================================
  914. void cameraSessionStarted()
  915. {
  916. JUCE_CAMERA_LOG ("cameraSessionStarted()");
  917. cameraOpenCallback (cameraId, {});
  918. }
  919. void cameraSessionRuntimeError (const String& error)
  920. {
  921. JUCE_CAMERA_LOG ("cameraSessionRuntimeError(), error = " + error);
  922. if (! notifiedOfCameraOpening)
  923. {
  924. cameraOpenCallback ({}, error);
  925. }
  926. else
  927. {
  928. if (owner.onErrorOccurred != nullptr)
  929. owner.onErrorOccurred (error);
  930. }
  931. }
  932. void callListeners (const Image& image)
  933. {
  934. const ScopedLock sl (listenerLock);
  935. listeners.call ([=] (Listener& l) { l.imageReceived (image); });
  936. if (listeners.size() == 1)
  937. triggerStillPictureCapture();
  938. }
  939. void notifyPictureTaken (const Image& image)
  940. {
  941. JUCE_CAMERA_LOG ("notifyPictureTaken()");
  942. if (pictureTakenCallback != nullptr)
  943. pictureTakenCallback (image);
  944. }
  945. //==============================================================================
  946. void triggerStillPictureCapture()
  947. {
  948. captureSession.takeStillPicture();
  949. }
  950. //==============================================================================
  951. CameraDevice& owner;
  952. String cameraId;
  953. InternalOpenCameraResultCallback cameraOpenCallback;
  954. CriticalSection listenerLock;
  955. ListenerList<Listener> listeners;
  956. std::function<void (const Image&)> pictureTakenCallback;
  957. CaptureSession captureSession;
  958. bool notifiedOfCameraOpening = false;
  959. //==============================================================================
  960. struct IOSVersion
  961. {
  962. int major;
  963. int minor;
  964. };
  965. static IOSVersion getIOSVersion()
  966. {
  967. auto processInfo = [NSProcessInfo processInfo];
  968. if (! [processInfo respondsToSelector: @selector (operatingSystemVersion)])
  969. return {7, 0}; // Below 8.0 in fact, but only care that it's below 8
  970. return { (int)[processInfo operatingSystemVersion].majorVersion,
  971. (int)[processInfo operatingSystemVersion].minorVersion };
  972. }
  973. static IOSVersion iosVersion;
  974. friend struct CameraDevice::ViewerComponent;
  975. JUCE_DECLARE_NON_COPYABLE (Pimpl)
  976. };
  977. CameraDevice::Pimpl::IOSVersion CameraDevice::Pimpl::iosVersion = CameraDevice::Pimpl::getIOSVersion();
  978. int CameraDevice::Pimpl::CaptureSession::numCaptureSessions = 0;
  979. //==============================================================================
  980. struct CameraDevice::ViewerComponent : public UIViewComponent
  981. {
  982. //==============================================================================
  983. struct JuceCameraDeviceViewerClass : public ObjCClass<UIView>
  984. {
  985. JuceCameraDeviceViewerClass() : ObjCClass<UIView> ("JuceCameraDeviceViewerClass_")
  986. {
  987. addMethod (@selector (layoutSubviews), layoutSubviews, "v@:");
  988. registerClass();
  989. }
  990. private:
  991. static void layoutSubviews (id self, SEL)
  992. {
  993. sendSuperclassMessage<void> (self, @selector (layoutSubviews));
  994. UIView* asUIView = (UIView*) self;
  995. updateOrientation (self);
  996. if (auto* previewLayer = getPreviewLayer (self))
  997. previewLayer.frame = asUIView.bounds;
  998. }
  999. static AVCaptureVideoPreviewLayer* getPreviewLayer (id self)
  1000. {
  1001. UIView* asUIView = (UIView*) self;
  1002. if (asUIView.layer.sublayers != nil && [asUIView.layer.sublayers count] > 0)
  1003. if ([asUIView.layer.sublayers[0] isKindOfClass: [AVCaptureVideoPreviewLayer class]])
  1004. return (AVCaptureVideoPreviewLayer*) asUIView.layer.sublayers[0];
  1005. return nil;
  1006. }
  1007. static void updateOrientation (id self)
  1008. {
  1009. if (auto* previewLayer = getPreviewLayer (self))
  1010. {
  1011. UIDeviceOrientation o = [UIDevice currentDevice].orientation;
  1012. if (UIDeviceOrientationIsPortrait (o) || UIDeviceOrientationIsLandscape (o))
  1013. {
  1014. if (previewLayer.connection != nil)
  1015. previewLayer.connection.videoOrientation = (AVCaptureVideoOrientation) o;
  1016. }
  1017. }
  1018. }
  1019. };
  1020. ViewerComponent (CameraDevice& device)
  1021. {
  1022. static JuceCameraDeviceViewerClass cls;
  1023. // Initial size that can be overriden later.
  1024. setSize (640, 480);
  1025. auto view = [cls.createInstance() init];
  1026. setView (view);
  1027. auto* previewLayer = device.pimpl->captureSession.createPreviewLayer();
  1028. previewLayer.frame = view.bounds;
  1029. UIInterfaceOrientation statusBarOrientation = [UIApplication sharedApplication].statusBarOrientation;
  1030. AVCaptureVideoOrientation videoOrientation = statusBarOrientation != UIInterfaceOrientationUnknown
  1031. ? (AVCaptureVideoOrientation) statusBarOrientation
  1032. : AVCaptureVideoOrientationPortrait;
  1033. previewLayer.connection.videoOrientation = videoOrientation;
  1034. [view.layer addSublayer: previewLayer];
  1035. }
  1036. };
  1037. //==============================================================================
  1038. String CameraDevice::getFileExtension()
  1039. {
  1040. return ".mov";
  1041. }
  1042. #if JUCE_DEPRECATION_IGNORED
  1043. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  1044. #endif