g711.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package track
  2. import (
  3. "io"
  4. "go.uber.org/zap"
  5. "m7s.live/engine/v4/codec"
  6. . "m7s.live/engine/v4/common"
  7. "m7s.live/engine/v4/util"
  8. )
  9. var _ SpesificTrack = (*G711)(nil)
  10. func NewG711(puber IPuber, alaw bool, stuff ...any) (g711 *G711) {
  11. g711 = &G711{}
  12. if alaw {
  13. g711.Name = "pcma"
  14. g711.PayloadType = 8
  15. } else {
  16. g711.Name = "pcmu"
  17. g711.PayloadType = 0
  18. }
  19. if alaw {
  20. g711.CodecID = codec.CodecID_PCMA
  21. } else {
  22. g711.CodecID = codec.CodecID_PCMU
  23. }
  24. g711.SampleSize = 8
  25. g711.Channels = 1
  26. g711.AVCCHead = []byte{(byte(g711.CodecID) << 4) | (1 << 1)}
  27. g711.SetStuff(uint32(8000), g711, stuff, puber)
  28. if g711.BytesPool == nil {
  29. g711.BytesPool = make(util.BytesPool, 17)
  30. }
  31. return
  32. }
  33. type G711 struct {
  34. Audio
  35. }
  36. func (g711 *G711) WriteAVCC(ts uint32, frame *util.BLL) error {
  37. if l := frame.ByteLength; l < 2 {
  38. g711.Error("AVCC data too short", zap.Int("len", l))
  39. return io.ErrShortWrite
  40. }
  41. i := 0
  42. frame.Range(func(v util.Buffer) bool {
  43. if i == 0 {
  44. v = v.SubBuf(1, v.Len()-1)
  45. }
  46. g711.Value.AUList.Push(g711.BytesPool.GetShell(v))
  47. i++
  48. return true
  49. })
  50. g711.Audio.WriteAVCC(ts, frame)
  51. return nil
  52. }
  53. func (g711 *G711) WriteRTPFrame(rtpItem *util.ListItem[RTPFrame]) {
  54. frame := &rtpItem.Value
  55. g711.Value.RTP.Push(rtpItem)
  56. if g711.SampleRate != 90000 {
  57. g711.generateTimestamp(uint32(uint64(frame.Timestamp) * 90000 / uint64(g711.SampleRate)))
  58. }
  59. g711.AppendAuBytes(frame.Payload)
  60. g711.Flush()
  61. }
  62. func (g711 *G711) CompleteRTP(value *AVFrame) {
  63. if value.AUList.ByteLength > RTPMTU {
  64. var packets [][][]byte
  65. r := value.AUList.Next.Value.NewReader()
  66. for bufs := r.ReadN(RTPMTU); len(bufs) > 0; bufs = r.ReadN(RTPMTU) {
  67. packets = append(packets, bufs)
  68. }
  69. g711.PacketizeRTP(packets...)
  70. } else {
  71. g711.Audio.CompleteRTP(value)
  72. }
  73. }