- add more DVB-T support
[enigma2.git] / lib / dvb / db.cpp
1 #include <errno.h>
2 #include <lib/dvb/db.h>
3 #include <lib/dvb/frontend.h>
4 #include <lib/base/eerror.h>
5 #include <lib/base/estring.h>
6 #include <lib/dvb_si/sdt.h>
7 #include <lib/dvb_si/descriptor_tag.h>
8 #include <lib/dvb_si/service_descriptor.h>
9 #include <lib/dvb_si/satellite_delivery_system_descriptor.h>
10
11 DEFINE_REF(eDVBService);
12
13 eDVBService::eDVBService()
14 {
15 }
16
17 eDVBService::~eDVBService()
18 {
19 }
20
21 eDVBService &eDVBService::operator=(const eDVBService &s)
22 {
23         m_service_name = s.m_service_name;
24         m_provider_name = s.m_provider_name;
25         m_flags = s.m_flags;
26         m_ca = s.m_ca;
27         m_cache = s.m_cache;
28         return *this;
29 }
30
31 RESULT eDVBService::getName(const eServiceReference &ref, std::string &name)
32 {
33         name = convertDVBUTF8(m_service_name);
34         return 0;
35 }
36
37 int eDVBService::getLength(const eServiceReference &ref)
38 {
39         return -1;
40 }
41
42 int eDVBService::checkFilter(const eServiceReferenceDVB &ref, const eDVBChannelQuery &query)
43 {
44         int res = 0;
45         switch (query.m_type)
46         {
47         case eDVBChannelQuery::tName:
48                 res = m_service_name.find(query.m_string) != std::string::npos;
49                 break;
50         case eDVBChannelQuery::tProvider:
51                 res = m_provider_name.find(query.m_string) != std::string::npos;
52                 break;
53         case eDVBChannelQuery::tType:
54                 res = ref.getServiceType() == query.m_int;
55                 break;
56         case eDVBChannelQuery::tBouquet:
57                 res = 0;
58                 break;
59         case eDVBChannelQuery::tSatellitePosition:
60                 res = (ref.getDVBNamespace().get() >> 16) == query.m_int;
61                 break;
62         case eDVBChannelQuery::tChannelID:
63         {
64                 eDVBChannelID chid;
65                 ref.getChannelID(chid);
66                 res = chid == query.m_channelid;
67                 break;
68         }
69         case eDVBChannelQuery::tAND:
70                 res = checkFilter(ref, *query.m_p1) && checkFilter(ref, *query.m_p2);
71                 break;
72         case eDVBChannelQuery::tOR:
73                 res = checkFilter(ref, *query.m_p1) || checkFilter(ref, *query.m_p2);
74                 break;
75         }
76
77         if (query.m_inverse)
78                 return !res;
79         else
80                 return res;
81 }
82
83 int eDVBService::getCachePID(cacheID id)
84 {
85         std::map<int, int>::iterator it = m_cache.find(id);
86         if ( it != m_cache.end() )
87                 return it->second;
88         return -1;
89 }
90
91 void eDVBService::setCachePID(cacheID id, int pid)
92 {
93         m_cache[id] = pid;
94 }
95
96 DEFINE_REF(eDVBDB);
97
98         /* THIS CODE IS BAD. it should be replaced by somethine better. */
99 void eDVBDB::load()
100 {
101         eDebug("---- opening lame channel db");
102         FILE *f=fopen("lamedb", "rt");
103         if (!f)
104                 return;
105         char line[256];
106         if ((!fgets(line, 256, f)) || strncmp(line, "eDVB services", 13))
107         {
108                 eDebug("not a servicefile");
109                 fclose(f);
110                 return;
111         }
112         eDebug("reading services");
113         if ((!fgets(line, 256, f)) || strcmp(line, "transponders\n"))
114         {
115                 eDebug("services invalid, no transponders");
116                 fclose(f);
117                 return;
118         }
119
120         // clear all transponders
121
122         while (!feof(f))
123         {
124                 if (!fgets(line, 256, f))
125                         break;
126                 if (!strcmp(line, "end\n"))
127                         break;
128                 int dvb_namespace=-1, transport_stream_id=-1, original_network_id=-1;
129                 sscanf(line, "%x:%x:%x", &dvb_namespace, &transport_stream_id, &original_network_id);
130                 if (original_network_id == -1)
131                         continue;
132                 eDVBChannelID channelid = eDVBChannelID(
133                         eDVBNamespace(dvb_namespace),
134                         eTransportStreamID(transport_stream_id),
135                         eOriginalNetworkID(original_network_id));
136
137                 ePtr<eDVBFrontendParameters> feparm = new eDVBFrontendParameters;
138                 while (!feof(f))
139                 {
140                         fgets(line, 256, f);
141                         if (!strcmp(line, "/\n"))
142                                 break;
143                         if (line[1]=='s')
144                         {
145                                 eDVBFrontendParametersSatellite sat;
146                                 int frequency, symbol_rate, polarisation, fec, orbital_position, inversion;
147                                 sscanf(line+2, "%d:%d:%d:%d:%d:%d", &frequency, &symbol_rate, &polarisation, &fec, &inversion, &orbital_position);
148                                 sat.frequency = frequency;
149                                 sat.symbol_rate = symbol_rate;
150                                 sat.polarisation = polarisation;
151                                 sat.fec = fec;
152                                 sat.orbital_position = orbital_position;
153                                 sat.inversion = inversion;
154                                 // ...
155 //                              t.setSatellite(frequency, symbol_rate, polarisation, fec, sat, inversion);
156                                 feparm->setDVBS(sat);
157                         } else if (line[1]=='t')
158                         {
159                                 eDVBFrontendParametersTerrestrial ter;
160                                 int frequency, bandwidth, code_rate_HP, code_rate_LP, modulation, transmission_mode, guard_interval, hierarchy, inversion;
161                                 sscanf(line+2, "%d:%d:%d:%d:%d:%d:%d:%d:%d", &frequency, &bandwidth, &code_rate_HP, &code_rate_LP, &modulation, &transmission_mode, &guard_interval, &hierarchy, &inversion);
162                                 ter.frequency = frequency;
163                                 ter.bandwidth = bandwidth;
164                                 ter.code_rate_HP = code_rate_HP;
165                                 ter.code_rate_LP = code_rate_LP;
166                                 ter.modulation = modulation;
167                                 ter.transmission_mode = transmission_mode;
168                                 ter.guard_interval = guard_interval;
169                                 ter.hierarchy = hierarchy;
170                                 ter.inversion = inversion;
171                                 
172                                 feparm->setDVBT(ter);
173                         } else if (line[1]=='c')
174                         {
175                                 int frequency, symbol_rate, inversion=0, modulation=3;
176                                 sscanf(line+2, "%d:%d:%d:%d", &frequency, &symbol_rate, &inversion, &modulation);
177 //                              t.setCable(frequency, symbol_rate, inversion, modulation);
178                         }
179                 }
180                 addChannelToList(channelid, feparm);
181         }
182
183         if ((!fgets(line, 256, f)) || strcmp(line, "services\n"))
184         {
185                 eDebug("services invalid, no services");
186                 return;
187         }
188
189         // clear all services
190
191         int count=0;
192
193         while (!feof(f))
194         {
195                 if (!fgets(line, 256, f))
196                         break;
197                 if (!strcmp(line, "end\n"))
198                         break;
199
200                 int service_id=-1, dvb_namespace, transport_stream_id=-1, original_network_id=-1, service_type=-1, service_number=-1;
201                 sscanf(line, "%x:%x:%x:%x:%d:%d", &service_id, &dvb_namespace, &transport_stream_id, &original_network_id, &service_type, &service_number);
202                 if (service_number == -1)
203                         continue;
204                 ePtr<eDVBService> s = new eDVBService;
205                 eServiceReferenceDVB ref =
206                                                 eServiceReferenceDVB(
207                                                 eDVBNamespace(dvb_namespace),
208                                                 eTransportStreamID(transport_stream_id),
209                                                 eOriginalNetworkID(original_network_id),
210                                                 eServiceID(service_id),
211                                                 service_type);
212                 count++;
213                 fgets(line, 256, f);
214                 if (strlen(line))
215                         line[strlen(line)-1]=0;
216                 s->m_service_name=line;
217                 fgets(line, 256, f);
218                 if (strlen(line))
219                         line[strlen(line)-1]=0;
220
221                 std::string str=line;
222
223                 if (str[1]!=':')        // old ... (only service_provider)
224                 {
225                         s->m_provider_name=line;
226                 } else
227                         while ((!str.empty()) && str[1]==':') // new: p:, f:, c:%02d...
228                         {
229                                 unsigned int c=str.find(',');
230                                 char p=str[0];
231                                 std::string v;
232                                 if (c == std::string::npos)
233                                 {
234                                         v=str.substr(2);
235                                         str="";
236                                 } else
237                                 {
238                                         v=str.substr(2, c-2);
239                                         str=str.substr(c+1);
240                                 }
241 //                              eDebug("%c ... %s", p, v.c_str());
242                                 if (p == 'p')
243                                         s->m_provider_name=v;
244                                 else if (p == 'f')
245                                 {
246                                         sscanf(v.c_str(), "%x", &s->m_flags);
247                                 } else if (p == 'c')
248                                 {
249                                         int cid, val;
250                                         sscanf(v.c_str(), "%02d%04x", &cid, &val);
251                                         s->m_cache[cid]=val;
252                                 } else if (p == 'C')
253                                 {
254                                         int val;
255                                         sscanf(v.c_str(), "%04x", &val);
256                                         s->m_ca.insert(val);
257                                 }
258                         }
259                 addService(ref, s);
260         }
261
262         eDebug("loaded %d services", count);
263
264         fclose(f);
265 }
266
267 void eDVBDB::save()
268 {
269         eDebug("---- saving lame channel db");
270         FILE *f=fopen("lamedb", "wt");
271         int channels=0, services=0;
272         if (!f)
273                 eFatal("couldn't save lame channel db!");
274         fprintf(f, "eDVB services /3/\n");
275         fprintf(f, "transponders\n");
276         for (std::map<eDVBChannelID, channel>::const_iterator i(m_channels.begin());
277                         i != m_channels.end(); ++i)
278         {
279                 const eDVBChannelID &chid = i->first;
280                 const channel &ch = i->second;
281
282                 fprintf(f, "%08x:%04x:%04x\n", chid.dvbnamespace.get(),
283                                 chid.transport_stream_id.get(), chid.original_network_id.get());
284                 eDVBFrontendParametersSatellite sat;
285                 eDVBFrontendParametersTerrestrial ter;
286                 if (!ch.m_frontendParameters->getDVBS(sat))
287                 {
288                         fprintf(f, "\ts %d:%d:%d:%d:%d:%d\n",
289                                 sat.frequency, sat.symbol_rate,
290                                 sat.polarisation, sat.fec, sat.inversion,
291                                 sat.orbital_position);
292                 }
293                 if (!ch.m_frontendParameters->getDVBT(ter))
294                 {
295                         fprintf(f, "\tt %d:%d:%d:%d:%d:%d:%d:%d:%d\n",
296                                 ter.frequency, ter.bandwidth, ter.code_rate_HP,
297                                 ter.code_rate_LP, ter.modulation, ter.transmission_mode,
298                                 ter.guard_interval, ter.hierarchy, ter.inversion);
299                 }
300                 fprintf(f, "/\n");
301                 channels++;
302         }
303         fprintf(f, "end\nservices\n");
304
305         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i(m_services.begin());
306                 i != m_services.end(); ++i)
307         {
308                 const eServiceReferenceDVB &s = i->first;
309                 fprintf(f, "%04x:%08x:%04x:%04x:%d:%d\n",
310                                 s.getServiceID().get(), s.getDVBNamespace().get(),
311                                 s.getTransportStreamID().get(),s.getOriginalNetworkID().get(),
312                                 s.getServiceType(),
313                                 0);
314
315                 fprintf(f, "%s\n", i->second->m_service_name.c_str());
316                 fprintf(f, "p:%s", i->second->m_provider_name.c_str());
317
318                 // write cached pids
319                 for (std::map<int,int>::const_iterator ca(i->second->m_cache.begin());
320                         ca != i->second->m_cache.end(); ++ca)
321                         fprintf(f, ",c:%02d%04x", ca->first, ca->second);
322
323                 // write cached ca pids
324                 for (std::set<int>::const_iterator ca(i->second->m_ca.begin());
325                         ca != i->second->m_ca.end(); ++ca)
326                         fprintf(f, ",C:%04x", *ca);
327
328                 fprintf(f, "\n");
329                 services++;
330         }
331         fprintf(f, "end\nHave a lot of bugs!\n");
332         eDebug("saved %d channels and %d services!", channels, services);
333         fclose(f);
334 }
335
336 eDVBDB::eDVBDB()
337 {
338         load();
339 }
340
341 eDVBDB::~eDVBDB()
342 {
343 //      save();
344 }
345
346 RESULT eDVBDB::addChannelToList(const eDVBChannelID &id, iDVBFrontendParameters *feparm)
347 {
348         channel ch;
349         assert(feparm);
350         ch.m_frontendParameters = feparm;
351         m_channels.insert(std::pair<eDVBChannelID, channel>(id, ch));
352         return 0;
353 }
354
355 RESULT eDVBDB::removeChannel(const eDVBChannelID &id)
356 {
357         m_channels.erase(id);
358         return 0;
359 }
360
361 RESULT eDVBDB::getChannelFrontendData(const eDVBChannelID &id, ePtr<iDVBFrontendParameters> &parm)
362 {
363         std::map<eDVBChannelID, channel>::iterator i = m_channels.find(id);
364         if (i == m_channels.end())
365         {
366                 parm = 0;
367                 return -ENOENT;
368         }
369         parm = i->second.m_frontendParameters;
370         return 0;
371 }
372
373 RESULT eDVBDB::addService(const eServiceReferenceDVB &serviceref, eDVBService *service)
374 {
375         m_services.insert(std::pair<eServiceReferenceDVB, ePtr<eDVBService> >(serviceref, service));
376         return 0;
377 }
378
379 RESULT eDVBDB::getService(const eServiceReferenceDVB &reference, ePtr<eDVBService> &service)
380 {
381         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i;
382         i = m_services.find(reference);
383         if (i == m_services.end())
384         {
385                 service = 0;
386                 return -ENOENT;
387         }
388         service = i->second;
389         return 0;
390 }
391
392 RESULT eDVBDB::startQuery(ePtr<iDVBChannelListQuery> &query, eDVBChannelQuery *q)
393 {
394         query = new eDVBDBQuery(this, eServiceReference(), q);
395         return 0;
396 }
397
398 DEFINE_REF(eDVBDBQuery);
399
400 eDVBDBQuery::eDVBDBQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query): m_db(db), m_query(query)
401 {
402                 // TODO: use SOURCE ...
403         m_cursor = m_db->m_services.begin();
404 }
405
406 RESULT eDVBDBQuery::getNextResult(eServiceReferenceDVB &ref)
407 {
408         while (m_cursor != m_db->m_services.end())
409         {
410                 ref = m_cursor->first;
411                 
412                 int res = (!m_query) || m_cursor->second->checkFilter(ref, *m_query);
413
414                 ++m_cursor;
415                 
416                 if (res)
417                         return 0;
418         }
419         return 1;
420 }
421
422 /* (<name|provider|type|bouquet|satpos|chid> <==|...> <"string"|int>)[AND (..)] */
423
424         /* never, NEVER write a parser in C++! */
425 RESULT parseExpression(ePtr<eDVBChannelQuery> &res, std::list<std::string>::const_iterator begin, std::list<std::string>::const_iterator end)
426 {
427         std::list<std::string>::const_iterator end_of_exp;
428         if (*begin == "(")
429         {
430                 end_of_exp = begin;
431                 while (end_of_exp != end)
432                         if (*end_of_exp == ")")
433                                 break;
434                         else
435                                 ++end_of_exp;
436         
437                 if (end_of_exp == end)
438                 {
439                         eDebug("expression parse: end of expression while searching for closing brace");
440                         return -1;
441                 }
442                 
443                 ++begin;
444                 // begin..end_of_exp
445                 int r = parseExpression(res, begin, end_of_exp);
446                 if (r)
447                         return r;
448                 ++end_of_exp;
449                 
450                         /* we had only one sub expression */
451                 if (end_of_exp == end)
452                         return 1;
453                 
454                         /* otherwise we have an operator here.. */
455                 
456                 ePtr<eDVBChannelQuery> r2 = res;
457                 res = new eDVBChannelQuery();
458                 res->m_p1 = r2;
459                 res->m_inverse = 0;
460                 r2 = 0;
461                 
462                 if (*end_of_exp == "||")
463                         res->m_type = eDVBChannelQuery::tOR;
464                 else if (*end_of_exp == "&&")
465                         res->m_type = eDVBChannelQuery::tAND;
466                 else
467                 {
468                         eDebug("found operator %s, but only && and || are allowed!", end_of_exp->c_str());
469                         res = 0;
470                         return 1;
471                 }
472                 
473                 ++end_of_exp;
474                 
475                 return parseExpression(res->m_p2, end_of_exp, end);
476         }
477         
478         // "begin" <op> "end"
479         std::string type, op, val;
480         
481         res = new eDVBChannelQuery();
482         
483         int cnt = 0;
484         while (begin != end)
485         {
486                 switch (cnt)
487                 {
488                 case 0:
489                         type = *begin;
490                         break;
491                 case 1:
492                         op = *begin;
493                         break;
494                 case 2:
495                         val = *begin;
496                         break;
497                 case 3:
498                         eDebug("malformed query: got '%s', but expected only <type> <op> <val>", begin->c_str());
499                         return 1;
500                 }
501                 ++begin;
502                 ++cnt;
503         }
504         
505         if (cnt != 3)
506         {
507                 eDebug("malformed query: missing stuff");
508                 res = 0;
509                 return 1;
510         }
511         
512         if (type == "name")
513                 res->m_type = eDVBChannelQuery::tName;
514         else if (type == "provider")
515                 res->m_type = eDVBChannelQuery::tProvider;
516         else if (type == "type")
517                 res->m_type = eDVBChannelQuery::tType;
518         else if (type == "bouquet")
519                 res->m_type = eDVBChannelQuery::tBouquet;
520         else if (type == "satellitePosition")
521                 res->m_type = eDVBChannelQuery::tSatellitePosition;
522         else if (type == "channelID")
523                 res->m_type = eDVBChannelQuery::tChannelID;
524         else
525         {
526                 eDebug("malformed query: invalid type %s", type.c_str());
527                 res = 0;
528                 return 1;
529         }
530         
531         eDebug("type is %d, nice!", res->m_type);
532         
533         if (op == "==")
534                 res->m_inverse = 0;
535         else if (op == "!=")
536                 res->m_inverse = 1;
537         else
538         {
539                 eDebug("invalid operator %s", op.c_str());
540                 res = 0;
541                 return 1;
542         }
543         
544         res->m_string = val;
545         res->m_int = atoi(val.c_str());
546 //      res->m_channelid = eDVBChannelID(val);
547         
548         return 0;
549 }
550
551 RESULT eDVBChannelQuery::compile(ePtr<eDVBChannelQuery> &res, std::string query)
552 {
553         std::list<std::string> tokens;
554         
555         std::string current_token;
556         
557 //      eDebug("splitting %s....", query.c_str());
558         unsigned int i = 0;
559         const char *splitchars="()";
560         int quotemode = 0, lastsplit = 0, lastalnum = 0;
561         while (i <= query.size())
562         {
563                 int c = (i < query.size()) ? query[i] : ' ';
564                 ++i;
565                 
566                 int issplit = !!strchr(splitchars, c);
567                 int isaln = isalnum(c);
568                 int iswhite = c == ' ';
569                 int isquot = c == '\"';
570                 
571                 if (quotemode)
572                 {
573                         iswhite = issplit = 0;
574                         isaln = lastalnum;
575                 }
576                 
577                 if (issplit || iswhite || isquot || lastsplit || (lastalnum != isaln))
578                 {
579                         if (current_token.size())
580                                 tokens.push_back(current_token);
581                         current_token.clear();
582                 }
583                 
584                 if (!(iswhite || isquot))
585                         current_token += c;
586                 
587                 if (isquot)
588                         quotemode = !quotemode;
589                 lastsplit = issplit;
590                 lastalnum = isaln;
591         }
592         
593 //      for (std::list<std::string>::const_iterator a(tokens.begin()); a != tokens.end(); ++a)
594 //      {
595 //              printf("%s\n", a->c_str());
596 //      }
597         
598                 /* now we recursivly parse that. */
599         return  parseExpression(res, tokens.begin(), tokens.end());
600 /*      
601         res = new eDVBChannelQuery();
602         res->m_type = eDVBChannelQuery::tName;
603         res->m_inverse = 0;
604         res->m_string = query;
605         return 0; */
606 }
607
608 DEFINE_REF(eDVBChannelQuery);