summaryrefslogtreecommitdiffstats
path: root/stream/tv.c
blob: 77279e4bcd3f43ce55461cc3161d24414bae93e9 (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
/*
 * TV Interface for MPlayer
 *
 * API idea based on libvo2
 *
 * Copyright (C) 2001 Alex Beregszaszi
 *
 * Feb 19, 2002: Significant rewrites by Charles R. Henrich (henrich@msu.edu)
 *               to add support for audio, and bktr *BSD support.
 *
 * This file is part of MPlayer.
 *
 * MPlayer is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * MPlayer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <sys/time.h>
#include <libavutil/avstring.h>

#include "config.h"


#include "common/msg.h"

#include "stream.h"
#include "demux/demux.h"
#include "demux/stheader.h"

#include "audio/format.h"
#include "video/img_fourcc.h"
#include "osdep/timer.h"

#include "tv.h"

#include "frequencies.h"

tv_channels_t *tv_channel_list;
tv_channels_t *tv_channel_current, *tv_channel_last;
char *tv_channel_last_real;

/* enumerating drivers (like in stream.c) */
extern const tvi_info_t tvi_info_dummy;
extern const tvi_info_t tvi_info_v4l2;

/** List of drivers in autodetection order */
static const tvi_info_t* tvi_driver_list[]={
#if HAVE_TV_V4L2
    &tvi_info_v4l2,
#endif
    &tvi_info_dummy,
    NULL
};

tvi_handle_t *tv_new_handle(int size, struct mp_log *log, const tvi_functions_t *functions)
{
    tvi_handle_t *h = malloc(sizeof(*h));

    if (!h)
        return NULL;

    h->priv = calloc(1, size);

    if (!h->priv) {
        free(h);
        return NULL;
    }

    h->log        = log;
    h->functions  = functions;
    h->seq        = 0;
    h->chanlist   = -1;
    h->chanlist_s = NULL;
    h->norm       = -1;
    h->channel    = -1;
    h->scan       = NULL;

    return h;
}

void tv_free_handle(tvi_handle_t *h)
{
    if (!h)
        return;
    free(h->priv);
    free(h->scan);
    free(h);
}

void tv_start_scan(tvi_handle_t *tvh, int start)
{
    MP_INFO(tvh, "start scan\n");
    tvh->tv_param->scan=start?1:0;
}

static int tv_set_freq_float(tvi_handle_t *tvh, float freq)
{
    return tv_set_freq(tvh, freq/1000.0*16);
}

static void tv_scan(tvi_handle_t *tvh)
{
    unsigned int now;
    struct CHANLIST cl;
    tv_channels_t *tv_channel_tmp=NULL;
    tv_channels_t *tv_channel_add=NULL;
    tv_scan_t* scan;
    int found=0, index=1;

    //Channel scanner without tuner is useless and causes crash due to uninitialized chanlist_s
    if (tvh->functions->control(tvh->priv, TVI_CONTROL_IS_TUNER, 0) != TVI_CONTROL_TRUE)
    {
        MP_WARN(tvh, "Channel scanner is not available without tuner\n");
        tvh->tv_param->scan=0;
        return;
    }

    scan = tvh->scan;
    now=(unsigned int)mp_time_us();
    if (!scan) {
        scan=calloc(1,sizeof(tv_scan_t));
        tvh->scan=scan;
        cl = tvh->chanlist_s[scan->channel_num];
        tv_set_freq_float(tvh, cl.freq);
        scan->scan_timer=now+1e6*tvh->tv_param->scan_period;
    }
    if(scan->scan_timer>now)
        return;

    if (tv_get_signal(tvh)>tvh->tv_param->scan_threshold) {
        cl = tvh->chanlist_s[scan->channel_num];
        tv_channel_tmp=tv_channel_list;
        while (tv_channel_tmp) {
            index++;
            if (cl.freq==tv_channel_tmp->freq){
                found=1;
                break;
            }
            tv_channel_add=tv_channel_tmp;
            tv_channel_tmp=tv_channel_tmp->next;
        }
        if (!found) {
            MP_INFO(tvh, "Found new channel: %s (#%d). \n",cl.name,index);
            scan->new_channels++;
            tv_channel_tmp = malloc(sizeof(tv_channels_t));
            tv_channel_tmp->index=index;
            tv_channel_tmp->next=NULL;
            tv_channel_tmp->prev=tv_channel_add;
            tv_channel_tmp->freq=cl.freq;
            snprintf(tv_channel_tmp->name,sizeof(tv_channel_tmp->name),"ch%d",index);
            strncpy(tv_channel_tmp->number, cl.name, 5);
            tv_channel_tmp->number[4]='\0';
            if (!tv_channel_list)
                tv_channel_list=tv_channel_tmp;
            else {
                tv_channel_add->next=tv_channel_tmp;
                tv_channel_list->prev=tv_channel_tmp;
            }
        }else
            MP_INFO(tvh, "Found existing channel: %s-%s.\n",
                tv_channel_tmp->number,tv_channel_tmp->name);
    }
    scan->channel_num++;
    scan->scan_timer=now+1e6*tvh->tv_param->scan_period;
    if (scan->channel_num>=chanlists[tvh->chanlist].count) {
        tvh->tv_param->scan=0;
        MP_INFO(tvh, "TV scan end. Found %d new channels.\n", scan->new_channels);
        tv_channel_tmp=tv_channel_list;
        if(tv_channel_tmp){
            MP_INFO(tvh, "channels=");
            while(tv_channel_tmp){
                MP_INFO(tvh, "%s-%s",tv_channel_tmp->number,tv_channel_tmp->name);
                if(tv_channel_tmp->next)
                    MP_INFO(tvh, ",");
                tv_channel_tmp=tv_channel_tmp->next;
            }
            MP_INFO(tvh, "\n");
        }
        if (!tv_channel_current) tv_channel_current=tv_channel_list;
        if (tv_channel_current)
            tv_set_freq_float(tvh, tv_channel_current->freq);
        free(tvh->scan);
        tvh->scan=NULL;
    }else{
        cl = tvh->chanlist_s[scan->channel_num];
        tv_set_freq_float(tvh, cl.freq);
        MP_INFO(tvh, "Trying: %s (%.2f). \n",cl.name,1e-3*cl.freq);
    }
}

/* ================== DEMUX_TV ===================== */
/*
  Return value:
    0 = EOF(?) or no stream
    1 = successfully read a packet
*/
/* fill demux->video and demux->audio */

static int demux_tv_fill_buffer(demuxer_t *demux)
{
    tvi_handle_t *tvh=(tvi_handle_t*)(demux->priv);
    demux_packet_t* dp;
    unsigned int len=0;
    struct sh_stream *want_audio = NULL, *want_video = NULL;

    for (int n = 0; n < demux->num_streams; n++) {
        struct sh_stream *sh = demux->streams[n];
        if (!demuxer_stream_has_packets_queued(demux, sh) &&
            demuxer_stream_is_selected(demux, sh))
        {
            if (sh->type == STREAM_AUDIO)
                want_audio = sh;
            if (sh->type == STREAM_VIDEO)
                want_video = sh;
        }
    }

    /* ================== ADD AUDIO PACKET =================== */

    if (want_audio && tvh->tv_param->noaudio == 0 &&
        tvh->functions->control(tvh->priv,
                                TVI_CONTROL_IS_AUDIO, 0) == TVI_CONTROL_TRUE)
        {
        len = tvh->functions->get_audio_framesize(tvh->priv);

        dp=new_demux_packet(len);
        dp->keyframe = true;
        dp->pts=tvh->functions->grab_audio_frame(tvh->priv, dp->buffer,len);
        demuxer_add_packet(demux, want_audio, dp);
        }

    /* ================== ADD VIDEO PACKET =================== */

    if (want_video && tvh->functions->control(tvh->priv,
                            TVI_CONTROL_IS_VIDEO, 0) == TVI_CONTROL_TRUE)
        {
                len = tvh->functions->get_video_framesize(tvh->priv);
        dp=new_demux_packet(len);
        dp->keyframe = true;
                dp->pts=tvh->functions->grab_video_frame(tvh->priv, dp->buffer, len);
                demuxer_add_packet(demux, want_video, dp);
         }

    if (tvh->tv_param->scan) tv_scan(tvh);
    return 1;
}

static int norm_from_string(tvi_handle_t *tvh, char* norm)
{
    const tvi_functions_t *funcs = tvh->functions;
    char str[20];
    int ret;

    strncpy(str, norm, sizeof(str)-1);
    str[sizeof(str)-1] = '\0';
    ret=funcs->control(tvh->priv, TVI_CONTROL_SPC_GET_NORMID, str);

    if (ret == TVI_CONTROL_TRUE) {
        int *v = (int *)str;
        return *v;
    }

    if(ret!=TVI_CONTROL_UNKNOWN)
    {
        MP_WARN(tvh, "tv.c: norm_from_string(%s): Bogus norm parameter, setting %s.\n", norm,"default");
        return 0;
    }

    if (!strcasecmp(norm, "pal"))
        return TV_NORM_PAL;
    else if (!strcasecmp(norm, "ntsc"))
        return TV_NORM_NTSC;
    else if (!strcasecmp(norm, "secam"))
        return TV_NORM_SECAM;
    else if (!strcasecmp(norm, "palnc"))
        return TV_NORM_PALNC;
    else if (!strcasecmp(norm, "palm"))
        return TV_NORM_PALM;
    else if (!strcasecmp(norm, "paln"))
        return TV_NORM_PALN;
    else if (!strcasecmp(norm, "ntscjp"))
        return TV_NORM_NTSCJP;
    else {
        MP_WARN(tvh, "tv.c: norm_from_string(%s): Bogus norm parameter, setting %s.\n", norm, "PAL");
        return TV_NORM_PAL;
    }
}

static void parse_channels(tvi_handle_t *tvh)
{
    char** channels = tvh->tv_param->channels;

    MP_INFO(tvh, "TV channel names detected.\n");
    tv_channel_list = malloc(sizeof(tv_channels_t));
    tv_channel_list->index=1;
    tv_channel_list->next=NULL;
    tv_channel_list->prev=NULL;
    tv_channel_current = tv_channel_list;
    tv_channel_current->norm = tvh->norm;

    while (*channels) {
        char* tmp = *(channels++);
        char* sep = strchr(tmp,'-');
        int i;
        struct CHANLIST cl;

        if (!sep) continue; // Wrong syntax, but mplayer should not crash

        av_strlcpy(tv_channel_current->name, sep + 1,
                        sizeof(tv_channel_current->name));
        sep[0] = '\0';
        strncpy(tv_channel_current->number, tmp, 5);
        tv_channel_current->number[4]='\0';

        while ((sep=strchr(tv_channel_current->name, '_')))
            sep[0] = ' ';

        // if channel number is a number and larger than 1000 threat it as frequency
        // tmp still contain pointer to null-terminated string with channel number here
        if (atoi(tmp)>1000){
            tv_channel_current->freq=atoi(tmp);
        }else{
            tv_channel_current->freq = 0;
            for (i = 0; i < chanlists[tvh->chanlist].count; i++) {
                cl = tvh->chanlist_s[i];
                if (!strcasecmp(cl.name, tv_channel_current->number)) {
                    tv_channel_current->freq=cl.freq;
                    break;
                }
            }
        }
        if (tv_channel_current->freq == 0)
            MP_ERR(tvh, "Couldn't find frequency for channel %s (%s)\n",
                            tv_channel_current->number, tv_channel_current->name);
        else {
          sep = strchr(tv_channel_current->name, '-');
          if ( !sep ) sep = strchr(tv_channel_current->name, '+');

          if ( sep ) {
            i = atoi (sep+1);
            if ( sep[0] == '+' ) tv_channel_current->freq += i * 100;
            if ( sep[0] == '-' ) tv_channel_current->freq -= i * 100;
            sep[0] = '\0';
          }

          sep = strchr(tv_channel_current->name, '=');
          if ( sep ) {
            tv_channel_current->norm = norm_from_string(tvh, sep+1);
            sep[0] = '\0';
          }
        }

        /*MP_INFO(tvh, "-- Detected channel %s - %s (%5.3f)\n",
                        tv_channel_current->number, tv_channel_current->name,
                        (float)tv_channel_current->freq/1000);*/

        tv_channel_current->next = malloc(sizeof(tv_channels_t));
        tv_channel_current->next->index = tv_channel_current->index + 1;
        tv_channel_current->next->prev = tv_channel_current;
        tv_channel_current->next->next = NULL;
        tv_channel_current = tv_channel_current->next;
        tv_channel_current->norm = tvh->norm;
    }
    if (tv_channel_current->prev)
        tv_channel_current->prev->next = NULL;
    free(tv_channel_current);
}

int tv_set_norm(tvi_handle_t *tvh, char* norm)
{
    tvh->norm = norm_from_string(tvh, norm);

    MP_VERBOSE(tvh, "Selected norm : %s\n", norm);
    if (tvh->functions->control(tvh->priv, TVI_CONTROL_TUN_SET_NORM, &tvh->norm) != TVI_CONTROL_TRUE) {
        MP_ERR(tvh, "Error: Cannot set norm!\n");
        return 0;
    }
    return 1;
}

static int tv_set_norm_i(tvi_handle_t *tvh, int norm)
{
   tvh->norm = norm;

   MP_VERBOSE(tvh, "Selected norm id: %d\n", norm);
   if (tvh->functions->control(tvh->priv, TVI_CONTROL_TUN_SET_NORM, &tvh->norm) != TVI_CONTROL_TRUE) {
      MP_ERR(tvh, "Error: Cannot set norm!\n");
      return 0;
   }

   return 1;
}

static void set_norm_and_freq(tvi_handle_t *tvh, tv_channels_t *chan)
{
    MP_INFO(tvh, "Selected channel: %s - %s (freq: %.3f)\n",
           chan->number, chan->name, chan->freq/1000.0);
    tv_set_norm_i(tvh, chan->norm);
    tv_set_freq_float(tvh, chan->freq);
}

static int open_tv(tvi_handle_t *tvh)
{
    int i;
    const tvi_functions_t *funcs = tvh->functions;
    static const int tv_fmt_list[] = {
      MP_FOURCC_YV12,
      MP_FOURCC_I420,
      MP_FOURCC_UYVY,
      MP_FOURCC_YUY2,
      MP_FOURCC_RGB32,
      MP_FOURCC_RGB24,
      MP_FOURCC_RGB16,
      MP_FOURCC_RGB15
    };

    if (funcs->control(tvh->priv, TVI_CONTROL_IS_VIDEO, 0) != TVI_CONTROL_TRUE)
    {
        MP_ERR(tvh, "Error: No video input present!\n");
        return 0;
    }

    if (tvh->tv_param->outfmt == -1)
      for (i = 0; i < sizeof (tv_fmt_list) / sizeof (*tv_fmt_list); i++)
        {
          tvh->tv_param->outfmt = tv_fmt_list[i];
          if (funcs->control (tvh->priv, TVI_CONTROL_VID_SET_FORMAT,
                              &tvh->tv_param->outfmt) == TVI_CONTROL_TRUE)
            break;
        }
    else
    {
    switch(tvh->tv_param->outfmt)
    {
        case MP_FOURCC_YV12:
        case MP_FOURCC_I420:
        case MP_FOURCC_UYVY:
        case MP_FOURCC_YUY2:
        case MP_FOURCC_RGB32:
        case MP_FOURCC_RGB24:
        case MP_FOURCC_BGR32:
        case MP_FOURCC_BGR24:
        case MP_FOURCC_BGR16:
        case MP_FOURCC_BGR15:
            break;
        default:
            MP_ERR(tvh, "==================================================================\n"\
                        " WARNING: UNTESTED OR UNKNOWN OUTPUT IMAGE FORMAT REQUESTED (0x%x)\n"\
                        " This may cause buggy playback or program crash! Bug reports will\n"\
                        " be ignored! You should try again with YV12 (which is the default\n"\
                        " colorspace) and read the documentation!\n"\
                        "==================================================================\n"
                ,tvh->tv_param->outfmt);
    }
    funcs->control(tvh->priv, TVI_CONTROL_VID_SET_FORMAT, &tvh->tv_param->outfmt);
    }

    /* set some params got from cmdline */
    funcs->control(tvh->priv, TVI_CONTROL_SPC_SET_INPUT, &tvh->tv_param->input);

    if ((!strcmp(tvh->tv_param->driver, "v4l2") && tvh->tv_param->normid >= 0))
        tv_set_norm_i(tvh, tvh->tv_param->normid);
    else
        tv_set_norm(tvh,tvh->tv_param->norm);

    /* limits on w&h are norm-dependent -- JM */
    if (tvh->tv_param->width != -1 && tvh->tv_param->height != -1) {
        // first tell the driver both width and height, some drivers do not support setting them independently.
        int dim[2];
        dim[0] = tvh->tv_param->width; dim[1] = tvh->tv_param->height;
        funcs->control(tvh->priv, TVI_CONTROL_VID_SET_WIDTH_HEIGHT, dim);
    }
    /* set width */
    if (tvh->tv_param->width != -1)
    {
        if (funcs->control(tvh->priv, TVI_CONTROL_VID_CHK_WIDTH, &tvh->tv_param->width) == TVI_CONTROL_TRUE)
            funcs->control(tvh->priv, TVI_CONTROL_VID_SET_WIDTH, &tvh->tv_param->width);
        else
        {
            MP_ERR(tvh, "Unable to set requested width: %d\n", tvh->tv_param->width);
            funcs->control(tvh->priv, TVI_CONTROL_VID_GET_WIDTH, &tvh->tv_param->width);
        }
    }

    /* set height */
    if (tvh->tv_param->height != -1)
    {
        if (funcs->control(tvh->priv, TVI_CONTROL_VID_CHK_HEIGHT, &tvh->tv_param->height) == TVI_CONTROL_TRUE)
            funcs->control(tvh->priv, TVI_CONTROL_VID_SET_HEIGHT, &tvh->tv_param->height);
        else
        {
            MP_ERR(tvh, "Unable to set requested height: %d\n", tvh->tv_param->height);
            funcs->control(tvh->priv, TVI_CONTROL_VID_GET_HEIGHT, &tvh->tv_param->height);
        }
    }

    if (funcs->control(tvh->priv, TVI_CONTROL_IS_TUNER, 0) != TVI_CONTROL_TRUE)
    {
        MP_WARN(tvh, "Selected input hasn't got a tuner!\n");
        goto done;
    }

    /* select channel list */
    for (i = 0; chanlists[i].name != NULL; i++)
    {
        if (!strcasecmp(chanlists[i].name, tvh->tv_param->chanlist))
        {
            tvh->chanlist = i;
            tvh->chanlist_s = chanlists[i].list;
            break;
        }
    }

    if (tvh->chanlist == -1) {
        MP_WARN(tvh, "Unable to find selected channel list! (%s)\n",
            tvh->tv_param->chanlist);
        return 0;
    } else
        MP_VERBOSE(tvh, "Selected channel list: %s (including %d channels)\n",
            chanlists[tvh->chanlist].name, chanlists[tvh->chanlist].count);

    if (tvh->tv_param->freq && tvh->tv_param->channel)
    {
        MP_WARN(tvh, "You can't set frequency and channel simultaneously!\n");
        goto done;
    }

    /* Handle channel names */
    if (tvh->tv_param->channels) {
        parse_channels(tvh);
    } else
            tv_channel_last_real = malloc(5);

    if (tv_channel_list) {
        int channel = 0;
        if (tvh->tv_param->channel)
         {
           if (isdigit(*tvh->tv_param->channel))
                /* if tvh->tv_param->channel begins with a digit interpret it as a number */
                channel = atoi(tvh->tv_param->channel);
           else
              {
                /* if tvh->tv_param->channel does not begin with a digit
                   set the first channel that contains tvh->tv_param->channel in its name */

                tv_channel_current = tv_channel_list;
                while ( tv_channel_current ) {
                        if ( strstr(tv_channel_current->name, tvh->tv_param->channel) )
                          break;
                        tv_channel_current = tv_channel_current->next;
                        }
                if ( !tv_channel_current ) tv_channel_current = tv_channel_list;
              }
         }
        else
                channel = 1;

        if ( channel ) {
        tv_channel_current = tv_channel_list;
        for (int n = 1; n < channel; n++)
                if (tv_channel_current->next)
                        tv_channel_current = tv_channel_current->next;
        }

        set_norm_and_freq(tvh, tv_channel_current);
        tv_channel_last = tv_channel_current;
    } else {
    /* we need to set frequency */
    if (tvh->tv_param->freq)
    {
        unsigned long freq = atof(tvh->tv_param->freq)*16;

        /* set freq in MHz */
        funcs->control(tvh->priv, TVI_CONTROL_TUN_SET_FREQ, &freq);

        funcs->control(tvh->priv, TVI_CONTROL_TUN_GET_FREQ, &freq);
        MP_VERBOSE(tvh, "Selected frequency: %lu (%.3f)\n",
            freq, freq/16.0);
    }

            if (tvh->tv_param->channel) {
        struct CHANLIST cl;

        MP_VERBOSE(tvh, "Requested channel: %s\n", tvh->tv_param->channel);
        for (i = 0; i < chanlists[tvh->chanlist].count; i++)
        {
            cl = tvh->chanlist_s[i];
                    //  printf("count%d: name: %s, freq: %d\n",
                    //  i, cl.name, cl.freq);
            if (!strcasecmp(cl.name, tvh->tv_param->channel))
            {
                        strcpy(tv_channel_last_real, cl.name);
                tvh->channel = i;
                MP_INFO(tvh, "Selected channel: %s (freq: %.3f)\n",
                    cl.name, cl.freq/1000.0);
                tv_set_freq_float(tvh, cl.freq);
                break;
            }
        }
    }
    }

    /* grep frequency in chanlist */
    {
        unsigned long i2;
        int freq;

        tv_get_freq(tvh, &i2);

        freq = (int) (((float)(i2/16))*1000)+250;

        for (i = 0; i < chanlists[tvh->chanlist].count; i++)
        {
            if (tvh->chanlist_s[i].freq == freq)
            {
                tvh->channel = i+1;
                break;
            }
        }
    }

done:
    /* also start device! */
        return 1;
}

static tvi_handle_t *tv_begin(tv_param_t* tv_param, struct mp_log *log)
{
    int i;
    tvi_handle_t* h;
    if(tv_param->driver && !strcmp(tv_param->driver,"help")){
        mp_info(log, "Available drivers:\n");
        for(i=0;tvi_driver_list[i];i++){
            mp_info(log, " %s\t%s",tvi_driver_list[i]->short_name,tvi_driver_list[i]->name);
            if(tvi_driver_list[i]->comment)
                mp_info(log, " (%s)",tvi_driver_list[i]->comment);
            mp_info(log, "\n");
        }
        return NULL;
    }

    for(i=0;tvi_driver_list[i];i++){
        if (!tv_param->driver || !strcmp(tvi_driver_list[i]->short_name, tv_param->driver)){
            h=tvi_driver_list[i]->tvi_init(log, tv_param);
            //Requested driver initialization failed
            if (!h && tv_param->driver)
                return NULL;
            //Driver initialization failed during autodetection process.
            if (!h)
                continue;

            h->tv_param=tv_param;
            MP_INFO(h, "Selected driver: %s\n name: %s\n author: %s\n comment: %s\n", tvi_driver_list[i]->short_name,
            tvi_driver_list[i]->name,
            tvi_driver_list[i]->author,
            tvi_driver_list[i]->comment?tvi_driver_list[i]->comment:"");
            tv_param->driver=strdup(tvi_driver_list[i]->short_name);
            return h;
        }
    }

    if(tv_param->driver)
        mp_err(log, "No such driver: %s\n", tv_param->driver);
    else
        mp_err(log, "TV driver autodetection failed.\n");
    return NULL;
}

static int tv_uninit(tvi_handle_t *tvh)
{
    int res;
    if(!tvh) return 1;
    if (!tvh->priv) return 1;
    res=tvh->functions->uninit(tvh->priv);
    if(res) {
        free(tvh->priv);
        tvh->priv=NULL;
    }
    return res;
}

static int demux_open_tv(demuxer_t *demuxer, enum demux_check check)
{
    tvi_handle_t *tvh;
    sh_video_t *sh_video;
    sh_audio_t *sh_audio = NULL;
    const tvi_functions_t *funcs;

    if (check > DEMUX_CHECK_REQUEST || demuxer->stream->type != STREAMTYPE_TV)
        return -1;

    demuxer->priv=NULL;
    if(!(tvh=tv_begin(demuxer->stream->priv, demuxer->log))) return -1;
    if (!tvh->functions->init(tvh->priv)) return -1;

    tvh->demuxer = demuxer;

    if (!open_tv(tvh)){
        tv_uninit(tvh);
        return -1;
    }
    funcs = tvh->functions;
    demuxer->priv=tvh;

    struct sh_stream *sh_v = new_sh_stream(demuxer, STREAM_VIDEO);
    sh_video = sh_v->video;

    /* get IMAGE FORMAT */
    int fourcc;
    funcs->control(tvh->priv, TVI_CONTROL_VID_GET_FORMAT, &fourcc);
    if (fourcc == MP_FOURCC_MJPEG) {
        sh_v->codec = "mjpeg";
    } else {
        sh_v->codec = "rawvideo";
        sh_v->format = fourcc;
    }

    /* set FPS and FRAMETIME */

    if(!sh_video->fps)
    {
        float tmp;
        if (funcs->control(tvh->priv, TVI_CONTROL_VID_GET_FPS, &tmp) != TVI_CONTROL_TRUE)
             sh_video->fps = 25.0f; /* on PAL */
        else sh_video->fps = tmp;
    }

    if (tvh->tv_param->fps != -1.0f)
        sh_video->fps = tvh->tv_param->fps;

    /* If playback only mode, go to immediate mode, fail silently */
    if(tvh->tv_param->immediate == 1)
        {
        funcs->control(tvh->priv, TVI_CONTROL_IMMEDIATE, 0);
        tvh->tv_param->noaudio = 1;
        }

    /* set width */
    funcs->control(tvh->priv, TVI_CONTROL_VID_GET_WIDTH, &sh_video->disp_w);

    /* set height */
    funcs->control(tvh->priv, TVI_CONTROL_VID_GET_HEIGHT, &sh_video->disp_h);

    demuxer->seekable = 0;

    /* here comes audio init */
    if (tvh->tv_param->noaudio == 0 && funcs->control(tvh->priv, TVI_CONTROL_IS_AUDIO, 0) == TVI_CONTROL_TRUE)
    {
        int audio_format;

        /* yeah, audio is present */

        funcs->control(tvh->priv, TVI_CONTROL_AUD_SET_SAMPLERATE,
                                  &tvh->tv_param->audiorate);

        if (funcs->control(tvh->priv, TVI_CONTROL_AUD_GET_FORMAT, &audio_format) != TVI_CONTROL_TRUE)
            goto no_audio;

        switch(audio_format)
        {
            case AF_FORMAT_U8:
            case AF_FORMAT_S8:
            case AF_FORMAT_U16_LE:
            case AF_FORMAT_U16_BE:
            case AF_FORMAT_S16_LE:
            case AF_FORMAT_S16_BE:
            case AF_FORMAT_S32_LE:
            case AF_FORMAT_S32_BE:
                break;
            case AF_FORMAT_MPEG2:
            default:
                MP_ERR(tvh, "Audio type '%s' unsupported!\n",
                    af_fmt_to_str(audio_format));
                goto no_audio;
        }

        struct sh_stream *sh_a = new_sh_stream(demuxer, STREAM_AUDIO);
        sh_audio = sh_a->audio;

        funcs->control(tvh->priv, TVI_CONTROL_AUD_GET_SAMPLERATE,
                   &sh_audio->samplerate);
        int nchannels = sh_audio->channels.num;
        funcs->control(tvh->priv, TVI_CONTROL_AUD_GET_CHANNELS,
                   &nchannels);
        mp_chmap_from_channels(&sh_audio->channels, nchannels);

        sh_a->codec = "mp-pcm";
        sh_a->format = audio_format;

        int samplesize = af_fmt2bits(audio_format) / 8;
        int block_align = samplesize * sh_audio->channels.num;
        int bytes_per_second = sh_audio->samplerate * block_align;

        sh_audio->bitrate = bytes_per_second * 8;

        // emulate WF for win32 codecs:
        sh_audio->wf = talloc_zero(sh_audio, MP_WAVEFORMATEX);
        sh_audio->wf->wFormatTag = sh_a->format;
        sh_audio->wf->nChannels = sh_audio->channels.num;
        sh_audio->wf->wBitsPerSample = samplesize * 8;
        sh_audio->wf->nSamplesPerSec = sh_audio->samplerate;
        sh_audio->wf->nBlockAlign = block_align;
        sh_audio->wf->nAvgBytesPerSec = bytes_per_second;

        MP_VERBOSE(tvh, "  TV audio: %d channels, %d bits, %d Hz\n",
          sh_audio->wf->nChannels, sh_audio->wf->wBitsPerSample,
          sh_audio->wf->nSamplesPerSec);
    }
no_audio:

    if(!(funcs->start(tvh->priv))){
        // start failed :(
        tv_uninit(tvh);
        return -1;
    }

    /* set color eq */
    tv_set_color_options(tvh, TV_COLOR_BRIGHTNESS, tvh->tv_param->brightness);
    tv_set_color_options(tvh, TV_COLOR_HUE, tvh->tv_param->hue);
    tv_set_color_options(tvh, TV_COLOR_SATURATION, tvh->tv_param->saturation);
    tv_set_color_options(tvh, TV_COLOR_CONTRAST, tvh->tv_param->contrast);

    if(tvh->tv_param->gain!=-1)
        if(funcs->control(tvh->priv,TVI_CONTROL_VID_SET_GAIN,&tvh->tv_param->gain)!=TVI_CONTROL_TRUE)
            MP_WARN(tvh, "Unable to set gain control!\n");

    return 0;
}

static void demux_close_tv(demuxer_t *demuxer)
{
    tvi_handle_t *tvh=(tvi_handle_t*)(demuxer->priv);
    if (!tvh) return;
    tv_uninit(tvh);
    free(tvh);
    demuxer->priv=NULL;
}

int tv_set_color_options(tvi_handle_t *tvh, int opt, int value)
{
    const tvi_functions_t *funcs = tvh->functions;

    switch(opt)
    {
        case TV_COLOR_BRIGHTNESS:
            return funcs->control(tvh->priv, TVI_CONTROL_VID_SET_BRIGHTNESS, &value);
        case TV_COLOR_HUE:
            return funcs->control(tvh->priv, TVI_CONTROL_VID_SET_HUE, &value);
        case TV_COLOR_SATURATION:
            return funcs->control(tvh->priv, TVI_CONTROL_VID_SET_SATURATION, &value);
        case TV_COLOR_CONTRAST:
            return funcs->control(tvh->priv, TVI_CONTROL_VID_SET_CONTRAST, &value);
        default:
            MP_WARN(tvh, "Unknown color option (%d) specified!\n", opt);
    }

    return TVI_CONTROL_UNKNOWN;
}

int tv_get_color_options(tvi_handle_t *tvh, int opt, int* value)
{
    const tvi_functions_t *funcs = tvh->functions;

    switch(opt)
    {
        case TV_COLOR_BRIGHTNESS:
            return funcs->control(tvh->priv, TVI_CONTROL_VID_GET_BRIGHTNESS, value);
        case TV_COLOR_HUE:
            return funcs->control(tvh->priv, TVI_CONTROL_VID_GET_HUE, value);
        case TV_COLOR_SATURATION:
            return funcs->control(tvh->priv, TVI_CONTROL_VID_GET_SATURATION, value);
        case TV_COLOR_CONTRAST:
            return funcs->control(tvh->priv, TVI_CONTROL_VID_GET_CONTRAST, value);
        default:
            MP_WARN(tvh, "Unknown color option (%d) specified!\n", opt);
    }

    return TVI_CONTROL_UNKNOWN;
}

int tv_get_freq(tvi_handle_t *tvh, unsigned long *freq)
{
    if (tvh->functions->control(tvh->priv, TVI_CONTROL_IS_TUNER, 0) == TVI_CONTROL_TRUE)
    {
        tvh->functions->control(tvh->priv, TVI_CONTROL_TUN_GET_FREQ, freq);
        MP_VERBOSE(tvh, "Current frequency: %lu (%.3f)\n",
            *freq, *freq/16.0);
    }
    return 1;
}

int tv_set_freq(tvi_handle_t *tvh, unsigned long freq)
{
    if (tvh->functions->control(tvh->priv, TVI_CONTROL_IS_TUNER, 0) == TVI_CONTROL_TRUE)
    {
//      unsigned long freq = atof(tvh->tv_param->freq)*16;

        /* set freq in MHz */
        tvh->functions->control(tvh->priv, TVI_CONTROL_TUN_SET_FREQ, &freq);

        tvh->functions->control(tvh->priv, TVI_CONTROL_TUN_GET_FREQ, &freq);
        MP_VERBOSE(tvh, "Current frequency: %lu (%.3f)\n",
            freq, freq/16.0);
    }
    return 1;
}

int tv_get_signal(tvi_handle_t *tvh)
{
    int signal=0;
    if (tvh->functions->control(tvh->priv, TVI_CONTROL_IS_TUNER, 0) != TVI_CONTROL_TRUE ||
        tvh->functions->control(tvh->priv, TVI_CONTROL_TUN_GET_SIGNAL, &signal)!=TVI_CONTROL_TRUE)
        return 0;

    return signal;
}

/*****************************************************************
 * \brief tune current frequency by step_interval value
 * \parameter step_interval increment value in 1/16 MHz
 * \note frequency is rounded to 1/16 MHz value
 * \return 1
 *
 */
int tv_step_freq(tvi_handle_t* tvh, float step_interval){
    unsigned long frequency;

    tvh->tv_param->scan=0;
    tv_get_freq(tvh,&frequency);
    frequency+=step_interval;
    return tv_set_freq(tvh,frequency);
}

int tv_step_channel_real(tvi_handle_t *tvh, int direction)
{
    struct CHANLIST cl;

    tvh->tv_param->scan=0;
    if (direction == TV_CHANNEL_LOWER)
    {
        if (tvh->channel-1 >= 0)
        {
            strcpy(tv_channel_last_real, tvh->chanlist_s[tvh->channel].name);
            cl = tvh->chanlist_s[--tvh->channel];
            MP_INFO(tvh, "Selected channel: %s (freq: %.3f)\n",
                cl.name, cl.freq/1000.0);
            tv_set_freq_float(tvh, cl.freq);
        }
    }

    if (direction == TV_CHANNEL_HIGHER)
    {
        if (tvh->channel+1 < chanlists[tvh->chanlist].count)
        {
            strcpy(tv_channel_last_real, tvh->chanlist_s[tvh->channel].name);
            cl = tvh->chanlist_s[++tvh->channel];
            MP_INFO(tvh, "Selected channel: %s (freq: %.3f)\n",
                cl.name, cl.freq/1000.0);
            tv_set_freq_float(tvh, cl.freq);
        }
    }
    return 1;
}

int tv_step_channel(tvi_handle_t *tvh, int direction) {
        tvh->tv_param->scan=0;
        if (tv_channel_list) {
                if (direction == TV_CHANNEL_HIGHER) {
                        tv_channel_last = tv_channel_current;
                        if (tv_channel_current->next)
                                tv_channel_current = tv_channel_current->next;
                        else
                                tv_channel_current = tv_channel_list;
                        set_norm_and_freq(tvh, tv_channel_current);
                }
                if (direction == TV_CHANNEL_LOWER) {
                        tv_channel_last = tv_channel_current;
                        if (tv_channel_current->prev)
                                tv_channel_current = tv_channel_current->prev;
                        else
                                while (tv_channel_current->next)
                                        tv_channel_current = tv_channel_current->next;
                        set_norm_and_freq(tvh, tv_channel_current);
                }
        } else tv_step_channel_real(tvh, direction);
        return 1;
}

int tv_set_channel_real(tvi_handle_t *tvh, char *channel) {
        int i;
        struct CHANLIST cl;

        tvh->tv_param->scan=0;
        strcpy(tv_channel_last_real, tvh->chanlist_s[tvh->channel].name);
        for (i = 0; i < chanlists[tvh->chanlist].count; i++)
        {
            cl = tvh->chanlist_s[i];
//          printf("count%d: name: %s, freq: %d\n",
//              i, cl.name, cl.freq);
            if (!strcasecmp(cl.name, channel))
            {
                tvh->channel = i;
                MP_INFO(tvh, "Selected channel: %s (freq: %.3f)\n",
                    cl.name, cl.freq/1000.0);
                tv_set_freq_float(tvh, cl.freq);
                break;
            }
        }
        return 1;
}

int tv_set_channel(tvi_handle_t *tvh, char *channel) {
        int i, channel_int;

        tvh->tv_param->scan=0;
        if (tv_channel_list) {
                tv_channel_last = tv_channel_current;
                channel_int = atoi(channel);
                tv_channel_current = tv_channel_list;
                for (i = 1; i < channel_int; i++)
                        if (tv_channel_current->next)
                                tv_channel_current = tv_channel_current->next;
                set_norm_and_freq(tvh, tv_channel_current);
        } else tv_set_channel_real(tvh, channel);
        return 1;
}

int tv_last_channel(tvi_handle_t *tvh) {

        tvh->tv_param->scan=0;
        if (tv_channel_list) {
                tv_channels_t *tmp;

                tmp = tv_channel_last;
                tv_channel_last = tv_channel_current;
                tv_channel_current = tmp;

                set_norm_and_freq(tvh, tv_channel_current);
        } else {
                int i;
                struct CHANLIST cl;

                for (i = 0; i < chanlists[tvh->chanlist].count; i++)
                {
                    cl = tvh->chanlist_s[i];
                    if (!strcasecmp(cl.name, tv_channel_last_real))
                    {
                        strcpy(tv_channel_last_real, tvh->chanlist_s[tvh->channel].name);
                        tvh->channel = i;
                        MP_INFO(tvh, "Selected channel: %s (freq: %.3f)\n",
                            cl.name, cl.freq/1000.0);
                        tv_set_freq_float(tvh, cl.freq);
                        break;
                    }
                }
        }
        return 1;
}

int tv_step_norm(tvi_handle_t *tvh)
{
  tvh->norm++;
  if (tvh->functions->control(tvh->priv, TVI_CONTROL_TUN_SET_NORM,
                              &tvh->norm) != TVI_CONTROL_TRUE) {
    tvh->norm = 0;
    if (tvh->functions->control(tvh->priv, TVI_CONTROL_TUN_SET_NORM,
                                &tvh->norm) != TVI_CONTROL_TRUE) {
      MP_ERR(tvh, "Error: Cannot set norm!\n");
      return 0;
    }
  }
    return 1;
}

int tv_step_chanlist(tvi_handle_t *tvh)
{
    return 1;
}

demuxer_desc_t demuxer_desc_tv = {
    .name = "tv",
    .desc = "TV card demuxer",
    .type = DEMUXER_TYPE_TV,
    .fill_buffer = demux_tv_fill_buffer,
    .open = demux_open_tv,
    .close = demux_close_tv,
};