From 322c332170c1a4ff7bd9d2b4a006d9df6e72b952 Mon Sep 17 00:00:00 2001 From: Alex X Date: Sat, 4 May 2024 07:44:30 +0300 Subject: [PATCH] Fix JPEG from mjpg-streamer project --- internal/mjpeg/init.go | 2 ++ pkg/mjpeg/helpers.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 pkg/mjpeg/helpers.go diff --git a/internal/mjpeg/init.go b/internal/mjpeg/init.go index e2e6c772..f2519a61 100644 --- a/internal/mjpeg/init.go +++ b/internal/mjpeg/init.go @@ -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() diff --git a/pkg/mjpeg/helpers.go b/pkg/mjpeg/helpers.go new file mode 100644 index 00000000..21000b9b --- /dev/null +++ b/pkg/mjpeg/helpers.go @@ -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() +}