summaryrefslogtreecommitdiff
path: root/p2pvr/scanner/p2scan.cpp
blob: cb3e0fc89d4d4c284bd6d918d2876d723cb920e1 (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
/*
 * tv_grab_dvb - dump dvb epg info in xmltv
 * Version 0.2 - 20/04/2004 - First Public Release
 *
 * Copyright (C) 2004 Mark Bryars <dvb at darkskiez d0t co d0t uk>
 *
 * DVB code Mercilessly ripped off from dvddate
 * dvbdate Copyright (C) Laurence Culhane 2002 <dvbdate@holmes.demon.co.uk>
 *
 * This program 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.
 *
 * This program 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 this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 * Or, point your browser to http://www.gnu.org/copyleft/gpl.html
 */

const char *id = "@(#) $Id: tv_grab_dvb.c 86 2010-10-29 20:27:31Z pmhahn $";

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/poll.h>
#include <errno.h>
#include <getopt.h>
#include <stdarg.h>
#include <stdint.h>
#include <signal.h>
#include <time.h>
#include <stdbool.h>
#include <assert.h>
#include <glibmm.h>
#include <boost/bind.hpp>

#include <linux/dvb/dmx.h>
#include "si_tables.h"
#include "tv_grab_dvb.h"

#include "variables.h"
#include "rowProcessor.h"

struct EitProgram {
	VariableType serviceID;
	VariableType eventID;
	VariableType title;
	VariableType titleLang;
	VariableType subtitle;
	VariableType subtitleLang;
	VariableType descLang;
	VariableType desc1;
	VariableType desc2;
	VariableType desc3;
	VariableType videoAspect;
	VariableType audioChannels;
	VariableType language;
	VariableType teletextSubtitleLang;
	VariableType category;
	VariableType dvbRating;
	VariableType contentIdentType;
	VariableType contentIdent;
	VariableType startTime;
	VariableType stopTime;
};

Glib::ustring title("title");
#include "xmlObjectLoader.h"
#include "rowSet.h"
template <class C, class M>
const M &
getMember(M C::*t, C * p) {
	return p->*t;
}
SimpleMessageException(NoSuchAttribute);
class EitRows : public RowSet {
	public:
		EitRows(const xmlpp::Element * p);
		~EitRows();
		void execute(const RowProcessor *) const;
		void loadComplete(const CommonObjects *) {
		}
		void setFilter(const Glib::ustring &) {
		}
		unsigned int columnCount() const {
			return 1;
		}
		const Glib::ustring & getColumnName(unsigned int) const {
			return title;
		}
		VariableType getCurrentValue(const Glib::ustring &) const {
			return current->title;
		}
		VariableType getCurrentValue(unsigned int) const {
			return current->title;
		}
		bool isNull(unsigned int ) const {
			return false;
		}
		bool isNull(const Glib::ustring & ) const {
			return false;
		}
#define returnAttr(name) if (attrName == #name) return boost::bind(getMember<EitProgram, VariableType>, &EitProgram::name, boost::ref(current))
		RowAttribute resolveAttr(const Glib::ustring & attrName) const {
			returnAttr(serviceID);
			returnAttr(eventID);
			returnAttr(title);
			returnAttr(titleLang);
			returnAttr(subtitle);
			returnAttr(subtitleLang);
			returnAttr(descLang);
			returnAttr(desc1);
			returnAttr(desc2);
			returnAttr(desc3);
			returnAttr(videoAspect);
			returnAttr(audioChannels);
			returnAttr(language);
			returnAttr(teletextSubtitleLang);
			returnAttr(category);
			returnAttr(dvbRating);
			returnAttr(contentIdentType);
			returnAttr(contentIdent);
			returnAttr(startTime);
			returnAttr(stopTime);
			throw NoSuchAttribute(attrName);
		}
	private:
		enum ER { TITLE, SUB_TITLE };
		enum CR { LANGUAGE, VIDEO, AUDIO, SUBTITLES };
		Variable demux;
		Variable timeout;
		void openInput() const;
		void readEventTables(const RowProcessor *) const;
		bool parseEIT(const u_char *data, size_t len, const RowProcessor *) const;
		void parseEventDescription(const u_char *data, enum ER round) const;
		void parseLongEventDescription(const u_char *data) const;
		void parseComponentDescription(const u_char *data, enum CR round, int *seen) const;
		void parseContentDescription(const u_char *data) const;
		void parseRatingDescription(const u_char *data) const;
		void parseContentIdentifierDescription(const u_char *data) const;
		void parseDescription(const u_char * data, size_t len) const;

		Glib::ustring convert(const char * txt) const;

		mutable int fd_epg;
		mutable EitProgram * current;

		static const std::string EitEncoding;
		static const std::string UTF8;
};

DECLARE_LOADER("eitrows", EitRows);

const std::string EitRows::EitEncoding("ISO6937");
const std::string EitRows::UTF8("UTF8");

EitRows::EitRows(const xmlpp::Element * p) :
	RowSet(p),
	demux(p, "demux", false, "/dev/dvb/adapter0/demux0"),
	timeout(p, "timeout", false, 10000),
	fd_epg(0),
	current(NULL)
{
}

EitRows::~EitRows()
{
	if (fd_epg) {
		close(fd_epg);
	}
}

static int time_offset   = 0;
static int chan_filter	     = 0;
static int chan_filter_mask = 0;
static bool ignore_bad_dates = true;
static bool ignore_updates = true;
static bool silent = false;

typedef struct chninfo {
	struct chninfo *next;
	int sid;
	int eid;
	int ver;
} chninfo_t;

static struct chninfo *channels;

/* Parse command line arguments. {{{ */
int do_options(int arg_count, char **arg_strings) {
	static const struct option Long_Options[] = {
		{"help", 0, 0, 'h'},
		{"chanidents", 1, 0, 'c'},
		{0, 0, 0, 0}
	};
	int Option_Index = 0;

	while (1) {
		int c = getopt_long(arg_count, arg_strings, "udscmpnht:o:f:i:e:", Long_Options, &Option_Index);
		if (c == EOF)
			break;
		switch (c) {
		case 'u':
			ignore_updates = false;
			break;
		case 'd':
			ignore_bad_dates = false;
			break;
		case 'n':
			chan_filter = 0x4e;
			chan_filter_mask = 0xfe;
			break;
		case 'm':
			chan_filter = 0x4e;
			chan_filter_mask = 0xff;
			break;
		case 'p':
			chan_filter = 0x4f;
			chan_filter_mask = 0xff;
			break;
		case 's':
			silent = true;
			break;
		case 'h':
		case '?':
			break;
		case 0:
		default:
			_exit(1);
		}
	}
	return 0;
} /*}}}*/


/* Parse language-id translation file. {{{ */
static const char *xmllang(const u_char *l) {
	static union lookup_key lang;
	lang.c[0] = (char)l[0];
	lang.c[1] = (char)l[1];
	lang.c[2] = (char)l[2];
	lang.c[3] = '\0';

	const char *c = lookup(languageid_table, lang.i);
	return c ? c : lang.c;
} /*}}}*/

Glib::ustring
EitRows::convert(const char * txt) const
{
	char enc[20];
	switch ((unsigned char)*txt) {
		case 0x20 ... 0xFF:
			return Glib::convert(txt, UTF8, EitEncoding);
		case 0x01 ... 0x05:
			snprintf(enc, sizeof(enc), "ISO-8859-%d\n", txt[0] + 4);
			return Glib::convert(txt + 1, UTF8, "ISO-8859-5");
		case 0x10:
			snprintf(enc, sizeof(enc), "ISO-8859-%02x%02x\n", txt[1], txt[2]);
			return Glib::convert(txt + 3, UTF8, enc);
		case 0x11:
			return Glib::convert(txt, UTF8, "ISO-10646");
		case 0x06 ... 0x0F:
		case 0x12 ... 0x1F:
			// Values for the first byte of "0x00", "0x06" to "0x0F", and "0x12" to "0x1F" are reserved for future use.
			//fprintf(stderr, "Reserved encoding: %02x\n", txt[0]);
			//fprintf(stderr, "%s\n", txt);
		case 0x00: // empty string
			return "";
	}
}

/* Parse 0x4D Short Event Descriptor. {{{ */
void
EitRows::parseEventDescription(const u_char *data, enum ER round) const {
	assert(GetDescriptorTag(data) == 0x4D);
	const struct descr_short_event *evtdesc = reinterpret_cast<const struct descr_short_event *>(data);
	char evt[256];
	char dsc[256];

	size_t evtlen = evtdesc->event_name_length;
	if (round == TITLE) {
		if (!evtlen)
			return;
		assert(evtlen < sizeof(evt));
		memcpy(evt, &evtdesc->data, evtlen);
		evt[evtlen] = '\0';
		current->titleLang = xmllang(&evtdesc->lang_code1);
		current->title = convert(evt);
		return;
	}

	if (round == SUB_TITLE) {
		size_t dsclen = evtdesc->data[evtlen];
		assert(dsclen < sizeof(dsc));
		memcpy(dsc, &evtdesc->data[evtlen+1], dsclen);
		dsc[dsclen] = '\0';

		if (*dsc) {
			current->subtitleLang = xmllang(&evtdesc->lang_code1);
			current->subtitle = convert(dsc);
		}
	}
} /*}}}*/

/* Parse 0x4E Extended Event Descriptor. {{{ */
void
EitRows::parseLongEventDescription(const u_char *data) const {
	assert(GetDescriptorTag(data) == 0x4E);
	const struct descr_extended_event *levt = reinterpret_cast<const struct descr_extended_event *>(data);
	char dsc[256];
	bool non_empty = (levt->descriptor_number || levt->last_descriptor_number || levt->length_of_items || levt->data[0]);

	if (non_empty && levt->descriptor_number == 0) {
		current->descLang = levt->lang_code1;

		const u_char *p = reinterpret_cast<const u_char *>(&levt->data);
		const void *data_end = data + DESCR_GEN_LEN + GetDescriptorLength(data);
		while (p < levt->data + levt->length_of_items) {
			const struct item_extended_event *name = reinterpret_cast<const struct item_extended_event *>(p);
			size_t name_len = name->item_description_length;
			assert(p + ITEM_EXTENDED_EVENT_LEN + name_len < data_end);
			assert(name_len < sizeof(dsc));
			memcpy(dsc, &name->data, name_len);
			dsc[name_len] = '\0';
			current->desc1 = convert(dsc);

			p += ITEM_EXTENDED_EVENT_LEN + name_len;

			const struct item_extended_event *value = reinterpret_cast<const struct item_extended_event *>(p);
			size_t value_len = value->item_description_length;
			assert(p + ITEM_EXTENDED_EVENT_LEN + value_len < data_end);
			assert(value_len < sizeof(dsc));
			memcpy(dsc, &value->data, value_len);
			dsc[value_len] = '\0';
			current->desc2 = convert(dsc);

			p += ITEM_EXTENDED_EVENT_LEN + value_len;
		}
		const struct item_extended_event *text = reinterpret_cast<const struct item_extended_event *>(p);
		size_t len = text->item_description_length;
		if (non_empty && len) {
			assert(len < sizeof(dsc));
			memcpy(dsc, &text->data, len);
			dsc[len] = '\0';
			current->desc3 = convert(dsc);
		}

	}
} /*}}}*/

/* Parse 0x50 Component Descriptor.  {{{
   video is a flag, 1=> output the video information, 0=> output the
   audio information.  seen is a pointer to a counter to ensure we
   only output the first one of each (XMLTV can't cope with more than
   one) */
void
EitRows::parseComponentDescription(const u_char *data, enum CR round, int *seen) const {
	assert(GetDescriptorTag(data) == 0x50);
	const struct descr_component *dc = reinterpret_cast<const struct descr_component *>(data);
	char buf[256];

	size_t len = dc->descriptor_length;
	assert(len < sizeof(buf));
	memcpy(buf, &dc->data, len);
	buf[len] = '\0';

	switch (dc->stream_content) {
		case 0x01: // Video Info
			if (round == VIDEO && !*seen) {
				//if ((dc->component_type-1)&0x08) //HD TV
				//if ((dc->component_type-1)&0x04) //30Hz else 25
				current->videoAspect = lookup(aspect_table, (dc->component_type-1) & 0x03);
				(*seen)++;
			}
			break;
		case 0x02: // Audio Info
			if (round == AUDIO && !*seen) {
				current->audioChannels = lookup(audio_table, (dc->component_type));
				(*seen)++;
			}
			if (round == LANGUAGE) {
				if (!*seen)
					current->language = xmllang(&dc->lang_code1);
				(*seen)++;
			}
			break;
		case 0x03: // Teletext Info
			if (round == SUBTITLES) {
				// FIXME: is there a suitable XMLTV output for this?
				// if ((dc->component_type)&0x10) //subtitles
				// if ((dc->component_type)&0x20) //subtitles for hard of hearing
				current->teletextSubtitleLang = xmllang(&dc->lang_code1);
			}
			break;
			// case 0x04: // AC3 info
	}
} /*}}}*/

static inline void set_bit(int *bf, int b) {
	int i = b / 8 / sizeof(int);
	int s = b % (8 * sizeof(int));
	bf[i] |= (1 << s);
}

static inline bool get_bit(int *bf, int b) {
	int i = b / 8 / sizeof(int);
	int s = b % (8 * sizeof(int));
	return bf[i] & (1 << s);
}

/* Parse 0x54 Content Descriptor. {{{ */
void
EitRows::parseContentDescription(const u_char *data) const {
	assert(GetDescriptorTag(data) == 0x54);
	const struct descr_content *dc = reinterpret_cast<const struct descr_content *>(data);
	int once[256/8/sizeof(int)] = {0,};
	for (const u_char * p = reinterpret_cast<const u_char*>(&dc->data); p < data + dc->descriptor_length; p += NIBBLE_CONTENT_LEN) {
		const struct nibble_content *nc = reinterpret_cast<const nibble_content *>(p);
		int c1 = (nc->content_nibble_level_1 << 4) + nc->content_nibble_level_2;
		if (c1 > 0 && !get_bit(once, c1)) {
			set_bit(once, c1);
			const char *c = lookup(description_table, c1);
			if (c)
				if (c[0])
					current->category = c;
		}
		// This is weird in the uk, they use user but not content, and almost the same values
	}
} /*}}}*/

/* Parse 0x55 Rating Descriptor. {{{ */
void
EitRows::parseRatingDescription(const u_char *data) const {
	assert(GetDescriptorTag(data) == 0x55);
	const struct descr_parental_rating *pr = reinterpret_cast<const struct descr_parental_rating *>(data);
	for (const u_char * p = reinterpret_cast<const u_char *>(&pr->data); p < data + pr->descriptor_length; p += PARENTAL_RATING_ITEM_LEN) {
		const struct parental_rating_item *pr = reinterpret_cast<const struct parental_rating_item *>(p);
		switch (pr->rating) {
			case 0x00: /*undefined*/
				break;
			case 0x01 ... 0x0F:
				current->dvbRating = pr->rating + 3;
				break;
			case 0x10 ... 0xFF: /*broadcaster defined*/
				break;
		}
	}
} /*}}}*/

/* Parse 0x5F Private Data Specifier. {{{ */
int parsePrivateDataSpecifier(const u_char *data) {
	assert(GetDescriptorTag(data) == 0x5F);
	return GetPrivateDataSpecifier(data);
} /*}}}*/

/* Parse 0x76 Content Identifier Descriptor. {{{ */
/* See ETSI TS 102 323, section 12 */
void
EitRows::parseContentIdentifierDescription(const u_char *data) const {
	assert(GetDescriptorTag(data) == 0x76);
	const struct descr_content_identifier *ci = reinterpret_cast<const struct descr_content_identifier *>(data);
	for (const u_char * p = reinterpret_cast<const u_char *>(&ci->data); p < data + ci->descriptor_length; /* at end */) {
		const struct descr_content_identifier_crid *crid = reinterpret_cast<const struct descr_content_identifier_crid *>(p);
		struct descr_content_identifier_crid_local *crid_data;

		int crid_length = 3;

		char type_buf[32];
		const char *type;
		char buf[256];

		type = lookup(crid_type_table, crid->crid_type);
		if (type == NULL)
		{
			type = type_buf;
			sprintf(type_buf, "0x%2x", crid->crid_type);
		}

		switch (crid->crid_location)
		{
		case 0x01: /* Carried in Content Identifier Table (CIT) */
			break;
		default:
			break;
		case 0x00: /* Carried explicitly within descriptor */
			crid_data = (descr_content_identifier_crid_local_t *)&crid->crid_ref_data;
			size_t cridlen = crid_data->crid_length;
			assert(cridlen < sizeof(buf));
			memcpy(buf, &crid_data->crid_byte, cridlen);
			buf[cridlen] = '\0';

			current->contentIdentType = type;
			current->contentIdent = buf;
			crid_length = 2 + crid_data->crid_length;
			break;
		}

		p += crid_length;
	}
} /*}}}*/

/* Parse Descriptor. {{{
 * Tags should be output in this order:

'title', 'sub-title', 'desc', 'credits', 'date', 'category', 'language',
'orig-language', 'length', 'icon', 'url', 'country', 'episode-num',
'video', 'audio', 'previously-shown', 'premiere', 'last-chance',
'new', 'subtitles', 'rating', 'star-rating'
*/
void
EitRows::parseDescription(const u_char * data, size_t len) const {
	int round, pds = 0;

	for (round = 0; round < 8; round++) {
		int seen = 0; // no title/language/video/audio/subtitles seen in this round
		for (const u_char * p = data; p < data + len; p += DESCR_GEN_LEN + GetDescriptorLength(p)) {
			const struct descr_gen *desc = reinterpret_cast<const struct descr_gen *>(p);
			switch (GetDescriptorTag(desc)) {
				case 0:
					break;
				case 0x4D: //short evt desc, [title] [sub-title]
					// there can be multiple language versions of these
					if (round == 0) {
						parseEventDescription(p, TITLE);
					}
					else if (round == 1)
						parseEventDescription(p, SUB_TITLE);
					break;
				case 0x4E: //long evt descriptor [desc]
					if (round == 2)
						parseLongEventDescription(p);
					break;
				case 0x50: //component desc [language] [video] [audio] [subtitles]
					if (round == 4)
						parseComponentDescription(p, LANGUAGE, &seen);
					else if (round == 5)
						parseComponentDescription(p, VIDEO, &seen);
					else if (round == 6)
						parseComponentDescription(p, AUDIO, &seen);
					else if (round == 7)
						parseComponentDescription(p, SUBTITLES, &seen);
					break;
				case 0x53: // CA Identifier Descriptor
					break;
				case 0x54: // content desc [category]
					if (round == 3)
						parseContentDescription(p);
					break;
				case 0x55: // Parental Rating Descriptor [rating]
					if (round == 7)
						parseRatingDescription(p);
					break;
				case 0x5f: // Private Data Specifier
					pds = parsePrivateDataSpecifier(p);
					break;
				case 0x64: // Data broadcast desc - Text Desc for Data components
					break;
				case 0x69: // Programm Identification Label
					break;
				case 0x81: // TODO ???
					if (pds == 5) // ARD_ZDF_ORF
						break;
				case 0x82: // VPS (ARD, ZDF, ORF)
					if (pds == 5) // ARD_ZDF_ORF
						// TODO: <programme @vps-start="???">
						break;
				case 0x4F: // Time Shifted Event
				case 0x52: // Stream Identifier Descriptor
				case 0x5E: // Multi Lingual Component Descriptor
				case 0x83: // Logical Channel Descriptor (some kind of news-ticker on ARD-MHP-Data?)
				case 0x84: // Preferred Name List Descriptor
				case 0x85: // Preferred Name Identifier Descriptor
				case 0x86: // Eacem Stream Identifier Descriptor
					break;
				case 0x76: // Content identifier descriptor
					if (round == 5)
						parseContentIdentifierDescription(p);
					break;
				default:
					break;
			}
		}
	}
} /*}}}*/

/* Check that program has at least a title as is required by xmltv.dtd. {{{ */
static bool validateDescription(const u_char *data, size_t len) {
	for (const u_char * p = data; p < data + len; p += DESCR_GEN_LEN + GetDescriptorLength(p)) {
		const struct descr_gen *desc = reinterpret_cast<const struct descr_gen *>(p);
		if (GetDescriptorTag(desc) == 0x4D) {
			const struct descr_short_event *evtdesc = reinterpret_cast<const struct descr_short_event *>(p);
			// make sure that title isn't empty
			if (evtdesc->event_name_length) return true;
		}
	}
	return false;
} /*}}}*/

/* Use the routine specified in ETSI EN 300 468 V1.4.1, {{{
 * "Specification for Service Information in Digital Video Broadcasting"
 * to convert from Modified Julian Date to Year, Month, Day. */
static boost::posix_time::ptime parseMJD(long int mjd) {
	int year = (int) ((mjd - 15078.2) / 365.25);
	int month = (int) ((mjd - 14956.1 - (int) (year * 365.25)) / 30.6001);
	int day = mjd - 14956 - (int) (year * 365.25) - (int) (month * 30.6001);
	int i = (month == 14 || month == 15) ? 1 : 0;
	year += i ;
	month = month - 1 - i * 12;

	return boost::posix_time::ptime(boost::gregorian::date(1900 + year, month, day));
} /*}}}*/

bool
EitRows::parseEIT(const u_char *data, size_t len, const RowProcessor * rp) const {
	const struct eit *e = reinterpret_cast<const struct eit *>(data);

	len -= 4; //remove CRC

	// For each event listing
	bool found = false;
	for (const u_char *p = reinterpret_cast<const u_char *>(&e->data); p < data + len; p += EIT_EVENT_LEN + GetEITDescriptorsLoopLength(p)) {
		const struct eit_event *evt = reinterpret_cast<const struct eit_event *>(p);
		struct chninfo *c;
		// find existing information?
		for (c = channels; c != NULL; c = c->next) {
			// found it
			if (c->sid == HILO(e->service_id) && (c->eid == HILO(evt->event_id))) {
				if (c->ver <= e->version_number) // seen it before or its older FIXME: wrap-around to 0
					return false;
				else {
					c->ver = e->version_number; // update outputted version
					if (ignore_updates) {
						return false;
					}
					break;
				}
			}
		}

		// its a new program
		if (c == NULL) {
			chninfo_t *nc = static_cast<struct chninfo *>(malloc(sizeof(struct chninfo)));
			nc->sid = HILO(e->service_id);
			nc->eid = HILO(evt->event_id);
			nc->ver = e->version_number;
			nc->next = channels;
			channels = nc;
		}

		// No program info at end! Just skip it
		if (GetEITDescriptorsLoopLength(evt) == 0)
			return false;

		boost::posix_time::ptime startTime = parseMJD(HILO(evt->mjd)) + boost::posix_time::time_duration(
				BcdCharToInt(evt->start_time_h) + time_offset,
				BcdCharToInt(evt->start_time_m),
				BcdCharToInt(evt->start_time_s));
		EitProgram results;
		current = &results;
		results.startTime = startTime;
		results.stopTime = startTime + boost::posix_time::time_duration(
				BcdCharToInt(evt->duration_h),
				BcdCharToInt(evt->duration_m),
				BcdCharToInt(evt->duration_s));

		// a program must have a title that isn't empty
		if (!validateDescription(reinterpret_cast<const u_char *>(&evt->data), GetEITDescriptorsLoopLength(evt))) {
			return false;
		}


		results.serviceID = HILO(e->service_id);
		results.eventID = HILO(evt->event_id);

		//1 Airing, 2 Starts in a few seconds, 3 Pausing, 4 About to air

		parseDescription(reinterpret_cast<const u_char *>(&evt->data), GetEITDescriptorsLoopLength(evt));
		rowNum += 1;
		rp->rowReady();
		found = true;
	}
	return found;
}

SimpleMessageException(ErrorReadingData);
void
EitRows::readEventTables(const RowProcessor * rp) const
{
	u_char buf[1<<12];
	struct pollfd ufd;
	memset(&ufd, 0, sizeof(pollfd));
	ufd.fd = fd_epg;
	ufd.events = POLLIN;
	size_t n;
	time_t lastuseful = 0;
	while ((poll(&ufd, 1, (int64_t)timeout()) == 1) && (n = read(fd_epg, buf, sizeof(buf)))) {
		if (n < sizeof(struct si_tab))
			throw ErrorReadingData("Smaller that si_tab");
		struct si_tab *tab = (struct si_tab *)buf;
		size_t l = sizeof(struct si_tab) + GetSectionLength(tab);
		if (n < l)
			throw ErrorReadingData("Smaller that section length");
		if (_dvb_crc32(buf, l) == 0) {
			if (parseEIT(buf, l, rp)) {
				time(&lastuseful);
			}
			else {
				if (lastuseful < time(NULL) - 5) {
					break;
				}
			}
		}
	}
}

SimpleMessageException(DemuxOpenFailure);
SimpleMessageException(DemuxSetFilterFailure);

void
EitRows::openInput() const
{
	if ((fd_epg = open(demux(), O_RDWR)) < 0) {
		throw DemuxOpenFailure(strerror(errno));
	}

	struct dmx_sct_filter_params sctFilterParams;
	memset(&sctFilterParams, 0, sizeof(dmx_sct_filter_params));
	sctFilterParams.pid = 18; // EIT data
	sctFilterParams.timeout = 0;
	sctFilterParams.flags =  DMX_IMMEDIATE_START;
	sctFilterParams.filter.filter[0] = chan_filter; // 4e is now/next this multiplex, 4f others
	sctFilterParams.filter.mask[0] = chan_filter_mask;

	if (ioctl(fd_epg, DMX_SET_FILTER, &sctFilterParams) < 0) {
		throw DemuxSetFilterFailure(strerror(errno));
	}
}

void
EitRows::execute(const RowProcessor * rp) const
{
	openInput();
	readEventTables(rp);
	if (rowNum < 10) {
	}
	close(fd_epg);
	fd_epg = 0;
}