github.com/aamcrae/webcam@v0.0.0-20210915060337-934acc13bdc3/frame/jpeg.go (about)

     1  // Copyright 2019 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     https://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package frame
    16  
    17  import (
    18  	"bytes"
    19  	"image"
    20  	"image/color"
    21  	"image/jpeg"
    22  	"runtime"
    23  )
    24  
    25  type fJPEG struct {
    26  	img     image.Image
    27  	release func()
    28  }
    29  
    30  // Register this framer for this format.
    31  func init() {
    32  	RegisterFramer("JPEG", newJPEGFramer)
    33  }
    34  
    35  // Return a framer for JPEG.
    36  func newJPEGFramer(w, h, stride, size int) func([]byte, func()) (Frame, error) {
    37  	return jpegFramer
    38  }
    39  
    40  // Wrap a jpeg block in a Frame so that it can be used as an image.
    41  func jpegFramer(f []byte, rel func()) (Frame, error) {
    42  	img, err := jpeg.Decode(bytes.NewBuffer(f))
    43  	if err != nil {
    44  		if rel != nil {
    45  			rel()
    46  		}
    47  		return nil, err
    48  	}
    49  	fr := &fJPEG{img: img, release: rel}
    50  	runtime.SetFinalizer(fr, func(obj Frame) {
    51  		obj.Release()
    52  	})
    53  	return fr, nil
    54  }
    55  
    56  func (f *fJPEG) ColorModel() color.Model {
    57  	return f.img.ColorModel()
    58  }
    59  
    60  func (f *fJPEG) Bounds() image.Rectangle {
    61  	return f.img.Bounds()
    62  }
    63  
    64  func (f *fJPEG) At(x, y int) color.Color {
    65  	return f.img.At(x, y)
    66  }
    67  
    68  // Done with frame, release back to camera (if required).
    69  func (f *fJPEG) Release() {
    70  	if f.release != nil {
    71  		f.release()
    72  		// Make sure it only gets called once.
    73  		f.release = nil
    74  	}
    75  }