From 63f694a0a520ce4e151445a45d9e25f2dbc368ed Mon Sep 17 00:00:00 2001 From: Saxon Date: Fri, 15 Nov 2019 16:25:35 +1030 Subject: [PATCH] codec/mjpeg/jpeg.go: added writeHuffman function to write JPEG huffman tables to an io.Writer. --- codec/mjpeg/jpeg.go | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/codec/mjpeg/jpeg.go b/codec/mjpeg/jpeg.go index c5c42c06..570fa769 100644 --- a/codec/mjpeg/jpeg.go +++ b/codec/mjpeg/jpeg.go @@ -24,7 +24,10 @@ LICENSE package mjpeg -import "io" +import ( + "fmt" + "io" +) // JPEG marker codes. const ( @@ -37,11 +40,36 @@ const ( sof0 = 0xc0 // Baseline ) -// putMarker writes an JPEG marker with code to w. -func putMarker(w io.Writer, code byte) error { +// writeMarker writes an JPEG marker with code to w. +func writeMarker(w io.Writer, code byte) error { _, err := w.Write([]byte{0xff, code}) if err != nil { return err } return nil } + +// writeHuffman write a JPEG huffman table to w. +func writeHuffman(w io.Writer, class, id int, bits, values []byte) error { + _, err := w.Write([]byte{byte(class<<4 | id)}) + if err != nil { + return fmt.Errorf("could not write class and id: %w", err) + } + + var n int + for i := 1; i <= 16; i++ { + n += int(bits[i]) + } + + _, err = w.Write(bits[1:17]) + if err != nil { + return fmt.Errorf("could not write first lot of huffman bytes: %w", err) + } + + _, err = w.Write(values[0:n]) + if err != nil { + return fmt.Errorf("could not write second lot of huffman bytes: %w", err) + } + + return nil +}