plugin_win_mf_consumer_video.cxx 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547
  1. /* Copyright (C) 2013 Mamadou DIOP
  2. * Copyright (C) 2013 Doubango Telecom <http://www.doubango.org>
  3. *
  4. * This file is part of Open Source Doubango Framework.
  5. *
  6. * DOUBANGO is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * DOUBANGO is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with DOUBANGO.
  18. */
  19. #include "plugin_win_mf_config.h"
  20. #include "internals/mf_utils.h"
  21. #include "tinymedia/tmedia_consumer.h"
  22. #include "tsk_safeobj.h"
  23. #include "tsk_string.h"
  24. #include "tsk_thread.h"
  25. #include "tsk_debug.h"
  26. #include <initguid.h>
  27. #include <assert.h>
  28. // Whether to use Direct3D device for direct rendering or Media Foundation topology and custom source
  29. // Using Media Foundation (MF) introduce delay when the input fps is different than the one in the custom src.
  30. // It's very hard to have someting accurate when using MF because the input FPS change depending on the congestion control. D3D is the best choice as frames are displayed as they arrive
  31. #if !defined(PLUGIN_MF_CV_USE_D3D9)
  32. # define PLUGIN_MF_CV_USE_D3D9 1
  33. #endif
  34. /******* ********/
  35. #if PLUGIN_MF_CV_USE_D3D9
  36. #include <d3d9.h>
  37. #include <dxva2api.h>
  38. #ifdef _MSC_VER
  39. #pragma comment(lib, "d3d9")
  40. #endif
  41. const DWORD NUM_BACK_BUFFERS = 2;
  42. static HRESULT CreateDeviceD3D9(
  43. HWND hWnd,
  44. IDirect3DDevice9** ppDevice,
  45. IDirect3D9 **ppD3D,
  46. D3DPRESENT_PARAMETERS &d3dpp
  47. );
  48. static HRESULT TestCooperativeLevel(
  49. struct plugin_win_mf_consumer_video_s *pSelf
  50. );
  51. static HRESULT CreateSwapChain(
  52. HWND hWnd,
  53. UINT32 nFrameWidth,
  54. UINT32 nFrameHeight,
  55. IDirect3DDevice9* pDevice,
  56. IDirect3DSwapChain9 **ppSwapChain);
  57. static LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
  58. static inline HWND Window(struct plugin_win_mf_consumer_video_s *pSelf);
  59. static inline LONG Width(const RECT& r);
  60. static inline LONG Height(const RECT& r);
  61. static inline RECT CorrectAspectRatio(const RECT& src, const MFRatio& srcPAR);
  62. static inline RECT LetterBoxRect(const RECT& rcSrc, const RECT& rcDst);
  63. static inline HRESULT UpdateDestinationRect(struct plugin_win_mf_consumer_video_s *pSelf, BOOL bForce = FALSE);
  64. static HRESULT ResetDevice(struct plugin_win_mf_consumer_video_s *pSelf, BOOL bUpdateDestinationRect = FALSE);
  65. static HRESULT SetFullscreen(struct plugin_win_mf_consumer_video_s *pSelf, BOOL bFullScreen);
  66. static HWND CreateFullScreenWindow(struct plugin_win_mf_consumer_video_s *pSelf);
  67. static HRESULT HookWindow(struct plugin_win_mf_consumer_video_s *pSelf, HWND hWnd);
  68. static HRESULT UnhookWindow(struct plugin_win_mf_consumer_video_s *pSelf);
  69. typedef struct plugin_win_mf_consumer_video_s {
  70. TMEDIA_DECLARE_CONSUMER;
  71. BOOL bStarted, bPrepared, bPaused, bFullScreen, bWindowHooked;
  72. BOOL bPluginFireFox, bPluginWebRTC4All;
  73. HWND hWindow;
  74. WNDPROC wndProc;
  75. HWND hWindowFullScreen;
  76. RECT rcWindow;
  77. RECT rcDest;
  78. MFRatio pixelAR;
  79. UINT32 nNegWidth;
  80. UINT32 nNegHeight;
  81. UINT32 nNegFps;
  82. D3DLOCKED_RECT rcLock;
  83. IDirect3DDevice9* pDevice;
  84. IDirect3D9 *pD3D;
  85. IDirect3DSwapChain9 *pSwapChain;
  86. D3DPRESENT_PARAMETERS d3dpp;
  87. TSK_DECLARE_SAFEOBJ;
  88. }
  89. plugin_win_mf_consumer_video_t;
  90. static int _plugin_win_mf_consumer_video_unprepare(plugin_win_mf_consumer_video_t* pSelf);
  91. /* ============ Media Consumer Interface ================= */
  92. static int plugin_win_mf_consumer_video_set(tmedia_consumer_t *self, const tmedia_param_t* param)
  93. {
  94. int ret = 0;
  95. HRESULT hr = S_OK;
  96. plugin_win_mf_consumer_video_t* pSelf = (plugin_win_mf_consumer_video_t*)self;
  97. if(!self || !param) {
  98. TSK_DEBUG_ERROR("Invalid parameter");
  99. CHECK_HR(hr = E_POINTER);
  100. }
  101. if(param->value_type == tmedia_pvt_int64) {
  102. if(tsk_striequals(param->key, "remote-hwnd")) {
  103. HWND hWnd = reinterpret_cast<HWND>((INT64)*((int64_t*)param->value));
  104. if(hWnd != pSelf->hWindow) {
  105. tsk_safeobj_lock(pSelf); // block consumer thread
  106. pSelf->hWindow = hWnd;
  107. if(pSelf->bPrepared) {
  108. hr = ResetDevice(pSelf);
  109. }
  110. tsk_safeobj_unlock(pSelf); // unblock consumer thread
  111. }
  112. }
  113. }
  114. else if(param->value_type == tmedia_pvt_int32) {
  115. if(tsk_striequals(param->key, "fullscreen")) {
  116. BOOL bFullScreen = !!*((int32_t*)param->value);
  117. TSK_DEBUG_INFO("[MF video consumer] Full Screen = %d", bFullScreen);
  118. CHECK_HR(hr = SetFullscreen(pSelf, bFullScreen));
  119. }
  120. else if(tsk_striequals(param->key, "create-on-current-thead")) {
  121. // DSCONSUMER(self)->create_on_ui_thread = *((int32_t*)param->value) ? tsk_false : tsk_true;
  122. }
  123. else if(tsk_striequals(param->key, "plugin-firefox")) {
  124. pSelf->bPluginFireFox = (*((int32_t*)param->value) != 0);
  125. }
  126. else if(tsk_striequals(param->key, "plugin-webrtc4all")) {
  127. pSelf->bPluginWebRTC4All = (*((int32_t*)param->value) != 0);
  128. }
  129. }
  130. CHECK_HR(hr);
  131. bail:
  132. return SUCCEEDED(hr) ? 0 : -1;
  133. }
  134. static int plugin_win_mf_consumer_video_prepare(tmedia_consumer_t* self, const tmedia_codec_t* codec)
  135. {
  136. plugin_win_mf_consumer_video_t* pSelf = (plugin_win_mf_consumer_video_t*)self;
  137. if(!pSelf || !codec && codec->plugin) {
  138. TSK_DEBUG_ERROR("Invalid parameter");
  139. return -1;
  140. }
  141. if(pSelf->bPrepared) {
  142. TSK_DEBUG_WARN("D3D9 video consumer already prepared");
  143. return -1;
  144. }
  145. // FIXME: DirectShow requires flipping but not D3D9
  146. // The Core library always tries to flip when OSType==Win32. Must be changed
  147. TMEDIA_CODEC_VIDEO(codec)->in.flip = tsk_false;
  148. HRESULT hr = S_OK;
  149. HWND hWnd = Window(pSelf);
  150. TMEDIA_CONSUMER(pSelf)->video.fps = TMEDIA_CODEC_VIDEO(codec)->in.fps;
  151. TMEDIA_CONSUMER(pSelf)->video.in.width = TMEDIA_CODEC_VIDEO(codec)->in.width;
  152. TMEDIA_CONSUMER(pSelf)->video.in.height = TMEDIA_CODEC_VIDEO(codec)->in.height;
  153. if(!TMEDIA_CONSUMER(pSelf)->video.display.width) {
  154. TMEDIA_CONSUMER(pSelf)->video.display.width = TMEDIA_CONSUMER(pSelf)->video.in.width;
  155. }
  156. if(!TMEDIA_CONSUMER(pSelf)->video.display.height) {
  157. TMEDIA_CONSUMER(pSelf)->video.display.height = TMEDIA_CONSUMER(pSelf)->video.in.height;
  158. }
  159. pSelf->nNegFps = TMEDIA_CONSUMER(pSelf)->video.fps;
  160. pSelf->nNegWidth = (UINT32)TMEDIA_CONSUMER(pSelf)->video.display.width;
  161. pSelf->nNegHeight = (UINT32)TMEDIA_CONSUMER(pSelf)->video.display.height;
  162. TSK_DEBUG_INFO("D3D9 video consumer: fps=%d, width=%d, height=%d",
  163. pSelf->nNegFps,
  164. pSelf->nNegWidth,
  165. pSelf->nNegHeight);
  166. TMEDIA_CONSUMER(pSelf)->video.display.chroma = tmedia_chroma_rgb32;
  167. TMEDIA_CONSUMER(pSelf)->decoder.codec_id = tmedia_codec_id_none; // means accept RAW fames
  168. // The window handle is not created until the call is connect (incoming only) - At least on Internet Explorer 10
  169. if(hWnd && !pSelf->bPluginWebRTC4All) {
  170. CHECK_HR(hr = CreateDeviceD3D9(hWnd, &pSelf->pDevice, &pSelf->pD3D, pSelf->d3dpp));
  171. CHECK_HR(hr = CreateSwapChain(hWnd, pSelf->nNegWidth, pSelf->nNegHeight, pSelf->pDevice, &pSelf->pSwapChain));
  172. }
  173. else {
  174. if(hWnd && pSelf->bPluginWebRTC4All) {
  175. TSK_DEBUG_INFO("[MF consumer] HWND is defined but we detected webrtc4all...delaying D3D9 device creating until session get connected");
  176. }
  177. else {
  178. TSK_DEBUG_WARN("Delaying D3D9 device creation because HWND is not defined yet");
  179. }
  180. }
  181. bail:
  182. pSelf->bPrepared = SUCCEEDED(hr);
  183. return pSelf->bPrepared ? 0 : -1;
  184. }
  185. static int plugin_win_mf_consumer_video_start(tmedia_consumer_t* self)
  186. {
  187. plugin_win_mf_consumer_video_t* pSelf = (plugin_win_mf_consumer_video_t*)self;
  188. if(!pSelf) {
  189. TSK_DEBUG_ERROR("Invalid parameter");
  190. return -1;
  191. }
  192. if(pSelf->bStarted) {
  193. TSK_DEBUG_INFO("D3D9 video consumer already started");
  194. return 0;
  195. }
  196. if(!pSelf->bPrepared) {
  197. TSK_DEBUG_ERROR("D3D9 video consumer not prepared");
  198. return -1;
  199. }
  200. HRESULT hr = S_OK;
  201. pSelf->bPaused = false;
  202. pSelf->bStarted = true;
  203. return SUCCEEDED(hr) ? 0 : -1;
  204. }
  205. static int plugin_win_mf_consumer_video_consume(tmedia_consumer_t* self, const void* buffer, tsk_size_t size, const tsk_object_t* proto_hdr)
  206. {
  207. plugin_win_mf_consumer_video_t* pSelf = (plugin_win_mf_consumer_video_t*)self;
  208. HRESULT hr = S_OK;
  209. HWND hWnd = Window(pSelf);
  210. IDirect3DSurface9 *pSurf = NULL;
  211. IDirect3DSurface9 *pBB = NULL;
  212. if(!pSelf) {
  213. TSK_DEBUG_ERROR("Invalid parameter");
  214. return -1; // because of the mutex lock do it here
  215. }
  216. tsk_safeobj_lock(pSelf);
  217. if(!buffer || !size) {
  218. TSK_DEBUG_ERROR("Invalid parameter");
  219. CHECK_HR(hr = E_INVALIDARG);
  220. }
  221. if(!pSelf->bStarted) {
  222. TSK_DEBUG_INFO("D3D9 video consumer not started");
  223. CHECK_HR(hr = E_FAIL);
  224. }
  225. if(!hWnd) {
  226. TSK_DEBUG_INFO("Do not draw frame because HWND not set");
  227. goto bail; // not an error as the application can decide to set the HWND at any time
  228. }
  229. if (!pSelf->bWindowHooked) {
  230. // Do not hook "hWnd" as it could be the fullscreen handle which is always hooked.
  231. CHECK_HR(hr = HookWindow(pSelf, pSelf->hWindow));
  232. }
  233. if(!pSelf->pDevice || !pSelf->pD3D || !pSelf->pSwapChain) {
  234. if(pSelf->pDevice || pSelf->pD3D || pSelf->pSwapChain) {
  235. CHECK_HR(hr = E_POINTER); // They must be "all null" or "all valid"
  236. }
  237. if(hWnd) {
  238. // means HWND was not set but defined now
  239. pSelf->nNegWidth = (UINT32)TMEDIA_CONSUMER(pSelf)->video.in.width;
  240. pSelf->nNegHeight = (UINT32)TMEDIA_CONSUMER(pSelf)->video.in.height;
  241. CHECK_HR(hr = CreateDeviceD3D9(hWnd, &pSelf->pDevice, &pSelf->pD3D, pSelf->d3dpp));
  242. CHECK_HR(hr = CreateSwapChain(hWnd, pSelf->nNegWidth, pSelf->nNegHeight, pSelf->pDevice, &pSelf->pSwapChain));
  243. }
  244. }
  245. if(pSelf->nNegWidth != TMEDIA_CONSUMER(pSelf)->video.in.width || pSelf->nNegHeight != TMEDIA_CONSUMER(pSelf)->video.in.height) {
  246. TSK_DEBUG_INFO("Negotiated and input video sizes are different:%d#%d or %d#%d",
  247. pSelf->nNegWidth, TMEDIA_CONSUMER(pSelf)->video.in.width,
  248. pSelf->nNegHeight, TMEDIA_CONSUMER(pSelf)->video.in.height);
  249. // Update media type
  250. SafeRelease(&pSelf->pSwapChain);
  251. CHECK_HR(hr = CreateSwapChain(hWnd, (UINT32)TMEDIA_CONSUMER(pSelf)->video.in.width, (UINT32)TMEDIA_CONSUMER(pSelf)->video.in.height, pSelf->pDevice, &pSelf->pSwapChain));
  252. pSelf->nNegWidth = (UINT32)TMEDIA_CONSUMER(pSelf)->video.in.width;
  253. pSelf->nNegHeight = (UINT32)TMEDIA_CONSUMER(pSelf)->video.in.height;
  254. // Update Destination will do noting if the window size haven't changed.
  255. // Force updating the destination rect if negotiated size change
  256. CHECK_HR(hr = UpdateDestinationRect(pSelf, TRUE/* Force */));
  257. }
  258. CHECK_HR(hr = TestCooperativeLevel(pSelf));
  259. CHECK_HR(hr = UpdateDestinationRect(pSelf));
  260. CHECK_HR(hr = pSelf->pSwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &pSurf));
  261. CHECK_HR(hr = pSurf->LockRect(&pSelf->rcLock, NULL, D3DLOCK_NOSYSLOCK ));
  262. // Fast copy() using MMX, SSE, or SSE2
  263. hr = MFCopyImage(
  264. (BYTE*)pSelf->rcLock.pBits,
  265. pSelf->rcLock.Pitch,
  266. (BYTE*)buffer,
  267. (pSelf->nNegWidth << 2),
  268. (pSelf->nNegWidth << 2),
  269. pSelf->nNegHeight
  270. );
  271. if(FAILED(hr)) {
  272. // unlock() before leaving
  273. pSurf->UnlockRect();
  274. CHECK_HR(hr);
  275. }
  276. CHECK_HR(hr = pSurf->UnlockRect());
  277. // Color fill the back buffer
  278. CHECK_HR(hr = pSelf->pDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &pBB));
  279. #if METROPOLIS
  280. CHECK_HR(hr = pSelf->pDevice->ColorFill(pBB, NULL, D3DCOLOR_XRGB(0x00, 0x00, 0x00)));
  281. #else
  282. CHECK_HR(hr = pSelf->pDevice->ColorFill(pBB, NULL, D3DCOLOR_XRGB(0xFF, 0xFF, 0xFF)));
  283. #endif
  284. // Resize keeping aspect ratio and Blit the frame (required)
  285. hr = pSelf->pDevice->StretchRect(
  286. pSurf,
  287. NULL,
  288. pBB,
  289. &pSelf->rcDest/*NULL*/,
  290. D3DTEXF_LINEAR
  291. ); // could fail when display is being resized
  292. if(SUCCEEDED(hr)) {
  293. // Present the frame
  294. CHECK_HR(hr = pSelf->pDevice->Present(NULL, NULL, NULL, NULL));
  295. }
  296. else {
  297. TSK_DEBUG_INFO("StretchRect returned ...%x", hr);
  298. }
  299. bail:
  300. SafeRelease(&pSurf);
  301. SafeRelease(&pBB);
  302. tsk_safeobj_unlock(pSelf);
  303. return SUCCEEDED(hr) ? 0 : -1;
  304. }
  305. static int plugin_win_mf_consumer_video_pause(tmedia_consumer_t* self)
  306. {
  307. plugin_win_mf_consumer_video_t* pSelf = (plugin_win_mf_consumer_video_t*)self;
  308. if(!pSelf) {
  309. TSK_DEBUG_ERROR("Invalid parameter");
  310. return -1;
  311. }
  312. if(!pSelf->bStarted) {
  313. TSK_DEBUG_INFO("MF video producer not started");
  314. return 0;
  315. }
  316. HRESULT hr = S_OK;
  317. pSelf->bPaused = true;
  318. return SUCCEEDED(hr) ? 0 : -1;
  319. }
  320. static int plugin_win_mf_consumer_video_stop(tmedia_consumer_t* self)
  321. {
  322. plugin_win_mf_consumer_video_t* pSelf = (plugin_win_mf_consumer_video_t*)self;
  323. if(!pSelf) {
  324. TSK_DEBUG_ERROR("Invalid parameter");
  325. return -1;
  326. }
  327. HRESULT hr = S_OK;
  328. pSelf->bStarted = false;
  329. pSelf->bPaused = false;
  330. if(pSelf->hWindowFullScreen) {
  331. ::InvalidateRect(pSelf->hWindowFullScreen, NULL, FALSE);
  332. ::ShowWindow(pSelf->hWindowFullScreen, SW_HIDE);
  333. }
  334. // next start() will be called after prepare()
  335. return _plugin_win_mf_consumer_video_unprepare(pSelf);
  336. }
  337. static int _plugin_win_mf_consumer_video_unprepare(plugin_win_mf_consumer_video_t* pSelf)
  338. {
  339. if(!pSelf) {
  340. TSK_DEBUG_ERROR("Invalid parameter");
  341. return -1;
  342. }
  343. UnhookWindow(pSelf);
  344. if(pSelf->bStarted) {
  345. // plugin_win_mf_producer_video_stop(TMEDIA_PRODUCER(pSelf));
  346. TSK_DEBUG_ERROR("Consumer must be stopped before calling unprepare");
  347. return -1;
  348. }
  349. SafeRelease(&pSelf->pDevice);
  350. SafeRelease(&pSelf->pD3D);
  351. SafeRelease(&pSelf->pSwapChain);
  352. pSelf->bPrepared = false;
  353. return 0;
  354. }
  355. //
  356. // D3D9 video consumer object definition
  357. //
  358. /* constructor */
  359. static tsk_object_t* plugin_win_mf_consumer_video_ctor(tsk_object_t * self, va_list * app)
  360. {
  361. MFUtils::Startup();
  362. plugin_win_mf_consumer_video_t *pSelf = (plugin_win_mf_consumer_video_t *)self;
  363. if(pSelf) {
  364. /* init base */
  365. tmedia_consumer_init(TMEDIA_CONSUMER(pSelf));
  366. TMEDIA_CONSUMER(pSelf)->video.display.chroma = tmedia_chroma_rgb32;
  367. TMEDIA_CONSUMER(pSelf)->decoder.codec_id = tmedia_codec_id_none; // means accept RAW fames
  368. /* init self */
  369. tsk_safeobj_init(pSelf);
  370. TMEDIA_CONSUMER(pSelf)->video.fps = 15;
  371. TMEDIA_CONSUMER(pSelf)->video.display.width = 0; // use codec value
  372. TMEDIA_CONSUMER(pSelf)->video.display.height = 0; // use codec value
  373. TMEDIA_CONSUMER(pSelf)->video.display.auto_resize = tsk_true;
  374. pSelf->pixelAR.Denominator = pSelf->pixelAR.Numerator = 1;
  375. }
  376. return self;
  377. }
  378. /* destructor */
  379. static tsk_object_t* plugin_win_mf_consumer_video_dtor(tsk_object_t * self)
  380. {
  381. plugin_win_mf_consumer_video_t *pSelf = (plugin_win_mf_consumer_video_t *)self;
  382. if(pSelf) {
  383. /* stop */
  384. if(pSelf->bStarted) {
  385. plugin_win_mf_consumer_video_stop(TMEDIA_CONSUMER(pSelf));
  386. }
  387. /* deinit base */
  388. tmedia_consumer_deinit(TMEDIA_CONSUMER(pSelf));
  389. /* deinit self */
  390. _plugin_win_mf_consumer_video_unprepare(pSelf);
  391. tsk_safeobj_deinit(pSelf);
  392. }
  393. return self;
  394. }
  395. /* object definition */
  396. static const tsk_object_def_t plugin_win_mf_consumer_video_def_s = {
  397. sizeof(plugin_win_mf_consumer_video_t),
  398. plugin_win_mf_consumer_video_ctor,
  399. plugin_win_mf_consumer_video_dtor,
  400. tsk_null,
  401. };
  402. /* plugin definition*/
  403. static const tmedia_consumer_plugin_def_t plugin_win_mf_consumer_video_plugin_def_s = {
  404. &plugin_win_mf_consumer_video_def_s,
  405. tmedia_video,
  406. "D3D9 video consumer",
  407. plugin_win_mf_consumer_video_set,
  408. plugin_win_mf_consumer_video_prepare,
  409. plugin_win_mf_consumer_video_start,
  410. plugin_win_mf_consumer_video_consume,
  411. plugin_win_mf_consumer_video_pause,
  412. plugin_win_mf_consumer_video_stop
  413. };
  414. const tmedia_consumer_plugin_def_t *plugin_win_mf_consumer_video_plugin_def_t = &plugin_win_mf_consumer_video_plugin_def_s;
  415. // Helper functions
  416. static HRESULT CreateDeviceD3D9(
  417. HWND hWnd,
  418. IDirect3DDevice9** ppDevice,
  419. IDirect3D9 **ppD3D,
  420. D3DPRESENT_PARAMETERS &d3dpp
  421. )
  422. {
  423. HRESULT hr = S_OK;
  424. D3DDISPLAYMODE mode = { 0 };
  425. D3DPRESENT_PARAMETERS pp = {0};
  426. if(!ppDevice || *ppDevice || !ppD3D || *ppD3D) {
  427. CHECK_HR(hr = E_POINTER);
  428. }
  429. if(!(*ppD3D = Direct3DCreate9(D3D_SDK_VERSION))) {
  430. CHECK_HR(hr = E_OUTOFMEMORY);
  431. }
  432. CHECK_HR(hr = (*ppD3D)->GetAdapterDisplayMode(
  433. D3DADAPTER_DEFAULT,
  434. &mode
  435. ));
  436. CHECK_HR(hr = (*ppD3D)->CheckDeviceType(
  437. D3DADAPTER_DEFAULT,
  438. D3DDEVTYPE_HAL,
  439. mode.Format,
  440. D3DFMT_X8R8G8B8,
  441. TRUE // windowed
  442. ));
  443. pp.BackBufferFormat = D3DFMT_X8R8G8B8;
  444. pp.SwapEffect = D3DSWAPEFFECT_DISCARD;
  445. pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  446. pp.Windowed = TRUE;
  447. pp.hDeviceWindow = hWnd;
  448. CHECK_HR(hr = (*ppD3D)->CreateDevice(
  449. D3DADAPTER_DEFAULT,
  450. D3DDEVTYPE_HAL,
  451. hWnd,
  452. D3DCREATE_HARDWARE_VERTEXPROCESSING,
  453. &pp,
  454. ppDevice
  455. ));
  456. d3dpp = pp;
  457. bail:
  458. if(FAILED(hr)) {
  459. SafeRelease(ppD3D);
  460. SafeRelease(ppDevice);
  461. }
  462. return hr;
  463. }
  464. static HRESULT TestCooperativeLevel(
  465. struct plugin_win_mf_consumer_video_s *pSelf
  466. )
  467. {
  468. HRESULT hr = S_OK;
  469. if (!pSelf || !pSelf->pDevice) {
  470. CHECK_HR(hr = E_POINTER);
  471. }
  472. switch((hr = pSelf->pDevice->TestCooperativeLevel())) {
  473. case D3D_OK: {
  474. break;
  475. }
  476. case D3DERR_DEVICELOST: {
  477. hr = S_OK;
  478. break;
  479. }
  480. case D3DERR_DEVICENOTRESET: {
  481. hr = ResetDevice(pSelf, TRUE);
  482. break;
  483. }
  484. default: {
  485. break;
  486. }
  487. }
  488. CHECK_HR(hr);
  489. bail:
  490. return hr;
  491. }
  492. static HRESULT CreateSwapChain(
  493. HWND hWnd,
  494. UINT32 nFrameWidth,
  495. UINT32 nFrameHeight,
  496. IDirect3DDevice9* pDevice,
  497. IDirect3DSwapChain9 **ppSwapChain
  498. )
  499. {
  500. HRESULT hr = S_OK;
  501. D3DPRESENT_PARAMETERS pp = { 0 };
  502. if(!pDevice || !ppSwapChain || *ppSwapChain) {
  503. CHECK_HR(hr = E_POINTER);
  504. }
  505. pp.BackBufferWidth = nFrameWidth;
  506. pp.BackBufferHeight = nFrameHeight;
  507. pp.Windowed = TRUE;
  508. pp.SwapEffect = D3DSWAPEFFECT_FLIP;
  509. pp.hDeviceWindow = hWnd;
  510. pp.BackBufferFormat = D3DFMT_X8R8G8B8;
  511. pp.Flags =
  512. D3DPRESENTFLAG_VIDEO | D3DPRESENTFLAG_DEVICECLIP |
  513. D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;
  514. pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  515. pp.BackBufferCount = NUM_BACK_BUFFERS;
  516. CHECK_HR(hr = pDevice->CreateAdditionalSwapChain(&pp, ppSwapChain));
  517. bail:
  518. return hr;
  519. }
  520. static inline HWND Window(struct plugin_win_mf_consumer_video_s *pSelf)
  521. {
  522. return pSelf ? (pSelf->bFullScreen ? pSelf->hWindowFullScreen : pSelf->hWindow) : NULL;
  523. }
  524. static inline LONG Width(const RECT& r)
  525. {
  526. return r.right - r.left;
  527. }
  528. static inline LONG Height(const RECT& r)
  529. {
  530. return r.bottom - r.top;
  531. }
  532. //-----------------------------------------------------------------------------
  533. // CorrectAspectRatio
  534. //
  535. // Converts a rectangle from the source's pixel aspect ratio (PAR) to 1:1 PAR.
  536. // Returns the corrected rectangle.
  537. //
  538. // For example, a 720 x 486 rect with a PAR of 9:10, when converted to 1x1 PAR,
  539. // is stretched to 720 x 540.
  540. // Copyright (C) Microsoft
  541. //-----------------------------------------------------------------------------
  542. static inline RECT CorrectAspectRatio(const RECT& src, const MFRatio& srcPAR)
  543. {
  544. // Start with a rectangle the same size as src, but offset to the origin (0,0).
  545. RECT rc = {0, 0, src.right - src.left, src.bottom - src.top};
  546. if ((srcPAR.Numerator != 1) || (srcPAR.Denominator != 1)) {
  547. // Correct for the source's PAR.
  548. if (srcPAR.Numerator > srcPAR.Denominator) {
  549. // The source has "wide" pixels, so stretch the width.
  550. rc.right = MulDiv(rc.right, srcPAR.Numerator, srcPAR.Denominator);
  551. }
  552. else if (srcPAR.Numerator < srcPAR.Denominator) {
  553. // The source has "tall" pixels, so stretch the height.
  554. rc.bottom = MulDiv(rc.bottom, srcPAR.Denominator, srcPAR.Numerator);
  555. }
  556. // else: PAR is 1:1, which is a no-op.
  557. }
  558. return rc;
  559. }
  560. //-------------------------------------------------------------------
  561. // LetterBoxDstRect
  562. //
  563. // Takes a src rectangle and constructs the largest possible
  564. // destination rectangle within the specifed destination rectangle
  565. // such thatthe video maintains its current shape.
  566. //
  567. // This function assumes that pels are the same shape within both the
  568. // source and destination rectangles.
  569. // Copyright (C) Microsoft
  570. //-------------------------------------------------------------------
  571. static inline RECT LetterBoxRect(const RECT& rcSrc, const RECT& rcDst)
  572. {
  573. // figure out src/dest scale ratios
  574. int iSrcWidth = Width(rcSrc);
  575. int iSrcHeight = Height(rcSrc);
  576. int iDstWidth = Width(rcDst);
  577. int iDstHeight = Height(rcDst);
  578. int iDstLBWidth;
  579. int iDstLBHeight;
  580. if (MulDiv(iSrcWidth, iDstHeight, iSrcHeight) <= iDstWidth) {
  581. // Column letter boxing ("pillar box")
  582. iDstLBWidth = MulDiv(iDstHeight, iSrcWidth, iSrcHeight);
  583. iDstLBHeight = iDstHeight;
  584. }
  585. else {
  586. // Row letter boxing.
  587. iDstLBWidth = iDstWidth;
  588. iDstLBHeight = MulDiv(iDstWidth, iSrcHeight, iSrcWidth);
  589. }
  590. // Create a centered rectangle within the current destination rect
  591. RECT rc;
  592. LONG left = rcDst.left + ((iDstWidth - iDstLBWidth) >> 1);
  593. LONG top = rcDst.top + ((iDstHeight - iDstLBHeight) >> 1);
  594. SetRect(&rc, left, top, left + iDstLBWidth, top + iDstLBHeight);
  595. return rc;
  596. }
  597. static inline HRESULT UpdateDestinationRect(plugin_win_mf_consumer_video_t *pSelf, BOOL bForce /*= FALSE*/)
  598. {
  599. HRESULT hr = S_OK;
  600. HWND hwnd = Window(pSelf);
  601. if(!pSelf) {
  602. CHECK_HR(hr = E_POINTER);
  603. }
  604. if(!hwnd) {
  605. CHECK_HR(hr = E_HANDLE);
  606. }
  607. RECT rcClient;
  608. GetClientRect(hwnd, &rcClient);
  609. // only update destination if window size changed
  610. if(bForce || (rcClient.bottom != pSelf->rcWindow.bottom || rcClient.left != pSelf->rcWindow.left || rcClient.right != pSelf->rcWindow.right || rcClient.top != pSelf->rcWindow.top)) {
  611. CHECK_HR(hr = ResetDevice(pSelf));
  612. pSelf->rcWindow = rcClient;
  613. #if 1
  614. RECT rcSrc = { 0, 0, pSelf->nNegWidth, pSelf->nNegHeight };
  615. rcSrc = CorrectAspectRatio(rcSrc, pSelf->pixelAR);
  616. pSelf->rcDest = LetterBoxRect(rcSrc, rcClient);
  617. #else
  618. long w = rcClient.right - rcClient.left;
  619. long h = rcClient.bottom - rcClient.top;
  620. float ratio = ((float)pSelf->nNegWidth/(float)pSelf->nNegHeight);
  621. // (w/h)=ratio =>
  622. // 1) h=w/ratio
  623. // and
  624. // 2) w=h*ratio
  625. pSelf->rcDest.right = (int)(w/ratio) > h ? (int)(h * ratio) : w;
  626. pSelf->rcDest.bottom = (int)(pSelf->rcDest.right/ratio) > h ? h : (int)(pSelf->rcDest.right/ratio);
  627. pSelf->rcDest.left = ((w - pSelf->rcDest.right) >> 1);
  628. pSelf->rcDest.top = ((h - pSelf->rcDest.bottom) >> 1);
  629. #endif
  630. //::InvalidateRect(hwnd, NULL, FALSE);
  631. }
  632. bail:
  633. return hr;
  634. }
  635. static HRESULT ResetDevice(plugin_win_mf_consumer_video_t *pSelf, BOOL bUpdateDestinationRect /*= FALSE*/)
  636. {
  637. HRESULT hr = S_OK;
  638. tsk_safeobj_lock(pSelf);
  639. HWND hWnd = Window(pSelf);
  640. if (pSelf->pDevice) {
  641. D3DPRESENT_PARAMETERS d3dpp = pSelf->d3dpp;
  642. hr = pSelf->pDevice->Reset(&d3dpp);
  643. if (FAILED(hr)) {
  644. SafeRelease(&pSelf->pDevice);
  645. SafeRelease(&pSelf->pD3D);
  646. SafeRelease(&pSelf->pSwapChain);
  647. }
  648. }
  649. if (pSelf->pDevice == NULL && hWnd) {
  650. CHECK_HR(hr = CreateDeviceD3D9(hWnd, &pSelf->pDevice, &pSelf->pD3D, pSelf->d3dpp));
  651. CHECK_HR(hr = CreateSwapChain(hWnd, pSelf->nNegWidth, pSelf->nNegHeight, pSelf->pDevice, &pSelf->pSwapChain));
  652. }
  653. if(bUpdateDestinationRect) { // endless loop guard
  654. CHECK_HR(hr = UpdateDestinationRect(pSelf));
  655. }
  656. bail:
  657. tsk_safeobj_unlock(pSelf);
  658. return hr;
  659. }
  660. static HRESULT SetFullscreen(struct plugin_win_mf_consumer_video_s *pSelf, BOOL bFullScreen)
  661. {
  662. HRESULT hr = S_OK;
  663. if(!pSelf) {
  664. CHECK_HR(hr = E_POINTER);
  665. }
  666. if(pSelf->bFullScreen != bFullScreen) {
  667. tsk_safeobj_lock(pSelf);
  668. if(bFullScreen) {
  669. HWND hWnd = CreateFullScreenWindow(pSelf);
  670. if(hWnd) {
  671. ::ShowWindow(hWnd, SW_SHOWDEFAULT);
  672. ::UpdateWindow(hWnd);
  673. }
  674. }
  675. else if(pSelf->hWindowFullScreen) {
  676. ::ShowWindow(pSelf->hWindowFullScreen, SW_HIDE);
  677. }
  678. pSelf->bFullScreen = bFullScreen;
  679. if(pSelf->bPrepared) {
  680. hr = ResetDevice(pSelf);
  681. }
  682. tsk_safeobj_unlock(pSelf);
  683. CHECK_HR(hr);
  684. }
  685. bail:
  686. return hr;
  687. }
  688. static LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
  689. {
  690. switch(uMsg) {
  691. case WM_CREATE:
  692. case WM_SIZE:
  693. case WM_MOVE: {
  694. struct plugin_win_mf_consumer_video_s* pSelf = dynamic_cast<struct plugin_win_mf_consumer_video_s*>((struct plugin_win_mf_consumer_video_s*)GetPropA(hWnd, "Self"));
  695. if (pSelf) {
  696. }
  697. break;
  698. }
  699. case WM_ERASEBKGND: {
  700. return TRUE; // avoid background erasing.
  701. }
  702. case WM_CHAR:
  703. case WM_KEYUP: {
  704. struct plugin_win_mf_consumer_video_s* pSelf = dynamic_cast<struct plugin_win_mf_consumer_video_s*>((struct plugin_win_mf_consumer_video_s*)GetPropA(hWnd, "Self"));
  705. if (pSelf) {
  706. SetFullscreen(pSelf, FALSE);
  707. }
  708. break;
  709. }
  710. }
  711. return DefWindowProc(hWnd, uMsg, wParam, lParam);
  712. }
  713. static HWND CreateFullScreenWindow(struct plugin_win_mf_consumer_video_s *pSelf)
  714. {
  715. HRESULT hr = S_OK;
  716. if(!pSelf) {
  717. return NULL;
  718. }
  719. if(!pSelf->hWindowFullScreen) {
  720. WNDCLASS wc = {0};
  721. wc.lpfnWndProc = WndProc;
  722. wc.hInstance = GetModuleHandle(NULL);
  723. wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  724. wc.lpszClassName = L"WindowClass";
  725. RegisterClass(&wc);
  726. pSelf->hWindowFullScreen = ::CreateWindowEx(
  727. NULL,
  728. wc.lpszClassName,
  729. L"Doubango's Video Consumer Fullscreen",
  730. WS_EX_TOPMOST | WS_POPUP,
  731. 0, 0,
  732. GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
  733. NULL,
  734. NULL,
  735. GetModuleHandle(NULL),
  736. NULL);
  737. SetPropA(pSelf->hWindowFullScreen, "Self", pSelf);
  738. }
  739. return pSelf->hWindowFullScreen;
  740. }
  741. static HRESULT HookWindow(plugin_win_mf_consumer_video_s *pSelf, HWND hWnd)
  742. {
  743. HRESULT hr = S_OK;
  744. tsk_safeobj_lock(pSelf);
  745. CHECK_HR(hr = UnhookWindow(pSelf));
  746. if ((pSelf->hWindow = hWnd)) {
  747. pSelf->wndProc = (WNDPROC)SetWindowLongPtr(pSelf->hWindow, GWLP_WNDPROC, (LONG_PTR)WndProc);
  748. if (!pSelf->wndProc) {
  749. TSK_DEBUG_ERROR("HookWindowLongPtr() failed with errcode=%d", GetLastError());
  750. CHECK_HR(hr = E_FAIL);
  751. }
  752. pSelf->bWindowHooked = TRUE;
  753. }
  754. bail:
  755. tsk_safeobj_unlock(pSelf);
  756. return S_OK;
  757. }
  758. static HRESULT UnhookWindow(struct plugin_win_mf_consumer_video_s *pSelf)
  759. {
  760. tsk_safeobj_lock(pSelf);
  761. if (pSelf->hWindow && pSelf->wndProc) {
  762. SetWindowLongPtr(pSelf->hWindow, GWLP_WNDPROC, (LONG_PTR)pSelf->wndProc);
  763. pSelf->wndProc = NULL;
  764. }
  765. if(pSelf->hWindow) {
  766. ::InvalidateRect(pSelf->hWindow, NULL, FALSE);
  767. }
  768. pSelf->bWindowHooked = FALSE;
  769. tsk_safeobj_unlock(pSelf);
  770. return S_OK;
  771. }
  772. #else /* !PLUGIN_MF_CV_USE_D3D9 */
  773. #include "internals/mf_custom_src.h"
  774. #include "internals/mf_display_watcher.h"
  775. #include "internals/mf_codec.h"
  776. #include <KS.h>
  777. #include <Codecapi.h>
  778. // 0: {{[Source] -> (VideoProcessor) -> SampleGrabber}} , {{[Decoder]}} -> RTP
  779. // 1: {{[Source] -> (VideoProcessor) -> [Decoder] -> SampleGrabber}} -> RTP
  780. // (VideoProcessor) is optional
  781. // "{{" and "}}" defines where the graph starts and ends respectively. For "0", [Decoder] is a stand-alone IMFTransform.
  782. #if !defined(PLUGIN_MF_CV_BUNDLE_CODEC)
  783. # define PLUGIN_MF_CV_BUNDLE_CODEC 0
  784. #endif
  785. // Uncompressed video frame will come from Doubango core and it's up to the converter to match the requested chroma.
  786. // Supported values: NV12, I420, RGB32 and RGB24. (RGB formats are not recommended because of performance issues)
  787. // To avoid chroma conversion (performance issues) we use NV12 when the codec is bundled as MediaFoundation codecs most likely only support this format.
  788. // NV12 is the native format for media foundation codecs (e.g. Intel Quick Sync) and the GPU.
  789. // I420 is the native format for FFmpeg, libvpx and libtheora.
  790. const GUID kDefaultUncompressedType
  791. #if PLUGIN_MF_CV_BUNDLE_CODEC
  792. = MFVideoFormat_NV12;
  793. #else
  794. = MFVideoFormat_I420;
  795. #endif
  796. DEFINE_GUID(PLUGIN_MF_LOW_LATENCY,
  797. 0x9c27891a, 0xed7a, 0x40e1, 0x88, 0xe8, 0xb2, 0x27, 0x27, 0xa0, 0x24, 0xee);
  798. static void* TSK_STDCALL RunSessionThread(void *pArg);
  799. static int _plugin_win_mf_consumer_video_unprepare(struct plugin_win_mf_consumer_video_s* pSelf);
  800. typedef struct plugin_win_mf_consumer_video_s {
  801. TMEDIA_DECLARE_CONSUMER;
  802. bool bStarted, bPrepared;
  803. HWND hWindow;
  804. tsk_thread_handle_t* ppTread[1];
  805. UINT32 nNegWidth;
  806. UINT32 nNegHeight;
  807. UINT32 nNegFps;
  808. MFCodecVideo *pDecoder;
  809. IMFMediaSession *pSession;
  810. CMFSource *pSource;
  811. IMFActivate *pSinkActivate;
  812. DisplayWatcher* pDisplayWatcher;
  813. IMFTopology *pTopologyFull;
  814. IMFTopology *pTopologyPartial;
  815. IMFMediaType *pOutType;
  816. }
  817. plugin_win_mf_consumer_video_t;
  818. /* ============ Media Consumer Interface ================= */
  819. static int plugin_win_mf_consumer_video_set(tmedia_consumer_t *self, const tmedia_param_t* param)
  820. {
  821. int ret = 0;
  822. HRESULT hr = S_OK;
  823. plugin_win_mf_consumer_video_t* pSelf = (plugin_win_mf_consumer_video_t*)self;
  824. if(!self || !param) {
  825. TSK_DEBUG_ERROR("Invalid parameter");
  826. return -1;
  827. }
  828. if(param->value_type == tmedia_pvt_int64) {
  829. if(tsk_striequals(param->key, "remote-hwnd")) {
  830. HWND hWnd = reinterpret_cast<HWND>((INT64)*((int64_t*)param->value));
  831. if(hWnd != pSelf->hWindow) {
  832. pSelf->hWindow = hWnd;
  833. if(pSelf->pDisplayWatcher) {
  834. CHECK_HR(hr = pSelf->pDisplayWatcher->SetHwnd(hWnd));
  835. }
  836. }
  837. }
  838. }
  839. else if(param->value_type == tmedia_pvt_int32) {
  840. if(tsk_striequals(param->key, "fullscreen")) {
  841. if(pSelf->pDisplayWatcher) {
  842. CHECK_HR(hr = pSelf->pDisplayWatcher->SetFullscreen(!!*((int32_t*)param->value)));
  843. }
  844. }
  845. else if(tsk_striequals(param->key, "create-on-current-thead")) {
  846. // DSCONSUMER(self)->create_on_ui_thread = *((int32_t*)param->value) ? tsk_false : tsk_true;
  847. }
  848. else if(tsk_striequals(param->key, "plugin-firefox")) {
  849. /*DSCONSUMER(self)->plugin_firefox = (*((int32_t*)param->value) != 0);
  850. if(DSCONSUMER(self)->display){
  851. DSCONSUMER(self)->display->setPluginFirefox((DSCONSUMER(self)->plugin_firefox == tsk_true));
  852. }*/
  853. }
  854. }
  855. bail:
  856. return SUCCEEDED(hr) ? 0 : -1;
  857. }
  858. static int plugin_win_mf_consumer_video_prepare(tmedia_consumer_t* self, const tmedia_codec_t* codec)
  859. {
  860. plugin_win_mf_consumer_video_t* pSelf = (plugin_win_mf_consumer_video_t*)self;
  861. if(!pSelf || !codec && codec->plugin) {
  862. TSK_DEBUG_ERROR("Invalid parameter");
  863. return -1;
  864. }
  865. if(pSelf->bPrepared) {
  866. TSK_DEBUG_WARN("MF video consumer already prepared");
  867. return -1;
  868. }
  869. // FIXME: DirectShow requires flipping but not MF
  870. // The Core library always tries to flip when OSType==Win32. Must be changed
  871. TMEDIA_CODEC_VIDEO(codec)->in.flip = tsk_false;
  872. HRESULT hr = S_OK;
  873. TMEDIA_CONSUMER(pSelf)->video.fps = TMEDIA_CODEC_VIDEO(codec)->in.fps;
  874. TMEDIA_CONSUMER(pSelf)->video.in.width = TMEDIA_CODEC_VIDEO(codec)->in.width;
  875. TMEDIA_CONSUMER(pSelf)->video.in.height = TMEDIA_CODEC_VIDEO(codec)->in.height;
  876. if(!TMEDIA_CONSUMER(pSelf)->video.display.width) {
  877. TMEDIA_CONSUMER(pSelf)->video.display.width = TMEDIA_CONSUMER(pSelf)->video.in.width;
  878. }
  879. if(!TMEDIA_CONSUMER(pSelf)->video.display.height) {
  880. TMEDIA_CONSUMER(pSelf)->video.display.height = TMEDIA_CONSUMER(pSelf)->video.in.height;
  881. }
  882. pSelf->nNegFps = TMEDIA_CONSUMER(pSelf)->video.fps;
  883. pSelf->nNegWidth = TMEDIA_CONSUMER(pSelf)->video.display.width;
  884. pSelf->nNegHeight = TMEDIA_CONSUMER(pSelf)->video.display.height;
  885. TSK_DEBUG_INFO("MF video consumer: fps=%d, width=%d, height=%d",
  886. pSelf->nNegFps,
  887. pSelf->nNegWidth,
  888. pSelf->nNegHeight);
  889. if(kDefaultUncompressedType == MFVideoFormat_NV12) {
  890. TMEDIA_CONSUMER(pSelf)->video.display.chroma = tmedia_chroma_nv12;
  891. }
  892. else if(kDefaultUncompressedType == MFVideoFormat_I420) {
  893. TMEDIA_CONSUMER(pSelf)->video.display.chroma = tmedia_chroma_yuv420p;
  894. }
  895. else if(kDefaultUncompressedType == MFVideoFormat_RGB32) {
  896. TMEDIA_CONSUMER(pSelf)->video.display.chroma = tmedia_chroma_rgb32;
  897. }
  898. else if(kDefaultUncompressedType == MFVideoFormat_RGB24) {
  899. TMEDIA_CONSUMER(pSelf)->video.display.chroma = tmedia_chroma_rgb24;
  900. }
  901. else {
  902. CHECK_HR(hr = E_NOTIMPL);
  903. }
  904. TMEDIA_CONSUMER(pSelf)->decoder.codec_id = tmedia_codec_id_none; // means accept RAW fames
  905. IMFMediaSink* pMediaSink = NULL;
  906. IMFAttributes* pSessionAttributes = NULL;
  907. // Set session attributes
  908. CHECK_HR(hr = MFCreateAttributes(&pSessionAttributes, 1));
  909. CHECK_HR(hr = pSessionAttributes->SetUINT32(PLUGIN_MF_LOW_LATENCY, 1));
  910. CHECK_HR(hr = MFCreateMediaType(&pSelf->pOutType));
  911. CHECK_HR(hr = pSelf->pOutType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video));
  912. #if PLUGIN_MF_CV_BUNDLE_CODEC
  913. if((codec->id == tmedia_codec_id_h264_bp || codec->id == tmedia_codec_id_h264_mp) && MFUtils::IsLowLatencyH264Supported()) {
  914. // both Microsoft and Intel encoders support NV12 only as input
  915. // static const BOOL kIsEncoder = FALSE;
  916. // hr = MFUtils::GetBestCodec(kIsEncoder, MFMediaType_Video, MFVideoFormat_H264, MFVideoFormat_NV12, &pSelf->pDecoder);
  917. pSelf->pDecoder = (codec->id == tmedia_codec_id_h264_bp) ? MFCodecVideoH264::CreateCodecH264Base(MFCodecType_Decoder) : MFCodecVideoH264::CreateCodecH264Main(MFCodecType_Decoder);
  918. if(pSelf->pDecoder) {
  919. hr = pSelf->pDecoder->Initialize(
  920. pSelf->nNegFps,
  921. pSelf->nNegWidth,
  922. pSelf->nNegHeight);
  923. if(FAILED(hr)) {
  924. SafeRelease(&pSelf->pDecoder);
  925. hr = S_OK;
  926. }
  927. }
  928. if(SUCCEEDED(hr) && pSelf->pDecoder) {
  929. TMEDIA_CONSUMER(pSelf)->decoder.codec_id = codec->id; // means accept ENCODED fames
  930. CHECK_HR(hr = pSelf->pOutType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_H264));
  931. }
  932. else {
  933. SafeRelease(&pSelf->pDecoder);
  934. TSK_DEBUG_WARN("Failed to find H.264 HW encoder...fallback to SW implementation");
  935. }
  936. }
  937. #endif
  938. if(!pSelf->pDecoder) {
  939. CHECK_HR(hr = pSelf->pOutType->SetGUID(MF_MT_SUBTYPE, kDefaultUncompressedType));
  940. TMEDIA_CONSUMER(pSelf)->video.display.chroma = kDefaultUncompressedType == MFVideoFormat_NV12 ? tmedia_chroma_nv12 : tmedia_chroma_yuv420p;
  941. }
  942. CHECK_HR(hr = pSelf->pOutType->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive));
  943. CHECK_HR(hr = pSelf->pOutType->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE));
  944. CHECK_HR(hr = MFSetAttributeSize(pSelf->pOutType, MF_MT_FRAME_SIZE, pSelf->nNegWidth, pSelf->nNegHeight));
  945. CHECK_HR(hr = MFSetAttributeRatio(pSelf->pOutType, MF_MT_FRAME_RATE, pSelf->nNegFps, 1));
  946. CHECK_HR(hr = MFSetAttributeRatio(pSelf->pOutType, MF_MT_PIXEL_ASPECT_RATIO, 1, 1));
  947. CHECK_HR(hr = CMFSource::CreateInstanceEx(IID_IMFMediaSource, (void**)&pSelf->pSource, pSelf->pOutType));
  948. // Apply Encoder output type (must be called before SetInputType)
  949. //if(pSelf->pDecoder) {
  950. // CHECK_HR(hr = pSelf->pDecoder->SetOutputType(0, pSelf->pOutType, 0/*MFT_SET_TYPE_TEST_ONLY*/));
  951. //}
  952. // Create the Media Session.
  953. CHECK_HR(hr = MFCreateMediaSession(pSessionAttributes, &pSelf->pSession));
  954. // Create the EVR activation object.
  955. CHECK_HR(hr = MFCreateVideoRendererActivate(pSelf->hWindow, &pSelf->pSinkActivate));
  956. // Create the topology.
  957. CHECK_HR(hr = MFUtils::CreateTopology(
  958. pSelf->pSource,
  959. pSelf->pDecoder ? pSelf->pDecoder->GetMFT() : NULL,
  960. pSelf->pSinkActivate,
  961. NULL/*Preview*/,
  962. pSelf->pOutType,
  963. &pSelf->pTopologyPartial));
  964. // Resolve topology (adds video processors if needed).
  965. CHECK_HR(hr = MFUtils::ResolveTopology(pSelf->pTopologyPartial, &pSelf->pTopologyFull));
  966. // Find EVR
  967. CHECK_HR(hr = MFUtils::FindNodeObject(pSelf->pTopologyFull, MFUtils::g_ullTopoIdSinkMain, (void**)&pMediaSink));
  968. // Create EVR watcher
  969. pSelf->pDisplayWatcher = new DisplayWatcher(pSelf->hWindow, pMediaSink, hr);
  970. CHECK_HR(hr);
  971. bail:
  972. SafeRelease(&pMediaSink);
  973. SafeRelease(&pSessionAttributes);
  974. pSelf->bPrepared = SUCCEEDED(hr);
  975. return pSelf->bPrepared ? 0 : -1;
  976. }
  977. static int plugin_win_mf_consumer_video_start(tmedia_consumer_t* self)
  978. {
  979. plugin_win_mf_consumer_video_t* pSelf = (plugin_win_mf_consumer_video_t*)self;
  980. if(!pSelf) {
  981. TSK_DEBUG_ERROR("Invalid parameter");
  982. return -1;
  983. }
  984. if(pSelf->bStarted) {
  985. TSK_DEBUG_INFO("MF video consumer already started");
  986. return 0;
  987. }
  988. if(!pSelf->bPrepared) {
  989. TSK_DEBUG_ERROR("MF video consumer not prepared");
  990. return -1;
  991. }
  992. HRESULT hr = S_OK;
  993. // Run EVR watcher
  994. if(pSelf->pDisplayWatcher) {
  995. CHECK_HR(hr = pSelf->pDisplayWatcher->Start());
  996. }
  997. // Run the media session.
  998. CHECK_HR(hr = MFUtils::RunSession(pSelf->pSession, pSelf->pTopologyFull));
  999. // Start asynchronous watcher thread
  1000. pSelf->bStarted = true;
  1001. int ret = tsk_thread_create(&pSelf->ppTread[0], RunSessionThread, pSelf);
  1002. if(ret != 0) {
  1003. TSK_DEBUG_ERROR("Failed to create thread");
  1004. hr = E_FAIL;
  1005. pSelf->bStarted = false;
  1006. if(pSelf->ppTread[0]) {
  1007. tsk_thread_join(&pSelf->ppTread[0]);
  1008. }
  1009. MFUtils::ShutdownSession(pSelf->pSession, pSelf->pSource);
  1010. CHECK_HR(hr = E_FAIL);
  1011. }
  1012. bail:
  1013. return SUCCEEDED(hr) ? 0 : -1;
  1014. }
  1015. static int plugin_win_mf_consumer_video_consume(tmedia_consumer_t* self, const void* buffer, tsk_size_t size, const tsk_object_t* proto_hdr)
  1016. {
  1017. plugin_win_mf_consumer_video_t* pSelf = (plugin_win_mf_consumer_video_t*)self;
  1018. HRESULT hr = S_OK;
  1019. if(!pSelf || !buffer || !size) {
  1020. TSK_DEBUG_ERROR("Invalid parameter");
  1021. CHECK_HR(hr = E_INVALIDARG);
  1022. }
  1023. if(!pSelf->bStarted) {
  1024. TSK_DEBUG_INFO("MF video consumer not started");
  1025. CHECK_HR(hr = E_FAIL);
  1026. }
  1027. if(!pSelf->pSource) {
  1028. TSK_DEBUG_ERROR("No video custom source");
  1029. CHECK_HR(hr = E_FAIL);
  1030. }
  1031. if(pSelf->nNegWidth != TMEDIA_CONSUMER(pSelf)->video.in.width || pSelf->nNegHeight != TMEDIA_CONSUMER(pSelf)->video.in.height) {
  1032. TSK_DEBUG_INFO("Negotiated and input video sizes are different:%d#%d or %d#%d",
  1033. pSelf->nNegWidth, TMEDIA_CONSUMER(pSelf)->video.in.width,
  1034. pSelf->nNegHeight, TMEDIA_CONSUMER(pSelf)->video.in.height);
  1035. // Update media type
  1036. CHECK_HR(hr = MFSetAttributeSize(pSelf->pOutType, MF_MT_FRAME_SIZE, TMEDIA_CONSUMER(pSelf)->video.in.width, TMEDIA_CONSUMER(pSelf)->video.in.height));
  1037. CHECK_HR(hr = MFSetAttributeRatio(pSelf->pOutType, MF_MT_FRAME_RATE, TMEDIA_CONSUMER(pSelf)->video.fps, 1));
  1038. CHECK_HR(hr = pSelf->pSession->ClearTopologies());
  1039. //
  1040. // FIXME: Using same EVR when the size is just swapped (e.g. [640, 480] -> [480, 640]) doesn't work while other changes does (e.g. [352, 288] -> [640, 480])
  1041. // /!\This look like a bug in Media Foundation
  1042. //
  1043. if(pSelf->nNegWidth == TMEDIA_CONSUMER(pSelf)->video.in.height && pSelf->nNegHeight == TMEDIA_CONSUMER(pSelf)->video.in.width) { // swapped?
  1044. TSK_DEBUG_INFO("/!\\ Size swapped");
  1045. IMFActivate* pSinkActivate = NULL;
  1046. IMFTopology* pTopologyPartial = NULL;
  1047. hr = MFCreateVideoRendererActivate(pSelf->hWindow, &pSinkActivate);
  1048. if(FAILED(hr)) {
  1049. goto end_of_swapping;
  1050. }
  1051. hr = MFUtils::CreateTopology(
  1052. pSelf->pSource,
  1053. pSelf->pDecoder ? pSelf->pDecoder->GetMFT() : NULL,
  1054. pSinkActivate,
  1055. NULL/*Preview*/,
  1056. pSelf->pOutType,
  1057. &pTopologyPartial);
  1058. if(FAILED(hr)) {
  1059. goto end_of_swapping;
  1060. }
  1061. if(SUCCEEDED(hr)) {
  1062. SafeRelease(&pSelf->pSinkActivate);
  1063. SafeRelease(&pSelf->pTopologyPartial);
  1064. pSelf->pSinkActivate = pSinkActivate;
  1065. pSinkActivate = NULL;
  1066. pSelf->pTopologyPartial = pTopologyPartial;
  1067. pTopologyPartial = NULL;
  1068. }
  1069. end_of_swapping:
  1070. SafeRelease(&pSinkActivate);
  1071. SafeRelease(&pTopologyPartial);
  1072. CHECK_HR(hr);
  1073. }
  1074. // Set media type again (not required but who know)
  1075. CHECK_HR(hr = MFUtils::SetMediaType(pSelf->pSource, pSelf->pOutType));
  1076. // Rebuild topology using the partial one
  1077. IMFTopology* pTopologyFull = NULL;
  1078. hr = MFUtils::ResolveTopology(pSelf->pTopologyPartial, &pTopologyFull);
  1079. if(SUCCEEDED(hr)) {
  1080. SafeRelease(&pSelf->pTopologyFull);
  1081. pSelf->pTopologyFull = pTopologyFull;
  1082. pTopologyFull = NULL;
  1083. }
  1084. SafeRelease(&pTopologyFull);
  1085. CHECK_HR(hr);
  1086. // Find Main Sink
  1087. IMFMediaSink* pMediaSink = NULL;
  1088. hr = MFUtils::FindNodeObject(pSelf->pTopologyFull, MFUtils::g_ullTopoIdSinkMain, (void**)&pMediaSink);
  1089. if(SUCCEEDED(hr)) {
  1090. if(pSelf->pDisplayWatcher) {
  1091. delete pSelf->pDisplayWatcher, pSelf->pDisplayWatcher = NULL;
  1092. }
  1093. pSelf->pDisplayWatcher = new DisplayWatcher(pSelf->hWindow, pMediaSink, hr);
  1094. if(SUCCEEDED(hr) && pSelf->bStarted) {
  1095. hr = pSelf->pDisplayWatcher->Start();
  1096. }
  1097. }
  1098. SafeRelease(&pMediaSink);
  1099. CHECK_HR(hr);
  1100. // Update the topology associated to the media session
  1101. CHECK_HR(hr = pSelf->pSession->SetTopology(MFSESSION_SETTOPOLOGY_IMMEDIATE, pSelf->pTopologyFull));
  1102. // Update negotiated width and height
  1103. pSelf->nNegWidth = TMEDIA_CONSUMER(pSelf)->video.in.width;
  1104. pSelf->nNegHeight = TMEDIA_CONSUMER(pSelf)->video.in.height;
  1105. }
  1106. // Deliver buffer
  1107. CHECK_HR(hr = pSelf->pSource->CopyVideoBuffer(pSelf->nNegWidth, pSelf->nNegHeight, buffer, size));
  1108. bail:
  1109. return SUCCEEDED(hr) ? 0 : -1;
  1110. }
  1111. static int plugin_win_mf_consumer_video_pause(tmedia_consumer_t* self)
  1112. {
  1113. plugin_win_mf_consumer_video_t* pSelf = (plugin_win_mf_consumer_video_t*)self;
  1114. if(!pSelf) {
  1115. TSK_DEBUG_ERROR("Invalid parameter");
  1116. return -1;
  1117. }
  1118. if(!pSelf->bStarted) {
  1119. TSK_DEBUG_INFO("MF video producer not started");
  1120. return 0;
  1121. }
  1122. HRESULT hr = MFUtils::PauseSession(pSelf->pSession);
  1123. return SUCCEEDED(hr) ? 0 : -1;
  1124. }
  1125. static int plugin_win_mf_consumer_video_stop(tmedia_consumer_t* self)
  1126. {
  1127. plugin_win_mf_consumer_video_t* pSelf = (plugin_win_mf_consumer_video_t*)self;
  1128. if(!pSelf) {
  1129. TSK_DEBUG_ERROR("Invalid parameter");
  1130. return -1;
  1131. }
  1132. HRESULT hr = S_OK;
  1133. // stop EVR watcher
  1134. if(pSelf->pDisplayWatcher) {
  1135. hr = pSelf->pDisplayWatcher->Stop();
  1136. }
  1137. // for the thread
  1138. pSelf->bStarted = false;
  1139. hr = MFUtils::ShutdownSession(pSelf->pSession, NULL); // stop session to wakeup the asynchronous thread
  1140. if(pSelf->ppTread[0]) {
  1141. tsk_thread_join(&pSelf->ppTread[0]);
  1142. }
  1143. hr = MFUtils::ShutdownSession(NULL, pSelf->pSource); // stop source to release the camera
  1144. // next start() will be called after prepare()
  1145. return _plugin_win_mf_consumer_video_unprepare(pSelf);
  1146. }
  1147. static int _plugin_win_mf_consumer_video_unprepare(plugin_win_mf_consumer_video_t* pSelf)
  1148. {
  1149. if(!pSelf) {
  1150. TSK_DEBUG_ERROR("Invalid parameter");
  1151. return -1;
  1152. }
  1153. if(pSelf->bStarted) {
  1154. // plugin_win_mf_producer_video_stop(TMEDIA_PRODUCER(pSelf));
  1155. TSK_DEBUG_ERROR("Consumer must be stopped before calling unprepare");
  1156. }
  1157. if(pSelf->pDisplayWatcher) {
  1158. pSelf->pDisplayWatcher->Stop();
  1159. }
  1160. if(pSelf->pSource) {
  1161. pSelf->pSource->Shutdown();
  1162. pSelf->pSource = NULL;
  1163. }
  1164. if(pSelf->pSession) {
  1165. pSelf->pSession->Shutdown();
  1166. pSelf->pSession = NULL;
  1167. }
  1168. SafeRelease(&pSelf->pDecoder);
  1169. SafeRelease(&pSelf->pSession);
  1170. SafeRelease(&pSelf->pSource);
  1171. SafeRelease(&pSelf->pSinkActivate);
  1172. SafeRelease(&pSelf->pTopologyFull);
  1173. SafeRelease(&pSelf->pTopologyPartial);
  1174. SafeRelease(&pSelf->pOutType);
  1175. if(pSelf->pDisplayWatcher) {
  1176. delete pSelf->pDisplayWatcher;
  1177. pSelf->pDisplayWatcher = NULL;
  1178. }
  1179. pSelf->bPrepared = false;
  1180. return 0;
  1181. }
  1182. //
  1183. // Media Foundation video consumer object definition
  1184. //
  1185. /* constructor */
  1186. static tsk_object_t* plugin_win_mf_consumer_video_ctor(tsk_object_t * self, va_list * app)
  1187. {
  1188. MFUtils::Startup();
  1189. plugin_win_mf_consumer_video_t *pSelf = (plugin_win_mf_consumer_video_t *)self;
  1190. if(pSelf) {
  1191. /* init base */
  1192. tmedia_consumer_init(TMEDIA_CONSUMER(pSelf));
  1193. TMEDIA_CONSUMER(pSelf)->video.display.chroma = tmedia_chroma_yuv420p;
  1194. TMEDIA_CONSUMER(pSelf)->decoder.codec_id = tmedia_codec_id_none; // means accept RAW fames
  1195. /* init self */
  1196. // consumer->create_on_ui_thread = tsk_true;
  1197. TMEDIA_CONSUMER(pSelf)->video.fps = 15;
  1198. TMEDIA_CONSUMER(pSelf)->video.display.width = 0; // use codec value
  1199. TMEDIA_CONSUMER(pSelf)->video.display.height = 0; // use codec value
  1200. TMEDIA_CONSUMER(pSelf)->video.display.auto_resize = tsk_true;
  1201. TSK_DEBUG_INFO("Create WinMF video consumer");
  1202. }
  1203. return self;
  1204. }
  1205. /* destructor */
  1206. static tsk_object_t* plugin_win_mf_consumer_video_dtor(tsk_object_t * self)
  1207. {
  1208. plugin_win_mf_consumer_video_t *pSelf = (plugin_win_mf_consumer_video_t *)self;
  1209. if(pSelf) {
  1210. /* stop */
  1211. if(pSelf->bStarted) {
  1212. plugin_win_mf_consumer_video_stop(TMEDIA_CONSUMER(pSelf));
  1213. }
  1214. /* deinit base */
  1215. tmedia_consumer_deinit(TMEDIA_CONSUMER(pSelf));
  1216. /* deinit self */
  1217. _plugin_win_mf_consumer_video_unprepare(pSelf);
  1218. }
  1219. return self;
  1220. }
  1221. /* object definition */
  1222. static const tsk_object_def_t plugin_win_mf_consumer_video_def_s = {
  1223. sizeof(plugin_win_mf_consumer_video_t),
  1224. plugin_win_mf_consumer_video_ctor,
  1225. plugin_win_mf_consumer_video_dtor,
  1226. tsk_null,
  1227. };
  1228. /* plugin definition*/
  1229. static const tmedia_consumer_plugin_def_t plugin_win_mf_consumer_video_plugin_def_s = {
  1230. &plugin_win_mf_consumer_video_def_s,
  1231. tmedia_video,
  1232. "Media Foundation video consumer",
  1233. plugin_win_mf_consumer_video_set,
  1234. plugin_win_mf_consumer_video_prepare,
  1235. plugin_win_mf_consumer_video_start,
  1236. plugin_win_mf_consumer_video_consume,
  1237. plugin_win_mf_consumer_video_pause,
  1238. plugin_win_mf_consumer_video_stop
  1239. };
  1240. const tmedia_consumer_plugin_def_t *plugin_win_mf_consumer_video_plugin_def_t = &plugin_win_mf_consumer_video_plugin_def_s;
  1241. // Run session async thread
  1242. static void* TSK_STDCALL RunSessionThread(void *pArg)
  1243. {
  1244. plugin_win_mf_consumer_video_t *pSelf = (plugin_win_mf_consumer_video_t *)pArg;
  1245. HRESULT hrStatus = S_OK;
  1246. HRESULT hr = S_OK;
  1247. IMFMediaEvent *pEvent = NULL;
  1248. MediaEventType met;
  1249. TSK_DEBUG_INFO("RunSessionThread (MF video consumer) - ENTER");
  1250. while(pSelf->bStarted) {
  1251. CHECK_HR(hr = pSelf->pSession->GetEvent(0, &pEvent));
  1252. CHECK_HR(hr = pEvent->GetStatus(&hrStatus));
  1253. CHECK_HR(hr = pEvent->GetType(&met));
  1254. if (FAILED(hrStatus) /*&& hrStatus != MF_E_NO_SAMPLE_TIMESTAMP*/) {
  1255. TSK_DEBUG_ERROR("Session error: 0x%x (event id: %d)\n", hrStatus, met);
  1256. hr = hrStatus;
  1257. goto bail;
  1258. }
  1259. if (met == MESessionEnded) {
  1260. break;
  1261. }
  1262. SafeRelease(&pEvent);
  1263. }
  1264. bail:
  1265. TSK_DEBUG_INFO("RunSessionThread (MF video consumer) - EXIT");
  1266. return NULL;
  1267. }
  1268. #endif /* PLUGIN_MF_CV_USE_D3D9 */