forked from TensorStack-AI/TensorStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVideoService.cs
More file actions
377 lines (334 loc) · 17.4 KB
/
VideoService.cs
File metadata and controls
377 lines (334 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
// Copyright (c) TensorStack. All rights reserved.
// Licensed under the Apache 2.0 License.
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using TensorStack.Common;
using TensorStack.Common.Tensor;
using TensorStack.Common.Video;
namespace TensorStack.Video
{
public static class VideoService
{
/// <summary>
/// Load the video information.
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>VideoInfo.</returns>
/// <exception cref="System.Exception">Failed to open video file.</exception>
public static VideoInfo LoadVideoInfo(string filename)
{
using (var videoReader = new VideoCapture(filename))
{
if (!videoReader.IsOpened())
throw new Exception("Failed to open video file.");
return new VideoInfo(filename, videoReader.FrameWidth, videoReader.FrameHeight, (float)videoReader.Fps, videoReader.FrameCount);
}
}
/// <summary>
/// Loads the VideoTensor from file.
/// </summary>
/// <param name="videoFile">The video file.</param>
/// <param name="frameRate">The frame rate.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <returns>VideoTensor.</returns>
public static VideoTensor LoadVideoTensor(string videoFile, int? width = default, int? height = default, float? frameRate = default, ResizeMode resizeMode = ResizeMode.Crop)
{
return ReadVideo(videoFile, width, height, frameRate, resizeMode);
}
/// <summary>
/// Loads the VideoTensor from file asynchronous.
/// </summary>
/// <param name="videoFile">The video file.</param>
/// <param name="frameRate">The frame rate.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>Task<VideoTensor>.</returns>
public static Task<VideoTensor> LoadVideoTensorAsync(string videoFile, int? width = default, int? height = default, float? frameRate = default, ResizeMode resizeMode = ResizeMode.Crop, CancellationToken cancellationToken = default)
{
return Task.Run(() => ReadVideo(videoFile, width, height, frameRate, resizeMode, cancellationToken));
}
/// <summary>
/// Saves the video.
/// </summary>
/// <param name="videoTensor">The video tensor.</param>
/// <param name="videoFile">The video file.</param>
/// <param name="framerate">The framerate.</param>
/// <param name="videoCodec">The video codec.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
public static async Task SaveVideoTensorAync(VideoTensor videoTensor, string videoFile, float? framerate = default, string videoCodec = "mp4v", CancellationToken cancellationToken = default)
{
var frames = videoTensor
.Split()
.Select(frame => new ImageTensor(frame))
.ToAsyncEnumerable();
await frames.SaveAync(videoFile, framerate ?? videoTensor.FrameRate, videoCodec, cancellationToken);
}
/// <summary>
/// Save video stream as an asynchronous operation.
/// </summary>
/// <param name="videoFile">The video file.</param>
/// <param name="imageFrames">The image frames.</param>
/// <param name="videoCodec">The video codec.</param>
/// <param name="framerate">The framerate.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>A Task representing the asynchronous operation.</returns>
internal static async Task WriteVideoStreamAsync(IAsyncEnumerable<VideoFrame> imageFrames, string videoFile, string videoCodec, float? framerate = default, int? width = default, int? height = default, CancellationToken cancellationToken = default)
{
var fourcc = VideoWriter.FourCC(videoCodec);
var firstFrame = await imageFrames.FirstAsync(cancellationToken);
var fullSequence = CacheFirstAndIterate(firstFrame, imageFrames, cancellationToken);
var outputHeight = height.NullIfZero() ?? firstFrame.Frame.Dimensions[2];
var outputWidth = width.NullIfZero() ?? firstFrame.Frame.Dimensions[3];
var outputFramerate = framerate ?? firstFrame.SourceFrameRate;
var frameSize = new Size(outputWidth, outputHeight);
await WriteVideoFramesAsync(fullSequence, videoFile, frameSize, outputFramerate, fourcc, cancellationToken);
}
/// <summary>
/// Get video stream as an asynchronous operation.
/// </summary>
/// <param name="videoFile">The video file.</param>
/// <param name="frameRate">The frame rate.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>A Task<IAsyncEnumerable`1> representing the asynchronous operation.</returns>
/// <exception cref="System.Exception">Failed to open video file.</exception>
internal static async IAsyncEnumerable<VideoFrame> ReadStreamAsync(string videoFile, float? frameRate = default, int? width = default, int? height = default, ResizeMode resizeMode = ResizeMode.Stretch, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
using (var videoReader = new VideoCapture(videoFile))
{
if (!videoReader.IsOpened())
throw new Exception("Failed to open video file.");
await Task.Yield();
var frameCount = 0;
var videoSize = new Size(videoReader.FrameWidth, videoReader.FrameHeight);
var videoNewSize = GetNewVideoSize(width, height, videoSize, resizeMode);
var videoCropSize = GetCropVideoSize(width, height, videoNewSize, resizeMode);
var videoframeRate = GetVideoFrameRate(videoReader.Fps, frameRate);
var frameSkipInterval = GetFrameInterval(videoReader.Fps, frameRate);
using (var frame = new Mat())
{
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
videoReader.Read(frame);
if (frame.Empty())
break;
if (frameCount % frameSkipInterval == 0)
{
if (videoSize != videoNewSize)
Cv2.Resize(frame, frame, videoNewSize);
yield return new VideoFrame(frame.ToTensor(videoCropSize), videoframeRate);
}
frameCount++;
}
}
}
}
/// <summary>
/// Creates a new VideoTensor (in-memory)
/// </summary>
/// <param name="videoFile">The video file.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="frameRate">The frame rate.</param>
/// <param name="resizeMode">The resize mode.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>VideoTensor.</returns>
/// <exception cref="System.Exception">Failed to open video file.</exception>
internal static VideoTensor ReadVideo(string videoFile, int? width = default, int? height = default, float? frameRate = default, ResizeMode resizeMode = ResizeMode.Stretch, CancellationToken cancellationToken = default)
{
using (var videoReader = new VideoCapture(videoFile))
{
if (!videoReader.IsOpened())
throw new Exception("Failed to open video file.");
var frameCount = 0;
var result = new List<ImageTensor>();
var videoSize = new Size(videoReader.FrameWidth, videoReader.FrameHeight);
var videoNewSize = GetNewVideoSize(width, height, videoSize, resizeMode);
var videoCropSize = GetCropVideoSize(width, height, videoNewSize, resizeMode);
var videoframeRate = GetVideoFrameRate(videoReader.Fps, frameRate);
var frameSkipInterval = GetFrameInterval(videoReader.Fps, frameRate);
using (var frame = new Mat())
{
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
videoReader.Read(frame);
if (frame.Empty())
break;
if (frameCount % frameSkipInterval == 0)
{
if (videoSize != videoNewSize)
Cv2.Resize(frame, frame, videoNewSize);
result.Add(frame.ToTensor(videoCropSize));
}
frameCount++;
}
}
return new VideoTensor(result.Join(), videoframeRate);
}
}
/// <summary>
/// Gets the video frame rate.
/// </summary>
/// <param name="framerate">The framerate.</param>
/// <param name="newFramerate">The new framerate.</param>
/// <returns>System.Single.</returns>
private static float GetVideoFrameRate(double framerate, float? newFramerate)
{
return (float)(newFramerate.HasValue ? Math.Min(newFramerate.Value, framerate) : framerate);
}
/// <summary>
/// Gets the video size scaled to the aspect and ResizeMode
/// </summary>
/// <param name="cropWidth">Width of the crop.</param>
/// <param name="cropHeight">Height of the crop.</param>
/// <param name="currentSize">Size of the current.</param>
/// <param name="resizeMode">The resize mode.</param>
/// <returns>Size.</returns>
private static Size GetNewVideoSize(int? cropWidth, int? cropHeight, Size currentSize, ResizeMode resizeMode)
{
var width = cropWidth.NullIfZero();
var height = cropHeight.NullIfZero();
if (!width.HasValue && !height.HasValue)
return currentSize;
if (resizeMode == ResizeMode.Stretch)
{
if (width.HasValue && height.HasValue)
return new Size(width.Value, height.Value);
if (width.HasValue)
return new Size(width.Value, currentSize.Height);
if (height.HasValue)
return new Size(currentSize.Width, height.Value);
}
if (width.HasValue && height.HasValue)
{
var scaleX = (float)width.Value / currentSize.Width;
var scaleY = (float)height.Value / currentSize.Height;
var scale = Math.Max(scaleX, scaleY);
return new Size((int)(currentSize.Width * scale), (int)(currentSize.Height * scale));
}
else if (width.HasValue)
{
var scaleX = (float)width.Value / currentSize.Width;
return new Size((int)(currentSize.Width * scaleX), (int)(currentSize.Height * scaleX));
}
else if (height.HasValue)
{
var scaleY = (float)height.Value / currentSize.Height;
return new Size((int)(currentSize.Width * scaleY), (int)(currentSize.Height * scaleY));
}
return currentSize;
}
/// <summary>
/// Gets the size of the crop video.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="currentSize">Size of the current.</param>
/// <param name="resizeMode">The resize mode.</param>
/// <returns>Size.</returns>
private static Size GetCropVideoSize(int? cropWidth, int? cropHeight, Size currentSize, ResizeMode resizeMode)
{
var cropSize = default(Size);
if (resizeMode == ResizeMode.Crop)
{
var width = cropWidth.NullIfZero();
var height = cropHeight.NullIfZero();
if (width.HasValue || height.HasValue)
{
if (width.HasValue && height.HasValue)
cropSize = new Size(width.Value, height.Value);
else if (width.HasValue)
cropSize = new Size(width.Value, currentSize.Height);
else if (height.HasValue)
cropSize = new Size(currentSize.Width, height.Value);
}
}
return cropSize;
}
/// <summary>
/// Gets the frame interval.
/// </summary>
/// <param name="framerate">The framerate.</param>
/// <param name="newFramerate">The new framerate.</param>
/// <returns>System.Int32.</returns>
private static int GetFrameInterval(double framerate, float? newFramerate)
{
if (!newFramerate.HasValue)
return 1;
return (int)(Math.Round(framerate) / Math.Min(Math.Round(newFramerate.Value), Math.Round(framerate)));
}
/// <summary>
/// Write video frames to disk.
/// </summary>
/// <param name="videoFile">The video file.</param>
/// <param name="framerate">The framerate.</param>
/// <param name="fourcc">The fourcc.</param>
/// <param name="videoFrames">The full sequence.</param>
/// <param name="frameSize">Size of the frame.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>A Task representing the asynchronous operation.</returns>
internal static async Task WriteVideoFramesAsync(IAsyncEnumerable<ImageTensor> videoFrames, string videoFile, Size frameSize, float framerate, int fourcc, CancellationToken cancellationToken)
{
await Task.Run(async () =>
{
using (var writer = new VideoWriter(videoFile, fourcc, framerate, frameSize))
{
if (!writer.IsOpened())
throw new Exception("Failed to open VideoWriter..");
await foreach (var imageFrame in videoFrames)
{
cancellationToken.ThrowIfCancellationRequested();
using (var mat = imageFrame.ToMat())
{
writer.Write(mat);
}
}
}
}, cancellationToken);
}
/// <summary>
/// Caches the first item and iterate.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="firstItem">The first item.</param>
/// <param name="remainingItems">The remaining items.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>IAsyncEnumerable<T>.</returns>
internal static async IAsyncEnumerable<ImageTensor> CacheFirstAndIterate(VideoFrame firstItem, IAsyncEnumerable<VideoFrame> remainingItems, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
yield return firstItem.Frame;
await foreach (var item in remainingItems.WithCancellation(cancellationToken))
{
yield return item.Frame;
}
}
/// <summary>
/// Caches the first item and iterate.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="firstItem">The first item.</param>
/// <param name="remainingItems">The remaining items.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>IAsyncEnumerable<T>.</returns>
internal static async IAsyncEnumerable<ImageTensor> CacheFirstAndIterate(ImageTensor firstItem, IAsyncEnumerable<ImageTensor> remainingItems, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
yield return firstItem;
await foreach (var item in remainingItems.WithCancellation(cancellationToken))
{
yield return item;
}
}
}
}