Close Show/hide page

Updated FLV Encoder, 3.5x faster with Alchemy

Thumbnail - Click me
Demo: Record and encode FLV’s from webcam in realtime, using Alchemy

Or, download AIR desktop version

This is an update to FLV Encoder which adds an optional Alchemy routine that’s about 3.5x faster, as well as FileStream support for writing directly to a local file using AIR. The library has been architected in such a way that you can use the package while targeting either the browser (no FileStream support) or AIR, and either Flash 9 (no Alchemy support) or Flash 10 – without getting class dependency compiler errors.

I’ve put the package on Github, along with a couple examples (including the one from the last post). The API has changed a little so be sure to also see the example code below. A method updateDurationMetadata() has been added so the video duration does not have to be declared at the start. Also, a bug where the top-most line of pixels was not being written has been fixed.

Realtime encoding demo:

Because of the increased speed of the Alchemy version, it is now viable to encode FLV’s in realtime as the audio and video is being captured, at least within certain limits. Click on the thumbnail above for an online demo that encodes webcam video and audio to a file at 320×240 in real time. If your system is fast enough, you can keep the framerate set to 15FPS with minimal hiccups. The browser-based version must store the entire FLV in memory before saving to disk, but the equivalent AIR version can save its contents directly to a file so that the only limiting factor is disk space. I’m using a dynamic timing and queuing system to keep video and audio in sync which could be the topic of another post.

Updated usage examples:

[A] To encode an FLV to a ByteArray, start by instantiating ByteArrayFlvEncoder. The rest is similar to the last version, but you can now call updateDurationMetadata() when you’re done to update the duration property in the metadata. Finally, call kill() to prepare the object for garbage collection:

var baFlvEncoder:ByteArrayFlvEncoder = new ByteArrayFlvEncoder(myFrameRate);
	
baFlvEncoder.setVideoProperties(myWidth, myHeight, VideoPayloadMakerAlchemy);
// (Omit the 3rd argument to NOT use Alchemy if you're targeting Flash 9)
baFlvEncoder.setAudioProperties(BaseFlvEncoder.SAMPLERATE_44KHZ, true, false, true);
	
baFlvEncoder.start();
	
baFlvEncoder.addFrame(myBitmapData, myAudioByteArray);
baFlvEncoder.addFrame(myBitmapData, myAudioByteArray); // etc.
	
baFlvEncoder.updateDurationMetadata();
	
saveOutMyFileUsingFileReference( baFlvEncoder.byteArray );
	
baFlvEncoder.kill(); // for garbage collection

[B] To encode an FLV directly to a local file (in AIR), instantiate FileStreamFlvEncoder with a File reference, and open up the exposed FileStream, and then close it when you’re all done:

var myFile:File = File.documentsDirectory.resolvePath("video.flv");
var fsFlvEncoder:FileStreamFlvEncoder = new FileStreamFlvEncoder(myFile, myFrameRate);
fsFlvEncoder.fileStream.openAsync(myFile, FileMode.UPDATE);
	
fsFlvEncoder.setVideoProperties(myWidth, myHeight, VideoPayloadMakerAlchemy);
fsFlvEncoder.setAudioProperties(BaseFlvEncoder.SAMPLERATE_44KHZ, true, false, true);
	
fsFlvEncoder.start();
	
fsFlvEncoder.addFrame(myBitmapData, myAudioByteArray);
fsFlvEncoder.addFrame(myBitmapData, myAudioByteArray); // etc.
	
fsFlvEncoder.updateDurationMetadata();
	
fsFlvEncoder.fileStream.close();

fsFlvEncoder.kill();

A new instance of FlvEncoder should be created for every new FLV to be generated.

If you’re using the Alchemy version, the SWC lives in leelib/util/flvEncoder/alchemy, so be sure add that folder to your project library path. The C++ code is there as well.

Note that the current Alchemy video encoding routine is being done synchronously, which means that although it’s much faster than the regular AS3 version, the main Flash thread must still wait for the Alchemy encoding to be done before continuing. An asynchronous version would allow for a real-time encoding scenario that is more flexible and probably with less ‘dropouts’, and would probably prompt the need an internal queuing system. Anyway, this warrants further development.

- Source code (Github)

Licensed under a Creative Commons Attribution 3.0 License.

100 Responses to “Updated FLV Encoder, 3.5x faster with Alchemy”

  1. I was wondering. Would it be possible to capture the stage or a visual container instead of the camera and send it to an flv?

  2. zanuka says:

    yes i am in the process of adapting it to android and iOS now… so far so good :-)

    thanks again Lee for this excellent utility! the alchemy version is very fast, but it runs much slower on mobile so I’m looking to take the Native Extension route

  3. zanuka says:

    @learningengineer…. yes this is super easy, and lee’s example is already doing it by adding camera/video to the _output sprite, which is a visual display object…

  4. dania says:

    Hi can i use write such a program for only Audio recording with having to check for the webcam when in run it ?
    and whats the difference in size between the resulted flv and the mp3 file ?
    thaaanx

  5. dania says:

    Hi can i write such a program for only Audio recording with having to check for the webcam when in run it ?
    and whats the difference in size between the resulted flv and the mp3 file ?
    thaaanx

  6. Marios says:

    Hello. i am getting this error. But it happens in the middle of the video that i want to export. It works great for some time and then it throws this error.
    Can you help me?
    Thank you in advance!

    RangeError: Error #2006: The supplied index is out of bounds.
    at flash.utils::ByteArray/writeBytes()
    at leelib.util.flvEncoder::VideoPayloadMakerAlchemy/writeAlchemyDataTo()[C:\Users\Marios\Adobe CS5 projects\Flash professional\Eshadow_NEW\Eshadow\src\leelib\util\flvEncoder\VideoPayloadMakerAlchemy.as:111]
    at leelib.util.flvEncoder::VideoPayloadMakerAlchemy/make()[C:\Users\Marios\Adobe CS5 projects\Flash professional\Eshadow_NEW\Eshadow\src\leelib\util\flvEncoder\VideoPayloadMakerAlchemy.as:77]
    at leelib.util.flvEncoder::FlvEncoder/writeVideoTagTo()[C:\Users\Marios\Adobe CS5 projects\Flash professional\Eshadow_NEW\Eshadow\src\leelib\util\flvEncoder\FlvEncoder.as:379]
    at leelib.util.flvEncoder::FlvEncoder/addFrame()[C:\Users\Marios\Adobe CS5 projects\Flash professional\Eshadow_NEW\Eshadow\src\leelib\util\flvEncoder\FlvEncoder.as:193]

  7. Krx says:

    Hello
    Great example.
    I would like to record small 5-10 seconds video messages , left by users on our website.
    Did anyone managed to get this to work on webserver and to get compressed flv files?
    Regards

  8. shammi says:

    hi i am not able to find the example for Updated FLV Encoder, it is amazing that i do not have to wait for encoding. like in the earlier example.

  9. shammi says:

    ok done i un-commented this line in leelibExamples.flvEncoder.webcam.WebcamApp _baFlvEncoder.setVideoProperties(OUTPUT_WIDTH,OUTPUT_HEIGHT, VideoPayloadMakerAlchemy); and it’s working but still taking time to encode. however the example on this page does not wait for encoding at all.

  10. luqman says:

    this is awesome..however is it possible to change this so that it encodes to mp4 (h264)? if so, how?

  11. stauros says:

    could you give the example code for the demo shown above because i have problems encoding in realtime based on the code you give in the description…

  12. Antony says:

    How save audio??

    var baAudio:ByteArray = new ByteArray();
    var seconds:Number = _bitmaps.length / FLV_FRAMERATE;
    _sound.extract(baAudio, seconds * 44000 + 1000);

    _baFlvEncoder.addFrame(_bitmaps[i], baAudio);

    it’s dosn’t work! :((

  13. american gigolo says:

    neither the air nor your browser version are saving the audio, i checked on the browser and the webcam mic is set.

    im very interested in this but i need audio, thanks

  14. ramesh says:

    iam using it for recording my dynamic animation. bt its not working for longer then 6sec files. it`s going under default default timeout period

    Error: Error #1502: A script has executed for longer than the default timeout period of 15 seconds.
    at leelib.util.flvEncoder::VideoPayloadMaker/make()[D:leelib\util\flvEncoder\VideoPayloadMaker.as:58]

  15. american gigolo says:

    anyone willing to get paid a few bucks and work on this to work for me?

  16. M.USAMA says:

    but your output flv is not working in my window media player or any other desktop player only works in flash player why??….

  17. Lauwisme says:

    To what resolution/framerate did you get the air/alchemy version to go before the output got too bad to use? I’m trying to get the best resolution at 25 fps, but that isn’t all that high it would seem…

  18. Aoi says:

    I tried to compile your webcam example code from github, but no audio is being recorded. The SampleData event is never triggered. Please help

  19. freak182 says:

    This is cool stuff…been looking for encoder without using red5 or server stuff…thanks a lot…you rocks!!!!

  20. Prem Kumar says:

    This is awesome .. thanks for making it .. i have done sample on this .. it was fine. but my problem is with the File size , (for 20 sec it is is 66 MB). is there anyway to reduce the file size of the flv . Please help me on this .

    Thanks and Regards ,
    Prem.

  21. doggystash says:

    It seems that the sample for download is not the new one.
    Is there any other way to have the new demo used here?

    Thanks!

  22. jtellier says:

    I am also looking for the newest code, as the AIR version is very different. Any chance that can be updated? Thanks!

  23. harilalkm says:

    Hi
    It’s an awsome demo. I have been searching for this for last one month.

    Is it possible to share the code of real time encoding app , which you are showcased.
    regards
    Harilal K M

  24. Basically to follow up on the up-date of this subject on your internet website and wish to let you know merely how a lot I loved the time you took to create this valuable post. Within the post, you really spoke of how to actually handle this matter with all ease. It would be my pleasure to collect some much more tips from your web page and come as significantly as offer other individuals what I learned from you. Many thanks for your usual terrific effort.

  25. Karzin says:

    This is great! Helped me a lot!

    People, as far as i could test here, the sound will only work above 10.1 version of flash player

  26. mika says:

    Hi there,
    Thank you for sharing this is really nice.
    I tried to compile the helper from C using FlasCC but run into some errors for files missing.
    Do you plan to give more info about the C to swc process by any chance?
    Your help is much appreciated.
    Thanks!

  27. Boris says:

    Good day.

    Tried to connect an example. Did not happen.
    Created a file action.fla. It pointed out the connection class:

    import leelibExamples.flvEncoder.webcam.*;
    var test=new WebcamApp();

    В результате выдает ошибку:
    TypeError: Error #1009: Can not access a property or method of an object reference “null”.
    at leelibExamples.flvEncoder.webcam::WebcamApp()
    at action_fla::MainTimeline/frame1()

    Help, please.

  28. Boris says:

    Hellow. What is bag?

    ArgumentError: Error #2015: Недопустимые данные BitmapData.
    at flash.display::BitmapData/ctor()
    at flash.display::BitmapData()
    at leelibExamples.flvEncoder.webcam::WebcamApp/captureFrame()
    at Function/http://adobe.com/AS3/2006/builtin::apply()
    at SetIntervalTimer/onTimer()
    at flash.utils::Timer/_timerDispatch()
    at flash.utils::Timer/tick()

  29. Boris says:

    Hellow.
    Does anyone have a source code demo / blog / assets / WebcamRealTimeFlvEncoder.swf ?

  30. I just published OGG / Theora and FFmpeg wrappers for AS3, written in Alchemy 2 (FlasCC). It has similar philosophy to Lee’s FLV wrappers, but offer obviously better (even a bit slower) compression. Free for non-commercial use…it’s first version, so if interested to try out /test at the same time head to http://rainbowcreatures.com/product_flashywrappers.php :)

  31. Adan says:

    Hi, I would like to know how do you do the AIR direct encoding and saving into disk. This is the optimum in terms of memmory and performance, and perhaps will allow me save videos of bigger frame-size.

    Can you give me a small clue?
    Thank you!

  32. Adan says:

    OH, wait, is there… written… I was touching the webcam example… sorry!!

  33. Franky says:

    Hi, i will ad in the “jumping ball demo” a moving object with tweener for the later recording file, can you help me to find the right selection in the sample file?

  34. yue says:

    Thanks Lee Felarca. I have the problem is with the File Size of the FLV(for 20 sec, size is 66 mb). I am doing the Rendering on the Client Side itself. So is there anyway to reduce the file size using that library . Is there anyone who worked on this library . Any help would be greatly appreciated.

  35. Adan Levy says:

    Wow
    After using it, I agree with Alchemy as a good name. Pure magic…

  36. Fabio says:

    Any feedback on implementing this with iOS?

    Thanks!

  37. Edward says:

    it doesnt work,,, can you put any example alive!!!

  38. Joao says:

    Amazing work! Could you send me the source from the air desktop version. I couldn´t find a way to make work the FileStreamFlvEncoder version, to record direct to hd. I made with bytearray version.

    Thanks a lot!

    Joao

  39. Denis says:

    Hi Lee,

    I tried your code from Github.
    It works well (congrats)…

    … except that the audio and the video are not in synch (with and without Alchemy).

    In your demo above, you seem to have fix the issue.

    Have you modified the Github code ? Or the option for synching is not called from the Github examples ?

    Thanks by advance,
    Denis

  40. Denis says:

    Sorry Lee,

    You’re code is not responsible for the problem of sync between audio and video.

    After some research, I’ve found that in my AIR project, the activityLevel of the microphone stays at -1 during a second or two at the beginning.

    During this time, the sound is not recorded, only the vidéo.

    Denis

  41. Daniel says:

    Great job, Lee!

    I am using the AIR version, recording 30 seconds of video and audio. When I try to encode it after finished recording, everything goes well (but I can’t have a larger resolution, Flash runs out of memory). But when I try to encode in real time, the audio gets out of sync, although the system is using the same values for the position of the audio ByteArray.

    I noticed you have a resync funcionality in your AIR demo, but I can’t find it on GitHub. Any help would be greatly appreciated.

    Thanks in advance.

  42. Daniel says:

    Actually, my issue was apparently the same as Denis’s. It didn’t look like it was, because the audio got more and more out of synch as the time passed, during playback. But I tryied to call _micUtil.record(); and then used setTimeout to start capturing and encoding 200ms after that. And it solved the issue.

  43. ak says:

    Thanks for the great code lee!! I am using your code and trying to enhance it further. I wanted to know if it is at all possible, to encode and save the flv file on the server in real time, instead of getting saved on the clients side. Or someone else can help me out with this question.

  44. Efren Lugo says:

    How do you compile all the action scripts? I had trying to import on Flash… advice please.

  45. Matt says:

    Anyone have a quick example of how to do video only? I tried following the samples above using Flash CC but I am confused on how the addFrame part works. It shows a comment for //etc there but I am not sure what that is telling me.

  46. Gabriel says:

    Hi,
    i was trying to use some of your code to make a test, but i can’t make it work to record in realtime 15 fps. At 5fps works very well.
    Your example works like a charm @ 25fps.
    Can you tell me what you did to record in 15fps ?

    I tried with timer, but no sucess…

    Thanks,
    Gabriel

  47. DeeDee says:

    Hi and thanks very much for the code. I’m currently working on a project that uploads the byte array to a file on a server and it’s all working ok but the file size is huge – is there any way to compress it before I send it or are there any settings in the flvencoder file that I can change? I don’t mind losing some quality.

  48. Padmanaban says:

    Actually i implement the code in flash works fine but i want to save the web cam feed directly to the file when i click the record button how i can to do that.

  49. Pratik says:

    Hello ,
    You have really done a great coding , that i have not found over the google alternate to this. Thanks .

    Well,
    I would like to record video of 5 min but it stucks when i try to save. Gives an memory error.
    Can you help me how to resolve this issue ?

    Save file using php backend is also fine.

    Thanks and awaiting your response.

    Regards
    pratik b.

  50. Jon says:

    I’m working on something using your flv encoder where I’m recording short 5 second flv’s, and saving it to disk. I then convert them to mp4 and concatenate it to the previous 5 second clip using FFMPEG. I’m experiencing intermittent issues where the appended video will freeze half way through. I’m wondering if anyone else has experienced issues with this or if there are any adjustments that could be made to the settings of the flv encoder to attempt resolve this.
    Here are the commands I’m using to convert to MP4 and to concatenate them.

    ffmpeg -i temp.flv -qscale 0 -pix_fmt yuv420p -ar 22050 -vcodec libx264 temp.mp4 -y

    ffmpeg -y -f concat -i temp_concat_list.txt -c copy ../videos/temp_concat.mp4 -y

    Thanks in advance!

    Jon

Leave a Reply