]> git.vomp.tv Git - vompclient.git/blob - vdr.cc
Windows fixes
[vompclient.git] / vdr.cc
1 /*
2     Copyright 2004-2020 Chris Tallon
3
4     This file is part of VOMP.
5
6     VOMP is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     VOMP is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with VOMP.  If not, see <https://www.gnu.org/licenses/>.
18 */
19
20 #include <climits>
21
22 #include "recman.h"
23 #include "recinfo.h"
24 #include "channel.h"
25 #include "event.h"
26 #include "wol.h"
27 #include "vdrrequestpacket.h"
28 #include "vdrresponsepacket.h"
29 #include "command.h"
30 #ifdef VOMP_MEDIAPLAYER
31 #include "media.h"
32 #include "mediaprovider.h"
33 #include "mediaproviderids.h"
34 #endif
35 #include "vdrcommand.h"
36 #include "video.h"
37 #include "osd.h"
38 #include "movieinfo.h"
39 #include "seriesinfo.h"
40 #include "osdvector.h"
41 #include "tvmedia.h"
42
43 #include "vdr.h"
44
45 #define VOMP_PROTOCOL_VERSION 0x00000500
46
47 VDR* VDR::instance = NULL;
48 #ifdef VOMP_MEDIAPLAYER
49 //prepare a request
50 //will create a request package from a command variable and fill this
51 //caller has to destroy buffer
52 static SerializeBuffer * prepareRequest(VDR_Command *cmd) {
53   SerializeBuffer *buf=new SerializeBuffer(512,false,true);
54   if (cmd->serialize(buf) != 0) {
55     delete buf;
56     return NULL;
57   }
58   return buf;
59 }
60
61 //handle request/response
62 //TODO avoid copy of buffer (needs extension of requestpacket)
63 //TODO avoid command 2x (needs some more restructuring)
64 SerializeBuffer * VDR::doRequestResponse(SerializeBuffer *rq,int cmd) {
65   VDR_RequestPacket *rt=new VDR_RequestPacket;
66   if (! rt) {
67     delete rq;
68     return NULL;
69   }
70   if (! rt->init(cmd,true,rq->getCurrent()-rq->getStart())) {
71     delete rq;
72     delete rt;
73     return NULL;
74   }
75   if (! rt->copyin(rq->getStart(),(ULONG)(rq->getCurrent()-rq->getStart()))) {
76     delete rq;
77     delete rt;
78     return NULL;
79   }
80   delete rq;
81   VDR_ResponsePacket *rp=RequestResponse(rt);
82   logger->log("doRequestResponse",Log::DEBUG,"got response %p",rp);
83   if ( !rp) {
84     delete rt;
85     return NULL;
86   }
87   SerializeBuffer *buf=new SerializeBuffer(rp->getUserData(),rp->getUserDataLength(),true,true,false);
88   delete rp;
89   return buf;
90 }
91
92 //deserialize a received response
93 //delete the package
94 //return !=0 on error
95 static int decodeResponse(SerializeBuffer *rp,VDR_Command *c) {
96   ULONG expected=c->command;
97   if (c->deserialize(rp) != 0) {
98     delete rp;
99     Log::getInstance()->log("VDR", Log::ERR, "decodeResponse unable to deserialize for command %lu",expected);
100     return -1;
101   }
102   delete rp;
103   if (c->command != expected) {
104    Log::getInstance()->log("VDR", Log::ERR, "decodeResponse unexpected response received 0x%lx, expected 0x%lx",c->command,expected);
105     return -1;
106   }
107   Log::getInstance()->log("VDR", Log::DEBUG, "decodeResponse successfully decoded command 0x%lx",expected);
108   return 0;
109 }
110
111 #endif
112
113 VDR::VDR()
114 {
115   if (instance) return;
116   instance = this;
117
118   TEMP_SINGLE_VDR_PR = NULL; // FIXME what is this
119 #ifdef VOMP_MEDIAPLAYER
120   providerId=MPROVIDERID_VDR;
121   subRange=MPROVIDERRANGE_VDR;
122   MediaPlayerRegister::getInstance()->registerMediaProvider(this,MPROVIDERID_VDR,MPROVIDERRANGE_VDR);
123 #endif
124 }
125
126 VDR::~VDR()
127 {
128   instance = NULL;
129   if (initted) shutdown();
130 }
131
132 VDR* VDR::getInstance()
133 {
134   return instance;
135 }
136
137 int VDR::init()
138 {
139   if (initted) return 0;
140   initted = 1;
141   logger = Log::getInstance();
142   tcp.init();
143   return 1;
144 }
145
146 int VDR::shutdown()
147 {
148   if (!initted) return 0;
149   initted = 0;
150   disconnect();
151   return 1;
152 }
153
154 void VDR::setServerIP(const char* newIP)
155 {
156   strcpy(serverIP, newIP);
157 }
158
159 void VDR::setServerPort(USHORT newPort)
160 {
161   serverPort = newPort;
162 }
163
164 int VDR::connect()
165 {
166   maxChannelNumber = 0;
167   channelNumberWidth = 1;
168
169   tcp.shutdown();
170   if (!tcp.connect(serverIP, serverPort)) return 0;
171
172   connected = true;
173
174   threadStartProtect.lock();
175   vdrThread = std::thread( [this]
176   {
177     threadStartProtect.lock();
178     threadStartProtect.unlock();
179     threadMethod();
180   });
181   threadStartProtect.unlock();
182
183   return 1;
184 }
185
186 void VDR::disconnect()
187 {
188   logger->log("VDR", Log::DEBUG, "Disconnect start");
189
190   if (vdrThread.joinable())
191   {
192     threadReqStop = true;
193     tcp.abortCall();
194     vdrThread.join();
195     threadReqStop = false;
196     logger->log("VDR", Log::DEBUG, "done thread stop");
197   }
198
199   connected = false;
200   logger->log("VDR", Log::DEBUG, "Disconnect");
201 }
202
203 void VDR::setReceiveWindow(size_t size)
204 {
205   //if (connected && size) tcpold->setReceiveWindow(size);
206 }
207
208 ///////////////////////////////////////////////////////
209
210 void VDR::threadMethod()
211 {
212   logger->log("VDR", Log::DEBUG, "VDR RUN");  
213
214   ULONG channelID;
215   
216   ULONG requestID;
217   ULONG userDataLength;
218   void* userData;
219
220   ULONG streamID;
221   ULONG flag;
222
223   VDR_ResponsePacket* vresp;
224   
225   ULONG timeNow = 0;
226   ULONG lastKAsent = 0;
227   ULONG lastKArecv = time(NULL);
228   bool readSuccess;
229
230   while(1)
231   {
232     if (threadReqStop) return;
233
234     timeNow = time(NULL);
235     
236     readSuccess = tcp.read(&channelID, sizeof(ULONG));
237
238     if (threadReqStop) return;
239
240     if (!readSuccess)
241     {
242       //logger->log("VDR", Log::DEBUG, "Net read timeout");
243       if (!tcp.status()) { connectionDied(); return; } // return to stop this thread
244     }
245       
246     // Error or timeout.
247
248     if (!lastKAsent) // have not sent a KA
249     {
250       if (lastKArecv < (timeNow - 5))
251       {
252         //logger->log("VDR", Log::DEBUG, "Sending KA packet");
253         if (!sendKA(timeNow))
254         {
255           logger->log("VDR", Log::DEBUG, "Could not send KA, calling connectionDied");
256           connectionDied();
257           return;
258         }
259         lastKAsent = timeNow;
260
261         if (threadReqStop) return;
262       }
263     }
264     else
265     {
266       if (lastKAsent <= (timeNow - 10))
267       {
268         logger->log("VDR", Log::DEBUG, "lastKA over 10s ago, calling connectionDied");
269         connectionDied();
270         return;
271       }    
272     }
273
274     if (!readSuccess) continue; // no data was read but the connection is ok.
275     
276     // Data was read
277             
278     channelID = ntohl(channelID);
279
280     if (channelID == CHANNEL_REQUEST_RESPONSE)
281     {
282       if (!tcp.read(&requestID, sizeof(ULONG))) break;
283       if (threadReqStop) return;
284       requestID = ntohl(requestID);
285       if (!tcp.read(&userDataLength, sizeof(ULONG))) break;
286       if (threadReqStop) return;
287       userDataLength = ntohl(userDataLength);
288       if (userDataLength > 5000000) break; // how big can these packets get?
289       userData = NULL;
290       if (userDataLength > 0)
291       {
292         userData = malloc(userDataLength);
293         if (!userData) break;
294         if (!tcp.read(userData, userDataLength))
295         {
296           free(userData);
297           break;
298         }
299
300         if (threadReqStop)
301         {
302           free(userData);
303           return;
304         }
305       }
306
307       vresp = new VDR_ResponsePacket();  
308       vresp->setResponse(requestID, reinterpret_cast<UCHAR*>(userData), userDataLength);
309       // vresp now owns userData unless something calls vresp->getUserData()
310 //      logger->log("VDR", Log::DEBUG, "Rxd a response packet, requestID=%lu, len=%lu", requestID, userDataLength);
311
312       if (!edFindAndCall(vresp)) // makes ED lock, find receiver for vresp (using ed_cb_find() ) and then call (using ed_cb_call() )
313       {
314         // If edFindAndCall returns true, edr was called and vresp was handed off.
315         // else, delete vresp here.
316         delete vresp;
317       }
318       if (threadReqStop) return;
319     }
320     else if (channelID == CHANNEL_STREAM || channelID == CHANNEL_TVMEDIA)
321     {
322       if (!tcp.read(&streamID, sizeof(ULONG))) break;
323       if (threadReqStop) return;
324       streamID = ntohl(streamID);
325
326       if (!tcp.read(&flag, sizeof(ULONG))) break;
327       if (threadReqStop) return;
328       flag = ntohl(flag);
329
330       if (!tcp.read(&userDataLength, sizeof(ULONG))) break;
331       if (threadReqStop) return;
332       userDataLength = ntohl(userDataLength);
333       userData = NULL;
334       if (userDataLength > 0)
335       {
336         userData = malloc(userDataLength);
337         if (!userData) break;
338         if (!tcp.read(userData, userDataLength))
339         {
340           free(userData);
341           break;
342         }
343
344         if (threadReqStop)
345         {
346           free(userData);
347           return;
348         }
349       }
350
351       vresp = new VDR_ResponsePacket();    
352       vresp->setStream(streamID, flag, reinterpret_cast<UCHAR*>(userData), userDataLength, channelID);
353       //logger->log("VDR", Log::DEBUG, "Rxd a stream packet, streamID=%lu, flag=%lu, len=%lu", streamID, flag, userDataLength);
354
355       if (!edFindAndCall(vresp)) // makes ED lock, find receiver for vresp (using ed_cb_find() ) and then call (using ed_cb_call() )
356       {
357         // If edFindAndCall returns true, edr was called and vresp was handed off.
358         // else, delete vresp here.
359         delete vresp;
360       }
361
362       if (threadReqStop) return;
363     }
364     else if (channelID == CHANNEL_KEEPALIVE)
365     {
366       ULONG KAreply = 0;
367       if (!tcp.read(&KAreply, sizeof(ULONG))) break;
368       if (threadReqStop) return;
369       KAreply = ntohl(KAreply);
370       if (KAreply == lastKAsent) // successful KA response
371       {
372         lastKAsent = 0;
373         lastKArecv = KAreply;
374         //logger->log("VDR", Log::DEBUG, "Rxd correct KA reply");
375       }
376     }
377     else
378     {
379       logger->log("VDR", Log::ERR, "Rxd a response packet on channel %lu !!", channelID);
380       break;
381     }
382
383     // Who deletes vresp?
384     // If RR, the individual protocol functions must delete vresp.
385     // If stream, the data and length is taken out in ed_cb_call and vresp is deleted there.
386   }
387  
388   connectionDied();
389 }
390
391 void VDR::connectionDied()
392 {
393   // Called from within threadMethod to do cleanup if it decides the connection has died
394
395   connected = false; // though actually it could still be connected until someone calls vdr->disconnect
396
397   // Need to wake up any waiting channel 1 request-response threads
398   // Normally this is done by a packet coming in with channelid and requestid      
399   // Instead, go through the list and for each channel 1 edr, make an empty vresp
400   // An empty vresp will have userData == NULL, which means vresp->noResponse() == true
401
402   // If it's a stream receiver, generate a stream packet with flag == connection_lost
403
404   edMutex.lock();
405   VDR_PacketReceiver* vdrpr;
406   VDR_ResponsePacket* vresp;
407   while(receivers.size())
408   {
409     vdrpr = dynamic_cast<VDR_PacketReceiver*>(*(receivers.begin()));
410     if (vdrpr->receiverChannel == CHANNEL_REQUEST_RESPONSE)
411     {
412       vresp = new VDR_ResponsePacket();
413       vresp->setResponse(vdrpr->requestSerialNumber, NULL, 0);
414       logger->log("VDR", Log::DEBUG, "Timeouts: created blank response packet for request serial %lu", vdrpr->requestSerialNumber);
415       edMutex.unlock();
416       if (!edFindAndCall(vresp)) // makes ED lock, find receiver for vresp (using ed_cb_find() ) and then call (using ed_cb_call() )
417       {
418         // If edFindAndCall returns true, edr was called and vresp was handed off.
419         // else, delete vresp here.
420         logger->log("VDR", Log::ERR, "Timeouts: no waiting thread found for request serial %lu !!!", vdrpr->requestSerialNumber);
421         delete vresp;
422       }
423       edMutex.lock();
424     }
425     else if (vdrpr->receiverChannel == CHANNEL_STREAM || vdrpr->receiverChannel == CHANNEL_TVMEDIA)
426     {
427       vresp = new VDR_ResponsePacket();
428       vresp->setStream(vdrpr->streamID, 2 /* connection-lost flag */ , NULL, 0, vdrpr->receiverChannel);
429       logger->log("VDR", Log::DEBUG, "Timeouts: created blank response packet for streamid %lu", vdrpr->streamID);
430       edMutex.unlock();
431       if (!edFindAndCall(vresp)) // makes ED lock, find receiver for vresp (using ed_cb_find() ) and then call (using ed_cb_call() )
432       {
433         // If edFindAndCall returns true, edr was called and vresp was handed off.
434         // else, delete vresp here.
435         logger->log("VDR", Log::ERR, "Timeouts: no waiting stream receiver found for streamid %lu !!!", vdrpr->streamID);
436         delete vresp;
437       }
438       edMutex.lock();
439
440       for(EDRL::iterator i = receivers.begin(); i != receivers.end(); i++)
441         if (dynamic_cast<VDR_PacketReceiver*>(*i) == vdrpr) { receivers.erase(i); break; }
442     }
443   }
444   edMutex.unlock();
445   // Ok, all event receviers should be dealt with. just in case there weren't any, inform command
446   logger->log("VDR", Log::DEBUG, "edUnlock at end of connectionDied");
447
448   Command::getInstance()->connectionLost();
449 }
450
451 bool VDR::ed_cb_find(EDReceiver* edr, void* userTag)
452 {
453   // edr is a VDR_PacketReceiver object made in VDR::RequestResponse
454   // userTag is a VDR_ResponsePacket made in threadMethod
455
456   VDR_PacketReceiver* vdrpr = dynamic_cast<VDR_PacketReceiver*>(edr);
457   VDR_ResponsePacket* vresp = reinterpret_cast<VDR_ResponsePacket*>(userTag);
458   
459   // Is vresp for vdrpr ?
460   
461   ULONG packetChannel = vresp->getChannelID();
462   //logger->log("VDR", Log::DEBUG, "TVMedia debug %d %d %x", vdrpr->receiverChannel,packetChannel,vdrpr);
463   if (vdrpr->receiverChannel != packetChannel) return false;
464
465   if (packetChannel == CHANNEL_REQUEST_RESPONSE)
466   {
467     if (vdrpr->requestSerialNumber == vresp->getRequestID()) return true;
468   }
469   else if (packetChannel == CHANNEL_STREAM)
470   {
471     if (vdrpr->streamID == vresp->getStreamID()) return true;
472   }
473   else if (packetChannel == CHANNEL_TVMEDIA)
474   {
475     if (vdrpr->streamID == vresp->getStreamID()) return true;
476   }
477
478   return false;
479 }
480
481 VDR_ResponsePacket* VDR::RequestResponse(VDR_RequestPacket* vrp)
482 {
483   //logger->log("VDR", Log::DEBUG, "RR %lu", vrp->getOpcode());
484
485   if (!connected)
486   {
487     logger->log("VDR", Log::DEBUG, "RR when !connected");
488     VDR_ResponsePacket* vresp = new VDR_ResponsePacket();
489     return vresp; // "no-response" return
490   }
491
492   // ED make new VDR and register
493   // make a VDR_PacketReceiver
494   // - init with serial number of request packet
495
496   VDR_PacketReceiver vdrpr;
497 //  vdrpr.requestTime = time(NULL);
498   vdrpr.receiverChannel = VDR::CHANNEL_REQUEST_RESPONSE;
499   vdrpr.requestSerialNumber = vrp->getSerial();
500
501   edRegister(&vdrpr);
502    
503   edMutex.lock();
504
505
506   if (!tcp.write(vrp->getPtr(), vrp->getLen()))
507   {
508     edMutex.unlock();
509     edUnregister(&vdrpr);
510     VDR_ResponsePacket* vresp = new VDR_ResponsePacket();
511     return vresp; // "no-response" return
512   }
513
514   // Sleep and block this thread. The sleep unlocks the mutex
515 //  logger->log("VDR", Log::DEBUG, "RR sleep - opcode %lu", vrp->getOpcode());
516   edSleepThisReceiver(&vdrpr);
517 //  logger->log("VDR", Log::DEBUG, "RR unsleep");
518     
519   // Woken because a response packet has arrived, mutex will be locked
520 //  logger->log("VDR", Log::DEBUG, "Packet delivered to me, requestID: %lu", vdrpr.save_vresp->getRequestID());
521   
522   edMutex.unlock();
523   return vdrpr.save_vresp;
524 }
525
526 bool VDR::sendKA(ULONG timeStamp)
527 {
528   char buffer[8];
529
530   int pos=0;
531   ULONG ul=CHANNEL_KEEPALIVE;
532   buffer[pos++]=(ul>>24)&0xff;
533   buffer[pos++]=(ul>>16)&0xff;
534   buffer[pos++]=(ul>>8)&0xff;
535   buffer[pos++]=ul &0xff;
536   ul=timeStamp;
537   buffer[pos++]=(ul>>24)&0xff;
538   buffer[pos++]=(ul>>16)&0xff;
539   buffer[pos++]=(ul>>8)&0xff;
540   buffer[pos++]=ul &0xff;
541   return tcp.write(buffer, 8);
542 }
543
544 /////////////////////////////////////////////////////////////////////////////
545
546 // Here VDR takes a break for the VDR_PacketReceiver helper class
547
548 void VDR_PacketReceiver::call(void* userTag, bool& r_deregisterEDR, bool& r_wakeThread, bool& r_deleteEDR)
549 {
550   if (receiverChannel == VDR::CHANNEL_REQUEST_RESPONSE)
551   {
552     // It's a RR. Save vresp and, signal the waiting thread and return.
553     // VDR::RequestResponse will be blocking waiting for this to happen.
554     // That function has a pointer to this object and can read save_vresp.
555     save_vresp = reinterpret_cast<VDR_ResponsePacket*>(userTag);
556
557     r_deregisterEDR = true;
558     r_wakeThread = true;
559     r_deleteEDR = false;
560   }
561   else if (receiverChannel == VDR::CHANNEL_STREAM)
562   {
563     // It's a stream packet. Pass off the stream data to streamReceiver,
564     // delete the vresp. Keep this PacketReceiver for the next stream packet.
565     VDR_ResponsePacket* vresp = reinterpret_cast<VDR_ResponsePacket*>(userTag);
566     streamReceiver->streamReceive(vresp->getFlag(), vresp->getUserData(), vresp->getUserDataLength());
567     delete vresp;
568
569     r_deregisterEDR = false;
570     r_wakeThread = false;
571     r_deleteEDR = false;
572   }
573   else if (receiverChannel == VDR::CHANNEL_TVMEDIA)
574   {
575     // It's TVMedia
576     // Pass off the vresp object to OSDVector
577     // This used to return true which would signal the cond (wake the thread)
578     // but am going to try setting this to false because I don't know that there is a thread to signal
579     // delete the EDR. It's made once per media requested and wasn't owned/deleted by anything before
580
581     VDR_ResponsePacket* vresp = reinterpret_cast<VDR_ResponsePacket*>(userTag);
582     Log::getInstance()->log("VDR", Log::DEBUG, "TVMedia Pictures arrived VDR %x", vresp->getStreamID());
583     OsdVector *osd=dynamic_cast<OsdVector*>(Osd::getInstance());
584     if (osd) osd->getPictReader()->receivePicture(vresp);
585     // else delete vresp; //nonsense // only rpi does CHANNEL_TVMEDIA, rpi has osdvector. therefore, can't get here.
586
587     r_deregisterEDR = true;
588     r_wakeThread = false;
589     r_deleteEDR = true;
590   }
591   else abort(); // unknown receiverChannel, should not happen
592 }
593
594 /////////////////////////////////////////////////////////////////////////////
595
596 int VDR::doLogin(unsigned int* v_server_min, unsigned int* v_server_max, unsigned int* v_client,
597                 ASLPrefList& list, int &subtitles)
598 {
599   VDR_RequestPacket vrp;
600   if (!vrp.init(VDR_LOGIN, true, 6)) return 0;
601
602   MACAddress myMAC = tcp.getMAC();
603   if (!vrp.copyin(reinterpret_cast<UCHAR*>(&myMAC), 6)) return 0;
604
605   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
606   if (vresp->noResponse()) { delete vresp; return 0; }
607
608   ULONG vdrTime = vresp->extractULONG();
609   logger->log("VDR", Log::DEBUG, "vdrtime = %lu", vdrTime);
610   long vdrTimeOffset = vresp->extractLONG();
611   logger->log("VDR", Log::DEBUG, "offset = %i", vdrTimeOffset);
612
613   unsigned int version_min=vresp->extractULONG();
614
615   *v_server_min=version_min;
616   unsigned int version_max=vresp->extractULONG();
617   *v_server_max=version_max;
618   *v_client=VOMP_PROTOCOL_VERSION;
619
620   if (0x00000302 <= version_max) {
621           unsigned int numlangcodes = vresp->extractULONG();
622           subtitles = vresp->extractULONG();
623           list.clear();
624           for (unsigned int i=0; i<numlangcodes; i++) {
625                   ASLPref newpref;
626                   newpref.audiopref = vresp->extractLONG();
627                   newpref.subtitlepref = vresp->extractLONG();
628                   newpref.langcode = vresp->extractStdString();
629                   //logger->log("VDR", Log::DEBUG, "Langpref %s %d %d", newpref.langcode.c_str(),  newpref.audiopref,  newpref.subtitlepref);
630                   list.push_back(newpref);
631           }
632   }
633
634
635   delete vresp;
636
637   if ((version_min > VOMP_PROTOCOL_VERSION)
638                   || (version_max < VOMP_PROTOCOL_VERSION) ) {
639
640           return 0;
641
642   }
643
644   // Set the time and zone on the MVP only
645
646 #if !defined(WIN32) && !defined(__ANDROID__)
647   struct timespec currentTime;
648   currentTime.tv_sec = vdrTime;
649   currentTime.tv_nsec = 0;
650
651   int b = clock_settime(CLOCK_REALTIME, &currentTime);
652
653   logger->log("VDR", Log::DEBUG, "set clock = %u", b);
654
655   // now make a TZ variable and set it
656   char sign;
657   int hours;
658   int minutes;
659   if (vdrTimeOffset > 0) sign = '-';
660   else sign = '+';
661
662   vdrTimeOffset = abs(vdrTimeOffset);
663
664   hours = (int)vdrTimeOffset / 3600;
665   minutes = vdrTimeOffset % 3600;
666
667   logger->log("VDR", Log::DEBUG, "%c %i %i", sign, hours, minutes);
668
669   minutes = (int)minutes / 60;
670
671   logger->log("VDR", Log::DEBUG, "%c %i %i", sign, hours, minutes);
672
673   char newTZ[30];
674   sprintf(newTZ, "MVP%c%i:%i", sign, hours, minutes);
675   setenv("TZ", newTZ, 1);
676
677   logger->log("VDR", Log::DEBUG, "Timezone data: %s", newTZ);
678 #endif
679
680   setCharset(Osd::getInstance()->charSet());
681
682   return 1;
683 }
684
685 bool VDR::LogExtern(const char* logString)
686 {
687   if (!connected) return false;
688   int stringLength = strlen(logString);
689   int packetLength = stringLength + 8;
690   char *buffer=new char[packetLength + 1];
691   int pos=0;
692   ULONG ul=CHANNEL_NETLOG;
693   buffer[pos++]=(ul>>24)&0xff;
694   buffer[pos++]=(ul>>16)&0xff;
695   buffer[pos++]=(ul>>8)&0xff;
696   buffer[pos++]=ul &0xff;
697   ul=stringLength;
698   buffer[pos++]=(ul>>24)&0xff;
699   buffer[pos++]=(ul>>16)&0xff;
700   buffer[pos++]=(ul>>8)&0xff;
701   buffer[pos++]=ul &0xff;
702
703   strcpy(&buffer[8], logString);
704   
705   if (!tcp.write(buffer, packetLength))
706   {
707     connected = false; // stop the rest of the connection  
708     delete [] buffer;
709     return false;
710   }
711   delete [] buffer;
712   return true;
713 }
714
715 bool VDR::setCharset(int charset)
716 {
717   VDR_RequestPacket vrp;
718   if (!vrp.init(VDR_SETCHARSET, true, sizeof(ULONG))) return false;
719   if (!vrp.addULONG(charset)) return false;
720
721   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
722   if (vresp->noResponse()) { delete vresp; return false; }
723
724   ULONG success = vresp->extractULONG();
725   delete vresp;
726
727   if (!success) return false;
728
729   return true;
730 }
731
732 bool VDR::getRecordingsList(RecMan* recman)
733 {
734   VDR_RequestPacket vrp;
735   if (!vrp.init(VDR_GETRECORDINGLIST, true, 0)) return false;
736
737   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
738   if (vresp->noResponse()) { delete vresp; return false; }
739
740   ULONG totalSpace = vresp->extractULONG();
741   ULONG freeSpace = vresp->extractULONG();
742   ULONG percent = vresp->extractULONG();
743
744   recman->setStats(totalSpace, freeSpace, percent);
745
746   ULONG start;
747   UCHAR isNew;
748   char* name;
749   char* fileName;
750
751   while (!vresp->end())
752   {
753     start = vresp->extractULONG();
754     isNew = vresp->extractUCHAR();
755     name = vresp->extractString();
756     fileName = vresp->extractString();
757     recman->addEntry(isNew, start, name, fileName);
758     delete[] name;
759     delete[] fileName;
760   }
761   delete vresp;
762
763   return true;
764 }
765
766 int VDR::deleteRecording(char* fileName)
767 {
768   VDR_RequestPacket vrp;
769   if (!vrp.init(VDR_DELETERECORDING, true, strlen(fileName) + 1)) return 0;
770   if (!vrp.addString(fileName)) return 0;
771   
772   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
773   if (vresp->noResponse()) { delete vresp; return 0; }
774   
775   int toReturn = static_cast<int>(vresp->extractULONG());
776   delete vresp;
777
778   return toReturn;
779 }
780
781 int VDR::deleteRecResume(char* fileName)
782 {
783   VDR_RequestPacket vrp;
784   if (!vrp.init(VDR_DELETERECRESUME, true, strlen(fileName) + 1)) return 0;
785   if (!vrp.addString(fileName)) return 0;
786
787   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
788   if (vresp->noResponse()) { delete vresp; return 0; }
789
790   int toReturn = static_cast<int>(vresp->extractULONG());
791   delete vresp;
792
793   return toReturn;
794 }
795
796 char* VDR::moveRecording(char* fileName, char* newPath)
797 {
798   VDR_RequestPacket vrp;
799   if (!vrp.init(VDR_MOVERECORDING, true, strlen(fileName) + 1 + strlen(newPath) + 1)) return NULL;
800   if (!vrp.addString(fileName)) return NULL;
801   if (!vrp.addString(newPath)) return NULL;
802   
803   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
804   if (vresp->noResponse()) { delete vresp; return NULL; }
805   
806   char* toReturn = NULL;
807   int success = static_cast<int>(vresp->extractULONG());
808   if (success == 1)
809   {
810     toReturn = vresp->extractString();
811   }
812
813   delete vresp;
814
815   return toReturn;
816 }
817
818 ChannelList* VDR::getChannelsList(ULONG type)
819 {
820   VDR_RequestPacket vrp;
821   if (!vrp.init(VDR_GETCHANNELLIST, true, 0)) return NULL;
822
823   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
824   if (vresp->noResponse()) { delete vresp; return NULL; }
825   
826   ChannelList* chanList = new ChannelList();
827
828   bool h264support=Video::getInstance()->supportsh264();
829   bool mpeg2support=Video::getInstance()->supportsmpeg2();
830
831   while (!vresp->end())
832   {
833     Channel* chan = new Channel();
834     chan->number = vresp->extractULONG();
835     chan->type = vresp->extractULONG();
836     chan->name = vresp->extractString();
837     chan->vstreamtype = static_cast<UCHAR>(vresp->extractULONG());
838
839     if (chan->type == type && ((chan->vstreamtype==0x1b && h264support)|| (chan->vstreamtype!=0x1b &&mpeg2support)) )
840     {
841       chanList->push_back(chan);
842       logger->log("VDR", Log::DEBUG, "Have added a channel to list. %lu %lu %s", chan->number, chan->type, chan->name);
843       if (chan->number > maxChannelNumber) maxChannelNumber = chan->number;
844     }
845     else
846     {
847       delete chan;
848     }
849   }
850
851   delete vresp;
852
853   if (maxChannelNumber > 99999)
854     channelNumberWidth = 6;
855   else if (maxChannelNumber > 9999)
856     channelNumberWidth = 5;
857   else if (maxChannelNumber > 999)
858     channelNumberWidth = 4;
859   else if (maxChannelNumber > 99)
860     channelNumberWidth = 3;
861   else if (maxChannelNumber > 9)
862     channelNumberWidth = 2;
863   else
864     channelNumberWidth = 1;
865
866   return chanList;
867 }
868
869 int VDR::streamChannel(ULONG number, StreamReceiver* tstreamReceiver)
870 {
871   VDR_RequestPacket vrp;
872   if (!vrp.init(VDR_STREAMCHANNEL, true, sizeof(ULONG))) return 0;
873   if (!vrp.addULONG(number)) return 0;
874   
875   
876   VDR_PacketReceiver* vdrpr = new VDR_PacketReceiver();
877   vdrpr->receiverChannel = VDR::CHANNEL_STREAM;
878   vdrpr->streamID = vrp.getSerial();
879   vdrpr->streamReceiver = tstreamReceiver;
880   edRegister(vdrpr);
881   TEMP_SINGLE_VDR_PR = vdrpr;
882   
883   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
884   if (vresp->noResponse())
885   {
886     delete vresp;
887     edUnregister(vdrpr);
888     delete vdrpr;
889     return 0;
890   }
891   
892   int toReturn = static_cast<int>(vresp->extractULONG());
893   logger->log("VDR", Log::DEBUG, "VDR said %lu to start streaming request", toReturn);
894   delete vresp;
895
896   return toReturn;
897 }
898
899 int VDR::stopStreaming()
900 {
901   VDR_RequestPacket vrp;
902   if (!vrp.init(VDR_STOPSTREAMING, true, 0)) return 0;
903
904   if (TEMP_SINGLE_VDR_PR) // this block only needs to be done if it was a live stream
905                           // TEMP_SINGLE_VDR_PR will not be set unless we are streaming a channel
906   {
907     edUnregister(TEMP_SINGLE_VDR_PR);
908     delete TEMP_SINGLE_VDR_PR;
909     TEMP_SINGLE_VDR_PR = NULL;
910   }
911
912   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
913   if (vresp->noResponse()) { delete vresp; return 0; }
914   
915   int toReturn = static_cast<int>(vresp->extractULONG());
916   delete vresp;
917
918   return toReturn;
919 }
920
921 UCHAR* VDR::getBlock(ULLONG position, UINT maxAmount, UINT* amountReceived)
922 {
923   VDR_RequestPacket vrp;
924   if (!vrp.init(VDR_GETBLOCK, true, sizeof(ULLONG) + sizeof(ULONG))) return NULL;
925   if (!vrp.addULLONG(position)) return NULL;
926   if (!vrp.addULONG(maxAmount)) return NULL;
927
928   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
929   if (vresp->noResponse()) { delete vresp; return NULL; }
930
931   if (vresp->serverError())
932   {
933     logger->log("VDR", Log::DEBUG, "Detected getblock 0");
934     *amountReceived = 0;
935     delete vresp;
936     return NULL;
937   }
938
939   // Special handling for getblock
940   UCHAR* toReturn = vresp->getUserData();
941   *amountReceived = vresp->getUserDataLength();
942   
943   delete vresp;
944   
945   return toReturn;
946 }
947
948 ULLONG VDR::streamRecording(char* fileName, ULONG* totalFrames, bool* IsPesRecording)
949 {
950   VDR_RequestPacket vrp;
951   if (!vrp.init(VDR_STREAMRECORDING, true, strlen(fileName) + 1)) return 0;
952   if (!vrp.addString(fileName)) return 0;
953
954   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
955   if (vresp->noResponse()) { delete vresp; return 0; }
956   
957   ULLONG lengthBytes = vresp->extractULLONG();
958   ULONG lengthFrames = vresp->extractULONG();
959   UCHAR isPesRecording = vresp->extractUCHAR();
960   delete vresp;
961
962   *totalFrames = lengthFrames;
963   *IsPesRecording = (isPesRecording);//convert Uchar to bool
964
965   logger->log("VDR", Log::DEBUG, "VDR said length is: %llu %lu, IsPesRecording %x", lengthBytes, lengthFrames, *IsPesRecording);
966
967   return lengthBytes;
968 }
969
970 ULLONG VDR::positionFromFrameNumber(ULONG frameNumber)
971 {
972   VDR_RequestPacket vrp;
973   if (!vrp.init(VDR_POSFROMFRAME, true, sizeof(ULONG))) return 0;
974   if (!vrp.addULONG(frameNumber)) return 0;
975
976   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
977   if (vresp->noResponse()) { delete vresp; return 0; }
978   
979   ULLONG position = vresp->extractULLONG();
980   delete vresp;
981   
982   logger->log("VDR", Log::DEBUG, "VDR said new position is: %llu", position);
983
984   return position;
985 }
986
987 ULONG VDR::frameNumberFromPosition(ULLONG position)
988 {
989   VDR_RequestPacket vrp;
990   if (!vrp.init(VDR_FRAMEFROMPOS, true, sizeof(ULLONG))) return 0;
991   if (!vrp.addULLONG(position)) return 0;
992
993   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
994   if (vresp->noResponse()) { delete vresp; return 0; }
995   
996   ULONG framenumber = vresp->extractULONG();
997   delete vresp;
998   
999   logger->log("VDR", Log::DEBUG, "VDR said new framenumber is: %u", framenumber);
1000
1001   return framenumber;
1002 }
1003
1004 bool VDR::getNextIFrame(ULONG frameNumber, ULONG direction, ULLONG* rfilePosition, ULONG* rframeNumber, ULONG* rframeLength)
1005 {
1006   VDR_RequestPacket vrp;
1007   if (!vrp.init(VDR_GETNEXTIFRAME, true, sizeof(ULONG)*2)) return false;
1008   if (!vrp.addULONG(frameNumber)) return false;
1009   if (!vrp.addULONG(direction)) return false;
1010
1011   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1012   if (vresp->noResponse()) { delete vresp; return false; }
1013   
1014   if (vresp->serverError())
1015   {
1016     logger->log("VDR", Log::DEBUG, "Detected getNextIFrame error");
1017     delete vresp;
1018     return false;
1019   }
1020
1021   *rfilePosition = vresp->extractULLONG();
1022   *rframeNumber = vresp->extractULONG();
1023   *rframeLength = vresp->extractULONG();
1024
1025   delete vresp;
1026
1027   logger->log("VDR", Log::DEBUG, "VDR GNIF said %llu %lu %lu", *rfilePosition, *rframeNumber, *rframeLength);
1028
1029   return true;
1030 }
1031
1032 EventList* VDR::getChannelSchedule(ULONG number)
1033 {
1034   time_t now;
1035   time(&now);
1036   return getChannelSchedule(number, now, 24 * 60 * 60);
1037 }
1038
1039 EventList* VDR::getChannelSchedule(ULONG number, time_t start, ULONG duration)
1040 {
1041 // retrieve event list (vector of events) from vdr within filter window. duration is in seconds
1042
1043   VDR_RequestPacket vrp;
1044   if (!vrp.init(VDR_GETCHANNELSCHEDULE, true, sizeof(ULONG)*3)) return NULL;
1045   if (!vrp.addULONG(number)) return NULL;
1046   if (!vrp.addULONG(start)) return NULL;
1047   if (!vrp.addULONG(duration)) return NULL;
1048
1049   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1050   if (vresp->noResponse()) { delete vresp; return NULL; }
1051
1052   // received a ulong(0) - schedules error in the plugin
1053   if (vresp->serverError())
1054   {
1055     delete vresp;
1056     return NULL;
1057   }
1058
1059   EventList* eventList = new EventList();
1060
1061   while (!vresp->end())
1062   {
1063     Event* event = new Event();
1064     event->id = vresp->extractULONG();
1065     event->time = vresp->extractULONG();
1066     event->duration = vresp->extractULONG();
1067     event->title = vresp->extractString();
1068     event->subtitle = vresp->extractString();
1069     event->description = vresp->extractString();
1070     eventList->push_back(event);
1071   }
1072
1073   delete vresp;
1074
1075   logger->log("VDR", Log::DEBUG, "Success got to end of getChannelSchedule");
1076   return eventList;
1077 }
1078
1079 int VDR::configSave(const char* section, const char* key, const char* value)
1080 {
1081   VDR_RequestPacket vrp;
1082   if (!vrp.init(VDR_CONFIGSAVE, false, 0)) return 0;
1083   if (!vrp.addString(section)) return 0;
1084   if (!vrp.addString(key)) return 0;
1085   if (!vrp.addString(value)) return 0;
1086
1087   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1088   if (vresp->noResponse()) { delete vresp; return 0; }
1089
1090   int toReturn = static_cast<int>(vresp->extractULONG());
1091   delete vresp;
1092
1093   return toReturn;
1094 }
1095
1096 char* VDR::configLoad(const char* section, const char* key)
1097 {
1098   VDR_RequestPacket vrp;
1099   if (!vrp.init(VDR_CONFIGLOAD, false, 0)) return NULL;
1100   if (!vrp.addString(section)) return NULL;
1101   if (!vrp.addString(key)) return NULL;
1102
1103   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1104   if (vresp->noResponse()) { delete vresp; return NULL; }
1105   
1106   char* toReturn = vresp->extractString();
1107   delete vresp;
1108
1109   return toReturn;
1110 }
1111
1112 RecTimerList* VDR::getRecTimersList()
1113 {
1114   VDR_RequestPacket vrp;
1115   if (!vrp.init(VDR_GETTIMERS, true, 0)) return NULL;
1116
1117   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1118   if (vresp->noResponse()) { delete vresp; return NULL; }
1119
1120   RecTimerList* recTimerList = new RecTimerList();
1121
1122   ULONG numTimers = vresp->extractULONG();
1123   if (numTimers > 0)
1124   {
1125     RecTimer* newRecTimer;
1126     char* tempString;
1127
1128     while (!vresp->end())
1129     {
1130       newRecTimer = new RecTimer();
1131       newRecTimer->active = vresp->extractULONG();
1132       newRecTimer->recording = vresp->extractULONG();
1133       newRecTimer->pending = vresp->extractULONG();
1134       newRecTimer->priority = vresp->extractULONG();
1135       newRecTimer->lifeTime = vresp->extractULONG();
1136       newRecTimer->channelNumber = vresp->extractULONG();
1137       newRecTimer->startTime = vresp->extractULONG();
1138       newRecTimer->stopTime = vresp->extractULONG();
1139       newRecTimer->day = vresp->extractULONG();
1140       newRecTimer->weekDays = vresp->extractULONG();
1141
1142       tempString = vresp->extractString();
1143       newRecTimer->setFile(tempString);
1144       delete[] tempString;
1145
1146       recTimerList->push_back(newRecTimer);
1147       logger->log("VDR", Log::DEBUG, "TL: %lu %lu %lu %lu %lu %lu %lu %lu %s",
1148         newRecTimer->active, newRecTimer->recording, newRecTimer->pending, newRecTimer->priority, newRecTimer->lifeTime,
1149         newRecTimer->channelNumber, newRecTimer->startTime, newRecTimer->stopTime, newRecTimer->getFile());
1150     }
1151   }
1152
1153   delete vresp;
1154
1155   sort(recTimerList->begin(), recTimerList->end(), RecTimerSorter());
1156
1157   return recTimerList;
1158 }
1159
1160 ULONG VDR::setEventTimer(char* timerString)
1161 {
1162   VDR_RequestPacket vrp;
1163   if (!vrp.init(VDR_SETTIMER, true, strlen(timerString) + 1)) return 0;
1164   if (!vrp.addString(timerString)) return 0;
1165
1166   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1167   if (vresp->noResponse()) { delete vresp; return 0; }
1168   
1169   ULONG toReturn = vresp->extractULONG();
1170   delete vresp;
1171
1172   return toReturn;
1173 }
1174
1175 RecInfo* VDR::getRecInfo(char* fileName)
1176 {
1177   VDR_RequestPacket vrp;
1178   if (!vrp.init(VDR_GETRECINFO2, true, strlen(fileName) + 1)) return NULL;
1179   if (!vrp.addString(fileName)) return NULL;
1180   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1181
1182   if (vresp->noResponse()) { delete vresp; return NULL; }
1183
1184   if (vresp->serverError())
1185   {
1186     logger->log("VDR", Log::DEBUG, "Could not get rec info");
1187     delete vresp;
1188     return NULL;
1189   }
1190
1191   RecInfo* recInfo = new RecInfo();
1192
1193   recInfo->timerStart = vresp->extractULONG();
1194   recInfo->timerEnd = vresp->extractULONG();
1195   recInfo->resumePoint = vresp->extractULONG();
1196   recInfo->summary = vresp->extractString();
1197
1198   ULONG numComponents = vresp->extractULONG();
1199   if (numComponents)
1200   {
1201     recInfo->setNumComponents(numComponents);
1202     for (ULONG i = 0; i < numComponents; i++)
1203     {
1204       recInfo->streams[i] = vresp->extractUCHAR();
1205       recInfo->types[i] = vresp->extractUCHAR();
1206       recInfo->languages[i] = vresp->extractString();
1207       recInfo->descriptions[i] = vresp->extractString();
1208     }
1209   }
1210   recInfo->fps=vresp->extractdouble();
1211   recInfo->title=vresp->extractString();
1212   
1213   // New stuff
1214   recInfo->channelName = vresp->extractString();
1215   recInfo->duration = vresp->extractULONG();
1216   recInfo->fileSize = vresp->extractULONG();
1217   recInfo->priority = vresp->extractULONG();
1218   recInfo->lifetime = vresp->extractULONG();
1219
1220   recInfo->print();
1221
1222   delete vresp;
1223   return recInfo;
1224 }
1225
1226 // FIXME obselete
1227 ULLONG VDR::rescanRecording(ULONG* totalFrames)
1228 {
1229   VDR_RequestPacket vrp;
1230   if (!vrp.init(VDR_RESCANRECORDING, true, 0)) return 0;
1231
1232   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1233   if (vresp->noResponse()) { delete vresp; return 0; }
1234   
1235   ULLONG lengthBytes = vresp->extractULLONG();
1236   ULONG lengthFrames = vresp->extractULONG();
1237   delete vresp;
1238   
1239   logger->log("VDR", Log::DEBUG, "VDR said length is: %llu %lu", lengthBytes, lengthFrames);
1240
1241   *totalFrames = lengthFrames;
1242   return lengthBytes;
1243 }
1244
1245 MarkList* VDR::getMarks(char* fileName)
1246 {
1247   VDR_RequestPacket vrp;
1248   if (!vrp.init(VDR_GETMARKS, true, strlen(fileName) + 1)) return NULL;
1249   if (!vrp.addString(fileName)) return NULL;
1250
1251   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1252   if (vresp->noResponse()) { delete vresp; return NULL; }
1253   
1254   if (vresp->serverError())
1255   {
1256     delete vresp;
1257     return NULL;
1258   }
1259
1260   MarkList* markList = new MarkList();
1261
1262   while (!vresp->end())
1263   {
1264     Mark* mark = new Mark();
1265     mark->pos = vresp->extractULONG();
1266
1267     markList->push_back(mark);
1268     logger->log("VDR", Log::DEBUG, "Have added a mark to list. %lu", mark->pos);
1269   }
1270
1271   delete vresp;
1272   
1273   return markList;
1274 }
1275
1276 void VDR::getChannelPids(Channel* channel)
1277 {
1278   VDR_RequestPacket vrp;
1279   if (!vrp.init(VDR_GETCHANNELPIDS, true, sizeof(ULONG))) return ;
1280   if (!vrp.addULONG(channel->number)) return ;
1281
1282   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1283   if (vresp->noResponse()) { delete vresp; return ; }
1284   
1285   // Format of response
1286   // vpid
1287   // number of apids
1288   // {
1289   //    apid
1290   //    lang string
1291   // }
1292
1293   channel->vpid = vresp->extractULONG();
1294   channel->vstreamtype = static_cast<UCHAR>(vresp->extractULONG());
1295   channel->numAPids = vresp->extractULONG();
1296
1297   for (ULONG i = 0; i < channel->numAPids; i++)
1298   {
1299     apid newapid;
1300     newapid.pid = vresp->extractULONG();
1301     char * name=vresp->extractString();
1302     strncpy(newapid.desc,name,9);
1303     delete [] name;
1304     channel->apids.push_back(newapid);
1305   }
1306
1307   channel->numDPids = vresp->extractULONG();
1308
1309   for (ULONG i = 0; i < channel->numDPids; i++)
1310   {
1311     apid newdpid;
1312     newdpid.pid = vresp->extractULONG();
1313     char * name=vresp->extractString();
1314     strncpy(newdpid.desc,name,9);
1315     delete [] name;
1316     channel->dpids.push_back(newdpid);
1317   }
1318
1319   channel->numSPids = vresp->extractULONG();
1320
1321   for (ULONG i = 0; i < channel->numSPids; i++)
1322   {
1323     apid newspid;
1324     newspid.pid = vresp->extractULONG();
1325     char * name=vresp->extractString();
1326     strncpy(newspid.desc,name,9);
1327     delete [] name;
1328     channel->spids.push_back(newspid);
1329   }
1330   channel->tpid = vresp->extractULONG();
1331   // extension
1332   for (ULONG i = 0; i < channel->numAPids; i++)
1333   {
1334           channel->apids[i].type = vresp->extractULONG();
1335   }
1336   for (ULONG i = 0; i < channel->numDPids; i++)
1337   {
1338           channel->dpids[i].type = vresp->extractULONG();
1339   }
1340   for (ULONG i = 0; i < channel->numSPids; i++)
1341   {
1342           channel->spids[i].type = vresp->extractULONG();
1343           channel->spids[i].data1 = vresp->extractULONG();
1344           channel->spids[i].data2 = vresp->extractULONG();
1345   }
1346
1347   delete vresp;
1348   
1349   return ;
1350 }
1351
1352 #ifdef VOMP_MEDIAPLAYER
1353 MediaList * VDR::getRootList() {
1354   return getMediaList(NULL);
1355 }
1356 /**
1357   * media List Request:
1358   * mediaURI
1359   * Media List response:
1360   * mediaList
1361 */
1362 MediaList* VDR::getMediaList(const MediaURI * root)
1363 {
1364   logger->log("VDR", Log::DEBUG, "getMediaList %s,d=%s, prov=%d", (root?root->getName():"NULL"), 
1365       ((root && root->hasDisplayName())?root->getDisplayName():"NULL"),
1366       (root?root->getProvider():providerId));
1367   MediaURI remoteURI(root);
1368   VDR_GetMediaListRequest request(&remoteURI);
1369   SerializeBuffer *vrp=prepareRequest(&request);
1370   if (!vrp) {
1371     logger->log("VDR", Log::ERR, "getMediaList unable to create command");
1372     return NULL;
1373   }
1374     
1375   SerializeBuffer* vresp = doRequestResponse(vrp,request.command);
1376   if (!vresp) {
1377     Command::getInstance()->connectionLost();
1378     return NULL;
1379   }
1380   
1381   MediaList *rt=new MediaList(NULL);
1382   ULONG rtflags=0;
1383   VDR_GetMediaListResponse resp(&rtflags,rt);
1384   if (decodeResponse(vresp,&resp) != 0) {
1385     return NULL;
1386   }
1387   return rt;
1388 }
1389
1390 /**
1391   * get image Request:
1392   * uri,x,y, channel
1393   * get media response:
1394   * 4 flags
1395   * 8 len of image
1396 */
1397 int VDR::openMedium(ULONG channel,const MediaURI *uri,  ULLONG * size, ULONG x, ULONG y)
1398 {
1399   MediaURI remoteURI(uri);
1400   VDR_OpenMediumRequest request(&channel,&remoteURI,&x,&y);
1401   *size=0;
1402   SerializeBuffer *vrp=prepareRequest(&request);
1403   if (!vrp) {
1404     logger->log("VDR", Log::ERR, "openMedium unable to create command");
1405     return -1;
1406   }
1407   SerializeBuffer* vresp = doRequestResponse(vrp,request.command);
1408   if (!vresp) {
1409     Command::getInstance()->connectionLost();
1410     return -1;
1411   }
1412   ULONG flags=0;
1413   VDR_OpenMediumResponse response(&flags,size);
1414   if (decodeResponse(vresp,&response) != 0) {
1415     return -1;
1416   }
1417   logger->log("VDR", Log::DEBUG, "openMedia len=%llu", *size);
1418   return 0;
1419 }
1420
1421 /**
1422   * getMediaBlock - no separate response class - simple data block
1423   * resp
1424   * packet
1425   */
1426 int VDR::getMediaBlock(ULONG channel, ULLONG position, ULONG maxAmount, ULONG* amountReceived, unsigned char **buffer)
1427 {
1428   *amountReceived=0;
1429   VDR_GetMediaBlockRequest request(&channel,&position,&maxAmount);
1430   SerializeBuffer *vrp=prepareRequest(&request);
1431   if (!vrp) {
1432     logger->log("VDR", Log::ERR, "getMediaBlock unable to create command");
1433     return -1;
1434   }
1435   SerializeBuffer* vresp = doRequestResponse(vrp,request.command);
1436   if (!vresp) {
1437     Command::getInstance()->connectionLost();
1438     return -1;
1439   }
1440   
1441   // Special handling for getblock
1442   *amountReceived = (ULONG)(vresp->getEnd()-vresp->getStart());
1443   *buffer = vresp->steelBuffer();
1444   delete vresp;
1445   return 0;
1446 }
1447
1448 /**
1449   * VDR_GETMEDIAINFO
1450   * channel
1451   * rt
1452   * flags
1453   * info
1454   */
1455
1456 int VDR::getMediaInfo(ULONG channel, MediaInfo * result) {
1457   if (! result) return -1;
1458   VDR_GetMediaInfoRequest request(&channel);
1459   SerializeBuffer *vrp=prepareRequest(&request);
1460   if (!vrp) {
1461     logger->log("VDR", Log::ERR, "getMediaInfo unable to create command");
1462     return -1;
1463   }
1464   SerializeBuffer* vresp = doRequestResponse(vrp,request.command);
1465   if (!vresp) {
1466     Command::getInstance()->connectionLost();
1467     return -1;
1468   }
1469
1470   ULONG flags=0;
1471   VDR_GetMediaInfoResponse response(&flags,result);
1472   if (decodeResponse(vresp,&response) != 0) {
1473     return -1;
1474   }
1475   return 0;
1476 }
1477
1478 /**
1479   * VDR_CLOSECHANNEL
1480   * channel
1481   * rt
1482   * flags
1483   */
1484
1485 int VDR::closeMediaChannel(ULONG channel) {
1486   VDR_CloseMediaChannelRequest request(&channel);
1487   SerializeBuffer *vrp=prepareRequest(&request);
1488   if (!vrp) {
1489     logger->log("VDR", Log::ERR, "closeMediaChannel unable to create command");
1490     return -1;
1491   }
1492   SerializeBuffer* vresp = doRequestResponse(vrp,request.command);
1493   if (!vresp) {
1494     Command::getInstance()->connectionLost();
1495     return -1;
1496   }
1497   ULONG flags;
1498   VDR_CloseMediaChannelResponse response(&flags);
1499   if (decodeResponse(vresp,&response) != 0) return -1;
1500   return (flags != 0)?-1:0;
1501 }
1502
1503 #endif
1504
1505
1506 int VDR::deleteTimer(RecTimer* delTimer)
1507 {
1508   logger->log("VDR", Log::DEBUG, "Delete timer called");
1509   
1510   VDR_RequestPacket vrp;
1511   if (!vrp.init(VDR_DELETETIMER, false, 0)) return 0;
1512   if (!vrp.addULONG(delTimer->channelNumber)) return 0;
1513   if (!vrp.addULONG(delTimer->weekDays)) return 0;    
1514   if (!vrp.addULONG(delTimer->day)) return 0;
1515   if (!vrp.addULONG(delTimer->startTime)) return 0;  
1516   if (!vrp.addULONG(delTimer->stopTime)) return 0; 
1517    
1518   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1519   if (vresp->noResponse()) { delete vresp; return 0; }
1520   
1521   int toReturn = static_cast<int>(vresp->extractULONG());
1522   delete vresp;
1523
1524   return toReturn;
1525 }
1526
1527 I18n::lang_code_list VDR::getLanguageList()
1528 {
1529   I18n::lang_code_list CodeList;
1530   CodeList["en"] = "English"; // Default entry
1531   VDR_RequestPacket vrp;
1532   if (!vrp.init(VDR_GETLANGUAGELIST, false, 0)) return CodeList;
1533   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1534   if (vresp->noResponse() || vresp->end())
1535   {
1536     delete vresp;
1537     return CodeList;
1538   }
1539   CodeList.clear();
1540   while (!vresp->end())
1541   {
1542     char* c_code = vresp->extractString();
1543     char* c_name = vresp->extractString();
1544     std::string code = c_code;
1545     std::string name = c_name;
1546     CodeList[code] = name;
1547     delete[] c_code;
1548     delete[] c_name;
1549   }
1550   delete vresp;
1551   return CodeList;
1552 }
1553
1554 int VDR::getLanguageContent(const std::string code, I18n::trans_table& texts)
1555 {
1556   VDR_RequestPacket vrp;
1557   if (!vrp.init(VDR_GETLANGUAGECONTENT, false, 0)) return 0;
1558   if (!vrp.addString(code.c_str())) return 0;
1559   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1560   if (vresp->noResponse()) { delete vresp; return 0; }
1561   texts.clear();
1562   while (!vresp->end())
1563   {
1564     char* c_key = vresp->extractString();
1565     char* c_text = vresp->extractString();
1566     std::string key = c_key;
1567     std::string text = c_text;
1568     texts[key] = text;
1569     delete[] c_key;
1570     delete[] c_text;
1571   }
1572   delete vresp;
1573   return 1;
1574 }
1575
1576 void VDR::shutdownVDR()
1577 {
1578   if(doVDRShutdown)
1579     logger->log("VDR", Log::DEBUG, "Shutting down vdr");
1580   else
1581     logger->log("VDR", Log::DEBUG, "Shutting down vomp only");
1582
1583   if(!doVDRShutdown || !connected)
1584     return;
1585
1586   VDR_RequestPacket vrp;
1587   logger->log("VDR", Log::DEBUG, "Sending shutdown");
1588   if (!vrp.init(VDR_SHUTDOWN, false, 0)) return;
1589   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1590   delete vresp;
1591
1592   logger->log("VDR", Log::DEBUG, "VDR shutdown");
1593 }
1594
1595 void VDR::getScraperEventType(char * fileName, int & movieID,
1596                 int & seriesID, int & episodeID)
1597 {
1598         movieID = 0;
1599         seriesID = 0;
1600         episodeID = 0;
1601         VDR_RequestPacket vrp;
1602         if (!vrp.init(VDR_GETRECSCRAPEREVENTTYPE, true, strlen(fileName) + 1)) return;
1603         if (!vrp.addString(fileName)) return ;
1604         Log::getInstance()->log("Recording", Log::DEBUG, "Before Response ");
1605         VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1606         Log::getInstance()->log("Recording", Log::DEBUG, "After Response ");
1607         if (vresp->noResponse()) { delete vresp; return ; }
1608         int type = vresp->extractUCHAR();
1609         if (type == 0) //serie
1610         {
1611                 seriesID = vresp->extractLONG();
1612                 episodeID = vresp->extractLONG();
1613         } else if (type == 1) //movie
1614         {
1615                 movieID = vresp->extractLONG();
1616         }
1617         delete vresp;
1618
1619 }
1620
1621 void VDR::getScraperEventType(UINT channelid, UINT eventid, int & movieID,
1622                 int & seriesID, int & episodeID, int & epgImage )
1623 {
1624         movieID = 0;
1625         seriesID = 0;
1626         episodeID = 0;
1627         epgImage = 0;
1628         VDR_RequestPacket vrp;
1629         if (!vrp.init(VDR_GETEVENTSCRAPEREVENTTYPE, false, 0)) return;
1630         if (!vrp.addULONG(channelid)) return ;
1631         if (!vrp.addULONG(eventid)) return ;
1632         Log::getInstance()->log("Recording", Log::DEBUG, "Before Response ");
1633         VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1634         Log::getInstance()->log("Recording", Log::DEBUG, "After Response ");
1635         if (vresp->noResponse()) { delete vresp; return ; }
1636         int type = vresp->extractUCHAR();
1637         if (type == 0) //serie
1638         {
1639                 seriesID = vresp->extractLONG();
1640                 episodeID = vresp->extractLONG();
1641         } else if (type == 1) //movie
1642         {
1643                 movieID = vresp->extractLONG();
1644         }
1645         epgImage = vresp->extractLONG();
1646         delete vresp;
1647
1648 }
1649
1650 MovieInfo *VDR::getScraperMovieInfo(int movieID)
1651 {
1652         VDR_RequestPacket vrp;
1653         if (!vrp.init(VDR_GETSCRAPERMOVIEINFO, false, 0)) return NULL;
1654         if (!vrp.addULONG(movieID)) return NULL;
1655         VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1656         if (vresp->noResponse()) { delete vresp; return NULL; }
1657         MovieInfo * movieinf= new MovieInfo();
1658
1659         movieinf->id=movieID;
1660         movieinf->title = vresp->extractStdString();
1661         movieinf->originalTitle = vresp->extractStdString();
1662         movieinf->tagline = vresp->extractStdString();
1663         movieinf->overview = vresp->extractStdString();
1664         movieinf->adult = vresp->extractUCHAR();
1665         movieinf->collectionName = vresp->extractStdString();
1666
1667         movieinf->budget = vresp->extractLONG();
1668         movieinf->revenue = vresp->extractLONG();
1669         movieinf->genres = vresp->extractStdString();
1670         movieinf->homepage = vresp->extractStdString();
1671         movieinf->releaseDate = vresp->extractStdString();
1672         movieinf->runtime = vresp->extractLONG();
1673         movieinf->popularity = vresp->extractdouble();
1674         movieinf->voteAverage = vresp->extractdouble();
1675         movieinf->poster.width = vresp->extractULONG();
1676         movieinf->poster.height = vresp->extractULONG();
1677         movieinf->poster.info.setMovieInfo(movieinf);
1678         movieinf->poster.info.setElement(0,0);
1679         movieinf->fanart.width = vresp->extractULONG();
1680         movieinf->fanart.height = vresp->extractULONG();
1681         movieinf->fanart.info.setMovieInfo(movieinf);
1682         movieinf->fanart.info.setElement(1,0);
1683         movieinf->collectionPoster.width = vresp->extractULONG();
1684         movieinf->collectionPoster.height = vresp->extractULONG();
1685         movieinf->collectionPoster.info.setMovieInfo(movieinf);
1686         movieinf->collectionPoster.info.setElement(2,0);
1687         movieinf->collectionFanart.width = vresp->extractULONG();
1688         movieinf->collectionFanart.height = vresp->extractULONG();
1689         movieinf->collectionFanart.info.setMovieInfo(movieinf);
1690         movieinf->collectionFanart.info.setElement(3,0);
1691         ULONG num_actors =  vresp->extractULONG();
1692         movieinf->actors.clear();
1693         movieinf->actors.reserve(num_actors);
1694         for (ULONG acty=0; acty < num_actors; acty++) {
1695                 Actor new_act;
1696                 new_act.name =  vresp->extractStdString();
1697                 new_act.role =  vresp->extractStdString();
1698                 new_act.thumb.width = vresp->extractULONG();
1699                 new_act.thumb.height = vresp->extractULONG();
1700                 new_act.thumb.info.setMovieInfo(movieinf);
1701                 new_act.thumb.info.setElement(4,acty);
1702                 movieinf->actors.push_back(new_act);
1703         }
1704
1705
1706         delete vresp;
1707         return movieinf;
1708
1709 }
1710
1711 SeriesInfo *VDR::getScraperSeriesInfo(int seriesID, int episodeID)
1712 {
1713         VDR_RequestPacket vrp;
1714         if (!vrp.init(VDR_GETSCRAPERSERIESINFO, false, 0)) return NULL;
1715         if (!vrp.addULONG(seriesID)) return NULL;
1716         if (!vrp.addULONG(episodeID)) return NULL;
1717
1718         VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1719         if (vresp->noResponse()) { delete vresp; return 0; }
1720         SeriesInfo * seriesinf= new SeriesInfo();
1721
1722         seriesinf->id=seriesID;
1723
1724
1725         seriesinf->name = vresp->extractStdString();
1726         seriesinf->overview = vresp->extractStdString();
1727         seriesinf->firstAired = vresp->extractStdString();
1728         seriesinf->network = vresp->extractStdString();
1729         seriesinf->genre = vresp->extractStdString();
1730         seriesinf->rating =  vresp->extractdouble();
1731         seriesinf->status = vresp->extractStdString();
1732
1733
1734         seriesinf->episode.episodeid=episodeID;
1735         seriesinf->episode.number = vresp->extractLONG();
1736         seriesinf->episode.season = vresp->extractLONG();
1737         seriesinf->episode.name =  vresp->extractStdString();
1738         seriesinf->episode.firstAired =  vresp->extractStdString();
1739         seriesinf->episode.guestStars =  vresp->extractStdString();
1740         seriesinf->episode.overview =  vresp->extractStdString();
1741         seriesinf->episode.rating = vresp->extractdouble();
1742         seriesinf->episode.image.width =  vresp->extractULONG();
1743         seriesinf->episode.image.height =  vresp->extractULONG();
1744         seriesinf->episode.image.info.setSeriesInfo(seriesinf);
1745         seriesinf->episode.image.info.setElement(0,0);
1746
1747
1748         ULONG num_actors =  vresp->extractULONG();
1749         seriesinf->actors.clear();
1750         seriesinf->actors.reserve(num_actors);
1751         for (ULONG acty=0; acty < num_actors; acty++) {
1752                 Actor new_act;
1753                 new_act.name =  vresp->extractStdString();
1754                 new_act.role =  vresp->extractStdString();
1755                 new_act.thumb.width = vresp->extractULONG();
1756                 new_act.thumb.height = vresp->extractULONG();
1757                 new_act.thumb.info.setSeriesInfo(seriesinf);
1758                 new_act.thumb.info.setElement(1,acty);
1759                 seriesinf->actors.push_back(new_act);
1760         }
1761         ULONG num_posters =  vresp->extractULONG();
1762         for (ULONG medias = 0; medias < num_posters; medias++ ) {
1763                 TVMedia media;
1764                 media.info.setSeriesInfo(seriesinf);
1765                 media.info.setElement(2,medias);
1766                 media.width =  vresp->extractULONG();
1767                 media.height = vresp->extractULONG();
1768                 seriesinf->posters.push_back(media);
1769         }
1770
1771         ULONG num_banners =  vresp->extractULONG();
1772         for (ULONG medias = 0; medias < num_banners; medias++ ) {
1773                 TVMedia media;
1774                 media.info.setSeriesInfo(seriesinf);
1775                 media.info.setElement(3,medias);
1776                 media.width =  vresp->extractULONG();
1777                 media.height = vresp->extractULONG();
1778                 seriesinf->banners.push_back(media);
1779         }
1780         ULONG num_fanarts =  vresp->extractULONG();
1781         for (ULONG medias = 0; medias < num_fanarts; medias++ ) {
1782                 TVMedia media;
1783                 media.info.setSeriesInfo(seriesinf);
1784                 media.info.setElement(4,medias);
1785                 media.width =  vresp->extractULONG();
1786                 media.height = vresp->extractULONG();
1787                 seriesinf->fanart.push_back(media);
1788         }
1789         seriesinf->seasonposter.width = vresp->extractULONG();
1790         seriesinf->seasonposter.height = vresp->extractULONG();
1791         seriesinf->seasonposter.info.setSeriesInfo(seriesinf);
1792         seriesinf->seasonposter.info.setElement(5,0);
1793
1794         delete vresp;
1795         return seriesinf;
1796
1797 }
1798
1799 ULONG VDR::loadTVMedia(TVMediaInfo& tvmedia)
1800 {
1801         VDR_RequestPacket vrp;
1802
1803         if (!vrp.init(VDR_LOADTVMEDIA, false, 0)) return ULONG_MAX;
1804         if (!vrp.addULONG(tvmedia.type)) return ULONG_MAX;
1805         if (!vrp.addULONG(tvmedia.primary_id)) return ULONG_MAX;
1806         if (!vrp.addULONG(tvmedia.secondary_id)) return ULONG_MAX;
1807         if (!vrp.addULONG(tvmedia.type_pict)) return ULONG_MAX;
1808         if (!vrp.addULONG(tvmedia.container)) return ULONG_MAX;
1809         if (!vrp.addULONG(tvmedia.container_member)) return ULONG_MAX;
1810 /*      Log::getInstance()->log("VDR", Log::DEBUG, "TVMedia with ID %d %d; %d %d %d %d;%d",
1811                         tvmedia.primary_id,tvmedia.secondary_id,tvmedia.type,tvmedia.type_pict,
1812                         tvmedia.container,tvmedia.container_member,vrp.getSerial());*/
1813
1814
1815         VDR_PacketReceiver* vdrpr = new VDR_PacketReceiver();
1816         vdrpr->receiverChannel = VDR::CHANNEL_TVMEDIA;
1817         vdrpr->streamID = vrp.getSerial();
1818         vdrpr->streamReceiver = NULL;
1819         edRegister(vdrpr);
1820
1821
1822         VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1823         //if (vresp->noResponse()) { delete vresp; return ULONG_MAX; }
1824         delete vresp;
1825
1826         return vrp.getSerial();
1827 }
1828
1829 ULONG VDR::loadTVMediaRecThumb(TVMediaInfo & media)
1830 {
1831
1832         VDR_RequestPacket vrp;
1833
1834         if (!vrp.init(VDR_LOADTVMEDIARECTHUMB, false, 0)) return ULONG_MAX;
1835         if (!vrp.addString(media.primary_name.c_str())) return ULONG_MAX;
1836
1837         VDR_PacketReceiver* vdrpr = new VDR_PacketReceiver();
1838         vdrpr->receiverChannel = VDR::CHANNEL_TVMEDIA;
1839         vdrpr->streamID = vrp.getSerial();
1840         vdrpr->streamReceiver = NULL;
1841         edRegister(vdrpr);
1842
1843
1844         VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1845         //if (vresp->noResponse()) { delete vresp; return ULONG_MAX; }
1846         delete vresp;
1847
1848         return vrp.getSerial();
1849 }
1850
1851 ULONG VDR::loadTVMediaEventThumb(TVMediaInfo & media)
1852 {
1853
1854         VDR_RequestPacket vrp;
1855
1856         if (!vrp.init(VDR_LOADTVMEDIAEVENTTHUMB, false, 0)) return ULONG_MAX;
1857         if (!vrp.addULONG(media.primary_id)) return ULONG_MAX;
1858         if (!vrp.addULONG(media.secondary_id)) return ULONG_MAX;
1859
1860         VDR_PacketReceiver* vdrpr = new VDR_PacketReceiver();
1861         vdrpr->receiverChannel = VDR::CHANNEL_TVMEDIA;
1862         vdrpr->streamID = vrp.getSerial();
1863         vdrpr->streamReceiver = NULL;
1864         edRegister(vdrpr);
1865
1866
1867         VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1868         //if (vresp->noResponse()) { delete vresp; return ULONG_MAX; }
1869         delete vresp;
1870
1871         return vrp.getSerial();
1872 }
1873
1874 ULONG VDR::loadChannelLogo(TVMediaInfo & media)
1875 {
1876
1877         VDR_RequestPacket vrp;
1878
1879         if (!vrp.init(VDR_LOADCHANNELLOGO, false, 0)) return ULONG_MAX;
1880         if (!vrp.addULONG(media.primary_id)) return ULONG_MAX;
1881
1882         VDR_PacketReceiver* vdrpr = new VDR_PacketReceiver();
1883         vdrpr->receiverChannel = VDR::CHANNEL_TVMEDIA;
1884         vdrpr->streamID = vrp.getSerial();
1885         vdrpr->streamReceiver = NULL;
1886         edRegister(vdrpr);
1887
1888
1889         VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1890         //if (vresp->noResponse()) { delete vresp; return ULONG_MAX; }
1891         delete vresp;
1892
1893 //      Log::getInstance()->log("VDR", Log::DEBUG, "TVMedia Channel Logo %d %x",
1894 //                              media.primary_id,vrp.getSerial());
1895
1896         return vrp.getSerial();
1897 }