I want to write a screencasting program for the Windows platform, but am unsure of how to capture the screen. The only method I'm aware of is to use GDI, but I'm curious whether there are other ways to go about this, and, if there are, which incurs the least overhead? Speed is a priority.
The screencasting program will be for recording game footage, although, if this does narrow down the options, I'm still open for any other suggestions that fall out of this scope. Knowledge isn't bad, after all.
Edit: I came across this article: Various methods for capturing the screen. It has introduced me to the Windows Media API way of doing it and the DirectX way of doing it. It mentions in the Conclusion that disabling hardware acceleration could drastically improve the performance of the capture application. I'm curious as to why this is. Could anyone fill in the missing blanks for me?
Edit: I read that screencasting programs such as Camtasia use their own capture driver. Could someone give me an in-depth explanation on how it works, and why it is faster? I may also need guidance on implementing something like that, but I'm sure there is existing documentation anyway.
Also, I now know how FRAPS records the screen. It hooks the underlying graphics API to read from the back buffer. From what I understand, this is faster than reading from the front buffer, because you are reading from system RAM, rather than video RAM. You can read the article here.
This is what I use to collect single frames, but if you modify this and keep the two targets open all the time then you could "stream" it to disk using a static counter for the file name. - I can't recall where I found this, but it has been modified, thanks to whoever!
void dump_buffer()
{
IDirect3DSurface9* pRenderTarget=NULL;
IDirect3DSurface9* pDestTarget=NULL;
const char file[] = "Pickture.bmp";
// sanity checks.
if (Device == NULL)
return;
// get the render target surface.
HRESULT hr = Device->GetRenderTarget(0, &pRenderTarget);
// get the current adapter display mode.
//hr = pDirect3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT,&d3ddisplaymode);
// create a destination surface.
hr = Device->CreateOffscreenPlainSurface(DisplayMde.Width,
DisplayMde.Height,
DisplayMde.Format,
D3DPOOL_SYSTEMMEM,
&pDestTarget,
NULL);
//copy the render target to the destination surface.
hr = Device->GetRenderTargetData(pRenderTarget, pDestTarget);
//save its contents to a bitmap file.
hr = D3DXSaveSurfaceToFile(file,
D3DXIFF_BMP,
pDestTarget,
NULL,
NULL);
// clean up.
pRenderTarget->Release();
pDestTarget->Release();
}
EDIT: I can see that this is listed under your first edit link as "the GDI way". This is still a decent way to go even with the performance advisory on that site, you can get to 30fps easily I would think.
From this comment (I have no experience doing this, I'm just referencing someone who does):
HDC hdc = GetDC(NULL); // get the desktop device context
HDC hDest = CreateCompatibleDC(hdc); // create a device context to use yourself
// get the height and width of the screen
int height = GetSystemMetrics(SM_CYVIRTUALSCREEN);
int width = GetSystemMetrics(SM_CXVIRTUALSCREEN);
// create a bitmap
HBITMAP hbDesktop = CreateCompatibleBitmap( hdc, width, height);
// use the previously created device context with the bitmap
SelectObject(hDest, hbDesktop);
// copy from the desktop device context to the bitmap device context
// call this once per 'frame'
BitBlt(hDest, 0,0, width, height, hdc, 0, 0, SRCCOPY);
// after the recording is done, release the desktop context you got..
ReleaseDC(NULL, hdc);
// ..delete the bitmap you were using to capture frames..
DeleteObject(hbDesktop);
// ..and delete the context you created
DeleteDC(hDest);
I'm not saying this is the fastest, but the BitBlt operation is generally very fast if you're copying between compatible device contexts.
For reference, Open Broadcaster Software implements something like this as part of their "dc_capture" method, although rather than creating the destination context hDest using CreateCompatibleDC they use an IDXGISurface1, which works with DirectX 10+. If there is no support for this they fall back to CreateCompatibleDC.
To change it to use a specific application, you need to change the first line to GetDC(game) where game is the handle of the game's window, and then set the right height and width of the game's window too.
Once you have the pixels in hDest/hbDesktop, you still need to save it to a file, but if you're doing screen capture then I would think you would want to buffer a certain number of them in memory and save to the video file in chunks, so I will not point to code for saving a static image to disk.
I wrote a video capture software, similar to FRAPS for DirectX applications. The source code is available and my article explains the general technique. Look at http://blog.nektra.com/main/2013/07/23/instrumenting-direct3d-applications-to-capture-video-and-calculate-frames-per-second/
Respect to your questions related to performance,
DirectX should be faster than GDI except when you are reading from the frontbuffer which is very slow. My approach is similar to FRAPS (reading from backbuffer). I intercept a set of methods from Direct3D interfaces.
For video recording in realtime (with minimal application impact), a fast codec is essential. FRAPS uses it's own lossless video codec. Lagarith and HUFFYUV are generic lossless video codecs designed for realtime applications. You should look at them if you want to output video files.
Another approach to recording screencasts could be to write a Mirror Driver. According to Wikipedia: When video mirroring is active, each time the system draws to the primary video device at a location inside the mirrored area, a copy of the draw operation is executed on the mirrored video device in real-time. See mirror drivers at MSDN: http://msdn.microsoft.com/en-us/library/windows/hardware/ff568315(v=vs.85).aspx.
I use d3d9 to get the backbuffer, and save that to a png file using the d3dx library:
IDirect3DSurface9 *surface ;
// GetBackBuffer
idirect3ddevice9->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &surface ) ;
// save the surface
D3DXSaveSurfaceToFileA( "filename.png", D3DXIFF_PNG, surface, NULL, NULL ) ;
SAFE_RELEASE( surface ) ;
To do this you should create your swapbuffer with
d3dpps.SwapEffect = D3DSWAPEFFECT_COPY ; // for screenshots.
(So you guarantee the backbuffer isn't mangled before you take the screenshot).
In my Impression, the GDI approach and the DX approach are different in its nature.
painting using GDI applies the FLUSH method, the FLUSH approach draws the frame then clear it and redraw another frame in the same buffer, this will result in flickering in games require high frame rate.
WHY DX quicker?
in DX (or graphics world), a more mature method called double buffer rendering is applied, where two buffers are present, when present the front buffer to the hardware, you can render to the other buffer as well, then after the frame 1 is finished rendering, the system swap to the other buffer( locking it for presenting to hardware , and release the previous buffer ), in this way the rendering inefficiency is greatly improved.
WHY turning down hardware acceleration quicker?
although with double buffer rendering, the FPS is improved, but the time for rendering is still limited. modern graphic hardware usually involves a lot of optimization during rendering typically like anti-aliasing, this is very computation intensive, if you don't require that high quality graphics, of course you can just disable this option. and this will save you some time.
I think what you really need is a replay system, which I totally agree with what people discussed.
I wrote a class that implemented the GDI method for screen capture. I too wanted extra speed so, after discovering the DirectX method (via GetFrontBuffer) I tried that, expecting it to be faster.
I was dismayed to find that GDI performs about 2.5x faster. After 100 trials capturing my dual monitor display, the GDI implementation averaged 0.65s per screen capture, while the DirectX method averaged 1.72s. So GDI is definitely faster than GetFrontBuffer, according to my tests.
I was unable to get Brandrew's code working to test DirectX via GetRenderTargetData. The screen copy came out purely black. However, it could copy that blank screen super fast! I'll keep tinkering with that and hope to get a working version to see real results from it.
For C++ you can use: http://www.pinvoke.net/default.aspx/gdi32/BitBlt.html
This may hower not work on all types of 3D applications/video apps. Then this link may be more useful as it describes 3 different methods you can use.
Old answer (C#):
You can use System.Drawing.Graphics.Copy, but it is not very fast.
A sample project I wrote doing exactly this: http://blog.tedd.no/index.php/2010/08/16/c-image-analysis-auto-gaming-with-source/
I'm planning to update this sample using a faster method like Direct3D: http://spazzarama.com/2009/02/07/screencapture-with-direct3d/
And here is a link for capturing to video: How to capture screen to be video using C# .Net?
You want the Desktop Duplication API (available since Windows 8). That is the officially recommended way of doing it, and it's also the most CPU efficient.
One nice feature it has for screencasting is that it detects window movement, so you can transmit block deltas when windows get moved around, instead of raw pixels. Also, it tells you which rectangles have changed, from one frame to the next.
The Microsoft example code is quite complex, but the API is actually simple and easy to use. I've put together an example project that is much simpler:
Simplified Sample Code
WindowsDesktopDuplicationSample
Microsoft References
Desktop Duplication API
Official example code (my example above is a stripped down version of this)
A few things I've been able to glean: apparently using a "mirror driver" is fast though I'm not aware of an OSS one.
Why is RDP so fast compared to other remote control software?
Also apparently using some convolutions of StretchRect are faster than BitBlt
http://betterlogic.com/roger/2010/07/fast-screen-capture/comment-page-1/#comment-5193
And the one you mentioned (fraps hooking into the D3D dll's) is probably the only way for D3D applications, but won't work with Windows XP desktop capture. So now I just wish there were a fraps equivalent speed-wise for normal desktop windows...anybody?
(I think with aero you might be able to use fraps-like hooks, but XP users would be out of luck).
Also apparently changing screen bit depths and/or disabling hardware accel. might help (and/or disabling aero).
https://github.com/rdp/screen-capture-recorder-program includes a reasonably fast BitBlt based capture utility, and a benchmarker as part of its install, which can let you benchmark BitBlt speeds to optimize them.
VirtualDub also has an "opengl" screen capture module that is said to be fast and do things like change detection http://www.virtualdub.org/blog/pivot/entry.php?id=290
You can try the c++ open source project WinRobot #git, a powerful screen capturer
CComPtr<IWinRobotService> pService;
hr = pService.CoCreateInstance(__uuidof(ServiceHost) );
//get active console session
CComPtr<IUnknown> pUnk;
hr = pService->GetActiveConsoleSession(&pUnk);
CComQIPtr<IWinRobotSession> pSession = pUnk;
// capture screen
pUnk = 0;
hr = pSession->CreateScreenCapture(0,0,1280,800,&pUnk);
// get screen image data(with file mapping)
CComQIPtr<IScreenBufferStream> pBuffer = pUnk;
Support :
UAC Window
Winlogon
DirectShowOverlay
Screen Recording can be done in C# using VLC API. I have done a sample program to demonstrate this. It uses LibVLCSharp and VideoLAN.LibVLC.Windows libraries. You could achieve many more features related to video rendering using this cross platform API.
For API documentation see: LibVLCSharp API Github
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using LibVLCSharp.Shared;
namespace ScreenRecorderNetApp
{
class Program
{
static void Main(string[] args)
{
Core.Initialize();
using (var libVlc = new LibVLC())
using (var mediaPlayer = new MediaPlayer(libVlc))
{
var media = new Media(libVlc, "screen://", FromType.FromLocation);
media.AddOption(":screen-fps=24");
media.AddOption(":sout=#transcode{vcodec=h264,vb=0,scale=0,acodec=mp4a,ab=128,channels=2,samplerate=44100}:file{dst=testvlc.mp4}");
media.AddOption(":sout-keep");
mediaPlayer.Play(media);
Thread.Sleep(10*1000);
mediaPlayer.Stop();
}
}
}
}
This might not be the fastest method, but it is leightweight and easy to use. The image is returned as an integer array containing the RGB colors.
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#include <Windows.h>
int* screenshot(int& width, int& height) {
HDC hdc = GetDC(NULL); // get the desktop device context
HDC cdc = CreateCompatibleDC(hdc); // create a device context to use yourself
height = (int)GetSystemMetrics(SM_CYVIRTUALSCREEN); // get the width and height of the screen
width = 16*height/9; // only capture left monitor for dual screen setups, for both screens use (int)GetSystemMetrics(SM_CXVIRTUALSCREEN);
HBITMAP hbitmap = CreateCompatibleBitmap(hdc, width, height); // create a bitmap
SelectObject(cdc, hbitmap); // use the previously created device context with the bitmap
BITMAPINFOHEADER bmi = { 0 };
bmi.biSize = sizeof(BITMAPINFOHEADER);
bmi.biPlanes = 1;
bmi.biBitCount = 32;
bmi.biWidth = width;
bmi.biHeight = -height; // flip image upright
bmi.biCompression = BI_RGB;
bmi.biSizeImage = 3*width*height;
BitBlt(cdc, 0, 0, width, height, hdc, 0, 0, SRCCOPY); // copy from desktop device context to bitmap device context
ReleaseDC(NULL, hdc);
int* image = new int[width*height];
GetDIBits(cdc, hbitmap, 0, height, image, (BITMAPINFO*)&bmi, DIB_RGB_COLORS);
DeleteObject(hbitmap);
DeleteDC(cdc);
return image;
}
The above code combines this answer and this answer.
Example on how to use it:
int main() {
int width=0, height=0;
int* image = screenshot(width, height);
// access pixel colors for position (x|y)
const int x=0, y=0;
const int color = image[x+y*width];
const int red = (color>>16)&255;
const int green = (color>> 8)&255;
const int blue = color &255;
delete[] image;
}
i myself do it with directx and think it's as fast as you would want it to be. i don't have a quick code sample, but i found this which should be useful. the directx11 version should not differ a lot, directx9 maybe a little more, but thats the way to go
DXGI Desktop Capture
Project that captures the desktop image with DXGI duplication. Saves the captured image to the file in different image formats (*.bmp; *.jpg; *.tif).
This sample is written in C++. You also need some experience with DirectX (D3D11, D2D1).
What the Application Can Do
If you have more than one desktop monitor, you can choose.
Resize the captured desktop image.
Choose different scaling modes.
You can show or hide the mouse icon in the output image.
You can rotate the image for the output picture, or leave it as default.
I realize the following suggestion doesn't answer your question, but the simplest method I have found to capture a rapidly-changing DirectX view, is to plug a video camera into the S-video port of the video card, and record the images as a movie. Then transfer the video from the camera back to an MPG, WMV, AVI etc. file on the computer.
Windows.Graphics.Capture
Enables apps to capture environments, application windows, and displays in a secure, easy to use way with the use of a system picker UI control.
https://blogs.windows.com/windowsdeveloper/2019/09/16/new-ways-to-do-screen-capture/
I am using IMFMediaEngine to playback video streams (Smooth Streaming, HLS) and possibly with PlayReady later.
It works wonderfully using TransferVideoFrame to draw the video onto a texture. But I understand that it is a requirement for PlayReady + DRM + 1080p videos, to use DirectComposition. So I am trying to make this works.
Also another advantage of doing it this way, the video frame rendering is independent from the app so possible stuttering or lag in the app UI won't affect the video playback.
I am able to make it work, but unfortunately the IDCompositionVisual I am using always end up being restricted to 640x480. So the video has to downscale to it. Then if I transform this to scale it up, I get an ugly stretched picture.
I am registering the Visual this way:
pMediaAttributes->SetUnknown(MF_MEDIA_ENGINE_PLAYBACK_VISUAL, m_pDcompVideoVisual);
As documented here:
https://msdn.microsoft.com/en-us/library/windows/desktop/hh162850(v=vs.85).aspx
Trying to create a surface prior and SetContent on the Visual doesn't change anything. It's like the video player override it with it's own surface, 640x480. It would really be nice to stick it to the simple player, and find the real solution to this problem and be able to specify the size of the Visual Surface when I received the MF_MEDIA_ENGINE_EVENT_FORMATCHANGE event.
Because this is an option in IMFMediaEngine to specify a DirectComposition surface, there must be a way to make this work.
Based on the docs I see for IMFMediaEngine, you should be able to handle DRM protected content using IMFMediaEngineProtectedContent->TransferVideoFrame:
“For protected content, call this method instead of the IMFMediaEngine::TransferVideoFrame method.”
Something like this can go in the VideoPlayer::CaptureFrame method of the sample you provided:
// Transfer the frame to the texture
auto pIMFMediaEngineUnknown = reinterpret_cast<IUnknown *>(m_pMediaEngine);
IMFMediaEngineProtectedContent *temp = 0;
pIMFMediaEngineUnknown->QueryInterface(IID_PPV_ARGS(&temp));
DWORD flags = 0;
HRESULT ret = temp->TransferVideoFrame(m_pRenderTarget, &videoRect, &targetRect, &borderColor, &flags);
temp->Release();
//HRESULT ret = m_pMediaEngine->TransferVideoFrame(m_pRenderTarget, &videoRect, &targetRect, &borderColor);
assert(ret == S_OK && "Failed to transfer video frame");
Give this a shot with 1080p protected content.
I am creating an app in Qt, similar to scribble (given in sample app). Purpose is to let user draw freehand and once finished, upload these drawing to net. As of now I am saving the drawing as PNG image every 5 seconds, so that the loss of data in an event of unexpected shut-down is minimum (I kept 5 sec to minimize write operations; Real real-time would be highly desirable).
But the problem is, I am saving the entire page as an image every 5 seconds, where the new data added may be few pixels. I was wondering if I could write ONLY the new pixels added into the disk; there is no constraint that I should use PNG while saving; I can convert the data to PNG at the end when user says he is finished.
The piece of code for saving very basic;
void SaveData(const QString &fileName, const char *fileFormat, QImage image)
{
mutex.lock();
QImage visibleImage = image;
if (visibleImage.save(fileName, fileFormat, 50))
{
system("sync");
mutex.unlock();
return true;
} else {
mutex.unlock();
return false;
}
}
I just wonder if REAL real-time save as the pixels getting added if possible..!
Thanks in advance
DK
I suggest you to use tiles to save the image. Split the canvas to many e.g. 64x64 rectangles. And save each rectangle into separate file. When something is changed, you need to rewrite only few small files instead of rewriting the whole picture.
Also there is another dangerous thing in your code. When you run QImage::save, it most likely will erase file contents and write new contents. If the system was shutted down between there two actions, your file will became empty. So it's important to write new contents to a temporary file and then move it to the proper location. Keeping several old version of a file also can be useful. Who knows how the file system will react on the shutdown.
You could maybe use a memory mapped file, something like:
QFile file("rawimage.dat");
file.open(QIODevice::ReadWrite);
// Make sure there is enough memory for the image
quint32 width = 16;
quint32 height = 16;
quint32 bpp32 = 4;
qint64 file_size = width * height * bpp32;
file.resize(file_size);
uchar* mem = file.map(0, file_size);
// make a QImage that uses the file as memory
QImage img(mem, 16, 16, QImage::Format_ARGB32);
// Do some drawing in the image
img.fill(0);
// finished with the file
file.unmap(mem);
file.close();
You will need to check that it actually flushes to disk correctly - I haven't tested this. Ideally on Windows you'd want to be able to call 'FlushViewOfFile' on the memory mapped handle to ensure that modified pages are written to disk. It doesn't look like there is a way of calling this in Qt so you might need to do something operating system specific here to ensure that the disk image is consistent when you want it to be.
You could create a list of QPainterPath objects of the drawn items, which are then rendered to the QImage. You'd need to change the mouse events to do the following: -
Mouse Down : create a new QPainterPath (painterPath) and call painterPath->moveTo
Mouse Move : call painterPath->LineTo
Mouse Up : Store the QPainterPath in a list.
In the paint event, you then pass each new QPainterPath to be drawn
To back up, every n seconds, open up a file and append a stream of the new QPainterPaths since the last time the list was saved.
To restore, open the file, stream them back in and draw them on to the Image.
This can be optimised to check for new items and not to bother saving if none exist. In addition, rather than being time based, you could maintain a number of points that are created in the QPainterPath and only save when it exceeds a certain number.
Note that if you do go down this route, you may also want to store Painter settings with each QPainterPath, if the user can also change things such as pen colour, width etc.
Other advantages come with using QPainterpath - for example, the user could open up one image and then a second, choosing to have it drawn on top of the first.
If you want real-time saving then I suggest you use an uncompressed bitmap format. Changing pixels would be as simple as seeking inside the file to the x-y co-ordinates, usually calculated as
file.seek(y * lineWidth + x * pixelDataSize);
file.write(pixelData);
A user installed our application to a server PC, shared the install directory as network drive Z: and now opens the app from different client PCs all over his shop. Everything works fine except for a naggling bug on one of the PCs:
On the Problem PC, the app can load .jpg files for inventory items just fine and show the corresponding QPixmap in a QLabel. When the inventory item he is currently viewing does not yet have an image assigned to it, he can open a file dialog, choose an image and display that correctly. However, saving the (new/changed) QPixmap as a .jpg stores it to disc as a series of colored vertical lines on a black background:
Saving is done via QPixmap::save( const QString & fileName, ...) with the file name set programmatically to "<some_id>.jpg" to designate the desired file format. Returns true, but the resulting file looks like modern art.
However, saving images works fine on the server and the other clients.
Both the server and the Problem PC run Windows XP at an identical patch level.
Process Explorer shows identical DLLs for the app process on server and Problem PC except for the Problem PC using dnsapi.dll, which the server doesn't.
Process Explorer also shows that on both server and client the Qt DLL used to deal with JPEGs is
\Device\LanmanRedirector\<server>\<app>\plugins\imageformats\qjpeg4.dll, and a drive-wide search on the Problem PC for qjpeg*.dll came up empty, so the app should use the same JPEG handling code on both computers.
Any suggestions?
(EDIT: added OS and patch status to problem description.)
EDIT: Solution: on the problem machine we had a 16 bpp colour depth. Setting that to 32 bpp solved our problem instantly. I also replaced
_pm.save( sDestFileName )
with
_pm.toImage().convertToFormat( QImage::Format_RGB32 ).save( sDestFileName )
so that we won't run into this on every old client PC running less than 32 bpp.
Here are a few things to try to isolate the problem:
Copy qjpeg4.dll to the client's working directory
Is the image corrupted when saving as PNG or GIF?
Convert your data to a QImage and work from that.
Consider the byte format (I usually use ARGB32 because it is int-aligned)
To test where the problem occurs, you might try converting the image to JPG format then viewing it in a debugging window.
The function below is from an OSS program I wrote. You might try using it then displaying the contents of the QImage referred to in the second parameter:
//! Saves image with JPEG compression in given quality (0 - 100, Qt's scale)
//! #param[in] in The lossless input image
//! #param[out] out The image to save to using JPEG compression
//! #param quality The quality level (0 - 100, 0 the most compressed)
//! #return The size of the saved image
quint32 Window::imageSaveLossy(QImage &in, QImage &out, quint8 quality)
{
quint32 retval;
QByteArray ba;
QBuffer buffer(&ba);
buffer.open(QIODevice::WriteOnly);
QImage temp(in.size(), QImage::Format_ARGB32);
temp.fill(QColor(Qt::white).rgb());
QPainter painter(&temp);
painter.drawImage(0, 0, in);
temp.save(&buffer, "JPG", quality);
out.loadFromData(ba, "JPG");
retval = (quint32)ba.size();
buffer.close();
return retval;
}