Avoiding time_increment_bits problem when encoding bad header MPEG4 videos to Ogg Theora

There is some debate going on lately about the migration of YouTube to [[HTML5]], and whether they (i.e. YouTube’s owner, Google) should support [[H.264]] or [[Theora]] as standard codecs for the upcoming <video> tag. See, for example, how the FSF asks for support for Theora.

The thing is, I discovered [[x264]] not so long ago, and I thought it was a “free version” of H.264. I began using it to reencode the medium-to-low quality videos I keep (e.g., movies and series). The resulting quality/file size ratio stunned me. I could reencode most material downloaded from e.g. p2p sources to 2/3 of their size, keeping the copy indistinguishable from the original with the bare eye.

However, after realizing that x264 is just a free implementation of the proprietary H.264 codec, and in the wake of the H.264/Theora debate, I decided to give Ogg Theora a go. I expected a fair competitor to H.264, although still noticeably behind in quality/size ratio. And that I found. I for one do not care if I need a 10% larger file to attain the same quality, if it means using free formats, so I decided to adopt Theora for everyday reencoding.

After three paragraphs of introduction, let’s get to the point. Which is that reencoding some files with [[ffmpeg2theora]] I would get the following error:

% ffmpeg2theora -i example_video.avi -o output.ogg
[avi @ 0x22b7560]Something went wrong during header parsing, I will ignore it and try to continue anyway.
[NULL @ 0x22b87f0]hmm, seems the headers are not complete, trying to guess time_increment_bits
[NULL @ 0x22b87f0]my guess is 15 bits ;)
[NULL @ 0x22b87f0]looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag
Input #0, avi, from 'example_video.avi':
  Metadata:
    Title           : example_video.avi
  Duration: 00:44:46.18, start: 0.000000, bitrate: 1093 kb/s
    Stream #0.0: Video: mpeg4, yuv420p, 624x464, 23.98 tbr, 23.98 tbn, 23.98 tbc
    Stream #0.1: Audio: mp3, 48000 Hz, 2 channels, s16, 32 kb/s
  .

[mpeg4 @ 0x22b87f0]hmm, seems the headers are not complete, trying to guess time_increment_bits
[mpeg4 @ 0x22b87f0]my guess is 16 bits ;)
[mpeg4 @ 0x22b87f0]hmm, seems the headers are not complete, trying to guess time_increment_bits
[mpeg4 @ 0x22b87f0]my guess is 16 bits ;)
[mpeg4 @ 0x22b87f0]looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag
    Last message repeated 1 times
[mpeg4 @ 0x22b87f0]warning: first frame is no keyframe

I searched the web for solutions, but to no avail. Usually pasting literal errors in Google yields good results, but in this case I only found developer forums where this bug was discussed. What I haven’t found is simple instructions on how to avoid it in practice.

Well, here it goes my simple solution: pass it through [[MEncoder]] first. Where the following fails:

% ffmpeg2theora -i input.avi -o output.ogg

the following succeeds:

% mencoder input.avi -ovc copy -oac copy -o filtered.avi
% ffmpeg2theora -i filtered.avi -o output.ogg

I guess that what happens is basically that mencoder takes the “raw” video data in input.avi and makes a copy into filtered.avi (which ends up being exactly the same video), building sane headers in the process.

Comments (3)

El p2p no es robar, es compartir

Mucho se habla sobre la legitimidad de compartir material audiovisual en redes [[es:peer-to-peer|p2p]], sobre todo en el caso de materiales cubiertos por [[es:copyright|copyright]]. Las discusiones se centran principalmente en dos cuestiones: la legalidad de dicha práctica, y el efecto económico sobre un mercado (venta de copias físicas) que muchos vemos como obsoleto. Básicamente las preguntas son: ¿El Estado lo permite ahora y/o debe permitirlo en el futuro? y ¿Quién pierde y cuánto, quién gana, y cuanto?

Me gustaría añadir un ángulo diferente (aunque indudablemente tratado también por otros extensamente), y es la moralidad. Muchos pensarán que este debate está superado, porque aunque legalmente se permita el p2p, nadie en su sano juicio puede pensar que obtener algo “gratis total”, privando de ingresos al creador, es “moralmente bueno”. Nada más lejos de la realidad. Si releemos esa frase, y el párrafo anterior, vemos que ese juicio supuestamente moral está realmente basado en legalidad y/o economía, temas que deben tratarse separadamente, aunque todo esté más o menos unido. Yo me refiero a un análisis más ideológico.

Primero podríamos empezar por acotar qué es “robar”. Si nos preguntan qué es robar, la primera respuesta sería: quitar algo a alguien. Esta definición es muy buena, porque resume muy bien el problema. Quitar implica que se hace sin consentimiento, y, sobre todo, que el legítimo dueño lo pierde. Si alguien te quita una manzana, te quedas sin ella. Si alguien escucha tu idea y la aplica, no te quedas sin ella. Puede aplicarse el verbo “copiar”, pero nunca “robar”. La única manera de robar una idea es que te laven el cerebro para que dejes de tenerla, contra tu voluntad. De esto podría acusarse a emisoras de radio emitiendo machaconamente los últimos singles de ciertos cantantes, pero nunca a usuarios de p2p.

Entonces, si el usuario de p2p no tiene como objetivo robar (quitar) , ¿cuál es su objetivo? Dos cosas, de las cuales la primera es obvia: obtener. Pero la segunda es igualmente importante: compartir (dar). Las redes p2p no funcionarían si sus usuarios no dieran, además de recibir. Además, nadie roba, ya que por mucho que un usuario dé a los demás, no pierde nada de lo que ya tiene. Esto, que es un detalle técnico obvio, es de vital importancia moral. Compartir es algo que requiere cierto esfuerzo, por pequeño que sea. Aunque paguemos una conexión a Internet con el objetivo de obtener del p2p (no de dar), pagar la conexión no es el único coste. Mucha gente deja encendido el ordenador más tiempo del necesario para bajar (obtener) lo que desea, porque quieren subir (dar) a otros. Los ficheros, una vez bajados, ocupan espacio en el disco duro. Sería más cómodo borrarlos nada más bajarlos y verlos, pero mucha gente los sigue sirviendo (dando) aún cuando esto no les aporte beneficios directos. Otro ejemplo más: las conexiones a Internet (al menos en España) son muy asiméticas: permiten bajar información a nuestro ordenador muy rápidamente, pero subir información de nuestro ordenador a otros es comparativamente muy lento. Todos los usuarios de p2p que conozco lamentan este hecho, cuando si su objetivo es simplemente obtener (bajar) y no dar (subir), la asimetría debería serles indiferente. Es más, pensemos en la génesis de un archivo p2p. Un CD de Metallica que acabe en [[es:BitTorrent (protocolo)|BitTorrent]] no empieza su vida allí como un bien que la gente quiere bajar para ahorrarse el comprarlo. Como el lector encontrará obvio, el primer paso, que precede a lo anterior, es subir el CD por primera vez a la red p2p. Alguien compra su CD de Metallica en su tienda de siempre, y al llegar a casa decide compartirlo. Como tiene un bien que le ha producido beneficio (le gusta Metallica) a cambio de una contraprestación (dinero), y como ve que puede repartir ese beneficio a una comunidad amplia (usuarios de p2p) sin perder el bien original (copiar, no robar), se toma su tiempo para subirlo a la red y que todos puedan bajarlo sin pasar por el esfuerzo económico que él tuvo que pasar.

Claro, podría alguien decirme, dar a los demás no produce beneficios directos, pero eso no quiere decir que el usuario de p2p que sube contenidos lo haga desinteresadamente. En primer lugar, los usuarios que no suben nada tienden a recibir menos conexiones de otros usuarios (si yo tengo el capítulo 1 de una serie, y tú el 2, y tú no me das nada del que tienes, probablemente yo no te daré nada del que tengo. Esto lo controla el programa de p2p automáticamente). Además, globalmente es deseable que todo el mundo suba contenidos con fluidez, para que todo el mundo los baje con fluidez. O sea, ¡que no son Hermanitas de la Caridad! (Bueno, las Hermanitas de la Caridad son buenas porque creen en un dios que las condenará al Infierno por toda la eternidad si son malas, o al menos que las premiará más cuanto mejores sean, así que el desinterés es un concepto muy relativo). Precisamente aquí es donde entra la moralidad. El universo p2p es uno en el que el usuario aprende que compartir puede ser beneficioso para todos, el “win-win” que dicen los americanos. Aprende que si te has bajado algo de la comunidad (otras decenas de usuarios que tenían el fichero y lo compartieron contigo), es justo y deseable que tú hagas lo mismo con otros, porque probablemente otros también lo desean. Desde la experiencia personal digo que alguna vez me he bajado algo que he visto mejorable (por ejemplo los subtítulos estaban mal, los nombres de los ficheros estaban incompletos o alfabéticamente desordenados, una peli incluye anuncios…) y he dedicado un tiempo a corregirlo, no solo para mí (que si así fuera, probablemente no valdría la pena el esfuerzo), sino para luego subirlo de nuevo corregido, con la intención de que la gente se baje la versión “buena”. ¿Por qué? Pues porque me sabe mal que todo el mundo tenga que pasar por el mismo trabajo de arreglar el vídeo o lo que sea, si yo con un mínimo esfuerzo (a veces no tan mínimo) puedo solucionarlo para todos. Al fin y al cabo, me gustaría que los demás lo hicieran por mí.

Para mí, este aspecto de que “compartir es bueno”, es una baza moral enorme del p2p. Tras siglos de “tanto tienes, tanto vales”, de “gana dinero, sea como sea” y “si la gente desea lo que tienes, haz que paguen por ello”, y viendo a donde nos ha llevado moralmente, no puedo por menos que alegrarme de ver llegar una tecnología que permite una compartición desinteresada (o interesada porque si yo soy bueno, todo el mundo es bueno, y deseo eso) de bienes. El p2p es un soplo de aire fresco en el panorama de modelos de crear bienestar: gente que hace que otros obtengan bienestar dentro de un esquema en el que ellos también obtienen ese bienestar. Colaboración real, esto es lo que promueve el p2p. ¿No sería genial que esta ideología trascendiese a todos los ámbitos sociales? Y todo esto lo quieren eliminar, para seguir metiéndonos en la cabeza la idea de que si tienes algo que otros quieren, aunque no te cueste nada compartirlo, no debes hacerlo gratis. Que dar sin exigir es malo. En el ejemplo del CD de Metallica de dos párrafos más arriba, quieren convencer al usuario que se compró el CD y lo subió de que si él tuvo que pagar, que paguen todos. Que su generosidad al compartirlo es mala. ¡Que está robando! Y quieren envenenar así la moralidad colectiva de la ciudadanía con la triste excusa de ganar más dinero. No os dejéis convencer, por favor.

Comments (2)

Hardware compatibility is better with Windows… not

One of the (few, but legitimate) reasons given by some Windows users to not switch to Linux is that many pieces of hardware are not recognized by the latter. Sure enough, 99.9%, if not all, of the devices sold in shops are “Windows compatible”. The manufacturers of devices make damn sure their device, be it a pendrive or a printer, a computer screen or a keyboard, will work on any PC running Windows. They will even ship a CD with the drivers in the same package, so that installation of the device is as smooth as possible in Microsoft’s platform. Linux compatibility? Well, they usually just don’t care. Those hackers will make it work anyway, so why bother? And their market share is too small to take them into account.

Now, let’s pass to some personal experience with a webcam. I bought a webcam for my girlfriend’s laptop, which doesn’t have one integrated. The webcam was a cheap Logitech USB one, with “Designed for Skype” and “Windows compatible” written all around on the box. It even came with a CD, marked prominently as “Windows drivers”. My girlfriend’s laptop runs Windows Vista, and I decided to give it a chance, and plugged the webcam without further consideration. A message from our beloved OS informed me that a new device had been plugged (brilliant!) but Windows lacked the necessary drivers to make it work (bummer!). OK, no problem. We had the drivers, right? I unplugged the camera, inserted the CD, and followed the instructions to get the drivers installed. Everything went fine, except that the progress bar with the installation percent went on for more than 12 minutes (checked on the watch) before reaching 100%. After installation, Windows informed me that a system reboot was necessary, and so I did. After reboot, the camera would work.

As I had my Asus Eee at hand, I decided to try the webcam on it. I plugged it, and nothing happened. I just saw the green light on the camera turn on. Well, maybe it worked… I opened Cheese, a Linux program to show the output of webcams. I was a bit wary, because the Eee has an integrated webcam, so maybe there would be some interference or something. Not so. Cheese showed me immediately the output of the webcam I had just plugged, and offered me a menu with two entries (USB webcam and integrated one), so I could choose. That’s it. No CD with drivers, no 12-minute installation, no reboot, no nothing. Just plug and play.

Perhaps it is worth mentioning that the next time I tried to use the webcam on the Vista laptop, it would ask me for driver installation again! I don’t know why… I must have done something wrong in the first installation… With Windows, who knows?

Comments (10)

Soy un PC y quiero ser libre

Leído vía Menéame, un vídeo hecho por alumnos de una escuela de Ordizia, mi pueblo natal:

Comments (3)

Making iSight camera work in Ubuntu

As I said in a previous post, I bought a [[MacBook]], and I am making all bits work correctly. Out-of-the-box support from Ubuntu (the only GNU/Linux I tried on the MacBook so far) is excellent, but some things (camera, WiFi…) need proprietary drivers, so some more tweaks are needed.

I have followed the instructions in the Ubuntu community site, as with the procedures detailed in the previous post.

Basically, it all boils down to:

Fetch the Apple drivers for the camera

As root (if, unlike me, you like sudo, then run the following as user, but prepended with sudo), mount the Mac OSX partition (you didn’t delete it, right?) and copy the relevant file somewhere else (the cp command should be all in one line):

# cd
# mkdir /mnt/macosx
# mount /dev/sda2 /mnt/macosx
# cp /mnt/macosx/System/Library/Extensions/
     IOUSBFamily.kext/Contents/PlugIns/AppleUSBVideoSupport.kext/
     Contents/MacOS/AppleUSBVideoSupport .
# umount /mnt/macosx

You might have noticed that the Mac OSX partition is not sda1, but sda2. Don’t ask me. It turns out like this after following my own installation instructions. Apple must have decided to install the OS in the second partition for some reason.

Install the required packages

We need a package called isight-firmware-tools. Unfortunately it is not present in the Hardy repos at the moment (it was in the Gutsy ones, I think). You can add a Launchpad repo, editing /etc/apt/sources.list to add:

deb http://ppa.launchpad.net/mactel-support/ubuntu hardy main
deb-src http://ppa.launchpad.net/mactel-support/ubuntu hardy main

Then, as root:

# aptitude update
# aptitude install isight-firmware-tools

You will be prompted for a path to the driver you copied before. You can press Enter without paying much attention, then execute (assuming you copied the driver to your root home):

# cd
# ift-extract -a ./AppleUSBVideoSupport

To activate the driver, restart [[HAL (software)|HAL]]:

# /etc/init.d/hal restart

Test it with [[Ekiga]]

As explained in the Ubuntu community site, you can run Ekiga as user (after installing the ekiga package). Choose V4L2 as video plugin, and Built-in iSight should appear among the Input device list. If it does, the process worked.

Comments (22)