bytedeco / javacv

Java interface to OpenCV, FFmpeg, and more
Other
7.51k stars 1.58k forks source link

use java multithread to pull the same one rtsp stream,some is correct some is error with "Could not open input" #1963

Open ayoullf opened 1 year ago

ayoullf commented 1 year ago

javacv version:1.5.8; system:windows10 my code is `public void run() { LOG.info("####the {} rtsp stream:{},is running", count, rtspStream); System.setProperty("org.bytedeco.javacpp.logger", "slf4j"); System.setProperty("org.bytedeco.javacpp.logger.debug", "true"); FFmpegLogCallback.set(); try { grabber = new FFmpegFrameGrabber(rtspStream); grabber.setOption("rtsp_transport", "tcp"); grabber.setOption("stimeout", "2000000"); grabber.setFormat("rtsp");//rtsp FFmpegLogCallback.set(); grabber.start();

        int width = grabber.getImageWidth();
        int height = grabber.getImageHeight();
        if (width == 0 && height == 0) {
            LOG.error("[ERROR]   timeout...");
            return;
        }
        Frame frame = grabber.grabImage();
        while (null == frame) {
            LOG.info("device {} frame is null,execute restart grabber……", count);
            Thread.sleep(100);
            grabber.restart();
            frame = grabber.grabImage();
        }
        String file = fileUrl + File.separator + name;
        if (!FileUtil.exist(file)) {
            FileUtil.mkdir(file);
        }
        ImageIO.write(FrameToBufferedImage(frame), "jpg", new File(fileUrl + File.separator + name + File.separator + count + ".jpg"));
    } catch (FrameGrabber.Exception e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (null != grabber) {
            try {
                grabber.close();
                grabber.release();
            } catch (FrameGrabber.Exception e) {
                e.printStackTrace();
            }
        }
        countDownLatch.countDown();
    }

}

public static BufferedImage FrameToBufferedImage(Frame frame) {
    Java2DFrameConverter converter = new Java2DFrameConverter();
    BufferedImage bufferedImage = converter.getBufferedImage(frame);

// bufferedImage=rotateClockwise90(bufferedImage); return bufferedImage; }` the "rtspStream" is the same,I run with 2 thread is normal,More than 2 threads will report an error. Whether more than two rtsp streams can not be opened at the same time

saudet commented 1 year ago

Some codecs are not thread safe. Try with another codec.

ayoullf commented 1 year ago

thank you!if rtspSream is different,will this problem occur?

saudet commented 1 year ago

I don't think there's any problems relating to multithreading with the socket API, so if some problems occur there, it might be issues with your network.