window-basic-main-screenshot.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include "window-basic-main.hpp"
  15. #include "screenshot-obj.hpp"
  16. #include <qt-wrappers.hpp>
  17. #ifdef _WIN32
  18. #include <wincodec.h>
  19. #include <wincodecsdk.h>
  20. #include <wrl/client.h>
  21. #pragma comment(lib, "windowscodecs.lib")
  22. #endif
  23. static void ScreenshotTick(void *param, float);
  24. /* ========================================================================= */
  25. ScreenshotObj::ScreenshotObj(obs_source_t *source)
  26. : weakSource(OBSGetWeakRef(source))
  27. {
  28. obs_add_tick_callback(ScreenshotTick, this);
  29. }
  30. ScreenshotObj::~ScreenshotObj()
  31. {
  32. obs_enter_graphics();
  33. gs_stagesurface_destroy(stagesurf);
  34. gs_texrender_destroy(texrender);
  35. obs_leave_graphics();
  36. obs_remove_tick_callback(ScreenshotTick, this);
  37. if (th.joinable()) {
  38. th.join();
  39. if (cx && cy) {
  40. OBSBasic *main = OBSBasic::Get();
  41. main->ShowStatusBarMessage(
  42. QTStr("Basic.StatusBar.ScreenshotSavedTo")
  43. .arg(QT_UTF8(path.c_str())));
  44. main->lastScreenshot = path;
  45. main->OnEvent(OBS_FRONTEND_EVENT_SCREENSHOT_TAKEN);
  46. }
  47. }
  48. }
  49. void ScreenshotObj::Screenshot()
  50. {
  51. OBSSource source = OBSGetStrongRef(weakSource);
  52. if (source) {
  53. cx = obs_source_get_width(source);
  54. cy = obs_source_get_height(source);
  55. } else {
  56. obs_video_info ovi;
  57. obs_get_video_info(&ovi);
  58. cx = ovi.base_width;
  59. cy = ovi.base_height;
  60. }
  61. if (!cx || !cy) {
  62. blog(LOG_WARNING, "Cannot screenshot, invalid target size");
  63. obs_remove_tick_callback(ScreenshotTick, this);
  64. deleteLater();
  65. return;
  66. }
  67. #ifdef _WIN32
  68. enum gs_color_space space =
  69. obs_source_get_color_space(source, 0, nullptr);
  70. if (space == GS_CS_709_EXTENDED) {
  71. /* Convert for JXR */
  72. space = GS_CS_709_SCRGB;
  73. }
  74. #else
  75. /* Tonemap to SDR if HDR */
  76. const enum gs_color_space space = GS_CS_SRGB;
  77. #endif
  78. const enum gs_color_format format = gs_get_format_from_space(space);
  79. texrender = gs_texrender_create(format, GS_ZS_NONE);
  80. stagesurf = gs_stagesurface_create(cx, cy, format);
  81. if (gs_texrender_begin_with_color_space(texrender, cx, cy, space)) {
  82. vec4 zero;
  83. vec4_zero(&zero);
  84. gs_clear(GS_CLEAR_COLOR, &zero, 0.0f, 0);
  85. gs_ortho(0.0f, (float)cx, 0.0f, (float)cy, -100.0f, 100.0f);
  86. gs_blend_state_push();
  87. gs_blend_function(GS_BLEND_ONE, GS_BLEND_ZERO);
  88. if (source) {
  89. obs_source_inc_showing(source);
  90. obs_source_video_render(source);
  91. obs_source_dec_showing(source);
  92. } else {
  93. obs_render_main_texture();
  94. }
  95. gs_blend_state_pop();
  96. gs_texrender_end(texrender);
  97. }
  98. }
  99. void ScreenshotObj::Download()
  100. {
  101. gs_stage_texture(stagesurf, gs_texrender_get_texture(texrender));
  102. }
  103. void ScreenshotObj::Copy()
  104. {
  105. uint8_t *videoData = nullptr;
  106. uint32_t videoLinesize = 0;
  107. if (gs_stagesurface_map(stagesurf, &videoData, &videoLinesize)) {
  108. if (gs_stagesurface_get_color_format(stagesurf) == GS_RGBA16F) {
  109. const uint32_t linesize = cx * 8;
  110. half_bytes.reserve(cx * cy * 8);
  111. for (uint32_t y = 0; y < cy; y++) {
  112. const uint8_t *const line =
  113. videoData + (y * videoLinesize);
  114. half_bytes.insert(half_bytes.end(), line,
  115. line + linesize);
  116. }
  117. } else {
  118. image = QImage(cx, cy, QImage::Format::Format_RGBX8888);
  119. int linesize = image.bytesPerLine();
  120. for (int y = 0; y < (int)cy; y++)
  121. memcpy(image.scanLine(y),
  122. videoData + (y * videoLinesize),
  123. linesize);
  124. }
  125. gs_stagesurface_unmap(stagesurf);
  126. }
  127. }
  128. void ScreenshotObj::Save()
  129. {
  130. OBSBasic *main = OBSBasic::Get();
  131. config_t *config = main->Config();
  132. const char *mode = config_get_string(config, "Output", "Mode");
  133. const char *type = config_get_string(config, "AdvOut", "RecType");
  134. const char *adv_path =
  135. strcmp(type, "Standard")
  136. ? config_get_string(config, "AdvOut", "FFFilePath")
  137. : config_get_string(config, "AdvOut", "RecFilePath");
  138. const char *rec_path =
  139. strcmp(mode, "Advanced")
  140. ? config_get_string(config, "SimpleOutput", "FilePath")
  141. : adv_path;
  142. bool noSpace =
  143. config_get_bool(config, "SimpleOutput", "FileNameWithoutSpace");
  144. const char *filenameFormat =
  145. config_get_string(config, "Output", "FilenameFormatting");
  146. bool overwriteIfExists =
  147. config_get_bool(config, "Output", "OverwriteIfExists");
  148. const char *ext = half_bytes.empty() ? "png" : "jxr";
  149. path = GetOutputFilename(
  150. rec_path, ext, noSpace, overwriteIfExists,
  151. GetFormatString(filenameFormat, "Screenshot", nullptr).c_str());
  152. th = std::thread([this] { MuxAndFinish(); });
  153. }
  154. #ifdef _WIN32
  155. static HRESULT SaveJxrImage(LPCWSTR path, uint8_t *pixels, uint32_t cx,
  156. uint32_t cy, IWICBitmapFrameEncode *frameEncode,
  157. IPropertyBag2 *options)
  158. {
  159. wchar_t lossless[] = L"Lossless";
  160. PROPBAG2 bag = {};
  161. bag.pstrName = lossless;
  162. VARIANT value = {};
  163. value.vt = VT_BOOL;
  164. value.bVal = TRUE;
  165. HRESULT hr = options->Write(1, &bag, &value);
  166. if (FAILED(hr))
  167. return hr;
  168. hr = frameEncode->Initialize(options);
  169. if (FAILED(hr))
  170. return hr;
  171. hr = frameEncode->SetSize(cx, cy);
  172. if (FAILED(hr))
  173. return hr;
  174. hr = frameEncode->SetResolution(72, 72);
  175. if (FAILED(hr))
  176. return hr;
  177. WICPixelFormatGUID pixelFormat = GUID_WICPixelFormat64bppRGBAHalf;
  178. hr = frameEncode->SetPixelFormat(&pixelFormat);
  179. if (FAILED(hr))
  180. return hr;
  181. if (memcmp(&pixelFormat, &GUID_WICPixelFormat64bppRGBAHalf,
  182. sizeof(WICPixelFormatGUID)) != 0)
  183. return E_FAIL;
  184. hr = frameEncode->WritePixels(cy, cx * 8, cx * cy * 8, pixels);
  185. if (FAILED(hr))
  186. return hr;
  187. hr = frameEncode->Commit();
  188. if (FAILED(hr))
  189. return hr;
  190. return S_OK;
  191. }
  192. static HRESULT SaveJxr(LPCWSTR path, uint8_t *pixels, uint32_t cx, uint32_t cy)
  193. {
  194. Microsoft::WRL::ComPtr<IWICImagingFactory> factory;
  195. HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory, NULL,
  196. CLSCTX_INPROC_SERVER,
  197. IID_PPV_ARGS(factory.GetAddressOf()));
  198. if (FAILED(hr))
  199. return hr;
  200. Microsoft::WRL::ComPtr<IWICStream> stream;
  201. hr = factory->CreateStream(stream.GetAddressOf());
  202. if (FAILED(hr))
  203. return hr;
  204. hr = stream->InitializeFromFilename(path, GENERIC_WRITE);
  205. if (FAILED(hr))
  206. return hr;
  207. Microsoft::WRL::ComPtr<IWICBitmapEncoder> encoder = NULL;
  208. hr = factory->CreateEncoder(GUID_ContainerFormatWmp, NULL,
  209. encoder.GetAddressOf());
  210. if (FAILED(hr))
  211. return hr;
  212. hr = encoder->Initialize(stream.Get(), WICBitmapEncoderNoCache);
  213. if (FAILED(hr))
  214. return hr;
  215. Microsoft::WRL::ComPtr<IWICBitmapFrameEncode> frameEncode;
  216. Microsoft::WRL::ComPtr<IPropertyBag2> options;
  217. hr = encoder->CreateNewFrame(frameEncode.GetAddressOf(),
  218. options.GetAddressOf());
  219. if (FAILED(hr))
  220. return hr;
  221. hr = SaveJxrImage(path, pixels, cx, cy, frameEncode.Get(),
  222. options.Get());
  223. if (FAILED(hr))
  224. return hr;
  225. encoder->Commit();
  226. return S_OK;
  227. }
  228. #endif // #ifdef _WIN32
  229. void ScreenshotObj::MuxAndFinish()
  230. {
  231. if (half_bytes.empty()) {
  232. image.save(QT_UTF8(path.c_str()));
  233. blog(LOG_INFO, "Saved screenshot to '%s'", path.c_str());
  234. } else {
  235. #ifdef _WIN32
  236. wchar_t *path_w = nullptr;
  237. os_utf8_to_wcs_ptr(path.c_str(), 0, &path_w);
  238. if (path_w) {
  239. SaveJxr(path_w, half_bytes.data(), cx, cy);
  240. bfree(path_w);
  241. }
  242. #endif // #ifdef _WIN32
  243. }
  244. deleteLater();
  245. }
  246. /* ========================================================================= */
  247. #define STAGE_SCREENSHOT 0
  248. #define STAGE_DOWNLOAD 1
  249. #define STAGE_COPY_AND_SAVE 2
  250. #define STAGE_FINISH 3
  251. static void ScreenshotTick(void *param, float)
  252. {
  253. ScreenshotObj *data = reinterpret_cast<ScreenshotObj *>(param);
  254. if (data->stage == STAGE_FINISH) {
  255. return;
  256. }
  257. obs_enter_graphics();
  258. switch (data->stage) {
  259. case STAGE_SCREENSHOT:
  260. data->Screenshot();
  261. break;
  262. case STAGE_DOWNLOAD:
  263. data->Download();
  264. break;
  265. case STAGE_COPY_AND_SAVE:
  266. data->Copy();
  267. QMetaObject::invokeMethod(data, "Save");
  268. obs_remove_tick_callback(ScreenshotTick, data);
  269. break;
  270. }
  271. obs_leave_graphics();
  272. data->stage++;
  273. }
  274. void OBSBasic::Screenshot(OBSSource source)
  275. {
  276. if (!!screenshotData) {
  277. blog(LOG_WARNING, "Cannot take new screenshot, "
  278. "screenshot currently in progress");
  279. return;
  280. }
  281. screenshotData = new ScreenshotObj(source);
  282. }
  283. void OBSBasic::ScreenshotSelectedSource()
  284. {
  285. OBSSceneItem item = GetCurrentSceneItem();
  286. if (item) {
  287. Screenshot(obs_sceneitem_get_source(item));
  288. } else {
  289. blog(LOG_INFO, "Could not take a source screenshot: "
  290. "no source selected");
  291. }
  292. }
  293. void OBSBasic::ScreenshotProgram()
  294. {
  295. Screenshot(GetProgramSource());
  296. }
  297. void OBSBasic::ScreenshotScene()
  298. {
  299. Screenshot(GetCurrentSceneSource());
  300. }