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.

1338 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. MessageManager::callAsync ([weakRef = WeakReference<CaptureSession> { this }, error]() mutable
  324. {
  325. if (weakRef != nullptr)
  326. weakRef->owner.cameraOpenCallback ({}, error);
  327. });
  328. return;
  329. }
  330. // ... so add audio explicitly here
  331. error = addInputToDevice (audioDevice);
  332. if (error.isNotEmpty())
  333. {
  334. MessageManager::callAsync ([weakRef = WeakReference<CaptureSession> { this }, error]() mutable
  335. {
  336. if (weakRef != nullptr)
  337. weakRef->owner.cameraOpenCallback ({}, error);
  338. });
  339. return;
  340. }
  341. [captureSession.get() commitConfiguration];
  342. if (! captureSession.get().running)
  343. [captureSession.get() startRunning];
  344. });
  345. }
  346. AVCaptureVideoPreviewLayer* createPreviewLayer()
  347. {
  348. if (! openedOk())
  349. {
  350. // A session must be started first!
  351. jassertfalse;
  352. return nullptr;
  353. }
  354. previewLayer = [AVCaptureVideoPreviewLayer layerWithSession: captureSession.get()];
  355. return previewLayer;
  356. }
  357. void takeStillPicture()
  358. {
  359. if (! openedOk())
  360. {
  361. // A session must be started first!
  362. jassert (openedOk());
  363. return;
  364. }
  365. stillPictureTaker.takePicture (previewLayer.connection.videoOrientation);
  366. }
  367. void startRecording (const File& file)
  368. {
  369. if (! openedOk())
  370. {
  371. // A session must be started first!
  372. jassertfalse;
  373. return;
  374. }
  375. if (file.existsAsFile())
  376. {
  377. // File overwriting is not supported by iOS video recorder, the target
  378. // file must not exist.
  379. jassertfalse;
  380. return;
  381. }
  382. videoRecorder.startRecording (file, previewLayer.connection.videoOrientation);
  383. }
  384. void stopRecording()
  385. {
  386. videoRecorder.stopRecording();
  387. }
  388. Time getTimeOfFirstRecordedFrame() const
  389. {
  390. return videoRecorder.getTimeOfFirstRecordedFrame();
  391. }
  392. JUCE_DECLARE_WEAK_REFERENCEABLE (CaptureSession)
  393. private:
  394. String addInputToDevice (AVCaptureDevice* device)
  395. {
  396. NSError* error = nil;
  397. auto input = [AVCaptureDeviceInput deviceInputWithDevice: device
  398. error: &error];
  399. if (error != nil)
  400. return nsStringToJuce (error.localizedDescription);
  401. if (! [captureSession.get() canAddInput: input])
  402. return "Could not add input to camera session.";
  403. [captureSession.get() addInput: input];
  404. return {};
  405. }
  406. //==============================================================================
  407. struct SessionDelegateClass : public ObjCClass<NSObject>
  408. {
  409. SessionDelegateClass() : ObjCClass<NSObject> ("SessionDelegateClass_")
  410. {
  411. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  412. addMethod (@selector (sessionDidStartRunning:), started, "v@:@");
  413. addMethod (@selector (sessionDidStopRunning:), stopped, "v@:@");
  414. addMethod (@selector (sessionRuntimeError:), runtimeError, "v@:@");
  415. addMethod (@selector (sessionWasInterrupted:), interrupted, "v@:@");
  416. addMethod (@selector (sessionInterruptionEnded:), interruptionEnded, "v@:@");
  417. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  418. addIvar<CaptureSession*> ("owner");
  419. registerClass();
  420. }
  421. //==============================================================================
  422. static CaptureSession& getOwner (id self) { return *getIvar<CaptureSession*> (self, "owner"); }
  423. static void setOwner (id self, CaptureSession* s) { object_setInstanceVariable (self, "owner", s); }
  424. private:
  425. //==============================================================================
  426. static void started (id self, SEL, NSNotification* notification)
  427. {
  428. JUCE_CAMERA_LOG (nsStringToJuce ([notification description]));
  429. ignoreUnused (notification);
  430. dispatch_async (dispatch_get_main_queue(),
  431. ^{
  432. getOwner (self).cameraSessionStarted();
  433. });
  434. }
  435. static void stopped (id, SEL, NSNotification* notification)
  436. {
  437. JUCE_CAMERA_LOG (nsStringToJuce ([notification description]));
  438. ignoreUnused (notification);
  439. }
  440. static void runtimeError (id self, SEL, NSNotification* notification)
  441. {
  442. JUCE_CAMERA_LOG (nsStringToJuce ([notification description]));
  443. dispatch_async (dispatch_get_main_queue(),
  444. ^{
  445. NSError* error = notification.userInfo[AVCaptureSessionErrorKey];
  446. auto errorString = error != nil ? nsStringToJuce (error.localizedDescription) : String();
  447. getOwner (self).cameraSessionRuntimeError (errorString);
  448. });
  449. }
  450. static void interrupted (id, SEL, NSNotification* notification)
  451. {
  452. JUCE_CAMERA_LOG (nsStringToJuce ([notification description]));
  453. ignoreUnused (notification);
  454. }
  455. static void interruptionEnded (id, SEL, NSNotification* notification)
  456. {
  457. JUCE_CAMERA_LOG (nsStringToJuce ([notification description]));
  458. ignoreUnused (notification);
  459. }
  460. };
  461. //==============================================================================
  462. class StillPictureTaker
  463. {
  464. public:
  465. StillPictureTaker (CaptureSession& cs)
  466. : captureSession (cs),
  467. captureOutput (createCaptureOutput()),
  468. photoOutputDelegate (nullptr)
  469. {
  470. if (Pimpl::getIOSVersion().major >= 10)
  471. {
  472. static PhotoOutputDelegateClass cls;
  473. photoOutputDelegate.reset ([cls.createInstance() init]);
  474. PhotoOutputDelegateClass::setOwner (photoOutputDelegate.get(), this);
  475. }
  476. captureSession.addOutputIfPossible (captureOutput);
  477. }
  478. void takePicture (AVCaptureVideoOrientation orientationToUse)
  479. {
  480. if (takingPicture)
  481. {
  482. // Picture taking already in progress!
  483. jassertfalse;
  484. return;
  485. }
  486. takingPicture = true;
  487. printImageOutputDebugInfo (captureOutput);
  488. if (auto* connection = findVideoConnection (captureOutput))
  489. {
  490. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  491. if (Pimpl::getIOSVersion().major >= 10 && [captureOutput isKindOfClass: [AVCapturePhotoOutput class]])
  492. {
  493. auto* photoOutput = (AVCapturePhotoOutput*) captureOutput;
  494. auto outputConnection = [photoOutput connectionWithMediaType: AVMediaTypeVideo];
  495. outputConnection.videoOrientation = orientationToUse;
  496. [photoOutput capturePhotoWithSettings: [AVCapturePhotoSettings photoSettings]
  497. delegate: id<AVCapturePhotoCaptureDelegate> (photoOutputDelegate.get())];
  498. return;
  499. }
  500. #endif
  501. auto* stillImageOutput = (AVCaptureStillImageOutput*) captureOutput;
  502. auto outputConnection = [stillImageOutput connectionWithMediaType: AVMediaTypeVideo];
  503. outputConnection.videoOrientation = orientationToUse;
  504. [stillImageOutput captureStillImageAsynchronouslyFromConnection: connection completionHandler:
  505. ^(CMSampleBufferRef imageSampleBuffer, NSError* error)
  506. {
  507. takingPicture = false;
  508. if (error != nil)
  509. {
  510. JUCE_CAMERA_LOG ("Still picture capture failed, error: " + nsStringToJuce (error.localizedDescription));
  511. jassertfalse;
  512. return;
  513. }
  514. NSData* imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation: imageSampleBuffer];
  515. auto image = ImageFileFormat::loadFrom (imageData.bytes, (size_t) imageData.length);
  516. callListeners (image);
  517. MessageManager::callAsync ([this, image] { notifyPictureTaken (image); });
  518. }];
  519. }
  520. else
  521. {
  522. // Could not find a connection of video type
  523. jassertfalse;
  524. }
  525. }
  526. private:
  527. static AVCaptureOutput* createCaptureOutput()
  528. {
  529. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  530. if (Pimpl::getIOSVersion().major >= 10)
  531. return [AVCapturePhotoOutput new];
  532. #endif
  533. return [AVCaptureStillImageOutput new];
  534. }
  535. static void printImageOutputDebugInfo (AVCaptureOutput* captureOutput)
  536. {
  537. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  538. if (Pimpl::getIOSVersion().major >= 10 && [captureOutput isKindOfClass: [AVCapturePhotoOutput class]])
  539. {
  540. auto* photoOutput = (AVCapturePhotoOutput*) captureOutput;
  541. String typesString;
  542. for (AVVideoCodecType type in photoOutput.availablePhotoCodecTypes)
  543. typesString << nsStringToJuce (type) << " ";
  544. JUCE_CAMERA_LOG ("Available image codec types: " + typesString);
  545. JUCE_CAMERA_LOG ("Still image stabilization supported: " + String ((int) photoOutput.stillImageStabilizationSupported));
  546. JUCE_CAMERA_LOG ("Dual camera fusion supported: " + String ((int) photoOutput.dualCameraFusionSupported));
  547. JUCE_CAMERA_LOG ("Supports flash: " + String ((int) [photoOutput.supportedFlashModes containsObject: @(AVCaptureFlashModeOn)]));
  548. JUCE_CAMERA_LOG ("Supports auto flash: " + String ((int) [photoOutput.supportedFlashModes containsObject: @(AVCaptureFlashModeAuto)]));
  549. JUCE_CAMERA_LOG ("Max bracketed photo count: " + String (photoOutput.maxBracketedCapturePhotoCount));
  550. JUCE_CAMERA_LOG ("Lens stabilization during bracketed capture supported: " + String ((int) photoOutput.lensStabilizationDuringBracketedCaptureSupported));
  551. JUCE_CAMERA_LOG ("Live photo capture supported: " + String ((int) photoOutput.livePhotoCaptureSupported));
  552. #if defined (__IPHONE_11_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_11_0
  553. if (Pimpl::getIOSVersion().major >= 11)
  554. {
  555. typesString.clear();
  556. for (AVFileType type in photoOutput.availablePhotoFileTypes)
  557. typesString << nsStringToJuce (type) << " ";
  558. JUCE_CAMERA_LOG ("Available photo file types: " + typesString);
  559. typesString.clear();
  560. for (AVFileType type in photoOutput.availableRawPhotoFileTypes)
  561. typesString << nsStringToJuce (type) << " ";
  562. JUCE_CAMERA_LOG ("Available RAW photo file types: " + typesString);
  563. typesString.clear();
  564. for (AVFileType type in photoOutput.availableLivePhotoVideoCodecTypes)
  565. typesString << nsStringToJuce (type) << " ";
  566. JUCE_CAMERA_LOG ("Available live photo video codec types: " + typesString);
  567. JUCE_CAMERA_LOG ("Dual camera dual photo delivery supported: " + String ((int) photoOutput.dualCameraDualPhotoDeliverySupported));
  568. JUCE_CAMERA_LOG ("Camera calibration data delivery supported: " + String ((int) photoOutput.cameraCalibrationDataDeliverySupported));
  569. JUCE_CAMERA_LOG ("Depth data delivery supported: " + String ((int) photoOutput.depthDataDeliverySupported));
  570. }
  571. #endif
  572. return;
  573. }
  574. #endif
  575. auto* stillImageOutput = (AVCaptureStillImageOutput*) captureOutput;
  576. String typesString;
  577. for (AVVideoCodecType type in stillImageOutput.availableImageDataCodecTypes)
  578. typesString << nsStringToJuce (type) << " ";
  579. JUCE_CAMERA_LOG ("Available image codec types: " + typesString);
  580. JUCE_CAMERA_LOG ("Still image stabilization supported: " + String ((int) stillImageOutput.stillImageStabilizationSupported));
  581. JUCE_CAMERA_LOG ("Automatically enables still image stabilization when available: " + String ((int) stillImageOutput.automaticallyEnablesStillImageStabilizationWhenAvailable));
  582. JUCE_CAMERA_LOG ("Output settings for image output: " + nsStringToJuce ([stillImageOutput.outputSettings description]));
  583. }
  584. //==============================================================================
  585. static AVCaptureConnection* findVideoConnection (AVCaptureOutput* output)
  586. {
  587. for (AVCaptureConnection* connection in output.connections)
  588. for (AVCaptureInputPort* port in connection.inputPorts)
  589. if ([port.mediaType isEqual: AVMediaTypeVideo])
  590. return connection;
  591. return nullptr;
  592. }
  593. //==============================================================================
  594. class PhotoOutputDelegateClass : public ObjCClass<NSObject>
  595. {
  596. public:
  597. PhotoOutputDelegateClass() : ObjCClass<NSObject> ("PhotoOutputDelegateClass_")
  598. {
  599. addMethod (@selector (captureOutput:willBeginCaptureForResolvedSettings:), willBeginCaptureForSettings, "v@:@@");
  600. addMethod (@selector (captureOutput:willCapturePhotoForResolvedSettings:), willCaptureForSettings, "v@:@@");
  601. addMethod (@selector (captureOutput:didCapturePhotoForResolvedSettings:), didCaptureForSettings, "v@:@@");
  602. addMethod (@selector (captureOutput:didFinishCaptureForResolvedSettings:error:), didFinishCaptureForSettings, "v@:@@@");
  603. if (Pimpl::getIOSVersion().major >= 11)
  604. addMethod (@selector (captureOutput:didFinishProcessingPhoto:error:), didFinishProcessingPhoto, "v@:@@@");
  605. else
  606. addMethod (@selector (captureOutput:didFinishProcessingPhotoSampleBuffer:previewPhotoSampleBuffer:resolvedSettings:bracketSettings:error:), didFinishProcessingPhotoSampleBuffer, "v@:@@@@@@");
  607. addIvar<StillPictureTaker*> ("owner");
  608. registerClass();
  609. }
  610. //==============================================================================
  611. static StillPictureTaker& getOwner (id self) { return *getIvar<StillPictureTaker*> (self, "owner"); }
  612. static void setOwner (id self, StillPictureTaker* t) { object_setInstanceVariable (self, "owner", t); }
  613. private:
  614. static void willBeginCaptureForSettings (id, SEL, AVCapturePhotoOutput*, AVCaptureResolvedPhotoSettings*)
  615. {
  616. JUCE_CAMERA_LOG ("willBeginCaptureForSettings()");
  617. }
  618. static void willCaptureForSettings (id, SEL, AVCapturePhotoOutput*, AVCaptureResolvedPhotoSettings*)
  619. {
  620. JUCE_CAMERA_LOG ("willCaptureForSettings()");
  621. }
  622. static void didCaptureForSettings (id, SEL, AVCapturePhotoOutput*, AVCaptureResolvedPhotoSettings*)
  623. {
  624. JUCE_CAMERA_LOG ("didCaptureForSettings()");
  625. }
  626. static void didFinishCaptureForSettings (id, SEL, AVCapturePhotoOutput*, AVCaptureResolvedPhotoSettings*, NSError* error)
  627. {
  628. String errorString = error != nil ? nsStringToJuce (error.localizedDescription) : String();
  629. ignoreUnused (errorString);
  630. JUCE_CAMERA_LOG ("didFinishCaptureForSettings(), error = " + errorString);
  631. }
  632. static void didFinishProcessingPhoto (id self, SEL, AVCapturePhotoOutput*, AVCapturePhoto* capturePhoto, NSError* error)
  633. {
  634. getOwner (self).takingPicture = false;
  635. String errorString = error != nil ? nsStringToJuce (error.localizedDescription) : String();
  636. ignoreUnused (errorString);
  637. JUCE_CAMERA_LOG ("didFinishProcessingPhoto(), error = " + errorString);
  638. if (error != nil)
  639. {
  640. JUCE_CAMERA_LOG ("Still picture capture failed, error: " + nsStringToJuce (error.localizedDescription));
  641. jassertfalse;
  642. return;
  643. }
  644. auto* imageOrientation = (NSNumber *) capturePhoto.metadata[(NSString*) kCGImagePropertyOrientation];
  645. auto* uiImage = getImageWithCorrectOrientation ((CGImagePropertyOrientation) imageOrientation.unsignedIntValue,
  646. [capturePhoto CGImageRepresentation]);
  647. auto* imageData = UIImageJPEGRepresentation (uiImage, 0.f);
  648. auto image = ImageFileFormat::loadFrom (imageData.bytes, (size_t) imageData.length);
  649. getOwner (self).callListeners (image);
  650. MessageManager::callAsync ([self, image]() { getOwner (self).notifyPictureTaken (image); });
  651. }
  652. static UIImage* getImageWithCorrectOrientation (CGImagePropertyOrientation imageOrientation,
  653. CGImageRef imageData)
  654. {
  655. auto origWidth = CGImageGetWidth (imageData);
  656. auto origHeight = CGImageGetHeight (imageData);
  657. auto targetSize = getTargetImageDimensionFor (imageOrientation, imageData);
  658. UIGraphicsBeginImageContext (targetSize);
  659. CGContextRef context = UIGraphicsGetCurrentContext();
  660. switch (imageOrientation)
  661. {
  662. case kCGImagePropertyOrientationUp:
  663. CGContextScaleCTM (context, 1.0, -1.0);
  664. CGContextTranslateCTM (context, 0.0, -targetSize.height);
  665. break;
  666. case kCGImagePropertyOrientationRight:
  667. CGContextRotateCTM (context, 90 * MathConstants<CGFloat>::pi / 180);
  668. CGContextScaleCTM (context, targetSize.height / origHeight, -targetSize.width / origWidth);
  669. break;
  670. case kCGImagePropertyOrientationDown:
  671. CGContextTranslateCTM (context, targetSize.width, 0.0);
  672. CGContextScaleCTM (context, -1.0, 1.0);
  673. break;
  674. case kCGImagePropertyOrientationLeft:
  675. CGContextRotateCTM (context, -90 * MathConstants<CGFloat>::pi / 180);
  676. CGContextScaleCTM (context, targetSize.height / origHeight, -targetSize.width / origWidth);
  677. CGContextTranslateCTM (context, -targetSize.width, -targetSize.height);
  678. break;
  679. case kCGImagePropertyOrientationUpMirrored:
  680. case kCGImagePropertyOrientationDownMirrored:
  681. case kCGImagePropertyOrientationLeftMirrored:
  682. case kCGImagePropertyOrientationRightMirrored:
  683. default:
  684. // Not implemented.
  685. jassertfalse;
  686. break;
  687. }
  688. CGContextDrawImage (context, CGRectMake (0, 0, targetSize.width, targetSize.height), imageData);
  689. UIImage* correctedImage = UIGraphicsGetImageFromCurrentImageContext();
  690. UIGraphicsEndImageContext();
  691. return correctedImage;
  692. }
  693. static CGSize getTargetImageDimensionFor (CGImagePropertyOrientation imageOrientation,
  694. CGImageRef imageData)
  695. {
  696. auto width = CGImageGetWidth (imageData);
  697. auto height = CGImageGetHeight (imageData);
  698. switch (imageOrientation)
  699. {
  700. case kCGImagePropertyOrientationUp:
  701. case kCGImagePropertyOrientationUpMirrored:
  702. case kCGImagePropertyOrientationDown:
  703. case kCGImagePropertyOrientationDownMirrored:
  704. return CGSizeMake ((CGFloat) width, (CGFloat) height);
  705. case kCGImagePropertyOrientationRight:
  706. case kCGImagePropertyOrientationRightMirrored:
  707. case kCGImagePropertyOrientationLeft:
  708. case kCGImagePropertyOrientationLeftMirrored:
  709. return CGSizeMake ((CGFloat) height, (CGFloat) width);
  710. }
  711. jassertfalse;
  712. return CGSizeMake ((CGFloat) width, (CGFloat) height);
  713. }
  714. static void didFinishProcessingPhotoSampleBuffer (id self, SEL, AVCapturePhotoOutput*,
  715. CMSampleBufferRef imageBuffer, CMSampleBufferRef imagePreviewBuffer,
  716. AVCaptureResolvedPhotoSettings*, AVCaptureBracketedStillImageSettings*,
  717. NSError* error)
  718. {
  719. getOwner (self).takingPicture = false;
  720. String errorString = error != nil ? nsStringToJuce (error.localizedDescription) : String();
  721. ignoreUnused (errorString);
  722. JUCE_CAMERA_LOG ("didFinishProcessingPhotoSampleBuffer(), error = " + errorString);
  723. if (error != nil)
  724. {
  725. JUCE_CAMERA_LOG ("Still picture capture failed, error: " + nsStringToJuce (error.localizedDescription));
  726. jassertfalse;
  727. return;
  728. }
  729. NSData* origImageData = [AVCapturePhotoOutput JPEGPhotoDataRepresentationForJPEGSampleBuffer: imageBuffer previewPhotoSampleBuffer: imagePreviewBuffer];
  730. auto origImage = [UIImage imageWithData: origImageData];
  731. auto imageOrientation = uiImageOrientationToCGImageOrientation (origImage.imageOrientation);
  732. auto* uiImage = getImageWithCorrectOrientation (imageOrientation, origImage.CGImage);
  733. auto* imageData = UIImageJPEGRepresentation (uiImage, 0.f);
  734. auto image = ImageFileFormat::loadFrom (imageData.bytes, (size_t) imageData.length);
  735. getOwner (self).callListeners (image);
  736. MessageManager::callAsync ([self, image]() { getOwner (self).notifyPictureTaken (image); });
  737. }
  738. static CGImagePropertyOrientation uiImageOrientationToCGImageOrientation (UIImageOrientation orientation)
  739. {
  740. switch (orientation)
  741. {
  742. case UIImageOrientationUp: return kCGImagePropertyOrientationUp;
  743. case UIImageOrientationDown: return kCGImagePropertyOrientationDown;
  744. case UIImageOrientationLeft: return kCGImagePropertyOrientationLeft;
  745. case UIImageOrientationRight: return kCGImagePropertyOrientationRight;
  746. case UIImageOrientationUpMirrored: return kCGImagePropertyOrientationUpMirrored;
  747. case UIImageOrientationDownMirrored: return kCGImagePropertyOrientationDownMirrored;
  748. case UIImageOrientationLeftMirrored: return kCGImagePropertyOrientationLeftMirrored;
  749. case UIImageOrientationRightMirrored: return kCGImagePropertyOrientationRightMirrored;
  750. }
  751. }
  752. };
  753. //==============================================================================
  754. void callListeners (const Image& image)
  755. {
  756. captureSession.callListeners (image);
  757. }
  758. void notifyPictureTaken (const Image& image)
  759. {
  760. captureSession.notifyPictureTaken (image);
  761. }
  762. CaptureSession& captureSession;
  763. AVCaptureOutput* captureOutput;
  764. std::unique_ptr<NSObject, NSObjectDeleter> photoOutputDelegate;
  765. bool takingPicture = false;
  766. };
  767. //==============================================================================
  768. // NB: FileOutputRecordingDelegateClass callbacks can be called from any thread (incl.
  769. // the message thread), so waiting for an event when stopping recording is not an
  770. // option and VideoRecorder must be alive at all times in order to get stopped
  771. // recording callback.
  772. class VideoRecorder
  773. {
  774. public:
  775. VideoRecorder (CaptureSession& session)
  776. : movieFileOutput ([AVCaptureMovieFileOutput new]),
  777. delegate (nullptr)
  778. {
  779. static FileOutputRecordingDelegateClass cls;
  780. delegate.reset ([cls.createInstance() init]);
  781. FileOutputRecordingDelegateClass::setOwner (delegate.get(), this);
  782. session.addOutputIfPossible (movieFileOutput);
  783. }
  784. ~VideoRecorder()
  785. {
  786. stopRecording();
  787. // Shutting down a device while recording will stop the recording
  788. // abruptly and the recording will be lost.
  789. jassert (! recordingInProgress);
  790. }
  791. void startRecording (const File& file, AVCaptureVideoOrientation orientationToUse)
  792. {
  793. if (Pimpl::getIOSVersion().major >= 10)
  794. printVideoOutputDebugInfo (movieFileOutput);
  795. auto url = [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())
  796. isDirectory: NO];
  797. auto outputConnection = [movieFileOutput connectionWithMediaType: AVMediaTypeVideo];
  798. outputConnection.videoOrientation = orientationToUse;
  799. [movieFileOutput startRecordingToOutputFileURL: url recordingDelegate: delegate.get()];
  800. }
  801. void stopRecording()
  802. {
  803. [movieFileOutput stopRecording];
  804. }
  805. Time getTimeOfFirstRecordedFrame() const
  806. {
  807. return Time (firstRecordedFrameTimeMs.get());
  808. }
  809. private:
  810. static void printVideoOutputDebugInfo (AVCaptureMovieFileOutput* output)
  811. {
  812. ignoreUnused (output);
  813. JUCE_CAMERA_LOG ("Available video codec types:");
  814. #if JUCE_CAMERA_LOG_ENABLED
  815. for (AVVideoCodecType type in output.availableVideoCodecTypes)
  816. JUCE_CAMERA_LOG (nsStringToJuce (type));
  817. #endif
  818. JUCE_CAMERA_LOG ("Output settings per video connection:");
  819. #if JUCE_CAMERA_LOG_ENABLED
  820. for (AVCaptureConnection* connection in output.connections)
  821. JUCE_CAMERA_LOG (nsStringToJuce ([[output outputSettingsForConnection: connection] description]));
  822. #endif
  823. }
  824. //==============================================================================
  825. struct FileOutputRecordingDelegateClass : public ObjCClass<NSObject<AVCaptureFileOutputRecordingDelegate>>
  826. {
  827. FileOutputRecordingDelegateClass() : ObjCClass<NSObject<AVCaptureFileOutputRecordingDelegate>> ("FileOutputRecordingDelegateClass_")
  828. {
  829. addMethod (@selector (captureOutput:didStartRecordingToOutputFileAtURL:fromConnections:), started, "v@:@@@");
  830. addMethod (@selector (captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:), stopped, "v@:@@@@");
  831. addIvar<VideoRecorder*> ("owner");
  832. registerClass();
  833. }
  834. //==============================================================================
  835. static VideoRecorder& getOwner (id self) { return *getIvar<VideoRecorder*> (self, "owner"); }
  836. static void setOwner (id self, VideoRecorder* r) { object_setInstanceVariable (self, "owner", r); }
  837. private:
  838. static void started (id self, SEL, AVCaptureFileOutput*, NSURL*, NSArray<AVCaptureConnection*>*)
  839. {
  840. JUCE_CAMERA_LOG ("Started recording");
  841. getOwner (self).firstRecordedFrameTimeMs.set (Time::getCurrentTime().toMilliseconds());
  842. getOwner (self).recordingInProgress = true;
  843. }
  844. static void stopped (id self, SEL, AVCaptureFileOutput*, NSURL*, NSArray<AVCaptureConnection*>*, NSError* error)
  845. {
  846. String errorString;
  847. bool recordingPlayable = true;
  848. // There might have been an error in the recording, yet there may be a playable file...
  849. if ([error code] != noErr)
  850. {
  851. id value = [[error userInfo] objectForKey: AVErrorRecordingSuccessfullyFinishedKey];
  852. if (value != nil && ! [value boolValue])
  853. recordingPlayable = false;
  854. errorString = nsStringToJuce (error.localizedDescription) + ", playable: " + String ((int) recordingPlayable);
  855. }
  856. JUCE_CAMERA_LOG ("Stopped recording, error = " + errorString);
  857. getOwner (self).recordingInProgress = false;
  858. }
  859. };
  860. AVCaptureMovieFileOutput* movieFileOutput;
  861. std::unique_ptr<NSObject<AVCaptureFileOutputRecordingDelegate>, NSObjectDeleter> delegate;
  862. bool recordingInProgress = false;
  863. Atomic<int64> firstRecordedFrameTimeMs { 0 };
  864. };
  865. //==============================================================================
  866. void addOutputIfPossible (AVCaptureOutput* output)
  867. {
  868. dispatch_async (captureSessionQueue,^
  869. {
  870. if ([captureSession.get() canAddOutput: output])
  871. {
  872. [captureSession.get() beginConfiguration];
  873. [captureSession.get() addOutput: output];
  874. [captureSession.get() commitConfiguration];
  875. return;
  876. }
  877. // Can't add output to camera session!
  878. jassertfalse;
  879. });
  880. }
  881. //==============================================================================
  882. void cameraSessionStarted()
  883. {
  884. sessionStarted = true;
  885. owner.cameraSessionStarted();
  886. }
  887. void cameraSessionRuntimeError (const String& error)
  888. {
  889. owner.cameraSessionRuntimeError (error);
  890. }
  891. void callListeners (const Image& image)
  892. {
  893. owner.callListeners (image);
  894. }
  895. void notifyPictureTaken (const Image& image)
  896. {
  897. owner.notifyPictureTaken (image);
  898. }
  899. Pimpl& owner;
  900. dispatch_queue_t captureSessionQueue;
  901. std::unique_ptr<AVCaptureSession, NSObjectDeleter> captureSession;
  902. std::unique_ptr<NSObject, NSObjectDeleter> delegate;
  903. StillPictureTaker stillPictureTaker;
  904. VideoRecorder videoRecorder;
  905. AVCaptureDevice* cameraDevice = nil;
  906. AVCaptureVideoPreviewLayer* previewLayer = nil;
  907. bool sessionStarted = false;
  908. WaitableEvent sessionClosedEvent;
  909. static int numCaptureSessions;
  910. };
  911. //==============================================================================
  912. void cameraSessionStarted()
  913. {
  914. JUCE_CAMERA_LOG ("cameraSessionStarted()");
  915. cameraOpenCallback (cameraId, {});
  916. }
  917. void cameraSessionRuntimeError (const String& error)
  918. {
  919. JUCE_CAMERA_LOG ("cameraSessionRuntimeError(), error = " + error);
  920. if (! notifiedOfCameraOpening)
  921. {
  922. cameraOpenCallback ({}, error);
  923. }
  924. else
  925. {
  926. if (owner.onErrorOccurred != nullptr)
  927. owner.onErrorOccurred (error);
  928. }
  929. }
  930. void callListeners (const Image& image)
  931. {
  932. const ScopedLock sl (listenerLock);
  933. listeners.call ([=] (Listener& l) { l.imageReceived (image); });
  934. if (listeners.size() == 1)
  935. triggerStillPictureCapture();
  936. }
  937. void notifyPictureTaken (const Image& image)
  938. {
  939. JUCE_CAMERA_LOG ("notifyPictureTaken()");
  940. if (pictureTakenCallback != nullptr)
  941. pictureTakenCallback (image);
  942. }
  943. //==============================================================================
  944. void triggerStillPictureCapture()
  945. {
  946. captureSession.takeStillPicture();
  947. }
  948. //==============================================================================
  949. CameraDevice& owner;
  950. String cameraId;
  951. InternalOpenCameraResultCallback cameraOpenCallback;
  952. CriticalSection listenerLock;
  953. ListenerList<Listener> listeners;
  954. std::function<void (const Image&)> pictureTakenCallback;
  955. CaptureSession captureSession;
  956. bool notifiedOfCameraOpening = false;
  957. //==============================================================================
  958. struct IOSVersion
  959. {
  960. int major;
  961. int minor;
  962. };
  963. static IOSVersion getIOSVersion()
  964. {
  965. auto processInfo = [NSProcessInfo processInfo];
  966. if (! [processInfo respondsToSelector: @selector (operatingSystemVersion)])
  967. return {7, 0}; // Below 8.0 in fact, but only care that it's below 8
  968. return { (int)[processInfo operatingSystemVersion].majorVersion,
  969. (int)[processInfo operatingSystemVersion].minorVersion };
  970. }
  971. static IOSVersion iosVersion;
  972. friend struct CameraDevice::ViewerComponent;
  973. JUCE_DECLARE_NON_COPYABLE (Pimpl)
  974. };
  975. CameraDevice::Pimpl::IOSVersion CameraDevice::Pimpl::iosVersion = CameraDevice::Pimpl::getIOSVersion();
  976. int CameraDevice::Pimpl::CaptureSession::numCaptureSessions = 0;
  977. //==============================================================================
  978. struct CameraDevice::ViewerComponent : public UIViewComponent
  979. {
  980. //==============================================================================
  981. struct JuceCameraDeviceViewerClass : public ObjCClass<UIView>
  982. {
  983. JuceCameraDeviceViewerClass() : ObjCClass<UIView> ("JuceCameraDeviceViewerClass_")
  984. {
  985. addMethod (@selector (layoutSubviews), layoutSubviews, "v@:");
  986. registerClass();
  987. }
  988. private:
  989. static void layoutSubviews (id self, SEL)
  990. {
  991. sendSuperclassMessage<void> (self, @selector (layoutSubviews));
  992. UIView* asUIView = (UIView*) self;
  993. updateOrientation (self);
  994. if (auto* previewLayer = getPreviewLayer (self))
  995. previewLayer.frame = asUIView.bounds;
  996. }
  997. static AVCaptureVideoPreviewLayer* getPreviewLayer (id self)
  998. {
  999. UIView* asUIView = (UIView*) self;
  1000. if (asUIView.layer.sublayers != nil && [asUIView.layer.sublayers count] > 0)
  1001. if ([asUIView.layer.sublayers[0] isKindOfClass: [AVCaptureVideoPreviewLayer class]])
  1002. return (AVCaptureVideoPreviewLayer*) asUIView.layer.sublayers[0];
  1003. return nil;
  1004. }
  1005. static void updateOrientation (id self)
  1006. {
  1007. if (auto* previewLayer = getPreviewLayer (self))
  1008. {
  1009. UIDeviceOrientation o = [UIDevice currentDevice].orientation;
  1010. if (UIDeviceOrientationIsPortrait (o) || UIDeviceOrientationIsLandscape (o))
  1011. {
  1012. if (previewLayer.connection != nil)
  1013. previewLayer.connection.videoOrientation = (AVCaptureVideoOrientation) o;
  1014. }
  1015. }
  1016. }
  1017. };
  1018. ViewerComponent (CameraDevice& device)
  1019. {
  1020. static JuceCameraDeviceViewerClass cls;
  1021. // Initial size that can be overriden later.
  1022. setSize (640, 480);
  1023. auto view = [cls.createInstance() init];
  1024. setView (view);
  1025. auto* previewLayer = device.pimpl->captureSession.createPreviewLayer();
  1026. previewLayer.frame = view.bounds;
  1027. UIInterfaceOrientation statusBarOrientation = [UIApplication sharedApplication].statusBarOrientation;
  1028. AVCaptureVideoOrientation videoOrientation = statusBarOrientation != UIInterfaceOrientationUnknown
  1029. ? (AVCaptureVideoOrientation) statusBarOrientation
  1030. : AVCaptureVideoOrientationPortrait;
  1031. previewLayer.connection.videoOrientation = videoOrientation;
  1032. [view.layer addSublayer: previewLayer];
  1033. }
  1034. };
  1035. //==============================================================================
  1036. String CameraDevice::getFileExtension()
  1037. {
  1038. return ".mov";
  1039. }
  1040. #if JUCE_DEPRECATION_IGNORED
  1041. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  1042. #endif