Go语言 multipart/x-mixed-replace PNG流始终显示前一帧

mgdq6dx1  于 9个月前  发布在  Go
关注(0)|答案(4)|浏览(119)

在制作了一个通过multipart/x-mixed-replaceContent-Type头将PNG图像流传输到浏览器的程序后,我注意到只有前一帧显示在<img>标记中,而不是最近发送的帧。
这种行为非常烦人,因为我只在图像更改为保存带宽时发送更新,这意味着在我等待更新时屏幕上会出现错误的帧。
具体来说,我使用的是Brave浏览器(基于chromium),但由于我已经尝试了上下两种“屏蔽”,我认为这个问题至少也会发生在其他基于chromium的浏览器中。
搜索该问题只产生一个相关结果(和许多不相关的)这是this HowToForge线程,没有回复。同样,我也认为这个问题与缓冲有关,但我确保刷新缓冲区无济于事,与线程中的用户非常相似。用户确实报告说它在他们的一个服务器上工作,而不是另一个,这让我相信它可能与特定的HTTP头或其他沿着这些行的东西有关。我的第一个猜测是Content-Length,因为浏览器可以从中判断图像何时完成,但它似乎没有任何效果。
所以本质上,我的问题是:**有没有一种方法可以告诉浏览器显示最新的multipart/x-mixed-replace**而不是之前的那个?如果这不是标准行为,原因是什么?
当然,这里是相关的源代码,虽然我想这更像是一个普通的HTTP问题,而不是与代码有关的问题:

服务器端

package routes

import (
    "crypto/md5"
    "fmt"
    "image/color"
    "net/http"
    "time"

    brain "path/to/image/generator/module"
)

func init() {
    RouteHandler{
        function: func(w http.ResponseWriter, r *http.Request) {
            w.Header().Set("Content-Type", "multipart/x-mixed-replace; boundary=frame")
            w.Header().Set("Cache-Control", "no-cache") // <- Just in case
            w.WriteHeader(200)

            // If the request contains a token and the token maps to a valid "brain", start consuming frames from
            // the brain and returning them to the client
            params := r.URL.Query()
            if val, ok := params["token"]; ok && len(val) > 0 {
                if b, ok := SharedMemory["brains"].(map[string]*brain.Brain)[val[0]]; ok && !b.CheckHasExit() {
                    // Keep a checksum of the previous frame to avoid sending frames which haven't changed. Frames cannot
                    // be compared directly (at least efficiently) as they are slices not arrays
                    previousFrameChecksum := [16]byte{}

                    for {
                        if !b.CheckHasExit() {
                            frame, err := b.GetNextFrame(SharedMemory["conf"].(map[string]interface{})["DISPLAY_COL"].(color.Color))
                            if err == nil && md5.Sum(frame) != previousFrameChecksum {
                                // Only write the frame if we succesfully read it and it's different to the previous
                                _, err = w.Write([]byte(fmt.Sprintf("--frame\r\nContent-Type: image/png\r\nContent-Size: %d\r\n\r\n%s\r\n", len(frame), frame)))
                                if err != nil {
                                    // The client most likely disconnected, so we should end the stream. As the brain still exists, the
                                    // user can re-connect at any time
                                    return
                                }
                                // Update the checksum to this frame
                                previousFrameChecksum = md5.Sum(frame)
                                // If possible, flush the buffer to make sure the frame is sent ASAP
                                if flusher, ok := w.(http.Flusher); ok {
                                    flusher.Flush()
                                }
                            }
                            // Limit the framerate to reduce CPU usage
                            <-time.After(time.Duration(SharedMemory["conf"].(map[string]interface{})["FPS_LIMITER_INTERVAL"].(int)) * time.Millisecond)
                        } else {
                            // The brain has exit so there is no more we can do - we are braindead :P
                            return
                        }
                    }
                }
            }
        },
    }.Register("/stream", "/stream.png")
}

字符串

客户端(start()运行在onload主体中)

function start() {
    // Fetch the token from local storage. If it's empty, the server will automatically create a new one
    var token = localStorage.getItem("token");
    // Create a session with the server
    http = new XMLHttpRequest();
    http.open("GET", "/startsession?token="+(token)+"&w="+(parent.innerWidth)+"&h="+(parent.innerHeight));
    http.send();
    http.onreadystatechange = (e) => {
        if (http.readyState === 4 && http.status === 200) {
            // Save the returned token
            token = http.responseText;
            localStorage.setItem("token", token);
            // Create screen
            var img = document.createElement("img");
            img.alt = "main display";
            // Hide the loader when it loads
            img.onload = function() {
                var loader = document.getElementById("loader");
                loader.remove();
            }
            // Start loading
            img.src = "/stream.png?token="+token;
            // Start capturing keystrokes
            document.onkeydown = function(e) {
                // Send the keypress to the server as a command (ignore the response)
                cmdsend = new XMLHttpRequest();
                cmdsend.open("POST", "/cmd?token="+(token));
                cmdsend.send("keypress:"+e.code);
                // Catch special cases
                if (e.code === "Escape") {
                    // Clear local storage to remove leftover token
                    localStorage.clear();
                    // Remove keypress handler
                    document.onkeydown = function(e) {}
                    // Notify the user
                    alert("Session ended succesfully and the screen is inactive. You may now close this tab.");
                }
                // Cancel whatever it is the keypress normally does
                return false;
            }
            // Add screen to body
            document.getElementById("body").appendChild(img);
        } else if (http.readyState === 4) {
            alert("Error while starting the session: "+http.responseText);
        }
    }
}

p4rjhz4m

p4rjhz4m1#

多部分MIME消息中的部分以MIME报头开始,以边界结束。在第一个真实的部分之前有一个边界。这个初始边界关闭MIME前导。
你的代码假设一个部分以边界开始。基于这个假设,你首先发送边界,然后是MIME头,然后是MIME体。然后你停止发送,直到下一个部分准备好。因此,只有当你发送下一个部分时,一个部分的结束才会被检测到,因为只有这样你才发送前一个部分的结束边界。
为了解决这个问题,你的代码应该首先发送一个边界来结束MIME前导。对于每个新的部分,它应该发送MIME头,MIME体,然后发送边界来结束这个部分。

cvxl0en2

cvxl0en22#

我遇到了同样的问题:使用multipart/x-mixed-replace时有1帧延迟
这个问题似乎出现在Chrome中,它似乎与Chrome no longer supportmultipart/x-mixed-replace资源有关。这个问题在Firefox中不存在。
所以,“欺骗”Chrome显示视频流的唯一方法是将每个图像发送两次,或者接受将有1帧延迟。

rqqzpn5f

rqqzpn5f3#

这是Chrome的问题。在Firefox中,它按预期工作。
我用下面的方法解决了这个问题C# example

var chromeWorkaround = Encoding.UTF8.GetBytes($"\r\n--{Boundary}\r\n\r\n--{Boundary}\r\n");

字符串
把这个附加到你的流中,它似乎会强制Chrome立即渲染。
我在这里报告:https://bugs.chromium.org/p/chromium/issues/detail?id=1250396

whlutmcx

whlutmcx4#

我设法让它发送图像立即没有1帧延迟与谷歌Chrome发送以下序列:

def frame_generator():
    image = None

    buf = BytesIO()
    buf.write(b"Content-Type: image/jpeg\r\n\r\n")
    yield buf.getvalue()

    while True:
        image = self.get_image()
        img = Image.fromarray(image)

        buf = BytesIO()
        img.save(buf, "JPEG")
        buf.write(b"\r\n--frame\r\n")
        buf.write(b"Content-Type: image/jpeg\r\n\r\n")
        yield buf.getvalue()

字符串

相关问题