VR中的IPWebcam滞后问题(Unity 2019)

时间:2019-07-18 09:37:51

标签: c# unity3d webcam virtual-reality

我正在一个VR项目中,我有2台显示器显示2个不同的IPWebCam,我的问题是超级笨拙,如果要在我的代码中添加多线程来修复它,或者有什么问题,我一直在徘徊我做错了。

我将统一版本2019.1.8f1与oculus rift 2配合使用。

using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.IO;
using UnityEngine.UI;

public class WebStream : MonoBehaviour
{
    public MeshRenderer frame;

    public string sourceURL;
    private Texture2D texture;
    private Stream stream;

    private void Start ()
    {
        GetVideo ();
    }

    public void GetVideo ()
    {
        texture = new Texture2D (2, 2);
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create (sourceURL);
        WebResponse resp = req.GetResponse ();
        stream = resp.GetResponseStream ();
        StartCoroutine (GetFrame ());
    }

    IEnumerator GetFrame ()
    {
        Byte[] JpegData = new Byte[100000];

        while (true) {
            int bytesToRead = FindLength (stream);
            if (bytesToRead == -1) {
                print ("End of stream");
                yield break;
            }

            int leftToRead = bytesToRead;

            while (leftToRead > 0) {
                leftToRead -= stream.Read (JpegData, bytesToRead - leftToRead, leftToRead);
                yield return null;
            }

            MemoryStream ms = new MemoryStream (JpegData, 0, bytesToRead, false, true);

            texture.LoadImage (ms.GetBuffer ());
            frame.material.mainTexture = texture;
            stream.ReadByte ();
            stream.ReadByte ();
        }
    }

    int FindLength (Stream stream)
    {
        int b;
        string line = "";
        int result = -1;
        bool atEOL = false;

        while ((b = stream.ReadByte ()) != -1) {
            if (b == 10)
                continue;
            if (b == 13) {
                if (atEOL) {
                    stream.ReadByte ();
                    return result;
                }
                if (line.StartsWith ("Content-Length:")) {
                    result = Convert.ToInt32 (line.Substring ("Content-Length:".Length).Trim ());
                } else {
                    line = "";
                }
                atEOL = true;
            } else {
                atEOL = false;
                line += (char)b;
            }
        }
        return -1;
    }
}

如果可能的话,我想在此代码中插入多线程,以期解决滞后问题...

0 个答案:

没有答案