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.

886 lines
31KB

  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. swapVariables (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. {
  330. CameraDevice::Listener* const l = listeners[i];
  331. if (l != nullptr)
  332. l->imageReceived (image);
  333. }
  334. }
  335. //==============================================================================
  336. class DShowCaptureViewerComp : public Component,
  337. public ChangeListener
  338. {
  339. public:
  340. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  341. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  342. {
  343. setOpaque (true);
  344. owner->addChangeListener (this);
  345. owner->addUser();
  346. owner->viewerComps.add (this);
  347. setSize (owner->width, owner->height);
  348. }
  349. ~DShowCaptureViewerComp()
  350. {
  351. if (owner != nullptr)
  352. {
  353. owner->viewerComps.removeFirstMatchingValue (this);
  354. owner->removeUser();
  355. owner->removeChangeListener (this);
  356. }
  357. }
  358. void ownerDeleted()
  359. {
  360. owner = nullptr;
  361. }
  362. void paint (Graphics& g)
  363. {
  364. g.setColour (Colours::black);
  365. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  366. if (owner != nullptr)
  367. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  368. else
  369. g.fillAll (Colours::black);
  370. }
  371. void changeListenerCallback (ChangeBroadcaster*)
  372. {
  373. const int64 now = Time::currentTimeMillis();
  374. if (now >= lastRepaintTime + (1000 / maxFPS))
  375. {
  376. lastRepaintTime = now;
  377. repaint();
  378. if (owner != nullptr)
  379. maxFPS = owner->getPreviewMaxFPS();
  380. }
  381. }
  382. private:
  383. DShowCameraDeviceInteral* owner;
  384. int maxFPS;
  385. int64 lastRepaintTime;
  386. };
  387. //==============================================================================
  388. bool ok;
  389. int width, height;
  390. Time firstRecordedTime;
  391. Array <DShowCaptureViewerComp*> viewerComps;
  392. private:
  393. CameraDevice* const owner;
  394. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  395. ComSmartPtr <IBaseFilter> filter;
  396. ComSmartPtr <IBaseFilter> smartTee;
  397. ComSmartPtr <IGraphBuilder> graphBuilder;
  398. ComSmartPtr <ISampleGrabber> sampleGrabber;
  399. ComSmartPtr <IMediaControl> mediaControl;
  400. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  401. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  402. ComSmartPtr <IBaseFilter> asfWriter;
  403. int activeUsers;
  404. Array <int> widths, heights;
  405. DWORD graphRegistrationID;
  406. CriticalSection imageSwapLock;
  407. bool imageNeedsFlipping;
  408. Image loadingImage;
  409. Image activeImage;
  410. bool recordNextFrameTime;
  411. int previewMaxFPS;
  412. void getVideoSizes (IAMStreamConfig* const streamConfig)
  413. {
  414. widths.clear();
  415. heights.clear();
  416. int count = 0, size = 0;
  417. streamConfig->GetNumberOfCapabilities (&count, &size);
  418. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  419. {
  420. for (int i = 0; i < count; ++i)
  421. {
  422. VIDEO_STREAM_CONFIG_CAPS scc;
  423. AM_MEDIA_TYPE* config;
  424. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  425. if (SUCCEEDED (hr))
  426. {
  427. const int w = scc.InputSize.cx;
  428. const int h = scc.InputSize.cy;
  429. bool duplicate = false;
  430. for (int j = widths.size(); --j >= 0;)
  431. {
  432. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  433. {
  434. duplicate = true;
  435. break;
  436. }
  437. }
  438. if (! duplicate)
  439. {
  440. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  441. widths.add (w);
  442. heights.add (h);
  443. }
  444. deleteMediaType (config);
  445. }
  446. }
  447. }
  448. }
  449. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  450. const int minWidth, const int minHeight,
  451. const int maxWidth, const int maxHeight)
  452. {
  453. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  454. streamConfig->GetNumberOfCapabilities (&count, &size);
  455. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  456. {
  457. AM_MEDIA_TYPE* config;
  458. VIDEO_STREAM_CONFIG_CAPS scc;
  459. for (int i = 0; i < count; ++i)
  460. {
  461. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  462. if (SUCCEEDED (hr))
  463. {
  464. if (scc.InputSize.cx >= minWidth
  465. && scc.InputSize.cy >= minHeight
  466. && scc.InputSize.cx <= maxWidth
  467. && scc.InputSize.cy <= maxHeight)
  468. {
  469. int area = scc.InputSize.cx * scc.InputSize.cy;
  470. if (area > bestArea)
  471. {
  472. bestIndex = i;
  473. bestArea = area;
  474. }
  475. }
  476. deleteMediaType (config);
  477. }
  478. }
  479. if (bestIndex >= 0)
  480. {
  481. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  482. hr = streamConfig->SetFormat (config);
  483. deleteMediaType (config);
  484. return SUCCEEDED (hr);
  485. }
  486. }
  487. return false;
  488. }
  489. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection,
  490. ComSmartPtr<IPin>& result, const char* pinName = nullptr)
  491. {
  492. ComSmartPtr <IEnumPins> enumerator;
  493. ComSmartPtr <IPin> pin;
  494. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  495. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  496. {
  497. PIN_DIRECTION dir;
  498. pin->QueryDirection (&dir);
  499. if (wantedDirection == dir)
  500. {
  501. PIN_INFO info = { 0 };
  502. pin->QueryPinInfo (&info);
  503. if (pinName == nullptr || String (pinName).equalsIgnoreCase (String (info.achName)))
  504. {
  505. result = pin;
  506. return true;
  507. }
  508. }
  509. }
  510. return false;
  511. }
  512. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  513. {
  514. ComSmartPtr <IPin> in, out;
  515. return getPin (first, PINDIR_OUTPUT, out)
  516. && getPin (second, PINDIR_INPUT, in)
  517. && SUCCEEDED (graphBuilder->Connect (out, in));
  518. }
  519. bool addGraphToRot()
  520. {
  521. ComSmartPtr <IRunningObjectTable> rot;
  522. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  523. return false;
  524. ComSmartPtr <IMoniker> moniker;
  525. WCHAR buffer[128];
  526. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  527. if (FAILED (hr))
  528. return false;
  529. graphRegistrationID = 0;
  530. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  531. }
  532. void removeGraphFromRot()
  533. {
  534. ComSmartPtr <IRunningObjectTable> rot;
  535. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  536. rot->Revoke (graphRegistrationID);
  537. }
  538. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  539. {
  540. if (pmt->cbFormat != 0)
  541. CoTaskMemFree ((PVOID) pmt->pbFormat);
  542. if (pmt->pUnk != nullptr)
  543. pmt->pUnk->Release();
  544. CoTaskMemFree (pmt);
  545. }
  546. //==============================================================================
  547. class GrabberCallback : public ComBaseClassHelperBase <ISampleGrabberCB>
  548. {
  549. public:
  550. GrabberCallback (DShowCameraDeviceInteral& owner_) : owner (owner_) {}
  551. JUCE_COMRESULT QueryInterface (REFIID refId, void** result)
  552. {
  553. if (refId == IID_ISampleGrabberCB) { AddRef(); *result = dynamic_cast <ISampleGrabberCB*> (this); return S_OK; }
  554. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  555. *result = nullptr;
  556. return E_NOINTERFACE;
  557. }
  558. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/) { return E_FAIL; }
  559. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  560. {
  561. owner.handleFrame (time, buffer, bufferSize);
  562. return S_OK;
  563. }
  564. private:
  565. DShowCameraDeviceInteral& owner;
  566. JUCE_DECLARE_NON_COPYABLE (GrabberCallback);
  567. };
  568. ComSmartPtr <GrabberCallback> callback;
  569. Array <CameraDevice::Listener*> listeners;
  570. CriticalSection listenerLock;
  571. //==============================================================================
  572. JUCE_DECLARE_NON_COPYABLE (DShowCameraDeviceInteral);
  573. };
  574. //==============================================================================
  575. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  576. : name (name_)
  577. {
  578. isRecording = false;
  579. }
  580. CameraDevice::~CameraDevice()
  581. {
  582. stopRecording();
  583. delete static_cast <DShowCameraDeviceInteral*> (internal);
  584. internal = nullptr;
  585. }
  586. Component* CameraDevice::createViewerComponent()
  587. {
  588. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  589. }
  590. String CameraDevice::getFileExtension()
  591. {
  592. return ".wmv";
  593. }
  594. void CameraDevice::startRecordingToFile (const File& file, int quality)
  595. {
  596. stopRecording();
  597. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  598. d->addUser();
  599. isRecording = d->createFileCaptureFilter (file, quality);
  600. }
  601. Time CameraDevice::getTimeOfFirstRecordedFrame() const
  602. {
  603. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  604. return d->firstRecordedTime;
  605. }
  606. void CameraDevice::stopRecording()
  607. {
  608. if (isRecording)
  609. {
  610. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  611. d->removeFileCaptureFilter();
  612. d->removeUser();
  613. isRecording = false;
  614. }
  615. }
  616. void CameraDevice::addListener (Listener* listenerToAdd)
  617. {
  618. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  619. if (listenerToAdd != nullptr)
  620. d->addListener (listenerToAdd);
  621. }
  622. void CameraDevice::removeListener (Listener* listenerToRemove)
  623. {
  624. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  625. if (listenerToRemove != nullptr)
  626. d->removeListener (listenerToRemove);
  627. }
  628. //==============================================================================
  629. namespace
  630. {
  631. ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  632. const int deviceIndexToOpen,
  633. String& name)
  634. {
  635. int index = 0;
  636. ComSmartPtr <IBaseFilter> result;
  637. ComSmartPtr <ICreateDevEnum> pDevEnum;
  638. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  639. if (SUCCEEDED (hr))
  640. {
  641. ComSmartPtr <IEnumMoniker> enumerator;
  642. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  643. if (SUCCEEDED (hr) && enumerator != nullptr)
  644. {
  645. ComSmartPtr <IMoniker> moniker;
  646. ULONG fetched;
  647. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  648. {
  649. ComSmartPtr <IBaseFilter> captureFilter;
  650. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  651. if (SUCCEEDED (hr))
  652. {
  653. ComSmartPtr <IPropertyBag> propertyBag;
  654. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  655. if (SUCCEEDED (hr))
  656. {
  657. VARIANT var;
  658. var.vt = VT_BSTR;
  659. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  660. propertyBag = nullptr;
  661. if (SUCCEEDED (hr))
  662. {
  663. if (names != nullptr)
  664. names->add (var.bstrVal);
  665. if (index == deviceIndexToOpen)
  666. {
  667. name = var.bstrVal;
  668. result = captureFilter;
  669. break;
  670. }
  671. ++index;
  672. }
  673. }
  674. }
  675. }
  676. }
  677. }
  678. return result;
  679. }
  680. }
  681. StringArray CameraDevice::getAvailableDevices()
  682. {
  683. StringArray devs;
  684. String dummy;
  685. enumerateCameras (&devs, -1, dummy);
  686. return devs;
  687. }
  688. CameraDevice* CameraDevice::openDevice (int index,
  689. int minWidth, int minHeight,
  690. int maxWidth, int maxHeight)
  691. {
  692. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  693. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  694. if (SUCCEEDED (hr))
  695. {
  696. String name;
  697. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  698. if (filter != nullptr)
  699. {
  700. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  701. DShowCameraDeviceInteral* const intern
  702. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  703. minWidth, minHeight, maxWidth, maxHeight);
  704. cam->internal = intern;
  705. if (intern->ok)
  706. return cam.release();
  707. }
  708. }
  709. return nullptr;
  710. }