Streaming of a mp4(stream) downloads then plays

Viewed 93

.NET Core 3.1 / WebAPI (ControllerBase)

I am trying to stream a MP4 from our S3 AWS bucket (We can't use presigned url's)

My code:

        public async Task Stream([FromRoute] int id)
    {
        var response = CaseArtifactService.StreamArtifactTest(new CaseArtifactRequest()
        {
            CaseArtifactId = id
        });

        this.Response.StatusCode = 200;

        this.Response.Headers.Add(HeaderNames.ContentType,
            response.Result.Key.ToLower().EndsWith(".png") ? ContentType.Png : ContentType.VideoMp4);
        this.Response.Headers.Add(HeaderNames.ContentDisposition, "inline");

        this.Response.Headers.Add(HeaderNames.AcceptRanges, "bytes");

        var inputStream = response.Result.ResponseStream;
        
        await using var outputStream = this.Response.Body;

        const int bufferSize = 1 << 10;
        var buffer = new byte[bufferSize];

        try
        {
            this.Response.Headers.Add(HeaderNames.ContentLength, inputStream.Length.ToString());
            this.Response.Headers.Add(HeaderNames.ContentRange,
                $"{0}-{inputStream.Length - 1}/{inputStream.Length}");
            Debug.WriteLine($"File Can Seek: {inputStream.CanSeek}");
            
        }
        catch
        {
            // ignored
        }
        finally
        {
            while (true)
            {
                var bytesRead = await inputStream.ReadAsync(buffer, 0, bufferSize);

                if (bytesRead == 0) break;
                await outputStream.WriteAsync(buffer, 0, bytesRead);
            }
        }
    }

The stream is coming back okay, and it does indeed "stream", but it downloads the entire file first, and THEN starts streaming in chunks.

I've played with a few different setups, and even added in the "Accept-Ranges", and the "Content-Range" header pieces. I am not seeing any improvement.

If anyone could possibly point me in the correct direction, i'd greatly appreciate it.

First Line: It downloads in full. Video still shows loading. Second Line: Video starts playing. File size increases with time. (Preferred)

0 Answers
Related