writer.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package rtpdump
  4. import (
  5. "fmt"
  6. "io"
  7. "sync"
  8. )
  9. // Writer writes the RTPDump file format
  10. type Writer struct {
  11. writerMu sync.Mutex
  12. writer io.Writer
  13. }
  14. // NewWriter makes a new Writer and immediately writes the given Header
  15. // to begin the file.
  16. func NewWriter(w io.Writer, hdr Header) (*Writer, error) {
  17. preamble := fmt.Sprintf(
  18. "#!rtpplay1.0 %s/%d\n",
  19. hdr.Source.To4().String(),
  20. hdr.Port)
  21. if _, err := w.Write([]byte(preamble)); err != nil {
  22. return nil, err
  23. }
  24. hData, err := hdr.Marshal()
  25. if err != nil {
  26. return nil, err
  27. }
  28. if _, err := w.Write(hData); err != nil {
  29. return nil, err
  30. }
  31. return &Writer{writer: w}, nil
  32. }
  33. // WritePacket writes a Packet to the output
  34. func (w *Writer) WritePacket(p Packet) error {
  35. w.writerMu.Lock()
  36. defer w.writerMu.Unlock()
  37. data, err := p.Marshal()
  38. if err != nil {
  39. return err
  40. }
  41. if _, err := w.writer.Write(data); err != nil {
  42. return err
  43. }
  44. return nil
  45. }