-
Notifications
You must be signed in to change notification settings - Fork 515
Expand file tree
/
Copy pathFFmpegCameraSource.cs
More file actions
203 lines (169 loc) · 8.83 KB
/
FFmpegCameraSource.cs
File metadata and controls
203 lines (169 loc) · 8.83 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
using FFmpeg.AutoGen;
using Microsoft.Extensions.Logging;
using SIPSorcery;
using SIPSorceryMedia.Abstractions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace SIPSorceryMedia.FFmpeg
{
public class FFmpegCameraSource : FFmpegVideoSource
{
private static ILogger logger = LogFactory.CreateLogger<FFmpegCameraSource>();
private readonly Camera _camera;
private IEnumerable<Camera.CameraFormat>? _filteredFormats;
/// <summary>
/// Construct an FFmpeg camera/input device source provided input path.
/// </summary>
/// <remarks>See </remarks>
/// <param name="path"></param>
public FFmpegCameraSource(string path) : this(FFmpegCameraManager.GetCameraByPath(path) ?? new() { Path = path })
{
}
/// <summary>
/// Construct an FFmpeg camera/input device source provided a <see cref="Camera"/>.
/// </summary>
/// <param name="camera"></param>
/// <exception cref="NotSupportedException">Platform is currently not supported.</exception>
public unsafe FFmpegCameraSource(Camera camera)
{
_camera = camera;
_sourcePixFmts = _camera.AvailableFormats?.Select(f => f.PixelFormat).Distinct().ToArray();
string inputFormat = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dshow"
: RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "v4l2"
: RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "avfoundation"
: throw new NotSupportedException($"Cannot find adequate input format" +
$" - OSArchitecture:[{RuntimeInformation.OSArchitecture}]" +
$" - OSDescription:[{RuntimeInformation.OSDescription}]");
var _aVInputFormat = ffmpeg.av_find_input_format(inputFormat);
CreateVideoDecoder(_camera.Path, _aVInputFormat, false, true);
InitialiseDecoder();
}
/// <summary>
/// Filter for the desired <see cref="Camera.CameraFormat"/>(s) to use
/// and resets the underlying <see cref="FFmpegVideoDecoder"/>.
/// </summary>
/// <remarks>Will use highest framerate then resolution after filtered.
/// </remarks>
/// <param name="formatFilter">Filter function.</param>
/// <returns><see langword="true"/> If decoder resets successfully.
/// <br/>Increase FFmpeg verbosity / loglevel for more information.</returns>
public bool RestrictCameraFormats(Func<Camera.CameraFormat, bool> formatFilter)
{
_filteredFormats = _camera.AvailableFormats?.Where(formatFilter.Invoke)
.OrderByDescending(c => c.FPS)
.ThenByDescending(c => c.Width > c.Height ? c.Width : c.Height);
var maxAllowedres = _filteredFormats?.FirstOrDefault().ToOptionDictionary();
if (maxAllowedres == null)
{
logger.LogWarning("camera/input device \"{name}\" doesn't have any recognizable filtered formats to be used.", _camera.Name);
return false;
}
return SetCameraDeviceOptions(maxAllowedres);
}
/// <summary>
/// Filter for available FFmpeg camera/input device options and resets the underlying
/// <see cref="FFmpegVideoDecoder"/> with the specified options.
/// </summary>
/// <remarks>Will use highest framerate then resolution after filtered.
/// <br/><br/>
/// <i>This is an advanced control for camera/input devices options filtering.
/// <br/>Most usage will use <see cref="RestrictCameraFormats"/> filter.</i>
/// <br/><br/> See <see href="https://www.ffmpeg.org/ffmpeg-devices.html">FFmpeg documentation on the device options</see>
/// for your system's <see cref="AVInputFormat"/> (i.e. dshow, avfoundation, v4l2, etc.)
/// </remarks>
/// <param name="optFilter">Filter function.</param>
/// <returns><see langword="true"/> If decoder resets successfully.
/// <br/>Increase FFmpeg verbosity / loglevel for more information.</returns>
public bool RestrictCameraOptions(Func<Dictionary<string, string>, bool> optFilter)
{
var filtered = _camera.AvailableOptions?.Where(optFilter.Invoke)
.OrderByDescending(d => int.Parse(d["max_fps"]))
.ThenByDescending(d => int.Parse(d["min_fps"]))
.ThenByDescending(d =>
{
var max_s = d["max_s"].Split(['x'], StringSplitOptions.RemoveEmptyEntries);
var max_w = int.Parse(max_s[0]);
var max_h = int.Parse(max_s[1]);
return max_h > max_w ? max_h : max_w;
})
.ThenByDescending(d =>
{
var min_s = d["min_s"].Split(['x'], StringSplitOptions.RemoveEmptyEntries);
var min_w = int.Parse(min_s[0]);
var min_h = int.Parse(min_s[1]);
return min_h > min_w ? min_h : min_w;
})
.FirstOrDefault()?
.Where(kp => !kp.Key.Contains("min_"))
.ToDictionary(d => d.Key switch
{
"max_s" => "video_size",
"max_fps" => "framerate",
_ => d.Key
},
kp => kp.Value
);
if (filtered is null)
logger.LogWarning($"No camera/input device options to be used.");
return SetCameraDeviceOptions(filtered);
}
/// <summary>
/// Resets the underlying <see cref="FFmpegVideoDecoder"/> with the provided options.
/// </summary>
/// <remarks>
/// <br/><i>This is an advanced options for if you know/static preconfigured device options beforehand.
/// Most usage will use <see cref="RestrictCameraFormats"/> or <see cref="RestrictCameraOptions"/> filter.</i>
/// <br/><br/>
/// See <see href="https://www.ffmpeg.org/ffmpeg-devices.html">FFmpeg documentation on the device options</see>
/// for your system's <see cref="AVInputFormat"/> (i.e. dshow, avfoundation, v4l2, etc.)
/// </remarks>
/// <param name="options">A dictionary of device options</param>
/// <returns><see langword="true"/> If decoder resets successfully.
/// <br/>Increase FFmpeg verbosity / loglevel for more information.</returns>
public bool SetCameraDeviceOptions(Dictionary<string, string>? options)
{
_videoDecoder?.Dispose();
return InitialiseDecoder(options);
}
internal override async void OnNegotiatedPixelFormat(AVPixelFormat ongoingFmt, AVPixelFormat chosenPixFmt)
{
base.OnNegotiatedPixelFormat(ongoingFmt, chosenPixFmt);
if (ongoingFmt == chosenPixFmt)
return;
var formats = _filteredFormats ?? _camera.AvailableFormats;
if (formats == null)
return;
var chosenfmt = formats?.FirstOrDefault(f => f.PixelFormat == chosenPixFmt);
if (chosenfmt.HasValue && _videoDecoder != null)
{
_videoDecoder.OnEndOfFile -= VideoDecoder_OnEndOfFile;
await _videoDecoder.Close();
_videoDecoder.Dispose();
InitialiseDecoder(chosenfmt.Value.ToOptionDictionary());
_videoDecoder.StartDecode();
_videoDecoder.OnEndOfFile += VideoDecoder_OnEndOfFile;
}
}
}
internal static class FFmpegCameraExtensions
{
internal static Dictionary<string, string>? ToOptionDictionary(this Camera.CameraFormat c)
{
if (c.Equals(default(Camera.CameraFormat))
|| c.FPS == 0 || c.Width == 0 || c.Height == 0
)
return null;
return new Dictionary<string, string>()
{
{ "pixel_format", ffmpeg.av_get_pix_fmt_name(c.PixelFormat) },
{ "video_size", $"{c.Width}x{c.Height}" },
{ "framerate", $"{c.FPS}" },
};
}
}
}