ScreenshotObj.cpp 9.7 KB

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