1 /* This file is part of the Pangolin Project.
2  * http://github.com/stevenlovegrove/Pangolin
3  *
4  * Copyright (c) 2014 Steven Lovegrove
5  *
6  * Permission is hereby granted, free of charge, to any person
7  * obtaining a copy of this software and associated documentation
8  * files (the "Software"), to deal in the Software without
9  * restriction, including without limitation the rights to use,
10  * copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the
12  * Software is furnished to do so, subject to the following
13  * conditions:
14  *
15  * The above copyright notice and this permission notice shall be
16  * included in all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20  * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22  * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25  * OTHER DEALINGS IN THE SOFTWARE.
26  */
27 
28 #include <pangolin/video/drivers/debayer.h>
29 #include <pangolin/factory/factory_registry.h>
30 #include <pangolin/video/iostream_operators.h>
31 
32 #ifdef HAVE_DC1394
33 #   include <dc1394/conversions.h>
34     const bool have_dc1394 = true;
35 #else
36     const bool have_dc1394 = false;
37 #endif
38 
39 namespace pangolin
40 {
41 
BayerOutputFormat(const StreamInfo & stream_in,bayer_method_t method,size_t start_offset)42 pangolin::StreamInfo BayerOutputFormat( const StreamInfo& stream_in, bayer_method_t method, size_t start_offset)
43 {
44     const bool downsample = (method == BAYER_METHOD_DOWNSAMPLE) || (method == BAYER_METHOD_DOWNSAMPLE_MONO);
45 
46     const size_t w = downsample ? stream_in.Width() / 2 : stream_in.Width();
47     const size_t h = downsample ? stream_in.Height() / 2 : stream_in.Height();
48 
49     pangolin::PixelFormat fmt =
50         (method == BAYER_METHOD_NONE) ?
51             stream_in.PixFormat() :
52             pangolin::PixelFormatFromString(
53                 (stream_in.PixFormat().bpp == 16) ?
54                 (method == BAYER_METHOD_DOWNSAMPLE_MONO ? "GRAY16LE" : "RGB48") :
55                 (method == BAYER_METHOD_DOWNSAMPLE_MONO ? "GRAY8" : "RGB24")
56             );
57 
58     fmt.channel_bit_depth = stream_in.PixFormat().channel_bit_depth;
59 
60     return pangolin::StreamInfo( fmt, w, h, w*fmt.bpp / 8, (unsigned char*)0 + start_offset );
61 }
62 
DebayerVideo(std::unique_ptr<VideoInterface> & src_,const std::vector<bayer_method_t> & bayer_method,color_filter_t tile)63 DebayerVideo::DebayerVideo(std::unique_ptr<VideoInterface> &src_, const std::vector<bayer_method_t>& bayer_method, color_filter_t tile)
64     : src(std::move(src_)), size_bytes(0), methods(bayer_method), tile(tile)
65 {
66     if(!src.get()) {
67         throw VideoException("DebayerVideo: VideoInterface in must not be null");
68     }
69     videoin.push_back(src.get());
70 
71     while(methods.size() < src->Streams().size()) {
72         methods.push_back(BAYER_METHOD_NONE);
73     }
74 
75     for(size_t s=0; s< src->Streams().size(); ++s) {
76         if( (methods[s] < BAYER_METHOD_NONE) && (!have_dc1394 || src->Streams()[0].IsPitched()) ) {
77             pango_print_warn("debayer: Switching to simple downsampling method because No DC1394 or image is pitched.\n");
78             methods[s] = BAYER_METHOD_DOWNSAMPLE;
79         }
80 
81         const StreamInfo& stin = src->Streams()[s];
82         streams.push_back(BayerOutputFormat(stin, methods[s], size_bytes));
83         size_bytes += streams.back().SizeBytes();
84     }
85 
86     buffer = std::unique_ptr<unsigned char[]>(new unsigned char[src->SizeBytes()]);
87 }
88 
~DebayerVideo()89 DebayerVideo::~DebayerVideo()
90 {
91 }
92 
93 //! Implement VideoInput::Start()
Start()94 void DebayerVideo::Start()
95 {
96     videoin[0]->Start();
97 }
98 
99 //! Implement VideoInput::Stop()
Stop()100 void DebayerVideo::Stop()
101 {
102     videoin[0]->Stop();
103 }
104 
105 //! Implement VideoInput::SizeBytes()
SizeBytes() const106 size_t DebayerVideo::SizeBytes() const
107 {
108     return size_bytes;
109 }
110 
111 //! Implement VideoInput::Streams()
Streams() const112 const std::vector<StreamInfo>& DebayerVideo::Streams() const
113 {
114     return streams;
115 }
116 
117 
AvailableFrames() const118 unsigned int DebayerVideo::AvailableFrames() const
119 {
120     BufferAwareVideoInterface* vpi = dynamic_cast<BufferAwareVideoInterface*>(videoin[0]);
121     if(!vpi)
122     {
123         pango_print_warn("Debayer: child interface is not buffer aware.");
124         return 0;
125     }
126     else
127     {
128         return vpi->AvailableFrames();
129     }
130 }
131 
DropNFrames(uint32_t n)132 bool DebayerVideo::DropNFrames(uint32_t n)
133 {
134     BufferAwareVideoInterface* vpi = dynamic_cast<BufferAwareVideoInterface*>(videoin[0]);
135     if(!vpi)
136     {
137         pango_print_warn("Debayer: child interface is not buffer aware.");
138         return false;
139     }
140     else
141     {
142         return vpi->DropNFrames(n);
143     }
144 }
145 
146 template<typename Tup, typename Tout, typename Tin>
DownsampleToMono(Image<Tout> & out,const Image<Tin> & in)147 void DownsampleToMono(Image<Tout>& out, const Image<Tin>& in)
148 {
149     for(int y=0; y< (int)out.h; ++y) {
150       Tout* pixout = out.RowPtr(y);
151       const Tin* irow0 = in.RowPtr(2*y);
152       const Tin* irow1 = in.RowPtr(2*y+1);
153       for(size_t x=0; x<out.w; ++x) {
154           Tup val = ((Tup)irow0[0] + (Tup)irow0[1] + (Tup)irow1[0] + (Tup)irow1[1]) / 4;
155           *(pixout++) = (Tout)std::min(std::max(static_cast<Tup>(0), val), static_cast<Tup>(std::numeric_limits<Tout>::max()));
156           irow0 += 2;
157           irow1 += 2;
158       }
159     }
160 }
161 
162 template<typename Tout, typename Tin>
DownsampleDebayer(Image<Tout> & out,const Image<Tin> & in,color_filter_t tile)163 void DownsampleDebayer(Image<Tout>& out, const Image<Tin>& in, color_filter_t tile)
164 {
165     switch(tile) {
166       case DC1394_COLOR_FILTER_RGGB:
167         for(int y=0; y< (int)out.h; ++y) {
168           Tout* pixout = out.RowPtr(y);
169           const Tin* irow0 = in.RowPtr(2*y);
170           const Tin* irow1 = in.RowPtr(2*y+1);
171           for(size_t x=0; x<out.w; ++x) {
172               *(pixout++) = irow0[2*x];
173               *(pixout++) = (irow0[2*x+1] + irow1[2*x]) >> 1;
174               *(pixout++) = irow1[2*x+1];
175           }
176         }
177         break;
178       case DC1394_COLOR_FILTER_GBRG:
179         for(int y=0; y< (int)out.h; ++y) {
180           Tout* pixout = out.RowPtr(y);
181           const Tin* irow0 = in.RowPtr(2*y);
182           const Tin* irow1 = in.RowPtr(2*y+1);
183           for(size_t x=0; x<out.w; ++x) {
184              *(pixout++) = irow1[2*x];
185              *(pixout++) = (irow0[2*x] + irow1[2*x+1]) >> 1;
186              *(pixout++) = irow0[2*x+1];
187           }
188         }
189         break;
190       case DC1394_COLOR_FILTER_GRBG:
191         for(int y=0; y< (int)out.h; ++y) {
192           Tout* pixout = out.RowPtr(y);
193           const Tin* irow0 = in.RowPtr(2*y);
194           const Tin* irow1 = in.RowPtr(2*y+1);
195           for(size_t x=0; x<out.w; ++x) {
196              *(pixout++) = irow0[2*x+1];
197              *(pixout++) = (irow0[2*x] + irow1[2*x+1]) >> 1;
198              *(pixout++) = irow1[2*x];
199           }
200         }
201         break;
202       case DC1394_COLOR_FILTER_BGGR:
203         for(int y=0; y< (int)out.h; ++y) {
204           Tout* pixout = out.RowPtr(y);
205           const Tin* irow0 = in.RowPtr(2*y);
206           const Tin* irow1 = in.RowPtr(2*y+1);
207           for(size_t x=0; x<out.w; ++x) {
208              *(pixout++) = irow1[2*x+1];
209              *(pixout++) = (irow0[2*x+1] + irow1[2*x]) >> 1;
210              *(pixout++) = irow0[2*x];
211           }
212         }
213         break;
214     }
215 }
216 
217 template<typename T>
PitchedImageCopy(Image<T> & img_out,const Image<T> & img_in)218 void PitchedImageCopy( Image<T>& img_out, const Image<T>& img_in ) {
219     if( img_out.w != img_in.w || img_out.h != img_in.h || sizeof(T) * img_in.w > img_out.pitch) {
220         throw std::runtime_error("PitchedImageCopy: Incompatible image sizes");
221     }
222 
223     for(size_t y=0; y < img_out.h; ++y) {
224         std::memcpy(img_out.RowPtr((int)y), img_in.RowPtr((int)y), sizeof(T) * img_in.w);
225     }
226 }
227 
228 template<typename Tout, typename Tin>
ProcessImage(Image<Tout> & img_out,const Image<Tin> & img_in,bayer_method_t method,color_filter_t tile)229 void ProcessImage(Image<Tout>& img_out, const Image<Tin>& img_in, bayer_method_t method, color_filter_t tile)
230 {
231     if(method == BAYER_METHOD_NONE) {
232         PitchedImageCopy(img_out, img_in.template UnsafeReinterpret<Tout>() );
233     }else if(method == BAYER_METHOD_DOWNSAMPLE_MONO) {
234         if( sizeof(Tout) == 1) {
235             DownsampleToMono<int,Tout, Tin>(img_out, img_in);
236         }else{
237             DownsampleToMono<double,Tout, Tin>(img_out, img_in);
238         }
239     }else if(method == BAYER_METHOD_DOWNSAMPLE) {
240         DownsampleDebayer(img_out, img_in, tile);
241     }else{
242 #ifdef HAVE_DC1394
243         if(sizeof(Tout) == 1) {
244             dc1394_bayer_decoding_8bit(
245                 (uint8_t*)img_in.ptr, (uint8_t*)img_out.ptr, img_in.w, img_in.h,
246                 (dc1394color_filter_t)tile, (dc1394bayer_method_t)method
247             );
248         }else if(sizeof(Tout) == 2) {
249             dc1394_bayer_decoding_16bit(
250                 (uint16_t*)img_in.ptr, (uint16_t*)img_out.ptr, img_in.w, img_in.h,
251                 (dc1394color_filter_t)tile, (dc1394bayer_method_t)method,
252                 16
253             );
254         }
255 #endif
256     }
257 }
258 
ProcessStreams(unsigned char * out,const unsigned char * in)259 void DebayerVideo::ProcessStreams(unsigned char* out, const unsigned char *in)
260 {
261     for(size_t s=0; s<streams.size(); ++s) {
262         const StreamInfo& stin = videoin[0]->Streams()[s];
263         Image<unsigned char> img_in  = stin.StreamImage(in);
264         Image<unsigned char> img_out = Streams()[s].StreamImage(out);
265 
266         if(methods[s] == BAYER_METHOD_NONE) {
267             const size_t num_bytes = std::min(img_in.w, img_out.w) * stin.PixFormat().bpp / 8;
268             for(size_t y=0; y < img_out.h; ++y) {
269                 std::memcpy(img_out.RowPtr((int)y), img_in.RowPtr((int)y), num_bytes);
270             }
271         }else if(stin.PixFormat().bpp == 8) {
272             ProcessImage(img_out, img_in, methods[s], tile);
273         }else if(stin.PixFormat().bpp == 16){
274             Image<uint16_t> img_in16  = img_in.UnsafeReinterpret<uint16_t>();
275             Image<uint16_t> img_out16 = img_out.UnsafeReinterpret<uint16_t>();
276             ProcessImage(img_out16, img_in16, methods[s], tile);
277         }else {
278             throw std::runtime_error("debayer: unhandled format combination: " + stin.PixFormat().format );
279         }
280     }
281 }
282 
283 //! Implement VideoInput::GrabNext()
GrabNext(unsigned char * image,bool wait)284 bool DebayerVideo::GrabNext( unsigned char* image, bool wait )
285 {
286     if(videoin[0]->GrabNext(buffer.get(),wait)) {
287         ProcessStreams(image, buffer.get());
288         return true;
289     }else{
290         return false;
291     }
292 }
293 
294 //! Implement VideoInput::GrabNewest()
GrabNewest(unsigned char * image,bool wait)295 bool DebayerVideo::GrabNewest( unsigned char* image, bool wait )
296 {
297     if(videoin[0]->GrabNewest(buffer.get(),wait)) {
298         ProcessStreams(image, buffer.get());
299         return true;
300     }else{
301         return false;
302     }
303 }
304 
InputStreams()305 std::vector<VideoInterface*>& DebayerVideo::InputStreams()
306 {
307     return videoin;
308 }
309 
ColorFilterFromString(std::string str)310 color_filter_t DebayerVideo::ColorFilterFromString(std::string str)
311 {
312   if(!str.compare("rggb") || !str.compare("RGGB")) return DC1394_COLOR_FILTER_RGGB;
313   else if(!str.compare("gbrg") || !str.compare("GBRG")) return DC1394_COLOR_FILTER_GBRG;
314   else if(!str.compare("grbg") || !str.compare("GRBG")) return DC1394_COLOR_FILTER_GRBG;
315   else if(!str.compare("bggr") || !str.compare("BGGR")) return DC1394_COLOR_FILTER_BGGR;
316   else {
317      pango_print_error("Debayer error, %s is not a valid tile type using RGGB\n", str.c_str());
318      return DC1394_COLOR_FILTER_RGGB;
319   }
320 }
321 
BayerMethodFromString(std::string str)322 bayer_method_t DebayerVideo::BayerMethodFromString(std::string str)
323 {
324   if(!str.compare("nearest")) return BAYER_METHOD_NEAREST;
325   else if(!str.compare("simple")) return BAYER_METHOD_SIMPLE;
326   else if(!str.compare("bilinear")) return BAYER_METHOD_BILINEAR;
327   else if(!str.compare("hqlinear")) return BAYER_METHOD_HQLINEAR;
328   else if(!str.compare("downsample")) return BAYER_METHOD_DOWNSAMPLE;
329   else if(!str.compare("edgesense")) return BAYER_METHOD_EDGESENSE;
330   else if(!str.compare("vng")) return BAYER_METHOD_VNG;
331   else if(!str.compare("ahd")) return BAYER_METHOD_AHD;
332   else if(!str.compare("mono")) return BAYER_METHOD_DOWNSAMPLE_MONO;
333   else if(!str.compare("none")) return BAYER_METHOD_NONE;
334   else {
335      pango_print_error("Debayer error, %s is not a valid debayer method using downsample\n", str.c_str());
336      return BAYER_METHOD_DOWNSAMPLE;
337   }
338 }
339 
PANGOLIN_REGISTER_FACTORY(DebayerVideo)340 PANGOLIN_REGISTER_FACTORY(DebayerVideo)
341 {
342     struct DebayerVideoFactory final : public FactoryInterface<VideoInterface> {
343         std::unique_ptr<VideoInterface> Open(const Uri& uri) override {
344             std::unique_ptr<VideoInterface> subvid = pangolin::OpenVideo(uri.url);
345             const std::string tile_string = uri.Get<std::string>("tile","rggb");
346             const std::string method = uri.Get<std::string>("method","none");
347             const color_filter_t tile = DebayerVideo::ColorFilterFromString(tile_string);
348 
349             std::vector<bayer_method_t> methods;
350             for(size_t s=0; s < subvid->Streams().size(); ++s) {
351                 const std::string key = std::string("method") + ToString(s+1);
352                 std::string method_s = uri.Get<std::string>(key, method);
353                 methods.push_back(DebayerVideo::BayerMethodFromString(method_s));
354             }
355             return std::unique_ptr<VideoInterface>( new DebayerVideo(subvid, methods, tile) );
356         }
357     };
358 
359     FactoryRegistry<VideoInterface>::I().RegisterFactory(std::make_shared<DebayerVideoFactory>(), 10, "debayer");
360 }
361 
362 }
363