version: use compile date if commit date is unavailable. default to "(no branch)"
[enigma2.git] / lib / dvb / db.cpp
1 #include <errno.h>
2 #include <lib/dvb/db.h>
3 #include <lib/dvb/dvb.h>
4 #include <lib/dvb/frontend.h>
5 #include <lib/dvb/epgcache.h>
6 #include <lib/base/eenv.h>
7 #include <lib/base/eerror.h>
8 #include <lib/base/estring.h>
9 #include <xmlccwrap/xmlccwrap.h>
10 #include <dvbsi++/service_description_section.h>
11 #include <dvbsi++/descriptor_tag.h>
12 #include <dvbsi++/service_descriptor.h>
13 #include <dvbsi++/satellite_delivery_system_descriptor.h>
14
15 DEFINE_REF(eDVBService);
16
17 RESULT eBouquet::addService(const eServiceReference &ref, eServiceReference before)
18 {
19         list::iterator it =
20                 std::find(m_services.begin(), m_services.end(), ref);
21         if ( it != m_services.end() )
22                 return -1;
23         if (before.valid())
24         {
25                 it = std::find(m_services.begin(), m_services.end(), before);
26                 m_services.insert(it, ref);
27         }
28         else
29                 m_services.push_back(ref);
30         return 0;
31 }
32
33 RESULT eBouquet::removeService(const eServiceReference &ref)
34 {
35         list::iterator it =
36                 std::find(m_services.begin(), m_services.end(), ref);
37         if ( it == m_services.end() )
38                 return -1;
39         m_services.erase(it);
40         return 0;
41 }
42
43 RESULT eBouquet::moveService(const eServiceReference &ref, unsigned int pos)
44 {
45         if ( pos < 0 || pos >= m_services.size() )
46                 return -1;
47         ++pos;
48         list::iterator source=m_services.end();
49         list::iterator dest=m_services.end();
50         bool forward = false;
51         for (list::iterator it(m_services.begin()); it != m_services.end(); ++it)
52         {
53                 if (dest == m_services.end() && !--pos)
54                         dest = it;
55                 if (*it == ref)
56                 {
57                         source = it;
58                         forward = pos>0;
59                 }
60                 if (dest != m_services.end() && source != m_services.end())
61                         break;
62         }
63         if (dest == m_services.end() || source == m_services.end() || source == dest)
64                 return -1;
65         while (source != dest)
66         {
67                 if (forward)
68                         std::iter_swap(source++, source);
69                 else
70                         std::iter_swap(source--, source);
71         }
72         return 0;
73 }
74
75 RESULT eBouquet::flushChanges()
76 {
77         FILE *f=fopen(eEnv::resolve("${sysconfdir}/enigma2/" + m_filename).c_str(), "w");
78         if (!f)
79                 return -1;
80         if ( fprintf(f, "#NAME %s\r\n", m_bouquet_name.c_str()) < 0 )
81                 goto err;
82         for (list::iterator i(m_services.begin()); i != m_services.end(); ++i)
83         {
84                 eServiceReference tmp = *i;
85                 std::string str = tmp.path;
86                 if ( fprintf(f, "#SERVICE %s\r\n", tmp.toString().c_str()) < 0 )
87                         goto err;
88                 if ( i->name.length() )
89                         if ( fprintf(f, "#DESCRIPTION %s\r\n", i->name.c_str()) < 0 )
90                                 goto err;
91         }
92         fclose(f);
93         return 0;
94 err:
95         fclose(f);
96         eDebug("couldn't write file %s", m_filename.c_str());
97         return -1;
98 }
99
100 RESULT eBouquet::setListName(const std::string &name)
101 {
102         m_bouquet_name = name;
103         return 0;
104 }
105
106 eDVBService::eDVBService()
107         :m_cache(0), m_flags(0)
108 {
109 }
110
111 eDVBService::~eDVBService()
112 {
113         delete [] m_cache;
114 }
115
116 eDVBService &eDVBService::operator=(const eDVBService &s)
117 {
118         m_service_name = s.m_service_name;
119         m_service_name_sort = s.m_service_name_sort;
120         m_provider_name = s.m_provider_name;
121         m_flags = s.m_flags;
122         m_ca = s.m_ca;
123         copyCache(s.m_cache);
124         return *this;
125 }
126
127 void eDVBService::genSortName()
128 {
129         m_service_name_sort = removeDVBChars(m_service_name);
130         makeUpper(m_service_name_sort);
131         while ((!m_service_name_sort.empty()) && m_service_name_sort[0] == ' ')
132                 m_service_name_sort.erase(0, 1);
133
134                 /* put unnamed services at the end, not at the beginning. */
135         if (m_service_name_sort.empty())
136                 m_service_name_sort = "\xFF";
137 }
138
139 RESULT eDVBService::getName(const eServiceReference &ref, std::string &name)
140 {
141         if (!ref.name.empty())
142                 name = ref.name; // use renamed service name..
143         else if (!m_service_name.empty())
144                 name = m_service_name;
145         else
146                 name = "(...)";
147         return 0;
148 }
149
150 RESULT eDVBService::getEvent(const eServiceReference &ref, ePtr<eServiceEvent> &ptr, time_t start_time)
151 {
152         return eEPGCache::getInstance()->lookupEventTime(ref, start_time, ptr);
153 }
154
155 int eDVBService::isPlayable(const eServiceReference &ref, const eServiceReference &ignore, bool simulate)
156 {
157         ePtr<eDVBResourceManager> res_mgr;
158         if ( eDVBResourceManager::getInstance( res_mgr ) )
159                 eDebug("isPlayble... no res manager!!");
160         else
161         {
162                 eDVBChannelID chid, chid_ignore;
163                 ((const eServiceReferenceDVB&)ref).getChannelID(chid);
164                 ((const eServiceReferenceDVB&)ignore).getChannelID(chid_ignore);
165                 return res_mgr->canAllocateChannel(chid, chid_ignore, simulate);
166         }
167         return 0;
168 }
169
170 int eDVBService::checkFilter(const eServiceReferenceDVB &ref, const eDVBChannelQuery &query)
171 {
172         int res = 0;
173         switch (query.m_type)
174         {
175         case eDVBChannelQuery::tName:
176                 res = m_service_name_sort == query.m_string;
177                 break;
178         case eDVBChannelQuery::tProvider:
179                 if (query.m_string == "Unknown" && m_provider_name.empty())
180                         res = 1;
181                 else
182                         res = m_provider_name == query.m_string;
183                 break;
184         case eDVBChannelQuery::tType:
185         {
186                 int service_type = ref.getServiceType();
187                 if (query.m_int == 1) // TV Service
188                 {
189                         // Hack for dish network
190                         int onid = ref.getOriginalNetworkID().get();
191                         if (onid >= 0x1001 && onid <= 0x100b)
192                         {
193                                 static int dish_tv_types[] = { 128, 133, 137, 140, 144, 145, 150, 154, 160, 163, 164, 165, 166, 167, 168, 173, 174 };
194                                 static size_t dish_tv_num_types = sizeof(dish_tv_types) / sizeof(int);
195                                 if (std::binary_search(dish_tv_types, dish_tv_types + dish_tv_num_types, service_type))
196                                         return true;
197                         }
198                 }
199                 res = service_type == query.m_int;
200                 break;
201         }
202         case eDVBChannelQuery::tBouquet:
203                 res = 0;
204                 break;
205         case eDVBChannelQuery::tSatellitePosition:
206                 res = ((unsigned int)ref.getDVBNamespace().get())>>16 == (unsigned int)query.m_int;
207                 break;
208         case eDVBChannelQuery::tFlags:
209                 res = (m_flags & query.m_int) == query.m_int;
210                 break;
211         case eDVBChannelQuery::tChannelID:
212         {
213                 eDVBChannelID chid;
214                 ref.getChannelID(chid);
215                 res = chid == query.m_channelid;
216                 break;
217         }
218         case eDVBChannelQuery::tAND:
219                 res = checkFilter(ref, *query.m_p1) && checkFilter(ref, *query.m_p2);
220                 break;
221         case eDVBChannelQuery::tOR:
222                 res = checkFilter(ref, *query.m_p1) || checkFilter(ref, *query.m_p2);
223                 break;
224         case eDVBChannelQuery::tAny:
225                 res = 1;
226                 break;
227         }
228
229         if (query.m_inverse)
230                 return !res;
231         else
232                 return res;
233 }
234
235 bool eDVBService::cacheEmpty()
236 {
237         if (m_cache)
238                 for (int i=0; i < cacheMax; ++i)
239                         if (m_cache[i] != -1)
240                                 return false;
241         return true;
242 }
243
244 void eDVBService::initCache()
245 {
246         m_cache = new int[cacheMax];
247         memset(m_cache, -1, sizeof(int) * cacheMax);
248 }
249
250 void eDVBService::copyCache(int *source)
251 {
252         if (source)
253         {
254                 if (!m_cache)
255                         m_cache = new int[cacheMax];
256                 memcpy(m_cache, source, cacheMax * sizeof(int));
257         }
258         else
259         {
260                 delete [] m_cache;
261                 m_cache = 0;
262         }
263 }
264
265 int eDVBService::getCacheEntry(cacheID id)
266 {
267         if (id >= cacheMax || !m_cache)
268                 return -1;
269         return m_cache[id];
270 }
271
272 void eDVBService::setCacheEntry(cacheID id, int pid)
273 {
274         if (!m_cache)
275                 initCache();
276         if (id < cacheMax)
277                 m_cache[id] = pid;
278 }
279
280 DEFINE_REF(eDVBDB);
281
282 void eDVBDB::reloadServicelist()
283 {
284         loadServicelist(eEnv::resolve("${sysconfdir}/enigma2/lamedb").c_str());
285 }
286
287 void eDVBDB::parseServiceData(ePtr<eDVBService> s, std::string str)
288 {
289         while ((!str.empty()) && str[1]==':') // new: p:, f:, c:%02d...
290         {
291                 size_t c=str.find(',');
292                 char p=str[0];
293                 std::string v;
294                 if (c == std::string::npos)
295                 {
296                         v=str.substr(2);
297                         str="";
298                 } else
299                 {
300                         v=str.substr(2, c-2);
301                         str=str.substr(c+1);
302                 }
303 //              eDebug("%c ... %s", p, v.c_str());
304                 if (p == 'p')
305                         s->m_provider_name=v;
306                 else if (p == 'f')
307                 {
308                         sscanf(v.c_str(), "%x", &s->m_flags);
309                 } else if (p == 'c')
310                 {
311                         int cid, val;
312                         sscanf(v.c_str(), "%02d%x", &cid, &val);
313                         s->setCacheEntry((eDVBService::cacheID)cid,val);
314                 } else if (p == 'C')
315                 {
316                         int val;
317                         sscanf(v.c_str(), "%04x", &val);
318                         s->m_ca.push_front((uint16_t)val);
319                 }
320         }
321 }
322
323         /* THIS CODE IS BAD. it should be replaced by somethine better. */
324 void eDVBDB::loadServicelist(const char *file)
325 {
326         eDebug("---- opening lame channel db");
327         FILE *f=fopen(file, "rt");
328         if (!f && strcmp(file, eEnv::resolve("${sysconfdir}/enigma2/lamedb").c_str()) == 0)
329         {
330                 struct stat s;
331                 if ( !stat("lamedb", &s) )
332                 {
333                         if ( !stat(eEnv::resolve("${sysconfdir}/enigma2").c_str(), &s) )
334                         {
335                                 rename("lamedb", eEnv::resolve("${sysconfdir}/enigma2/lamedb").c_str());
336                                 reloadServicelist();
337                         }
338                 }
339                 return;
340         }
341         char line[256];
342         int version=3;
343         if ((!fgets(line, 256, f)) || sscanf(line, "eDVB services /%d/", &version) != 1)
344         {
345                 eDebug("not a valid servicefile");
346                 fclose(f);
347                 return;
348         }
349         eDebug("reading services (version %d)", version);
350         if ((!fgets(line, 256, f)) || strcmp(line, "transponders\n"))
351         {
352                 eDebug("services invalid, no transponders");
353                 fclose(f);
354                 return;
355         }
356
357         // clear all transponders
358
359         while (!feof(f))
360         {
361                 if (!fgets(line, 256, f))
362                         break;
363                 if (!strcmp(line, "end\n"))
364                         break;
365                 int dvb_namespace=-1, transport_stream_id=-1, original_network_id=-1;
366                 sscanf(line, "%x:%x:%x", &dvb_namespace, &transport_stream_id, &original_network_id);
367                 if (original_network_id == -1)
368                         continue;
369                 eDVBChannelID channelid = eDVBChannelID(
370                         eDVBNamespace(dvb_namespace),
371                         eTransportStreamID(transport_stream_id),
372                         eOriginalNetworkID(original_network_id));
373
374                 ePtr<eDVBFrontendParameters> feparm = new eDVBFrontendParameters;
375                 while (!feof(f))
376                 {
377                         fgets(line, 256, f);
378                         if (!strcmp(line, "/\n"))
379                                 break;
380                         if (line[1]=='s')
381                         {
382                                 eDVBFrontendParametersSatellite sat;
383                                 int frequency, symbol_rate, polarisation, fec, orbital_position, inversion,
384                                         flags=0,
385                                         system=eDVBFrontendParametersSatellite::System_DVB_S,
386                                         modulation=eDVBFrontendParametersSatellite::Modulation_QPSK,
387                                         rolloff=eDVBFrontendParametersSatellite::RollOff_alpha_0_35,
388                                         pilot=eDVBFrontendParametersSatellite::Pilot_Unknown;
389                                 if (version == 3)
390                                         sscanf(line+3, "%d:%d:%d:%d:%d:%d:%d:%d:%d:%d", &frequency, &symbol_rate, &polarisation, &fec, &orbital_position, &inversion, &system, &modulation, &rolloff, &pilot);
391                                 else
392                                         sscanf(line+3, "%d:%d:%d:%d:%d:%d:%d:%d:%d:%d:%d", &frequency, &symbol_rate, &polarisation, &fec, &orbital_position, &inversion, &flags, &system, &modulation, &rolloff, &pilot);
393                                 sat.frequency = frequency;
394                                 sat.symbol_rate = symbol_rate;
395                                 sat.polarisation = polarisation;
396                                 sat.fec = fec;
397                                 sat.orbital_position =
398                                         orbital_position < 0 ? orbital_position + 3600 : orbital_position;
399                                 sat.inversion = inversion;
400                                 sat.system = system;
401                                 sat.modulation = modulation;
402                                 sat.rolloff = rolloff;
403                                 sat.pilot = pilot;
404                                 feparm->setDVBS(sat);
405                                 feparm->setFlags(flags);
406                         } else if (line[1]=='t')
407                         {
408                                 eDVBFrontendParametersTerrestrial ter;
409                                 int frequency, bandwidth, code_rate_HP, code_rate_LP, modulation, transmission_mode, guard_interval, hierarchy, inversion, flags=0;
410                                 sscanf(line+3, "%d:%d:%d:%d:%d:%d:%d:%d:%d:%d", &frequency, &bandwidth, &code_rate_HP, &code_rate_LP, &modulation, &transmission_mode, &guard_interval, &hierarchy, &inversion, &flags);
411                                 ter.frequency = frequency;
412                                 ter.bandwidth = bandwidth;
413                                 ter.code_rate_HP = code_rate_HP;
414                                 ter.code_rate_LP = code_rate_LP;
415                                 ter.modulation = modulation;
416                                 ter.transmission_mode = transmission_mode;
417                                 ter.guard_interval = guard_interval;
418                                 ter.hierarchy = hierarchy;
419                                 ter.inversion = inversion;
420                                 feparm->setDVBT(ter);
421                                 feparm->setFlags(flags);
422                         } else if (line[1]=='c')
423                         {
424                                 eDVBFrontendParametersCable cab;
425                                 int frequency, symbol_rate,
426                                         inversion=eDVBFrontendParametersCable::Inversion_Unknown,
427                                         modulation=eDVBFrontendParametersCable::Modulation_Auto,
428                                         fec_inner=eDVBFrontendParametersCable::FEC_Auto,
429                                         flags=0;
430                                 sscanf(line+3, "%d:%d:%d:%d:%d:%d", &frequency, &symbol_rate, &inversion, &modulation, &fec_inner, &flags);
431                                 cab.frequency = frequency;
432                                 cab.fec_inner = fec_inner;
433                                 cab.inversion = inversion;
434                                 cab.symbol_rate = symbol_rate;
435                                 cab.modulation = modulation;
436                                 feparm->setDVBC(cab);
437                                 feparm->setFlags(flags);
438                         }
439                 }
440                 addChannelToList(channelid, feparm);
441         }
442
443         if ((!fgets(line, 256, f)) || strcmp(line, "services\n"))
444         {
445                 eDebug("services invalid, no services");
446                 return;
447         }
448
449         // clear all services
450
451         int count=0;
452
453         while (!feof(f))
454         {
455                 if (!fgets(line, 256, f))
456                         break;
457                 if (!strcmp(line, "end\n"))
458                         break;
459
460                 int service_id=-1, dvb_namespace, transport_stream_id=-1, original_network_id=-1, service_type=-1, service_number=-1;
461                 sscanf(line, "%x:%x:%x:%x:%d:%d", &service_id, &dvb_namespace, &transport_stream_id, &original_network_id, &service_type, &service_number);
462                 if (service_number == -1)
463                         continue;
464                 ePtr<eDVBService> s = new eDVBService;
465                 eServiceReferenceDVB ref =
466                                                 eServiceReferenceDVB(
467                                                 eDVBNamespace(dvb_namespace),
468                                                 eTransportStreamID(transport_stream_id),
469                                                 eOriginalNetworkID(original_network_id),
470                                                 eServiceID(service_id),
471                                                 service_type);
472                 count++;
473                 fgets(line, 256, f);
474                 if (strlen(line))
475                         line[strlen(line)-1]=0;
476
477                 s->m_service_name = line;
478                 s->genSortName();
479
480                 fgets(line, 256, f);
481                 if (strlen(line))
482                         line[strlen(line)-1]=0;
483                 if (line[1]!=':')       // old ... (only service_provider)
484                         s->m_provider_name=line;
485                 else
486                         parseServiceData(s, line);
487                 addService(ref, s);
488         }
489
490         eDebug("loaded %d services", count);
491
492         fclose(f);
493 }
494
495 void eDVBDB::saveServicelist(const char *file)
496 {
497         eDebug("---- saving lame channel db");
498         FILE *f=fopen(file, "w");
499         int channels=0, services=0;
500         if (!f)
501                 eFatal("couldn't save lame channel db!");
502         fprintf(f, "eDVB services /4/\n");
503         fprintf(f, "transponders\n");
504         for (std::map<eDVBChannelID, channel>::const_iterator i(m_channels.begin());
505                         i != m_channels.end(); ++i)
506         {
507                 const eDVBChannelID &chid = i->first;
508                 const channel &ch = i->second;
509
510                 fprintf(f, "%08x:%04x:%04x\n", chid.dvbnamespace.get(),
511                                 chid.transport_stream_id.get(), chid.original_network_id.get());
512                 eDVBFrontendParametersSatellite sat;
513                 eDVBFrontendParametersTerrestrial ter;
514                 eDVBFrontendParametersCable cab;
515                 unsigned int flags;  // flagOnlyFree yet..
516                 ch.m_frontendParameters->getFlags(flags);
517                 if (!ch.m_frontendParameters->getDVBS(sat))
518                 {
519                         if (sat.system == eDVBFrontendParametersSatellite::System_DVB_S2)
520                         {
521                                 fprintf(f, "\ts %d:%d:%d:%d:%d:%d:%d:%d:%d:%d:%d\n",
522                                         sat.frequency, sat.symbol_rate,
523                                         sat.polarisation, sat.fec,
524                                         sat.orbital_position > 1800 ? sat.orbital_position - 3600 : sat.orbital_position,
525                                         sat.inversion,
526                                         flags,
527                                         sat.system,
528                                         sat.modulation,
529                                         sat.rolloff,
530                                         sat.pilot);
531                         }
532                         else
533                         {
534                                 fprintf(f, "\ts %d:%d:%d:%d:%d:%d:%d\n",
535                                         sat.frequency, sat.symbol_rate,
536                                         sat.polarisation, sat.fec,
537                                         sat.orbital_position > 1800 ? sat.orbital_position - 3600 : sat.orbital_position,
538                                         sat.inversion, flags);
539                         }
540                 }
541                 else if (!ch.m_frontendParameters->getDVBT(ter))
542                 {
543                         fprintf(f, "\tt %d:%d:%d:%d:%d:%d:%d:%d:%d:%d\n",
544                                 ter.frequency, ter.bandwidth, ter.code_rate_HP,
545                                 ter.code_rate_LP, ter.modulation, ter.transmission_mode,
546                                 ter.guard_interval, ter.hierarchy, ter.inversion, flags);
547                 }
548                 else if (!ch.m_frontendParameters->getDVBC(cab))
549                 {
550                         fprintf(f, "\tc %d:%d:%d:%d:%d:%d\n",
551                                 cab.frequency, cab.symbol_rate, cab.inversion, cab.modulation, cab.fec_inner, flags);
552                 }
553                 fprintf(f, "/\n");
554                 channels++;
555         }
556         fprintf(f, "end\nservices\n");
557
558         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i(m_services.begin());
559                 i != m_services.end(); ++i)
560         {
561                 const eServiceReferenceDVB &s = i->first;
562                 fprintf(f, "%04x:%08x:%04x:%04x:%d:%d\n",
563                                 s.getServiceID().get(), s.getDVBNamespace().get(),
564                                 s.getTransportStreamID().get(),s.getOriginalNetworkID().get(),
565                                 s.getServiceType(),
566                                 0);
567
568                 fprintf(f, "%s\n", i->second->m_service_name.c_str());
569
570                 fprintf(f, "p:%s", i->second->m_provider_name.c_str());
571
572                 // write cached pids
573                 for (int x=0; x < eDVBService::cacheMax; ++x)
574                 {
575                         int entry = i->second->getCacheEntry((eDVBService::cacheID)x);
576                         if (entry != -1)
577                                 fprintf(f, ",c:%02d%04x", x, entry);
578                 }
579
580                 // write cached ca pids
581                 for (CAID_LIST::const_iterator ca(i->second->m_ca.begin());
582                         ca != i->second->m_ca.end(); ++ca)
583                         fprintf(f, ",C:%04x", *ca);
584
585                 if (i->second->m_flags)
586                         fprintf(f, ",f:%x", i->second->m_flags);
587
588                 fprintf(f, "\n");
589                 services++;
590         }
591         fprintf(f, "end\nHave a lot of bugs!\n");
592         eDebug("saved %d channels and %d services!", channels, services);
593         fclose(f);
594 }
595
596 void eDVBDB::saveServicelist()
597 {
598         saveServicelist(eEnv::resolve("${sysconfdir}/enigma2/lamedb").c_str());
599 }
600
601 void eDVBDB::loadBouquet(const char *path)
602 {
603         std::string bouquet_name = path;
604         if (!bouquet_name.length())
605         {
606                 eDebug("Bouquet load failed.. no path given..");
607                 return;
608         }
609         size_t pos = bouquet_name.rfind('/');
610         if ( pos != std::string::npos )
611                 bouquet_name.erase(0, pos+1);
612         if (bouquet_name.empty())
613         {
614                 eDebug("Bouquet load failed.. no filename given..");
615                 return;
616         }
617         eBouquet &bouquet = m_bouquets[bouquet_name];
618         bouquet.m_filename = bouquet_name;
619         std::list<eServiceReference> &list = bouquet.m_services;
620         list.clear();
621
622         std::string p = eEnv::resolve("${sysconfdir}/enigma2/");
623         p+=path;
624         eDebug("loading bouquet... %s", p.c_str());
625         FILE *fp=fopen(p.c_str(), "rt");
626         int entries=0;
627         if (!fp)
628         {
629                 struct stat s;
630                 if ( !stat(path, &s) )
631                 {
632                         rename(path, p.c_str() );
633                         loadBouquet(path);
634                         return;
635                 }
636                 eDebug("failed to open.");
637                 if ( strstr(path, "bouquets.tv") )
638                 {
639                         eDebug("recreate bouquets.tv");
640                         bouquet.m_bouquet_name="Bouquets (TV)";
641                         bouquet.flushChanges();
642                 }
643                 else if ( strstr(path, "bouquets.radio") )
644                 {
645                         eDebug("recreate bouquets.radio");
646                         bouquet.m_bouquet_name="Bouquets (Radio)";
647                         bouquet.flushChanges();
648                 }
649                 return;
650         }
651         char line[256];
652         bool read_descr=false;
653         eServiceReference *e = NULL;
654         while (1)
655         {
656                 if (!fgets(line, 256, fp))
657                         break;
658                 line[strlen(line)-1]=0;
659                 if (strlen(line) && line[strlen(line)-1]=='\r')
660                         line[strlen(line)-1]=0;
661                 if (!line[0])
662                         break;
663                 if (line[0]=='#')
664                 {
665                         if (!strncmp(line, "#SERVICE", 8))
666                         {
667                                 int offs = line[8] == ':' ? 10 : 9;
668                                 eServiceReference tmp(line+offs);
669                                 if (tmp.type != eServiceReference::idDVB)
670                                 {
671                                         eDebug("only DVB Bouquets supported");
672                                         continue;
673                                 }
674                                 if ( tmp.flags&eServiceReference::canDescent )
675                                 {
676                                         size_t pos = tmp.path.rfind('/');
677                                         char buf[256];
678                                         std::string path = tmp.path;
679                                         if ( pos != std::string::npos )
680                                                 path.erase(0, pos+1);
681                                         if (path.empty())
682                                         {
683                                                 eDebug("Bouquet load failed.. no filename given..");
684                                                 continue;
685                                         }
686                                         pos = path.find("FROM BOUQUET ");
687                                         if (pos != std::string::npos)
688                                         {
689                                                 char endchr = path[pos+13];
690                                                 if (endchr != '"')
691                                                 {
692                                                         eDebug("ignore invalid bouquet '%s' (only \" are allowed)",
693                                                                 tmp.toString().c_str());
694                                                         continue;
695                                                 }
696                                                 char *beg = &path[pos+14];
697                                                 char *end = strchr(beg, endchr);
698                                                 path.assign(beg, end - beg);
699                                         }
700                                         else
701                                         {
702                                                 snprintf(buf, 256, "FROM BOUQUET \"%s\" ORDER BY bouquet", path.c_str());
703                                                 tmp.path = buf;
704                                         }
705                                         loadBouquet(path.c_str());
706                                 }
707                                 list.push_back(tmp);
708                                 e = &list.back();
709                                 read_descr=true;
710                                 ++entries;
711                         }
712                         else if (read_descr && !strncmp(line, "#DESCRIPTION", 12))
713                         {
714                                 int offs = line[12] == ':' ? 14 : 13;
715                                 e->name = line+offs;
716                                 read_descr=false;
717                         }
718                         else if (!strncmp(line, "#NAME ", 6))
719                                 bouquet.m_bouquet_name=line+6;
720                         continue;
721                 }
722         }
723         fclose(fp);
724         eDebug("%d entries in Bouquet %s", entries, bouquet_name.c_str());
725 }
726
727 void eDVBDB::reloadBouquets()
728 {
729         m_bouquets.clear();
730         loadBouquet("bouquets.tv");
731         loadBouquet("bouquets.radio");
732 // create default bouquets when missing
733         if ( m_bouquets.find("userbouquet.favourites.tv") == m_bouquets.end() )
734         {
735                 eBouquet &b = m_bouquets["userbouquet.favourites.tv"];
736                 b.m_filename = "userbouquet.favourites.tv";
737                 b.m_bouquet_name = "Favourites (TV)";
738                 b.flushChanges();
739                 eServiceReference ref;
740                 memset(ref.data, 0, sizeof(ref.data));
741                 ref.type=1;
742                 ref.flags=7;
743                 ref.data[0]=1;
744                 ref.path="FROM BOUQUET \"userbouquet.favourites.tv\" ORDER BY bouquet";
745                 eBouquet &parent = m_bouquets["bouquets.tv"];
746                 parent.m_services.push_back(ref);
747                 parent.flushChanges();
748         }
749         if ( m_bouquets.find("userbouquet.favourites.radio") == m_bouquets.end() )
750         {
751                 eBouquet &b = m_bouquets["userbouquet.favourites.radio"];
752                 b.m_filename = "userbouquet.favourites.radio";
753                 b.m_bouquet_name = "Favourites (Radio)";
754                 b.flushChanges();
755                 eServiceReference ref;
756                 memset(ref.data, 0, sizeof(ref.data));
757                 ref.type=1;
758                 ref.flags=7;
759                 ref.data[0]=2;
760                 ref.path="FROM BOUQUET \"userbouquet.favourites.radio\" ORDER BY bouquet";
761                 eBouquet &parent = m_bouquets["bouquets.radio"];
762                 parent.m_services.push_back(ref);
763                 parent.flushChanges();
764         }
765 }
766
767 eDVBDB *eDVBDB::instance;
768
769 using namespace xmlcc;
770
771 eDVBDB::eDVBDB()
772 {
773         instance = this;
774         reloadServicelist();
775 }
776
777 PyObject *eDVBDB::readSatellites(ePyObject sat_list, ePyObject sat_dict, ePyObject tp_dict)
778 {
779         if (!PyDict_Check(tp_dict)) {
780                 PyErr_SetString(PyExc_StandardError,
781                         "type error");
782                         eDebug("arg 2 is not a python dict");
783                 return NULL;
784         }
785         else if (!PyDict_Check(sat_dict))
786         {
787                 PyErr_SetString(PyExc_StandardError,
788                         "type error");
789                         eDebug("arg 1 is not a python dict");
790                 return NULL;
791         }
792         else if (!PyList_Check(sat_list))
793         {
794                 PyErr_SetString(PyExc_StandardError,
795                         "type error");
796                         eDebug("arg 0 is not a python list");
797                 return NULL;
798         }
799         XMLTree tree;
800         tree.setFilename("/etc/tuxbox/satellites.xml");
801         tree.read();
802         Element *root = tree.getRoot();
803         if (!root)
804         {
805                 eDebug("couldn't open /etc/tuxbox/satellites.xml!!");
806                 Py_INCREF(Py_False);
807                 return Py_False;
808         }
809         int tmp, *dest = NULL,
810                 modulation, system, freq, sr, pol, fec, inv, pilot, rolloff, tsid, onid;
811         char *end_ptr;
812         const Attribute *at;
813         std::string name;
814         const ElementList &root_elements = root->getElementList();
815         for (ElementConstIterator it(root_elements.begin()); it != root_elements.end(); ++it)
816         {
817 //              eDebug("element: %s", (*it)->name().c_str());
818                 const Element *el = *it;
819                 const ElementList &sat_elements = el->getElementList();
820                 const AttributeList &sat_attributes = el->getAttributeList();
821                 ePyObject sat_name;
822                 ePyObject sat_pos;
823                 ePyObject sat_flags;
824                 for (AttributeConstIterator it(sat_attributes.begin()); it != sat_attributes.end(); ++it)
825                 {
826 //                      eDebug("\tattr: %s", at->name().c_str());
827                         at = *it;
828                         name = at->name();
829                         if (name == "name")
830                                 sat_name = PyString_FromString(at->value().c_str());
831                         else if (name == "flags")
832                         {
833                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
834                                 if (!*end_ptr)
835                                         sat_flags = PyInt_FromLong(tmp);
836                         }
837                         else if (name == "position")
838                         {
839                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
840                                 if (!*end_ptr)
841                                 {
842                                         if (tmp < 0)
843                                                 tmp = 3600 + tmp;
844                                         sat_pos = PyInt_FromLong(tmp);
845                                 }
846                         }
847                 }
848                 if (sat_pos && sat_name)
849                 {
850                         ePyObject tplist = PyList_New(0);
851                         ePyObject tuple = PyTuple_New(3);
852                         if (!sat_flags)
853                                 sat_flags = PyInt_FromLong(0);
854                         PyTuple_SET_ITEM(tuple, 0, sat_pos);
855                         PyTuple_SET_ITEM(tuple, 1, sat_name);
856                         PyTuple_SET_ITEM(tuple, 2, sat_flags);
857                         PyList_Append(sat_list, tuple);
858                         Py_DECREF(tuple);
859                         PyDict_SetItem(sat_dict, sat_pos, sat_name);
860                         PyDict_SetItem(tp_dict, sat_pos, tplist);
861                         for (ElementConstIterator it(sat_elements.begin()); it != sat_elements.end(); ++it)
862                         {
863                                 //eDebug("\telement: %s", (*it)->name().c_str());
864                                 const AttributeList &tp_attributes = (*it)->getAttributeList();
865                                 AttributeConstIterator end = tp_attributes.end();
866                                 modulation = eDVBFrontendParametersSatellite::Modulation_QPSK;
867                                 system = eDVBFrontendParametersSatellite::System_DVB_S;
868                                 freq = 0;
869                                 sr = 0;
870                                 pol = -1;
871                                 fec = eDVBFrontendParametersSatellite::FEC_Auto;
872                                 inv = eDVBFrontendParametersSatellite::Inversion_Unknown;
873                                 pilot = eDVBFrontendParametersSatellite::Pilot_Unknown;
874                                 rolloff = eDVBFrontendParametersSatellite::RollOff_alpha_0_35;
875                                 tsid = -1;
876                                 onid = -1;
877
878                                 for (AttributeConstIterator it(tp_attributes.begin()); it != end; ++it)
879                                 {
880                                         at = *it;
881                                         //eDebug("\t\tattr: %s", at->name().c_str());
882                                         name = at->name();
883                                         if (name == "modulation") dest = &modulation;
884                                         else if (name == "system") dest = &system;
885                                         else if (name == "frequency") dest = &freq;
886                                         else if (name == "symbol_rate") dest = &sr;
887                                         else if (name == "polarization") dest = &pol;
888                                         else if (name == "fec_inner") dest = &fec;
889                                         else if (name == "inversion") dest = &inv;
890                                         else if (name == "rolloff") dest = &rolloff;
891                                         else if (name == "pilot") dest = &pilot;
892                                         else if (name == "tsid") dest = &tsid;
893                                         else if (name == "onid") dest = &onid;
894                                         else continue;
895                                         if (dest)
896                                         {
897                                                 //eDebug("\t\t\tvalue: %s", at->value().c_str());
898                                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
899                                                 if (!*end_ptr)
900                                                         *dest = tmp;
901                                         }
902                                 }
903                                 if (freq && sr && pol != -1)
904                                 {
905                                         tuple = PyTuple_New(12);
906                                         PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(0));
907                                         PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(freq));
908                                         PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(sr));
909                                         PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(pol));
910                                         PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong(fec));
911                                         PyTuple_SET_ITEM(tuple, 5, PyInt_FromLong(system));
912                                         PyTuple_SET_ITEM(tuple, 6, PyInt_FromLong(modulation));
913                                         PyTuple_SET_ITEM(tuple, 7, PyInt_FromLong(inv));
914                                         PyTuple_SET_ITEM(tuple, 8, PyInt_FromLong(rolloff));
915                                         PyTuple_SET_ITEM(tuple, 9, PyInt_FromLong(pilot));
916                                         PyTuple_SET_ITEM(tuple, 10, PyInt_FromLong(tsid));
917                                         PyTuple_SET_ITEM(tuple, 11, PyInt_FromLong(onid));
918                                         PyList_Append(tplist, tuple);
919                                         Py_DECREF(tuple);
920                                 }
921                         }
922                         Py_DECREF(tplist);
923                 }
924                 else
925                 {
926                         if (sat_pos)
927                                 Py_DECREF(sat_pos);
928                         if (sat_name)
929                                 Py_DECREF(sat_name);
930                         if (sat_flags)
931                                 Py_DECREF(sat_flags);
932                 }
933         }
934         Py_INCREF(Py_True);
935         return Py_True;
936 }
937
938 PyObject *eDVBDB::readCables(ePyObject cab_list, ePyObject tp_dict)
939 {
940         if (!PyDict_Check(tp_dict)) {
941                 PyErr_SetString(PyExc_StandardError,
942                         "type error");
943                         eDebug("arg 1 is not a python dict");
944                 return NULL;
945         }
946         else if (!PyList_Check(cab_list))
947         {
948                 PyErr_SetString(PyExc_StandardError,
949                         "type error");
950                         eDebug("arg 0 is not a python list");
951                 return NULL;
952         }
953         XMLTree tree;
954         tree.setFilename("/etc/tuxbox/cables.xml");
955         tree.read();
956         Element *root = tree.getRoot();
957         if (!root)
958         {
959                 eDebug("couldn't open /etc/tuxbox/cables.xml!!");
960                 Py_INCREF(Py_False);
961                 return Py_False;
962         }
963         const Attribute *at;
964         int tmp, *dest,
965                 modulation, fec, freq, sr;
966         std::string name;
967         char *end_ptr;
968         const ElementList &root_elements = root->getElementList();
969         for (ElementConstIterator it(root_elements.begin()); it != root_elements.end(); ++it)
970         {
971 //              eDebug("element: %s", el->name().c_str());
972                 const Element *el = *it;
973                 const ElementList &cab_elements = el->getElementList();
974                 const AttributeList &cab_attributes = el->getAttributeList();
975                 ePyObject cab_name;
976                 ePyObject cab_flags;
977                 for (AttributeConstIterator it(cab_attributes.begin()); it != cab_attributes.end(); ++it)
978                 {
979 //                      eDebug("\tattr: %s", at->name().c_str());
980                         at = *it;
981                         name = at->name();
982                         if (name == "name")
983                                 cab_name = PyString_FromString(at->value().c_str());
984                         else if (name == "flags")
985                         {
986                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
987                                 if (!*end_ptr)
988                                         cab_flags = PyInt_FromLong(tmp);
989                         }
990                 }
991                 if (cab_name)
992                 {
993                         ePyObject tplist = PyList_New(0);
994                         ePyObject tuple = PyTuple_New(2);
995                         if (!cab_flags)
996                                 cab_flags = PyInt_FromLong(0);
997                         PyTuple_SET_ITEM(tuple, 0, cab_name);
998                         PyTuple_SET_ITEM(tuple, 1, cab_flags);
999                         PyList_Append(cab_list, tuple);
1000                         Py_DECREF(tuple);
1001                         PyDict_SetItem(tp_dict, cab_name, tplist);
1002                         for (ElementConstIterator it(cab_elements.begin()); it != cab_elements.end(); ++it)
1003                         {
1004 //                              eDebug("\telement: %s", (*it)->name().c_str());
1005                                 const AttributeList &tp_attributes = (*it)->getAttributeList();
1006                                 AttributeConstIterator end = tp_attributes.end();
1007                                 modulation = eDVBFrontendParametersCable::Modulation_QAM64;
1008                                 fec = eDVBFrontendParametersCable::FEC_Auto;
1009                                 freq = 0;
1010                                 sr = 0;
1011                                 for (AttributeConstIterator it(tp_attributes.begin()); it != end; ++it)
1012                                 {
1013 //                                      eDebug("\t\tattr: %s", at->name().c_str());
1014                                         at = *it;
1015                                         dest = 0;
1016                                         name = at->name();
1017                                         if (name == "modulation") dest = &modulation;
1018                                         else if (name == "frequency") dest = &freq;
1019                                         else if (name == "symbol_rate") dest = &sr;
1020                                         else if (name == "fec_inner") dest = &fec;
1021                                         else continue;
1022                                         if (dest)
1023                                         {
1024                                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
1025                                                 if (!*end_ptr)
1026                                                         *dest = tmp;
1027                                         }
1028                                 }
1029                                 if (freq && sr)
1030                                 {
1031                                         while (freq > 999999)
1032                                                 freq /= 10;
1033                                         tuple = PyTuple_New(5);
1034                                         PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(1));
1035                                         PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(freq));
1036                                         PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(sr));
1037                                         PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(modulation));
1038                                         PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong(fec));
1039                                         PyList_Append(tplist, tuple);
1040                                         Py_DECREF(tuple);
1041                                 }
1042                         }
1043                         Py_DECREF(tplist);
1044                 }
1045                 else if (cab_flags)
1046                         Py_DECREF(cab_flags);
1047         }
1048         Py_INCREF(Py_True);
1049         return Py_True;
1050 }
1051
1052 PyObject *eDVBDB::readTerrestrials(ePyObject ter_list, ePyObject tp_dict)
1053 {
1054         if (!PyDict_Check(tp_dict)) {
1055                 PyErr_SetString(PyExc_StandardError,
1056                         "type error");
1057                         eDebug("arg 1 is not a python dict");
1058                 return NULL;
1059         }
1060         else if (!PyList_Check(ter_list))
1061         {
1062                 PyErr_SetString(PyExc_StandardError,
1063                         "type error");
1064                         eDebug("arg 0 is not a python list");
1065                 return NULL;
1066         }
1067         XMLTree tree;
1068         tree.setFilename("/etc/tuxbox/terrestrial.xml");
1069         tree.read();
1070         Element *root = tree.getRoot();
1071         if (!root)
1072         {
1073                 eDebug("couldn't open /etc/tuxbox/terrestrial.xml!!");
1074                 Py_INCREF(Py_False);
1075                 return Py_False;
1076         }
1077         const Attribute *at;
1078         std::string name;
1079         int tmp, *dest,
1080                 freq, bw, constellation, crh = 5, crl = 5, guard = 4, transm, hierarchy, inv = 2;
1081         char *end_ptr;
1082         const ElementList &root_elements = root->getElementList();
1083         for (ElementConstIterator it(root_elements.begin()); it != root_elements.end(); ++it)
1084         {
1085 //              eDebug("element: %s", el->name().c_str());
1086                 const Element *el = *it;
1087                 const ElementList &ter_elements = el->getElementList();
1088                 const AttributeList &ter_attributes = el->getAttributeList();
1089                 ePyObject ter_name;
1090                 ePyObject ter_flags;
1091                 for (AttributeConstIterator it(ter_attributes.begin()); it != ter_attributes.end(); ++it)
1092                 {
1093 //                      eDebug("\tattr: %s", at->name().c_str());
1094                         at = *it;
1095                         name = at->name();
1096                         if (name == "name")
1097                                 ter_name = PyString_FromString(at->value().c_str());
1098                         else if (name == "flags")
1099                         {
1100                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
1101                                 if (!*end_ptr)
1102                                         ter_flags = PyInt_FromLong(tmp);
1103                         }
1104                 }
1105                 if (ter_name)
1106                 {
1107                         ePyObject tplist = PyList_New(0);
1108                         ePyObject tuple = PyTuple_New(2);
1109                         if (!ter_flags)
1110                                 ter_flags = PyInt_FromLong(0);
1111                         PyTuple_SET_ITEM(tuple, 0, ter_name);
1112                         PyTuple_SET_ITEM(tuple, 1, ter_flags);
1113                         PyList_Append(ter_list, tuple);
1114                         Py_DECREF(tuple);
1115                         PyDict_SetItem(tp_dict, ter_name, tplist);
1116                         for (ElementConstIterator it(ter_elements.begin()); it != ter_elements.end(); ++it)
1117                         {
1118 //                              eDebug("\telement: %s", (*it)->name().c_str());
1119                                 const AttributeList &tp_attributes = (*it)->getAttributeList();
1120                                 AttributeConstIterator end = tp_attributes.end();
1121                                 freq = 0;
1122                                 bw = eDVBFrontendParametersTerrestrial::Bandwidth_Auto;
1123                                 constellation = eDVBFrontendParametersTerrestrial::Modulation_Auto;
1124                                 crh = eDVBFrontendParametersTerrestrial::FEC_Auto;
1125                                 crl = eDVBFrontendParametersTerrestrial::FEC_Auto;
1126                                 guard = eDVBFrontendParametersTerrestrial::GuardInterval_Auto;
1127                                 transm = eDVBFrontendParametersTerrestrial::TransmissionMode_Auto;
1128                                 hierarchy = eDVBFrontendParametersTerrestrial::Hierarchy_Auto;
1129                                 inv = eDVBFrontendParametersTerrestrial::Inversion_Unknown;
1130                                 for (AttributeConstIterator it(tp_attributes.begin()); it != end; ++it)
1131                                 {
1132 //                                      eDebug("\t\tattr: %s", at->name().c_str());
1133                                         at = *it;
1134                                         dest = 0;
1135                                         name = at->name();
1136                                         if (name == "centre_frequency") dest = &freq;
1137                                         else if (name == "bandwidth") dest = &bw;
1138                                         else if (name == "constellation") dest = &constellation;
1139                                         else if (name == "code_rate_hp") dest = &crh;
1140                                         else if (name == "code_rate_lp") dest = &crl;
1141                                         else if (name == "guard_interval") dest = &guard;
1142                                         else if (name == "transmission_mode") dest = &transm;
1143                                         else if (name == "hierarchy_information") dest = &hierarchy;
1144                                         else if (name == "inversion") dest = &inv;
1145                                         else continue;
1146                                         if (dest)
1147                                         {
1148                                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
1149                                                 if (!*end_ptr)
1150                                                         *dest = tmp;
1151                                         }
1152                                 }
1153                                 if (freq)
1154                                 {
1155                                         if (crh > 5) // our terrestrial.xml is buggy... 6 for AUTO
1156                                                 crh = 5;
1157                                         if (crl > 5) // our terrestrial.xml is buggy... 6 for AUTO
1158                                                 crl = 5;
1159                                         tuple = PyTuple_New(10);
1160                                         PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(2));
1161                                         PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(freq));
1162                                         PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(bw));
1163                                         PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(constellation));
1164                                         PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong(crh));
1165                                         PyTuple_SET_ITEM(tuple, 5, PyInt_FromLong(crl));
1166                                         PyTuple_SET_ITEM(tuple, 6, PyInt_FromLong(guard));
1167                                         PyTuple_SET_ITEM(tuple, 7, PyInt_FromLong(transm));
1168                                         PyTuple_SET_ITEM(tuple, 8, PyInt_FromLong(hierarchy));
1169                                         PyTuple_SET_ITEM(tuple, 9, PyInt_FromLong(inv));
1170                                         PyList_Append(tplist, tuple);
1171                                         Py_DECREF(tuple);
1172                                 }
1173                         }
1174                         Py_DECREF(tplist);
1175                 }
1176                 else if (ter_flags)
1177                         Py_DECREF(ter_flags);
1178         }
1179         Py_INCREF(Py_True);
1180         return Py_True;
1181 }
1182
1183 eDVBDB::~eDVBDB()
1184 {
1185         instance=NULL;
1186 }
1187
1188 RESULT eDVBDB::removeService(const eServiceReference &ref)
1189 {
1190         if (ref.type == eServiceReference::idDVB)
1191         {
1192                 eServiceReferenceDVB &service = (eServiceReferenceDVB&)ref;
1193                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(service));
1194                 if (it != m_services.end())
1195                 {
1196                         m_services.erase(it);
1197                         return 0;
1198                 }
1199         }
1200         return -1;
1201 }
1202
1203 RESULT eDVBDB::removeServices(int dvb_namespace, int tsid, int onid, unsigned int orb_pos)
1204 {
1205         return removeServices(eDVBChannelID(eDVBNamespace(dvb_namespace), eTransportStreamID(tsid), eOriginalNetworkID(onid)), orb_pos);
1206 }
1207
1208 RESULT eDVBDB::removeServices(eDVBChannelID chid, unsigned int orbpos)
1209 {
1210         RESULT ret=-1;
1211         eDVBNamespace eNs;
1212         eTransportStreamID eTsid;
1213         eOriginalNetworkID eOnid;
1214         std::map<eDVBChannelID, channel>::iterator it(m_channels.begin());
1215         std::set<eDVBChannelID> removed_chids;
1216         while (it != m_channels.end())
1217         {
1218                 const eDVBChannelID &ch = it->first;
1219                 bool remove=true;
1220                 int system;
1221                 it->second.m_frontendParameters->getSystem(system);
1222                 if ( system == iDVBFrontend::feSatellite )
1223                 {
1224                         eDVBFrontendParametersSatellite sat;
1225                         it->second.m_frontendParameters->getDVBS(sat);
1226                         if ((unsigned int)sat.orbital_position != orbpos)
1227                                 remove=false;
1228                 }
1229                 if ( remove && chid.dvbnamespace != eNs ) // namespace given?
1230                 {
1231                         if ( system == iDVBFrontend::feCable && chid.dvbnamespace.get() == (int)0xFFFF0000 )
1232                                 ;
1233                         else if ( system == iDVBFrontend::feTerrestrial && chid.dvbnamespace.get() == (int)0xEEEE0000 )
1234                                 ;
1235                         else if ( chid.dvbnamespace != ch.dvbnamespace )
1236                                 remove=false;
1237                 }
1238                 else if ( system == iDVBFrontend::feCable || system == iDVBFrontend::feTerrestrial )
1239                         remove=false;
1240                 if ( remove && chid.original_network_id != eOnid && chid.original_network_id != ch.original_network_id )
1241                         remove=false;
1242                 if ( remove && chid.transport_stream_id != eTsid && chid.transport_stream_id != ch.transport_stream_id )
1243                         remove=false;
1244                 if ( remove )
1245                 {
1246                         eDebug("remove %08x %04x %04x",
1247                                 ch.dvbnamespace.get(),
1248                                 ch.original_network_id.get(),
1249                                 ch.transport_stream_id.get());
1250                         removed_chids.insert(it->first);
1251                         m_channels.erase(it++);
1252                 }
1253                 else
1254                         ++it;
1255         }
1256         if (!removed_chids.empty())
1257         {
1258                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator service(m_services.begin());
1259                 while(service != m_services.end())
1260                 {
1261                         eDVBChannelID chid;
1262                         service->first.getChannelID(chid);
1263                         std::set<eDVBChannelID>::iterator it(removed_chids.find(chid));
1264                         if (it != removed_chids.end())
1265                                 m_services.erase(service++);
1266                         else
1267                                 ++service;
1268                         ret=0;
1269                 }
1270         }
1271         return ret;
1272 }
1273
1274 RESULT eDVBDB::removeServices(iDVBFrontendParameters *feparm)
1275 {
1276         int ret = -1;
1277         std::set<eDVBChannelID> removed_chids;
1278         std::map<eDVBChannelID, channel>::iterator it(m_channels.begin());
1279         while (it != m_channels.end())
1280         {
1281                 int diff;
1282                 if (!feparm->calculateDifference(&(*it->second.m_frontendParameters), diff, false))
1283                 {
1284                         if (diff < 4000)
1285                         {
1286                                 removed_chids.insert(it->first);
1287                                 m_channels.erase(it++);
1288                         }
1289                         else
1290                                 ++it;
1291                 }
1292                 else
1293                         ++it;
1294         }
1295         if (!removed_chids.empty())
1296         {
1297                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator service(m_services.begin());
1298                 while(service != m_services.end())
1299                 {
1300                         eDVBChannelID chid;
1301                         service->first.getChannelID(chid);
1302                         std::set<eDVBChannelID>::iterator it(removed_chids.find(chid));
1303                         if (it != removed_chids.end())
1304                                 m_services.erase(service++);
1305                         else
1306                                 ++service;
1307                 }
1308                 ret = 0;
1309         }
1310         return ret;
1311 }
1312
1313 RESULT eDVBDB::addFlag(const eServiceReference &ref, unsigned int flagmask)
1314 {
1315         if (ref.type == eServiceReference::idDVB)
1316         {
1317                 eServiceReferenceDVB &service = (eServiceReferenceDVB&)ref;
1318                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(service));
1319                 if (it != m_services.end())
1320                         it->second->m_flags |= ~flagmask;
1321                 return 0;
1322         }
1323         return -1;
1324 }
1325
1326 RESULT eDVBDB::removeFlag(const eServiceReference &ref, unsigned int flagmask)
1327 {
1328         if (ref.type == eServiceReference::idDVB)
1329         {
1330                 eServiceReferenceDVB &service = (eServiceReferenceDVB&)ref;
1331                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(service));
1332                 if (it != m_services.end())
1333                         it->second->m_flags &= ~flagmask;
1334                 return 0;
1335         }
1336         return -1;
1337 }
1338
1339 RESULT eDVBDB::removeFlags(unsigned int flagmask, int dvb_namespace, int tsid, int onid, unsigned int orb_pos)
1340 {
1341         return removeFlags(flagmask, eDVBChannelID(eDVBNamespace(dvb_namespace), eTransportStreamID(tsid), eOriginalNetworkID(onid)), orb_pos);
1342 }
1343
1344 RESULT eDVBDB::removeFlags(unsigned int flagmask, eDVBChannelID chid, unsigned int orbpos)
1345 {
1346         eDVBNamespace eNs;
1347         eTransportStreamID eTsid;
1348         eOriginalNetworkID eOnid;
1349         std::map<eDVBChannelID, channel>::iterator it(m_channels.begin());
1350         std::set<eDVBChannelID> removed_chids;
1351         while (it != m_channels.end())
1352         {
1353                 const eDVBChannelID &ch = it->first;
1354                 bool remove=true;
1355                 int system;
1356                 it->second.m_frontendParameters->getSystem(system);
1357                 if ( orbpos != 0xFFFFFFFF && system == iDVBFrontend::feSatellite )
1358                 {
1359                         eDVBFrontendParametersSatellite sat;
1360                         it->second.m_frontendParameters->getDVBS(sat);
1361                         if ((unsigned int)sat.orbital_position != orbpos)
1362                                 remove=false;
1363                 }
1364                 if ( remove && chid.dvbnamespace != eNs )
1365                 {
1366                         if (system == iDVBFrontend::feCable && chid.dvbnamespace.get() == (int)0xFFFF0000)
1367                                 ;
1368                         else if (system == iDVBFrontend::feTerrestrial && chid.dvbnamespace.get() == (int)0xEEEE0000)
1369                                 ;
1370                         else if ( chid.dvbnamespace != ch.dvbnamespace )
1371                                 remove=false;
1372                 }
1373                 if ( remove && chid.original_network_id != eOnid && chid.original_network_id != ch.original_network_id )
1374                         remove=false;
1375                 if ( remove && chid.transport_stream_id != eTsid && chid.transport_stream_id != ch.transport_stream_id )
1376                         remove=false;
1377                 if ( remove )
1378                         removed_chids.insert(it->first);
1379                 ++it;
1380         }
1381         if (!removed_chids.empty())
1382         {
1383                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator service(m_services.begin());
1384                 while(service != m_services.end())
1385                 {
1386                         eDVBChannelID chid;
1387                         service->first.getChannelID(chid);
1388                         std::set<eDVBChannelID>::iterator it(removed_chids.find(chid));
1389                         if (it != removed_chids.end())
1390                                 service->second->m_flags &= ~flagmask;
1391                         ++service;
1392                 }
1393         }
1394         return 0;
1395 }
1396
1397 RESULT eDVBDB::addChannelToList(const eDVBChannelID &id, iDVBFrontendParameters *feparm)
1398 {
1399         channel ch;
1400         std::map<eDVBChannelID, channel>::iterator it = m_channels.find(id);
1401         ASSERT(feparm);
1402         ch.m_frontendParameters = feparm;
1403         if (it != m_channels.end())
1404                 it->second = ch;
1405         else
1406                 m_channels.insert(std::pair<eDVBChannelID, channel>(id, ch));
1407         return 0;
1408 }
1409
1410 RESULT eDVBDB::removeChannel(const eDVBChannelID &id)
1411 {
1412         m_channels.erase(id);
1413         return 0;
1414 }
1415
1416 RESULT eDVBDB::getChannelFrontendData(const eDVBChannelID &id, ePtr<iDVBFrontendParameters> &parm)
1417 {
1418         std::map<eDVBChannelID, channel>::iterator i = m_channels.find(id);
1419         if (i == m_channels.end())
1420         {
1421                 parm = 0;
1422                 return -ENOENT;
1423         }
1424         parm = i->second.m_frontendParameters;
1425         return 0;
1426 }
1427
1428 RESULT eDVBDB::addService(const eServiceReferenceDVB &serviceref, eDVBService *service)
1429 {
1430         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(serviceref));
1431         if (it == m_services.end())
1432                 m_services.insert(std::pair<eServiceReferenceDVB, ePtr<eDVBService> >(serviceref, service));
1433         return 0;
1434 }
1435
1436 RESULT eDVBDB::getService(const eServiceReferenceDVB &reference, ePtr<eDVBService> &service)
1437 {
1438         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i;
1439         i = m_services.find(reference);
1440         if (i == m_services.end())
1441         {
1442                 service = 0;
1443                 return -ENOENT;
1444         }
1445         service = i->second;
1446         return 0;
1447 }
1448
1449 RESULT eDVBDB::flush()
1450 {
1451         saveServicelist();
1452         return 0;
1453 }
1454
1455 RESULT eDVBDB::getBouquet(const eServiceReference &ref, eBouquet* &bouquet)
1456 {
1457         std::string str = ref.path;
1458         if (str.empty())
1459         {
1460                 eDebug("getBouquet failed.. no path given!");
1461                 return -1;
1462         }
1463         size_t pos = str.find("FROM BOUQUET \"");
1464         if ( pos != std::string::npos )
1465         {
1466                 str.erase(0, pos+14);
1467                 pos = str.find('"');
1468                 if ( pos != std::string::npos )
1469                         str.erase(pos);
1470                 else
1471                         str.clear();
1472         }
1473         if (str.empty())
1474         {
1475                 eDebug("getBouquet failed.. couldn't parse bouquet name");
1476                 return -1;
1477         }
1478         std::map<std::string, eBouquet>::iterator i =
1479                 m_bouquets.find(str);
1480         if (i == m_bouquets.end())
1481         {
1482                 bouquet = 0;
1483                 return -ENOENT;
1484         }
1485         bouquet = &i->second;
1486         return 0;
1487 }
1488
1489 RESULT eDVBDB::startQuery(ePtr<iDVBChannelListQuery> &query, eDVBChannelQuery *q, const eServiceReference &source)
1490 {
1491         if ( source.path.find("FROM") != std::string::npos )
1492         {
1493                 if ( source.path.find("BOUQUET") != std::string::npos )
1494                         query = new eDVBDBBouquetQuery(this, source, q);
1495                 else if ( source.path.find("SATELLITES") != std::string::npos )
1496                         query = new eDVBDBSatellitesQuery(this, source, q);
1497                 else if ( source.path.find("PROVIDERS") != std::string::npos )
1498                         query = new eDVBDBProvidersQuery(this, source, q);
1499                 else
1500                         eFatal("invalid query %s", source.toString().c_str());
1501         }
1502         else
1503                 query = new eDVBDBQuery(this, source, q);
1504         return 0;
1505 }
1506
1507 eServiceReference eDVBDB::searchReference(int tsid, int onid, int sid)
1508 {
1509         eServiceID Sid(sid);
1510         eTransportStreamID Tsid(tsid);
1511         eOriginalNetworkID Onid(onid);
1512         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator sit(m_services.begin());
1513                 sit != m_services.end(); ++sit)
1514         {
1515                 if (sit->first.getTransportStreamID() == Tsid &&
1516                         sit->first.getOriginalNetworkID() == Onid &&
1517                         sit->first.getServiceID() == Sid)
1518                         return sit->first;
1519         }
1520         return eServiceReference();
1521 }
1522
1523 DEFINE_REF(eDVBDBQueryBase);
1524
1525 eDVBDBQueryBase::eDVBDBQueryBase(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1526         :m_db(db), m_query(query), m_source(source)
1527 {
1528 }
1529
1530 int eDVBDBQueryBase::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
1531 {
1532         ePtr<eDVBService> a_service, b_service;
1533         int sortmode = m_query ? m_query->m_sort : eDVBChannelQuery::tName;
1534
1535         if ((sortmode == eDVBChannelQuery::tName) || (sortmode == eDVBChannelQuery::tProvider))
1536         {
1537                 if (a.name.empty() && m_db->getService(a, a_service))
1538                         return 1;
1539                 if (b.name.empty() && m_db->getService(b, b_service))
1540                         return 1;
1541         }
1542
1543         switch (sortmode)
1544         {
1545         case eDVBChannelQuery::tName:
1546                 if (a_service)
1547                 {
1548                         if (b_service)
1549                                 return a_service->m_service_name_sort < b_service->m_service_name_sort;
1550                         else
1551                         {
1552                                 std::string str = b.name;
1553                                 makeUpper(str);
1554                                 return a_service->m_service_name_sort < str;
1555                         }
1556                 }
1557                 else if (b_service)
1558                 {
1559                         std::string str = a.name;
1560                         makeUpper(str);
1561                         return str < b_service->m_service_name_sort;
1562                 }
1563                 else
1564                 {
1565                         std::string aa = a.name, bb = b.name;
1566                         makeUpper(aa);
1567                         makeUpper(bb);
1568                         return aa < bb;
1569                 }
1570         case eDVBChannelQuery::tProvider:
1571                 return a_service->m_provider_name < b_service->m_provider_name;
1572         case eDVBChannelQuery::tType:
1573                 return a.getServiceType() < b.getServiceType();
1574         case eDVBChannelQuery::tBouquet:
1575                 return 0;
1576         case eDVBChannelQuery::tSatellitePosition:
1577                 return (a.getDVBNamespace().get() >> 16) < (b.getDVBNamespace().get() >> 16);
1578         default:
1579                 return 1;
1580         }
1581         return 0;
1582 }
1583
1584 eDVBDBQuery::eDVBDBQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1585         :eDVBDBQueryBase(db, source, query)
1586 {
1587         m_cursor = m_db->m_services.begin();
1588 }
1589
1590 RESULT eDVBDBQuery::getNextResult(eServiceReferenceDVB &ref)
1591 {
1592         while (m_cursor != m_db->m_services.end())
1593         {
1594                 ePtr<eDVBService> service = m_cursor->second;
1595                 if (service->isHidden())
1596                         ++m_cursor;
1597                 else
1598                 {
1599                         ref = m_cursor->first;
1600
1601                         int res = (!m_query) || service->checkFilter(ref, *m_query);
1602
1603                         ++m_cursor;
1604
1605                         if (res)
1606                                 return 0;
1607                 }
1608         }
1609
1610         ref.type = eServiceReference::idInvalid;
1611
1612         return 1;
1613 }
1614
1615 eDVBDBBouquetQuery::eDVBDBBouquetQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1616         :eDVBDBQueryBase(db, source, query), m_cursor(db->m_bouquets[query->m_bouquet_name].m_services.begin())
1617 {
1618 }
1619
1620 RESULT eDVBDBBouquetQuery::getNextResult(eServiceReferenceDVB &ref)
1621 {
1622         eBouquet &bouquet = m_db->m_bouquets[m_query->m_bouquet_name];
1623         std::list<eServiceReference> &list = bouquet.m_services;
1624         while (m_cursor != list.end())
1625         {
1626                 ref = *((eServiceReferenceDVB*)&(*m_cursor));
1627
1628                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it =
1629                         m_db->m_services.find(ref);
1630
1631                 int res = (!m_query) || it == m_db->m_services.end() || !(it->second->isHidden() && it->second->checkFilter(ref, *m_query));
1632
1633                 ++m_cursor;
1634
1635                 if (res)
1636                         return 0;
1637         }
1638
1639         ref.type = eServiceReference::idInvalid;
1640
1641         return 1;
1642 }
1643
1644 eDVBDBListQuery::eDVBDBListQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1645         :eDVBDBQueryBase(db, source, query), m_cursor(m_list.end())
1646 {
1647 }
1648
1649 RESULT eDVBDBListQuery::getNextResult(eServiceReferenceDVB &ref)
1650 {
1651         if (m_cursor != m_list.end())
1652         {
1653                 ref = *m_cursor++;
1654                 return 0;
1655         }
1656         ref.type = eServiceReference::idInvalid;
1657         return 1;
1658 }
1659
1660 int eDVBDBListQuery::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
1661 {
1662         if ( m_query->m_sort == eDVBChannelQuery::tSatellitePosition )
1663         {
1664                 int x = (a.getDVBNamespace().get() >> 16);
1665                 int y = (b.getDVBNamespace().get() >> 16);
1666                 if ( x > 1800 )
1667                         x -= 3600;
1668                 if ( y > 1800 )
1669                         y -= 3600;
1670                 return x < y;
1671         }
1672         std::string aa = a.name, bb = b.name;
1673         makeUpper(aa);
1674         makeUpper(bb);
1675         return aa < bb;
1676 }
1677
1678 eDVBDBSatellitesQuery::eDVBDBSatellitesQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1679         :eDVBDBListQuery(db, source, query)
1680 {
1681         std::set<unsigned int> found;
1682         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
1683                 it != m_db->m_services.end(); ++it)
1684         {
1685                 int res = !it->second->isHidden() && it->second->checkFilter(it->first, *query);
1686                 if (res)
1687                 {
1688                         unsigned int dvbnamespace = it->first.getDVBNamespace().get()&0xFFFF0000;
1689                         if (found.find(dvbnamespace) == found.end())
1690                         {
1691                                 found.insert(dvbnamespace);
1692                                 eServiceReferenceDVB ref;
1693                                 ref.setDVBNamespace(dvbnamespace);
1694                                 ref.flags=eServiceReference::flagDirectory;
1695                                 char buf[128];
1696                                 snprintf(buf, 128, "(satellitePosition == %d) && ", dvbnamespace>>16);
1697
1698                                 ref.path=buf+source.path;
1699                                 unsigned int pos=ref.path.find("FROM");
1700                                 ref.path.erase(pos);
1701                                 ref.path+="ORDER BY name";
1702 //                              eDebug("ref.path now %s", ref.path.c_str());
1703                                 m_list.push_back(ref);
1704
1705                                 ref.path=buf+source.path;
1706                                 pos=ref.path.find("FROM");
1707                                 ref.path.erase(pos+5);
1708                                 ref.path+="PROVIDERS ORDER BY name";
1709 //                              eDebug("ref.path now %s", ref.path.c_str());
1710                                 m_list.push_back(ref);
1711
1712                                 snprintf(buf, 128, "(satellitePosition == %d) && (flags == %d) && ", dvbnamespace>>16, eDVBService::dxNewFound);
1713                                 ref.path=buf+source.path;
1714                                 pos=ref.path.find("FROM");
1715                                 ref.path.erase(pos);
1716                                 ref.path+="ORDER BY name";
1717 //                              eDebug("ref.path now %s", ref.path.c_str());
1718                                 m_list.push_back(ref);
1719                         }
1720                 }
1721         }
1722         m_cursor=m_list.begin();
1723 }
1724
1725 eDVBDBProvidersQuery::eDVBDBProvidersQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1726         :eDVBDBListQuery(db, source, query)
1727 {
1728         std::set<std::string> found;
1729         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
1730                 it != m_db->m_services.end(); ++it)
1731         {
1732                 int res = !it->second->isHidden() && it->second->checkFilter(it->first, *query);
1733                 if (res)
1734                 {
1735                         const char *provider_name = it->second->m_provider_name.length() ?
1736                                 it->second->m_provider_name.c_str() :
1737                                 "Unknown";
1738                         if (found.find(std::string(provider_name)) == found.end())
1739                         {
1740                                 found.insert(std::string(provider_name));
1741                                 eServiceReferenceDVB ref;
1742                                 char buf[64];
1743                                 ref.name=provider_name;
1744                                 snprintf(buf, 64, "(provider == \"%s\") && ", provider_name);
1745                                 ref.path=buf+source.path;
1746                                 unsigned int pos = ref.path.find("FROM");
1747                                 ref.flags=eServiceReference::flagDirectory;
1748                                 ref.path.erase(pos);
1749                                 ref.path+="ORDER BY name";
1750 //                              eDebug("ref.path now %s", ref.path.c_str());
1751                                 m_list.push_back(ref);
1752                         }
1753                 }
1754         }
1755         m_cursor=m_list.begin();
1756 }
1757
1758 /* (<name|provider|type|bouquet|satpos|chid> <==|...> <"string"|int>)[||,&& (..)] */
1759
1760 static int decodeType(const std::string &type)
1761 {
1762         if (type == "name")
1763                 return eDVBChannelQuery::tName;
1764         else if (type == "provider")
1765                 return eDVBChannelQuery::tProvider;
1766         else if (type == "type")
1767                 return eDVBChannelQuery::tType;
1768         else if (type == "bouquet")
1769                 return eDVBChannelQuery::tBouquet;
1770         else if (type == "satellitePosition")
1771                 return eDVBChannelQuery::tSatellitePosition;
1772         else if (type == "channelID")
1773                 return eDVBChannelQuery::tChannelID;
1774         else if (type == "flags")
1775                 return eDVBChannelQuery::tFlags;
1776         else
1777                 return -1;
1778 }
1779
1780         /* never, NEVER write a parser in C++! */
1781 RESULT parseExpression(ePtr<eDVBChannelQuery> &res, std::list<std::string>::const_iterator begin, std::list<std::string>::const_iterator end)
1782 {
1783         std::list<std::string>::const_iterator end_of_exp;
1784
1785         if (begin == end)
1786                 return 0;
1787
1788         if (*begin == "(")
1789         {
1790                 end_of_exp = begin;
1791                 while (end_of_exp != end)
1792                         if (*end_of_exp == ")")
1793                                 break;
1794                         else
1795                                 ++end_of_exp;
1796
1797                 if (end_of_exp == end)
1798                 {
1799                         eDebug("expression parse: end of expression while searching for closing brace");
1800                         return -1;
1801                 }
1802
1803                 ++begin;
1804                 // begin..end_of_exp
1805                 int r = parseExpression(res, begin, end_of_exp);
1806                 if (r)
1807                         return r;
1808                 ++end_of_exp;
1809
1810                         /* we had only one sub expression */
1811                 if (end_of_exp == end)
1812                 {
1813 //                      eDebug("only one sub expression");
1814                         return 0;
1815                 }
1816
1817                         /* otherwise we have an operator here.. */
1818
1819                 ePtr<eDVBChannelQuery> r2 = res;
1820                 res = new eDVBChannelQuery();
1821                 res->m_sort = 0;
1822                 res->m_p1 = r2;
1823                 res->m_inverse = 0;
1824                 r2 = 0;
1825
1826                 if (*end_of_exp == "||")
1827                         res->m_type = eDVBChannelQuery::tOR;
1828                 else if (*end_of_exp == "&&")
1829                         res->m_type = eDVBChannelQuery::tAND;
1830                 else
1831                 {
1832                         eDebug("found operator %s, but only && and || are allowed!", end_of_exp->c_str());
1833                         res = 0;
1834                         return 1;
1835                 }
1836
1837                 ++end_of_exp;
1838
1839                 return parseExpression(res->m_p2, end_of_exp, end);
1840         }
1841
1842         // "begin" <op> "end"
1843         std::string type, op, val;
1844
1845         res = new eDVBChannelQuery();
1846         res->m_sort = 0;
1847
1848         int cnt = 0;
1849         while (begin != end)
1850         {
1851                 switch (cnt)
1852                 {
1853                 case 0:
1854                         type = *begin;
1855                         break;
1856                 case 1:
1857                         op = *begin;
1858                         break;
1859                 case 2:
1860                         val = *begin;
1861                         break;
1862                 case 3:
1863                         eDebug("malformed query: got '%s', but expected only <type> <op> <val>", begin->c_str());
1864                         return 1;
1865                 }
1866                 ++begin;
1867                 ++cnt;
1868         }
1869
1870         if (cnt != 3)
1871         {
1872                 eDebug("malformed query: missing stuff");
1873                 res = 0;
1874                 return 1;
1875         }
1876
1877         res->m_type = decodeType(type);
1878
1879         if (res->m_type == -1)
1880         {
1881                 eDebug("malformed query: invalid type %s", type.c_str());
1882                 res = 0;
1883                 return 1;
1884         }
1885
1886         if (op == "==")
1887                 res->m_inverse = 0;
1888         else if (op == "!=")
1889                 res->m_inverse = 1;
1890         else
1891         {
1892                 eDebug("invalid operator %s", op.c_str());
1893                 res = 0;
1894                 return 1;
1895         }
1896
1897         res->m_string = val;
1898
1899         if (res->m_type == eDVBChannelQuery::tChannelID)
1900         {
1901                 int ns, tsid, onid;
1902                 if (sscanf(val.c_str(), "%08x%04x%04x", &ns, &tsid, &onid) == 3)
1903                         res->m_channelid = eDVBChannelID(eDVBNamespace(ns), eTransportStreamID(tsid), eOriginalNetworkID(onid));
1904                 else
1905                         eDebug("couldn't parse channelid !! format should be hex NNNNNNNNTTTTOOOO (namespace, tsid, onid)");
1906         }
1907         else
1908                 res->m_int = atoi(val.c_str());
1909
1910         return 0;
1911 }
1912
1913 RESULT eDVBChannelQuery::compile(ePtr<eDVBChannelQuery> &res, std::string query)
1914 {
1915         std::list<std::string> tokens;
1916
1917         std::string current_token;
1918         std::string bouquet_name;
1919
1920 //      eDebug("splitting %s....", query.c_str());
1921         unsigned int i = 0;
1922         const char *splitchars="()";
1923         int quotemode = 0, lastsplit = 0, lastalnum = 0;
1924         while (i <= query.size())
1925         {
1926                 int c = (i < query.size()) ? query[i] : ' ';
1927                 ++i;
1928
1929                 int issplit = !!strchr(splitchars, c);
1930                 int isaln = isalnum(c);
1931                 int iswhite = c == ' ';
1932                 int isquot = c == '\"';
1933
1934                 if (quotemode)
1935                 {
1936                         iswhite = issplit = 0;
1937                         isaln = lastalnum;
1938                 }
1939
1940                 if (issplit || iswhite || isquot || lastsplit || (lastalnum != isaln))
1941                 {
1942                         if (current_token.size())
1943                                 tokens.push_back(current_token);
1944                         current_token.clear();
1945                 }
1946
1947                 if (!(iswhite || isquot))
1948                         current_token += c;
1949
1950                 if (isquot)
1951                         quotemode = !quotemode;
1952                 lastsplit = issplit;
1953                 lastalnum = isaln;
1954         }
1955
1956 //      for (std::list<std::string>::const_iterator a(tokens.begin()); a != tokens.end(); ++a)
1957 //      {
1958 //              printf("%s\n", a->c_str());
1959 //      }
1960
1961         int sort = eDVBChannelQuery::tName;
1962                 /* check for "ORDER BY ..." */
1963
1964         std::list<std::string>::iterator it = tokens.begin();
1965         while (it != tokens.end())
1966         {
1967                 if (*it == "ORDER")
1968                 {
1969                         tokens.erase(it++);
1970                         if (it != tokens.end() && *it == "BY")
1971                         {
1972                                 tokens.erase(it++);
1973                                 sort = decodeType(*it);
1974                                 tokens.erase(it++);
1975                         } else
1976                                 sort = -1;
1977                 }
1978                 else if (*it == "FROM")
1979                 {
1980                         tokens.erase(it++);
1981                         if (it != tokens.end() && *it == "BOUQUET")
1982                         {
1983                                 tokens.erase(it++);
1984                                 bouquet_name = *it;
1985                                 tokens.erase(it++);
1986                         }
1987                         else if (it != tokens.end() && *it == "SATELLITES")
1988                                 tokens.erase(it++);
1989                         else if (it != tokens.end() && *it == "PROVIDERS")
1990                                 tokens.erase(it++);
1991                         else
1992                         {
1993                                 eDebug("FROM unknown %s", (*it).c_str());
1994                                 tokens.erase(it++);
1995                         }
1996                 }
1997                 else
1998                         ++it;
1999         }
2000
2001         if (sort == -1)
2002         {
2003                 eWarning("ORDER BY .. string invalid.");
2004                 res = 0;
2005                 return -1;
2006         }
2007
2008 //      eDebug("sort by %d", sort);
2009
2010                 /* now we recursivly parse that. */
2011         int r = parseExpression(res, tokens.begin(), tokens.end());
2012
2013                 /* we have an empty (but valid!) expression */
2014         if (!r && !res)
2015         {
2016                 res = new eDVBChannelQuery();
2017                 res->m_inverse = 0;
2018                 res->m_type = eDVBChannelQuery::tAny;
2019         }
2020
2021         if (res)
2022         {
2023                 res->m_sort = sort;
2024                 res->m_bouquet_name = bouquet_name;
2025         }
2026
2027 //      eDebug("return: %d", r);
2028         return r;
2029 }
2030
2031 DEFINE_REF(eDVBChannelQuery);