You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

OpusEncodeStream.cs 3.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. namespace Discord.Audio
  5. {
  6. internal class OpusEncodeStream : RTPWriteStream
  7. {
  8. public const int SampleRate = 48000;
  9. private int _frameSize;
  10. private byte[] _partialFrameBuffer;
  11. private int _partialFramePos;
  12. private readonly OpusEncoder _encoder;
  13. internal OpusEncodeStream(IAudioTarget target, byte[] secretKey, int channels, int samplesPerFrame, uint ssrc, int? bitrate = null)
  14. : base(target, secretKey, samplesPerFrame, ssrc)
  15. {
  16. _encoder = new OpusEncoder(SampleRate, channels);
  17. _frameSize = samplesPerFrame * channels * 2;
  18. _partialFrameBuffer = new byte[_frameSize];
  19. _encoder.SetForwardErrorCorrection(true);
  20. if (bitrate != null)
  21. _encoder.SetBitrate(bitrate.Value);
  22. }
  23. public override void Write(byte[] buffer, int offset, int count)
  24. {
  25. WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
  26. }
  27. public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  28. {
  29. //Assume threadsafe
  30. while (count > 0)
  31. {
  32. if (_partialFramePos + count >= _frameSize)
  33. {
  34. int partialSize = _frameSize - _partialFramePos;
  35. Buffer.BlockCopy(buffer, offset, _partialFrameBuffer, _partialFramePos, partialSize);
  36. offset += partialSize;
  37. count -= partialSize;
  38. _partialFramePos = 0;
  39. int encFrameSize = _encoder.EncodeFrame(_partialFrameBuffer, 0, _frameSize, _buffer, 0);
  40. await base.WriteAsync(_buffer, 0, encFrameSize, cancellationToken).ConfigureAwait(false);
  41. }
  42. else
  43. {
  44. Buffer.BlockCopy(buffer, offset, _partialFrameBuffer, _partialFramePos, count);
  45. _partialFramePos += count;
  46. break;
  47. }
  48. }
  49. }
  50. public override void Flush()
  51. {
  52. FlushAsync(CancellationToken.None).GetAwaiter().GetResult();
  53. }
  54. public override async Task FlushAsync(CancellationToken cancellationToken)
  55. {
  56. try
  57. {
  58. int encFrameSize = _encoder.EncodeFrame(_partialFrameBuffer, 0, _partialFramePos, _buffer, 0);
  59. base.Write(_buffer, 0, encFrameSize);
  60. }
  61. catch (Exception) { } //Incomplete frame
  62. _partialFramePos = 0;
  63. await base.FlushAsync(cancellationToken).ConfigureAwait(false);
  64. }
  65. protected override void Dispose(bool disposing)
  66. {
  67. base.Dispose(disposing);
  68. if (disposing)
  69. _encoder.Dispose();
  70. }
  71. }
  72. }