Skip to content

Commit

Permalink
Fix JPEG from mjpg-streamer project
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexxIT committed May 4, 2024
1 parent a03db50 commit 322c332
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
2 changes: 2 additions & 0 deletions internal/mjpeg/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ func handlerKeyframe(w http.ResponseWriter, r *http.Request) {
return
}
log.Debug().Msgf("[mjpeg] transcoding time=%s", time.Since(ts))
case core.CodecJPEG:
b = mjpeg.FixJPEG(b)
}

h := w.Header()
Expand Down
35 changes: 35 additions & 0 deletions pkg/mjpeg/helpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package mjpeg

import (
"bytes"
"image/jpeg"
)

// FixJPEG - reencode JPEG if it has wrong header
//
// for example, this app produce "bad" images:
// https://github.com/jacksonliam/mjpg-streamer
//
// and they can't be uploaded to the Telegram servers:
// {"ok":false,"error_code":400,"description":"Bad Request: IMAGE_PROCESS_FAILED"}
func FixJPEG(b []byte) []byte {
// skip non-JPEG
if len(b) < 10 || b[0] != 0xFF || b[1] != 0xD8 {
return b
}
// skip if header OK for imghdr library
// https://docs.python.org/3/library/imghdr.html
if string(b[2:4]) == "\xFF\xDB" || string(b[6:10]) == "JFIF" || string(b[6:10]) == "Exif" {
return b
}

img, err := jpeg.Decode(bytes.NewReader(b))
if err != nil {
return b
}
buf := bytes.NewBuffer(nil)
if err = jpeg.Encode(buf, img, nil); err != nil {
return b
}
return buf.Bytes()
}

0 comments on commit 322c332

Please sign in to comment.