从外部服务流媒体视频

本文关键字:视频 流媒体 服务 从外部 | 更新日期: 2023-09-27 18:10:46

我正在做一个项目(服务器端),我需要流数据(视频,大文件)到客户端。

这在ByteRangeStreamContent上工作得很好,因为我从磁盘提供文件,并且可以创建一个可搜索的流(FileStream)。

    if (Request.Headers.Range != null)
    {
                try
                {
                        HttpResponseMessage partialResponse = Request.CreateResponse(HttpStatusCode.PartialContent);
                        partialResponse.Content = new ByteRangeStreamContent(fs, Request.Headers.Range, mediaType);
                        return partialResponse;
                }
                catch (InvalidByteRangeException invalidByteRangeException)
                {
                        return Request.CreateErrorResponse(invalidByteRangeException);
                }
     }
     else
     {
                    response.Content = new StreamContent(fs);
                    response.Content.Headers.ContentType = mediaType;
                    return response;
     }

但是,我将文件提供程序从磁盘移动到外部服务。该服务允许我获取数据块(范围{0}-{1})。

当然,不可能在内存中下载整个文件,然后为ByteRangeStreamContent使用MemoryStream,原因很明显(太多的并发下载将在某个时刻消耗所有可用内存)。

我找到了这篇文章https://vikingerik.wordpress.com/2014/09/28/progressive-download-support-in-asp-net-web-api/,作者说:

我对我的库的一个修改请求是只支持读取需要的数据并发送出去,而不是打开一个流完整的数据。我不确定这能买到什么,直到用户指出他们正在从WCF流中读取资源数据哪个不支持查找,需要读取整个流到MemoryStream中,以便允许库生成输出。

这个限制在这个特定的对象中仍然存在,但是有一个解决方案。而不是使用ByteRangeStreamContent,您可以而是使用ByteArrayContent对象。因为大多数人RANGE请求将针对单个开始和结束字节,您可以拉从HttpRequestMessage获取范围,只检索您需要的字节需要并将其作为字节流发送回来。您还需要添加CONTENT-RANGE报头,并将响应码设置为206(PartialContent),但这可能是一个可行的替代方案(尽管我对于不想要或不能轻易获得的用户,我还没有测试过兼容流对象。

所以,我的问题基本上是:我怎么做呢?

从外部服务流媒体视频

我终于做到了。

方法如下:

自定义实现stream:

public class BufferedHTTPStream : Stream
    {
        private readonly Int64 cacheLength = 4000000;
        private const Int32 noDataAvaiable = 0;
        private MemoryStream stream = null;
        private Int64 currentChunkNumber = -1;
        private Int64? length;
        private Boolean isDisposed = false;
        private Func<long, long, Stream> _getStream;
        private Func<long> _getContentLength;
        public BufferedHTTPStream(Func<long, long, Stream> streamFunc, Func<long> lengthFunc)
        {
            _getStream = streamFunc;
            _getContentLength = lengthFunc;
        }
        public override Boolean CanRead
        {
            get
            {
                EnsureNotDisposed();
                return true;
            }
        }
        public override Boolean CanWrite
        {
            get
            {
                EnsureNotDisposed();
                return false;
            }
        }
        public override Boolean CanSeek
        {
            get
            {
                EnsureNotDisposed();
                return true;
            }
        }
        public override Int64 Length
        {
            get
            {
                EnsureNotDisposed();
                if (length == null)
                {
                    length = _getContentLength();
                }
                return length.Value;
            }
        }
        public override Int64 Position
        {
            get
            {
                EnsureNotDisposed();
                Int64 streamPosition = (stream != null) ? stream.Position : 0;
                Int64 position = (currentChunkNumber != -1) ? currentChunkNumber * cacheLength : 0;
                return position + streamPosition;
            }
            set
            {
                EnsureNotDisposed();
                EnsurePositiv(value, "Position");
                Seek(value);
            }
        }
        public override Int64 Seek(Int64 offset, SeekOrigin origin)
        {
            EnsureNotDisposed();
            switch (origin)
            {
                case SeekOrigin.Begin:
                    break;
                case SeekOrigin.Current:
                    offset = Position + offset;
                    break;
                default:
                    offset = Length + offset;
                    break;
            }
            return Seek(offset);
        }
        private Int64 Seek(Int64 offset)
        {
            Int64 chunkNumber = offset / cacheLength;
            if (currentChunkNumber != chunkNumber)
            {
                ReadChunk(chunkNumber);
                currentChunkNumber = chunkNumber;
            }
            offset = offset - currentChunkNumber * cacheLength;
            stream.Seek(offset, SeekOrigin.Begin);
            return Position;
        }
        private void ReadNextChunk()
        {
            currentChunkNumber += 1;
            ReadChunk(currentChunkNumber);
        }
        private void ReadChunk(Int64 chunkNumberToRead)
        {
            Int64 rangeStart = chunkNumberToRead * cacheLength;
            if (rangeStart >= Length) { return; }
            Int64 rangeEnd = rangeStart + cacheLength - 1;
            if (rangeStart + cacheLength > Length)
            {
                rangeEnd = Length - 1;
            }
            if (stream != null) { stream.Close(); }
            stream = new MemoryStream((int)cacheLength);
            var responseStream = _getStream(rangeStart, rangeEnd);
            responseStream.Position = 0;
            responseStream.CopyTo(stream);
            responseStream.Close();
            stream.Position = 0;
        }
        public override void Close()
        {
            EnsureNotDisposed();
            base.Close();
            if (stream != null) { stream.Close(); }
            isDisposed = true;
        }
        public override Int32 Read(Byte[] buffer, Int32 offset, Int32 count)
        {
            EnsureNotDisposed();
            EnsureNotNull(buffer, "buffer");
            EnsurePositiv(offset, "offset");
            EnsurePositiv(count, "count");
            if (buffer.Length - offset < count) { throw new ArgumentException("count"); }
            if (stream == null) { ReadNextChunk(); }
            if (Position >= Length) { return noDataAvaiable; }
            if (Position + count > Length)
            {
                count = (Int32)(Length - Position);
            }
            Int32 bytesRead = stream.Read(buffer, offset, count);
            Int32 totalBytesRead = bytesRead;
            count -= bytesRead;
            while (count > noDataAvaiable)
            {
                ReadNextChunk();
                offset = offset + bytesRead;
                bytesRead = stream.Read(buffer, offset, count);
                count -= bytesRead;
                totalBytesRead = totalBytesRead + bytesRead;
            }
            return totalBytesRead;
        }
        public override void SetLength(Int64 value)
        {
            EnsureNotDisposed();
            throw new NotImplementedException();
        }
        public override void Write(Byte[] buffer, Int32 offset, Int32 count)
        {
            EnsureNotDisposed();
            throw new NotImplementedException();
        }
        public override void Flush()
        {
            EnsureNotDisposed();
        }
        private void EnsureNotNull(Object obj, String name)
        {
            if (obj != null) { return; }
            throw new ArgumentNullException(name);
        }
        private void EnsureNotDisposed()
        {
            if (!isDisposed) { return; }
            throw new ObjectDisposedException("BufferedHTTPStream");
        }
        private void EnsurePositiv(Int32 value, String name)
        {
            if (value > -1) { return; }
            throw new ArgumentOutOfRangeException(name);
        }
        private void EnsurePositiv(Int64 value, String name)
        {
            if (value > -1) { return; }
            throw new ArgumentOutOfRangeException(name);
        }
        private void EnsureNegativ(Int64 value, String name)
        {
            if (value < 0) { return; }
            throw new ArgumentOutOfRangeException(name);
        }
    }

用法:

    var fs = new BufferedHTTPStream((start, end) => 
    {
        // return stream from external service
    }, () => 
    {
       // return stream length from external service
    });
    HttpResponseMessage partialResponse = Request.CreateResponse(HttpStatusCode.PartialContent);
partialResponse.Content = new ByteRangeStreamContent(fs, Request.Headers.Range, mediaType);
    partialResponse.Content.Headers.ContentDisposition = new     ContentDispositionHeaderValue("attachment")
                            {
                                FileName = fileName
                            };
    return partialResponse;