Debian Codegraph @

src/lib/tsreader/TSReader.cpp

raw
1 /*
2 * Copyright (C) 2005-2012 Team Kodi
3 * https://kodi.tv
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 *************************************************************************
19 * Parts of this file originate from Team MediaPortal's
20 * TsReader DirectShow filter
21 * MediaPortal is a GPL'ed HTPC-Application
22 * Copyright (C) 2005-2012 Team MediaPortal
23 * http://www.team-mediaportal.com
24 *
25 * Changes compared to Team MediaPortal's version:
26 * - Code cleanup for PVR addon usage
27 * - Code refactoring for cross platform usage
28 *************************************************************************/
29
30 #include "TSReader.h"
31 #include <kodi/General.h> //for kodi::Log
32 #include <kodi/Filesystem.h>
33 #include "MultiFileReader.h"
34 #include "utils.h"
35 #include "TSDebug.h"
36 #include <kodi/tools/StringUtils.h>
37 #ifdef LIVE555
38 #include "MemoryReader.h"
39 #include "MepoRTSPClient.h"
40 #include "MemoryBuffer.h"
41 #endif
42 #include "FileUtils.h"
43
44 #include <thread>
45
46 using namespace std;
47
48 template<typename T> void SafeDelete(T*& p)
49 {
50 if (p)
51 {
52 delete p;
53 p = nullptr;
54 }
55 }
56
57 namespace MPTV
58 {
59 CTsReader::CTsReader() : m_demultiplexer(*this),
60 m_fileName(""), m_startTickCount(), m_startTime(0)
61 {
62 m_fileReader = NULL;
63 m_fileDuration = NULL;
64 m_bLiveTv = false;
65 m_bTimeShifting = false;
66 m_bIsRTSP = false;
67 m_cardSettings = NULL;
68 m_cardId = -1;
69 m_State = State_Stopped;
70 m_lastPause = 0;
71 m_WaitForSeekToEof = 0;
72 m_bRecording = false;
73
74 #ifdef LIVE555
75 m_rtspClient = NULL;
76 m_buffer = NULL;
77 #endif
78 }
79
80 CTsReader::~CTsReader(void)
81 {
82 SafeDelete(m_fileReader);
83 #ifdef LIVE555
84 SafeDelete(m_buffer);
85 SafeDelete(m_rtspClient);
86 #endif
87 }
88
89 std::string CTsReader::TranslatePath(const char* pszFileName)
90 {
91 std::string sFileName = pszFileName;
92 #if defined (TARGET_WINDOWS_DESKTOP)
93 // Can we access the given file already?
94 if (OS::CFile::Exists(pszFileName))
95 {
96 kodi::Log(ADDON_LOG_DEBUG, "Found the timeshift buffer at: %s\n", pszFileName);
97 return ToKodiPath(sFileName);
98 }
99 kodi::Log(ADDON_LOG_INFO, "Cannot access '%s' directly. Assuming multiseat mode. Need to translate to UNC filename.", pszFileName);
100 #elif defined (TARGET_WINDOWS_STORE)
101 kodi::Log(ADDON_LOG_DEBUG, "WindowsStore: need to translate '%s' to UNC filename.", pszFileName);
102 #else
103 kodi::Log(ADDON_LOG_DEBUG, "Multiseat mode; need to translate '%s' to UNC filename.", pszFileName);
104 #endif
105
106 bool bFound = false;
107
108 // Card Id given? (only for Live TV / Radio). Check for an UNC path (e.g. \\tvserver\timeshift)
109 if (m_cardId >= 0)
110 {
111 Card tscard;
112
113 if ((m_cardSettings) && (m_cardSettings->GetCard(m_cardId, tscard)))
114 {
115 if (!tscard.TimeshiftFolderUNC.empty())
116 {
117 kodi::tools::StringUtils::Replace(sFileName, tscard.TimeshiftFolder.c_str(), tscard.TimeshiftFolderUNC.c_str());
118 bFound = true;
119 }
120 else
121 {
122 kodi::Log(ADDON_LOG_ERROR, "No timeshift share known for card %i '%s'. Check your TVServerKodi settings!", tscard.IdCard, tscard.Name.c_str());
123 }
124 }
125 }
126 else
127 {
128 // No Card Id given. This is a recording. Check for an UNC path (e.g. \\tvserver\recordings)
129 size_t found = string::npos;
130
131 if ((m_cardSettings) && (m_cardSettings->size() > 0))
132 {
133 for (CCards::iterator it = m_cardSettings->begin(); it < m_cardSettings->end(); ++it)
134 {
135 // Determine whether the first part of the recording filename is shared with this card
136 found = sFileName.find(it->RecordingFolder);
137 if (found != string::npos)
138 {
139 if (!it->RecordingFolderUNC.empty())
140 {
141 // Remove the original base path and replace it with the given path
142 kodi::tools::StringUtils::Replace(sFileName, it->RecordingFolder.c_str(), it->RecordingFolderUNC.c_str());
143 bFound = true;
144 break;
145 }
146 }
147 }
148 }
149 }
150
151 sFileName = ToKodiPath(sFileName);
152
153 if (bFound)
154 {
155 kodi::Log(ADDON_LOG_INFO, "Translate path %s -> %s", pszFileName, sFileName.c_str());
156 }
157 else
158 {
159 kodi::Log(ADDON_LOG_ERROR, "Could not find a network share for '%s'. Check your TVServerKodi settings!", pszFileName);
160 if (!kodi::vfs::FileExists(pszFileName, false))
161 {
162 kodi::Log(ADDON_LOG_ERROR, "Cannot access '%s'", pszFileName);
163 kodi::QueueFormattedNotification(QUEUE_ERROR, "Cannot access: %s", pszFileName);
164 sFileName.clear();
165 return sFileName;
166 }
167 }
168
169 #if defined (TARGET_WINDOWS_DESKTOP)
170 // Can we now access the given file?
171 long errCode;
172 if (!OS::CFile::Exists(sFileName, &errCode))
173 {
174 switch (errCode)
175 {
176 case ERROR_FILE_NOT_FOUND:
177 kodi::Log(ADDON_LOG_ERROR, "File not found: %s.\n", sFileName.c_str());
178 break;
179 case ERROR_ACCESS_DENIED:
180 {
181 char strUserName[256];
182 DWORD lLength = 256;
183
184 if (GetUserNameA(strUserName, &lLength))
185 {
186 kodi::Log(ADDON_LOG_ERROR, "Access denied on %s. Check share access rights for user '%s' or connect as a different user using the Explorer.\n", sFileName.c_str(), strUserName);
187 }
188 else
189 {
190 kodi::Log(ADDON_LOG_ERROR, "Access denied on %s. Check share access rights.\n", sFileName.c_str());
191 }
192 kodi::QueueFormattedNotification(QUEUE_ERROR, "Access denied: %s", sFileName.c_str());
193 break;
194 }
195 default:
196 kodi::Log(ADDON_LOG_ERROR, "Cannot find or access file: %s. Check share access rights.", sFileName.c_str());
197 }
198
199 sFileName.clear();
200 }
201 #elif defined TARGET_WINDOWS_STORE
202 if (!kodi::vfs::FileExists(sFileName, false))
203 {
204 kodi::Log(ADDON_LOG_ERROR, "Cannot find or access file: %s. Did you enable the vfs.smb2 plugin?\n", sFileName.c_str());
205 }
206 #endif
207
208 return sFileName;
209 }
210
211 long CTsReader::Open(const char* pszFileName)
212 {
213 kodi::Log(ADDON_LOG_INFO, "TsReader open '%s'", pszFileName);
214
215 m_fileName = pszFileName;
216
217 if (m_State != State_Stopped)
218 Close();
219
220 // check file type
221 size_t length = m_fileName.length();
222
223 if ((length > 7) && (strnicmp(m_fileName.c_str(), "rtsp://", 7) == 0))
224 {
225 // rtsp:// stream
226 // open stream
227 kodi::Log(ADDON_LOG_DEBUG, "open rtsp: %s", m_fileName.c_str());
228 #ifdef LIVE555
229 //strcpy(m_rtspClient.m_outFileName, "e:\\temp\\rtsptest.ts");
230 delete m_buffer;
231 m_buffer = new CMemoryBuffer();
232 delete m_rtspClient;
233 m_rtspClient = new CRTSPClient();
234 m_rtspClient->Initialize(m_buffer);
235
236 if ( !m_rtspClient->OpenStream(m_fileName.c_str()) )
237 {
238 SafeDelete(m_rtspClient);
239 SafeDelete(m_buffer);
240 return E_FAIL;
241 }
242
243 m_bIsRTSP = true;
244 m_bTimeShifting = true;
245 m_bLiveTv = true;
246
247 // are we playing a recording via RTSP
248 if (m_fileName.find_first_of("/stream") == string::npos )
249 {
250 // yes, then we're not timeshifting
251 m_bTimeShifting = false;
252 m_bLiveTv = false;
253 }
254
255 // play
256 m_rtspClient->Play(0.0,0.0);
257 delete m_fileReader;
258 m_fileReader = new CMemoryReader(*m_buffer);
259 m_State = State_Running;
260 #else
261 kodi::Log(ADDON_LOG_ERROR, "Failed to open %s. PVR client is compiled without LIVE555 RTSP support.", m_fileName.c_str());
262 kodi::QueueNotification(QUEUE_ERROR, "PVR client has no RTSP support: %s", m_fileName.c_str());
263 return E_FAIL;
264 #endif //LIVE555
265 }
266 else
267 {
268 if ((length < 9) || (strnicmp(&m_fileName.c_str()[length - 9], ".tsbuffer", 9) != 0))
269 {
270 // local .ts file
271 m_bTimeShifting = false;
272 m_bLiveTv = false;
273 m_bIsRTSP = false;
274 m_fileReader = new FileReader();
275 }
276 else
277 {
278 // local timeshift buffer file file
279 m_bTimeShifting = true;
280 m_bLiveTv = true;
281 m_bIsRTSP = false;
282 m_fileReader = new MultiFileReader();
283 }
284
285 // Translate path (e.g. Local filepath to smb://user:pass@share)
286 m_fileName = TranslatePath(m_fileName.c_str());
287
288 if (m_fileName.empty())
289 return S_FALSE;
290
291 // open file
292 long retval = m_fileReader->OpenFile(m_fileName);
293 if (retval != S_OK)
294 {
295 kodi::Log(ADDON_LOG_ERROR, "Failed to open file '%s' as '%s'", pszFileName, m_fileName.c_str());
296 return retval;
297 }
298 // detect audio/video pids
299 m_demultiplexer.SetFileReader(m_fileReader);
300 m_demultiplexer.Start();
301
302 m_fileReader->SetFilePointer(0LL, FILE_BEGIN);
303 m_State = State_Running;
304
305 time(&m_startTime);
306 m_startTickCount = GetTickCount64();
307 }
308 return S_OK;
309 }
310
311 long CTsReader::Read(unsigned char* pbData, size_t lDataLength, size_t *dwReadBytes)
312 {
313 if (m_fileReader)
314 {
315 return m_fileReader->Read(pbData, lDataLength, dwReadBytes);
316 }
317
318 *dwReadBytes = 0;
319 return S_FALSE;
320 }
321
322 void CTsReader::Close()
323 {
324 if (m_fileReader)
325 {
326 if (m_bIsRTSP)
327 {
328 #ifdef LIVE555
329 kodi::Log(ADDON_LOG_INFO, "TsReader: closing RTSP client");
330 m_rtspClient->Stop();
331 SafeDelete(m_rtspClient);
332 SafeDelete(m_buffer);
333 #endif
334 }
335 else
336 {
337 kodi::Log(ADDON_LOG_INFO, "TsReader: closing file");
338 m_fileReader->CloseFile();
339 }
340 SafeDelete(m_fileReader);
341 m_State = State_Stopped;
342 }
343 }
344
345 bool CTsReader::OnZap(const char* pszFileName, int64_t timeShiftBufferPos, long timeshiftBufferID)
346 {
347 string newFileName;
348
349 kodi::Log(ADDON_LOG_INFO, "TsReader: OnZap(%s)", pszFileName);
350
351 // Check whether the new channel url/timeshift buffer is changed
352 // In case of a new url/timeshift buffer file, close the old one first
353 newFileName = TranslatePath(pszFileName);
354 if (newFileName != m_fileName)
355 {
356 Close();
357 return (S_OK == Open(pszFileName));
358 }
359 else
360 {
361 if (m_fileReader)
362 {
363 kodi::Log(ADDON_LOG_DEBUG, "%s: request new PAT", __FUNCTION__);
364
365 int64_t pos_before, pos_after;
366 MultiFileReader* fileReader = dynamic_cast<MultiFileReader*>(m_fileReader);
367
368 if (!fileReader)
369 {
370 return false;
371 }
372
373 pos_before = fileReader->GetFilePointer();
374
375 if ((timeShiftBufferPos > 0) && (timeshiftBufferID != -1))
376 {
377 pos_after = fileReader->SetCurrentFilePointer(timeShiftBufferPos, timeshiftBufferID);
378 }
379 else
380 {
381 if (timeShiftBufferPos < 0)
382 {
383 pos_after = m_fileReader->SetFilePointer(0LL, FILE_BEGIN);
384 }
385 else
386 {
387 pos_after = m_fileReader->SetFilePointer(0LL, FILE_END);
388 if ((timeShiftBufferPos > 0) && (pos_after > timeShiftBufferPos))
389 {
390 /* Move backward */
391 pos_after = fileReader->SetFilePointer((timeShiftBufferPos - pos_after), FILE_CURRENT);
392 }
393 }
394 }
395
396 m_demultiplexer.RequestNewPat();
397 fileReader->OnChannelChange();
398
399 kodi::Log(ADDON_LOG_DEBUG, "%s:: move from %I64d to %I64d tsbufpos %I64d", __FUNCTION__, pos_before, pos_after, timeShiftBufferPos);
400 std::this_thread::sleep_for(std::chrono::milliseconds(100));
401
402 // Set the stream start times to this new channel
403 time(&m_startTime);
404 m_startTickCount = GetTickCount64();
405
406 return true;
407 }
408 return false;
409 }
410 }
411
412 void CTsReader::SetCardSettings(CCards* cardSettings)
413 {
414 m_cardSettings = cardSettings;
415 }
416
417 void CTsReader::SetDirectory(string& directory)
418 {
419 std::string tmp = directory;
420
421 #ifdef TARGET_WINDOWS_DESKTOP
422 if (tmp.find("smb://") != string::npos)
423 {
424 // Convert XBMC smb share name back to a real windows network share...
425 kodi::tools::StringUtils::Replace(tmp, "smb://", "\\\\");
426 kodi::tools::StringUtils::Replace(tmp, "/", "\\");
427 }
428 #else
429 //TODO: do something useful...
430 #endif
431 m_basePath = tmp;
432 }
433
434 void CTsReader::SetCardId(int id)
435 {
436 m_cardId = id;
437 }
438
439 bool CTsReader::IsTimeShifting()
440 {
441 return m_bTimeShifting;
442 }
443
444 long CTsReader::Pause(bool UNUSED(bPaused))
445 {
446 kodi::Log(ADDON_LOG_DEBUG, "TsReader: Pause - IsTimeShifting = %d - state = %d", IsTimeShifting(), m_State);
447
448 if (m_State == State_Running)
449 {
450 m_lastPause = GetTickCount64();
451 #ifdef LIVE555
452 // Are we using rtsp?
453 if (m_bIsRTSP)
454 {
455 kodi::Log(ADDON_LOG_DEBUG, "CTsReader::Pause() ->pause rtsp"); // at position: %f", (m_seekTime.Millisecs() / 1000.0f));
456 m_rtspClient->Pause();
457 }
458 #endif //LIVE555
459 m_State = State_Paused;
460 }
461 else if (m_State == State_Paused)
462 {
463 #ifdef LIVE555
464 // Are we using rtsp?
465 if (m_bIsRTSP)
466 {
467 kodi::Log(ADDON_LOG_DEBUG, "CTsReader::Pause() is paused, continue rtsp"); // at position: %f", (m_seekTime.Millisecs() / 1000.0f));
468 m_rtspClient->Continue();
469 kodi::Log(ADDON_LOG_DEBUG, "CTsReader::Pause() rtsp running"); // at position: %f", (m_seekTime.Millisecs() / 1000.0f));
470 }
471 m_State = State_Running;
472 #endif //LIVE555
473 }
474
475 kodi::Log(ADDON_LOG_DEBUG, "TsReader: Pause - END - state = %d", m_State);
476 return S_OK;
477 }
478
479 bool CTsReader::IsSeeking()
480 {
481 return (m_WaitForSeekToEof > 0);
482 }
483
484 int64_t CTsReader::GetFileSize()
485 {
486 return m_fileReader->GetFileSize();
487 }
488
489 int64_t CTsReader::GetFilePointer()
490 {
491 return m_fileReader->GetFilePointer();
492 }
493
494 time_t CTsReader::GetStartTime()
495 {
496 return m_startTime;
497 }
498
499 int64_t CTsReader::GetPtsBegin()
500 {
501 return 0;
502 }
503
504 int64_t CTsReader::GetPtsEnd()
505 {
506 return (GetTickCount64() - m_startTickCount) * 1000; // useconds
507 }
508
509 int64_t CTsReader::SetFilePointer(int64_t llDistanceToMove, unsigned long dwMoveMethod)
510 {
511 // Are we using rtsp?
512 if (m_bIsRTSP)
513 {
514 // TODO: fixme...
515 // Need to translate the distance to move (bytes) to a time
516 // then ask live555 to seek to that time
517 return m_fileReader->GetFilePointer();
518 }
519 else
520 {
521 return m_fileReader->SetFilePointer(llDistanceToMove, dwMoveMethod);
522 }
523 }
524 }