FfmpegDecoder.cs 11 KB

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