Sun 8 Oct 2006
Использование lighttpd, Mplayer/Mencoder и Flvtool2 для реализации потоковой раздачи Flash Video
Posted by Scoundrel under Uncategorized ·
Это очень короткий пост о том, как при помощи набора бесплатных инструсментов реализовать полнофункциональный потоковый видео сервер, основанный на flash video. Итак, что же мы хотим получить после окончания настройки сервера? Все очень просто - мы хотим получить бесплатный функциональный аналог решения по стримингу видео, реализованного в Flash Communication Server (Flash Media Server) компании Macromedia.
Первым нашим шагом, как и при использовании любой другой технологии потоковой передачи видео, будет конвертация видео файлов в специализированный формат, предназначенный для передачи по сети в виде потока (этот формат называется “Flash Video” (flv)) и добавление в него специализированной мета-информации, предназначенной для плееров, которые реализуют “перемотку” видео потока до нужного вам места в видео файле. В интернете есть множество статей, авторы которых смело заявляют “просто запустите ffmpeg и все будет отлично”, но я вынужден не согласиться с ними. Ffmpeg - это не подходящий инструмент для поставленной задачи, т.к. он поддерживает очень маленькое количество входных форматов видео-файлов, а мы не хотим организовывать двухэтапное перекодирование видео через промежуточных формат, понятный ffmpeg. Именно поэтому мой выбор - это бесплатное ПО со скромным именем mplayer, содержащее в себе утилиту mencoder, предназначенную для перекодирования видео-файлов из одного формата в другой и понимающей огромное количество входных форматов.
В первую очередь вам нужно будет скачать пакет исходных кодов для mplayer с официального сайта mplayer и скомпилировать их. Я не буду описывать здесь, как это сделать, т.к. существует море статей, рассказывающий ою этом, но хочу привлечь ваше внимание к просому факту: Постарайтесь минимизировать набор выключенных кодеков на этапе компиляции установив все требующиеся библиотеки из репозитория вашего дистрибутива или соберите их самостоятельно, т.к. чем больше кодеков у вас будет, тем больше форматов видео файлов вы сможете обрабатывать”.
После установки mplayer/mencoder вам будет нужно установить интерпретатор языка Ruby чтобы запустить ПО flvtool2. Пожалуйста, убедитесь, что у вас стоит версия Ruby не ниже 1.8.4.
Следующим шагом будет инсталляция flvtool2 - небольшой утилиты, позволяющей вставлять meta-информацию в видео-файлы и позволяющую использовать “перемотку” видео потока во flash плеерах. Исходные тексты можно получить на домашней странице проекта, но я хочу посоветовать вам использовать последнюю версию flvtool2 из SVN-репозитория (процесс описан на домашней странице проекта).
Небольшое замечание: текущая версия flvtool2 содержит маленькую, но очень неприятную ошибку, не дающую использовать данное ПО с файлами, сгенерированными mencoder’ом. Когда вы запустите flvtool2, вы получите следующий результат:
Для решения этой проблемы откройте файл lib/flv/amf_string_buffer.rb в исходных текстах flvtool2 и измените строку 163 с
write [(time.to_i * 1000.0)].pack(’G')
на
write [(time.to_f * 1000.0)].pack(’G')
Хочу сказать ОГРОМНОЕ СПАСИБО Дмитрию Штефлюку за это исправление.
Итак, сейчас вы готовы к конвертации ваших видео файлов из любого формата в формат flv. Вы можете сделать это, используя следующий набор команд:
Эти команды конвертируют файл orig_file.ext
в dest_file.flv и добавляют meta информацию в него.
Последнее, что вам нужно будет сделать - это скачать Lighttpd web server с его официального сайта и установить его . После этого, включите стриминг-модуль в config-файле и вы сможете ипользовать любой flash player, понимающий идею стриминга видео для создания вашего союственного сервиса Youtube и зарабатывания вашего первого миллиарда долларов.
А для того, чтобы отблагодарить автора статьи, поддержите ее на digg.com
Notice: Читайте мою новую статью о стриминге видео “Стриминг Flash Video при помощи Nginx” чтобы узнать, как реализовать стриминг сервер на nginx.
- Русский Feed Восстановлен
- Стриминг Flash Video при помощи Nginx
- HAProxy - Надежный, высокопроизводительный балансировщик нагрузки для TCP/HTTP
- SOS!
- Варианты настройки Ruby On Rails на максимальную производительность: mongrel vs lighttpd vs nginx
October 8th, 2006 at 8:35 am
[...] Want to say sorry to all my Russian language readers because my Russian Feed has been broken for last week or so after hoster changes. As for now feed works fine and you can read my last post in your native language! [...]
October 8th, 2006 at 10:55 am
[...] current version of flvtool2 has really annoying bug, that prevents it from working with mencoder generated flv files [...]
Small addition: with ffmpeg you have the same problem
October 8th, 2006 at 3:32 pm
[...] Using Lighttpd, Mplayer/Mencoder and Flvtool2 to Implement Flash Video Streaming So, what we are going to get at the end of our setup? We are going to get some type of completely free streaming support that is available with Macromedia’s non-free Flash Communication Server (Flash Media Server) (FCS). [...]
October 8th, 2006 at 5:39 pm
Or… you could run a Red5 server - http://osflash.org/red5
October 8th, 2006 at 11:48 pm
[...] Here’s a guide on how to use Lighttpd and a few tools to create a video streaming server. Did this guy miss the memo on Red5? Ah well. Posted in Uncategorized | [...]
October 9th, 2006 at 5:32 am
[...] read more | digg story [...]
October 9th, 2006 at 6:31 am
Добрый день!
Хочу опубликовать вашу статью на сайте. Допустимо ли это?
October 9th, 2006 at 7:30 am
Nice Article. I think even some websites provides them like templates (they even include hosting). Look at http://www.alstrasoft.com/.
October 9th, 2006 at 8:18 am
[...] Homo-Adminus Blog » Using Lighttpd, Mplayer/Mencoder and Flvtool2 to Implement Flash Video Streaming (tags: flash video streaming howto linux lighttpd youtube web2.0 web videos) Posted by xtra Filed in [...]
October 9th, 2006 at 8:43 am
“..Ffmpeg sucks..”
Mplayer/Mencoder relies on ffmpeg to do much of the encoding… - it’s included with the package.
October 9th, 2006 at 9:17 am
[...] Homo-Adminus Blog » Using Lighttpd, Mplayer/Mencoder and Flvtool2 to Implement Flash Video Streaming (tags: server video flash) [...]
October 9th, 2006 at 1:11 pm
[...] Das Homo Adminus Blog beschreibt, wie man mit Opensource-Mitteln eben diesen Service aufsetzen kann. [...]
October 9th, 2006 at 1:23 pm
[...] A guide to setting up a flash video streaming server. http://http://blog.kovyrin.net/2006/10/08/lighttpd-memcoder-flvtool-for-streaming/ [...]
October 9th, 2006 at 4:20 pm
[...] Hier ist ein technischer Artikel, der beschreibt, wie man einen Flash Video Streaming Server aufsetzt - gewissermassen als freie Alternative zum Flash Media Server. [...]
October 9th, 2006 at 6:34 pm
[...] Article about how to create your own video sharing service with flash video streaming using only open-source tools.read more | digg story [...]
October 9th, 2006 at 6:56 pm
[...] Article about how to create your own video sharing service with flash video streaming using only open-source tools.read more | digg story [...]
October 9th, 2006 at 8:59 pm
[...] Como está caliente el tema de YouTube, aquí va un tutorial de cómo crear tu propio servidor de streaming de video, y así poder ganar tu propio billón y medio de dólares (artículo original, en Inglés). Lo primero que hay que tener en cuenta es que se necesitará el Flash Communication Server (Flash Media Server) (que no es gratuito), así como un lenguaje enfocado a la Web, es este caso usaremos Ruby. También se necesitarán códecs para convertir los videos a formato Flash Video (.flv) que es el formato que se usará para el streaming. Se usa este tipo de formato ya que se pueden agregar metadatos que permiten habilitar la función de Pausa/Play/Avanzar/Retroceder durante la reproducción en la página Web. [...]
October 9th, 2006 at 10:38 pm
Hey, looks like someone stole your blog entry without giving any credit:
http : // www . zoji . com / kao / blogs / 75691
October 10th, 2006 at 4:53 am
2madkarma: thanks. will write an email to him.
October 10th, 2006 at 5:07 am
My humble apologizes. It has been fixed.
October 10th, 2006 at 5:28 am
2Kermee: Great thanks!
October 10th, 2006 at 7:25 am
[...] Hoy la Costa Oeste anoche anochecia agitada, Google decidia comprar youtube, mostrando un cambio de politica (en lugar de desarrolar buenos productos o adquirir productos novedosos para incorporarlos, compran trafico puro y duro). Mark Cuban llamaba gilipollas a Sergei y Larry y seguro que tontos no son. Muchas de las personas que mas quiero y admiro curran en Google ahora mismo y se alli no dejan entrar a tontos precisamente. Por si acaso, lo lo primero que pense es que me iba a pillar el youtube-dl (un scriptito en python para bajar videos de youtube) y bajarme todo lo que pudiera, porque se acabo lo que se daba. Youtube es un coladero de infracciones de copyright, que una empresa pequegna (de las de cara a cruz y que sea lo que dios diga) puede permitirse con tal de crecer en trafico, pero para un gigante como Google significa denuncias de competidores como Sony, cuyos abogados hoy fijo que no duermen. La empresa que una vez mas nos sorprendia con su tecnologia cambia y madura y con su madurez manda la industria a al agno 99, a comprar trafico y dinero rapido, que es para lo que estan las empresas. En el metro escuche a dos que decian que lo han hecho para joder a Yahoo y Flickr, quien sabe, lo interesante es que nuestra querida industria se nos vuelve gilipollas de nuevo y eso significa dos cosas: la primera es que compraran cualquier mierda con tal de que haya usuarios y la segunda es que muchisima gente sin idea volvera a forrarse, asi que habra que prepararse por si nos toca. Youtube no es tecnologia, son muchas maquinas y mucha pasta de ancho de banda, con una minima planificacion para que la cosa escale y no se desborde (basicamente tener los videos replicados un minimo de tres veces (un maximo relativo a la demanda del video) y un buen balanceador de carga. Lo siguiente es una traduccion por pedacitos de un articulo que encontre en del.icio.us y que esta [aqui] y que comenta como con dos o tres escriptitos en unix, nos podemos hacer un servicio como youtube, para ti y para tus amigos, sin censura y sin aparecer en los logs de nadie. La manera mas facil de montarse eso, y que puede ser como esta montado youtube, es bajarse el servidor flash de la misma macromedia, pero con lighttpd (una especie de apache ligero y modular) y mplayer se puede conseguir el mismo efecto. [...]
October 10th, 2006 at 11:24 am
[...] Article about how to create your own video sharing service with flash video streaming using only open-source tools.read more | digg story [...]
October 10th, 2006 at 12:46 pm
[...] Link [...]
October 10th, 2006 at 7:40 pm
[...] Homo-Adminus Blog » Using Lighttpd, Mplayer/Mencoder and Flvtool2 to Implement Flash Video Streaming Using Lighttpd, Mplayer/Mencoder and Flvtool2 to Implement Flash Video Streaming (tags: opensource reference tools media development) [...]
October 10th, 2006 at 11:24 pm
[...] Homo-Adminus Blog » Using Lighttpd, Mplayer/Mencoder and Flvtool2 to Implement Flash Video Streaming Free Flash Video Streaming (tags: linux lighttpd flash video streaming howto videos mplayer FLV) [...]
October 11th, 2006 at 12:33 am
[...] Using Lighttpd, Mplayer/Mencoder and Flvtool2 to Implement Flash Video Streaming (tags: sysadmin lighttpd multimedia ruby web freebsd) [...]
October 11th, 2006 at 7:16 pm
[...] Article about how to create your own video sharing service with flash video streaming using only open-source tools.read more | digg story Related Articles: Fund That Lost Billions Moves to Shut DownThe fund has lost $6.4 billion, according to the letter, which said assets were down 65 to 70 percent for…Research Analyst: YouTube Headed for a Big CrashYouTube has grown dramatically over the last couple of years by providing users the ability to post and share videos…Program Yourself… Trippy Video On YoutubeYou probably won’t regret seeing this.read more | digg story…Billionaires only: The 400 Richest AmericansA nine-figure fortune won’t get you much mention these days, at least not here. This year, for the first time,…Effects of Youtube, Myspace, and the new mediaAs people post content on Youtube, and new shows and novel forms of content pop-up around the Internet, and everyone… [...]
October 14th, 2006 at 11:00 pm
[...] Last your action, if it was not done before, should be conversion of your video files to FLV format and adding meta info to your created flv files. You can read how to do it in my previous post. [...]
October 14th, 2006 at 11:22 pm
Notice: Read my new article about flash streaming “Flash Video (FLV) Streaming with Nginx” to learn, how to implement streaming server with nginx.
October 16th, 2006 at 7:25 pm
[...] Homo-Adminus Blog » Using Lighttpd, Mplayer/Mencoder and Flvtool2 to Implement Flash Video Streaming (tags: kovyrin blog lighttpd memcoder flvtool streaming flash homoAdminus) [...]
October 18th, 2006 at 11:55 pm
[...] Il secondo, sempre in inglese, spiega come creare il proprio personalissimo portale per lo streaming video, in poche parole un piccolo youtube. [...]
October 19th, 2006 at 9:33 pm
[...] Pues mi buscador me dice que mire en Using Lighttpd, Mplayer/Mencoder and Flvtool2 to Implement Flash Video Streaming y allí me indican sustituya en /opt/lib/site_ruby/1.8/flv/amf_string_buffer.rb la línea 163 : [...]
October 22nd, 2006 at 8:47 pm
You probably didn’t understand how mod_flv_streaming works: It requires a start-parameter in the url and therefore won’t work with (most) flv players out there. See the docs at: http://jan.kneschke.de/projects/flv-streaming/
October 22nd, 2006 at 9:34 pm
I completely understand how it works because I’ve used it on our streaming servers before nginx got same feature.
October 23rd, 2006 at 2:42 pm
[...] 十大javascript开发库 web应用服务 如何做一个类似youtube的网站 [...]
October 31st, 2006 at 12:07 pm
Огромное спасибо за статью
Обязательно использую
November 2nd, 2006 at 7:37 am
[...] Using Lighttpd, Mplayer/Mencoder and Flvtool2 to Implement Flash Video Streaming Some type of completely free streaming support that is available with Macromedia’s non-free Flash Communication Server (Flash Media Server) (FCS) (categories: video streaming lighttpd flash administration webdev ) [...]
November 4th, 2006 at 5:37 pm
[...] - Using Lighttpd, Mplayer/Mencoder and Flvtool2 to Implement Flash Video Streaming [...]
November 6th, 2006 at 7:57 pm
Small detail in comparison, but what’s the best way to get frame grabs of the videos, like YouTube has as a single-image preview?
November 6th, 2006 at 9:13 pm
2Ben: I’m working on post about thumbs ripping now. Gonna finish it this week.
November 7th, 2006 at 11:01 pm
2Scoundrel: Excellent! Looking forward to instructions on doing thumbnail ripping! Thanks!
November 9th, 2006 at 9:56 am
[...] permalink Dazu solltest du aber auch etwas hier im Forum finden.. Naja ich umschreibe dein Problem mal: YouTube! Soetwas mchtest du doch anbieten, oder seh ich das falsch? Dazu kann ich dir folgende Links empfehlen: Flashcomguru.com - The Flash Video Resource: ‘Streaming’ flv video via PHP, take two Homo-Adminus Blog Using Lighttpd, Mplayer/Mencoder and Flvtool2 to Implement Flash Video Streaming [...]
November 17th, 2006 at 6:08 pm
When I run the mencoder command, I get this error:
CAN’T GET SPECIFIED FORMAT
Cannot initialize muxer.
Exiting…
Any ideas? Mplayer can play fli files fine…
Thanks for the help.
November 25th, 2006 at 12:31 am
Can this solution be utilized in a shared hosting environment. For example, could I install and run the mplayer and mencoder on a shared hosting site with GoDaddy. The server is Red Hat Linux with Apache.
Any advice would be greatly appreciated.
Thanks!
December 8th, 2006 at 2:56 pm
[...] Link dump Using Lighttpd, Mplayer/Mencoder and Flvtool2 to Implement Flash Video Streaming :: Homo-Adminus Blog by Alexey Kovyrin Video Blogging using Django and Flash(tm) Video (FLV) DRM - Daniel’s Random Mutterings digg - How to create your own Youtube and get your own billion Eh some i found. I looked for Rails version since I am versed n Rails now instead of python but if you have any leads they would be much appreciated. [...]
January 17th, 2007 at 2:06 pm
Can i apply this solution for live streaming? (input from a webcam for example)
February 4th, 2007 at 11:19 am
>любой flash player, понимающий идею стриминга >видео
Например? С поддержкой конструкции ?start=
February 4th, 2007 at 5:49 pm
2alex: да. именно. он должен читать метаинфо в самом начале и потом при переходах по видео (перематывании) делать ?start=XXX на позицию, указанную в метаинфо рядом с номером ближайшего кейфрейма.
February 4th, 2007 at 6:34 pm
Да это я понял. Есть уже существующие и работающие реализации - желательно на флэше? Пробовал http://www.flashcomguru.com/index.cfm/2005/11/2/Streaming-flv-video-via-PHP-take-two . При перемотке не обрывает старые закачки. 10 раз перемотаю - имею 11 потоков для одного файла. Ещё раз 6-7 перемотаю - плеер повиснет.
February 4th, 2007 at 7:21 pm
2alex: Мы писали сами… Наш флеш-девелопер за день наколбасил хотя до этого ваще не видел флеш-фидео. Потому я уверен, что не сильно сложно. Хотя, может, есть и готовое.
February 21st, 2007 at 2:47 am
Спасибо за пост. mplayer forever.
Достойной заменой может послужить Yamdi, делающая то же самое в контексте задачи и работающая в на порядки быстрее.
Но flvtool2 в силу свой чистой скриптовости имхо жутко тормозная штука и на больших роликах массовую конвертацию делает тяжким трудом
February 21st, 2007 at 3:35 am
2lhotski: Wow! Great thanks really useful thing!
February 24th, 2007 at 4:06 pm
[...] If you don’t want to upload your video at Youtube[1] and if you don’t want to set up a streaming server[2] here are some instructions mainly from Netzspielwiese[3] First convert you video with Riva encoder[4] to Flash format, then install the Wordtube[5] plugin and insert some cryptic code in your blog and your video will look like this one. [...]
March 21st, 2007 at 10:49 am
Здравствуйте! Спасибо за информацию! Есть вопрос - какая конфигурация сервера подойдёт для создания работоспособного сайта с видеоконтентом (на начальной стадии)?
Спасибо.
March 26th, 2007 at 7:57 am
[...] If you don’t want to upload your video at Youtube[1] and if you don’t want to set up a streaming server[2] here are some instructions mainly from Netzspielwiese[3] for an alternative. [...]
March 29th, 2007 at 11:51 am
[...] Использование lighttpd, Mplayer/Mencoder и Flvtool2 для реализации потоковой раздачи Flash Video [...]
March 29th, 2007 at 12:00 pm
[...] Использование lighttpd, Mplayer/Mencoder и Flvtool2 для реализации потоковой раздачи Flash Video [...]
April 4th, 2007 at 8:34 am
[...] I started from this blog entry. But as I’m using ubuntu dapper, I have the nice debian apt tool [...]
May 27th, 2007 at 4:33 am
[...] あと配信に関しては http://blog.kovyrin.net/2006/10/08/lighttpd-memcoder-flvtool-for-streaming/ http://blog.lighttpd.net/articles/2006/03/09/flv-streaming-with-lighttpd あたりはどうでしょう。 [...]
May 27th, 2007 at 4:34 am
[...] Using Lighttpd, Mplayer/Mencoder and Flvtool2 to Implement Flash Video Streaming [...]
June 11th, 2007 at 11:53 am
Hi, I have use the same mencoder command above listed and it works fine. But my video player is a bit big, and when I play the converted flv video, its pixelated,i.e the quality is not good.
What are the things I need to change to make it a size of 407×305 and quality will be better.
August 28th, 2007 at 8:33 am
[...] read more | digg story Posted by seethepost Filed in news [...]
October 18th, 2007 at 2:16 pm
[...] to create your own video sharing service with flash video streaming using only open-source tools.read more | digg story [?] Share [...]
December 11th, 2007 at 11:53 pm
[...] to create your own video sharing service with flash video streaming using only open-source tools.read more | digg story Posted in Uncategorized | Leave a [...]
February 18th, 2008 at 7:42 pm
[...] Using Lighttpd, Mplayer/Mencoder and Flvtool2 to Implement Flash Video Streaming [...]
February 20th, 2008 at 1:08 pm
Есть проблема при конвертации mov (QuickTime) файла в flv. Вот такая команда.
mencoder input.mov -o output.flv -of lavf \
-oac mp3lame -lameopts abr:br=56 -srate 22050 -ovc lavc \
-lavcopts vcodec=flv:vbitrate=500:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 \
i_certify_that_my_video_stream_does_not_use_b_frames
С -nosound работает. То есть как я понял проблема с
аудио кодеком.
Opening audio decoder: [faad] AAC (MPEG2/4 Advanced Audio Coding)
AUDIO: 44100 Hz, 2 ch, s16le, 64.0 kbit/4.54% (ratio: 8000->176400)
Selected audio codec: [faad] afm: faad (FAAD AAC (MPEG-2/MPEG-4 Audio) decoder)
Но итоге получаю ошибку.
Cannot initialize muxer.
Exiting…
Кто-нибудь сталкивался с подобным?
March 30th, 2008 at 7:54 pm
You should probably use flvmeta (http://code.google.com/p/flvmeta/) instead of flvtool2.
It’s a small tool written in C that is much faster than flvtool2, which is written in ruby, and uses way too much memory.