1
0

window-basic-main-screenshot.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. /******************************************************************************
  2. Copyright (C) 2020 by Hugh 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. }
  45. }
  46. }
  47. void ScreenshotObj::Screenshot()
  48. {
  49. OBSSource source = OBSGetStrongRef(weakSource);
  50. if (source) {
  51. cx = obs_source_get_base_width(source);
  52. cy = obs_source_get_base_height(source);
  53. } else {
  54. obs_video_info ovi;
  55. obs_get_video_info(&ovi);
  56. cx = ovi.base_width;
  57. cy = ovi.base_height;
  58. }
  59. if (!cx || !cy) {
  60. blog(LOG_WARNING, "Cannot screenshot, invalid target size");
  61. obs_remove_tick_callback(ScreenshotTick, this);
  62. deleteLater();
  63. return;
  64. }
  65. #ifdef _WIN32
  66. enum gs_color_space space =
  67. obs_source_get_color_space(source, 0, nullptr);
  68. if (space == GS_CS_709_EXTENDED) {
  69. /* Convert for JXR */
  70. space = GS_CS_709_SCRGB;
  71. }
  72. #else
  73. /* Tonemap to SDR if HDR */
  74. const enum gs_color_space space = GS_CS_SRGB;
  75. #endif
  76. const enum gs_color_format format = gs_get_format_from_space(space);
  77. texrender = gs_texrender_create(format, GS_ZS_NONE);
  78. stagesurf = gs_stagesurface_create(cx, cy, format);
  79. if (gs_texrender_begin_with_color_space(texrender, cx, cy, space)) {
  80. vec4 zero;
  81. vec4_zero(&zero);
  82. gs_clear(GS_CLEAR_COLOR, &zero, 0.0f, 0);
  83. gs_ortho(0.0f, (float)cx, 0.0f, (float)cy, -100.0f, 100.0f);
  84. gs_blend_state_push();
  85. gs_blend_function(GS_BLEND_ONE, GS_BLEND_ZERO);
  86. if (source) {
  87. obs_source_inc_showing(source);
  88. obs_source_video_render(source);
  89. obs_source_dec_showing(source);
  90. } else {
  91. obs_render_main_texture();
  92. }
  93. gs_blend_state_pop();
  94. gs_texrender_end(texrender);
  95. }
  96. }
  97. void ScreenshotObj::Download()
  98. {
  99. gs_stage_texture(stagesurf, gs_texrender_get_texture(texrender));
  100. }
  101. void ScreenshotObj::Copy()
  102. {
  103. uint8_t *videoData = nullptr;
  104. uint32_t videoLinesize = 0;
  105. if (gs_stagesurface_map(stagesurf, &videoData, &videoLinesize)) {
  106. if (gs_stagesurface_get_color_format(stagesurf) == GS_RGBA16F) {
  107. const uint32_t linesize = cx * 8;
  108. half_bytes.reserve(cx * cy * 8);
  109. for (uint32_t y = 0; y < cy; y++) {
  110. const uint8_t *const line =
  111. videoData + (y * videoLinesize);
  112. half_bytes.insert(half_bytes.end(), line,
  113. line + linesize);
  114. }
  115. } else {
  116. image = QImage(cx, cy, QImage::Format::Format_RGBX8888);
  117. int linesize = image.bytesPerLine();
  118. for (int y = 0; y < (int)cy; y++)
  119. memcpy(image.scanLine(y),
  120. videoData + (y * videoLinesize),
  121. linesize);
  122. }
  123. gs_stagesurface_unmap(stagesurf);
  124. }
  125. }
  126. void ScreenshotObj::Save()
  127. {
  128. OBSBasic *main = OBSBasic::Get();
  129. config_t *config = main->Config();
  130. const char *mode = config_get_string(config, "Output", "Mode");
  131. const char *type = config_get_string(config, "AdvOut", "RecType");
  132. const char *adv_path =
  133. strcmp(type, "Standard")
  134. ? config_get_string(config, "AdvOut", "FFFilePath")
  135. : config_get_string(config, "AdvOut", "RecFilePath");
  136. const char *rec_path =
  137. strcmp(mode, "Advanced")
  138. ? config_get_string(config, "SimpleOutput", "FilePath")
  139. : adv_path;
  140. bool noSpace =
  141. config_get_bool(config, "SimpleOutput", "FileNameWithoutSpace");
  142. const char *filenameFormat =
  143. config_get_string(config, "Output", "FilenameFormatting");
  144. bool overwriteIfExists =
  145. config_get_bool(config, "Output", "OverwriteIfExists");
  146. const char *ext = half_bytes.empty() ? "png" : "jxr";
  147. path = GetOutputFilename(
  148. rec_path, ext, noSpace, overwriteIfExists,
  149. GetFormatString(filenameFormat, "Screenshot", nullptr).c_str());
  150. th = std::thread([this] { MuxAndFinish(); });
  151. }
  152. #ifdef _WIN32
  153. static HRESULT SaveJxrImage(LPCWSTR path, uint8_t *pixels, uint32_t cx,
  154. uint32_t cy, IWICBitmapFrameEncode *frameEncode,
  155. IPropertyBag2 *options)
  156. {
  157. wchar_t lossless[] = L"Lossless";
  158. PROPBAG2 bag = {};
  159. bag.pstrName = lossless;
  160. VARIANT value = {};
  161. value.vt = VT_BOOL;
  162. value.bVal = TRUE;
  163. HRESULT hr = options->Write(1, &bag, &value);
  164. if (FAILED(hr))
  165. return hr;
  166. hr = frameEncode->Initialize(options);
  167. if (FAILED(hr))
  168. return hr;
  169. hr = frameEncode->SetSize(cx, cy);
  170. if (FAILED(hr))
  171. return hr;
  172. hr = frameEncode->SetResolution(72, 72);
  173. if (FAILED(hr))
  174. return hr;
  175. WICPixelFormatGUID pixelFormat = GUID_WICPixelFormat64bppRGBAHalf;
  176. hr = frameEncode->SetPixelFormat(&pixelFormat);
  177. if (FAILED(hr))
  178. return hr;
  179. if (memcmp(&pixelFormat, &GUID_WICPixelFormat64bppRGBAHalf,
  180. sizeof(WICPixelFormatGUID)) != 0)
  181. return E_FAIL;
  182. hr = frameEncode->WritePixels(cy, cx * 8, cx * cy * 8, pixels);
  183. if (FAILED(hr))
  184. return hr;
  185. hr = frameEncode->Commit();
  186. if (FAILED(hr))
  187. return hr;
  188. return S_OK;
  189. }
  190. static HRESULT SaveJxr(LPCWSTR path, uint8_t *pixels, uint32_t cx, uint32_t cy)
  191. {
  192. Microsoft::WRL::ComPtr<IWICImagingFactory> factory;
  193. HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory, NULL,
  194. CLSCTX_INPROC_SERVER,
  195. IID_PPV_ARGS(factory.GetAddressOf()));
  196. if (FAILED(hr))
  197. return hr;
  198. Microsoft::WRL::ComPtr<IWICStream> stream;
  199. hr = factory->CreateStream(stream.GetAddressOf());
  200. if (FAILED(hr))
  201. return hr;
  202. hr = stream->InitializeFromFilename(path, GENERIC_WRITE);
  203. if (FAILED(hr))
  204. return hr;
  205. Microsoft::WRL::ComPtr<IWICBitmapEncoder> encoder = NULL;
  206. hr = factory->CreateEncoder(GUID_ContainerFormatWmp, NULL,
  207. encoder.GetAddressOf());
  208. if (FAILED(hr))
  209. return hr;
  210. hr = encoder->Initialize(stream.Get(), WICBitmapEncoderNoCache);
  211. if (FAILED(hr))
  212. return hr;
  213. Microsoft::WRL::ComPtr<IWICBitmapFrameEncode> frameEncode;
  214. Microsoft::WRL::ComPtr<IPropertyBag2> options;
  215. hr = encoder->CreateNewFrame(frameEncode.GetAddressOf(),
  216. options.GetAddressOf());
  217. if (FAILED(hr))
  218. return hr;
  219. hr = SaveJxrImage(path, pixels, cx, cy, frameEncode.Get(),
  220. options.Get());
  221. if (FAILED(hr))
  222. return hr;
  223. encoder->Commit();
  224. return S_OK;
  225. }
  226. #endif // #ifdef _WIN32
  227. void ScreenshotObj::MuxAndFinish()
  228. {
  229. if (half_bytes.empty()) {
  230. image.save(QT_UTF8(path.c_str()));
  231. blog(LOG_INFO, "Saved screenshot to '%s'", path.c_str());
  232. } else {
  233. #ifdef _WIN32
  234. wchar_t *path_w = nullptr;
  235. os_utf8_to_wcs_ptr(path.c_str(), 0, &path_w);
  236. if (path_w) {
  237. SaveJxr(path_w, half_bytes.data(), cx, cy);
  238. bfree(path_w);
  239. }
  240. #endif // #ifdef _WIN32
  241. }
  242. deleteLater();
  243. }
  244. /* ========================================================================= */
  245. #define STAGE_SCREENSHOT 0
  246. #define STAGE_DOWNLOAD 1
  247. #define STAGE_COPY_AND_SAVE 2
  248. #define STAGE_FINISH 3
  249. static void ScreenshotTick(void *param, float)
  250. {
  251. ScreenshotObj *data = reinterpret_cast<ScreenshotObj *>(param);
  252. if (data->stage == STAGE_FINISH) {
  253. return;
  254. }
  255. obs_enter_graphics();
  256. switch (data->stage) {
  257. case STAGE_SCREENSHOT:
  258. data->Screenshot();
  259. break;
  260. case STAGE_DOWNLOAD:
  261. data->Download();
  262. break;
  263. case STAGE_COPY_AND_SAVE:
  264. data->Copy();
  265. QMetaObject::invokeMethod(data, "Save");
  266. obs_remove_tick_callback(ScreenshotTick, data);
  267. break;
  268. }
  269. obs_leave_graphics();
  270. data->stage++;
  271. }
  272. void OBSBasic::Screenshot(OBSSource source)
  273. {
  274. if (!!screenshotData) {
  275. blog(LOG_WARNING, "Cannot take new screenshot, "
  276. "screenshot currently in progress");
  277. return;
  278. }
  279. screenshotData = new ScreenshotObj(source);
  280. }
  281. void OBSBasic::ScreenshotSelectedSource()
  282. {
  283. OBSSceneItem item = GetCurrentSceneItem();
  284. if (item) {
  285. Screenshot(obs_sceneitem_get_source(item));
  286. } else {
  287. blog(LOG_INFO, "Could not take a source screenshot: "
  288. "no source selected");
  289. }
  290. }
  291. void OBSBasic::ScreenshotProgram()
  292. {
  293. Screenshot(GetProgramSource());
  294. }
  295. void OBSBasic::ScreenshotScene()
  296. {
  297. Screenshot(GetCurrentSceneSource());
  298. }