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.

873 lines
30KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. interface ISampleGrabberCB : public IUnknown
  19. {
  20. virtual STDMETHODIMP SampleCB (double, IMediaSample*) = 0;
  21. virtual STDMETHODIMP BufferCB (double, BYTE*, long) = 0;
  22. };
  23. interface ISampleGrabber : public IUnknown
  24. {
  25. virtual HRESULT STDMETHODCALLTYPE SetOneShot (BOOL) = 0;
  26. virtual HRESULT STDMETHODCALLTYPE SetMediaType (const AM_MEDIA_TYPE*) = 0;
  27. virtual HRESULT STDMETHODCALLTYPE GetConnectedMediaType (AM_MEDIA_TYPE*) = 0;
  28. virtual HRESULT STDMETHODCALLTYPE SetBufferSamples (BOOL) = 0;
  29. virtual HRESULT STDMETHODCALLTYPE GetCurrentBuffer (long*, long*) = 0;
  30. virtual HRESULT STDMETHODCALLTYPE GetCurrentSample (IMediaSample**) = 0;
  31. virtual HRESULT STDMETHODCALLTYPE SetCallback (ISampleGrabberCB*, long) = 0;
  32. };
  33. static const IID IID_ISampleGrabberCB = { 0x0579154A, 0x2B53, 0x4994, { 0xB0, 0xD0, 0xE7, 0x73, 0x14, 0x8E, 0xFF, 0x85 } };
  34. static const IID IID_ISampleGrabber = { 0x6B652FFF, 0x11FE, 0x4fce, { 0x92, 0xAD, 0x02, 0x66, 0xB5, 0xD7, 0xC7, 0x8F } };
  35. static const CLSID CLSID_SampleGrabber = { 0xC1F400A0, 0x3F08, 0x11d3, { 0x9F, 0x0B, 0x00, 0x60, 0x08, 0x03, 0x9E, 0x37 } };
  36. static const CLSID CLSID_NullRenderer = { 0xC1F400A4, 0x3F08, 0x11d3, { 0x9F, 0x0B, 0x00, 0x60, 0x08, 0x03, 0x9E, 0x37 } };
  37. //==============================================================================
  38. class DShowCameraDeviceInteral : public ChangeBroadcaster
  39. {
  40. public:
  41. DShowCameraDeviceInteral (CameraDevice* const owner_,
  42. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  43. const ComSmartPtr <IBaseFilter>& filter_,
  44. int minWidth, int minHeight,
  45. int maxWidth, int maxHeight)
  46. : owner (owner_),
  47. captureGraphBuilder (captureGraphBuilder_),
  48. filter (filter_),
  49. ok (false),
  50. imageNeedsFlipping (false),
  51. width (0),
  52. height (0),
  53. activeUsers (0),
  54. recordNextFrameTime (false),
  55. previewMaxFPS (60)
  56. {
  57. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  58. if (FAILED (hr))
  59. return;
  60. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  61. if (FAILED (hr))
  62. return;
  63. hr = graphBuilder.QueryInterface (mediaControl);
  64. if (FAILED (hr))
  65. return;
  66. {
  67. ComSmartPtr <IAMStreamConfig> streamConfig;
  68. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  69. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  70. if (streamConfig != nullptr)
  71. {
  72. getVideoSizes (streamConfig);
  73. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  74. return;
  75. }
  76. }
  77. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  78. if (FAILED (hr))
  79. return;
  80. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  81. if (FAILED (hr))
  82. return;
  83. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  84. if (FAILED (hr))
  85. return;
  86. if (! connectFilters (filter, smartTee))
  87. return;
  88. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  89. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  90. if (FAILED (hr))
  91. return;
  92. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  93. if (FAILED (hr))
  94. return;
  95. {
  96. AM_MEDIA_TYPE mt = { 0 };
  97. mt.majortype = MEDIATYPE_Video;
  98. mt.subtype = MEDIASUBTYPE_RGB24;
  99. mt.formattype = FORMAT_VideoInfo;
  100. sampleGrabber->SetMediaType (&mt);
  101. }
  102. callback = new GrabberCallback (*this);
  103. hr = sampleGrabber->SetCallback (callback, 1);
  104. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  105. if (FAILED (hr))
  106. return;
  107. ComSmartPtr <IPin> grabberInputPin;
  108. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  109. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  110. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  111. return;
  112. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  113. if (FAILED (hr))
  114. return;
  115. AM_MEDIA_TYPE mt = { 0 };
  116. hr = sampleGrabber->GetConnectedMediaType (&mt);
  117. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  118. width = pVih->bmiHeader.biWidth;
  119. height = pVih->bmiHeader.biHeight;
  120. ComSmartPtr <IBaseFilter> nullFilter;
  121. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  122. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  123. if (connectFilters (sampleGrabberBase, nullFilter)
  124. && addGraphToRot())
  125. {
  126. activeImage = Image (Image::RGB, width, height, true);
  127. loadingImage = Image (Image::RGB, width, height, true);
  128. ok = true;
  129. }
  130. }
  131. ~DShowCameraDeviceInteral()
  132. {
  133. if (mediaControl != nullptr)
  134. mediaControl->Stop();
  135. removeGraphFromRot();
  136. for (int i = viewerComps.size(); --i >= 0;)
  137. viewerComps.getUnchecked(i)->ownerDeleted();
  138. callback = nullptr;
  139. graphBuilder = nullptr;
  140. sampleGrabber = nullptr;
  141. mediaControl = nullptr;
  142. filter = nullptr;
  143. captureGraphBuilder = nullptr;
  144. smartTee = nullptr;
  145. smartTeePreviewOutputPin = nullptr;
  146. smartTeeCaptureOutputPin = nullptr;
  147. asfWriter = nullptr;
  148. }
  149. void addUser()
  150. {
  151. if (ok && activeUsers++ == 0)
  152. mediaControl->Run();
  153. }
  154. void removeUser()
  155. {
  156. if (ok && --activeUsers == 0)
  157. mediaControl->Stop();
  158. }
  159. int getPreviewMaxFPS() const
  160. {
  161. return previewMaxFPS;
  162. }
  163. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  164. {
  165. if (recordNextFrameTime)
  166. {
  167. const double defaultCameraLatency = 0.1;
  168. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  169. recordNextFrameTime = false;
  170. ComSmartPtr <IPin> pin;
  171. if (getPin (filter, PINDIR_OUTPUT, pin))
  172. {
  173. ComSmartPtr <IAMPushSource> pushSource;
  174. HRESULT hr = pin.QueryInterface (pushSource);
  175. if (pushSource != nullptr)
  176. {
  177. REFERENCE_TIME latency = 0;
  178. hr = pushSource->GetLatency (&latency);
  179. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  180. }
  181. }
  182. }
  183. {
  184. const int lineStride = width * 3;
  185. const ScopedLock sl (imageSwapLock);
  186. {
  187. const Image::BitmapData destData (loadingImage, 0, 0, width, height, Image::BitmapData::writeOnly);
  188. for (int i = 0; i < height; ++i)
  189. memcpy (destData.getLinePointer ((height - 1) - i),
  190. buffer + lineStride * i,
  191. lineStride);
  192. }
  193. imageNeedsFlipping = true;
  194. }
  195. if (listeners.size() > 0)
  196. callListeners (loadingImage);
  197. sendChangeMessage();
  198. }
  199. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  200. {
  201. if (imageNeedsFlipping)
  202. {
  203. const ScopedLock sl (imageSwapLock);
  204. std::swap (loadingImage, activeImage);
  205. imageNeedsFlipping = false;
  206. }
  207. RectanglePlacement rp (RectanglePlacement::centred);
  208. double dx = 0, dy = 0, dw = width, dh = height;
  209. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  210. const int rx = roundToInt (dx), ry = roundToInt (dy);
  211. const int rw = roundToInt (dw), rh = roundToInt (dh);
  212. {
  213. Graphics::ScopedSaveState ss (g);
  214. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  215. g.fillAll (Colours::black);
  216. }
  217. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  218. }
  219. bool createFileCaptureFilter (const File& file, int quality)
  220. {
  221. removeFileCaptureFilter();
  222. file.deleteFile();
  223. mediaControl->Stop();
  224. firstRecordedTime = Time();
  225. recordNextFrameTime = true;
  226. previewMaxFPS = 60;
  227. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  228. if (SUCCEEDED (hr))
  229. {
  230. ComSmartPtr <IFileSinkFilter> fileSink;
  231. hr = asfWriter.QueryInterface (fileSink);
  232. if (SUCCEEDED (hr))
  233. {
  234. hr = fileSink->SetFileName (file.getFullPathName().toWideCharPointer(), 0);
  235. if (SUCCEEDED (hr))
  236. {
  237. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  238. if (SUCCEEDED (hr))
  239. {
  240. ComSmartPtr <IConfigAsfWriter> asfConfig;
  241. hr = asfWriter.QueryInterface (asfConfig);
  242. asfConfig->SetIndexMode (true);
  243. ComSmartPtr <IWMProfileManager> profileManager;
  244. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  245. // This gibberish is the DirectShow profile for a video-only wmv file.
  246. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  247. "<streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" "
  248. "streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  249. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  250. "<videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  251. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" "
  252. "btemporalcompression=\"1\" lsamplesize=\"0\">"
  253. "<videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  254. "<rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  255. "<rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  256. "<bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  257. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" "
  258. "biclrused=\"0\" biclrimportant=\"0\"/>"
  259. "</videoinfoheader>"
  260. "</wmmediatype>"
  261. "</streamconfig>"
  262. "</profile>");
  263. const int fps[] = { 10, 15, 30 };
  264. int maxFramesPerSecond = fps [jlimit (0, numElementsInArray (fps) - 1, quality & 0xff)];
  265. if ((quality & 0xff000000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  266. maxFramesPerSecond = (quality >> 24) & 0xff;
  267. prof = prof.replace ("$WIDTH", String (width))
  268. .replace ("$HEIGHT", String (height))
  269. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  270. ComSmartPtr <IWMProfile> currentProfile;
  271. hr = profileManager->LoadProfileByData (prof.toWideCharPointer(), currentProfile.resetAndGetPointerAddress());
  272. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  273. if (SUCCEEDED (hr))
  274. {
  275. ComSmartPtr <IPin> asfWriterInputPin;
  276. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  277. {
  278. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  279. if (SUCCEEDED (hr) && ok && activeUsers > 0
  280. && SUCCEEDED (mediaControl->Run()))
  281. {
  282. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  283. if ((quality & 0x00ff0000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  284. previewMaxFPS = (quality >> 16) & 0xff;
  285. return true;
  286. }
  287. }
  288. }
  289. }
  290. }
  291. }
  292. }
  293. removeFileCaptureFilter();
  294. if (ok && activeUsers > 0)
  295. mediaControl->Run();
  296. return false;
  297. }
  298. void removeFileCaptureFilter()
  299. {
  300. mediaControl->Stop();
  301. if (asfWriter != nullptr)
  302. {
  303. graphBuilder->RemoveFilter (asfWriter);
  304. asfWriter = nullptr;
  305. }
  306. if (ok && activeUsers > 0)
  307. mediaControl->Run();
  308. previewMaxFPS = 60;
  309. }
  310. //==============================================================================
  311. void addListener (CameraDevice::Listener* listenerToAdd)
  312. {
  313. const ScopedLock sl (listenerLock);
  314. if (listeners.size() == 0)
  315. addUser();
  316. listeners.addIfNotAlreadyThere (listenerToAdd);
  317. }
  318. void removeListener (CameraDevice::Listener* listenerToRemove)
  319. {
  320. const ScopedLock sl (listenerLock);
  321. listeners.removeFirstMatchingValue (listenerToRemove);
  322. if (listeners.size() == 0)
  323. removeUser();
  324. }
  325. void callListeners (const Image& image)
  326. {
  327. const ScopedLock sl (listenerLock);
  328. for (int i = listeners.size(); --i >= 0;)
  329. if (CameraDevice::Listener* const l = listeners[i])
  330. l->imageReceived (image);
  331. }
  332. //==============================================================================
  333. class DShowCaptureViewerComp : public Component,
  334. public ChangeListener
  335. {
  336. public:
  337. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  338. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  339. {
  340. setOpaque (true);
  341. owner->addChangeListener (this);
  342. owner->addUser();
  343. owner->viewerComps.add (this);
  344. setSize (owner->width, owner->height);
  345. }
  346. ~DShowCaptureViewerComp()
  347. {
  348. if (owner != nullptr)
  349. {
  350. owner->viewerComps.removeFirstMatchingValue (this);
  351. owner->removeUser();
  352. owner->removeChangeListener (this);
  353. }
  354. }
  355. void ownerDeleted()
  356. {
  357. owner = nullptr;
  358. }
  359. void paint (Graphics& g)
  360. {
  361. g.setColour (Colours::black);
  362. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  363. if (owner != nullptr)
  364. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  365. else
  366. g.fillAll (Colours::black);
  367. }
  368. void changeListenerCallback (ChangeBroadcaster*)
  369. {
  370. const int64 now = Time::currentTimeMillis();
  371. if (now >= lastRepaintTime + (1000 / maxFPS))
  372. {
  373. lastRepaintTime = now;
  374. repaint();
  375. if (owner != nullptr)
  376. maxFPS = owner->getPreviewMaxFPS();
  377. }
  378. }
  379. private:
  380. DShowCameraDeviceInteral* owner;
  381. int maxFPS;
  382. int64 lastRepaintTime;
  383. };
  384. //==============================================================================
  385. bool ok;
  386. int width, height;
  387. Time firstRecordedTime;
  388. Array <DShowCaptureViewerComp*> viewerComps;
  389. private:
  390. CameraDevice* const owner;
  391. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  392. ComSmartPtr <IBaseFilter> filter;
  393. ComSmartPtr <IBaseFilter> smartTee;
  394. ComSmartPtr <IGraphBuilder> graphBuilder;
  395. ComSmartPtr <ISampleGrabber> sampleGrabber;
  396. ComSmartPtr <IMediaControl> mediaControl;
  397. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  398. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  399. ComSmartPtr <IBaseFilter> asfWriter;
  400. int activeUsers;
  401. Array <int> widths, heights;
  402. DWORD graphRegistrationID;
  403. CriticalSection imageSwapLock;
  404. bool imageNeedsFlipping;
  405. Image loadingImage;
  406. Image activeImage;
  407. bool recordNextFrameTime;
  408. int previewMaxFPS;
  409. void getVideoSizes (IAMStreamConfig* const streamConfig)
  410. {
  411. widths.clear();
  412. heights.clear();
  413. int count = 0, size = 0;
  414. streamConfig->GetNumberOfCapabilities (&count, &size);
  415. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  416. {
  417. for (int i = 0; i < count; ++i)
  418. {
  419. VIDEO_STREAM_CONFIG_CAPS scc;
  420. AM_MEDIA_TYPE* config;
  421. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  422. if (SUCCEEDED (hr))
  423. {
  424. const int w = scc.InputSize.cx;
  425. const int h = scc.InputSize.cy;
  426. bool duplicate = false;
  427. for (int j = widths.size(); --j >= 0;)
  428. {
  429. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  430. {
  431. duplicate = true;
  432. break;
  433. }
  434. }
  435. if (! duplicate)
  436. {
  437. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  438. widths.add (w);
  439. heights.add (h);
  440. }
  441. deleteMediaType (config);
  442. }
  443. }
  444. }
  445. }
  446. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  447. const int minWidth, const int minHeight,
  448. const int maxWidth, const int maxHeight)
  449. {
  450. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  451. streamConfig->GetNumberOfCapabilities (&count, &size);
  452. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  453. {
  454. AM_MEDIA_TYPE* config;
  455. VIDEO_STREAM_CONFIG_CAPS scc;
  456. for (int i = 0; i < count; ++i)
  457. {
  458. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  459. if (SUCCEEDED (hr))
  460. {
  461. if (scc.InputSize.cx >= minWidth
  462. && scc.InputSize.cy >= minHeight
  463. && scc.InputSize.cx <= maxWidth
  464. && scc.InputSize.cy <= maxHeight)
  465. {
  466. int area = scc.InputSize.cx * scc.InputSize.cy;
  467. if (area > bestArea)
  468. {
  469. bestIndex = i;
  470. bestArea = area;
  471. }
  472. }
  473. deleteMediaType (config);
  474. }
  475. }
  476. if (bestIndex >= 0)
  477. {
  478. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  479. hr = streamConfig->SetFormat (config);
  480. deleteMediaType (config);
  481. return SUCCEEDED (hr);
  482. }
  483. }
  484. return false;
  485. }
  486. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection,
  487. ComSmartPtr<IPin>& result, const char* pinName = nullptr)
  488. {
  489. ComSmartPtr <IEnumPins> enumerator;
  490. ComSmartPtr <IPin> pin;
  491. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  492. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  493. {
  494. PIN_DIRECTION dir;
  495. pin->QueryDirection (&dir);
  496. if (wantedDirection == dir)
  497. {
  498. PIN_INFO info = { 0 };
  499. pin->QueryPinInfo (&info);
  500. if (pinName == nullptr || String (pinName).equalsIgnoreCase (String (info.achName)))
  501. {
  502. result = pin;
  503. return true;
  504. }
  505. }
  506. }
  507. return false;
  508. }
  509. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  510. {
  511. ComSmartPtr <IPin> in, out;
  512. return getPin (first, PINDIR_OUTPUT, out)
  513. && getPin (second, PINDIR_INPUT, in)
  514. && SUCCEEDED (graphBuilder->Connect (out, in));
  515. }
  516. bool addGraphToRot()
  517. {
  518. ComSmartPtr <IRunningObjectTable> rot;
  519. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  520. return false;
  521. ComSmartPtr <IMoniker> moniker;
  522. WCHAR buffer[128];
  523. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  524. if (FAILED (hr))
  525. return false;
  526. graphRegistrationID = 0;
  527. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  528. }
  529. void removeGraphFromRot()
  530. {
  531. ComSmartPtr <IRunningObjectTable> rot;
  532. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  533. rot->Revoke (graphRegistrationID);
  534. }
  535. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  536. {
  537. if (pmt->cbFormat != 0)
  538. CoTaskMemFree ((PVOID) pmt->pbFormat);
  539. if (pmt->pUnk != nullptr)
  540. pmt->pUnk->Release();
  541. CoTaskMemFree (pmt);
  542. }
  543. //==============================================================================
  544. class GrabberCallback : public ComBaseClassHelperBase <ISampleGrabberCB>
  545. {
  546. public:
  547. GrabberCallback (DShowCameraDeviceInteral& cam) : owner (cam) {}
  548. STDMETHODIMP SampleCB (double, IMediaSample*) { return E_FAIL; }
  549. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  550. {
  551. owner.handleFrame (time, buffer, bufferSize);
  552. return S_OK;
  553. }
  554. private:
  555. DShowCameraDeviceInteral& owner;
  556. JUCE_DECLARE_NON_COPYABLE (GrabberCallback);
  557. };
  558. ComSmartPtr <GrabberCallback> callback;
  559. Array <CameraDevice::Listener*> listeners;
  560. CriticalSection listenerLock;
  561. //==============================================================================
  562. JUCE_DECLARE_NON_COPYABLE (DShowCameraDeviceInteral);
  563. };
  564. //==============================================================================
  565. CameraDevice::CameraDevice (const String& nm, int /*index*/)
  566. : name (nm)
  567. {
  568. isRecording = false;
  569. }
  570. CameraDevice::~CameraDevice()
  571. {
  572. stopRecording();
  573. delete static_cast <DShowCameraDeviceInteral*> (internal);
  574. internal = nullptr;
  575. }
  576. Component* CameraDevice::createViewerComponent()
  577. {
  578. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  579. }
  580. String CameraDevice::getFileExtension()
  581. {
  582. return ".wmv";
  583. }
  584. void CameraDevice::startRecordingToFile (const File& file, int quality)
  585. {
  586. stopRecording();
  587. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  588. d->addUser();
  589. isRecording = d->createFileCaptureFilter (file, quality);
  590. }
  591. Time CameraDevice::getTimeOfFirstRecordedFrame() const
  592. {
  593. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  594. return d->firstRecordedTime;
  595. }
  596. void CameraDevice::stopRecording()
  597. {
  598. if (isRecording)
  599. {
  600. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  601. d->removeFileCaptureFilter();
  602. d->removeUser();
  603. isRecording = false;
  604. }
  605. }
  606. void CameraDevice::addListener (Listener* listenerToAdd)
  607. {
  608. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  609. if (listenerToAdd != nullptr)
  610. d->addListener (listenerToAdd);
  611. }
  612. void CameraDevice::removeListener (Listener* listenerToRemove)
  613. {
  614. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  615. if (listenerToRemove != nullptr)
  616. d->removeListener (listenerToRemove);
  617. }
  618. //==============================================================================
  619. namespace
  620. {
  621. ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  622. const int deviceIndexToOpen,
  623. String& name)
  624. {
  625. int index = 0;
  626. ComSmartPtr <IBaseFilter> result;
  627. ComSmartPtr <ICreateDevEnum> pDevEnum;
  628. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  629. if (SUCCEEDED (hr))
  630. {
  631. ComSmartPtr <IEnumMoniker> enumerator;
  632. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  633. if (SUCCEEDED (hr) && enumerator != nullptr)
  634. {
  635. ComSmartPtr <IMoniker> moniker;
  636. ULONG fetched;
  637. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  638. {
  639. ComSmartPtr <IBaseFilter> captureFilter;
  640. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  641. if (SUCCEEDED (hr))
  642. {
  643. ComSmartPtr <IPropertyBag> propertyBag;
  644. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  645. if (SUCCEEDED (hr))
  646. {
  647. VARIANT var;
  648. var.vt = VT_BSTR;
  649. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  650. propertyBag = nullptr;
  651. if (SUCCEEDED (hr))
  652. {
  653. if (names != nullptr)
  654. names->add (var.bstrVal);
  655. if (index == deviceIndexToOpen)
  656. {
  657. name = var.bstrVal;
  658. result = captureFilter;
  659. break;
  660. }
  661. ++index;
  662. }
  663. }
  664. }
  665. }
  666. }
  667. }
  668. return result;
  669. }
  670. }
  671. StringArray CameraDevice::getAvailableDevices()
  672. {
  673. StringArray devs;
  674. String dummy;
  675. enumerateCameras (&devs, -1, dummy);
  676. return devs;
  677. }
  678. CameraDevice* CameraDevice::openDevice (int index,
  679. int minWidth, int minHeight,
  680. int maxWidth, int maxHeight)
  681. {
  682. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  683. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  684. if (SUCCEEDED (hr))
  685. {
  686. String name;
  687. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  688. if (filter != nullptr)
  689. {
  690. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  691. DShowCameraDeviceInteral* const intern
  692. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  693. minWidth, minHeight, maxWidth, maxHeight);
  694. cam->internal = intern;
  695. if (intern->ok)
  696. return cam.release();
  697. }
  698. }
  699. return nullptr;
  700. }