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