2
0

recorder.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package player
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "time"
  11. )
  12. type Recorder struct {
  13. path string
  14. bid string
  15. wr *writer
  16. }
  17. func NewRecorder(path string, bid string) (Player, error) {
  18. if path = strings.TrimSpace(path); path == "" {
  19. return nil, errors.New("illegal arguments: empty path")
  20. }
  21. if bid = strings.TrimSpace(bid); bid == "" {
  22. return nil, errors.New("illegal arguments: empty bid")
  23. }
  24. var (
  25. r = Recorder{
  26. path: path,
  27. bid: bid,
  28. }
  29. err error
  30. )
  31. if err = r.Available(nil); err != nil {
  32. return nil, err
  33. }
  34. return &r, nil
  35. }
  36. func (r *Recorder) Available(context.Context) error {
  37. if r.path == "" || r.bid == "" {
  38. return errors.New("illegal state")
  39. }
  40. var (
  41. f *os.File
  42. err error
  43. )
  44. if f, err = os.OpenFile(
  45. filepath.Join(r.path, ".watchdog"),
  46. os.O_APPEND|os.O_WRONLY|os.O_CREATE,
  47. 0666); err != nil {
  48. return err
  49. }
  50. defer func() {
  51. if f == nil {
  52. return
  53. }
  54. _ = f.Close()
  55. _ = os.Remove(f.Name())
  56. }()
  57. return nil
  58. }
  59. func (r *Recorder) Start(stop chan error) error {
  60. var (
  61. pipe io.WriteCloser
  62. err error
  63. )
  64. pipe, err = os.OpenFile(
  65. filepath.Join(r.path, fmt.Sprintf("%s_%s.TS", r.bid, time.Now().String())),
  66. os.O_APPEND|os.O_WRONLY|os.O_CREATE,
  67. 0666)
  68. if err != nil {
  69. return err
  70. }
  71. r.wr = Writer(pipe)
  72. go r.wr.Run(stop)
  73. return nil
  74. }
  75. func (r *Recorder) Write(d []byte) error {
  76. if r.wr == nil {
  77. return io.ErrClosedPipe
  78. }
  79. return r.wr.Write(d)
  80. }
  81. func (r *Recorder) Close() error {
  82. if r.wr != nil {
  83. _ = r.wr.Close()
  84. }
  85. return nil
  86. }