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.

415 lines
14KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 6 technical preview.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For this technical preview, this file is not subject to commercial licensing.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. #if ! (defined (MAC_OS_X_VERSION_10_16) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_16)
  14. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  15. #define JUCE_DEPRECATION_IGNORED 1
  16. #endif
  17. struct CameraDevice::Pimpl
  18. {
  19. Pimpl (CameraDevice& ownerToUse, const String& deviceNameToUse, int /*index*/,
  20. int /*minWidth*/, int /*minHeight*/,
  21. int /*maxWidth*/, int /*maxHeight*/,
  22. bool useHighQuality)
  23. : owner (ownerToUse),
  24. deviceName (deviceNameToUse)
  25. {
  26. session = [[AVCaptureSession alloc] init];
  27. session.sessionPreset = useHighQuality ? AVCaptureSessionPresetHigh
  28. : AVCaptureSessionPresetMedium;
  29. refreshConnections();
  30. static DelegateClass cls;
  31. callbackDelegate = (id<AVCaptureFileOutputRecordingDelegate>) [cls.createInstance() init];
  32. DelegateClass::setOwner (callbackDelegate, this);
  33. SEL runtimeErrorSel = NSSelectorFromString (nsStringLiteral ("captureSessionRuntimeError:"));
  34. [[NSNotificationCenter defaultCenter] addObserver: callbackDelegate
  35. selector: runtimeErrorSel
  36. name: AVCaptureSessionRuntimeErrorNotification
  37. object: session];
  38. }
  39. ~Pimpl()
  40. {
  41. [[NSNotificationCenter defaultCenter] removeObserver: callbackDelegate];
  42. [session stopRunning];
  43. removeInput();
  44. removeImageCapture();
  45. removeMovieCapture();
  46. [session release];
  47. [callbackDelegate release];
  48. }
  49. //==============================================================================
  50. bool openedOk() const noexcept { return openingError.isEmpty(); }
  51. void takeStillPicture (std::function<void(const Image&)> pictureTakenCallbackToUse)
  52. {
  53. if (pictureTakenCallbackToUse == nullptr)
  54. {
  55. jassertfalse;
  56. return;
  57. }
  58. pictureTakenCallback = std::move (pictureTakenCallbackToUse);
  59. triggerImageCapture();
  60. }
  61. void startRecordingToFile (const File& file, int /*quality*/)
  62. {
  63. stopRecording();
  64. refreshIfNeeded();
  65. firstPresentationTime = Time::getCurrentTime();
  66. file.deleteFile();
  67. isRecording = true;
  68. [fileOutput startRecordingToOutputFileURL: createNSURLFromFile (file)
  69. recordingDelegate: callbackDelegate];
  70. }
  71. void stopRecording()
  72. {
  73. if (isRecording)
  74. {
  75. [fileOutput stopRecording];
  76. isRecording = false;
  77. }
  78. }
  79. Time getTimeOfFirstRecordedFrame() const
  80. {
  81. return firstPresentationTime;
  82. }
  83. void addListener (CameraDevice::Listener* listenerToAdd)
  84. {
  85. const ScopedLock sl (listenerLock);
  86. listeners.add (listenerToAdd);
  87. if (listeners.size() == 1)
  88. triggerImageCapture();
  89. }
  90. void removeListener (CameraDevice::Listener* listenerToRemove)
  91. {
  92. const ScopedLock sl (listenerLock);
  93. listeners.remove (listenerToRemove);
  94. }
  95. static StringArray getAvailableDevices()
  96. {
  97. StringArray results;
  98. NSArray* devices = [AVCaptureDevice devicesWithMediaType: AVMediaTypeVideo];
  99. for (AVCaptureDevice* device : devices)
  100. results.add (nsStringToJuce ([device localizedName]));
  101. return results;
  102. }
  103. AVCaptureSession* getCaptureSession()
  104. {
  105. return session;
  106. }
  107. private:
  108. //==============================================================================
  109. struct DelegateClass : public ObjCClass<NSObject>
  110. {
  111. DelegateClass() : ObjCClass<NSObject> ("JUCECameraDelegate_")
  112. {
  113. addIvar<Pimpl*> ("owner");
  114. addProtocol (@protocol (AVCaptureFileOutputRecordingDelegate));
  115. addMethod (@selector (captureOutput:didStartRecordingToOutputFileAtURL: fromConnections:), didStartRecordingToOutputFileAtURL, "v@:@@@");
  116. addMethod (@selector (captureOutput:didPauseRecordingToOutputFileAtURL: fromConnections:), didPauseRecordingToOutputFileAtURL, "v@:@@@");
  117. addMethod (@selector (captureOutput:didResumeRecordingToOutputFileAtURL: fromConnections:), didResumeRecordingToOutputFileAtURL, "v@:@@@");
  118. addMethod (@selector (captureOutput:willFinishRecordingToOutputFileAtURL:fromConnections:error:), willFinishRecordingToOutputFileAtURL, "v@:@@@@");
  119. SEL runtimeErrorSel = NSSelectorFromString (nsStringLiteral ("captureSessionRuntimeError:"));
  120. addMethod (runtimeErrorSel, sessionRuntimeError, "v@:@");
  121. registerClass();
  122. }
  123. static void setOwner (id self, Pimpl* owner) { object_setInstanceVariable (self, "owner", owner); }
  124. static Pimpl& getOwner (id self) { return *getIvar<Pimpl*> (self, "owner"); }
  125. private:
  126. static void didStartRecordingToOutputFileAtURL (id, SEL, AVCaptureFileOutput*, NSURL*, NSArray*) {}
  127. static void didPauseRecordingToOutputFileAtURL (id, SEL, AVCaptureFileOutput*, NSURL*, NSArray*) {}
  128. static void didResumeRecordingToOutputFileAtURL (id, SEL, AVCaptureFileOutput*, NSURL*, NSArray*) {}
  129. static void willFinishRecordingToOutputFileAtURL (id, SEL, AVCaptureFileOutput*, NSURL*, NSArray*, NSError*) {}
  130. static void sessionRuntimeError (id self, SEL, NSNotification* notification)
  131. {
  132. JUCE_CAMERA_LOG (nsStringToJuce ([notification description]));
  133. NSError* error = notification.userInfo[AVCaptureSessionErrorKey];
  134. auto errorString = error != nil ? nsStringToJuce (error.localizedDescription) : String();
  135. getOwner (self).cameraSessionRuntimeError (errorString);
  136. }
  137. };
  138. //==============================================================================
  139. void addImageCapture()
  140. {
  141. if (imageOutput == nil)
  142. {
  143. imageOutput = [[AVCaptureStillImageOutput alloc] init];
  144. auto imageSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
  145. [imageOutput setOutputSettings: imageSettings];
  146. [imageSettings release];
  147. [session addOutput: imageOutput];
  148. }
  149. }
  150. void addMovieCapture()
  151. {
  152. if (fileOutput == nil)
  153. {
  154. fileOutput = [[AVCaptureMovieFileOutput alloc] init];
  155. [session addOutput: fileOutput];
  156. }
  157. }
  158. void removeImageCapture()
  159. {
  160. if (imageOutput != nil)
  161. {
  162. [session removeOutput: imageOutput];
  163. [imageOutput release];
  164. imageOutput = nil;
  165. }
  166. }
  167. void removeMovieCapture()
  168. {
  169. if (fileOutput != nil)
  170. {
  171. [session removeOutput: fileOutput];
  172. [fileOutput release];
  173. fileOutput = nil;
  174. }
  175. }
  176. void removeCurrentSessionVideoInputs()
  177. {
  178. if (session != nil)
  179. {
  180. NSArray<AVCaptureDeviceInput*>* inputs = session.inputs;
  181. for (AVCaptureDeviceInput* input : inputs)
  182. if ([input.device hasMediaType: AVMediaTypeVideo])
  183. [session removeInput:input];
  184. }
  185. }
  186. void addInput()
  187. {
  188. if (currentInput == nil)
  189. {
  190. NSArray* availableDevices = [AVCaptureDevice devicesWithMediaType: AVMediaTypeVideo];
  191. for (AVCaptureDevice* device : availableDevices)
  192. {
  193. if (deviceName == nsStringToJuce ([device localizedName]))
  194. {
  195. removeCurrentSessionVideoInputs();
  196. NSError* err = nil;
  197. AVCaptureDeviceInput* inputDevice = [[AVCaptureDeviceInput alloc] initWithDevice: device
  198. error: &err];
  199. jassert (err == nil);
  200. if ([session canAddInput: inputDevice])
  201. {
  202. [session addInput: inputDevice];
  203. currentInput = inputDevice;
  204. }
  205. else
  206. {
  207. jassertfalse;
  208. [inputDevice release];
  209. }
  210. return;
  211. }
  212. }
  213. }
  214. }
  215. void removeInput()
  216. {
  217. if (currentInput != nil)
  218. {
  219. [session removeInput: currentInput];
  220. [currentInput release];
  221. currentInput = nil;
  222. }
  223. }
  224. void refreshConnections()
  225. {
  226. [session beginConfiguration];
  227. removeInput();
  228. removeImageCapture();
  229. removeMovieCapture();
  230. addInput();
  231. addImageCapture();
  232. addMovieCapture();
  233. [session commitConfiguration];
  234. }
  235. void refreshIfNeeded()
  236. {
  237. if (getVideoConnection() == nullptr)
  238. refreshConnections();
  239. }
  240. AVCaptureConnection* getVideoConnection() const
  241. {
  242. if (imageOutput != nil)
  243. for (AVCaptureConnection* connection in imageOutput.connections)
  244. if ([connection isActive] && [connection isEnabled])
  245. for (AVCaptureInputPort* port in [connection inputPorts])
  246. if ([[port mediaType] isEqual: AVMediaTypeVideo])
  247. return connection;
  248. return nil;
  249. }
  250. void handleImageCapture (const Image& image)
  251. {
  252. const ScopedLock sl (listenerLock);
  253. listeners.call ([=] (Listener& l) { l.imageReceived (image); });
  254. if (! listeners.isEmpty())
  255. triggerImageCapture();
  256. }
  257. void triggerImageCapture()
  258. {
  259. refreshIfNeeded();
  260. if (auto* videoConnection = getVideoConnection())
  261. {
  262. [imageOutput captureStillImageAsynchronouslyFromConnection: videoConnection
  263. completionHandler: ^(CMSampleBufferRef sampleBuffer, NSError* error)
  264. {
  265. if (error != nil)
  266. {
  267. JUCE_CAMERA_LOG ("Still picture capture failed, error: " + nsStringToJuce (error.localizedDescription));
  268. jassertfalse;
  269. return;
  270. }
  271. NSData* imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation: sampleBuffer];
  272. auto image = ImageFileFormat::loadFrom (imageData.bytes, (size_t) imageData.length);
  273. handleImageCapture (image);
  274. WeakReference<Pimpl> weakRef (this);
  275. MessageManager::callAsync ([weakRef, image]() mutable
  276. {
  277. if (weakRef != nullptr && weakRef->pictureTakenCallback != nullptr)
  278. weakRef->pictureTakenCallback (image);
  279. });
  280. }];
  281. }
  282. }
  283. void cameraSessionRuntimeError (const String& error)
  284. {
  285. JUCE_CAMERA_LOG ("cameraSessionRuntimeError(), error = " + error);
  286. if (owner.onErrorOccurred != nullptr)
  287. owner.onErrorOccurred (error);
  288. }
  289. //==============================================================================
  290. CameraDevice& owner;
  291. String deviceName;
  292. AVCaptureSession* session = nil;
  293. AVCaptureMovieFileOutput* fileOutput = nil;
  294. AVCaptureStillImageOutput* imageOutput = nil;
  295. AVCaptureDeviceInput* currentInput = nil;
  296. id<AVCaptureFileOutputRecordingDelegate> callbackDelegate = nil;
  297. String openingError;
  298. Time firstPresentationTime;
  299. bool isRecording = false;
  300. CriticalSection listenerLock;
  301. ListenerList<Listener> listeners;
  302. std::function<void(const Image&)> pictureTakenCallback = nullptr;
  303. //==============================================================================
  304. JUCE_DECLARE_WEAK_REFERENCEABLE (Pimpl)
  305. JUCE_DECLARE_NON_COPYABLE (Pimpl)
  306. };
  307. //==============================================================================
  308. struct CameraDevice::ViewerComponent : public NSViewComponent
  309. {
  310. ViewerComponent (CameraDevice& device)
  311. {
  312. JUCE_AUTORELEASEPOOL
  313. {
  314. AVCaptureVideoPreviewLayer* previewLayer = [[AVCaptureVideoPreviewLayer alloc] init];
  315. AVCaptureSession* session = device.pimpl->getCaptureSession();
  316. [session stopRunning];
  317. [previewLayer setSession: session];
  318. [session startRunning];
  319. NSView* view = [[NSView alloc] init];
  320. [view setLayer: previewLayer];
  321. setView (view);
  322. }
  323. }
  324. ~ViewerComponent()
  325. {
  326. setView (nil);
  327. }
  328. JUCE_DECLARE_NON_COPYABLE (ViewerComponent)
  329. };
  330. String CameraDevice::getFileExtension()
  331. {
  332. return ".mov";
  333. }
  334. #if JUCE_DEPRECATION_IGNORED
  335. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  336. #endif