Line data Source code
1 : /*
2 : * If not stated otherwise in this file or this component's LICENSE file the
3 : * following copyright and licenses apply:
4 : *
5 : * Copyright 2024 Sky UK
6 : *
7 : * Licensed under the Apache License, Version 2.0 (the "License");
8 : * you may not use this file except in compliance with the License.
9 : * You may obtain a copy of the License at
10 : *
11 : * http://www.apache.org/licenses/LICENSE-2.0
12 : *
13 : * Unless required by applicable law or agreed to in writing, software
14 : * distributed under the License is distributed on an "AS IS" BASIS,
15 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 : * See the License for the specific language governing permissions and
17 : * limitations under the License.
18 : */
19 :
20 : #include "TextTrackAccessor.h"
21 :
22 : #include <algorithm>
23 : #include <cctype>
24 : #include <cerrno>
25 : #include <cinttypes>
26 : #include <cstdlib>
27 : #include <cstring>
28 : #include <fcntl.h>
29 : #include <filesystem>
30 : #include <fstream>
31 : #include <mutex>
32 : #include <stdexcept>
33 : #include <string>
34 : #include <sys/stat.h>
35 : #include <unistd.h>
36 :
37 : namespace
38 : {
39 : constexpr char kSubtitleDataEnv[] = "RIALTO_SHOW_SUBTITLE_DATA";
40 : constexpr char kSubtitleLogPathEnv[] = "RIALTO_SUBTITLE_LOG_PATH";
41 : constexpr std::size_t kSubtitleLogChunkSize{400};
42 : constexpr const char *kSubtitleLogDirectories[]{"/opt/logs", "/tmp"};
43 :
44 9 : bool isValidSubtitleLogFileName(const std::string &fileName)
45 : {
46 18 : return !fileName.empty() && fileName != "." && fileName != ".." && fileName.find("..") == std::string::npos &&
47 9 : std::all_of(fileName.begin(), fileName.end(),
48 240 : [](unsigned char ch) { return std::isalnum(ch) || ch == '.' || ch == '_' || ch == '-'; });
49 : }
50 :
51 24 : bool isEnvironmentVariableEnabled(const char *name)
52 : {
53 24 : const char *value = std::getenv(name);
54 24 : if (!value || value[0] == '\0')
55 : {
56 13 : return false;
57 : }
58 :
59 11 : std::string stringValue(value);
60 11 : std::transform(stringValue.begin(), stringValue.end(), stringValue.begin(),
61 20 : [](char character)
62 : {
63 20 : if (character >= 'A' && character <= 'Z')
64 : {
65 2 : return static_cast<char>(character + ('a' - 'A'));
66 : }
67 18 : return character;
68 : });
69 11 : return stringValue == "1" || stringValue == "true" || stringValue == "yes" || stringValue == "on";
70 : }
71 :
72 : #ifdef RIALTO_LOG_DEBUG_ENABLED
73 10 : bool isSubtitleDebugLoggingEnabled()
74 : {
75 10 : const RIALTO_DEBUG_LEVEL logLevels = firebolt::rialto::logging::getLogLevels(RIALTO_COMPONENT_SERVER);
76 10 : return logLevels == RIALTO_DEBUG_LEVEL_EXTERNAL || (logLevels & RIALTO_DEBUG_LEVEL_DEBUG) != 0;
77 : }
78 : #endif
79 :
80 : #ifdef RIALTO_LOG_DEBUG_ENABLED
81 9 : std::string escapeNullBytes(const std::string &data)
82 : {
83 9 : std::string escaped;
84 9 : escaped.reserve(data.size());
85 4935 : for (char ch : data)
86 : {
87 4926 : if (ch == '\0')
88 : {
89 1 : escaped += "\\0";
90 : }
91 : else
92 : {
93 4925 : escaped += ch;
94 : }
95 : }
96 9 : return escaped;
97 : }
98 : #endif
99 :
100 10 : void logSubtitleData(const std::string &data)
101 : {
102 : #ifdef RIALTO_LOG_DEBUG_ENABLED
103 10 : if (!isSubtitleDebugLoggingEnabled())
104 : {
105 2 : return;
106 : }
107 :
108 9 : const std::string logData{escapeNullBytes(data)};
109 9 : if (logData.empty())
110 : {
111 1 : RIALTO_SERVER_LOG_DEBUG("Subtitle data: ");
112 1 : return;
113 : }
114 :
115 8 : std::size_t offset{};
116 8 : bool firstChunk{true};
117 27 : while (offset < logData.size())
118 : {
119 19 : std::size_t chunkEnd{std::min(offset + kSubtitleLogChunkSize, logData.size())};
120 831 : while (chunkEnd < logData.size() && chunkEnd > offset &&
121 411 : (static_cast<unsigned char>(logData[chunkEnd]) & 0xc0) == 0x80)
122 : {
123 401 : --chunkEnd;
124 : }
125 19 : if (chunkEnd == offset)
126 : {
127 1 : chunkEnd = std::min(offset + kSubtitleLogChunkSize, logData.size());
128 : }
129 :
130 19 : const std::string chunk{logData.substr(offset, chunkEnd - offset)};
131 19 : if (firstChunk)
132 : {
133 8 : RIALTO_SERVER_LOG_DEBUG("Subtitle data: %s\n", chunk.c_str());
134 8 : firstChunk = false;
135 : }
136 : else
137 : {
138 11 : RIALTO_SERVER_LOG_DEBUG("Subtitle data (continued): %s\n", chunk.c_str());
139 : }
140 19 : offset = chunkEnd;
141 : }
142 : #else
143 : static_cast<void>(data);
144 : #endif
145 9 : }
146 :
147 10 : bool writeSubtitleDataToFile(const char *path, const std::string &data, std::string &error)
148 : {
149 : namespace fs = std::filesystem;
150 10 : const fs::path configuredPath{path};
151 10 : if (!configuredPath.is_absolute())
152 : {
153 1 : error = "path must be absolute";
154 1 : return false;
155 : }
156 :
157 9 : const fs::path fileName{configuredPath.filename()};
158 9 : const std::string fileNameString{fileName.string()};
159 9 : if (!isValidSubtitleLogFileName(fileNameString))
160 : {
161 1 : error = "filename must contain only letters, digits, '.', '_' or '-' and must not contain '..'";
162 1 : return false;
163 : }
164 :
165 8 : const fs::path parentDirectory{configuredPath.parent_path()};
166 8 : const char *allowedDirectory{};
167 16 : for (const char *allowedRoot : kSubtitleLogDirectories)
168 : {
169 15 : if (parentDirectory == fs::path{allowedRoot})
170 : {
171 7 : allowedDirectory = allowedRoot;
172 7 : break;
173 : }
174 : }
175 8 : if (!allowedDirectory)
176 : {
177 1 : error = "directory must be exactly /opt/logs or /tmp";
178 1 : return false;
179 : }
180 :
181 : static std::mutex logMutex;
182 7 : const std::lock_guard<std::mutex> lock{logMutex};
183 7 : const int directoryFd{open(allowedDirectory, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)};
184 7 : if (directoryFd < 0)
185 : {
186 2 : error = "cannot open log directory: " + std::string{std::strerror(errno)};
187 1 : return false;
188 : }
189 :
190 6 : const int logFileFd{openat(directoryFd, fileNameString.c_str(),
191 : O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK, 0664)};
192 6 : const int openError{errno};
193 6 : if (close(directoryFd) != 0 && logFileFd >= 0)
194 : {
195 0 : const int closeError{errno};
196 0 : close(logFileFd);
197 0 : error = "cannot close log directory: " + std::string{std::strerror(closeError)};
198 0 : return false;
199 : }
200 6 : if (logFileFd < 0)
201 : {
202 6 : error = "cannot open log file: " + std::string{std::strerror(openError)};
203 3 : return false;
204 : }
205 :
206 3 : struct stat fileStatus
207 : {
208 : };
209 3 : if (fstat(logFileFd, &fileStatus) != 0)
210 : {
211 0 : const int statError{errno};
212 0 : close(logFileFd);
213 0 : error = "cannot inspect log file: " + std::string{std::strerror(statError)};
214 0 : return false;
215 : }
216 3 : if (!S_ISREG(fileStatus.st_mode))
217 : {
218 0 : close(logFileFd);
219 0 : error = "log path must refer to a regular file";
220 0 : return false;
221 : }
222 3 : if (fileStatus.st_nlink != 1)
223 : {
224 1 : close(logFileFd);
225 1 : error = "log file must not have hard links";
226 1 : return false;
227 : }
228 2 : if (fileStatus.st_uid != geteuid())
229 : {
230 0 : close(logFileFd);
231 0 : error = "log file must be owned by the Rialto process user";
232 0 : return false;
233 : }
234 :
235 2 : const std::string logEntry{"Subtitle data: " + data + '\n'};
236 2 : const char *nextByte{logEntry.data()};
237 2 : std::size_t remaining{logEntry.size()};
238 4 : while (remaining > 0)
239 : {
240 2 : const ssize_t result{write(logFileFd, nextByte, remaining)};
241 2 : if (result < 0 && errno == EINTR)
242 : {
243 0 : continue;
244 : }
245 2 : if (result < 0)
246 : {
247 0 : const int writeError{errno};
248 0 : close(logFileFd);
249 0 : error = "cannot write log file: " + std::string{std::strerror(writeError)};
250 0 : return false;
251 : }
252 2 : if (result == 0)
253 : {
254 0 : close(logFileFd);
255 0 : error = "write returned zero bytes";
256 0 : return false;
257 : }
258 :
259 2 : const std::size_t bytesWritten{static_cast<std::size_t>(result)};
260 2 : if (bytesWritten > remaining)
261 : {
262 0 : close(logFileFd);
263 0 : error = "write returned more bytes than requested";
264 0 : return false;
265 : }
266 2 : nextByte += bytesWritten;
267 2 : remaining -= bytesWritten;
268 : }
269 :
270 2 : if (close(logFileFd) != 0)
271 : {
272 0 : error = "cannot close log file: " + std::string{std::strerror(errno)};
273 0 : return false;
274 : }
275 2 : return true;
276 10 : }
277 : } // namespace
278 :
279 : namespace firebolt::rialto::server
280 : {
281 0 : ITextTrackAccessorFactory &ITextTrackAccessorFactory::getFactory()
282 : {
283 0 : static TextTrackAccessorFactory factory;
284 0 : return factory;
285 : }
286 :
287 0 : std::shared_ptr<ITextTrackAccessor> TextTrackAccessorFactory::getTextTrackAccessor() const
288 : try
289 : {
290 : static std::shared_ptr<TextTrackAccessor> textTrackAccessor{
291 0 : std::make_shared<TextTrackAccessor>(firebolt::rialto::wrappers::ITextTrackPluginWrapperFactory::getFactory()
292 0 : ->getTextTrackPluginWrapper(),
293 0 : firebolt::rialto::wrappers::IThunderWrapperFactory::getFactory()
294 0 : ->getThunderWrapper())};
295 :
296 0 : return textTrackAccessor;
297 : }
298 0 : catch (const std::exception &e)
299 : {
300 0 : return nullptr;
301 : }
302 :
303 50 : TextTrackAccessor::TextTrackAccessor(
304 : const std::shared_ptr<firebolt::rialto::wrappers::ITextTrackPluginWrapper> &textTrackPluginWrapper,
305 50 : const std::shared_ptr<firebolt::rialto::wrappers::IThunderWrapper> &thunderWrapper)
306 50 : : m_textTrackPluginWrapper{textTrackPluginWrapper}, m_thunderWrapper{thunderWrapper}
307 : {
308 50 : if (!createTextTrackControlInterface())
309 : {
310 4 : RIALTO_SERVER_LOG_ERROR("Failed to create TextTrack interfaces");
311 4 : throw std::runtime_error("Failed to create TextTrack interfaces");
312 : }
313 62 : }
314 :
315 : TextTrackAccessor::~TextTrackAccessor() {}
316 :
317 2 : std::optional<uint32_t> TextTrackAccessor::openSession(const std::string &displayName)
318 : {
319 2 : uint32_t sessionId = {};
320 2 : uint32_t result = m_textTrackWrapper->openSession(displayName, sessionId);
321 2 : if (m_thunderWrapper->isSuccessful(result))
322 : {
323 1 : RIALTO_SERVER_LOG_MIL("TextTrack session %u created with display '%s'", sessionId, displayName.c_str());
324 1 : return sessionId;
325 : }
326 :
327 1 : RIALTO_SERVER_LOG_ERROR("Failed to create TextTrack session with display '%s'; error '%s'", displayName.c_str(),
328 : m_thunderWrapper->errorToString(result));
329 1 : return std::nullopt;
330 : }
331 :
332 2 : bool TextTrackAccessor::closeSession(uint32_t sessionId)
333 : {
334 2 : uint32_t result = m_textTrackWrapper->closeSession(sessionId);
335 2 : if (m_thunderWrapper->isSuccessful(result))
336 : {
337 1 : RIALTO_SERVER_LOG_MIL("TextTrack session %u closed", sessionId);
338 1 : return true;
339 : }
340 :
341 1 : RIALTO_SERVER_LOG_ERROR("Failed to close TextTrack session %u; error %s", sessionId,
342 : m_thunderWrapper->errorToString(result));
343 1 : return false;
344 : }
345 :
346 2 : bool TextTrackAccessor::pause(uint32_t sessionId)
347 : {
348 2 : uint32_t result = m_textTrackWrapper->pauseSession(sessionId);
349 2 : if (m_thunderWrapper->isSuccessful(result))
350 : {
351 1 : RIALTO_SERVER_LOG_INFO("TextTrack session %u paused", sessionId);
352 1 : return true;
353 : }
354 :
355 1 : RIALTO_SERVER_LOG_ERROR("Failed to pause TextTrack session %u; error %s", sessionId,
356 : m_thunderWrapper->errorToString(result));
357 1 : return false;
358 : }
359 :
360 2 : bool TextTrackAccessor::play(uint32_t sessionId)
361 : {
362 2 : uint32_t result = m_textTrackWrapper->resumeSession(sessionId);
363 2 : if (m_thunderWrapper->isSuccessful(result))
364 : {
365 1 : RIALTO_SERVER_LOG_INFO("TextTrack session %u resumed", sessionId);
366 1 : return true;
367 : }
368 :
369 1 : RIALTO_SERVER_LOG_ERROR("Failed to resume TextTrack session %u; error %s", sessionId,
370 : m_thunderWrapper->errorToString(result));
371 1 : return false;
372 : }
373 :
374 4 : bool TextTrackAccessor::mute(uint32_t sessionId, bool mute)
375 : {
376 4 : if (mute)
377 : {
378 2 : uint32_t result = m_textTrackWrapper->muteSession(sessionId);
379 2 : if (m_thunderWrapper->isSuccessful(result))
380 : {
381 1 : RIALTO_SERVER_LOG_INFO("TextTrack session %u muted", sessionId);
382 1 : return true;
383 : }
384 :
385 1 : RIALTO_SERVER_LOG_ERROR("Failed to mute TextTrack session %u; error %s", sessionId,
386 : m_thunderWrapper->errorToString(result));
387 : }
388 : else
389 : {
390 2 : uint32_t result = m_textTrackWrapper->unmuteSession(sessionId);
391 2 : if (m_thunderWrapper->isSuccessful(result))
392 : {
393 1 : RIALTO_SERVER_LOG_INFO("TextTrack session %u unmuted", sessionId);
394 1 : return true;
395 : }
396 :
397 1 : RIALTO_SERVER_LOG_ERROR("Failed to unmute TextTrack session %u; error %s", sessionId,
398 : m_thunderWrapper->errorToString(result));
399 : }
400 :
401 2 : return false;
402 : }
403 :
404 2 : bool TextTrackAccessor::setPosition(uint32_t sessionId, uint64_t mediaTimestampMs)
405 : {
406 2 : uint32_t result = m_textTrackWrapper->sendSessionTimestamp(sessionId, mediaTimestampMs);
407 2 : if (m_thunderWrapper->isSuccessful(result))
408 : {
409 1 : RIALTO_SERVER_LOG_INFO("TextTrack session %u set position to %" PRIu64, sessionId, mediaTimestampMs);
410 1 : return true;
411 : }
412 :
413 1 : RIALTO_SERVER_LOG_ERROR("Failed to set position of TextTrack session %u to %" PRIu64 "; error %s", sessionId,
414 : mediaTimestampMs, m_thunderWrapper->errorToString(result));
415 1 : return false;
416 : }
417 :
418 26 : bool TextTrackAccessor::sendData(uint32_t sessionId, const std::string &data, DataType datatype, int64_t displayOffsetMs)
419 : {
420 26 : const char *subtitleLogPath = std::getenv(kSubtitleLogPathEnv);
421 26 : if (subtitleLogPath && subtitleLogPath[0] != '\0')
422 : {
423 10 : std::string error;
424 10 : if (!writeSubtitleDataToFile(subtitleLogPath, data, error))
425 : {
426 8 : RIALTO_SERVER_LOG_ERROR("Failed to capture subtitle data to '%s': %s", subtitleLogPath, error.c_str());
427 8 : if (isEnvironmentVariableEnabled(kSubtitleDataEnv))
428 : {
429 1 : logSubtitleData(data);
430 : }
431 : }
432 10 : }
433 16 : else if (isEnvironmentVariableEnabled(kSubtitleDataEnv))
434 : {
435 9 : logSubtitleData(data);
436 : }
437 :
438 26 : firebolt::rialto::wrappers::ITextTrackWrapper::DataType wrapperDataType{};
439 26 : if (datatype == DataType::WebVTT)
440 : {
441 1 : wrapperDataType = firebolt::rialto::wrappers::ITextTrackWrapper::DataType::WEBVTT;
442 : }
443 25 : else if (datatype == DataType::TTML)
444 : {
445 23 : wrapperDataType = firebolt::rialto::wrappers::ITextTrackWrapper::DataType::TTML;
446 : }
447 2 : else if (datatype == DataType::CC)
448 : {
449 1 : RIALTO_SERVER_LOG_WARN("Data received for ClosedCaptions. It should not happen.");
450 1 : return false;
451 : }
452 : else
453 : {
454 1 : RIALTO_SERVER_LOG_ERROR("Unknown data type");
455 1 : return false;
456 : }
457 :
458 24 : const uint32_t result = m_textTrackWrapper->sendSessionData(sessionId, wrapperDataType, displayOffsetMs, data);
459 24 : if (m_thunderWrapper->isSuccessful(result))
460 : {
461 23 : RIALTO_SERVER_LOG_DEBUG("Sending data to TextTrack session %u was successful; size %zu", sessionId, data.size());
462 23 : return true;
463 : }
464 :
465 1 : RIALTO_SERVER_LOG_ERROR("Failed to send data to TextTrack session %u; error %s", sessionId,
466 : m_thunderWrapper->errorToString(result));
467 1 : return false;
468 : }
469 :
470 50 : bool TextTrackAccessor::createTextTrackControlInterface()
471 : {
472 50 : if (!m_textTrackPluginWrapper)
473 : {
474 1 : RIALTO_SERVER_LOG_ERROR("TextTrackPlugin is null!");
475 1 : return false;
476 : }
477 :
478 49 : uint32_t openResult = m_textTrackPluginWrapper->open();
479 :
480 49 : if (m_thunderWrapper->isSuccessful(openResult))
481 : {
482 48 : if (m_textTrackPluginWrapper->isOperational())
483 : {
484 47 : m_textTrackWrapper = m_textTrackPluginWrapper->interface();
485 47 : if (m_textTrackWrapper)
486 : {
487 46 : RIALTO_SERVER_LOG_INFO("Created TextTrack interface");
488 46 : return true;
489 : }
490 : else
491 : {
492 1 : RIALTO_SERVER_LOG_ERROR("Failed to create TextTrack interface");
493 : }
494 : }
495 : else
496 : {
497 1 : RIALTO_SERVER_LOG_ERROR("TextTrack plugin is NOT operational");
498 : }
499 : }
500 : else
501 : {
502 1 : RIALTO_SERVER_LOG_ERROR("Failed to open TextTrack plugin; error '%s'",
503 : m_thunderWrapper->errorToString(openResult));
504 : }
505 :
506 3 : return false;
507 : }
508 :
509 2 : bool TextTrackAccessor::setSessionWebVTTSelection(uint32_t sessionId)
510 : {
511 2 : uint32_t result = m_textTrackWrapper->setSessionWebVTTSelection(sessionId);
512 :
513 2 : if (m_thunderWrapper->isSuccessful(result))
514 : {
515 1 : RIALTO_SERVER_LOG_INFO("Setting WebVTT selection for session %u was successful", sessionId);
516 1 : return true;
517 : }
518 :
519 1 : RIALTO_SERVER_LOG_ERROR("Failed to set WebVTT selection for session %u; error %s", sessionId,
520 : m_thunderWrapper->errorToString(result));
521 1 : return false;
522 : }
523 :
524 2 : bool TextTrackAccessor::setSessionTTMLSelection(uint32_t sessionId)
525 : {
526 2 : uint32_t result = m_textTrackWrapper->setSessionTTMLSelection(sessionId);
527 2 : if (m_thunderWrapper->isSuccessful(result))
528 : {
529 1 : RIALTO_SERVER_LOG_INFO("Setting TTML selection for session %u was successful", sessionId);
530 1 : return true;
531 : }
532 :
533 1 : RIALTO_SERVER_LOG_ERROR("Failed to set TTML selection for session %u; error %s", sessionId,
534 : m_thunderWrapper->errorToString(result));
535 1 : return false;
536 : }
537 :
538 2 : bool TextTrackAccessor::setSessionCCSelection(uint32_t sessionId, const std::string &service)
539 : {
540 2 : uint32_t result = m_textTrackWrapper->setSessionClosedCaptionsService(sessionId, service);
541 2 : if (m_thunderWrapper->isSuccessful(result))
542 : {
543 1 : RIALTO_SERVER_LOG_INFO("Setting CC selection service '%s' for session %u was successful", service.c_str(),
544 : sessionId);
545 1 : return true;
546 : }
547 :
548 1 : RIALTO_SERVER_LOG_ERROR("Failed to set CC selection service '%s' for session %u; error %s", service.c_str(),
549 : sessionId, m_thunderWrapper->errorToString(result));
550 1 : return false;
551 : }
552 :
553 0 : bool TextTrackAccessor::resetSession(uint32_t sessionId)
554 : {
555 0 : uint32_t result = m_textTrackWrapper->resetSession(sessionId);
556 0 : if (m_thunderWrapper->isSuccessful(result))
557 : {
558 0 : RIALTO_SERVER_LOG_MIL("Resseting session %u was successful", sessionId);
559 0 : return true;
560 : }
561 :
562 0 : RIALTO_SERVER_LOG_ERROR("Failed to reset session %u; error %s", sessionId, m_thunderWrapper->errorToString(result));
563 0 : return false;
564 : }
565 :
566 2 : bool TextTrackAccessor::associateVideoDecoder(uint32_t sessionId, const std::string &videoDecoder)
567 : {
568 2 : uint32_t result = m_textTrackWrapper->associateVideoDecoder(sessionId, videoDecoder);
569 2 : if (m_thunderWrapper->isSuccessful(result))
570 : {
571 1 : RIALTO_SERVER_LOG_MIL("Associating video decoder '%s' with session %u was successful", videoDecoder.c_str(),
572 : sessionId);
573 1 : return true;
574 : }
575 :
576 1 : RIALTO_SERVER_LOG_ERROR("Failed to associate video decoder '%s' with session %u; error %s", videoDecoder.c_str(),
577 : sessionId, m_thunderWrapper->errorToString(result));
578 1 : return false;
579 : }
580 :
581 : } // namespace firebolt::rialto::server
|