Giter Club home page Giter Club logo

rtsp-ffmpeg's Introduction

rtsp-ffmpeg

Lazy Node.js FFMpeg wrapper for streaming RTSP into MotionJPEG. It runs FFMpeg process only when someone is subscribed to its data event. Every data event contains one image Buffer object.

Installation

  1. Download FFmpeg to your local machine.

  2. Install package in your project npm install rtsp-ffmpeg

Sample

With socket.io library.

Server:

const app = require('express')(),
  server = require('http').Server(app),
  io = require('socket.io')(server),
  rtsp = require('rtsp-ffmpeg');
server.listen(6147);
var uri = 'rtsp://freja.hiof.no:1935/rtplive/definst/hessdalen03.stream',
  stream = new rtsp.FFMpeg({input: uri});
io.on('connection', function(socket) {
  var pipeStream = function(data) {
    socket.emit('data', data.toString('base64'));
  };
  stream.on('data', pipeStream);
  socket.on('disconnect', function() {
    stream.removeListener('data', pipeStream);
  });
});
app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

Client (index.html):

NB!

this is not efficient example, but simple. For drawing images on canvas please look at this example by Seikon:

<img id="img">
<script src="/socket.io/socket.io.js"></script>
<script>
	var img = document.getElementById('img'),
		socket = io('');
	socket.on('data', function(data) {
		img.src = 'data:image/jpeg;base64,' + data;
	});
</script>

For more detailed example look at /example/server.js For the large resolution images or IP cameras example check /example/server-canvas.js

FFMpeg

  var ffmpeg = new FFMpeg({
    input: 'rtsp://localhost' // stream uri
    , rate: 10 // output framerate (optional)
    , resolution: '640x480' // output resolution in WxH format (optional)
    , quality: 3 // JPEG compression quality level (optional)
  });

If you have an error Error: spawn ffmpeg ENOENT, you should first install ffmpeg package. After that, if the starup command differs from ffmpeg, you can change it in the static property like this, for example:

FFMpeg.cmd = 'C:\\ffmpeg.exe';

rtsp-ffmpeg's People

Contributors

agsh avatar bitdeli-chef avatar igkvl avatar jeronimoek avatar pacozaa avatar seikon avatar silverfire avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rtsp-ffmpeg's Issues

audio

i'm probably barking up the wrong tree here but is there a way to pull audio too or will this only parse the visual stream?

[Windows] Unrecognized option updatefirst

Hello,

On windows plateform, running the provided example give the following error :

Unrecognized option updatefirst

Then if I comment the line , '-updatefirst', '1' on rtsp-ffmpeg.js I get another error :

Error: Trailing options were found on the commandline.

Any chance to get a fix for this please ?

Regards,
Zombitch

About Currupted Img

Hi, I try to use dynamic link to change the camera screen. But the result is this

img

qq 20170801162202

this is my code

var rtsp = require('rtsp-ffmpeg');
var uri = 'rtsp://xxxx:[email protected]:554/h264/ch1/main/av_stream',
    stream = new rtsp.FFMpeg({
        input: uri,
        rate: 10,
        resolution: '640x480',
        quality: 3
    });


 io.on('connection', socket => {
  console.log('connection')
    var pipeStream = function(data) {
      socket.emit('data', new Buffer(data).toString('base64'));
    };
    stream.on('data', pipeStream);
    socket.on('URI', data => {
      console.log(data);
      uri = `rtsp://${data.userName}:${data.passWord}@${data.ip}:${data.RTSP}/h264/ch1/main/av_stream`
      stream.input = uri;
      console.log(stream.input)
      stream.restart()
    })
    socket.on('disconnect', function() {
      stream.removeListener('data', pipeStream);
    });
}) 

please tell me where am i wrong. :)

Restart method

I notice that the restart method was not declared as stop/start on the prototype... Is that normal ?

See line 111:

FFMpeg.restart = function()

When replaced by

FFMpeg.prototype.restart = function()

I can restart the streaming if needed.

Resolution setting does not work

The resolution setting does not work currently: the setting is completed ignored.

The reason is that the code places the scaling flag (-s XXX) after the pipe flag (-), which makes it ignored:

return this.arguments.concat(
  [ <other flags> ]
  , [ <other flags> , '-']
  , this.resolution ? ['-s', this.resolution] : []
);

To fix, I simply moved the resolution flag before the pipe-flag:

return this.arguments.concat(
  [ <other flags> ]
  , this.resolution ? ['-s', this.resolution] : []
  , [ <other flags> , '-']
);

How to autenticate to rtps

I have a IP Camera whose url to start streaming is:

rtsp://192.168.1.168:80/ch0_0.264

But after var stream = new rtsp.FFMpeg({input:uri}), I need to autenticate with RTPS protocol before start streaming. How can I do it this with this library?

Thank you in advance!

How do I switch RTSP streams?

I want to switch the camera screen with the button on the client side. So i did this.

code

consle

but the client didn't change. am i did wrong? please tell me the right way.

Add way to include additional ffmpeg flags

The library is a nice wrapper around receiving frames from ffmpeg, but it's a hassle when you want to include an extra flag for ffmpeg, but the library has no way to do so.

Perhaps an options.additionalFlags property (which is appended to the arguments list -- well, just before the pipe-flag, as mentioned in my other issue) would be sufficient.

Examples...

Hi, i'm trying your libraries here. but i confused how to run it.
what i do is run node examples\server.js then run browser points to http://localhost:6147
but it doesnt do anything.
try to debug with firebug, and i've got many request aborted.

Thanks

Object.observer error

Hi,

Latest ffmpeg is correctly install and i have this if i require rtsp-ffmpeg on my server.js. Any idea ?

C:\...\node_modules\rtsp-ffmpeg\lib\rtsp
-ffmpeg.js:34
                Object.observe(this, observer.bind(this));
                       ^

TypeError: Object.observe is not a function
    at new FFMpeg (C:\Users\Wifsimster\Documents\GitHub\overwatch\node_modules\r
tsp-ffmpeg\lib\rtsp-ffmpeg.js:34:10)
    at Object.<anonymous> (C:\Users\Wifsimster\Documents\GitHub\overwatch\server
.js:39:14)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

Event stream.on is never fired

Hi, I'm trying to run your server example. Whether I left the URLs unchanged or if I change it to my cameras streams, the socket events fire up as expected, but not the On event of the Stream object. Can you help me pls? My cameras URL are like this: rtsp://192.168.1.48:554/profile1. Thank you.

RTSP H264 stream no image output no error, how to turn error log on

My stream source is in RTSP protocol and H264 encode from camera, tested with VLC is OK, but use example/server.js and select cam3(my own cam) there is no image output, no error output, if I select cam0, its OK.
I add console.log before wsocket.emit('data', data); in example/server.js, and I can see console.log is not called when use cam3(my own cam).

I see this in ../lib/rtsp-ffmpeg.js


FFMpeg.prototype._args = function() {
        return this.arguments.concat([
                '-loglevel', 'quiet'

So, how to turn loglevel to highest

Not Work

Hi i can try to execute the example server but i've this error... can anyone help me?
tnx

rtsp-ffmpeg.js:89
throw new Error(data);
^

Error: ffmpeg version N-91441-g3a2d21bc5f Copyright (c) 2000-2018 the FFmpeg developers
built with gcc 7.3.0 (GCC)
configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-bzlib --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth

at Socket.<anonymous> (D:\workspace\bitbucket\webrtc\rtsp-ffmpeg\node_modules\rtsp-ffmpeg\lib\rtsp-ffmpeg.js:89:9)
at Socket.emit (events.js:182:13)
at addChunk (_stream_readable.js:279:12)
at readableAddChunk (_stream_readable.js:264:11)
at Socket.Readable.push (_stream_readable.js:219:10)
at Pipe.onread (net.js:636:20)

Windows:NSSM: FFMpeg executable wasn't found

Hi,
OS: Windows10
FFmpeg installed correctly

The app works if run via cmd.exe
If install the app as a service via NSSM I get the next error:

d:\app\Node\rest\rtsp-api-main\node_modules\rtsp-ffmpeg\lib\rtsp-ffmpeg.js:117
			throw new Error('FFMpeg executable wasn\'t found. Install this package and check FFMpeg.cmd property');
			^

Error: FFMpeg executable wasn't found. Install this package and check FFMpeg.cmd property
    at ChildProcess.<anonymous> (d:\app\Node\rest\rtsp-api-main\node_modules\rtsp-ffmpeg\lib\rtsp-ffmpeg.js:117:10)
    at ChildProcess.emit (events.js:315:20)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
    at onErrorNT (internal/child_process.js:465:16)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)

Html5 video compatibility

Hello,
I'm trying to use your library to run video in a html5 video player

But unfortunately I'm not succeeding, would you have an example of playing videos in html5?

How to run multiple stream in FFMPEG in RTSP?

Hello,

Suppose I have two media stream
https://localhost:6147/?url=rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov and
https://localhost:6147/?url=rtsp://ipcam.stream:8554/bars

Now, I want to run both streams at the same time with different-different browsers. But write now the output is coming common stream in both browsers and "I want to get output is a different stream with different browser at a time"

How can I manage? Any help would be very appreciated!

Keep stream alive?

Is there a way to keep the stream alive even when no clients are connected? Working on a UI for my CCTV system and every time I switch pages the stream drops out and I end up waiting a long time for the stream to come back up.

Volatile messages

I suggest a small change, case to a certain client is not ready to receive messages (network slowness or other issues)..

Use "volatile" messages:
socket.volatile.emit('data', data.toString('base64'));

If the client doesn't receive all "frames", the application will not be affected.

Stream not terminated properly by FFMpeg.stop (on Windows)

In my program, I have buttons to start and stop a "preview" of the selected camera. The first time previewing is run, the stream loads fine -- ffmpeg starts up, receives the data, and retransmits it to my NodeJS program in a format it can understand.

However, if I then stop the stream:

ffmpegInstance.removeListener("data", listener); // calls stop()

...and then start a new stream within about 30 seconds, that second stream fails to load.

Camera model: Reolink C2 (https://www.amazon.com/gp/product/B01LS71KNO)

I did a variety of additional tests to try to narrow down what the problem was.

Some observations:

  1. After FFMpeg.stop() was called, all ffmpeg streams from my network camera would fail for the next ~30 seconds -- including external ffmpeg launches from cmd, which just write to a file.
  2. It's not just an issue of the camera needing time between streams or something, because I can start and stop overlapping and "right after each other" streams, as many as I want, so long as they're all done from those external cmd-launched ffmpeg instances. (rather than being preceded by a stream for which FFMpeg.stop() is called)
  3. The situation remains the same, even if I exactly match the command-line options between the FFMpeg spawned-process and the from-cmd spawned-process. In other words, it's definitely not an issue with what flags are passed.
  4. The issue also occurs if I force-stop the ffmpeg process. (either by killing the process in task manager, or pressing ctrl+c in the console from which my parent program is run)

So what are the errors that occur in the ffmpeg process, specifically?
Well, lots of lines like this:

[mp4 @ 000001ec843da040] Non-monotonous DTS in output stream 0:1; previous: 1022089453, current: 101517; changing to 1022089454. This may result in incorrect timestamps in the output file.
[rtsp @ 000001ec83b4d840] RTP: PT=61: bad cseq 414e expected=ca0a
[mp4 @ 000001ec843da040] Non-monotonous DTS in output stream 0:0; previous: 2774137739, current: 567874; changing to 2774137740. This may result in incorrect timestamps in the output file.
[mp4 @ 000001ec843da040] Non-monotonous DTS in output stream 0:0; previous: 2774137740, current: 1521704688; changing to 2774137741. This may result in incorrect timestamps in the output file.
[rtsp @ 000001ec83b4d840] RTP: PT=60: bad cseq a5b6 expected=4e9b
[rtsp @ 000001ec83b4d840] RTP: PT=60: bad cseq 4e9c expected=a5b8
[mp4 @ 000001ec843da040] Non-monotonous DTS in output stream 0:0; previous: 2774137741, current: 573904; changing to 2774137742. This may result in incorrect timestamps in the output file.
[rtsp @ 000001ec83b4d840] RTP: PT=60: bad cseq a5b9 expected=4e9e
[rtsp @ 000001ec83b4d840] RTP: PT=60: bad cseq 4e9f expected=a5bb
[rtsp @ 000001ec83b4d840] RTP: PT=60: bad cseq a5bc expected=4ea1
[rtsp @ 000001ec83b4d840] RTP: PT=60: bad cseq 4ea2 expected=a5be

Anyway, observations 3 and 4 were interesting, as they seemed to indicate that the problem was a failure of rtsp-ffmpeg to properly close down the stream or something.

And indeed, that is what I found. After hours of debugging, I finally figured out how to fix the issue:

FFMpeg.prototype.stop = function() {

	// replace this...
	//this.child.kill();
	
	// with this...
	this.child.stdin.write("q\r\n");

	delete this.child;
	this.emit('stop');
};

With the change above, the function still causes the process to close, but apparently it does it more "gracefully" -- allowing the ffmpeg process to do some cleanup which is apparently required for an RTSP stream (over TCP), in order for the subsequent stream to not have issues.

I've confirmed that the fix above is what solves the issue for me. Though keep in mind that I'm on Windows, so perhaps this issue doesn't show up on other platforms. But in any case, it was a super annoying bug, which I'm hoping can get fixed in this repo so others won't have to hit it.

Some posts by another user (and others) who seem to have hit the same issue:

Old bug ticket for ffmpeg, which seems somewhat similar but for the UDP protocol, and fixed years ago: (not that relevant solution-wise, but similar symptoms)

EDIT: I forgot that you also have to comment out the part below, otherwise the library spawns a new ffmpeg process after the first one gracefully exits (and then when the parent program exits, the second ffmpeg instance abruptly exits, causing the same problem -- just at a later point):

// comment out the below part
/*this.child.on('close', function(code) {
	if (code === 0) {
		setTimeout(FFMpeg.prototype.start.bind(this), 1000);
	}
}.bind(this));*/

High Memory Footprint, How To Change Video To Lowest Quality

screenshot 2018-09-17 09 07 32

We're running a 3 * 3 camera setup rotating by 9 cams on a 10 second interval. The issue we're having is the memory footprint is hovering around 800 MB. Is this normal? How can we reduce it? Perhaps quality settings? Can you explain in better detail the effects of the configurations settings ie: new rtsp.FFMpeg({input: uri, resolution: '640x360', quality: 12}) <--- This part!

Thanks!

corrupted images

hi, I am getting corrupted/chopped images. what might be causing this, I am trying to build home surveillance system on raspberry pi with some cheap chinese ip cameras. video on vlc doesn't seem to be flaky or anything. I tried websocket example and tried to save images do disk, most of the time I get corrupted or chopped images. so what might be the problem?

Streamming is lagging and after a while server crash

I run your example but i found a lot of bugs there. When u declare the stream
var stream = new rtsp.FFMpeg({ input: uri } there is nowhere any parameter about latency (maybe no-cache option). Your example need improvement and as i saw from other issues too you have to reply them. Best regards

ffmpeg ENONET

const url = 'rtsp://user:[email protected]:554';
const stream = new rtsp.FFMpeg({input: url});

io.on('connection', function(socket) {
console.log('user');
var pipeStream = function(data) {
socket.emit('data', data.toString('base64'));
};
stream.on('data', pipeStream);
socket.on('disconnect', function() {
stream.removeListener('data', pipeStream);
});
});

and client

<script src="/socket.io/socket.io.js"></script> <script> var img = document.getElementById('img'), socket = io(); socket.on('data', function(data) { img.src = 'data:image/jpeg;base64,' + data; }); </script>

I get this error
events.js:160
throw er; // Unhandled 'error' event
^

Error: spawn ffmpeg ENOENT
at exports._errnoException (util.js:1018:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
at onErrorNT (internal/child_process.js:367:16)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)

plese help! Thanks

High resolution video playback

When I try to playback 4k video from my cam using the example code, it show only part of the video in the screen.
2017-07-14_172021
How can I fix it? Thanks!

P.S.: I had tried 1080p also same issue. I had changed to 704*576 and work perfectly. However I need to playback at lease 1080p for my project.

Enhancement: Allow to use custom ffmpeg params

I had to customize the lib to be able to use parameter like "-vf crop=ih:ih:(iw-ih)/2:0, transpose=2" in FFMpeg.prototype._args method.

It could be good to expose a way for the user to use custom parameters... A callback ? A generic array that will be concat to existing params ?

Could you do it for me ? :-D

spawn ffmpeg ENOENT

Hi,

I have been trying to find the solution to this error for weeks now :(

events.js:182
throw er; // Unhandled 'error' event
^

Error: spawn ffmpeg ENOENT
at exports._errnoException (util.js:1024:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:192:19)
at onErrorNT (internal/child_process.js:374:16)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)

I am using the example on your github page and this is the error I get...

Please can you give me some assistance in the matter...

Thanx.

How can I add more rtsp address?

First of all, thanks for good code.

I have some problems now.
in your code, "var cams" in "server.js" are hardcoded.

var cams = ['rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov']

Can I enter the rtsp address for additional streaming on the web?
notitle

As shown in the picture, I want to create a button and add rtsp

Plz.. I really want know how can i solve this problem :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.