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.

1294 lines
57KB

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