usbcapture.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. package usbcapture
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log"
  7. "mime/multipart"
  8. "net/http"
  9. "net/textproto"
  10. "os"
  11. "strings"
  12. "syscall"
  13. "github.com/vladimirvivien/go4vl/device"
  14. "github.com/vladimirvivien/go4vl/v4l2"
  15. )
  16. // NewInstance creates a new video capture instance
  17. func NewInstance(config *Config) (*Instance, error) {
  18. if config == nil {
  19. return nil, fmt.Errorf("config cannot be nil")
  20. }
  21. //Check if the video device exists
  22. if _, err := os.Stat(config.DeviceName); os.IsNotExist(err) {
  23. return nil, fmt.Errorf("video device %s does not exist", config.DeviceName)
  24. } else if err != nil {
  25. return nil, fmt.Errorf("failed to check video device: %w", err)
  26. }
  27. //Check if the device file actualy points to a video device
  28. isValidDevice, err := checkVideoCaptureDevice(config.DeviceName)
  29. if err != nil {
  30. return nil, fmt.Errorf("failed to check video device: %w", err)
  31. }
  32. if !isValidDevice {
  33. return nil, fmt.Errorf("device %s is not a video capture device", config.DeviceName)
  34. }
  35. //Get the supported resolutions of the video device
  36. formatInfo, err := GetV4L2FormatInfo(config.DeviceName)
  37. if err != nil {
  38. return nil, fmt.Errorf("failed to get video device format info: %w", err)
  39. }
  40. if len(formatInfo) == 0 {
  41. return nil, fmt.Errorf("no supported formats found for device %s", config.DeviceName)
  42. }
  43. return &Instance{
  44. Config: config,
  45. Capturing: false,
  46. SupportedResolutions: formatInfo,
  47. }, nil
  48. }
  49. // start http service
  50. func (i *Instance) ServeVideoStream(w http.ResponseWriter, req *http.Request) {
  51. mimeWriter := multipart.NewWriter(w)
  52. w.Header().Set("Content-Type", fmt.Sprintf("multipart/x-mixed-replace; boundary=%s", mimeWriter.Boundary()))
  53. partHeader := make(textproto.MIMEHeader)
  54. partHeader.Add("Content-Type", "image/jpeg")
  55. var frame []byte
  56. for frame = range i.frames_buff {
  57. if len(frame) == 0 {
  58. log.Print("skipping empty frame")
  59. continue
  60. }
  61. partWriter, err := mimeWriter.CreatePart(partHeader)
  62. if err != nil {
  63. log.Printf("failed to create multi-part writer: %s", err)
  64. return
  65. }
  66. if _, err := partWriter.Write(frame); err != nil {
  67. if errors.Is(err, syscall.EPIPE) {
  68. //broken pipe, the client browser has exited
  69. return
  70. }
  71. log.Printf("failed to write image: %s", err)
  72. }
  73. }
  74. }
  75. // start video capture
  76. func (i *Instance) StartVideoCapture(openWithResolution *CaptureResolution) error {
  77. if i.Capturing {
  78. return fmt.Errorf("video capture already started")
  79. }
  80. devName := i.Config.DeviceName
  81. frameRate := 25
  82. buffSize := 8
  83. format := "mjpeg"
  84. if openWithResolution == nil {
  85. return fmt.Errorf("resolution not provided")
  86. }
  87. //Check if the video device is a capture device
  88. isCaptureDev, err := checkVideoCaptureDevice(devName)
  89. if err != nil {
  90. return fmt.Errorf("failed to check video device: %w", err)
  91. }
  92. if !isCaptureDev {
  93. return fmt.Errorf("device %s is not a video capture device", devName)
  94. }
  95. //Check if the selected FPS is valid in the provided Resolutions
  96. resolutionIsSupported, err := deviceSupportResolution(i.Config.DeviceName, openWithResolution)
  97. if err != nil {
  98. return err
  99. }
  100. if !resolutionIsSupported {
  101. return errors.New("this device do not support the required resolution settings")
  102. }
  103. //Open the video device
  104. camera, err := device.Open(devName,
  105. device.WithIOType(v4l2.IOTypeMMAP),
  106. device.WithPixFormat(v4l2.PixFormat{
  107. PixelFormat: getFormatType(format),
  108. Width: uint32(openWithResolution.Width),
  109. Height: uint32(openWithResolution.Height),
  110. Field: v4l2.FieldAny,
  111. }),
  112. device.WithFPS(uint32(frameRate)),
  113. device.WithBufferSize(uint32(buffSize)),
  114. )
  115. if err != nil {
  116. return fmt.Errorf("failed to open video device: %w", err)
  117. }
  118. i.camera = camera
  119. caps := camera.Capability()
  120. log.Printf("device [%s] opened\n", devName)
  121. log.Printf("device info: %s", caps.String())
  122. //2025/03/16 15:45:25 device info: driver: uvcvideo; card: USB Video: USB Video; bus info: usb-0000:00:14.0-2
  123. // set device format
  124. currFmt, err := camera.GetPixFormat()
  125. if err != nil {
  126. log.Fatalf("unable to get format: %s", err)
  127. }
  128. log.Printf("Current format: %s", currFmt)
  129. //2025/03/16 15:45:25 Current format: Motion-JPEG [1920x1080]; field=any; bytes per line=0; size image=0; colorspace=Default; YCbCr=Default; Quant=Default; XferFunc=Default
  130. i.pixfmt = currFmt.PixelFormat
  131. i.width = int(currFmt.Width)
  132. i.height = int(currFmt.Height)
  133. i.streamInfo = fmt.Sprintf("%s - %s [%dx%d] %d fps",
  134. caps.Card,
  135. v4l2.PixelFormats[currFmt.PixelFormat],
  136. currFmt.Width, currFmt.Height, frameRate,
  137. )
  138. // start capture
  139. ctx, cancel := context.WithCancel(context.TODO())
  140. if err := camera.Start(ctx); err != nil {
  141. log.Fatalf("stream capture: %s", err)
  142. }
  143. i.cameraStartContext = cancel
  144. // video stream
  145. i.frames_buff = camera.GetOutput()
  146. log.Printf("device capture started (buffer size set %d)", camera.BufferCount())
  147. i.Capturing = true
  148. return nil
  149. }
  150. // GetStreamInfo returns the stream information string
  151. func (i *Instance) GetStreamInfo() string {
  152. return i.streamInfo
  153. }
  154. // IsCapturing checks if the camera is currently capturing video
  155. func (i *Instance) IsCapturing() bool {
  156. return i.Capturing
  157. }
  158. // StopCapture stops the video capture and closes the camera device
  159. func (i *Instance) StopCapture() error {
  160. if i.camera != nil {
  161. i.cameraStartContext()
  162. i.camera.Close()
  163. i.camera = nil
  164. }
  165. i.Capturing = false
  166. return nil
  167. }
  168. // Close closes the camera device and releases resources
  169. func (i *Instance) Close() error {
  170. if i.camera != nil {
  171. i.StopCapture()
  172. }
  173. return nil
  174. }
  175. func getFormatType(fmtStr string) v4l2.FourCCType {
  176. switch strings.ToLower(fmtStr) {
  177. case "jpeg":
  178. return v4l2.PixelFmtJPEG
  179. case "mpeg":
  180. return v4l2.PixelFmtMPEG
  181. case "mjpeg":
  182. return v4l2.PixelFmtMJPEG
  183. case "h264", "h.264":
  184. return v4l2.PixelFmtH264
  185. case "yuyv":
  186. return v4l2.PixelFmtYUYV
  187. case "rgb":
  188. return v4l2.PixelFmtRGB24
  189. }
  190. return v4l2.PixelFmtMPEG
  191. }