github.com/aamcrae/webcam@v0.0.0-20210915060337-934acc13bdc3/frame/yuyv422.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 "fmt" 19 "image" 20 "image/color" 21 "runtime" 22 ) 23 24 type fYUYV422 struct { 25 model color.Model 26 b image.Rectangle 27 stride int 28 size int 29 frame []byte 30 release func() 31 } 32 33 // Register a framer factory for this format. 34 func init() { 35 RegisterFramer("YUYV", newFramerYUYV422) 36 } 37 38 func newFramerYUYV422(w, h, stride, size int) func([]byte, func()) (Frame, error) { 39 return func(b []byte, rel func()) (Frame, error) { 40 return frameYUYV422(size, stride, w, h, b, rel) 41 } 42 } 43 44 // Wrap a raw webcam frame in a Frame so that it can be used as an image. 45 func frameYUYV422(size, stride, w, h int, b []byte, rel func()) (Frame, error) { 46 if len(b) != size { 47 if rel != nil { 48 defer rel() 49 } 50 return nil, fmt.Errorf("Wrong frame length (exp: %d, read %d)", size, len(b)) 51 } 52 f := &fYUYV422{model: color.YCbCrModel, b: image.Rect(0, 0, w, h), stride: stride, frame: b, release: rel} 53 runtime.SetFinalizer(f, func(obj Frame) { 54 obj.Release() 55 }) 56 return f, nil 57 } 58 59 func (f *fYUYV422) ColorModel() color.Model { 60 return f.model 61 } 62 63 func (f *fYUYV422) Bounds() image.Rectangle { 64 return f.b 65 } 66 67 func (f *fYUYV422) At(x, y int) color.Color { 68 index := f.stride*y + (x&^1)*2 69 if x&1 == 0 { 70 return color.YCbCr{f.frame[index], f.frame[index+1], f.frame[index+3]} 71 } else { 72 return color.YCbCr{f.frame[index+2], f.frame[index+1], f.frame[index+3]} 73 } 74 } 75 76 // Done with frame, release back to camera (if required). 77 func (f *fYUYV422) Release() { 78 if f.release != nil { 79 f.release() 80 // Make sure it only gets called once. 81 f.release = nil 82 } 83 }