Connecting a webcam

Many people have problems reading out a webcam on a RaspBerry Pi. I encountered it too. One of the first error messages logged is this:

libv4l2: error allocating conversion buffer

I traced the problem, by tracing the 'streamer' binary with strace. The problem is this line:

mmap2(NULL, 268435456, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = -1 ENOMEM (Cannot allocate memory)

Apparently, libv4l2 tries to allocate a conversion buffer length 268435456 bytes, or 256 MiB. Or, in the case of a first release RaspberryPi, all of it's memory, which obviously is never available. So this call will never succeed. On the other hand, it is hardly conceivable that libv4l2 will really need all that memory. Luckily, the kernel designers have a solution for problems caused by applications claiming too much memory. A solution is to add this line to /etc/sysctl.conf:

vm.overcommit_memory=1

Now all memory allocations succeed, no matter how little memory is present. Obviously, this has it's problems. E.g. if an application tries to find out how much memory there is, by allocating it, this fails. Also, it is now much easier for an application to crash the system. And, an application reserving memory, then assuming it can use it, can unexpectedly fail (and crash) later.

Another option is to temporarily use overcommit, e.g.:

sysctl vm.overcommit_memory=1
streamer -t 0:30 -o video.avi
systctl vm.overcommit_memory=0

The best way, of course, is to repair libv4l2..