Skip to content

Commit 3812359

Browse files
committed
Reduce loading time
1 parent 1d4c9a1 commit 3812359

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

Console/Audio/Containers/Matroska/HttpSegmentedStream.cs

+17-2
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ internal sealed class HttpSegmentedStream : Stream
99
private readonly HttpClient _httpClient;
1010
private Stream? _httpStream;
1111
private bool _positionChanged;
12+
private long _chunkPosition;
1213

1314
private HttpSegmentedStream(
1415
IDownloadUrlHandler downloadUrlHandler,
@@ -67,11 +68,21 @@ public override async ValueTask<int> ReadAsync(
6768
CancellationToken cancellationToken = default
6869
)
6970
{
70-
if (_httpStream is null || _positionChanged)
71+
if (
72+
_httpStream is null
73+
|| _positionChanged
74+
&& Position < _chunkPosition
75+
&& Position > (_chunkPosition + _httpStream?.Length)
76+
)
7177
{
7278
await ReadNextChunk(cancellationToken);
7379
_positionChanged = false;
7480
}
81+
else if (_positionChanged)
82+
{
83+
_httpStream?.Seek(Math.Abs(Position - _chunkPosition), SeekOrigin.Begin);
84+
_positionChanged = false;
85+
}
7586

7687
int bytesLeftToRead;
7788
var totalRead = 0;
@@ -153,13 +164,17 @@ private async Task ReadNextChunk(CancellationToken cancellationToken)
153164
if (_httpStream is not null)
154165
await _httpStream.DisposeAsync();
155166

156-
_httpStream = await _httpClient.GetStreamAsync(
167+
var response = await _httpClient.GetAsync(
157168
AppendRangeToUrl(
158169
await _downloadUrlHandler.GetUrl(),
159170
Position,
160171
Position + BufferSize - 1
161172
),
173+
HttpCompletionOption.ResponseContentRead,
162174
cancellationToken
163175
);
176+
177+
_httpStream = await response.Content.ReadAsStreamAsync(cancellationToken);
178+
_chunkPosition = Position;
164179
}
165180
}

0 commit comments

Comments
 (0)