2004-11-01 14:11

November 1st, 2004 by Vasil Kolev

And now about the live and dead video…

First, equipment:
A camera with firewire (IEEE1394) output (I can’t remember the exact model);
Laptop with firewire port, centrino/1.4GHz, and ethernet port;
Server that has a good connectivity (marla);
A pipe from the laptop to the server with enough bandwidth (the sum of the streams + ~25%), to be able to catch up with the transmission, the errors and the bursts that follow.

Why firewire? Because it has better quality, and doesn’t use too much CPU (which can’t be said about v4l), and it’s usage is easier.

Software:

dvgrab from Debian with one patch by me, to make it not to write to the disk;
ffmpeg and ffserver, version 0.4.8 (the newer ones suck), for the encoding and broadcasting, with a small patch, that solves a problem when sending over the network (described here);
wget for archiving;

Principle of work – ffpmeg sends a few (in our case three) different streams (in our case two video and one audio) to the server which assembles them, and sends them to the different clients on request.

The situation:

The laptop stayed next to the camera, and was receiving the raw video, encoding it in some streams, and sending it to the server, where people were watching it. From the same server with wget there was a download of the current stream for archival (it was done to zadnik.org, to lower a bit the load on marla’s drive, thanks, Velin :) ).

Configuration, commands, etc :

Because dvgrab has its own opinion on a lot of questions, we created a named pipe (FIFO) with the command

mknod p av.dv

, and ran it in the following way:

dvgrab --format raw --frames 0 --buffers 1500 --size 0 > av.dv

The options in short mean rew format (e.g. no reencoding by it), frames means at how many frames to start writing a new file (e.g. to write only to stdout), size is a similar option, but in megabytes, and buffers is how many frames to buffer – 1500 is ~62 secs, which worked in most situations.
From dvgrab the raw stream went to ffmpeg, through the following command:

ffmpeg -i av.dv http://marla.ludost.net:8090/feed1.ffm

Nothing complex, it was taking the parameters of the streams from the configuration of ffserver.
(I’m not really sure what was the exact problem for doing dvgrab … | ffmpeg …, but there was, so we used named pipe)

On the server there was a ffserver running, which’s configuration cane seen at https://vasil.ludost.net/ffserver.conf. ffmpeg used the options inside, to know what streams to send. There isn’t anything special inside, only you should write it in a way that minimizes the number of streams (for example, all three streams use the same audio stream, mp3/mono/64kbps). I recommend running it with a higher priority, if the machine is loaded. Also this configuration doesn’t work if you want to view the video from windows with WMP, you’ll need an ASF stream.

Specific notes:

Test everything one-two days before making the real live broadcast (the problems are easily discovered by the users, not like the other services).
Make sure that the pipe used for sending the master stream is good enough (and keep in touch with the people that are responsible for it).
Make sure that the processor of the machine that does the encoding can withstand the load, and turn off all of its power saving.
The reconfiguration of the streaming server in the middle of the live feed means a short interruption of the broadcast (the server doesn’t have a reload, only restart).
It’s possible to use ffmpeg to read directly from firewire, if the camera is supported from the kernel (which wasn’t our case, so we used dvgrab (I don’t think that there are a lot of supported ones)). A problem will be the lack of buffer in ffmpeg, there will be a problem with the errors in the link.

Things for the future:

A local copy of the raw material (we weren’t able to make one this time, because of the lack of disk space).
A nicely made filler, which to be shown when there isn’t a live feed.
Momentarily accessible archive.
A way to transmit/broadcast over RTSP (may be through darwin streaming server?).
A better encoder, maybe based on MPlayer.
ASF stream, to be viewable from windows (WMP) machines.
Instruments for testing of the link, if if can sustain a given bandwidth for a long period.
Replication of the streaming server, if we make more than 70mbps traffic.

2004-11-01 13:43

November 1st, 2004 by Vasil Kolev

И сега за живото и мъртво видео…

Първо, техниката:
Камера с firewire (IEEE1394) изход (не помня точния модел);
Лаптоп с firewire порт, centrino/1.4GHz, и ethernet платка;
Сървър на сериозен bandwidth (marla);
Канал между laptop-а и сървъра с достатъчно bandwidth (сбора от потоците + ~25%), за да може да наваксва на предаването, грешките по линията и burst-овете след тях.

Защо firewire? Понеже може да извади много по-добро качество, и не товари процесора (което не може да се каже за v4l), и подкарването му е по-проста задача.

Софтуер:
dvgrab от Debian с един patch от моя страна, за да не пише по диска;
ffmpeg и ffserver, версия 0.4.8 (новите са много омазани), съответно за кодиране и за разпръскване, с patch, който да реши един проблем при пращането през мрежата (описан ето тук);
wget за архивиране;

Общ принцип на работа – ffmpeg изпраща няколкото (в нашия случай три) различни потока (в нашия случай два видео и един аудио) до сървъра, който си ги сглабя, и дава на различните клиенти при заявка.

Ситуация:

Laptop-а се намираше до камерата, и приемаше от нея видеото, кодираше го в няколко потока, и го пращаше до сървъра, откъдето хората го гледаха. От същия сървър с wget се теглеше текущия поток, с архивна цел (правеше се до zadnik.org, за да намаля малко натоварването по диска на marla, Велин, благодаря :) ).

Конфигурация, команди и т.н.:

Понеже dvgrab има собствено мнение по бая въпроси, трябваше да създадем един named pipe (FIFO) с командата

mknod p av.dv

, и да го пускаме по следния начин:

dvgrab --format raw --frames 0 --buffers 1500 --size 0 > av.dv

Опциите накратко значат raw формат (т.е. никакво прекодиране от негова страна), frames значи на колко кадъра да започва нов файл (т.е. да пише само в stdout), size е подобна опция, но в мегабайти, а buffers е колко кадъра да буферира – 1500 отговаря на ~62 секунди, което успя да се справи с доста ситуации.
От dvgrab видеото отиваше във ffmpeg, чрез следната команда:

ffmpeg -i av.dv http://marla.ludost.net:8090/feed1.ffm

Фактически нищо сложно, параметрите на потоците се определяха от конфигурацията на ffserver-а.
(не съм сигурен защо имаше проблем да направим dvgrab … | ffmpeg …, но все пак имаше, и за това използвахме named pipe)

На сървъра стоеше ffserver, чиято конфигурация може да се види на https://vasil.ludost.net/ffserver.conf. ffmpeg използва опциите вътре, за да определи какви потоци да изпраща. По самата конфигурация няма нищо специално, само трябва да се направи по такъв начин, че да се минимизира броя на потоците (например и трите използват един и същи audio поток, mp3/mono/64kbps). Препоръчвам да се пуска с по-голям приоритет, ако машината е натоварена. Също така тази настройка не работи за гледане на видеото от windows с windows media player, трябва да се пусне ASF поток.

Специфични моменти:

Тествайте всичко ден-два преди да пуснете реалното предаване (проблемите се усещат твърде лесно от потребителите, за разлика от други услуги).
Убедете се, че линията, използвана за излъчване, е достатъчно добра (и поддържайте връзка с хората, които отговарят за нея).
Убедете се, че процесорът на машината, която кодира, може да понесе натоварването и му изключете всичкия power saving.
Преконфигурирането на streaming сървъра по средата на живо предаване значи кратко прекъсване на предаването (сървъра няма reload, само restart).
Възможно е да се използва ffmpeg да чете директно от firewire, ако камерата се поддържа от ядрото (което не беше случая с нашата, и за това използвахме dvgrab (мисля, че не са много поддържаните)). Проблем ще е липсата на буфер в ffmpeg, ще има проблем с избягването на проблеми в линията.

Неща за правене в бъдеще:

Локално копие на чистия материал (сега не успяхме, понеже нямахме достатъчно дисково пространство).
Добре направен filler, който да се показва докато няма живо предаване.
Моментално достъпен архив.
Възможност за предаване по RTSP (може би чрез darwin streaming server?).
По-добър encoder, може би базиран на codec-ите на MPlayer.
ASF поток, за да може да се гледа от windows машини (с WMP).
Инструментариум за тест на поддържана за дълъг период постоянна пропусквателна способност на връзка.
Репликация на streaming сървъра, ако надминем 70 mbps трафик.

2004-10-31 22:28

October 31st, 2004 by Vasil Kolev

The Sunday is a lazy day …

Nothing serious, we had breakfast at “Divaka”, I went to my hairdresser to get my split hairs cut, then I took Velin from his office and we walked to the center, where with Lora, Albert and Fozzie got dinner again at “Divaka” (and worked on a plan to kidnap the waitress, who we all liked (but nobody was carrying a bag, because of a lack of planning)).

I feel dizzy for third day in a row, I wonder if I’m getting sick again, or it’s just from the hard punching of the bag and the wall behind it.

I’ll probably write the documentation of the video recording tomorrow, I’m waiting for Rumen to send me the commands that are written in a file on his laptop, I don’t feel like remembering them.

2004-10-31 22:22

October 31st, 2004 by Vasil Kolev

Неделята е мързелив ден…

Нищо особено, закусихме в “Дивака”, аз минах най-накрая през фризьора да ми изреже цъфтежите, след което взех Велин от офиса му и го разходих до центъра, където пак в “Дивака” с Лора, Алберт и Fozzie вечеряхме (и се обмисляше план за отвличане на сервитьорката, която ни хареса на всички (ама никой не си носеше чувал, ей това е липса на планиране)).

На мен за трети ден подред ми се вие свят, чудя се дали не се разболявам пак, или просто блъскам твърде силно по крушата и стената зад нея.

Нещата за видеото ще напиша най-вероятно утре, чакам Румен да ми прати командите, които имам записани на laptop-а му, че не ми се възстановяват по памет.

2004-10-30 21:43

October 30th, 2004 by Vasil Kolev

Yesterday I didn’t blog, because I felt sleepy in the afternoon, and fell asleep around 6… I woke up for a while around 23, because the alarm of one apartment from the building across the street was screaming for about half a hour, but then I fell asleep again. I can’t remember what I did that day :)

In the morning me and Velin started tormenting ftp.uni-sofia.bg – we tried to install Boyan Krosnov’s traffic stats system, but it turned out that it wasn’t working with the version of perl there (5.8, marla uses 5.6) (Boyan, the problem is that the things that go out from XML::Dumper can’t be imported for some reason, if you have the time, call on ICQ). This information will be handy when I decide to upgrade marla from woody to sarge.

Nothing more interesting – I’m reading Wikipedia and unable to stop. I’m apathetic, and have to prepare myself for the Tuesday’s lecture, to write something on the way that I did the live broadcast of the OpenFest, and to see what will I do with one shared storage…

2004-10-30 21:38

October 30th, 2004 by Vasil Kolev

Вчера не съм блогвал, понеже следобяда ми се доспа, и заспах около 6… Събудих се за малко около 23, понеже алармата на един апартамент от отсрещния блок рева около час, но после пак заспах. Не помня точно какво правих :)

Сутринта с Велин се хванахме да тормозим ftp.uni-sofia.bg – опитахме се да инсталираме системата на Боян Кроснов за отчитане на трафик, но се оказа, че не се разбира с версията на perl там (5.8, а marla е с 5.6) (Бояне, проблема е, че това, което вадиш чрез XML::Dumper, после не може да се import-не, ако имаш време, обади се на ICQ). Информацията ще ми е бая полезна, като реша да upgrade-вам marla от woody на sarge.

Иначе нищо интересно – чета разни работи от Wikipedia и не мога да се спра. Хванала ме е апатията, а трябва да се подготвя за лекцията във вторник, да напиша нещо кратко по темата как точно правих излъчването на OpenFest, и да видя какво ще правим със един shared storage…

2004-10-29 15:34

October 29th, 2004 by Vasil Kolev

Some technical things, that I wanted to write down…

I did a reconfiguration of the 3ware driver of the controller in marla – I lowered TW_MAX_CMDS_PER_LUN down to 64. The reason was a discussion at linux-kernel, where the explanation was that the queue of the block layer can hold up to 128 requests, and the one of the driver by default is 256, so the kernel can’t do any reordering and optimizations, the cotroller swallows all (and it can’t optimize them because it doesn’t have enough information, and can screw the things up). The result is a lot more responsive machine, and loadavg rarely going over 3-4.

There’s a patch, that makes this parameter controllable through sysctl, but I didn’t want to meddle in the kernel too much, I prefer to stick the the vanilla one. If I have the time, I could try to lower it to 32, but before that I’ll have to check how many requests can the controller process effectively in parallel.

(some additional information – the controller is 3ware Escalade 7500-8, with one RAID5 array on it, consisting of 4 200GB drives)

2004-10-29 15:21

October 29th, 2004 by Vasil Kolev

Няколко технически неща, които се каня да напиша от известно време…

Направих една пренастройка в 3ware драйвера на контролера на marla – намалих TW_MAX_CMDS_PER_LUN на 64. Причината беше една дискусия в linux-kernel, в която се обясняваше, че големината на опашката на block layer-а е 128, а на тоя драйвер по подразбиране е 256, така че самото ядро изобщо не може да направи някакво преподреждане и оптимизация, контролера гълта всичко (а той самия не може да ги оптимизира, понеже няма достатъчно информация, и може да омаже нещо). Резултатът е една доста по-нормално отговаряща машина, и loadavg рядко се качва над 3-4.

Има и patch, който прави този параметър настройваем през sysctl, но не ми се бърникаше сериозно по ядрото, предпочитам да се придържам към vanilla kernel-а. Ако намеря време, мога да пробвам да смъкна параметъра на 32, но преди това трябва да си изясня колко заявки може да обработва паралелно и ефективни контролера.

(малко допълнителна информация – контролера е 3ware Escalade 7500-8, с един RAID5 масив на него, от 4 диска по 200GB)

2004-10-29 01:05

October 29th, 2004 by Vasil Kolev

Again a quirky day…

Today I got my boxing bag, the gloves, bandages, etc,etc … It’s a bit strange when your consultant is ex-professional kickboxer (who is also your uncle) – I had some problems with the carrying (good thing that we didn’t get the big boxing bag, I tried to pick it up, and my shoulders started to pop). I just have to mount it, but this needs planning.

Today’s network security lecture was almost a failure. Today it was planned for desync and flipflop to speak about 802.11*, CAN/LIN, etc, but they weren’t here, so at the entrance of FMI I found out that I’ll have to do this lecture, so I printed my plan at Shiyachki’s room, and entered the hall almost on time. Of course, it was horrible – I was still in the high rpms because of the busy day, I was speaking too fast, got confused a lot, confused the students ( next time I’ll probably reexplain the netmasks), looks like that without preparation it just doesn’t work (at least I should’ve drank a valerianae)… I can work in such situations , if it’s systems or machine related, but not with people…

Before the next lecture I’ll find someone to practice on, and after that I’ll tell it to the students. I have to talk about TCP, and there are some bad moments there.

2004-10-29 00:58

October 29th, 2004 by Vasil Kolev

Пак сбъркан ден…

Днес си взех боксовия чувал, ръкавици, бинтове, и т.н., и т.н. Това консултант да ти е бивш професионален кикбоксьор (който и ти е чичо) на моменти си е чак проклятие – аз лично се озорих с носенето (добре, че не взехме големия чувал, един път се опитах да го вдигна, и ми изпукаха раменете). Остава монтирането, но то има нужда от планиране.

Днешната лекция по мрежова сигурност беше бая сериозна издънка. По принцип трябваше да говорят desync и флопа за 802.11*, CAN/LIN и подобни неща, но ги нямаше, та се получи следната ситуация – на входа на ФМИ в 19:07 разбрах, че аз трябва да си водя следващата лекция, та набързо отпечатах плана си за TCP/IP при Шиячки, и нахълтах точно навреме в залата, за да говоря. Разбира се, получи се ужасно – бях на високи обороти още от целия ден, говорех бързо, обърквах се на места, обърках и студентите за някои работи (следващия път вероятно пак ще обясня netmask-ите), изобщо без да съм се подготвил не се получава (поне да бях изпил един-два валериана, да не ми е толкова изнервено)… С такава ситуация мога да се справя, ако е някакъв проблем по машини или системи, но не и с хора …

За следващия път ще си намеря някой, на който първо да разкажа веднъж лекцията, и след това да я обяснявам на студентите. И без това имам да говоря за TCP, където има някои сложни моменти.

2004-10-28 00:32

October 28th, 2004 by Vasil Kolev

I must really be careful what I’m saying. A few moments ago there was a (not really strong) earthquake, and I got reminded that on my last lecture I mentioned that it was about time to happen…

I want to apologize, I didn’t mean it…

Here’s a link.

2004-10-28 00:30

October 28th, 2004 by Vasil Kolev

Трябва да внимавам какво говоря. Преди малко имаше (не особено силно) земетресение, и ми напомниха, че на последната си лекция споменах, че е крайно време да се случи…

Извинявам се на всички, аз така без да искам …

Ето и линк .

2004-10-27 23:35

October 27th, 2004 by Vasil Kolev

Today we fixed the problem at the project – the engineer came, changed the firmware of the device, and everything started working (now it gets ~11 seconds downtime). Now we’ll have to finish the full tests, with cards and terminals, and the project will be complete. I love when things are working :)

At FSA-members there is a discussion about a server – we have it, the problem is to find what to use it for, and where to place it. That’s not made easier by the size (8U) and the weight (70 kg)…

I fixed the 3ware driver at marla, following a discussion at linux-kernel, let’s see how will it behave.

In the evening me, my brother and my father celebrated my father’s birthday – now he’s 50 years old. We were at a quiet and calm place upstairs in “Tukan”, drank a jug of wine, talked, made some plans, and then I walked him to the taxi. The present was the book with the diary of gen. Nikola Mihov, and the last album of Kultur Shock, I think that he’ll appreciate them :)

One of the most important things that I’ve learned from him is that you have to take responsibility and do the job – when there is a problem not to ask “who’s guilty”, but “how can it be fixed” (or not to ask, and just fix it). A lot of people are doing exactly the opposite, and you can’t do any work with them…

Tomorrow I’ll be getting a better punching bag, and normal gloves, after which the hanging on the celling will follow (the neighbors surely will hear it :) ).

2004-10-27 23:20

October 27th, 2004 by Vasil Kolev

Днес решихме проблема в проекта – просто дойде инженера, смени firmware на устройството, и всичко тръгна (последно – ~11 секунди downtime). Сега останаха пълните тестове, с карти и терминали, и може да броим проекта за завършен. Обичам нещата да работят :)

В FSA-members тече обсъждане на един сървър – имаме го, въпроса е да му се намери употреба и къде да го сложим. Задачата изобщо не се улеснява от това, че тежи около 70 килограма, и е 8U…

Оправих нещо по marla по 3ware драйвера, следвайки няколко обяснения в linux-kernel, да видим как ще се държи.

Вечерта аз, брат ми и баща ми отпразнувахме рождения ден на баща ми – направи 50 години. Бяхме на тихо и спокойно горе в “Тукан”, изпихме си една каничка вино, поговорихме си, направихме малко планове за действие, и после го изпратих. Подарих му книжката с дневника на ген. Никола Михов, и новия албум на Kultur Shock, мисля, че ще ги оцени :)

Едно от много важните неща, които съм научил от него е, че трябва да се поема отговорност и да се върши работата – при проблем да не питам ‘кой е виновен’, а ‘как може да се реши проблема’ (или даже да не питам, а да го решавам). При много хора е обратното, и с тях нищо не може да се свърши…

Утре ще си вземам хубава боксова круша, и нормални ръкавици, след което ще последва окачане на тавана (няма само съседите да ми бучат :) ).

2004-10-26 23:10

October 26th, 2004 by Vasil Kolev

The rest is something nice, if it isn’t interrupted…

Around noon I got a call to tell me that tomorrow the engineer that’s going to fix the problem with the retarded device at the project is coming. Tomorrow I’ll have to get up around 10…

At some moment I remembered, that tomorrow my father has a birthday, do I went out to pick a present for him – tomorrow he’ll be in Sofia, and we’ll celebrate it somewhere quietly.

In the evening followed the network security lecture, Pentchev was speaking about PPP, he was late a bit, and had to prolong it with 10 minutes. There was another problem with his X on the FreeBSD, it denied to communicate with the projector (not like the projector at IEC, where we had no such problems), so he had to show the presentation under windows, where he had some CSS problems.

I finished the uploading of the presentations, and IMO there aren’t a lot more photos to be uploaded at the OpenFest 2004 archive. It’s definitely generating a lot of traffic on marla.

I’ll have to find someone to transcribe my lecture from OpenFest, I can’t stand listening to myself. Some day I’ll gather some strength, will watch all the records, and do something about it.

2004-10-26 23:01

October 26th, 2004 by Vasil Kolev

Почивката е хубаво нещо, ако не ти я прекъсват…

Около обяд ми се обадиха да ми кажат, че утре пристига инженера, който трябва да реши проблема с малоумното устройство в проекта. Утре трябва да стана около 10…

По някое време се сетих, че утре баща ми има рожден ден, и излязох да му взема подарък – утре ще е в София, и ще го отпразнуваме тихо и спокойно.

Вечерта беше лекцията по мрежова сигурност, Пенчев говори за PPP, закъсня леко, и му се наложи да я удължи с около 10 минути. Друг проблем беше, че X-а под FreeBSD не се разбра с проектора (за разлика от проектора в IEC, където такива проблеми нямаше), та се наложи да показва презентацията си под windows, където имаше и някакви проблеми с CSS-а.

Довърших качването на презентациите, а като гледам, не останаха да се качват и снимки от много хора в архива на OpenFest 2004. Определено генерират бая трафик на marla.

Трябва да намеря някой да ми транскрибира лекцията от OpenFest, аз лично не мога да се трая, като се слушам. Един ден ще събера желание, ще си изгледам записите, и ще реша какво да направя по въпроса…

2004-10-25 23:41

October 25th, 2004 by Vasil Kolev

It’s nice to get up in 12…

Today I fixed the opefest’s archive – I put together the video, uploaded the presentations and photos, and if someone’s interested, it’s available at openfest.org/archive/2004/. I fought for half a hour to pull out the audio stream from the AVI files, but couldn’t find a good enough instrument (only ffmpeg has a clear way, and it gave SIGFPE (probably because libmp3lame is missing, but I’m not in the mood to tackle that), if someone knows a small and working program, drop me a line).

The video editing was really simple, with

mencoder -forceidx -ovc copy -oac copy [-ss beg] [-frames count] -o OUTPUT.avi INPUT.avi

, I just looked what was in each file, and pulled it out. I haven’t glued them together, I know there will be gaps, no need to make them more.

This week I’ll probably work on a shared storage, which will be demonstrated at BAIT expo, and I’m thinking about the cluster I should make…

2004-10-25 23:35

October 25th, 2004 by Vasil Kolev

Хубаво е да станеш в 12…

Днес оправих архива на OpenFest – оформих видеото, качих колкото имах презентации и снимки, и който се интересува, да гледа на openfest.org/archive/2004/. Борих се половин час да изтръгна audio потоците от видео файловете, ама не намерих подходящ инструмент (само ffmpeg май има чист начин, и той даде SIGFPE (сигурно е от липсата на libmp3lame, но не ми се занимава с това), ако някой се сеща за кратко и работещо програмче, да се обади).

Оформянето на видео файловете стана адски просто,с

mencoder -forceidx -ovc copy -oac copy [-ss beg] [-frames count] -o OUTPUT.avi INPUT.avi

, като просто прегледах в кой файл какво има, и ги извадих. Не съм налепял парчетата, така и така ще има дупки.

Аз тази седмица вероятно ще си играя с един shared storage, който ще бъде демонстрира на BAIT expo, и мисля какъв клъстер да направя…

2004-10-25 13:43

October 25th, 2004 by Vasil Kolev

To see what did OpenFest do to me, take a look at this и this photos…

2004-10-25 13:42

October 25th, 2004 by Vasil Kolev

За да се види докъде ме докара OpenFest, вижте тази и тази снимки…