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