audio.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package track
  2. import (
  3. "go.uber.org/zap"
  4. "m7s.live/engine/v4/codec"
  5. . "m7s.live/engine/v4/common"
  6. "m7s.live/engine/v4/util"
  7. )
  8. type Audio struct {
  9. Media
  10. CodecID codec.AudioCodecID
  11. Channels byte
  12. SampleSize byte
  13. SizeLength int // 通常为13
  14. IndexLength int
  15. IndexDeltaLength int
  16. AVCCHead []byte // 音频包在AVCC格式中,AAC会有两个字节,其他的只有一个字节
  17. codec.AudioSpecificConfig
  18. }
  19. func (a *Audio) Attach() {
  20. if err := a.Publisher.GetStream().AddTrack(a).Await(); err != nil {
  21. a.Error("attach audio track failed", zap.Error(err))
  22. } else {
  23. a.Info("audio track attached", zap.Uint32("sample rate", a.SampleRate))
  24. }
  25. }
  26. func (a *Audio) Detach() {
  27. a.Publisher.GetStream().RemoveTrack(a)
  28. }
  29. func (a *Audio) GetName() string {
  30. if a.Name == "" {
  31. return a.CodecID.String()
  32. }
  33. return a.Name
  34. }
  35. func (a *Audio) GetCodec() codec.AudioCodecID {
  36. return a.CodecID
  37. }
  38. func (av *Audio) WriteADTS(pts uint32, adts util.IBytes) {
  39. }
  40. func (av *Audio) WriteSequenceHead(sh []byte) error {
  41. av.Media.WriteSequenceHead(sh)
  42. return nil
  43. }
  44. func (av *Audio) Flush() {
  45. if av.CodecID == codec.CodecID_AAC && av.Value.ADTS == nil {
  46. item := av.BytesPool.Get(7)
  47. av.ToADTS(av.Value.AUList.ByteLength, item.Value)
  48. av.Value.ADTS = item
  49. }
  50. av.Media.Flush()
  51. if av.CodecID != codec.CodecID_AAC && !av.iframeReceived {
  52. av.iframeReceived = true
  53. av.Attach()
  54. }
  55. }
  56. func (av *Audio) WriteRawBytes(pts uint32, raw util.IBytes) {
  57. curValue := av.Value
  58. curValue.BytesIn += raw.Len()
  59. av.Value.AUList.Push(av.GetFromPool(raw))
  60. av.generateTimestamp(pts)
  61. av.Flush()
  62. }
  63. func (av *Audio) WriteAVCC(ts uint32, frame *util.BLL) {
  64. av.Value.WriteAVCC(ts, frame)
  65. av.generateTimestamp(ts * 90)
  66. av.Flush()
  67. }
  68. func (a *Audio) CompleteAVCC(value *AVFrame) {
  69. value.AVCC.Push(a.BytesPool.GetShell(a.AVCCHead))
  70. value.AUList.Range(func(v *util.BLL) bool {
  71. v.Range(func(v util.Buffer) bool {
  72. value.AVCC.Push(a.BytesPool.GetShell(v))
  73. return true
  74. })
  75. return true
  76. })
  77. }
  78. func (a *Audio) CompleteRTP(value *AVFrame) {
  79. a.PacketizeRTP(value.AUList.ToList()...)
  80. }
  81. func (a *Audio) Narrow() {
  82. // if a.HistoryRing == nil && a.IDRing != nil {
  83. // a.narrow(int(a.Value.Sequence - a.IDRing.Value.Sequence))
  84. // }
  85. a.AddIDR()
  86. }