Debian Codegraph @

src/pvrclient-mediaportal.cpp

raw
1 /*
2 * Copyright (C) 2005-2021 Team Kodi (https://kodi.tv)
3 *
4 * SPDX-License-Identifier: GPL-2.0-or-later
5 * See LICENSE.md for more information.
6 */
7
8 #include <ctime>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <clocale>
12
13 #include <kodi/tools/StringUtils.h>
14
15 #include "timers.h"
16 #include "channels.h"
17 #include "recordings.h"
18 #include "epg.h"
19 #include "settings.h"
20 #include "utils.h"
21 #include "pvrclient-mediaportal.h"
22 #include "lib/tsreader/TSReader.h"
23 #ifdef TARGET_WINDOWS
24 #include "FileUtils.h"
25 #endif
26 #include "GUIDialogRecordSettings.h"
27
28 #include <kodi/General.h>
29 #include <kodi/Filesystem.h>
30
31 using namespace kodi::tools;
32 using namespace std;
33 using namespace MPTV;
34
35 /* Globals */
36 int g_iTVServerKodiBuild = 0;
37
38 /* TVServerKodi plugin supported versions */
39 #define TVSERVERKODI_MIN_VERSION_STRING "1.1.7.107"
40 #define TVSERVERKODI_MIN_VERSION_BUILD 107
41 #define TVSERVERKODI_RECOMMENDED_VERSION_STRING "1.2.3.122 till 1.20.0.140"
42 #define TVSERVERKODI_RECOMMENDED_VERSION_BUILD 140
43
44 template<typename T> void SafeDelete(T*& p)
45 {
46 if (p)
47 {
48 delete p;
49 p = nullptr;
50 }
51 }
52
53 /************************************************************/
54 /** Class interface */
55
56 cPVRClientMediaPortal::cPVRClientMediaPortal(const kodi::addon::IInstanceInfo& instance) :
57 kodi::addon::CInstancePVRClient(instance),
58 m_state(PVR_CONNECTION_STATE_UNKNOWN)
59 {
60 m_iCurrentChannel = -1;
61 m_bCurrentChannelIsRadio = false;
62 m_iCurrentCard = -1;
63 m_tcpclient = new MPTV::Socket(MPTV::af_unspec, MPTV::pf_inet, MPTV::sock_stream, MPTV::tcp);
64 m_bStop = true;
65 m_bTimeShiftStarted = false;
66 m_bSkipCloseLiveStream = false;
67 m_BackendUTCoffset = 0;
68 m_BackendTime = 0;
69 m_tsreader = NULL;
70 m_genretable = NULL;
71 m_signalStateCounter = 0;
72 m_iSignal = 0;
73 m_iSNR = 0;
74 m_lastSelectedRecording = NULL;
75
76 /* Generate the recording life time strings */
77 Timer::lifetimeValues = new cLifeTimeValues();
78 }
79
80 cPVRClientMediaPortal::~cPVRClientMediaPortal()
81 {
82 kodi::Log(ADDON_LOG_DEBUG, "->~cPVRClientMediaPortal()");
83 Disconnect();
84
85 SafeDelete(Timer::lifetimeValues);
86 SafeDelete(m_tcpclient);
87 SafeDelete(m_genretable);
88 SafeDelete(m_lastSelectedRecording);
89 }
90
91 string cPVRClientMediaPortal::SendCommand(const char* command)
92 {
93 std::string cmd(command);
94 return SendCommand(cmd);
95 }
96
97 string cPVRClientMediaPortal::SendCommand(const string& command)
98 {
99 std::lock_guard<std::mutex> critsec(m_mutex);
100
101 if ( !m_tcpclient->send(command) )
102 {
103 if ( !m_tcpclient->is_valid() )
104 {
105 SetConnectionState(PVR_CONNECTION_STATE_DISCONNECTED);
106
107 // Connection lost, try to reconnect
108 if (TryConnect() == ADDON_STATUS_OK)
109 {
110 // Resend the command
111 if (!m_tcpclient->send(command))
112 {
113 kodi::Log(ADDON_LOG_ERROR, "SendCommand('%s') failed.", command.c_str());
114 return "";
115 }
116 }
117 else
118 {
119 kodi::Log(ADDON_LOG_ERROR, "SendCommand: reconnect failed.");
120 return "";
121 }
122 }
123 }
124
125 string result;
126
127 if ( !m_tcpclient->ReadLine( result ) )
128 {
129 kodi::Log(ADDON_LOG_ERROR, "SendCommand - Failed.");
130 return "";
131 }
132
133 if (result.find("[ERROR]:") != std::string::npos)
134 {
135 kodi::Log(ADDON_LOG_ERROR, "TVServerKodi error: %s", result.c_str());
136 }
137
138 return result;
139 }
140
141
142 bool cPVRClientMediaPortal::SendCommand2(const string& command, vector<string>& lines)
143 {
144 string result = SendCommand(command);
145
146 if (result.empty())
147 {
148 return false;
149 }
150
151 Tokenize(result, lines, ",");
152
153 return true;
154 }
155
156 ADDON_STATUS cPVRClientMediaPortal::TryConnect()
157 {
158 /* Open Connection to MediaPortal Backend TV Server via the TVServerKodi plugin */
159 kodi::Log(ADDON_LOG_INFO, "Mediaportal pvr addon " STR(MPTV_VERSION) " connecting to %s:%i", CSettings::Get().GetHostname().c_str(), CSettings::Get().GetPort());
160
161 PVR_CONNECTION_STATE result = Connect();
162
163 switch (result)
164 {
165 case PVR_CONNECTION_STATE_ACCESS_DENIED:
166 case PVR_CONNECTION_STATE_UNKNOWN:
167 case PVR_CONNECTION_STATE_SERVER_MISMATCH:
168 case PVR_CONNECTION_STATE_VERSION_MISMATCH:
169 return ADDON_STATUS_PERMANENT_FAILURE;
170 case PVR_CONNECTION_STATE_DISCONNECTED:
171 case PVR_CONNECTION_STATE_SERVER_UNREACHABLE:
172 kodi::Log(ADDON_LOG_ERROR, "Could not connect to MediaPortal TV Server backend.");
173 // Start background thread for connecting to the backend
174 if (!m_running)
175 {
176 m_running = true;
177 m_thread = std::thread([&] { Process(); });
178 }
179 return ADDON_STATUS_LOST_CONNECTION;
180 case PVR_CONNECTION_STATE_CONNECTING:
181 case PVR_CONNECTION_STATE_CONNECTED:
182 break;
183 }
184
185 return ADDON_STATUS_OK;
186 }
187
188 PVR_CONNECTION_STATE cPVRClientMediaPortal::Connect(bool updateConnectionState)
189 {
190 std::lock_guard<std::mutex> critsec(m_connectionMutex);
191
192 string result;
193
194 if (!m_tcpclient->create())
195 {
196 kodi::Log(ADDON_LOG_ERROR, "Could not connect create socket");
197 if (updateConnectionState)
198 {
199 SetConnectionState(PVR_CONNECTION_STATE_UNKNOWN);
200 }
201 return PVR_CONNECTION_STATE_UNKNOWN;
202 }
203 if (updateConnectionState)
204 {
205 SetConnectionState(PVR_CONNECTION_STATE_CONNECTING);
206 }
207
208 if (!m_tcpclient->connect(CSettings::Get().GetHostname(), (unsigned short) CSettings::Get().GetPort()))
209 {
210 if (updateConnectionState)
211 {
212 SetConnectionState(PVR_CONNECTION_STATE_SERVER_UNREACHABLE);
213 }
214 return PVR_CONNECTION_STATE_SERVER_UNREACHABLE;
215 }
216
217 m_tcpclient->set_non_blocking(1);
218 kodi::Log(ADDON_LOG_INFO, "Connected to %s:%i", CSettings::Get().GetHostname().c_str(), CSettings::Get().GetPort());
219
220 result = SendCommand("PVRclientXBMC:0-1\n");
221
222 if (result.length() == 0)
223 {
224 if (updateConnectionState)
225 {
226 SetConnectionState(PVR_CONNECTION_STATE_UNKNOWN);
227 }
228 return PVR_CONNECTION_STATE_UNKNOWN;
229 }
230
231 if(result.find("Unexpected protocol") != std::string::npos)
232 {
233 kodi::Log(ADDON_LOG_ERROR, "TVServer does not accept protocol: PVRclientXBMC:0-1");
234 if (updateConnectionState)
235 {
236 SetConnectionState(PVR_CONNECTION_STATE_SERVER_MISMATCH);
237 }
238 return PVR_CONNECTION_STATE_SERVER_MISMATCH;
239 }
240
241 vector<string> fields;
242 int major = 0, minor = 0, revision = 0;
243
244 // Check the version of the TVServerKodi plugin:
245 Tokenize(result, fields, "|");
246 if(fields.size() < 2)
247 {
248 kodi::Log(ADDON_LOG_ERROR, "Your TVServerKodi version is too old. Please upgrade to '%s' or higher!", TVSERVERKODI_MIN_VERSION_STRING);
249 kodi::QueueFormattedNotification(QUEUE_ERROR, kodi::addon::GetLocalizedString(30051).c_str(), TVSERVERKODI_MIN_VERSION_STRING);
250 if (updateConnectionState)
251 {
252 SetConnectionState(PVR_CONNECTION_STATE_VERSION_MISMATCH);
253 }
254 return PVR_CONNECTION_STATE_VERSION_MISMATCH;
255 }
256
257 // Ok, this TVServerKodi version answers with a version string
258 int count = sscanf(fields[1].c_str(), "%5d.%5d.%5d.%5d", &major, &minor, &revision, &g_iTVServerKodiBuild);
259 if( count < 4 )
260 {
261 kodi::Log(ADDON_LOG_ERROR, "Could not parse the TVServerKodi version string '%s'", fields[1].c_str());
262 if (updateConnectionState)
263 {
264 SetConnectionState(PVR_CONNECTION_STATE_VERSION_MISMATCH);
265 }
266 return PVR_CONNECTION_STATE_VERSION_MISMATCH;
267 }
268
269 // Check for the minimal requirement: 1.1.0.70
270 if( g_iTVServerKodiBuild < TVSERVERKODI_MIN_VERSION_BUILD ) //major < 1 || minor < 1 || revision < 0 || build < 70
271 {
272 kodi::Log(ADDON_LOG_ERROR, "Your TVServerKodi version '%s' is too old. Please upgrade to '%s' or higher!", fields[1].c_str(), TVSERVERKODI_MIN_VERSION_STRING);
273 kodi::QueueFormattedNotification(QUEUE_ERROR, kodi::addon::GetLocalizedString(30051).c_str(), fields[1].c_str(), TVSERVERKODI_MIN_VERSION_STRING);
274 if (updateConnectionState)
275 {
276 SetConnectionState(PVR_CONNECTION_STATE_VERSION_MISMATCH);
277 }
278 return PVR_CONNECTION_STATE_VERSION_MISMATCH;
279 }
280 else
281 {
282 kodi::Log(ADDON_LOG_INFO, "Your TVServerKodi version is '%s'", fields[1].c_str());
283
284 // Advice to upgrade:
285 if( g_iTVServerKodiBuild < TVSERVERKODI_RECOMMENDED_VERSION_BUILD )
286 {
287 kodi::Log(ADDON_LOG_INFO, "It is advised to upgrade your TVServerKodi version '%s' to '%s' or higher!", fields[1].c_str(), TVSERVERKODI_RECOMMENDED_VERSION_STRING);
288 }
289 }
290
291 /* Store connection string */
292 char buffer[512];
293 snprintf(buffer, 512, "%s:%i", CSettings::Get().GetHostname().c_str(), CSettings::Get().GetPort());
294 m_ConnectionString = buffer;
295
296 if (updateConnectionState)
297 {
298 SetConnectionState(PVR_CONNECTION_STATE_CONNECTED);
299 }
300
301 /* Load additional settings */
302 LoadGenreTable();
303 LoadCardSettings();
304
305 /* The pvr addon cannot access Kodi's current locale settings, so just use the system default */
306 setlocale(LC_ALL, "");
307
308 return PVR_CONNECTION_STATE_CONNECTED;
309 }
310
311 void cPVRClientMediaPortal::Disconnect()
312 {
313 string result;
314
315 kodi::Log(ADDON_LOG_INFO, "Disconnect");
316
317 if (m_running)
318 {
319 m_running = false;
320 if (m_thread.joinable())
321 m_thread.join();
322 }
323
324 if (m_tcpclient->is_valid() && m_bTimeShiftStarted)
325 {
326 result = SendCommand("IsTimeshifting:\n");
327
328 if (result.find("True") != std::string::npos )
329 {
330 if ((CSettings::Get().GetStreamingMethod()==TSReader) && (m_tsreader != NULL))
331 {
332 m_tsreader->Close();
333 SafeDelete(m_tsreader);
334 }
335 SendCommand("StopTimeshift:\n");
336 }
337 }
338
339 m_bStop = true;
340
341 m_tcpclient->close();
342
343 SetConnectionState(PVR_CONNECTION_STATE_DISCONNECTED);
344 }
345
346 /* IsUp()
347 * \brief Check whether we still have a connection with the TVServer. If not, try
348 * to reconnect
349 * \return True when a connection is available, False when even a reconnect failed
350 */
351 bool cPVRClientMediaPortal::IsUp()
352 {
353 if (m_state == PVR_CONNECTION_STATE_CONNECTED)
354 {
355 return true;
356 }
357 else
358 {
359 return false;
360 }
361 }
362
363 void cPVRClientMediaPortal::Process()
364 {
365 kodi::Log(ADDON_LOG_DEBUG, "Background thread started.");
366
367 bool keepWaiting = true;
368 PVR_CONNECTION_STATE state;
369
370 while (m_running && keepWaiting)
371 {
372 state = Connect(false);
373
374 switch (state)
375 {
376 case PVR_CONNECTION_STATE_ACCESS_DENIED:
377 case PVR_CONNECTION_STATE_UNKNOWN:
378 case PVR_CONNECTION_STATE_SERVER_MISMATCH:
379 case PVR_CONNECTION_STATE_VERSION_MISMATCH:
380 keepWaiting = false;
381 break;
382 case PVR_CONNECTION_STATE_CONNECTED:
383 keepWaiting = false;
384 break;
385 default:
386 break;
387 }
388
389 if (keepWaiting)
390 {
391 // Wait for 1 minute before re-trying
392 std::this_thread::sleep_for(std::chrono::milliseconds(60000));
393 }
394 }
395 SetConnectionState(state);
396
397 kodi::Log(ADDON_LOG_DEBUG, "Background thread finished.");
398 }
399
400
401 /************************************************************/
402 /** General handling */
403
404 PVR_ERROR cPVRClientMediaPortal::GetCapabilities(kodi::addon::PVRCapabilities& capabilities)
405 {
406 kodi::Log(ADDON_LOG_DEBUG, "->GetCapabilities()");
407
408 capabilities.SetSupportsEPG(true);
409 capabilities.SetSupportsEPGEdl(false);
410 capabilities.SetSupportsTV(true);
411 capabilities.SetSupportsRadio(CSettings::Get().GetRadioEnabled());
412 capabilities.SetSupportsRecordings(true);
413 capabilities.SetSupportsRecordingsDelete(true);
414 capabilities.SetSupportsRecordingsUndelete(false);
415 capabilities.SetSupportsTimers(true);
416 capabilities.SetSupportsChannelGroups(true);
417 capabilities.SetSupportsChannelScan(false);
418 capabilities.SetSupportsChannelSettings(false);
419 capabilities.SetHandlesInputStream(true);
420 capabilities.SetHandlesDemuxing(false);
421 capabilities.SetSupportsRecordingPlayCount((g_iTVServerKodiBuild < 117) ? false : true);
422 capabilities.SetSupportsLastPlayedPosition((g_iTVServerKodiBuild < 121) ? false : true);
423 capabilities.SetSupportsRecordingEdl(true);
424 capabilities.SetSupportsRecordingsRename(true);
425 capabilities.SetSupportsRecordingsLifetimeChange(false);
426 capabilities.SetSupportsDescrambleInfo(false);
427 capabilities.SetSupportsAsyncEPGTransfer(false);
428
429 return PVR_ERROR_NO_ERROR;
430 }
431
432 // Used among others for the server name string in the "Recordings" view
433 PVR_ERROR cPVRClientMediaPortal::GetBackendName(std::string& name)
434 {
435 if (!IsUp())
436 {
437 name = CSettings::Get().GetHostname();
438 return PVR_ERROR_NO_ERROR;
439 }
440
441 kodi::Log(ADDON_LOG_DEBUG, "->GetBackendName()");
442
443 if (m_BackendName.length() == 0)
444 {
445 m_BackendName = "MediaPortal TV-server (";
446 m_BackendName += SendCommand("GetBackendName:\n");
447 m_BackendName += ")";
448 }
449
450 name = m_BackendName;
451 return PVR_ERROR_NO_ERROR;
452 }
453
454 PVR_ERROR cPVRClientMediaPortal::GetBackendVersion(std::string& version)
455 {
456 if (!IsUp())
457 return PVR_ERROR_SERVER_ERROR;
458
459 if(m_BackendVersion.length() == 0)
460 {
461 m_BackendVersion = SendCommand("GetVersion:\n");
462 }
463
464 kodi::Log(ADDON_LOG_DEBUG, "GetBackendVersion: %s", m_BackendVersion.c_str());
465
466 version = m_BackendVersion;
467 return PVR_ERROR_NO_ERROR;
468 }
469
470 PVR_ERROR cPVRClientMediaPortal::GetConnectionString(std::string& connection)
471 {
472 if (m_ConnectionString.empty())
473 return PVR_ERROR_NO_ERROR;
474
475 kodi::Log(ADDON_LOG_DEBUG, "GetConnectionString: %s", m_ConnectionString.c_str());
476 connection = m_ConnectionString;
477 return PVR_ERROR_NO_ERROR;
478 }
479
480 PVR_ERROR cPVRClientMediaPortal::GetDriveSpace(uint64_t& total, uint64_t& used)
481 {
482 string result;
483 vector<string> fields;
484
485 total = 0;
486 used = 0;
487
488 if (!IsUp())
489 return PVR_ERROR_SERVER_ERROR;
490
491 result = SendCommand("GetDriveSpace:\n");
492
493 Tokenize(result, fields, "|");
494
495 if(fields.size() >= 2)
496 {
497 total = std::stoll(fields[0]);
498 used = std::stoll(fields[1]);
499 }
500
501 return PVR_ERROR_NO_ERROR;
502 }
503
504 PVR_ERROR cPVRClientMediaPortal::GetBackendTime(time_t *localTime, int *gmtOffset)
505 {
506 string result;
507 vector<string> fields;
508 int year = 0, month = 0, day = 0;
509 int hour = 0, minute = 0, second = 0;
510 struct tm timeinfo;
511
512 if (!IsUp())
513 return PVR_ERROR_SERVER_ERROR;
514
515 result = SendCommand("GetTime:\n");
516
517 if (result.length() == 0)
518 return PVR_ERROR_SERVER_ERROR;
519
520 Tokenize(result, fields, "|");
521
522 if(fields.size() >= 3)
523 {
524 //[0] date + time TV Server
525 //[1] UTC offset hours
526 //[2] UTC offset minutes
527 //From CPVREpg::CPVREpg(): Expected PVREpg GMT offset is in seconds
528 m_BackendUTCoffset = ((atoi(fields[1].c_str()) * 60) + atoi(fields[2].c_str())) * 60;
529
530 int count = sscanf(fields[0].c_str(), "%4d-%2d-%2d %2d:%2d:%2d", &year, &month, &day, &hour, &minute, &second);
531
532 if(count == 6)
533 {
534 //timeinfo = *localtime ( &rawtime );
535 kodi::Log(ADDON_LOG_DEBUG, "GetMPTVTime: time from MP TV Server: %d-%d-%d %d:%d:%d, offset %d seconds", year, month, day, hour, minute, second, m_BackendUTCoffset );
536 timeinfo.tm_hour = hour;
537 timeinfo.tm_min = minute;
538 timeinfo.tm_sec = second;
539 timeinfo.tm_year = year - 1900;
540 timeinfo.tm_mon = month - 1;
541 timeinfo.tm_mday = day;
542 timeinfo.tm_isdst = -1; //Actively determines whether DST is in effect from the specified time and the local time zone.
543 // Make the other fields empty:
544 timeinfo.tm_wday = 0;
545 timeinfo.tm_yday = 0;
546
547 m_BackendTime = mktime(&timeinfo);
548
549 if(m_BackendTime < 0)
550 {
551 kodi::Log(ADDON_LOG_DEBUG, "GetMPTVTime: Unable to convert string '%s' into date+time", fields[0].c_str());
552 return PVR_ERROR_SERVER_ERROR;
553 }
554
555 kodi::Log(ADDON_LOG_DEBUG, "GetMPTVTime: localtime %s", asctime(localtime(&m_BackendTime)));
556 kodi::Log(ADDON_LOG_DEBUG, "GetMPTVTime: gmtime %s", asctime(gmtime(&m_BackendTime)));
557
558 *localTime = m_BackendTime;
559 *gmtOffset = m_BackendUTCoffset;
560 return PVR_ERROR_NO_ERROR;
561 }
562 else
563 {
564 return PVR_ERROR_SERVER_ERROR;
565 }
566 }
567 else
568 return PVR_ERROR_SERVER_ERROR;
569 }
570
571 /************************************************************/
572 /** EPG handling */
573
574 namespace
575 {
576
577 std::string ParseAsW3CDateString(time_t time)
578 {
579 std::tm* tm = std::localtime(&time);
580 char buffer[16];
581 std::strftime(buffer, 16, "%Y-%m-%d", tm);
582
583 return buffer;
584 }
585
586 } // unnamed namespace
587
588 PVR_ERROR cPVRClientMediaPortal::GetEPGForChannel(int channelUid, time_t start, time_t end, kodi::addon::PVREPGTagsResultSet& results)
589 {
590 vector<string> lines;
591 char command[256];
592 string result;
593 cEpg epg;
594 struct tm starttime;
595 struct tm endtime;
596
597 starttime = *gmtime( &start );
598 endtime = *gmtime( &end );
599
600 if (!IsUp())
601 return PVR_ERROR_SERVER_ERROR;
602
603 // Request (extended) EPG data for the given period
604 snprintf(command, 256, "GetEPG:%i|%04d-%02d-%02dT%02d:%02d:%02d.0Z|%04d-%02d-%02dT%02d:%02d:%02d.0Z\n",
605 channelUid, //Channel id
606 starttime.tm_year + 1900, starttime.tm_mon + 1, starttime.tm_mday, //Start date [2..4]
607 starttime.tm_hour, starttime.tm_min, starttime.tm_sec, //Start time [5..7]
608 endtime.tm_year + 1900, endtime.tm_mon + 1, endtime.tm_mday, //End date [8..10]
609 endtime.tm_hour, endtime.tm_min, endtime.tm_sec); //End time [11..13]
610
611 result = SendCommand(command);
612 if(result.compare(0,5, "ERROR") != 0)
613 {
614 if( result.length() != 0)
615 {
616 epg.SetGenreTable(m_genretable);
617
618 Tokenize(result, lines, ",");
619
620 kodi::Log(ADDON_LOG_DEBUG, "Found %i EPG items for channel %i\n", lines.size(), channelUid);
621
622 for (vector<string>::iterator it = lines.begin(); it < lines.end(); ++it)
623 {
624 string& data(*it);
625
626 if( data.length() > 0)
627 {
628 uri::decode(data);
629
630 bool isEnd = epg.ParseLine(data);
631
632 if (isEnd && epg.StartTime() != 0)
633 {
634 kodi::addon::PVREPGTag broadcast;
635
636 broadcast.SetUniqueBroadcastId(epg.UniqueId());
637 broadcast.SetTitle(epg.Title());
638 broadcast.SetUniqueChannelId(channelUid);
639 broadcast.SetStartTime(epg.StartTime());
640 broadcast.SetEndTime(epg.EndTime());
641 broadcast.SetPlotOutline(epg.PlotOutline());
642 broadcast.SetPlot(epg.Description());
643 broadcast.SetIconPath("");
644 broadcast.SetGenreType(epg.GenreType());
645 broadcast.SetGenreSubType(epg.GenreSubType());
646 broadcast.SetGenreDescription(epg.Genre());
647 std::string strFirstAired(epg.OriginalAirDate() > 0 ? ParseAsW3CDateString(epg.OriginalAirDate()) : "");
648 broadcast.SetFirstAired(strFirstAired.c_str());
649 broadcast.SetParentalRating(epg.ParentalRating());
650 broadcast.SetStarRating(epg.StarRating());
651 broadcast.SetSeriesNumber(epg.SeriesNumber());
652 broadcast.SetEpisodeNumber(epg.EpisodeNumber());
653 broadcast.SetEpisodePartNumber(atoi(epg.EpisodePart()));
654 broadcast.SetEpisodeName(epg.EpisodeName());
655 broadcast.SetFlags(EPG_TAG_FLAG_UNDEFINED);
656
657 results.Add(broadcast);
658 }
659 epg.Reset();
660 }
661 }
662 }
663 else
664 {
665 kodi::Log(ADDON_LOG_DEBUG, "No EPG items found for channel %i", channelUid);
666 }
667 }
668 else
669 {
670 kodi::Log(ADDON_LOG_DEBUG, "RequestEPGForChannel(%i) %s", channelUid, result.c_str());
671 }
672
673 return PVR_ERROR_NO_ERROR;
674 }
675
676
677 /************************************************************/
678 /** Channel handling */
679
680 PVR_ERROR cPVRClientMediaPortal::GetChannelsAmount(int& amount)
681 {
682 string result;
683
684 if (!IsUp())
685 return PVR_ERROR_SERVER_ERROR;
686
687 // Get the total channel count (radio+tv)
688 // It is only used to check whether Kodi should request the channel list
689 result = SendCommand("GetChannelCount:\n");
690
691 amount = atol(result.c_str());
692 return PVR_ERROR_NO_ERROR;
693 }
694
695 PVR_ERROR cPVRClientMediaPortal::GetChannels(bool radio, kodi::addon::PVRChannelsResultSet& results)
696 {
697 vector<string> lines;
698 std::string command;
699 const char * baseCommand;
700 std::string stream;
701 std::string groups;
702
703 if (!IsUp())
704 return PVR_ERROR_SERVER_ERROR;
705
706 if(radio)
707 {
708 if(!CSettings::Get().GetRadioEnabled())
709 {
710 kodi::Log(ADDON_LOG_INFO, "Fetching radio channels is disabled.");
711 return PVR_ERROR_NO_ERROR;
712 }
713
714 baseCommand = "ListRadioChannels";
715 if (CSettings::Get().GetRadioGroup().empty())
716 {
717 kodi::Log(ADDON_LOG_DEBUG, "GetChannels(radio) all channels");
718 }
719 else
720 {
721 kodi::Log(ADDON_LOG_DEBUG, "GetChannels(radio) for radio group(s): '%s'", CSettings::Get().GetRadioGroup().c_str());
722 groups = uri::encode(uri::PATH_TRAITS, CSettings::Get().GetRadioGroup());
723 StringUtils::Replace(groups, "%7C","|");
724 }
725 }
726 else
727 {
728 baseCommand = "ListTVChannels";
729 if (CSettings::Get().GetTVGroup().empty())
730 {
731 kodi::Log(ADDON_LOG_DEBUG, "GetChannels(tv) all channels");
732 }
733 else
734 {
735 kodi::Log(ADDON_LOG_DEBUG, "GetChannels(tv) for TV group(s): '%s'", CSettings::Get().GetTVGroup().c_str());
736 groups = uri::encode(uri::PATH_TRAITS, CSettings::Get().GetTVGroup());
737 StringUtils::Replace(groups, "%7C","|");
738 }
739 }
740
741 if (groups.empty())
742 command = StringUtils::Format("%s\n", baseCommand);
743 else
744 command = StringUtils::Format("%s:%s\n", baseCommand, groups.c_str());
745
746 if( !SendCommand2(command, lines) )
747 return PVR_ERROR_SERVER_ERROR;
748
749 #ifdef TARGET_WINDOWS_DESKTOP
750 bool bCheckForThumbs = false;
751 /* Check if we can find the MediaPortal channel logo folders on this machine */
752 std::string strThumbPath;
753 std::string strProgramData;
754
755 if (OS::GetProgramData(strProgramData) == true)
756 {
757 strThumbPath = strProgramData + "\\Team MediaPortal\\MediaPortal\\Thumbs\\";
758 if (radio)
759 strThumbPath += "Radio\\";
760 else
761 strThumbPath += "TV\\logos\\";
762
763 bCheckForThumbs = OS::CFile::Exists(strThumbPath);
764 }
765 #endif // TARGET_WINDOWS_DESKTOP
766
767
768 for (vector<string>::iterator it = lines.begin(); it < lines.end(); ++it)
769 {
770 string& data(*it);
771
772 if (data.length() == 0)
773 {
774 if(radio)
775 kodi::Log(ADDON_LOG_DEBUG, "TVServer returned no data. Empty/non existing radio group '%s'?", CSettings::Get().GetRadioGroup().c_str());
776 else
777 kodi::Log(ADDON_LOG_DEBUG, "TVServer returned no data. Empty/non existing tv group '%s'?", CSettings::Get().GetTVGroup().c_str());
778 break;
779 }
780
781 uri::decode(data);
782
783 cChannel channel;
784 if( channel.Parse(data) )
785 {
786 // Cache this channel in our local uid-channel list
787 // This cache is used for the GUIDialogRecordSettings
788 m_channels[channel.UID()] = channel;
789
790 kodi::addon::PVRChannel tag;
791
792 // Prepare the PVR_CHANNEL struct to transfer this channel to Kodi
793 tag.SetUniqueId(channel.UID());
794 if (channel.MajorChannelNr() == -1)
795 {
796 tag.SetChannelNumber(channel.ExternalID());
797 }
798 else
799 {
800 tag.SetChannelNumber(channel.MajorChannelNr());
801 tag.SetSubChannelNumber(channel.MinorChannelNr());
802 }
803 tag.SetChannelName(channel.Name());
804 tag.SetIconPath("");
805 #ifdef TARGET_WINDOWS_DESKTOP
806 if (bCheckForThumbs)
807 {
808 const int ciExtCount = 5;
809 string strIconExt [ciExtCount] = { ".png", ".jpg", ".jpeg", ".bmp", ".gif" };
810 string strIconName;
811 string strIconBaseName;
812
813 kodi::Log(ADDON_LOG_DEBUG, "Checking for a channel thumbnail for channel %s in %s", channel.Name(), strThumbPath.c_str());
814
815 strIconBaseName = strThumbPath + ToThumbFileName(channel.Name());
816
817 for (int i=0; i < ciExtCount; i++)
818 {
819 strIconName = strIconBaseName + strIconExt[i];
820 if ( OS::CFile::Exists(strIconName) )
821 {
822 tag.SetIconPath(strIconName);
823 kodi::Log(ADDON_LOG_DEBUG, "Found channel thumb: %s", tag.GetIconPath().c_str());
824 break;
825 }
826 }
827 }
828 #endif
829 tag.SetEncryptionSystem(channel.Encrypted());
830 tag.SetIsRadio(radio);
831 tag.SetIsHidden(!channel.VisibleInGuide());
832
833 if(channel.IsWebstream())
834 {
835 kodi::Log(ADDON_LOG_DEBUG, "Channel '%s' has a webstream: %s. TODO fixme.", channel.Name(), channel.URL());
836 tag.SetMimeType("");
837 }
838 else
839 {
840 if (CSettings::Get().GetStreamingMethod()==TSReader)
841 {
842 // TSReader
843 //Use OpenLiveStream to read from the timeshift .ts file or an rtsp stream
844 if (!radio)
845 tag.SetMimeType("video/mp2t");
846 else
847 tag.SetMimeType("");
848 }
849 else
850 {
851 //Use GetLiveStreamURL to fetch an rtsp stream
852 kodi::Log(ADDON_LOG_DEBUG, "Channel '%s' has a rtsp stream: %s. TODO fixme.", channel.Name(), channel.URL());
853 tag.SetMimeType("");
854 }
855 }
856
857 if( (!CSettings::Get().GetOnlyFTA()) || (tag.GetEncryptionSystem()==0))
858 {
859 results.Add(tag);
860 }
861 }
862 }
863
864 //pthread_mutex_unlock(&m_critSection);
865 return PVR_ERROR_NO_ERROR;
866 }
867
868 /************************************************************/
869 /** Channel group handling **/
870
871 PVR_ERROR cPVRClientMediaPortal::GetChannelGroupsAmount(int& amount)
872 {
873 // Not directly possible at the moment
874 kodi::Log(ADDON_LOG_DEBUG, "GetChannelGroupsAmount: TODO");
875
876 if (!IsUp())
877 return PVR_ERROR_SERVER_ERROR;
878
879 // just tell Kodi that we have groups
880 amount = 1;
881 return PVR_ERROR_NO_ERROR;
882 }
883
884 PVR_ERROR cPVRClientMediaPortal::GetChannelGroups(bool radio, kodi::addon::PVRChannelGroupsResultSet& results)
885 {
886 vector<string> lines;
887 std::string filters;
888
889 if (!IsUp())
890 return PVR_ERROR_SERVER_ERROR;
891
892 if(radio)
893 {
894 if (!CSettings::Get().GetRadioEnabled())
895 {
896 kodi::Log(ADDON_LOG_DEBUG, "Skipping GetChannelGroups for radio. Radio support is disabled.");
897 return PVR_ERROR_NO_ERROR;
898 }
899
900 filters = CSettings::Get().GetRadioGroup();
901
902 kodi::Log(ADDON_LOG_DEBUG, "GetChannelGroups for radio");
903 if (!SendCommand2("ListRadioGroups\n", lines))
904 return PVR_ERROR_SERVER_ERROR;
905 }
906 else
907 {
908 filters = CSettings::Get().GetTVGroup();
909
910 kodi::Log(ADDON_LOG_DEBUG, "GetChannelGroups for TV");
911 if (!SendCommand2("ListGroups\n", lines))
912 return PVR_ERROR_SERVER_ERROR;
913 }
914
915 for (vector<string>::iterator it = lines.begin(); it < lines.end(); ++it)
916 {
917 string& data(*it);
918
919 if (data.length() == 0)
920 {
921 kodi::Log(ADDON_LOG_DEBUG, "TVServer returned no data. No %s groups found?", ((radio) ? "radio" : "tv"));
922 break;
923 }
924
925 uri::decode(data);
926
927 if (data.compare("All Channels") == 0)
928 {
929 kodi::Log(ADDON_LOG_DEBUG, "Skipping All Channels (%s) group", ((radio) ? "radio" : "tv"));
930 }
931 else
932 {
933 if (!filters.empty())
934 {
935 if (filters.find(data.c_str()) == string::npos)
936 {
937 // Skip this backend group. It is not in our filter list
938 continue;
939 }
940 }
941
942 kodi::addon::PVRChannelGroup tag;
943 tag.SetIsRadio(radio);
944 tag.SetGroupName(data);
945 kodi::Log(ADDON_LOG_DEBUG, "Adding %s group: %s", ((radio) ? "radio" : "tv"), tag.GetGroupName().c_str());
946 results.Add(tag);
947 }
948 }
949
950 return PVR_ERROR_NO_ERROR;
951 }
952
953 PVR_ERROR cPVRClientMediaPortal::GetChannelGroupMembers(const kodi::addon::PVRChannelGroup& group, kodi::addon::PVRChannelGroupMembersResultSet& results)
954 {
955 //TODO: code below is similar to GetChannels code. Refactor and combine...
956 vector<string> lines;
957 std::string command;
958
959 if (!IsUp())
960 return PVR_ERROR_SERVER_ERROR;
961
962 if (group.GetIsRadio())
963 {
964 if (CSettings::Get().GetRadioEnabled())
965 {
966 kodi::Log(ADDON_LOG_DEBUG, "GetChannelGroupMembers: for radio group '%s'", group.GetGroupName().c_str());
967 command = StringUtils::Format("ListRadioChannels:%s\n", uri::encode(uri::PATH_TRAITS, group.GetGroupName()).c_str());
968 }
969 else
970 {
971 kodi::Log(ADDON_LOG_DEBUG, "Skipping GetChannelGroupMembers for radio. Radio support is disabled.");
972 return PVR_ERROR_NO_ERROR;
973 }
974 }
975 else
976 {
977 kodi::Log(ADDON_LOG_DEBUG, "GetChannelGroupMembers: for tv group '%s'", group.GetGroupName().c_str());
978 command = StringUtils::Format("ListTVChannels:%s\n", uri::encode(uri::PATH_TRAITS, group.GetGroupName()).c_str());
979 }
980
981 if (!SendCommand2(command, lines))
982 return PVR_ERROR_SERVER_ERROR;
983
984 for (vector<string>::iterator it = lines.begin(); it < lines.end(); ++it)
985 {
986 string& data(*it);
987
988 if (data.length() == 0)
989 {
990 if(group.GetIsRadio())
991 kodi::Log(ADDON_LOG_DEBUG, "TVServer returned no data. Empty/non existing radio group '%s'?", CSettings::Get().GetRadioGroup().c_str());
992 else
993 kodi::Log(ADDON_LOG_DEBUG, "TVServer returned no data. Empty/non existing tv group '%s'?", CSettings::Get().GetTVGroup().c_str());
994 break;
995 }
996
997 uri::decode(data);
998
999 cChannel channel;
1000 if( channel.Parse(data) )
1001 {
1002 kodi::addon::PVRChannelGroupMember tag;
1003
1004 tag.SetChannelUniqueId(channel.UID());
1005 if (channel.MajorChannelNr() == -1)
1006 {
1007 tag.SetChannelNumber(channel.ExternalID());
1008 }
1009 else
1010 {
1011 tag.SetChannelNumber(channel.MajorChannelNr());
1012 tag.SetSubChannelNumber(channel.MinorChannelNr());
1013 }
1014 tag.SetGroupName(group.GetGroupName());
1015
1016
1017 // Don't add encrypted channels when FTA only option is turned on
1018 if( (!CSettings::Get().GetOnlyFTA()) || (channel.Encrypted()==false))
1019 {
1020 kodi::Log(ADDON_LOG_DEBUG, "GetChannelGroupMembers: add channel %s to group '%s' (Backend channel uid=%d, channelnr=%d)",
1021 channel.Name(), group.GetGroupName().c_str(), tag.GetChannelUniqueId(), tag.GetChannelNumber());
1022 results.Add(tag);
1023 }
1024 }
1025 }
1026
1027 return PVR_ERROR_NO_ERROR;
1028 }
1029
1030 /************************************************************/
1031 /** Record handling **/
1032
1033 PVR_ERROR cPVRClientMediaPortal::GetRecordingsAmount(bool deleted, int& amount)
1034 {
1035 string result;
1036
1037 if (!IsUp())
1038 return PVR_ERROR_SERVER_ERROR;
1039
1040 result = SendCommand("GetRecordingCount:\n");
1041
1042 amount = atol(result.c_str());
1043 return PVR_ERROR_NO_ERROR;
1044 }
1045
1046 PVR_ERROR cPVRClientMediaPortal::GetRecordings(bool deleted, kodi::addon::PVRRecordingsResultSet& results)
1047 {
1048 vector<string> lines;
1049 string result;
1050
1051 if (!IsUp())
1052 return PVR_ERROR_SERVER_ERROR;
1053
1054 if(CSettings::Get().GetResolveRTSPHostname() == false)
1055 {
1056 result = SendCommand("ListRecordings:False\n");
1057 }
1058 else
1059 {
1060 result = SendCommand("ListRecordings\n");
1061 }
1062
1063 if( result.length() == 0 )
1064 {
1065 kodi::Log(ADDON_LOG_DEBUG, "Backend returned no recordings" );
1066 return PVR_ERROR_NO_ERROR;
1067 }
1068
1069 Tokenize(result, lines, ",");
1070
1071 for (vector<string>::iterator it = lines.begin(); it != lines.end(); ++it)
1072 {
1073 string& data(*it);
1074 uri::decode(data);
1075
1076 kodi::Log(ADDON_LOG_DEBUG, "RECORDING: %s", data.c_str() );
1077
1078 std::string strRecordingId;
1079 std::string strDirectory;
1080 std::string strEpisodeName;
1081 cRecording recording;
1082
1083 recording.SetCardSettings(&m_cCards);
1084 recording.SetGenreTable(m_genretable);
1085
1086 if (recording.ParseLine(data))
1087 {
1088 strRecordingId = StringUtils::Format("%i", recording.Index());
1089 strEpisodeName = recording.EpisodeName();
1090
1091 kodi::addon::PVRRecording tag;
1092
1093 tag.SetRecordingId(strRecordingId);
1094 tag.SetTitle(recording.Title());
1095 tag.SetEpisodeName(recording.EpisodeName());
1096 tag.SetPlot(recording.Description());
1097 tag.SetChannelName(recording.ChannelName());
1098 tag.SetChannelUid(recording.ChannelID());
1099 tag.SetRecordingTime(recording.StartTime());
1100 tag.SetDuration((int) recording.Duration());
1101 tag.SetPriority(0); // only available for schedules, not for recordings
1102 tag.SetLifetime(recording.Lifetime());
1103 tag.SetGenreType(recording.GenreType());
1104 tag.SetGenreSubType(recording.GenreSubType());
1105 tag.SetGenreDescription(recording.GetGenre());
1106 tag.SetPlayCount(recording.TimesWatched());
1107 tag.SetLastPlayedPosition(recording.LastPlayedPosition());
1108 tag.SetEpisodeNumber(recording.GetEpisodeNumber());
1109 tag.SetSeriesNumber(recording.GetSeriesNumber());
1110 tag.SetEPGEventId(EPG_TAG_INVALID_UID);
1111 tag.SetChannelType(recording.GetChannelType());
1112
1113 strDirectory = recording.Directory();
1114 if (strDirectory.length() > 0)
1115 {
1116 StringUtils::Replace(strDirectory, "\\", " - "); // Kodi supports only 1 sublevel below Recordings, so flatten the MediaPortal directory structure
1117 tag.SetDirectory(strDirectory); // used in Kodi as directory structure below "Recordings"
1118 if ((StringUtils::EqualsNoCase(strDirectory, tag.GetTitle())) && (strEpisodeName.length() > 0))
1119 {
1120 strEpisodeName = recording.Title();
1121 strEpisodeName+= " - ";
1122 strEpisodeName+= recording.EpisodeName();
1123 tag.SetTitle(strEpisodeName);
1124 }
1125 }
1126 else
1127 {
1128 tag.SetDirectory("");
1129 }
1130
1131 tag.SetThumbnailPath("");
1132
1133 #ifdef TARGET_WINDOWS_DESKTOP
1134 std::string recordingUri(ToKodiPath(recording.FilePath()));
1135 if (CSettings::Get().GetUseRTSP() == false)
1136 {
1137 /* Recording thumbnail */
1138 std::string strThumbnailName(recordingUri);
1139 StringUtils::Replace(strThumbnailName, ".ts", ".jpg");
1140 /* Check if it exists next to the recording */
1141 if (kodi::vfs::FileExists(strThumbnailName, false))
1142 {
1143 tag.SetThumbnailPath(strThumbnailName);
1144 }
1145 else
1146 {
1147 /* Check also: C:\ProgramData\Team MediaPortal\MediaPortal TV Server\thumbs */
1148 std::string strThumbnailFilename = recording.FileName();
1149 StringUtils::Replace(strThumbnailFilename, ".ts", ".jpg");
1150 std::string strProgramData;
1151 if (OS::GetProgramData(strProgramData))
1152 {
1153 /* MediaPortal 1 */
1154 strThumbnailName = strProgramData +
1155 "\\Team MediaPortal\\MediaPortal TV Server\\thumbs\\" +
1156 strThumbnailFilename;
1157 if (kodi::vfs::FileExists(strThumbnailName, false))
1158 {
1159 tag.SetThumbnailPath(strThumbnailName);
1160 }
1161 else
1162 {
1163 /* MediaPortal 2 */
1164 strThumbnailName = strProgramData +
1165 "\\Team MediaPortal\\MP2-Server\\SlimTVCore\\v3.0\\thumbs\\" +
1166 strThumbnailFilename;
1167 if (kodi::vfs::FileExists(strThumbnailName, false))
1168 {
1169 tag.SetThumbnailPath(strThumbnailName);
1170 }
1171 }
1172 }
1173 else
1174 tag.SetThumbnailPath("");
1175 }
1176 }
1177 #endif /* TARGET_WINDOWS_DESKTOP */
1178
1179 if (CSettings::Get().GetStreamingMethod()!=TSReader)
1180 {
1181 // Use rtsp url and Kodi's internal FFMPeg playback
1182 kodi::Log(ADDON_LOG_DEBUG, "Recording '%s' has a rtsp url '%s'. TODO Fix me. ", recording.Title(), recording.Stream());
1183 }
1184
1185 results.Add(tag);
1186 }
1187 }
1188
1189 m_iLastRecordingUpdate = std::chrono::system_clock::now();
1190
1191 return PVR_ERROR_NO_ERROR;
1192 }
1193
1194 PVR_ERROR cPVRClientMediaPortal::DeleteRecording(const kodi::addon::PVRRecording& recording)
1195 {
1196 char command[1200];
1197 string result;
1198
1199 if (!IsUp())
1200 return PVR_ERROR_SERVER_ERROR;
1201
1202 snprintf(command, 1200, "DeleteRecordedTV:%s\n", recording.GetRecordingId().c_str());
1203
1204 result = SendCommand(command);
1205
1206 if(result.find("True") == string::npos)
1207 {
1208 kodi::Log(ADDON_LOG_ERROR, "Deleting recording %s [failed]", recording.GetRecordingId().c_str());
1209 return PVR_ERROR_FAILED;
1210 }
1211 kodi::Log(ADDON_LOG_DEBUG, "Deleting recording %s [done]", recording.GetRecordingId().c_str());
1212
1213 // Although Kodi initiates the deletion of this recording, we still have to trigger Kodi to update its
1214 // recordings list to remove the recording at the Kodi side
1215 kodi::addon::CInstancePVRClient::TriggerRecordingUpdate();
1216
1217 return PVR_ERROR_NO_ERROR;
1218 }
1219
1220 PVR_ERROR cPVRClientMediaPortal::RenameRecording(const kodi::addon::PVRRecording& recording)
1221 {
1222 char command[1200];
1223 string result;
1224
1225 if (!IsUp())
1226 return PVR_ERROR_SERVER_ERROR;
1227
1228 snprintf(command, 1200, "UpdateRecording:%s|%s\n",
1229 recording.GetRecordingId().c_str(),
1230 uri::encode(uri::PATH_TRAITS, recording.GetTitle()).c_str());
1231
1232 result = SendCommand(command);
1233
1234 if(result.find("True") == string::npos)
1235 {
1236 kodi::Log(ADDON_LOG_ERROR, "RenameRecording(%s) to %s [failed]", recording.GetRecordingId().c_str(), recording.GetTitle().c_str());
1237 return PVR_ERROR_FAILED;
1238 }
1239 kodi::Log(ADDON_LOG_DEBUG, "RenameRecording(%s) to %s [done]", recording.GetRecordingId().c_str(), recording.GetTitle().c_str());
1240
1241 // Although Kodi initiates the rename of this recording, we still have to trigger Kodi to update its
1242 // recordings list to see the renamed recording at the Kodi side
1243 kodi::addon::CInstancePVRClient::TriggerRecordingUpdate();
1244
1245 return PVR_ERROR_NO_ERROR;
1246 }
1247
1248 PVR_ERROR cPVRClientMediaPortal::SetRecordingPlayCount(const kodi::addon::PVRRecording& recording, int count)
1249 {
1250 if ( g_iTVServerKodiBuild < 117 )
1251 return PVR_ERROR_NOT_IMPLEMENTED;
1252
1253 if (!IsUp())
1254 return PVR_ERROR_SERVER_ERROR;
1255
1256 char command[512];
1257 string result;
1258
1259 snprintf(command, 512, "SetRecordingTimesWatched:%i|%i\n", std::atoi(recording.GetRecordingId().c_str()), count);
1260
1261 result = SendCommand(command);
1262
1263 if(result.find("True") == string::npos)
1264 {
1265 kodi::Log(ADDON_LOG_ERROR, "%s: id=%s to %i [failed]", __FUNCTION__, recording.GetRecordingId().c_str(), count);
1266 return PVR_ERROR_FAILED;
1267 }
1268
1269 kodi::Log(ADDON_LOG_DEBUG, "%s: id=%s to %i [successful]", __FUNCTION__, recording.GetRecordingId().c_str(), count);
1270 kodi::addon::CInstancePVRClient::TriggerRecordingUpdate();
1271
1272 return PVR_ERROR_NO_ERROR;
1273 }
1274
1275 PVR_ERROR cPVRClientMediaPortal::SetRecordingLastPlayedPosition(const kodi::addon::PVRRecording& recording, int lastplayedposition)
1276 {
1277 if ( g_iTVServerKodiBuild < 121 )
1278 return PVR_ERROR_NOT_IMPLEMENTED;
1279
1280 if (!IsUp())
1281 return PVR_ERROR_SERVER_ERROR;
1282
1283 char command[512];
1284 string result;
1285
1286 if (lastplayedposition < 0)
1287 {
1288 lastplayedposition = 0;
1289 }
1290
1291 snprintf(command, 512, "SetRecordingStopTime:%i|%i\n", std::atoi(recording.GetRecordingId().c_str()), lastplayedposition);
1292
1293 result = SendCommand(command);
1294
1295 if(result.find("True") == string::npos)
1296 {
1297 kodi::Log(ADDON_LOG_ERROR, "%s: id=%s to %i [failed]", __FUNCTION__, recording.GetRecordingId().c_str(), lastplayedposition);
1298 return PVR_ERROR_FAILED;
1299 }
1300
1301 kodi::Log(ADDON_LOG_DEBUG, "%s: id=%s to %i [successful]", __FUNCTION__, recording.GetRecordingId().c_str(), lastplayedposition);
1302 kodi::addon::CInstancePVRClient::TriggerRecordingUpdate();
1303
1304 return PVR_ERROR_NO_ERROR;
1305 }
1306
1307 PVR_ERROR cPVRClientMediaPortal::GetRecordingLastPlayedPosition(const kodi::addon::PVRRecording& recording, int& position)
1308 {
1309 if ( g_iTVServerKodiBuild < 121 )
1310 return PVR_ERROR_NOT_IMPLEMENTED;
1311
1312 if (!IsUp())
1313 return PVR_ERROR_SERVER_ERROR;
1314
1315 char command[512];
1316 string result;
1317
1318 snprintf(command, 512, "GetRecordingStopTime:%i\n", std::atoi(recording.GetRecordingId().c_str()));
1319
1320 result = SendCommand(command);
1321
1322 if(result.find("-1") != string::npos)
1323 {
1324 kodi::Log(ADDON_LOG_ERROR, "%s: id=%s fetching stoptime [failed]", __FUNCTION__, recording.GetRecordingId().c_str());
1325 return PVR_ERROR_UNKNOWN;
1326 }
1327
1328 position = std::atoi(result.c_str());
1329
1330 kodi::Log(ADDON_LOG_DEBUG, "%s: id=%s stoptime=%i {s} [successful]", __FUNCTION__, recording.GetRecordingId().c_str(), position);
1331
1332 return PVR_ERROR_NO_ERROR;
1333 }
1334
1335 /************************************************************/
1336 /** Timer handling */
1337
1338 PVR_ERROR cPVRClientMediaPortal::GetTimersAmount(int& amount)
1339 {
1340 string result;
1341
1342 if (!IsUp())
1343 return PVR_ERROR_SERVER_ERROR;
1344
1345 result = SendCommand("GetScheduleCount:\n");
1346
1347 amount = std::stol(result);
1348 return PVR_ERROR_NO_ERROR;
1349 }
1350
1351 PVR_ERROR cPVRClientMediaPortal::GetTimers(kodi::addon::PVRTimersResultSet& results)
1352 {
1353 vector<string> lines;
1354 string result;
1355
1356 if (!IsUp())
1357 return PVR_ERROR_SERVER_ERROR;
1358
1359 result = SendCommand("ListSchedules:True\n");
1360
1361 if (result.length() > 0)
1362 {
1363 Tokenize(result, lines, ",");
1364
1365 for (vector<string>::iterator it = lines.begin(); it != lines.end(); ++it)
1366 {
1367 string& data(*it);
1368 uri::decode(data);
1369
1370 kodi::Log(ADDON_LOG_DEBUG, "SCHEDULED: %s", data.c_str() );
1371
1372 cTimer timer;
1373 timer.SetGenreTable(m_genretable);
1374
1375 if(timer.ParseLine(data.c_str()) == true)
1376 {
1377 kodi::addon::PVRTimer tag;
1378 timer.GetPVRtimerinfo(tag);
1379 results.Add(tag);
1380 }
1381 }
1382 }
1383
1384 if ( std::chrono::system_clock::now() > m_iLastRecordingUpdate + std::chrono::milliseconds(15000))
1385 {
1386 kodi::addon::CInstancePVRClient::TriggerRecordingUpdate();
1387 }
1388
1389 return PVR_ERROR_NO_ERROR;
1390 }
1391
1392 PVR_ERROR cPVRClientMediaPortal::GetTimerInfo(unsigned int timernumber, kodi::addon::PVRTimer& timerinfo)
1393 {
1394 string result;
1395 char command[256];
1396
1397 kodi::Log(ADDON_LOG_DEBUG, "->GetTimerInfo(%u)", timernumber);
1398
1399 if (!IsUp())
1400 return PVR_ERROR_SERVER_ERROR;
1401
1402 snprintf(command, 256, "GetScheduleInfo:%u\n", timernumber);
1403
1404 result = SendCommand(command);
1405
1406 if (result.length() == 0)
1407 return PVR_ERROR_SERVER_ERROR;
1408
1409 cTimer timer;
1410 if( timer.ParseLine(result.c_str()) == false )
1411 {
1412 kodi::Log(ADDON_LOG_DEBUG, "GetTimerInfo(%i) parsing server response failed. Response: %s", timernumber, result.c_str());
1413 return PVR_ERROR_SERVER_ERROR;
1414 }
1415
1416 timer.GetPVRtimerinfo(timerinfo);
1417 return PVR_ERROR_NO_ERROR;
1418 }
1419
1420 PVR_ERROR cPVRClientMediaPortal::GetTimerTypes(std::vector<kodi::addon::PVRTimerType>& types)
1421 {
1422 if (Timer::lifetimeValues == NULL)
1423 return PVR_ERROR_FAILED;
1424
1425 //Note: schedule priority support is not implemented here
1426 // The MediaPortal TV Server database has a priority field but their wiki
1427 // says: "This feature is yet to be enabled".
1428
1429 // One-shot epg-based (maps to MediaPortal 'Once')
1430 {
1431 kodi::addon::PVRTimerType type;
1432 type.SetId(cKodiTimerTypeOffset + TvDatabase::Once);
1433 type.SetAttributes(MPTV_RECORD_ONCE);
1434 type.SetDescription(kodi::addon::GetLocalizedString(30110)); /* Record once */
1435 Timer::lifetimeValues->SetLifeTimeValues(type);
1436 types.emplace_back(type);
1437 }
1438
1439 // Series weekly epg-based (maps to MediaPortal 'EveryTimeOnThisChannel')
1440 {
1441 kodi::addon::PVRTimerType type;
1442 type.SetId(cKodiTimerTypeOffset + TvDatabase::EveryTimeOnThisChannel);
1443 type.SetAttributes(MPTV_RECORD_EVERY_TIME_ON_THIS_CHANNEL);
1444 type.SetDescription(kodi::addon::GetLocalizedString(30115)); /* Record every time on this channel */
1445 Timer::lifetimeValues->SetLifeTimeValues(type);
1446 types.emplace_back(type);
1447 }
1448
1449 // Series weekly epg-based (maps to MediaPortal 'EveryTimeOnEveryChannel')
1450 {
1451 kodi::addon::PVRTimerType type;
1452 type.SetId(cKodiTimerTypeOffset + TvDatabase::EveryTimeOnEveryChannel);
1453 type.SetAttributes(MPTV_RECORD_EVERY_TIME_ON_EVERY_CHANNEL);
1454 type.SetDescription(kodi::addon::GetLocalizedString(30116)); /* Record every time on every channel */
1455 Timer::lifetimeValues->SetLifeTimeValues(type);
1456 types.emplace_back(type);
1457 }
1458
1459 // Series weekly epg-based (maps to MediaPortal 'Weekly')
1460 {
1461 kodi::addon::PVRTimerType type;
1462 type.SetId(cKodiTimerTypeOffset + TvDatabase::Weekly);
1463 type.SetAttributes(MPTV_RECORD_WEEKLY);
1464 type.SetDescription(kodi::addon::GetLocalizedString(30117)); /* "Record every week at this time" */
1465 Timer::lifetimeValues->SetLifeTimeValues(type);
1466 types.emplace_back(type);
1467 }
1468
1469 // Series daily epg-based (maps to MediaPortal 'Daily')
1470 {
1471 kodi::addon::PVRTimerType type;
1472 type.SetId(cKodiTimerTypeOffset + TvDatabase::Daily);
1473 type.SetAttributes(MPTV_RECORD_DAILY);
1474 type.SetDescription(kodi::addon::GetLocalizedString(30118)); /* Record every day at this time */
1475 Timer::lifetimeValues->SetLifeTimeValues(type);
1476 types.emplace_back(type);
1477 }
1478
1479 // Series Weekends epg-based (maps to MediaPortal 'WorkingDays')
1480 {
1481 kodi::addon::PVRTimerType type;
1482 type.SetId(cKodiTimerTypeOffset + TvDatabase::WorkingDays);
1483 type.SetAttributes(MPTV_RECORD_WORKING_DAYS);
1484 type.SetDescription(kodi::addon::GetLocalizedString(30114)); /* Record weekdays */
1485 Timer::lifetimeValues->SetLifeTimeValues(type);
1486 types.emplace_back(type);
1487 }
1488
1489 // Series Weekends epg-based (maps to MediaPortal 'Weekends')
1490 {
1491 kodi::addon::PVRTimerType type;
1492 type.SetId(cKodiTimerTypeOffset + TvDatabase::Weekends);
1493 type.SetAttributes(MPTV_RECORD_WEEEKENDS);
1494 type.SetDescription(kodi::addon::GetLocalizedString(30113)); /* Record Weekends */
1495 Timer::lifetimeValues->SetLifeTimeValues(type);
1496 types.emplace_back(type);
1497 }
1498
1499 // Series weekly epg-based (maps to MediaPortal 'WeeklyEveryTimeOnThisChannel')
1500 {
1501 kodi::addon::PVRTimerType type;
1502 type.SetId(cKodiTimerTypeOffset + TvDatabase::WeeklyEveryTimeOnThisChannel);
1503 type.SetAttributes(MPTV_RECORD_WEEKLY_EVERY_TIME_ON_THIS_CHANNEL);
1504 type.SetDescription(kodi::addon::GetLocalizedString(30119)); /* Weekly on this channel */
1505 Timer::lifetimeValues->SetLifeTimeValues(type);
1506 types.emplace_back(type);
1507 }
1508
1509 /* Kodi specific 'Manual' schedule type */
1510 {
1511 kodi::addon::PVRTimerType type;
1512 type.SetId(cKodiTimerTypeOffset + TvDatabase::KodiManual);
1513 type.SetAttributes(MPTV_RECORD_MANUAL);
1514 type.SetDescription(kodi::addon::GetLocalizedString(30122)); /* Manual */
1515 Timer::lifetimeValues->SetLifeTimeValues(type);
1516 types.emplace_back(type);
1517 }
1518
1519 return PVR_ERROR_NO_ERROR;
1520 }
1521
1522 PVR_ERROR cPVRClientMediaPortal::AddTimer(const kodi::addon::PVRTimer& timerinfo)
1523 {
1524 string result;
1525
1526 #ifdef _TIME32_T_DEFINED
1527 kodi::Log(ADDON_LOG_DEBUG, "->AddTimer Channel: %i, starttime: %i endtime: %i program: %s", timerinfo.GetClientChannelUid(), timerinfo.GetStartTime(), timerinfo.GetEndTime(), timerinfo.GetTitle().c_str());
1528 #else
1529 kodi::Log(ADDON_LOG_DEBUG, "->AddTimer Channel: %i, 64 bit times not yet supported!", timerinfo.GetClientChannelUid());
1530 #endif
1531
1532 if (!IsUp())
1533 return PVR_ERROR_SERVER_ERROR;
1534
1535 cTimer timer(timerinfo);
1536
1537 if (CSettings::Get().GetEnableOldSeriesDlg() && (timerinfo.GetStartTime() > 0) &&
1538 (timerinfo.GetEPGUid() != PVR_TIMER_NO_EPG_UID) &&
1539 ((timerinfo.GetTimerType() - cKodiTimerTypeOffset) == (unsigned int) TvDatabase::Once)
1540 )
1541 {
1542 /* New scheduled recording, not an instant or manual recording
1543 * Present a custom dialog with advanced recording settings
1544 */
1545 std::string strChannelName;
1546 if (timerinfo.GetClientChannelUid() >= 0)
1547 {
1548 strChannelName = m_channels[timerinfo.GetClientChannelUid()].Name();
1549 }
1550 CGUIDialogRecordSettings dlgRecSettings( timerinfo, timer, strChannelName);
1551
1552 int dlogResult = dlgRecSettings.DoModal();
1553
1554 if (dlogResult == 0)
1555 return PVR_ERROR_NO_ERROR; // user canceled timer in dialog
1556 }
1557
1558 result = SendCommand(timer.AddScheduleCommand());
1559
1560 if(result.find("True") == string::npos)
1561 {
1562 kodi::Log(ADDON_LOG_DEBUG, "AddTimer for channel: %i [failed]", timerinfo.GetClientChannelUid());
1563 return PVR_ERROR_FAILED;
1564 }
1565 kodi::Log(ADDON_LOG_DEBUG, "AddTimer for channel: %i [done]", timerinfo.GetClientChannelUid());
1566
1567 // Although Kodi adds this timer, we still have to trigger Kodi to update its timer list to
1568 // see this new timer at the Kodi side
1569 kodi::addon::CInstancePVRClient::TriggerTimerUpdate();
1570 if (timerinfo.GetStartTime() <= 0)
1571 {
1572 // Refresh the recordings list to see the newly created recording
1573 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1574
1575 kodi::addon::CInstancePVRClient::TriggerRecordingUpdate();
1576 }
1577
1578 return PVR_ERROR_NO_ERROR;
1579 }
1580
1581 PVR_ERROR cPVRClientMediaPortal::DeleteTimer(const kodi::addon::PVRTimer& timer, bool UNUSED(forceDelete))
1582 {
1583 char command[256];
1584 string result;
1585
1586 if (!IsUp())
1587 return PVR_ERROR_SERVER_ERROR;
1588
1589 // Check if this timer has a parent schedule and a program id
1590 // When true, it has no real schedule at the Mediaportal side.
1591 // The best we can do in that case is disable the timer for this program only
1592 if ((timer.GetParentClientIndex() > 0) && (timer.GetEPGUid() > 0))
1593 {
1594 // Don't delete this timer, but disable it only
1595 kodi::addon::PVRTimer disableMe = timer;
1596 disableMe.SetState(PVR_TIMER_STATE_DISABLED);
1597 return UpdateTimer(disableMe);
1598 }
1599
1600 cTimer mepotimer(timer);
1601
1602 snprintf(command, 256, "DeleteSchedule:%i\n", mepotimer.Index());
1603
1604 kodi::Log(ADDON_LOG_DEBUG, "DeleteTimer: About to delete MediaPortal schedule index=%i", mepotimer.Index());
1605 result = SendCommand(command);
1606
1607 if(result.find("True") == string::npos)
1608 {
1609 kodi::Log(ADDON_LOG_DEBUG, "DeleteTimer %i [failed]", mepotimer.Index());
1610 return PVR_ERROR_FAILED;
1611 }
1612 kodi::Log(ADDON_LOG_DEBUG, "DeleteTimer %i [done]", mepotimer.Index());
1613
1614 // Although Kodi deletes this timer, we still have to trigger Kodi to update its timer list to
1615 // remove the timer from the Kodi list
1616 kodi::addon::CInstancePVRClient::TriggerTimerUpdate();
1617
1618 return PVR_ERROR_NO_ERROR;
1619 }
1620
1621 PVR_ERROR cPVRClientMediaPortal::UpdateTimer(const kodi::addon::PVRTimer& timerinfo)
1622 {
1623 string result;
1624
1625 #ifdef _TIME32_T_DEFINED
1626 kodi::Log(ADDON_LOG_DEBUG, "->UpdateTimer Index: %i Channel: %i, starttime: %i endtime: %i program: %s", timerinfo.GetClientIndex(), timerinfo.GetClientChannelUid(), timerinfo.GetStartTime(), timerinfo.GetEndTime(), timerinfo.GetTitle());
1627 #else
1628 kodi::Log(ADDON_LOG_DEBUG, "->UpdateTimer Channel: %i, 64 bit times not yet supported!", timerinfo.GetClientChannelUid());
1629 #endif
1630
1631 if (!IsUp())
1632 return PVR_ERROR_SERVER_ERROR;
1633
1634 cTimer timer(timerinfo);
1635
1636 result = SendCommand(timer.UpdateScheduleCommand());
1637 if(result.find("True") == string::npos)
1638 {
1639 kodi::Log(ADDON_LOG_DEBUG, "UpdateTimer for channel: %i [failed]", timerinfo.GetClientChannelUid());
1640 return PVR_ERROR_FAILED;
1641 }
1642 kodi::Log(ADDON_LOG_DEBUG, "UpdateTimer for channel: %i [done]", timerinfo.GetClientChannelUid());
1643
1644 // Although Kodi changes this timer, we still have to trigger Kodi to update its timer list to
1645 // see the timer changes at the Kodi side
1646 kodi::addon::CInstancePVRClient::TriggerTimerUpdate();
1647
1648 return PVR_ERROR_NO_ERROR;
1649 }
1650
1651
1652 /************************************************************/
1653 /** Live stream handling */
1654
1655 // The MediaPortal TV Server uses rtsp streams which Kodi can handle directly
1656 // via the dvdplayer (ffmpeg) so we don't need to open the streams in this
1657 // pvr addon.
1658 // However, we still need to request the stream URL for the channel we want
1659 // to watch as it is not known on beforehand.
1660 // Most of the times it is the same URL for each selected channel. Only the
1661 // stream itself changes. Example URL: rtsp://tvserverhost/stream2.0
1662 // The number 2.0 may change when the tvserver is streaming multiple tv channels
1663 // at the same time.
1664 //
1665 // The rtsp code from ffmpeg does not function well enough for this addon.
1666 // Therefore the new TSReader version uses the Live555 library here to open rtsp
1667 // urls or it can read directly from the timeshift buffer file.
1668 bool cPVRClientMediaPortal::OpenLiveStream(const kodi::addon::PVRChannel& channelinfo)
1669 {
1670 string result;
1671 char command[256] = "";
1672 const char* sResolveRTSPHostname = booltostring(CSettings::Get().GetResolveRTSPHostname());
1673 vector<string> timeshiftfields;
1674
1675 kodi::Log(ADDON_LOG_INFO, "Open Live stream for channel uid=%i", channelinfo.GetUniqueId());
1676 if (!IsUp())
1677 {
1678 m_iCurrentChannel = -1;
1679 m_bTimeShiftStarted = false;
1680 m_bSkipCloseLiveStream = false; //initialization
1681 m_signalStateCounter = 0;
1682 kodi::Log(ADDON_LOG_ERROR, "Open Live stream failed. No connection to backend.");
1683 return false;
1684 }
1685
1686 if (((int)channelinfo.GetUniqueId()) == m_iCurrentChannel)
1687 {
1688 kodi::Log(ADDON_LOG_INFO, "New channel uid equal to the already streaming channel. Skipping re-tune.");
1689 return true;
1690 }
1691
1692 m_iCurrentChannel = -1; // make sure that it is not a valid channel nr in case it will fail lateron
1693 m_signalStateCounter = 0;
1694 m_bTimeShiftStarted = false;
1695 m_bSkipCloseLiveStream = false; //initialization
1696
1697 // Start the timeshift
1698 // Use the optimized TimeshiftChannel call (don't stop a running timeshift)
1699 snprintf(command, 256, "TimeshiftChannel:%i|%s|False\n", channelinfo.GetUniqueId(), sResolveRTSPHostname);
1700 result = SendCommand(command);
1701
1702 if (result.find("ERROR") != std::string::npos || result.length() == 0)
1703 {
1704 kodi::Log(ADDON_LOG_ERROR, "Could not start the timeshift for channel uid=%i. Reason: %s", channelinfo.GetUniqueId(), result.c_str());
1705 if (g_iTVServerKodiBuild>=109)
1706 {
1707 Tokenize(result, timeshiftfields, "|");
1708 //[0] = string error message
1709 //[1] = TvResult (optional field. SendCommand can also return a timeout)
1710
1711 if(timeshiftfields.size()>1)
1712 {
1713 //For TVServer 1.2.1:
1714 //enum TvResult
1715 //{
1716 // Succeeded = 0, (this is not an error)
1717 // AllCardsBusy = 1,
1718 // ChannelIsScrambled = 2,
1719 // NoVideoAudioDetected = 3,
1720 // NoSignalDetected = 4,
1721 // UnknownError = 5,
1722 // UnableToStartGraph = 6,
1723 // UnknownChannel = 7,
1724 // NoTuningDetails = 8,
1725 // ChannelNotMappedToAnyCard = 9,
1726 // CardIsDisabled = 10,
1727 // ConnectionToSlaveFailed = 11,
1728 // NotTheOwner = 12,
1729 // GraphBuildingFailed = 13,
1730 // SWEncoderMissing = 14,
1731 // NoFreeDiskSpace = 15,
1732 // NoPmtFound = 16,
1733 //};
1734
1735 int tvresult = std::atoi(timeshiftfields[1].c_str());
1736 // Display one of the localized error messages 30060-30075
1737 kodi::QueueNotification(QUEUE_ERROR, "", kodi::addon::GetLocalizedString(30059 + tvresult));
1738 }
1739 else
1740 {
1741 kodi::QueueNotification(QUEUE_ERROR, "", result);
1742 }
1743 }
1744 else
1745 {
1746 if (result.find("[ERROR]: TVServer answer: ") != std::string::npos)
1747 {
1748 //Skip first part: "[ERROR]: TVServer answer: "
1749 kodi::QueueFormattedNotification(QUEUE_ERROR, "TVServer: %s", result.substr(26).c_str());
1750 }
1751 else
1752 {
1753 //Skip first part: "[ERROR]: "
1754 kodi::QueueNotification(QUEUE_ERROR, "", result.substr(7));
1755 }
1756 }
1757 m_iCurrentChannel = -1;
1758 if (m_tsreader != nullptr)
1759 {
1760 SafeDelete(m_tsreader);
1761 }
1762 return false;
1763 }
1764 else
1765 {
1766 Tokenize(result, timeshiftfields, "|");
1767
1768 if(timeshiftfields.size()<4)
1769 {
1770 kodi::Log(ADDON_LOG_ERROR, "OpenLiveStream: Field count mismatch (<4). Data: %s\n", result.c_str());
1771 m_iCurrentChannel = -1;
1772 return false;
1773 }
1774
1775 //[0] = rtsp url
1776 //[1] = original (unresolved) rtsp url
1777 //[2] = timeshift buffer filename
1778 //[3] = card id (TVServerKodi build >= 106)
1779 //[4] = tsbuffer pos (TVServerKodi build >= 110)
1780 //[5] = tsbuffer file nr (TVServerKodi build >= 110)
1781
1782 m_PlaybackURL = timeshiftfields[0];
1783 if (CSettings::Get().GetStreamingMethod() == TSReader)
1784 {
1785 kodi::Log(ADDON_LOG_INFO, "Channel timeshift buffer: %s", timeshiftfields[2].c_str());
1786 if (channelinfo.GetIsRadio())
1787 {
1788 // 100 ms sleep to allow the buffer to fill
1789 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1790 }
1791 }
1792 else
1793 {
1794 kodi::Log(ADDON_LOG_INFO, "Channel stream URL: %s", m_PlaybackURL.c_str());
1795 }
1796
1797 if (CSettings::Get().GetSleepOnRTSPurl() > 0)
1798 {
1799 kodi::Log(ADDON_LOG_INFO, "Sleeping %i ms before opening stream: %s", CSettings::Get().GetSleepOnRTSPurl(), timeshiftfields[0].c_str());
1800 std::this_thread::sleep_for(std::chrono::milliseconds(CSettings::Get().GetSleepOnRTSPurl()));
1801 }
1802
1803 // Check the returned stream URL. When the URL is an rtsp stream, we need
1804 // to close it again after watching to stop the timeshift.
1805 // A radio web stream (added to the TV Server) will return the web stream
1806 // URL without starting a timeshift.
1807 if(timeshiftfields[0].compare(0,4, "rtsp") == 0)
1808 {
1809 m_bTimeShiftStarted = true;
1810 }
1811
1812 if (CSettings::Get().GetStreamingMethod() == TSReader)
1813 {
1814 if (m_tsreader != NULL)
1815 {
1816 bool bReturn = false;
1817
1818 // Continue with the existing TsReader.
1819 kodi::Log(ADDON_LOG_INFO, "Re-using existing TsReader...");
1820 //if(g_bDirectTSFileRead)
1821 if(CSettings::Get().GetUseRTSP() == false)
1822 {
1823 m_tsreader->SetCardId(std::atoi(timeshiftfields[3].c_str()));
1824
1825 if ((g_iTVServerKodiBuild >=110) && (timeshiftfields.size()>=6))
1826 bReturn = m_tsreader->OnZap(timeshiftfields[2].c_str(), atoll(timeshiftfields[4].c_str()), atol(timeshiftfields[5].c_str()));
1827 else
1828 bReturn = m_tsreader->OnZap(timeshiftfields[2].c_str(), -1, -1);
1829 }
1830 else
1831 {
1832 // RTSP url
1833 kodi::Log(ADDON_LOG_INFO, "Skipping OnZap for TSReader RTSP");
1834 bReturn = true; //Fast forward seek (OnZap) does not work for RTSP
1835 }
1836
1837 if (bReturn)
1838 {
1839 m_iCurrentChannel = (int) channelinfo.GetUniqueId();
1840 m_iCurrentCard = std::atoi(timeshiftfields[3].c_str());
1841 m_bCurrentChannelIsRadio = channelinfo.GetIsRadio();
1842 }
1843 else
1844 {
1845 kodi::Log(ADDON_LOG_ERROR, "Re-using the existing TsReader failed.");
1846 CloseLiveStream();
1847 }
1848
1849 return bReturn;
1850 }
1851 else
1852 {
1853 kodi::Log(ADDON_LOG_INFO, "Creating a new TsReader...");
1854 m_tsreader = new CTsReader();
1855 }
1856
1857 if (!CSettings::Get().GetUseRTSP())
1858 {
1859 // Reading directly from the Timeshift buffer
1860 m_tsreader->SetCardSettings(&m_cCards);
1861 m_tsreader->SetCardId(std::atoi(timeshiftfields[3].c_str()));
1862
1863 //if (g_szTimeshiftDir.length() > 0)
1864 // m_tsreader->SetDirectory(g_szTimeshiftDir);
1865
1866 if ( m_tsreader->Open(timeshiftfields[2].c_str()) != S_OK )
1867 {
1868 kodi::Log(ADDON_LOG_ERROR, "Cannot open timeshift buffer %s", timeshiftfields[2].c_str());
1869 CloseLiveStream();
1870 return false;
1871 }
1872 }
1873 else
1874 {
1875 // use the RTSP url and live555
1876 if ( m_tsreader->Open(timeshiftfields[0].c_str()) != S_OK)
1877 {
1878 kodi::Log(ADDON_LOG_ERROR, "Cannot open channel url %s", timeshiftfields[0].c_str());
1879 CloseLiveStream();
1880 return false;
1881 }
1882 std::this_thread::sleep_for(std::chrono::milliseconds(400));
1883 }
1884 }
1885
1886 // at this point everything is ready for playback
1887 m_iCurrentChannel = (int) channelinfo.GetUniqueId();
1888 m_iCurrentCard = std::atoi(timeshiftfields[3].c_str());
1889 m_bCurrentChannelIsRadio = channelinfo.GetIsRadio();
1890 }
1891 kodi::Log(ADDON_LOG_INFO, "OpenLiveStream: success for channel id %i (%s) on card %i", m_iCurrentChannel, channelinfo.GetChannelName().c_str(), m_iCurrentCard);
1892
1893 return true;
1894 }
1895
1896 int cPVRClientMediaPortal::ReadLiveStream(unsigned char *pBuffer, unsigned int iBufferSize)
1897 {
1898 size_t read_wanted = iBufferSize;
1899 size_t read_done = 0;
1900 static int read_timeouts = 0;
1901 unsigned char* bufptr = pBuffer;
1902
1903 //kodi::Log(ADDON_LOG_DEBUG, "->ReadLiveStream(buf_size=%i)", buf_size);
1904 if (CSettings::Get().GetStreamingMethod() != TSReader)
1905 {
1906 kodi::Log(ADDON_LOG_ERROR, "ReadLiveStream: this function should not be called in FFMPEG/RTSP mode. Use 'Reset the PVR database' to re-read the channel list");
1907 return 0;
1908 }
1909
1910 if (!m_tsreader)
1911 {
1912 kodi::Log(ADDON_LOG_ERROR, "ReadLiveStream: failed. No open TSReader");
1913 return -1;
1914 }
1915
1916 if ((m_tsreader->State() == State_Paused) && (CSettings::Get().GetUseRTSP()))
1917 {
1918 //kodi::Log(ADDON_LOG_ERROR, "ReadLiveStream: failed. Stream is paused");
1919 return 0;
1920 }
1921
1922 while (read_done < static_cast<size_t>(iBufferSize))
1923 {
1924 read_wanted = iBufferSize - read_done;
1925
1926 if (m_tsreader->Read(bufptr, read_wanted, &read_wanted) > 0)
1927 {
1928 std::this_thread::sleep_for(std::chrono::milliseconds(20));
1929 read_timeouts++;
1930 return static_cast<int>(read_wanted);
1931 }
1932 read_done += read_wanted;
1933
1934 if ( read_done < static_cast<size_t>(iBufferSize) )
1935 {
1936 if (read_timeouts > 200)
1937 {
1938 if (m_bCurrentChannelIsRadio == false || read_done == 0)
1939 {
1940 kodi::Log(ADDON_LOG_INFO, "Kodi requested %u bytes, but the TSReader got only %lu bytes in 2 seconds", iBufferSize, read_done);
1941 }
1942 read_timeouts = 0;
1943
1944 //TODO
1945 //if read_done == 0 then check if the backend is still timeshifting,
1946 //or retrieve the reason why the timeshifting was stopped/failed...
1947
1948 return static_cast<int>(read_done);
1949 }
1950 bufptr += read_wanted;
1951 read_timeouts++;
1952 std::this_thread::sleep_for(std::chrono::milliseconds(10));
1953 }
1954 }
1955 read_timeouts = 0;
1956
1957 return static_cast<int>(read_done);
1958 }
1959
1960 void cPVRClientMediaPortal::CloseLiveStream(void)
1961 {
1962 string result;
1963
1964 if (!IsUp())
1965 return;
1966
1967 if (m_bTimeShiftStarted && !m_bSkipCloseLiveStream)
1968 {
1969 if (CSettings::Get().GetStreamingMethod() == TSReader && m_tsreader)
1970 {
1971 m_tsreader->Close();
1972 SafeDelete(m_tsreader);
1973 }
1974 result = SendCommand("StopTimeshift:\n");
1975 kodi::Log(ADDON_LOG_INFO, "CloseLiveStream: %s", result.c_str());
1976 m_bTimeShiftStarted = false;
1977 m_iCurrentChannel = -1;
1978 m_iCurrentCard = -1;
1979 m_PlaybackURL.clear();
1980
1981 m_signalStateCounter = 0;
1982 }
1983 }
1984
1985 int64_t cPVRClientMediaPortal::SeekLiveStream(int64_t iPosition, int iWhence)
1986 {
1987 if (CSettings::Get().GetStreamingMethod() == ffmpeg || !m_tsreader)
1988 {
1989 kodi::Log(ADDON_LOG_ERROR, "SeekLiveStream: is not supported in FFMPEG/RTSP mode.");
1990 return -1;
1991 }
1992
1993 if (iPosition == 0 && iWhence == SEEK_CUR)
1994 {
1995 return m_tsreader->GetFilePointer();
1996 }
1997 return m_tsreader->SetFilePointer(iPosition, iWhence);
1998 }
1999
2000 int64_t cPVRClientMediaPortal::LengthLiveStream(void)
2001 {
2002 if (CSettings::Get().GetStreamingMethod() == ffmpeg || !m_tsreader)
2003 {
2004 return -1;
2005 }
2006 return m_tsreader->GetFileSize();
2007 }
2008
2009 bool cPVRClientMediaPortal::IsRealTimeStream()
2010 {
2011 return m_bTimeShiftStarted;
2012 }
2013
2014 PVR_ERROR cPVRClientMediaPortal::GetSignalStatus(int channelUid, kodi::addon::PVRSignalStatus& signalStatus)
2015 {
2016 if (g_iTVServerKodiBuild < 108 || (m_iCurrentChannel == -1))
2017 {
2018 // Not yet supported or playing webstream
2019 return PVR_ERROR_NO_ERROR;
2020 }
2021
2022 string result;
2023
2024 // Limit the GetSignalQuality calls to once every 10 s
2025 if (m_signalStateCounter == 0)
2026 {
2027 // Request the signal quality for the current streaming card from the backend
2028 result = SendCommand("GetSignalQuality\n");
2029
2030 if (result.length() > 0)
2031 {
2032 int signallevel = 0;
2033 int signalquality = 0;
2034
2035 // Fetch the signal level and SNR values from the result string
2036 if (sscanf(result.c_str(),"%5i|%5i", &signallevel, &signalquality) == 2)
2037 {
2038 m_iSignal = (int) (signallevel * 655.35); // 100% is 0xFFFF 65535
2039 m_iSNR = (int) (signalquality * 655.35); // 100% is 0xFFFF 65535
2040 }
2041 }
2042 }
2043 m_signalStateCounter++;
2044 if (m_signalStateCounter > 10)
2045 m_signalStateCounter = 0;
2046
2047 signalStatus.SetSignal(m_iSignal);
2048 signalStatus.SetSNR(m_iSNR);
2049 signalStatus.SetBER(m_signalStateCounter);
2050 signalStatus.SetAdapterStatus("timeshifting"); // hardcoded for now...
2051
2052
2053 if (m_iCurrentCard >= 0)
2054 {
2055 // Try to determine the name of the tv/radio card from the local card cache
2056 Card currentCard;
2057 if (m_cCards.GetCard(m_iCurrentCard, currentCard) == true)
2058 {
2059 signalStatus.SetAdapterName(currentCard.Name);
2060 return PVR_ERROR_NO_ERROR;
2061 }
2062 }
2063
2064 signalStatus.SetAdapterName("");
2065
2066 return PVR_ERROR_NO_ERROR;
2067 }
2068
2069
2070 /************************************************************/
2071 /** Record stream handling */
2072 // MediaPortal recordings are also rtsp streams. Main difference here with
2073 // respect to the live tv streams is that the URLs for the recordings
2074 // can be requested on beforehand (done in the TVServerKodi plugin).
2075
2076 bool cPVRClientMediaPortal::OpenRecordedStream(const kodi::addon::PVRRecording& recording)
2077 {
2078 kodi::Log(ADDON_LOG_INFO, "OpenRecordedStream (id=%s, RTSP=%d)", recording.GetRecordingId().c_str(), (CSettings::Get().GetUseRTSP() ? "true" : "false"));
2079
2080 m_bTimeShiftStarted = false;
2081
2082 if (!IsUp())
2083 return false;
2084
2085 if (CSettings::Get().GetStreamingMethod() == ffmpeg)
2086 {
2087 kodi::Log(ADDON_LOG_ERROR, "Addon is in 'ffmpeg' mode. Kodi should play the RTSP url directly. Please reset your Kodi PVR database!");
2088 return false;
2089 }
2090
2091 std::string recfile = "";
2092
2093 cRecording* myrecording = GetRecordingInfo(recording);
2094
2095 if (!myrecording)
2096 {
2097 return false;
2098 }
2099
2100 if (!CSettings::Get().GetUseRTSP())
2101 {
2102 recfile = myrecording->FilePath();
2103 if (recfile.empty())
2104 {
2105 kodi::Log(ADDON_LOG_ERROR, "Backend returned an empty recording filename for recording id %s.", recording.GetRecordingId().c_str());
2106 recfile = myrecording->Stream();
2107 if (!recfile.empty())
2108 {
2109 kodi::Log(ADDON_LOG_INFO, "Trying to use the recording RTSP stream URL name instead.");
2110 }
2111 }
2112 }
2113 else
2114 {
2115 recfile = myrecording->Stream();
2116 if (recfile.empty())
2117 {
2118 kodi::Log(ADDON_LOG_ERROR, "Backend returned an empty RTSP stream URL for recording id %s.", recording.GetRecordingId().c_str());
2119 recfile = myrecording->FilePath();
2120 if (!recfile.empty())
2121 {
2122 kodi::Log(ADDON_LOG_INFO, "Trying to use the filename instead.");
2123 }
2124 }
2125 }
2126
2127 if (recfile.empty())
2128 {
2129 kodi::Log(ADDON_LOG_ERROR, "Recording playback not possible. Backend returned an empty filename and no RTSP stream URL for recording id %s", recording.GetRecordingId().c_str());
2130 kodi::QueueNotification(QUEUE_ERROR, "", kodi::addon::GetLocalizedString(30052));
2131 // Tell Kodi to re-read the list with recordings to remove deleted/non-existing recordings as a result of backend auto-deletion.
2132 kodi::addon::CInstancePVRClient::TriggerRecordingUpdate();
2133 return false;
2134 }
2135
2136 // We have a recording file name or RTSP url, time to open it...
2137 m_tsreader = new CTsReader();
2138 m_tsreader->SetCardSettings(&m_cCards);
2139 if ( m_tsreader->Open(recfile.c_str()) != S_OK )
2140 return false;
2141
2142 return true;
2143 }
2144
2145 void cPVRClientMediaPortal::CloseRecordedStream(void)
2146 {
2147 if (!IsUp() || CSettings::Get().GetStreamingMethod() == ffmpeg)
2148 return;
2149
2150 if (m_tsreader)
2151 {
2152 kodi::Log(ADDON_LOG_INFO, "CloseRecordedStream: Stop TSReader...");
2153 m_tsreader->Close();
2154 SafeDelete(m_tsreader);
2155 }
2156 else
2157 {
2158 kodi::Log(ADDON_LOG_DEBUG, "CloseRecordedStream: Nothing to do.");
2159 }
2160 }
2161
2162 int cPVRClientMediaPortal::ReadRecordedStream(unsigned char *pBuffer, unsigned int iBufferSize)
2163 {
2164 size_t read_wanted = static_cast<size_t>(iBufferSize);
2165 size_t read_done = 0;
2166 unsigned char* bufptr = pBuffer;
2167
2168 if (CSettings::Get().GetStreamingMethod() == ffmpeg)
2169 return -1;
2170
2171 while (read_done < static_cast<size_t>(iBufferSize))
2172 {
2173 read_wanted = iBufferSize - read_done;
2174 if (!m_tsreader)
2175 return -1;
2176
2177 if (m_tsreader->Read(bufptr, read_wanted, &read_wanted) > 0)
2178 {
2179 std::this_thread::sleep_for(std::chrono::milliseconds(20));
2180 return static_cast<int>(read_wanted);
2181 }
2182 read_done += read_wanted;
2183
2184 if ( read_done < static_cast<size_t>(iBufferSize) )
2185 {
2186 bufptr += read_wanted;
2187 std::this_thread::sleep_for(std::chrono::milliseconds(20));
2188 }
2189 }
2190
2191 return static_cast<int>(read_done);
2192 }
2193
2194 int64_t cPVRClientMediaPortal::SeekRecordedStream(int64_t iPosition, int iWhence)
2195 {
2196 if (CSettings::Get().GetStreamingMethod() == ffmpeg || !m_tsreader)
2197 {
2198 return -1;
2199 }
2200 #ifdef _DEBUG
2201 kodi::Log(ADDON_LOG_DEBUG, "SeekRec: Current pos %lli", m_tsreader->GetFilePointer());
2202 #endif
2203 kodi::Log(ADDON_LOG_DEBUG,"SeekRec: iWhence %i pos %lli", iWhence, iPosition);
2204
2205 return m_tsreader->SetFilePointer(iPosition, iWhence);
2206 }
2207
2208 int64_t cPVRClientMediaPortal::LengthRecordedStream(void)
2209 {
2210 if (CSettings::Get().GetStreamingMethod() == ffmpeg || !m_tsreader)
2211 {
2212 return -1;
2213 }
2214 return m_tsreader->GetFileSize();
2215 }
2216
2217 PVR_ERROR cPVRClientMediaPortal::GetRecordingStreamProperties(const kodi::addon::PVRRecording& recording,
2218 std::vector<kodi::addon::PVRStreamProperty>& properties)
2219 {
2220 // GetRecordingStreamProperties is called before OpenRecordedStream
2221 // If we return a stream URL here, Kodi will use its internal player to open the stream and bypass the PVR addon
2222
2223 cRecording* myrecording = GetRecordingInfo(recording);
2224
2225 if (!myrecording)
2226 return PVR_ERROR_NO_ERROR;
2227
2228 properties.emplace_back(PVR_STREAM_PROPERTY_MIMETYPE, "video/mp2t");
2229
2230 if (CSettings::Get().GetStreamingMethod() == ffmpeg)
2231 {
2232 properties.emplace_back(PVR_STREAM_PROPERTY_STREAMURL, myrecording->Stream());
2233 }
2234 else if (!CSettings::Get().GetUseRTSP())
2235 {
2236 if (myrecording->IsRecording() == false)
2237 {
2238 #ifdef TARGET_WINDOWS_DESKTOP
2239 if (OS::CFile::Exists(myrecording->FilePath()))
2240 {
2241 std::string recordingUri(ToKodiPath(myrecording->FilePath()));
2242
2243 // Direct file playback by Kodi (without involving the addon)
2244 properties.emplace_back(PVR_STREAM_PROPERTY_STREAMURL, recordingUri.c_str());
2245 }
2246 #endif
2247 }
2248 else
2249 {
2250 // Indicate that this is a real-time stream
2251 properties.emplace_back(PVR_STREAM_PROPERTY_ISREALTIMESTREAM, "true");
2252 }
2253 }
2254
2255 return PVR_ERROR_NO_ERROR;
2256 }
2257
2258 PVR_ERROR cPVRClientMediaPortal::GetChannelStreamProperties(const kodi::addon::PVRChannel& channel,
2259 std::vector<kodi::addon::PVRStreamProperty>& properties)
2260 {
2261 // Is this a webstream?
2262 try
2263 {
2264 cChannel& selectedChannel = m_channels.at(channel.GetUniqueId());
2265
2266 if (selectedChannel.IsWebstream())
2267 {
2268 kodi::Log(ADDON_LOG_DEBUG, "GetChannelStreamProperties (webstream) for uid=%i is '%s'",
2269 channel.GetUniqueId(), selectedChannel.URL());
2270 properties.emplace_back(PVR_STREAM_PROPERTY_STREAMURL, selectedChannel.URL());
2271 properties.emplace_back(PVR_STREAM_PROPERTY_ISREALTIMESTREAM, "true");
2272 return PVR_ERROR_NO_ERROR;
2273 }
2274 }
2275 catch (const std::out_of_range& oor)
2276 {
2277 // channel not found in our plugin channel cache
2278 }
2279
2280 if (CSettings::Get().GetStreamingMethod() == ffmpeg)
2281 {
2282 // GetChannelStreamProperties is called before OpenLiveStream by Kodi, so we should already open the stream here...
2283 // The actual call to OpenLiveStream will return immediately since we've already tuned the correct channel here.
2284 if (m_bTimeShiftStarted == true)
2285 {
2286 //CloseLiveStream();
2287 }
2288 if (OpenLiveStream(channel) == true)
2289 {
2290 if (!m_PlaybackURL.empty())
2291 {
2292 kodi::Log(ADDON_LOG_DEBUG, "GetChannelStreamProperties (ffmpeg) for uid=%i is '%s'", channel.GetUniqueId(),
2293 m_PlaybackURL.c_str());
2294 properties.emplace_back(PVR_STREAM_PROPERTY_STREAMURL, m_PlaybackURL);
2295 properties.emplace_back(PVR_STREAM_PROPERTY_ISREALTIMESTREAM, "true");
2296 properties.emplace_back(PVR_STREAM_PROPERTY_MIMETYPE, "video/mp2t");
2297 return PVR_ERROR_NO_ERROR;
2298 }
2299 }
2300 }
2301 else if (CSettings::Get().GetStreamingMethod() == TSReader)
2302 {
2303 if ((m_bTimeShiftStarted == true) && (CSettings::Get().GetFastChannelSwitch() == true))
2304 {
2305 // This ignores the next CloseLiveStream call from Kodi to speedup channel switching
2306 m_bSkipCloseLiveStream = true;
2307 }
2308 }
2309 else
2310 {
2311 kodi::Log(ADDON_LOG_ERROR, "GetChannelStreamProperties for uid=%i returned no URL",
2312 channel.GetUniqueId());
2313 }
2314
2315 return PVR_ERROR_NO_ERROR;
2316 }
2317
2318 void cPVRClientMediaPortal::PauseStream(bool bPaused)
2319 {
2320 if (m_tsreader)
2321 m_tsreader->Pause(bPaused);
2322 }
2323
2324 bool cPVRClientMediaPortal::CanPauseStream()
2325 {
2326 if (m_tsreader)
2327 return true;
2328 else
2329 return false;
2330 }
2331
2332 bool cPVRClientMediaPortal::CanSeekStream()
2333 {
2334 if (m_tsreader)
2335 return true;
2336 else
2337 return false;
2338 }
2339
2340 void cPVRClientMediaPortal::LoadGenreTable()
2341 {
2342 // Read the genre string to type/subtype translation file:
2343 if(CSettings::Get().GetReadGenre())
2344 {
2345 string sGenreFile = UserPath() + PATH_SEPARATOR_CHAR + "resources" + PATH_SEPARATOR_CHAR + "genre_translation.xml";
2346
2347 if (!kodi::vfs::FileExists(sGenreFile, false))
2348 {
2349 sGenreFile = UserPath() + PATH_SEPARATOR_CHAR + "genre_translation.xml";
2350 if (!kodi::vfs::FileExists(sGenreFile, false))
2351 {
2352 sGenreFile = ClientPath() + PATH_SEPARATOR_CHAR + "resources" + PATH_SEPARATOR_CHAR + "genre_translation.xml";
2353 }
2354 }
2355
2356 m_genretable = new CGenreTable(sGenreFile);
2357 }
2358 }
2359
2360 void cPVRClientMediaPortal::LoadCardSettings()
2361 {
2362 kodi::Log(ADDON_LOG_DEBUG, "Loading card settings");
2363
2364 /* Retrieve card settings (needed for Live TV and recordings folders) */
2365 vector<string> lines;
2366
2367 if ( SendCommand2("GetCardSettings\n", lines) )
2368 {
2369 m_cCards.ParseLines(lines);
2370 }
2371 }
2372
2373 void cPVRClientMediaPortal::SetConnectionState(PVR_CONNECTION_STATE newState)
2374 {
2375 if (newState != m_state)
2376 {
2377 kodi::Log(ADDON_LOG_DEBUG, "Connection state changed to '%s'",
2378 GetConnectionStateString(newState));
2379 m_state = newState;
2380
2381 /* Notify connection state change (callback!) */
2382 std::string connection;
2383 GetConnectionString(connection);
2384 kodi::addon::CInstancePVRClient::ConnectionStateChange(connection, m_state, "");
2385 }
2386 }
2387
2388 const char* cPVRClientMediaPortal::GetConnectionStateString(PVR_CONNECTION_STATE state) const
2389 {
2390 switch (state)
2391 {
2392 case PVR_CONNECTION_STATE_SERVER_UNREACHABLE:
2393 return "Backend server is not reachable";
2394 case PVR_CONNECTION_STATE_SERVER_MISMATCH:
2395 return "Backend server is reachable, but the expected type of server is not running";
2396 case PVR_CONNECTION_STATE_VERSION_MISMATCH:
2397 return "Backend server is reachable, but the server version does not match client requirements";
2398 case PVR_CONNECTION_STATE_ACCESS_DENIED:
2399 return "Backend server is reachable, but denies client access (e.g. due to wrong credentials)";
2400 case PVR_CONNECTION_STATE_CONNECTED:
2401 return "Connection to backend server is established";
2402 case PVR_CONNECTION_STATE_DISCONNECTED:
2403 return "No connection to backend server (e.g. due to network errors or client initiated disconnect)";
2404 case PVR_CONNECTION_STATE_CONNECTING:
2405 return "Connecting to backend";
2406 case PVR_CONNECTION_STATE_UNKNOWN:
2407 default:
2408 return "Unknown state";
2409 }
2410 }
2411
2412 cRecording* cPVRClientMediaPortal::GetRecordingInfo(const kodi::addon::PVRRecording& recording)
2413 {
2414 // Is this the same recording as the previous one?
2415 if (m_lastSelectedRecording)
2416 {
2417 int recId = std::atoi(recording.GetRecordingId().c_str());
2418 if (m_lastSelectedRecording->Index() == recId)
2419 {
2420 return m_lastSelectedRecording;
2421 }
2422 SafeDelete(m_lastSelectedRecording);
2423 }
2424
2425 if (!IsUp())
2426 return nullptr;
2427
2428 string result;
2429 string command;
2430
2431 command = StringUtils::Format("GetRecordingInfo:%s|%s|True|%s\n",
2432 recording.GetRecordingId().c_str(),
2433 ((CSettings::Get().GetUseRTSP() || CSettings::Get().GetStreamingMethod() == ffmpeg) ? "True" : "False"),
2434 CSettings::Get().GetResolveRTSPHostname() ? "True" : "False"
2435 );
2436 result = SendCommand(command);
2437 uri::decode(result);
2438
2439 if (result.empty())
2440 {
2441 kodi::Log(ADDON_LOG_ERROR, "Backend command '%s' returned a zero-length answer.", command.c_str());
2442 return nullptr;
2443 }
2444
2445 m_lastSelectedRecording = new cRecording();
2446 if (!m_lastSelectedRecording->ParseLine(result))
2447 {
2448 kodi::Log(ADDON_LOG_ERROR, "Parsing result from '%s' command failed. Result='%s'.", command.c_str(), result.c_str());
2449 return nullptr;
2450 }
2451 kodi::Log(ADDON_LOG_INFO, "RECORDING: %s", result.c_str());
2452 return m_lastSelectedRecording;
2453 }
2454
2455 PVR_ERROR cPVRClientMediaPortal::GetStreamTimes(kodi::addon::PVRStreamTimes& stream_times)
2456 {
2457 if (!m_bTimeShiftStarted && m_lastSelectedRecording)
2458 {
2459 // Recording playback
2460 // Warning: documentation in xbmc_pvr_types.h is wrong. pts values are not in seconds.
2461 stream_times.SetStartTime(0); // seconds
2462 stream_times.SetPTSStart(0); // Unit must match Kodi's internal m_clock.GetClock() which is in useconds
2463 stream_times.SetPTSBegin(0); // useconds
2464 stream_times.SetPTSEnd(((int64_t)m_lastSelectedRecording->Duration()) * STREAM_TIME_BASE); //useconds
2465 return PVR_ERROR_NO_ERROR;
2466 }
2467 else if (m_bTimeShiftStarted)
2468 {
2469 stream_times.SetStartTime(m_tsreader->GetStartTime());
2470 stream_times.SetPTSStart(0); // Unit must match Kodi's internal m_clock.GetClock() which is in useconds
2471 stream_times.SetPTSBegin(m_tsreader->GetPtsBegin()); // useconds
2472 stream_times.SetPTSEnd(m_tsreader->GetPtsEnd());
2473 return PVR_ERROR_NO_ERROR;
2474 }
2475 *stream_times = { 0 };
2476
2477 return PVR_ERROR_NOT_IMPLEMENTED;
2478 }
2479
2480 PVR_ERROR cPVRClientMediaPortal::GetStreamReadChunkSize(int& chunksize)
2481 {
2482 chunksize = 32 * 1024;
2483 return PVR_ERROR_NO_ERROR;
2484 }
2485
2486 namespace
2487 {
2488 int GetFileContents(const std::string& url, std::string& content)
2489 {
2490 content.clear();
2491 kodi::vfs::CFile file;
2492 if (file.OpenFile(url))
2493 {
2494 char buffer[1024];
2495 while (int bytesRead = file.Read(buffer, 1024))
2496 content.append(buffer, bytesRead);
2497 }
2498
2499 return content.length();
2500 }
2501 }
2502
2503 PVR_ERROR cPVRClientMediaPortal::GetRecordingEdl(const kodi::addon::PVRRecording& recording, std::vector<kodi::addon::PVREDLEntry>& edl) // bilkusg
2504 {
2505 cRecording* myrecording = GetRecordingInfo(recording);
2506 if (!myrecording)
2507 return PVR_ERROR_SERVER_ERROR;
2508
2509 const std::string pvrSmbPath = m_tsreader->TranslatePath(myrecording->FilePath());
2510 const std::string edlFilePath = pvrSmbPath.substr(0, pvrSmbPath.find_last_of('.')) + ".edl";
2511 kodi::Log(ADDON_LOG_DEBUG, "GetRecordingEdl for %s from %s", myrecording->FilePath(), edlFilePath.c_str());
2512
2513 if (!kodi::vfs::FileExists(edlFilePath))
2514 return PVR_ERROR_NO_ERROR;
2515 std::string edlFileContents;
2516 int edlLength = GetFileContents(edlFilePath, edlFileContents);
2517 if (edlLength == 0)
2518 return PVR_ERROR_NO_ERROR;
2519
2520 std::istringstream stream(edlFileContents);
2521 std::string line;
2522 int lineNumber = 0;
2523 while (std::getline(stream, line))
2524 {
2525 float start = 0.0f, stop = 0.0f;
2526 unsigned int type = PVR_EDL_TYPE_CUT;
2527 lineNumber++;
2528 if (std::sscanf(line.c_str(), "%f %f %u", &start, &stop, &type) < 2 || type > PVR_EDL_TYPE_COMBREAK)
2529 {
2530 kodi::Log(ADDON_LOG_INFO, "%s Unable to parse EDL entry for recording '%s' at line %d. Skipping.", __func__,
2531 edlFilePath.c_str(), lineNumber);
2532 continue;
2533 }
2534
2535 start = std::max(start, 0.0f);
2536 stop = std::max(stop, 0.0f);
2537 start = std::min(start, stop);
2538 stop = std::max(start, stop);
2539
2540 kodi::Log(ADDON_LOG_DEBUG, "%s EDL for '%s', line %d - start: %f stop: %f type: %d", __func__, edlFilePath.c_str(), lineNumber, start, stop, type);
2541
2542 kodi::addon::PVREDLEntry edlEntry;
2543 edlEntry.SetStart(static_cast<int64_t>(start * 1000.0f));
2544 edlEntry.SetEnd(static_cast<int64_t>(stop * 1000.0f));
2545 edlEntry.SetType(static_cast<PVR_EDL_TYPE>(type));
2546
2547 edl.emplace_back(edlEntry);
2548 }
2549 kodi::Log(ADDON_LOG_INFO, "%s - recording '%s' has '%d' EDL entries available", __func__, recording.GetTitle().c_str(), edl.size());
2550 return PVR_ERROR_NO_ERROR;
2551 }