如何使用.NET Core解析MPEG视频流 [英] How to Parse an MPEG Video Stream using .NET Core

查看:32
本文介绍了如何使用.NET Core解析MPEG视频流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于个人项目,我试图从IP摄像机的MPEG流中读取数据,并在收到的各个帧上执行某些计算机视觉任务(使用.NET Core 2.2).

For a personal project, I am attempting to read from a IP Camera's MPEG stream and perform some computer-vision tasks on the individual frames I receive (Using .NET Core 2.2).

我对相机的MPEG端点执行 GET 请求,并且返回了 multipart/x-mixed-replace 响应,该响应持续流传输看起来是单个帧的内容作为JPEG图像.

I perform a GET request to the Camera's MPEG endpoint and I'm returned a multipart/x-mixed-replace response that continually streams what appear to be individual frames as JPEG images.

我难以理解的是从多部分响应中解析出帧的正确方法-如何对于我来说,获取帧并不重要,如果有更好的解析方法这种流,我当然愿意改变-视频检索/处理对我来说是一个全新的世界:)

What I'm having trouble understanding is the correct way to parse out the frames from the multi-part response - how the frames are retrieved is unimportant to me, if there's a better way to parse this kind of stream, I'm certainly open to change - video retrieval/processing is a whole new world for me :)

供参考:

MPEG端点:

GET http://192.168.0.14/mjpeg.cgi

示例响应标题:

Content-Type: multipart/x-mixed-replace;boundary=--video boundary--

示例响应正文:

Content-length: 41142
Date: 02-02-2019 12:43:19 AM
Content-type: image/jpeg

[payload]

--video boundary--
Content-length: 41220
Date: 02-02-2019 12:43:19 AM
Content-type: image/jpeg

[payload]

--video boundary--

我到目前为止所拥有的:

var client = new HttpClient() {
    BaseAddress = new Uri(streamUrl)
};

var stream = await client.GetStreamAsync(resource);

using (var streamReader = new StreamReader(stream)) {                
    while(true) {
        await GetFrameStart(streamReader);
        var frame = await ReadFrame(streamReader);

        // Get byte[] from returned frame above and construct image
    };
}

// ---

// Fast forward to the start of the Frame's bytes
static async Task GetFrameStart(StreamReader reader) {
    string buffer = null;
    while (buffer != string.Empty) {
        buffer = await reader.ReadLineAsync();
    }
}

// Read entire byte array until the video boundary is met
static async Task<String> ReadFrame(StreamReader reader) {
    string result = string.Empty;
    string line = null;

    while(!isBoundary(line)) {
        line = await reader.ReadLineAsync();
        if (!isBoundary(line)) result += line;
    };

    return result;
}

上面的代码似乎在给我还每一帧的单独[有效负载],但是如果我将字符串转换为字节并写入磁盘时,该图像不是有效的jpeg:

The above seems to be giving me back the individual [payload] of each frame, however if I when I convert the string to bytes and write to disk, the image is not a valid jpeg:

var bytes = Encoding.UTF8.GetBytes(frame);

using (var fs = new FileStream("test.jpeg", FileMode.Create, FileAccess.Write)) {
    fs.Write(bytes, 0, bytes.Length);
}

推荐答案

您可以使用有关更多信息,请参见此答案:

See this Answer for more info:

希望这会有所帮助.

这篇关于如何使用.NET Core解析MPEG视频流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆