title: Linux: Screen desktop video capture over network, and VNC framerate
body: <p>Sorry for the wall of text - TL;DR:</p>
  
  <ul>
  <li>What is the framerate of VNC connection (in frames/sec) - or rather, who determines it: client or server? </li>
  <li>Any other suggestions for desktop screen capture - but "correctly timecoded"/ with unjittered framerate (with a stable period); and with possibility to obtain it as uncompressed (or lossless) image sequence?</li>
  </ul>
  
  <p>Briefly - I have a typical problem that I am faced with: I sometimes develop hardware, and want to record a video that shows <em>both</em> commands entered on the PC ('desktop capture'), <em>and</em> responses of the hardware ('live video'). A chunk of an intro follows, before I get to the specific detail(s). 
  &nbsp;<br>
  &nbsp;  </p>
  
  <h1>Intro/Context</h1>
  
  <p>My strategy, for now, is to use a video camera to record the process of hardware testing (<em>as 'live' video</em>) - and do a desktop capture at the same time. The video camera produces a 29.97 (30) FPS MPEG-2 .AVI video; and I want to get the desktop capture as an image sequence of PNGs at the same frame rate as the video. The idea, then, would be: if the frame rate of the two videos is the same; then I could simply</p>
  
  <ul>
  <li>align the time of start of the desktop capture, with the matching point in the 'live' video</li>
  <li>Set up a <a href="http://en.wikipedia.org/wiki/Picture-in-picture" rel="noreferrer">picture-in-picture</a>, where a scaled down version of the desktop capture is put - as overlay - on top of the 'live' video 
  
  <ul>
  <li>(where a portion of the screen on the 'live' video, serves as a visual sync source with the 'desktop capture' overlay)</li>
  </ul></li>
  <li>Export a 'final' combined video, compressed appropriately for the Internet</li>
  </ul>
  
  <p>In principle, I guess one could use a command line tool like <code>ffmpeg</code> for this process; however I would prefer to use a GUI for finding the alignment start point for the two videos. </p>
  
  <p>Eventually, what I also want to achieve, is to preserve maximum quality when exporting the 'final' video: the 'live' video is already compressed when out of the camera, which means additional degradation when it passes through the Theora .ogv codec - which is why I'd like to keep the original videos, and use something like a command line to generate a 'final' video anew, if a different compression/resolution is required. This is also why I like to have the 'desktop capture' video as a PNG sequence (although I guess any uncompressed format would do): I take measures to 'adjust' the desktop, so there aren't many gradients, and lossless encoding (i.e. PNG) would be appropriate. 
  &nbsp;<br>
  &nbsp;  </p>
  
  <h1>Desktop capture options</h1>
  
  <p>Well, there are many troubles in this process under Ubuntu Lucid, which I currently use (<em>and you can read about some of my ordeals in <a href="http://ubuntuforums.org/showthread.php?t=1541822" rel="noreferrer">10.04: Video overlay/composite editing with Theora ogv - Ubuntu Forums</a></em>). However, one of the crucial problems is the assumption, that the frame rate of the two incoming videos is equal - in reality, usually the desktop capture is of a lower framerate; and even worse, very often frames are <em>out of sync</em>.</p>
  
  <p>This, then, requires the hassle of sitting in front of a video editor, and manually cutting and editing less-than-a-second clips on frame level - requiring <em>hours</em> of work for what will be in the end a 5 <em>minute</em> video. On the other hand, if the two videos ('live' and 'capture') <em>did</em> have the same framerate and sync: in principle, you wouldn't need more than a couple of minutes for finding the start sync point in a video editor - and the rest of the 'merged' video processing could be handled by a single command line. Which is why, in this post, I would like to focus on the <strong>desktop capture</strong> part.</p>
  
  <p>As far as I can see, there are only few <em>viable</em> (as opposed to <a href="http://www.linuxhaxor.net/?p=815" rel="noreferrer">5 Ways to Screencast Your Linux Desktop</a>) alternatives for desktop capture in Linux / Ubuntu (note, I typically use a laptop as target for desktop capturing):</p>
  
  <ol>
  <li>Have your target PC (laptop) clone the desktop on its VGA output; use a VGA-to-composite or VGA-to-S-video hardware to obtain a video signal from VGA; use video capture card on a different PC to grab video</li>
  <li>Use <a href="http://recordmydesktop.sourceforge.net/about.php" rel="noreferrer">recordMyDesktop</a> on the target PC</li>
  <li>Set up a <a href="http://bobpeers.com/linux/vnc" rel="noreferrer">VNC server</a> (<a href="https://help.ubuntu.com/community/VNC/Servers#vino" rel="noreferrer">vi</a><a href="http://www.debianadmin.com/remote-desktop-sharing-in-ubuntu.html" rel="noreferrer">no</a> on Ubuntu; or <a href="http://www.realvnc.com/products/free/4.1/man/vncserver.html" rel="noreferrer">vncserver</a>) on the target PC to be captured; use VNC capture software (such as <a href="https://wiki.ubuntu.com/ScreenCasts/VNCREC#twibright%20version" rel="noreferrer">vncrec</a>) on a different PC to grab/record the VNC stream (<em>which can, subsequently, be converted to video</em>). </li>
  <li>Use <code>ffmpeg</code> with <code>x11grab</code> option</li>
  <li>*(<em>use some tool on the target PC, that would do a <a href="http://en.wikipedia.org/wiki/Direct_memory_access" rel="noreferrer">DMA</a> transfer of a desktop image frame directly - from the graphics card frame buffer memory, to the network adapter memory</em>)</li>
  </ol>
  
  <p>Please note that the usefulness of the above approaches are limited by my context of use: the target PC that I want to capture, typically runs software (utilizing the tested hardware) that moves around massive ammounts of data; best you could say about describing such a system is "barely stable" :) I'd guess this is similar to problems gamers face, when wanting to obtain a video capture of a demanding game. And as soon as I start using something like <code>recordMyDesktop</code>, which also uses quite a bit of resources and wants to capture on the local hard disk - I immediately get severe kernel crashes (often with no vmcore generated).</p>
  
  <p>So, in my context, I typically do assume involvement of a <em>second</em> computer - to run the capture and recording of the 'target' PC desktop. Other than that,  the pros and cons I can see so far with the above options, are included below.</p>
  
  <h2>(Desktop preparation)</h2>
  
  <p>For all of the methods discussed below, I tend to "prepare" the desktop beforehand:</p>
  
  <ul>
  <li>Remove desktop backgrounds and icons</li>
  <li>Set the resolution down to 800x600 via System/Preferences/Monitors (<code>gnome-desktop-properties</code>)</li>
  <li><a href="http://ubuntuforums.org/showthread.php?t=1476572" rel="noreferrer">Change color depth</a> down to 16 bpp (using <code>xdpyinfo | grep "of root"</code> to check)</li>
  </ul>
  
  <p>... in order to minimize the load on desktop capture software. Note that changing color depth on Ubuntu requires changes to xorg.conf; however, "<a href="http://ubuntuforums.org/showthread.php?t=1437980&amp;p=9021250" rel="noreferrer">No xorg.conf (is) found in /etc/X11 (Ubuntu 10.04)</a>" - so you may need to run <code>sudo Xorg -configure</code> first.</p>
  
  <p>In order to keep graphics resource use low, also I usually had <code>compiz</code> disabled - or rather, I'd have 'System/Preferences/Appearance/Visual Effects' set to "None". However, after I tried enabling <code>compiz</code> by setting 'Visual Effects' to "Normal" (<em>which <a href="https://bugs.launchpad.net/ubuntu/+source/compiz/+bug/441993" rel="noreferrer">doesn't get saved</a></em>), I can notice windows on the LCD screen are redrawn much faster; so I keep it like this, also for desktop capture. I find this a bit strange: how could <em>more</em> effects cause a <em>faster</em> screen refresh? It doesn't look like it's due to a proprietary driver (the card is "<em>Intel Corporation N10 Family Integrated Graphics Controller</em>", and no proprietary driver option is given by Ubuntu upon switch to <code>compiz</code>) - although, it could be that all the blurring and effects just cheat my eyes :) ).</p>
  
  <h2>Cloning VGA</h2>
  
  <p>Well, this is the most expencive option (as it requires additional purchase of not just one, but two pieces of hardware: VGA converter, and video capture card); and applicable mostly to laptops (which have both a screen + additional VGA output - for desktops one may also have to invest in an additional graphics card, or a VGA cloning hardware).</p>
  
  <p>However, it is also the only option that requires no additional software of the target PC whatsoever (and thus uses 0% processing power of the target CPU) - AND also the only one that will give a video with a <em>true</em>, unjittered framerate of 30 fps (as it is performed by separate hardware - although, with the assumption that clock domains misalignment, present between individual hardware pieces, is negligible). </p>
  
  <p>Actually, as I already own something like a capture card, I have already invested in a VGA converter - in expectation that it will eventually allow me to produce final "merged" videos with only 5 mins of looking for alignment point, and a single command line; but I am yet to see whether this process will work as intended. I'm also wandering how possible it will be to capture desktop as  uncompressed video @ 800x600, 30 fps. </p>
  
  <h2>recordMyDesktop</h2>
  
  <p>Well, if you run <code>recordMyDesktop</code> without any arguments - it starts first with capturing (what looks like) raw image data, in a folder like <code>/tmp/rMD-session-7247</code>; and after you press Ctrl-C to interrupt it, it will encode this raw image data into an .ogv. Obviously, grabbing large image data on the same hard disk as my test software (which also moves large ammounts of data), is usually a cause for an instacrash :)</p>
  
  <p>Hence, what I tried doing is to <a href="http://www.jonathanmoeller.com/screed/?p=1590" rel="noreferrer">setup Samba</a> to share a drive on the network; then on the target PC, I'd connect to this drive - and instruct <code>recordMyDesktop</code> to use this network drive (via <a href="http://www.g-loaded.eu/2008/12/08/access-gvfs-mounts-from-the-command-line/" rel="noreferrer">gvfs</a>) as its temporary files location:</p>
  
  <pre><code>recordmydesktop --workdir /home/user/.gvfs/test\ on\ 192.168.1.100/capture/ --no-sound --quick-subsampling --fps 30 --overwrite -o capture.ogv 
  </code></pre>
  
  <p>Note that, while this command will use the network location for temporary files (and thus makes it possible for <code>recordMyDesktop</code> to run in parallel with my software) - as soon as you hit Ctrl-C, it will start encoding and saving <code>capture.ogv</code> directly on the local hard drive of the target (though, at that point, I don't really care :) )</p>
  
  <p>First of my nags with <code>recordMyDesktop</code> is that you cannot instruct it to keep the temporary files, and avoid encoding them, on end: you can use Ctrl+Alt+p for pause - or you can hit Ctrl-C quickly after the first one, to cause it to crash; which will then leave the temporary files (<em>if you don't hit Ctrl-C quickly enough the second time, the program will "Cleanning up cache..."</em>). You can then run, say: </p>
  
  <pre><code>recordmydesktop --rescue /home/user/.gvfs/test\ on\ 192.168.1.100/capture/rMD-session-7247/
  </code></pre>
  
  <p>... in order to convert the raw temporary data. However, more often than not, <code>recordMyDesktop</code> will itself segfault in the midst of performing this "rescue". Although, the reason why I want to keep the temp files, is to have the uncompressed source for the picture-in-picture montage. Note that the "<code>--on-the-fly-encoding</code>" will avoid using temp files altogether - at the expence of using more CPU processing power (which, for me, again is cause for crashes.) </p>
  
  <p>Then, there is the framerate - obviously, you can set <em>requested</em> framerate using the '<code>--fps N</code>' option; however, that is no guarantee that you will actually obtain that framerate; for instance, I'd get: </p>
  
  <pre><code>recordmydesktop --fps 25
  ...
  Saved 2983 frames in a total of 6023 requests
  ...
  </code></pre>
  
  <p>... for a capture with my test software running; which means that the <em>actually achieved</em> rate is more like 25*2983/6032 = 12.3632 fps! </p>
  
  <p>Obviously, frames are dropped - and mostly that shows as <a href="http://ubuntuforums.org/showthread.php?t=1469103" rel="noreferrer">video playback is too fast</a>. However, if I lower the requested fps to 12 - then according to saved/total reports, I achieve something like 11 fps; and in this case, video playback doesn't look 'sped up'.  And I still haven't tried aligning such a capture with a live video - so I have no idea if those frames that actually have been saved, also have an accurate timestamp.</p>
  
  <h2>VNC capture</h2>
  
  <p>The VNC capture, for me, consists of running a VNC server on the 'target' PC, and running <code>vncrec</code> (twibright edition) on the 'recorder' PC. As VNC server, I use <code>vino</code>, which is "System/Preferences/Remote Desktop (Preferences)". And apparently, even if <a href="http://ubuntuforums.org/showthread.php?t=8742" rel="noreferrer">vino configuration</a> may not be the easiest thing to manage, <code>vino</code> as a server seems not too taxing to the 'target' PC; as I haven't experienced crashes when it runs in parallel with my test software. </p>
  
  <p>On the other hand, when <code>vncrec</code> is capturing on the 'recorder' PC, it also raises a window showing you the 'target' desktop as it is seen in 'realtime'; when there are large updates (i.e. whole windows moving) on the 'target' - one can, quite visibly, see problems with the update/refresh rate on the 'recorder'. But, for only small updates (i.e. just a cursor moving on a static background), things seem OK. </p>
  
  <p>This makes me wonder about one of my primary questions with this post - what is it, that sets the framerate in a VNC connection? </p>
  
  <p>I haven't found a clear answer to this, but from bits and pieces of info (<em>see refs below</em>), I gather that:</p>
  
  <ul>
  <li>The VNC server simply sends changes (screen changes + clicks etc) as fast as it can, when it receives them ; limited by the max network bandwidth that is available to the server</li>
  <li>The VNC client receives those change events delayed and jittered by the network connection, and attempts to reconstruct the desktop "video" stream, again as fast as it can </li>
  </ul>
  
  <p>... which means, one cannot state anything in terms of a stable, periodic frame rate (as in video). </p>
  
  <p>As far as <code>vncrec</code> as a client goes, the end videos I get usually are declared as 10 fps, although frames can be rather displaced/jittered (which then requires the cutting in video editors). Note that the <a href="http://ronja.twibright.com/utils/vncrec-twibright/README" rel="noreferrer">vncrec-twibright/README</a> states: "<em>The sample rate of the movie is 10 by default or overriden by VNCREC_MOVIE_FRAMERATE environment variable, or 10 if not specified.</em>"; however, the manpage also states "<em>VNCREC_MOVIE_FRAMERATE - Specifies frame rate of the output movie. Has an effect only in -movie mode. Defaults to 10. Try 24 when your transcoder vomits from 10.</em>". And if one looks into "<code>vncrec/sockets.c</code>" source, one can see: </p>
  
  <pre><code>void print_movie_frames_up_to_time(struct timeval tv)
  {
    static double framerate;
    ....
    memcpy(out, bufoutptr, buffered);
    if (appData.record)
      {
        writeLogHeader (); /* Writes the timestamp */
        fwrite (bufoutptr, 1, buffered, vncLog);
      }
  </code></pre>
  
  <p>... which shows that some timestamps are written - but whether those timestamps originate from the "original" 'target' PC, or the 'recorder' one, I cannot tell. 
  <strong>EDIT</strong>: thanks to the answer by @kanaka, I checked through <a href="http://ronja.twibright.com/utils/vncrec-twibright/vncrec/sockets.c" rel="noreferrer">vncrec/sockets.c</a> again, and can see that it is the <code>writeLogHeader</code> function itself calling <code>gettimeofday</code>; so the timestamps it writes are local - that is, they originate from the 'recorder' PC (<em>and hence, these timestamps do not accurately describe when the frames originated on the 'target' PC</em>).   </p>
  
  <p>In any case, it still seems to me, that the server sends - and <code>vncrec</code> as client receives - <em>whenever</em>; and it is only in the process of encoding a video file from the raw capture afterwards, that some form of a frame rate is set/interpolated. </p>
  
  <p>I'd also like to state that on my 'target' laptop, the <a href="http://ubuntuforums.org/showthread.php?t=1565114" rel="noreferrer">wired network connection is broken</a>; so the wireless is my only option to get access to the router and the local network - at far lower speed than the 100MB/s that the router could handle from wired connections. However, if the jitter in captured frames is caused by wrong timestamps due to load on the 'target' PC, I don't think good network bandwidth will help too much. </p>
  
  <p>Finally, as far as VNC goes, there could be other alternatives to try - such as <a href="http://www.vislab.usyd.edu.au/moinwiki/VNCast" rel="noreferrer">VNCast</a> server (<em>promising, but requires some time to build from source, and is in "early experimental version"</em>); or <a href="http://handhelds.freshmeat.net/projects/multivnc" rel="noreferrer">MultiVNC</a> (<em>although, it just seems like a client/viewer, without options for recording</em>). </p>
  
  <h2>ffmpeg with x11grab</h2>
  
  <p>Haven't played with this much, but, I've tried it in connection with <code>netcat</code>; this:</p>
  
  <pre><code># 'target'
  ffmpeg -f x11grab -b 8000k -r 30 -s 800x600 -i :0.0 -f rawvideo - | nc 192.168.1.100 5678
  # 'recorder'
  nc -l 0.0.0.0 5678 &gt; raw.video  #
  </code></pre>
  
  <p>... does capture a file, but <code>ffplay</code> cannot read the captured file properly; while:</p>
  
  <pre><code># 'target'
  ffmpeg -f x11grab -b 500k -r 30 -s 800x600 -i :0.0 -f yuv4mpegpipe -pix_fmt yuv444p - | nc 192.168.1.100 5678
  # 'recorder'
  nc -l 0.0.0.0 5678 | ffmpeg -i - /path/to/samplimg%03d.png
  </code></pre>
  
  <p>does produce .png images - but with compression artifacts (result of the compression involved with <code>yuv4mpegpipe</code>, I guess). </p>
  
  <p>Thus, I'm not liking <code>ffmpeg</code>+<code>x11grab</code> too much currently - but maybe I simply don't know how to set it up for my needs. </p>
  
  <h2>*( graphics card -> DMA -> network )</h2>
  
  <p>I am, admittedly, not sure something like this exists - in fact, I would wager it doesn't :) And I'm no expert here, but I speculate:</p>
  
  <p>if DMA memory transfer can be initiated from the graphics card (or its buffer that keeps the current desktop bitmap) as <em>source</em>, and the network adapter as <em>destination</em> - then in principle, it should be possible to obtain an uncompressed desktop capture with a correct (and decent) framerate. The point in using DMA transfer would be, of course, to relieve the processor from the task of copying the desktop image to the network interface (<em>and thus, reduce the influence the capturing software can have on the processes running on the 'target' PC - especially those dealing with RAM or hard-disk</em>). </p>
  
  <p>A suggestion like this, of course, assumes that: there are massive ammounts of network bandwidth (<em>for 800x600, 30 fps at least 800*600*3*30 = 43200000 bps = 42 MiB/s, which should be OK for local 100 MB/s networks</em>); plenty of hard disk on the other PC that does the 'recording' - and finally, software that can afterwards read that raw data, and generate image sequences or videos based on it :) </p>
  
  <p>The bandwidth and hard disk demands I could live with - as long as there is guarantee both for a stable framerate and uncompressed data; which is why I'd love to hear if something like this already exists. </p>
  
  <p>-- -- -- -- --&nbsp;</p>
  
  <p>Well, I guess that was it - as brief as I could put it :) Any suggestions for tools - or process(es), that can result with a desktop capture</p>
  
  <ul>
  <li>in uncompressed format (ultimately convertible to uncompressed/lossless PNG image sequence), and</li>
  <li>with a "correctly timecoded", stable framerate</li>
  </ul>
  
  <p>..., that will ultimately lend itself to 'easy', single command-line processing for generating 'picture-in-picture' overlay videos - will be greatly appreciated!</p>
  
  <p>Thanks in advance for any comments,<br>
  Cheers!  </p>
  
  <hr>
  
  <h2>References</h2>
  
  <ol>
  <li><a href="http://idlebox.net/2009/0817-Producing-Screencasts-on-Linux.blog" rel="noreferrer">Experiences Producing a Screencast on Linux for CryptoTE - idlebox.net</a></li>
  <li><a href="http://forum.videolan.org/viewtopic.php?f=7&amp;t=16311&amp;start=0" rel="noreferrer">The VideoLAN Forums • View topic - VNC Client input support (like screen://)</a></li>
  <li><a href="http://markmail.org/message/tv6aht3krqgjtb2b#page:1+mid:pr3vmdj5axhukx65" rel="noreferrer">VNCServer throttles user inpt for slow client - Kyprianou, Mark - com.realvnc.vnc-list - MarkMail</a></li>
  <li><a href="http://linux.about.com/od/linux101/l/blnewbie4_3_11.htm" rel="noreferrer">Linux FAQ - X Windows: How do I Display and Control a Remote Desktop using VNC</a></li>
  <li><a href="http://www.realvnc.com/support/faq.html#bandwidth" rel="noreferrer">How much bandwidth does VNC require? RealVNC - Frequently asked questions</a></li>
  <li><a href="http://www.karlrunge.com/x11vnc/faq.html" rel="noreferrer">x11vnc: a VNC server for real X displays</a></li>
  <li><a href="http://wiki.debian.org/HowtoRecordVNC" rel="noreferrer">HowtoRecordVNC (an X11 session) - Debian Wiki</a></li>
  <li><a href="http://www.bauer-power.net/2010/05/alternative-to-gtk-recordmydesktop-in.html" rel="noreferrer">Alternative To gtk-RecordMyDesktop in Ubuntu</a></li>
  <li><a href="http://lists.mplayerhq.hu/pipermail/ffmpeg-user/2007-February/006993.html" rel="noreferrer">(Ffmpeg-user) How do I use pipes in ffmpeg</a></li>
  <li><a href="http://comments.gmane.org/gmane.comp.video.ffmpeg.devel/111944" rel="noreferrer">(ffmpeg-devel) (PATCH) Fix segfault in x11grab when drawing Cursor on Xservers that don't support the XFixes extension</a></li>
  </ol>