AvioContext.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using Bmp.Core.FFMpeg.CsCorePorts.FFMpegWrap.Interops;
  2. namespace Bmp.Core.FFMpeg.CsCorePorts.FFMpegWrap;
  3. internal sealed class AvioContext : IDisposable
  4. {
  5. // ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable
  6. private readonly FfmpegCalls.AvioReadData _readDataCallback;
  7. private readonly FfmpegCalls.AvioSeek _seekCallback;
  8. private readonly FfmpegCalls.AvioWriteData _writeDataCallback;
  9. private unsafe AVIOContext* _context;
  10. private AvioBuffer _buffer;
  11. // ReSharper restore PrivateFieldCanBeConvertedToLocalVariable
  12. public unsafe nint ContextPtr
  13. {
  14. get { return (nint)_context; }
  15. }
  16. public unsafe AVIOContext Context
  17. {
  18. get
  19. {
  20. if (_context == null)
  21. return default;
  22. return *_context;
  23. }
  24. }
  25. public AvioContext(
  26. FfmpegCalls.AvioReadData readDataCallback,
  27. FfmpegCalls.AvioSeek seekCallback)
  28. : this(readDataCallback, seekCallback, null)
  29. {
  30. }
  31. public unsafe AvioContext(
  32. FfmpegCalls.AvioReadData readDataCallback,
  33. FfmpegCalls.AvioSeek seekCallback,
  34. FfmpegCalls.AvioWriteData writeDataCallback)
  35. {
  36. _readDataCallback = readDataCallback;
  37. _seekCallback = seekCallback;
  38. _writeDataCallback = writeDataCallback;
  39. //make sure that the buffer won't be disposed
  40. //the buffer may change. we always have to free _context->buffer
  41. _buffer = new AvioBuffer { SuppressAvFree = true };
  42. _context = FfmpegCalls.AvioAllocContext(_buffer, _writeDataCallback != null, nint.Zero,
  43. _readDataCallback, _writeDataCallback, _seekCallback);
  44. }
  45. public unsafe void Dispose()
  46. {
  47. GC.SuppressFinalize(this);
  48. if (_context != null)
  49. {
  50. //free the allocated buffer
  51. //note: the internal buffer could have changed, and be != _buffer
  52. FfmpegCalls.AvFree((nint)_context->buffer);
  53. //free the context itself
  54. FfmpegCalls.AvFree((nint)_context);
  55. _context = null;
  56. }
  57. }
  58. ~AvioContext()
  59. {
  60. Dispose();
  61. }
  62. }