69 changed files with 9635 additions and 1284 deletions
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,216 @@
@@ -0,0 +1,216 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// Some code by AI //
|
||||
// //
|
||||
// This program is free software; you can redistribute it and/or modify //
|
||||
// it under the terms of the GNU General Public License as published by //
|
||||
// the Free Software Foundation as version 3 of the License, or //
|
||||
// (at your option) any later version. //
|
||||
// //
|
||||
// This program is distributed in the hope that it will be useful, //
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
|
||||
// GNU General Public License V3 for more details. //
|
||||
// //
|
||||
// You should have received a copy of the GNU General Public License //
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifndef INCLUDE_DVBDEMODHBBTV_H |
||||
#define INCLUDE_DVBDEMODHBBTV_H |
||||
|
||||
#include <vector> |
||||
|
||||
#include <QElapsedTimer> |
||||
#include <QJsonObject> |
||||
#include <QMap> |
||||
#include <QObject> |
||||
#include <QPointer> |
||||
#include <QRectF> |
||||
#include <QTimer> |
||||
|
||||
#include "dtv/dtvapps.h" |
||||
|
||||
class DTVCarouselServer; |
||||
class QKeyEvent; |
||||
class QNetworkAccessManager; |
||||
class QWebEnginePage; |
||||
class QWebEngineProfile; |
||||
class QWebEngineView; |
||||
class QWidget; |
||||
class DVBDemodHbbTVInterceptor; |
||||
|
||||
// Runs the HbbTV applications (TS 102 796) of the service played, in a browser (Qt WebEngine) over the video: the
|
||||
// AUTOSTART one of the service's AIT when it's played, and those it starts (as from the red button), from the
|
||||
// service's carousels (served by a DTVCarouselServer) or from the internet. The OIPF objects applications use (the
|
||||
// application manager, video/broadcast, configuration...) are oipf.js's. Keys in the application's keyset are given to
|
||||
// it; the video is drawn where its video/broadcast object is
|
||||
class DVBDemodHbbTV : public QObject |
||||
{ |
||||
Q_OBJECT |
||||
|
||||
public: |
||||
struct Channel { |
||||
int m_networkId = -1; //!< original_network_id
|
||||
int m_transportStreamId = -1; |
||||
int m_serviceId = 0; |
||||
int m_lcn = -1; |
||||
QString m_name; |
||||
bool m_radio = false; |
||||
bool m_hd = false; |
||||
}; |
||||
|
||||
struct Programme { |
||||
int m_eventId = 0; |
||||
QString m_name; |
||||
QString m_description; |
||||
qint64 m_start = 0; //!< UTC, seconds since 1970
|
||||
int m_duration = 0; //!< Seconds
|
||||
}; |
||||
|
||||
DVBDemodHbbTV(DTVApps *apps, QObject *parent = nullptr); |
||||
~DVBDemodHbbTV(); |
||||
|
||||
//! The browser, as a child of the video widget: transparent, not taking the mouse or focus (keys are given by
|
||||
//! keyPress()), hidden while no application's visible. Its geometry is set with setViewGeometry()
|
||||
QWebEngineView *createView(QWidget *parent); |
||||
void setViewGeometry(const QRect& geometry); |
||||
//! The view moved to another widget, as the full screen video's
|
||||
void setViewParent(QWidget *parent); |
||||
//! The view hidden while something's shown over the video instead (as the programme guide)
|
||||
void setSuppressed(bool suppressed); |
||||
//! The keyboard focus given to the page while it's shown (so the application's focused items show as focused),
|
||||
//! else to the video widget. The page's keys are caught before the browser has them: those in the application's
|
||||
//! keyset given to it as keyPress() gives them, others to the video widget
|
||||
void takeFocus(); |
||||
QWebEnginePage *getPage() { return m_page; } |
||||
//! Whether applications may use the internet: if not, only the carousels are loaded from
|
||||
void setNetworkAllowed(bool allowed); |
||||
//! The user agent sent, for testing as a particular TV: empty for SDRangel's own. The environment variable
|
||||
//! DTV_HBBTV_USER_AGENT sets it too
|
||||
void setUserAgent(const QString& userAgent); |
||||
QString getUserAgent() const; |
||||
//! The ids of DVB channels: ID_DVB_T 12, ID_DVB_T2 16, ID_DVB_S 11, ID_DVB_S2 15
|
||||
void setIdType(int idType) { m_idType = idType; } |
||||
|
||||
//! The service played (its m_serviceId 0 if none), and the multiplex's others. A new service stops the application
|
||||
void setService(const Channel& channel, const std::vector<Channel>& channels, const std::vector<Programme>& programmes); |
||||
//! After channelChangeRequested: whether the service's playing
|
||||
void channelChangeResult(bool ok); |
||||
void stop(); //!< Stops the application, until the service changes
|
||||
|
||||
//! A key, given to the application if it's in its keyset: true if it was. Red with no application running
|
||||
//! starts the AUTOSTART one again (as when it's exited), and is given to it when it asks for it
|
||||
bool keyPress(QKeyEvent *event); |
||||
bool keyRelease(QKeyEvent *event); |
||||
//! The red button, as pressed and released: false if there's no application for it
|
||||
bool pressRed(); |
||||
//! The service has an AUTOSTART HbbTV application that can be loaded (whether it's running or not)
|
||||
bool hasAutostartApp() const; |
||||
|
||||
bool isRunning() const { return !m_appUrl.isEmpty(); } |
||||
//! What's being waited for, after the user's pressed red or a key the application has: the application starting,
|
||||
//! or loading (with how much of its carousel's been received). Empty when there's nothing to say
|
||||
QString getStatus() const; |
||||
//! The page's showing the status itself (over the application): it needn't be shown over the video
|
||||
bool isStatusInPage() const { return !m_pageStatus.isEmpty(); } |
||||
bool isVisible() const { return m_visible; } |
||||
int getKeyset() const { return m_keyset; } |
||||
QString getAppUrl() const { return m_appUrl; } |
||||
QString getAppName() const { return m_appName; } |
||||
|
||||
//! An event of the player playing the application's media (mediaRequest's id): metadata (duration, width,
|
||||
//! height), playing, time (position), waiting, ended, error (code, message)
|
||||
void mediaEvent(int id, const QString& type, const QJsonObject& data = QJsonObject()); |
||||
int getMediaId() const { return m_mediaId; } |
||||
|
||||
//! Map a Qt key to an HbbTV key code and the keyset bit it needs: false if it isn't one
|
||||
static bool keyCode(int qtKey, int& code, int& keysetBit); |
||||
//! What applications have stored (cookies, as sign-ins, and the cache) forgotten
|
||||
static void clearData(); |
||||
|
||||
signals: |
||||
void visibleChanged(bool visible); |
||||
//! Where the application wants the video, as fractions of the page: null for all of it
|
||||
void videoAreaChanged(const QRectF& area); |
||||
void channelChangeRequested(int networkId, int transportStreamId, int serviceId); |
||||
void channelStepRequested(int direction); |
||||
void appStarted(const QString& url, const QString& name); |
||||
//! The application's media (as iPlayer's video): command load (url, with FFmpeg's options), play, pause, seek
|
||||
//! (position, seconds) or stop. Media's played by the GUI's player, under the page
|
||||
void mediaRequest(const QString& command, int id, const QString& url, const QMap<QString, QString>& options, double position); |
||||
void appStopped(); |
||||
//! The application's console messages, and what it does, for the log
|
||||
void log(const QString& message); |
||||
|
||||
protected: |
||||
bool eventFilter(QObject *object, QEvent *event) override; |
||||
|
||||
private: |
||||
friend class DVBDemodHbbTVPage; |
||||
|
||||
//! Applications' profile: kept (cookies, local storage, cache), so sign-ins last from one run to the next. Shared
|
||||
//! by the demodulators running applications (a profile's storage can only be open once), and deleted with the last
|
||||
static QWebEngineProfile *acquireProfile(); |
||||
static void releaseProfile(); |
||||
|
||||
void check(); |
||||
void launch(const DTVApps::App& app, const QString& suffix); |
||||
void navigate(const QString& url, const QString& name, uint32_t organisationId, int applicationId, bool autostart); |
||||
void message(const QJsonObject& message); |
||||
void consoleMessage(int level, const QString& message, int line, const QString& source); |
||||
void createApplication(const QString& uri); |
||||
void destroyApplication(); |
||||
void setVisible(bool visible); |
||||
void showView(); |
||||
void loadFinished(bool ok); |
||||
void updateScript(); |
||||
void showStatus(); //!< getStatus() in the page, over what the application shows
|
||||
void updateProxy(); |
||||
QJsonObject configuration() const; |
||||
QJsonObject channelJson(const Channel& channel) const; |
||||
QString appUrl(const DTVApps::App& app) const; |
||||
void makeTransparent(); |
||||
void downloadRequested(const QUrl& url, const QString& mimeType); |
||||
|
||||
DTVApps *m_apps; |
||||
DTVCarouselServer *m_server; |
||||
QWebEngineProfile *m_profile; |
||||
QWebEnginePage *m_page; |
||||
QPointer<QWebEngineView> m_view; |
||||
DVBDemodHbbTVInterceptor *m_interceptor; |
||||
QNetworkAccessManager *m_network; |
||||
QString m_oipfScript; |
||||
QTimer m_timer; |
||||
int m_idType; |
||||
|
||||
Channel m_channel; |
||||
std::vector<Channel> m_channels; |
||||
std::vector<Programme> m_programmes; |
||||
|
||||
QString m_appUrl; //!< Running, empty if none
|
||||
QString m_appName; |
||||
uint32_t m_organisationId; |
||||
int m_applicationId; |
||||
bool m_autostartApp; //!< The running one's the service's AUTOSTART application
|
||||
bool m_autostartDisabled; //!< Until the service changes (it destroyed itself, or failed to load)
|
||||
qint64 m_autostartRetryAt; //!< When a failed AUTOSTART application's tried again (ms since epoch), 0 none
|
||||
bool m_visible; |
||||
bool m_loaded; |
||||
bool m_suppressed; |
||||
int m_keyset; |
||||
QRectF m_videoArea; |
||||
bool m_pendingRed; //!< Red's to be given to the application started for it, once it asks for it
|
||||
int m_mediaId; //!< Of the media being played, 0 if none
|
||||
QElapsedTimer m_userRequest; //!< Since the user last pressed red or gave the application a key
|
||||
QElapsedTimer m_failed; //!< Since an application last failed to load
|
||||
int m_appCarouselPid; //!< The carousel the running application's loaded from, -1 if none
|
||||
int m_loadsStarted; //!< Qt 5: page loads started, to tell a failed load from one replaced by another
|
||||
QElapsedTimer m_loadedAt; //!< Since the running application's page loaded
|
||||
bool m_keysetSinceLoad; //!< It's set its keyset since: it's ready
|
||||
QString m_pageStatus; //!< Status last shown in the page
|
||||
QElapsedTimer m_redDelivered; //!< Since red was last given to the application
|
||||
QElapsedTimer m_pendingRedTimer; |
||||
}; |
||||
|
||||
#endif // INCLUDE_DVBDEMODHBBTV_H
|
||||
@ -0,0 +1,938 @@
@@ -0,0 +1,938 @@
|
||||
// The objects an HbbTV application (TS 102 796, with the OIPF DAE objects it uses) expects of the TV it runs on, for
|
||||
// applications run by SDRangel's DVB demodulator. Injected into each page before its own scripts run, after
|
||||
// window.__sdrangelHbbTVConfig is set to the TV's state: the service played and the others of the multiplex,
|
||||
// the application's ids, and the languages and country. Messages go to SDRangel as console messages (\u0001sdrangel:
|
||||
// and JSON), and SDRangel calls window.__sdrangelHbbTV's functions: key() for keys in the application's keyset,
|
||||
// update() when the service or the list changes, channelChanged() after a setChannel()
|
||||
(function () { |
||||
'use strict'; |
||||
|
||||
if (window.__sdrangelHbbTV) { |
||||
return; |
||||
} |
||||
|
||||
var config = window.__sdrangelHbbTVConfig || {}; |
||||
var keysetValue = 0; |
||||
var ownerApplication = null; |
||||
var videoObjects = []; // video/broadcast objects bound to the service, or with a channel set
|
||||
var state = new WeakMap(); // Each object's state
|
||||
var lastVideo = ''; |
||||
|
||||
function send(message) { |
||||
console.log('\u0001sdrangel:' + JSON.stringify(message)); |
||||
} |
||||
|
||||
// Keys (OIPF DAE 7.2.5.2, TS 102 796 Annex A)
|
||||
var keys = { |
||||
VK_LEFT: 37, VK_UP: 38, VK_RIGHT: 39, VK_DOWN: 40, VK_ENTER: 13, VK_BACK: 461, |
||||
VK_RED: 403, VK_GREEN: 404, VK_YELLOW: 405, VK_BLUE: 406, |
||||
VK_0: 48, VK_1: 49, VK_2: 50, VK_3: 51, VK_4: 52, VK_5: 53, VK_6: 54, VK_7: 55, VK_8: 56, VK_9: 57, |
||||
VK_PLAY: 415, VK_PAUSE: 19, VK_PLAY_PAUSE: 402, VK_STOP: 413, VK_FAST_FWD: 417, VK_REWIND: 412, |
||||
VK_TRACK_NEXT: 425, VK_TRACK_PREV: 424, VK_RECORD: 416, VK_PAGE_UP: 33, VK_PAGE_DOWN: 34, |
||||
VK_INFO: 457, VK_TELETEXT: 459, VK_SUBTITLE: 460 |
||||
}; |
||||
|
||||
window.KeyEvent = window.KeyEvent || {}; |
||||
|
||||
Object.keys(keys).forEach(function (name) { |
||||
window.KeyEvent[name] = keys[name]; |
||||
window[name] = keys[name]; |
||||
}); |
||||
|
||||
var keyNames = { |
||||
37: 'ArrowLeft', 38: 'ArrowUp', 39: 'ArrowRight', 40: 'ArrowDown', 13: 'Enter', 461: 'GoBack', |
||||
403: 'ColorF0Red', 404: 'ColorF1Green', 405: 'ColorF2Yellow', 406: 'ColorF3Blue', |
||||
415: 'MediaPlay', 19: 'MediaPause', 402: 'MediaPlayPause', 413: 'MediaStop', 417: 'MediaFastForward', |
||||
412: 'MediaRewind', 425: 'MediaTrackNext', 424: 'MediaTrackPrevious', 416: 'MediaRecord', |
||||
33: 'PageUp', 34: 'PageDown', 457: 'Info', 459: 'Teletext', 460: 'Subtitle' |
||||
}; |
||||
|
||||
// The physical key, as code gives it: applications that map keys by their own tables fall back to it (as the BBC's)
|
||||
var codeNames = { |
||||
37: 'ArrowLeft', 38: 'ArrowUp', 39: 'ArrowRight', 40: 'ArrowDown', 13: 'Enter', 461: 'BrowserBack', |
||||
403: 'ColorF0Red', 404: 'ColorF1Green', 405: 'ColorF2Yellow', 406: 'ColorF3Blue', |
||||
415: 'MediaPlay', 19: 'MediaPause', 402: 'MediaPlayPause', 413: 'MediaStop', 417: 'MediaFastForward', |
||||
412: 'MediaRewind', 425: 'MediaTrackNext', 424: 'MediaTrackPrevious', 416: 'MediaRecord', |
||||
33: 'PageUp', 34: 'PageDown', 457: 'Info', 460: 'Subtitle' |
||||
}; |
||||
|
||||
function keyEvent(type, code) { |
||||
var key = keyNames[code] || ((code >= 48) && (code <= 57) ? String.fromCharCode(code) : 'Unidentified'); |
||||
var physical = codeNames[code] || ((code >= 48) && (code <= 57) ? 'Digit' + String.fromCharCode(code) : ''); |
||||
var event = new KeyboardEvent(type, { bubbles: true, cancelable: true, key: key, code: physical }); |
||||
// Applications read keyCode (or which), which a KeyboardEvent's dictionary doesn't set
|
||||
Object.defineProperty(event, 'keyCode', { get: function () { return code; } }); |
||||
Object.defineProperty(event, 'which', { get: function () { return code; } }); |
||||
Object.defineProperty(event, 'charCode', { get: function () { return type === 'keypress' ? code : 0; } }); |
||||
var target = document.activeElement || document.body || document; |
||||
target.dispatchEvent(event); |
||||
} |
||||
|
||||
// The keyset (OIPF DAE 7.2.5)
|
||||
var keyset = { |
||||
RED: 0x1, GREEN: 0x2, YELLOW: 0x4, BLUE: 0x8, NAVIGATION: 0x10, VCR: 0x20, SCROLL: 0x40, INFO: 0x80, |
||||
NUMERIC: 0x100, ALPHA: 0x200, OTHER: 0x400, |
||||
maximumValue: 0x1FF, |
||||
otherKeys: [], |
||||
maximumOtherKeys: [], |
||||
supportsPointer: false, |
||||
setValue: function (value, otherKeys) { |
||||
keysetValue = (value | 0) & 0x7FF; |
||||
send({ t: 'keyset', v: keysetValue }); |
||||
return keysetValue; |
||||
}, |
||||
getKey: function (code) { return null; }, |
||||
getKeyLabel: function (code) { return null; } |
||||
}; |
||||
|
||||
Object.defineProperty(keyset, 'value', { get: function () { return keysetValue; } }); |
||||
|
||||
// Channels: of the configuration, as objects of OIPF DAE 7.13.11
|
||||
var ID_DVB_C = 10, ID_DVB_S = 11, ID_DVB_T = 12, ID_DVB_S2 = 15, ID_DVB_T2 = 16; |
||||
|
||||
function makeChannel(c) { |
||||
if (!c) { |
||||
return null; |
||||
} |
||||
|
||||
return { |
||||
channelType: c.radio ? 1 : 0, // TYPE_TV 0, TYPE_RADIO 1
|
||||
idType: c.idType || ID_DVB_T, |
||||
ccid: 'ccid:' + c.onid + '.' + c.tsid + '.' + c.sid, |
||||
onid: c.onid, |
||||
tsid: c.tsid, |
||||
sid: c.sid, |
||||
nid: c.onid, |
||||
name: c.name || '', |
||||
majorChannel: c.lcn > 0 ? c.lcn : 0, |
||||
minorChannel: 0, |
||||
dsd: null, |
||||
favourite: false, |
||||
favIDs: [], |
||||
locked: false, |
||||
manualBlock: false, |
||||
hidden: false, |
||||
ipBroadcastID: null, |
||||
longName: c.name || '', |
||||
description: '', |
||||
authorised: true, |
||||
genre: [], |
||||
isHD: !!c.hd, |
||||
is3D: false, |
||||
logoURL: null |
||||
}; |
||||
} |
||||
|
||||
function channelList() { |
||||
var list = (config.channels || []).map(makeChannel); |
||||
list.item = function (index) { return list[index] || null; }; |
||||
list.getChannel = function (ccid) { |
||||
for (var i = 0; i < list.length; i++) { |
||||
if (list[i].ccid === ccid) { |
||||
return list[i]; |
||||
} |
||||
} |
||||
return null; |
||||
}; |
||||
list.getChannelByTriplet = function (onid, tsid, sid) { |
||||
for (var i = 0; i < list.length; i++) { |
||||
if ((list[i].onid === onid) && ((tsid === undefined) || (tsid === null) || (tsid < 0) || (list[i].tsid === tsid)) && (list[i].sid === sid)) { |
||||
return list[i]; |
||||
} |
||||
} |
||||
return null; |
||||
}; |
||||
list.getChannelBySourceID = function () { return null; }; |
||||
return list; |
||||
} |
||||
|
||||
function programmes() { |
||||
var list = (config.programmes || []).map(function (p) { |
||||
return { |
||||
name: p.name || '', description: p.description || '', longDescription: p.description || '', |
||||
startTime: p.start, duration: p.duration, programmeID: p.id !== undefined ? String(p.id) : '', |
||||
programmeIDType: 0, channelID: config.channel ? makeChannel(config.channel).ccid : '', |
||||
parentalRatings: [], getSIDescriptors: function () { return []; } |
||||
}; |
||||
}); |
||||
list.item = function (index) { return list[index] || null; }; |
||||
return list; |
||||
} |
||||
|
||||
// The owner application (OIPF DAE 7.2.2)
|
||||
function application() { |
||||
if (ownerApplication) { |
||||
return ownerApplication; |
||||
} |
||||
|
||||
var privateData = { keyset: keyset, getFreeMem: function () { return 64 * 1024 * 1024; } }; |
||||
Object.defineProperty(privateData, 'currentChannel', { get: function () { return makeChannel(config.channel); } }); |
||||
|
||||
ownerApplication = { |
||||
visible: true, |
||||
active: true, |
||||
permissions: [], |
||||
isPrimaryReceiver: true, |
||||
privateData: privateData, |
||||
show: function () { this.visible = true; send({ t: 'show' }); return true; }, |
||||
hide: function () { this.visible = false; send({ t: 'hide' }); return true; }, |
||||
activate: function () { this.active = true; }, |
||||
deactivate: function () { this.active = false; }, |
||||
destroyApplication: function () { send({ t: 'destroy' }); }, |
||||
createApplication: function (uri, createChild) { |
||||
send({ t: 'create', uri: String(uri), child: !!createChild }); |
||||
return { visible: false, privateData: {}, show: function () {}, hide: function () {}, destroyApplication: function () {} }; |
||||
}, |
||||
startWidget: function () { return null; }, |
||||
stopWidget: function () {}, |
||||
addEventListener: function () {}, |
||||
removeEventListener: function () {} |
||||
}; |
||||
return ownerApplication; |
||||
} |
||||
|
||||
var configuration = { |
||||
preferredAudioLanguage: config.language || 'eng', |
||||
preferredSubtitleLanguage: config.language || 'eng', |
||||
preferredUILanguage: config.language || 'eng', |
||||
countryId: config.country || 'GBR', |
||||
regionId: 0, |
||||
pvrPolicy: 0, |
||||
pvrSaveEpisodes: 0, |
||||
pvrSaveDays: 0, |
||||
pvrStartPadding: 0, |
||||
pvrEndPadding: 0, |
||||
preferredTimeShiftMode: 0, |
||||
subtitlesEnabled: false, |
||||
audioDescriptionEnabled: false, |
||||
getText: function () { return null; }, |
||||
setText: function () {} |
||||
}; |
||||
|
||||
var localSystem = { |
||||
deviceID: 'sdrangel', |
||||
systemReady: true, |
||||
vendorName: 'SDRangel', |
||||
modelName: 'DVBDemod', |
||||
familyName: 'SDRangel', |
||||
softwareVersion: config.version || '', |
||||
hardwareVersion: '', |
||||
serialNumber: '', |
||||
releaseVersion: 0, |
||||
majorVersion: 1, |
||||
minorVersion: 0, |
||||
oipfProfile: 'OITF_HD_UIPROF+DVB_T+DVB_T2+DVB_S+DVB_S2', |
||||
pvrEnabled: false, |
||||
ciplusEnabled: false, |
||||
powerState: 1, |
||||
previousPowerState: 1, |
||||
timeCurrentPowerState: 0, |
||||
volume: 100, |
||||
mute: false, |
||||
tvStandardsSupported: 0, |
||||
tvStandard: 0, |
||||
setPowerState: function () { return false; }, |
||||
setPvrSupport: function () { return 0; } |
||||
}; |
||||
|
||||
function capabilitiesXml() { |
||||
var xml = '<profilelist><ui_profile name="OITF_HD_UIPROF+DVB_T+DVB_T2+DVB_S+DVB_S2"><ext><colorkeys>true</colorkeys>' + |
||||
'<video_broadcast type="ID_DVB_T" scaling="arbitrary" minSize="0">true</video_broadcast></ext></ui_profile>' + |
||||
'<broadcast>urn:dvb:broadcast:ird:video:25_Hz_H.264_AVC_HDTV_IRD</broadcast></profilelist>'; |
||||
return new DOMParser().parseFromString(xml, 'text/xml'); |
||||
} |
||||
|
||||
// video/broadcast (OIPF DAE 7.13.1)
|
||||
var PLAYSTATE_UNREALIZED = 0, PLAYSTATE_CONNECTING = 1, PLAYSTATE_PRESENTING = 2, PLAYSTATE_STOPPED = 3; |
||||
|
||||
function videoState(object) { |
||||
var s = state.get(object); |
||||
|
||||
if (!s) { |
||||
s = { playState: PLAYSTATE_UNREALIZED, fullScreen: false, pendingChannel: null }; |
||||
state.set(object, s); |
||||
} |
||||
|
||||
return s; |
||||
} |
||||
|
||||
function fire(object, name, properties, handlerArguments) { |
||||
var handler = object['on' + name]; |
||||
|
||||
if (typeof handler === 'function') { |
||||
try { |
||||
handler.apply(object, handlerArguments); |
||||
} catch (e) { |
||||
console.error(e); |
||||
} |
||||
} |
||||
|
||||
var event = new CustomEvent(name, { bubbles: false }); |
||||
|
||||
Object.keys(properties).forEach(function (key) { |
||||
Object.defineProperty(event, key, { value: properties[key] }); |
||||
}); |
||||
|
||||
object.dispatchEvent(event); |
||||
} |
||||
|
||||
function setPlayState(object, playState, error) { |
||||
var s = videoState(object); |
||||
|
||||
if (s.playState === playState) { |
||||
return; |
||||
} |
||||
|
||||
s.playState = playState; |
||||
|
||||
if ((playState === PLAYSTATE_PRESENTING) || (playState === PLAYSTATE_CONNECTING)) { |
||||
if (videoObjects.indexOf(object) < 0) { |
||||
videoObjects.push(object); |
||||
} |
||||
} else { |
||||
videoObjects = videoObjects.filter(function (o) { return o !== object; }); |
||||
} |
||||
|
||||
fire(object, 'PlayStateChange', { state: playState, error: error }, [playState, error]); |
||||
reportVideo(); |
||||
} |
||||
|
||||
var videoBroadcast = { |
||||
bindToCurrentChannel: function () { |
||||
setPlayState(this, PLAYSTATE_PRESENTING); |
||||
return makeChannel(config.channel); |
||||
}, |
||||
setChannel: function (channel, trickplay, contentAccessDescriptorURL, quiet) { |
||||
if (!channel) { |
||||
setPlayState(this, PLAYSTATE_UNREALIZED); |
||||
return; |
||||
} |
||||
|
||||
var current = config.channel; |
||||
|
||||
if (current && (channel.sid === current.sid) && (channel.onid === current.onid)) { |
||||
setPlayState(this, PLAYSTATE_PRESENTING); |
||||
var self = this; |
||||
setTimeout(function () { fire(self, 'ChannelChangeSucceeded', { channel: makeChannel(current) }, [makeChannel(current)]); }, 0); |
||||
return; |
||||
} |
||||
|
||||
videoState(this).pendingChannel = channel; |
||||
setPlayState(this, PLAYSTATE_CONNECTING); |
||||
send({ t: 'setChannel', onid: channel.onid, tsid: channel.tsid, sid: channel.sid }); |
||||
}, |
||||
prevChannel: function () { send({ t: 'step', d: -1 }); }, |
||||
nextChannel: function () { send({ t: 'step', d: 1 }); }, |
||||
stop: function () { setPlayState(this, PLAYSTATE_STOPPED); }, |
||||
release: function () { setPlayState(this, PLAYSTATE_UNREALIZED); }, |
||||
setFullScreen: function (fullScreen) { |
||||
videoState(this).fullScreen = !!fullScreen; |
||||
fire(this, 'FullScreenChange', {}, []); |
||||
reportVideo(); |
||||
}, |
||||
getChannelConfig: function () { |
||||
return { channelList: channelList(), favouriteLists: [], currentFavouriteList: null, onChannelScan: null }; |
||||
}, |
||||
getComponents: function (type) { |
||||
// VIDEO 0, AUDIO 1, SUBTITLE 2
|
||||
if ((type === 1) || (type === undefined) || (type === null)) { |
||||
var audio = [{ type: 1, componentTag: 0, pid: 0, encoding: 'MPEG1_L2', language: config.language || 'eng', audioDescription: false, audioChannels: 2 }]; |
||||
return type === 1 ? audio : [{ type: 0, componentTag: 0, pid: 0, encoding: 'H264', aspectRatio: 1.78 }].concat(audio); |
||||
} |
||||
return type === 0 ? [{ type: 0, componentTag: 0, pid: 0, encoding: 'H264', aspectRatio: 1.78 }] : []; |
||||
}, |
||||
getCurrentActiveComponents: function (type) { return this.getComponents(type); }, |
||||
selectComponent: function () {}, |
||||
unselectComponent: function () {}, |
||||
setVolume: function () { return true; }, |
||||
getVolume: function () { return 100; }, |
||||
createChannelObject: function (idType, onid, tsid, sid) { |
||||
return makeChannel({ idType: idType, onid: onid, tsid: tsid, sid: sid }); |
||||
} |
||||
}; |
||||
|
||||
var applicationManager = { |
||||
getOwnerApplication: function (doc) { return application(); }, |
||||
getChildApplications: function () { return []; }, |
||||
gc: function () {}, |
||||
onLowMemory: null, |
||||
onApplicationLoaded: null, |
||||
onApplicationUnloaded: null, |
||||
onApplicationLoadError: null |
||||
}; |
||||
|
||||
var objectTypes = { |
||||
'application/oipfapplicationmanager': applicationManager, |
||||
'application/oipfconfiguration': { }, |
||||
'application/oipfcapabilities': { |
||||
hasCapability: function (capability) { return false; }, |
||||
extraSDVideoDecodes: 0, |
||||
extraHDVideoDecodes: 0 |
||||
}, |
||||
'video/broadcast': videoBroadcast, |
||||
'application/oipfdrmagent': { |
||||
sendDRMMessage: function () { return ''; }, |
||||
DRMSystemStatus: function () { return 1; } |
||||
}, |
||||
'application/oipfparentalcontrolmanager': { |
||||
parentalRatingSchemes: [], |
||||
isPINEntryLocked: false, |
||||
getBlockUnrated: function () { return false; } |
||||
}, |
||||
'application/oipfsearchmanager': { |
||||
createSearch: function () { return null; }, |
||||
getChannelConfig: function () { return videoBroadcast.getChannelConfig(); } |
||||
} |
||||
}; |
||||
|
||||
function typeOf(object) { |
||||
return (object.getAttribute('type') || '').toLowerCase(); |
||||
} |
||||
|
||||
// The objects' methods and properties, on every <object>, of the ones of its type: an application's objects may be
|
||||
// in its markup, before any script of its runs
|
||||
var methods = {}; |
||||
|
||||
Object.keys(objectTypes).forEach(function (type) { |
||||
Object.keys(objectTypes[type]).forEach(function (name) { |
||||
if (typeof objectTypes[type][name] === 'function') { |
||||
methods[name] = methods[name] || {}; |
||||
methods[name][type] = objectTypes[type][name]; |
||||
} |
||||
}); |
||||
}); |
||||
|
||||
Object.keys(methods).forEach(function (name) { |
||||
if (name in HTMLObjectElement.prototype) { |
||||
return; |
||||
} |
||||
|
||||
Object.defineProperty(HTMLObjectElement.prototype, name, { |
||||
configurable: true, |
||||
value: function () { |
||||
var method = methods[name][typeOf(this)]; |
||||
return method ? method.apply(this, arguments) : undefined; |
||||
} |
||||
}); |
||||
}); |
||||
|
||||
var properties = { |
||||
playState: function (o) { return typeOf(o) === 'video/broadcast' ? videoState(o).playState : undefined; }, |
||||
fullScreen: function (o) { return typeOf(o) === 'video/broadcast' ? videoState(o).fullScreen : undefined; }, |
||||
currentChannel: function (o) { |
||||
return (typeOf(o) === 'video/broadcast') && (videoState(o).playState !== PLAYSTATE_UNREALIZED) ? makeChannel(config.channel) : null; |
||||
}, |
||||
programmes: function (o) { return typeOf(o) === 'video/broadcast' ? programmes() : undefined; }, |
||||
configuration: function (o) { return typeOf(o) === 'application/oipfconfiguration' ? configuration : undefined; }, |
||||
localSystem: function (o) { return typeOf(o) === 'application/oipfconfiguration' ? localSystem : undefined; }, |
||||
xmlCapabilities: function (o) { return typeOf(o) === 'application/oipfcapabilities' ? capabilitiesXml() : undefined; }, |
||||
DRMSystemStatus: function (o) { return undefined; } |
||||
}; |
||||
|
||||
Object.keys(properties).forEach(function (name) { |
||||
if (name in HTMLObjectElement.prototype) { |
||||
return; |
||||
} |
||||
|
||||
Object.defineProperty(HTMLObjectElement.prototype, name, { |
||||
configurable: true, |
||||
get: function () { return properties[name](this); } |
||||
}); |
||||
}); |
||||
|
||||
// The constants of video/broadcast
|
||||
[['PLAYSTATE_UNREALIZED', 0], ['PLAYSTATE_CONNECTING', 1], ['PLAYSTATE_PRESENTING', 2], ['PLAYSTATE_STOPPED', 3], |
||||
['COMPONENT_TYPE_VIDEO', 0], ['COMPONENT_TYPE_AUDIO', 1], ['COMPONENT_TYPE_SUBTITLE', 2]].forEach(function (c) { |
||||
if (!(c[0] in HTMLObjectElement.prototype)) { |
||||
Object.defineProperty(HTMLObjectElement.prototype, c[0], { configurable: true, value: c[1] }); |
||||
} |
||||
}); |
||||
|
||||
window.oipfObjectFactory = { |
||||
isObjectSupported: function (type) { return String(type).toLowerCase() in objectTypes; }, |
||||
createVideoBroadcastObject: function () { return createObject('video/broadcast'); }, |
||||
createApplicationManagerObject: function () { return createObject('application/oipfApplicationManager'); }, |
||||
createConfigurationObject: function () { return createObject('application/oipfConfiguration'); }, |
||||
createCapabilitiesObject: function () { return createObject('application/oipfCapabilities'); }, |
||||
createDrmAgentObject: function () { return createObject('application/oipfDrmAgent'); }, |
||||
createParentalControlManagerObject: function () { return createObject('application/oipfParentalControlManager'); }, |
||||
createSearchManagerObject: function () { return createObject('application/oipfSearchManager'); }, |
||||
createVideoMpegObject: function () { return document.createElement('video'); } |
||||
}; |
||||
|
||||
function createObject(type) { |
||||
var object = document.createElement('object'); |
||||
object.setAttribute('type', type); |
||||
return object; |
||||
} |
||||
|
||||
// Where the video's shown: in the bound video/broadcast object, as fractions of the page (1280 by 720 pixels), or
|
||||
// full screen if there's none, or it's set to full screen
|
||||
function reportVideo() { |
||||
var message = { t: 'video', full: true }; |
||||
var width = window.innerWidth || 1280, height = window.innerHeight || 720; |
||||
|
||||
// Media SDRangel's playing first: it's the video shown
|
||||
var objects = (typeof playingMedia === 'function' ? playingMedia() : []).concat(videoObjects); |
||||
|
||||
for (var i = 0; i < objects.length; i++) { |
||||
var object = objects[i]; |
||||
|
||||
if (!object.isConnected || ((object instanceof HTMLObjectElement) && videoState(object).fullScreen)) { |
||||
continue; |
||||
} |
||||
|
||||
var style = window.getComputedStyle(object); |
||||
var rect = object.getBoundingClientRect(); |
||||
|
||||
if ((style.display === 'none') || (style.visibility === 'hidden') || (rect.width <= 0) || (rect.height <= 0)) { |
||||
message = { t: 'video', full: false, hidden: true }; |
||||
continue; |
||||
} |
||||
|
||||
message = { t: 'video', full: false, x: rect.left / width, y: rect.top / height, w: rect.width / width, h: rect.height / height }; |
||||
break; |
||||
} |
||||
|
||||
var text = JSON.stringify(message); |
||||
|
||||
if (text !== lastVideo) { |
||||
lastVideo = text; |
||||
send(message); |
||||
} |
||||
} |
||||
|
||||
setInterval(reportVideo, 250); |
||||
|
||||
// dvb: URLs (TS 102 851) of carousel files, as the server serves them: the page is http://dvb-onid-tsid-sid-ctag.localhost,
|
||||
// as its carousel's dvb://onid.tsid.sid.ctag/ would be on a TV. "dvb:/path" is of the page's own carousel
|
||||
function mapUrl(url) { |
||||
if ((typeof url !== 'string') || !/^dvb:/i.test(url) || /^dvb:\/\/current\.ait/i.test(url)) { |
||||
return url; |
||||
} |
||||
|
||||
var match = /^dvb:\/\/([0-9a-f]*)\.([0-9a-f]*)\.([0-9a-f]+)\.([0-9a-f]+)(\/.*)?$/i.exec(url); |
||||
|
||||
if (match) { |
||||
var port = /\.localhost$/.test(location.hostname) ? location.port : config.serverPort; |
||||
return 'http://dvb-' + (match[1] || 'x') + '-' + (match[2] || 'x') + '-' + match[3] + '-' + match[4] + '.localhost:' |
||||
+ port + (match[5] || '/'); |
||||
} |
||||
|
||||
var path = url.replace(/^dvb:/i, ''); |
||||
return new URL(path, location.href).href; |
||||
} |
||||
|
||||
// A carousel's page's request to another site, by SDRangel's proxy where it has one (with Qt 5), which makes it with
|
||||
// the page's TV origin: of the page's own origin, so not cross-origin
|
||||
function proxyUrl(url) { |
||||
if (!config.proxy || !/\.localhost$/.test(location.hostname)) { |
||||
return url; |
||||
} |
||||
|
||||
var target; |
||||
|
||||
try { |
||||
target = new URL(url, location.href); |
||||
} catch (e) { |
||||
return url; |
||||
} |
||||
|
||||
if (!/^https?:$/.test(target.protocol) || (target.origin === location.origin) || /\.localhost$/.test(target.hostname)) { |
||||
return url; |
||||
} |
||||
|
||||
return location.origin + config.proxy + '?url=' + encodeURIComponent(target.href); |
||||
} |
||||
|
||||
var xhrOpen = XMLHttpRequest.prototype.open; |
||||
XMLHttpRequest.prototype.open = function (method, url) { |
||||
var args = Array.prototype.slice.call(arguments); |
||||
args[1] = proxyUrl(mapUrl(String(url))); |
||||
return xhrOpen.apply(this, args); |
||||
}; |
||||
|
||||
if (window.fetch) { |
||||
var fetchOriginal = window.fetch; |
||||
window.fetch = function (input, init) { |
||||
return fetchOriginal.call(window, typeof input === 'string' ? proxyUrl(mapUrl(input)) : input, init); |
||||
}; |
||||
} |
||||
|
||||
// Media an application plays from the internet, as iPlayer's: the browser can't decode it (H.264 and AAC aren't
|
||||
// built into Qt WebEngine), so SDRangel's player plays it, under the page, in the element's place. The element
|
||||
// stands in for it: its source isn't given to the browser, and its state (paused, currentTime, duration...) and
|
||||
// events (loadedmetadata, playing, timeupdate, ended...) are SDRangel's player's
|
||||
var srcDescriptor = Object.getOwnPropertyDescriptor(HTMLMediaElement.prototype, 'src'); |
||||
var mediaLoad = HTMLMediaElement.prototype.load; |
||||
var mediaPlay = HTMLMediaElement.prototype.play; |
||||
var setAttributeOriginal = Element.prototype.setAttribute; |
||||
var removeAttributeOriginal = Element.prototype.removeAttribute; |
||||
var mediaProxies = {}; // By id
|
||||
var nextMediaId = 1; |
||||
var mediaState = new WeakMap(); // Element to its state
|
||||
|
||||
function isStreamUrl(url) { |
||||
return (typeof url === 'string') && /^https?:/i.test(url); |
||||
} |
||||
|
||||
function timeRanges(ranges) { |
||||
return { |
||||
length: ranges.length, |
||||
start: function (i) { return ranges[i][0]; }, |
||||
end: function (i) { return ranges[i][1]; } |
||||
}; |
||||
} |
||||
|
||||
function fireMedia(element, name) { |
||||
element.dispatchEvent(new Event(name)); |
||||
} |
||||
|
||||
// The element's properties, as its stand-in's
|
||||
function makeProxy(element) { |
||||
var m = { |
||||
id: nextMediaId++, url: '', paused: true, currentTime: 0, duration: NaN, readyState: 0, networkState: 0, |
||||
ended: false, seeking: false, error: null, width: 0, height: 0, volume: 1, muted: false, playbackRate: 1 |
||||
}; |
||||
mediaState.set(element, m); |
||||
mediaProxies[m.id] = element; |
||||
|
||||
var define = function (name, get, set) { |
||||
Object.defineProperty(element, name, { configurable: true, get: get, set: set }); |
||||
}; |
||||
|
||||
define('src', function () { return m.url; }, function (value) { setSource(element, value); }); |
||||
define('currentSrc', function () { return m.url; }); |
||||
define('currentTime', function () { return m.currentTime; }, function (value) { |
||||
value = Number(value); |
||||
|
||||
if (isNaN(value)) { |
||||
return; |
||||
} |
||||
|
||||
m.currentTime = value; |
||||
m.seeking = true; |
||||
m.ended = false; |
||||
fireMedia(element, 'seeking'); |
||||
send({ t: 'media', cmd: 'seek', id: m.id, position: value }); |
||||
}); |
||||
define('duration', function () { return m.duration; }); |
||||
define('paused', function () { return m.paused; }); |
||||
define('ended', function () { return m.ended; }); |
||||
define('seeking', function () { return m.seeking; }); |
||||
define('readyState', function () { return m.readyState; }); |
||||
define('networkState', function () { return m.networkState; }); |
||||
define('error', function () { return m.error; }); |
||||
define('videoWidth', function () { return m.width; }); |
||||
define('videoHeight', function () { return m.height; }); |
||||
define('volume', function () { return m.volume; }, function (value) { m.volume = value; fireMedia(element, 'volumechange'); }); |
||||
define('muted', function () { return m.muted; }, function (value) { m.muted = !!value; fireMedia(element, 'volumechange'); }); |
||||
define('playbackRate', function () { return m.playbackRate; }, function (value) { m.playbackRate = value; }); |
||||
define('seekable', function () { |
||||
if (isFinite(m.duration) && (m.duration > 0)) { |
||||
return timeRanges([[0, m.duration]]); |
||||
} |
||||
return timeRanges(m.readyState > 0 ? [[0, m.currentTime]] : []); |
||||
}); |
||||
define('buffered', function () { return timeRanges(m.readyState > 0 ? [[m.currentTime, m.currentTime + 5]] : []); }); |
||||
define('played', function () { return timeRanges([]); }); |
||||
|
||||
element.play = function () { |
||||
if (!m.url) { |
||||
return Promise.resolve(); |
||||
} |
||||
|
||||
if (m.paused || m.ended) |
||||
{ |
||||
if (m.ended) { |
||||
m.currentTime = 0; |
||||
m.ended = false; |
||||
send({ t: 'media', cmd: 'seek', id: m.id, position: 0 }); |
||||
} |
||||
|
||||
m.paused = false; |
||||
fireMedia(element, 'play'); |
||||
send({ t: 'media', cmd: 'play', id: m.id }); |
||||
} |
||||
|
||||
return Promise.resolve(); |
||||
}; |
||||
element.pause = function () { |
||||
if (m.url && !m.paused) { |
||||
m.paused = true; |
||||
send({ t: 'media', cmd: 'pause', id: m.id }); |
||||
fireMedia(element, 'pause'); |
||||
} |
||||
}; |
||||
element.load = function () { |
||||
var source = m.url || sourceChild(element); |
||||
|
||||
if (source) { |
||||
setSource(element, source); |
||||
} else { |
||||
stopProxy(element); |
||||
} |
||||
}; |
||||
|
||||
return m; |
||||
} |
||||
|
||||
function sourceChild(element) { |
||||
var sources = element.getElementsByTagName ? element.getElementsByTagName('source') : []; |
||||
|
||||
for (var i = 0; i < sources.length; i++) { |
||||
var src = sources[i].getAttribute('src'); |
||||
|
||||
if (src) { |
||||
return mapUrl(new URL(src, location.href).href); |
||||
} |
||||
} |
||||
|
||||
return ''; |
||||
} |
||||
|
||||
function stopProxy(element) { |
||||
var m = mediaState.get(element); |
||||
|
||||
if (m && m.url) { |
||||
send({ t: 'media', cmd: 'stop', id: m.id }); |
||||
m.url = ''; |
||||
m.paused = true; |
||||
m.readyState = 0; |
||||
m.networkState = 0; |
||||
m.duration = NaN; |
||||
fireMedia(element, 'emptied'); |
||||
} |
||||
} |
||||
|
||||
function setSource(element, value) { |
||||
var url = value ? mapUrl(new URL(String(value), location.href).href) : ''; |
||||
|
||||
if (!isStreamUrl(url)) { |
||||
stopProxy(element); |
||||
|
||||
if (value && srcDescriptor && srcDescriptor.set) { |
||||
srcDescriptor.set.call(element, value); |
||||
} |
||||
|
||||
return; |
||||
} |
||||
|
||||
var m = mediaState.get(element) || makeProxy(element); |
||||
console.log('[sdrangel] media ' + m.id + ': ' + url); |
||||
m.url = url; |
||||
m.paused = true; |
||||
m.ended = false; |
||||
m.currentTime = 0; |
||||
m.duration = NaN; |
||||
m.readyState = 0; |
||||
m.networkState = 2; // NETWORK_LOADING
|
||||
m.error = null; |
||||
fireMedia(element, 'loadstart'); |
||||
send({ t: 'media', cmd: 'load', id: m.id, url: url }); |
||||
|
||||
if (element.autoplay || element.hasAttribute('autoplay')) { |
||||
element.play(); |
||||
} |
||||
} |
||||
|
||||
if (srcDescriptor && srcDescriptor.set) { |
||||
Object.defineProperty(HTMLMediaElement.prototype, 'src', { |
||||
configurable: true, |
||||
get: srcDescriptor.get, |
||||
set: function (value) { setSource(this, value); } |
||||
}); |
||||
} |
||||
|
||||
Element.prototype.setAttribute = function (name, value) { |
||||
if ((this instanceof HTMLMediaElement) && (String(name).toLowerCase() === 'src')) { |
||||
setSource(this, value); |
||||
return; |
||||
} |
||||
|
||||
return setAttributeOriginal.apply(this, arguments); |
||||
}; |
||||
|
||||
Element.prototype.removeAttribute = function (name) { |
||||
if ((this instanceof HTMLMediaElement) && (String(name).toLowerCase() === 'src')) { |
||||
stopProxy(this); |
||||
} |
||||
|
||||
return removeAttributeOriginal.apply(this, arguments); |
||||
}; |
||||
|
||||
// An element given <source> children, then loaded or played
|
||||
HTMLMediaElement.prototype.load = function () { |
||||
var source = sourceChild(this); |
||||
|
||||
if (isStreamUrl(source)) { |
||||
setSource(this, source); |
||||
return; |
||||
} |
||||
|
||||
return mediaLoad.apply(this, arguments); |
||||
}; |
||||
|
||||
HTMLMediaElement.prototype.play = function () { |
||||
var source = sourceChild(this); |
||||
|
||||
if (isStreamUrl(source)) { |
||||
setSource(this, source); |
||||
return this.play(); |
||||
} |
||||
|
||||
return mediaPlay.apply(this, arguments); |
||||
}; |
||||
|
||||
// What SDRangel's player can play
|
||||
var canPlayType = HTMLMediaElement.prototype.canPlayType; |
||||
HTMLMediaElement.prototype.canPlayType = function (type) { |
||||
var t = String(type).toLowerCase(); |
||||
var result = /application\/dash\+xml|mpegurl|video\/mp4|audio\/mp4|video\/mp2t|audio\/mpeg|audio\/aac/.test(t) ? 'probably' |
||||
: canPlayType.call(this, type); |
||||
console.log('[sdrangel] canPlayType ' + type + ' "' + result + '"'); |
||||
return result; |
||||
}; |
||||
|
||||
// From SDRangel's player
|
||||
function mediaEvent(id, type, data) { |
||||
var element = mediaProxies[id]; |
||||
var m = element && mediaState.get(element); |
||||
|
||||
if (!m || !m.url) { |
||||
return; |
||||
} |
||||
|
||||
data = data || {}; |
||||
|
||||
if (type === 'metadata') { |
||||
m.duration = (data.duration === null) || (data.duration === undefined) ? Infinity : data.duration; |
||||
m.width = data.width || 0; |
||||
m.height = data.height || 0; |
||||
m.readyState = 4; // HAVE_ENOUGH_DATA
|
||||
m.networkState = 1; |
||||
fireMedia(element, 'durationchange'); |
||||
fireMedia(element, 'loadedmetadata'); |
||||
fireMedia(element, 'loadeddata'); |
||||
fireMedia(element, 'canplay'); |
||||
fireMedia(element, 'canplaythrough'); |
||||
} else if (type === 'playing') { |
||||
if (m.seeking) { |
||||
m.seeking = false; |
||||
fireMedia(element, 'seeked'); |
||||
} |
||||
fireMedia(element, 'playing'); |
||||
} else if (type === 'time') { |
||||
m.currentTime = data.position; |
||||
fireMedia(element, 'timeupdate'); |
||||
} else if (type === 'waiting') { |
||||
fireMedia(element, 'waiting'); |
||||
} else if (type === 'ended') { |
||||
m.ended = true; |
||||
m.paused = true; |
||||
fireMedia(element, 'pause'); |
||||
fireMedia(element, 'ended'); |
||||
} else if (type === 'error') { |
||||
m.error = { code: data.code || 4, message: data.message || '', MEDIA_ERR_ABORTED: 1, MEDIA_ERR_NETWORK: 2, |
||||
MEDIA_ERR_DECODE: 3, MEDIA_ERR_SRC_NOT_SUPPORTED: 4 }; |
||||
fireMedia(element, 'error'); |
||||
} |
||||
} |
||||
|
||||
// Playing elements, for where the video goes
|
||||
function playingMedia() { |
||||
var list = []; |
||||
|
||||
Object.keys(mediaProxies).forEach(function (id) { |
||||
var element = mediaProxies[id]; |
||||
var m = mediaState.get(element); |
||||
|
||||
if (m && m.url && element.isConnected) { |
||||
list.push(element); |
||||
} |
||||
}); |
||||
|
||||
return list; |
||||
} |
||||
|
||||
// Media Source Extensions, for the log: applications that use them can't be played
|
||||
if (window.MediaSource) { |
||||
var addSourceBuffer = MediaSource.prototype.addSourceBuffer; |
||||
MediaSource.prototype.addSourceBuffer = function (type) { |
||||
console.log('[sdrangel] MSE addSourceBuffer ' + type); |
||||
return addSourceBuffer.apply(this, arguments); |
||||
}; |
||||
} |
||||
|
||||
// Dialogs would block the application
|
||||
window.alert = function (text) { console.log('alert: ' + text); }; |
||||
window.confirm = function (text) { console.log('confirm: ' + text); return false; }; |
||||
window.prompt = function (text) { console.log('prompt: ' + text); return null; }; |
||||
|
||||
// SDRangel's status (as the red button loading), over everything the application shows
|
||||
var statusElement = null; |
||||
|
||||
function showStatus(text) { |
||||
if (!text) { |
||||
if (statusElement && statusElement.parentNode) { |
||||
statusElement.parentNode.removeChild(statusElement); |
||||
} |
||||
statusElement = null; |
||||
return; |
||||
} |
||||
|
||||
if (!statusElement || !statusElement.isConnected) { |
||||
statusElement = document.createElement('div'); |
||||
statusElement.setAttribute('style', 'position: fixed; right: 64px; bottom: 48px; z-index: 2147483647; ' + |
||||
'padding: 8px 16px; border-radius: 8px; background: rgba(16, 16, 16, 0.8); color: #f1efe8; ' + |
||||
'font: 24px sans-serif; pointer-events: none'); |
||||
(document.body || document.documentElement).appendChild(statusElement); |
||||
} |
||||
|
||||
statusElement.textContent = text; |
||||
} |
||||
|
||||
window.__sdrangelHbbTV = { |
||||
status: showStatus, |
||||
// A key in the application's keyset, down or up
|
||||
key: function (code, down) { |
||||
if (down) { |
||||
keyEvent('keydown', code); |
||||
keyEvent('keypress', code); |
||||
} else { |
||||
keyEvent('keyup', code); |
||||
} |
||||
}, |
||||
update: function (newConfig) { |
||||
config = newConfig || config; |
||||
}, |
||||
// An event of SDRangel's player, playing an element's media
|
||||
media: function (id, type, data) { |
||||
mediaEvent(id, type, data); |
||||
}, |
||||
// After a setChannel(): the service's playing, or it couldn't be (error: OIPF's error code)
|
||||
channelChanged: function (ok, error) { |
||||
videoObjects.slice().concat([]).forEach(function (object) { |
||||
if (videoState(object).playState !== PLAYSTATE_CONNECTING) { |
||||
return; |
||||
} |
||||
|
||||
var channel = makeChannel(config.channel); |
||||
videoState(object).pendingChannel = null; |
||||
|
||||
if (ok) { |
||||
setPlayState(object, PLAYSTATE_PRESENTING); |
||||
fire(object, 'ChannelChangeSucceeded', { channel: channel }, [channel]); |
||||
} else { |
||||
setPlayState(object, PLAYSTATE_UNREALIZED, error); |
||||
fire(object, 'ChannelChangeError', { channel: channel, errorState: error }, [channel, error]); |
||||
} |
||||
}); |
||||
} |
||||
}; |
||||
|
||||
document.addEventListener('DOMContentLoaded', function () { send({ t: 'loaded', url: location.href }); }); |
||||
window.addEventListener('error', function (e) { |
||||
send({ t: 'error', message: String(e.message), source: String(e.filename || ''), line: e.lineno || 0 }); |
||||
}); |
||||
})(); |
||||
@ -0,0 +1,964 @@
@@ -0,0 +1,964 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// Some code by AI //
|
||||
// //
|
||||
// This program is free software; you can redistribute it and/or modify //
|
||||
// it under the terms of the GNU General Public License as published by //
|
||||
// the Free Software Foundation as version 3 of the License, or //
|
||||
// (at your option) any later version. //
|
||||
// //
|
||||
// This program is distributed in the hope that it will be useful, //
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
|
||||
// GNU General Public License V3 for more details. //
|
||||
// //
|
||||
// You should have received a copy of the GNU General Public License //
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#include <algorithm> |
||||
|
||||
#include <QMutexLocker> |
||||
|
||||
#include "dtv/dtvapps.h" |
||||
|
||||
namespace { |
||||
|
||||
// PMT stream types
|
||||
constexpr int m_streamPrivateSections = 0x05; //!< As the AIT's
|
||||
constexpr int m_streamDsmccB = 0x0B; //!< DSM-CC U-N messages: object carousels
|
||||
constexpr int m_streamDsmccD = 0x0D; //!< DSM-CC, any type
|
||||
|
||||
// Descriptors
|
||||
constexpr int m_carouselIdentifierDescriptor = 0x13; |
||||
constexpr int m_associationTagDescriptor = 0x14; |
||||
constexpr int m_streamIdentifierDescriptor = 0x52; |
||||
constexpr int m_dataBroadcastIdDescriptor = 0x66; |
||||
constexpr int m_applicationSignallingDescriptor = 0x6F; |
||||
|
||||
// AIT descriptors (TS 102 809 5.3.5, 5.3.6)
|
||||
constexpr int m_applicationDescriptor = 0x00; |
||||
constexpr int m_applicationNameDescriptor = 0x01; |
||||
constexpr int m_transportProtocolDescriptor = 0x02; |
||||
constexpr int m_simpleApplicationLocationDescriptor = 0x15; |
||||
constexpr int m_simpleApplicationBoundaryDescriptor = 0x17; |
||||
|
||||
constexpr int m_protocolObjectCarousel = 0x0001; |
||||
constexpr int m_protocolHTTP = 0x0003; |
||||
|
||||
bool isDsmcc(int streamType) |
||||
{ |
||||
return (streamType == m_streamDsmccB) || (streamType == m_streamDsmccD); |
||||
} |
||||
|
||||
// An application's transport: by its transport_protocol_descriptor
|
||||
struct Transport |
||||
{ |
||||
int m_protocol = 0; |
||||
int m_label = 0; |
||||
QStringList m_urlBases; |
||||
int m_componentTag = -1; |
||||
int m_remoteNetworkId = -1; |
||||
int m_remoteTransportStreamId = -1; |
||||
int m_remoteServiceId = -1; |
||||
}; |
||||
|
||||
Transport transportProtocol(const uint8_t *d, int length) |
||||
{ |
||||
Transport transport; |
||||
|
||||
if (length < 3) { |
||||
return transport; |
||||
} |
||||
|
||||
transport.m_protocol = (d[0] << 8) | d[1]; |
||||
transport.m_label = d[2]; |
||||
int i = 3; |
||||
|
||||
if (transport.m_protocol == m_protocolObjectCarousel) |
||||
{ |
||||
if (i >= length) { |
||||
return transport; |
||||
} |
||||
|
||||
const bool remote = d[i] & 0x80; |
||||
i++; |
||||
|
||||
if (remote) |
||||
{ |
||||
if (i + 6 > length) { |
||||
return transport; |
||||
} |
||||
|
||||
transport.m_remoteNetworkId = (d[i] << 8) | d[i + 1]; |
||||
transport.m_remoteTransportStreamId = (d[i + 2] << 8) | d[i + 3]; |
||||
transport.m_remoteServiceId = (d[i + 4] << 8) | d[i + 5]; |
||||
i += 6; |
||||
} |
||||
|
||||
if (i < length) { |
||||
transport.m_componentTag = d[i]; |
||||
} |
||||
} |
||||
else if (transport.m_protocol == m_protocolHTTP) |
||||
{ |
||||
// URL bases, each with its extensions (which aren't needed to start the application)
|
||||
while (i < length) |
||||
{ |
||||
const int baseLength = d[i]; |
||||
|
||||
if (i + 1 + baseLength > length) { |
||||
break; |
||||
} |
||||
|
||||
transport.m_urlBases.append(QString::fromLatin1((const char *) d + i + 1, baseLength)); |
||||
i += 1 + baseLength; |
||||
|
||||
if (i >= length) { |
||||
break; |
||||
} |
||||
|
||||
const int extensions = d[i]; |
||||
i++; |
||||
|
||||
for (int e = 0; (e < extensions) && (i < length); e++) { |
||||
i += 1 + d[i]; |
||||
} |
||||
} |
||||
} |
||||
|
||||
return transport; |
||||
} |
||||
|
||||
void applyTransport(DTVApps::App& app, const Transport& transport) |
||||
{ |
||||
if (transport.m_protocol == m_protocolHTTP) |
||||
{ |
||||
for (const QString& base : transport.m_urlBases) |
||||
{ |
||||
if (!app.m_urlBases.contains(base)) { |
||||
app.m_urlBases.append(base); |
||||
} |
||||
} |
||||
} |
||||
else if ((transport.m_protocol == m_protocolObjectCarousel) && (app.m_componentTag < 0)) |
||||
{ |
||||
app.m_componentTag = transport.m_componentTag; |
||||
app.m_remoteNetworkId = transport.m_remoteNetworkId; |
||||
app.m_remoteTransportStreamId = transport.m_remoteTransportStreamId; |
||||
app.m_remoteServiceId = transport.m_remoteServiceId; |
||||
} |
||||
} |
||||
|
||||
} // namespace
|
||||
|
||||
QString DTVApps::App::url(int originalNetworkId, int transportStreamId) const |
||||
{ |
||||
QString location = m_location; |
||||
|
||||
if (!m_urlBases.isEmpty()) |
||||
{ |
||||
const QString& base = m_urlBases.first(); |
||||
|
||||
if (base.endsWith('/') && location.startsWith('/')) { |
||||
location = location.mid(1); |
||||
} |
||||
|
||||
return base + location; |
||||
} |
||||
|
||||
if (m_componentTag >= 0) |
||||
{ |
||||
// dvb://original_network_id.transport_stream_id.service_id.component_tag/path, in hex
|
||||
const bool remote = m_remoteServiceId >= 0; |
||||
const int networkId = remote ? m_remoteNetworkId : originalNetworkId; |
||||
const int tsId = remote ? m_remoteTransportStreamId : transportStreamId; |
||||
const int serviceId = remote ? m_remoteServiceId : m_serviceId; |
||||
|
||||
if (location.startsWith('/')) { |
||||
location = location.mid(1); |
||||
} |
||||
|
||||
return QString("dvb://%1.%2.%3.%4/%5") |
||||
.arg(networkId >= 0 ? QString::number(networkId, 16) : QString()) |
||||
.arg(tsId >= 0 ? QString::number(tsId, 16) : QString()) |
||||
.arg(serviceId, 0, 16) |
||||
.arg(m_componentTag, 0, 16) |
||||
.arg(location); |
||||
} |
||||
|
||||
return location; |
||||
} |
||||
|
||||
QString DTVApps::App::controlCodeName() const |
||||
{ |
||||
switch (m_controlCode) |
||||
{ |
||||
case 1: return "AUTOSTART"; |
||||
case 2: return "PRESENT"; |
||||
case 3: return "DESTROY"; |
||||
case 4: return "KILL"; |
||||
case 5: return "PREFETCH"; |
||||
case 6: return "REMOTE"; |
||||
case 7: return "DISABLED"; |
||||
case 8: return "PLAYBACK_AUTOSTART"; |
||||
default: return QString::number(m_controlCode); |
||||
} |
||||
} |
||||
|
||||
QString DTVApps::App::typeName() const |
||||
{ |
||||
switch (m_applicationType) |
||||
{ |
||||
case 0x0001: return "DVB-J"; |
||||
case 0x0002: return "DVB-HTML"; |
||||
case m_hbbtvApplicationType: return "HbbTV"; |
||||
default: return QString("0x%1").arg(m_applicationType, 4, 16, QChar('0')); |
||||
} |
||||
} |
||||
|
||||
QString DTVApps::App::idText() const |
||||
{ |
||||
return QString("%1.%2").arg(m_organisationId, 0, 16).arg(m_applicationId, 0, 16); |
||||
} |
||||
|
||||
QString DTVApps::Carousel::kindName() const |
||||
{ |
||||
QStringList kinds; |
||||
|
||||
if (m_dataBroadcastId == m_mhegDataBroadcastId) { |
||||
kinds.append("MHEG-5"); |
||||
} |
||||
|
||||
if ((m_dataBroadcastId == m_hbbtvDataBroadcastId) || m_hbbtvApp) { |
||||
kinds.append("HbbTV"); |
||||
} |
||||
|
||||
return kinds.isEmpty() ? QString("DSM-CC") : kinds.join(", "); |
||||
} |
||||
|
||||
DTVApps::DTVApps() : |
||||
m_wanted(8192, false), |
||||
m_transportStreamId(-1), |
||||
m_originalNetworkId(-1), |
||||
m_carouselService(0), |
||||
m_carouselServiceApplied(0), |
||||
m_revision(0) |
||||
{ |
||||
updatePids(); |
||||
} |
||||
|
||||
DTVApps::~DTVApps() |
||||
{ |
||||
} |
||||
|
||||
void DTVApps::reset() |
||||
{ |
||||
QMutexLocker locker(&m_mutex); |
||||
m_assemblers.clear(); |
||||
m_transportStreamId = -1; |
||||
m_originalNetworkId = -1; |
||||
m_programs.clear(); |
||||
m_services.clear(); |
||||
m_aits.clear(); |
||||
m_carousels.clear(); |
||||
m_carouselServices.clear(); |
||||
m_carouselPids.clear(); |
||||
updatePids(); |
||||
m_revision++; |
||||
} |
||||
|
||||
void DTVApps::setCarouselService(int serviceId) |
||||
{ |
||||
m_carouselService = serviceId; |
||||
} |
||||
|
||||
void DTVApps::feed(const uint8_t *p) |
||||
{ |
||||
if ((p[0] != 0x47) || (p[1] & 0x80)) { // Lost sync, or uncorrectable errors
|
||||
return; |
||||
} |
||||
|
||||
const int pid = ((p[1] & 0x1F) << 8) | p[2]; |
||||
QMutexLocker locker(&m_mutex); // Uncontended but for reads, which are infrequent
|
||||
|
||||
if (m_carouselService != m_carouselServiceApplied) { |
||||
updateCarousels(); |
||||
} |
||||
|
||||
if (m_wanted[pid]) { |
||||
packet(pid, p); |
||||
} |
||||
} |
||||
|
||||
void DTVApps::packet(int pid, const uint8_t *p) |
||||
{ |
||||
std::unique_ptr<DTVSectionAssembler>& assembler = m_assemblers[pid]; |
||||
|
||||
if (!assembler) { |
||||
assembler.reset(new DTVSectionAssembler()); |
||||
} |
||||
|
||||
assembler->packet(p, [this, pid](const uint8_t *s, int length) { |
||||
// The long form, with a CRC; current, not a table to apply next
|
||||
if ((length >= 12) && (s[1] & 0x80) && (s[5] & 0x01)) { |
||||
section(pid, s, length); |
||||
} |
||||
}); |
||||
} |
||||
|
||||
void DTVApps::section(int pid, const uint8_t *s, int length) |
||||
{ |
||||
const int table = s[0]; |
||||
|
||||
if ((pid == m_patPid) && (table == m_patTable)) |
||||
{ |
||||
pat(s, length); |
||||
} |
||||
else if ((pid == m_sdtPid) && (table == m_sdtActual)) |
||||
{ |
||||
const int originalNetworkId = (s[8] << 8) | s[9]; |
||||
|
||||
if (originalNetworkId != m_originalNetworkId) |
||||
{ |
||||
m_originalNetworkId = originalNetworkId; |
||||
m_revision++; |
||||
} |
||||
} |
||||
else if (table == m_pmtTable) |
||||
{ |
||||
pmt(pid, s, length); |
||||
} |
||||
else if (table == m_aitTable) |
||||
{ |
||||
ait(pid, s, length); |
||||
} |
||||
else if ((table == m_dsmccInfoTable) || (table == m_dsmccDataTable)) |
||||
{ |
||||
// A DSI on a carousel stream of a service whose carousels are received starts a carousel. The DSI's
|
||||
// message id (0x1006) follows the section header and the protocol discriminator and type
|
||||
if ((table == m_dsmccInfoTable) && (m_carousels.count(pid) == 0) && (length >= 12) |
||||
&& (s[10] == 0x10) && (s[11] == 0x06)) |
||||
{ |
||||
for (const auto& service : m_services) |
||||
{ |
||||
if (!carouselWanted(service.first)) { |
||||
continue; |
||||
} |
||||
|
||||
for (const Stream& stream : service.second.m_streams) |
||||
{ |
||||
if ((stream.m_pid == pid) && isDsmcc(stream.m_type) && (m_carousels.count(pid) == 0)) |
||||
{ |
||||
m_carousels[pid].reset(new DTVCarousel(pid)); |
||||
m_carouselServices[pid] = service.first; |
||||
m_carouselPids[pid].insert(pid); |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
auto fed = m_carouselPids.find(pid); |
||||
|
||||
if (fed == m_carouselPids.end()) { |
||||
return; |
||||
} |
||||
|
||||
bool tagsChanged = false; |
||||
|
||||
for (int carouselPid : fed->second) |
||||
{ |
||||
DTVCarousel *carousel = m_carousels[carouselPid].get(); |
||||
const size_t tags = carousel->getAssociationTags().size(); |
||||
|
||||
if (carousel->section(s, length)) { |
||||
m_revision++; |
||||
} |
||||
|
||||
tagsChanged |= carousel->getAssociationTags().size() != tags; |
||||
} |
||||
|
||||
if (tagsChanged) { |
||||
updateCarousels(); // Its DIIs or DDBs may be on other PIDs
|
||||
} |
||||
} |
||||
} |
||||
|
||||
// program_association_section: the transport stream id, and the PMTs' PIDs
|
||||
void DTVApps::pat(const uint8_t *s, int length) |
||||
{ |
||||
const int transportStreamId = (s[3] << 8) | s[4]; |
||||
|
||||
if ((m_transportStreamId >= 0) && (transportStreamId != m_transportStreamId)) |
||||
{ |
||||
// Another transport stream
|
||||
m_originalNetworkId = -1; |
||||
m_programs.clear(); // So the PIDs read are those of the new one's
|
||||
m_services.clear(); |
||||
m_aits.clear(); |
||||
m_carousels.clear(); |
||||
m_carouselServices.clear(); |
||||
m_carouselPids.clear(); |
||||
m_revision++; |
||||
} |
||||
|
||||
m_transportStreamId = transportStreamId; |
||||
std::map<int, int> programs; |
||||
|
||||
for (int i = 8; i + 4 <= length - 4; i += 4) |
||||
{ |
||||
const int program = (s[i] << 8) | s[i + 1]; |
||||
const int pid = ((s[i + 2] & 0x1F) << 8) | s[i + 3]; |
||||
|
||||
if (program != 0) { // Not the NIT
|
||||
programs[program] = pid; |
||||
} |
||||
} |
||||
|
||||
if (programs != m_programs) |
||||
{ |
||||
m_programs = programs; |
||||
|
||||
for (auto it = m_services.begin(); it != m_services.end();) |
||||
{ |
||||
auto program = m_programs.find(it->first); |
||||
|
||||
if ((program == m_programs.end()) || (program->second != it->second.m_pmtPid)) { |
||||
it = m_services.erase(it); |
||||
} else { |
||||
++it; |
||||
} |
||||
} |
||||
|
||||
updateCarousels(); |
||||
m_revision++; |
||||
} |
||||
} |
||||
|
||||
// TS_program_map_section: the streams of a service, with the AIT's and the carousels'
|
||||
void DTVApps::pmt(int pid, const uint8_t *s, int length) |
||||
{ |
||||
const int program = (s[3] << 8) | s[4]; |
||||
auto it = m_programs.find(program); |
||||
|
||||
if ((it == m_programs.end()) || (it->second != pid)) { |
||||
return; |
||||
} |
||||
|
||||
const int version = (s[5] >> 1) & 0x1F; |
||||
Service& service = m_services[program]; |
||||
|
||||
if ((service.m_pmtPid == pid) && (service.m_pmtVersion == version)) { |
||||
return; |
||||
} |
||||
|
||||
service.m_pmtPid = pid; |
||||
service.m_pmtVersion = version; |
||||
service.m_streams.clear(); |
||||
const int end = length - 4; |
||||
int i = 12 + (((s[10] & 0x0F) << 8) | s[11]); |
||||
|
||||
while (i + 5 <= end) |
||||
{ |
||||
Stream stream; |
||||
stream.m_type = s[i]; |
||||
stream.m_pid = ((s[i + 1] & 0x1F) << 8) | s[i + 2]; |
||||
const int descriptorsEnd = std::min(end, i + 5 + (((s[i + 3] & 0x0F) << 8) | s[i + 4])); |
||||
i += 5; |
||||
|
||||
while (i + 2 <= descriptorsEnd) |
||||
{ |
||||
const int tag = s[i]; |
||||
const int dl = std::min((int) s[i + 1], descriptorsEnd - i - 2); |
||||
const uint8_t *d = s + i + 2; |
||||
|
||||
if ((tag == m_streamIdentifierDescriptor) && (dl >= 1)) { |
||||
stream.m_componentTag = d[0]; |
||||
} else if ((tag == m_associationTagDescriptor) && (dl >= 2)) { |
||||
stream.m_associationTags.push_back((d[0] << 8) | d[1]); |
||||
} else if ((tag == m_carouselIdentifierDescriptor) && (dl >= 4)) { |
||||
stream.m_carouselId = ((uint32_t) d[0] << 24) | (d[1] << 16) | (d[2] << 8) | d[3]; |
||||
} else if ((tag == m_dataBroadcastIdDescriptor) && (dl >= 2)) { |
||||
stream.m_dataBroadcastId = (d[0] << 8) | d[1]; |
||||
} else if (tag == m_applicationSignallingDescriptor) { |
||||
stream.m_ait = true; |
||||
} |
||||
|
||||
i += 2 + s[i + 1]; |
||||
} |
||||
|
||||
i = descriptorsEnd; |
||||
|
||||
// An AIT's stream is of private sections, with the application signalling descriptor (TS 102 809 5.3.5.1)
|
||||
if (stream.m_ait && (stream.m_type != m_streamPrivateSections)) { |
||||
stream.m_ait = false; |
||||
} |
||||
|
||||
service.m_streams.push_back(stream); |
||||
} |
||||
|
||||
updateCarousels(); |
||||
m_revision++; |
||||
} |
||||
|
||||
// application_information_section (TS 102 809 5.3.4): the applications, each with its descriptors, and descriptors
|
||||
// common to them (as transports applications refer to by label)
|
||||
void DTVApps::ait(int pid, const uint8_t *s, int length) |
||||
{ |
||||
const int applicationType = ((s[3] << 8) | s[4]) & 0x7FFF; // After the test_application_flag
|
||||
const int version = (s[5] >> 1) & 0x1F; |
||||
const int sectionNumber = s[6]; |
||||
AIT& table = m_aits[{pid, applicationType}]; |
||||
|
||||
if (table.m_version != version) |
||||
{ |
||||
table.m_version = version; |
||||
table.m_sections.clear(); |
||||
} |
||||
else if (table.m_sections.count(sectionNumber) != 0) |
||||
{ |
||||
return; |
||||
} |
||||
|
||||
const int end = length - 4; |
||||
int i = 8; |
||||
const int commonEnd = std::min(end, i + 2 + (((s[i] & 0x0F) << 8) | s[i + 1])); |
||||
i += 2; |
||||
std::map<int, Transport> commonTransports; |
||||
|
||||
for (; i + 2 <= commonEnd; i += 2 + s[i + 1]) |
||||
{ |
||||
if ((s[i] == m_transportProtocolDescriptor) && (i + 2 + s[i + 1] <= commonEnd)) |
||||
{ |
||||
const Transport transport = transportProtocol(s + i + 2, s[i + 1]); |
||||
commonTransports[transport.m_label] = transport; |
||||
} |
||||
} |
||||
|
||||
i = commonEnd; |
||||
|
||||
if (i + 2 > end) { |
||||
return; |
||||
} |
||||
|
||||
const int loopEnd = std::min(end, i + 2 + (((s[i] & 0x0F) << 8) | s[i + 1])); |
||||
i += 2; |
||||
std::vector<App> apps; |
||||
|
||||
while (i + 9 <= loopEnd) |
||||
{ |
||||
App app; |
||||
app.m_organisationId = ((uint32_t) s[i] << 24) | (s[i + 1] << 16) | (s[i + 2] << 8) | s[i + 3]; |
||||
app.m_applicationId = (s[i + 4] << 8) | s[i + 5]; |
||||
app.m_applicationType = applicationType; |
||||
app.m_controlCode = s[i + 6]; |
||||
const int descriptorsEnd = std::min(loopEnd, i + 9 + (((s[i + 7] & 0x0F) << 8) | s[i + 8])); |
||||
i += 9; |
||||
std::vector<int> labels; |
||||
|
||||
for (; i + 2 <= descriptorsEnd; i += 2 + s[i + 1]) |
||||
{ |
||||
const int tag = s[i]; |
||||
const int dl = s[i + 1]; |
||||
const uint8_t *d = s + i + 2; |
||||
|
||||
if (i + 2 + dl > descriptorsEnd) { |
||||
break; |
||||
} |
||||
|
||||
if (tag == m_applicationDescriptor) |
||||
{ |
||||
// Profiles, then service_bound_flag, visibility, priority and transport protocol labels
|
||||
const int profilesLength = d[0]; |
||||
|
||||
if (1 + profilesLength + 2 > dl) { |
||||
continue; |
||||
} |
||||
|
||||
for (int p = 1; p + 5 <= 1 + profilesLength; p += 5) { |
||||
app.m_profiles.push_back((((d[p] << 8) | d[p + 1]) << 24) | (d[p + 2] << 16) | (d[p + 3] << 8) | d[p + 4]); |
||||
} |
||||
|
||||
const int flags = d[1 + profilesLength]; |
||||
app.m_serviceBound = flags & 0x80; |
||||
app.m_visibility = (flags >> 5) & 3; |
||||
app.m_priority = d[2 + profilesLength]; |
||||
|
||||
for (int l = 3 + profilesLength; l < dl; l++) { |
||||
labels.push_back(d[l]); |
||||
} |
||||
} |
||||
else if ((tag == m_applicationNameDescriptor) && (dl >= 4)) |
||||
{ |
||||
// The first language's name
|
||||
const int nameLength = std::min((int) d[3], dl - 4); |
||||
app.m_language = QString::fromLatin1((const char *) d, 3); |
||||
app.m_name = dvbText(d + 4, nameLength); |
||||
} |
||||
else if (tag == m_transportProtocolDescriptor) |
||||
{ |
||||
applyTransport(app, transportProtocol(d, dl)); |
||||
} |
||||
else if (tag == m_simpleApplicationLocationDescriptor) |
||||
{ |
||||
app.m_location = QString::fromLatin1((const char *) d, dl); |
||||
} |
||||
else if ((tag == m_simpleApplicationBoundaryDescriptor) && (dl >= 1)) |
||||
{ |
||||
for (int b = 1, n = 0; (n < d[0]) && (b < dl); n++) |
||||
{ |
||||
const int boundaryLength = std::min((int) d[b], dl - b - 1); |
||||
app.m_boundaries.append(QString::fromLatin1((const char *) d + b + 1, boundaryLength)); |
||||
b += 1 + d[b]; |
||||
} |
||||
} |
||||
} |
||||
|
||||
i = descriptorsEnd; |
||||
|
||||
for (int label : labels) |
||||
{ |
||||
auto transport = commonTransports.find(label); |
||||
|
||||
if (transport != commonTransports.end()) { |
||||
applyTransport(app, transport->second); |
||||
} |
||||
} |
||||
|
||||
apps.push_back(app); |
||||
} |
||||
|
||||
table.m_sections[sectionNumber] = apps; |
||||
m_revision++; |
||||
} |
||||
|
||||
bool DTVApps::carouselWanted(int serviceId) const |
||||
{ |
||||
return (m_carouselServiceApplied == -1) || ((m_carouselServiceApplied != 0) && (m_carouselServiceApplied == serviceId)); |
||||
} |
||||
|
||||
// The PID of a service's stream with an association tag (that of an association_tag_descriptor, or in DVB usually its
|
||||
// component tag, TR 101 202 4.7.7.1), -1 if none has it
|
||||
int DTVApps::resolveTag(int serviceId, int tag) const |
||||
{ |
||||
auto service = m_services.find(serviceId); |
||||
|
||||
if (service == m_services.end()) { |
||||
return -1; |
||||
} |
||||
|
||||
for (const Stream& stream : service->second.m_streams) |
||||
{ |
||||
if (std::find(stream.m_associationTags.begin(), stream.m_associationTags.end(), tag) != stream.m_associationTags.end()) { |
||||
return stream.m_pid; |
||||
} |
||||
} |
||||
|
||||
for (const Stream& stream : service->second.m_streams) |
||||
{ |
||||
if ((stream.m_componentTag >= 0) && (stream.m_componentTag == (tag & 0xFF))) { |
||||
return stream.m_pid; |
||||
} |
||||
} |
||||
|
||||
return -1; |
||||
} |
||||
|
||||
// The carousels of the services chosen are kept, those of others dropped, and each is fed from the PIDs its taps
|
||||
// point to too
|
||||
void DTVApps::updateCarousels() |
||||
{ |
||||
m_carouselServiceApplied = m_carouselService; |
||||
|
||||
for (auto it = m_carousels.begin(); it != m_carousels.end();) |
||||
{ |
||||
const int pid = it->first; |
||||
const int serviceId = m_carouselServices[pid]; |
||||
bool keep = false; |
||||
auto service = m_services.find(serviceId); |
||||
|
||||
if (carouselWanted(serviceId) && (service != m_services.end())) |
||||
{ |
||||
for (const Stream& stream : service->second.m_streams) { |
||||
keep |= (stream.m_pid == pid) && isDsmcc(stream.m_type); |
||||
} |
||||
} |
||||
|
||||
if (keep) |
||||
{ |
||||
++it; |
||||
} |
||||
else |
||||
{ |
||||
m_carouselServices.erase(pid); |
||||
it = m_carousels.erase(it); |
||||
m_revision++; |
||||
} |
||||
} |
||||
|
||||
m_carouselPids.clear(); |
||||
|
||||
for (const auto& carousel : m_carousels) |
||||
{ |
||||
m_carouselPids[carousel.first].insert(carousel.first); |
||||
|
||||
for (int tag : carousel.second->getAssociationTags()) |
||||
{ |
||||
const int pid = resolveTag(m_carouselServices[carousel.first], tag); |
||||
|
||||
if (pid >= 0) { |
||||
m_carouselPids[pid].insert(carousel.first); |
||||
} |
||||
} |
||||
} |
||||
|
||||
updatePids(); |
||||
} |
||||
|
||||
void DTVApps::updatePids() |
||||
{ |
||||
std::vector<bool> wanted(8192, false); |
||||
wanted[m_patPid] = true; |
||||
wanted[m_sdtPid] = true; |
||||
|
||||
for (const auto& program : m_programs) { |
||||
wanted[program.second] = true; |
||||
} |
||||
|
||||
for (const auto& service : m_services) |
||||
{ |
||||
const bool carousels = carouselWanted(service.first); |
||||
|
||||
for (const Stream& stream : service.second.m_streams) |
||||
{ |
||||
// Every service's AIT; carousels of those chosen (to find their DSIs)
|
||||
if (stream.m_ait || (carousels && isDsmcc(stream.m_type))) { |
||||
wanted[stream.m_pid] = true; |
||||
} |
||||
} |
||||
} |
||||
|
||||
for (const auto& pid : m_carouselPids) { |
||||
wanted[pid.first] = true; |
||||
} |
||||
|
||||
for (auto it = m_assemblers.begin(); it != m_assemblers.end();) |
||||
{ |
||||
if (!wanted[it->first]) { |
||||
it = m_assemblers.erase(it); |
||||
} else { |
||||
++it; |
||||
} |
||||
} |
||||
|
||||
m_wanted = wanted; |
||||
} |
||||
|
||||
QString DTVApps::dvbText(const uint8_t *text, int length) |
||||
{ |
||||
// EN 300 468 Annex A: an optional character table first. Names are usually ASCII
|
||||
if ((length >= 1) && (text[0] == 0x15)) { |
||||
return QString::fromUtf8((const char *) text + 1, length - 1); |
||||
} else if ((length >= 3) && (text[0] == 0x10)) { |
||||
return QString::fromLatin1((const char *) text + 3, length - 3); |
||||
} else if ((length >= 1) && (text[0] < 0x20)) { |
||||
return QString::fromLatin1((const char *) text + 1, length - 1); |
||||
} else { |
||||
return QString::fromLatin1((const char *) text, length); |
||||
} |
||||
} |
||||
|
||||
int DTVApps::getTransportStreamId() const |
||||
{ |
||||
QMutexLocker locker(&m_mutex); |
||||
return m_transportStreamId; |
||||
} |
||||
|
||||
int DTVApps::getOriginalNetworkId() const |
||||
{ |
||||
QMutexLocker locker(&m_mutex); |
||||
return m_originalNetworkId; |
||||
} |
||||
|
||||
std::vector<DTVApps::App> DTVApps::getApps(int serviceId) const |
||||
{ |
||||
QMutexLocker locker(&m_mutex); |
||||
std::vector<App> apps; |
||||
|
||||
for (const auto& service : m_services) |
||||
{ |
||||
if ((serviceId != 0) && (service.first != serviceId)) { |
||||
continue; |
||||
} |
||||
|
||||
std::set<std::pair<uint32_t, int>> seen; |
||||
|
||||
for (const Stream& stream : service.second.m_streams) |
||||
{ |
||||
if (!stream.m_ait) { |
||||
continue; |
||||
} |
||||
|
||||
for (const auto& table : m_aits) |
||||
{ |
||||
if (table.first.first != stream.m_pid) { |
||||
continue; |
||||
} |
||||
|
||||
for (const auto& section : table.second.m_sections) |
||||
{ |
||||
for (App app : section.second) |
||||
{ |
||||
if (!seen.insert({app.m_organisationId, app.m_applicationId}).second) { |
||||
continue; |
||||
} |
||||
|
||||
app.m_serviceId = service.first; |
||||
|
||||
if ((app.m_componentTag >= 0) && (app.m_remoteServiceId < 0)) { |
||||
app.m_carouselPid = resolveTag(service.first, app.m_componentTag); |
||||
} |
||||
|
||||
apps.push_back(app); |
||||
} |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
return apps; |
||||
} |
||||
|
||||
std::vector<DTVApps::Carousel> DTVApps::getCarousels(int serviceId) const |
||||
{ |
||||
// Of all services: a carousel shared by services may have its data_broadcast_id in some of their PMTs only, and
|
||||
// applications in it signalled in some of their AITs
|
||||
const std::vector<App> apps = getApps(); |
||||
QMutexLocker locker(&m_mutex); |
||||
std::vector<Carousel> carousels; |
||||
std::map<int, int> dataBroadcastIds; |
||||
|
||||
for (const auto& service : m_services) |
||||
{ |
||||
for (const Stream& stream : service.second.m_streams) |
||||
{ |
||||
if (stream.m_dataBroadcastId >= 0) { |
||||
dataBroadcastIds[stream.m_pid] = stream.m_dataBroadcastId; |
||||
} |
||||
} |
||||
} |
||||
|
||||
for (const auto& service : m_services) |
||||
{ |
||||
if ((serviceId != 0) && (service.first != serviceId)) { |
||||
continue; |
||||
} |
||||
|
||||
for (const Stream& stream : service.second.m_streams) |
||||
{ |
||||
if (!isDsmcc(stream.m_type)) { |
||||
continue; |
||||
} |
||||
|
||||
// Those with a carousel id, or an application, or a DSI: not those of only a carousel's modules
|
||||
bool app = false; |
||||
bool hbbtv = false; |
||||
|
||||
for (const App& a : apps) |
||||
{ |
||||
if (a.m_carouselPid == stream.m_pid) |
||||
{ |
||||
app |= a.m_serviceId == service.first; |
||||
hbbtv |= a.m_applicationType == m_hbbtvApplicationType; |
||||
} |
||||
} |
||||
|
||||
auto received = m_carousels.find(stream.m_pid); |
||||
|
||||
if ((stream.m_carouselId < 0) && !app && (received == m_carousels.end())) { |
||||
continue; |
||||
} |
||||
|
||||
Carousel carousel; |
||||
carousel.m_serviceId = service.first; |
||||
carousel.m_pid = stream.m_pid; |
||||
carousel.m_componentTag = stream.m_componentTag; |
||||
carousel.m_carouselId = stream.m_carouselId; |
||||
auto dataBroadcastId = dataBroadcastIds.find(stream.m_pid); |
||||
carousel.m_dataBroadcastId = dataBroadcastId != dataBroadcastIds.end() ? dataBroadcastId->second : -1; |
||||
carousel.m_hbbtvApp = hbbtv; |
||||
|
||||
if (received != m_carousels.end()) |
||||
{ |
||||
const DTVCarousel *c = received->second.get(); |
||||
carousel.m_received = c->getCarouselId() >= 0; |
||||
carousel.m_carouselId = carousel.m_received ? c->getCarouselId() : carousel.m_carouselId; |
||||
carousel.m_progress = c->getProgress(); |
||||
carousel.m_complete = c->isComplete(); |
||||
|
||||
for (const DTVCarousel::Entry& entry : c->getEntries()) { |
||||
carousel.m_files += (entry.m_kind == DTVCarousel::Kind::File) && entry.m_received ? 1 : 0; |
||||
} |
||||
} |
||||
|
||||
carousels.push_back(carousel); |
||||
} |
||||
} |
||||
|
||||
return carousels; |
||||
} |
||||
|
||||
std::vector<int> DTVApps::getServices() const |
||||
{ |
||||
QMutexLocker locker(&m_mutex); |
||||
std::vector<int> services; |
||||
|
||||
for (const auto& service : m_services) |
||||
{ |
||||
bool interactive = false; |
||||
|
||||
for (const Stream& stream : service.second.m_streams) { |
||||
interactive |= stream.m_ait || isDsmcc(stream.m_type); |
||||
} |
||||
|
||||
if (interactive) { |
||||
services.push_back(service.first); |
||||
} |
||||
} |
||||
|
||||
return services; |
||||
} |
||||
|
||||
int DTVApps::getComponentPid(int serviceId, int componentTag) const |
||||
{ |
||||
QMutexLocker locker(&m_mutex); |
||||
return resolveTag(serviceId, componentTag); |
||||
} |
||||
|
||||
bool DTVApps::isCarouselComplete(int pid) const |
||||
{ |
||||
QMutexLocker locker(&m_mutex); |
||||
auto it = m_carousels.find(pid); |
||||
return (it != m_carousels.end()) && it->second->isComplete(); |
||||
} |
||||
|
||||
std::vector<DTVCarousel::Entry> DTVApps::getCarouselEntries(int pid) const |
||||
{ |
||||
QMutexLocker locker(&m_mutex); |
||||
auto it = m_carousels.find(pid); |
||||
return it != m_carousels.end() ? it->second->getEntries() : std::vector<DTVCarousel::Entry>(); |
||||
} |
||||
|
||||
bool DTVApps::getCarouselFile(int pid, const QString& path, QByteArray& data) const |
||||
{ |
||||
QMutexLocker locker(&m_mutex); |
||||
auto it = m_carousels.find(pid); |
||||
return (it != m_carousels.end()) && it->second->getFile(path, data); |
||||
} |
||||
|
||||
std::map<QString, QByteArray> DTVApps::getCarouselFiles(int pid) const |
||||
{ |
||||
QMutexLocker locker(&m_mutex); |
||||
auto it = m_carousels.find(pid); |
||||
return it != m_carousels.end() ? it->second->getFiles() : std::map<QString, QByteArray>(); |
||||
} |
||||
@ -0,0 +1,181 @@
@@ -0,0 +1,181 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// Some code by AI //
|
||||
// //
|
||||
// This program is free software; you can redistribute it and/or modify //
|
||||
// it under the terms of the GNU General Public License as published by //
|
||||
// the Free Software Foundation as version 3 of the License, or //
|
||||
// (at your option) any later version. //
|
||||
// //
|
||||
// This program is distributed in the hope that it will be useful, //
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
|
||||
// GNU General Public License V3 for more details. //
|
||||
// //
|
||||
// You should have received a copy of the GNU General Public License //
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifndef INCLUDE_DTVAPPS_H |
||||
#define INCLUDE_DTVAPPS_H |
||||
|
||||
#include <atomic> |
||||
#include <cstdint> |
||||
#include <map> |
||||
#include <memory> |
||||
#include <set> |
||||
#include <vector> |
||||
|
||||
#include <QMutex> |
||||
#include <QString> |
||||
#include <QStringList> |
||||
|
||||
#include "export.h" |
||||
#include "dtv/dtvsections.h" |
||||
#include "dtv/dtvcarousel.h" |
||||
|
||||
// The interactive applications of a DVB transport stream's services (the red button): from each service's PMT, its
|
||||
// AIT (application information table, TS 102 809 5.3) and object carousels; from the AITs, the applications
|
||||
// (HbbTV's, TS 102 796, and others), with where they're loaded from: a URL, or a carousel. The carousels (MHEG-5's,
|
||||
// as the UK's, and HbbTV's) of the services chosen are received, as DTVCarousels. Fed with the transport stream's
|
||||
// packets in the demodulator's thread; read from others
|
||||
class SDRBASE_API DTVApps |
||||
{ |
||||
public: |
||||
static constexpr int m_hbbtvApplicationType = 0x0010; |
||||
static constexpr int m_mhegDataBroadcastId = 0x0106; //!< UK MHEG-5 (D-Book)
|
||||
static constexpr int m_hbbtvDataBroadcastId = 0x0123; |
||||
|
||||
struct SDRBASE_API App { |
||||
int m_serviceId = 0; |
||||
uint32_t m_organisationId = 0; |
||||
int m_applicationId = 0; |
||||
int m_applicationType = 0; //!< 0x10 HbbTV
|
||||
int m_controlCode = 0; //!< 1 AUTOSTART, 2 PRESENT, ...
|
||||
int m_visibility = 3; //!< 0 not visible, 1 to applications only, 3 to users too
|
||||
int m_priority = 0; |
||||
bool m_serviceBound = false; |
||||
QString m_name; |
||||
QString m_language; |
||||
std::vector<int> m_profiles; //!< HbbTV's application_profile, each as profile << 24 | major << 16 | minor << 8 | micro
|
||||
QStringList m_urlBases; //!< Of HTTP transports
|
||||
int m_componentTag = -1; //!< Of an object carousel transport: the carousel's PMT component tag
|
||||
int m_carouselPid = -1; //!< That stream's PID, -1 if it's not in the PMT
|
||||
//! A carousel of another service (not received): that service's original network, transport stream and id
|
||||
int m_remoteNetworkId = -1; |
||||
int m_remoteTransportStreamId = -1; |
||||
int m_remoteServiceId = -1; |
||||
QString m_location; //!< Initial path, from the simple_application_location_descriptor
|
||||
QStringList m_boundaries; //!< Of the application, from the simple_application_boundary_descriptor
|
||||
|
||||
//! Where the application starts: a URL base and the location, or for a carousel a dvb: URL (TS 102 851)
|
||||
QString url(int originalNetworkId, int transportStreamId) const; |
||||
QString controlCodeName() const; |
||||
QString typeName() const; |
||||
//! The application id as HbbTV shows it: organisation.application, in hex
|
||||
QString idText() const; |
||||
}; |
||||
|
||||
struct SDRBASE_API Carousel { |
||||
int m_serviceId = 0; |
||||
int m_pid = 0; |
||||
int m_componentTag = -1; |
||||
int64_t m_carouselId = -1; //!< From the PMT's carousel_identifier_descriptor, or the DSI
|
||||
int m_dataBroadcastId = -1; //!< 0x0106 MHEG-5, 0x0123 HbbTV, -1 if not signalled
|
||||
bool m_hbbtvApp = false; //!< An HbbTV application's in it (MHEG-5 and HbbTV may share a carousel)
|
||||
bool m_received = false; //!< Its DSI has been received
|
||||
DTVCarousel::Progress m_progress; |
||||
bool m_complete = false; |
||||
int m_files = 0; //!< Received
|
||||
|
||||
QString kindName() const; //!< MHEG-5, HbbTV, both, or DSM-CC
|
||||
}; |
||||
|
||||
DTVApps(); |
||||
~DTVApps(); |
||||
void reset(); //!< For a new transport stream: forgets everything
|
||||
|
||||
//! One 188-byte packet
|
||||
void feed(const uint8_t *packet); |
||||
|
||||
//! The service whose carousels are received: 0 none, -1 all of them
|
||||
void setCarouselService(int serviceId); |
||||
int getCarouselService() const { return m_carouselService; } |
||||
|
||||
int getTransportStreamId() const; |
||||
int getOriginalNetworkId() const; //!< From the SDT, -1 until it's received
|
||||
//! The applications of a service, or all of them (0)
|
||||
std::vector<App> getApps(int serviceId = 0) const; |
||||
//! The object carousels of a service, or all of them (0), signalled in the PMT or received
|
||||
std::vector<Carousel> getCarousels(int serviceId = 0) const; |
||||
std::vector<int> getServices() const; //!< With applications or carousels
|
||||
//! The PID of a service's stream with a component tag (as an application's carousel), -1 if it hasn't one
|
||||
int getComponentPid(int serviceId, int componentTag) const; |
||||
//! The carousel on a PID: its tree, and files
|
||||
std::vector<DTVCarousel::Entry> getCarouselEntries(int pid) const; |
||||
bool getCarouselFile(int pid, const QString& path, QByteArray& data) const; |
||||
//! The carousel on a PID is being received, and has all its modules
|
||||
bool isCarouselComplete(int pid) const; |
||||
std::map<QString, QByteArray> getCarouselFiles(int pid) const; |
||||
//! Changes when anything that's read does
|
||||
int getRevision() const { return m_revision; } |
||||
|
||||
private: |
||||
static constexpr int m_patPid = 0x0000; |
||||
static constexpr int m_sdtPid = 0x0011; |
||||
static constexpr int m_patTable = 0x00; |
||||
static constexpr int m_pmtTable = 0x02; |
||||
static constexpr int m_sdtActual = 0x42; |
||||
static constexpr int m_aitTable = 0x74; |
||||
static constexpr int m_dsmccInfoTable = 0x3B; //!< DSI and DII
|
||||
static constexpr int m_dsmccDataTable = 0x3C; //!< DDB
|
||||
|
||||
struct Stream { |
||||
int m_pid = 0; |
||||
int m_type = 0; |
||||
int m_componentTag = -1; |
||||
std::vector<int> m_associationTags; |
||||
int64_t m_carouselId = -1; |
||||
int m_dataBroadcastId = -1; |
||||
bool m_ait = false; |
||||
}; |
||||
|
||||
struct Service { |
||||
int m_pmtPid = -1; |
||||
int m_pmtVersion = -1; |
||||
std::vector<Stream> m_streams; |
||||
}; |
||||
|
||||
struct AIT { |
||||
int m_version = -1; |
||||
std::map<int, std::vector<App>> m_sections; //!< By section number
|
||||
}; |
||||
|
||||
void packet(int pid, const uint8_t *p); |
||||
void section(int pid, const uint8_t *s, int length); |
||||
void pat(const uint8_t *s, int length); |
||||
void pmt(int pid, const uint8_t *s, int length); |
||||
void ait(int pid, const uint8_t *s, int length); |
||||
void updatePids(); |
||||
void updateCarousels(); |
||||
int resolveTag(int serviceId, int tag) const; |
||||
bool carouselWanted(int serviceId) const; |
||||
static QString dvbText(const uint8_t *text, int length); |
||||
|
||||
mutable QMutex m_mutex; |
||||
std::map<int, std::unique_ptr<DTVSectionAssembler>> m_assemblers; //!< By PID: of the PIDs read
|
||||
std::vector<bool> m_wanted; //!< By PID: those read
|
||||
int m_transportStreamId; |
||||
int m_originalNetworkId; |
||||
std::map<int, int> m_programs; //!< From the PAT: program number to PMT PID
|
||||
std::map<int, Service> m_services; //!< By program number (service id)
|
||||
std::map<std::pair<int, int>, AIT> m_aits; //!< By PID and application type
|
||||
std::map<int, std::unique_ptr<DTVCarousel>> m_carousels; //!< By PID of its DSI
|
||||
std::map<int, int> m_carouselServices; //!< Carousel PID to its service
|
||||
std::map<int, std::set<int>> m_carouselPids; //!< PID to the carousels (by DSI PID) fed from it
|
||||
std::atomic<int> m_carouselService; |
||||
int m_carouselServiceApplied; |
||||
std::atomic<int> m_revision; |
||||
}; |
||||
|
||||
#endif // INCLUDE_DTVAPPS_H
|
||||
@ -0,0 +1,784 @@
@@ -0,0 +1,784 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// Some code by AI //
|
||||
// //
|
||||
// This program is free software; you can redistribute it and/or modify //
|
||||
// it under the terms of the GNU General Public License as published by //
|
||||
// the Free Software Foundation as version 3 of the License, or //
|
||||
// (at your option) any later version. //
|
||||
// //
|
||||
// This program is distributed in the hope that it will be useful, //
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
|
||||
// GNU General Public License V3 for more details. //
|
||||
// //
|
||||
// You should have received a copy of the GNU General Public License //
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#include <algorithm> |
||||
#include <cstring> |
||||
|
||||
#include "dtv/dtvcarousel.h" |
||||
|
||||
namespace { |
||||
|
||||
// Reads big-endian fields, stopping (ok false) at the end rather than reading past it
|
||||
struct Reader |
||||
{ |
||||
const uint8_t *m_data; |
||||
int m_length; |
||||
int m_offset = 0; |
||||
bool m_ok = true; |
||||
|
||||
Reader(const uint8_t *data, int length) : m_data(data), m_length(length) {} |
||||
|
||||
bool has(int n) |
||||
{ |
||||
if ((n < 0) || (m_offset + n > m_length)) { |
||||
m_ok = false; |
||||
} |
||||
return m_ok; |
||||
} |
||||
uint32_t u8() { return has(1) ? m_data[m_offset++] : 0; } |
||||
uint32_t u16() |
||||
{ |
||||
if (!has(2)) { |
||||
return 0; |
||||
} |
||||
const uint32_t v = (m_data[m_offset] << 8) | m_data[m_offset + 1]; |
||||
m_offset += 2; |
||||
return v; |
||||
} |
||||
uint32_t u32() |
||||
{ |
||||
if (!has(4)) { |
||||
return 0; |
||||
} |
||||
const uint32_t v = ((uint32_t) m_data[m_offset] << 24) | (m_data[m_offset + 1] << 16) | (m_data[m_offset + 2] << 8) | m_data[m_offset + 3]; |
||||
m_offset += 4; |
||||
return v; |
||||
} |
||||
uint64_t u64() |
||||
{ |
||||
const uint64_t high = u32(); |
||||
return (high << 32) | u32(); |
||||
} |
||||
const uint8_t *bytes(int n) |
||||
{ |
||||
if (!has(n)) { |
||||
return nullptr; |
||||
} |
||||
const uint8_t *p = m_data + m_offset; |
||||
m_offset += n; |
||||
return p; |
||||
} |
||||
void skip(int n) { bytes(n); } |
||||
int left() const { return m_length - m_offset; } |
||||
const uint8_t *here() const { return m_data + m_offset; } |
||||
}; |
||||
|
||||
constexpr int m_dsiMessage = 0x1006; |
||||
constexpr int m_diiMessage = 0x1002; |
||||
constexpr int m_ddbMessage = 0x1003; |
||||
constexpr uint32_t m_tagBIOP = 0x49534F06; //!< TAG_BIOP profile
|
||||
constexpr uint32_t m_tagObjectLocation = 0x49534F50; //!< BIOP::ObjectLocation component
|
||||
constexpr uint32_t m_tagConnBinder = 0x49534F40; //!< DSM::ConnBinder component
|
||||
constexpr int m_compressedModuleDescriptor = 0x09; |
||||
|
||||
} // namespace
|
||||
|
||||
bool DTVCarousel::ObjectRef::operator<(const ObjectRef& other) const |
||||
{ |
||||
if (m_carouselId != other.m_carouselId) { |
||||
return m_carouselId < other.m_carouselId; |
||||
} |
||||
if (m_moduleId != other.m_moduleId) { |
||||
return m_moduleId < other.m_moduleId; |
||||
} |
||||
return m_objectKey < other.m_objectKey; |
||||
} |
||||
|
||||
DTVCarousel::DTVCarousel(int pid) : |
||||
m_pid(pid), |
||||
m_carouselId(-1), |
||||
m_revision(0) |
||||
{ |
||||
} |
||||
|
||||
void DTVCarousel::reset() |
||||
{ |
||||
m_carouselId = -1; |
||||
m_gateway = ObjectRef(); |
||||
m_associationTags.clear(); |
||||
m_modules.clear(); |
||||
m_diiModules.clear(); |
||||
m_objects.clear(); |
||||
m_revision++; |
||||
} |
||||
|
||||
QString DTVCarousel::kindName(Kind kind) |
||||
{ |
||||
switch (kind) |
||||
{ |
||||
case Kind::File: return "file"; |
||||
case Kind::Directory: return "directory"; |
||||
case Kind::Gateway: return "service gateway"; |
||||
case Kind::Stream: return "stream"; |
||||
default: return "unknown"; |
||||
} |
||||
} |
||||
|
||||
QString DTVCarousel::localPath(const QString& path) |
||||
{ |
||||
// Names have no separators, and aren't . or .. (parseModule), so only Windows' reserved characters are left
|
||||
QString local = path.startsWith('/') ? path.mid(1) : path; |
||||
|
||||
for (QChar& c : local) |
||||
{ |
||||
if ((c < QChar(0x20)) || QString("\\:*?\"<>|").contains(c)) { |
||||
c = '_'; |
||||
} |
||||
} |
||||
|
||||
return local; |
||||
} |
||||
|
||||
DTVCarousel::Kind DTVCarousel::kindFromId(const uint8_t *id, int length) |
||||
{ |
||||
// "fil", "dir", "srg", "str", "ste", usually with a terminating 0
|
||||
if (length < 3) { |
||||
return Kind::Unknown; |
||||
} |
||||
|
||||
if (std::memcmp(id, "fil", 3) == 0) { |
||||
return Kind::File; |
||||
} else if (std::memcmp(id, "dir", 3) == 0) { |
||||
return Kind::Directory; |
||||
} else if (std::memcmp(id, "srg", 3) == 0) { |
||||
return Kind::Gateway; |
||||
} else if ((std::memcmp(id, "str", 3) == 0) || (std::memcmp(id, "ste", 3) == 0)) { |
||||
return Kind::Stream; |
||||
} else { |
||||
return Kind::Unknown; |
||||
} |
||||
} |
||||
|
||||
bool DTVCarousel::section(const uint8_t *s, int length) |
||||
{ |
||||
// The section header (8 bytes), then the message (from a 12 byte header with its adaptation), then the CRC
|
||||
if (length < 8 + 12 + 4) { |
||||
return false; |
||||
} |
||||
|
||||
const uint8_t *m = s + 8; |
||||
const int messageLength = length - 8 - 4; |
||||
|
||||
// protocolDiscriminator 0x11 and dsmccType 0x03 (download) of the dsmccMessageHeader or dsmccDownloadDataHeader
|
||||
if ((m[0] != 0x11) || (m[1] != 0x03)) { |
||||
return false; |
||||
} |
||||
|
||||
const int messageId = (m[2] << 8) | m[3]; |
||||
const uint32_t id = ((uint32_t) m[4] << 24) | (m[5] << 16) | (m[6] << 8) | m[7]; // transactionId, or downloadId
|
||||
const int adaptationLength = m[9]; |
||||
const int bodyLength = std::min(messageLength - 12 - adaptationLength, ((m[10] << 8) | m[11]) - adaptationLength); |
||||
|
||||
if (bodyLength <= 0) { |
||||
return false; |
||||
} |
||||
|
||||
const uint8_t *body = m + 12 + adaptationLength; |
||||
const int revision = m_revision; |
||||
|
||||
if ((s[0] == 0x3B) && (messageId == m_dsiMessage)) |
||||
{ |
||||
dsi(body, bodyLength); |
||||
} |
||||
else if ((s[0] == 0x3B) && (messageId == m_diiMessage)) |
||||
{ |
||||
dii(body, bodyLength, id); |
||||
} |
||||
else if ((s[0] == 0x3C) && (messageId == m_ddbMessage) && (m_carouselId >= 0) && (id == (uint32_t) m_carouselId)) |
||||
{ |
||||
ddb(body, bodyLength); |
||||
} |
||||
|
||||
return m_revision != revision; |
||||
} |
||||
|
||||
// DownloadServerInitiate: in an object carousel, the IOR of the service gateway (ServiceGatewayInfo)
|
||||
void DTVCarousel::dsi(const uint8_t *m, int length) |
||||
{ |
||||
Reader r(m, length); |
||||
r.skip(20); // serverId
|
||||
r.skip(r.u16()); // compatibilityDescriptor
|
||||
const int privateDataLength = r.u16(); |
||||
|
||||
if (!r.has(privateDataLength)) { |
||||
return; |
||||
} |
||||
|
||||
ObjectRef gateway; |
||||
Kind kind; |
||||
int used; |
||||
std::vector<int> tags; |
||||
|
||||
if (!parseIOR(r.here(), privateDataLength, used, gateway, kind, &tags) || (gateway.m_moduleId < 0)) { |
||||
return; |
||||
} |
||||
|
||||
if ((gateway.m_carouselId != m_carouselId) || (gateway.m_moduleId != m_gateway.m_moduleId) |
||||
|| (gateway.m_objectKey != m_gateway.m_objectKey)) |
||||
{ |
||||
// A new carousel, or one restructured
|
||||
reset(); |
||||
m_carouselId = gateway.m_carouselId; |
||||
m_gateway = gateway; |
||||
} |
||||
|
||||
m_associationTags.insert(tags.begin(), tags.end()); |
||||
} |
||||
|
||||
// DownloadInfoIndication: the modules of (part of) the carousel, with their sizes and versions
|
||||
void DTVCarousel::dii(const uint8_t *m, int length, uint32_t transactionId) |
||||
{ |
||||
Reader r(m, length); |
||||
const uint32_t downloadId = r.u32(); |
||||
|
||||
if ((m_carouselId < 0) || (downloadId != (uint32_t) m_carouselId)) { |
||||
return; |
||||
} |
||||
|
||||
const int blockSize = r.u16(); |
||||
r.skip(1 + 1 + 4 + 4); // windowSize, ackPeriod, tCDownloadWindow, tCDownloadScenario
|
||||
r.skip(r.u16()); // compatibilityDescriptor
|
||||
const int numberOfModules = r.u16(); |
||||
|
||||
if (!r.m_ok || (blockSize == 0)) { |
||||
return; |
||||
} |
||||
|
||||
std::vector<int> listed; |
||||
|
||||
for (int i = 0; (i < numberOfModules) && r.m_ok; i++) |
||||
{ |
||||
const int moduleId = r.u16(); |
||||
const int64_t moduleSize = r.u32(); |
||||
const int moduleVersion = r.u8(); |
||||
const int moduleInfoLength = r.u8(); |
||||
const uint8_t *info = r.bytes(moduleInfoLength); |
||||
|
||||
if (!r.m_ok) { |
||||
break; |
||||
} |
||||
|
||||
// BIOP::ModuleInfo: timeouts, taps (the PIDs the module's blocks are on), and descriptors
|
||||
Reader ri(info, moduleInfoLength); |
||||
ri.skip(4 + 4 + 4); // moduleTimeOut, blockTimeOut, minBlockTime
|
||||
const int tapsCount = ri.u8(); |
||||
|
||||
for (int t = 0; (t < tapsCount) && ri.m_ok; t++) |
||||
{ |
||||
ri.skip(2 + 2); // id, use
|
||||
const int associationTag = ri.u16(); |
||||
ri.skip(ri.u8()); // selector
|
||||
|
||||
if (ri.m_ok) { |
||||
m_associationTags.insert(associationTag); |
||||
} |
||||
} |
||||
|
||||
int originalSize = -1; |
||||
const int userInfoLength = ri.u8(); |
||||
const uint8_t *userInfo = ri.bytes(userInfoLength); |
||||
|
||||
for (int d = 0; userInfo && (d + 2 <= userInfoLength); d += 2 + userInfo[d + 1]) |
||||
{ |
||||
// compressed_module_descriptor: compression_method (zlib), original_size
|
||||
if ((userInfo[d] == m_compressedModuleDescriptor) && (userInfo[d + 1] >= 5) && (d + 7 <= userInfoLength)) { |
||||
originalSize = (int) std::min<uint32_t>(0x7FFFFFFF, ((uint32_t) userInfo[d + 3] << 24) | (userInfo[d + 4] << 16) | (userInfo[d + 5] << 8) | userInfo[d + 6]); |
||||
} |
||||
} |
||||
|
||||
if ((moduleSize > m_maxModuleSize) || (originalSize > m_maxModuleSize)) { |
||||
continue; |
||||
} |
||||
|
||||
listed.push_back(moduleId); |
||||
auto it = m_modules.find(moduleId); |
||||
|
||||
if ((it != m_modules.end()) && ((it->second.m_version != moduleVersion) || (it->second.m_size != moduleSize) |
||||
|| (it->second.m_blockSize != blockSize) || (it->second.m_originalSize != originalSize))) |
||||
{ |
||||
dropModule(moduleId); |
||||
it = m_modules.end(); |
||||
} |
||||
|
||||
if (it == m_modules.end()) |
||||
{ |
||||
Module module; |
||||
module.m_size = (int) moduleSize; |
||||
module.m_version = moduleVersion; |
||||
module.m_blockSize = blockSize; |
||||
module.m_originalSize = originalSize; |
||||
module.m_blocks.assign((moduleSize + blockSize - 1) / blockSize, false); |
||||
Module& added = m_modules[moduleId] = module; |
||||
|
||||
if (moduleSize == 0) { |
||||
completeModule(moduleId, added); |
||||
} |
||||
} |
||||
} |
||||
|
||||
// The modules no DII lists any more are gone. A DII's identified by its transactionId's identification (bits 1
|
||||
// to 15): the version (bits 16 to 29) and update flag (bit 0) change when it's updated
|
||||
m_diiModules[(transactionId >> 1) & 0x7FFF] = listed; |
||||
std::set<int> current; |
||||
|
||||
for (const auto& dii : m_diiModules) { |
||||
current.insert(dii.second.begin(), dii.second.end()); |
||||
} |
||||
|
||||
std::vector<int> gone; |
||||
qint64 total = 0; |
||||
|
||||
for (const auto& module : m_modules) |
||||
{ |
||||
if (current.count(module.first) == 0) { |
||||
gone.push_back(module.first); |
||||
} else { |
||||
total += module.second.m_size; |
||||
} |
||||
} |
||||
|
||||
for (int moduleId : gone) |
||||
{ |
||||
dropModule(moduleId); |
||||
m_modules.erase(moduleId); |
||||
} |
||||
|
||||
// A carousel far larger than any real one: its data isn't believed
|
||||
if (total > m_maxCarouselSize) |
||||
{ |
||||
const int64_t carouselId = m_carouselId; |
||||
const ObjectRef gateway = m_gateway; |
||||
reset(); |
||||
m_carouselId = carouselId; |
||||
m_gateway = gateway; |
||||
} |
||||
} |
||||
|
||||
// DownloadDataBlock: a block of a module
|
||||
bool DTVCarousel::ddb(const uint8_t *m, int length) |
||||
{ |
||||
Reader r(m, length); |
||||
const int moduleId = r.u16(); |
||||
const int moduleVersion = r.u8(); |
||||
r.skip(1); |
||||
const int blockNumber = r.u16(); |
||||
|
||||
if (!r.m_ok) { |
||||
return false; |
||||
} |
||||
|
||||
auto it = m_modules.find(moduleId); |
||||
|
||||
if ((it == m_modules.end()) || it->second.m_complete || (it->second.m_version != moduleVersion) |
||||
|| (blockNumber >= (int) it->second.m_blocks.size()) || it->second.m_blocks[blockNumber]) { |
||||
return false; |
||||
} |
||||
|
||||
Module& module = it->second; |
||||
const int offset = blockNumber * module.m_blockSize; |
||||
const int expected = std::min(module.m_blockSize, module.m_size - offset); |
||||
|
||||
if (r.left() < expected) { |
||||
return false; |
||||
} |
||||
|
||||
if (module.m_data.empty()) { |
||||
module.m_data.resize(module.m_size); |
||||
} |
||||
|
||||
std::memcpy(module.m_data.data() + offset, r.here(), expected); |
||||
module.m_blocks[blockNumber] = true; |
||||
module.m_blocksReceived++; |
||||
|
||||
if (module.m_blocksReceived == (int) module.m_blocks.size()) { |
||||
completeModule(moduleId, module); |
||||
} |
||||
|
||||
return true; |
||||
} |
||||
|
||||
void DTVCarousel::completeModule(int moduleId, Module& module) |
||||
{ |
||||
if (module.m_originalSize >= 0) |
||||
{ |
||||
// zlib (RFC 1950), as qUncompress takes it after the size it expects, big-endian
|
||||
QByteArray compressed; |
||||
compressed.reserve(4 + module.m_size); |
||||
compressed.append((char) (module.m_originalSize >> 24)); |
||||
compressed.append((char) (module.m_originalSize >> 16)); |
||||
compressed.append((char) (module.m_originalSize >> 8)); |
||||
compressed.append((char) module.m_originalSize); |
||||
compressed.append((const char *) module.m_data.data(), module.m_size); |
||||
const QByteArray data = qUncompress(compressed); |
||||
|
||||
if (data.size() != module.m_originalSize) |
||||
{ |
||||
// Corrupt: received again
|
||||
module.m_blocks.assign(module.m_blocks.size(), false); |
||||
module.m_blocksReceived = 0; |
||||
return; |
||||
} |
||||
|
||||
parseModule(moduleId, (const uint8_t *) data.constData(), data.size()); |
||||
} |
||||
else |
||||
{ |
||||
parseModule(moduleId, module.m_data.data(), module.m_size); |
||||
} |
||||
|
||||
module.m_complete = true; |
||||
std::vector<uint8_t>().swap(module.m_data); // What's needed of it is in the objects
|
||||
m_revision++; |
||||
} |
||||
|
||||
// The BIOP messages of a module: each a file, directory, service gateway or stream (TR 101 202 4.7.3)
|
||||
void DTVCarousel::parseModule(int moduleId, const uint8_t *data, int length) |
||||
{ |
||||
int offset = 0; |
||||
|
||||
while (offset + 12 <= length) |
||||
{ |
||||
// magic "BIOP", biop_version 1.0, byte_order 0 (big-endian), message_type 0, message_size
|
||||
if ((std::memcmp(data + offset, "BIOP", 4) != 0) || (data[offset + 6] != 0)) { |
||||
return; |
||||
} |
||||
|
||||
const int64_t messageSize = ((uint32_t) data[offset + 8] << 24) | (data[offset + 9] << 16) | (data[offset + 10] << 8) | data[offset + 11]; |
||||
|
||||
if (offset + 12 + messageSize > length) { |
||||
return; |
||||
} |
||||
|
||||
Reader r(data + offset + 12, (int) messageSize); |
||||
offset += 12 + (int) messageSize; |
||||
|
||||
ObjectRef ref; |
||||
ref.m_carouselId = (uint32_t) m_carouselId; |
||||
ref.m_moduleId = moduleId; |
||||
const int keyLength = r.u8(); |
||||
const uint8_t *key = r.bytes(keyLength); |
||||
const int kindLength = r.u32(); |
||||
const uint8_t *kindId = r.bytes(kindLength); |
||||
r.skip(r.u16()); // objectInfo
|
||||
const int contexts = r.u8(); |
||||
|
||||
for (int i = 0; (i < contexts) && r.m_ok; i++) |
||||
{ |
||||
r.skip(4); // context_id
|
||||
r.skip(r.u16()); // context_data
|
||||
} |
||||
|
||||
const int bodyLength = r.u32(); |
||||
const uint8_t *body = r.bytes(bodyLength); |
||||
|
||||
if (!r.m_ok) { |
||||
continue; |
||||
} |
||||
|
||||
ref.m_objectKey = QByteArray((const char *) key, keyLength); |
||||
Object object; |
||||
object.m_kind = kindFromId(kindId, kindLength); |
||||
Reader b(body, bodyLength); |
||||
|
||||
if (object.m_kind == Kind::File) |
||||
{ |
||||
const int contentLength = b.u32(); |
||||
const uint8_t *content = b.bytes(contentLength); |
||||
|
||||
if (!b.m_ok) { |
||||
continue; |
||||
} |
||||
|
||||
object.m_content = QByteArray((const char *) content, contentLength); |
||||
} |
||||
else if ((object.m_kind == Kind::Directory) || (object.m_kind == Kind::Gateway)) |
||||
{ |
||||
const int bindings = b.u16(); |
||||
|
||||
for (int i = 0; (i < bindings) && b.m_ok; i++) |
||||
{ |
||||
// BIOP::Name: its components (one, in DVB): the id (the name) and kind
|
||||
Binding binding; |
||||
const int components = b.u8(); |
||||
|
||||
for (int c = 0; (c < components) && b.m_ok; c++) |
||||
{ |
||||
const int idLength = b.u8(); |
||||
const uint8_t *id = b.bytes(idLength); |
||||
b.skip(b.u8()); // kind
|
||||
|
||||
if (id) |
||||
{ |
||||
int n = idLength; |
||||
|
||||
while ((n > 0) && (id[n - 1] == 0)) { |
||||
n--; |
||||
} |
||||
|
||||
binding.m_name = QString::fromUtf8((const char *) id, n); |
||||
} |
||||
} |
||||
|
||||
b.skip(1); // bindingType
|
||||
int used = 0; |
||||
|
||||
if (!b.m_ok || !parseIOR(b.here(), b.left(), used, binding.m_object, binding.m_kind, nullptr)) { |
||||
break; |
||||
} |
||||
|
||||
b.skip(used); |
||||
const int objectInfoLength = b.u16(); |
||||
const uint8_t *objectInfo = b.bytes(objectInfoLength); |
||||
binding.m_size = -1; |
||||
|
||||
// A file's objectInfo starts with its size (DSM::File::ContentSize, 64 bits)
|
||||
if (objectInfo && (binding.m_kind == Kind::File) && (objectInfoLength >= 8)) |
||||
{ |
||||
Reader ri(objectInfo, objectInfoLength); |
||||
binding.m_size = (qint64) ri.u64(); |
||||
} |
||||
|
||||
// Names are of one component, without separators
|
||||
if (b.m_ok && !binding.m_name.isEmpty() && !binding.m_name.contains('/') && !binding.m_name.contains('\\') |
||||
&& (binding.m_name != ".") && (binding.m_name != "..")) { |
||||
object.m_bindings.push_back(binding); |
||||
} |
||||
} |
||||
} |
||||
|
||||
m_objects[ref] = std::move(object); |
||||
} |
||||
} |
||||
|
||||
void DTVCarousel::dropModule(int moduleId) |
||||
{ |
||||
bool dropped = false; |
||||
|
||||
for (auto it = m_objects.begin(); it != m_objects.end();) |
||||
{ |
||||
if (it->first.m_moduleId == moduleId) |
||||
{ |
||||
it = m_objects.erase(it); |
||||
dropped = true; |
||||
} |
||||
else |
||||
{ |
||||
++it; |
||||
} |
||||
} |
||||
|
||||
auto module = m_modules.find(moduleId); |
||||
|
||||
if ((module != m_modules.end()) && module->second.m_complete) { |
||||
dropped = true; |
||||
} |
||||
|
||||
if (dropped) { |
||||
m_revision++; |
||||
} |
||||
} |
||||
|
||||
// An IOP::IOR: the object's kind (its type_id), and from the BIOP profile its location (carousel, module and object
|
||||
// key) and the taps of its ConnBinder (the PIDs to look for it on, by association tag)
|
||||
bool DTVCarousel::parseIOR(const uint8_t *data, int length, int& used, ObjectRef& object, Kind& kind, std::vector<int> *tags) |
||||
{ |
||||
Reader r(data, length); |
||||
const int typeIdLength = r.u32(); |
||||
const uint8_t *typeId = r.bytes(typeIdLength); |
||||
kind = typeId ? kindFromId(typeId, typeIdLength) : Kind::Unknown; |
||||
r.skip((4 - (typeIdLength & 3)) & 3); // Aligned to 4 bytes
|
||||
const int profiles = r.u32(); |
||||
|
||||
for (int p = 0; (p < profiles) && r.m_ok; p++) |
||||
{ |
||||
const uint32_t profileTag = r.u32(); |
||||
const int profileLength = r.u32(); |
||||
const uint8_t *profile = r.bytes(profileLength); |
||||
|
||||
if (!profile || (profileTag != m_tagBIOP)) { |
||||
continue; |
||||
} |
||||
|
||||
Reader pr(profile, profileLength); |
||||
pr.skip(1); // profile_data_byte_order
|
||||
const int components = pr.u8(); |
||||
|
||||
for (int c = 0; (c < components) && pr.m_ok; c++) |
||||
{ |
||||
const uint32_t componentTag = pr.u32(); |
||||
const int componentLength = pr.u8(); |
||||
const uint8_t *component = pr.bytes(componentLength); |
||||
|
||||
if (!component) { |
||||
break; |
||||
} |
||||
|
||||
Reader cr(component, componentLength); |
||||
|
||||
if (componentTag == m_tagObjectLocation) |
||||
{ |
||||
object.m_carouselId = cr.u32(); |
||||
const int moduleId = cr.u16(); |
||||
cr.skip(2); // version
|
||||
const int keyLength = cr.u8(); |
||||
const uint8_t *key = cr.bytes(keyLength); |
||||
|
||||
if (cr.m_ok) |
||||
{ |
||||
object.m_moduleId = moduleId; |
||||
object.m_objectKey = QByteArray((const char *) key, keyLength); |
||||
} |
||||
} |
||||
else if ((componentTag == m_tagConnBinder) && tags) |
||||
{ |
||||
const int taps = cr.u8(); |
||||
|
||||
for (int t = 0; (t < taps) && cr.m_ok; t++) |
||||
{ |
||||
cr.skip(2 + 2); // id, use
|
||||
const int associationTag = cr.u16(); |
||||
cr.skip(cr.u8()); // selector
|
||||
|
||||
if (cr.m_ok) { |
||||
tags->push_back(associationTag); |
||||
} |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
used = r.m_offset; |
||||
return r.m_ok; |
||||
} |
||||
|
||||
DTVCarousel::Progress DTVCarousel::getProgress() const |
||||
{ |
||||
Progress progress; |
||||
|
||||
for (const auto& module : m_modules) |
||||
{ |
||||
progress.m_modules++; |
||||
progress.m_bytes += module.second.m_size; |
||||
|
||||
if (module.second.m_complete) |
||||
{ |
||||
progress.m_modulesComplete++; |
||||
progress.m_bytesComplete += module.second.m_size; |
||||
} |
||||
else if (module.second.m_blockSize > 0) |
||||
{ |
||||
progress.m_bytesComplete += std::min<qint64>(module.second.m_size, (qint64) module.second.m_blocksReceived * module.second.m_blockSize); |
||||
} |
||||
} |
||||
|
||||
return progress; |
||||
} |
||||
|
||||
bool DTVCarousel::isComplete() const |
||||
{ |
||||
if (m_modules.empty()) { |
||||
return false; |
||||
} |
||||
|
||||
for (const auto& module : m_modules) |
||||
{ |
||||
if (!module.second.m_complete) { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
return true; |
||||
} |
||||
|
||||
void DTVCarousel::walk(const ObjectRef& directory, const QString& path, int depth, std::set<ObjectRef>& visited, |
||||
std::vector<Entry> *entries, std::map<QString, QByteArray> *files, const QString *wanted) const |
||||
{ |
||||
auto it = m_objects.find(directory); |
||||
|
||||
if ((it == m_objects.end()) || (depth > m_maxDepth) || !visited.insert(directory).second) { |
||||
return; |
||||
} |
||||
|
||||
for (const Binding& binding : it->second.m_bindings) |
||||
{ |
||||
const QString childPath = path + "/" + binding.m_name; |
||||
auto child = m_objects.find(binding.m_object); |
||||
const bool received = child != m_objects.end(); |
||||
|
||||
// Only objects of this carousel are here: others (in other carousels) can't be received from it
|
||||
if (binding.m_object.m_carouselId != (uint32_t) m_carouselId) { |
||||
continue; |
||||
} |
||||
|
||||
if (binding.m_kind == Kind::File) |
||||
{ |
||||
if (entries) { |
||||
entries->push_back(Entry{childPath, Kind::File, received ? (qint64) child->second.m_content.size() : binding.m_size, received}); |
||||
} |
||||
|
||||
if (received && files && (!wanted || (*wanted == childPath))) { |
||||
(*files)[childPath] = child->second.m_content; |
||||
} |
||||
} |
||||
else |
||||
{ |
||||
if (entries) { |
||||
entries->push_back(Entry{childPath, binding.m_kind, -1, received}); |
||||
} |
||||
|
||||
if ((binding.m_kind == Kind::Directory) && received |
||||
&& (!wanted || wanted->startsWith(childPath + "/"))) { |
||||
walk(binding.m_object, childPath, depth + 1, visited, entries, files, wanted); |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
std::vector<DTVCarousel::Entry> DTVCarousel::getEntries() const |
||||
{ |
||||
std::vector<Entry> entries; |
||||
std::set<ObjectRef> visited; |
||||
walk(m_gateway, "", 0, visited, &entries, nullptr, nullptr); |
||||
std::sort(entries.begin(), entries.end(), [](const Entry& a, const Entry& b) { return a.m_path < b.m_path; }); |
||||
return entries; |
||||
} |
||||
|
||||
bool DTVCarousel::getFile(const QString& path, QByteArray& data) const |
||||
{ |
||||
// Only the directories on the way to it are walked
|
||||
const QString wanted = path.startsWith('/') ? path : "/" + path; |
||||
std::map<QString, QByteArray> files; |
||||
std::set<ObjectRef> visited; |
||||
walk(m_gateway, "", 0, visited, nullptr, &files, &wanted); |
||||
auto it = files.find(wanted); |
||||
|
||||
if (it == files.end()) { |
||||
return false; |
||||
} |
||||
|
||||
data = it->second; |
||||
return true; |
||||
} |
||||
|
||||
std::map<QString, QByteArray> DTVCarousel::getFiles() const |
||||
{ |
||||
std::map<QString, QByteArray> files; |
||||
std::set<ObjectRef> visited; |
||||
walk(m_gateway, "", 0, visited, nullptr, &files, nullptr); |
||||
return files; |
||||
} |
||||
@ -0,0 +1,150 @@
@@ -0,0 +1,150 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// Some code by AI //
|
||||
// //
|
||||
// This program is free software; you can redistribute it and/or modify //
|
||||
// it under the terms of the GNU General Public License as published by //
|
||||
// the Free Software Foundation as version 3 of the License, or //
|
||||
// (at your option) any later version. //
|
||||
// //
|
||||
// This program is distributed in the hope that it will be useful, //
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
|
||||
// GNU General Public License V3 for more details. //
|
||||
// //
|
||||
// You should have received a copy of the GNU General Public License //
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifndef INCLUDE_DTVCAROUSEL_H |
||||
#define INCLUDE_DTVCAROUSEL_H |
||||
|
||||
#include <cstdint> |
||||
#include <map> |
||||
#include <set> |
||||
#include <vector> |
||||
|
||||
#include <QByteArray> |
||||
#include <QString> |
||||
|
||||
#include "export.h" |
||||
|
||||
// A DSM-CC object carousel (ISO/IEC 13818-6, as profiled by EN 301 192 and TR 101 202): the files and directories
|
||||
// a broadcaster sends round and round, for MHEG-5 and HbbTV applications. Fed with the DSM-CC sections (tables 0x3B,
|
||||
// the DSI and DIIs, and 0x3C, the DDBs) of the PID the carousel's DSI is on, and of any others its taps point to.
|
||||
// The DSI gives the service gateway (the root directory) and the DII listing the modules; the DIIs give the modules'
|
||||
// sizes and versions; the DDBs their blocks. A complete module (zlib compressed or not) holds BIOP messages: files,
|
||||
// directories and the service gateway, which the file tree is built from. A module whose version changes is received
|
||||
// again
|
||||
class SDRBASE_API DTVCarousel |
||||
{ |
||||
public: |
||||
enum class Kind { |
||||
File, |
||||
Directory, |
||||
Gateway, //!< The root directory
|
||||
Stream, //!< A stream, or stream events: what's in the tree but not a file
|
||||
Unknown |
||||
}; |
||||
|
||||
//! What's in the tree, received or not: the size of a file's known from its directory before it's received
|
||||
struct Entry { |
||||
QString m_path; //!< From the service gateway, as /dir/file.html
|
||||
Kind m_kind; |
||||
qint64 m_size; //!< Of a file, -1 if not known
|
||||
bool m_received; //!< A file that's been received (directories are listed once they have been)
|
||||
}; |
||||
|
||||
struct Progress { |
||||
int m_modules = 0; //!< Listed by the DIIs
|
||||
int m_modulesComplete = 0; |
||||
qint64 m_bytes = 0; //!< Of the modules (as sent: compressed, if they are)
|
||||
qint64 m_bytesComplete = 0; |
||||
}; |
||||
|
||||
explicit DTVCarousel(int pid); |
||||
void reset(); |
||||
|
||||
//! A DSM-CC section of table 0x3B or 0x3C, with its CRC checked. Returns whether it changed what's received
|
||||
bool section(const uint8_t *s, int length); |
||||
|
||||
int getPid() const { return m_pid; } //!< The PID its DSI is on
|
||||
//! -1 until the DSI's received
|
||||
int64_t getCarouselId() const { return m_carouselId; } |
||||
//! The association tags of PIDs the DIIs and DDBs may come on, other than the DSI's (from the DSI's and DIIs' taps)
|
||||
const std::set<int>& getAssociationTags() const { return m_associationTags; } |
||||
Progress getProgress() const; |
||||
//! All the modules listed have been received
|
||||
bool isComplete() const; |
||||
//! Changes with each module completed or dropped, and with a new DSI
|
||||
int getRevision() const { return m_revision; } |
||||
|
||||
//! The tree, as far as it's been received, in path order
|
||||
std::vector<Entry> getEntries() const; |
||||
//! A file's contents, if it's been received
|
||||
bool getFile(const QString& path, QByteArray& data) const; |
||||
//! The files received, by path
|
||||
std::map<QString, QByteArray> getFiles() const; |
||||
|
||||
static QString kindName(Kind kind); |
||||
//! A file's path made safe to save it by, relative to a directory: characters not allowed in file names replaced
|
||||
static QString localPath(const QString& path); |
||||
|
||||
private: |
||||
static constexpr int m_maxModuleSize = 16 * 1024 * 1024; //!< Larger modules are ignored
|
||||
static constexpr qint64 m_maxCarouselSize = 64 * 1024 * 1024; |
||||
static constexpr int m_maxDepth = 32; |
||||
|
||||
struct ObjectRef { |
||||
uint32_t m_carouselId = 0; |
||||
int m_moduleId = -1; |
||||
QByteArray m_objectKey; |
||||
bool operator<(const ObjectRef& other) const; |
||||
}; |
||||
|
||||
struct Binding { |
||||
QString m_name; |
||||
Kind m_kind; |
||||
ObjectRef m_object; |
||||
qint64 m_size; //!< Of a file, from the binding's object info, -1 if not known
|
||||
}; |
||||
|
||||
struct Object { |
||||
Kind m_kind = Kind::Unknown; |
||||
QByteArray m_content; //!< Of a file
|
||||
std::vector<Binding> m_bindings; //!< Of a directory
|
||||
}; |
||||
|
||||
struct Module { |
||||
int m_size = 0; |
||||
int m_version = -1; |
||||
int m_blockSize = 0; |
||||
int m_originalSize = -1; //!< Uncompressed, when it's compressed
|
||||
std::vector<uint8_t> m_data; |
||||
std::vector<bool> m_blocks; //!< Received
|
||||
int m_blocksReceived = 0; |
||||
bool m_complete = false; |
||||
}; |
||||
|
||||
void dsi(const uint8_t *m, int length); |
||||
void dii(const uint8_t *m, int length, uint32_t transactionId); |
||||
bool ddb(const uint8_t *m, int length); |
||||
void completeModule(int moduleId, Module& module); |
||||
void parseModule(int moduleId, const uint8_t *data, int length); |
||||
void dropModule(int moduleId); |
||||
static bool parseIOR(const uint8_t *data, int length, int& used, ObjectRef& object, Kind& kind, std::vector<int> *tags); |
||||
static Kind kindFromId(const uint8_t *id, int length); |
||||
void walk(const ObjectRef& directory, const QString& path, int depth, std::set<ObjectRef>& visited, |
||||
std::vector<Entry> *entries, std::map<QString, QByteArray> *files, const QString *wanted) const; |
||||
|
||||
const int m_pid; |
||||
int64_t m_carouselId; |
||||
ObjectRef m_gateway; |
||||
std::set<int> m_associationTags; |
||||
std::map<int, Module> m_modules; //!< By module id
|
||||
std::map<int, std::vector<int>> m_diiModules; //!< By the DIIs' identification: the modules each lists
|
||||
std::map<ObjectRef, Object> m_objects; //!< From the modules complete
|
||||
int m_revision; |
||||
}; |
||||
|
||||
#endif // INCLUDE_DTVCAROUSEL_H
|
||||
@ -0,0 +1,500 @@
@@ -0,0 +1,500 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// Some code by AI //
|
||||
// //
|
||||
// This program is free software; you can redistribute it and/or modify //
|
||||
// it under the terms of the GNU General Public License as published by //
|
||||
// the Free Software Foundation as version 3 of the License, or //
|
||||
// (at your option) any later version. //
|
||||
// //
|
||||
// This program is distributed in the hope that it will be useful, //
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
|
||||
// GNU General Public License V3 for more details. //
|
||||
// //
|
||||
// You should have received a copy of the GNU General Public License //
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#include <memory> |
||||
|
||||
#include <QHostAddress> |
||||
#include <QNetworkAccessManager> |
||||
#include <QNetworkReply> |
||||
#include <QNetworkRequest> |
||||
#include <QRandomGenerator> |
||||
#include <QUrlQuery> |
||||
#include <QStringList> |
||||
#include <QTcpServer> |
||||
#include <QTcpSocket> |
||||
#include <QTimer> |
||||
#include <QUrl> |
||||
|
||||
#include "dtv/dtvapps.h" |
||||
#include "dtv/dtvcarouselserver.h" |
||||
|
||||
namespace { |
||||
|
||||
constexpr int m_maxHeader = 16384; |
||||
constexpr int m_maxBody = 1024 * 1024; //!< Of a request proxied
|
||||
constexpr int m_proxyTimeoutMs = 30000; |
||||
constexpr int m_retryMs = 250; |
||||
const QString m_hostPrefix = "dvb-"; |
||||
const QString m_hostSuffix = ".localhost"; |
||||
|
||||
} // namespace
|
||||
|
||||
DTVCarouselServer::DTVCarouselServer(DTVApps *apps, QObject *parent) : |
||||
QObject(parent), |
||||
m_apps(apps), |
||||
m_server(new QTcpServer(this)), |
||||
m_network(new QNetworkAccessManager(this)), |
||||
m_proxyEnabled(false) |
||||
{ |
||||
m_proxyToken = QByteArray::number(QRandomGenerator::global()->generate64(), 16) + QByteArray::number(QRandomGenerator::global()->generate64(), 16); |
||||
|
||||
connect(m_server, &QTcpServer::newConnection, this, &DTVCarouselServer::newConnection); |
||||
} |
||||
|
||||
DTVCarouselServer::~DTVCarouselServer() |
||||
{ |
||||
} |
||||
|
||||
bool DTVCarouselServer::start() |
||||
{ |
||||
if (m_server->isListening()) { |
||||
return true; |
||||
} |
||||
|
||||
if (!m_server->listen(QHostAddress::LocalHost, 0)) |
||||
{ |
||||
qWarning("DTVCarouselServer::start: can't listen: %s", qPrintable(m_server->errorString())); |
||||
return false; |
||||
} |
||||
|
||||
return true; |
||||
} |
||||
|
||||
void DTVCarouselServer::setProxy(bool enabled, const QString& userAgent) |
||||
{ |
||||
m_proxyEnabled = enabled; |
||||
m_userAgent = userAgent; |
||||
} |
||||
|
||||
QString DTVCarouselServer::getProxyPath() const |
||||
{ |
||||
return "/__sdrangel_proxy/" + QString::fromLatin1(m_proxyToken); |
||||
} |
||||
|
||||
int DTVCarouselServer::getPort() const |
||||
{ |
||||
return m_server->isListening() ? m_server->serverPort() : 0; |
||||
} |
||||
|
||||
QString DTVCarouselServer::httpUrl(const QString& dvbUrl) const |
||||
{ |
||||
// dvb://onid.tsid.sid.ctag/path, the onid and tsid may be empty, as they're not needed to find the carousel
|
||||
if (!dvbUrl.startsWith("dvb://", Qt::CaseInsensitive) || !m_server->isListening()) { |
||||
return QString(); |
||||
} |
||||
|
||||
const QString rest = dvbUrl.mid(6); |
||||
const int slash = rest.indexOf('/'); |
||||
const QStringList triplet = rest.left(slash < 0 ? rest.size() : slash).split('.'); |
||||
|
||||
if (triplet.size() != 4) { |
||||
return QString(); |
||||
} |
||||
|
||||
bool sidOK, tagOK; |
||||
triplet[2].toInt(&sidOK, 16); |
||||
triplet[3].toInt(&tagOK, 16); |
||||
|
||||
if (!sidOK || !tagOK) { |
||||
return QString(); |
||||
} |
||||
|
||||
const QString host = m_hostPrefix + QString("%1-%2-%3-%4") |
||||
.arg(triplet[0].isEmpty() ? QString("x") : triplet[0].toLower()) |
||||
.arg(triplet[1].isEmpty() ? QString("x") : triplet[1].toLower()) |
||||
.arg(triplet[2].toLower()) |
||||
.arg(triplet[3].toLower()) + m_hostSuffix; |
||||
return QString("http://%1:%2%3").arg(host).arg(m_server->serverPort()).arg(slash < 0 ? QString("/") : rest.mid(slash)); |
||||
} |
||||
|
||||
QString DTVCarouselServer::dvbUrl(const QString& httpUrl) const |
||||
{ |
||||
const QUrl url(httpUrl); |
||||
|
||||
if (!isServerUrl(httpUrl)) { |
||||
return QString(); |
||||
} |
||||
|
||||
QStringList parts = url.host().mid(m_hostPrefix.size(), url.host().size() - m_hostPrefix.size() - m_hostSuffix.size()).split('-'); |
||||
|
||||
for (QString& part : parts) |
||||
{ |
||||
if (part == "x") { |
||||
part.clear(); |
||||
} |
||||
} |
||||
|
||||
QString result = QString("dvb://%1%2").arg(parts.join('.')).arg(url.path(QUrl::FullyEncoded)); |
||||
|
||||
if (url.hasQuery()) { |
||||
result += "?" + url.query(QUrl::FullyEncoded); |
||||
} |
||||
|
||||
if (url.hasFragment()) { |
||||
result += "#" + url.fragment(QUrl::FullyEncoded); |
||||
} |
||||
|
||||
return result; |
||||
} |
||||
|
||||
bool DTVCarouselServer::isServerUrl(const QString& url) const |
||||
{ |
||||
const QUrl u(url); |
||||
int serviceId, componentTag; |
||||
return m_server->isListening() && (u.scheme() == "http") && (u.port() == m_server->serverPort()) |
||||
&& parseHost(u.host(), serviceId, componentTag); |
||||
} |
||||
|
||||
bool DTVCarouselServer::parseHost(const QString& host, int& serviceId, int& componentTag) |
||||
{ |
||||
QString name = host.toLower(); |
||||
const int colon = name.indexOf(':'); |
||||
|
||||
if (colon >= 0) { |
||||
name = name.left(colon); |
||||
} |
||||
|
||||
if (!name.startsWith(m_hostPrefix) || !name.endsWith(m_hostSuffix)) { |
||||
return false; |
||||
} |
||||
|
||||
const QStringList parts = name.mid(m_hostPrefix.size(), name.size() - m_hostPrefix.size() - m_hostSuffix.size()).split('-'); |
||||
|
||||
if (parts.size() != 4) { |
||||
return false; |
||||
} |
||||
|
||||
bool sidOK, tagOK; |
||||
serviceId = parts[2].toInt(&sidOK, 16); |
||||
componentTag = parts[3].toInt(&tagOK, 16); |
||||
return sidOK && tagOK && (serviceId > 0) && (serviceId <= 0xFFFF) && (componentTag >= 0) && (componentTag <= 0xFF); |
||||
} |
||||
|
||||
QString DTVCarouselServer::contentType(const QString& path) |
||||
{ |
||||
const QString lower = path.toLower(); |
||||
const int dot = lower.lastIndexOf('.'); |
||||
const QString extension = (dot >= 0) && (dot > lower.lastIndexOf('/')) ? lower.mid(dot + 1) : QString(); |
||||
|
||||
// HbbTV's XHTML (application/vnd.hbbtv.xhtml+xml) as HTML, which the browser's more lenient with
|
||||
if ((extension == "html") || (extension == "htm") || (extension == "xhtml") || (extension == "cehtml")) { |
||||
return "text/html"; |
||||
} else if (extension == "js") { |
||||
return "application/javascript"; |
||||
} else if (extension == "css") { |
||||
return "text/css"; |
||||
} else if (extension == "json") { |
||||
return "application/json"; |
||||
} else if (extension == "xml") { |
||||
return "application/xml"; |
||||
} else if (extension == "png") { |
||||
return "image/png"; |
||||
} else if ((extension == "jpg") || (extension == "jpeg")) { |
||||
return "image/jpeg"; |
||||
} else if (extension == "gif") { |
||||
return "image/gif"; |
||||
} else if (extension == "svg") { |
||||
return "image/svg+xml"; |
||||
} else if (extension == "woff") { |
||||
return "font/woff"; |
||||
} else if (extension == "woff2") { |
||||
return "font/woff2"; |
||||
} else if (extension == "ttf") { |
||||
return "font/ttf"; |
||||
} else if (extension == "mp4") { |
||||
return "video/mp4"; |
||||
} else if (extension == "mp3") { |
||||
return "audio/mpeg"; |
||||
} else if (extension == "txt") { |
||||
return "text/plain"; |
||||
} else { |
||||
return "application/octet-stream"; |
||||
} |
||||
} |
||||
|
||||
void DTVCarouselServer::newConnection() |
||||
{ |
||||
while (QTcpSocket *socket = m_server->nextPendingConnection()) |
||||
{ |
||||
connect(socket, &QTcpSocket::disconnected, socket, &QObject::deleteLater); |
||||
connect(socket, &QTcpSocket::readyRead, this, [this, socket]() { readRequest(socket); }); |
||||
} |
||||
} |
||||
|
||||
void DTVCarouselServer::readRequest(QTcpSocket *socket) |
||||
{ |
||||
QByteArray header = socket->property("header").toByteArray() + socket->readAll(); |
||||
const int end = header.indexOf("\r\n\r\n"); |
||||
|
||||
if (((end < 0) && (header.size() > m_maxHeader)) || (end > m_maxHeader)) |
||||
{ |
||||
reply(socket, 431, "Request Header Fields Too Large", "text/plain", QByteArray(), false); |
||||
return; |
||||
} |
||||
|
||||
if (end < 0) |
||||
{ |
||||
socket->setProperty("header", header); |
||||
return; |
||||
} |
||||
|
||||
const QList<QByteArray> lines = header.left(end).split('\n'); |
||||
const QList<QByteArray> requestLine = lines[0].trimmed().split(' '); |
||||
int contentLength = 0; |
||||
|
||||
for (int i = 1; i < lines.size(); i++) |
||||
{ |
||||
const QByteArray line = lines[i].trimmed(); |
||||
|
||||
if (line.toLower().startsWith("content-length:")) { |
||||
contentLength = line.mid(15).trimmed().toInt(); |
||||
} |
||||
} |
||||
|
||||
if ((contentLength < 0) || (contentLength > m_maxBody)) |
||||
{ |
||||
reply(socket, 413, "Payload Too Large", "text/plain", QByteArray(), false); |
||||
return; |
||||
} |
||||
|
||||
// The body, all of it
|
||||
QByteArray body = header.mid(end + 4); |
||||
|
||||
if (body.size() < contentLength) |
||||
{ |
||||
socket->setProperty("header", header); |
||||
return; |
||||
} |
||||
|
||||
body.truncate(contentLength); |
||||
|
||||
// One request a connection: it's closed after the reply
|
||||
disconnect(socket, &QTcpSocket::readyRead, this, nullptr); |
||||
|
||||
if (requestLine.size() < 2) |
||||
{ |
||||
reply(socket, 400, "Bad Request", "text/plain", QByteArray(), false); |
||||
return; |
||||
} |
||||
|
||||
if (m_proxyEnabled && requestLine[1].startsWith(getProxyPath().toLatin1() + "?")) |
||||
{ |
||||
QString proxyHost; |
||||
|
||||
for (int i = 1; i < lines.size(); i++) |
||||
{ |
||||
const QByteArray line = lines[i].trimmed(); |
||||
|
||||
if (line.toLower().startsWith("host:")) { |
||||
proxyHost = QString::fromLatin1(line.mid(5).trimmed()); |
||||
} |
||||
} |
||||
|
||||
proxy(socket, requestLine[0], requestLine[1], lines, body, proxyHost); |
||||
return; |
||||
} |
||||
|
||||
if ((requestLine[0] != "GET") && (requestLine[0] != "HEAD")) |
||||
{ |
||||
reply(socket, 405, "Method Not Allowed", "text/plain", QByteArray(), false); |
||||
return; |
||||
} |
||||
|
||||
std::shared_ptr<Request> request(new Request()); |
||||
request->m_socket = socket; |
||||
request->m_head = requestLine[0] == "HEAD"; |
||||
QString host; |
||||
|
||||
for (int i = 1; i < lines.size(); i++) |
||||
{ |
||||
const QByteArray line = lines[i].trimmed(); |
||||
|
||||
if (line.toLower().startsWith("host:")) { |
||||
host = QString::fromLatin1(line.mid(5).trimmed()); |
||||
} |
||||
} |
||||
|
||||
// The path, without the query or fragment, decoded: of names in the carousel's tree
|
||||
QByteArray target = requestLine[1]; |
||||
const int query = target.indexOf('?'); |
||||
|
||||
if (query >= 0) { |
||||
target = target.left(query); |
||||
} |
||||
|
||||
const QString path = QUrl::fromPercentEncoding(target); |
||||
|
||||
if (!parseHost(host, request->m_serviceId, request->m_componentTag) || !path.startsWith('/') || path.split('/').contains("..")) |
||||
{ |
||||
reply(socket, 404, "Not Found", "text/plain", QByteArray(), request->m_head); |
||||
return; |
||||
} |
||||
|
||||
request->m_path = path.endsWith('/') ? path + "index.html" : path; |
||||
request->m_waiting.start(); |
||||
respond(request.get()); |
||||
|
||||
if (request->m_socket && request->m_socket->property("pending").toBool()) |
||||
{ |
||||
// Not received yet: tried again, until it is or it's waited too long. The timer goes with the socket
|
||||
QTimer *timer = new QTimer(socket); |
||||
timer->setInterval(m_retryMs); |
||||
connect(timer, &QTimer::timeout, this, [this, request, timer]() { |
||||
if (!request->m_socket || !request->m_socket->property("pending").toBool()) { |
||||
timer->stop(); |
||||
} else { |
||||
respond(request.get()); |
||||
} |
||||
}); |
||||
timer->start(); |
||||
} |
||||
} |
||||
|
||||
void DTVCarouselServer::respond(Request *request) |
||||
{ |
||||
QTcpSocket *socket = request->m_socket; |
||||
|
||||
if (!socket) { |
||||
return; |
||||
} |
||||
|
||||
const int pid = m_apps->getComponentPid(request->m_serviceId, request->m_componentTag); |
||||
QByteArray data; |
||||
|
||||
if ((pid >= 0) && m_apps->getCarouselFile(pid, request->m_path, data)) |
||||
{ |
||||
socket->setProperty("pending", false); |
||||
reply(socket, 200, "OK", contentType(request->m_path).toLatin1(), data, request->m_head); |
||||
emit served(request->m_path, 200); |
||||
return; |
||||
} |
||||
|
||||
// Not there: if its carousel's complete it isn't in it, else it may yet be received
|
||||
if (((pid >= 0) && m_apps->isCarouselComplete(pid)) || (request->m_waiting.elapsed() >= m_waitMs)) |
||||
{ |
||||
socket->setProperty("pending", false); |
||||
reply(socket, 404, "Not Found", "text/plain", QByteArray(), request->m_head); |
||||
emit served(request->m_path, 404); |
||||
} |
||||
else |
||||
{ |
||||
socket->setProperty("pending", true); |
||||
} |
||||
} |
||||
|
||||
// A request of a carousel's application to another site, made for it with its TV origin and the browser's user agent
|
||||
void DTVCarouselServer::proxy(QTcpSocket *socket, const QByteArray& method, const QByteArray& target, const QList<QByteArray>& lines, |
||||
const QByteArray& body, const QString& host) |
||||
{ |
||||
int serviceId, componentTag; |
||||
|
||||
if (!parseHost(host, serviceId, componentTag)) |
||||
{ |
||||
reply(socket, 403, "Forbidden", "text/plain", QByteArray(), false); |
||||
return; |
||||
} |
||||
|
||||
const QUrlQuery query(QUrl("http://proxy" + QString::fromLatin1(target))); |
||||
const QUrl url(query.queryItemValue("url", QUrl::FullyDecoded)); |
||||
|
||||
if (!url.isValid() || ((url.scheme() != "http") && (url.scheme() != "https"))) |
||||
{ |
||||
reply(socket, 400, "Bad Request", "text/plain", QByteArray(), false); |
||||
return; |
||||
} |
||||
|
||||
QNetworkRequest request(url); |
||||
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); |
||||
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) |
||||
request.setTransferTimeout(m_proxyTimeoutMs); |
||||
#endif |
||||
|
||||
if (!m_userAgent.isEmpty()) { |
||||
request.setRawHeader("User-Agent", m_userAgent.toUtf8()); |
||||
} |
||||
|
||||
// dvb://onid.tsid.sid, from the carousel's host (dvb-onid-tsid-sid-ctag.localhost)
|
||||
QString name = host.toLower(); |
||||
name = name.left(name.indexOf(':') >= 0 ? name.indexOf(':') : name.size()); |
||||
const QStringList parts = name.mid(4, name.size() - 4 - 10).split('-'); |
||||
|
||||
if ((parts.size() == 4) && (parts[0] != "x") && (parts[1] != "x")) { |
||||
request.setRawHeader("Origin", QString("dvb://%1.%2.%3").arg(parts[0]).arg(parts[1]).arg(parts[2]).toLatin1()); |
||||
} |
||||
|
||||
// What the request says of its content, and what it accepts
|
||||
for (int i = 1; i < lines.size(); i++) |
||||
{ |
||||
const QByteArray line = lines[i].trimmed(); |
||||
const int colon = line.indexOf(':'); |
||||
|
||||
if (colon <= 0) { |
||||
continue; |
||||
} |
||||
|
||||
const QByteArray name = line.left(colon).trimmed(); |
||||
const QByteArray lower = name.toLower(); |
||||
|
||||
if ((lower == "content-type") || (lower == "accept") || (lower == "accept-language") || (lower == "authorization")) { |
||||
request.setRawHeader(name, line.mid(colon + 1).trimmed()); |
||||
} |
||||
} |
||||
|
||||
QPointer<QTcpSocket> client(socket); |
||||
QNetworkReply *networkReply = m_network->sendCustomRequest(request, method, body); |
||||
const bool head = method == "HEAD"; |
||||
|
||||
connect(networkReply, &QNetworkReply::finished, this, [this, networkReply, client, url, head]() { |
||||
networkReply->deleteLater(); |
||||
|
||||
if (!client) { |
||||
return; |
||||
} |
||||
|
||||
int status = networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); |
||||
QByteArray reason = networkReply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toByteArray(); |
||||
|
||||
if (status == 0) |
||||
{ |
||||
qDebug("DTVCarouselServer::proxy: %s: %s", qPrintable(url.toString()), qPrintable(networkReply->errorString())); |
||||
status = 502; |
||||
reason = "Bad Gateway"; |
||||
} |
||||
|
||||
const QByteArray type = networkReply->header(QNetworkRequest::ContentTypeHeader).toByteArray(); |
||||
reply(client, status, reason.isEmpty() ? QByteArray("OK") : reason, type.isEmpty() ? QByteArray("application/octet-stream") : type, |
||||
networkReply->readAll(), head); |
||||
emit served(QString("proxy %1").arg(url.toString()), status); |
||||
}); |
||||
} |
||||
|
||||
void DTVCarouselServer::reply(QTcpSocket *socket, int status, const QByteArray& reason, const QByteArray& type, const QByteArray& body, bool head) |
||||
{ |
||||
QByteArray response = "HTTP/1.1 " + QByteArray::number(status) + " " + reason + "\r\n"; |
||||
response += "Content-Type: " + type + "\r\n"; |
||||
response += "Content-Length: " + QByteArray::number(body.size()) + "\r\n"; |
||||
response += "Cache-Control: no-cache\r\n"; |
||||
response += "Connection: close\r\n\r\n"; |
||||
|
||||
if (!head) { |
||||
response += body; |
||||
} |
||||
|
||||
socket->write(response); |
||||
socket->disconnectFromHost(); |
||||
} |
||||
@ -0,0 +1,98 @@
@@ -0,0 +1,98 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// Some code by AI //
|
||||
// //
|
||||
// This program is free software; you can redistribute it and/or modify //
|
||||
// it under the terms of the GNU General Public License as published by //
|
||||
// the Free Software Foundation as version 3 of the License, or //
|
||||
// (at your option) any later version. //
|
||||
// //
|
||||
// This program is distributed in the hope that it will be useful, //
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
|
||||
// GNU General Public License V3 for more details. //
|
||||
// //
|
||||
// You should have received a copy of the GNU General Public License //
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifndef INCLUDE_DTVCAROUSELSERVER_H |
||||
#define INCLUDE_DTVCAROUSELSERVER_H |
||||
|
||||
#include <QByteArray> |
||||
#include <QElapsedTimer> |
||||
#include <QObject> |
||||
#include <QPointer> |
||||
#include <QString> |
||||
|
||||
#include "export.h" |
||||
|
||||
class DTVApps; |
||||
class QNetworkAccessManager; |
||||
class QTcpServer; |
||||
class QTcpSocket; |
||||
|
||||
// Serves the object carousels DTVApps receives over HTTP, on the loopback interface, for a browser running their
|
||||
// HbbTV applications. A carousel's dvb: URL (TS 102 851: dvb://onid.tsid.sid.ctag/path, in hex) is served as
|
||||
// http://dvb-onid-tsid-sid-ctag.localhost:port/path: each carousel its own origin, as its applications read files by
|
||||
// paths from its root, and *.localhost is the loopback interface to the browser (RFC 6761) without a resolver. A file
|
||||
// not received yet is waited for, as a receiver does while it loads the carousel's modules
|
||||
class SDRBASE_API DTVCarouselServer : public QObject |
||||
{ |
||||
Q_OBJECT |
||||
|
||||
public: |
||||
explicit DTVCarouselServer(DTVApps *apps, QObject *parent = nullptr); |
||||
~DTVCarouselServer(); |
||||
|
||||
bool start(); //!< Listens on a port of the loopback interface
|
||||
int getPort() const; |
||||
//! The HTTP URL a dvb: URL's served at: empty if it isn't one of a carousel (as dvb://current.ait/...)
|
||||
QString httpUrl(const QString& dvbUrl) const; |
||||
//! The dvb: URL an HTTP URL of the server's is of: empty if it isn't one
|
||||
QString dvbUrl(const QString& httpUrl) const; |
||||
//! Whether a URL's of the server
|
||||
bool isServerUrl(const QString& url) const; |
||||
static QString contentType(const QString& path); |
||||
//! Requests a carousel's application makes to other sites, made for it with the origin a TV gives it, its
|
||||
//! service's dvb: URL (dvb://onid.tsid.sid), which a browser can't always be made to (as Qt 5's WebEngine): to
|
||||
//! getProxyPath()?url=..., of the carousel's own origin, so they aren't cross-origin. Off until enabled
|
||||
void setProxy(bool enabled, const QString& userAgent); |
||||
//! As /__sdrangel_proxy/token: the token's random, so the proxy's only of pages given it
|
||||
QString getProxyPath() const; |
||||
|
||||
static constexpr int m_waitMs = 20000; //!< For a file not received yet
|
||||
|
||||
signals: |
||||
//! A request answered: the file's path, and the HTTP status
|
||||
void served(const QString& path, int status); |
||||
|
||||
private: |
||||
struct Request |
||||
{ |
||||
QPointer<QTcpSocket> m_socket; |
||||
QByteArray m_header; |
||||
QElapsedTimer m_waiting; |
||||
bool m_head = false; |
||||
int m_serviceId = 0; |
||||
int m_componentTag = 0; |
||||
QString m_path; |
||||
}; |
||||
|
||||
void newConnection(); |
||||
void readRequest(QTcpSocket *socket); |
||||
void respond(Request *request); |
||||
void reply(QTcpSocket *socket, int status, const QByteArray& reason, const QByteArray& type, const QByteArray& body, bool head); |
||||
void proxy(QTcpSocket *socket, const QByteArray& method, const QByteArray& target, const QList<QByteArray>& lines, |
||||
const QByteArray& body, const QString& host); |
||||
static bool parseHost(const QString& host, int& serviceId, int& componentTag); |
||||
|
||||
DTVApps *m_apps; |
||||
QTcpServer *m_server; |
||||
QNetworkAccessManager *m_network; |
||||
QByteArray m_proxyToken; |
||||
bool m_proxyEnabled; |
||||
QString m_userAgent; |
||||
}; |
||||
|
||||
#endif // INCLUDE_DTVCAROUSELSERVER_H
|
||||
@ -0,0 +1,59 @@
@@ -0,0 +1,59 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// Some code by AI //
|
||||
// //
|
||||
// This program is free software; you can redistribute it and/or modify //
|
||||
// it under the terms of the GNU General Public License as published by //
|
||||
// the Free Software Foundation as version 3 of the License, or //
|
||||
// (at your option) any later version. //
|
||||
// //
|
||||
// This program is distributed in the hope that it will be useful, //
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
|
||||
// GNU General Public License V3 for more details. //
|
||||
// //
|
||||
// You should have received a copy of the GNU General Public License //
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#include "dtvguide.h" |
||||
|
||||
QString DTVGuide::Service::channelText() const |
||||
{ |
||||
if (m_channel < 0) { |
||||
return QString(); |
||||
} |
||||
|
||||
return m_minorChannel >= 0 ? QString("%1.%2").arg(m_channel).arg(m_minorChannel) : QString::number(m_channel); |
||||
} |
||||
|
||||
bool DTVGuide::Service::channelBefore(const Service& other) const |
||||
{ |
||||
// Unsigned, so -1 (none) sorts last
|
||||
if (m_channel != other.m_channel) { |
||||
return (unsigned) m_channel < (unsigned) other.m_channel; |
||||
} |
||||
|
||||
return (unsigned) m_minorChannel < (unsigned) other.m_minorChannel; |
||||
} |
||||
|
||||
QString DTVGuide::genreName(int genre, int networkId) const |
||||
{ |
||||
(void) networkId; |
||||
return genreText(genre); |
||||
} |
||||
|
||||
// Content level 1: EN 300 468 table 29
|
||||
QString DTVGuide::genreText(int genre) |
||||
{ |
||||
static const char *const names[16] = { |
||||
"", "Film/Drama", "News/Current affairs", "Entertainment", "Sport", "Children's", "Music", "Arts/Culture", |
||||
"Social/Political", "Education/Factual", "Leisure/Hobbies", "", "", "", "", "" |
||||
}; |
||||
|
||||
if (genre < 0) { |
||||
return QString(); |
||||
} |
||||
|
||||
return QString(names[(genre >> 4) & 0x0F]); |
||||
} |
||||
@ -0,0 +1,215 @@
@@ -0,0 +1,215 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// Some code by AI //
|
||||
// //
|
||||
// This program is free software; you can redistribute it and/or modify //
|
||||
// it under the terms of the GNU General Public License as published by //
|
||||
// the Free Software Foundation as version 3 of the License, or //
|
||||
// (at your option) any later version. //
|
||||
// //
|
||||
// This program is distributed in the hope that it will be useful, //
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
|
||||
// GNU General Public License V3 for more details. //
|
||||
// //
|
||||
// You should have received a copy of the GNU General Public License //
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifndef INCLUDE_DTVGUIDE_H |
||||
#define INCLUDE_DTVGUIDE_H |
||||
|
||||
#include <utility> |
||||
#include <vector> |
||||
|
||||
#include <QList> |
||||
#include <QString> |
||||
#include <QStringList> |
||||
|
||||
#include "export.h" |
||||
|
||||
// A digital TV programme guide, as the guide's views (sdrgui/dtv) show it: the services of a network (or, for ATSC,
|
||||
// a market) with their schedules, from a broadcast system's service information. DVB's EPG (EN 300 468's SDT, NIT
|
||||
// and EIT) and ATSC's PSIP (A/65's VCT and EIT) each implement it. Services are identified by a network id and a
|
||||
// service id (DVB's original_network_id and service_id; ATSC's transport stream id and program_number), events by
|
||||
// their id in their service. Read from any thread
|
||||
class SDRBASE_API DTVGuide |
||||
{ |
||||
public: |
||||
struct Event |
||||
{ |
||||
int m_eventId = 0; |
||||
qint64 m_start = 0; //!< UTC, seconds since 1970
|
||||
int m_duration = 0; //!< Seconds
|
||||
QString m_title; |
||||
QString m_text; //!< The short description, then any extended description
|
||||
//! Content nibbles (level 1 * 16 + level 2, EN 300 468 table 29), -1 if none. Other systems' genres are given
|
||||
//! as the nearest of these, with their own code from bit 8 (ATSC's A/65 table 6.20), which genreName() names
|
||||
int m_genre = -1; |
||||
int m_minimumAge = 0; //!< From the parental rating, 0 if none
|
||||
bool m_hd = false; |
||||
bool m_subtitles = false; //!< Or captions
|
||||
bool m_audioDescription = false; |
||||
QString m_guidance; //!< As "Contains strong language" (UK), or a rating (ATSC's content advisory)
|
||||
//! The same event on another service (as in HD), from an event linkage descriptor, -1 if none
|
||||
int m_linkNetworkId = -1; |
||||
int m_linkServiceId = -1; |
||||
//! From DVB's EIT (table 6): 0 undefined, 1 not running, 2 starts in a few seconds, 3 pausing, 4 running. Kept
|
||||
//! up to date by broadcasters that use it in the present and following table, to start and end recordings
|
||||
int m_runningStatus = 0; |
||||
//! The content identifier descriptor's CRIDs (TS 102 323, as the UK's D-Book uses them), lower case, empty if
|
||||
//! none: the programme's (a repeat has its first showing's), and its series'. As broadcast: a relative CRID's
|
||||
//! authority is the service's (or its transport stream's, network's), the same for its events
|
||||
QString m_programmeCrid; |
||||
QString m_seriesCrid; |
||||
|
||||
qint64 end() const { return m_start + m_duration; } |
||||
bool isValid() const { return m_duration > 0; } |
||||
}; |
||||
|
||||
struct SDRBASE_API Service |
||||
{ |
||||
int m_networkId = 0; //!< DVB's original_network_id, ATSC's transport stream id
|
||||
int m_transportStreamId = -1; |
||||
int m_serviceId = 0; //!< MPEG program number
|
||||
QString m_name; |
||||
QString m_provider; |
||||
int m_type = 0; //!< DVB's service_type: 1 TV, 2 radio, 0x16 to 0x19 HD TV, 0x0C data...
|
||||
int m_channel = -1; //!< Logical channel number (ATSC's major channel number), -1 if none
|
||||
int m_minorChannel = -1; //!< ATSC's minor channel number, -1 if none
|
||||
bool m_visible = true; //!< The logical channel's visible_service_flag: false to hide it from lists
|
||||
bool m_actual = false; //!< In the transport stream being received
|
||||
int m_events = 0; |
||||
qint64 m_frequency = 0; //!< Of its transport stream, Hz, 0 if not known
|
||||
//! Its transport stream is described by the NIT (or has been received), so it's in this area and can be
|
||||
//! searched for if its frequency isn't known, unlike other regions' (whose SI the UK also carries)
|
||||
bool m_multiplexKnown = false; |
||||
//! Left out of its transport stream's SDT (a complete version of it): no longer broadcast there. Not listed by
|
||||
//! getServices(), and never m_actual
|
||||
bool m_removed = false; |
||||
|
||||
//! The number viewers select it by: "4", or ATSC's "7.1"; empty if none
|
||||
QString channelText() const; |
||||
//! Order by channel number (major, then minor), those without last
|
||||
bool channelBefore(const Service& other) const; |
||||
}; |
||||
|
||||
//! A multiplex of the network, from DVB's NIT, or learned by tuning to it
|
||||
struct TransportStream |
||||
{ |
||||
int m_networkId = 0; //!< original_network_id
|
||||
int m_transportStreamId = 0; |
||||
qint64 m_frequency = 0; //!< Centre, Hz
|
||||
int m_bandwidth = 8000000; //!< Hz
|
||||
bool m_t2 = false; //!< From a T2 delivery system descriptor. The UK describes T2 multiplexes as DVB-T
|
||||
int m_plpId = -1; //!< DVB-T2 PLP, -1 if not known
|
||||
bool m_lowPriority = false; //!< DVB-T hierarchical modes: carried in the low priority stream
|
||||
bool m_actual = false; //!< From the NIT of the network being received, rather than another's
|
||||
bool m_learned = false; //!< The frequency was learned by tuning to it (setFrequency), rather than from a NIT
|
||||
// From a satellite delivery system descriptor (or learned receiving DVB-S or S2): the frequency's the downlink's
|
||||
bool m_satellite = false; |
||||
bool m_s2 = false; //!< DVB-S2, else DVB-S
|
||||
int m_symbolRate = 0; //!< Symbols a second
|
||||
int m_polarisation = 0; //!< 0 linear horizontal, 1 linear vertical, 2 circular left, 3 circular right
|
||||
int m_orbitalPosition = 0; //!< Tenths of a degree east (west negative)
|
||||
int m_fecInner = 0; //!< EN 300 468 table 35: 1 1/2, 2 2/3, 3 3/4, 4 5/6, 5 7/8, 15 none, 0 not defined
|
||||
int m_rollOff = -1; //!< DVB-S2: 0 0.35, 1 0.25, 2 0.20 (as the NIT codes them), S2X's 4 0.15, 5 0.10, 6 0.05 (learned from the BBHEADERs), -1 not known
|
||||
int m_isi = -1; //!< DVB-S2: the input stream it was received in (of a multiple input stream), -1 if not
|
||||
}; |
||||
|
||||
virtual ~DTVGuide() {} |
||||
|
||||
//! UTC, seconds since 1970, from the broadcast's time table and the time since it was received. 0 until received
|
||||
virtual qint64 getTime() const = 0; |
||||
virtual int getTransportStreamId() const = 0; |
||||
//! The network id of the transport stream being received, -1 if not known
|
||||
virtual int getNetworkId() const = 0; |
||||
//! The services, without those removed
|
||||
virtual std::vector<Service> getServices() const = 0; |
||||
//! The same programme as a service's on now on another service, as in HD. False if none
|
||||
virtual bool getSimulcast(int networkId, int serviceId, Service& simulcast) const = 0; |
||||
//! A service, as getServices() gives it. False if not in the guide
|
||||
virtual bool getService(int networkId, int serviceId, Service& service) const = 0; |
||||
//! A programme of a service's schedule, by its id. False if not in the guide
|
||||
virtual bool getEvent(int networkId, int serviceId, int eventId, Event& event) const = 0; |
||||
//! Changes whenever what the guide gives does, so views can skip rebuilding what hasn't changed
|
||||
virtual quint64 getRevision() const = 0; |
||||
//! Of a service in the transport stream being received (or the first with the id, if not known yet)
|
||||
virtual bool getNowNext(int serviceId, Event& now, Event& next) const = 0; |
||||
//! Of any service in the guide
|
||||
virtual bool getNowNext(int networkId, int serviceId, Event& now, Event& next) const = 0; |
||||
//! A service's schedule, in order, from the time less an hour (or all, if no time)
|
||||
virtual std::vector<Event> getEvents(int networkId, int serviceId) const = 0; |
||||
//! The same for many services (network and service ids) at once, in their order
|
||||
virtual std::vector<std::vector<Event>> getEvents(const std::vector<std::pair<int, int>>& services) const = 0; |
||||
//! For each service (network and service ids), a value that changes whenever what getEvents() gives for it may
|
||||
//! (but for the time passing), so views can skip fetching schedules that haven't changed. 0 if not in the guide
|
||||
virtual std::vector<quint64> getServiceRevisions(const std::vector<std::pair<int, int>>& services) const = 0; |
||||
virtual int getEventCount() const = 0; |
||||
//! The name of an event's genre (Event::m_genre), as the network names it (the UK's differ), empty if none
|
||||
virtual QString genreName(int genre, int networkId) const; |
||||
|
||||
//! EN 300 468 table 29's name of a genre's level 1, empty if none
|
||||
static QString genreText(int genre); |
||||
}; |
||||
|
||||
//! A programme from the guide to record
|
||||
struct SDRBASE_API DTVScheduledRecording |
||||
{ |
||||
int m_networkId = 0; |
||||
int m_serviceId = 0; |
||||
int m_eventId = 0; |
||||
qint64 m_start = 0; //!< UTC, seconds since 1970. Updated if the guide changes
|
||||
int m_duration = 0; //!< Seconds
|
||||
QString m_title; |
||||
QString m_serviceName; |
||||
|
||||
qint64 end() const { return m_start + m_duration; } |
||||
bool operator==(const DTVScheduledRecording& other) const { |
||||
return (m_networkId == other.m_networkId) && (m_serviceId == other.m_serviceId) && (m_eventId == other.m_eventId) |
||||
&& (m_start == other.m_start) && (m_duration == other.m_duration) && (m_title == other.m_title); |
||||
} |
||||
}; |
||||
|
||||
//! A series to record, from the programme guide: each programme of a service with its series CRID, once (a
|
||||
//! repeat, by its programme CRID, isn't recorded again)
|
||||
struct SDRBASE_API DTVSeriesRecording |
||||
{ |
||||
int m_networkId = 0; |
||||
int m_serviceId = 0; |
||||
QString m_seriesCrid; //!< Lower case, as the guide has it
|
||||
QString m_title; //!< Of the programme it was set from
|
||||
QString m_serviceName; |
||||
QStringList m_scheduled; //!< Programme CRIDs (or "event:" ids, without one) scheduled already, the latest last
|
||||
|
||||
bool operator==(const DTVSeriesRecording& other) const { |
||||
return (m_networkId == other.m_networkId) && (m_serviceId == other.m_serviceId) && (m_seriesCrid == other.m_seriesCrid) |
||||
&& (m_title == other.m_title) && (m_scheduled == other.m_scheduled); |
||||
} |
||||
}; |
||||
|
||||
// Recordings of programmes from the guide, as the guide's views schedule them: a demodulator implements it
|
||||
class SDRBASE_API DTVRecordingSchedule |
||||
{ |
||||
public: |
||||
virtual ~DTVRecordingSchedule() {} |
||||
|
||||
//! A programme from the guide to record. False if it's already scheduled
|
||||
virtual bool scheduleRecording(int networkId, int serviceId, int eventId) = 0; |
||||
virtual void cancelScheduledRecording(int networkId, int serviceId, int eventId) = 0; |
||||
virtual bool isScheduled(int networkId, int serviceId, int eventId) const = 0; |
||||
virtual QList<DTVScheduledRecording> getScheduledRecordings() const = 0; |
||||
//! Record a programme's series: every programme of its service with its series CRID, each once (not repeats).
|
||||
//! False if it has no series CRID, it's recorded already, or series can't be recorded
|
||||
virtual bool scheduleSeries(int networkId, int serviceId, int eventId) = 0; |
||||
//! Stop recording a programme's series (the programmes scheduled from it stay scheduled)
|
||||
virtual void cancelSeries(int networkId, int serviceId, int eventId) = 0; |
||||
virtual void cancelSeries(int networkId, int serviceId, const QString& seriesCrid) = 0; |
||||
//! The programme's series is being recorded
|
||||
virtual bool isSeriesScheduled(int networkId, int serviceId, int eventId) const = 0; |
||||
virtual QList<DTVSeriesRecording> getSeriesRecordings() const = 0; |
||||
//! Scheduled recordings may retune to their service's multiplex
|
||||
virtual bool recordRetune() const = 0; |
||||
}; |
||||
|
||||
#endif // INCLUDE_DTVGUIDE_H
|
||||
@ -0,0 +1,331 @@
@@ -0,0 +1,331 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// Some code by AI //
|
||||
// //
|
||||
// This program is free software; you can redistribute it and/or modify //
|
||||
// it under the terms of the GNU General Public License as published by //
|
||||
// the Free Software Foundation as version 3 of the License, or //
|
||||
// (at your option) any later version. //
|
||||
// //
|
||||
// This program is distributed in the hope that it will be useful, //
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
|
||||
// GNU General Public License V3 for more details. //
|
||||
// //
|
||||
// You should have received a copy of the GNU General Public License //
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#include <map> |
||||
|
||||
#include <QApplication> |
||||
#include <QClipboard> |
||||
#include <QDialogButtonBox> |
||||
#include <QDir> |
||||
#include <QFile> |
||||
#include <QFileDialog> |
||||
#include <QFileInfo> |
||||
#include <QHeaderView> |
||||
#include <QLabel> |
||||
#include <QMenu> |
||||
#include <QMessageBox> |
||||
#include <QPushButton> |
||||
#include <QScrollBar> |
||||
#include <QSplitter> |
||||
#include <QTreeWidget> |
||||
#include <QVBoxLayout> |
||||
|
||||
#include "dtv/dtvapps.h" |
||||
#include "dtv/dtvappsdialog.h" |
||||
|
||||
namespace { |
||||
|
||||
constexpr int m_pidRole = Qt::UserRole; //!< Of a carousel's items
|
||||
constexpr int m_pathRole = Qt::UserRole + 1; //!< Of a file or directory's, "" for the carousel's
|
||||
|
||||
QString sizeText(qint64 bytes) |
||||
{ |
||||
if (bytes < 0) { |
||||
return QString(); |
||||
} else if (bytes < 10000) { |
||||
return QString("%1 B").arg(bytes); |
||||
} else { |
||||
return QString("%1 KB").arg((bytes + 512) / 1024); |
||||
} |
||||
} |
||||
|
||||
QString expandedKey(int pid, const QString& path) |
||||
{ |
||||
return QString("%1:%2").arg(pid).arg(path); |
||||
} |
||||
|
||||
} // namespace
|
||||
|
||||
DTVAppsDialog::DTVAppsDialog(DTVApps *apps, QWidget *parent) : |
||||
QDialog(parent), |
||||
m_apps(apps), |
||||
m_serviceId(0), |
||||
m_revision(-1) |
||||
{ |
||||
setWindowTitle("Interactive Applications"); |
||||
resize(900, 600); |
||||
|
||||
QVBoxLayout *layout = new QVBoxLayout(this); |
||||
m_service = new QLabel(); |
||||
layout->addWidget(m_service); |
||||
|
||||
QSplitter *splitter = new QSplitter(Qt::Vertical); |
||||
|
||||
m_appsTree = new QTreeWidget(); |
||||
m_appsTree->setHeaderLabels({"Application", "Id", "Type", "Control", "Starts from"}); |
||||
m_appsTree->setRootIsDecorated(false); |
||||
m_appsTree->setToolTip("The service's applications, from its application information table (AIT). AUTOSTART applications start with the service; " |
||||
"PRESENT ones are started by the user (as from the red button). Right click to copy where one starts from"); |
||||
m_appsTree->setContextMenuPolicy(Qt::CustomContextMenu); |
||||
connect(m_appsTree, &QTreeWidget::customContextMenuRequested, this, &DTVAppsDialog::appsMenu); |
||||
splitter->addWidget(m_appsTree); |
||||
|
||||
m_carouselsTree = new QTreeWidget(); |
||||
m_carouselsTree->setHeaderLabels({"Carousel", "Kind", "Size", "Received"}); |
||||
m_carouselsTree->setToolTip("The service's object carousels: the files of its MHEG-5 and HbbTV applications, sent round and round. " |
||||
"Expand one to see its files, as far as they've been received"); |
||||
connect(m_carouselsTree, &QTreeWidget::itemExpanded, this, [this](QTreeWidgetItem *item) { |
||||
const int pid = item->data(0, m_pidRole).toInt(); |
||||
const QString path = item->data(0, m_pathRole).toString(); |
||||
m_expanded.insert(expandedKey(pid, path)); |
||||
|
||||
if (!item->parent() && (item->childCount() == 0)) { |
||||
fillFiles(item); |
||||
} |
||||
}); |
||||
connect(m_carouselsTree, &QTreeWidget::itemCollapsed, this, [this](QTreeWidgetItem *item) { |
||||
m_expanded.erase(expandedKey(item->data(0, m_pidRole).toInt(), item->data(0, m_pathRole).toString())); |
||||
}); |
||||
connect(m_carouselsTree, &QTreeWidget::itemSelectionChanged, this, [this]() { m_save->setEnabled(selectedCarousel() >= 0); }); |
||||
splitter->addWidget(m_carouselsTree); |
||||
splitter->setStretchFactor(0, 1); |
||||
splitter->setStretchFactor(1, 3); |
||||
layout->addWidget(splitter); |
||||
|
||||
QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Close); |
||||
m_save = buttons->addButton("Save Files...", QDialogButtonBox::ActionRole); |
||||
m_save->setToolTip("Save the files of the carousel selected that have been received, to a directory"); |
||||
m_save->setEnabled(false); |
||||
connect(m_save, &QPushButton::clicked, this, &DTVAppsDialog::saveFiles); |
||||
connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject); |
||||
layout->addWidget(buttons); |
||||
|
||||
connect(&m_timer, &QTimer::timeout, this, &DTVAppsDialog::refresh); |
||||
m_timer.start(1000); |
||||
refresh(); |
||||
} |
||||
|
||||
void DTVAppsDialog::setService(int serviceId, const QString& name) |
||||
{ |
||||
if ((serviceId != m_serviceId) || (name != m_serviceName)) |
||||
{ |
||||
if (serviceId != m_serviceId) { |
||||
m_expanded.clear(); |
||||
} |
||||
|
||||
m_serviceId = serviceId; |
||||
m_serviceName = name; |
||||
m_revision = -1; |
||||
refresh(); |
||||
} |
||||
} |
||||
|
||||
void DTVAppsDialog::refresh() |
||||
{ |
||||
const int revision = m_apps->getRevision(); |
||||
|
||||
if (revision == m_revision) { |
||||
return; |
||||
} |
||||
|
||||
m_revision = revision; |
||||
|
||||
if (m_serviceId == 0) { |
||||
m_service->setText("No service is being played"); |
||||
} else { |
||||
m_service->setText(QString("%1 (service %2)").arg(m_serviceName.isEmpty() ? QString("Service") : m_serviceName).arg(m_serviceId)); |
||||
} |
||||
|
||||
refreshApps(); |
||||
refreshCarousels(); |
||||
} |
||||
|
||||
void DTVAppsDialog::refreshApps() |
||||
{ |
||||
const int transportStreamId = m_apps->getTransportStreamId(); |
||||
const int networkId = m_apps->getOriginalNetworkId(); |
||||
const int scroll = m_appsTree->verticalScrollBar()->value(); |
||||
m_appsTree->clear(); |
||||
|
||||
if (m_serviceId == 0) { |
||||
return; |
||||
} |
||||
|
||||
for (const DTVApps::App& app : m_apps->getApps(m_serviceId)) |
||||
{ |
||||
QTreeWidgetItem *item = new QTreeWidgetItem(m_appsTree); |
||||
item->setText(0, app.m_name); |
||||
item->setText(1, app.idText()); |
||||
item->setText(2, app.typeName()); |
||||
item->setText(3, app.controlCodeName()); |
||||
item->setText(4, app.url(networkId, transportStreamId)); |
||||
item->setToolTip(4, item->text(4)); |
||||
} |
||||
|
||||
for (int column = 0; column < 4; column++) { |
||||
m_appsTree->resizeColumnToContents(column); |
||||
} |
||||
|
||||
m_appsTree->verticalScrollBar()->setValue(scroll); |
||||
} |
||||
|
||||
void DTVAppsDialog::refreshCarousels() |
||||
{ |
||||
const int selected = selectedCarousel(); |
||||
const int scroll = m_carouselsTree->verticalScrollBar()->value(); |
||||
m_carouselsTree->clear(); |
||||
|
||||
if (m_serviceId == 0) { |
||||
return; |
||||
} |
||||
|
||||
for (const DTVApps::Carousel& carousel : m_apps->getCarousels(m_serviceId)) |
||||
{ |
||||
QTreeWidgetItem *item = new QTreeWidgetItem(m_carouselsTree); |
||||
item->setText(0, carousel.m_componentTag >= 0 ? QString("PID 0x%1 (component %2)").arg(carousel.m_pid, 0, 16).arg(carousel.m_componentTag) |
||||
: QString("PID 0x%1").arg(carousel.m_pid, 0, 16)); |
||||
item->setText(1, carousel.kindName()); |
||||
item->setData(0, m_pidRole, carousel.m_pid); |
||||
item->setData(0, m_pathRole, QString()); |
||||
|
||||
if (!carousel.m_received) |
||||
{ |
||||
item->setText(3, "Not yet"); |
||||
} |
||||
else |
||||
{ |
||||
const DTVCarousel::Progress& progress = carousel.m_progress; |
||||
item->setText(2, sizeText(progress.m_bytes)); |
||||
item->setText(3, carousel.m_complete ? QString("Complete: %1 files").arg(carousel.m_files) |
||||
: QString("%1 of %2 modules, %3%: %4 files").arg(progress.m_modulesComplete).arg(progress.m_modules) |
||||
.arg(progress.m_bytes > 0 ? (int) (100 * progress.m_bytesComplete / progress.m_bytes) : 0).arg(carousel.m_files)); |
||||
item->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); |
||||
} |
||||
|
||||
if (carousel.m_pid == selected) { |
||||
item->setSelected(true); |
||||
} |
||||
|
||||
if (carousel.m_received && (m_expanded.count(expandedKey(carousel.m_pid, QString())) != 0)) |
||||
{ |
||||
fillFiles(item); |
||||
item->setExpanded(true); |
||||
} |
||||
} |
||||
|
||||
for (int column = 0; column < 4; column++) { |
||||
m_carouselsTree->resizeColumnToContents(column); |
||||
} |
||||
|
||||
m_carouselsTree->verticalScrollBar()->setValue(scroll); |
||||
} |
||||
|
||||
// A carousel's tree, as far as it's been received: what's been listed in directories received, files received or not
|
||||
void DTVAppsDialog::fillFiles(QTreeWidgetItem *carouselItem) |
||||
{ |
||||
const int pid = carouselItem->data(0, m_pidRole).toInt(); |
||||
std::map<QString, QTreeWidgetItem*> directories; |
||||
directories[QString()] = carouselItem; |
||||
|
||||
for (const DTVCarousel::Entry& entry : m_apps->getCarouselEntries(pid)) |
||||
{ |
||||
// Entries are in path order, so a directory's before what's in it
|
||||
const int slash = entry.m_path.lastIndexOf('/'); |
||||
auto parent = directories.find(entry.m_path.left(slash)); |
||||
QTreeWidgetItem *item = new QTreeWidgetItem(parent != directories.end() ? parent->second : carouselItem); |
||||
item->setText(0, entry.m_path.mid(slash + 1)); |
||||
item->setText(1, DTVCarousel::kindName(entry.m_kind)); |
||||
item->setText(2, sizeText(entry.m_size)); |
||||
item->setText(3, entry.m_received ? "Yes" : "No"); |
||||
item->setData(0, m_pidRole, pid); |
||||
item->setData(0, m_pathRole, entry.m_path); |
||||
|
||||
if (entry.m_kind == DTVCarousel::Kind::Directory) |
||||
{ |
||||
directories[entry.m_path] = item; |
||||
|
||||
if (m_expanded.count(expandedKey(pid, entry.m_path)) != 0) { |
||||
item->setExpanded(true); |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
int DTVAppsDialog::selectedCarousel() const |
||||
{ |
||||
const QList<QTreeWidgetItem*> items = m_carouselsTree->selectedItems(); |
||||
|
||||
if (items.isEmpty()) { |
||||
return -1; |
||||
} |
||||
|
||||
return items[0]->data(0, m_pidRole).toInt(); |
||||
} |
||||
|
||||
void DTVAppsDialog::appsMenu(const QPoint& position) |
||||
{ |
||||
QTreeWidgetItem *item = m_appsTree->itemAt(position); |
||||
|
||||
if (!item) { |
||||
return; |
||||
} |
||||
|
||||
QMenu menu(this); |
||||
QAction *copy = menu.addAction("Copy URL"); |
||||
|
||||
if (menu.exec(m_appsTree->viewport()->mapToGlobal(position)) == copy) { |
||||
QApplication::clipboard()->setText(item->text(4)); |
||||
} |
||||
} |
||||
|
||||
void DTVAppsDialog::saveFiles() |
||||
{ |
||||
const int pid = selectedCarousel(); |
||||
|
||||
if (pid < 0) { |
||||
return; |
||||
} |
||||
|
||||
const QString directory = QFileDialog::getExistingDirectory(this, "Save the carousel's files to"); |
||||
|
||||
if (directory.isEmpty()) { |
||||
return; |
||||
} |
||||
|
||||
int saved = 0; |
||||
QStringList failed; |
||||
|
||||
for (const auto& file : m_apps->getCarouselFiles(pid)) |
||||
{ |
||||
const QString path = QDir(directory).filePath(DTVCarousel::localPath(file.first)); |
||||
QDir().mkpath(QFileInfo(path).path()); |
||||
QFile out(path); |
||||
|
||||
if (out.open(QIODevice::WriteOnly) && (out.write(file.second) == file.second.size())) { |
||||
saved++; |
||||
} else { |
||||
failed.append(file.first); |
||||
} |
||||
} |
||||
|
||||
if (!failed.isEmpty()) { |
||||
QMessageBox::warning(this, "Save Files", QString("%1 files saved. Couldn't save %2 files, as %3").arg(saved).arg(failed.size()).arg(failed[0])); |
||||
} else { |
||||
QMessageBox::information(this, "Save Files", QString("%1 files saved to %2").arg(saved).arg(QDir::toNativeSeparators(directory))); |
||||
} |
||||
} |
||||
@ -0,0 +1,67 @@
@@ -0,0 +1,67 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// Some code by AI //
|
||||
// //
|
||||
// This program is free software; you can redistribute it and/or modify //
|
||||
// it under the terms of the GNU General Public License as published by //
|
||||
// the Free Software Foundation as version 3 of the License, or //
|
||||
// (at your option) any later version. //
|
||||
// //
|
||||
// This program is distributed in the hope that it will be useful, //
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
|
||||
// GNU General Public License V3 for more details. //
|
||||
// //
|
||||
// You should have received a copy of the GNU General Public License //
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifndef INCLUDE_DTVAPPSDIALOG_H |
||||
#define INCLUDE_DTVAPPSDIALOG_H |
||||
|
||||
#include <set> |
||||
|
||||
#include <QDialog> |
||||
#include <QTimer> |
||||
|
||||
#include "export.h" |
||||
|
||||
class DTVApps; |
||||
class QLabel; |
||||
class QPushButton; |
||||
class QTreeWidget; |
||||
class QTreeWidgetItem; |
||||
|
||||
// The interactive applications (red button) of the service played, from its AIT, and its object carousels: how much
|
||||
// of each has been received, and its files, which can be saved
|
||||
class SDRGUI_API DTVAppsDialog : public QDialog |
||||
{ |
||||
Q_OBJECT |
||||
|
||||
public: |
||||
DTVAppsDialog(DTVApps *apps, QWidget *parent = nullptr); |
||||
//! The service played: 0 if none
|
||||
void setService(int serviceId, const QString& name); |
||||
|
||||
private: |
||||
void refresh(); |
||||
void refreshApps(); |
||||
void refreshCarousels(); |
||||
void fillFiles(QTreeWidgetItem *carouselItem); |
||||
void appsMenu(const QPoint& position); |
||||
void saveFiles(); |
||||
int selectedCarousel() const; //!< Its PID, -1 if none's selected
|
||||
|
||||
DTVApps *m_apps; |
||||
int m_serviceId; |
||||
QString m_serviceName; |
||||
int m_revision; |
||||
QLabel *m_service; |
||||
QTreeWidget *m_appsTree; |
||||
QTreeWidget *m_carouselsTree; |
||||
QPushButton *m_save; |
||||
std::set<QString> m_expanded; //!< Of the carousels' items: by PID, and path
|
||||
QTimer m_timer; |
||||
}; |
||||
|
||||
#endif // INCLUDE_DTVAPPSDIALOG_H
|
||||
@ -0,0 +1,240 @@
@@ -0,0 +1,240 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// Some code by AI //
|
||||
// //
|
||||
// This program is free software; you can redistribute it and/or modify //
|
||||
// it under the terms of the GNU General Public License as published by //
|
||||
// the Free Software Foundation as version 3 of the License, or //
|
||||
// (at your option) any later version. //
|
||||
// //
|
||||
// This program is distributed in the hope that it will be useful, //
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
|
||||
// GNU General Public License V3 for more details. //
|
||||
// //
|
||||
// You should have received a copy of the GNU General Public License //
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#include <cmath> |
||||
|
||||
#include <QDateTime> |
||||
|
||||
#include "dtv/dtvtsfifo.h" |
||||
#include "dtv/dtvstreamremuxer.h" |
||||
#include "dtv/dtvstreamplayback.h" |
||||
|
||||
namespace { |
||||
|
||||
constexpr int m_fifoSize = 8 * 1024 * 1024; |
||||
constexpr int m_checkMs = 250; |
||||
constexpr qint64 m_endedMs = 1500; //!< No pictures for this long, with the stream all read: it's ended
|
||||
|
||||
} // namespace
|
||||
|
||||
DTVStreamPlayback::DTVStreamPlayback(AudioFifo *audioFifo, DTVVideoPlayer::FrameCallback frameCallback, |
||||
DTVVideoPlayer::CanShowCallback canShowCallback, std::function<void(DTVVideoPlayer *)> configure, QObject *parent) : |
||||
QObject(parent), |
||||
m_audioFifo(audioFifo), |
||||
m_frameCallback(frameCallback), |
||||
m_canShowCallback(canShowCallback), |
||||
m_configure(configure), |
||||
m_position(0.0), |
||||
m_playing(false), |
||||
m_fifo(new DTVTSFifo(m_fifoSize)), |
||||
m_remuxer(nullptr), |
||||
m_player(nullptr), |
||||
m_frameTime(std::nan("")), |
||||
m_frameAt(0), |
||||
m_playingSignalled(false), |
||||
m_duration(std::nan("")) |
||||
{ |
||||
connect(&m_timer, &QTimer::timeout, this, &DTVStreamPlayback::check); |
||||
} |
||||
|
||||
DTVStreamPlayback::~DTVStreamPlayback() |
||||
{ |
||||
stop(); |
||||
} |
||||
|
||||
void DTVStreamPlayback::load(const QString& url, const QMap<QString, QString>& options) |
||||
{ |
||||
stop(); |
||||
m_url = url; |
||||
m_options = options; |
||||
m_position = 0.0; |
||||
m_duration = std::nan(""); |
||||
startRemuxer(0.0); |
||||
m_timer.start(m_checkMs); |
||||
} |
||||
|
||||
void DTVStreamPlayback::play() |
||||
{ |
||||
if (!isLoaded() || m_playing) { |
||||
return; |
||||
} |
||||
|
||||
m_playing = true; |
||||
|
||||
if (!m_remuxer) { |
||||
startRemuxer(m_position); |
||||
} |
||||
|
||||
startPlayer(); |
||||
} |
||||
|
||||
// Paused where it is: the player stopped, and the stream made ready to go on from there
|
||||
void DTVStreamPlayback::pause() |
||||
{ |
||||
if (!m_playing) { |
||||
return; |
||||
} |
||||
|
||||
m_position = getPosition(); |
||||
m_playing = false; |
||||
stopPlayer(); |
||||
stopRemuxer(); |
||||
startRemuxer(m_position); |
||||
} |
||||
|
||||
void DTVStreamPlayback::seek(double position) |
||||
{ |
||||
if (!isLoaded()) { |
||||
return; |
||||
} |
||||
|
||||
m_position = std::max(0.0, position); |
||||
stopPlayer(); |
||||
stopRemuxer(); |
||||
startRemuxer(m_position); |
||||
|
||||
if (m_playing) { |
||||
startPlayer(); |
||||
} |
||||
} |
||||
|
||||
void DTVStreamPlayback::stop() |
||||
{ |
||||
m_timer.stop(); |
||||
stopPlayer(); |
||||
stopRemuxer(); |
||||
m_playing = false; |
||||
m_url.clear(); |
||||
} |
||||
|
||||
double DTVStreamPlayback::getPosition() const |
||||
{ |
||||
const double frameTime = m_frameTime; |
||||
const double offset = m_remuxer ? m_remuxer->getTimestampOffset() : std::nan(""); |
||||
|
||||
if (m_player && !std::isnan(frameTime) && !std::isnan(offset)) { |
||||
return frameTime + offset; |
||||
} |
||||
|
||||
return m_position; |
||||
} |
||||
|
||||
double DTVStreamPlayback::getDuration() const |
||||
{ |
||||
return m_duration; |
||||
} |
||||
|
||||
void DTVStreamPlayback::setAudioOutput(int sampleRate, double latency) |
||||
{ |
||||
if (m_player) { |
||||
m_player->setAudioOutput(sampleRate, latency); |
||||
} |
||||
} |
||||
|
||||
void DTVStreamPlayback::startRemuxer(double position) |
||||
{ |
||||
m_fifo->reset(); |
||||
m_remuxer = new DTVStreamRemuxer(m_fifo.get(), m_url, m_options, position, this); |
||||
DTVStreamRemuxer *remuxer = m_remuxer; |
||||
|
||||
connect(m_remuxer, &DTVStreamRemuxer::opened, this, [this, remuxer](double duration, int width, int height) { |
||||
if (remuxer != m_remuxer) { |
||||
return; |
||||
} |
||||
|
||||
const bool first = std::isnan(m_duration); |
||||
m_duration = duration; |
||||
|
||||
if (first) { |
||||
emit metadata(duration, width, height); |
||||
} |
||||
}, Qt::QueuedConnection); |
||||
connect(m_remuxer, &DTVStreamRemuxer::failed, this, [this, remuxer](const QString& message) { |
||||
if (remuxer == m_remuxer) { |
||||
emit error(message); |
||||
} |
||||
}, Qt::QueuedConnection); |
||||
|
||||
m_remuxer->start(); |
||||
} |
||||
|
||||
void DTVStreamPlayback::stopRemuxer() |
||||
{ |
||||
if (m_remuxer) |
||||
{ |
||||
m_remuxer->stop(); |
||||
delete m_remuxer; |
||||
m_remuxer = nullptr; |
||||
} |
||||
} |
||||
|
||||
void DTVStreamPlayback::startPlayer() |
||||
{ |
||||
if (m_player) { |
||||
return; |
||||
} |
||||
|
||||
m_frameTime = std::nan(""); |
||||
m_playingSignalled = false; |
||||
m_player = new DTVVideoPlayer(m_fifo.get(), m_audioFifo); |
||||
m_player->setService(0); // The remuxed stream's one
|
||||
|
||||
if (m_configure) { |
||||
m_configure(m_player); |
||||
} |
||||
|
||||
m_player->setFrameCallback([this](GLVideoFramePtr frame) { |
||||
m_frameTime = frame->m_timestamp; |
||||
m_frameAt = QDateTime::currentMSecsSinceEpoch(); |
||||
|
||||
if (!m_playingSignalled.exchange(true)) |
||||
{ |
||||
qDebug("DTVStreamPlayback: first picture at %.3f", frame->m_timestamp); |
||||
QMetaObject::invokeMethod(this, [this]() { emit playing(); }, Qt::QueuedConnection); |
||||
} |
||||
|
||||
if (m_frameCallback) { |
||||
m_frameCallback(frame); |
||||
} |
||||
}); |
||||
m_player->setCanShowCallback(m_canShowCallback); |
||||
m_player->start(); |
||||
} |
||||
|
||||
void DTVStreamPlayback::stopPlayer() |
||||
{ |
||||
if (m_player) |
||||
{ |
||||
m_player->stopPlayer(); |
||||
delete m_player; |
||||
m_player = nullptr; |
||||
} |
||||
} |
||||
|
||||
// The end: the stream's all been read and played (no pictures for a while)
|
||||
void DTVStreamPlayback::check() |
||||
{ |
||||
if (m_playing && m_remuxer && m_remuxer->isFinished() && (m_fifo->fill() == 0) && m_playingSignalled |
||||
&& (QDateTime::currentMSecsSinceEpoch() - m_frameAt > m_endedMs)) |
||||
{ |
||||
m_position = getPosition(); |
||||
m_playing = false; |
||||
stopPlayer(); |
||||
emit ended(); |
||||
} |
||||
} |
||||
@ -0,0 +1,97 @@
@@ -0,0 +1,97 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// Some code by AI //
|
||||
// //
|
||||
// This program is free software; you can redistribute it and/or modify //
|
||||
// it under the terms of the GNU General Public License as published by //
|
||||
// the Free Software Foundation as version 3 of the License, or //
|
||||
// (at your option) any later version. //
|
||||
// //
|
||||
// This program is distributed in the hope that it will be useful, //
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
|
||||
// GNU General Public License V3 for more details. //
|
||||
// //
|
||||
// You should have received a copy of the GNU General Public License //
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifndef INCLUDE_DTVSTREAMPLAYBACK_H |
||||
#define INCLUDE_DTVSTREAMPLAYBACK_H |
||||
|
||||
#include <atomic> |
||||
#include <functional> |
||||
#include <memory> |
||||
|
||||
#include <QMap> |
||||
#include <QObject> |
||||
#include <QString> |
||||
#include <QTimer> |
||||
|
||||
#include "dtv/dtvvideoplayer.h" |
||||
#include "export.h" |
||||
|
||||
class AudioFifo; |
||||
class DTVTSFifo; |
||||
class DTVStreamRemuxer; |
||||
|
||||
// Plays a stream from the internet, as an interactive application's video element would (as iPlayer's): remuxed to a
|
||||
// transport stream (DTVStreamRemuxer), played by a DTVVideoPlayer as a broadcast is. Loading opens the stream (and
|
||||
// fills the buffer); playing starts the player; pausing and seeking stop it, and start the stream again from the
|
||||
// position, as the player plays what it's given as it comes
|
||||
class SDRGUI_API DTVStreamPlayback : public QObject |
||||
{ |
||||
Q_OBJECT |
||||
|
||||
public: |
||||
//! configure: called with each player made, to set it up as the broadcast's is (deinterlacing, volume...)
|
||||
DTVStreamPlayback(AudioFifo *audioFifo, DTVVideoPlayer::FrameCallback frameCallback, DTVVideoPlayer::CanShowCallback canShowCallback, |
||||
std::function<void(DTVVideoPlayer *)> configure, QObject *parent = nullptr); |
||||
~DTVStreamPlayback(); |
||||
|
||||
//! options: FFmpeg's, as user_agent and headers
|
||||
void load(const QString& url, const QMap<QString, QString>& options); |
||||
void play(); |
||||
void pause(); |
||||
void seek(double position); |
||||
void stop(); |
||||
|
||||
bool isLoaded() const { return !m_url.isEmpty(); } |
||||
bool isPlaying() const { return m_playing; } |
||||
double getPosition() const; //!< Seconds into the stream, of the picture shown
|
||||
double getDuration() const; //!< NaN until known, infinite if live
|
||||
void setAudioOutput(int sampleRate, double latency); |
||||
DTVVideoPlayer *getPlayer() { return m_player; } |
||||
|
||||
signals: |
||||
void metadata(double duration, int width, int height); |
||||
void playing(); //!< The first picture's shown, after play() or a seek
|
||||
void ended(); |
||||
void error(const QString& message); |
||||
|
||||
private: |
||||
void startRemuxer(double position); |
||||
void stopRemuxer(); |
||||
void startPlayer(); |
||||
void stopPlayer(); |
||||
void check(); |
||||
|
||||
AudioFifo *m_audioFifo; |
||||
DTVVideoPlayer::FrameCallback m_frameCallback; |
||||
DTVVideoPlayer::CanShowCallback m_canShowCallback; |
||||
std::function<void(DTVVideoPlayer *)> m_configure; |
||||
QString m_url; |
||||
QMap<QString, QString> m_options; |
||||
double m_position; //!< Where the stream's started from (when paused, where it's paused)
|
||||
bool m_playing; |
||||
std::unique_ptr<DTVTSFifo> m_fifo; |
||||
DTVStreamRemuxer *m_remuxer; |
||||
DTVVideoPlayer *m_player; |
||||
std::atomic<double> m_frameTime; //!< Timestamp of the last picture shown, NaN if none yet
|
||||
std::atomic<qint64> m_frameAt; //!< When, ms since epoch
|
||||
std::atomic<bool> m_playingSignalled; |
||||
double m_duration; |
||||
QTimer m_timer; |
||||
}; |
||||
|
||||
#endif // INCLUDE_DTVSTREAMPLAYBACK_H
|
||||
@ -0,0 +1,289 @@
@@ -0,0 +1,289 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// Some code by AI //
|
||||
// //
|
||||
// This program is free software; you can redistribute it and/or modify //
|
||||
// it under the terms of the GNU General Public License as published by //
|
||||
// the Free Software Foundation as version 3 of the License, or //
|
||||
// (at your option) any later version. //
|
||||
// //
|
||||
// This program is distributed in the hope that it will be useful, //
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
|
||||
// GNU General Public License V3 for more details. //
|
||||
// //
|
||||
// You should have received a copy of the GNU General Public License //
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#include <algorithm> |
||||
#include <cmath> |
||||
#include <iterator> |
||||
#include <limits> |
||||
|
||||
extern "C" { |
||||
#include <libavformat/avformat.h> |
||||
#include <libavutil/opt.h> |
||||
} |
||||
|
||||
#include "dtv/dtvtsfifo.h" |
||||
#include "dtv/dtvstreamremuxer.h" |
||||
|
||||
namespace { |
||||
|
||||
constexpr int m_fifoHigh = 3 * 1024 * 1024; //!< Bytes in the FIFO above which writing waits
|
||||
constexpr int m_ioBufferSize = 188 * 512; |
||||
|
||||
QString errorText(int error) |
||||
{ |
||||
char text[AV_ERROR_MAX_STRING_SIZE] = {0}; |
||||
av_strerror(error, text, sizeof(text)); |
||||
return QString::fromUtf8(text); |
||||
} |
||||
|
||||
} // namespace
|
||||
|
||||
DTVStreamRemuxer::DTVStreamRemuxer(DTVTSFifo *fifo, const QString& url, const QMap<QString, QString>& options, double start, QObject *parent) : |
||||
QThread(parent), |
||||
m_fifo(fifo), |
||||
m_url(url), |
||||
m_options(options), |
||||
m_start(start), |
||||
m_stop(false), |
||||
m_duration(std::nan("")), |
||||
m_offset(std::nan("")), |
||||
m_finished(false) |
||||
{ |
||||
} |
||||
|
||||
DTVStreamRemuxer::~DTVStreamRemuxer() |
||||
{ |
||||
stop(); |
||||
} |
||||
|
||||
void DTVStreamRemuxer::stop() |
||||
{ |
||||
m_stop = true; |
||||
wait(); |
||||
} |
||||
|
||||
int DTVStreamRemuxer::interrupt(void *opaque) |
||||
{ |
||||
return static_cast<DTVStreamRemuxer *>(opaque)->m_stop ? 1 : 0; |
||||
} |
||||
|
||||
// The muxer's output, into the FIFO: as fast as it's read from it
|
||||
int DTVStreamRemuxer::writePacket(void *opaque, const uint8_t *buf, int size) |
||||
{ |
||||
DTVStreamRemuxer *remuxer = static_cast<DTVStreamRemuxer *>(opaque); |
||||
|
||||
while (!remuxer->m_stop && (remuxer->m_fifo->fill() > m_fifoHigh)) { |
||||
msleep(20); |
||||
} |
||||
|
||||
if (remuxer->m_stop) { |
||||
return AVERROR_EXIT; |
||||
} |
||||
|
||||
remuxer->m_fifo->write(buf, size); |
||||
return size; |
||||
} |
||||
|
||||
void DTVStreamRemuxer::run() |
||||
{ |
||||
AVFormatContext *in = avformat_alloc_context(); |
||||
AVFormatContext *out = nullptr; |
||||
AVPacket *packet = av_packet_alloc(); |
||||
in->interrupt_callback.callback = &DTVStreamRemuxer::interrupt; |
||||
in->interrupt_callback.opaque = this; |
||||
|
||||
AVDictionary *options = nullptr; |
||||
|
||||
for (auto it = m_options.begin(); it != m_options.end(); ++it) { |
||||
av_dict_set(&options, it.key().toUtf8().constData(), it.value().toUtf8().constData(), 0); |
||||
} |
||||
|
||||
av_dict_set(&options, "reconnect", "1", 0); |
||||
int ret = avformat_open_input(&in, m_url.toUtf8().constData(), nullptr, &options); |
||||
av_dict_free(&options); |
||||
|
||||
if (ret < 0) |
||||
{ |
||||
if (!m_stop) { |
||||
emit failed(QString("Can't open %1: %2").arg(m_url).arg(errorText(ret))); |
||||
} |
||||
|
||||
av_packet_free(&packet); |
||||
return; |
||||
} |
||||
|
||||
ret = avformat_find_stream_info(in, nullptr); |
||||
|
||||
if ((ret < 0) && !m_stop) { |
||||
qDebug("DTVStreamRemuxer::run: avformat_find_stream_info: %s", qPrintable(errorText(ret))); |
||||
} |
||||
|
||||
// The best video (the largest picture, up to 1080 lines, and of those the highest bit rate) and audio (the
|
||||
// highest bit rate): the others discarded, so their segments aren't fetched
|
||||
int video = -1, audio = -1; |
||||
|
||||
for (unsigned int i = 0; i < in->nb_streams; i++) |
||||
{ |
||||
const AVCodecParameters *p = in->streams[i]->codecpar; |
||||
|
||||
if (p->codec_type == AVMEDIA_TYPE_VIDEO) |
||||
{ |
||||
const AVCodecParameters *best = video >= 0 ? in->streams[video]->codecpar : nullptr; |
||||
const int64_t pixels = (int64_t) p->width * p->height; |
||||
const int64_t bestPixels = best ? (int64_t) best->width * best->height : -1; |
||||
|
||||
if ((p->height <= 1088) && (!best || (pixels > bestPixels) || ((pixels == bestPixels) && (p->bit_rate > best->bit_rate)))) { |
||||
video = (int) i; |
||||
} |
||||
} |
||||
else if (p->codec_type == AVMEDIA_TYPE_AUDIO) |
||||
{ |
||||
if ((audio < 0) || (p->bit_rate > in->streams[audio]->codecpar->bit_rate)) { |
||||
audio = (int) i; |
||||
} |
||||
} |
||||
} |
||||
|
||||
for (unsigned int i = 0; i < in->nb_streams; i++) { |
||||
in->streams[i]->discard = ((int) i == video) || ((int) i == audio) ? AVDISCARD_DEFAULT : AVDISCARD_ALL; |
||||
} |
||||
|
||||
if ((video < 0) && (audio < 0)) |
||||
{ |
||||
emit failed(QString("%1 has no video or audio").arg(m_url)); |
||||
avformat_close_input(&in); |
||||
av_packet_free(&packet); |
||||
return; |
||||
} |
||||
|
||||
// Live streams have no duration
|
||||
const double duration = in->duration != AV_NOPTS_VALUE ? in->duration / (double) AV_TIME_BASE : std::numeric_limits<double>::infinity(); |
||||
m_duration = duration; |
||||
emit opened(duration, video >= 0 ? in->streams[video]->codecpar->width : 0, video >= 0 ? in->streams[video]->codecpar->height : 0); |
||||
|
||||
if (m_start > 0.0) |
||||
{ |
||||
const int64_t target = (int64_t) (m_start * AV_TIME_BASE) + (in->start_time != AV_NOPTS_VALUE ? in->start_time : 0); |
||||
ret = avformat_seek_file(in, -1, INT64_MIN, target, target, 0); |
||||
|
||||
if (ret < 0) { |
||||
qDebug("DTVStreamRemuxer::run: seek to %.1f s: %s", m_start, qPrintable(errorText(ret))); |
||||
} |
||||
} |
||||
|
||||
// A transport stream, as a broadcast's: its streams' timestamps from m_timestampStart
|
||||
avformat_alloc_output_context2(&out, nullptr, "mpegts", nullptr); |
||||
int outIndex[64]; |
||||
std::fill(std::begin(outIndex), std::end(outIndex), -1); |
||||
|
||||
for (int s : {video, audio}) |
||||
{ |
||||
if ((s < 0) || (s >= 64)) { |
||||
continue; |
||||
} |
||||
|
||||
AVStream *os = avformat_new_stream(out, nullptr); |
||||
avcodec_parameters_copy(os->codecpar, in->streams[s]->codecpar); |
||||
os->codecpar->codec_tag = 0; |
||||
os->time_base = AVRational{1, 90000}; |
||||
outIndex[s] = os->index; |
||||
} |
||||
|
||||
uint8_t *ioBuffer = (uint8_t *) av_malloc(m_ioBufferSize); |
||||
// FFmpeg 7 (libavformat 61) made the buffer const
|
||||
#if LIBAVFORMAT_VERSION_MAJOR >= 61 |
||||
int (*write)(void *, const uint8_t *, int) = &DTVStreamRemuxer::writePacket; |
||||
#else |
||||
int (*write)(void *, uint8_t *, int) = [](void *opaque, uint8_t *buf, int size) { return writePacket(opaque, buf, size); }; |
||||
#endif |
||||
out->pb = avio_alloc_context(ioBuffer, m_ioBufferSize, 1, this, nullptr, write, nullptr); |
||||
out->flags |= AVFMT_FLAG_CUSTOM_IO; |
||||
AVDictionary *muxOptions = nullptr; |
||||
av_dict_set(&muxOptions, "mpegts_flags", "resend_headers", 0); |
||||
ret = avformat_write_header(out, &muxOptions); |
||||
av_dict_free(&muxOptions); |
||||
|
||||
if (ret < 0) |
||||
{ |
||||
emit failed(QString("Can't remux %1: %2").arg(m_url).arg(errorText(ret))); |
||||
} |
||||
else |
||||
{ |
||||
int64_t base = AV_NOPTS_VALUE; // The first packet's time (in AV_TIME_BASE)
|
||||
|
||||
while (!m_stop) |
||||
{ |
||||
ret = av_read_frame(in, packet); |
||||
|
||||
if (ret < 0) |
||||
{ |
||||
if (ret != AVERROR_EXIT) { |
||||
m_finished = true; |
||||
} |
||||
|
||||
break; |
||||
} |
||||
|
||||
const int s = packet->stream_index; |
||||
|
||||
if ((s < 0) || (s >= 64) || (outIndex[s] < 0) || ((packet->dts == AV_NOPTS_VALUE) && (packet->pts == AV_NOPTS_VALUE))) |
||||
{ |
||||
av_packet_unref(packet); |
||||
continue; |
||||
} |
||||
|
||||
const AVRational inBase = in->streams[s]->time_base; |
||||
const int64_t first = packet->dts != AV_NOPTS_VALUE ? packet->dts : packet->pts; |
||||
|
||||
if (base == AV_NOPTS_VALUE) |
||||
{ |
||||
// Positions are from the stream's start, as a media element's currentTime is
|
||||
base = av_rescale_q(first, inBase, AVRational{1, AV_TIME_BASE}); |
||||
m_offset = (base - (in->start_time != AV_NOPTS_VALUE ? in->start_time : 0)) / (double) AV_TIME_BASE - m_timestampStart; |
||||
qDebug("DTVStreamRemuxer::run: start_time %.3f, first packet (stream %d) %.3f, pts %.3f", in->start_time / (double) AV_TIME_BASE, s, |
||||
base / (double) AV_TIME_BASE, packet->pts != AV_NOPTS_VALUE ? packet->pts * av_q2d(inBase) : -1.0); |
||||
} |
||||
|
||||
// Rebased, to start at m_timestampStart
|
||||
const int64_t shift = av_rescale_q((int64_t) (m_timestampStart * AV_TIME_BASE) - base, AVRational{1, AV_TIME_BASE}, inBase); |
||||
|
||||
if (packet->pts != AV_NOPTS_VALUE) { |
||||
packet->pts += shift; |
||||
} |
||||
|
||||
if (packet->dts != AV_NOPTS_VALUE) { |
||||
packet->dts += shift; |
||||
} |
||||
|
||||
AVStream *os = out->streams[outIndex[s]]; |
||||
av_packet_rescale_ts(packet, inBase, os->time_base); |
||||
packet->stream_index = os->index; |
||||
packet->pos = -1; |
||||
ret = av_interleaved_write_frame(out, packet); |
||||
|
||||
if ((ret < 0) && (ret != AVERROR_EXIT)) { |
||||
qDebug("DTVStreamRemuxer::run: write: %s", qPrintable(errorText(ret))); |
||||
} |
||||
} |
||||
|
||||
if (!m_stop) { |
||||
av_write_trailer(out); |
||||
} |
||||
} |
||||
|
||||
if (out->pb) |
||||
{ |
||||
avio_flush(out->pb); |
||||
av_freep(&out->pb->buffer); |
||||
avio_context_free(&out->pb); |
||||
} |
||||
|
||||
avformat_free_context(out); |
||||
avformat_close_input(&in); |
||||
av_packet_free(&packet); |
||||
} |
||||
@ -0,0 +1,74 @@
@@ -0,0 +1,74 @@
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
|
||||
// Some code by AI //
|
||||
// //
|
||||
// This program is free software; you can redistribute it and/or modify //
|
||||
// it under the terms of the GNU General Public License as published by //
|
||||
// the Free Software Foundation as version 3 of the License, or //
|
||||
// (at your option) any later version. //
|
||||
// //
|
||||
// This program is distributed in the hope that it will be useful, //
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
|
||||
// GNU General Public License V3 for more details. //
|
||||
// //
|
||||
// You should have received a copy of the GNU General Public License //
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
|
||||
///////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifndef INCLUDE_DTVSTREAMREMUXER_H |
||||
#define INCLUDE_DTVSTREAMREMUXER_H |
||||
|
||||
#include <atomic> |
||||
|
||||
#include <QMap> |
||||
#include <QString> |
||||
#include <QThread> |
||||
|
||||
#include "export.h" |
||||
|
||||
class DTVTSFifo; |
||||
struct AVFormatContext; |
||||
|
||||
// A stream from the internet (DASH, HLS, or a file), as an application plays, remuxed to a transport stream of one
|
||||
// service, its best video and audio, for DTVVideoPlayer to play as it does a broadcast. Written to a FIFO, waiting
|
||||
// while it's full, so it's read as fast as it's played. Timestamps start at 1 s, so the stream's time of what's
|
||||
// shown (from its start) is the frame's timestamp plus getTimestampOffset()
|
||||
class SDRGUI_API DTVStreamRemuxer : public QThread |
||||
{ |
||||
Q_OBJECT |
||||
|
||||
public: |
||||
//! options: FFmpeg's, as user_agent and headers. From start seconds into the stream
|
||||
DTVStreamRemuxer(DTVTSFifo *fifo, const QString& url, const QMap<QString, QString>& options, double start, QObject *parent = nullptr); |
||||
~DTVStreamRemuxer(); |
||||
|
||||
void stop(); //!< And waits for the thread
|
||||
double getDuration() const { return m_duration; } //!< Seconds, NaN until known, infinite if live
|
||||
double getTimestampOffset() const { return m_offset; } //!< NaN until the first packet's written
|
||||
bool isFinished() const { return m_finished; } //!< The end of the stream written
|
||||
|
||||
static constexpr double m_timestampStart = 1.0; |
||||
|
||||
signals: |
||||
void opened(double duration, int width, int height); |
||||
void failed(const QString& error); |
||||
|
||||
protected: |
||||
void run() override; |
||||
|
||||
private: |
||||
static int writePacket(void *opaque, const uint8_t *buf, int size); |
||||
static int interrupt(void *opaque); |
||||
|
||||
DTVTSFifo *m_fifo; |
||||
const QString m_url; |
||||
const QMap<QString, QString> m_options; |
||||
const double m_start; |
||||
std::atomic<bool> m_stop; |
||||
std::atomic<double> m_duration; |
||||
std::atomic<double> m_offset; |
||||
std::atomic<bool> m_finished; |
||||
}; |
||||
|
||||
#endif // INCLUDE_DTVSTREAMREMUXER_H
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,233 @@
@@ -0,0 +1,233 @@
|
||||
/**
|
||||
* SDRangel |
||||
* This is the web REST/JSON API of SDRangel SDR software. SDRangel is an Open Source Qt5/OpenGL 3.0+ (4.3+ in Windows) GUI and server Software Defined Radio and signal analyzer in software. It supports Airspy, BladeRF, HackRF, LimeSDR, PlutoSDR, RTL-SDR, SDRplay RSP1 and FunCube --- Limitations and specifcities: * In SDRangel GUI the first Rx device set cannot be deleted. Conversely the server starts with no device sets and its number of device sets can be reduced to zero by as many calls as necessary to /sdrangel/deviceset with DELETE method. * Preset import and export from/to file is a server only feature. * Device set focus is a GUI only feature. * The following channels are not implemented (status 501 is returned): ATV and DATV demodulators, Channel Analyzer NG, LoRa demodulator * The device settings and report structures contains only the sub-structure corresponding to the device type. The DeviceSettings and DeviceReport structures documented here shows all of them but only one will be or should be present at a time * The channel settings and report structures contains only the sub-structure corresponding to the channel type. The ChannelSettings and ChannelReport structures documented here shows all of them but only one will be or should be present at a time ---
|
||||
* |
||||
* OpenAPI spec version: 7.0.0 |
||||
* Contact: f4exb06@gmail.com |
||||
* |
||||
* NOTE: This class is auto generated by the swagger code generator program. |
||||
* https://github.com/swagger-api/swagger-codegen.git
|
||||
* Do not edit the class manually. |
||||
*/ |
||||
|
||||
|
||||
#include "SWGDVBDemodApp.h" |
||||
|
||||
#include "SWGHelpers.h" |
||||
|
||||
#include <QJsonDocument> |
||||
#include <QJsonArray> |
||||
#include <QObject> |
||||
#include <QDebug> |
||||
|
||||
namespace SWGSDRangel { |
||||
|
||||
SWGDVBDemodApp::SWGDVBDemodApp(QString* json) { |
||||
init(); |
||||
this->fromJson(*json); |
||||
} |
||||
|
||||
SWGDVBDemodApp::SWGDVBDemodApp() { |
||||
application_id = nullptr; |
||||
m_application_id_isSet = false; |
||||
type = nullptr; |
||||
m_type_isSet = false; |
||||
control_code = nullptr; |
||||
m_control_code_isSet = false; |
||||
name = nullptr; |
||||
m_name_isSet = false; |
||||
url = nullptr; |
||||
m_url_isSet = false; |
||||
carousel_pid = 0; |
||||
m_carousel_pid_isSet = false; |
||||
} |
||||
|
||||
SWGDVBDemodApp::~SWGDVBDemodApp() { |
||||
this->cleanup(); |
||||
} |
||||
|
||||
void |
||||
SWGDVBDemodApp::init() { |
||||
application_id = new QString(""); |
||||
m_application_id_isSet = false; |
||||
type = new QString(""); |
||||
m_type_isSet = false; |
||||
control_code = new QString(""); |
||||
m_control_code_isSet = false; |
||||
name = new QString(""); |
||||
m_name_isSet = false; |
||||
url = new QString(""); |
||||
m_url_isSet = false; |
||||
carousel_pid = 0; |
||||
m_carousel_pid_isSet = false; |
||||
} |
||||
|
||||
void |
||||
SWGDVBDemodApp::cleanup() { |
||||
if(application_id != nullptr) {
|
||||
delete application_id; |
||||
} |
||||
if(type != nullptr) {
|
||||
delete type; |
||||
} |
||||
if(control_code != nullptr) {
|
||||
delete control_code; |
||||
} |
||||
if(name != nullptr) {
|
||||
delete name; |
||||
} |
||||
if(url != nullptr) {
|
||||
delete url; |
||||
} |
||||
|
||||
} |
||||
|
||||
SWGDVBDemodApp* |
||||
SWGDVBDemodApp::fromJson(QString &json) { |
||||
QByteArray array (json.toStdString().c_str()); |
||||
QJsonDocument doc = QJsonDocument::fromJson(array); |
||||
QJsonObject jsonObject = doc.object(); |
||||
this->fromJsonObject(jsonObject); |
||||
return this; |
||||
} |
||||
|
||||
void |
||||
SWGDVBDemodApp::fromJsonObject(QJsonObject &pJson) { |
||||
::SWGSDRangel::setValue(&application_id, pJson["applicationId"], "QString", "QString"); |
||||
|
||||
::SWGSDRangel::setValue(&type, pJson["type"], "QString", "QString"); |
||||
|
||||
::SWGSDRangel::setValue(&control_code, pJson["controlCode"], "QString", "QString"); |
||||
|
||||
::SWGSDRangel::setValue(&name, pJson["name"], "QString", "QString"); |
||||
|
||||
::SWGSDRangel::setValue(&url, pJson["url"], "QString", "QString"); |
||||
|
||||
::SWGSDRangel::setValue(&carousel_pid, pJson["carouselPid"], "qint32", ""); |
||||
|
||||
} |
||||
|
||||
QString |
||||
SWGDVBDemodApp::asJson () |
||||
{ |
||||
QJsonObject* obj = this->asJsonObject(); |
||||
|
||||
QJsonDocument doc(*obj); |
||||
QByteArray bytes = doc.toJson(); |
||||
delete obj; |
||||
return QString(bytes); |
||||
} |
||||
|
||||
QJsonObject* |
||||
SWGDVBDemodApp::asJsonObject() { |
||||
QJsonObject* obj = new QJsonObject(); |
||||
if(application_id != nullptr && *application_id != QString("")){ |
||||
toJsonValue(QString("applicationId"), application_id, obj, QString("QString")); |
||||
} |
||||
if(type != nullptr && *type != QString("")){ |
||||
toJsonValue(QString("type"), type, obj, QString("QString")); |
||||
} |
||||
if(control_code != nullptr && *control_code != QString("")){ |
||||
toJsonValue(QString("controlCode"), control_code, obj, QString("QString")); |
||||
} |
||||
if(name != nullptr && *name != QString("")){ |
||||
toJsonValue(QString("name"), name, obj, QString("QString")); |
||||
} |
||||
if(url != nullptr && *url != QString("")){ |
||||
toJsonValue(QString("url"), url, obj, QString("QString")); |
||||
} |
||||
if(m_carousel_pid_isSet){ |
||||
obj->insert("carouselPid", QJsonValue(carousel_pid)); |
||||
} |
||||
|
||||
return obj; |
||||
} |
||||
|
||||
QString* |
||||
SWGDVBDemodApp::getApplicationId() { |
||||
return application_id; |
||||
} |
||||
void |
||||
SWGDVBDemodApp::setApplicationId(QString* application_id) { |
||||
this->application_id = application_id; |
||||
this->m_application_id_isSet = true; |
||||
} |
||||
|
||||
QString* |
||||
SWGDVBDemodApp::getType() { |
||||
return type; |
||||
} |
||||
void |
||||
SWGDVBDemodApp::setType(QString* type) { |
||||
this->type = type; |
||||
this->m_type_isSet = true; |
||||
} |
||||
|
||||
QString* |
||||
SWGDVBDemodApp::getControlCode() { |
||||
return control_code; |
||||
} |
||||
void |
||||
SWGDVBDemodApp::setControlCode(QString* control_code) { |
||||
this->control_code = control_code; |
||||
this->m_control_code_isSet = true; |
||||
} |
||||
|
||||
QString* |
||||
SWGDVBDemodApp::getName() { |
||||
return name; |
||||
} |
||||
void |
||||
SWGDVBDemodApp::setName(QString* name) { |
||||
this->name = name; |
||||
this->m_name_isSet = true; |
||||
} |
||||
|
||||
QString* |
||||
SWGDVBDemodApp::getUrl() { |
||||
return url; |
||||
} |
||||
void |
||||
SWGDVBDemodApp::setUrl(QString* url) { |
||||
this->url = url; |
||||
this->m_url_isSet = true; |
||||
} |
||||
|
||||
qint32 |
||||
SWGDVBDemodApp::getCarouselPid() { |
||||
return carousel_pid; |
||||
} |
||||
void |
||||
SWGDVBDemodApp::setCarouselPid(qint32 carousel_pid) { |
||||
this->carousel_pid = carousel_pid; |
||||
this->m_carousel_pid_isSet = true; |
||||
} |
||||
|
||||
|
||||
bool |
||||
SWGDVBDemodApp::isSet(){ |
||||
bool isObjectUpdated = false; |
||||
do{ |
||||
if(application_id && *application_id != QString("")){ |
||||
isObjectUpdated = true; break; |
||||
} |
||||
if(type && *type != QString("")){ |
||||
isObjectUpdated = true; break; |
||||
} |
||||
if(control_code && *control_code != QString("")){ |
||||
isObjectUpdated = true; break; |
||||
} |
||||
if(name && *name != QString("")){ |
||||
isObjectUpdated = true; break; |
||||
} |
||||
if(url && *url != QString("")){ |
||||
isObjectUpdated = true; break; |
||||
} |
||||
if(m_carousel_pid_isSet){ |
||||
isObjectUpdated = true; break; |
||||
} |
||||
}while(false); |
||||
return isObjectUpdated; |
||||
} |
||||
} |
||||
|
||||
@ -0,0 +1,89 @@
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* SDRangel |
||||
* This is the web REST/JSON API of SDRangel SDR software. SDRangel is an Open Source Qt5/OpenGL 3.0+ (4.3+ in Windows) GUI and server Software Defined Radio and signal analyzer in software. It supports Airspy, BladeRF, HackRF, LimeSDR, PlutoSDR, RTL-SDR, SDRplay RSP1 and FunCube --- Limitations and specifcities: * In SDRangel GUI the first Rx device set cannot be deleted. Conversely the server starts with no device sets and its number of device sets can be reduced to zero by as many calls as necessary to /sdrangel/deviceset with DELETE method. * Preset import and export from/to file is a server only feature. * Device set focus is a GUI only feature. * The following channels are not implemented (status 501 is returned): ATV and DATV demodulators, Channel Analyzer NG, LoRa demodulator * The device settings and report structures contains only the sub-structure corresponding to the device type. The DeviceSettings and DeviceReport structures documented here shows all of them but only one will be or should be present at a time * The channel settings and report structures contains only the sub-structure corresponding to the channel type. The ChannelSettings and ChannelReport structures documented here shows all of them but only one will be or should be present at a time ---
|
||||
* |
||||
* OpenAPI spec version: 7.0.0 |
||||
* Contact: f4exb06@gmail.com |
||||
* |
||||
* NOTE: This class is auto generated by the swagger code generator program. |
||||
* https://github.com/swagger-api/swagger-codegen.git
|
||||
* Do not edit the class manually. |
||||
*/ |
||||
|
||||
/*
|
||||
* SWGDVBDemodApp.h |
||||
* |
||||
* An interactive application of a service, from its application information table (AIT) |
||||
*/ |
||||
|
||||
#ifndef SWGDVBDemodApp_H_ |
||||
#define SWGDVBDemodApp_H_ |
||||
|
||||
#include <QJsonObject> |
||||
|
||||
|
||||
#include <QString> |
||||
|
||||
#include "SWGObject.h" |
||||
#include "export.h" |
||||
|
||||
namespace SWGSDRangel { |
||||
|
||||
class SWG_API SWGDVBDemodApp: public SWGObject { |
||||
public: |
||||
SWGDVBDemodApp(); |
||||
SWGDVBDemodApp(QString* json); |
||||
virtual ~SWGDVBDemodApp(); |
||||
void init(); |
||||
void cleanup(); |
||||
|
||||
virtual QString asJson () override; |
||||
virtual QJsonObject* asJsonObject() override; |
||||
virtual void fromJsonObject(QJsonObject &json) override; |
||||
virtual SWGDVBDemodApp* fromJson(QString &jsonString) override; |
||||
|
||||
QString* getApplicationId(); |
||||
void setApplicationId(QString* application_id); |
||||
|
||||
QString* getType(); |
||||
void setType(QString* type); |
||||
|
||||
QString* getControlCode(); |
||||
void setControlCode(QString* control_code); |
||||
|
||||
QString* getName(); |
||||
void setName(QString* name); |
||||
|
||||
QString* getUrl(); |
||||
void setUrl(QString* url); |
||||
|
||||
qint32 getCarouselPid(); |
||||
void setCarouselPid(qint32 carousel_pid); |
||||
|
||||
|
||||
virtual bool isSet() override; |
||||
|
||||
private: |
||||
QString* application_id; |
||||
bool m_application_id_isSet; |
||||
|
||||
QString* type; |
||||
bool m_type_isSet; |
||||
|
||||
QString* control_code; |
||||
bool m_control_code_isSet; |
||||
|
||||
QString* name; |
||||
bool m_name_isSet; |
||||
|
||||
QString* url; |
||||
bool m_url_isSet; |
||||
|
||||
qint32 carousel_pid; |
||||
bool m_carousel_pid_isSet; |
||||
|
||||
}; |
||||
|
||||
} |
||||
|
||||
#endif /* SWGDVBDemodApp_H_ */ |
||||
@ -0,0 +1,317 @@
@@ -0,0 +1,317 @@
|
||||
/**
|
||||
* SDRangel |
||||
* This is the web REST/JSON API of SDRangel SDR software. SDRangel is an Open Source Qt5/OpenGL 3.0+ (4.3+ in Windows) GUI and server Software Defined Radio and signal analyzer in software. It supports Airspy, BladeRF, HackRF, LimeSDR, PlutoSDR, RTL-SDR, SDRplay RSP1 and FunCube --- Limitations and specifcities: * In SDRangel GUI the first Rx device set cannot be deleted. Conversely the server starts with no device sets and its number of device sets can be reduced to zero by as many calls as necessary to /sdrangel/deviceset with DELETE method. * Preset import and export from/to file is a server only feature. * Device set focus is a GUI only feature. * The following channels are not implemented (status 501 is returned): ATV and DATV demodulators, Channel Analyzer NG, LoRa demodulator * The device settings and report structures contains only the sub-structure corresponding to the device type. The DeviceSettings and DeviceReport structures documented here shows all of them but only one will be or should be present at a time * The channel settings and report structures contains only the sub-structure corresponding to the channel type. The ChannelSettings and ChannelReport structures documented here shows all of them but only one will be or should be present at a time ---
|
||||
* |
||||
* OpenAPI spec version: 7.0.0 |
||||
* Contact: f4exb06@gmail.com |
||||
* |
||||
* NOTE: This class is auto generated by the swagger code generator program. |
||||
* https://github.com/swagger-api/swagger-codegen.git
|
||||
* Do not edit the class manually. |
||||
*/ |
||||
|
||||
|
||||
#include "SWGDVBDemodCarousel.h" |
||||
|
||||
#include "SWGHelpers.h" |
||||
|
||||
#include <QJsonDocument> |
||||
#include <QJsonArray> |
||||
#include <QObject> |
||||
#include <QDebug> |
||||
|
||||
namespace SWGSDRangel { |
||||
|
||||
SWGDVBDemodCarousel::SWGDVBDemodCarousel(QString* json) { |
||||
init(); |
||||
this->fromJson(*json); |
||||
} |
||||
|
||||
SWGDVBDemodCarousel::SWGDVBDemodCarousel() { |
||||
pid = 0; |
||||
m_pid_isSet = false; |
||||
component_tag = 0; |
||||
m_component_tag_isSet = false; |
||||
carousel_id = 0L; |
||||
m_carousel_id_isSet = false; |
||||
kind = nullptr; |
||||
m_kind_isSet = false; |
||||
received = 0; |
||||
m_received_isSet = false; |
||||
modules = 0; |
||||
m_modules_isSet = false; |
||||
modules_complete = 0; |
||||
m_modules_complete_isSet = false; |
||||
bytes = 0L; |
||||
m_bytes_isSet = false; |
||||
bytes_complete = 0L; |
||||
m_bytes_complete_isSet = false; |
||||
files = 0; |
||||
m_files_isSet = false; |
||||
} |
||||
|
||||
SWGDVBDemodCarousel::~SWGDVBDemodCarousel() { |
||||
this->cleanup(); |
||||
} |
||||
|
||||
void |
||||
SWGDVBDemodCarousel::init() { |
||||
pid = 0; |
||||
m_pid_isSet = false; |
||||
component_tag = 0; |
||||
m_component_tag_isSet = false; |
||||
carousel_id = 0L; |
||||
m_carousel_id_isSet = false; |
||||
kind = new QString(""); |
||||
m_kind_isSet = false; |
||||
received = 0; |
||||
m_received_isSet = false; |
||||
modules = 0; |
||||
m_modules_isSet = false; |
||||
modules_complete = 0; |
||||
m_modules_complete_isSet = false; |
||||
bytes = 0L; |
||||
m_bytes_isSet = false; |
||||
bytes_complete = 0L; |
||||
m_bytes_complete_isSet = false; |
||||
files = 0; |
||||
m_files_isSet = false; |
||||
} |
||||
|
||||
void |
||||
SWGDVBDemodCarousel::cleanup() { |
||||
|
||||
|
||||
|
||||
if(kind != nullptr) {
|
||||
delete kind; |
||||
} |
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
} |
||||
|
||||
SWGDVBDemodCarousel* |
||||
SWGDVBDemodCarousel::fromJson(QString &json) { |
||||
QByteArray array (json.toStdString().c_str()); |
||||
QJsonDocument doc = QJsonDocument::fromJson(array); |
||||
QJsonObject jsonObject = doc.object(); |
||||
this->fromJsonObject(jsonObject); |
||||
return this; |
||||
} |
||||
|
||||
void |
||||
SWGDVBDemodCarousel::fromJsonObject(QJsonObject &pJson) { |
||||
::SWGSDRangel::setValue(&pid, pJson["pid"], "qint32", ""); |
||||
|
||||
::SWGSDRangel::setValue(&component_tag, pJson["componentTag"], "qint32", ""); |
||||
|
||||
::SWGSDRangel::setValue(&carousel_id, pJson["carouselId"], "qint64", ""); |
||||
|
||||
::SWGSDRangel::setValue(&kind, pJson["kind"], "QString", "QString"); |
||||
|
||||
::SWGSDRangel::setValue(&received, pJson["received"], "qint32", ""); |
||||
|
||||
::SWGSDRangel::setValue(&modules, pJson["modules"], "qint32", ""); |
||||
|
||||
::SWGSDRangel::setValue(&modules_complete, pJson["modulesComplete"], "qint32", ""); |
||||
|
||||
::SWGSDRangel::setValue(&bytes, pJson["bytes"], "qint64", ""); |
||||
|
||||
::SWGSDRangel::setValue(&bytes_complete, pJson["bytesComplete"], "qint64", ""); |
||||
|
||||
::SWGSDRangel::setValue(&files, pJson["files"], "qint32", ""); |
||||
|
||||
} |
||||
|
||||
QString |
||||
SWGDVBDemodCarousel::asJson () |
||||
{ |
||||
QJsonObject* obj = this->asJsonObject(); |
||||
|
||||
QJsonDocument doc(*obj); |
||||
QByteArray bytes = doc.toJson(); |
||||
delete obj; |
||||
return QString(bytes); |
||||
} |
||||
|
||||
QJsonObject* |
||||
SWGDVBDemodCarousel::asJsonObject() { |
||||
QJsonObject* obj = new QJsonObject(); |
||||
if(m_pid_isSet){ |
||||
obj->insert("pid", QJsonValue(pid)); |
||||
} |
||||
if(m_component_tag_isSet){ |
||||
obj->insert("componentTag", QJsonValue(component_tag)); |
||||
} |
||||
if(m_carousel_id_isSet){ |
||||
obj->insert("carouselId", QJsonValue(carousel_id)); |
||||
} |
||||
if(kind != nullptr && *kind != QString("")){ |
||||
toJsonValue(QString("kind"), kind, obj, QString("QString")); |
||||
} |
||||
if(m_received_isSet){ |
||||
obj->insert("received", QJsonValue(received)); |
||||
} |
||||
if(m_modules_isSet){ |
||||
obj->insert("modules", QJsonValue(modules)); |
||||
} |
||||
if(m_modules_complete_isSet){ |
||||
obj->insert("modulesComplete", QJsonValue(modules_complete)); |
||||
} |
||||
if(m_bytes_isSet){ |
||||
obj->insert("bytes", QJsonValue(bytes)); |
||||
} |
||||
if(m_bytes_complete_isSet){ |
||||
obj->insert("bytesComplete", QJsonValue(bytes_complete)); |
||||
} |
||||
if(m_files_isSet){ |
||||
obj->insert("files", QJsonValue(files)); |
||||
} |
||||
|
||||
return obj; |
||||
} |
||||
|
||||
qint32 |
||||
SWGDVBDemodCarousel::getPid() { |
||||
return pid; |
||||
} |
||||
void |
||||
SWGDVBDemodCarousel::setPid(qint32 pid) { |
||||
this->pid = pid; |
||||
this->m_pid_isSet = true; |
||||
} |
||||
|
||||
qint32 |
||||
SWGDVBDemodCarousel::getComponentTag() { |
||||
return component_tag; |
||||
} |
||||
void |
||||
SWGDVBDemodCarousel::setComponentTag(qint32 component_tag) { |
||||
this->component_tag = component_tag; |
||||
this->m_component_tag_isSet = true; |
||||
} |
||||
|
||||
qint64 |
||||
SWGDVBDemodCarousel::getCarouselId() { |
||||
return carousel_id; |
||||
} |
||||
void |
||||
SWGDVBDemodCarousel::setCarouselId(qint64 carousel_id) { |
||||
this->carousel_id = carousel_id; |
||||
this->m_carousel_id_isSet = true; |
||||
} |
||||
|
||||
QString* |
||||
SWGDVBDemodCarousel::getKind() { |
||||
return kind; |
||||
} |
||||
void |
||||
SWGDVBDemodCarousel::setKind(QString* kind) { |
||||
this->kind = kind; |
||||
this->m_kind_isSet = true; |
||||
} |
||||
|
||||
qint32 |
||||
SWGDVBDemodCarousel::getReceived() { |
||||
return received; |
||||
} |
||||
void |
||||
SWGDVBDemodCarousel::setReceived(qint32 received) { |
||||
this->received = received; |
||||
this->m_received_isSet = true; |
||||
} |
||||
|
||||
qint32 |
||||
SWGDVBDemodCarousel::getModules() { |
||||
return modules; |
||||
} |
||||
void |
||||
SWGDVBDemodCarousel::setModules(qint32 modules) { |
||||
this->modules = modules; |
||||
this->m_modules_isSet = true; |
||||
} |
||||
|
||||
qint32 |
||||
SWGDVBDemodCarousel::getModulesComplete() { |
||||
return modules_complete; |
||||
} |
||||
void |
||||
SWGDVBDemodCarousel::setModulesComplete(qint32 modules_complete) { |
||||
this->modules_complete = modules_complete; |
||||
this->m_modules_complete_isSet = true; |
||||
} |
||||
|
||||
qint64 |
||||
SWGDVBDemodCarousel::getBytes() { |
||||
return bytes; |
||||
} |
||||
void |
||||
SWGDVBDemodCarousel::setBytes(qint64 bytes) { |
||||
this->bytes = bytes; |
||||
this->m_bytes_isSet = true; |
||||
} |
||||
|
||||
qint64 |
||||
SWGDVBDemodCarousel::getBytesComplete() { |
||||
return bytes_complete; |
||||
} |
||||
void |
||||
SWGDVBDemodCarousel::setBytesComplete(qint64 bytes_complete) { |
||||
this->bytes_complete = bytes_complete; |
||||
this->m_bytes_complete_isSet = true; |
||||
} |
||||
|
||||
qint32 |
||||
SWGDVBDemodCarousel::getFiles() { |
||||
return files; |
||||
} |
||||
void |
||||
SWGDVBDemodCarousel::setFiles(qint32 files) { |
||||
this->files = files; |
||||
this->m_files_isSet = true; |
||||
} |
||||
|
||||
|
||||
bool |
||||
SWGDVBDemodCarousel::isSet(){ |
||||
bool isObjectUpdated = false; |
||||
do{ |
||||
if(m_pid_isSet){ |
||||
isObjectUpdated = true; break; |
||||
} |
||||
if(m_component_tag_isSet){ |
||||
isObjectUpdated = true; break; |
||||
} |
||||
if(m_carousel_id_isSet){ |
||||
isObjectUpdated = true; break; |
||||
} |
||||
if(kind && *kind != QString("")){ |
||||
isObjectUpdated = true; break; |
||||
} |
||||
if(m_received_isSet){ |
||||
isObjectUpdated = true; break; |
||||
} |
||||
if(m_modules_isSet){ |
||||
isObjectUpdated = true; break; |
||||
} |
||||
if(m_modules_complete_isSet){ |
||||
isObjectUpdated = true; break; |
||||
} |
||||
if(m_bytes_isSet){ |
||||
isObjectUpdated = true; break; |
||||
} |
||||
if(m_bytes_complete_isSet){ |
||||
isObjectUpdated = true; break; |
||||
} |
||||
if(m_files_isSet){ |
||||
isObjectUpdated = true; break; |
||||
} |
||||
}while(false); |
||||
return isObjectUpdated; |
||||
} |
||||
} |
||||
|
||||
@ -0,0 +1,113 @@
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* SDRangel |
||||
* This is the web REST/JSON API of SDRangel SDR software. SDRangel is an Open Source Qt5/OpenGL 3.0+ (4.3+ in Windows) GUI and server Software Defined Radio and signal analyzer in software. It supports Airspy, BladeRF, HackRF, LimeSDR, PlutoSDR, RTL-SDR, SDRplay RSP1 and FunCube --- Limitations and specifcities: * In SDRangel GUI the first Rx device set cannot be deleted. Conversely the server starts with no device sets and its number of device sets can be reduced to zero by as many calls as necessary to /sdrangel/deviceset with DELETE method. * Preset import and export from/to file is a server only feature. * Device set focus is a GUI only feature. * The following channels are not implemented (status 501 is returned): ATV and DATV demodulators, Channel Analyzer NG, LoRa demodulator * The device settings and report structures contains only the sub-structure corresponding to the device type. The DeviceSettings and DeviceReport structures documented here shows all of them but only one will be or should be present at a time * The channel settings and report structures contains only the sub-structure corresponding to the channel type. The ChannelSettings and ChannelReport structures documented here shows all of them but only one will be or should be present at a time ---
|
||||
* |
||||
* OpenAPI spec version: 7.0.0 |
||||
* Contact: f4exb06@gmail.com |
||||
* |
||||
* NOTE: This class is auto generated by the swagger code generator program. |
||||
* https://github.com/swagger-api/swagger-codegen.git
|
||||
* Do not edit the class manually. |
||||
*/ |
||||
|
||||
/*
|
||||
* SWGDVBDemodCarousel.h |
||||
* |
||||
* An object carousel of a service |
||||
*/ |
||||
|
||||
#ifndef SWGDVBDemodCarousel_H_ |
||||
#define SWGDVBDemodCarousel_H_ |
||||
|
||||
#include <QJsonObject> |
||||
|
||||
|
||||
#include <QString> |
||||
|
||||
#include "SWGObject.h" |
||||
#include "export.h" |
||||
|
||||
namespace SWGSDRangel { |
||||
|
||||
class SWG_API SWGDVBDemodCarousel: public SWGObject { |
||||
public: |
||||
SWGDVBDemodCarousel(); |
||||
SWGDVBDemodCarousel(QString* json); |
||||
virtual ~SWGDVBDemodCarousel(); |
||||
void init(); |
||||
void cleanup(); |
||||
|
||||
virtual QString asJson () override; |
||||
virtual QJsonObject* asJsonObject() override; |
||||
virtual void fromJsonObject(QJsonObject &json) override; |
||||
virtual SWGDVBDemodCarousel* fromJson(QString &jsonString) override; |
||||
|
||||
qint32 getPid(); |
||||
void setPid(qint32 pid); |
||||
|
||||
qint32 getComponentTag(); |
||||
void setComponentTag(qint32 component_tag); |
||||
|
||||
qint64 getCarouselId(); |
||||
void setCarouselId(qint64 carousel_id); |
||||
|
||||
QString* getKind(); |
||||
void setKind(QString* kind); |
||||
|
||||
qint32 getReceived(); |
||||
void setReceived(qint32 received); |
||||
|
||||
qint32 getModules(); |
||||
void setModules(qint32 modules); |
||||
|
||||
qint32 getModulesComplete(); |
||||
void setModulesComplete(qint32 modules_complete); |
||||
|
||||
qint64 getBytes(); |
||||
void setBytes(qint64 bytes); |
||||
|
||||
qint64 getBytesComplete(); |
||||
void setBytesComplete(qint64 bytes_complete); |
||||
|
||||
qint32 getFiles(); |
||||
void setFiles(qint32 files); |
||||
|
||||
|
||||
virtual bool isSet() override; |
||||
|
||||
private: |
||||
qint32 pid; |
||||
bool m_pid_isSet; |
||||
|
||||
qint32 component_tag; |
||||
bool m_component_tag_isSet; |
||||
|
||||
qint64 carousel_id; |
||||
bool m_carousel_id_isSet; |
||||
|
||||
QString* kind; |
||||
bool m_kind_isSet; |
||||
|
||||
qint32 received; |
||||
bool m_received_isSet; |
||||
|
||||
qint32 modules; |
||||
bool m_modules_isSet; |
||||
|
||||
qint32 modules_complete; |
||||
bool m_modules_complete_isSet; |
||||
|
||||
qint64 bytes; |
||||
bool m_bytes_isSet; |
||||
|
||||
qint64 bytes_complete; |
||||
bool m_bytes_complete_isSet; |
||||
|
||||
qint32 files; |
||||
bool m_files_isSet; |
||||
|
||||
}; |
||||
|
||||
} |
||||
|
||||
#endif /* SWGDVBDemodCarousel_H_ */ |
||||
Loading…
Reference in new issue