set overwrite on LV2_PATH pref env update
[goodguy/cinelerra.git] / cinelerra-5.1 / cinelerra / devicev4l2base.C
1
2 /*
3  * CINELERRA
4  * Copyright (C) 2008 Adam Williams <broadcast at earthling dot net>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21
22
23 #ifdef HAVE_VIDEO4LINUX2
24
25 #include "bctimer.h"
26 #include "channel.h"
27 #include "chantables.h"
28 #include "clip.h"
29 #include "condition.h"
30 #include "devicev4l2base.h"
31 #include "mutex.h"
32 #include "picture.h"
33 #include "preferences.h"
34 #include "recordconfig.h"
35 #include "videodevice.h"
36
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <stdint.h>
40 #include <unistd.h>
41 #include <string.h>
42 #include <errno.h>
43 #include <fcntl.h>
44
45 #include <linux/videodev2.h>
46 #include <sys/ioctl.h>
47 #include <sys/mman.h>
48
49
50 DeviceV4L2BufferQ::
51 DeviceV4L2BufferQ(int qsize)
52 {
53         reset();
54         bfr_lock = new Mutex("DeviceV4L2BufferQ::bfr_lock");
55         buffers = new int[limit=qsize];
56 }
57
58 DeviceV4L2BufferQ::
59 ~DeviceV4L2BufferQ()
60 {
61         delete [] buffers;
62         delete bfr_lock;
63 }
64
65 int DeviceV4L2BufferQ::q(int bfr)
66 {
67         int result = 0;
68         bfr_lock->lock("DeviceV4L2Buffer::q");
69         int in1 = in+1;
70         if( in1 >= limit ) in1 = 0;
71         if( in1 != out )
72         {
73                 buffers[in] = bfr;
74                 in = in1;
75         }
76         else
77                 result = -1;
78         bfr_lock->unlock();
79         return result;
80 }
81
82 int DeviceV4L2BufferQ::dq(Condition *time_lock, int time_out)
83 {
84         int result = -1;
85         bfr_lock->lock(" DeviceV4L2Buffer::dq 0");
86         time_lock->reset();
87         if( in == out )
88         {
89                 bfr_lock->unlock();
90                 if( time_lock->timed_lock(time_out, "DeviceV4L2Buffer::dq 1") )
91                         printf("DeviceV4L2Buffer::wait time_out\n");
92                 bfr_lock->lock(" DeviceV4L2Buffer::dq 2");
93         }
94         if( in != out )
95         {
96                 result = buffers[out];
97                 int out1 = out+1;
98                 if( out1 >= limit ) out1 = 0;
99                 out = out1;
100         }
101         bfr_lock->unlock();
102         return result;
103 }
104
105 int DeviceV4L2BufferQ::dq()
106 {
107         int result = -1;
108         bfr_lock->lock(" DeviceV4L2Buffer::dq");
109         if( in != out )
110         {
111                 result = buffers[out];
112                 int out1 = out+1;
113                 if( out1 >= limit ) out1 = 0;
114                 out = out1;
115         }
116         bfr_lock->unlock();
117         return result;
118 }
119
120
121
122 DeviceV4L2Base::DeviceV4L2Base()
123  : Thread(1, 0, 0)
124 {
125         v4l2_lock = new Mutex("DeviceV4L2Input::v4l2_lock", 0);
126         qbfrs_lock = new Mutex("DeviceV4L2Base::qbfrs_lock");
127         video_lock = new Condition(0, "DeviceV4L2Base::video_lock", 1);
128         dev_fd = -1;
129         iwidth = 0;
130         iheight = 0;
131         color_model = -1;
132         device_buffers = 0;
133         device_channel = 0;
134         total_buffers = 0;
135         streamon = 0;
136         dev_status = 0;
137         opened = 0;
138         q_bfrs = 0;
139         done = 0;
140         put_thread = 0;
141 }
142
143 DeviceV4L2Base::~DeviceV4L2Base()
144 {
145         close_dev();
146         delete video_lock;
147         delete qbfrs_lock;
148         delete v4l2_lock;
149 }
150
151
152
153 DeviceV4L2Put::DeviceV4L2Put(DeviceV4L2Base *v4l2)
154  : Thread(1, 0, 0)
155 {
156         this->v4l2 = v4l2;
157         done = 0;
158         putq = new DeviceV4L2BufferQ(256);
159         buffer_lock = new Condition(0, "DeviceV4L2Put::buffer_lock");
160 }
161
162 DeviceV4L2Put::~DeviceV4L2Put()
163 {
164         if(Thread::running())
165         {
166                 done = 1;
167                 buffer_lock->unlock();
168                 Thread::cancel();
169         }
170         Thread::join();
171         delete buffer_lock;
172         delete putq;
173 }
174
175
176 void DeviceV4L2Put::run()
177 {
178         while(!done)
179         {
180                 buffer_lock->lock("DeviceV4L2Put::run");
181                 if(done) break;
182                 int bfr = putq->dq();
183                 if( bfr < 0 ) continue;
184                 struct v4l2_buffer arg;
185                 memset(&arg, 0, sizeof(arg));
186                 arg.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
187                 arg.index = bfr;
188                 arg.memory = V4L2_MEMORY_MMAP;
189
190                 Thread::enable_cancel();
191                 v4l2->qbfrs_lock->lock("DeviceV4L2Put::run");
192 // This locks up if there's no signal.
193                 if( v4l2->vioctl(VIDIOC_QBUF, &arg) < 0 )
194                         perror("DeviceV4L2Put::run 1 VIDIOC_QBUF");
195                 else
196                         ++v4l2->q_bfrs;
197                 v4l2->qbfrs_lock->unlock();
198                 Thread::disable_cancel();
199         }
200 }
201
202
203
204
205 int DeviceV4L2Base::get_sources()
206 {
207         v4l2_lock->lock("DeviceV4L2Base::get_sources");
208         VideoDevice *video_device = v4l2_device();
209         if( !video_device ) return 1;
210         const char *dev_path = video_device->in_config->get_path();
211         int vfd = open(dev_path, O_RDWR+O_CLOEXEC);
212         if(vfd < 0)
213         {
214                 perror("DeviceV4L2Base::get_sources open failed");
215                 printf("DeviceV4L2Base::get_sources path: %s\n", dev_path);
216                 return 1;
217         }
218
219 // Get the Inputs
220
221         for(int i = 0; i < 20; ++i)
222         {
223                 struct v4l2_input arg;
224                 memset(&arg, 0, sizeof(arg));
225                 arg.index = i;
226
227                 if(ioctl(vfd, VIDIOC_ENUMINPUT, &arg) < 0) break;
228                 Channel *channel = video_device->new_input_source((char*)arg.name);
229                 channel->device_index = i;
230                 channel->tuner = arg.type == V4L2_INPUT_TYPE_TUNER ? arg.tuner : -1;
231         }
232
233 // Get the picture controls
234         for(int i = V4L2_CID_BASE; i < V4L2_CID_LASTP1; i++)
235         {
236                 struct v4l2_queryctrl arg;
237                 memset(&arg, 0, sizeof(arg));
238                 arg.id = i;
239 // This returns errors for unsupported controls which is what we want.
240                 if(!ioctl(vfd, VIDIOC_QUERYCTRL, &arg))
241                 {
242 // Test if control exists already
243                         if(!video_device->picture->get_item((const char*)arg.name, arg.id))
244                         {
245 // Add control
246                                 PictureItem *item = video_device->picture->new_item((const char*)arg.name);
247                                 item->device_id = arg.id;
248                                 item->min = arg.minimum;
249                                 item->max = arg.maximum;
250                                 item->step = arg.step;
251                                 item->default_ = arg.default_value;
252                                 item->type = arg.type;
253                                 item->value = arg.default_value;
254                         }
255                 }
256         }
257
258 // Load defaults for picture controls
259         video_device->picture->load_defaults();
260
261         close(vfd);
262         v4l2_lock->unlock();
263         return 0;
264 }
265
266 int DeviceV4L2Base::vioctl(unsigned long int req, void *arg)
267 {
268         int result = ioctl(dev_fd, req, arg);
269         return result;
270 }
271
272 int DeviceV4L2Base::v4l2_open(int color_model)
273 {
274         VideoDevice *video_device = v4l2_device();
275         if( !video_device ) return 1;
276
277         struct v4l2_capability cap;
278         memset(&cap, 0, sizeof(cap));
279         if(vioctl(VIDIOC_QUERYCAP, &cap))
280                 perror("DeviceV4L2Base::v4l2_open VIDIOC_QUERYCAP");
281
282 // printf("DeviceV4L2Base::v4l2_open dev_fd=%d driver=%s card=%s bus_info=%s version=%d\n",
283 // dev_fd(), cap.driver, cap.card, cap.bus_info, cap.version);
284 // printf("    ");
285 // if( (cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) ) printf("VIDEO_CAPTURE ");
286 // if( (cap.capabilities & V4L2_CAP_VIDEO_OUTPUT)  ) printf("VIDEO_OUTPUT ");
287 // if( (cap.capabilities & V4L2_CAP_VIDEO_OVERLAY) ) printf("VIDEO_OVERLAY ");
288 // if( (cap.capabilities & V4L2_CAP_VBI_CAPTURE)   ) printf("VBI_CAPTURE ");
289 // if( (cap.capabilities & V4L2_CAP_VBI_OUTPUT)    ) printf("VBI_OUTPUT ");
290 // if( (cap.capabilities & V4L2_CAP_RDS_CAPTURE)   ) printf("RDS_CAPTURE ");
291 // if( (cap.capabilities & V4L2_CAP_TUNER)         ) printf("TUNER ");
292 // if( (cap.capabilities & V4L2_CAP_AUDIO)         ) printf("AUDIO ");
293 // if( (cap.capabilities & V4L2_CAP_RADIO)         ) printf("RADIO ");
294 // if( (cap.capabilities & V4L2_CAP_READWRITE)     ) printf("READWRITE ");
295 // if( (cap.capabilities & V4L2_CAP_ASYNCIO)       ) printf("ASYNCIO ");
296 // if( (cap.capabilities & V4L2_CAP_STREAMING)     ) printf("STREAMING ");
297 // printf("\n");
298
299         int config_width = video_device->in_config->w;
300         int config_height = video_device->in_config->h;
301         int config_area = config_width * config_height;
302         int best_width = config_width;
303         int best_height = config_height;
304         unsigned int best_format = 0;
305         int best_merit = 0;
306         int best_color_model = -1;
307         int best_area = INT_MAX;
308         int driver = video_device->in_config->driver;
309
310         for( int i=0; i<20; ++i ) {
311                 struct v4l2_fmtdesc fmt;
312                 memset(&fmt,0,sizeof(fmt));
313                 fmt.index = i;
314                 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
315                 if( vioctl(VIDIOC_ENUM_FMT,&fmt) != 0 ) break;
316                 printf("DeviceV4L2Base::v4l2_open");
317                 // printf("format=\"%s\";",&fmt.description[0]);
318                 printf(" pixels=\"%4.4s\"; res=\"",(char*)&fmt.pixelformat);
319
320                 int merit = 0;
321                 int cmodel = -1;
322                 switch(fmt.pixelformat)
323                 {
324                 case V4L2_PIX_FMT_YUYV:    cmodel = BC_YUV422;  merit = 4;  break;
325                 case V4L2_PIX_FMT_UYVY:    cmodel = BC_UVY422;  merit = 4;  break;
326                 case V4L2_PIX_FMT_Y41P:    cmodel = BC_YUV411P; merit = 1;  break;
327                 case V4L2_PIX_FMT_YVU420:  cmodel = BC_YUV420P; merit = 3;  break;
328                 case V4L2_PIX_FMT_YUV422P: cmodel = BC_YUV422P; merit = 4;  break;
329                 case V4L2_PIX_FMT_RGB24:   cmodel = BC_RGB888;  merit = 6;  break;
330                 case V4L2_PIX_FMT_MJPEG:
331                         cmodel = BC_COMPRESSED;
332                         merit = driver == VIDEO4LINUX2JPEG ||
333                                 driver == CAPTURE_JPEG_WEBCAM ? 7 : 0;
334                         break;
335                 case V4L2_PIX_FMT_MPEG:
336                         cmodel = BC_YUV420P;
337                         merit = driver == VIDEO4LINUX2MPEG ? 7 : 2;
338                         break;
339                 }
340                 if( cmodel >= 0 && merit > best_merit )
341                 {
342                         best_merit = merit;
343                         best_format = fmt.pixelformat;
344                         best_color_model = cmodel;
345                 }
346
347                 for( int n=0; n<20; ++n ) {
348                         struct v4l2_frmsizeenum fsz;
349                         memset(&fsz,0,sizeof(fsz));
350                         fsz.index = n;
351                         fsz.pixel_format = fmt.pixelformat;
352                         if( vioctl(VIDIOC_ENUM_FRAMESIZES,&fsz) != 0 ) break;
353                         int w = fsz.discrete.width, h = fsz.discrete.height;
354                         if( n > 0 ) printf(" ");
355                         printf("%dx%d",w,h);
356                         int area = w * h;
357                         if( area > config_area ) continue;
358                         int diff = abs(area-config_area);
359                         if( diff < best_area ) {
360                                 best_area = diff;
361                                 best_width = w;
362                                 best_height = h;
363                         }
364                 }
365                 printf("\"\n");
366         }
367
368         if( !best_format )
369         {
370                 printf("DeviceV4L2Base::v4l2_open cant determine best_format\n");
371                 switch(driver)
372                 {
373                 case VIDEO4LINUX2JPEG:
374                         best_format = V4L2_PIX_FMT_MJPEG;
375                         break;
376                 case VIDEO4LINUX2MPEG:
377                         best_format = V4L2_PIX_FMT_MPEG;
378                         break;
379                 default:
380                         best_color_model = color_model;
381                         best_format = cmodel_to_device(color_model);
382                         break;
383                 }
384                 printf("DeviceV4L2Base::v4l2_open ");
385                 printf(_(" attempting format %4.4s\n"),
386                         (char *)&best_format);
387         }
388         if(driver == VIDEO4LINUX2JPEG && best_format != V4L2_PIX_FMT_MJPEG)
389         {
390                 printf("DeviceV4L2Base::v4l2_open ");
391                 printf(_("jpeg driver and best_format not mjpeg (%4.4s)\n"),
392                         (char *)&best_format);
393                 return 1;
394         }
395         if(driver == VIDEO4LINUX2MPEG && best_format != V4L2_PIX_FMT_MPEG)
396         {
397                 printf("DeviceV4L2Base::v4l2_open ");
398                 printf(_("mpeg driver and best_format not mpeg (%4.4s)\n"),
399                         (char *)&best_format);
400                 return 1;
401         }
402         if(config_width != best_width || config_height != best_height)
403         {
404                 printf("DeviceV4L2Base::v4l2_open ");
405                 printf(_("config geom %dx%d != %dx%d best_geom\n"),
406                         config_width, config_height, best_width, best_height);
407         }
408
409 // Set up frame rate
410         struct v4l2_streamparm v4l2_parm;
411         memset(&v4l2_parm, 0, sizeof(v4l2_parm));
412         v4l2_parm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
413         if(vioctl(VIDIOC_G_PARM, &v4l2_parm) < 0)
414                 perror("DeviceV4L2Base::v4l2_open VIDIOC_G_PARM");
415         if(v4l2_parm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME)
416         {
417                 v4l2_parm.parm.capture.capturemode |= V4L2_CAP_TIMEPERFRAME;
418                 v4l2_parm.parm.capture.timeperframe.numerator = 1;
419                 v4l2_parm.parm.capture.timeperframe.denominator =
420                         (unsigned long)((float)1 /
421                         video_device->frame_rate * 10000000);
422                 if(vioctl(VIDIOC_S_PARM, &v4l2_parm) < 0)
423                         perror("DeviceV4L2Base::v4l2_open VIDIOC_S_PARM");
424
425                 if(vioctl(VIDIOC_G_PARM, &v4l2_parm) < 0)
426                         perror("DeviceV4L2Base::v4l2_open VIDIOC_G_PARM");
427         }
428
429         printf("v4l2 s_fmt %dx%d %4.4s\n", best_width, best_height, (char*)&best_format);
430 // Set up data format
431         struct v4l2_format v4l2_params;
432         memset(&v4l2_params, 0, sizeof(v4l2_params));
433         v4l2_params.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
434         if(vioctl(VIDIOC_G_FMT, &v4l2_params) < 0)
435                 perror("DeviceV4L2Base::v4l2_open VIDIOC_G_FMT 1");
436         v4l2_params.fmt.pix.width = best_width;
437         v4l2_params.fmt.pix.height = best_height;
438         v4l2_params.fmt.pix.pixelformat = best_format;
439         if(vioctl(VIDIOC_S_FMT, &v4l2_params) < 0)
440                 perror("DeviceV4L2Base::v4l2_open VIDIOC_S_FMT");
441         memset(&v4l2_params, 0, sizeof(v4l2_params));
442         v4l2_params.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
443         if(vioctl(VIDIOC_G_FMT, &v4l2_params) < 0)
444                 perror("DeviceV4L2Base::v4l2_open VIDIOC_G_FMT 2");
445         if( v4l2_params.fmt.pix.pixelformat != best_format )
446         {
447                 printf("DeviceV4L2Base::v4l2_open  set format %4.4s != %4.4s best_format\n",
448                          (char*)&v4l2_params.fmt.pix.pixelformat, (char*)&best_format);
449                 return 1;
450         }
451         iwidth = v4l2_params.fmt.pix.width;
452         iheight = v4l2_params.fmt.pix.height;
453         if( iwidth != best_width || iheight != best_height )
454         {
455                 printf("DeviceV4L2Base::v4l2_open  set geom %dx%d != %dx%d best_geom\n",
456                         iwidth, iheight, best_width, best_height);
457                 return 1;
458         }
459
460 // Set picture controls.  This driver requires the values to be set once to default
461 // values and then again to different values before it takes up the values.
462 // Unfortunately VIDIOC_S_CTRL resets the audio to mono in 2.6.7.
463         PictureConfig *picture = video_device->picture;
464         for(int i = 0; i < picture->controls.total; i++)
465         {
466                 struct v4l2_queryctrl arg;
467                 memset(&arg, 0, sizeof(arg));
468                 PictureItem *item = picture->controls.values[i];
469                 arg.id = item->device_id;
470                 if(!vioctl(VIDIOC_QUERYCTRL, &arg))
471                 {
472                         struct v4l2_control ctrl_arg;
473                         memset(&ctrl_arg, 0, sizeof(ctrl_arg));
474                         ctrl_arg.id = item->device_id;
475                         ctrl_arg.value = 0;
476                         if(vioctl(VIDIOC_S_CTRL, &ctrl_arg) < 0)
477                                 perror("DeviceV4L2Base::v4l2_open VIDIOC_S_CTRL");
478                 }
479                 else
480                 {
481                         printf("DeviceV4L2Base::v4l2_open VIDIOC_S_CTRL 1 %s/id %08x failed\n",
482                                 item->name, item->device_id);
483                 }
484         }
485
486
487         for(int i = 0; i < picture->controls.total; i++)
488         {
489                 struct v4l2_queryctrl arg;
490                 memset(&arg, 0, sizeof(arg));
491                 PictureItem *item = picture->controls.values[i];
492                 arg.id = item->device_id;
493
494                 if(!vioctl(VIDIOC_QUERYCTRL, &arg))
495                 {
496                         struct v4l2_control ctrl_arg;
497                         memset(&ctrl_arg, 0, sizeof(ctrl_arg));
498                         ctrl_arg.id = item->device_id;
499                         ctrl_arg.value = item->value;
500                         if(vioctl(VIDIOC_S_CTRL, &ctrl_arg) < 0)
501                                 perror("DeviceV4L2Base::v4l2_open VIDIOC_S_CTRL");
502                 }
503                 else
504                 {
505                         printf("DeviceV4L2Base::v4l2_open VIDIOC_S_CTRL 2 %s/id %08x failed\n",
506                                 item->name, item->device_id);
507                 }
508         }
509
510
511 // Set input
512         Channel *video_channel = video_device->channel;
513         ArrayList<Channel*> *inputs = video_device->get_inputs();
514         int input = video_channel->input;
515         device_channel = input >= 0 && input < inputs->total ?
516                 inputs->values[input] : 0;
517         if(!device_channel)
518         {
519 // Try first input
520                 if(inputs->total)
521                 {
522                         device_channel = inputs->values[0];
523                         printf("DeviceV4L2Base::v4l2_open user channel not found.  Using %s\n",
524                                 device_channel->device_name);
525                 }
526                 else
527                 {
528                         printf("DeviceV4L2Base::v4l2_open channel \"%s\" not found.\n",
529                                 video_channel->title);
530                 }
531         }
532
533 // Translate input to API structures
534         input = device_channel ? device_channel->device_index : 0;
535         if(vioctl(VIDIOC_S_INPUT, &input) < 0)
536                 perror("DeviceV4L2Base::v4l2_open VIDIOC_S_INPUT");
537
538 // Set norm
539         v4l2_std_id std_id = 0;
540         switch(video_channel->norm)
541         {
542                 case NTSC: std_id = V4L2_STD_NTSC; break;
543                 case PAL: std_id = V4L2_STD_PAL; break;
544                 case SECAM: std_id = V4L2_STD_SECAM; break;
545                 default: std_id = V4L2_STD_NTSC_M; break;
546         }
547         if(vioctl(VIDIOC_S_STD, &std_id))
548                 perror("DeviceV4L2Base::v4l2_open VIDIOC_S_STD");
549
550         int dev_tuner = device_channel ? device_channel->tuner : -1;
551         if( (cap.capabilities & V4L2_CAP_TUNER) && dev_tuner >= 0 )
552         {
553                 struct v4l2_tuner tuner;
554                 memset(&tuner, 0, sizeof(tuner));
555                 tuner.index = dev_tuner;
556                 if(!vioctl(VIDIOC_G_TUNER, &tuner))
557                 {
558 // printf("DeviceV4L2Base::v4l2_open audmode=%d rxsubchans=%d\n",
559 //   tuner.audmode, tuner.rxsubchans);
560                         tuner.index = dev_tuner;
561                         tuner.type = V4L2_TUNER_ANALOG_TV;
562                         tuner.audmode = V4L2_TUNER_MODE_STEREO;
563                         tuner.rxsubchans = V4L2_TUNER_SUB_STEREO;
564                         if(vioctl(VIDIOC_S_TUNER, &tuner) < 0)
565                                 perror("DeviceV4L2Base::v4l2_open VIDIOC_S_TUNER");
566 // Set frequency
567                         struct v4l2_frequency frequency;
568                         memset(&frequency, 0, sizeof(frequency));
569                         frequency.tuner = video_channel->tuner;
570                         frequency.type = V4L2_TUNER_ANALOG_TV;
571                         int table = video_channel->freqtable;
572                         int entry = video_channel->entry;
573                         frequency.frequency = (int)(chanlists[table].list[entry].freq * 0.016);
574 // printf("DeviceV4L2Base::v4l2_open tuner=%d freq=%d norm=%d\n",
575 //   video_channel->tuner, frequency.frequency, video_channel->norm);
576                         if(vioctl(VIDIOC_S_FREQUENCY, &frequency) < 0)
577                                 perror("DeviceV4L2Base::v4l2_open VIDIOC_S_FREQUENCY");
578                 }
579                 else
580                         perror("DeviceV4L2Base::v4l2_open VIDIOC_G_TUNER");
581         }
582
583 // Set compression
584         if(color_model == BC_COMPRESSED)
585         {
586                 struct v4l2_jpegcompression jpeg_arg;
587                 memset(&jpeg_arg, 0, sizeof(jpeg_arg));
588                 if(vioctl(VIDIOC_G_JPEGCOMP, &jpeg_arg) < 0)
589                         perror("DeviceV4L2Base::v4l2_open VIDIOC_G_JPEGCOMP");
590                 jpeg_arg.quality = video_device->quality / 2;
591                 if(vioctl(VIDIOC_S_JPEGCOMP, &jpeg_arg) < 0)
592                         perror("DeviceV4L2Base::v4l2_open VIDIOC_S_JPEGCOMP");
593         }
594
595         this->color_model = best_color_model;
596         return 0;
597 }
598
599 int DeviceV4L2Base::v4l2_status()
600 {
601         int result = 1;
602         Channel *channel = device_channel;
603         if( !channel )
604         {
605                 dev_status = 0;
606         }
607         else if( channel->tuner >= 0 )
608         {
609                 struct v4l2_tuner tuner;
610                 memset(&tuner,0,sizeof(tuner));
611                 tuner.index = channel->tuner;
612                 if( !vioctl(VIDIOC_G_TUNER, &tuner) )
613                 {
614                         dev_status = tuner.signal ? 1 : 0;
615                         result = 0;
616                 }
617                 else
618                         perror("DeviceV4L2Base::v4l2_status VIDIOC_S_TUNER");
619         }
620         else
621         {
622                 struct v4l2_input arg;
623                 memset(&arg, 0, sizeof(arg));
624                 arg.index = channel->device_index;
625                 if( !vioctl(VIDIOC_ENUMINPUT, &arg) )
626                 {
627                         dev_status = (arg.status &
628                         (V4L2_IN_ST_NO_POWER | V4L2_IN_ST_NO_SIGNAL)) ? 0 : 1;
629                         result = 0;
630                 }
631                 else
632                         perror("DeviceV4L2Base::v4l2_status VIDIOC_ENUMINPUT");
633         }
634         return result;
635 }
636
637 void DeviceV4L2Base::dev_close()
638 {
639         if( dev_fd >= 0 )
640         {
641                 ::close(dev_fd);
642                 dev_fd = -1;
643         }
644 }
645
646 int DeviceV4L2Base::dev_open()
647 {
648         if( dev_fd < 0 )
649         {
650                 VideoDevice *video_device = v4l2_device();
651                 if( !video_device )
652                 {
653                         printf("DeviceV4L2Base::dev_open: video_device not available\n");
654                         Timer::delay(250);
655                         return -1;
656                 }
657                 const char *dev_path = video_device->in_config->get_path();
658                 dev_fd = open(dev_path, O_RDWR);
659                 if( dev_fd < 0 )
660                 {
661                         perror("DeviceV4L2Base::dev_open: open_failed");
662                         printf("DeviceV4L2Base::dev_open: dev_path %s\n", dev_path);
663                         return 1;
664                 }
665                 video_device->set_cloexec_flag(dev_fd, 1);
666         }
667         return 0;
668 }
669
670
671 int DeviceV4L2Base::open_dev(int color_model)
672 {
673         v4l2_lock->lock("DeviceV4L2Base::open_dev");
674         int result = 0;
675         if( !opened )
676         {
677                 result = dev_open();
678                 if( !result )
679                         result = v4l2_open(color_model);
680                 if( !result )
681                         result = start_dev();
682                 if( !result )
683                 {
684                         qbfrs_lock->reset();
685                         video_lock->reset();
686                         getq = new DeviceV4L2BufferQ(total_buffers+1);
687                         put_thread = new DeviceV4L2Put(this);
688                         put_thread->start();
689                         done = 0;
690                         Thread::start();
691                 }
692                 else
693                         printf("DeviceV4L2Base::open_dev failed\n");
694         }
695         if( result )
696         {
697                 printf("DeviceV4L2Base::open_dev: adaptor open failed\n");
698                 stop_dev();
699                 dev_close();
700         }
701         else
702                 opened = 1;
703         v4l2_lock->unlock();
704         return result;
705 }
706
707 void DeviceV4L2Base::close_dev()
708 {
709         v4l2_lock->lock("DeviceV4L2Base::close_dev");
710         if( opened )
711         {
712                 if(Thread::running())
713                 {
714                         done = 1;
715                         Thread::cancel();
716                 }
717                 Thread::join();
718                 if(put_thread)
719                 {
720                         delete put_thread;
721                         put_thread = 0;
722                 }
723                 stop_dev();
724                 dev_close();
725                 delete getq;
726                 getq = 0;
727                 opened = 0;
728         }
729         v4l2_lock->unlock();
730 }
731
732 int DeviceV4L2Base::status_dev()
733 {
734         v4l2_lock->lock("DeviceV4L2Base::status_dev");
735         int result = dev_fd >= 0 ? v4l2_status() : 1;
736         v4l2_lock->unlock();
737         return result;
738 }
739
740 unsigned int DeviceV4L2Base::cmodel_to_device(int color_model)
741 {
742         switch(color_model)
743         {
744         case BC_COMPRESSED:     return V4L2_PIX_FMT_MJPEG;
745         case BC_YUV422:         return V4L2_PIX_FMT_YUYV;
746         case BC_UVY422:         return V4L2_PIX_FMT_UYVY;
747         case BC_YUV411P:        return V4L2_PIX_FMT_Y41P;
748         case BC_YUV420P:        return V4L2_PIX_FMT_YVU420;
749         case BC_YUV422P:        return V4L2_PIX_FMT_YUV422P;
750         case BC_RGB888:         return V4L2_PIX_FMT_RGB24;
751         }
752         return 0;
753 }
754
755 DeviceV4L2VFrame::DeviceV4L2VFrame(int dev_fd, unsigned long ofs, unsigned long sz)
756 {
757         dev_data = (unsigned char*)mmap(NULL, dev_size=sz,
758                 PROT_READ | PROT_WRITE, MAP_SHARED, dev_fd, ofs);
759         if(dev_data == MAP_FAILED) {
760                 perror("DeviceV4L2VFrame::DeviceV4L2VFrame: mmap");
761                 dev_data = 0;
762         }
763 }
764
765
766 DeviceV4L2VFrame::~DeviceV4L2VFrame()
767 {
768         munmap(dev_data, dev_size);
769 }
770
771 int DeviceV4L2Base::start_dev()
772 {
773         VideoDevice *video_device = v4l2_device();
774         if( !video_device ) return 1;
775
776 // Errors here are fatal.
777         int req_buffers = video_device->in_config->capture_length;
778         req_buffers = MAX(req_buffers, 2);
779         req_buffers = MIN(req_buffers, 0xff);
780
781         struct v4l2_requestbuffers requestbuffers;
782         memset(&requestbuffers, 0, sizeof(requestbuffers));
783 //printf("DeviceV4L2Base::start_dev requested %d buffers\n", req_buffers);
784         requestbuffers.count = req_buffers;
785         requestbuffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
786         requestbuffers.memory = V4L2_MEMORY_MMAP;
787         if(vioctl(VIDIOC_REQBUFS, &requestbuffers) < 0)
788         {
789                 perror("DeviceV4L2Base::start_dev VIDIOC_REQBUFS");
790                 return 1;
791         }
792         int bfr_count = requestbuffers.count;
793 //printf("DeviceV4L2Base::start_dev got %d buffers\n", bfr_count);
794         device_buffers = new DeviceV4L2VFrame *[bfr_count];
795         memset(device_buffers, 0, bfr_count*sizeof(device_buffers[0]));
796
797 //printf("DeviceV4L2Base::start_dev color_model=%d\n", color_model);
798         int y_offset = 0, line_size = -1;
799         int u_offset = 0, v_offset = 0;
800
801         if(color_model != BC_COMPRESSED)
802         {
803                 switch(color_model)
804                 {
805                 case BC_YUV422P:
806                         u_offset = iwidth * iheight;
807                         v_offset = u_offset + u_offset / 2;
808                         break;
809                 case BC_YUV420P:
810                 case BC_YUV411P:
811 // In 2.6.7, the v and u are inverted for 420 but not 422
812                         v_offset = iwidth * iheight;
813                         u_offset = v_offset + v_offset / 4;
814                         break;
815                 }
816         }
817
818         total_buffers = 0;
819         for(int i = 0; i < bfr_count; i++)
820         {
821                 struct v4l2_buffer buffer;
822                 memset(&buffer, 0, sizeof(buffer));
823                 buffer.type = requestbuffers.type;
824                 buffer.index = i;
825                 if(vioctl(VIDIOC_QUERYBUF, &buffer) < 0)
826                 {
827                         perror("DeviceV4L2Base::start_dev VIDIOC_QUERYBUF");
828                         continue;
829                 }
830
831                 DeviceV4L2VFrame *dframe =
832                         new DeviceV4L2VFrame(dev_fd, buffer.m.offset, buffer.length);
833                 unsigned char *data = dframe->get_dev_data();
834                 if( !data ) continue;
835                 device_buffers[total_buffers++] = dframe;
836                 if(color_model != BC_COMPRESSED)
837                         dframe->reallocate(data, 0, y_offset, u_offset, v_offset,
838                                 iwidth, iheight, color_model, line_size);
839                 else
840                         dframe->set_compressed_memory(data, 0, 0, dframe->get_dev_size());
841         }
842
843         q_bfrs = 0;
844         for(int i = 0; i < total_buffers; i++)
845         {
846                 struct v4l2_buffer buffer;
847                 memset(&buffer, 0, sizeof(buffer));
848                 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
849                 buffer.memory = V4L2_MEMORY_MMAP;
850                 buffer.index = i;
851
852                 if(vioctl(VIDIOC_QBUF, &buffer) < 0)
853                 {
854                         perror("DeviceV4L2Base::start_dev VIDIOC_QBUF");
855                         continue;
856                 }
857                 ++q_bfrs;
858         }
859
860         int streamon_arg = V4L2_BUF_TYPE_VIDEO_CAPTURE;
861         if(vioctl(VIDIOC_STREAMON, &streamon_arg) < 0)
862         {
863                 perror("DeviceV4L2Base::start_dev VIDIOC_STREAMON");
864                 return 1;
865         }
866
867         streamon = 1;
868         return 0;
869 }
870
871 int DeviceV4L2Base::stop_dev()
872 {
873         if( streamon )
874         {
875                 int streamoff_arg = V4L2_BUF_TYPE_VIDEO_CAPTURE;
876                 if(vioctl(VIDIOC_STREAMOFF, &streamoff_arg) < 0)
877                         perror("DeviceV4L2Base::stop_stream_capture VIDIOC_STREAMOFF");
878                 streamon = 0;
879         }
880
881         for( int i = 0; i < total_buffers; i++ )
882         {
883                 delete device_buffers[i];
884         }
885
886         struct v4l2_requestbuffers requestbuffers;
887         memset(&requestbuffers, 0, sizeof(requestbuffers));
888         requestbuffers.count = 0;
889         requestbuffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
890         requestbuffers.memory = V4L2_MEMORY_MMAP;
891         vioctl(VIDIOC_REQBUFS, &requestbuffers);
892
893         delete [] device_buffers;
894         device_buffers = 0;
895         total_buffers = 0;
896         return 0;
897 }
898
899
900 void DeviceV4L2Base::run()
901 {
902         Thread::disable_cancel();
903         int min_buffers = total_buffers / 2;
904         if( min_buffers > 3 ) min_buffers = 3;
905
906 // Read buffers continuously
907         while( !done )
908         {
909                 int retry = 0;
910                 int qbfrs = q_bfrs;
911                 while( !done && (!qbfrs || (!retry && qbfrs < min_buffers)) )
912                 {
913                         Thread::enable_cancel();
914                         Timer::delay(10);
915                         Thread::disable_cancel();
916                         ++retry;  qbfrs = q_bfrs;
917                 }
918                 if( done ) break;
919                 struct v4l2_buffer buffer;
920                 memset(&buffer, 0, sizeof(buffer));
921                 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
922                 buffer.memory = V4L2_MEMORY_MMAP;
923
924 // The driver returns the first buffer not queued, so only one buffer
925 // can be unqueued at a time.
926                 Thread::enable_cancel();
927                 qbfrs_lock->lock("DeviceV4L2Base::run");
928                 int result = vioctl(VIDIOC_DQBUF, &buffer);
929                 if( !result ) --q_bfrs;
930                 qbfrs_lock->unlock();
931                 Thread::disable_cancel();
932                 if(result < 0)
933                 {
934                         perror("DeviceV4L2Base::run VIDIOC_DQBUF");
935                         Thread::enable_cancel();
936                         Timer::delay(10);
937                         Thread::disable_cancel();
938                         continue;
939                 }
940
941 // Get output frame
942                 int bfr = buffer.index;
943 // Set output frame data size/time, queue video
944                 VFrame *frame = device_buffers[bfr];
945                 if(color_model == BC_COMPRESSED)
946                         frame->set_compressed_size(buffer.bytesused);
947                 struct timeval *tv = &buffer.timestamp;
948                 double bfr_time = tv->tv_sec + tv->tv_usec / 1000000.;
949                 frame->set_timestamp(bfr_time);
950                 if( !getq->q(bfr) ) video_lock->unlock();
951         }
952 }
953
954 #endif