FfmpegDecoder.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. 
  2. using System.Runtime.InteropServices;
  3. using Bmp.Core.FFMpeg.CsCoreExt;
  4. namespace Bmp.Core.FFMpeg.CsCorePorts.FFMpegWrap;
  5. /// <summary>
  6. /// Generic FFmpeg based decoder.
  7. /// </summary>
  8. /// <remarks>
  9. /// The <see cref="FfmpegDecoder" /> uses the FFmpeg libraries to decode audio files.
  10. /// In order to make sure that the FFmpeg libraries are compatible with the <see cref="FfmpegDecoder" />,
  11. /// use the binaries shipped with the CSCore.Ffmpeg project.
  12. /// If a custom build is necessary, use the FFmpeg source code, from the CSCore git repository
  13. /// (https://github.com/filoe/cscore).
  14. /// </remarks>
  15. public class FfmpegDecoder : IWaveSource
  16. {
  17. // BmpMod: Add `AttachedPic` and `BitPerRawSample`
  18. public FFMpegAttachedPicCollection? AttachedPics => _formatContext == null ? null : new FFMpegAttachedPicCollection(_formatContext.FormatContext);
  19. public unsafe int? BitPerRawSample => _formatContext != null ? _formatContext.SelectedStream.Stream.codec->bits_per_raw_sample : null;
  20. public unsafe long? StreamBitPerSecond => _formatContext != null ? _formatContext.SelectedStream.Stream.codec->bit_rate : null;
  21. public long? FileBitPerSecond => _formatContext?.FormatContext.bit_rate;
  22. public unsafe string? FileFormat
  23. {
  24. get
  25. {
  26. if (_formatContext == null) return null;
  27. var codec = Marshal.PtrToStringUTF8((nint)_formatContext.SelectedStream.Stream.codec->codec->long_name);
  28. var container = Marshal.PtrToStringUTF8((nint)_formatContext.FormatContext.iformat->name);
  29. return $"{codec} @ {container}";
  30. }
  31. }
  32. // Orig
  33. private readonly object _lockObject = new object();
  34. private readonly Uri _uri;
  35. private FfmpegStream? _ffmpegStream;
  36. private AvFormatContext? _formatContext;
  37. private bool _disposeStream = false;
  38. private byte[] _overflowBuffer = Array.Empty<byte>();
  39. private int _overflowCount;
  40. private int _overflowOffset;
  41. private long _position;
  42. private Stream? _stream;
  43. /// <summary>
  44. /// Gets a dictionary with found metadata.
  45. /// </summary>
  46. public Dictionary<string, string> Metadata
  47. {
  48. get
  49. {
  50. if (_formatContext == null)
  51. return new Dictionary<string, string>();
  52. return _formatContext.Metadata;
  53. }
  54. }
  55. /// <summary>
  56. /// Initializes a new instance of the <see cref="FfmpegDecoder" /> class based on a specified filename or url.
  57. /// </summary>
  58. /// <param name="url">A url containing a filename or web url. </param>
  59. /// <exception cref="FfmpegException">
  60. /// Any ffmpeg error.
  61. /// </exception>
  62. /// <exception cref="NotSupportedException">
  63. /// DBL format is not supported.
  64. /// or
  65. /// Audio Sample Format not supported.
  66. /// </exception>
  67. /// <exception cref="ArgumentNullException">uri</exception>
  68. public FfmpegDecoder(string url)
  69. {
  70. const int invalidArgument = unchecked((int)0xffffffea);
  71. _uri = new Uri(url);
  72. try
  73. {
  74. _formatContext = new AvFormatContext(url);
  75. Initialize();
  76. }
  77. catch (FfmpegException ex)
  78. {
  79. if (ex.ErrorCode == invalidArgument && "avformat_open_input".Equals(ex.Function, StringComparison.OrdinalIgnoreCase))
  80. {
  81. if (!TryInitializeWithFileAsStream(url))
  82. throw;
  83. }
  84. else
  85. {
  86. throw;
  87. }
  88. }
  89. }
  90. /// <summary>
  91. /// Initializes a new instance of the <see cref="FfmpegDecoder" /> class based on a <see cref="Stream" />.
  92. /// </summary>
  93. /// <param name="stream">The stream.</param>
  94. /// <exception cref="FfmpegException">Any ffmpeg error.</exception>
  95. /// <exception cref="ArgumentNullException">stream</exception>
  96. /// <exception cref="ArgumentException">Stream is not readable.</exception>
  97. /// <exception cref="OutOfMemoryException">Could not allocate FormatContext.</exception>
  98. /// <exception cref="NotSupportedException">
  99. /// DBL format is not supported.
  100. /// or
  101. /// Audio Sample Format not supported.
  102. /// </exception>
  103. public FfmpegDecoder(Stream stream)
  104. {
  105. if (stream == null)
  106. throw new ArgumentNullException("stream");
  107. InitializeWithStream(stream, false);
  108. }
  109. /// <summary>
  110. /// Reads a sequence of bytes from the <see cref="FfmpegDecoder" /> and advances the position within the
  111. /// stream by the
  112. /// number of bytes read.
  113. /// </summary>
  114. /// <param name="buffer">
  115. /// An array of bytes. When this method returns, the <paramref name="buffer" /> contains the specified
  116. /// array of bytes with the values between <paramref name="offset" /> and (<paramref name="offset" /> +
  117. /// <paramref name="count" /> - 1) replaced by the bytes read from the current source.
  118. /// </param>
  119. /// <param name="offset">
  120. /// The zero-based offset in the <paramref name="buffer" /> at which to begin storing the data
  121. /// read from the current stream.
  122. /// </param>
  123. /// <param name="count">The maximum number of bytes to read from the current source.</param>
  124. /// <returns>The total number of bytes read into the buffer.</returns>
  125. public int Read(byte[] buffer, int offset, int count)
  126. {
  127. var read = 0;
  128. count -= count % WaveFormat.BlockAlign;
  129. var fetchedOverflows = GetOverflows(buffer, ref offset, count);
  130. read += fetchedOverflows;
  131. while (read < count)
  132. {
  133. long packetPosition;
  134. int bufferLength;
  135. lock (_lockObject)
  136. {
  137. using (var frame = new AvFrame(_formatContext))
  138. {
  139. double seconds;
  140. bufferLength = frame.ReadNextFrame(out seconds, ref _overflowBuffer);
  141. packetPosition = this.GetRawElements(TimeSpan.FromSeconds(seconds));
  142. }
  143. }
  144. if (bufferLength <= 0)
  145. {
  146. //if (_uri != null && !_uri.IsFile)
  147. //{
  148. // //webstream: don't exit, maybe the connection was lost -> give it a try to recover
  149. // Thread.Sleep(10);
  150. //}
  151. //else
  152. break; //no webstream -> exit
  153. }
  154. var bytesToCopy = Math.Min(count - read, bufferLength);
  155. Array.Copy(_overflowBuffer, 0, buffer, offset, bytesToCopy);
  156. read += bytesToCopy;
  157. offset += bytesToCopy;
  158. _overflowCount = bufferLength > bytesToCopy ? bufferLength - bytesToCopy : 0;
  159. _overflowOffset = bufferLength > bytesToCopy ? bytesToCopy : 0;
  160. _position = packetPosition + read - fetchedOverflows;
  161. }
  162. if (fetchedOverflows == read)
  163. {
  164. //no new packet was decoded -> add the read bytes to the position
  165. _position += read;
  166. }
  167. return read;
  168. }
  169. /// <summary>
  170. /// Gets a value indicating whether the <see cref="FfmpegDecoder" /> supports seeking.
  171. /// </summary>
  172. public bool CanSeek
  173. {
  174. get
  175. {
  176. if (_formatContext == null)
  177. return false;
  178. return _formatContext.CanSeek;
  179. }
  180. }
  181. /// <summary>
  182. /// Gets the <see cref="IAudioSource.WaveFormat" /> of the waveform-audio data.
  183. /// </summary>
  184. public WaveFormat WaveFormat { get; private set; }
  185. /// <summary>
  186. /// Gets or sets the current position in bytes.
  187. /// </summary>
  188. public long Position
  189. {
  190. get { return _position; }
  191. set { SeekPosition(value); }
  192. }
  193. /// <summary>
  194. /// Gets the length of the waveform-audio data in bytes.
  195. /// </summary>
  196. public long Length
  197. {
  198. get
  199. {
  200. if (_formatContext == null || _formatContext.SelectedStream == null)
  201. return 0;
  202. return this.GetRawElements(TimeSpan.FromSeconds(_formatContext.LengthInSeconds));
  203. }
  204. }
  205. /// <summary>
  206. /// Releases all allocated resources used by the <see cref="FfmpegDecoder" />.
  207. /// </summary>
  208. public void Dispose()
  209. {
  210. Dispose(true);
  211. }
  212. /// <summary>
  213. /// Releases unmanaged and - optionally - managed resources.
  214. /// </summary>
  215. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  216. protected void Dispose(bool disposing)
  217. {
  218. GC.SuppressFinalize(this);
  219. if (disposing)
  220. {
  221. if (_disposeStream && _stream != null)
  222. {
  223. _stream.Dispose();
  224. _stream = null;
  225. }
  226. if (_formatContext != null)
  227. {
  228. _formatContext.Dispose();
  229. _formatContext = null;
  230. }
  231. if (_ffmpegStream != null)
  232. {
  233. _ffmpegStream.Dispose();
  234. _ffmpegStream = null;
  235. }
  236. }
  237. }
  238. private unsafe void Initialize()
  239. {
  240. if (_formatContext == null) throw new InvalidOperationException();
  241. WaveFormat = _formatContext.SelectedStream.GetSuggestedWaveFormat();
  242. }
  243. private void InitializeWithStream(Stream stream, bool disposeStream)
  244. {
  245. _stream = stream;
  246. _disposeStream = disposeStream;
  247. _ffmpegStream = new FfmpegStream(stream, false);
  248. _formatContext = new AvFormatContext(_ffmpegStream);
  249. Initialize();
  250. }
  251. private bool TryInitializeWithFileAsStream(string filename)
  252. {
  253. if (!File.Exists(filename))
  254. return false;
  255. Stream stream = null;
  256. try
  257. {
  258. stream = File.OpenRead(filename);
  259. InitializeWithStream(stream, true);
  260. return true;
  261. }
  262. catch (Exception)
  263. {
  264. if (stream != null)
  265. {
  266. stream.Dispose();
  267. }
  268. return false;
  269. }
  270. }
  271. /// <summary>
  272. /// Finalizes an instance of the <see cref="FfmpegDecoder" /> class.
  273. /// </summary>
  274. ~FfmpegDecoder()
  275. {
  276. Dispose(false);
  277. }
  278. private void SeekPosition(long position)
  279. {
  280. //https://ffmpeg.org/doxygen/trunk/seek-test_8c-source.html
  281. var seconds = this.GetMilliseconds(position) / 1000.0;
  282. lock (_lockObject)
  283. {
  284. _formatContext.SeekFile(seconds);
  285. _position = position;
  286. _overflowCount = 0;
  287. _overflowOffset = 0;
  288. }
  289. }
  290. private int GetOverflows(byte[] buffer, ref int offset, int count)
  291. {
  292. if (_overflowCount != 0 && _overflowBuffer != null && count > 0)
  293. {
  294. var bytesToCopy = Math.Min(count, _overflowCount);
  295. Array.Copy(_overflowBuffer, _overflowOffset, buffer, offset, bytesToCopy);
  296. _overflowCount -= bytesToCopy;
  297. _overflowOffset += bytesToCopy;
  298. offset += bytesToCopy;
  299. return bytesToCopy;
  300. }
  301. return 0;
  302. }
  303. }