在Java环境中如何解码H.264视频帧

20

有没有人知道如何在Java环境中解码H.264视频帧?

我的网络摄像头产品支持RTP / RTSP流媒体传输。

我的网络摄像头提供标准的RTP / RTSP服务,同时还支持“HTTP上的RTP / RTSP”。

RTSP端口:TCP 554 RTP起始端口:UDP 5000

5个回答

6

或者使用Xuggler。它适用于RTP、RTMP、HTTP或其他协议,并且可以解码和编码H264和大多数其他编解码器。并且该软件是活跃维护的、免费的、开源的(LGPL)。


通常不建议使用像Xuggler这样的不活跃项目,我建议找一些正在积极开发中的东西。 - Steve Glick
实际上,@ArtClarke开发了它的替代品humble-video :) - Matthieu

6
我找到了一个基于JavaCV的FFmpegFrameGrabber类的非常简单和直观的解决方案。这个库允许你通过Java包装ffmpeg来播放流媒体。
如何使用呢?
首先,你需要下载并安装该库,可以使用Maven或Gradle进行。
这里有一个名为StreamingClient的类,它调用了一个名为SimplePlayer的类,该类具有播放视频的线程。
public class StreamingClient extends Application implements GrabberListener
{
    public static void main(String[] args)
    {
        launch(args);
    }

    private Stage primaryStage;
    private ImageView imageView;

    private SimplePlayer simplePlayer;

    @Override
    public void start(Stage stage) throws Exception
    {
        String source = "rtsp://184.72.239.149/vod/mp4:BigBuckBunny_115k.mov"; // the video is weird for 1 minute then becomes stable

        primaryStage = stage;
        imageView = new ImageView();

        StackPane root = new StackPane();

        root.getChildren().add(imageView);
        imageView.fitWidthProperty().bind(primaryStage.widthProperty());
        imageView.fitHeightProperty().bind(primaryStage.heightProperty());

        Scene scene = new Scene(root, 640, 480);

        primaryStage.setTitle("Streaming Player");
        primaryStage.setScene(scene);
        primaryStage.show();

        simplePlayer = new SimplePlayer(source, this);
    }

    @Override
    public void onMediaGrabbed(int width, int height)
    {
        primaryStage.setWidth(width);
        primaryStage.setHeight(height);
    }

    @Override
    public void onImageProcessed(Image image)
    {
        LogHelper.e(TAG, "image: " + image);

        Platform.runLater(() -> {
            imageView.setImage(image);
        });
    }

    @Override
    public void onPlaying() {}

    @Override
    public void onGainControl(FloatControl gainControl) {}

    @Override
    public void stop() throws Exception
    {
        simplePlayer.stop();
    }
}

SimplePlayer类使用FFmpegFrameGrabber来解码一个frame,然后将其转换为图像并在您的舞台上显示。

public class SimplePlayer
{
    private static volatile Thread playThread;
    private AnimationTimer timer;

    private SourceDataLine soundLine;

    private int counter;

    public SimplePlayer(String source, GrabberListener grabberListener)
    {
        if (grabberListener == null) return;
        if (source.isEmpty()) return;

        counter = 0;

        playThread = new Thread(() -> {
            try {
                FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(source);
                grabber.start();

                grabberListener.onMediaGrabbed(grabber.getImageWidth(), grabber.getImageHeight());

                if (grabber.getSampleRate() > 0 && grabber.getAudioChannels() > 0) {
                    AudioFormat audioFormat = new AudioFormat(grabber.getSampleRate(), 16, grabber.getAudioChannels(), true, true);

                    DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
                    soundLine = (SourceDataLine) AudioSystem.getLine(info);
                    soundLine.open(audioFormat);
                    soundLine.start();
                }

                Java2DFrameConverter converter = new Java2DFrameConverter();

                while (!Thread.interrupted()) {
                    Frame frame = grabber.grab();
                    if (frame == null) {
                        break;
                    }
                    if (frame.image != null) {

                        Image image = SwingFXUtils.toFXImage(converter.convert(frame), null);
                        Platform.runLater(() -> {
                            grabberListener.onImageProcessed(image);
                        });
                    } else if (frame.samples != null) {
                        ShortBuffer channelSamplesFloatBuffer = (ShortBuffer) frame.samples[0];
                        channelSamplesFloatBuffer.rewind();

                        ByteBuffer outBuffer = ByteBuffer.allocate(channelSamplesFloatBuffer.capacity() * 2);

                        for (int i = 0; i < channelSamplesFloatBuffer.capacity(); i++) {
                            short val = channelSamplesFloatBuffer.get(i);
                            outBuffer.putShort(val);
                        }
                    }
                }
                grabber.stop();
                grabber.release();
                Platform.exit();
            } catch (Exception exception) {
                System.exit(1);
            }
        });
        playThread.start();
    }

    public void stop()
    {
        playThread.interrupt();
    }
}

4
您可以使用一个纯Java库叫做JCodec(http://jcodec.org)来实现。解码一个H.264帧就像这样简单:
ByteBuffer bb = ... // Your frame data is stored in this buffer
H264Decoder decoder = new H264Decoder();
Picture out = Picture.create(1920, 1088, ColorSpace.YUV_420); // Allocate output frame of max size
Picture real = decoder.decodeFrame(bb, out.getData());
BufferedImage bi = JCodecUtil.toBufferedImage(real); // If you prefere AWT image

如果您想从容器(如MP4)中读取一个帧,可以使用一个方便的帮助类FrameGrab:
int frameNumber = 150;
BufferedImage frame = FrameGrab.getFrame(new File("filename.mp4"), frameNumber);
ImageIO.write(frame, "png", new File("frame_150.png"));

最后,这里是一个完整的复杂示例:
private static void avc2png(String in, String out) throws IOException {
    SeekableByteChannel sink = null;
    SeekableByteChannel source = null;
    try {
        source = readableFileChannel(in);
        sink = writableFileChannel(out);

        MP4Demuxer demux = new MP4Demuxer(source);

        H264Decoder decoder = new H264Decoder();

        Transform transform = new Yuv420pToRgb(0, 0);

        MP4DemuxerTrack inTrack = demux.getVideoTrack();

        VideoSampleEntry ine = (VideoSampleEntry) inTrack.getSampleEntries()[0];
        Picture target1 = Picture.create((ine.getWidth() + 15) & ~0xf, (ine.getHeight() + 15) & ~0xf,
                ColorSpace.YUV420);
        Picture rgb = Picture.create(ine.getWidth(), ine.getHeight(), ColorSpace.RGB);
        ByteBuffer _out = ByteBuffer.allocate(ine.getWidth() * ine.getHeight() * 6);
        BufferedImage bi = new BufferedImage(ine.getWidth(), ine.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
        AvcCBox avcC = Box.as(AvcCBox.class, Box.findFirst(ine, LeafBox.class, "avcC"));

        decoder.addSps(avcC.getSpsList());
        decoder.addPps(avcC.getPpsList());

        Packet inFrame;
        int totalFrames = (int) inTrack.getFrameCount();
        for (int i = 0; (inFrame = inTrack.getFrames(1)) != null; i++) {
            ByteBuffer data = inFrame.getData();

            Picture dec = decoder.decodeFrame(splitMOVPacket(data, avcC), target1.getData());
            transform.transform(dec, rgb);
            _out.clear();

            AWTUtil.toBufferedImage(rgb, bi);
            ImageIO.write(bi, "png", new File(format(out, i)));
            if (i % 100 == 0)
                System.out.println((i * 100 / totalFrames) + "%");
        }
    } finally {
        if (sink != null)
            sink.close();
        if (source != null)
            source.close();
    }
}

1
工作速度太慢了,每个getFrame()需要一秒钟,而且它执行的解码操作与您相同。 - Nativ

4
我认为最好的解决方案是使用“JNI + ffmpeg”。在我目前的项目中,我需要在基于libgdx的java openGL游戏中同时播放几个全屏视频。我尝试了几乎所有免费库,但没有一个有可接受的性能。所以最终我决定编写自己的jni C代码与ffmpeg一起工作。以下是我的笔记本电脑上的最终表现:
环境: CPU:Core i7 Q740 @1.73G,Video:nVidia GeForce GT 435M, 操作系统:Windows 7 64位,Java:Java7u60 64位 视频:h264rgb / h264编码,无声音,分辨率:1366 * 768 解决方案:解码:JNI + ffmpeg v2.2.2,上传到GPU:使用lwjgl更新openGL纹理 性能:解码速度:700-800FPS,纹理上传:每帧约1ms。
我只花了几天时间完成了第一个版本。但第一个版本的解码速度只有大约120FPS,上传时间大约为每帧5毫秒。经过几个月的优化,我得到了这个最终性能和一些额外的功能。现在我可以同时播放多个高清视频而不会出现任何缓慢。
我的游戏中大多数视频都有透明背景。这种透明视频是一个mp4文件,其中有2个视频流,一个流存储h264rgb编码的rgb数据,另一个流存储h264编码的alpha数据。因此,要播放alpha视频,我需要解码2个视频流并将它们合并然后上传到GPU。结果,我可以在我的游戏中同时播放几个透明高清视频和一个不透明高清视频。

我为Android创建了一个应用程序,它可以记录摄像头拍摄的视频并使用RTP / RTSP发送。我使用了MediaRecorder类来捕获和编码从相机中获取的视频。我使用VLC测试了我的实现,并且它正常工作。我尝试创建一个使用Java的客户端来接收负载96。例如,我尝试使用Toolkit类,但它的方法createImage(payload,0,payloadLength)仅从作为byte []的负载中提取JPG或PNG。我还尝试使用Xuggler,但我只找到了使用MP4文件的示例,我需要从byte []解码。(我不懂C语言) - Teocci

0

9
JMF已经被放弃多年,因此长期项目不应依赖它。但如果只是一次性的事情,我同意JMF是一个不错的解决方案。尽管我认为JMF只支持H263。 - Yuvi Masory
3
如果JMF不再使用,有什么可以替代它的工具? - kevindaub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接