Design of Single-Window Capture API
In this issue, I propose a new feature and API sketch, and invite discussion.
We’ve talked about wanting to capture directly to GPU memory. This is much faster than capturing to CPU memory. If the user is going to encode to H.264 (such as for screen sharing or recording), or send to an AI library, this is definitely a performance win. It also has less impact on other programs.
On Linux/X11, captures to GPU memory can only come from a single window, not the entire screen. This is the opposite of Windows DXGI Desktop Duplication, which can only capture the entire screen. Windows WGC does both, but is going to be quite tough to implement, and isn’t supported on early versions of Windows. I don’t remember about Wayland or macOS.
That means that we’ll want to add single-window capture as an explicit capability of the MSS API, rather than having it be entirely based on a bounding box.
To be clear, this proposal isn’t about adding GPU capture to MSS, not yet. It’s about adding single-window capture. But we do want to anticipate the needs of GPU capture as we design the single-window capture API.
Example
Under this proposal, most of the time, the user can do something simple:
with mss.MSS(window="GitHub - Firefox") as sct:
...
or
with mss.MSS(window=re.compile(r"(^| - )Firefox$") as sct:
...
More advanced use cases are still accommodated by this proposal, such as the CP2077 example below.
When to specify the window
It might seem most convenient for the user to specify the window as part of the grab() call. But that has some problems; we may need to have them specify the window as part of the MSS object construction. I’ll explore the problems here.
We want to make things easy for the users, to free them from having to think about the implementation. As an example, we let the users use backend="default" (the default value). In my head, I’ve been using this as “let MSS decide at runtime”, not “an always-the-same default for the current platform”.
This is because of the limitations I mentioned above. If the user wants to capture a single window, there may be faster mechanisms available than to capture the whole screen. Or vice versa. Or their version of Windows might not support WGC. Specifying backend="default" means that the user wants MSS to choose which backend to use, in the given circumstance. We can write a small decision tree (just some nested if/else logic) for that.
We currently create the MSSImplementation object as part of the MSS constructor. Since this is before grab has been called, then if the user is using backend="default", then we want to know whether they’ll be using single-window or full-screen capture at that time.
Again, while this isn’t necessary with the current backends, it will become necessary with anticipated future backends.
Alternatives (about when to specify the window)
One alternative might be for the user to specify whether they want to use single-window or full-screen capture at construction time, and defer specifying the window to use until later. I’m not sure this buys us anything.
Another alternative might be to defer backend instantiation until the first grab, and to create other backends if the user changes between full-screen and single-window mode. This may be awkward to implement, especially around things like monitor enumeration. I’m not sure that the extra complexity is worthwhile.
How to specify the window
Different platforms may have different ways that users might want to specify the window to use. Here, I’ll refer to this as the window selector. As an initial proposal, I suggest the following.
To accommodate a wide variety of window selection needs, the API I’m proposing is quite flexible, but still easy to implement and to use. The user may specify the window as any of the following:
- An integer, giving the native ID. This is a Window XID on Linux/X11, HWND on Windows, and CGWindowID on macOS. This identifies a specific currently-existing native window, not an application-level window that survives recreation.
- A string, giving the user-visible title, such as “Firefox - GitHub”.
- A
re.Patternobject, to be matched against the user-visible title, such asre.compile(r"(^| - )Firefox$"). - A Mapping. The keys are platform-specific, but include a few common ones such as "id" (native ID), "exe" (process executable), "pid", "title", "class" (
WM_CLASS/lpszClassName, usually more stable than the title), etc, in addition to some platform-specific values if appropriate. The values are strings orre.Patterns if appropriate, or integers if that makes more sense. The targeted window is whatever matches all the criteria. In practice, this will probably just have one entry, but using a Mapping makes it easy to allow for a flexible key/value pair. Examples:window={"class": "firefox-esr"}, orwindow={"pid": 12345}. - A callback function. This will be called with a list of all the windows available. Specifically, it receives a Sequence of (MSS-defined) window objects, each with properties similar to those in the mapping described above. The callback must return whichever window object is desired. This is the most flexible option, but can be cumbersome to use in simple programs. The above options are provided as a convenience for the common cases.
- The window objects deliberately aren’t simple mappings. This is because it may be expensive to collect all the potentially-useful information about all windows, when the user only cares about one or two attributes. Specifying these as objects makes it simpler to lazily populate.
- 💭 We may want to extend the callback API in the future, so should be careful to make it forwards-compatible. There are a few ways to do this; we can discuss if desired.
💭 We should consider the specific convenience selectors we want to make available, and their semantics. For instance, is a string as a shorthand clearly a shortcut for a title? At any point in the docs where we use a string selector, we should probably note at that point that it’s shorthand for {"title": "Firefox"}.
💭 The convenience selectors (other than native ID) might not be unique: there could be several Firefox windows open. In that event, we need to decide whether we raise an exception, use some sort of predefined tie-breaker (like first created or top in window stack), or what. The user can, of course, choose their own tie-breaker by using a callback function instead of a convenience selector.
Persistence
The target window is selected, according to the window selector, when the MSS object is created. After that time, the same window will continue to be used for future captures as long as it exists. For instance, if the user’s window selector specifies the window entitled “GitHub - Firefox”, then the actual window that the MSS object is targeting remains with that OS window, even if the title changes.
If the targeted window is destroyed, then when grab is next called, what should MSS do? I propose that it searches for a new window, based on the same selector as the user originally passed. This allows the program to continue following an application through common situations, such as switching between fullscreen and windowed modes, where the application may internally destroy and recreate its native window.
Exceptions
If the callback function used as a window specifier raises an exception, then that is propagated upwards.
If this happens on a retargeting grab (one after the initial MSS construction), then the MSS object remains in a valid and usable state. This allows a user to do something like this:
class WindowNotFound(Exception):
pass
def window_selector(windows):
for window in windows:
if window.title == "Cyberpunk 2077 (C) 2020 by CD Projekt RED":
return window
raise WindowNotFound()
wait_for_new_window_count = 0
with mss.MSS(window=window_selector) as sct:
while True:
try:
img = sct.grab()
except WindowNotFound:
# Poll for up to to one second, to wait for CP2077 to create
# its new window when switching between full-screen and
# windowed mode.
wait_for_new_window_count += 1
if wait_for_new_window_count > 60:
# The game has probably exited.
break
time.sleep(1/60)
continue
wait_for_new_window_count = 0 # Reset the poll counter
process_screenshot(img)
💭 Note that this code snippet assumes that the initial call to mss.MSS will successfully find a window. It’s possible to provide ways for the selector to request a refresh of the window list, which could be used both in the initial call, and in updates. I’m not sure if this is worthwhile.
Alternatives (persistence)
We could simply specify that attempting to grab a window that’s been destroyed will raise a ScreenShotError, and the user will need to recreate the MSS object. This seems like some significant extra burden on users, especially those wanting to use a pattern like the CP2077 example above. It would also mean creating and destroying XCB connections in the delay loop. It seems that the persistence and exception features described above aren’t difficult to implement, and allow for the best reuse of resources.
We could also specify ways to retarget an existing MSS object to a new window after the grab fails, rather than having MSS automatically find the new target window. This isn’t a bad feature to provide, but I suspect it requires most of the same internal machinery anyway.
Window changes
I don’t recommend any explicit action from MSS if the targeted window size changes. The ScreenShot object already provides its size, and the user can take appropriate actions on change if needed. Different use cases have different needs; a user who is scaling their screenshots to a particular size (such as for streaming or neural net inputs) won’t care, while a user who is capturing to a video file might.
💭 I think that if a window is minimized (iconified) or unmapped, it should probably be treated the same as if it was destroyed.
Implementation note
The different convenience window selectors can be implemented as simple functions, reducing the bulk of the internal window selection code to just the callback API.
These convenience window selectors can raise a ScreenShotError (I recommend a new dedicated subclass) if they don’t match any windows. As specified above, the normal path will simply propagate this upwards.
Alternatives (how to specify the window)
A couple of alternatives seem obvious, but have some subtle disadvantages. Whether these are worthwhile is a judgment call.
- Have the
MSSobject provide a method that returns a list of windows. However, this requires the MSS object to be constructed first. This means that a constructor usingbackend="default"would still need to be told if it will be used to target a single window or a full screen. - Make an
MSSclass (rather than instance) method that returns a list of windows. The user is expected to choose their desired window and provide its native ID to the MSS constructor. Under Linux/X11, this would require making a separate XCB connection whenever the list of windows is requested. This also means that the user would need to recreate the MSS object each time the window is destroyed and recreated, such as when switching to fullscreen. Doing so may be quite annoying in the typical ‘with/while‘ pattern.
I like the ease-of-use of allowing the user to specify, in a simple way, the window they want to capture. The alternatives seem more cumbersome to use for simple use cases, and provide little additional clarity for advanced use cases.
The only use case that I see that is benefited by providing grab a window selector, rather than the MSS constructor, is when the desired target window is changing frequently. I don’t think this is likely to be a significant use case.
There’s no problem adding a method to the MSS objects that provides a list of windows. It might be useful for some users, such as when populating a window selection UI. But I don’t think it should be the basis of the window selection API.
Capabilities
This isn’t yet relevant, but I’ll mention it here.
If a particular combination of options is requested when the MSS constructor is invoked, and it’s not possible to fulfill these, I suggest that we simply raise an exception. For example, if a user requests single-window capture to the GPU on Windows 8, then MSS should raise an exception.
💭 We might consider an API that can be used to query the different option combinations available on the current platform.
I suggest that we do not try to track windows ourselves and crop a full-screen capture, if single-window capture is requested but not available. We simply raise an exception.
That is because full-screen capture is always the composited image, including overlapping windows. This risks inadvertent information exposure if, for instance, a user is streaming to Twitch and a popup with private information temporarily appears on their screen. In this example, the original developer of the app may not be aware of the risk; they may have tested on a different version of Windows that does support WGC.
Open questions
@halldorfannar pointed out two considerations.
- 💭 Should single-window capture grab the entire window, including borders, or just the client area? The OS API defaults vary. I suggest we add this as another option to the MSS constructor, but for the initial implementation, make the behavior explicitly platform-specific. We should add this option in a future update.
- 💭 Should we allow the user to specify crop offsets from the outside, instead of having to give an explicit width and height with the crop rectangle (which would require already knowing the window size)? In the conversation context, this was about allowing the user to crop out system borders. Note, however, that using
GetDCExinstead ofGetWindowDCwould provide a cleaner route, if the option described in the previous question is adopted. That said, there may be other reasons a user would want to crop out other borders, such as parts of the application’s UI.
I like simple user-facing things.
All points you listed in the "How to specify the window" section are good for me. It enables both simple usage, and more complex ones.
Indeed, if window is a string, I would think it is about the window's title, and it could be a good shortcut than expecting users to specifiy a dictionary.
The callback idea is clean, and already used for screenshot file names, I think people will easily use it when needed. For future-proof implementation/changes, simply passing a Window object as only argument could be enough, right? On our end, we would have space for changes on the Window object directly, without touching the callback signature. But this is
I like the polling idea in the CP2077 example, and it also resonates with a request I had myself: launch MSS before the expected window is available/existing. It would allow capturing from the second 1, instead of launching the window (game, browser, or whatever), then MSS. Such a scenario could be as simple as recording a meeting: yes, I could launch MSS right after the beginning, but it would be more practical to run MSS and forget it. This is a bad example haha, but recoridng the screen for game automation, where the game starts right after the window creation, that could be a use case I guess: learning from frame 1 and not from frame START+N.
About opened questions, both a valid points, and I can't decide. Lets image 2 use cases:
- Getting a one-time screenshot of the window XXX.
- Recording the window YYY to analyze its content.
Case 1: I would like to have borders by default, it seems the most logical option. Case 2: only keeping the content would be interesting, it is less data to handle, and borders are completely obsolete in most of the cases.
So, having an option to exclude borders is interesting (meaning they would be included by default since it is the case from the start of the project, and changing that would be a breaking change).
Note: points with the 💭 icon I did not responsed are ones I fully agree with you.
Finally, it will fix #194 (at last!).
I like that we are trying to get this in with minimal disruption. I am looking at the current declaration of the grab function:
def grab(self, monitor: Monitor, /) -> bytearray | tuple[bytearray, Size]:
"""Retrieve all pixels from a monitor. Pixels have to be RGB.
If the monitor size is not in pixel units, include a Size in
pixels (see issue #23).
"""
and feeling that if we require users to specify the window at MSS construction time, why wouldn't we similarly require the monitor at construction time? That would be consistent and allow us to improve the buffer pre-allocation system that is getting merged soon. BUT, there is a wrinkle. The monitors have not been enumerated! That leads me to think that perhaps we should be thinking about a two-phase initialization system (there is a hint towards that in the original proposal, where the option of stating just window vs fullscreen during MSS creation is proposed). In the two phase initialization I'm proposing here, a user creates MSS (which enumerates monitors). And then second phase the user initializes grab configuration (which monitor(s) to grab or window). I'm just putting this forward as an idea. It has good internal consistency, but it does introduce a new API.
I agree that the choice of the "best default" backend is going to be affected by what kind of grab the user intends to perform. We should have that information before we initialize the backend. Putting on my software architect hat and ignoring all the history of MSS (I know, this gives me a lot of freedom) I would have proposed an MSS MonitorSurface class that has a grab method and an MSS WindowSurface class that has a grab method. This would align well with OOP and prevent us from having to speculate about resources/initialization that might be needed. The class names are just what came to mind. The idea is that they are created by the user and can track associated resources. This approach would be backwards compatible in the sense that if people wanted to capture a window (which is not possible today) they would need create an instance of the new WindowSurface class (or whatever we want to call this thingy).
Maybe this is a bad idea and you have a better one! Or the original proposal is better. I just want us to have an open dialog about this.
@BoboTiG , do you have any thoughts on Halldor's idea?
I'm not sure to follow the idea of the 2-stages initialization. @halldorfannar do you have an example to illustrate maybe? Would this be a breaking change on how users will use MSS?
I talked with @halldorfannar about this.
I don't want to put words into his mouth, but I'll give you my interpretation, with the caveat that I probably am wrong about much of this.
He's concerned that, as we add features, we may end up with an API that ends up putting a lot of options into places that they're overnumerous, or of limited relevance for some situations: such as having grab() provide flags about whether you want window borders or not, while the user is (in their application) grabbing a full screen.
Now that we're talking about adding new dimensions to what users might want to do - like capturing a single window or capturing to GPU memory - all the options that we want to provide, well, they have to go somewhere. And today, we pretty much have two places they could go: the MSS constructor, or the grab() method.
This is something that happens in a lot of libraries when they try to allow too many use cases, conceptually, with too few entry points. You end up with an overwhelming number of flags in just a few places, even though they only apply in conceptually different uses. Often, it would be much cleaner if you separate these uses into separate methods, or separate classes. For instance, a WindowSurface and a MonitorSurface would have different flags to their grab methods: it wouldn't make sense, for instance, to put an "include_borders" flag on the MonitorSurface.grab method.
This makes it much easier for the users to understand what they need to care about. They don't end up seeing a bunch of flags that are irrelevant for their use case. Instead, they're looking just at classes and methods that align with what they need.
As for backwards compatibility, that was a large part of our conversation. He's proposing an API that would be different than the current one, and while it can - and should - preserve compatibility, it's tricky to do so efficiently. We're still thinking about that.
We also talked a lot about wanting to keep the API simple, especially for simple use cases. One of the great things about MSS is that it's easy for new programmers to use, and that's important to preserve.
So over the next little while, we'll be coming up with some short code samples that we might expect users to write, illustrating APIs that use this concept.
Importantly, these are meant to be examples to be discussed: we expect our ideas to have flaws as well as strengths, some ideas to be terrible, and to need improvements. I certainly expect to put some half-baked ideas out there that aren't complete solutions, like that they break compatibility, with the hope that we can talk about ways to turn them into fully-formed plans. We hope that, by discussing some of these ideas, that we can find ways to combine their strengths.
You're definitely a part of this, so it would be good to hear your thoughts as we propose ideas!
And you remind me that we can break things in that cycle, I completely missed that 😅
I understand the root cause and the need, and it makes sense to do something about it right now. Can't wait to read your ideas :)
Thanks for the write-up @jholveck. I will now attempt to formalize my concerns with where we are currently heading. Please understand that once we have evaluated and discussed all other options, our current course may still be the best (i.e. the least bad option, in a list of bad options). But we cannot know this unless we explore the other options. So here goes.
During MSS construction we now have backend selection as an option. By default it is set to "default" where the idea is that the implementation chooses the best option, based on what is available. But this can be overridden by the user by specifying an implemented backend for the current platform. On Windows we currently only have gdi backend but dxgi is being designed. The issue with both of these backend is that they do not provide proper single window capture, for that we will need to implement a wgc backend (Windows Graphics Capture). If we just follow the current course we are on, I would envision this usage:
# To capture a monitor we preferably want to use DXGI as the backend, since that is best.
# The software does not know that we are about to capture a full frame so we must know
# about this and make the educated decision for MSS:
with mss.MSS(backend="dxgi") as sct:
img = sct.grab(sct.monitors[1])
# To capture a window we must use WGC as the backend. Again, this selection is made
# during MSS construction so we push this onto the user:
with mss.MSS(backend="wgc") as sct:
img = sct.grab_window(hwnd)
# Note: I have assumed that we will create a new function `grab_window` since there will
# be very little overlap between the two in this design.
This isn't great. I don't mind giving users advanced controls - like backend selection. But I prefer to make those choices safe (i.e. any choice you make will still result in a correct, albeit potentially less efficient outcome). I also worry that we aren't as "user friendly" as before. We would have to publish capability matrices, like this one, in our docs:
If we were to build a new API, not shackled by what we've done so far, I would find something like this to be user friendly:
from mss import list_monitors, MonitorCapture, WindowCapture
monitors = list_monitors() # explicit discovery
# Note that the above is more expensive on X11 so we shouldn't hide it in a constructor.
# Secondly, this makes the action clearly tied to a call-site so we don't have to deal with monitors
# being unplugged (other than fail gracefully when users pass invalid data to us). If a user wants
# to handle this case, the user will have to call `list_monitors` again. Currently in our docs we warn
# users that our monitor list is cached, so we are not changing behavior with this - just making it
# more explicit and reusable. On Linux/X11 we would tell users to not call this function repeatedly
# unless they want to refresh the list.
mon = monitors.primary
with MonitorCapture(mon) as cap:
img = cap.grab()
with WindowCapture(hwnd, region="client") as cap:
img = cap.grab()
The above would make the two paths more harmonious. But we could also put options that are cheap, like region, inside the corresponding grab functions instead of during Capture object construction. This would give more flexibility to the user, which is good. For MonitorCapture we could have region as we have today to specify a region of the monitor while for WindowCapture the grab method would have a more capable region option that can take a string ("client"), a None (capture entire Window) or 4-tuple of ints to define a region of the window. Casting this into code:
WindowCapture(hwnd, cursor=False, backend="auto")
WindowCapture.grab(region=None)
MonitorCapture(monitor, cursor=False, backend="auto)
MonitorCapture.grab(region=None)
NOTE We eventually have to plan for GPU/Cuda vs CPU as in where the image returned by grab should reside. So we should probably add that option to these constructors.
Backwards Compatibility
For the existing path with MSS.grab we could simply construct a MonitorCapture object, but we unfortunately cannot do that until we know what monitor is being captured. This would lead to a potential hitch for the first frame being captured, but after that we could use the cached MonitorCapture object.
Those are my rough ideas. Please shoot holes. Nothing is holy. I just wanted to propose an alternative to our current course, so we had something else we could consider and hopefully improve to a state where we feel good about it. But if we can't - we at least tried! 😅
This isn't great. I don't mind giving users advanced controls - like backend selection. But I prefer to make those choices safe (i.e. any choice you make will still result in a correct, albeit potentially less efficient outcome).
I disagree here, if I understand you correctly. I think that trying to provide, for instance, single-window grab with the DXGI backend is not a good path. It becomes a leaky abstraction: questions like overlapping windows, or tracking window motion, or other similar issues, just can't be handled "correctly".
On Windows we currently only have
gdibackend butdxgiis being designed. The issue with both of these backend is that they do not provide proper single window capture, for that we will need to implement awgcbackend (Windows Graphics Capture).
Quick nit: doesn't GDI support single-window capture? I mean, we are using GetWindowDC to specify the source. Don't think you'll be off the hook for implementing single-window capture just because the wgc backend is a ways off! 😄
This isn't great. I don't mind giving users advanced controls - like backend selection. But I prefer to make those choices safe (i.e. any choice you make will still result in a correct, albeit potentially less efficient outcome).
I disagree here, if I understand you correctly. I think that trying to provide, for instance, single-window grab with the DXGI backend is not a good path. It becomes a leaky abstraction: questions like overlapping windows, or tracking window motion, or other similar issues, just can't be handled "correctly".
Yes, I should have been more clear in what I wrote. I agree that with the top level backend selection we give users a footgun. My second point that I was trying to make was that it also gave them a way to select something that wasn't ideal - but could be made to work. So I think we are aligned.
As for GDI - it only "kinda" support single window capture. GDI does have HWND-oriented options as you point out, but I would treat them carefully. GetWindowDC(hwnd) retrieves a DC for the entire window, including title bar, menus, and scroll bars; GetDC(hwnd) retrieves a DC for the client area. We could then do a BitBlt on that BUT:
- not reliable for every modern app
- may fail or return incomplete/black content for GPU/DirectX/composited surfaces
- may behave badly for minimized or hidden windows
- may not match WGC’s compositor-level window item semantics
- depends on how the target window/app participates in GDI painting
As I think about this some more, we can certainly add it and test it out. But it will have some ... limitations. But in the API I proposed, if we can get it to work decently then it would be valid choice when creating the WindowCapture object.
You might consider trying some of the different capture options in OBS Studio and see how they behave. For instance, in https://obsproject.com/kb/window-capture-sources , they say that BitBlt "is less efficient but may help with certain programs."
You might consider trying some of the different capture options in OBS Studio and see how they behave. For instance, in https://obsproject.com/kb/window-capture-sources , they say that BitBlt "is less efficient but may help with certain programs."
Cool, I will check that out. Any thoughts on the overall design?
Well, the design you laid out in this comment has the issue you already anticipated: that we can't provide the monitor list until the X connection has been established. I was waiting before commenting to see if I could come up with a more constructive response.
For the monitor list, you could talk about making a temporary connection or something. This would also mean that there might be issues if we wanted to give the user a way to know when the monitor list has changed (I can see a few reasonable APIs for this, such as callbacks, generators, or self-updating sequences). On X11, at least, an X client can get notifications when that happens (via XRRScreenChangeNotify). But we'd need an open X connection.
As for passing the hwnd, would we want to give the users a window list through a mechanism similar to monitors, or let them pass shortcuts like in my original proposal? If the former, then there are similar objections. If the latter, then the asymmetry between the window selection and monitor selection seems odd (but with an obvious solution: put monitor selection into a more forward-facing role).
I guess that does suggest a new possible idea.
Suppose have a WindowSurface and MonitorSurface, like you propose, and both of these take selectors: callbacks, indices, title / "primary", etc. We also have an mss.MSS that presents the whole virtual virtual framebuffer as a single surface, like what we have today. That would probably be a special case of MonitorSurface.
I think that works ok on first glance.
Yes, I see two possible paths to take. We are both looking at them, but perhaps seeing them a bit differently. I'm wondering if we can get away with a simple API, where we do indeed enumerate monitors and windows explicitly - before any capture is attempted - and the user triggers those operations, choosing what they need and not paying for the things they don't need.
In this API, we are not offering callbacks or events, because I feel that is scaffolding that the minority will need and they can easily have their AI coding assistants build that on top of the simple API. Maybe I should have mentioned that I'm also thinking about this as an opportunity to build a robust simpler core system with a simpler API, because I'm seeing that as the next evolutionary step for libraries. There isn't a need anymore to anticipate all possible use cases. As long as the core system can still be used, those rare cases can be handled with some extra code on top.
Now, we do need to play out the corner cases - to make sure there is a reasonable path to handle them with the simpler API. Here is an example:
- User enumerates monitors calling list_monitors. Then selects which monitor to use.
- User starts grabbing from said monitor but after a while the monitor loses connection or the desktop gets reconfigured so the call becomes invalid
I would say we raise an exception at this point. If the user wants their system to be robust, they can call list_monitor again and decide what to do. I feel it is a slippery slope for us to try to guess for them what should happen. Because, and I'm familiar with this in Windows, the two monitors might have switched roles (primary became secondary and vice versa). I think we should not choose to track the physical monitor that was originally used because that may NOT be what the user wants. This is why I want to make things simpler. Just raise an exception and make sure we have the APIs so the user can decide what to do at that point.
Here is another thought experiment:
- User enumerates the windows using our list_windows API and chooses which window to use (if the user is waiting for a particular window to spawn, they can just do this in a loop)
- They start grabbing from the window chosen, but after a while the window is closed.
We need to decide what to do at this point. Should we return the last image grabbed? Or should we raise an exception? It is probably most appropriate to raise an exception so the user can decide what to do at this point. They can go back to their original loop, waiting for a suitable window to resurface - or they could decide to end the capture.
I hope this gives some insight into what I'm thinking. Please point out where my ideas are bad or will not work! Good ideas are resistant to criticism, bad ideas are not. We only find out by being critical.
I will admit that the callback-based system is cumbersome. The whole reason I proposed it is so that the user can do arbitrary logic with the window list. The reason that would be in a callback, in my original proposal, is so that we have a chance to build the X connection.
I wouldn't mind having a separate connection object, that you can call list_whatever on, and then create WindowSurface or MonitorSurfaces from.
I'm not thrilled about having to set up a separate X connection just to call list_windows.
Another thing I'm not thrilled about is the idea of calling list_windows in a loop, even if that is on a persistent connection. Maybe it's just from my SRE work, but I've come to distrust polling, when an event-based mechanism is available. (In X, you can subscribe to changes to the window list, and I assume the same is true in the other platforms too.) Admittedly, that distrust is partly because polling loops in asynchronous systems tend to miss events, which isn't relevant here: the user's logic is almost certainly level-triggered, not edge-triggered, and they'll still eventually get a coherent window list. But it still doesn't sit well with me.
If I were doing this for myself, and didn't have to worry too much about ease of use, I'd make a generator method. This would produce a list of windows each iter call. Alternatively, it could yield a window each iter call, starting with the existing windows and then yielding windows as they're created or change properties. Either way, it would block as needed waiting for new window change events. But that's not terribly user-friendly.
Source-bound capture API
Status: design proposal for this issue and #470.
Current API
MSS currently creates one MSSImplementation in its constructor. The implementation provides monitors(),
grab(), cursor(), and close() (src/mss/base.py). Platform dispatchers select implementations from a string
backend, whose current automatic value is "default".
with MSS(backend="default") as sct:
image = sct.grab(sct.monitors[0])
image = sct.grab(sct.monitors[1])
image = sct.grab({"left": 10, "top": 20, "width": 640, "height": 480})
image = sct.grab((10, 20, 650, 500))
This API can also capture a rectangle from the desktop (combining all monitors). It remains available temporarily as a deprecated compatibility API.
New API
MSS becomes a platform session. It owns shared platform state, enumerates sources, and creates source-bound
Capture objects.
with MSS() as session:
desktop = session.desktop
monitors = session.list_monitors() # Actual monitors; no desktop entry.
windows = session.list_windows()
capture = session.create_capture(monitors[0])
image = capture.grab()
Window selection can reuse the same initialized session:
with MSS() as session:
window = session.find_window(title="Game")
if window is None:
window = session.find_window(title="Launcher")
if window is None:
raise RuntimeError("No matching window")
capture = session.create_capture(window)
The source types are explicit:
CaptureSource = Desktop | Monitor | Window
Region is not a source. It restricts a source:
capture = session.create_capture(
session.desktop,
region=Region(left=10, top=20, width=640, height=480),
)
Monitor becomes a read-only class as planned in #470. It may retain string-key lookup for migration, but new code
uses attributes:
monitor.width
monitor["width"] # Compatibility access.
Repeated capture and frame timing
A Capture can return one frame or an iterator of frames:
frame = capture.grab()
for frame in capture:
process(frame.image, frame.timing)
When frame notifications are required, iteration blocks until the backend reports another frame. It does not retarget a lost source. Frames may be coalesced or dropped when the consumer is slow.
The new API returns image data with timing metadata:
@dataclass(frozen=True, slots=True)
class FrameTiming:
presented_at_ns: int | None
acquired_at_ns: int
ready_at_ns: int
sequence: int
source_sequence: int | None
missed_frames: int | None
@dataclass(frozen=True, slots=True)
class Frame(Generic[ImageT]):
image: ImageT
timing: FrameTiming
Times use a documented monotonic nanosecond clock. presented_at_ns is set only when the backend supplies a reliable
presentation timestamp. Capture-call timing is not reported as presentation timing.
Capabilities and backend selection
Users can pass a capability mask when creating a capture:
class CaptureCapability(Flag):
NONE = 0
FRAME_NOTIFICATIONS = auto()
PRESENTATION_TIMESTAMPS = auto()
MISSED_FRAME_COUNT = auto()
GPU_MEMORY = auto()
DAMAGE_REGIONS = auto()
required = (
CaptureCapability.FRAME_NOTIFICATIONS
| CaptureCapability.PRESENTATION_TIMESTAMPS
)
capture = session.create_capture(
monitor,
backend="auto",
required_capabilities=required,
)
"auto" replaces "default" as the automatic selector in the new API. An explicit backend is still a string:
capture = session.create_capture(
monitor,
backend="dxgi",
required_capabilities=required,
)
Internally, the string resolves to a provider:
provider = backend_registry[backend_name]
support = provider.probe(session, source, configuration)
probe() reports source support, availability, and capabilities for the current system. Source support is not a
capability bit: a Window request already specifies the source type.
For backend="auto", MSS ranks providers that support the source and every required capability. It may try the next
eligible provider after an initialization failure. It never drops a required capability.
For an explicit backend, MSS does not fall back:
session.create_capture(
monitor,
backend="gdi",
required_capabilities=CaptureCapability.PRESENTATION_TIMESTAMPS,
)
# Raises UnsupportedCapabilitiesError if GDI cannot provide the timestamp.
The selected result is inspectable:
capture.backend # For example, "dxgi".
capture.capabilities # Capabilities guaranteed by this capture.
Temporary compatibility path
The old and new paths retain different semantics. MSS.grab(monitor) continues converting its input to an absolute
desktop rectangle. It does not call create_capture(monitor).
def grab(self, target: LegacyGrabTarget, /) -> ScreenShot:
if not self._legacy_grab_warned:
warnings.warn(
"MSS.grab() is deprecated; use MSS.create_capture() and "
"call grab() on the returned Capture",
DeprecationWarning,
stacklevel=2,
)
self._legacy_grab_warned = True
return self._grab_legacy(target)
_grab_legacy() accepts the current dictionaries, PIL-style tuples, monitor values, and the virtual-desktop entry at
MSS.monitors[0]. It reuses one desktop capture implementation rather than creating a Capture per frame.
MSS.monitors is also deprecated. Its replacement separates the desktop from real monitors:
session.desktop
session.list_monitors()
save() and shot() must call private compatibility helpers. They should not call the deprecated public grab() or
monitors property, which would produce warnings with incorrect call sites.
The existing constructor-level backend= remains for the compatibility path. "default" remains an accepted,
deprecated alias for "auto". Backend selection for new code belongs to create_capture(), where the source and
required capabilities are known.
The compatibility path can be removed in a later major release.
Internal split
MSS
├── PlatformSessionImplementation
│ ├── list_monitors()
│ ├── list_windows()
│ ├── probe_backends()
│ └── close()
├── legacy desktop capture
└── Capture
├── CaptureImplementation
├── grab()
├── frames()/__iter__()
└── close()
The session owns shared resources such as an X connection. A capture owns source-specific resources such as the X11
drawable state, Windows capture session, and reusable image buffers. Closing MSS closes its captures before closing
the shared session.
Regarding Capture resource lifetime:
The session owns shared resources such as an X connection. A capture owns source-specific resources such as the X11 drawable state, Windows capture session, and reusable image buffers. Closing MSS closes its captures before closing the shared session.
What happens when a user creates multiple Capture objects over time, just using the last one and ignoring others? This is realistic if the user is tracking the same application for a long time, across multiple mode changes (again, a game switching between full-screen and borderless/bordered mode).
It seems that their resources would be leaked until the session closes, unless the Capture objects are either explicitly closed by the user, or handled in Capture.__del__. The former is an easy place to make mistakes. The latter is going against the common admonitions against using __del__ for cleanups. It introduces a lot of concerns regarding threads, locking, calling during interpreter shutdown (although the last is not a problem in your current design), etc. These were some of the biggest problems I had to deal with when writing the XShmGetImage buffer management code; I redesigned that multiple times to make sure it was safe. These weren't just hypothetical concerns; the demos I'd written would easily have triggered them.
For that reason, I'd mostly been assuming that in a two-phase initialization system like this, we'd probably end up recommending a pair of nested with blocks. But not only is that aesthetically uncomfortable to my eye, but also the logic becomes annoying if you're wanting to track a window that's changing. (This is one of the main user stories I was considering.)
Edit: It does help with the aesthetics that you can do with mss.MSS() as session, session.create_capture(session.find_window("Portal")) as cap: on one line. Indeed, if we collapse that into a single utility function (so with mss.capture_window("Portal") as cap:), then my aesthetic concerns - which are partly about deeply nested blocks - nearly evaporate. The tangled logic still is a thing.
I do, however, particularly like that this allows some resources, like the XCB connection, to be shared between multiple surfaces.
Random extra wrenches to throw into our gears:
While we're talking about planning the API, we should also consider some other planned features and needs. I'm not saying that any of these are necessarily relevant, but they're some of the things I've been trying to keep in mind while thinking about these APIs.
- Desktop Duplication only allows you to capture one output (monitor) at a time. I mean, you can capture many of them and composite them yourself, but I don’t particularly see that as being MSS’s job. So we should make sure we never assume that all backends can return the full virtual space.
- Wayland will prompt the user, asking if the program is allowed to capture the screen. If you don’t want that prompt every time you run the program, then you can ask for persistent permissions. In that case, the program gets a token proving that the user approved the request. It needs to store that token (securely) and send it back to the system the next time you run the program. This storage should belong to the app, not MSS.
- It makes sense (I can elaborate on this) to be able to return a GPU-resident screenshot as a texture, such as an EGLImage for X11 + XComposite, or an ID3D11Texture2D with Windows + Desktop Duplication. But this may need the user to provide some extra context, such as the IDXGIDevice that they want the texture to be created within.
- Note that the above two fall into the general question of backend-specific functionality that we may want to expose.
- On macOS, the Touch Bar is also a monitor. There's a particular flag or something in the ScreenCaptureKit that makes it show up as "maybe not what you mean as a monitor".
- Streaming (alluded to in @halldorfannar 's most recent proposal).
- Many newer APIs — including Wayland’s API, Windows DXGI Desktop Duplication, and I think WGC, and macOS’s ScreenCaptureKit — are designed around streaming, rather than on-demand frames.
- As we improve performance, we need to think about the fact that the user can, even today, call
grab()faster than the system is producing frames. Letting the user sync their rate of frame consumption with the system’s rate of frame production would be a good idea. - The user may want to specify whether stale frames are still returned to the app (useful for video capture), or dropped (useful for web conferencing). This also includes letting the user specify how many buffers to pre-allocate (as @halldorfannar suggested in https://github.com/BoboTiG/python-mss/pull/539#issuecomment-4781222155) (which becomes much more important in Wayland, I think).
- Pixel formats. Our current BGRA 8-bit format doesn’t work for HDR sources: at best, it will downgrade it to SDR. Exporting a window showing a streaming video? It’s much more efficient, and has better fidelity, to capture it in something like NV12 (a common YUV 4:2:0 format) than BGRA, if the user can use that (such as if they’re saving it to a video file). In some APIs, you can request that the system convert automatically. But we may want to have something to let a user actually get an HDR or YUV image. (Note that YUV also requires multiple planes in all the common formats.)
- Color spaces. I’ve been thinking that we should specify the color format as attributes on the ScreenShot object (for motivation, see e.g. #207). But should we let the user request specific color spaces? As with pixel formats, some APIs (such as DXGI Desktop Duplication’s
IDXGIOutput5::DuplicateOutput1) let you request whether the system automatically does conversion to sRGB (at least, I think so, based on whether you specifyDXGI_FORMAT_R8G8B8A8_UNORMorDXGI_FORMAT_R8G8B8A8_UNORM_SRGB, although that’s in a weird place of specifying both color space and format, which graphics APIs are now moving away from).
I'm sure there's a lot of other future concerns I've run into that I forgot to list here. As I think of them, while you two sleep in Europe, I'll edit this comment until one of you :eyes: or otherwise reacts; after that, I'll just start a new comment if I think of more.
Regarding the temporary compatibility path:
So would the first call to _grab_legacy() (legacy path) now initialize a new backend instance? I've pushed back on having any deferred initialization, since I've dealt with problems in applications (I've discussed with you privately) with first-frame stutter. But I've run low on ideas that don't have that problem, and yet don't waste resources.
I've previously suggested writing user stories, and worked on that some today. But maybe it would be good to write proposed implementations for save and shot that use the new API, just to try it on for size.
Nit: I probably wouldn't explicitly put the "if we haven't warned yet" test in grab. The warnings.warn default settings already only issue each warning once per location. I think that it's fine to let the user adjust their warnings preferences if desired.
Regarding one of my key observations:
Platforms other than Linux (X11 or Wayland) probably could work great without a top-level MSS object. AFAIK, they don't have any shared resources of significance before the backend is chosen. But Linux needs a connection in order to list monitors and windows, etc.
I'm not too thrilled about the fact that Linux is imposing on us this extra layer of initialization. But c'est la vie.
I've been warming to @halldorfannar 's two-phase concept as probably the best we can do. I'm not saying that I'm happy with it. But I am slowly coming to think that it may be the best we can do, given the goals and architectural constraints.