(树莓派 csi 相机)使用 java 从 raspivid-stdout 读取 h264 数据

use*_*646 4 java stdout inputstream h.264 raspberry-pi

我想编写一个从树莓派 csi 相机读取 h264 流的 java 应用程序。csi 相机的接口是命令行 c 程序“raspivid”,它通常将捕获的视频写入文件。使用选项“-o -”r​​aspivid 将视频写入标准输出,此时我想捕获 h264 流并将其“管道化”而不更改数据。我的第一步是编写一个应用程序,该应用程序从标准输出读取数据并将其写入文件而不更改数据(因此您将获得一个可播放的 .h264 文件)。我的问题是写入的文件总是损坏的,当我用记事本++打开损坏的文件时,我可以看到与可播放的文件相比,有一般不同的“符号”。我认为问题是 InputStreamReader() 类,它将标准输出字节流转换为字符流。我无法为此找到合适的课程。这是我的实际代码:

public static void main(String[] args) throws IOException, InterruptedException
  {
    System.out.println("START PROGRAM");
    try
    {
    Process p = Runtime.getRuntime().exec("raspivid -w 100 -h 100 -n -t 5000 -o -");

    FileOutputStream fos = new FileOutputStream("testvid.h264");
    Writer out = new OutputStreamWriter(fos);
    BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));

    while (bri.read() != -1)
    {
      out.write(bri.read());
    }

    bri.close();
    out.close();
    }
    catch (Exception err)
    {
      err.printStackTrace();
    }
    System.out.println("END PROGRAM");
  }
Run Code Online (Sandbox Code Playgroud)

谢谢!

use*_*646 5

解决了问题!InputStreamReader 不是必需的,并且将字节流转换为字符流,反向转换是不可能的!这是工作代码(将标准输出字节流写入文件):

  public static void main(String[] args) throws IOException
  {
    System.out.println("START PROGRAM");
    long start = System.currentTimeMillis();
    try
    {

      Process p = Runtime.getRuntime().exec("raspivid -w 100 -h 100 -n -t 10000 -o -");
      BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
      //Direct methode p.getInputStream().read() also possible, but BufferedInputStream gives 0,5-1s better performance
      FileOutputStream fos = new FileOutputStream("testvid.h264");

      System.out.println("start writing");
      int read = bis.read();
      fos.write(read);

      while (read != -1)
      {
        read = bis.read();
        fos.write(read);
      }
      System.out.println("end writing");
      bis.close();
      fos.close();

    }
    catch (IOException ieo)
    {
      ieo.printStackTrace();
    }
    System.out.println("END PROGRAM");
    System.out.println("Duration in ms: " + (System.currentTimeMillis() - start));
  } 
Run Code Online (Sandbox Code Playgroud)