publisher-mp4.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package engine
  2. import (
  3. "io"
  4. "github.com/yapingcat/gomedia/go-mp4"
  5. "go.uber.org/zap"
  6. "m7s.live/engine/v4/track"
  7. "m7s.live/engine/v4/util"
  8. )
  9. type MP4Publisher struct {
  10. Publisher
  11. *mp4.MovDemuxer `json:"-" yaml:"-"`
  12. }
  13. // Start reading the MP4 file
  14. func (p *MP4Publisher) ReadMP4Data(source io.ReadSeeker) error {
  15. defer p.Stop()
  16. p.MovDemuxer = mp4.CreateMp4Demuxer(source)
  17. if tracks, err := p.ReadHead(); err != nil {
  18. if err == io.EOF {
  19. p.Info("Reached end of MP4 file")
  20. return nil
  21. }
  22. p.Error("Error reading MP4 header", zap.Error(err))
  23. return err
  24. } else {
  25. info := p.GetMp4Info()
  26. p.Info("MP4 info", zap.Any("info", info))
  27. for _, t := range tracks {
  28. p.Info("MP4 track", zap.Any("track", t))
  29. switch t.Cid {
  30. case mp4.MP4_CODEC_H264:
  31. p.VideoTrack = track.NewH264(p.Stream)
  32. case mp4.MP4_CODEC_H265:
  33. p.VideoTrack = track.NewH265(p.Stream)
  34. case mp4.MP4_CODEC_AAC:
  35. p.AudioTrack = track.NewAAC(p.Stream)
  36. case mp4.MP4_CODEC_G711A:
  37. p.AudioTrack = track.NewG711(p.Stream, true)
  38. case mp4.MP4_CODEC_G711U:
  39. p.AudioTrack = track.NewG711(p.Stream, false)
  40. }
  41. }
  42. for {
  43. pkg, err := p.ReadPacket()
  44. if err != nil {
  45. p.Error("Error reading MP4 packet", zap.Error(err))
  46. return err
  47. }
  48. switch pkg.Cid {
  49. case mp4.MP4_CODEC_H264, mp4.MP4_CODEC_H265:
  50. p.VideoTrack.WriteAnnexB(uint32(pkg.Pts*90), uint32(pkg.Dts*90), pkg.Data)
  51. case mp4.MP4_CODEC_AAC:
  52. p.AudioTrack.WriteADTS(uint32(pkg.Pts*90), util.Buffer(pkg.Data))
  53. case mp4.MP4_CODEC_G711A, mp4.MP4_CODEC_G711U:
  54. p.AudioTrack.WriteRawBytes(uint32(pkg.Pts*90), util.Buffer(pkg.Data))
  55. }
  56. }
  57. }
  58. }