summaryrefslogtreecommitdiff
path: root/device.c
blob: 184fb2d205ca939a0f338d1029a90bdc92117218 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
#include "common.h"
#include "udev.h"
#include <linux/dvb/video.h>

char DRIVERNAME[][15] = {
  "undef", "ivtv", "cx18", "pvrusb2", "cx88_blackbird", "hdpvr"
};

char CARDNAME[][9] = {
  "undef", "PVR150", "PVR250", "PVR350", "PVR500#1", "PVR500#2", "HVR1300", "HVR1600", "HVR1900", "HVR1950", "PVRUSB2", "HDPVR"
};

cPvrDevice *PvrDevices[kMaxPvrDevices];

cString cPvrDevice::externChannelSwitchScript;
int     cPvrDevice::VBIDeviceCount = 0;

cPvrDevice::cPvrDevice(int DeviceNumber, cDevice *ParentDevice)
:
#ifdef __DYNAMIC_DEVICE_PROBE
  cDevice(ParentDevice),
#endif
  number(DeviceNumber),
  CurrentNorm(0), //uint64_t can't be negative
  CurrentLinesPerFrame(-1),
  CurrentFrequency(-1),
  CurrentInput(-1),
  SupportsSlicedVBI(false),
  hasDecoder(false),
  hasTuner(true),
  streamType(0),
  dvrOpen(false),
  delivered(false),
  isClosing(false),
  readThreadRunning(false),
  ChannelSettingsDone(false),
  FirstChannelSwitch(true),
  pvrusb2_ready(true),
  driver(undef),
  cardname(UNDEF),
  tsBufferPrefill(0),
  readThread(0)
{
  log(pvrDEBUG2, "new cPvrDevice (%d)", number);
  v4l2_fd = mpeg_fd = radio_fd = -1;
  v4l2_dev = mpeg_dev = radio_dev = -1;
  vpid = apid = tpid = -1;
  cString devName;
  struct v4l2_capability video_vcap;
  struct v4l2_capability capability;
  struct v4l2_input input;
  int i;
  // put all values here that are set only *once*
  v4l2_dev = number; 
  devName = cString::sprintf("/dev/video%d", v4l2_dev);
  v4l2_fd = open(devName, O_RDWR);
  if (v4l2_fd < 0)
    log(pvrERROR, "cPvrDevice::cPvrDevice(): error opening video device %s: %s", *devName, strerror(errno));
  memset(&video_vcap, 0, sizeof(video_vcap));
  IOCTL(v4l2_fd, VIDIOC_QUERYCAP, &video_vcap);
  log(pvrDEBUG1, "%s = %s", *devName, video_vcap.card);
  BusID = cString::sprintf("%s", video_vcap.bus_info);
  log(pvrDEBUG1, "BusID = %s", *BusID);
  if       (!memcmp(video_vcap.driver, "ivtv", 4))                   driver = ivtv;
  else if  (!memcmp(video_vcap.driver, "cx18", 4))                   driver = cx18;
  else if  (!memcmp(video_vcap.driver, "pvrusb2", 7))                driver = pvrusb2;
  else if  (!memcmp(video_vcap.driver, "cx88_blackbird", 14))        driver = cx88_blackbird;
  else if  (!memcmp(video_vcap.driver, "hdpvr", 5))                  driver = hdpvr;
  else { driver = undef; log(pvrDEBUG1, "unknown video driver: \"%s\"",video_vcap.driver); }
  if       (!memcmp(video_vcap.card, "Hauppauge WinTV PVR-150", 23)) cardname = PVR150;
  else if  (!memcmp(video_vcap.card, "Hauppauge WinTV PVR-250", 23)) cardname = PVR250;
  else if  (!memcmp(video_vcap.card, "Hauppauge WinTV PVR-350", 23)) cardname = PVR350;
  else if  (!memcmp(video_vcap.card, "WinTV PVR 500 (unit #1)", 23)) cardname = PVR500_1;
  else if  (!memcmp(video_vcap.card, "WinTV PVR 500 (unit #2)", 23)) cardname = PVR500_2;
  else if  (!memcmp(video_vcap.card, "Hauppauge WinTV-HVR1300", 23)) cardname = HVR1300;
  else if  (!memcmp(video_vcap.card, "Hauppauge HVR-1600", 18))      cardname = HVR1600;
  else if  (!memcmp(video_vcap.card, "WinTV HVR-1900", 14))          cardname = HVR1900;
  else if  (!memcmp(video_vcap.card, "WinTV HVR-1950", 14))          cardname = HVR1950;
  else if  (!memcmp(video_vcap.card, "WinTV PVR USB2", 14))          cardname = PVRUSB2;
  else if  (!memcmp(video_vcap.card, "Hauppauge HD PVR", 16))        cardname = HDPVR;
  else if  (!memcmp(video_vcap.card, "Haupauge HD PVR", 15))         cardname = HDPVR; // spelling error in hdpvr
  else { cardname = UNDEF; log(pvrDEBUG1, "unknown video card: \"%s\"",video_vcap.card); }
  if (cardname == HVR1300)
     log(pvrERROR, "HVR 1300 is not really supported yet");
  driver_apiversion = video_vcap.version;
  log(pvrDEBUG1, "%s Version 0x%06x", DRIVERNAME[driver], driver_apiversion);
  if ((video_vcap.capabilities & V4L2_CAP_SLICED_VBI_CAPTURE) && (driver != pvrusb2)) {
    /*The pvrusb2 driver advertises vbi capability, although it isn't there.
      This was fixed in v4l-dvb hg in 01/2009 and will hopefully be in Kernel 2.6.30*/
    SupportsSlicedVBI = true;
    VBIDeviceCount++;
    log(pvrDEBUG1, "%s supports sliced VBI Capture, total number of VBI capable devices is now %d", *devName, VBIDeviceCount);

    cUdev::Init();
    cUdevDevice *v4ldev = cUdev::GetDeviceFromDevName(*devName);
    if (v4ldev != NULL) {
       static const char *propertyName = "ID_PATH";
       static const char *vbi_dev_name = "/dev/vbi";
       const char *id_path = v4ldev->GetPropertyValue(propertyName);
       if (id_path != NULL) {
          cList<cUdevDevice> *v4ldevices = cUdev::EnumDevices("video4linux", propertyName, id_path);
          for (cUdevDevice *dev = v4ldevices->First(); dev; dev = v4ldevices->Next(dev)) {
              log(pvrDEBUG1, "pvrinput: %s is related to %s", *devName, dev->GetDevnode());
              if (strncmp(dev->GetDevnode(), vbi_dev_name, strlen(vbi_dev_name)) == 0)
                 vbi_dev = dev->GetDevnode();
              }
          delete v4ldevices;
          }
       delete v4ldev;
       }
    cUdev::Free();
    }
  if (video_vcap.capabilities & V4L2_CAP_VIDEO_OUTPUT_OVERLAY)
     hasDecoder = true; //can only be a PVR350
  for (i = 0; i < kMaxPvrDevices; i++) {
    if (radio_dev<0 && (video_vcap.capabilities & V4L2_CAP_RADIO)) { //searching matching radio dev
      devName = cString::sprintf("/dev/radio%d", i);
      radio_fd = open(devName, O_RDWR);
      if (radio_fd >= 0) {
        memset(&capability, 0, sizeof(capability));
        if (IOCTL(radio_fd, VIDIOC_QUERYCAP, &capability) != 0)
           log(pvrERROR, "VIDIOC_QUERYCAP failed, %d:%s", errno, strerror(errno));
        if (!strncmp(*BusID, (const char*)capability.bus_info, strlen(*BusID) - 1)) {
          radio_dev = i; // store info for later
          log(pvrDEBUG1, "/dev/radio%d = FM radio dev",radio_dev);
          }
        close(radio_fd); // a pvrusb2 will remain on input 3. The bool FirstChannelSwitch will solve this later
        radio_fd = -1;
      }
    }
    if (mpeg_dev < 0 && (driver == cx88_blackbird)) { // the blackbird uses two (!) different devices, search the other one.
      close(v4l2_fd);
      v4l2_fd = -1;
      devName = cString::sprintf("/dev/video%d", i);
      mpeg_fd = open(devName, O_RDWR);
      if (mpeg_fd) {
        memset(&capability, 0, sizeof(capability));
        IOCTL(mpeg_fd, VIDIOC_QUERYCAP, &capability);
        if (!strncmp(*BusID, (const char*)capability.bus_info, strlen(*BusID) - 1)
           && !strcmp("cx8800", (const char*)capability.driver)) {
          mpeg_dev = v4l2_dev; //for this driver we found mpeg_dev up to now.
          v4l2_dev = i;        //reassigning, now with correct value.
          log(pvrDEBUG1, "/dev/video%d = v4l2 dev (analog properties: volume/hue/brightness/inputs..)", v4l2_dev);
          log(pvrDEBUG1, "/dev/video%d = mpeg dev (MPEG properties: bitrates/frame rate/filters..)", mpeg_dev);
          }
        close(mpeg_fd);
        mpeg_fd = -1;
        }
      }
    } // end device search loop
  switch (driver) {
    case ivtv:        //ivtv, cx18, pvrusb2 and hdpvr share the same device.
    case cx18:
    case pvrusb2:
    case hdpvr:
          mpeg_dev = v4l2_dev;
          mpeg_fd  = v4l2_fd;
          break;
    case cx88_blackbird:
                      //blackbird: reopen mpeg device.               //FIXME: WE SHOULD OPEN V4L2 DEV for inputs/picture properties/volume, mpeg for all other stuff 
          devName = cString::sprintf("/dev/video%d", mpeg_dev);
          v4l2_fd = open(devName, O_RDWR);                           //FIXME: FOR NOW THIS IS A WILD MIXTURE.
          break;
    default:;
    }
  QueryAllControls(); //we have to split in mpeg and v4l2 here.
  memset(&inputs, -1, sizeof(inputs)); 
  numInputs = 0;
  for (i = 0;; i++) {
    memset(&input, 0, sizeof(input));
    input.index = i;
    if (IOCTL(v4l2_fd, VIDIOC_ENUMINPUT, &input) == -1)
      break;
    else {
      log(pvrDEBUG1, "input %d = %s", i, input.name);
      numInputs++;
      }
    if      (!memcmp(input.name, "Tuner",        5)) { inputs[eTelevision] = inputs[eRadio] = i; continue; } //ivtv:   Radio and TV tuner are same input.
    else if (!memcmp(input.name, "television",  10)) { inputs[eTelevision] = i; continue; }                //pvrusb2
    else if (!memcmp(input.name, "Television",  10)) { inputs[eTelevision] = i; continue; }                //cx88_blackbird
    else if (!memcmp(input.name, "radio",        5)) { inputs[eRadio]      = i; continue; }                //pvrusb2
    else if (!memcmp(input.name, "Composite 0", 11)) { inputs[eComposite0] = i; continue; }
    else if (!memcmp(input.name, "Composite 1", 11)) { inputs[eComposite1] = i; continue; }
    else if (!memcmp(input.name, "Composite 2", 11)) { inputs[eComposite2] = i; continue; }
    else if (!memcmp(input.name, "Composite 3", 11)) { inputs[eComposite3] = i; continue; }
    else if (!memcmp(input.name, "Composite 4", 11)) { inputs[eComposite4] = i; continue; }
    else if (!memcmp(input.name, "Composite1",  10)) { inputs[eComposite1] = i; continue; }                //cx88_blackbird
    else if (!memcmp(input.name, "composite",    9)) { inputs[eComposite0] = i; continue; }                //pvrusb2
    else if (!memcmp(input.name, "Composite",    9)) { inputs[eComposite0] = i; continue; }                //hdpvr
    else if (!memcmp(input.name, "S-Video 3",    9)) { inputs[eSVideo3]    = i; continue; }
    else if (!memcmp(input.name, "S-Video 0",    9)) { inputs[eSVideo0]    = i; continue; }
    else if (!memcmp(input.name, "S-Video 1",    9)) { inputs[eSVideo1]    = i; continue; }
    else if (!memcmp(input.name, "S-Video 2",    9)) { inputs[eSVideo2]    = i; continue; }
    else if (!memcmp(input.name, "S-Video",      7)) { inputs[eSVideo0]    = i; continue; }                //cx88_blackbird & hdpvr
    else if (!memcmp(input.name, "s-video",      7)) { inputs[eSVideo0]    = i; continue; }                //pvrusb2
    else if (!memcmp(input.name, "Component",    9)) { inputs[eComponent]  = i; continue; }                //hdpvr
    else log(pvrERROR, "unknown input %s. PLEASE SEND LOG TO MAINTAINER.", input.name);
    }
  if (inputs[eTelevision] >= 0)
    SetInput(inputs[eTelevision]);
  else if ((driver == hdpvr) && (inputs[eComponent] >= 0)) {
    hasTuner = false;
    SetInput(inputs[eComponent]);
    }
  else {
    hasTuner = false;
    log(pvrERROR, "device has no tuner");
    }
  tsBuffer = new cRingBufferLinear(MEGABYTE(PvrSetup.TsBufferSizeMB), TS_SIZE, false, "PVRTS");
  tsBuffer->SetTimeouts(100, 100);
  ResetBuffering();
  GetStandard();
  if (driver == hdpvr) {
    SetControlValue(&PvrSetup.HDPVR_AudioEncoding, PvrSetup.HDPVR_AudioEncoding.value);
    SetAudioInput(PvrSetup.HDPVR_AudioInput);
    }
  else {
    SetControlValue(&PvrSetup.AudioEncoding, V4L2_MPEG_AUDIO_ENCODING_LAYER_2);
    SetControlValue(&PvrSetup.VideoBitratePeak, 15000000);
    SetVideoSize(720, CurrentLinesPerFrame == 525 ? 480 : 576);
    /* the driver will later automatically adjust the height depending on standard changes */ 
    }
  ReInit();
  StartSectionHandler();
  index = 0;
  while ((index < kMaxPvrDevices) && (PvrDevices[index] != NULL))
    index++;
  if (index < kMaxPvrDevices)
     PvrDevices[index] = this;
  else {
     index = -1;
     esyslog("ERROR: too many cPvrDevices!");
     }
}

cPvrDevice::~cPvrDevice()
{
  if ((index >= 0) && (index < kMaxPvrDevices) && (PvrDevices[index] == this))
     PvrDevices[index] = NULL;
#if VDRVERSNUM >= 10600
  StopSectionHandler();
#endif
  DetachAllReceivers();
  Stop();
  cRingBufferLinear *tsBuffer_tmp = tsBuffer;
  log(pvrDEBUG2, "~cPvrDevice()");
  tsBuffer = NULL;
  delete tsBuffer_tmp;
  close(radio_fd);
  close(v4l2_fd);
}

bool cPvrDevice::Probe(int DeviceNumber)
{
  // DIRTY HACK:
  // some ivtv devices create more than one /dev/video-node
  // so we have to be sure to grab only the right ones...
  if (DeviceNumber >= kMaxPvrDevices)
     return false;
  struct v4l2_capability vcap;
  struct v4l2_format vfmt;
  int v4l2_fd;
  bool found = false;
  memset(&vcap, 0, sizeof(vcap));
  memset(&vfmt, 0, sizeof(vfmt));
  cString device = cString::sprintf("/dev/video%d", DeviceNumber);
  v4l2_fd = open(device, O_RDONLY);
  if (v4l2_fd >= 0) {
    IOCTL(v4l2_fd, VIDIOC_QUERYCAP, &vcap);
    if (!memcmp(vcap.driver, "ivtv",4) ||
        !memcmp(vcap.driver, "cx18",4) ||
        !memcmp(vcap.driver, "pvrusb2", 7) ||
        !memcmp(vcap.driver, "hdpvr", 5))
       found = true;
    if (!memcmp(vcap.driver, "cx88_blackbird", 14)) {
      vfmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
      if (!IOCTL(v4l2_fd, VIDIOC_G_FMT, &vfmt) &&
         (v4l2_fourcc('M','P','E','G') == vfmt.fmt.pix.pixelformat))      
          found = true;
       }
    close(v4l2_fd);
    if (found)
       log(pvrINFO, "cPvrDevice::Probe():found %s", vcap.card);
    return found;
    }
  return false;
}

bool cPvrDevice::Initialize(void)
{
  cPlugin *dynamite = cPluginManager::GetPlugin("dynamite");
  int found = 0;
  VBIDeviceCount = 0;
#ifdef PVR_SOURCEPARAMS
  new cPvrSourceParam();
#endif
  for (int i = 0; i < kMaxPvrDevices; i++) {
    PvrDevices[i] = NULL;
    if (Probe(i)) {
#ifdef __DYNAMIC_DEVICE_PROBE
      if (dynamite)
         cDynamicDeviceProbe::QueueDynamicDeviceCommand(ddpcAttach, *cString::sprintf("/dev/video%d", i));
      else
#endif
      new cPvrDevice(i);
      found++;
      }
    }
  if (found)
    log(pvrINFO, "cPvrDevice::Initialize(): found %d PVR device%s", found, found > 1 ? "s" : "");
  else
    log(pvrINFO, "cPvrDevice::Initialize(): no PVR device found");
  externChannelSwitchScript = AddDirectory(cPlugin::ConfigDirectory(PLUGIN_NAME_I18N), "externchannelswitch.sh");
  if (dynamite)
     dynamite->Service("dynamite-AddUdevMonitor-v0.1", (void*)("video4linux /dev/video"));
  return found > 0;
}

void cPvrDevice::StopAll(void)
{
  /* recursively stop all threads inside pvrinputs devices */
  for (int i = 0; i < kMaxPvrDevices; i++) {
      if (PvrDevices[i])
         PvrDevices[i]->Stop();
      }
}

void cPvrDevice::Stop(void)
{
  if (readThread) {
     log(pvrDEBUG2,"cPvrDevice::Stop() for Device %i", index);
     StopReadThread();
     SetEncoderState(eStop);
     SetVBImode(CurrentLinesPerFrame, V4L2_MPEG_STREAM_VBI_FMT_NONE);
     }
}

void cPvrDevice::GetStandard(void)
{
  v4l2_std_id std;
  if (IOCTL(v4l2_fd, VIDIOC_G_STD, &std) == -1) {
     log(pvrERROR, "error VIDIOC_G_STD on /dev/video%d (%s): %d:%s",
         number, CARDNAME[cardname], errno, strerror(errno));
     }
  if (std & V4L2_STD_625_50)
    CurrentLinesPerFrame = 625;
  else
    CurrentLinesPerFrame = 525;
  /* the driver will automatically set the height to 576 or 480 on each change */  
  CurrentNorm = std;
  log(pvrINFO, "cPvrDevice::CurrentNorm=0x%08llx, CurrentLinesPerFrame=%d on /dev/video%d (%s)",
      std,  CurrentLinesPerFrame, number, CARDNAME[cardname]);
}

void cPvrDevice::StopReadThread(void)
{
  if (readThreadRunning) {
     log(pvrDEBUG2, "cPvrDevice::StopReadThread on /dev/video%d (%s): read thread exists, delete it", number, CARDNAME[cardname]);
     cPvrReadThread *readThread_tmp = readThread;
     readThread = NULL;
     delete readThread_tmp;
     }
  else
     log(pvrDEBUG2, "cPvrDevice::StopReadThread: no read thread running on /dev/video%d (%s)", number, CARDNAME[cardname]);
}

void cPvrDevice::ReInitAll(void)
{
  log(pvrDEBUG1, "cPvrDevice::ReInitAll");
  int i;
  for (i = 0; i < kMaxPvrDevices; i++) {
    if (PvrDevices[i])
      PvrDevices[i]->ReInit();
    }
}

int cPvrDevice::Count()
{
  int count = 0;
  for (int i = 0; i < kMaxPvrDevices; i++) {
    if (PvrDevices[i])
      count++;
    }
  return count;
}

cPvrDevice *cPvrDevice::Get(int index)
{
  int count = 0;
  for (int i = 0; i < kMaxPvrDevices; i++) {
    if (PvrDevices[i]) {
      if (count == index)
        return PvrDevices[i];
      count++;
    }
  }
  return NULL;
}

int  cPvrDevice::ReOpen(void)
{
  log(pvrDEBUG1, "cPvrDevice::ReOpen /dev/video%d = %s (%s)", number, CARDNAME[cardname], DRIVERNAME[driver]);
  int retry_count = 5;
  cString devName = cString::sprintf("/dev/video%d", number);
  retry:
  close(v4l2_fd);
  v4l2_fd = open(devName, O_RDWR);
  if (v4l2_fd < 0) {
    log(pvrERROR, "cPvrDevice::ReOpen: error reopening %s (%s): %d:%s",
        CARDNAME[cardname], *devName, errno, strerror(errno));
    retry_count--;
    if (retry_count > 0) {
      usleep(1000000);
      goto retry;
      }
    }
  else {
    log(pvrDEBUG2, "cPvrDevice::ReOpen: %s (%s) successfully re-opened", *devName, CARDNAME[cardname]);
    }
  return v4l2_fd;
}

void cPvrDevice::ReInit(void)
{
  log(pvrDEBUG1, "cPvrDevice::ReInit /dev/video%d = %s (%s)", number, CARDNAME[cardname], DRIVERNAME[driver]);
  SetControlValue(&PvrSetup.Brightness, PvrSetup.Brightness.value);
  SetControlValue(&PvrSetup.Contrast, PvrSetup.Contrast.value);
  SetControlValue(&PvrSetup.Saturation, PvrSetup.Saturation.value);
  SetControlValue(&PvrSetup.Hue, PvrSetup.Hue.value);
  SetControlValue(&PvrSetup.AspectRatio, PvrSetup.AspectRatio.value);
  SetControlValue(&PvrSetup.FilterSpatialMode, PvrSetup.FilterSpatialMode.value);
  SetControlValue(&PvrSetup.FilterSpatial, PvrSetup.FilterSpatial.value);
  SetControlValue(&PvrSetup.FilterLumaSpatialType, PvrSetup.FilterLumaSpatialType.value);
  SetControlValue(&PvrSetup.FilterChromaSpatialType, PvrSetup.FilterChromaSpatialType.value);
  SetControlValue(&PvrSetup.FilterTemporalMode, PvrSetup.FilterTemporalMode.value);
  SetControlValue(&PvrSetup.FilterTemporal, PvrSetup.FilterTemporal.value);
  SetControlValue(&PvrSetup.FilterMedianType, PvrSetup.FilterMedianType.value);
  SetControlValue(&PvrSetup.FilterLumaMedianBottom, PvrSetup.FilterLumaMedianBottom.value);
  SetControlValue(&PvrSetup.FilterLumaMedianTop, PvrSetup.FilterLumaMedianTop.value);
  SetControlValue(&PvrSetup.FilterChromaMedianBottom, PvrSetup.FilterChromaMedianBottom.value);
  SetControlValue(&PvrSetup.FilterChromaMedianTop, PvrSetup.FilterChromaMedianTop.value);

  if ((radio_fd >= 0) || (driver == pvrusb2 && CurrentInput == inputs[eRadio])) {
    SetControlValue(&PvrSetup.AudioVolumeFM, PvrSetup.AudioVolumeFM.value);
    SetControlValue(&PvrSetup.AudioMute, (int) (PvrSetup.AudioVolumeFM.value == 0));
    }
  else { //no radio
    SetAudioVolumeTV();
    SetControlValue(&PvrSetup.AudioMute, (int) (PvrSetup.AudioVolumeTVCommon.value == 0));
    }

  if (!dvrOpen) { 
    SetTunerAudioMode(PvrSetup.TunerAudioMode);
    SetInput(CurrentInput);
    if ((driver == cx18) || (driver == hdpvr))
      streamType = V4L2_MPEG_STREAM_TYPE_MPEG2_TS;
    else
      streamType = (PvrSetup.StreamType.value == 0) ? V4L2_MPEG_STREAM_TYPE_MPEG2_PS : V4L2_MPEG_STREAM_TYPE_MPEG2_DVD;
    SetControlValue(&PvrSetup.StreamType, streamType);
    SetControlValue(&PvrSetup.AudioBitrate, PvrSetup.AudioBitrate.value);
    SetControlValue(&PvrSetup.AudioSampling, PvrSetup.AudioSampling.value);
    if (driver == hdpvr) {
      SetControlValue(&PvrSetup.HDPVR_AudioEncoding, PvrSetup.HDPVR_AudioEncoding.value);
      SetAudioInput(PvrSetup.HDPVR_AudioInput);
      }
    SetControlValue(&PvrSetup.VideoBitrateTV, PvrSetup.VideoBitrateTV.value);
    SetControlValue(&PvrSetup.BitrateMode, PvrSetup.BitrateMode.value);
    SetControlValue(&PvrSetup.GopSize, PvrSetup.GopSize.queryctrl.default_value);
    SetControlValue(&PvrSetup.GopClosure, PvrSetup.GopClosure.queryctrl.default_value);
    SetControlValue(&PvrSetup.BFrames, PvrSetup.BFrames.queryctrl.default_value);
    }
}

bool cPvrDevice::Tune(int freq)
{
  double fac = 16;
  int freqaux = freq;
  int tune_dev;
  struct v4l2_frequency vf;
  if (CurrentFrequency == freq)
    return true;
  memset(&vf, 0, sizeof(vf));
  struct v4l2_tuner tuner;
  memset(&tuner, 0, sizeof(tuner));
  if (radio_fd >=0)
     tune_dev = radio_fd;
  else
     tune_dev = v4l2_fd;
  if (IOCTL(tune_dev, VIDIOC_G_TUNER, &tuner) == 0)
     fac = (tuner.capability & V4L2_TUNER_CAP_LOW) ? 16000 : 16;
  vf.tuner = 0;
  vf.type = tuner.type;
  vf.frequency = (int)((double)freqaux * fac / 1000.0);
  if (IOCTL(tune_dev, VIDIOC_S_FREQUENCY, &vf) == 0) {
    log(pvrDEBUG1, "cPvrDevice::Tune(): set Frequency on %s to %.2f MHz (%d)",
        CARDNAME[cardname], vf.frequency / fac, vf.frequency);
    }
  else {
    log(pvrERROR, "cPvrDevice::Tune(): error on %s tuning to %.2f MHz (%d): %d:%s",
        CARDNAME[cardname], vf.frequency / fac, vf.frequency, errno, strerror(errno));
    return false;
    }
  CurrentFrequency = freq;
  return true;
}

bool cPvrDevice::SetInput(int input)
{
  if (input == CurrentInput && !FirstChannelSwitch)
     return true;
  log(pvrDEBUG1, "cPvrDevice::SetInput on /dev/video%d (%s) to %d", number, CARDNAME[cardname], input);
  if (IOCTL(v4l2_fd, VIDIOC_S_INPUT, &input) != 0) {
    log(pvrERROR, "VIDIOC_S_INPUT failed on /dev/video%d (%s) for input%d, %d:%s",
        number, CARDNAME[cardname], errno, strerror(errno));
    return false;
    }
#if 1 /* workaround for pvrusb2 driver bug: no audio after switching from radio to TV */
  if ((input == 0) && (CurrentInput == 3) && (driver == pvrusb2)) {
    usleep(200000); /* 200msec */
    log(pvrDEBUG2, "cPvrDevice::SetInput on /dev/video%d (%s) again to %d (workaround for driver bug)",
        number, CARDNAME[cardname], input);
    IOCTL(v4l2_fd, VIDIOC_S_INPUT, &input); //set input television again
    }
#endif
  CurrentInput = input;
  if (driver == pvrusb2) {
    usleep(100000); /* 100msec */
    if (CurrentInput == inputs[eRadio])
       SetControlValue(&PvrSetup.AudioVolumeFM, PvrSetup.AudioVolumeFM.value);
    else //television or extern
       SetAudioVolumeTV();
    }
  return true;
}

bool cPvrDevice::SetAudioInput(int input)
{
  struct v4l2_audio a;
  a.index = input;
  log(pvrDEBUG1,"cPvrDevice::SetAudioInput on /dev/video%d (%s) to %d", number, CARDNAME[cardname], input);
  if (IOCTL(v4l2_fd, VIDIOC_S_AUDIO, &a) != 0) {
    log(pvrERROR, "VIDIOC_S_AUDIO failed on /dev/video%d (%s) for input%d, %d:%s",
        number, CARDNAME[cardname], errno, strerror(errno));
    return false;
    }
  return true;
}

bool cPvrDevice::SetVideoNorm(uint64_t norm)
{
  if (norm == CurrentNorm)
    return true;
  log(pvrDEBUG1, "SetVideoNorm(0x%08llx) for /dev/video%d (%s)", norm, number, CARDNAME[cardname]);
  if (hasDecoder) {
     log(pvrDEBUG1, "cPvrDevice::we need to stop the PVR350 decoder");
     struct video_command cmd;
     memset(&cmd, 0, sizeof(cmd));
     cmd.cmd = VIDEO_CMD_STOP;
     cmd.flags = VIDEO_CMD_STOP_TO_BLACK | VIDEO_CMD_STOP_IMMEDIATELY;
     if (IOCTL(v4l2_fd, VIDEO_COMMAND, &cmd) < 0)
        log(pvrERROR, "pvrinput: VIDEO_CMD_STOP error on /dev/video%d=%d:%s", number, strerror(errno));
     }
  if (IOCTL(v4l2_fd, VIDIOC_S_STD, &norm) !=0) {
     log(pvrERROR, "cPvrDevice::SetVideoNorm() on /dev/video%d (%s) failed, %d:%s",
         number, CARDNAME[cardname], errno, strerror(errno));
     return false;
     }
  CurrentNorm = norm;
  return true;
}

bool cPvrDevice::SetVideoSize(int width, int height)
{
  log(pvrDEBUG1, "cPvrDevice::SetVideoSize");
  struct v4l2_format vfmt;
  vfmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  if (IOCTL(v4l2_fd, VIDIOC_G_FMT, &vfmt) != 0) {
     log(pvrERROR, "cPvrDevice::SetVideoSize(): VIDIOC_G_FMT failed on /dev/video%d (%s), %d:%s",
         number, CARDNAME[cardname], errno, strerror(errno));
     return false;
     }
  vfmt.fmt.pix.width = width;
  vfmt.fmt.pix.height = height;
  if (IOCTL(v4l2_fd, VIDIOC_S_FMT, &vfmt) != 0) {
     log(pvrERROR, "cPvrDevice::SetVideoSize(): VIDIOC_S_FMT failed on /dev/video%d (%s), %d:%s",
         number, CARDNAME[cardname], errno, strerror(errno));
     return false;
     }
  return true;
}

void cPvrDevice::SetTunerAudioMode(int tuneraudiomode)
{
  if (!hasTuner)
    return;
  log(pvrDEBUG1, "cPvrDevice::SetTunerAudioMode(%s) on /dev/video%d (%s)",
     tuneraudiomode == V4L2_TUNER_MODE_MONO ? "mono" :
     tuneraudiomode == V4L2_TUNER_MODE_STEREO ? "stereo" :
     tuneraudiomode == V4L2_TUNER_MODE_LANG1 ? "lang1" :
     tuneraudiomode == V4L2_TUNER_MODE_LANG2 ? "lang2" : "bilingual",
     number, CARDNAME[cardname]);
  struct v4l2_tuner vt;
  memset(&vt, 0, sizeof(vt));
  vt.audmode = tuneraudiomode;
  if (IOCTL(v4l2_fd, VIDIOC_S_TUNER, &vt)) 
     log(pvrERROR, "cPvrDevice::SetTunerAudioMode(%d): error %d:%s on /dev/video%d (%s)",
         tuneraudiomode, errno, strerror(errno), number, CARDNAME[cardname]); 
}

void cPvrDevice::SetAudioVolumeTV()
{
  log(pvrDEBUG2, "AudioVolumeTVException.value=%d; AudioVolumeTVCommon.value=%d; number=%d, AudioVolumeTVExceptionCard=%d",
                  PvrSetup.AudioVolumeTVException.value, PvrSetup.AudioVolumeTVCommon.value, number, PvrSetup.AudioVolumeTVExceptionCard);
  if ((PvrSetup.AudioVolumeTVExceptionCard >= 0 && PvrSetup.AudioVolumeTVExceptionCard <= 7)
       && (number == PvrSetup.AudioVolumeTVExceptionCard)) { //special value selected for a /dev/videoX number
     log(pvrDEBUG1, "cPvrDevice::SetAudioVolumeTVException %d for /dev/video%d (%s)",
         PvrSetup.AudioVolumeTVException.value, number, CARDNAME[cardname]);
     SetControlValue(&PvrSetup.AudioVolumeTVException, PvrSetup.AudioVolumeTVException.value);
     }
  if (PvrSetup.AudioVolumeTVExceptionCard >= 9 && PvrSetup.AudioVolumeTVExceptionCard <=18) { //special value for card(s) with certain name
    if ((cardname == PVR150   && PvrSetup.AudioVolumeTVExceptionCard ==9)  ||
        (cardname == PVR250   && PvrSetup.AudioVolumeTVExceptionCard ==10) ||
        (cardname == PVR350   && PvrSetup.AudioVolumeTVExceptionCard ==11) ||
        (cardname == PVR500_1 && PvrSetup.AudioVolumeTVExceptionCard ==12) ||
        (cardname == PVR500_2 && PvrSetup.AudioVolumeTVExceptionCard ==13) ||
        (cardname == HVR1300  && PvrSetup.AudioVolumeTVExceptionCard ==14) ||
        (cardname == HVR1600  && PvrSetup.AudioVolumeTVExceptionCard ==15) ||
        (cardname == HVR1900  && PvrSetup.AudioVolumeTVExceptionCard ==16) ||
        (cardname == HVR1950  && PvrSetup.AudioVolumeTVExceptionCard ==17) ||
        (cardname == PVRUSB2  && PvrSetup.AudioVolumeTVExceptionCard ==18) ) {
            log(pvrDEBUG1, "cPvrDevice::SetAudioVolumeTVException %d for /dev/video%d (%s)",
                PvrSetup.AudioVolumeTVException.value, number, CARDNAME[cardname]);
            SetControlValue(&PvrSetup.AudioVolumeTVException, PvrSetup.AudioVolumeTVException.value);
            }
    }
  else { //no special value (PvrSetup.AudioVolumeTVExceptionCard ==8)
    log(pvrDEBUG1, "cPvrDevice::SetAudioVolumeTVCommon %d for /dev/video%d (%s)",
        PvrSetup.AudioVolumeTVCommon.value, number, CARDNAME[cardname]);
    SetControlValue(&PvrSetup.AudioVolumeTVCommon, PvrSetup.AudioVolumeTVCommon.value);
    }
}

void cPvrDevice::SetEncoderState(eEncState state)
{
  log(pvrDEBUG1, "cPvrDevice::SetEncoderState (%s) for /dev/video%d (%s)", state == eStop ? "Stop" : "Start", number, CARDNAME[cardname]);
  if (driver == ivtv || driver == cx18 || driver == hdpvr) {
    struct v4l2_encoder_cmd encoderCommand;
    memset(&encoderCommand, 0, sizeof(encoderCommand));
    switch (state) {
      case eStop  :  encoderCommand.cmd = V4L2_ENC_CMD_STOP;   break;
      case eStart :  encoderCommand.cmd = V4L2_ENC_CMD_START;  break;
      }
    if (IOCTL(v4l2_fd, VIDIOC_ENCODER_CMD, &encoderCommand)) {
      log(pvrERROR, "cPvrDevice::SetEncoderState(%s): error %d:%s on /dev/video%d (%s)",
          state == eStop ? "Stop" : "Start", errno, strerror(errno), number, CARDNAME[cardname]); 
      }
    }
  if (driver == pvrusb2 && state == eStop) {
    int retry_count = 5;
    retry:
    close(v4l2_fd);
    v4l2_fd = -1;
    log(pvrDEBUG2, "cPvrDevice::SetEncoderState (eStop): /dev/video%d (%s) is closed",
        number, CARDNAME[cardname]);
    pvrusb2_ready = false;
    cString devName = cString::sprintf("/dev/video%d", number);
    v4l2_fd = open(devName, O_RDWR);  //reopen for tuning
    if (v4l2_fd < 0) {
      log(pvrERROR, "cPvrDevice::SetEncoderState(eStop): error reopening %s (%s): %d:%s",
          CARDNAME[cardname], *devName, errno, strerror(errno));
      retry_count--;
      if (retry_count > 0)
        goto retry;
      }
    else {
      log(pvrDEBUG2, "cPvrDevice::SetEncoderState (eStop): %s (%s) successfully re-opened",
          *devName, CARDNAME[cardname]);
      pvrusb2_ready = true;
      }
   }
}

bool cPvrDevice::SetVBImode(int vbiLinesPerFrame, int vbistatus)
{
  if (*vbi_dev && SupportsSlicedVBI) {
     log(pvrDEBUG1, "SetVBImode(%d, %d) on %s (%s)", vbiLinesPerFrame, vbistatus, *vbi_dev, CARDNAME[cardname]);

     int vbi_fd = open(*vbi_dev, O_RDWR);
     if (vbi_fd < 0) {
        log(pvrERROR, "cPvrDevice::SetVBImode(): error opening %s (%s), %d:%s",
            *vbi_dev, CARDNAME[cardname], errno, strerror(errno));
        return false;
        }

     struct v4l2_format vbifmt;
     struct v4l2_ext_controls ctrls;
     struct v4l2_ext_control  ctrl;
     memset(&vbifmt, 0, sizeof(vbifmt));
     memset(&ctrls,  0, sizeof(ctrls));
     memset(&ctrl,   0, sizeof(ctrl));
     ctrl.id    = V4L2_CID_MPEG_STREAM_VBI_FMT;
     ctrl.value = vbistatus; 
     ctrls.ctrl_class = V4L2_CTRL_CLASS_MPEG;
     ctrls.controls = &ctrl;
     ctrls.count = 1;
     if (IOCTL(vbi_fd, VIDIOC_S_EXT_CTRLS, &ctrls) != 0) {
        log(pvrERROR, "cPvrDevice::SetVBImode(): error setting vbi mode (ctrls) on %s (%s), %d:%s",
            *vbi_dev, CARDNAME[cardname], errno, strerror(errno));
        close(vbi_fd);
        return false; 
        }
     if ((ctrl.value == V4L2_MPEG_STREAM_VBI_FMT_IVTV) && (vbiLinesPerFrame == 625)) {
        vbifmt.fmt.sliced.service_set = V4L2_SLICED_VBI_625;
        vbifmt.type = V4L2_BUF_TYPE_SLICED_VBI_CAPTURE;
        vbifmt.fmt.sliced.reserved[0] = 0;
        vbifmt.fmt.sliced.reserved[1] = 0;

        if (IOCTL(vbi_fd, VIDIOC_S_FMT, &vbifmt) < 0) {
           log(pvrERROR, "cPvrDevice::SetVBImode():error setting vbi mode (fmt) on %s (%s), %d:%s",
               *vbi_dev, CARDNAME[cardname], errno, strerror(errno));
           close(vbi_fd);
           return false;
           }
        }
     close(vbi_fd);
     }
  return true;
}

bool cPvrDevice::ParseChannel(const cChannel *Channel, int *input, uint64_t *norm, int *LinesPerFrame,
                              int *card, eInputType *inputType, int *apid, int *vpid, int *tpid) const
{
  *card = 999;
  *norm = CurrentNorm; //make sure we have a value if channels.conf has no optArg for norm
  *LinesPerFrame = CurrentLinesPerFrame; //see above
  *input = -1;
  if (Channel->IsCable() && Channel->Ca() == 0xA1) {
     Skins.Message(mtError, tr("pvrinput no longer supports old channel syntax!"), 2);
     log(pvrERROR, "cPvrDevice::pvrinput no longer supports old channel syntax!");
     return false;
     }
#ifdef PVR_SOURCEPARAMS
  if (cPvrSourceParam::IsPvr(Channel->Source())) {
     const char *str = Channel->Parameters();
#else
  if (Channel->IsPlug()) {
     const char *str = Channel->PluginParam();
#endif

     int inputIndex = 0;
     int standardIndex = 0;
     int cardIndex = 0;
     if (!cPvrSourceParam::ParseParameters(str, &inputIndex, &standardIndex, &cardIndex))
        return false;
     *input = inputs[cPvrSourceParam::sInputType[inputIndex]];
     *inputType = cPvrSourceParam::sInputType[inputIndex];
     if ((*inputType != eTelevision) && (*inputType != eRadio))
        *inputType = eExternalInput;
     if (standardIndex > 0) {
        *norm = cPvrSourceParam::sStandardNorm[standardIndex];
        *LinesPerFrame = cPvrSourceParam::sStandardLinesPerFrame[standardIndex];
        }
     if (cardIndex > 0)
        *card = cardIndex - 1;

     log(pvrDEBUG2, "ParseChannel %s input %d, norm=0x%08llx, card %d",
         (*inputType == eRadio) ? "Radio" : (*inputType == eTelevision) ? "TV" : "Ext", *input, *norm, *card);
     return true;
     }
  return false;
}

bool cPvrDevice::SetChannelDevice(const cChannel * Channel, bool LiveView)
{
  log(pvrDEBUG1, "cPvrDevice::SetChannelDevice %d (%s) %3.2fMHz (/dev/video%d = %s)",
      Channel->Number(), Channel->Name(), (double)Channel->Frequency() / 1000,  number, CARDNAME[cardname]);
  int input, LinesPerFrame, card;
  uint64_t norm;
  eInputType inputType;
  if (!ParseChannel(Channel, &input, &norm, &LinesPerFrame, &card, &inputType, &apid, &vpid, &tpid))
     return false;

  if ((Channel->GetChannelID() == CurrentChannel.GetChannelID()) && (Channel->Frequency() == CurrentFrequency) && (input == CurrentInput) && (norm == CurrentNorm))
    return true;
  log(pvrDEBUG1, "cPvrDevice::SetChannelDevice prepare switch to %d (%s) %3.2fMHz (/dev/video%d = %s)",
    Channel->Number(), Channel->Name(), (double)Channel->Frequency() / 1000,  number, CARDNAME[cardname]);
  newFrequency = Channel->Frequency();
  newInput = input;
  newNorm = norm;
  newLinesPerFrame = LinesPerFrame;
  newInputType = inputType;
  ChannelSettingsDone = false;
  CurrentChannel = *Channel;
  return true;
}

bool cPvrDevice::SetPid(cPidHandle * Handle, int Type, bool On)
{
  log(pvrDEBUG2, "cPvrDevice::SetPid %d = %s", Handle->pid, On?"On":"Off");
  return true;
}

int  cPvrDevice::OpenFilter(u_short Pid, u_char Tid, u_char Mask)
{
  int handle = sectionHandler.AddFilter(Pid, Tid, Mask);
  log(pvrDEBUG3, "cPvrDevice::OpenFilter: /dev/video%d (%s) pid = %d, tid = %d, mask = %d, handle = %d",
      number, CARDNAME[cardname], Pid, Tid, Mask, handle);
  return handle;
}

#if VDRVERSNUM >= 10600
void cPvrDevice::CloseFilter(int Handle)
{
  log(pvrDEBUG3, "cPvrDevice::CloseFilter: /dev/video%d (%s) handle = %d",
      number, CARDNAME[cardname], Handle);
  sectionHandler.RemoveFilter(Handle);
}
#endif

bool cPvrDevice::OpenDvr(void)
{
  log(pvrDEBUG1, "entering cPvrDevice::OpenDvr: Dvr of /dev/video%d (%s) is %s",
      number, CARDNAME[cardname], (dvrOpen)?"open":"closed");
  delivered = false;
  CloseDvr();
  while (dvrOpen) { //wait until CloseDvr has finnished
    usleep(40000);
    log(pvrDEBUG1, "OpenDvr: wait for CloseDvr on /dev/video%d (%s) to finnish", number, CARDNAME[cardname]);
    }
  tsBuffer->Clear();
  ResetBuffering();
  if (!dvrOpen) {
     if (PvrSetup.repeat_ReInitAll_after_next_encoderstop) {
        ReInitAll(); //some settings require an encoder stop, so we repeat them now
        PvrSetup.repeat_ReInitAll_after_next_encoderstop = false;
        }
     if (!ChannelSettingsDone) {
       if (driver == pvrusb2) {
          while (!pvrusb2_ready) { //re-opening pvrusb2 in SetEncoderState might be in progress
            usleep(40000);
            log(pvrDEBUG1, "OpenDvr: wait until /dev/video%d (%s) is ready", number, CARDNAME[cardname]);
            }
          } 
       switch (newInputType) {
         case eComposite0 ... eComposite4:   //no break here, continuing at next case item
         case eSVideo0 ... eSVideo3:         //no break here, continuing at next case item
         case eComponent:                    //no break here, continuing at next case item
         case eExternalInput:
               {
               log(pvrDEBUG2, "channel is external input.");
               if (radio_fd >= 0) {
                 close(radio_fd);
                 radio_fd = -1;
                 usleep(100000); /* 100msec */
                 SetAudioVolumeTV();
                 SetControlValue(&PvrSetup.VideoBitrateTV, PvrSetup.VideoBitrateTV.value);
                 }

               if (PvrSetup.UseExternChannelSwitchScript) {
                 cString cmd = cString::sprintf("%s %d %d %d %d",
                                 *externChannelSwitchScript, CurrentChannel.Sid(), CurrentChannel.Number(),
                                 number, CurrentChannel.Frequency());
                 log(pvrDEBUG1, "OpenDvr: calling %s", *cmd);
                 if (system(*cmd) < 0)
                    log(pvrERROR, "OpenDvr: executing %s failed", *cmd);
                 log(pvrDEBUG1, "OpenDvr: returned from %s", *cmd);
                 if (PvrSetup.ExternChannelSwitchSleep > 0) {
                   log(pvrDEBUG2, "OpenDvr: sleeping for %d seconds...", PvrSetup.ExternChannelSwitchSleep);
                   usleep(PvrSetup.ExternChannelSwitchSleep * 1000000);
                   log(pvrDEBUG2, "OpenDvr: waking up");
                   }
                 }

               if (!SetInput(newInput))
                  return false;
               if (!SetVideoNorm(newNorm))
                  return false;
               CurrentFrequency = newFrequency; // since we don't tune: set it here          
               break;
               }
         case eRadio:
               {
               log(pvrDEBUG2,"channel is FM radio.");
               switch (driver) {
                 case ivtv:
                 case cx18:
                 case pvrusb2:
                   if (radio_dev < 0)
                      return false; //no hardware support.
                   if (radio_fd < 0) {
                     cString devName = cString::sprintf("/dev/radio%d", radio_dev);
                     radio_fd = open(devName, O_RDONLY);
                     if (radio_fd < 0) {
                       log(pvrERROR, "Error opening FM radio device %s: %s", *devName, strerror(errno));
                       return false;
                       }
                     if (driver == pvrusb2)
                        CurrentInput = inputs[eRadio]; //opening the radio_fd automatically switched the input
                     usleep(100000); /* 100msec */
                     SetControlValue(&PvrSetup.AudioVolumeFM, PvrSetup.AudioVolumeFM.value);
                     }
                   break;
                 case cx88_blackbird:
                 case hdpvr:
                   break;
                 case undef:
                   log(pvrERROR, "driver is unknown!!");
                   return false;
                 }
               if (!Tune(newFrequency))
                  return false;
               break;
               }
         case eTelevision:
               {
               log(pvrDEBUG2, "channel is television.");
               if (radio_fd >= 0) {
                 close(radio_fd);
                 radio_fd = -1;
                 usleep(100000); /* 100msec */
                 SetAudioVolumeTV();
                 SetControlValue(&PvrSetup.VideoBitrateTV, PvrSetup.VideoBitrateTV.value);
                 }
               if (!SetInput(inputs[eTelevision]))
                  return false;
               if (!SetVideoNorm(newNorm))
                  return false;
               if (!Tune(newFrequency))
                  return false;
               }
         } //end: switch (newInputType)
       CurrentInputType = newInputType;
       ChannelSettingsDone = true;
       FirstChannelSwitch = false;
       } //end: if ((!ChannelSettingsDone)
     if (CurrentInputType == eTelevision)
        SetVBImode(newLinesPerFrame, PvrSetup.SliceVBI ? V4L2_MPEG_STREAM_VBI_FMT_IVTV : V4L2_MPEG_STREAM_VBI_FMT_NONE);
     SetEncoderState(eStart);
     if (!readThreadRunning) {
        log(pvrDEBUG2, "cPvrDevice::OpenDvr: create new readThread on /dev/video%d (%s)", number, CARDNAME[cardname]);
        readThread = new cPvrReadThread(tsBuffer, this);
        }
     } //end: if (!dvrOpen)
  dvrOpen = true;
  return true;
}

void cPvrDevice::CloseDvr(void)
{
  if (isClosing)
     return;
  isClosing = true;
  log(pvrDEBUG2, "entering cPvrDevice::CloseDvr: Dvr of /dev/video%d (%s) is %s",
      number, CARDNAME[cardname], (dvrOpen)?"open":"closed");
  if (dvrOpen) {
     StopReadThread();
     SetEncoderState(eStop);
     SetVBImode(CurrentLinesPerFrame, V4L2_MPEG_STREAM_VBI_FMT_NONE);
     }
  dvrOpen = false;
  isClosing = false;
}

void cPvrDevice::ResetBuffering()
{
  tsBufferPrefill = (MEGABYTE(PvrSetup.TsBufferSizeMB) * PvrSetup.TsBufferPrefillRatio) / 100;
  tsBufferPrefill -= (tsBufferPrefill % TS_SIZE);
  log(pvrDEBUG2, "cPvrDevice::ResetBuffering(): tsBuffer prefill = %d for /dev/video%d (%s)",
      tsBufferPrefill, number, CARDNAME[cardname]);
}

bool cPvrDevice::IsBuffering()
{
  int avail = tsBuffer->Available();
  if (tsBufferPrefill && (avail < tsBufferPrefill)) {
    log(pvrDEBUG2, "cPvrDevice::IsBuffering(): available = %d, prefill = %d for /dev/video%d (%s)",
        avail, tsBufferPrefill, number, CARDNAME[cardname]);
    return true;
    }
  tsBufferPrefill = 0;
  return false;
}

bool cPvrDevice::GetTSPacket(uchar *&Data)
{
  int Count = 0;
  if (!tsBuffer ) {
    log(pvrERROR, "cPvrDevice::GetTSPacket(): no tsBuffer for /dev/video%d (%s)", number, CARDNAME[cardname]);
    return false;
    }
  if (tsBuffer && readThreadRunning) {
    if (!IsBuffering()) {
      if (delivered) {
        tsBuffer->Del(TS_SIZE);
        delivered = false;
        //log(pvrDEBUG2, "cPvrDevice::GetTSPacket(): packet delivered");
        }
       uchar *p = tsBuffer->Get(Count);
       if (p && Count >= TS_SIZE) {
        if (*p != TS_SYNC_BYTE) {
          for (int i = 1; i < Count; i++) {
            if (p[i] == TS_SYNC_BYTE) {
              Count = i;
              break;
              } //end: if
            } //end: for
          tsBuffer->Del(Count);
          log(pvrINFO, "ERROR: cPvrDevice::GetTSPacket(): skipped %d bytes to sync on TS packet\n", Count);
          return false;
          }
        sectionHandler.ProcessTSPacket(p);
        delivered = true;
        Data = p;
        return true;
        }
      }
    cCondWait::SleepMs(10); // reduce cpu load while buffering
    Data = NULL;
    return true;
    }
  return false;
}

bool cPvrDevice::ProvidesSource(int Source) const
{
  bool isPvr = cPvrSourceParam::IsPvr(Source);
  log(pvrDEBUG2, "cPvrDevice::ProvidesSource Source=%s (%d) -> %s", (const char*)cSource::ToString(Source), Source, isPvr ? "true" : "false");
  return isPvr;
}

bool cPvrDevice::ProvidesTransponder(const cChannel *Channel) const
{
  return ProvidesSource(Channel->Source());
}

int cPvrDevice::NumProvidedSystems(void) const
{
  return 1;
}

int cPvrDevice::SignalStrength(void) const
{
  struct v4l2_tuner tuner;
  memset(&tuner, 0, sizeof(tuner));
  if ((IOCTL(v4l2_fd, VIDIOC_G_TUNER, &tuner) == 0) && (tuner.signal >= 0) && (tuner.signal <= 65535))
     return (tuner.signal * 100) / 65535;
  return -1;
}

int cPvrDevice::SignalQuality(void) const
{
  return -1;
}

const cChannel *cPvrDevice::GetCurrentlyTunedTransponder(void) const
{
  return &CurrentChannel;
}

bool cPvrDevice::IsTunedToTransponder(const cChannel *Channel) const
{
  return CurrentChannel.GetChannelID() == Channel->GetChannelID();
}

bool cPvrDevice::MaySwitchTransponder(const cChannel *Channel) const
{
  return CurrentChannel.GetChannelID() == Channel->GetChannelID();
}

bool cPvrDevice::ProvidesChannel(const cChannel *Channel, int Priority, bool *NeedsDetachReceivers) const
{
  bool result = false;
  bool hasPriority = Priority < 0 || Priority > this->Priority();
  bool needsDetachReceivers = true;
  int input, LinesPerFrame, dev;
  uint64_t norm;
  eInputType inputType; //only dummy
  int audioPid, videoPid, teletextPid; //only dummy
  if (!ParseChannel(Channel, &input, &norm, &LinesPerFrame, &dev, &inputType, &audioPid, &videoPid, &teletextPid))
    return false; // non-pvrinput channel or wrong syntax used, silently ignore this one
  if ((dev < 999) && (number != dev)) {
    log(pvrDEBUG1, "cPvrDevice::ProvidesChannel %s -> false (this is /dev/video%d, but CARD parameter says /dev/video%d only)",
        Channel->Name(), number, dev); 
    return false;
    }
  if ((PvrSetup.UseOnlyCard >= 0 && PvrSetup.UseOnlyCard <= 7) && (number != PvrSetup.UseOnlyCard)) { //select by number
    log(pvrDEBUG1, "cPvrDevice::ProvidesChannel %s -> false (this is /dev/video%d, but /dev/video%d only was selected in setup)",
        Channel->Name(), number, PvrSetup.UseOnlyCard);
    return false;
    }
  if (PvrSetup.UseOnlyCard >= 9 && PvrSetup.UseOnlyCard <= 19) { //select by Name
    if ((cardname == PVR150   && PvrSetup.UseOnlyCard != 9)  ||
        (cardname == PVR250   && PvrSetup.UseOnlyCard != 10) ||
        (cardname == PVR350   && PvrSetup.UseOnlyCard != 11) ||
        (cardname == PVR500_1 && PvrSetup.UseOnlyCard != 12) ||
        (cardname == PVR500_2 && PvrSetup.UseOnlyCard != 13) ||        
        (cardname == HVR1300  && PvrSetup.UseOnlyCard != 14) ||
        (cardname == HVR1600  && PvrSetup.UseOnlyCard != 15) ||
        (cardname == HVR1900  && PvrSetup.UseOnlyCard != 16) ||
        (cardname == HVR1950  && PvrSetup.UseOnlyCard != 17) ||
        (cardname == PVRUSB2  && PvrSetup.UseOnlyCard != 18) ||
        (cardname == HDPVR    && PvrSetup.UseOnlyCard != 19) ) {
           log(pvrDEBUG1, "cPvrDevice::ProvidesChannel %s -> false (this is %s, but %s only was selected in setup)",
               Channel->Name(), CARDNAME[cardname],
               PvrSetup.UseOnlyCard == 9 ? "PVR150" :
               PvrSetup.UseOnlyCard == 10 ? "PVR250" :
               PvrSetup.UseOnlyCard == 11 ? "PVR350" :
               PvrSetup.UseOnlyCard == 12 ? "PVR500#1" :
               PvrSetup.UseOnlyCard == 13 ? "PVR500#2" :
               PvrSetup.UseOnlyCard == 14 ? "HVR1300" :
               PvrSetup.UseOnlyCard == 15 ? "HVR1600" :
               PvrSetup.UseOnlyCard == 16 ? "HVR1900" :
               PvrSetup.UseOnlyCard == 17 ? "HVR1950" :
               PvrSetup.UseOnlyCard == 18 ? "PVRUSB2" :
               PvrSetup.UseOnlyCard == 19 ? "HDPVR" : "UNDEF");
           return false;
           }
    }
  if (inputType == eRadio) {
    if (radio_dev < 0) {
      log(pvrDEBUG1, "cPvrDevice::ProvidesChannel: /dev/video%d (%s) has no radio", number, CARDNAME[cardname]);
      return false;
      }
    }
  if ((input < 0) || (input >= numInputs)) {
    log(pvrERROR, "cPvrDevice::ProvidesChannel: input %d unknown on /dev/video%d (%s)",
        input, number, CARDNAME[cardname]);
    return false;
    }
  if ((Priority >= 0) && Receiving(true)) {
    if ((Channel->Number() == CurrentChannel.Number()) && (CurrentFrequency == Channel->Frequency()) && (CurrentInput == input) && (CurrentNorm == norm)) {
      needsDetachReceivers = false;
      result = true;
      log(pvrDEBUG1, "cPvrDevice::ProvidesChannel: %s already set -> true.", Channel->Name());
      }
    else
      result = hasPriority;
    }
  else
    result = hasPriority;
  if (NeedsDetachReceivers)
    *NeedsDetachReceivers = needsDetachReceivers;
  log(pvrDEBUG1, "cPvrDevice::ProvidesChannel: /dev/video%d (%s): Channel %d (%s) %3.2fMHz, -> %s",
      number, CARDNAME[cardname], Channel->Number(), Channel->Name(), (double)Channel->Frequency() / 1000,
      result ? "true" : "false");
  log(pvrDEBUG2, "cPvrDevice::ProvidesChannel: /dev/video%d: Receiving()=%s, needsDetachReceivers=%s, Priority=%d, hasPriority=%s",
      number, Receiving(true) ? "true" : "false", needsDetachReceivers ? "true" : "false", Priority, hasPriority ? "true" : "false");
  return result;
}

/*
if a card/driver has unsupported controls, it returns false for this
*/
bool cPvrDevice::ControlIdIsValid(__u32 ctrlid)
{
  if (driver == hdpvr) {
    if (/*(ctrlid != V4L2_CID_BRIGHTNESS) // these controls seem to use other values for the HD PVR
      && (ctrlid != V4L2_CID_CONTRAST)    // than the other PVRs (ioctl returns "invalid argument")
      && (ctrlid != V4L2_CID_SATURATION)  // so ignore them for now, since the defaults seem to be ok.
      && (ctrlid != V4L2_CID_HUE)
      &&*/ (ctrlid != V4L2_CID_SHARPNESS)
      && (ctrlid != V4L2_CID_MPEG_AUDIO_ENCODING)
      && (ctrlid != V4L2_CID_MPEG_VIDEO_ENCODING)
      && (ctrlid != V4L2_CID_MPEG_VIDEO_BITRATE_MODE)
      && (ctrlid != V4L2_CID_MPEG_VIDEO_BITRATE)
      && (ctrlid != V4L2_CID_MPEG_VIDEO_BITRATE_PEAK))
      return false;
    }
  return true;
}

/* 
Sets a V4L2 control.
If the value Val is out of range, the ivtv default value will be
used. The value set to V4L2 will be returned, either Val or the
default.
Has to be used *after* calling cPvrDevice::QueryAllControls()
20070506
If possible, use THIS function for setting VIDIOC_S_EXT_CTRLS.
-wirbel-
*/

int cPvrDevice::SetControlValue(struct valSet * vs, __s32 Val)
{
  if (SetControlValue(vs->ctrl_class, vs->queryctrl.id, Val, vs->queryctrl) == 0) {
     vs->value = Val;
     return 0;
     }
  return -1;
}

/*
functionality as above, but no valSet needed.
*/
int cPvrDevice::SetControlValue(__u32 control, __s32 Val)
{
  __u32 ctrl_class=V4L2_CTRL_CLASS_MPEG;
  struct v4l2_queryctrl *query = 0; 

  switch (control) {
  // picture properties
  case V4L2_CID_BRIGHTNESS:    ctrl_class = V4L2_CTRL_CLASS_USER;
                               query = &PvrSetup.Brightness.queryctrl;
                               break;
  case V4L2_CID_CONTRAST:      ctrl_class = V4L2_CTRL_CLASS_USER;
                               query = &PvrSetup.Contrast.queryctrl;
                               break;
  case V4L2_CID_SATURATION:    ctrl_class = V4L2_CTRL_CLASS_USER;
                               query = &PvrSetup.Saturation.queryctrl;
                               break;
  case V4L2_CID_HUE:           ctrl_class = V4L2_CTRL_CLASS_USER;
                               query = &PvrSetup.Hue.queryctrl;
                               break;
  // Audio
  case V4L2_CID_AUDIO_VOLUME:  ctrl_class = V4L2_CTRL_CLASS_USER;
                               query = &PvrSetup.AudioVolumeTVCommon.queryctrl;
                               break;
  case V4L2_CID_AUDIO_MUTE:    ctrl_class = V4L2_CTRL_CLASS_USER;
                               query = &PvrSetup.AudioMute.queryctrl;
                               break;
  case V4L2_CID_MPEG_AUDIO_L2_BITRATE:
                               query = &PvrSetup.AudioBitrate.queryctrl;
                               break;
  case V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ:
                               query = &PvrSetup.AudioSampling.queryctrl;
                               break;
  case V4L2_CID_MPEG_AUDIO_ENCODING:
                               if (driver == hdpvr)
                                 query = &PvrSetup.HDPVR_AudioEncoding.queryctrl;
                               else
                                 query = &PvrSetup.AudioEncoding.queryctrl;
                               break;
  // Video
  case V4L2_CID_MPEG_VIDEO_BITRATE:
                               query = &PvrSetup.VideoBitrateTV.queryctrl;
                               break;
  case V4L2_CID_MPEG_VIDEO_BITRATE_PEAK:
                               query = &PvrSetup.VideoBitratePeak.queryctrl;
                               break;
  case V4L2_CID_MPEG_VIDEO_ASPECT:
                               query = &PvrSetup.AspectRatio.queryctrl;
                               break;
  // MPEG
  case V4L2_CID_MPEG_STREAM_TYPE:
                               query = &PvrSetup.StreamType.queryctrl;
                               break;
  case V4L2_CID_MPEG_VIDEO_BITRATE_MODE:
                               query = &PvrSetup.BitrateMode.queryctrl;
                               break;
  case V4L2_CID_MPEG_VIDEO_B_FRAMES:
                               query = &PvrSetup.BFrames.queryctrl;
                               break;
  case V4L2_CID_MPEG_VIDEO_GOP_SIZE:
                               query = &PvrSetup.GopSize.queryctrl;
                               break;
  case V4L2_CID_MPEG_VIDEO_GOP_CLOSURE:
                               query = &PvrSetup.GopClosure.queryctrl;
                               break;
  // Video Filters
  case V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE:
                               query = &PvrSetup.FilterSpatialMode.queryctrl;
                               break;
  case V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER:
                               query = &PvrSetup.FilterSpatial.queryctrl;
                               break;
  case V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE:
                               query = &PvrSetup.FilterLumaSpatialType.queryctrl;
                               break;
  case V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE:
                               query = &PvrSetup.FilterChromaSpatialType.queryctrl;
                               break;
  case V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE:
                               query = &PvrSetup.FilterTemporalMode.queryctrl;
                               break;
  case V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER:
                               query = &PvrSetup.FilterTemporal.queryctrl;
                               break;
  case V4L2_CID_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE:
                               query = &PvrSetup.FilterMedianType.queryctrl;
                               break;
  case V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_BOTTOM:
                               query = &PvrSetup.FilterLumaMedianBottom.queryctrl;
                               break;
  case V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_TOP:
                               query = &PvrSetup.FilterLumaMedianTop.queryctrl;
                               break;
  case V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_BOTTOM:
                               query = &PvrSetup.FilterChromaMedianBottom.queryctrl;
                               break;
  case V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_TOP:
                               query = &PvrSetup.FilterChromaMedianTop.queryctrl;
                               break;
  case V4L2_CID_MPEG_STREAM_VBI_FMT:
                               if (SupportsSlicedVBI)
                                  query = &PvrSetup.VBIformat.queryctrl;
                               break;
  default:
    log(pvrERROR, "SetControlValue(__u32 control, __s32 Val): ERROR: control %d not included in switch(control)", control);
    return -1;
  }

  return SetControlValue(ctrl_class, control, Val, *query);
}


/* 
Sets a V4L2 control.
If the value Val is out of range, the ivtv default value will be
used. The value set to V4L2 will be returned, either Val or the
default.
Has to be used *after* calling cPvrDevice::QueryAllControls().
-wirbel-
*/
int cPvrDevice::SetControlValue(__u32 control_class, __u32 control, __s32 Val, struct v4l2_queryctrl queryctrl)
{
  struct v4l2_ext_controls ctrls;
  struct v4l2_ext_control  ctrl;

  if (!ControlIdIsValid(queryctrl.id)) // skip known unsupported controls of the driver with "no error"
    return Val;
  log (3, "SetControlValue(%s, %d)", queryctrl.name, Val);
  if ((queryctrl.flags & V4L2_CTRL_FLAG_DISABLED) == V4L2_CTRL_FLAG_DISABLED) {
    log(pvrINFO, " Error: this control is disabled by driver. Skipped.");
    return Val;
    }    
  if ((Val > queryctrl.maximum) || (Val < queryctrl.minimum)) {
    log(pvrINFO, "  Info: setting value to default(%d)", queryctrl.default_value);
    Val = queryctrl.default_value;
    }
  ctrl.id    = control;
  ctrl.value = Val;

  ctrls.ctrl_class = control_class;
  ctrls.controls = &ctrl;
  ctrls.count = 1;

  if (IOCTL(v4l2_fd, VIDIOC_S_EXT_CTRLS, &ctrls) != 0) {
    log(pvrERROR, "cPvrDevice::SetControlValue(): setting control value %s: %d:%s",
        queryctrl.name, errno, strerror(errno));
      }
  return Val;
}


/*
Queries the properties of a given valSet
20070510
-> Before using function, valSet's queryctrl.id has to be set.
-wirbel-
*/
int cPvrDevice::QueryControl(struct valSet * vs)
{
  if (!ControlIdIsValid(vs->queryctrl.id)) // skip known unsupported controls of the driver with "no error"
    return 0;
  vs->query_isvalid = false;
  if (vs->queryctrl.id == 0) {
    log(pvrERROR, "cPvrDevice::QueryControl(): valSet not initialized.");
    return -1;
    }
  if (IOCTL(v4l2_fd, VIDIOC_QUERYCTRL, &vs->queryctrl) != 0) {
    log(pvrERROR, "QueryControl(): quering control %d failed.", vs->queryctrl.id);
    return -1;
    }
  vs->query_isvalid = true;
  return 0;
}


/*
Queries the properties of all valSets used in SetControlValue
20070510
-wirbel-
*/
bool cPvrDevice::QueryAllControls(void)
{
  int err = 0;
  log(pvrDEBUG1, "QueryAllControls");

  PvrSetup.Brightness.ctrl_class                = V4L2_CTRL_CLASS_USER;
  PvrSetup.Contrast.ctrl_class                  = V4L2_CTRL_CLASS_USER;
  PvrSetup.Saturation.ctrl_class                = V4L2_CTRL_CLASS_USER;
  PvrSetup.Hue.ctrl_class                       = V4L2_CTRL_CLASS_USER;
  // Audio
  PvrSetup.AudioVolumeTVCommon.ctrl_class       = V4L2_CTRL_CLASS_USER;
  PvrSetup.AudioVolumeTVException.ctrl_class    = V4L2_CTRL_CLASS_USER;
  PvrSetup.AudioVolumeFM.ctrl_class             = V4L2_CTRL_CLASS_USER;
  PvrSetup.AudioMute.ctrl_class                 = V4L2_CTRL_CLASS_USER;
  PvrSetup.AudioBitrate.ctrl_class              = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.AudioSampling.ctrl_class             = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.AudioEncoding.ctrl_class             = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.HDPVR_AudioEncoding.ctrl_class       = V4L2_CTRL_CLASS_MPEG;
  // Video
  PvrSetup.VideoBitrateTV.ctrl_class            = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.VideoBitratePeak.ctrl_class          = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.AspectRatio.ctrl_class               = V4L2_CTRL_CLASS_MPEG;
  // MPEG
  PvrSetup.StreamType.ctrl_class                = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.BitrateMode.ctrl_class               = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.BFrames.ctrl_class                   = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.GopSize.ctrl_class                   = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.GopClosure.ctrl_class                = V4L2_CTRL_CLASS_MPEG;
  // Video Filters
  PvrSetup.FilterSpatialMode.ctrl_class         = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.FilterSpatial.ctrl_class             = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.FilterLumaSpatialType.ctrl_class     = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.FilterChromaSpatialType.ctrl_class   = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.FilterTemporalMode.ctrl_class        = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.FilterTemporal.ctrl_class            = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.FilterMedianType.ctrl_class          = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.FilterLumaMedianBottom.ctrl_class    = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.FilterLumaMedianTop.ctrl_class       = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.FilterChromaMedianBottom.ctrl_class  = V4L2_CTRL_CLASS_MPEG;
  PvrSetup.FilterChromaMedianTop.ctrl_class     = V4L2_CTRL_CLASS_MPEG;

  PvrSetup.Brightness.queryctrl.id              = V4L2_CID_BRIGHTNESS;
  PvrSetup.Contrast.queryctrl.id                = V4L2_CID_CONTRAST;
  PvrSetup.Saturation.queryctrl.id              = V4L2_CID_SATURATION;
  PvrSetup.Hue.queryctrl.id                     = V4L2_CID_HUE;
  // Audio
  PvrSetup.AudioVolumeTVCommon.queryctrl.id     = V4L2_CID_AUDIO_VOLUME;
  PvrSetup.AudioVolumeTVException.queryctrl.id  = V4L2_CID_AUDIO_VOLUME;
  PvrSetup.AudioVolumeFM.queryctrl.id           = V4L2_CID_AUDIO_VOLUME;
  PvrSetup.AudioMute.queryctrl.id               = V4L2_CID_AUDIO_MUTE;
  PvrSetup.AudioBitrate.queryctrl.id            = V4L2_CID_MPEG_AUDIO_L2_BITRATE;
  PvrSetup.AudioSampling.queryctrl.id           = V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ;
  PvrSetup.AudioEncoding.queryctrl.id           = V4L2_CID_MPEG_AUDIO_ENCODING;
  PvrSetup.HDPVR_AudioEncoding.queryctrl.id     = V4L2_CID_MPEG_AUDIO_ENCODING;
  // Video
  PvrSetup.VideoBitrateTV.queryctrl.id          = V4L2_CID_MPEG_VIDEO_BITRATE;
  PvrSetup.VideoBitratePeak.queryctrl.id        = V4L2_CID_MPEG_VIDEO_BITRATE_PEAK;
  PvrSetup.AspectRatio.queryctrl.id             = V4L2_CID_MPEG_VIDEO_ASPECT;
  // MPEG
  PvrSetup.StreamType.queryctrl.id              = V4L2_CID_MPEG_STREAM_TYPE;
  PvrSetup.BitrateMode.queryctrl.id             = V4L2_CID_MPEG_VIDEO_BITRATE_MODE;
  PvrSetup.BFrames.queryctrl.id                 = V4L2_CID_MPEG_VIDEO_B_FRAMES;
  PvrSetup.GopSize.queryctrl.id                 = V4L2_CID_MPEG_VIDEO_GOP_SIZE;
  PvrSetup.GopClosure.queryctrl.id              = V4L2_CID_MPEG_VIDEO_GOP_CLOSURE;
  // Video Filters
  PvrSetup.FilterSpatialMode.queryctrl.id       = V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE;
  PvrSetup.FilterSpatial.queryctrl.id           = V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER;
  PvrSetup.FilterLumaSpatialType.queryctrl.id   = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE;
  PvrSetup.FilterChromaSpatialType.queryctrl.id = V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE;
  PvrSetup.FilterTemporalMode.queryctrl.id      = V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE;
  PvrSetup.FilterTemporal.queryctrl.id          = V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER;
  PvrSetup.FilterMedianType.queryctrl.id        = V4L2_CID_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE;
  PvrSetup.FilterLumaMedianBottom.queryctrl.id  = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_BOTTOM;
  PvrSetup.FilterLumaMedianTop.queryctrl.id     = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_TOP;
  PvrSetup.FilterChromaMedianBottom.queryctrl.id= V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_BOTTOM;
  PvrSetup.FilterChromaMedianTop.queryctrl.id   = V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_TOP;
  if (SupportsSlicedVBI)
     PvrSetup.VBIformat.queryctrl.id            = V4L2_CID_MPEG_STREAM_VBI_FMT;
  /* now quering min, max, default */
  // picture properties
  err += QueryControl(&PvrSetup.Brightness);
  err += QueryControl(&PvrSetup.Contrast);
  err += QueryControl(&PvrSetup.Saturation);
  err += QueryControl(&PvrSetup.Hue);
  // Audio
  err += QueryControl(&PvrSetup.AudioVolumeTVCommon);
  err += QueryControl(&PvrSetup.AudioVolumeTVException);
  err += QueryControl(&PvrSetup.AudioVolumeFM);
  err += QueryControl(&PvrSetup.AudioMute);
  err += QueryControl(&PvrSetup.AudioBitrate);
  err += QueryControl(&PvrSetup.AudioSampling);
  if (driver == hdpvr)
    err += QueryControl(&PvrSetup.HDPVR_AudioEncoding);
  else
    err += QueryControl(&PvrSetup.AudioEncoding);
  // Video
  err += QueryControl(&PvrSetup.VideoBitrateTV);
  err += QueryControl(&PvrSetup.VideoBitratePeak);
  err += QueryControl(&PvrSetup.AspectRatio);
  // MPEG
  err += QueryControl(&PvrSetup.StreamType);
  err += QueryControl(&PvrSetup.BitrateMode);
  err += QueryControl(&PvrSetup.BFrames);
  err += QueryControl(&PvrSetup.GopSize);
  err += QueryControl(&PvrSetup.GopClosure);
  // Video Filters
  err += QueryControl(&PvrSetup.FilterSpatialMode);
  err += QueryControl(&PvrSetup.FilterSpatial);
  err += QueryControl(&PvrSetup.FilterLumaSpatialType);
  err += QueryControl(&PvrSetup.FilterChromaSpatialType);
  err += QueryControl(&PvrSetup.FilterTemporalMode);
  err += QueryControl(&PvrSetup.FilterTemporal);
  err += QueryControl(&PvrSetup.FilterMedianType);
  err += QueryControl(&PvrSetup.FilterLumaMedianBottom);
  err += QueryControl(&PvrSetup.FilterLumaMedianTop);
  err += QueryControl(&PvrSetup.FilterChromaMedianBottom);
  err += QueryControl(&PvrSetup.FilterChromaMedianTop);
  if (SupportsSlicedVBI)
     err += QueryControl(&PvrSetup.VBIformat);
  if (err)
    return false;

  // The following code checks wether a valSet.value is 
  // INVALID_VALUE and if so -> set it to its queryctrl.default_value.
  // The macro INIT(v) is a abbreviation for the 'if .. then' comparison.
  #define INIT(v) if (v.value == INVALID_VALUE) v.value=v.queryctrl.default_value
  // picture properties
  INIT(PvrSetup.Brightness);
  INIT(PvrSetup.Contrast);
  INIT(PvrSetup.Saturation);
  INIT(PvrSetup.Hue);
  // Audio
  if (PvrSetup.AudioVolumeTVCommon.value == INVALID_VALUE)
    PvrSetup.AudioVolumeTVCommon.value = (int)(0.95 * PvrSetup.AudioVolumeTVCommon.queryctrl.maximum);
  if (PvrSetup.AudioVolumeTVException.value == INVALID_VALUE)
    PvrSetup.AudioVolumeTVException.value = (int)(0.95 * PvrSetup.AudioVolumeTVException.queryctrl.maximum);
  if (PvrSetup.AudioVolumeFM.value == INVALID_VALUE)
    PvrSetup.AudioVolumeFM.value = PvrSetup.AudioVolumeFM.queryctrl.maximum;
  INIT(PvrSetup.AudioBitrate);
  INIT(PvrSetup.AudioSampling);
  if (driver == hdpvr)
    INIT(PvrSetup.HDPVR_AudioEncoding);
  // Video
  INIT(PvrSetup.VideoBitrateTV);
  INIT(PvrSetup.AspectRatio);
  // MPEG
  INIT(PvrSetup.BitrateMode);
  INIT(PvrSetup.BFrames);
  INIT(PvrSetup.GopSize);
  INIT(PvrSetup.GopClosure);
  // Video Filters
  INIT(PvrSetup.FilterSpatialMode);
  INIT(PvrSetup.FilterSpatial);
  INIT(PvrSetup.FilterLumaSpatialType);
  INIT(PvrSetup.FilterChromaSpatialType);
  INIT(PvrSetup.FilterTemporalMode);
  INIT(PvrSetup.FilterTemporal);
  INIT(PvrSetup.FilterMedianType);
  INIT(PvrSetup.FilterLumaMedianBottom);
  INIT(PvrSetup.FilterLumaMedianTop);
  INIT(PvrSetup.FilterChromaMedianBottom);
  INIT(PvrSetup.FilterChromaMedianTop);
  return true;
}


#ifdef __DYNAMIC_DEVICE_PROBE
cPvrDeviceProbe *cPvrDeviceProbe::probe = NULL;

void cPvrDeviceProbe::Init(void)
{
  if (!probe)
     probe = new cPvrDeviceProbe();
}

void cPvrDeviceProbe::Shutdown(void)
{
  if (probe)
     delete probe;
  probe = NULL;
}

cDevice *cPvrDeviceProbe::Attach(cDevice *ParentDevice, const char *DevPath)
{
  int nr = -1;
  if ((sscanf(DevPath, "/dev/video%d", &nr) == 1) && cPvrDevice::Probe(nr))
     return new cPvrDevice(nr, ParentDevice);
  return NULL;
}
#endif