1
0

ScreenshotObj.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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 "ScreenshotObj.hpp"
  15. #include <widgets/OBSBasic.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. #include "moc_ScreenshotObj.cpp"
  24. static void ScreenshotTick(void *param, float);
  25. ScreenshotObj::ScreenshotObj(obs_source_t *source) : weakSource(OBSGetWeakRef(source))
  26. {
  27. obs_add_tick_callback(ScreenshotTick, this);
  28. }
  29. ScreenshotObj::~ScreenshotObj()
  30. {
  31. obs_enter_graphics();
  32. gs_stagesurface_destroy(stagesurf);
  33. gs_texrender_destroy(texrender);
  34. obs_leave_graphics();
  35. obs_remove_tick_callback(ScreenshotTick, this);
  36. if (th.joinable()) {
  37. th.join();
  38. if (cx && cy) {
  39. OBSBasic *main = OBSBasic::Get();
  40. main->ShowStatusBarMessage(
  41. QTStr("Basic.StatusBar.ScreenshotSavedTo").arg(QT_UTF8(path.c_str())));
  42. main->lastScreenshot = path;
  43. main->OnEvent(OBS_FRONTEND_EVENT_SCREENSHOT_TAKEN);
  44. }
  45. }
  46. }
  47. void ScreenshotObj::Screenshot()
  48. {
  49. OBSSource source = OBSGetStrongRef(weakSource);
  50. if (source) {
  51. cx = obs_source_get_width(source);
  52. cy = obs_source_get_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 = obs_source_get_color_space(source, 0, nullptr);
  67. if (space == GS_CS_709_EXTENDED) {
  68. /* Convert for JXR */
  69. space = GS_CS_709_SCRGB;
  70. }
  71. #else
  72. /* Tonemap to SDR if HDR */
  73. const enum gs_color_space space = GS_CS_SRGB;
  74. #endif
  75. const enum gs_color_format format = gs_get_format_from_space(space);
  76. texrender = gs_texrender_create(format, GS_ZS_NONE);
  77. stagesurf = gs_stagesurface_create(cx, cy, format);
  78. if (gs_texrender_begin_with_color_space(texrender, cx, cy, space)) {
  79. vec4 zero;
  80. vec4_zero(&zero);
  81. gs_clear(GS_CLEAR_COLOR, &zero, 0.0f, 0);
  82. gs_ortho(0.0f, (float)cx, 0.0f, (float)cy, -100.0f, 100.0f);
  83. gs_blend_state_push();
  84. gs_blend_function(GS_BLEND_ONE, GS_BLEND_ZERO);
  85. if (source) {
  86. obs_source_inc_showing(source);
  87. obs_source_video_render(source);
  88. obs_source_dec_showing(source);
  89. } else {
  90. obs_render_main_texture();
  91. }
  92. gs_blend_state_pop();
  93. gs_texrender_end(texrender);
  94. }
  95. }
  96. void ScreenshotObj::Download()
  97. {
  98. gs_stage_texture(stagesurf, gs_texrender_get_texture(texrender));
  99. }
  100. void ScreenshotObj::Copy()
  101. {
  102. uint8_t *videoData = nullptr;
  103. uint32_t videoLinesize = 0;
  104. if (gs_stagesurface_map(stagesurf, &videoData, &videoLinesize)) {
  105. if (gs_stagesurface_get_color_format(stagesurf) == GS_RGBA16F) {
  106. const uint32_t linesize = cx * 8;
  107. half_bytes.reserve(cx * cy * 8);
  108. for (uint32_t y = 0; y < cy; y++) {
  109. const uint8_t *const line = videoData + (y * videoLinesize);
  110. half_bytes.insert(half_bytes.end(), line, line + linesize);
  111. }
  112. } else {
  113. image = QImage(cx, cy, QImage::Format::Format_RGBX8888);
  114. int linesize = image.bytesPerLine();
  115. for (int y = 0; y < (int)cy; y++)
  116. memcpy(image.scanLine(y), videoData + (y * videoLinesize), linesize);
  117. }
  118. gs_stagesurface_unmap(stagesurf);
  119. }
  120. }
  121. void ScreenshotObj::Save()
  122. {
  123. OBSBasic *main = OBSBasic::Get();
  124. config_t *config = main->Config();
  125. const char *mode = config_get_string(config, "Output", "Mode");
  126. const char *type = config_get_string(config, "AdvOut", "RecType");
  127. const char *adv_path = strcmp(type, "Standard") ? config_get_string(config, "AdvOut", "FFFilePath")
  128. : config_get_string(config, "AdvOut", "RecFilePath");
  129. const char *rec_path = strcmp(mode, "Advanced") ? config_get_string(config, "SimpleOutput", "FilePath")
  130. : adv_path;
  131. bool noSpace = config_get_bool(config, "SimpleOutput", "FileNameWithoutSpace");
  132. const char *filenameFormat = config_get_string(config, "Output", "FilenameFormatting");
  133. bool overwriteIfExists = config_get_bool(config, "Output", "OverwriteIfExists");
  134. const char *ext = half_bytes.empty() ? "png" : "jxr";
  135. path = GetOutputFilename(rec_path, ext, noSpace, overwriteIfExists,
  136. GetFormatString(filenameFormat, "Screenshot", nullptr).c_str());
  137. th = std::thread([this] { MuxAndFinish(); });
  138. }
  139. #ifdef _WIN32
  140. static HRESULT SaveJxrImage(LPCWSTR path, uint8_t *pixels, uint32_t cx, uint32_t cy, IWICBitmapFrameEncode *frameEncode,
  141. IPropertyBag2 *options)
  142. {
  143. wchar_t lossless[] = L"Lossless";
  144. PROPBAG2 bag = {};
  145. bag.pstrName = lossless;
  146. VARIANT value = {};
  147. value.vt = VT_BOOL;
  148. value.bVal = TRUE;
  149. HRESULT hr = options->Write(1, &bag, &value);
  150. if (FAILED(hr))
  151. return hr;
  152. hr = frameEncode->Initialize(options);
  153. if (FAILED(hr))
  154. return hr;
  155. hr = frameEncode->SetSize(cx, cy);
  156. if (FAILED(hr))
  157. return hr;
  158. hr = frameEncode->SetResolution(72, 72);
  159. if (FAILED(hr))
  160. return hr;
  161. WICPixelFormatGUID pixelFormat = GUID_WICPixelFormat64bppRGBAHalf;
  162. hr = frameEncode->SetPixelFormat(&pixelFormat);
  163. if (FAILED(hr))
  164. return hr;
  165. if (memcmp(&pixelFormat, &GUID_WICPixelFormat64bppRGBAHalf, sizeof(WICPixelFormatGUID)) != 0)
  166. return E_FAIL;
  167. hr = frameEncode->WritePixels(cy, cx * 8, cx * cy * 8, pixels);
  168. if (FAILED(hr))
  169. return hr;
  170. hr = frameEncode->Commit();
  171. if (FAILED(hr))
  172. return hr;
  173. return S_OK;
  174. }
  175. static HRESULT SaveJxr(LPCWSTR path, uint8_t *pixels, uint32_t cx, uint32_t cy)
  176. {
  177. Microsoft::WRL::ComPtr<IWICImagingFactory> factory;
  178. HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
  179. IID_PPV_ARGS(factory.GetAddressOf()));
  180. if (FAILED(hr))
  181. return hr;
  182. Microsoft::WRL::ComPtr<IWICStream> stream;
  183. hr = factory->CreateStream(stream.GetAddressOf());
  184. if (FAILED(hr))
  185. return hr;
  186. hr = stream->InitializeFromFilename(path, GENERIC_WRITE);
  187. if (FAILED(hr))
  188. return hr;
  189. Microsoft::WRL::ComPtr<IWICBitmapEncoder> encoder = NULL;
  190. hr = factory->CreateEncoder(GUID_ContainerFormatWmp, NULL, encoder.GetAddressOf());
  191. if (FAILED(hr))
  192. return hr;
  193. hr = encoder->Initialize(stream.Get(), WICBitmapEncoderNoCache);
  194. if (FAILED(hr))
  195. return hr;
  196. Microsoft::WRL::ComPtr<IWICBitmapFrameEncode> frameEncode;
  197. Microsoft::WRL::ComPtr<IPropertyBag2> options;
  198. hr = encoder->CreateNewFrame(frameEncode.GetAddressOf(), options.GetAddressOf());
  199. if (FAILED(hr))
  200. return hr;
  201. hr = SaveJxrImage(path, pixels, cx, cy, frameEncode.Get(), options.Get());
  202. if (FAILED(hr))
  203. return hr;
  204. encoder->Commit();
  205. return S_OK;
  206. }
  207. #endif // #ifdef _WIN32
  208. void ScreenshotObj::MuxAndFinish()
  209. {
  210. if (half_bytes.empty()) {
  211. image.save(QT_UTF8(path.c_str()));
  212. blog(LOG_INFO, "Saved screenshot to '%s'", path.c_str());
  213. } else {
  214. #ifdef _WIN32
  215. wchar_t *path_w = nullptr;
  216. os_utf8_to_wcs_ptr(path.c_str(), 0, &path_w);
  217. if (path_w) {
  218. SaveJxr(path_w, half_bytes.data(), cx, cy);
  219. bfree(path_w);
  220. }
  221. #endif // #ifdef _WIN32
  222. }
  223. deleteLater();
  224. }
  225. #define STAGE_SCREENSHOT 0
  226. #define STAGE_DOWNLOAD 1
  227. #define STAGE_COPY_AND_SAVE 2
  228. #define STAGE_FINISH 3
  229. static void ScreenshotTick(void *param, float)
  230. {
  231. ScreenshotObj *data = static_cast<ScreenshotObj *>(param);
  232. if (data->stage == STAGE_FINISH) {
  233. return;
  234. }
  235. obs_enter_graphics();
  236. switch (data->stage) {
  237. case STAGE_SCREENSHOT:
  238. data->Screenshot();
  239. break;
  240. case STAGE_DOWNLOAD:
  241. data->Download();
  242. break;
  243. case STAGE_COPY_AND_SAVE:
  244. data->Copy();
  245. QMetaObject::invokeMethod(data, "Save");
  246. obs_remove_tick_callback(ScreenshotTick, data);
  247. break;
  248. }
  249. obs_leave_graphics();
  250. data->stage++;
  251. }