1
0

window-basic-main-screenshot.cpp 9.0 KB

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