Browse Source

Merge pull request #3016 from srcejon/dvb

DVB: Add HbbTV support
chirpmodem-v8.0.0
Edouard Griffiths 1 month ago committed by GitHub
parent
commit
c65650f754
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 67
      plugins/channelrx/demoddvb/CMakeLists.txt
  2. 60
      plugins/channelrx/demoddvb/dvbdemod.cpp
  3. 27
      plugins/channelrx/demoddvb/dvbdemod.h
  4. 1
      plugins/channelrx/demoddvb/dvbdemod.qrc
  5. 5
      plugins/channelrx/demoddvb/dvbdemodbaseband.h
  6. 12
      plugins/channelrx/demoddvb/dvbdemodepg.cpp
  7. 121
      plugins/channelrx/demoddvb/dvbdemodepg.h
  8. 538
      plugins/channelrx/demoddvb/dvbdemodgui.cpp
  9. 45
      plugins/channelrx/demoddvb/dvbdemodgui.h
  10. 29
      plugins/channelrx/demoddvb/dvbdemodgui.ui
  11. 1257
      plugins/channelrx/demoddvb/dvbdemodhbbtv.cpp
  12. 216
      plugins/channelrx/demoddvb/dvbdemodhbbtv.h
  13. 9
      plugins/channelrx/demoddvb/dvbdemodsettings.cpp
  14. 40
      plugins/channelrx/demoddvb/dvbdemodsettings.h
  15. 7
      plugins/channelrx/demoddvb/dvbdemodsink.cpp
  16. 21
      plugins/channelrx/demoddvb/dvbdemodsink.h
  17. 938
      plugins/channelrx/demoddvb/hbbtv/oipf.js
  18. 136
      plugins/channelrx/demoddvb/readme.md
  19. 20
      sdrbase/CMakeLists.txt
  20. 964
      sdrbase/dtv/dtvapps.cpp
  21. 181
      sdrbase/dtv/dtvapps.h
  22. 784
      sdrbase/dtv/dtvcarousel.cpp
  23. 150
      sdrbase/dtv/dtvcarousel.h
  24. 500
      sdrbase/dtv/dtvcarouselserver.cpp
  25. 98
      sdrbase/dtv/dtvcarouselserver.h
  26. 59
      sdrbase/dtv/dtvguide.cpp
  27. 215
      sdrbase/dtv/dtvguide.h
  28. 21
      sdrbase/dtv/dtvpsi.cpp
  29. 18
      sdrbase/dtv/dtvpsi.h
  30. 42
      sdrbase/dtv/dtvrecorder.cpp
  31. 28
      sdrbase/dtv/dtvrecorder.h
  32. 18
      sdrbase/dtv/dtvsections.cpp
  33. 18
      sdrbase/dtv/dtvsections.h
  34. 30
      sdrbase/dtv/dtvtsfifo.cpp
  35. 13
      sdrbase/dtv/dtvtsfifo.h
  36. 20
      sdrbase/dtv/dtvudp.cpp
  37. 13
      sdrbase/dtv/dtvudp.h
  38. 66
      sdrbase/resources/webapi/doc/swagger/include/DVBDemod.yaml
  39. 60
      sdrgui/CMakeLists.txt
  40. 331
      sdrgui/dtv/dtvappsdialog.cpp
  41. 67
      sdrgui/dtv/dtvappsdialog.h
  42. 136
      sdrgui/dtv/dtvepgdialog.cpp
  43. 33
      sdrgui/dtv/dtvepgdialog.h
  44. 66
      sdrgui/dtv/dtvepggrid.cpp
  45. 17
      sdrgui/dtv/dtvepggrid.h
  46. 233
      sdrgui/dtv/dtvguideoverlay.cpp
  47. 37
      sdrgui/dtv/dtvguideoverlay.h
  48. 50
      sdrgui/dtv/dtvscope.cpp
  49. 12
      sdrgui/dtv/dtvscope.h
  50. 240
      sdrgui/dtv/dtvstreamplayback.cpp
  51. 97
      sdrgui/dtv/dtvstreamplayback.h
  52. 289
      sdrgui/dtv/dtvstreamremuxer.cpp
  53. 74
      sdrgui/dtv/dtvstreamremuxer.h
  54. 574
      sdrgui/dtv/dtvvideoplayer.cpp
  55. 53
      sdrgui/dtv/dtvvideoplayer.h
  56. 5
      sdrgui/gui/glvideorenderer.cpp
  57. 3
      sdrgui/gui/glvideorenderer.h
  58. 15
      sdrgui/gui/glvideowidget.cpp
  59. 4
      sdrgui/gui/glvideowidget.h
  60. 66
      swagger/sdrangel/api/swagger/include/DVBDemod.yaml
  61. 233
      swagger/sdrangel/code/qt5/client/SWGDVBDemodApp.cpp
  62. 89
      swagger/sdrangel/code/qt5/client/SWGDVBDemodApp.h
  63. 317
      swagger/sdrangel/code/qt5/client/SWGDVBDemodCarousel.cpp
  64. 113
      swagger/sdrangel/code/qt5/client/SWGDVBDemodCarousel.h
  65. 138
      swagger/sdrangel/code/qt5/client/SWGDVBDemodReport.cpp
  66. 28
      swagger/sdrangel/code/qt5/client/SWGDVBDemodReport.h
  67. 590
      swagger/sdrangel/code/qt5/client/SWGDVBDemodSettings.cpp
  68. 150
      swagger/sdrangel/code/qt5/client/SWGDVBDemodSettings.h
  69. 12
      swagger/sdrangel/code/qt5/client/SWGModelFactory.h

67
plugins/channelrx/demoddvb/CMakeLists.txt

@ -6,15 +6,10 @@ set(demoddvb_SOURCES @@ -6,15 +6,10 @@ set(demoddvb_SOURCES
dvbdemodbaseband.cpp
dvbdemodsink.cpp
dvbdemodplugin.cpp
dvbdemodtsfifo.cpp
dvbdemodpsi.cpp
dvbdemodsections.cpp
dvbdemodfreesat.cpp
dvbdemodfreesattables.cpp
dvbdemodtext.cpp
dvbdemodepg.cpp
dvbdemodrecorder.cpp
dvbdemodudp.cpp
dvbdemodwebapiadapter.cpp
)
@ -24,14 +19,9 @@ set(demoddvb_HEADERS @@ -24,14 +19,9 @@ set(demoddvb_HEADERS
dvbdemodbaseband.h
dvbdemodsink.h
dvbdemodplugin.h
dvbdemodtsfifo.h
dvbdemodpsi.h
dvbdemodsections.h
dvbdemodfreesat.h
dvbdemodtext.h
dvbdemodepg.h
dvbdemodrecorder.h
dvbdemodudp.h
dvbdemodwebapiadapter.h
)
@ -41,53 +31,30 @@ include_directories( @@ -41,53 +31,30 @@ include_directories(
)
if(NOT SERVER_MODE)
# The service is decoded and displayed with FFmpeg. Without a GUI, the transport stream can be sent over UDP
# The service is decoded and displayed with FFmpeg, by sdrgui's DTVVideoPlayer. Without a GUI, the transport stream
# can be sent over UDP
set(demoddvb_SOURCES
${demoddvb_SOURCES}
dvbdemodgui.cpp
dvbdemodgui.ui
dvbdemodvideoplayer.cpp
dvbdemodscope.cpp
dvbdemodepgdialog.cpp
dvbdemodepggrid.cpp
dvbdemodguideoverlay.cpp
dvbdemod.qrc
)
set(demoddvb_HEADERS
${demoddvb_HEADERS}
dvbdemodgui.h
dvbdemodvideoplayer.h
dvbdemodscope.h
dvbdemodepgdialog.h
dvbdemodepggrid.h
dvbdemodguideoverlay.h
)
include_directories(
${AVCODEC_INCLUDE_DIRS}
${AVFORMAT_INCLUDE_DIRS}
${AVUTIL_INCLUDE_DIRS}
${SWSCALE_INCLUDE_DIRS}
${SWRESAMPLE_INCLUDE_DIRS}
)
set(TARGET_NAME ${PLUGINS_PREFIX}demoddvb)
set(TARGET_LIB Qt::Widgets)
# Deinterlacing uses libavfilter, if available
if(NOT AVFILTER_LIBRARIES)
find_library(DVBDEMOD_AVFILTER_LIBRARY NAMES avfilter)
find_path(DVBDEMOD_AVFILTER_INCLUDE_DIR libavfilter/avfilter.h HINTS ${AVCODEC_INCLUDE_DIRS})
if(DVBDEMOD_AVFILTER_LIBRARY AND DVBDEMOD_AVFILTER_INCLUDE_DIR)
set(AVFILTER_LIBRARIES ${DVBDEMOD_AVFILTER_LIBRARY})
set(AVFILTER_INCLUDE_DIRS ${DVBDEMOD_AVFILTER_INCLUDE_DIR})
endif()
endif()
if(AVFILTER_LIBRARIES)
include_directories(${AVFILTER_INCLUDE_DIRS})
add_definitions(-DDVBDEMOD_DEINTERLACE)
# HbbTV applications are run in Qt WebEngine's browser (Qt 5.15 or 6)
if(Qt${QT_DEFAULT_MAJOR_VERSION}WebEngineWidgets_FOUND AND Qt${QT_DEFAULT_MAJOR_VERSION}QuickWidgets_FOUND)
set(demoddvb_SOURCES ${demoddvb_SOURCES} dvbdemodhbbtv.cpp)
set(demoddvb_HEADERS ${demoddvb_HEADERS} dvbdemodhbbtv.h)
set(TARGET_LIB ${TARGET_LIB} Qt::WebEngineCore Qt::WebEngineWidgets Qt::QuickWidgets)
set(DEMODDVB_HBBTV ON)
else()
message(STATUS "demoddvb: libavfilter not found, so no deinterlacing")
message(STATUS "DVB demodulator: not running HbbTV applications (no Qt WebEngine)")
endif()
set(TARGET_NAME ${PLUGINS_PREFIX}demoddvb)
set(TARGET_LIB Qt::Widgets ${AVCODEC_LIBRARIES} ${AVFORMAT_LIBRARIES} ${AVUTIL_LIBRARIES} ${SWSCALE_LIBRARIES} ${SWRESAMPLE_LIBRARIES} ${AVFILTER_LIBRARIES})
set(TARGET_LIB_GUI "sdrgui")
set(INSTALL_FOLDER ${INSTALL_PLUGINS_DIR})
else()
@ -117,16 +84,8 @@ target_link_libraries(${TARGET_NAME} PRIVATE @@ -117,16 +84,8 @@ target_link_libraries(${TARGET_NAME} PRIVATE
modemdvb
)
if(WIN32)
target_link_libraries(${TARGET_NAME} PRIVATE winmm) # The video player sets the timer resolution
endif()
if(APPLE AND NOT SERVER_MODE)
target_link_libraries(${TARGET_NAME} PRIVATE "-framework CoreVideo") # VideoToolbox frames' IOSurfaces
endif()
if(DEFINED FFMPEG_DEPENDS)
add_dependencies(${TARGET_NAME} ${FFMPEG_DEPENDS})
if(DEMODDVB_HBBTV)
target_compile_definitions(${TARGET_NAME} PRIVATE DVBDEMOD_HBBTV)
endif()
install(TARGETS ${TARGET_NAME} DESTINATION ${INSTALL_FOLDER})

60
plugins/channelrx/demoddvb/dvbdemod.cpp

@ -33,6 +33,8 @@ @@ -33,6 +33,8 @@
#include "SWGChannelReport.h"
#include "SWGChannelActions.h"
#include "SWGDVBDemodActions.h"
#include "SWGDVBDemodApp.h"
#include "SWGDVBDemodCarousel.h"
#include "SWGDVBDemodEPGEvent.h"
#include "SWGDVBDemodEPGService.h"
@ -337,6 +339,7 @@ void DVBDemod::retuned() @@ -337,6 +339,7 @@ void DVBDemod::retuned()
{
m_playingServiceId = 0; // The player chooses again from the new multiplex's
getEPG()->retuned();
getApps()->reset();
m_sinceRetune.start();
m_retuneSettled = false;
}
@ -1142,7 +1145,7 @@ bool DVBDemod::startRecording(QString& error) @@ -1142,7 +1145,7 @@ bool DVBDemod::startRecording(QString& error)
const QString name = service ? serviceName(serviceId)
: QString("DVB %1 MHz").arg((m_centerFrequency + m_settings.m_inputFrequencyOffset) / 1e6, 0, 'f', 3);
const int id = m_basebandSink->startRecording(recordingFileName(name, t),
service ? DVBDemodRecorder::Service : DVBDemodRecorder::Multiplex, serviceId, error);
service ? DTVRecorder::Service : DTVRecorder::Multiplex, serviceId, error);
if (id < 0) {
return false;
@ -1449,6 +1452,9 @@ void DVBDemod::setSchedule(const QList<DVBDemodSettings::ScheduledRecording>& sc @@ -1449,6 +1452,9 @@ void DVBDemod::setSchedule(const QList<DVBDemodSettings::ScheduledRecording>& sc
// follow changes to the programmes' times in the guide. A recording that's missed is dropped
void DVBDemod::checkSchedule()
{
// The carousels of the service played (or that would be) are received
getApps()->setCarouselService(currentServiceId());
if (m_settings.m_scheduledRecordings.isEmpty() && m_scheduledRecordingIds.empty() && m_settings.m_seriesRecordings.isEmpty()
&& !m_recordingRetune.m_active) {
return;
@ -1526,7 +1532,7 @@ void DVBDemod::checkSchedule() @@ -1526,7 +1532,7 @@ void DVBDemod::checkSchedule()
{
QString error;
const int id = m_basebandSink->startRecording(recordingFileName(QString("%1 - %2").arg(r.m_serviceName).arg(r.m_title), r.m_start),
DVBDemodRecorder::Service, r.m_serviceId, error);
DTVRecorder::Service, r.m_serviceId, error);
if (id >= 0)
{
@ -2141,6 +2147,9 @@ void DVBDemod::webapiUpdateChannelSettings( @@ -2141,6 +2147,9 @@ void DVBDemod::webapiUpdateChannelSettings(
if (channelSettingsKeys.contains("deinterlace")) {
settings.m_deinterlace = swgSettings->getDeinterlace() != 0;
}
if (channelSettingsKeys.contains("hbbtv")) {
settings.m_hbbtv = swgSettings->getHbbtv() != 0;
}
if (channelSettingsKeys.contains("avOffset")) {
settings.m_avOffset = swgSettings->getAvOffset();
}
@ -2264,6 +2273,7 @@ void DVBDemod::webapiFormatChannelSettings(SWGSDRangel::SWGChannelSettings& resp @@ -2264,6 +2273,7 @@ void DVBDemod::webapiFormatChannelSettings(SWGSDRangel::SWGChannelSettings& resp
swgSettings->setVideoEnabled(settings.m_videoEnabled ? 1 : 0);
swgSettings->setServiceId(settings.m_serviceId);
swgSettings->setDeinterlace(settings.m_deinterlace ? 1 : 0);
swgSettings->setHbbtv(settings.m_hbbtv ? 1 : 0);
swgSettings->setAvOffset(settings.m_avOffset);
swgSettings->setHardwareDecoding(settings.m_hardwareDecoding ? 1 : 0);
setString(swgSettings->getAudioLanguage(), [=](QString *s) { swgSettings->setAudioLanguage(s); }, settings.m_audioLanguage);
@ -2371,6 +2381,48 @@ void DVBDemod::webapiFormatEPGReport(SWGSDRangel::SWGDVBDemodReport *report) @@ -2371,6 +2381,48 @@ void DVBDemod::webapiFormatEPGReport(SWGSDRangel::SWGDVBDemodReport *report)
}
}
// The interactive applications and carousels of the service the report's of
void DVBDemod::webapiFormatAppsReport(SWGSDRangel::SWGDVBDemodReport *report)
{
const int serviceId = currentServiceId();
const DTVApps *apps = getApps();
if (serviceId == 0) {
return;
}
const int transportStreamId = apps->getTransportStreamId();
const int networkId = apps->getOriginalNetworkId();
for (const DTVApps::App& app : apps->getApps(serviceId))
{
SWGSDRangel::SWGDVBDemodApp *swgApp = new SWGSDRangel::SWGDVBDemodApp();
swgApp->setApplicationId(new QString(app.idText()));
swgApp->setType(new QString(app.typeName()));
swgApp->setControlCode(new QString(app.controlCodeName()));
swgApp->setName(new QString(app.m_name));
swgApp->setUrl(new QString(app.url(networkId, transportStreamId)));
swgApp->setCarouselPid(app.m_carouselPid);
report->getInteractiveApps()->append(swgApp);
}
for (const DTVApps::Carousel& carousel : apps->getCarousels(serviceId))
{
SWGSDRangel::SWGDVBDemodCarousel *swgCarousel = new SWGSDRangel::SWGDVBDemodCarousel();
swgCarousel->setPid(carousel.m_pid);
swgCarousel->setComponentTag(carousel.m_componentTag);
swgCarousel->setCarouselId(carousel.m_carouselId);
swgCarousel->setKind(new QString(carousel.kindName()));
swgCarousel->setReceived(carousel.m_received ? 1 : 0);
swgCarousel->setModules(carousel.m_progress.m_modules);
swgCarousel->setModulesComplete(carousel.m_progress.m_modulesComplete);
swgCarousel->setBytes(carousel.m_progress.m_bytes);
swgCarousel->setBytesComplete(carousel.m_progress.m_bytesComplete);
swgCarousel->setFiles(carousel.m_files);
report->getCarousels()->append(swgCarousel);
}
}
// What service_type is, for the web API
QString DVBDemod::serviceKind(int type)
{
@ -2729,6 +2781,7 @@ void DVBDemod::webapiFormatChannelReport(SWGSDRangel::SWGChannelReport& response @@ -2729,6 +2781,7 @@ void DVBDemod::webapiFormatChannelReport(SWGSDRangel::SWGChannelReport& response
*report->getSearchText() = getSearchText();
report->setScanTransponders(getScanTransponders());
webapiFormatEPGReport(report);
webapiFormatAppsReport(report);
if (status.m_standard == S::StandardDVBT2)
{
@ -3034,6 +3087,9 @@ void DVBDemod::webapiFormatChannelSettings( @@ -3034,6 +3087,9 @@ void DVBDemod::webapiFormatChannelSettings(
if (channelSettingsKeys.contains("deinterlace") || force) {
swgSettings->setDeinterlace(settings.m_deinterlace ? 1 : 0);
}
if (channelSettingsKeys.contains("hbbtv") || force) {
swgSettings->setHbbtv(settings.m_hbbtv ? 1 : 0);
}
if (channelSettingsKeys.contains("avOffset") || force) {
swgSettings->setAvOffset(settings.m_avOffset);
}

27
plugins/channelrx/demoddvb/dvbdemod.h

@ -47,7 +47,7 @@ class DeviceAPI; @@ -47,7 +47,7 @@ class DeviceAPI;
class QNetworkAccessManager;
class QNetworkReply;
class DVBDemod : public BasebandSampleSink, public ChannelAPI {
class DVBDemod : public BasebandSampleSink, public ChannelAPI, public DTVRecordingSchedule {
public:
class MsgConfigureDVBDemod : public Message {
MESSAGE_CLASS_DECLARATION
@ -148,11 +148,13 @@ public: @@ -148,11 +148,13 @@ public:
SWGSDRangel::SWGChannelSettings& response);
void getStatus(DVBDemodSink::Status& status) { m_basebandSink->getStatus(status); }
DVBDemodTSFifo *getTSFifo() { return m_basebandSink->getTSFifo(); }
DTVTSFifo *getTSFifo() { return m_basebandSink->getTSFifo(); }
AudioFifo *getAudioFifo() { return m_basebandSink->getAudioFifo(); }
void getAudioOutput(int& sampleRate, double& latency) const { m_basebandSink->getAudioOutput(sampleRate, latency); }
//! The programme guide, from the transport stream, shared by every DVB demodulator through a cache file
DVBDemodEPG *getEPG() { return m_basebandSink->getEPG(); }
//! The services' interactive applications, and the carousels of the one played
DTVApps *getApps() { return m_basebandSink->getApps(); }
// Recording, to .ts files in the settings' directory. Manual recordings are of the multiplex or the service
// selected, as the settings say. Scheduled recordings are of programmes in the guide
@ -161,21 +163,21 @@ public: @@ -161,21 +163,21 @@ public:
bool isRecording() const { return m_manualRecording >= 0; }
std::vector<DVBDemodSink::Recording> getRecordings() { return m_basebandSink->getRecordings(); }
//! A programme from the guide to record. False if it's already scheduled
bool scheduleRecording(int networkId, int serviceId, int eventId);
void cancelScheduledRecording(int networkId, int serviceId, int eventId);
bool isScheduled(int networkId, int serviceId, int eventId) const;
QList<DVBDemodSettings::ScheduledRecording> getScheduledRecordings() const { return m_settings.m_scheduledRecordings; }
bool scheduleRecording(int networkId, int serviceId, int eventId) override;
void cancelScheduledRecording(int networkId, int serviceId, int eventId) override;
bool isScheduled(int networkId, int serviceId, int eventId) const override;
QList<DTVScheduledRecording> getScheduledRecordings() const override { return m_settings.m_scheduledRecordings; }
//! 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, or it's recorded already
bool scheduleSeries(int networkId, int serviceId, int eventId);
bool scheduleSeries(int networkId, int serviceId, int eventId) override;
//! Stop recording a programme's series (the programmes scheduled from it stay scheduled)
void cancelSeries(int networkId, int serviceId, int eventId);
void cancelSeries(int networkId, int serviceId, const QString& seriesCrid);
void cancelSeries(int networkId, int serviceId, int eventId) override;
void cancelSeries(int networkId, int serviceId, const QString& seriesCrid) override;
//! Scheduled recordings may retune to their service's multiplex
bool recordRetune() const { return m_settings.m_recordRetune; }
bool recordRetune() const override { return m_settings.m_recordRetune; }
//! The programme's series is being recorded
bool isSeriesScheduled(int networkId, int serviceId, int eventId) const;
QList<DVBDemodSettings::SeriesRecording> getSeriesRecordings() const { return m_settings.m_seriesRecordings; }
bool isSeriesScheduled(int networkId, int serviceId, int eventId) const override;
QList<DTVSeriesRecording> getSeriesRecordings() const override { return m_settings.m_seriesRecordings; }
//! The service selected, or if automatic, the one the player's playing (it chose it), else (no player, as headless)
//! the first TV service of the multiplex by channel number. 0 if none known. Recording and the reports take this,
//! so they're of what's watched
@ -430,6 +432,7 @@ private: @@ -430,6 +432,7 @@ private:
void webapiFormatSatelliteReport(const DVBDemodSink::Status& status, SWGSDRangel::SWGDVBDemodReport *report);
void webapiFormatEPGReport(SWGSDRangel::SWGDVBDemodReport *report);
void webapiFormatEPGLists(SWGSDRangel::SWGDVBDemodReport *report, std::vector<DVBDemodEPG::Service> services, int serviceId);
void webapiFormatAppsReport(SWGSDRangel::SWGDVBDemodReport *report);
void webapiReverseSendSettings(const QList<QString>& channelSettingsKeys, const DVBDemodSettings& settings, bool force);
void webapiFormatChannelSettings(
const QList<QString>& channelSettingsKeys,

1
plugins/channelrx/demoddvb/dvbdemod.qrc

@ -3,5 +3,6 @@ @@ -3,5 +3,6 @@
<file>images/angeltv.png</file>
<file>icons/deinterlace.png</file>
<file>icons/gpu.png</file>
<file>hbbtv/oipf.js</file>
</qresource>
</RCC>

5
plugins/channelrx/demoddvb/dvbdemodbaseband.h

@ -112,7 +112,7 @@ public: @@ -112,7 +112,7 @@ public:
void reapplyRateSearchBand();
int getChannelSampleRate() const;
void getStatus(DVBDemodSink::Status& status) { m_sink.getStatus(status); }
DVBDemodTSFifo *getTSFifo() { return m_sink.getTSFifo(); }
DTVTSFifo *getTSFifo() { return m_sink.getTSFifo(); }
AudioFifo *getAudioFifo() { return m_sink.getAudioFifo(); }
bool isRunning() const { return m_running; }
void setFifoLabel(const QString& label) { m_sampleFifo.setLabel(label); }
@ -120,7 +120,8 @@ public: @@ -120,7 +120,8 @@ public:
//! The audio output's sample rate, and how long it buffers audio
void getAudioOutput(int& sampleRate, double& latency) const;
DVBDemodEPG *getEPG() { return m_sink.getEPG(); }
int startRecording(const QString& fileName, DVBDemodRecorder::Mode mode, int serviceId, QString& error) {
DTVApps *getApps() { return m_sink.getApps(); }
int startRecording(const QString& fileName, DTVRecorder::Mode mode, int serviceId, QString& error) {
return m_sink.startRecording(fileName, mode, serviceId, error);
}
void stopRecording(int id) { m_sink.stopRecording(id); }

12
plugins/channelrx/demoddvb/dvbdemodepg.cpp

@ -171,7 +171,7 @@ void DVBDemodEPG::feed(const uint8_t *p) @@ -171,7 +171,7 @@ void DVBDemodEPG::feed(const uint8_t *p)
}
const int pid = ((p[1] & 0x1F) << 8) | p[2];
DVBDemodSectionAssembler *assembler;
DTVSectionAssembler *assembler;
switch (pid)
{
@ -2069,10 +2069,6 @@ QString DVBDemodEPG::defaultCacheFileName() @@ -2069,10 +2069,6 @@ QString DVBDemodEPG::defaultCacheFileName()
// Content level 1: EN 300 468 table 29, or the UK D-Book's
QString DVBDemodEPG::genreText(int genre, int networkId)
{
static const char *const names[16] = {
"", "Film/Drama", "News/Current affairs", "Entertainment", "Sport", "Children's", "Music", "Arts/Culture",
"Social/Political", "Education/Factual", "Leisure/Hobbies", "", "", "", "", ""
};
static const char *const ukNames[16] = {
"", "Film", "News and Factual", "Entertainment", "Sport", "Children's", "Education", "Lifestyle",
"Drama", "", "", "", "", "", "", ""
@ -2082,5 +2078,9 @@ QString DVBDemodEPG::genreText(int genre, int networkId) @@ -2082,5 +2078,9 @@ QString DVBDemodEPG::genreText(int genre, int networkId)
return QString();
}
return QString((networkId == 0x233A ? ukNames : names)[(genre >> 4) & 0x0F]);
if (networkId != 0x233A) {
return DTVGuide::genreText(genre);
}
return QString(ukNames[(genre >> 4) & 0x0F]);
}

121
plugins/channelrx/demoddvb/dvbdemodepg.h

@ -29,101 +29,29 @@ @@ -29,101 +29,29 @@
#include <QMutex>
#include <QString>
#include "dvbdemodsections.h"
#include "dtv/dtvguide.h"
#include "dtv/dtvsections.h"
// Electronic programme guide, from the service information in the transport stream (EN 300 468): the Event
// Information Tables (now and next, and schedules of up to 8 days) of the services of this and other transport
// streams of the network, their names from the SDTs, logical channel numbers from the NITs, and the time from the
// TDT. Fed with every packet of the transport stream, in the demodulator's thread, and read from others
class DVBDemodEPG
// TDT: the guide (DTVGuide) for DVB. Fed with every packet of the transport stream, in the demodulator's thread, and read from others
class DVBDemodEPG : public 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
int m_genre = -1; //!< Content nibbles (level 1 * 16 + level 2, EN 300 468 table 29), -1 if none
int m_minimumAge = 0; //!< From the parental rating, 0 if none
bool m_hd = false;
bool m_subtitles = false;
bool m_audioDescription = false;
QString m_guidance; //!< UK, as "Contains strong language"
//! 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 the 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 Service
{
int m_networkId = 0; //!< original_network_id
int m_transportStreamId = -1;
int m_serviceId = 0;
QString m_name;
QString m_provider;
int m_type = 0; //!< service_type: 1 TV, 2 radio, 0x16 to 0x19 HD TV, 0x0C data...
int m_channel = -1; //!< Logical 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, from the NIT, 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;
};
//! A multiplex of the network, from the NIT's delivery system descriptors
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
};
DVBDemodEPG();
void clear();
//! A 188-byte transport stream packet
void feed(const uint8_t *packet);
//! UTC, seconds since 1970, from the TDT and the time since it was received. 0 until received
qint64 getTime() const;
int getTransportStreamId() const;
int getNetworkId() const; //!< original_network_id of the transport stream being received, -1 if not known
qint64 getTime() const override;
int getTransportStreamId() const override;
int getNetworkId() const override; //!< original_network_id of the transport stream being received, -1 if not known
//! The services: one for each service id and name of a network (the UK carries a service in every region's
//! transport stream), that of the transport stream received, else one whose multiplex is known, else that with the
//! most programmes. Services with the same ids but other names are each listed
std::vector<Service> getServices() const;
std::vector<Service> getServices() const override;
std::vector<TransportStream> getTransportStreams() const;
//! False if its frequency isn't known
bool getTransportStream(int networkId, int transportStreamId, TransportStream& transportStream) const;
@ -140,31 +68,31 @@ public: @@ -140,31 +68,31 @@ public:
//! The same programme as a service's on now on another service, as in HD, from the event linkage of its event
//! (the present event, or the schedule's at the time; just the present one, if the time isn't known). False if
//! none, or it isn't in this area
bool getSimulcast(int networkId, int serviceId, Service& simulcast) const;
bool getSimulcast(int networkId, int serviceId, Service& simulcast) const override;
//! A service, as getServices() gives it (or removed). False if not in the guide. A service id can be used in more
//! than one transport stream of a network: these, given only the network's and service's ids, take the
//! transport stream being received's, else one with a name, else any
bool getService(int networkId, int serviceId, Service& service) const;
bool getService(int networkId, int serviceId, Service& service) const override;
//! A programme of a service's schedule, by its id. False if not in the guide
bool getEvent(int networkId, int serviceId, int eventId, Event& event) const;
bool getEvent(int networkId, int serviceId, int eventId, Event& event) const override;
//! The running status of a service's programme, if it's the present or following event of the service's
//! transport stream being received (whose table's kept up to date): 0 to 4 (as Event's), -1 if not known
int getRunningStatus(int networkId, int serviceId, int eventId) const;
//! Changes whenever what the guide gives does (its services, events, multiplexes, or the one received), so views
//! can skip rebuilding what hasn't changed
quint64 getRevision() const { return m_revision; }
quint64 getRevision() const override { return m_revision; }
//! Of a service in the transport stream being received (or the first with the id, if not known yet)
bool getNowNext(int serviceId, Event& now, Event& next) const;
bool getNowNext(int serviceId, Event& now, Event& next) const override;
//! Of any service in the guide
bool getNowNext(int networkId, int serviceId, Event& now, Event& next) const;
bool getNowNext(int networkId, int serviceId, Event& now, Event& next) const override;
//! A service's schedule, in order, from the TDT time less an hour (or all, if no time)
std::vector<Event> getEvents(int networkId, int serviceId) const;
std::vector<Event> getEvents(int networkId, int serviceId) const override;
//! The same for many services (network and service ids) at once, in their order
std::vector<std::vector<Event>> getEvents(const std::vector<std::pair<int, int>>& services) const;
std::vector<std::vector<Event>> getEvents(const std::vector<std::pair<int, int>>& services) const override;
//! 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
std::vector<quint64> getServiceRevisions(const std::vector<std::pair<int, int>>& services) const;
int getEventCount() const;
std::vector<quint64> getServiceRevisions(const std::vector<std::pair<int, int>>& services) const override;
int getEventCount() const override;
bool isModified() const; //!< Since the last save or load
//! Cache, so the guide is complete straight away. Events that ended over an hour before now (UTC, seconds since
@ -181,6 +109,7 @@ public: @@ -181,6 +109,7 @@ public:
//! The UK (original_network_id 0x233A) uses the D-Book's names, which differ from EN 300 468's from 6
static QString genreText(int genre, int networkId);
QString genreName(int genre, int networkId) const override { return genreText(genre, networkId); }
static QString defaultCacheFileName();
private:
@ -300,12 +229,12 @@ private: @@ -300,12 +229,12 @@ private:
qint64 timeLocked() const;
bool newVersion(uint64_t sectionKey, int version);
DVBDemodSectionAssembler m_nitSections;
DVBDemodSectionAssembler m_sdtSections;
DVBDemodSectionAssembler m_eitSections;
DVBDemodSectionAssembler m_timeSections;
DVBDemodSectionAssembler m_freesatSiSections[2]; //!< SDT and BAT, on the home transponder's PID, or others'
DVBDemodSectionAssembler m_freesatEitSections[2]; //!< The whole network's EIT, the same
DTVSectionAssembler m_nitSections;
DTVSectionAssembler m_sdtSections;
DTVSectionAssembler m_eitSections;
DTVSectionAssembler m_timeSections;
DTVSectionAssembler m_freesatSiSections[2]; //!< SDT and BAT, on the home transponder's PID, or others'
DTVSectionAssembler m_freesatEitSections[2]; //!< The whole network's EIT, the same
struct FreesatChannel
{

538
plugins/channelrx/demoddvb/dvbdemodgui.cpp

@ -62,6 +62,11 @@ @@ -62,6 +62,11 @@
#include "gui/buttonswitch.h"
#include "gui/glvideowidget.h"
#include "dvbdemodgui.h"
#ifdef DVBDEMOD_HBBTV
#include <QJsonObject>
#include "dtv/dtvstreamplayback.h"
#include "dvbdemodhbbtv.h"
#endif
#ifdef _WIN32
#ifndef NOMINMAX
@ -356,9 +361,14 @@ void DVBDemodGUI::on_videoEnabled_toggled(bool checked) @@ -356,9 +361,14 @@ void DVBDemodGUI::on_videoEnabled_toggled(bool checked)
m_settings.m_videoEnabled = checked;
applySetting("videoEnabled");
if (checked) {
if (checked)
{
startPlayer();
} else {
}
else
{
m_streamPlaying = false; // An application's media, and the broadcast, stopped
stopStreamPlayback();
stopPlayer();
}
}
@ -534,7 +544,7 @@ void DVBDemodGUI::displayRecordings() @@ -534,7 +544,7 @@ void DVBDemodGUI::displayRecordings()
for (const auto& recording : recordings)
{
const DVBDemodRecorder::Status& s = recording.m_status;
const DTVRecorder::Status& s = recording.m_status;
bytes += s.m_bytes;
seconds = std::max(seconds, s.m_seconds);
QString line = QString("%1 (%2 MB)").arg(s.m_fileName).arg(s.m_bytes / 1e6, 0, 'f', 1);
@ -678,9 +688,9 @@ void DVBDemodGUI::on_epg_clicked() @@ -678,9 +688,9 @@ void DVBDemodGUI::on_epg_clicked()
{
if (!m_epgDialog)
{
m_epgDialog = new DVBDemodEPGDialog(m_dvbDemod, this);
m_epgDialog = new DTVEPGDialog(m_dvbDemod->getEPG(), m_dvbDemod, this);
m_epgDialog->setAttribute(Qt::WA_DeleteOnClose);
connect(m_epgDialog, &DVBDemodEPGDialog::serviceSelected, this, &DVBDemodGUI::epgServiceSelected);
connect(m_epgDialog, &DTVEPGDialog::serviceSelected, this, &DVBDemodGUI::epgServiceSelected);
}
m_epgDialog->setCurrentService(m_playingService != 0 ? m_playingService : m_settings.m_serviceId);
@ -689,10 +699,384 @@ void DVBDemodGUI::on_epg_clicked() @@ -689,10 +699,384 @@ void DVBDemodGUI::on_epg_clicked()
m_epgDialog->activateWindow();
}
void DVBDemodGUI::on_apps_clicked()
{
if (!m_appsDialog)
{
m_appsDialog = new DTVAppsDialog(m_dvbDemod->getApps(), this);
m_appsDialog->setAttribute(Qt::WA_DeleteOnClose);
}
updateAppsDialog();
m_appsDialog->show();
m_appsDialog->raise();
m_appsDialog->activateWindow();
}
// Whether the service's HbbTV applications are run (over the video)
void DVBDemodGUI::appsMenu(const QPoint& position)
{
QMenu menu(this);
menu.setToolTipsVisible(true);
QAction *run = menu.addAction("Run HbbTV applications (red button)");
run->setCheckable(true);
run->setChecked(m_settings.m_hbbtv);
run->setToolTip("Run the AUTOSTART application of the service played, and those it starts (as when the red button's pressed): from its "
"carousels or the internet. The coloured buttons are R, G, Y and B (or F1 to F4), and Back is Backspace");
#ifndef DVBDEMOD_HBBTV
run->setEnabled(false);
run->setToolTip("Not built: Qt WebEngine is needed");
#endif
QAction *clear = menu.addAction("Forget HbbTV sign-ins (cookies and cache)");
clear->setToolTip("Applications' cookies (as iPlayer's sign-in) and cache are kept from one run to the next: forget them");
#ifndef DVBDEMOD_HBBTV
clear->setEnabled(false);
#endif
QAction *chosen = menu.exec(ui->apps->mapToGlobal(position));
if (chosen == run)
{
m_settings.m_hbbtv = run->isChecked();
applySetting("hbbtv");
updateHbbTV();
}
#ifdef DVBDEMOD_HBBTV
else if (chosen == clear)
{
DVBDemodHbbTV::clearData();
}
#endif
}
void DVBDemodGUI::updateHbbTV()
{
#ifdef DVBDEMOD_HBBTV
const bool run = m_settings.m_hbbtv && (m_player || m_streamPlaying);
if (run && !m_hbbtv)
{
m_hbbtv = new DVBDemodHbbTV(m_dvbDemod->getApps(), this);
m_hbbtv->createView(m_videoScreen.load());
connect(m_hbbtv, &DVBDemodHbbTV::videoAreaChanged, this, &DVBDemodGUI::hbbtvVideoArea);
connect(m_hbbtv, &DVBDemodHbbTV::channelChangeRequested, this, &DVBDemodGUI::hbbtvChannelChange);
connect(m_hbbtv, &DVBDemodHbbTV::mediaRequest, this, &DVBDemodGUI::hbbtvMedia);
connect(m_hbbtv, &DVBDemodHbbTV::channelStepRequested, this, [this](int direction) {
QKeyEvent key(QEvent::KeyPress, direction > 0 ? Qt::Key_ChannelUp : Qt::Key_ChannelDown, Qt::NoModifier);
m_guideOverlay->handleKey(&key);
});
connect(m_hbbtv, &DVBDemodHbbTV::log, this, [](const QString& message) {
qDebug("DVBDemodGUI: HbbTV: %s", qPrintable(message));
});
qDebug("DVBDemodGUI: HbbTV: user agent %s", qPrintable(m_hbbtv->getUserAgent()));
m_hbbtvServiceState.clear();
updateHbbTVGeometry();
updateHbbTVService();
}
else if (!run && m_hbbtv)
{
delete m_hbbtv;
m_hbbtv = nullptr;
hbbtvVideoArea(QRectF());
m_hbbtvChannelRequest = 0;
stopStreamPlayback();
}
#endif
}
// The service played, the multiplex's others, and what's on: given to the application when they change
void DVBDemodGUI::updateHbbTVService()
{
#ifdef DVBDEMOD_HBBTV
if (!m_hbbtv) {
return;
}
const int serviceId = m_playingService != 0 ? m_playingService : m_dvbDemod->currentServiceId();
DVBDemodHbbTV::Channel channel;
std::vector<DVBDemodHbbTV::Channel> channels;
std::vector<DVBDemodHbbTV::Programme> programmes;
QString state = QString::number(serviceId);
for (const DVBDemodEPG::Service& service : m_dvbDemod->getEPG()->getServices())
{
if (!service.m_actual) {
continue;
}
DVBDemodHbbTV::Channel c;
c.m_networkId = service.m_networkId;
c.m_transportStreamId = service.m_transportStreamId;
c.m_serviceId = service.m_serviceId;
c.m_lcn = service.m_channel;
c.m_name = service.m_name;
c.m_radio = (service.m_type == 0x02) || (service.m_type == 0x07) || (service.m_type == 0x0A);
c.m_hd = (service.m_type == 0x11) || ((service.m_type >= 0x19) && (service.m_type <= 0x1F));
channels.push_back(c);
state += QString(";%1.%2.%3:%4:%5").arg(c.m_networkId).arg(c.m_transportStreamId).arg(c.m_serviceId).arg(c.m_lcn).arg(c.m_name);
if (c.m_serviceId == serviceId) {
channel = c;
}
}
// Before the guide has the service, it's known by its id, of the multiplex received
if ((channel.m_serviceId == 0) && (serviceId != 0)) {
channel.m_serviceId = serviceId;
}
DVBDemodEPG::Event now, next;
if ((serviceId != 0) && m_dvbDemod->getEPG()->getNowNext(serviceId, now, next))
{
for (const DVBDemodEPG::Event& event : {now, next})
{
if (event.isValid())
{
programmes.push_back(DVBDemodHbbTV::Programme{event.m_eventId, event.m_title, event.m_text, event.m_start, event.m_duration});
state += QString(";%1").arg(event.m_eventId);
}
}
}
if (state == m_hbbtvServiceState) {
return;
}
m_hbbtvServiceState = state;
const int standard = m_settings.m_standard;
m_hbbtv->setIdType(standard == DVBDemodSettings::StandardDVBS ? 11 : standard == DVBDemodSettings::StandardDVBS2 ? 15 : standard == DVBDemodSettings::StandardAutoSatellite ? 15
: (standard == DVBDemodSettings::StandardDVBT2) || (standard == DVBDemodSettings::StandardDVBT2Lite) ? 16 : 12);
m_hbbtv->setService(channel, channels, programmes);
#endif
}
// Applications are laid out for a 16:9 page, of 1280 by 720 pixels: the largest that fits on the screen, centred, as
// the picture is
QRect DVBDemodGUI::hbbtvPageRect(const QWidget *screen) const
{
const int width = screen->width();
const int height = screen->height();
int w = width, h = (width * 9) / 16;
if (h > height)
{
h = height;
w = (height * 16) / 9;
}
return QRect((width - w) / 2, (height - h) / 2, w, h);
}
void DVBDemodGUI::updateHbbTVGeometry()
{
#ifdef DVBDEMOD_HBBTV
if (!m_hbbtv) {
return;
}
GLVideoWidget *screen = m_videoScreen.load();
m_hbbtv->setViewParent(screen);
m_hbbtv->setViewGeometry(hbbtvPageRect(screen));
hbbtvVideoArea(m_hbbtvVideoArea);
#endif
}
// The video in the application's window: its area of the page, as an area of the screen
void DVBDemodGUI::hbbtvVideoArea(const QRectF& area)
{
m_hbbtvVideoArea = area;
GLVideoWidget *screen = m_videoScreen.load();
GLVideoWidget *other = screen == ui->screenTV ? m_fullScreenTV : ui->screenTV;
if (other) {
other->setVideoArea(QRectF());
}
if (area.isNull() || (screen->width() <= 0) || (screen->height() <= 0))
{
screen->setVideoArea(QRectF());
return;
}
const QRect page = hbbtvPageRect(screen);
screen->setVideoArea(QRectF((page.x() + area.x() * page.width()) / screen->width(), (page.y() + area.y() * page.height()) / screen->height(),
area.width() * page.width() / screen->width(), area.height() * page.height() / screen->height()));
}
// The application's video/broadcast setChannel(): a service of this multiplex, or another the guide knows of
void DVBDemodGUI::hbbtvChannelChange(int networkId, int transportStreamId, int serviceId)
{
#ifdef DVBDEMOD_HBBTV
(void) transportStreamId;
if (serviceId == m_playingService)
{
m_hbbtv->channelChangeResult(true);
return;
}
m_hbbtvChannelRequest = serviceId;
selectService(networkId, serviceId, this, [this](const QString& error) {
qDebug("DVBDemodGUI::hbbtvChannelChange: %s", qPrintable(error));
m_hbbtvChannelRequest = 0;
if (m_hbbtv) {
m_hbbtv->channelChangeResult(false);
}
});
#else
(void) networkId;
(void) transportStreamId;
(void) serviceId;
#endif
}
// The red button: given to the application, or the service's started again for it. The video gets the keys after
void DVBDemodGUI::hbbtvRed()
{
#ifdef DVBDEMOD_HBBTV
if (m_hbbtv)
{
m_hbbtv->pressRed();
m_hbbtv->takeFocus();
}
#endif
}
// Red buttons, on the ribbon, guide and here, while the service played has an HbbTV application to run
void DVBDemodGUI::displayRedButton()
{
bool shown = false;
#ifdef DVBDEMOD_HBBTV
shown = m_hbbtv && m_hbbtv->hasAutostartApp();
#endif
m_guideOverlay->setRedButton(shown);
ui->redButton->setVisible(shown);
}
// The application's media, as iPlayer's: played by a player of its own, in place of the broadcast's (stopped while
// it plays, and started again after), in the application's video window
void DVBDemodGUI::hbbtvMedia(const QString& command, int id, const QString& url, const QMap<QString, QString>& options, double position)
{
#ifdef DVBDEMOD_HBBTV
if (command == "load")
{
if (!m_streamPlayback)
{
m_streamPlayback = new DTVStreamPlayback(m_dvbDemod->getAudioFifo(),
[this](GLVideoFramePtr frame) { m_videoScreen.load()->setFrame(frame); },
[this](int type) { return m_videoScreen.load()->canShow((GLVideoFrame::Type) type); },
[this](DTVVideoPlayer *player) {
player->setAudioMute(m_settings.m_audioMute);
player->setAudioVolume(m_settings.m_audioVolume);
player->setDeinterlace(m_settings.m_deinterlace);
player->setHardwareDecoding(m_settings.m_hardwareDecoding);
player->setAVOffset(m_settings.m_avOffset);
},
this);
connect(m_streamPlayback, &DTVStreamPlayback::metadata, this, [this](double duration, int width, int height) {
if (m_hbbtv)
{
QJsonObject data;
data.insert("duration", std::isfinite(duration) ? QJsonValue(duration) : QJsonValue());
data.insert("width", width);
data.insert("height", height);
m_hbbtv->mediaEvent(m_mediaId, "metadata", data);
}
});
connect(m_streamPlayback, &DTVStreamPlayback::playing, this, [this]() {
if (m_hbbtv) {
m_hbbtv->mediaEvent(m_mediaId, "playing");
}
});
connect(m_streamPlayback, &DTVStreamPlayback::ended, this, [this]() {
if (m_hbbtv) {
m_hbbtv->mediaEvent(m_mediaId, "ended");
}
});
connect(m_streamPlayback, &DTVStreamPlayback::error, this, [this](const QString& message) {
qDebug("DVBDemodGUI: HbbTV: media error: %s", qPrintable(message));
if (m_hbbtv)
{
QJsonObject data;
data.insert("code", 2); // MEDIA_ERR_NETWORK
data.insert("message", message);
m_hbbtv->mediaEvent(m_mediaId, "error", data);
}
});
}
m_mediaId = id;
if (!m_streamPlaying)
{
m_streamPlaying = true;
stopPlayer();
showVideoMessage("");
}
m_streamPlayback->load(url, options);
}
else if (m_streamPlayback && (id == m_mediaId))
{
if (command == "play") {
m_streamPlayback->play();
} else if (command == "pause") {
m_streamPlayback->pause();
} else if (command == "seek") {
m_streamPlayback->seek(position);
} else if (command == "stop") {
stopStreamPlayback();
}
}
#else
(void) command;
(void) id;
(void) url;
(void) options;
(void) position;
#endif
}
void DVBDemodGUI::stopStreamPlayback()
{
#ifdef DVBDEMOD_HBBTV
if (m_streamPlayback) {
m_streamPlayback->stop();
}
m_mediaId = 0;
if (m_streamPlaying)
{
m_streamPlaying = false;
m_videoScreen.load()->clear();
if (m_settings.m_videoEnabled) {
startPlayer();
}
}
#endif
}
// The applications dialog shows the service whose carousels are received: the one played
void DVBDemodGUI::updateAppsDialog()
{
if (!m_appsDialog) {
return;
}
const int serviceId = m_playingService != 0 ? m_playingService : m_dvbDemod->currentServiceId();
const int index = ui->service->findData(serviceId);
m_appsDialog->setService(serviceId, (serviceId != 0) && (index >= 0) ? ui->service->itemText(index) : QString());
}
// Play a service chosen in the programme guide, retuning to its multiplex if it's on another
void DVBDemodGUI::epgServiceSelected(int networkId, int serviceId)
{
QPointer<DVBDemodEPGDialog> dialog = m_epgDialog;
QPointer<DTVEPGDialog> dialog = m_epgDialog;
selectService(networkId, serviceId, m_epgDialog, [this, dialog](const QString& error) {
QMessageBox::warning(dialog ? (QWidget *) dialog : (QWidget *) this, "Programme guide", QString("Can't play the service: %1").arg(error));
@ -1047,7 +1431,7 @@ QString DVBDemodGUI::languageName(const QString& code) @@ -1047,7 +1431,7 @@ QString DVBDemodGUI::languageName(const QString& code)
// language and kind (main or clean audio, audio description and its mix, normal or hard of hearing subtitles) and
// whether to show subtitles, which the player applies to later services too (the language alone where the kind's not
// there)
void DVBDemodGUI::tracksChanged(const DVBDemodVideoPlayer::Tracks& tracks)
void DVBDemodGUI::tracksChanged(const DTVVideoPlayer::Tracks& tracks)
{
if (!fromPlayer()) {
return;
@ -1062,7 +1446,7 @@ void DVBDemodGUI::tracksChanged(const DVBDemodVideoPlayer::Tracks& tracks) @@ -1062,7 +1446,7 @@ void DVBDemodGUI::tracksChanged(const DVBDemodVideoPlayer::Tracks& tracks)
for (const auto& track : tracks.m_audio)
{
if ((track.m_pid == tracks.m_audioPid) && (track.m_type == DVBDemodVideoPlayer::Track::AudioDescriptionMixed)) {
if ((track.m_pid == tracks.m_audioPid) && (track.m_type == DTVVideoPlayer::Track::AudioDescriptionMixed)) {
playingDescription = true;
}
}
@ -1075,15 +1459,15 @@ void DVBDemodGUI::tracksChanged(const DVBDemodVideoPlayer::Tracks& tracks) @@ -1075,15 +1459,15 @@ void DVBDemodGUI::tracksChanged(const DVBDemodVideoPlayer::Tracks& tracks)
switch (track.m_type)
{
case DVBDemodVideoPlayer::Track::AudioDescription:
case DTVVideoPlayer::Track::AudioDescription:
text = name + " + audio description";
description = true;
break;
case DVBDemodVideoPlayer::Track::AudioDescriptionMixed:
case DTVVideoPlayer::Track::AudioDescriptionMixed:
text = name + " (audio description)";
description = true;
break;
case DVBDemodVideoPlayer::Track::CleanAudio:
case DTVVideoPlayer::Track::CleanAudio:
text = name + " (clean audio)";
break;
default:
@ -1116,7 +1500,7 @@ void DVBDemodGUI::tracksChanged(const DVBDemodVideoPlayer::Tracks& tracks) @@ -1116,7 +1500,7 @@ void DVBDemodGUI::tracksChanged(const DVBDemodVideoPlayer::Tracks& tracks)
{
QString text = "Subtitles: " + languageName(track.m_language);
if (track.m_type == DVBDemodVideoPlayer::Track::SubtitlesHardOfHearing) {
if (track.m_type == DTVVideoPlayer::Track::SubtitlesHardOfHearing) {
text += " (hard of hearing)";
}
@ -1149,7 +1533,7 @@ void DVBDemodGUI::setTrackPreferences() @@ -1149,7 +1533,7 @@ void DVBDemodGUI::setTrackPreferences()
{
if (m_player)
{
typedef DVBDemodVideoPlayer::Track Track;
typedef DTVVideoPlayer::Track Track;
const Track::Type audioType = m_settings.m_audioDescription
? (m_settings.m_audioDescriptionMixed ? Track::AudioDescriptionMixed : Track::AudioDescription)
: m_settings.m_cleanAudio ? Track::CleanAudio : Track::Main;
@ -1165,7 +1549,7 @@ void DVBDemodGUI::on_audioTrack_currentIndexChanged(int index) @@ -1165,7 +1549,7 @@ void DVBDemodGUI::on_audioTrack_currentIndexChanged(int index)
return;
}
typedef DVBDemodVideoPlayer::Track Track;
typedef DTVVideoPlayer::Track Track;
const int type = ui->audioTrack->itemData(index, Qt::UserRole + 2).toInt();
m_settings.m_audioLanguage = ui->audioTrack->itemData(index, Qt::UserRole).toString();
m_settings.m_audioDescription = ui->audioTrack->itemData(index, Qt::UserRole + 1).toBool();
@ -1187,7 +1571,7 @@ void DVBDemodGUI::on_subtitleTrack_currentIndexChanged(int index) @@ -1187,7 +1571,7 @@ void DVBDemodGUI::on_subtitleTrack_currentIndexChanged(int index)
{
m_settings.m_subtitleLanguage = ui->subtitleTrack->itemData(index, Qt::UserRole).toString();
m_settings.m_subtitlesHardOfHearing = ui->subtitleTrack->itemData(index, Qt::UserRole + 2).toInt()
== DVBDemodVideoPlayer::Track::SubtitlesHardOfHearing;
== DTVVideoPlayer::Track::SubtitlesHardOfHearing;
}
setTrackPreferences();
@ -1248,7 +1632,7 @@ bool DVBDemodGUI::fromPlayer() const @@ -1248,7 +1632,7 @@ bool DVBDemodGUI::fromPlayer() const
return m_player && (sender() == m_player);
}
void DVBDemodGUI::servicesChanged(const QList<DVBDemodVideoPlayer::Service>& services)
void DVBDemodGUI::servicesChanged(const QList<DTVVideoPlayer::Service>& services)
{
if (!fromPlayer()) {
return;
@ -1364,6 +1748,16 @@ void DVBDemodGUI::serviceSelected(int id, bool hasVideo, bool hasAudio) @@ -1364,6 +1748,16 @@ void DVBDemodGUI::serviceSelected(int id, bool hasVideo, bool hasAudio)
m_serviceHasAudio = hasAudio;
m_playingService = id;
m_dvbDemod->setPlayingService(id); // So recording and the reports, in Automatic, are of this one
m_dvbDemod->getApps()->setCarouselService(m_dvbDemod->currentServiceId()); // Its carousels received straight away
updateAppsDialog();
updateHbbTVService();
#ifdef DVBDEMOD_HBBTV
if (m_hbbtv && (m_hbbtvChannelRequest != 0))
{
m_hbbtv->channelChangeResult(id == m_hbbtvChannelRequest);
m_hbbtvChannelRequest = 0;
}
#endif
m_lastFrames = 0;
m_framesTimer.start();
showServiceOverlay();
@ -1489,7 +1883,8 @@ DVBDemodGUI::DVBDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, Baseban @@ -1489,7 +1883,8 @@ DVBDemodGUI::DVBDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, Baseban
m_dvbDemod = reinterpret_cast<DVBDemod*>(rxChannel);
m_dvbDemod->setMessageQueueToGUI(getInputMessageQueue());
m_guideOverlay = new DVBDemodGuideOverlay(m_dvbDemod->getEPG(), this);
m_guideOverlay = new DTVGuideOverlay(m_dvbDemod->getEPG(), this);
m_guideOverlay->setLogo(QImage(":/demoddvb/images/angeltv.png"));
m_splitterTimer.setSingleShot(true);
connect(&m_splitterTimer, &QTimer::timeout, this, [this]() {
m_settings.m_splitterSizes = ui->splitter->sizes();
@ -1510,7 +1905,9 @@ DVBDemodGUI::DVBDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, Baseban @@ -1510,7 +1905,9 @@ DVBDemodGUI::DVBDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, Baseban
m_dvbDemod->scheduleRecording(networkId, serviceId, eventId);
}
});
connect(m_guideOverlay, &DVBDemodGuideOverlay::playService, this, &DVBDemodGUI::guideServiceSelected);
connect(m_guideOverlay, &DTVGuideOverlay::playService, this, &DVBDemodGUI::guideServiceSelected);
connect(m_guideOverlay, &DTVGuideOverlay::redButton, this, &DVBDemodGUI::hbbtvRed);
ui->redButton->setVisible(false);
connect(&MainCore::instance()->getMasterTimer(), SIGNAL(timeout()), this, SLOT(tick())); // 50 ms
@ -1548,10 +1945,11 @@ DVBDemodGUI::DVBDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, Baseban @@ -1548,10 +1945,11 @@ DVBDemodGUI::DVBDemodGUI(PluginAPI* pluginAPI, DeviceUISet *deviceUISet, Baseban
connect(&m_channelMarker, SIGNAL(highlightedByCursor()), this, SLOT(channelMarkerHighlightedByCursor()));
connect(getInputMessageQueue(), SIGNAL(messageEnqueued()), this, SLOT(handleInputMessages()));
#ifndef DVBDEMOD_DEINTERLACE
ui->deinterlace->setEnabled(false);
ui->deinterlace->setToolTip("Deinterlacing needs FFmpeg's libavfilter, which this build doesn't have");
#endif
if (!DTVVideoPlayer::canDeinterlace())
{
ui->deinterlace->setEnabled(false);
ui->deinterlace->setToolTip("Deinterlacing needs FFmpeg's libavfilter, which this build doesn't have");
}
displaySettings();
makeUIConnections();
@ -1571,18 +1969,25 @@ DVBDemodGUI::~DVBDemodGUI() @@ -1571,18 +1969,25 @@ DVBDemodGUI::~DVBDemodGUI()
m_dvbDemod->setMessageQueueToGUI(nullptr);
disconnect(&MainCore::instance()->getMasterTimer(), SIGNAL(timeout()), this, SLOT(tick()));
stopPlayer();
#ifdef DVBDEMOD_HBBTV
delete m_streamPlayback;
m_streamPlayback = nullptr;
m_streamPlaying = false;
delete m_hbbtv;
m_hbbtv = nullptr;
#endif
delete m_fullScreenTV;
delete ui;
}
void DVBDemodGUI::startPlayer()
{
if (m_player) {
if (m_player || m_streamPlaying) {
return;
}
m_dvbDemod->getTSFifo()->attachReader();
m_player = new DVBDemodVideoPlayer(m_dvbDemod->getTSFifo(), m_dvbDemod->getAudioFifo());
m_player = new DTVVideoPlayer(m_dvbDemod->getTSFifo(), m_dvbDemod->getAudioFifo());
// From the player's video thread
m_player->setFrameCallback([this](GLVideoFramePtr frame) {
m_videoScreen.load()->setFrame(frame);
@ -1597,10 +2002,11 @@ void DVBDemodGUI::startPlayer() @@ -1597,10 +2002,11 @@ void DVBDemodGUI::startPlayer()
m_player->setHardwareDecoding(m_settings.m_hardwareDecoding);
m_player->setAVOffset(m_settings.m_avOffset);
setTrackPreferences();
connect(m_player, &DVBDemodVideoPlayer::servicesChanged, this, &DVBDemodGUI::servicesChanged, Qt::QueuedConnection);
connect(m_player, &DVBDemodVideoPlayer::serviceSelected, this, &DVBDemodGUI::serviceSelected, Qt::QueuedConnection);
connect(m_player, &DVBDemodVideoPlayer::tracksChanged, this, &DVBDemodGUI::tracksChanged, Qt::QueuedConnection);
connect(m_player, &DTVVideoPlayer::servicesChanged, this, &DVBDemodGUI::servicesChanged, Qt::QueuedConnection);
connect(m_player, &DTVVideoPlayer::serviceSelected, this, &DVBDemodGUI::serviceSelected, Qt::QueuedConnection);
connect(m_player, &DTVVideoPlayer::tracksChanged, this, &DVBDemodGUI::tracksChanged, Qt::QueuedConnection);
m_player->start();
updateHbbTV();
}
void DVBDemodGUI::stopPlayer()
@ -1612,6 +2018,7 @@ void DVBDemodGUI::stopPlayer() @@ -1612,6 +2018,7 @@ void DVBDemodGUI::stopPlayer()
m_player->stopPlayer();
delete m_player;
m_player = nullptr;
updateHbbTV();
m_dvbDemod->getTSFifo()->detachReader(); // After the player's stopped, as its reads would attach it again
ui->screenTV->clear();
clearTracks();
@ -1717,6 +2124,7 @@ void DVBDemodGUI::displaySettings() @@ -1717,6 +2124,7 @@ void DVBDemodGUI::displaySettings()
}
updateAbsoluteCenterFrequency();
updateHbbTV();
blockApplySettings(false);
}
@ -1740,8 +2148,26 @@ void DVBDemodGUI::tick() @@ -1740,8 +2148,26 @@ void DVBDemodGUI::tick()
displayRecordings();
displaySimulcast();
m_guideOverlay->refresh();
updateHbbTVService();
displayRedButton();
}
#ifdef DVBDEMOD_HBBTV
if (m_hbbtv)
{
m_hbbtv->setSuppressed(m_guideOverlay->isShown());
// What the red button's waiting for, at the bottom right of the video, until there's nothing to wait for
const QString status = m_hbbtv->isStatusInPage() ? QString() : m_hbbtv->getStatus();
if (status != m_hbbtvStatus)
{
m_videoScreen.load()->setOverlay(status, status.isEmpty() ? 0.0 : 60.0);
m_hbbtvStatus = status;
}
}
#endif
if (++m_tickCount % 4 == 0) // 200 ms
{
displayStatus();
@ -1755,6 +2181,23 @@ void DVBDemodGUI::tick() @@ -1755,6 +2181,23 @@ void DVBDemodGUI::tick()
m_dvbDemod->getAudioOutput(sampleRate, latency);
m_player->setAudioOutput(sampleRate, latency);
}
#ifdef DVBDEMOD_HBBTV
if (m_streamPlayback && m_streamPlaying)
{
int sampleRate;
double latency;
m_dvbDemod->getAudioOutput(sampleRate, latency);
m_streamPlayback->setAudioOutput(sampleRate, latency);
if (m_hbbtv && m_streamPlayback->isPlaying())
{
QJsonObject data;
data.insert("position", m_streamPlayback->getPosition());
m_hbbtv->mediaEvent(m_mediaId, "time", data);
}
}
#endif
}
}
@ -1781,7 +2224,7 @@ void DVBDemodGUI::checkVideoReceived() @@ -1781,7 +2224,7 @@ void DVBDemodGUI::checkVideoReceived()
return;
}
DVBDemodVideoPlayer::Info info = m_player->getInfo();
DTVVideoPlayer::Info info = m_player->getInfo();
uint64_t frames = m_serviceHasVideo ? info.m_videoFrames : info.m_audioFrames;
if (frames != m_lastFrames)
@ -1834,6 +2277,18 @@ bool DVBDemodGUI::eventFilter(QObject *obj, QEvent *event) @@ -1834,6 +2277,18 @@ bool DVBDemodGUI::eventFilter(QObject *obj, QEvent *event)
m_pointerTimer.start(3000);
}
#ifdef DVBDEMOD_HBBTV
// With an application showing, a click gives the video the keys (for the application), rather than
// opening the ribbon, which would hide it. Double-clicking still goes full screen, and right-clicking
// opens the guide
if (m_hbbtv && m_hbbtv->isRunning() && m_hbbtv->isVisible() && !m_guideOverlay->isShown() && (type == QEvent::MouseButtonPress)
&& (static_cast<QMouseEvent*>(event)->button() == Qt::LeftButton))
{
m_hbbtv->takeFocus();
return true;
}
#endif
if (((type == QEvent::MouseMove) || (type == QEvent::MouseButtonPress) || (type == QEvent::MouseButtonDblClick))
&& m_guideOverlay->handleMouse(static_cast<QMouseEvent*>(event))) {
return true;
@ -1843,12 +2298,27 @@ bool DVBDemodGUI::eventFilter(QObject *obj, QEvent *event) @@ -1843,12 +2298,27 @@ bool DVBDemodGUI::eventFilter(QObject *obj, QEvent *event)
return true;
}
#ifdef DVBDEMOD_HBBTV
if (m_hbbtv && !m_guideOverlay->isShown())
{
if ((type == QEvent::KeyPress) && m_hbbtv->keyPress(static_cast<QKeyEvent*>(event))) {
return true;
}
if ((type == QEvent::KeyRelease) && m_hbbtv->keyRelease(static_cast<QKeyEvent*>(event))) {
return true;
}
}
#endif
if ((type == QEvent::KeyPress) && m_guideOverlay->handleKey(static_cast<QKeyEvent*>(event))) {
return true;
}
if (type == QEvent::Resize) {
if (type == QEvent::Resize)
{
m_guideOverlay->refresh(true);
updateHbbTVGeometry();
}
}
@ -1923,6 +2393,7 @@ void DVBDemodGUI::setVideoFullScreen(bool fullScreen) @@ -1923,6 +2393,7 @@ void DVBDemodGUI::setVideoFullScreen(bool fullScreen)
#endif
m_fullScreenTV->activateWindow();
m_fullScreenTV->setFocus();
updateHbbTVGeometry();
if (!m_videoMessage.isEmpty()) {
showVideoMessage(m_videoMessage);
@ -1932,6 +2403,7 @@ void DVBDemodGUI::setVideoFullScreen(bool fullScreen) @@ -1932,6 +2403,7 @@ void DVBDemodGUI::setVideoFullScreen(bool fullScreen)
{
m_videoScreen = ui->screenTV;
m_guideOverlay->setWidget(ui->screenTV);
updateHbbTVGeometry();
m_fullScreenTV->hide();
// Its frames may hold the decoder's GPU surfaces. Cleared now, and again a little later, as the video thread
@ -1981,7 +2453,7 @@ void DVBDemodGUI::setupStats() @@ -1981,7 +2453,7 @@ void DVBDemodGUI::setupStats()
// The player's A/V problems in the last 10 s (what's happening now, rather than since it started), from its counts then and
// now: frames late or with errors, the frame rate and stalls, A/V sync and the clock resynchronising, audio muted or
// missing, the audio FIFO running dry or overflowing, and TS the player didn't take. Orange while there are any
void DVBDemodGUI::displayAVStats(const DVBDemodVideoPlayer::Info& info, uint64_t tsOverflows)
void DVBDemodGUI::displayAVStats(const DTVVideoPlayer::Info& info, uint64_t tsOverflows)
{
const bool video = m_player && !info.m_videoCodec.isEmpty();
const bool audio = m_player && !info.m_audioCodec.isEmpty();
@ -2277,7 +2749,7 @@ QString DVBDemodGUI::shortCodecName(const QString& name) @@ -2277,7 +2749,7 @@ QString DVBDemodGUI::shortCodecName(const QString& name)
// The codecs and picture size in the table, the A/V problems, and the mute button green while audio is playing
void DVBDemodGUI::displayPlayerInfo(uint64_t tsOverflows)
{
DVBDemodVideoPlayer::Info info;
DTVVideoPlayer::Info info;
if (m_player) {
info = m_player->getInfo();
@ -2563,6 +3035,10 @@ void DVBDemodGUI::makeUIConnections() @@ -2563,6 +3035,10 @@ void DVBDemodGUI::makeUIConnections()
QObject::connect(ui->videoEnabled, &ButtonSwitch::toggled, this, &DVBDemodGUI::on_videoEnabled_toggled);
QObject::connect(ui->service, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &DVBDemodGUI::on_service_currentIndexChanged);
QObject::connect(ui->epg, &QToolButton::clicked, this, &DVBDemodGUI::on_epg_clicked);
QObject::connect(ui->apps, &QToolButton::clicked, this, &DVBDemodGUI::on_apps_clicked);
QObject::connect(ui->redButton, &QToolButton::clicked, this, &DVBDemodGUI::hbbtvRed);
ui->apps->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(ui->apps, &QToolButton::customContextMenuRequested, this, &DVBDemodGUI::appsMenu);
ui->epg->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(ui->epg, &QToolButton::customContextMenuRequested, this, &DVBDemodGUI::epgMenu);
QObject::connect(ui->scan, &QToolButton::clicked, this, &DVBDemodGUI::on_scan_clicked);

45
plugins/channelrx/demoddvb/dvbdemodgui.h

@ -36,15 +36,18 @@ @@ -36,15 +36,18 @@
#include "dvbdemodsettings.h"
#include "dvbdemodsink.h"
#include "dvbdemodvideoplayer.h"
#include "dvbdemodepgdialog.h"
#include "dvbdemodguideoverlay.h"
#include "dtv/dtvvideoplayer.h"
#include "dtv/dtvappsdialog.h"
#include "dtv/dtvepgdialog.h"
#include "dtv/dtvguideoverlay.h"
class PluginAPI;
class DeviceUISet;
class BasebandSampleSink;
class DVBDemod;
class GLVideoWidget;
class DVBDemodHbbTV;
class DTVStreamPlayback;
namespace Ui {
class DVBDemodGUI;
@ -101,7 +104,7 @@ private: @@ -101,7 +104,7 @@ private:
bool m_doApplySettings;
DVBDemod* m_dvbDemod;
DVBDemodVideoPlayer *m_player;
DTVVideoPlayer *m_player;
uint32_t m_tickCount;
bool m_videoFullScreen;
GLVideoWidget *m_fullScreenTV; //!< Window for full screen video, made when first needed
@ -109,17 +112,26 @@ private: @@ -109,17 +112,26 @@ private:
//! The polarisation command the user's typed or agreed to run, this session: one that came with a preset or
//! configuration (perhaps someone else's) is shown and confirmed before it's first run
QString m_polarisationCommandConfirmed;
DVBDemodGuideOverlay *m_guideOverlay; //!< Programme guide over full screen video
DTVGuideOverlay *m_guideOverlay; //!< Programme guide over full screen video
QTimer m_pointerTimer; //!< Hides the mouse pointer over full screen video when it stops
QTimer m_splitterTimer; //!< Saves the splitter's sizes once it stops moving
std::atomic<GLVideoWidget*> m_videoScreen; //!< Where the player shows video
// A message is shown in place of the video when there is none
QString m_videoMessage;
bool m_serviceHasVideo;
QList<DVBDemodVideoPlayer::Service> m_services;
QList<DTVVideoPlayer::Service> m_services;
int m_playingService; //!< Id of the service selected by the player, 0 for none yet
QString m_overlayText; //!< Last shown, to show it again if the service's name or number changes
QPointer<DVBDemodEPGDialog> m_epgDialog;
QPointer<DTVEPGDialog> m_epgDialog;
QPointer<DTVAppsDialog> m_appsDialog;
DVBDemodHbbTV *m_hbbtv = nullptr; //!< Runs the service's HbbTV applications, when they're enabled
QRectF m_hbbtvVideoArea; //!< Where the application wants the video, of its page, null for all
int m_hbbtvChannelRequest = 0; //!< A service the application's asked to play, 0 if none
QString m_hbbtvServiceState; //!< What it was last told of the service and multiplex
QString m_hbbtvStatus; //!< Shown over the video
DTVStreamPlayback *m_streamPlayback = nullptr; //!< Plays an application's media (as iPlayer's), from the internet
int m_mediaId = 0; //!< The application's media being played, 0 if none
bool m_streamPlaying = false; //!< Its stream's playing, in place of the broadcast (whose player's stopped)
QString m_nowTitle; //!< On the service playing, to show the overlay when it changes
bool m_serviceHasAudio;
uint64_t m_lastFrames; //!< Video or audio frames, to see if any are arriving
@ -178,7 +190,7 @@ private: @@ -178,7 +190,7 @@ private:
void setStatWarning(Stat row, bool warning);
void displayStatus();
void displayPlayerInfo(uint64_t tsOverflows);
void displayAVStats(const DVBDemodVideoPlayer::Info& info, uint64_t tsOverflows);
void displayAVStats(const DTVVideoPlayer::Info& info, uint64_t tsOverflows);
void displayT2Status(const DVBDemodSink::Status& status);
void displayScopeExtras(const DVBDemodSink::Status& status, double mer, double iterations, uint64_t errors);
void displayPLPs(const dvbt2::Receiver::Status& status);
@ -229,6 +241,19 @@ private slots: @@ -229,6 +241,19 @@ private slots:
void on_service_currentIndexChanged(int index);
void on_deinterlace_toggled(bool checked);
void on_epg_clicked();
void on_apps_clicked();
void updateAppsDialog();
void appsMenu(const QPoint& position);
void updateHbbTV(); //!< Running HbbTV applications or not, as the settings and player are
void updateHbbTVService();
void updateHbbTVGeometry();
QRect hbbtvPageRect(const QWidget *screen) const;
void hbbtvVideoArea(const QRectF& area);
void hbbtvChannelChange(int networkId, int transportStreamId, int serviceId);
void hbbtvRed(); //!< The red button clicked
void hbbtvMedia(const QString& command, int id, const QString& url, const QMap<QString, QString>& options, double position);
void stopStreamPlayback(); //!< The application's media stopped, and the broadcast played again
void displayRedButton();
void on_scan_clicked();
void on_simulcast_clicked();
void on_record_toggled(bool checked);
@ -239,12 +264,12 @@ private slots: @@ -239,12 +264,12 @@ private slots:
void on_hardwareDecoding_toggled(bool checked);
void on_audioTrack_currentIndexChanged(int index);
void on_subtitleTrack_currentIndexChanged(int index);
void tracksChanged(const DVBDemodVideoPlayer::Tracks& tracks);
void tracksChanged(const DTVVideoPlayer::Tracks& tracks);
void on_avOffset_valueChanged(int value);
void on_audioMute_toggled(bool checked);
void on_audioVolume_valueChanged(int value);
void audioSelect(const QPoint& p);
void servicesChanged(const QList<DVBDemodVideoPlayer::Service>& services);
void servicesChanged(const QList<DTVVideoPlayer::Service>& services);
void serviceSelected(int id, bool hasVideo, bool hasAudio);
void onWidgetRolled(QWidget* widget, bool rollDown);
void onSplitterMoved(int pos, int index);

29
plugins/channelrx/demoddvb/dvbdemodgui.ui

@ -686,7 +686,7 @@ @@ -686,7 +686,7 @@
</widget>
</item>
<item>
<widget class="DVBDemodScope" name="scope" native="true">
<widget class="DTVScope" name="scope" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
@ -975,6 +975,29 @@ @@ -975,6 +975,29 @@
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="apps">
<property name="toolTip">
<string>Show the interactive applications (red button) of the service played: HbbTV's and others from its AIT, and its MHEG-5 and HbbTV object carousels, with their files</string>
</property>
<property name="text">
<string>Apps</string>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="redButton">
<property name="toolTip">
<string>The red button: the service's interactive application (HbbTV), as R on the video</string>
</property>
<property name="styleSheet">
<string notr="true">QToolButton { color: #e62928; font-weight: bold; }</string>
</property>
<property name="text">
<string>Red</string>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="scan">
<property name="toolTip">
@ -1029,9 +1052,9 @@ @@ -1029,9 +1052,9 @@
<header>gui/buttonswitch.h</header>
</customwidget>
<customwidget>
<class>DVBDemodScope</class>
<class>DTVScope</class>
<extends>QWidget</extends>
<header>dvbdemodscope.h</header>
<header>dtv/dtvscope.h</header>
<container>1</container>
</customwidget>
<customwidget>

1257
plugins/channelrx/demoddvb/dvbdemodhbbtv.cpp

File diff suppressed because it is too large Load Diff

216
plugins/channelrx/demoddvb/dvbdemodhbbtv.h

@ -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

9
plugins/channelrx/demoddvb/dvbdemodsettings.cpp

@ -148,6 +148,7 @@ void DVBDemodSettings::resetToDefaults() @@ -148,6 +148,7 @@ void DVBDemodSettings::resetToDefaults()
m_videoEnabled = true;
m_serviceId = 0;
m_deinterlace = true;
m_hbbtv = false;
m_hardwareDecoding = true;
m_audioLanguage = "";
m_audioDescription = false;
@ -217,6 +218,7 @@ QByteArray DVBDemodSettings::serialize() const @@ -217,6 +218,7 @@ QByteArray DVBDemodSettings::serialize() const
s.writeS32(9, m_audioVolume);
s.writeString(10, m_audioDeviceName);
s.writeBool(11, m_deinterlace);
s.writeBool(65, m_hbbtv);
s.writeS32(12, m_standard);
s.writeS32(13, m_plpId);
s.writeS32(14, m_avOffset);
@ -309,6 +311,7 @@ bool DVBDemodSettings::deserialize(const QByteArray& data) @@ -309,6 +311,7 @@ bool DVBDemodSettings::deserialize(const QByteArray& data)
d.readS32(9, &m_audioVolume, 50);
d.readString(10, &m_audioDeviceName, AudioDeviceManager::m_defaultDeviceName);
d.readBool(11, &m_deinterlace, true);
d.readBool(65, &m_hbbtv, false);
d.readS32(12, &m_standard, StandardAutoTerrestrial);
if (!isValidStandard(m_standard)) {
@ -487,6 +490,9 @@ void DVBDemodSettings::applySettings(const QStringList& settingsKeys, const DVBD @@ -487,6 +490,9 @@ void DVBDemodSettings::applySettings(const QStringList& settingsKeys, const DVBD
if (settingsKeys.contains("deinterlace")) {
m_deinterlace = settings.m_deinterlace;
}
if (settingsKeys.contains("hbbtv")) {
m_hbbtv = settings.m_hbbtv;
}
if (settingsKeys.contains("avOffset")) {
m_avOffset = settings.m_avOffset;
}
@ -658,6 +664,9 @@ QString DVBDemodSettings::getDebugString(const QStringList& settingsKeys, bool f @@ -658,6 +664,9 @@ QString DVBDemodSettings::getDebugString(const QStringList& settingsKeys, bool f
if (settingsKeys.contains("deinterlace") || force) {
s.append(QString("m_deinterlace: %1").arg(m_deinterlace));
}
if (settingsKeys.contains("hbbtv") || force) {
s.append(QString("m_hbbtv: %1").arg(m_hbbtv));
}
if (settingsKeys.contains("avOffset") || force) {
s.append(QString("m_avOffset: %1").arg(m_avOffset));
}

40
plugins/channelrx/demoddvb/dvbdemodsettings.h

@ -24,6 +24,8 @@ @@ -24,6 +24,8 @@
#include <QString>
#include <QStringList>
#include "dtv/dtvguide.h"
class Serializable;
struct DVBDemodSettings
@ -40,40 +42,9 @@ struct DVBDemodSettings @@ -40,40 +42,9 @@ struct DVBDemodSettings
StandardDVBS2 = 6
};
//! A programme to record, from the programme guide
struct ScheduledRecording
{
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 ScheduledRecording& 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 SeriesRecording
{
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 SeriesRecording& 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);
}
};
//! A programme to record, from the programme guide, and a series
typedef DTVScheduledRecording ScheduledRecording;
typedef DTVSeriesRecording SeriesRecording;
qint64 m_inputFrequencyOffset;
int m_bandwidth; //!< Channel bandwidth in Hz: 8, 7 or 6 MHz
@ -96,6 +67,7 @@ struct DVBDemodSettings @@ -96,6 +67,7 @@ struct DVBDemodSettings
bool m_videoEnabled; //!< Decode and display the selected service
int m_serviceId; //!< MPEG program number of the service to play, 0 for the first with video
bool m_deinterlace;
bool m_hbbtv; //!< Run the service's HbbTV applications (red button), over the video
bool m_hardwareDecoding; //!< Decode video with the GPU, where possible
QString m_audioLanguage; //!< ISO 639-2 code of the audio to play, or empty for the first
bool m_audioDescription; //!< Play audio description, where a service has it

7
plugins/channelrx/demoddvb/dvbdemodsink.cpp

@ -956,6 +956,7 @@ void DVBDemodSink::processPacket(const uint8_t *packet) @@ -956,6 +956,7 @@ void DVBDemodSink::processPacket(const uint8_t *packet)
{
m_ratePackets++;
m_epg.feed(packet);
m_apps.feed(packet);
m_packetBlock.insert(m_packetBlock.end(), packet, packet + 188);
if (m_packetBlock.size() >= m_packetBlockSize) {
@ -995,10 +996,10 @@ void DVBDemodSink::flushPackets() @@ -995,10 +996,10 @@ void DVBDemodSink::flushPackets()
m_packetBlock.clear();
}
int DVBDemodSink::startRecording(const QString& fileName, DVBDemodRecorder::Mode mode, int serviceId, QString& error)
int DVBDemodSink::startRecording(const QString& fileName, DTVRecorder::Mode mode, int serviceId, QString& error)
{
// The file is created here, rather than in the demodulator's thread
std::unique_ptr<DVBDemodRecorder> recorder(new DVBDemodRecorder());
std::unique_ptr<DTVRecorder> recorder(new DTVRecorder());
if (!recorder->start(fileName, mode, serviceId, error)) {
return -1;
@ -1012,7 +1013,7 @@ int DVBDemodSink::startRecording(const QString& fileName, DVBDemodRecorder::Mode @@ -1012,7 +1013,7 @@ int DVBDemodSink::startRecording(const QString& fileName, DVBDemodRecorder::Mode
void DVBDemodSink::stopRecording(int id)
{
std::shared_ptr<DVBDemodRecorder> recorder;
std::shared_ptr<DTVRecorder> recorder;
{
QMutexLocker locker(&m_recordersMutex);

21
plugins/channelrx/demoddvb/dvbdemodsink.h

@ -40,10 +40,11 @@ @@ -40,10 +40,11 @@
#include "modemdvb/dvbs2receiver.h"
#include "dvbdemodepg.h"
#include "dvbdemodrecorder.h"
#include "dtv/dtvapps.h"
#include "dtv/dtvrecorder.h"
#include "dvbdemodsettings.h"
#include "dvbdemodtsfifo.h"
#include "dvbdemodudp.h"
#include "dtv/dtvtsfifo.h"
#include "dtv/dtvudp.h"
class DVBDemodSink : public ChannelSampleSink {
public:
@ -124,19 +125,20 @@ public: @@ -124,19 +125,20 @@ public:
//! Where the device's centre, and so its LO leakage, is in the channel, if it is
void configureDCRemoval();
void getStatus(Status& status);
DVBDemodTSFifo *getTSFifo() { return &m_tsFifo; }
DTVTSFifo *getTSFifo() { return &m_tsFifo; }
AudioFifo *getAudioFifo() { return &m_audioFifo; }
void setAudioFifoLabel(const QString& label) { m_audioFifo.setLabel(label); }
DVBDemodEPG *getEPG() { return &m_epg; }
DTVApps *getApps() { return &m_apps; }
struct Recording
{
int m_id;
DVBDemodRecorder::Status m_status;
DTVRecorder::Status m_status;
};
//! Records the multiplex, or a service, to a .ts file. Returns its id, or -1 with the error
int startRecording(const QString& fileName, DVBDemodRecorder::Mode mode, int serviceId, QString& error);
int startRecording(const QString& fileName, DTVRecorder::Mode mode, int serviceId, QString& error);
//! What's queued is written, and the file closed, in a thread of its own (up to 64 MB to a slow disk would hold
//! up the caller): this returns at once. Those still finishing are waited for when this is deleted
void stopRecording(int id);
@ -249,11 +251,12 @@ private: @@ -249,11 +251,12 @@ private:
std::deque<std::pair<uint64_t, uint64_t>> m_rateHistory;
double m_tsBitRate;
DVBDemodUDP m_udp;
DVBDemodTSFifo m_tsFifo;
DTVUDP m_udp;
DTVTSFifo m_tsFifo;
DVBDemodEPG m_epg; //!< Fed whether or not video is enabled, so it's also there in server builds
DTVApps m_apps; //!< As the EPG
QMutex m_recordersMutex; //!< For the following, as recordings are started and stopped from other threads
std::vector<std::pair<int, std::unique_ptr<DVBDemodRecorder>>> m_recorders;
std::vector<std::pair<int, std::unique_ptr<DTVRecorder>>> m_recorders;
int m_nextRecordingId;
std::vector<std::future<void>> m_stoppingRecorders; //!< Stopped, finishing their files
std::vector<uint8_t> m_packetBlock; //!< Packets delivered, not flushed yet

938
plugins/channelrx/demoddvb/hbbtv/oipf.js

@ -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 });
});
})();

136
plugins/channelrx/demoddvb/readme.md

@ -34,7 +34,7 @@ DVB-T2 (the T2-base and T2-Lite profiles): @@ -34,7 +34,7 @@ DVB-T2 (the T2-base and T2-Lite profiles):
The FFT size comes from the P1 symbol, the guard interval from the correlation of the following symbols, and the rest from the L1 signalling.
The FFT window is placed from the channel's measured impulse response, so echoes up to the length of the guard interval can be received, from the first
frame after acquisition (the response is measured from the first P2 symbol). With long echoes, the channel is estimated from the pilots of several symbols.
MISO is supported (both groups of transmitters, or either alone). Time-frequency slicing and recombining data PLPs with their common PLP aren't supported.
MISO is supported (both groups of transmitters, or either alone). Time-frequency slicing and recombining data PLPs with their common PLP aren't supported.
In the UK, the HD multiplexes (e.g. PSB3) use 32K extended carriers, GI 1/128, PP7 and one PLP of rotated 256-QAM 2/3 with 64K LDPC,
which is supported.
@ -80,10 +80,10 @@ Video and audio are decoded with FFmpeg, so the plugin can play any codec FFmpeg @@ -80,10 +80,10 @@ Video and audio are decoded with FFmpeg, so the plugin can play any codec FFmpeg
<h2>Sample rate</h2>
DVB-T is defined in terms of an elementary period of 7/64 us for 8 MHz channels, so the receiver works at 64/7 MS/s (9,142,857 S/s).
For 7 and 6 MHz channels it is 8 MS/s and 48/7 MS/s respectively.
For 7 and 6 MHz channels it is 8 MS/s and 48/7 MS/s respectively.
It's best to set the device sample rate to this, or to it multiplied by a power of 2, with decimation enabled.
Other channel sample rates from 0.875 to 2.2 times this (8.0 to 20.1 MS/s for 8 MHz channels) are resampled, which takes more CPU.
Other channel sample rates from 0.875 to 2.2 times this (8.0 to 20.1 MS/s for 8 MHz channels) are resampled, which takes more CPU.
The lowest still holds the 7.61 MHz occupied by an 8 MHz channel (7.77 MHz for DVB-T2 in extended carrier mode).
The receiver also measures the sample clock offset between the device and the transmitter, and resamples to correct it when it is more than 3 ppm (1 ppm for DVB-T2, whose 32K symbols are longer).
Smaller offsets are followed by moving the FFT window. A DVB-T2 32K signal may not be decoded until the offset has been corrected, a frame or two after the receiver finds it, if it's more than a few ppm.
@ -92,10 +92,10 @@ Devices that can run at 9,142,857 S/s include the USRP B210, SDRplay RSPduo, Lim @@ -92,10 +92,10 @@ Devices that can run at 9,142,857 S/s include the USRP B210, SDRplay RSPduo, Lim
An RTL-SDR can't run fast enough.
For DVB-S and DVB-S2, the device's sample rate should be at least 1.2 times the symbol rate: the signal
is 1 + roll-off times it wide, and losing a little of its edges (at roll-off 0.25 and 0.35) costs under 0.3 dB.
Higher is better if the device can keep up, leaving room for the signal being off centre and for the device's own filter.
For example, 33 MS/s or more for 27.5 MS/s (which needs a USRP B210 or similar), 27.6 MS/s or more for 23 MS/s,
and 1 MS/s or more for the 333 kS/s and 500 kS/s amateur signals on QO-100.
is 1 + roll-off times it wide, and losing a little of its edges (at roll-off 0.25 and 0.35) costs under 0.3 dB.
Higher is better if the device can keep up, leaving room for the signal being off centre and for the device's own filter.
For example, 33 MS/s or more for 27.5 MS/s (which needs a USRP B210 or similar), 27.6 MS/s or more for 23 MS/s,
and 1 MS/s or more for the 333 kS/s and 500 kS/s amateur signals on QO-100.
<h2>Satellite reception</h2>
@ -148,12 +148,12 @@ DVB-S and S2 symbol rate, in symbols a second. Type it, or choose a common one: @@ -148,12 +148,12 @@ DVB-S and S2 symbol rate, in symbols a second. Type it, or choose a common one:
(Astra 2's HD multiplexes are 23 MS/s DVB-S2 8PSK, and its SD ones 22 or 27.5 MS/s DVB-S), and 25,000 to 2,000,000 for amateur DATV (QO-100's wideband transponder).
The channel's sample rate is from 2 to 4 times this, but the device sample rate needs to be only 1.2 times this (see Sample rate above).
Auto (the default) measures the symbol rate of the strongest signal in the channel.
Auto (the default) measures the symbol rate of the strongest signal in the channel.
<h3>5: RO - Roll-off</h3>
DVB-S2 roll-off of the root raised cosine pulse: 0.35, 0.25, 0.20, DVB-S2X's 0.15, 0.10, 0.05, or Auto, which follows the BBHEADER (starting at 0.35). DVB-S's is always 0.35.
A matched filter with the wrong roll-off costs a few tenths of a dB.
A matched filter with the wrong roll-off costs a few tenths of a dB.
<h3>6: Rate - Code rate</h3>
@ -190,7 +190,7 @@ Average power of the signal in the channel, in dB. @@ -190,7 +190,7 @@ Average power of the signal in the channel, in dB.
<h3>12: UDP</h3>
When checked, the transport stream is sent as UDP datagrams to the given address (an IP address, or a host name) and port.
When checked, the transport stream is sent as UDP datagrams to the given address (an IP address, or a host name) and port.
It can be played with, for example:
vlc udp://@:5004
@ -218,7 +218,7 @@ rather than acquiring again, which takes a few tenths of a second. @@ -218,7 +218,7 @@ rather than acquiring again, which takes a few tenths of a second.
<h3>Signal and Video</h3>
The signal area is above the video area. Drag the bar between them to share the height out differently:
The signal area is above the video area. Drag the bar between them to share the height out differently:
dragging it to the top or bottom hides one area.
The sizes are saved with the settings.
@ -341,7 +341,7 @@ Decode and display the selected service. Click to play; click again to stop. @@ -341,7 +341,7 @@ Decode and display the selected service. Click to play; click again to stop.
Service to play. The list comes from the Service Description Table in the transport stream, which is repeated every few seconds,
so services are shown with their numbers until it has been received. Automatic plays the first service with video.
Data services, such as the Red Button, have no video or audio to play. Scrambled (encrypted, pay TV) services, such as most of Sky's,
can't be played: the video shows "Scrambled".
can't be played: the video shows "Scrambled".
<h4>3: HD</h4>
@ -350,7 +350,7 @@ When the programme playing is also available in HD, click the button to switch t @@ -350,7 +350,7 @@ When the programme playing is also available in HD, click the button to switch t
<h4>4: Deinterlace</h4>
Deinterlace the video, with FFmpeg's bwdif filter, which interpolates motion. SD services in the UK are interlaced, so without it, moving objects have combing artifacts.
Needs FFmpeg's libavfilter, without which the button is disabled.
Needs FFmpeg's libavfilter, without which the button is disabled.
<h4>5: Hardware decoding</h4>
@ -378,7 +378,7 @@ The button mutes the audio, and is green while audio is playing. Right click it @@ -378,7 +378,7 @@ The button mutes the audio, and is green while audio is playing. Right click it
<h4>9: Audio service</h4>
The audio list has each language, and audio description where the service supports it. In the UK, audio description is a separate
narration that is mixed with the main audio: the main audio is faded down while the narrator speaks.
narration that is mixed with the main audio: the main audio is faded down while the narrator speaks.
A description that is broadcast already mixed is listed as "(audio description)", and audio for the hard of hearing as "(clean audio)".
The choice is kept for other services: the same kind of track in the same language where they have it, else the language's main audio.
@ -427,9 +427,9 @@ or the other cable of a Sky Q LNB. Right click the EPG button to set a command t @@ -427,9 +427,9 @@ or the other cable of a Sky Q LNB. Right click the EPG button to set a command t
It's run before retuning, with %p in it replaced by H, V, L or R (horizontal, vertical, left or right hand circular), or that added as its last argument
if there's no %p, and should exit with 0 once switched; if it fails (or doesn't finish within 20 s), the device isn't retuned, and why is shown.
Without a command, a message box says which polarisation the multiplex needs: Continue to switch the LNB yourself and retune, or Cancel to stay on
the multiplex received.
the multiplex received.
The services are listed by channel number. Those in italics are on other multiplexes: playing one retunes the device to its multiplex.
The services are listed by channel number. Those in italics are on other multiplexes: playing one retunes the device to its multiplex.
The guide gives the frequencies of DVB-T multiplexes, but in the UK
not of DVB-T2 ones (PSB3, with the HD services), so the frequency of each multiplex received is remembered. Playing a service on a multiplex whose
frequency isn't known yet searches the UHF channels (21 to 48, then 49 to 69) for it, which takes a few seconds a channel; the progress is shown over
@ -452,6 +452,23 @@ An on-screen guide is also available by right-clicking on the video. @@ -452,6 +452,23 @@ An on-screen guide is also available by right-clicking on the video.
![On screen EPG](../../../doc/img/DVBDemod_onscreen_epg.png)
<h4>Apps</h4>
The Apps button opens a list of the interactive (red button) applications:
* Applications: from the service's application information table (AIT): HbbTV's (and DVB-J and DVB-HTML ones, should any be signalled), with
their names, ids, and whether they start with the service (AUTOSTART) or are started by the user, from the red button (PRESENT), and where
they start from: an HTTP URL, or a file in one of the service's carousels, as a dvb: URL.
* Carousels: the files of the service's MHEG-5 and HbbTV applications, sent round and round in
the transport stream, and how much of each has been received. A large carousel takes a minute or so, and is
received again as the broadcaster updates it.
Right click the Apps button to run the HbbTV applications.
Keys for the red, green, yellow and blue buttons are R, G, Y and B (or F1 to F4), Back is Backspace, and the arrows, Enter and digits are themselves.
Some broadcasters (such as the BBC) only serve their online applications to TVs they've certified, so videos may not play.
<h4>Scan</h4>
With a satellite standard, the Scan button scans a range of frequencies for transponders. The range is asked for when the scan starts, as From and To
@ -468,13 +485,13 @@ reception), these are downlink frequencies. The last scan's range is offered, or @@ -468,13 +485,13 @@ reception), these are downlink frequencies. The last scan's range is offered, or
The range can be wider than the device's sample rate: it's scanned in steps.
Transponders with a transport stream are added to the programme guide, with their frequency, symbol rate and standard, and their network's services and other
multiplexes come from their NIT and SDT.
multiplexes come from their NIT and SDT.
The signals the sweep found, each one tried and what it was, and the transponders found
are written to the log. The progress, and the transponders found when it's done,
are shown in the status and over the video; afterwards the device returns to where it was.
are shown in the status and over the video; afterwards the device returns to where it was.
While it scans, the button shows Stop, which stops it.
While it scans, the button shows Stop, which stops it.
<h4>Video</h4>
Displays the selected service, scaled to square pixels, so 16:9 anamorphic SD services are displayed with the right aspect ratio.
@ -538,6 +555,9 @@ they're left out unless asked for. For example, to get BBC One's schedule: @@ -538,6 +555,9 @@ they're left out unless asked for. For example, to get BBC One's schedule:
The play and recordEvent actions take a networkId too, from epgServiceList, for a service id used on more than one network.
The hbbtv setting (1 or 0) runs HbbTV applications, in the GUI. The report also gives the interactive applications of the service selected (interactiveApps: each one's id, type, control code, name and the URL it
starts from), and its object carousels (carousels: each one's PID, kind, and the modules, bytes and files of it received).
To receive DVB-S2 at 23 MS/s, with the roll-off from the BBHEADER, or with the standard and symbol rate found automatically:
curl -X PATCH "http://127.0.0.1:8091/sdrangel/deviceset/0/channel/0/settings" -d '{"channelType": "DVBDemod", "direction": 0, "DVBDemodSettings": {"standard": 6, "symbolRate": 23000000, "rollOff": 0}}'
@ -549,79 +569,3 @@ numbers (0 for the default region's). @@ -549,79 +569,3 @@ numbers (0 for the default region's).
The standard is 0 for automatic (DVB-T or T2), 1 DVB-T, 2 DVB-T2, 3 DVB-T2-Lite, 4 automatic (DVB-S or S2), 5 DVB-S and 6 DVB-S2. The DVB-S and S2
report adds the symbol rate set and measured, the roll-off, and, for DVB-S2, the MODCOD, pilots, frame size, input stream, Es/N0, and frame, dummy frame
and header miss counts.
<h2>Testing with recordings</h2>
Signals can be recorded to a .wav IQ file at 9 142 857 S/s from the device's recording control, then played back with the File Input device.
sdrangelbench can decode a recording to a transport stream file, printing the receiver state:
sdrangelbench -t dvbtfile -f recording.wav -a out=recording.ts
With analyse=1, it also counts clipped samples and prints the MER across the channel and of the carriers either side of the centre, which shows interference and LO leakage:
sdrangelbench -t dvbtfile -f recording.wav -a seconds=10,analyse=1
A transport stream can be played without a display, which prints the services and the codecs:
sdrangelbench -t dvbtplay -f recording.ts -a seconds=10
With subs=1 and ad=1, it prints the audio and subtitle tracks and when subtitles change, and wav= saves the audio played:
sdrangelbench -t dvbtplay -f recording.ts -a seconds=20,subs=1,ad=1,wav=audio.wav
The programme guide in a transport stream, with the multiplexes the NIT gives, can be printed, and the grid drawn to an image:
sdrangelbench -t dvbtepg -f recording.ts -a all=1,grid=grid.png
It can also create a recording from a transport stream file, for testing (the stream's bit rate must match the mode, which it prints):
sdrangelbench -t dvbtmod -a in=stream.ts,out=dvbt_490MHz,centre=490000000
and test the receiver with a simulated signal (by default with an echo of 0.3 at 40 samples: echo=0 for a Gaussian channel):
sdrangelbench -t dvbt -a snr=20,cfo=10000,ppm=2
sdrangelbench -t dvbt -a mod=qpsk,rate=1/2,snr=3,echo=0
sdrangelbench -t dvbt -a snr=22,cw=-10,cwfreq=1234567
sdrangelbench -t dvbt -a hier=2,mod=64qam,rate=1/2,lprate=3/4,stream=lp
For DVB-T2, the equivalents are dvbt2file (with plp=id to choose the PLP), dvbt2mod and dvbt2. dvbt2mod adds null packets to make up the rate of the
T2 mode, if tsrate gives the rate of the input stream. The mode is given by fft, ext, gi, pp, mod, rate, rot, fec (16k or 64k), ti (TI-blocks, 0 for none),
l1mod, tr and hem, and defaults to the UK HD multiplexes:
sdrangelbench -t dvbt2file -f recording.wav -a out=recording.ts
sdrangelbench -t dvbt2mod -a in=stream.ts,out=dvbt2_545MHz,centre=545833000,tsrate=24128342
sdrangelbench -t dvbt2 -a loop,snr=20,frames=3
sdrangelbench -t dvbt2
The last runs self tests of the tables and the FEC. With fectest, it tests the FEC alone in a Gaussian channel.
For DVB-S, the equivalents are dvbsfile (sr gives the symbol rate, and rate the code rate, auto by default), dvbsmod and dvbs, and for DVB-S2 dvbs2file,
dvbs2mod and dvbs2. A recording should be at 1.2 to 64 times the symbol rate. dvbs2mod's and dvbs2's mode is given by modcod (a number, 1 to 28, or e.g. 8psk2/3),
short, nopilots, ro (0.35 to 0.05), n (the scrambling code), vcm, mis, generic (a generic stream) and tsn (time slicing, each stream's time slice
number, as tsn=17/33 with mis=1). A VL-SNR MODCOD is vl and its VL-SNR header's index, 0 to 5 or 9 to 11 (as vl4 for BPSK-S 1/5), as the
modcod or in vcm, and vldummy=n sends n VL-SNR dummy frames first. dvbs2 simulates a channel given by snr (Es/N0 in dB, or offset from the
MODCOD's threshold), cfo, ppm, pn (phase noise), drift and conj=1 (the spectrum inverted), and lowsnr (the Es/N0 after the first quarter of the
signal, to test following a signal that fades), and by default first runs self tests of the tables and the FEC. It fails if any packet's lost
after the first frames, unless gaps allows a few runs of them (as a VL-SNR lock's first frames may be). dvbs2file takes isi (an input
stream, or a time slice), rxro (the matched filter's roll-off, else from the BBHEADER) and conj=1:
sdrangelbench -t dvbs2file -f recording.wav -a sr=23000000,out=recording.ts
sdrangelbench -t dvbs2mod -a in=stream.ts,out=dvbs2_qo100,sr=333000,modcod=qpsk3/4,centre=10491500000
sdrangelbench -t dvbs2 -a modcod=8psk2/3,sr=1000000,offset=0.5,cfo=20000,ppm=30
sdrangelbench -t dvbs2 -a noself=1,modcod=qpsk1/4,tsn=17/33,mis=1,ro=0.05,conj=1
sdrangelbench -t dvbs2 -a noself=1,modcod=vl4,offset=1,gaps=2
sdrangelbench -t dvbs2 -a fectest
sdrangelbench -t dvbs -a rate=7/8,ebn0=6
dvbsref and dvbs2ref check that signals generated by the DATV modulator's DVB-S and DVB-S2 encoders are decoded.
datvcmp compares these receivers with the [DATV demodulator](../demoddatv/readme.md)'s on the same simulated signal: the packets each decodes
against Es/N0, and the time and CPU each takes. std is s or s2, the mode as for dvbs and dvbs2, and snrs the Es/N0s, from:to:step:
sdrangelbench -t datvcmp -a std=s,rate=3/4,snrs=4:9:0.5
sdrangelbench -t datvcmp -a std=s2,modcod=8psk2/3,snrs=6:11:0.5
In a Gaussian channel, these receivers decode DVB-S 2.5 to 3.5 dB lower than the DATV demodulator with its best settings (soft Viterbi),
and DVB-S2 1 to 2.5 dB lower with pilots (its soft LDPC) and about 4 dB lower without, locking sooner, with a tenth or less of the CPU.
The DATV demodulator can't keep up with DVB-S above about 1.6 MS/s with soft Viterbi.

20
sdrbase/CMakeLists.txt

@ -184,6 +184,16 @@ set(sdrbase_SOURCES @@ -184,6 +184,16 @@ set(sdrbase_SOURCES
dsp/spectrumvis.cpp
dsp/wavfilerecord.cpp
dtv/dtvapps.cpp
dtv/dtvcarousel.cpp
dtv/dtvcarouselserver.cpp
dtv/dtvguide.cpp
dtv/dtvpsi.cpp
dtv/dtvrecorder.cpp
dtv/dtvsections.cpp
dtv/dtvtsfifo.cpp
dtv/dtvudp.cpp
device/deviceapi.cpp
device/deviceenumerator.cpp
device/deviceset.cpp
@ -448,6 +458,16 @@ set(sdrbase_HEADERS @@ -448,6 +458,16 @@ set(sdrbase_HEADERS
dsp/spectrumvis.h
dsp/wavfilerecord.h
dtv/dtvapps.h
dtv/dtvcarousel.h
dtv/dtvcarouselserver.h
dtv/dtvguide.h
dtv/dtvpsi.h
dtv/dtvrecorder.h
dtv/dtvsections.h
dtv/dtvtsfifo.h
dtv/dtvudp.h
device/deviceapi.h
device/deviceenumerator.h
device/deviceset.h

964
sdrbase/dtv/dtvapps.cpp

@ -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>();
}

181
sdrbase/dtv/dtvapps.h

@ -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

784
sdrbase/dtv/dtvcarousel.cpp

@ -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;
}

150
sdrbase/dtv/dtvcarousel.h

@ -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

500
sdrbase/dtv/dtvcarouselserver.cpp

@ -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();
}

98
sdrbase/dtv/dtvcarouselserver.h

@ -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

59
sdrbase/dtv/dtvguide.cpp

@ -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]);
}

215
sdrbase/dtv/dtvguide.h

@ -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

21
plugins/channelrx/demoddvb/dvbdemodpsi.cpp → sdrbase/dtv/dtvpsi.cpp

@ -1,5 +1,6 @@ @@ -1,5 +1,6 @@
///////////////////////////////////////////////////////////////////////////////////
// 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 //
@ -17,15 +18,15 @@ @@ -17,15 +18,15 @@
#include <algorithm>
#include "dvbdemodpsi.h"
#include "dvbdemodsections.h"
#include "dtv/dtvpsi.h"
#include "dtv/dtvsections.h"
DVBDemodPSI::DVBDemodPSI() :
DTVPSI::DTVPSI() :
m_transportStreamId(-1)
{
}
void DVBDemodPSI::reset()
void DTVPSI::reset()
{
m_partial.clear();
m_pat.reset();
@ -34,14 +35,14 @@ void DVBDemodPSI::reset() @@ -34,14 +35,14 @@ void DVBDemodPSI::reset()
m_channels.clear();
}
const std::map<int, int>& DVBDemodPSI::getChannels() const
const std::map<int, int>& DTVPSI::getChannels() const
{
static const std::map<int, int> none;
auto it = m_channels.find(m_transportStreamId);
return it != m_channels.end() ? it->second : none;
}
void DVBDemodPSI::feed(const uint8_t *data, int length)
void DTVPSI::feed(const uint8_t *data, int length)
{
// Complete a packet split between feeds
if (!m_partial.empty())
@ -83,7 +84,7 @@ void DVBDemodPSI::feed(const uint8_t *data, int length) @@ -83,7 +84,7 @@ void DVBDemodPSI::feed(const uint8_t *data, int length)
}
}
void DVBDemodPSI::packet(const uint8_t *p)
void DTVPSI::packet(const uint8_t *p)
{
if (p[1] & 0x80) { // Uncorrectable errors
return;
@ -100,7 +101,7 @@ void DVBDemodPSI::packet(const uint8_t *p) @@ -100,7 +101,7 @@ void DVBDemodPSI::packet(const uint8_t *p)
}
}
void DVBDemodPSI::section(const uint8_t *s, int length)
void DTVPSI::section(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)) {
@ -115,14 +116,14 @@ void DVBDemodPSI::section(const uint8_t *s, int length) @@ -115,14 +116,14 @@ void DVBDemodPSI::section(const uint8_t *s, int length)
}
// program_association_section (ISO/IEC 13818-1 2.4.4.3): the transport stream id
void DVBDemodPSI::pat(const uint8_t *s, int length)
void DTVPSI::pat(const uint8_t *s, int length)
{
(void) length;
m_transportStreamId = (s[3] << 8) | s[4];
}
// network_information_section (EN 300 468 5.2.1), with logical_channel_descriptors in the transport stream loop
void DVBDemodPSI::nit(const uint8_t *s, int length)
void DTVPSI::nit(const uint8_t *s, int length)
{
if (length < 16) {
return;

18
plugins/channelrx/demoddvb/dvbdemodpsi.h → sdrbase/dtv/dtvpsi.h

@ -1,5 +1,6 @@ @@ -1,5 +1,6 @@
///////////////////////////////////////////////////////////////////////////////////
// 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 //
@ -15,23 +16,24 @@ @@ -15,23 +16,24 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_DVBDEMODPSI_H
#define INCLUDE_DVBDEMODPSI_H
#ifndef INCLUDE_DTVPSI_H
#define INCLUDE_DTVPSI_H
#include <cstdint>
#include <map>
#include <vector>
#include "dvbdemodsections.h"
#include "export.h"
#include "dtv/dtvsections.h"
// What FFmpeg doesn't give of the transport stream's tables: the transport stream id, from the PAT, which changes
// with the multiplex, and the logical channel numbers of services (the numbers viewers select them by), from the
// logical channel descriptors (tag 0x83, as used in the UK, Europe and Australia) in the NIT. Fed with the
// transport stream, in any size pieces
class DVBDemodPSI
class SDRBASE_API DTVPSI
{
public:
DVBDemodPSI();
DTVPSI();
void reset(); //!< For a new stream: forgets everything
void feed(const uint8_t *data, int length);
//! -1 until the PAT has been received
@ -52,10 +54,10 @@ private: @@ -52,10 +54,10 @@ private:
void nit(const uint8_t *data, int length);
std::vector<uint8_t> m_partial; //!< Of a TS packet split between feeds
DVBDemodSectionAssembler m_pat;
DVBDemodSectionAssembler m_nit;
DTVSectionAssembler m_pat;
DTVSectionAssembler m_nit;
int m_transportStreamId;
std::map<int, std::map<int, int>> m_channels; //!< By transport stream id (the NIT's): service id to number
};
#endif // INCLUDE_DVBDEMODPSI_H
#endif // INCLUDE_DTVPSI_H

42
plugins/channelrx/demoddvb/dvbdemodrecorder.cpp → sdrbase/dtv/dtvrecorder.cpp

@ -21,9 +21,9 @@ @@ -21,9 +21,9 @@
#include <QDir>
#include <QFileInfo>
#include "dvbdemodrecorder.h"
#include "dtv/dtvrecorder.h"
DVBDemodRecorder::DVBDemodRecorder() :
DTVRecorder::DTVRecorder() :
m_mode(Multiplex),
m_serviceId(0),
m_started(false),
@ -41,14 +41,15 @@ DVBDemodRecorder::DVBDemodRecorder() : @@ -41,14 +41,15 @@ DVBDemodRecorder::DVBDemodRecorder() :
m_dropped(0),
m_running(false)
{
setSystemPids({0x0011, 0x0014}); // DVB's SDT, and TDT and TOT
}
DVBDemodRecorder::~DVBDemodRecorder()
DTVRecorder::~DTVRecorder()
{
stop();
}
bool DVBDemodRecorder::start(const QString& fileName, Mode mode, int serviceId, QString& error)
bool DTVRecorder::start(const QString& fileName, Mode mode, int serviceId, QString& error)
{
stop();
QDir().mkpath(QFileInfo(fileName).absolutePath());
@ -84,11 +85,11 @@ bool DVBDemodRecorder::start(const QString& fileName, Mode mode, int serviceId, @@ -84,11 +85,11 @@ bool DVBDemodRecorder::start(const QString& fileName, Mode mode, int serviceId,
m_error.clear();
m_timer.start();
m_running = true;
m_thread = std::thread(&DVBDemodRecorder::writer, this);
m_thread = std::thread(&DTVRecorder::writer, this);
return true;
}
void DVBDemodRecorder::stop()
void DTVRecorder::stop()
{
if (!m_running) {
return;
@ -113,7 +114,7 @@ void DVBDemodRecorder::stop() @@ -113,7 +114,7 @@ void DVBDemodRecorder::stop()
m_running = false;
}
DVBDemodRecorder::Status DVBDemodRecorder::getStatus() const
DTVRecorder::Status DTVRecorder::getStatus() const
{
std::lock_guard<std::mutex> lock(m_mutex);
Status status;
@ -127,7 +128,7 @@ DVBDemodRecorder::Status DVBDemodRecorder::getStatus() const @@ -127,7 +128,7 @@ DVBDemodRecorder::Status DVBDemodRecorder::getStatus() const
}
// Writes queued blocks until stopped, then what's left
void DVBDemodRecorder::writer()
void DTVRecorder::writer()
{
while (true)
{
@ -159,7 +160,7 @@ void DVBDemodRecorder::writer() @@ -159,7 +160,7 @@ void DVBDemodRecorder::writer()
}
// A packet to record, queued a block at a time
void DVBDemodRecorder::write(const uint8_t *packet)
void DTVRecorder::write(const uint8_t *packet)
{
m_block.insert(m_block.end(), packet, packet + 188);
@ -186,7 +187,7 @@ void DVBDemodRecorder::write(const uint8_t *packet) @@ -186,7 +187,7 @@ void DVBDemodRecorder::write(const uint8_t *packet)
m_available.notify_one();
}
void DVBDemodRecorder::feed(const uint8_t *p)
void DTVRecorder::feed(const uint8_t *p)
{
if (!m_running || (p[0] != 0x47)) {
return;
@ -229,7 +230,7 @@ void DVBDemodRecorder::feed(const uint8_t *p) @@ -229,7 +230,7 @@ void DVBDemodRecorder::feed(const uint8_t *p)
return;
}
if (m_started && (m_pids.test(pid) || (pid == m_sdtPid) || (pid == m_timePid))) {
if (m_started && (m_pids.test(pid) || m_systemPids.test(pid))) {
write(p);
}
}
@ -237,7 +238,16 @@ void DVBDemodRecorder::feed(const uint8_t *p) @@ -237,7 +238,16 @@ void DVBDemodRecorder::feed(const uint8_t *p)
// program_association_section (ISO/IEC 13818-1 2.4.4.3): the service's PMT PID. In another transport stream (the
// device retuned while recording), the service's PMT PID and version can be the same as before but its streams not:
// its state's forgotten, so its PMT there is read, and if it's not there, nothing more of it is recorded
void DVBDemodRecorder::pat(const uint8_t *s, int length)
void DTVRecorder::setSystemPids(const std::vector<int>& pids)
{
m_systemPids.reset();
for (int pid : pids) {
m_systemPids.set(pid & 0x1FFF);
}
}
void DTVRecorder::pat(const uint8_t *s, int length)
{
// With section_syntax_indicator set, so its CRC was checked; current, not one to apply next
if ((s[0] != 0x00) || !(s[1] & 0x80) || !(s[5] & 0x01) || (length < 12)) {
@ -302,7 +312,7 @@ void DVBDemodRecorder::pat(const uint8_t *s, int length) @@ -302,7 +312,7 @@ void DVBDemodRecorder::pat(const uint8_t *s, int length)
}
}
void DVBDemodRecorder::forgetService()
void DTVRecorder::forgetService()
{
m_pids.reset();
m_pmtPid = -1;
@ -312,7 +322,7 @@ void DVBDemodRecorder::forgetService() @@ -312,7 +322,7 @@ void DVBDemodRecorder::forgetService()
}
// TS_program_map_section (2.4.4.8): the PCR PID and elementary stream PIDs
void DVBDemodRecorder::pmt(const uint8_t *s, int length)
void DTVRecorder::pmt(const uint8_t *s, int length)
{
// Current, not one to apply next: its streams aren't sent yet
if ((s[0] != 0x02) || !(s[1] & 0x80) || !(s[5] & 0x01) || (length < 16) || ((((s[3] << 8) | s[4])) != m_serviceId)) {
@ -353,7 +363,7 @@ void DVBDemodRecorder::pmt(const uint8_t *s, int length) @@ -353,7 +363,7 @@ void DVBDemodRecorder::pmt(const uint8_t *s, int length)
}
// A PAT with just the service (and its CRC), in one packet
void DVBDemodRecorder::writePAT()
void DTVRecorder::writePAT()
{
uint8_t packet[188];
std::fill(packet, packet + 188, 0xFF);
@ -378,7 +388,7 @@ void DVBDemodRecorder::writePAT() @@ -378,7 +388,7 @@ void DVBDemodRecorder::writePAT()
s[9] = m_serviceId & 0xFF;
s[10] = 0xE0 | ((m_pmtPid >> 8) & 0x1F);
s[11] = m_pmtPid & 0xFF;
const uint32_t crc = dvbSectionCRC(s, 12);
const uint32_t crc = dtvSectionCRC(s, 12);
s[12] = (crc >> 24) & 0xFF;
s[13] = (crc >> 16) & 0xFF;
s[14] = (crc >> 8) & 0xFF;

28
plugins/channelrx/demoddvb/dvbdemodrecorder.h → sdrbase/dtv/dtvrecorder.h

@ -16,8 +16,8 @@ @@ -16,8 +16,8 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_DVBDEMODRECORDER_H
#define INCLUDE_DVBDEMODRECORDER_H
#ifndef INCLUDE_DTVRECORDER_H
#define INCLUDE_DTVRECORDER_H
#include <atomic>
#include <bitset>
@ -32,14 +32,16 @@ @@ -32,14 +32,16 @@
#include <QFile>
#include <QString>
#include "dvbdemodsections.h"
#include "export.h"
#include "dtv/dtvsections.h"
// Records the transport stream to a .ts file: the whole multiplex, or one service. A service's recording has its
// PMT, elementary streams (video, every audio track, subtitles, teletext, but not interactive data) and PCR, the SDT and time tables, and a
// PMT, elementary streams (video, every audio track, subtitles, teletext, but not interactive data) and PCR, the system's
// tables (setSystemPids(): DVB's SDT and time tables by default), and a
// PAT rewritten to list only it, so players don't offer services that aren't there. It starts at a PAT (once the
// service's PMT is known), so the file can be played from its start. Fed with packets in the demodulator's thread;
// the file is written in a thread of its own, so a slow disk never holds up demodulation (data is dropped instead)
class DVBDemodRecorder
class SDRBASE_API DTVRecorder
{
public:
enum Mode { Multiplex = 0, Service = 1 };
@ -54,9 +56,12 @@ public: @@ -54,9 +56,12 @@ public:
QString m_error;
};
DVBDemodRecorder();
~DVBDemodRecorder(); //!< Stops, if recording
DTVRecorder();
~DTVRecorder(); //!< Stops, if recording
//! The PIDs of the system's tables recorded with a service: DVB's SDT and TDT (0x11, 0x14) unless set (ATSC's
//! PSIP base PID, 0x1FFB). Before start()
void setSystemPids(const std::vector<int>& pids);
//! False with the error if the file can't be created
bool start(const QString& fileName, Mode mode, int serviceId, QString& error);
void stop();
@ -65,8 +70,6 @@ public: @@ -65,8 +70,6 @@ public:
private:
static constexpr int m_patPid = 0x0000;
static constexpr int m_sdtPid = 0x0011;
static constexpr int m_timePid = 0x0014;
static constexpr size_t m_blockSize = 188 * 512; // Packets are queued for the writer this many bytes at a time
static constexpr size_t m_maxQueued = 64 * 1024 * 1024; // Beyond which data is dropped, rather than wait for the disk
@ -80,12 +83,13 @@ private: @@ -80,12 +83,13 @@ private:
Mode m_mode;
int m_serviceId;
bool m_started; //!< Writing: from the first PAT, once the PMT is known
DVBDemodSectionAssembler m_patSections;
DVBDemodSectionAssembler m_pmtSections;
DTVSectionAssembler m_patSections;
DTVSectionAssembler m_pmtSections;
int m_transportStreamId;
int m_pmtPid; //!< Of the service, -1 until known
int m_pmtVersion;
std::bitset<8192> m_pids; //!< Recorded
std::bitset<8192> m_systemPids; //!< Also recorded, with a service
int m_patContinuity;
int m_patVersion; //!< Of the PAT written
// The PAT received's current version, as its sections come: once all have, whether the service is in it
@ -113,4 +117,4 @@ private: @@ -113,4 +117,4 @@ private:
bool m_running;
};
#endif // INCLUDE_DVBDEMODRECORDER_H
#endif // INCLUDE_DTVRECORDER_H

18
plugins/channelrx/demoddvb/dvbdemodsections.cpp → sdrbase/dtv/dtvsections.cpp

@ -18,9 +18,9 @@ @@ -18,9 +18,9 @@
#include <cstring>
#include "dvbdemodsections.h"
#include "dtv/dtvsections.h"
struct DVBDemodSectionCRC::CRCTable
struct DTVSectionCRC::CRCTable
{
uint32_t m_table[256];
@ -39,20 +39,20 @@ struct DVBDemodSectionCRC::CRCTable @@ -39,20 +39,20 @@ struct DVBDemodSectionCRC::CRCTable
}
};
const DVBDemodSectionCRC::CRCTable DVBDemodSectionCRC::m_crcTable; // Built before use from any thread
const DTVSectionCRC::CRCTable DTVSectionCRC::m_crcTable; // Built before use from any thread
uint32_t dvbSectionCRC(const uint8_t *data, int length)
uint32_t dtvSectionCRC(const uint8_t *data, int length)
{
uint32_t crc = 0xFFFFFFFF;
for (int i = 0; i < length; i++) {
crc = (crc << 8) ^ DVBDemodSectionCRC::m_crcTable.m_table[((crc >> 24) ^ data[i]) & 0xFF];
crc = (crc << 8) ^ DTVSectionCRC::m_crcTable.m_table[((crc >> 24) ^ data[i]) & 0xFF];
}
return crc;
}
void DVBDemodSectionAssembler::reset()
void DTVSectionAssembler::reset()
{
m_data.clear();
m_inSection = false;
@ -62,17 +62,17 @@ void DVBDemodSectionAssembler::reset() @@ -62,17 +62,17 @@ void DVBDemodSectionAssembler::reset()
// A complete section, if there's enough data: passed on if its CRC is correct. Sections with the long form
// (section_syntax_indicator 1) have a CRC, and of the short form only the TOT (0x73): the TDT (0x70), RST, ST and DIT
// don't (EN 300 468 5.2.5)
void DVBDemodSectionAssembler::complete(const SectionCallback& callback)
void DTVSectionAssembler::complete(const SectionCallback& callback)
{
const int length = 3 + (((m_data[1] & 0x0F) << 8) | m_data[2]);
const bool hasCRC = (m_data[1] & 0x80) || (m_data[0] == 0x73);
if ((length >= 7) && (!hasCRC || (dvbSectionCRC(m_data.data(), length) == 0))) {
if ((length >= 7) && (!hasCRC || (dtvSectionCRC(m_data.data(), length) == 0))) {
callback(m_data.data(), length);
}
}
void DVBDemodSectionAssembler::packet(const uint8_t *p, const SectionCallback& callback)
void DTVSectionAssembler::packet(const uint8_t *p, const SectionCallback& callback)
{
const bool start = (p[1] & 0x40) != 0;
const int adaptation = (p[3] >> 4) & 3;

18
plugins/channelrx/demoddvb/dvbdemodsections.h → sdrbase/dtv/dtvsections.h

@ -16,29 +16,31 @@ @@ -16,29 +16,31 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_DVBDEMODSECTIONS_H
#define INCLUDE_DVBDEMODSECTIONS_H
#ifndef INCLUDE_DTVSECTIONS_H
#define INCLUDE_DTVSECTIONS_H
#include <cstdint>
#include <functional>
#include <vector>
#include "export.h"
//! CRC-32/MPEG-2 of PSI/SI sections: 0 over a section including its CRC, if it's correct
uint32_t dvbSectionCRC(const uint8_t *data, int length);
SDRBASE_API uint32_t dtvSectionCRC(const uint8_t *data, int length);
//! dvbSectionCRC()'s table
class DVBDemodSectionCRC
//! dtvSectionCRC()'s table
class DTVSectionCRC
{
private:
struct CRCTable;
static const CRCTable m_crcTable;
friend uint32_t dvbSectionCRC(const uint8_t *data, int length);
friend SDRBASE_API uint32_t dtvSectionCRC(const uint8_t *data, int length);
};
//! Assembles the sections (ISO/IEC 13818-1 2.4.4) carried by one PID's transport stream packets
class DVBDemodSectionAssembler
class SDRBASE_API DTVSectionAssembler
{
public:
//! Called with each complete section whose CRC is correct, or that has none: sections with the short form
@ -58,4 +60,4 @@ private: @@ -58,4 +60,4 @@ private:
uint8_t m_last[188]; //!< The last packet, to recognise a duplicate of it
};
#endif // INCLUDE_DVBDEMODSECTIONS_H
#endif // INCLUDE_DTVSECTIONS_H

30
plugins/channelrx/demoddvb/dvbdemodtsfifo.cpp → sdrbase/dtv/dtvtsfifo.cpp

@ -23,9 +23,9 @@ @@ -23,9 +23,9 @@
#include "util/profiler.h"
#include "dvbdemodtsfifo.h"
#include "dtv/dtvtsfifo.h"
DVBDemodTSFifo::DVBDemodTSFifo(int size, bool needsReader) :
DTVTSFifo::DTVTSFifo(int size, bool needsReader) :
m_size((size_t) std::max(188, size)),
m_readPos(0),
m_writePos(0),
@ -39,7 +39,7 @@ DVBDemodTSFifo::DVBDemodTSFifo(int size, bool needsReader) : @@ -39,7 +39,7 @@ DVBDemodTSFifo::DVBDemodTSFifo(int size, bool needsReader) :
}
}
void DVBDemodTSFifo::attachLocked()
void DTVTSFifo::attachLocked()
{
if (m_buffer.size() != m_size) {
m_buffer.resize(m_size);
@ -52,7 +52,7 @@ void DVBDemodTSFifo::attachLocked() @@ -52,7 +52,7 @@ void DVBDemodTSFifo::attachLocked()
m_accepting = true;
}
void DVBDemodTSFifo::detachLocked()
void DTVTSFifo::detachLocked()
{
if (!m_needsReader) {
return;
@ -65,20 +65,20 @@ void DVBDemodTSFifo::detachLocked() @@ -65,20 +65,20 @@ void DVBDemodTSFifo::detachLocked()
std::vector<uint8_t>().swap(m_buffer);
}
void DVBDemodTSFifo::attachReader()
void DTVTSFifo::attachReader()
{
QMutexLocker locker(&m_mutex);
attachLocked();
}
void DVBDemodTSFifo::detachReader()
void DTVTSFifo::detachReader()
{
QMutexLocker locker(&m_mutex);
detachLocked();
m_dataAvailable.wakeAll();
}
void DVBDemodTSFifo::write(const uint8_t *data, int length)
void DTVTSFifo::write(const uint8_t *data, int length)
{
if (!isAccepting() || (length <= 0)) {
return;
@ -88,7 +88,7 @@ void DVBDemodTSFifo::write(const uint8_t *data, int length) @@ -88,7 +88,7 @@ void DVBDemodTSFifo::write(const uint8_t *data, int length)
writeLocked(data, length);
}
void DVBDemodTSFifo::writePackets(const uint8_t *packets, int count)
void DTVTSFifo::writePackets(const uint8_t *packets, int count)
{
if (!isAccepting() || (count <= 0)) {
return;
@ -107,7 +107,7 @@ void DVBDemodTSFifo::writePackets(const uint8_t *packets, int count) @@ -107,7 +107,7 @@ void DVBDemodTSFifo::writePackets(const uint8_t *packets, int count)
}
}
void DVBDemodTSFifo::writeLocked(const uint8_t *data, int length)
void DTVTSFifo::writeLocked(const uint8_t *data, int length)
{
if (m_buffer.empty()) {
return; // Detached meanwhile
@ -119,11 +119,11 @@ void DVBDemodTSFifo::writeLocked(const uint8_t *data, int length) @@ -119,11 +119,11 @@ void DVBDemodTSFifo::writeLocked(const uint8_t *data, int length)
if ((size_t) length > free)
{
m_overflows += length;
PROFILER_ADD("DVBDemod TS FIFO overflow (count = writes dropping data)", 0)
PROFILER_ADD("DTV TS FIFO overflow (count = writes dropping data)", 0)
if (m_needsReader && m_sinceRead.isValid() && (m_sinceRead.elapsed() > m_readerGoneMs))
{
qDebug("DVBDemodTSFifo::writeLocked: nothing read for %lld s: no reader", (long long) (m_sinceRead.elapsed() / 1000));
qDebug("DTVTSFifo::writeLocked: nothing read for %lld s: no reader", (long long) (m_sinceRead.elapsed() / 1000));
detachLocked();
}
@ -138,7 +138,7 @@ void DVBDemodTSFifo::writeLocked(const uint8_t *data, int length) @@ -138,7 +138,7 @@ void DVBDemodTSFifo::writeLocked(const uint8_t *data, int length)
m_dataAvailable.wakeAll();
}
int DVBDemodTSFifo::read(uint8_t *data, int length, int timeoutMs)
int DTVTSFifo::read(uint8_t *data, int length, int timeoutMs)
{
QMutexLocker locker(&m_mutex);
@ -168,7 +168,7 @@ int DVBDemodTSFifo::read(uint8_t *data, int length, int timeoutMs) @@ -168,7 +168,7 @@ int DVBDemodTSFifo::read(uint8_t *data, int length, int timeoutMs)
return length;
}
void DVBDemodTSFifo::reset()
void DTVTSFifo::reset()
{
QMutexLocker locker(&m_mutex);
m_readPos = 0;
@ -176,13 +176,13 @@ void DVBDemodTSFifo::reset() @@ -176,13 +176,13 @@ void DVBDemodTSFifo::reset()
m_fill = 0;
}
int DVBDemodTSFifo::fill()
int DTVTSFifo::fill()
{
QMutexLocker locker(&m_mutex);
return (int) m_fill;
}
uint64_t DVBDemodTSFifo::getOverflows()
uint64_t DTVTSFifo::getOverflows()
{
QMutexLocker locker(&m_mutex);
return m_overflows;

13
plugins/channelrx/demoddvb/dvbdemodtsfifo.h → sdrbase/dtv/dtvtsfifo.h

@ -16,8 +16,8 @@ @@ -16,8 +16,8 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_DVBDEMODTSFIFO_H
#define INCLUDE_DVBDEMODTSFIFO_H
#ifndef INCLUDE_DTVTSFIFO_H
#define INCLUDE_DTVTSFIFO_H
#include <atomic>
#include <cstdint>
@ -26,16 +26,17 @@ @@ -26,16 +26,17 @@
#include <QElapsedTimer>
#include <QMutex>
#include <QWaitCondition>
#include "export.h"
// Transport stream bytes from the demodulator to the video player, which may run in different threads.
// Transport stream bytes from a demodulator (DVB, ATSC) to the video player, which may run in different threads.
// Data that doesn't fit is dropped, as the demodulator must never wait
// With needsReader, as the demodulator's is (in a server build nothing reads it), nothing's kept, and the buffer isn't
// allocated, until a reader attaches (attachReader(), or its first read()); it's detached by detachReader(), or when
// nothing's been read for a long while (a reader gone without detaching)
class DVBDemodTSFifo
class SDRBASE_API DTVTSFifo
{
public:
explicit DVBDemodTSFifo(int size = 8 * 1024 * 1024, bool needsReader = false);
explicit DTVTSFifo(int size = 8 * 1024 * 1024, bool needsReader = false);
void write(const uint8_t *data, int length);
//! Whole 188-byte packets: as many as fit, the rest dropped
@ -73,4 +74,4 @@ private: @@ -73,4 +74,4 @@ private:
QElapsedTimer m_sinceRead; //!< With needsReader: since the reader last read
};
#endif // INCLUDE_DVBDEMODTSFIFO_H
#endif // INCLUDE_DTVTSFIFO_H

20
plugins/channelrx/demoddvb/dvbdemodudp.cpp → sdrbase/dtv/dtvudp.cpp

@ -21,9 +21,9 @@ @@ -21,9 +21,9 @@
#include <QDebug>
#include <QHostInfo>
#include "dvbdemodudp.h"
#include "dtv/dtvudp.h"
DVBDemodUDP::DVBDemodUDP() :
DTVUDP::DTVUDP() :
m_port(5004),
m_datagramFill(0),
m_datagrams(0),
@ -34,7 +34,7 @@ DVBDemodUDP::DVBDemodUDP() : @@ -34,7 +34,7 @@ DVBDemodUDP::DVBDemodUDP() :
{
}
DVBDemodUDP::~DVBDemodUDP()
DTVUDP::~DTVUDP()
{
{
std::lock_guard<std::mutex> lock(m_mutex);
@ -48,7 +48,7 @@ DVBDemodUDP::~DVBDemodUDP() @@ -48,7 +48,7 @@ DVBDemodUDP::~DVBDemodUDP()
}
}
void DVBDemodUDP::setDestination(const QString& address, uint16_t port)
void DTVUDP::setDestination(const QString& address, uint16_t port)
{
if ((address == m_name) && (port == m_port)) {
return; // As forced settings set it again
@ -79,13 +79,13 @@ void DVBDemodUDP::setDestination(const QString& address, uint16_t port) @@ -79,13 +79,13 @@ void DVBDemodUDP::setDestination(const QString& address, uint16_t port)
m_lookupGeneration = m_generation;
if (!m_lookupThread.joinable()) {
m_lookupThread = std::thread(&DVBDemodUDP::lookup, this);
m_lookupThread = std::thread(&DTVUDP::lookup, this);
} else {
m_lookupWake.notify_one();
}
}
void DVBDemodUDP::lookup()
void DTVUDP::lookup()
{
std::unique_lock<std::mutex> lock(m_mutex);
@ -106,7 +106,7 @@ void DVBDemodUDP::lookup() @@ -106,7 +106,7 @@ void DVBDemodUDP::lookup()
const QHostAddress found = info.addresses().isEmpty() ? QHostAddress() : info.addresses().first();
if (found.isNull()) {
qWarning() << "DVBDemodUDP::lookup: can't find" << name;
qWarning() << "DTVUDP::lookup: can't find" << name;
}
lock.lock();
@ -117,12 +117,12 @@ void DVBDemodUDP::lookup() @@ -117,12 +117,12 @@ void DVBDemodUDP::lookup()
}
}
void DVBDemodUDP::write(const uint8_t *packet)
void DTVUDP::write(const uint8_t *packet)
{
writePackets(packet, 1);
}
void DVBDemodUDP::writePackets(const uint8_t *packets, int count)
void DTVUDP::writePackets(const uint8_t *packets, int count)
{
for (int i = 0; i < count; i++)
{
@ -135,7 +135,7 @@ void DVBDemodUDP::writePackets(const uint8_t *packets, int count) @@ -135,7 +135,7 @@ void DVBDemodUDP::writePackets(const uint8_t *packets, int count)
}
}
void DVBDemodUDP::send()
void DTVUDP::send()
{
m_datagramFill = 0;

13
plugins/channelrx/demoddvb/dvbdemodudp.h → sdrbase/dtv/dtvudp.h

@ -16,8 +16,8 @@ @@ -16,8 +16,8 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_DVBDEMODUDP_H
#define INCLUDE_DVBDEMODUDP_H
#ifndef INCLUDE_DTVUDP_H
#define INCLUDE_DTVUDP_H
#include <atomic>
#include <condition_variable>
@ -29,14 +29,15 @@ @@ -29,14 +29,15 @@
#include <QHostAddress>
#include <QString>
#include <QUdpSocket>
#include "export.h"
// Sends transport stream packets over UDP, 7 to a datagram, as VLC and ffplay expect for udp:// URLs. Used in the
// demodulator's thread, where the socket is made, as a socket belongs to the thread that made it
class DVBDemodUDP
class SDRBASE_API DTVUDP
{
public:
DVBDemodUDP();
~DVBDemodUDP(); //!< Waits for a host name lookup under way
DTVUDP();
~DTVUDP(); //!< Waits for a host name lookup under way
//! address: an IP address, or a host name, looked up in a thread of its own (a lookup can take seconds, which
//! would hold up demodulation): nothing's sent until it's found. The same name again isn't looked up again.
@ -73,4 +74,4 @@ private: @@ -73,4 +74,4 @@ private:
std::thread m_lookupThread; //!< Started for the first host name
};
#endif // INCLUDE_DVBDEMODUDP_H
#endif // INCLUDE_DTVUDP_H

66
sdrbase/resources/webapi/doc/swagger/include/DVBDemod.yaml

@ -74,6 +74,11 @@ DVBDemodSettings: @@ -74,6 +74,11 @@ DVBDemodSettings:
type: integer
minimum: 0
maximum: 1
hbbtv:
description: "Run the service's HbbTV applications (the red button) over the video, in the GUI (1 for yes, 0 for no)."
type: integer
minimum: 0
maximum: 1
avOffset:
description: "Milliseconds to delay the picture relative to the sound, for lip sync. Negative to show it earlier."
type: integer
@ -364,6 +369,16 @@ DVBDemodReport: @@ -364,6 +369,16 @@ DVBDemodReport:
description: "A service's schedule, in order, from an hour ago, when epgReport is 2."
items:
$ref: "/doc/swagger/include/DVBDemod.yaml#/DVBDemodEPGEvent"
interactiveApps:
type: array
description: "The interactive applications (HbbTV's and others, from the AIT) of the service the report's of."
items:
$ref: "/doc/swagger/include/DVBDemod.yaml#/DVBDemodApp"
carousels:
type: array
description: "The object carousels (MHEG-5's and HbbTV's) of the service the report's of, and how much of each has been received."
items:
$ref: "/doc/swagger/include/DVBDemod.yaml#/DVBDemodCarousel"
recording:
type: integer
description: Number of recordings in progress
@ -484,6 +499,57 @@ DVBDemodActions: @@ -484,6 +499,57 @@ DVBDemodActions:
format: int64
description: "Downlink frequency, Hz, the scan ends at."
DVBDemodApp:
description: An interactive application of a service, from its application information table (AIT)
properties:
applicationId:
type: string
description: "organisation_id.application_id, in hex."
type:
type: string
description: "HbbTV, DVB-J, DVB-HTML, or the application_type in hex."
controlCode:
type: string
description: "AUTOSTART (started with the service), PRESENT (started by the user, as from the red button), KILL..."
name:
type: string
url:
type: string
description: "Where it starts: an HTTP URL, or a dvb: URL of a file in an object carousel."
carouselPid:
type: integer
description: "PID of the object carousel it's in, -1 if it isn't in one of this service's."
DVBDemodCarousel:
description: An object carousel of a service
properties:
pid:
type: integer
componentTag:
type: integer
carouselId:
type: integer
format: int64
kind:
type: string
description: "MHEG-5, HbbTV (or both, as a broadcaster may send them in one carousel), or DSM-CC."
received:
type: integer
description: "1 if its DSI has been received, so it's being received."
modules:
type: integer
modulesComplete:
type: integer
bytes:
type: integer
format: int64
bytesComplete:
type: integer
format: int64
files:
type: integer
description: "Files received."
DVBDemodEPGService:
description: A service in the DVB programme guide
properties:

60
sdrgui/CMakeLists.txt

@ -123,6 +123,12 @@ set(sdrgui_SOURCES @@ -123,6 +123,12 @@ set(sdrgui_SOURCES
dsp/scopevisxy.cpp
dtv/dtvappsdialog.cpp
dtv/dtvepgdialog.cpp
dtv/dtvepggrid.cpp
dtv/dtvguideoverlay.cpp
dtv/dtvscope.cpp
device/devicegui.cpp
device/deviceuiset.cpp
@ -268,6 +274,12 @@ set(sdrgui_HEADERS @@ -268,6 +274,12 @@ set(sdrgui_HEADERS
dsp/scopevisxy.h
dtv/dtvappsdialog.h
dtv/dtvepgdialog.h
dtv/dtvepggrid.h
dtv/dtvguideoverlay.h
dtv/dtvscope.h
device/devicegui.h
device/deviceuiset.h
@ -341,6 +353,40 @@ set(sdrgui_FORMS @@ -341,6 +353,40 @@ set(sdrgui_FORMS
qt_wrap_ui(sdrgui_FORMS_HEADERS ${sdrgui_FORMS})
# Digital TV's video player (DVB and ATSC demodulators): FFmpeg demultiplexes and decodes the transport stream
if(NOT FFMPEG_FOUND)
find_package(FFmpeg COMPONENTS AVCODEC AVFORMAT AVUTIL SWSCALE)
endif()
if(FFMPEG_FOUND)
set(sdrgui_SOURCES ${sdrgui_SOURCES} dtv/dtvvideoplayer.cpp dtv/dtvstreamremuxer.cpp dtv/dtvstreamplayback.cpp)
set(sdrgui_HEADERS ${sdrgui_HEADERS} dtv/dtvvideoplayer.h dtv/dtvstreamremuxer.h dtv/dtvstreamplayback.h)
set(sdrgui_DTV_INCLUDE_DIRS
${AVCODEC_INCLUDE_DIRS}
${AVFORMAT_INCLUDE_DIRS}
${AVUTIL_INCLUDE_DIRS}
${SWSCALE_INCLUDE_DIRS}
${SWRESAMPLE_INCLUDE_DIRS}
)
set(sdrgui_DTV_LIBRARIES ${AVCODEC_LIBRARIES} ${AVFORMAT_LIBRARIES} ${AVUTIL_LIBRARIES} ${SWSCALE_LIBRARIES} ${SWRESAMPLE_LIBRARIES})
# Deinterlacing uses libavfilter, if available
if(NOT AVFILTER_LIBRARIES)
find_library(DTV_AVFILTER_LIBRARY NAMES avfilter)
find_path(DTV_AVFILTER_INCLUDE_DIR libavfilter/avfilter.h HINTS ${AVCODEC_INCLUDE_DIRS})
if(DTV_AVFILTER_LIBRARY AND DTV_AVFILTER_INCLUDE_DIR)
set(AVFILTER_LIBRARIES ${DTV_AVFILTER_LIBRARY})
set(AVFILTER_INCLUDE_DIRS ${DTV_AVFILTER_INCLUDE_DIR})
endif()
endif()
if(AVFILTER_LIBRARIES)
set(sdrgui_DTV_INCLUDE_DIRS ${sdrgui_DTV_INCLUDE_DIRS} ${AVFILTER_INCLUDE_DIRS})
set(sdrgui_DTV_LIBRARIES ${sdrgui_DTV_LIBRARIES} ${AVFILTER_LIBRARIES})
set_source_files_properties(dtv/dtvvideoplayer.cpp PROPERTIES COMPILE_DEFINITIONS DTV_DEINTERLACE)
else()
message(STATUS "sdrgui: libavfilter not found, so no deinterlacing in the digital TV video player")
endif()
endif()
include_directories(
${CMAKE_SOURCE_DIR}/exports
${CMAKE_SOURCE_DIR}/sdrbase
@ -358,6 +404,20 @@ add_library(sdrgui @@ -358,6 +404,20 @@ add_library(sdrgui
${sdrgui_FORMS_HEADERS}
)
if(FFMPEG_FOUND)
target_include_directories(sdrgui PRIVATE ${sdrgui_DTV_INCLUDE_DIRS})
target_link_libraries(sdrgui ${sdrgui_DTV_LIBRARIES})
if(DEFINED FFMPEG_DEPENDS)
add_dependencies(sdrgui ${FFMPEG_DEPENDS})
endif()
if(WIN32)
target_link_libraries(sdrgui winmm) # The video player sets the timer resolution
endif()
if(APPLE)
target_link_libraries(sdrgui "-framework CoreVideo") # VideoToolbox frames' IOSurfaces
endif()
endif()
target_link_libraries(sdrgui
Qt::Core
Qt::Widgets

331
sdrgui/dtv/dtvappsdialog.cpp

@ -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)));
}
}

67
sdrgui/dtv/dtvappsdialog.h

@ -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

136
plugins/channelrx/demoddvb/dvbdemodepgdialog.cpp → sdrgui/dtv/dtvepgdialog.cpp

@ -34,14 +34,13 @@ @@ -34,14 +34,13 @@
#include <QTextBrowser>
#include <QVBoxLayout>
#include "dvbdemod.h"
#include "dvbdemodepggrid.h"
#include "dvbdemodepgdialog.h"
#include "dtv/dtvepggrid.h"
#include "dtv/dtvepgdialog.h"
DVBDemodEPGDialog::DVBDemodEPGDialog(DVBDemod *demod, QWidget *parent) :
DTVEPGDialog::DTVEPGDialog(DTVGuide *guide, DTVRecordingSchedule *schedule, QWidget *parent) :
QDialog(parent),
m_demod(demod),
m_epg(demod->getEPG()),
m_schedule(schedule),
m_epg(guide),
m_currentService(0)
{
setWindowTitle("Programme Guide");
@ -63,7 +62,7 @@ DVBDemodEPGDialog::DVBDemodEPGDialog(DVBDemod *demod, QWidget *parent) : @@ -63,7 +62,7 @@ DVBDemodEPGDialog::DVBDemodEPGDialog(DVBDemod *demod, QWidget *parent) :
m_scheduled->setToolTip("Programmes to record. Select one to cancel its recording");
m_scheduled->setPopupMode(QToolButton::InstantPopup);
m_scheduled->setMenu(new QMenu(m_scheduled));
connect(m_scheduled->menu(), &QMenu::aboutToShow, this, &DVBDemodEPGDialog::scheduledMenu);
connect(m_scheduled->menu(), &QMenu::aboutToShow, this, &DTVEPGDialog::scheduledMenu);
m_events = new QTableWidget(0, 4);
m_events->setHorizontalHeaderLabels({"Time", "Title", "Genre", "Info"});
@ -78,14 +77,14 @@ DVBDemodEPGDialog::DVBDemodEPGDialog(DVBDemod *demod, QWidget *parent) : @@ -78,14 +77,14 @@ DVBDemodEPGDialog::DVBDemodEPGDialog(DVBDemod *demod, QWidget *parent) :
m_events->setToolTip("Info: REC to be recorded, HD, S subtitles, AD audio description, and the minimum age from the parental rating.\n"
"Double-click to play the service. Right-click to record");
m_events->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_events, &QTableWidget::customContextMenuRequested, this, &DVBDemodEPGDialog::eventMenu);
connect(m_events, &QTableWidget::customContextMenuRequested, this, &DTVEPGDialog::eventMenu);
m_description = new QTextBrowser();
m_description->setMaximumHeight(160);
m_grid = new DVBDemodEPGGrid();
m_grid = new DTVEPGGrid();
m_grid->setToolTip("");
m_grid->setScheduled([this](int networkId, int serviceId, int eventId) { return m_demod->isScheduled(networkId, serviceId, eventId); });
m_grid->setScheduled([this](int networkId, int serviceId, int eventId) { return m_schedule->isScheduled(networkId, serviceId, eventId); });
QHBoxLayout *controls = new QHBoxLayout();
controls->addWidget(m_day);
@ -147,17 +146,17 @@ DVBDemodEPGDialog::DVBDemodEPGDialog(DVBDemod *demod, QWidget *parent) : @@ -147,17 +146,17 @@ DVBDemodEPGDialog::DVBDemodEPGDialog(DVBDemod *demod, QWidget *parent) :
showDescription();
}
});
connect(m_grid, &DVBDemodEPGGrid::eventSelected, this, [this](int row, int event) {
connect(m_grid, &DTVEPGGrid::eventSelected, this, [this](int row, int event) {
m_description->setHtml(describe(m_grid->row(row).m_events[event], m_grid->row(row).m_networkId));
});
connect(m_grid, &DVBDemodEPGGrid::eventActivated, this, [this](int row, int) {
connect(m_grid, &DTVEPGGrid::eventActivated, this, [this](int row, int) {
ListedService service;
if (gridService(row, service)) {
play(service);
}
});
connect(m_grid, &DVBDemodEPGGrid::eventMenuRequested, this, [this](int row, int event, const QPoint& globalPosition) {
connect(m_grid, &DTVEPGGrid::eventMenuRequested, this, [this](int row, int event, const QPoint& globalPosition) {
ListedService service;
// The event's copied: the menu's event loop may rebuild the grid
@ -165,19 +164,19 @@ DVBDemodEPGDialog::DVBDemodEPGDialog(DVBDemod *demod, QWidget *parent) : @@ -165,19 +164,19 @@ DVBDemodEPGDialog::DVBDemodEPGDialog(DVBDemod *demod, QWidget *parent) :
showEventMenu(service, m_grid->row(row).m_events[event], globalPosition);
}
});
connect(&m_timer, &QTimer::timeout, this, &DVBDemodEPGDialog::refresh);
connect(&m_timer, &QTimer::timeout, this, &DTVEPGDialog::refresh);
m_timer.start(10000); // The guide arrives over minutes
refresh();
}
qint64 DVBDemodEPGDialog::now() const
qint64 DTVEPGDialog::now() const
{
const qint64 t = m_epg->getTime();
return t > 0 ? t : QDateTime::currentSecsSinceEpoch();
}
void DVBDemodEPGDialog::setCurrentService(int serviceId)
void DTVEPGDialog::setCurrentService(int serviceId)
{
m_currentService = serviceId;
@ -191,21 +190,21 @@ void DVBDemodEPGDialog::setCurrentService(int serviceId) @@ -191,21 +190,21 @@ void DVBDemodEPGDialog::setCurrentService(int serviceId)
}
}
const DVBDemodEPGDialog::ListedService *DVBDemodEPGDialog::currentService() const
const DTVEPGDialog::ListedService *DTVEPGDialog::currentService() const
{
const int row = m_services->currentRow();
return (row >= 0) && (row < (int) m_listed.size()) ? &m_listed[row] : nullptr;
}
// A row of the grid's service, from the services it was built from. False if they've changed since
bool DVBDemodEPGDialog::gridService(int row, ListedService& service) const
bool DTVEPGDialog::gridService(int row, ListedService& service) const
{
if ((row < 0) || (row >= m_grid->rowCount()) || (row >= (int) m_gridServices.size())) {
return false;
}
const DVBDemodEPGGrid::Row& r = m_grid->row(row);
const DVBDemodEPG::Service& s = m_gridServices[row];
const DTVEPGGrid::Row& r = m_grid->row(row);
const DTVGuide::Service& s = m_gridServices[row];
if ((r.m_networkId != s.m_networkId) || (r.m_serviceId != s.m_serviceId)) {
return false;
@ -215,14 +214,14 @@ bool DVBDemodEPGDialog::gridService(int row, ListedService& service) const @@ -215,14 +214,14 @@ bool DVBDemodEPGDialog::gridService(int row, ListedService& service) const
return true;
}
void DVBDemodEPGDialog::refresh()
void DTVEPGDialog::refresh()
{
refreshDays();
refreshServices();
}
// Today and the next 7 days, local time
void DVBDemodEPGDialog::refreshDays()
void DTVEPGDialog::refreshDays()
{
const QDate today = QDateTime::fromSecsSinceEpoch(now()).toLocalTime().date();
@ -244,7 +243,7 @@ void DVBDemodEPGDialog::refreshDays() @@ -244,7 +243,7 @@ void DVBDemodEPGDialog::refreshDays()
m_day->blockSignals(false);
}
void DVBDemodEPGDialog::refreshServices()
void DTVEPGDialog::refreshServices()
{
const quint64 revision = m_epg->getRevision();
const bool others = m_otherMultiplexes->isChecked();
@ -258,20 +257,23 @@ void DVBDemodEPGDialog::refreshServices() @@ -258,20 +257,23 @@ void DVBDemodEPGDialog::refreshServices()
m_servicesRevision = revision;
m_servicesOthers = others;
std::vector<DVBDemodEPG::Service> services = m_epg->getServices();
std::vector<DTVGuide::Service> services = m_epg->getServices();
services.erase(std::remove_if(services.begin(), services.end(), [others](const DVBDemodEPG::Service& s) {
services.erase(std::remove_if(services.begin(), services.end(), [others](const DTVGuide::Service& s) {
return s.m_name.isEmpty() || !s.m_visible || (!others && !s.m_actual);
}), services.end());
std::sort(services.begin(), services.end(), [](const DVBDemodEPG::Service& a, const DVBDemodEPG::Service& b) {
const int ca = a.m_channel >= 0 ? a.m_channel : 0x7FFFFFFF, cb = b.m_channel >= 0 ? b.m_channel : 0x7FFFFFFF;
return ca != cb ? ca < cb : a.m_name < b.m_name;
std::sort(services.begin(), services.end(), [](const DTVGuide::Service& a, const DTVGuide::Service& b) {
if ((a.m_channel != b.m_channel) || (a.m_minorChannel != b.m_minorChannel)) {
return a.channelBefore(b);
}
return a.m_name < b.m_name;
});
QString key = QString::number(others);
for (const auto& s : services) {
key += QString("|%1/%2/%3/%4/%5/%6/%7").arg(s.m_networkId).arg(s.m_serviceId).arg(s.m_channel).arg(s.m_actual).arg(s.m_name)
key += QString("|%1/%2/%3/%4/%5/%6/%7").arg(s.m_networkId).arg(s.m_serviceId).arg(s.channelText()).arg(s.m_actual).arg(s.m_name)
.arg(s.m_frequency).arg(s.m_multiplexKnown);
}
@ -300,7 +302,7 @@ void DVBDemodEPGDialog::refreshServices() @@ -300,7 +302,7 @@ void DVBDemodEPGDialog::refreshServices()
for (const auto& s : services)
{
QListWidgetItem *item = new QListWidgetItem(s.m_channel >= 0 ? QString("%1 %2").arg(s.m_channel).arg(s.m_name) : s.m_name);
QListWidgetItem *item = new QListWidgetItem(s.m_channel >= 0 ? QString("%1 %2").arg(s.channelText()).arg(s.m_name) : s.m_name);
if (!s.m_actual)
{
@ -341,7 +343,7 @@ void DVBDemodEPGDialog::refreshServices() @@ -341,7 +343,7 @@ void DVBDemodEPGDialog::refreshServices()
}
// Every listed service's programmes, if the grid is shown, rebuilt if they've changed
void DVBDemodEPGDialog::refreshGrid()
void DTVEPGDialog::refreshGrid()
{
if (m_views->currentIndex() != 1) {
return;
@ -386,18 +388,18 @@ void DVBDemodEPGDialog::refreshGrid() @@ -386,18 +388,18 @@ void DVBDemodEPGDialog::refreshGrid()
return;
}
std::vector<std::vector<DVBDemodEPG::Event>> events = m_epg->getEvents(ids);
std::vector<DVBDemodEPGGrid::Row> rows;
std::vector<std::vector<DTVGuide::Event>> events = m_epg->getEvents(ids);
std::vector<DTVEPGGrid::Row> rows;
rows.reserve(m_gridServices.size());
for (size_t i = 0; i < m_gridServices.size(); i++)
{
const DVBDemodEPG::Service& s = m_gridServices[i];
DVBDemodEPGGrid::Row row;
const DTVGuide::Service& s = m_gridServices[i];
DTVEPGGrid::Row row;
row.m_networkId = s.m_networkId;
row.m_serviceId = s.m_serviceId;
row.m_name = s.m_name;
row.m_channel = s.m_channel;
row.m_channel = s.channelText();
row.m_actual = s.m_actual;
row.m_tunable = s.m_actual || (s.m_frequency > 0) || s.m_multiplexKnown;
row.m_events = std::move(events[i]);
@ -421,7 +423,7 @@ void DVBDemodEPGDialog::refreshGrid() @@ -421,7 +423,7 @@ void DVBDemodEPGDialog::refreshGrid()
}
// The grid goes to the start of the day chosen, or now for today
void DVBDemodEPGDialog::showDay()
void DTVEPGDialog::showDay()
{
if (m_views->currentIndex() != 1) {
return;
@ -433,14 +435,14 @@ void DVBDemodEPGDialog::showDay() @@ -433,14 +435,14 @@ void DVBDemodEPGDialog::showDay()
m_grid->scrollToTime(m_day->currentIndex() == 0 ? t - 1800 : dayStart);
}
void DVBDemodEPGDialog::play(ListedService service)
void DTVEPGDialog::play(ListedService service)
{
if (service.tunable()) {
emit serviceSelected(service.m_networkId, service.m_serviceId);
}
}
void DVBDemodEPGDialog::refreshEvents()
void DTVEPGDialog::refreshEvents()
{
const ListedService *service = currentService();
@ -457,8 +459,8 @@ void DVBDemodEPGDialog::refreshEvents() @@ -457,8 +459,8 @@ void DVBDemodEPGDialog::refreshEvents()
const qint64 dayStart = QDateTime(date, QTime(0, 0)).toSecsSinceEpoch();
const qint64 dayEnd = QDateTime(date.addDays(1), QTime(0, 0)).toSecsSinceEpoch();
const qint64 t = now();
std::vector<DVBDemodEPG::Event> events = m_epg->getEvents(service->m_networkId, service->m_serviceId);
events.erase(std::remove_if(events.begin(), events.end(), [dayStart, dayEnd](const DVBDemodEPG::Event& e) {
std::vector<DTVGuide::Event> events = m_epg->getEvents(service->m_networkId, service->m_serviceId);
events.erase(std::remove_if(events.begin(), events.end(), [dayStart, dayEnd](const DTVGuide::Event& e) {
return (e.m_start >= dayEnd) || (e.end() <= dayStart);
}), events.end());
@ -467,7 +469,7 @@ void DVBDemodEPGDialog::refreshEvents() @@ -467,7 +469,7 @@ void DVBDemodEPGDialog::refreshEvents()
for (const auto& e : events) {
key += QString("|%1/%2/%3/%4/%5").arg(e.m_eventId).arg(e.m_start).arg((e.m_start <= t) && (t < e.end())).arg(e.m_title)
.arg(m_demod->isScheduled(service->m_networkId, service->m_serviceId, e.m_eventId));
.arg(m_schedule->isScheduled(service->m_networkId, service->m_serviceId, e.m_eventId));
}
if (key == m_eventsKey) {
@ -491,7 +493,7 @@ void DVBDemodEPGDialog::refreshEvents() @@ -491,7 +493,7 @@ void DVBDemodEPGDialog::refreshEvents()
const QDateTime start = QDateTime::fromSecsSinceEpoch(e.m_start).toLocalTime();
const QDateTime end = QDateTime::fromSecsSinceEpoch(e.end()).toLocalTime();
QStringList info;
const bool scheduled = m_demod->isScheduled(service->m_networkId, service->m_serviceId, e.m_eventId);
const bool scheduled = m_schedule->isScheduled(service->m_networkId, service->m_serviceId, e.m_eventId);
if (scheduled) {
info.append("REC");
@ -516,7 +518,7 @@ void DVBDemodEPGDialog::refreshEvents() @@ -516,7 +518,7 @@ void DVBDemodEPGDialog::refreshEvents()
QTableWidgetItem *items[4] = {
new QTableWidgetItem(QString("%1 - %2").arg(start.toString("hh:mm")).arg(end.toString("hh:mm"))),
new QTableWidgetItem(e.m_title),
new QTableWidgetItem(DVBDemodEPG::genreText(e.m_genre, service->m_networkId)),
new QTableWidgetItem(m_epg->genreName(e.m_genre, service->m_networkId)),
new QTableWidgetItem(info.join(' '))
};
const bool onNow = (e.m_start <= t) && (t < e.end());
@ -559,7 +561,7 @@ void DVBDemodEPGDialog::refreshEvents() @@ -559,7 +561,7 @@ void DVBDemodEPGDialog::refreshEvents()
showDescription();
}
QString DVBDemodEPGDialog::describe(const DVBDemodEPG::Event& e, int networkId) const
QString DTVEPGDialog::describe(const DTVGuide::Event& e, int networkId) const
{
const QDateTime start = QDateTime::fromSecsSinceEpoch(e.m_start).toLocalTime();
const QDateTime end = QDateTime::fromSecsSinceEpoch(e.end()).toLocalTime();
@ -569,7 +571,7 @@ QString DVBDemodEPGDialog::describe(const DVBDemodEPG::Event& e, int networkId) @@ -569,7 +571,7 @@ QString DVBDemodEPGDialog::describe(const DVBDemodEPG::Event& e, int networkId)
.arg(start.toString("hh:mm"))
.arg(end.toString("hh:mm"))
.arg(e.m_duration / 60);
const QString genre = DVBDemodEPG::genreText(e.m_genre, networkId);
const QString genre = m_epg->genreName(e.m_genre, networkId);
if (!genre.isEmpty()) {
html += "&nbsp;&nbsp;" + genre.toHtmlEscaped();
@ -579,7 +581,7 @@ QString DVBDemodEPGDialog::describe(const DVBDemodEPG::Event& e, int networkId) @@ -579,7 +581,7 @@ QString DVBDemodEPGDialog::describe(const DVBDemodEPG::Event& e, int networkId)
html += "<br><i>" + e.m_guidance.toHtmlEscaped() + "</i>";
}
DVBDemodEPG::Service linked;
DTVGuide::Service linked;
if (linkedService(e, linked)) {
html += "<br>Also on " + linked.m_name.toHtmlEscaped();
@ -592,25 +594,25 @@ QString DVBDemodEPGDialog::describe(const DVBDemodEPG::Event& e, int networkId) @@ -592,25 +594,25 @@ QString DVBDemodEPGDialog::describe(const DVBDemodEPG::Event& e, int networkId)
return html;
}
bool DVBDemodEPGDialog::linkedService(const DVBDemodEPG::Event& event, DVBDemodEPG::Service& service) const
bool DTVEPGDialog::linkedService(const DTVGuide::Event& event, DTVGuide::Service& service) const
{
return (event.m_linkServiceId >= 0) && m_epg->getService(event.m_linkNetworkId, event.m_linkServiceId, service)
&& !service.m_name.isEmpty() && (service.m_actual || service.m_multiplexKnown);
}
// The programmes to be recorded, which the grid marks
QString DVBDemodEPGDialog::scheduleSignature() const
QString DTVEPGDialog::scheduleSignature() const
{
QString signature;
for (const auto& r : m_demod->getScheduledRecordings()) {
for (const auto& r : m_schedule->getScheduledRecordings()) {
signature += QString("%1/%2/%3|").arg(r.m_networkId).arg(r.m_serviceId).arg(r.m_eventId);
}
return signature;
}
void DVBDemodEPGDialog::showDescription()
void DTVEPGDialog::showDescription()
{
if (m_views->currentIndex() != 0) {
return; // The grid shows its selection's
@ -626,7 +628,7 @@ void DVBDemodEPGDialog::showDescription() @@ -626,7 +628,7 @@ void DVBDemodEPGDialog::showDescription()
}
}
void DVBDemodEPGDialog::eventMenu(const QPoint& position)
void DTVEPGDialog::eventMenu(const QPoint& position)
{
const int row = m_events->rowAt(position.y());
const ListedService *service = currentService();
@ -642,9 +644,9 @@ void DVBDemodEPGDialog::eventMenu(const QPoint& position) @@ -642,9 +644,9 @@ void DVBDemodEPGDialog::eventMenu(const QPoint& position)
// service the programme is also on, as in HD. Record a programme, or cancel its recording: only those of services that
// can be received, that haven't ended. The service and event are copies, as what they're from (the list, the table
// and the grid) can be rebuilt while the menu's open
void DVBDemodEPGDialog::showEventMenu(ListedService service, DVBDemodEPG::Event event, const QPoint& globalPosition)
void DTVEPGDialog::showEventMenu(ListedService service, DTVGuide::Event event, const QPoint& globalPosition)
{
const bool scheduled = m_demod->isScheduled(service.m_networkId, service.m_serviceId, event.m_eventId);
const bool scheduled = m_schedule->isScheduled(service.m_networkId, service.m_serviceId, event.m_eventId);
QMenu menu(this);
menu.setToolTipsVisible(true);
QAction *playAction = menu.addAction(service.m_actual ? QString("Play")
@ -652,7 +654,7 @@ void DVBDemodEPGDialog::showEventMenu(ListedService service, DVBDemodEPG::Event @@ -652,7 +654,7 @@ void DVBDemodEPGDialog::showEventMenu(ListedService service, DVBDemodEPG::Event
: service.m_multiplexKnown ? QString("Search for its multiplex and play")
: QString("Play (on another region's multiplex)"));
playAction->setEnabled(service.tunable());
DVBDemodEPG::Service linked;
DTVGuide::Service linked;
QAction *linkedAction = nullptr;
if (linkedService(event, linked))
@ -664,7 +666,7 @@ void DVBDemodEPGDialog::showEventMenu(ListedService service, DVBDemodEPG::Event @@ -664,7 +666,7 @@ void DVBDemodEPGDialog::showEventMenu(ListedService service, DVBDemodEPG::Event
QAction *recordAction = menu.addAction(scheduled ? "Cancel recording" : "Record");
// A service on another multiplex: recordable if scheduled recordings may retune to it
const bool reachable = service.m_actual || (m_demod->recordRetune() && service.tunable());
const bool reachable = service.m_actual || (m_schedule->recordRetune() && service.tunable());
if (!scheduled && !reachable)
{
@ -678,7 +680,7 @@ void DVBDemodEPGDialog::showEventMenu(ListedService service, DVBDemodEPG::Event @@ -678,7 +680,7 @@ void DVBDemodEPGDialog::showEventMenu(ListedService service, DVBDemodEPG::Event
// Its series, by its series CRID
QAction *seriesAction = nullptr;
const bool series = !event.m_seriesCrid.isEmpty() && m_demod->isSeriesScheduled(service.m_networkId, service.m_serviceId, event.m_eventId);
const bool series = !event.m_seriesCrid.isEmpty() && m_schedule->isSeriesScheduled(service.m_networkId, service.m_serviceId, event.m_eventId);
if (!event.m_seriesCrid.isEmpty())
{
@ -698,9 +700,9 @@ void DVBDemodEPGDialog::showEventMenu(ListedService service, DVBDemodEPG::Event @@ -698,9 +700,9 @@ void DVBDemodEPGDialog::showEventMenu(ListedService service, DVBDemodEPG::Event
if (seriesAction && (chosen == seriesAction))
{
if (series) {
m_demod->cancelSeries(service.m_networkId, service.m_serviceId, event.m_eventId);
m_schedule->cancelSeries(service.m_networkId, service.m_serviceId, event.m_eventId);
} else {
m_demod->scheduleSeries(service.m_networkId, service.m_serviceId, event.m_eventId);
m_schedule->scheduleSeries(service.m_networkId, service.m_serviceId, event.m_eventId);
}
m_eventsKey.clear();
@ -726,9 +728,9 @@ void DVBDemodEPGDialog::showEventMenu(ListedService service, DVBDemodEPG::Event @@ -726,9 +728,9 @@ void DVBDemodEPGDialog::showEventMenu(ListedService service, DVBDemodEPG::Event
}
if (scheduled) {
m_demod->cancelScheduledRecording(service.m_networkId, service.m_serviceId, event.m_eventId);
m_schedule->cancelScheduledRecording(service.m_networkId, service.m_serviceId, event.m_eventId);
} else {
m_demod->scheduleRecording(service.m_networkId, service.m_serviceId, event.m_eventId);
m_schedule->scheduleRecording(service.m_networkId, service.m_serviceId, event.m_eventId);
}
m_eventsKey.clear();
@ -737,15 +739,15 @@ void DVBDemodEPGDialog::showEventMenu(ListedService service, DVBDemodEPG::Event @@ -737,15 +739,15 @@ void DVBDemodEPGDialog::showEventMenu(ListedService service, DVBDemodEPG::Event
}
// The programmes to record, in time order: selecting one cancels it
void DVBDemodEPGDialog::scheduledMenu()
void DTVEPGDialog::scheduledMenu()
{
QMenu *menu = m_scheduled->menu();
menu->clear();
QList<DVBDemodSettings::ScheduledRecording> schedule = m_demod->getScheduledRecordings();
std::sort(schedule.begin(), schedule.end(), [](const DVBDemodSettings::ScheduledRecording& a, const DVBDemodSettings::ScheduledRecording& b) {
QList<DTVScheduledRecording> schedule = m_schedule->getScheduledRecordings();
std::sort(schedule.begin(), schedule.end(), [](const DTVScheduledRecording& a, const DTVScheduledRecording& b) {
return a.m_start < b.m_start;
});
const QList<DVBDemodSettings::SeriesRecording> series = m_demod->getSeriesRecordings();
const QList<DTVSeriesRecording> series = m_schedule->getSeriesRecordings();
if (schedule.isEmpty() && series.isEmpty())
{
@ -760,7 +762,7 @@ void DVBDemodEPGDialog::scheduledMenu() @@ -760,7 +762,7 @@ void DVBDemodEPGDialog::scheduledMenu()
const int networkId = s.m_networkId, serviceId = s.m_serviceId;
const QString crid = s.m_seriesCrid;
connect(action, &QAction::triggered, this, [this, networkId, serviceId, crid]() {
m_demod->cancelSeries(networkId, serviceId, crid);
m_schedule->cancelSeries(networkId, serviceId, crid);
m_eventsKey.clear();
refreshEvents();
refreshGrid();
@ -778,7 +780,7 @@ void DVBDemodEPGDialog::scheduledMenu() @@ -778,7 +780,7 @@ void DVBDemodEPGDialog::scheduledMenu()
.arg(QDateTime::fromSecsSinceEpoch(r.end()).toLocalTime().toString("hh:mm")).arg(r.m_serviceName).arg(r.m_title));
const int networkId = r.m_networkId, serviceId = r.m_serviceId, eventId = r.m_eventId;
connect(action, &QAction::triggered, this, [this, networkId, serviceId, eventId]() {
m_demod->cancelScheduledRecording(networkId, serviceId, eventId);
m_schedule->cancelScheduledRecording(networkId, serviceId, eventId);
m_eventsKey.clear();
refreshEvents();
refreshGrid();

33
plugins/channelrx/demoddvb/dvbdemodepgdialog.h → sdrgui/dtv/dtvepgdialog.h

@ -16,17 +16,17 @@ @@ -16,17 +16,17 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_DVBDEMODEPGDIALOG_H
#define INCLUDE_DVBDEMODEPGDIALOG_H
#ifndef INCLUDE_DTVEPGDIALOG_H
#define INCLUDE_DTVEPGDIALOG_H
#include <vector>
#include <QDialog>
#include <QTimer>
#include "dvbdemodepg.h"
#include "dtv/dtvguide.h"
#include "export.h"
class DVBDemod;
class QCheckBox;
class QToolButton;
class QComboBox;
@ -35,18 +35,19 @@ class QListWidget; @@ -35,18 +35,19 @@ class QListWidget;
class QTabWidget;
class QTableWidget;
class QTextBrowser;
class DVBDemodEPGGrid;
class DTVEPGGrid;
// The programme guide: the services of the network, by channel number, with either the schedule of the one selected a
// day at a time, or a grid of every service's programmes by time. Services in other transport streams (multiplexes)
// are shown in italics, and played by retuning to them, where the NIT gives their frequency, else greyed.
// Double-clicking a service, or one of its programmes, plays it. Right-click a programme to record it
class DVBDemodEPGDialog : public QDialog
class SDRGUI_API DTVEPGDialog : public QDialog
{
Q_OBJECT
public:
DVBDemodEPGDialog(DVBDemod *demod, QWidget *parent = nullptr);
//! schedule: null if programmes can't be recorded
DTVEPGDialog(DTVGuide *guide, DTVRecordingSchedule *schedule, QWidget *parent = nullptr);
//! Select the service in the list, as when it's playing
void setCurrentService(int serviceId);
@ -72,20 +73,20 @@ private: @@ -72,20 +73,20 @@ private:
void showDay();
//! Copies: what they're from may be rebuilt meanwhile
void play(ListedService service);
void showEventMenu(ListedService service, DVBDemodEPG::Event event, const QPoint& globalPosition);
void showEventMenu(ListedService service, DTVGuide::Event event, const QPoint& globalPosition);
void showDescription();
qint64 now() const;
QString describe(const DVBDemodEPG::Event& event, int networkId) const;
QString describe(const DTVGuide::Event& event, int networkId) const;
//! The service an event is also on (as in HD), if it can be played. False if none
bool linkedService(const DVBDemodEPG::Event& event, DVBDemodEPG::Service& service) const;
bool linkedService(const DTVGuide::Event& event, DTVGuide::Service& service) const;
QString scheduleSignature() const;
const ListedService *currentService() const;
bool gridService(int row, ListedService& service) const;
void eventMenu(const QPoint& position);
void scheduledMenu();
DVBDemod *m_demod;
DVBDemodEPG *m_epg;
DTVRecordingSchedule *m_schedule;
DTVGuide *m_epg;
QToolButton *m_scheduled;
QListWidget *m_services;
QComboBox *m_day;
@ -93,14 +94,14 @@ private: @@ -93,14 +94,14 @@ private:
QLabel *m_status;
QTableWidget *m_events;
QTabWidget *m_views;
DVBDemodEPGGrid *m_grid;
std::vector<DVBDemodEPG::Service> m_gridServices; //!< Rows of the grid
DTVEPGGrid *m_grid;
std::vector<DTVGuide::Service> m_gridServices; //!< Rows of the grid
QString m_gridKey; //!< The grid's rows and start
std::vector<quint64> m_gridServiceRevisions; //!< Their services' revisions
QTextBrowser *m_description;
QTimer m_timer;
std::vector<ListedService> m_listed;
std::vector<DVBDemodEPG::Event> m_shown; //!< Events in the table, in its order
std::vector<DTVGuide::Event> m_shown; //!< Events in the table, in its order
int m_currentService; //!< Service id to select, when listed
// What the list and grid were built from: when the guide, the services shown, the time window and the schedule
// are as they were, nothing is rebuilt, as making the keys below goes through every programme
@ -114,4 +115,4 @@ private: @@ -114,4 +115,4 @@ private:
QString m_eventsKey; //!< which would lose the scroll position
};
#endif // INCLUDE_DVBDEMODEPGDIALOG_H
#endif // INCLUDE_DTVEPGDIALOG_H

66
plugins/channelrx/demoddvb/dvbdemodepggrid.cpp → sdrgui/dtv/dtvepggrid.cpp

@ -28,9 +28,9 @@ @@ -28,9 +28,9 @@
#include <QScrollBar>
#include <QToolTip>
#include "dvbdemodepggrid.h"
#include "dtv/dtvepggrid.h"
DVBDemodEPGGrid::DVBDemodEPGGrid(QWidget *parent) :
DTVEPGGrid::DTVEPGGrid(QWidget *parent) :
QAbstractScrollArea(parent),
m_start(0),
m_end(0),
@ -44,32 +44,32 @@ DVBDemodEPGGrid::DVBDemodEPGGrid(QWidget *parent) : @@ -44,32 +44,32 @@ DVBDemodEPGGrid::DVBDemodEPGGrid(QWidget *parent) :
verticalScrollBar()->setSingleStep(20);
}
int DVBDemodEPGGrid::nameWidth() const
int DTVEPGGrid::nameWidth() const
{
return fontMetrics().horizontalAdvance("0000 Wwwwwwwwwwwwwwwwww");
}
int DVBDemodEPGGrid::headerHeight() const
int DTVEPGGrid::headerHeight() const
{
return fontMetrics().height() + 8;
}
int DVBDemodEPGGrid::rowHeight() const
int DTVEPGGrid::rowHeight() const
{
return 2 * fontMetrics().height() + 8;
}
double DVBDemodEPGGrid::x(qint64 utc) const
double DTVEPGGrid::x(qint64 utc) const
{
return nameWidth() + (utc - m_start) * m_pixelsPerHour / 3600.0 - horizontalScrollBar()->value();
}
qint64 DVBDemodEPGGrid::timeAt(double px) const
qint64 DTVEPGGrid::timeAt(double px) const
{
return m_start + (qint64) std::floor((px - nameWidth() + horizontalScrollBar()->value()) * 3600.0 / m_pixelsPerHour);
}
void DVBDemodEPGGrid::setRows(const std::vector<Row>& rows, qint64 start, qint64 now)
void DTVEPGGrid::setRows(const std::vector<Row>& rows, qint64 start, qint64 now)
{
// Keep the selection, by programme
int networkId = -1, serviceId = -1, eventId = -1;
@ -96,7 +96,7 @@ void DVBDemodEPGGrid::setRows(const std::vector<Row>& rows, qint64 start, qint64 @@ -96,7 +96,7 @@ void DVBDemodEPGGrid::setRows(const std::vector<Row>& rows, qint64 start, qint64
const Row& row = m_rows[r];
// Events can overlap (one within another), so the last to start may not be the last to end
for (const DVBDemodEPG::Event& e : row.m_events)
for (const DTVGuide::Event& e : row.m_events)
{
m_end = std::max(m_end, e.end());
m_longest[r] = std::max(m_longest[r], (qint64) e.m_duration);
@ -120,7 +120,7 @@ void DVBDemodEPGGrid::setRows(const std::vector<Row>& rows, qint64 start, qint64 @@ -120,7 +120,7 @@ void DVBDemodEPGGrid::setRows(const std::vector<Row>& rows, qint64 start, qint64
viewport()->update();
}
void DVBDemodEPGGrid::setNow(qint64 now)
void DTVEPGGrid::setNow(qint64 now)
{
if (std::abs((double) (now - m_now)) * m_pixelsPerHour >= 3600.0)
{
@ -129,12 +129,12 @@ void DVBDemodEPGGrid::setNow(qint64 now) @@ -129,12 +129,12 @@ void DVBDemodEPGGrid::setNow(qint64 now)
}
}
void DVBDemodEPGGrid::scrollToTime(qint64 utc)
void DTVEPGGrid::scrollToTime(qint64 utc)
{
horizontalScrollBar()->setValue((int) std::lround((utc - m_start) * m_pixelsPerHour / 3600.0));
}
void DVBDemodEPGGrid::scrollToService(int networkId, int serviceId)
void DTVEPGGrid::scrollToService(int networkId, int serviceId)
{
for (int r = 0; r < (int) m_rows.size(); r++)
{
@ -152,14 +152,14 @@ void DVBDemodEPGGrid::scrollToService(int networkId, int serviceId) @@ -152,14 +152,14 @@ void DVBDemodEPGGrid::scrollToService(int networkId, int serviceId)
}
}
bool DVBDemodEPGGrid::selection(int& row, int& event) const
bool DTVEPGGrid::selection(int& row, int& event) const
{
row = m_selectedRow;
event = m_selectedEvent;
return (row >= 0) && (event >= 0);
}
void DVBDemodEPGGrid::updateScrollBars()
void DTVEPGGrid::updateScrollBars()
{
const int width = (int) std::ceil((m_end - m_start) * m_pixelsPerHour / 3600.0);
const int height = (int) m_rows.size() * rowHeight();
@ -171,14 +171,14 @@ void DVBDemodEPGGrid::updateScrollBars() @@ -171,14 +171,14 @@ void DVBDemodEPGGrid::updateScrollBars()
verticalScrollBar()->setPageStep(viewHeight);
}
void DVBDemodEPGGrid::resizeEvent(QResizeEvent *event)
void DTVEPGGrid::resizeEvent(QResizeEvent *event)
{
QAbstractScrollArea::resizeEvent(event);
updateScrollBars();
}
// The row, and programme in it (-1 if none), at a point in the viewport. False if not in the programmes' area
bool DVBDemodEPGGrid::hit(const QPoint& position, int& row, int& event) const
bool DTVEPGGrid::hit(const QPoint& position, int& row, int& event) const
{
row = -1;
event = -1;
@ -196,7 +196,7 @@ bool DVBDemodEPGGrid::hit(const QPoint& position, int& row, int& event) const @@ -196,7 +196,7 @@ bool DVBDemodEPGGrid::hit(const QPoint& position, int& row, int& event) const
}
const qint64 t = timeAt(position.x());
const std::vector<DVBDemodEPG::Event>& events = m_rows[row].m_events;
const std::vector<DTVGuide::Event>& events = m_rows[row].m_events;
for (int e = 0; e < (int) events.size(); e++)
{
@ -210,7 +210,7 @@ bool DVBDemodEPGGrid::hit(const QPoint& position, int& row, int& event) const @@ -210,7 +210,7 @@ bool DVBDemodEPGGrid::hit(const QPoint& position, int& row, int& event) const
return true;
}
void DVBDemodEPGGrid::select(int row, int event)
void DTVEPGGrid::select(int row, int event)
{
if ((row == m_selectedRow) && (event == m_selectedEvent)) {
return;
@ -225,7 +225,7 @@ void DVBDemodEPGGrid::select(int row, int event) @@ -225,7 +225,7 @@ void DVBDemodEPGGrid::select(int row, int event)
}
}
void DVBDemodEPGGrid::mousePressEvent(QMouseEvent *event)
void DTVEPGGrid::mousePressEvent(QMouseEvent *event)
{
int row, e;
@ -236,7 +236,7 @@ void DVBDemodEPGGrid::mousePressEvent(QMouseEvent *event) @@ -236,7 +236,7 @@ void DVBDemodEPGGrid::mousePressEvent(QMouseEvent *event)
QAbstractScrollArea::mousePressEvent(event);
}
void DVBDemodEPGGrid::mouseDoubleClickEvent(QMouseEvent *event)
void DTVEPGGrid::mouseDoubleClickEvent(QMouseEvent *event)
{
int row, e;
@ -247,7 +247,7 @@ void DVBDemodEPGGrid::mouseDoubleClickEvent(QMouseEvent *event) @@ -247,7 +247,7 @@ void DVBDemodEPGGrid::mouseDoubleClickEvent(QMouseEvent *event)
}
}
void DVBDemodEPGGrid::contextMenuEvent(QContextMenuEvent *event)
void DTVEPGGrid::contextMenuEvent(QContextMenuEvent *event)
{
int row, e;
@ -259,7 +259,7 @@ void DVBDemodEPGGrid::contextMenuEvent(QContextMenuEvent *event) @@ -259,7 +259,7 @@ void DVBDemodEPGGrid::contextMenuEvent(QContextMenuEvent *event)
}
// Arrows move between programmes and services, Enter plays
void DVBDemodEPGGrid::keyPressEvent(QKeyEvent *event)
void DTVEPGGrid::keyPressEvent(QKeyEvent *event)
{
if ((m_selectedRow < 0) || (m_selectedEvent < 0))
{
@ -267,8 +267,8 @@ void DVBDemodEPGGrid::keyPressEvent(QKeyEvent *event) @@ -267,8 +267,8 @@ void DVBDemodEPGGrid::keyPressEvent(QKeyEvent *event)
return;
}
const std::vector<DVBDemodEPG::Event>& events = m_rows[m_selectedRow].m_events;
const DVBDemodEPG::Event& current = events[m_selectedEvent];
const std::vector<DTVGuide::Event>& events = m_rows[m_selectedRow].m_events;
const DTVGuide::Event& current = events[m_selectedEvent];
int row = m_selectedRow, e = m_selectedEvent;
switch (event->key())
@ -288,13 +288,13 @@ void DVBDemodEPGGrid::keyPressEvent(QKeyEvent *event) @@ -288,13 +288,13 @@ void DVBDemodEPGGrid::keyPressEvent(QKeyEvent *event)
for (int r = row + step; (r >= 0) && (r < (int) m_rows.size()); r += step)
{
const std::vector<DVBDemodEPG::Event>& other = m_rows[r].m_events;
const std::vector<DTVGuide::Event>& other = m_rows[r].m_events;
if (other.empty()) {
continue;
}
auto it = std::find_if(other.begin(), other.end(), [t](const DVBDemodEPG::Event& o) { return o.end() > t; });
auto it = std::find_if(other.begin(), other.end(), [t](const DTVGuide::Event& o) { return o.end() > t; });
row = r;
e = it != other.end() ? (int) (it - other.begin()) : (int) other.size() - 1;
break;
@ -313,7 +313,7 @@ void DVBDemodEPGGrid::keyPressEvent(QKeyEvent *event) @@ -313,7 +313,7 @@ void DVBDemodEPGGrid::keyPressEvent(QKeyEvent *event)
select(row, e);
// Keep it in view
const DVBDemodEPG::Event& selected = m_rows[row].m_events[e];
const DTVGuide::Event& selected = m_rows[row].m_events[e];
const double left = x(selected.m_start), right = x(selected.end());
if ((left < nameWidth()) || (right > viewport()->width())) {
@ -323,7 +323,7 @@ void DVBDemodEPGGrid::keyPressEvent(QKeyEvent *event) @@ -323,7 +323,7 @@ void DVBDemodEPGGrid::keyPressEvent(QKeyEvent *event)
scrollToService(m_rows[row].m_networkId, m_rows[row].m_serviceId);
}
bool DVBDemodEPGGrid::viewportEvent(QEvent *event)
bool DTVEPGGrid::viewportEvent(QEvent *event)
{
if (event->type() == QEvent::ToolTip)
{
@ -332,7 +332,7 @@ bool DVBDemodEPGGrid::viewportEvent(QEvent *event) @@ -332,7 +332,7 @@ bool DVBDemodEPGGrid::viewportEvent(QEvent *event)
if (hit(help->pos(), row, e) && (e >= 0))
{
const DVBDemodEPG::Event& ev = m_rows[row].m_events[e];
const DTVGuide::Event& ev = m_rows[row].m_events[e];
QToolTip::showText(help->globalPos(), QString("%1 - %2 %3")
.arg(QDateTime::fromSecsSinceEpoch(ev.m_start).toLocalTime().toString("hh:mm"))
.arg(QDateTime::fromSecsSinceEpoch(ev.end()).toLocalTime().toString("hh:mm"))
@ -349,7 +349,7 @@ bool DVBDemodEPGGrid::viewportEvent(QEvent *event) @@ -349,7 +349,7 @@ bool DVBDemodEPGGrid::viewportEvent(QEvent *event)
return QAbstractScrollArea::viewportEvent(event);
}
void DVBDemodEPGGrid::paintEvent(QPaintEvent *)
void DTVEPGGrid::paintEvent(QPaintEvent *)
{
QPainter painter(viewport());
const QPalette& pal = palette();
@ -376,11 +376,11 @@ void DVBDemodEPGGrid::paintEvent(QPaintEvent *) @@ -376,11 +376,11 @@ void DVBDemodEPGGrid::paintEvent(QPaintEvent *)
// In start order, ends needn't be (an event within another): from the first that could reach the view, by the
// row's longest, those that do
const auto first = std::lower_bound(row.m_events.begin(), row.m_events.end(), from - m_longest[r],
[](const DVBDemodEPG::Event& e, qint64 t) { return e.m_start < t; });
[](const DTVGuide::Event& e, qint64 t) { return e.m_start < t; });
for (auto it = first; (it != row.m_events.end()) && (it->m_start < to); ++it)
{
const DVBDemodEPG::Event& e = *it;
const DTVGuide::Event& e = *it;
if (e.end() <= from) {
continue;
@ -474,7 +474,7 @@ void DVBDemodEPGGrid::paintEvent(QPaintEvent *) @@ -474,7 +474,7 @@ void DVBDemodEPGGrid::paintEvent(QPaintEvent *)
QFont font = painter.font();
font.setItalic(!row.m_actual);
painter.setFont(font);
const QString text = row.m_channel >= 0 ? QString("%1 %2").arg(row.m_channel).arg(row.m_name) : row.m_name;
const QString text = !row.m_channel.isEmpty() ? QString("%1 %2").arg(row.m_channel).arg(row.m_name) : row.m_name;
painter.drawText(QRect(4, y, names - 8, rh), Qt::AlignVCenter | Qt::AlignLeft,
painter.fontMetrics().elidedText(text, Qt::ElideRight, names - 8));
painter.setPen(pal.color(QPalette::Mid));

17
plugins/channelrx/demoddvb/dvbdemodepggrid.h → sdrgui/dtv/dtvepggrid.h

@ -16,20 +16,21 @@ @@ -16,20 +16,21 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_DVBDEMODEPGGRID_H
#define INCLUDE_DVBDEMODEPGGRID_H
#ifndef INCLUDE_DTVEPGGRID_H
#define INCLUDE_DTVEPGGRID_H
#include <functional>
#include <vector>
#include <QAbstractScrollArea>
#include "dvbdemodepg.h"
#include "dtv/dtvguide.h"
#include "export.h"
// The programme guide as a grid of channels by time: a row per service, with its programmes as boxes along the time
// axis. The channel names on the left and the times along the top stay in place while scrolling. Clicking selects a
// programme, double-clicking or Enter activates it (to play its service), and right-clicking asks for a menu
class DVBDemodEPGGrid : public QAbstractScrollArea
class SDRGUI_API DTVEPGGrid : public QAbstractScrollArea
{
Q_OBJECT
@ -39,13 +40,13 @@ public: @@ -39,13 +40,13 @@ public:
int m_networkId = 0;
int m_serviceId = 0;
QString m_name;
int m_channel = -1;
QString m_channel; //!< Number, as "4" or "7.1", empty if none
bool m_actual = false; //!< In the transport stream being received
bool m_tunable = false; //!< Can be played: received, or its multiplex is in the area
std::vector<DVBDemodEPG::Event> m_events; //!< In time order
std::vector<DTVGuide::Event> m_events; //!< In time order
};
explicit DVBDemodEPGGrid(QWidget *parent = nullptr);
explicit DTVEPGGrid(QWidget *parent = nullptr);
//! The grid starts at start (UTC), with a line at now. The selection is kept if its programme is still there
void setRows(const std::vector<Row>& rows, qint64 start, qint64 now);
//! Move the line at now (UTC), as time passes, drawing again if it's moved by a pixel or more
@ -96,4 +97,4 @@ private: @@ -96,4 +97,4 @@ private:
static constexpr double m_pixelsPerHour = 240.0;
};
#endif // INCLUDE_DVBDEMODEPGGRID_H
#endif // INCLUDE_DTVEPGGRID_H

233
plugins/channelrx/demoddvb/dvbdemodguideoverlay.cpp → sdrgui/dtv/dtvguideoverlay.cpp

@ -31,22 +31,23 @@ @@ -31,22 +31,23 @@
#include "gui/glvideowidget.h"
#include "dvbdemodguideoverlay.h"
#include "dtv/dtvguideoverlay.h"
// Light text on translucent dark panels, so the picture shows through, and a colour per kind of programme
const QColor DVBDemodGuideOverlay::m_textColor(0xF1, 0xEF, 0xE8);
const QColor DVBDemodGuideOverlay::m_bodyColor(0xD3, 0xD1, 0xC7);
const QColor DVBDemodGuideOverlay::m_secondaryColor(0xB4, 0xB2, 0xA9);
const QColor DVBDemodGuideOverlay::m_mutedColor(0x88, 0x87, 0x80);
const QColor DVBDemodGuideOverlay::m_accentColor(0x5D, 0xCA, 0xA5);
const QColor DVBDemodGuideOverlay::m_warningColor(0xEF, 0x9F, 0x27);
const QColor DVBDemodGuideOverlay::m_recordColor(0xE2, 0x4B, 0x4A);
const QColor DVBDemodGuideOverlay::m_ageColor(0xF0, 0x99, 0x7B);
const QColor DVBDemodGuideOverlay::m_panelColor(14, 14, 14, 205);
const QColor DVBDemodGuideOverlay::m_dividerColor(241, 239, 232, 50);
const QColor DTVGuideOverlay::m_textColor(0xF1, 0xEF, 0xE8);
const QColor DTVGuideOverlay::m_bodyColor(0xD3, 0xD1, 0xC7);
const QColor DTVGuideOverlay::m_secondaryColor(0xB4, 0xB2, 0xA9);
const QColor DTVGuideOverlay::m_mutedColor(0x88, 0x87, 0x80);
const QColor DTVGuideOverlay::m_accentColor(0x5D, 0xCA, 0xA5);
const QColor DTVGuideOverlay::m_warningColor(0xEF, 0x9F, 0x27);
const QColor DTVGuideOverlay::m_recordColor(0xE2, 0x4B, 0x4A);
const QColor DTVGuideOverlay::m_redButtonColor(0xE6, 0x29, 0x28);
const QColor DTVGuideOverlay::m_ageColor(0xF0, 0x99, 0x7B);
const QColor DTVGuideOverlay::m_panelColor(14, 14, 14, 205);
const QColor DTVGuideOverlay::m_dividerColor(241, 239, 232, 50);
// Text with symbols, written as {dot}, {dash}, {up}, {down}, {left}, {right} and {rec}, so the source is ASCII
QString DVBDemodGuideOverlay::symbols(const char *text)
QString DTVGuideOverlay::symbols(const char *text)
{
QString s(text);
s.replace("{dot}", QChar(0x00B7));
@ -61,12 +62,12 @@ QString DVBDemodGuideOverlay::symbols(const char *text) @@ -61,12 +62,12 @@ QString DVBDemodGuideOverlay::symbols(const char *text)
// Pixels per pixel of a 1920 x 1080 layout, no less than half, so text is readable in a small window, where the
// layout is more compact instead
double DVBDemodGuideOverlay::scale(const QSize& size)
double DTVGuideOverlay::scale(const QSize& size)
{
return std::max(0.5, std::min(size.height() / 1080.0, size.width() / 1920.0));
}
QFont DVBDemodGuideOverlay::font(double pixels, bool medium)
QFont DTVGuideOverlay::font(double pixels, bool medium)
{
QFont f;
f.setPixelSize(std::max(8, (int) std::lround(pixels)));
@ -74,12 +75,12 @@ QFont DVBDemodGuideOverlay::font(double pixels, bool medium) @@ -74,12 +75,12 @@ QFont DVBDemodGuideOverlay::font(double pixels, bool medium)
return f;
}
QString DVBDemodGuideOverlay::localTime(qint64 utc, const char *format)
QString DTVGuideOverlay::localTime(qint64 utc, const char *format)
{
return QDateTime::fromSecsSinceEpoch(utc).toLocalTime().toString(format);
}
QString DVBDemodGuideOverlay::durationText(int seconds)
QString DTVGuideOverlay::durationText(int seconds)
{
const int minutes = (seconds + 30) / 60;
@ -91,7 +92,7 @@ QString DVBDemodGuideOverlay::durationText(int seconds) @@ -91,7 +92,7 @@ QString DVBDemodGuideOverlay::durationText(int seconds)
}
// Text, elided to fit width, with its top left at x, y
void DVBDemodGuideOverlay::drawText(QPainter& painter, int x, int y, int width, const QString& text, const QFont& f, const QColor& color)
void DTVGuideOverlay::drawText(QPainter& painter, int x, int y, int width, const QString& text, const QFont& f, const QColor& color)
{
const QFontMetrics metrics(f);
painter.setFont(f);
@ -99,19 +100,20 @@ void DVBDemodGuideOverlay::drawText(QPainter& painter, int x, int y, int width, @@ -99,19 +100,20 @@ void DVBDemodGuideOverlay::drawText(QPainter& painter, int x, int y, int width,
painter.drawText(x, y + metrics.ascent(), metrics.elidedText(text, Qt::ElideRight, std::max(0, width)));
}
void DVBDemodGuideOverlay::fillRounded(QPainter& painter, const QRectF& rect, double radius, const QColor& color)
void DTVGuideOverlay::fillRounded(QPainter& painter, const QRectF& rect, double radius, const QColor& color)
{
QPainterPath path;
path.addRoundedRect(rect, radius, radius);
painter.fillPath(path, color);
}
DVBDemodGuideOverlay::DVBDemodGuideOverlay(DVBDemodEPG *epg, QObject *parent) :
DTVGuideOverlay::DTVGuideOverlay(DTVGuide *epg, QObject *parent) :
QObject(parent),
m_epg(epg),
m_mode(Off),
m_playingService(0),
m_stepping(false),
m_redButton(false),
m_playedNetworkId(-1),
m_playedServiceId(-1),
m_row(0),
@ -125,7 +127,7 @@ DVBDemodGuideOverlay::DVBDemodGuideOverlay(DVBDemodEPG *epg, QObject *parent) : @@ -125,7 +127,7 @@ DVBDemodGuideOverlay::DVBDemodGuideOverlay(DVBDemodEPG *epg, QObject *parent) :
m_pressMode(Off)
{
m_hideTimer.setSingleShot(true);
connect(&m_hideTimer, &QTimer::timeout, this, &DVBDemodGuideOverlay::hide);
connect(&m_hideTimer, &QTimer::timeout, this, &DTVGuideOverlay::hide);
m_digitTimer.setSingleShot(true);
connect(&m_digitTimer, &QTimer::timeout, this, [this]() { digit(-1); });
m_clickTimer.setSingleShot(true);
@ -138,7 +140,7 @@ DVBDemodGuideOverlay::DVBDemodGuideOverlay(DVBDemodEPG *epg, QObject *parent) : @@ -138,7 +140,7 @@ DVBDemodGuideOverlay::DVBDemodGuideOverlay(DVBDemodEPG *epg, QObject *parent) :
});
}
void DVBDemodGuideOverlay::setWidget(GLVideoWidget *widget)
void DTVGuideOverlay::setWidget(GLVideoWidget *widget)
{
if (m_widget && (m_widget != widget)) {
m_widget->setGuide(QImage());
@ -153,7 +155,7 @@ void DVBDemodGuideOverlay::setWidget(GLVideoWidget *widget) @@ -153,7 +155,7 @@ void DVBDemodGuideOverlay::setWidget(GLVideoWidget *widget)
}
}
qint64 DVBDemodGuideOverlay::now() const
qint64 DTVGuideOverlay::now() const
{
const qint64 t = m_epg->getTime();
return t > 0 ? t : QDateTime::currentSecsSinceEpoch();
@ -162,7 +164,7 @@ qint64 DVBDemodGuideOverlay::now() const @@ -162,7 +164,7 @@ qint64 DVBDemodGuideOverlay::now() const
// TV and radio services that can be played (received, or on a multiplex of the area, retuned to or searched for if its
// frequency isn't known), and not hidden by their channel's visible_service_flag, by channel number. The one browsed or
// selected, and the one at the top of the guide's grid, stay so
void DVBDemodGuideOverlay::loadServices()
void DTVGuideOverlay::loadServices()
{
auto ids = [this](int row) {
return (row >= 0) && (row < (int) m_services.size())
@ -171,12 +173,15 @@ void DVBDemodGuideOverlay::loadServices() @@ -171,12 +173,15 @@ void DVBDemodGuideOverlay::loadServices()
const std::pair<int, int> selected = ids(m_row), first = ids(m_firstRow);
m_services = m_epg->getServices();
m_services.erase(std::remove_if(m_services.begin(), m_services.end(), [](const DVBDemodEPG::Service& s) {
m_services.erase(std::remove_if(m_services.begin(), m_services.end(), [](const DTVGuide::Service& s) {
return s.m_name.isEmpty() || !s.m_visible || (s.m_type == 0x0C) || (s.m_type == 0x10) || (!s.m_actual && !s.m_multiplexKnown);
}), m_services.end());
std::sort(m_services.begin(), m_services.end(), [](const DVBDemodEPG::Service& a, const DVBDemodEPG::Service& b) {
const int ca = a.m_channel >= 0 ? a.m_channel : 0x7FFFFFFF, cb = b.m_channel >= 0 ? b.m_channel : 0x7FFFFFFF;
return ca != cb ? ca < cb : a.m_name < b.m_name;
std::sort(m_services.begin(), m_services.end(), [](const DTVGuide::Service& a, const DTVGuide::Service& b) {
if ((a.m_channel != b.m_channel) || (a.m_minorChannel != b.m_minorChannel)) {
return a.channelBefore(b);
}
return a.m_name < b.m_name;
});
m_row = 0;
m_firstRow = 0;
@ -201,13 +206,13 @@ void DVBDemodGuideOverlay::loadServices() @@ -201,13 +206,13 @@ void DVBDemodGuideOverlay::loadServices()
}
}
int DVBDemodGuideOverlay::playingRow() const
int DTVGuideOverlay::playingRow() const
{
int remembered = -1;
for (int i = 0; i < (int) m_services.size(); i++)
{
const DVBDemodEPG::Service& s = m_services[i];
const DTVGuide::Service& s = m_services[i];
if (s.m_actual && (s.m_serviceId == m_playingService)) {
return i;
@ -223,37 +228,37 @@ int DVBDemodGuideOverlay::playingRow() const @@ -223,37 +228,37 @@ int DVBDemodGuideOverlay::playingRow() const
// A service's programmes, in order: the schedule, and for the multiplex being received, now and next too, which
// may be all there is
std::vector<DVBDemodEPG::Event> DVBDemodGuideOverlay::events(int row) const
std::vector<DTVGuide::Event> DTVGuideOverlay::events(int row) const
{
if ((row < 0) || (row >= (int) m_services.size())) {
return {};
}
const DVBDemodEPG::Service& s = m_services[row];
std::vector<DVBDemodEPG::Event> events = m_epg->getEvents(s.m_networkId, s.m_serviceId);
DVBDemodEPG::Event present, following;
const DTVGuide::Service& s = m_services[row];
std::vector<DTVGuide::Event> events = m_epg->getEvents(s.m_networkId, s.m_serviceId);
DTVGuide::Event present, following;
if (s.m_actual && m_epg->getNowNext(s.m_serviceId, present, following))
{
// Instead of the schedule's copies, which may have the times as planned rather than as broadcast
for (const DVBDemodEPG::Event *e : {&present, &following})
for (const DTVGuide::Event *e : {&present, &following})
{
if (e->isValid())
{
events.erase(std::remove_if(events.begin(), events.end(), [e](const DVBDemodEPG::Event& x) {
events.erase(std::remove_if(events.begin(), events.end(), [e](const DTVGuide::Event& x) {
return (x.m_eventId == e->m_eventId) || (x.m_start == e->m_start);
}), events.end());
events.push_back(*e);
}
}
std::sort(events.begin(), events.end(), [](const DVBDemodEPG::Event& a, const DVBDemodEPG::Event& b) { return a.m_start < b.m_start; });
std::sort(events.begin(), events.end(), [](const DTVGuide::Event& a, const DTVGuide::Event& b) { return a.m_start < b.m_start; });
}
return events;
}
bool DVBDemodGuideOverlay::hasPlaying()
bool DTVGuideOverlay::hasPlaying()
{
loadServices();
@ -265,7 +270,7 @@ bool DVBDemodGuideOverlay::hasPlaying() @@ -265,7 +270,7 @@ bool DVBDemodGuideOverlay::hasPlaying()
return playingRow() >= 0;
}
void DVBDemodGuideOverlay::showRibbon()
void DTVGuideOverlay::showRibbon()
{
// Shown again as each service starts playing: while stepping with the arrows, on the last asked for, not the
// one that's caught up
@ -283,7 +288,7 @@ void DVBDemodGuideOverlay::showRibbon() @@ -283,7 +288,7 @@ void DVBDemodGuideOverlay::showRibbon()
render();
}
void DVBDemodGuideOverlay::showGuide()
void DTVGuideOverlay::showGuide()
{
if (m_mode != Ribbon)
{
@ -303,7 +308,7 @@ void DVBDemodGuideOverlay::showGuide() @@ -303,7 +308,7 @@ void DVBDemodGuideOverlay::showGuide()
render();
}
void DVBDemodGuideOverlay::hide()
void DTVGuideOverlay::hide()
{
m_mode = Off;
m_stepping = false;
@ -311,13 +316,13 @@ void DVBDemodGuideOverlay::hide() @@ -311,13 +316,13 @@ void DVBDemodGuideOverlay::hide()
render(); // The channel number being entered, if any
}
void DVBDemodGuideOverlay::restartHideTimer()
void DTVGuideOverlay::restartHideTimer()
{
m_hideTimer.start((m_mode == Guide ? m_guideSeconds : m_ribbonSeconds) * 1000);
}
// On the guide if it's shown, else on the ribbon
void DVBDemodGuideOverlay::showMessage(const QString& message)
void DTVGuideOverlay::showMessage(const QString& message)
{
if (m_mode == Off) {
showRibbon();
@ -328,7 +333,7 @@ void DVBDemodGuideOverlay::showMessage(const QString& message) @@ -328,7 +333,7 @@ void DVBDemodGuideOverlay::showMessage(const QString& message)
render();
}
void DVBDemodGuideOverlay::refresh(bool force)
void DTVGuideOverlay::refresh(bool force)
{
if (((m_mode == Off) && m_digits.isEmpty()) || !m_widget) {
return;
@ -339,7 +344,7 @@ void DVBDemodGuideOverlay::refresh(bool force) @@ -339,7 +344,7 @@ void DVBDemodGuideOverlay::refresh(bool force)
}
}
bool DVBDemodGuideOverlay::handleKey(QKeyEvent *event)
bool DTVGuideOverlay::handleKey(QKeyEvent *event)
{
const int key = event->key();
const bool ok = (key == Qt::Key_Return) || (key == Qt::Key_Enter) || (key == Qt::Key_Select);
@ -491,7 +496,7 @@ bool DVBDemodGuideOverlay::handleKey(QKeyEvent *event) @@ -491,7 +496,7 @@ bool DVBDemodGuideOverlay::handleKey(QKeyEvent *event)
}
// Up to three digits of a channel number, played when complete, after a pause, or on OK (value < 0)
void DVBDemodGuideOverlay::digit(int value)
void DTVGuideOverlay::digit(int value)
{
if (value >= 0)
{
@ -524,7 +529,7 @@ void DVBDemodGuideOverlay::digit(int value) @@ -524,7 +529,7 @@ void DVBDemodGuideOverlay::digit(int value)
render();
}
void DVBDemodGuideOverlay::channelStep(int delta)
void DTVGuideOverlay::channelStep(int delta)
{
loadServices();
const int n = (int) m_services.size();
@ -541,7 +546,7 @@ void DVBDemodGuideOverlay::channelStep(int delta) @@ -541,7 +546,7 @@ void DVBDemodGuideOverlay::channelStep(int delta)
}
}
void DVBDemodGuideOverlay::stepRibbon(int delta)
void DTVGuideOverlay::stepRibbon(int delta)
{
const int n = (int) m_services.size();
@ -552,7 +557,7 @@ void DVBDemodGuideOverlay::stepRibbon(int delta) @@ -552,7 +557,7 @@ void DVBDemodGuideOverlay::stepRibbon(int delta)
m_row = (std::max(0, std::min(m_row, n - 1)) + delta + n) % n;
m_ribbonEvent = 0;
m_stepping = true;
const DVBDemodEPG::Service& s = m_services[m_row];
const DTVGuide::Service& s = m_services[m_row];
if (!(s.m_actual && (s.m_serviceId == m_playingService)))
{
@ -563,7 +568,7 @@ void DVBDemodGuideOverlay::stepRibbon(int delta) @@ -563,7 +568,7 @@ void DVBDemodGuideOverlay::stepRibbon(int delta)
}
// The ribbon is shown again once the service changes
void DVBDemodGuideOverlay::play(int row)
void DTVGuideOverlay::play(int row)
{
if ((row < 0) || (row >= (int) m_services.size()))
{
@ -571,7 +576,7 @@ void DVBDemodGuideOverlay::play(int row) @@ -571,7 +576,7 @@ void DVBDemodGuideOverlay::play(int row)
return;
}
const DVBDemodEPG::Service& s = m_services[row];
const DTVGuide::Service& s = m_services[row];
const bool playing = s.m_actual && (s.m_serviceId == m_playingService);
hide();
@ -584,9 +589,9 @@ void DVBDemodGuideOverlay::play(int row) @@ -584,9 +589,9 @@ void DVBDemodGuideOverlay::play(int row)
}
}
bool DVBDemodGuideOverlay::playSimulcast(int networkId, int serviceId)
bool DTVGuideOverlay::playSimulcast(int networkId, int serviceId)
{
DVBDemodEPG::Service simulcast;
DTVGuide::Service simulcast;
if (!m_epg->getSimulcast(networkId, serviceId, simulcast) || (simulcast.m_actual && (simulcast.m_serviceId == m_playingService))) {
return false;
@ -599,9 +604,9 @@ bool DVBDemodGuideOverlay::playSimulcast(int networkId, int serviceId) @@ -599,9 +604,9 @@ bool DVBDemodGuideOverlay::playSimulcast(int networkId, int serviceId)
return true;
}
QString DVBDemodGuideOverlay::simulcastName(int row) const
QString DTVGuideOverlay::simulcastName(int row) const
{
DVBDemodEPG::Service simulcast;
DTVGuide::Service simulcast;
if ((row < 0) || (row >= (int) m_services.size())
|| !m_epg->getSimulcast(m_services[row].m_networkId, m_services[row].m_serviceId, simulcast)) {
@ -611,13 +616,13 @@ QString DVBDemodGuideOverlay::simulcastName(int row) const @@ -611,13 +616,13 @@ QString DVBDemodGuideOverlay::simulcastName(int row) const
return simulcast.m_name;
}
void DVBDemodGuideOverlay::toggleRecording()
void DTVGuideOverlay::toggleRecording()
{
if ((m_row < 0) || (m_row >= (int) m_services.size()) || (m_guideEventId < 0)) {
return;
}
const DVBDemodEPG::Service& s = m_services[m_row];
const DTVGuide::Service& s = m_services[m_row];
if (m_toggleRecording) {
m_toggleRecording(s.m_networkId, s.m_serviceId, m_guideEventId);
@ -625,9 +630,9 @@ void DVBDemodGuideOverlay::toggleRecording() @@ -625,9 +630,9 @@ void DVBDemodGuideOverlay::toggleRecording()
}
// The programme on at a time, or the next after it, or the last before it
void DVBDemodGuideOverlay::selectGuideEventAt(qint64 utc)
void DTVGuideOverlay::selectGuideEventAt(qint64 utc)
{
const std::vector<DVBDemodEPG::Event> evs = events(m_row);
const std::vector<DTVGuide::Event> evs = events(m_row);
m_guideEventId = -1;
for (const auto& e : evs)
@ -644,7 +649,7 @@ void DVBDemodGuideOverlay::selectGuideEventAt(qint64 utc) @@ -644,7 +649,7 @@ void DVBDemodGuideOverlay::selectGuideEventAt(qint64 utc)
}
}
void DVBDemodGuideOverlay::moveGuideRow(int delta)
void DTVGuideOverlay::moveGuideRow(int delta)
{
const int n = (int) m_services.size();
@ -665,9 +670,9 @@ void DVBDemodGuideOverlay::moveGuideRow(int delta) @@ -665,9 +670,9 @@ void DVBDemodGuideOverlay::moveGuideRow(int delta)
}
// Along the row, scrolling the grid by half hours to keep the programme in view. Not back before the half hour now
void DVBDemodGuideOverlay::moveGuideEvent(int delta)
void DTVGuideOverlay::moveGuideEvent(int delta)
{
const std::vector<DVBDemodEPG::Event> evs = events(m_row);
const std::vector<DTVGuide::Event> evs = events(m_row);
const qint64 t = now();
const qint64 earliest = t - t % 1800;
int index = -1;
@ -691,13 +696,13 @@ void DVBDemodGuideOverlay::moveGuideEvent(int delta) @@ -691,13 +696,13 @@ void DVBDemodGuideOverlay::moveGuideEvent(int delta)
index++;
}
const DVBDemodEPG::Event& e = evs[index];
const DTVGuide::Event& e = evs[index];
m_guideEventId = e.m_eventId;
m_guideFocus = std::max(e.m_start, t);
keepGuideEventVisible(e.m_start);
}
void DVBDemodGuideOverlay::keepGuideEventVisible(qint64 start)
void DTVGuideOverlay::keepGuideEventVisible(qint64 start)
{
const qint64 t = now();
const qint64 earliest = t - t % 1800;
@ -711,7 +716,7 @@ void DVBDemodGuideOverlay::keepGuideEventVisible(qint64 start) @@ -711,7 +716,7 @@ void DVBDemodGuideOverlay::keepGuideEventVisible(qint64 start)
}
}
void DVBDemodGuideOverlay::keepGuideSelectionVisible()
void DTVGuideOverlay::keepGuideSelectionVisible()
{
if (m_row < m_firstRow) {
m_firstRow = m_row;
@ -722,8 +727,20 @@ void DVBDemodGuideOverlay::keepGuideSelectionVisible() @@ -722,8 +727,20 @@ void DVBDemodGuideOverlay::keepGuideSelectionVisible()
m_firstRow = std::max(0, std::min(m_firstRow, (int) m_services.size() - m_visibleRows));
}
double DVBDemodGuideOverlay::paintButton(QPainter& painter, double right, double y, double u, const QString& key,
const QString& label, HitArea::Kind kind)
void DTVGuideOverlay::setRedButton(bool shown)
{
if (shown != m_redButton)
{
m_redButton = shown;
if (m_mode != Off) {
render();
}
}
}
double DTVGuideOverlay::paintButton(QPainter& painter, double right, double y, double u, const QString& key,
const QString& label, HitArea::Kind kind, const QColor& keyColor)
{
const QFont keyFont = font(19 * u, true);
const QFont labelFont = font(21 * u);
@ -736,7 +753,7 @@ double DVBDemodGuideOverlay::paintButton(QPainter& painter, double right, double @@ -736,7 +753,7 @@ double DVBDemodGuideOverlay::paintButton(QPainter& painter, double right, double
painter.setBrush(Qt::NoBrush);
painter.drawRoundedRect(r, 19 * u, 19 * u);
painter.setFont(keyFont);
painter.setPen(m_accentColor);
painter.setPen(keyColor.isValid() ? keyColor : m_accentColor);
painter.drawText(QRectF(r.x() + 16 * u, r.y(), keyWidth, r.height()), Qt::AlignLeft | Qt::AlignVCenter, key);
painter.setFont(labelFont);
painter.setPen(m_textColor);
@ -746,7 +763,7 @@ double DVBDemodGuideOverlay::paintButton(QPainter& painter, double right, double @@ -746,7 +763,7 @@ double DVBDemodGuideOverlay::paintButton(QPainter& painter, double right, double
}
// The topmost: buttons are drawn after the grid they may overlap
const DVBDemodGuideOverlay::HitArea *DVBDemodGuideOverlay::hit(const QPointF& position) const
const DTVGuideOverlay::HitArea *DTVGuideOverlay::hit(const QPointF& position) const
{
for (auto it = m_hits.rbegin(); it != m_hits.rend(); ++it)
{
@ -759,7 +776,7 @@ const DVBDemodGuideOverlay::HitArea *DVBDemodGuideOverlay::hit(const QPointF& po @@ -759,7 +776,7 @@ const DVBDemodGuideOverlay::HitArea *DVBDemodGuideOverlay::hit(const QPointF& po
}
// Scroll the grid by half hours (not before the half hour now), selecting the programme at its start, or now
void DVBDemodGuideOverlay::stepWindow(int halfHours)
void DTVGuideOverlay::stepWindow(int halfHours)
{
const qint64 t = now();
m_windowStart = std::max(t - t % 1800, m_windowStart + halfHours * 1800);
@ -767,7 +784,7 @@ void DVBDemodGuideOverlay::stepWindow(int halfHours) @@ -767,7 +784,7 @@ void DVBDemodGuideOverlay::stepWindow(int halfHours)
selectGuideEventAt(m_guideFocus);
}
bool DVBDemodGuideOverlay::handleMouse(QMouseEvent *event)
bool DTVGuideOverlay::handleMouse(QMouseEvent *event)
{
const double ratio = m_widget ? m_widget->devicePixelRatioF() : 1.0; // None when testing
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
@ -844,6 +861,15 @@ bool DVBDemodGuideOverlay::handleMouse(QMouseEvent *event) @@ -844,6 +861,15 @@ bool DVBDemodGuideOverlay::handleMouse(QMouseEvent *event)
}
return true;
case HitArea::RedButton:
// The guide out of the way of the application
if (!doubleClick)
{
hide();
emit redButton();
}
return true;
case HitArea::ChannelUp: // A quick second click (a double-click) steps again
stepRibbon(1);
break;
@ -924,7 +950,7 @@ bool DVBDemodGuideOverlay::handleMouse(QMouseEvent *event) @@ -924,7 +950,7 @@ bool DVBDemodGuideOverlay::handleMouse(QMouseEvent *event)
}
// A row a notch, or with Shift or sideways, half an hour
bool DVBDemodGuideOverlay::handleWheel(QWheelEvent *event)
bool DTVGuideOverlay::handleWheel(QWheelEvent *event)
{
if (m_mode != Guide) {
return false;
@ -951,7 +977,7 @@ bool DVBDemodGuideOverlay::handleWheel(QWheelEvent *event) @@ -951,7 +977,7 @@ bool DVBDemodGuideOverlay::handleWheel(QWheelEvent *event)
}
// By the content's level 1 nibble: the UK's D-Book differs from EN 300 468 from 6 on
QColor DVBDemodGuideOverlay::genreColor(int genre, int networkId) const
QColor DTVGuideOverlay::genreColor(int genre, int networkId) const
{
static const QColor gray(0x88, 0x87, 0x80);
static const QColor drama(0x7F, 0x77, 0xDD);
@ -986,7 +1012,7 @@ QColor DVBDemodGuideOverlay::genreColor(int genre, int networkId) const @@ -986,7 +1012,7 @@ QColor DVBDemodGuideOverlay::genreColor(int genre, int networkId) const
}
// Into an image the size of the widget, which shows it over the video
void DVBDemodGuideOverlay::render()
void DTVGuideOverlay::render()
{
if (!m_widget) {
return;
@ -998,7 +1024,7 @@ void DVBDemodGuideOverlay::render() @@ -998,7 +1024,7 @@ void DVBDemodGuideOverlay::render()
m_widget->setGuide(((m_mode == Off) && m_digits.isEmpty()) || size.isEmpty() ? QImage() : image(size));
}
QImage DVBDemodGuideOverlay::image(const QSize& size)
QImage DTVGuideOverlay::image(const QSize& size)
{
m_hits.clear();
m_drawn.clear();
@ -1033,7 +1059,7 @@ QImage DVBDemodGuideOverlay::image(const QSize& size) @@ -1033,7 +1059,7 @@ QImage DVBDemodGuideOverlay::image(const QSize& size)
return image;
}
void DVBDemodGuideOverlay::paintClock(QPainter& painter, const QSize& size, qint64 t, double u, bool date)
void DTVGuideOverlay::paintClock(QPainter& painter, const QSize& size, qint64 t, double u, bool date)
{
const QString text = date ? localTime(t, "ddd d MMM HH:mm") : localTime(t);
const QFont f = font(28 * u, date);
@ -1046,12 +1072,8 @@ void DVBDemodGuideOverlay::paintClock(QPainter& painter, const QSize& size, qint @@ -1046,12 +1072,8 @@ void DVBDemodGuideOverlay::paintClock(QPainter& painter, const QSize& size, qint
painter.drawText(box, Qt::AlignCenter, text);
}
double DVBDemodGuideOverlay::paintLogo(QPainter& painter, double right, double centreY, double width, double height)
double DTVGuideOverlay::paintLogo(QPainter& painter, double right, double centreY, double width, double height)
{
if (m_logo.isNull()) {
m_logo = QImage(":/demoddvb/images/angeltv.png");
}
if (m_logo.isNull() || (width < 1.0) || (height < 1.0)) {
return 0.0;
}
@ -1069,7 +1091,7 @@ double DVBDemodGuideOverlay::paintLogo(QPainter& painter, double right, double c @@ -1069,7 +1091,7 @@ double DVBDemodGuideOverlay::paintLogo(QPainter& painter, double right, double c
}
// HD, subtitles, audio description and age as outlined badges, then extra text
void DVBDemodGuideOverlay::paintBadges(QPainter& painter, int x, int y, double u, const DVBDemodEPG::Event& event, const QString& extra)
void DTVGuideOverlay::paintBadges(QPainter& painter, int x, int y, double u, const DTVGuide::Event& event, const QString& extra)
{
const QFont f = font(19 * u);
const QFontMetrics metrics(f);
@ -1116,7 +1138,7 @@ void DVBDemodGuideOverlay::paintBadges(QPainter& painter, int x, int y, double u @@ -1116,7 +1138,7 @@ void DVBDemodGuideOverlay::paintBadges(QPainter& painter, int x, int y, double u
}
// Channel, programme on now (or browsed) with its progress, and the next, along the bottom
void DVBDemodGuideOverlay::paintRibbon(QPainter& painter, const QSize& size, qint64 t)
void DTVGuideOverlay::paintRibbon(QPainter& painter, const QSize& size, qint64 t)
{
const double u = scale(size);
const double margin = 48 * u;
@ -1128,13 +1150,21 @@ void DVBDemodGuideOverlay::paintRibbon(QPainter& painter, const QSize& size, qin @@ -1128,13 +1150,21 @@ void DVBDemodGuideOverlay::paintRibbon(QPainter& painter, const QSize& size, qin
m_drawn.push_back(bar);
paintClock(painter, size, t, u, false);
// The red button, above the bar's right end: the playing service's interactive application
if (m_redButton)
{
const double buttonY = bar.y() - 50 * u;
const double width = paintButton(painter, bar.right(), buttonY, u, symbols("{rec}"), "Red button", HitArea::RedButton, m_redButtonColor);
m_drawn.push_back(QRectF(bar.right() - width, buttonY, width, 38 * u));
}
if (m_services.empty())
{
drawText(painter, bar.x() + pad, bar.y() + pad, bar.width() - 2 * pad, "No programme guide yet", font(32 * u, true), m_textColor);
return;
}
const DVBDemodEPG::Service& s = m_services[std::min(m_row, (int) m_services.size() - 1)];
const DTVGuide::Service& s = m_services[std::min(m_row, (int) m_services.size() - 1)];
// Channel
const double channelWidth = 210 * u;
@ -1143,7 +1173,7 @@ void DVBDemodGuideOverlay::paintRibbon(QPainter& painter, const QSize& size, qin @@ -1143,7 +1173,7 @@ void DVBDemodGuideOverlay::paintRibbon(QPainter& painter, const QSize& size, qin
painter.setFont(font(58 * u, true));
const QFontMetrics numberMetrics(painter.font());
painter.drawText(QRectF(channelRect.x(), channelRect.y() - 10 * u, channelRect.width(), numberMetrics.height()),
Qt::AlignHCenter | Qt::AlignTop, s.m_channel >= 0 ? QString::number(s.m_channel) : QString());
Qt::AlignHCenter | Qt::AlignTop, s.channelText());
const QFont nameFont = font(24 * u);
const QFontMetrics nameMetrics(nameFont);
painter.setFont(nameFont);
@ -1177,8 +1207,8 @@ void DVBDemodGuideOverlay::paintRibbon(QPainter& painter, const QSize& size, qin @@ -1177,8 +1207,8 @@ void DVBDemodGuideOverlay::paintRibbon(QPainter& painter, const QSize& size, qin
painter.fillRect(QRectF(divider1, bar.y() + pad, std::max(1.0, u), height - 2 * pad), m_dividerColor);
// Programmes that haven't ended
std::vector<DVBDemodEPG::Event> evs = events(m_row);
evs.erase(std::remove_if(evs.begin(), evs.end(), [t](const DVBDemodEPG::Event& e) { return e.end() <= t; }), evs.end());
std::vector<DTVGuide::Event> evs = events(m_row);
evs.erase(std::remove_if(evs.begin(), evs.end(), [t](const DTVGuide::Event& e) { return e.end() <= t; }), evs.end());
m_ribbonEvent = std::max(0, std::min(m_ribbonEvent, (int) evs.size() - 1));
// The logo at the right, the programmes before it, unless the bar is too narrow to spare the room
@ -1197,12 +1227,12 @@ void DVBDemodGuideOverlay::paintRibbon(QPainter& painter, const QSize& size, qin @@ -1197,12 +1227,12 @@ void DVBDemodGuideOverlay::paintRibbon(QPainter& painter, const QSize& size, qin
}
else
{
const DVBDemodEPG::Event& e = evs[m_ribbonEvent];
const DTVGuide::Event& e = evs[m_ribbonEvent];
const bool onNow = e.m_start <= t;
const bool next = (m_ribbonEvent == 0) || ((m_ribbonEvent == 1) && (evs[0].m_start <= t));
const QString when = onNow ? "Now" : next ? "Next" : "Later";
QString label = symbols("%1 {dot} %2 {dash} %3").arg(when).arg(localTime(e.m_start)).arg(localTime(e.end()));
const QString genre = DVBDemodEPG::genreText(e.m_genre, s.m_networkId);
const QString genre = m_epg->genreName(e.m_genre, s.m_networkId);
if (!genre.isEmpty()) {
label += symbols(" {dot} %1").arg(genre);
@ -1238,7 +1268,7 @@ void DVBDemodGuideOverlay::paintRibbon(QPainter& painter, const QSize& size, qin @@ -1238,7 +1268,7 @@ void DVBDemodGuideOverlay::paintRibbon(QPainter& painter, const QSize& size, qin
if (m_ribbonEvent + 1 < (int) evs.size())
{
const DVBDemodEPG::Event& n = evs[m_ribbonEvent + 1];
const DTVGuide::Event& n = evs[m_ribbonEvent + 1];
drawText(painter, (int) x1, top, (int) sideWidth, symbols("%1 {dot} %2").arg(onNow ? "Next" : "Then").arg(localTime(n.m_start)),
font(21 * u), m_secondaryColor);
drawText(painter, (int) x1, top + (int) (30 * u), (int) sideWidth, n.m_title, font(30 * u, true), m_textColor);
@ -1246,7 +1276,7 @@ void DVBDemodGuideOverlay::paintRibbon(QPainter& painter, const QSize& size, qin @@ -1246,7 +1276,7 @@ void DVBDemodGuideOverlay::paintRibbon(QPainter& painter, const QSize& size, qin
if (m_message.isEmpty() && (m_ribbonEvent + 2 < (int) evs.size()))
{
const DVBDemodEPG::Event& n = evs[m_ribbonEvent + 2];
const DTVGuide::Event& n = evs[m_ribbonEvent + 2];
drawText(painter, (int) x1, top + (int) (78 * u), (int) sideWidth, QString("Then %1 %2").arg(localTime(n.m_start)).arg(n.m_title),
font(23 * u), m_mutedColor);
}
@ -1258,15 +1288,15 @@ void DVBDemodGuideOverlay::paintRibbon(QPainter& painter, const QSize& size, qin @@ -1258,15 +1288,15 @@ void DVBDemodGuideOverlay::paintRibbon(QPainter& painter, const QSize& size, qin
}
// The programme selected in detail over the dimmed picture, and channels by time below
void DVBDemodGuideOverlay::paintGuide(QPainter& painter, const QSize& size, qint64 t)
void DTVGuideOverlay::paintGuide(QPainter& painter, const QSize& size, qint64 t)
{
const double u = scale(size);
painter.fillRect(QRect(QPoint(0, 0), size), QColor(8, 8, 8, 150));
// The selection
const DVBDemodEPG::Service *service = m_services.empty() ? nullptr : &m_services[std::min(m_row, (int) m_services.size() - 1)];
const std::vector<DVBDemodEPG::Event> selectedRow = events(m_row);
const DVBDemodEPG::Event *selected = nullptr;
const DTVGuide::Service *service = m_services.empty() ? nullptr : &m_services[std::min(m_row, (int) m_services.size() - 1)];
const std::vector<DTVGuide::Event> selectedRow = events(m_row);
const DTVGuide::Event *selected = nullptr;
for (const auto& e : selectedRow)
{
@ -1327,9 +1357,9 @@ void DVBDemodGuideOverlay::paintGuide(QPainter& painter, const QSize& size, qint @@ -1327,9 +1357,9 @@ void DVBDemodGuideOverlay::paintGuide(QPainter& painter, const QSize& size, qint
}
else
{
const DVBDemodEPG::Event& e = *selected;
const DTVGuide::Event& e = *selected;
QStringList parts;
const QString genre = DVBDemodEPG::genreText(e.m_genre, service->m_networkId);
const QString genre = m_epg->genreName(e.m_genre, service->m_networkId);
if (!genre.isEmpty()) {
parts.append(genre);
@ -1372,6 +1402,11 @@ void DVBDemodGuideOverlay::paintGuide(QPainter& painter, const QSize& size, qint @@ -1372,6 +1402,11 @@ void DVBDemodGuideOverlay::paintGuide(QPainter& painter, const QSize& size, qint
// The grid
double buttonsRight = panel.right() - 4 * u;
buttonsRight -= paintButton(painter, buttonsRight, buttonsY, u, "G", "Close", HitArea::Close) + 14 * u;
if (m_redButton) {
buttonsRight -= paintButton(painter, buttonsRight, buttonsY, u, symbols("{rec}"), "Red button", HitArea::RedButton, m_redButtonColor) + 14 * u;
}
buttonsRight -= paintButton(painter, buttonsRight, buttonsY, u, "R", "Record", HitArea::Record) + 14 * u;
buttonsRight -= paintButton(painter, buttonsRight, buttonsY, u, "Enter", "Watch", HitArea::Watch) + 14 * u;
@ -1426,7 +1461,7 @@ void DVBDemodGuideOverlay::paintGuide(QPainter& painter, const QSize& size, qint @@ -1426,7 +1461,7 @@ void DVBDemodGuideOverlay::paintGuide(QPainter& painter, const QSize& size, qint
break;
}
const DVBDemodEPG::Service& s = m_services[row];
const DTVGuide::Service& s = m_services[row];
const double ry = rowsTop + i * rowHeight;
const double blockHeight = rowHeight - 8 * u;
const bool current = row == m_row;
@ -1441,7 +1476,7 @@ void DVBDemodGuideOverlay::paintGuide(QPainter& painter, const QSize& size, qint @@ -1441,7 +1476,7 @@ void DVBDemodGuideOverlay::paintGuide(QPainter& painter, const QSize& size, qint
painter.setFont(numberFont);
painter.setPen(current ? m_textColor : m_mutedColor);
painter.drawText(QRectF(panel.x() + pad + 4 * u, ry, 62 * u, blockHeight), Qt::AlignLeft | Qt::AlignVCenter,
s.m_channel >= 0 ? QString::number(s.m_channel) : QString());
s.channelText());
QFont nf = nameFont;
nf.setItalic(!s.m_actual); // Retunes, as in the guide window
const QFontMetrics nameMetrics(nf);
@ -1451,7 +1486,7 @@ void DVBDemodGuideOverlay::paintGuide(QPainter& painter, const QSize& size, qint @@ -1451,7 +1486,7 @@ void DVBDemodGuideOverlay::paintGuide(QPainter& painter, const QSize& size, qint
nameMetrics.elidedText(s.m_name, Qt::ElideRight, (int) (labelWidth - 84 * u)));
// Programmes
const std::vector<DVBDemodEPG::Event> evs = row == m_row ? selectedRow : events(row);
const std::vector<DTVGuide::Event> evs = row == m_row ? selectedRow : events(row);
bool any = false;
for (const auto& e : evs)

37
plugins/channelrx/demoddvb/dvbdemodguideoverlay.h → sdrgui/dtv/dtvguideoverlay.h

@ -1,5 +1,6 @@ @@ -1,5 +1,6 @@
///////////////////////////////////////////////////////////////////////////////////
// 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 //
@ -15,8 +16,8 @@ @@ -15,8 +16,8 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_DVBDEMODGUIDEOVERLAY_H
#define INCLUDE_DVBDEMODGUIDEOVERLAY_H
#ifndef INCLUDE_DTVGUIDEOVERLAY_H
#define INCLUDE_DTVGUIDEOVERLAY_H
#include <functional>
#include <vector>
@ -29,7 +30,8 @@ @@ -29,7 +30,8 @@
#include <QPointer>
#include <QTimer>
#include "dvbdemodepg.h"
#include "dtv/dtvguide.h"
#include "export.h"
class QKeyEvent;
class QMouseEvent;
@ -48,7 +50,7 @@ class GLVideoWidget; @@ -48,7 +50,7 @@ class GLVideoWidget;
// mouse: clicking the ribbon opens the guide; in the guide, clicking a programme or channel selects it,
// double-clicking watches it, buttons watch, record, close, page through the channels and step the time, and the
// wheel moves through the channels (with Shift, or sideways, the time). Right-clicking opens or closes the guide
class DVBDemodGuideOverlay : public QObject
class SDRGUI_API DTVGuideOverlay : public QObject
{
Q_OBJECT
@ -56,15 +58,19 @@ public: @@ -56,15 +58,19 @@ public:
typedef std::function<bool(int networkId, int serviceId, int eventId)> IsScheduled;
typedef std::function<void(int networkId, int serviceId, int eventId)> ToggleRecording;
explicit DVBDemodGuideOverlay(DVBDemodEPG *epg, QObject *parent = nullptr);
explicit DTVGuideOverlay(DTVGuide *epg, QObject *parent = nullptr);
//! To mark programmes to be recorded, and record them (R)
void setRecordings(IsScheduled isScheduled, ToggleRecording toggle) { m_isScheduled = isScheduled; m_toggleRecording = toggle; }
//! Shown at the top right of the guide (as the receiver's brand), none if null
void setLogo(const QImage& logo) { m_logo = logo; m_logoScaled = QImage(); }
//! Where to draw, null for nowhere (hiding the guide)
void setWidget(GLVideoWidget *widget);
//! The service playing, in the multiplex being received
void setPlaying(int serviceId) { m_playingService = serviceId; }
//! A red button on the ribbon and in the guide, for the playing service's interactive application
void setRedButton(bool shown);
void showRibbon();
//! If the guide has the service playing, for the ribbon to show
bool hasPlaying();
@ -84,6 +90,7 @@ public: @@ -84,6 +90,7 @@ public:
signals:
void playService(int networkId, int serviceId);
void redButton(); //!< The red button's clicked
private:
enum Mode { Off, Ribbon, Guide };
@ -91,7 +98,7 @@ private: @@ -91,7 +98,7 @@ private:
//! What's under the mouse, from the last image drawn
struct HitArea
{
enum Kind { Event, Channel, Watch, Simulcast, Record, Close, PageUp, PageDown, Earlier, Later, RibbonBar, ChannelUp, ChannelDown };
enum Kind { Event, Channel, Watch, Simulcast, Record, Close, PageUp, PageDown, Earlier, Later, RibbonBar, ChannelUp, ChannelDown, RedButton };
QRectF m_rect; //!< In the image's pixels
Kind m_kind;
@ -114,7 +121,7 @@ private: @@ -114,7 +121,7 @@ private:
//! The service playing, in the multiplex being received or, until its SI arrives after retuning, the one played
//! from here or last seen playing. -1 if not known
int playingRow() const;
std::vector<DVBDemodEPG::Event> events(int row) const;
std::vector<DTVGuide::Event> events(int row) const;
qint64 now() const;
void render();
void paintRibbon(QPainter& painter, const QSize& size, qint64 t);
@ -122,9 +129,11 @@ private: @@ -122,9 +129,11 @@ private:
void paintClock(QPainter& painter, const QSize& size, qint64 t, double u, bool date);
//! The logo, right-aligned to right and centred on centreY, at most width by height. Returns the width drawn, 0 if none
double paintLogo(QPainter& painter, double right, double centreY, double width, double height);
void paintBadges(QPainter& painter, int x, int y, double u, const DVBDemodEPG::Event& event, const QString& extra);
//! A button, outlined, with a key's name before its label, right-aligned to right. Returns its width
double paintButton(QPainter& painter, double right, double y, double u, const QString& key, const QString& label, HitArea::Kind kind);
void paintBadges(QPainter& painter, int x, int y, double u, const DTVGuide::Event& event, const QString& extra);
//! A button, outlined, with a key's name before its label (in keyColor, the accent if invalid), right-aligned to right.
//! Returns its width
double paintButton(QPainter& painter, double right, double y, double u, const QString& key, const QString& label, HitArea::Kind kind,
const QColor& keyColor = QColor());
void addHit(const QRectF& rect, HitArea::Kind kind, int row = -1, int eventId = -1) { m_hits.push_back({rect, kind, row, eventId}); }
const HitArea *hit(const QPointF& position) const;
void stepWindow(int halfHours);
@ -147,16 +156,17 @@ private: @@ -147,16 +156,17 @@ private:
void restartHideTimer();
void showMessage(const QString& message);
DVBDemodEPG *m_epg;
DTVGuide *m_epg;
IsScheduled m_isScheduled;
ToggleRecording m_toggleRecording;
QPointer<GLVideoWidget> m_widget;
Mode m_mode;
int m_playingService;
bool m_stepping; //!< Stepping with the ribbon's arrows: it stays on the channel asked for, until hidden
bool m_redButton; //!< Shown
int m_playedNetworkId; //!< The service last seen playing, or played from here, -1 if none
int m_playedServiceId;
std::vector<DVBDemodEPG::Service> m_services; //!< By channel number
std::vector<DTVGuide::Service> m_services; //!< By channel number
int m_row; //!< Service browsed or selected
int m_ribbonEvent; //!< Programme on the ribbon: 0 for on now, 1 next...
int m_guideEventId; //!< Programme selected in the guide, -1 if none
@ -192,9 +202,10 @@ private: @@ -192,9 +202,10 @@ private:
static const QColor m_accentColor;
static const QColor m_warningColor;
static const QColor m_recordColor;
static const QColor m_redButtonColor;
static const QColor m_ageColor;
static const QColor m_panelColor;
static const QColor m_dividerColor;
};
#endif // INCLUDE_DVBDEMODGUIDEOVERLAY_H
#endif // INCLUDE_DTVGUIDEOVERLAY_H

50
plugins/channelrx/demoddvb/dvbdemodscope.cpp → sdrgui/dtv/dtvscope.cpp

@ -26,17 +26,17 @@ @@ -26,17 +26,17 @@
#include <QPainter>
#include <QPainterPath>
#include "dvbdemodscope.h"
#include "dtv/dtvscope.h"
const QColor DVBDemodScope::m_gridColour(255, 255, 255, 64);
const QColor DVBDemodScope::m_zeroColour(255, 255, 255, 128);
const QColor DVBDemodScope::m_labelColour(200, 200, 200);
const QColor DTVScope::m_gridColour(255, 255, 255, 64);
const QColor DTVScope::m_zeroColour(255, 255, 255, 128);
const QColor DTVScope::m_labelColour(200, 200, 200);
const QColor DVBDemodScope::m_merColour(0, 220, 255);
const QColor DVBDemodScope::m_iterationsColour(255, 200, 0);
const QColor DVBDemodScope::m_errorsColour(255, 60, 60);
const QColor DTVScope::m_merColour(0, 220, 255);
const QColor DTVScope::m_iterationsColour(255, 200, 0);
const QColor DTVScope::m_errorsColour(255, 60, 60);
DVBDemodScope::DVBDemodScope(QWidget *parent) :
DTVScope::DTVScope(QWidget *parent) :
QWidget(parent),
m_view(Response),
m_constellationSize(0),
@ -53,7 +53,7 @@ DVBDemodScope::DVBDemodScope(QWidget *parent) : @@ -53,7 +53,7 @@ DVBDemodScope::DVBDemodScope(QWidget *parent) :
setView(Response);
}
void DVBDemodScope::setView(View view)
void DTVScope::setView(View view)
{
static const char *const tips[] = {
"the channel's frequency response across the carriers, relative to its mean: echoes give ripples, and interference or LO leakage dips",
@ -70,7 +70,7 @@ void DVBDemodScope::setView(View view) @@ -70,7 +70,7 @@ void DVBDemodScope::setView(View view)
update();
}
void DVBDemodScope::setData(const std::vector<std::complex<float>>& cells, const std::vector<float>& responseDb, int constellationSize, int alpha)
void DTVScope::setData(const std::vector<std::complex<float>>& cells, const std::vector<float>& responseDb, int constellationSize, int alpha)
{
if (!responseDb.empty() && (responseDb != m_responseDb)) {
addWaterfallRow(responseDb);
@ -83,12 +83,12 @@ void DVBDemodScope::setData(const std::vector<std::complex<float>>& cells, const @@ -83,12 +83,12 @@ void DVBDemodScope::setData(const std::vector<std::complex<float>>& cells, const
update();
}
void DVBDemodScope::setPoints(const std::vector<std::complex<float>>& points)
void DTVScope::setPoints(const std::vector<std::complex<float>>& points)
{
m_points = points;
}
void DVBDemodScope::setSpectrum(bool spectrum)
void DTVScope::setSpectrum(bool spectrum)
{
if (spectrum != m_spectrum)
{
@ -98,7 +98,7 @@ void DVBDemodScope::setSpectrum(bool spectrum) @@ -98,7 +98,7 @@ void DVBDemodScope::setSpectrum(bool spectrum)
}
}
void DVBDemodScope::setImpulseResponse(const std::vector<float>& powerDb, double resolution, int guard, double sampleRate)
void DTVScope::setImpulseResponse(const std::vector<float>& powerDb, double resolution, int guard, double sampleRate)
{
m_impulseDb = powerDb;
m_impulseResolution = resolution;
@ -110,7 +110,7 @@ void DVBDemodScope::setImpulseResponse(const std::vector<float>& powerDb, double @@ -110,7 +110,7 @@ void DVBDemodScope::setImpulseResponse(const std::vector<float>& powerDb, double
}
}
void DVBDemodScope::addHistory(double mer, double iterations, int errors, double interval)
void DTVScope::addHistory(double mer, double iterations, int errors, double interval)
{
m_history.push_back({(float) mer, (float) iterations, errors});
m_historyInterval = interval;
@ -124,14 +124,14 @@ void DVBDemodScope::addHistory(double mer, double iterations, int errors, double @@ -124,14 +124,14 @@ void DVBDemodScope::addHistory(double mer, double iterations, int errors, double
}
}
void DVBDemodScope::clearHistory()
void DTVScope::clearHistory()
{
m_history.clear();
m_waterfallRows = 0;
update();
}
void DVBDemodScope::contextMenuEvent(QContextMenuEvent *event)
void DTVScope::contextMenuEvent(QContextMenuEvent *event)
{
QMenu menu(this);
const char *const names[] = {"Frequency response", "Response waterfall", "Impulse response", "History"};
@ -151,7 +151,7 @@ void DVBDemodScope::contextMenuEvent(QContextMenuEvent *event) @@ -151,7 +151,7 @@ void DVBDemodScope::contextMenuEvent(QContextMenuEvent *event)
}
}
void DVBDemodScope::paintEvent(QPaintEvent *event)
void DTVScope::paintEvent(QPaintEvent *event)
{
(void) event;
QPainter painter(this);
@ -183,7 +183,7 @@ void DVBDemodScope::paintEvent(QPaintEvent *event) @@ -183,7 +183,7 @@ void DVBDemodScope::paintEvent(QPaintEvent *event)
}
// Which view, at the top right, as a reminder that right-clicking chooses another
void DVBDemodScope::paintTitle(QPainter& painter, const QRect& rect, const QString& title)
void DTVScope::paintTitle(QPainter& painter, const QRect& rect, const QString& title)
{
const QString text = title + " " + QChar(0x25BE);
const QFontMetrics metrics(painter.font());
@ -193,7 +193,7 @@ void DVBDemodScope::paintTitle(QPainter& painter, const QRect& rect, const QStri @@ -193,7 +193,7 @@ void DVBDemodScope::paintTitle(QPainter& painter, const QRect& rect, const QStri
painter.drawText(box, Qt::AlignCenter, text);
}
void DVBDemodScope::paintConstellation(QPainter& painter, const QRect& rect)
void DTVScope::paintConstellation(QPainter& painter, const QRect& rect)
{
const float range = 1.5f; // Of the unit power constellation, edge to centre
const float scale = rect.width() / (2.0f * range);
@ -266,7 +266,7 @@ void DVBDemodScope::paintConstellation(QPainter& painter, const QRect& rect) @@ -266,7 +266,7 @@ void DVBDemodScope::paintConstellation(QPainter& painter, const QRect& rect)
painter.restore();
}
void DVBDemodScope::paintResponse(QPainter& painter, const QRect& rect)
void DTVScope::paintResponse(QPainter& painter, const QRect& rect)
{
const float top = 10.0f, bottom = -30.0f; // dB, relative to the mean
auto y = [&](float db) {
@ -312,7 +312,7 @@ void DVBDemodScope::paintResponse(QPainter& painter, const QRect& rect) @@ -312,7 +312,7 @@ void DVBDemodScope::paintResponse(QPainter& painter, const QRect& rect)
}
// dB relative to the mean, -30 to +10, from black through blue, cyan and yellow to red
QRgb DVBDemodScope::waterfallColour(float db)
QRgb DTVScope::waterfallColour(float db)
{
static const int stops[5][3] = {{0, 0, 0}, {0, 0, 255}, {0, 255, 255}, {255, 255, 0}, {255, 0, 0}};
const float t = std::max(0.0f, std::min(1.0f, (db + 30.0f) / 40.0f)) * 4.0f;
@ -322,7 +322,7 @@ QRgb DVBDemodScope::waterfallColour(float db) @@ -322,7 +322,7 @@ QRgb DVBDemodScope::waterfallColour(float db)
(int) (stops[i][2] + f * (stops[i + 1][2] - stops[i][2])));
}
void DVBDemodScope::addWaterfallRow(const std::vector<float>& responseDb)
void DTVScope::addWaterfallRow(const std::vector<float>& responseDb)
{
const int width = (int) responseDb.size();
@ -356,7 +356,7 @@ void DVBDemodScope::addWaterfallRow(const std::vector<float>& responseDb) @@ -356,7 +356,7 @@ void DVBDemodScope::addWaterfallRow(const std::vector<float>& responseDb)
m_waterfallRows = std::min(m_waterfallRows + 1, m_waterfall.height());
}
void DVBDemodScope::paintWaterfall(QPainter& painter, const QRect& rect)
void DTVScope::paintWaterfall(QPainter& painter, const QRect& rect)
{
if (m_waterfallRows > 0)
{
@ -391,7 +391,7 @@ void DVBDemodScope::paintWaterfall(QPainter& painter, const QRect& rect) @@ -391,7 +391,7 @@ void DVBDemodScope::paintWaterfall(QPainter& painter, const QRect& rect)
}
}
void DVBDemodScope::paintImpulseResponse(QPainter& painter, const QRect& rect)
void DTVScope::paintImpulseResponse(QPainter& painter, const QRect& rect)
{
const int bins = (int) m_impulseDb.size();
@ -465,7 +465,7 @@ void DVBDemodScope::paintImpulseResponse(QPainter& painter, const QRect& rect) @@ -465,7 +465,7 @@ void DVBDemodScope::paintImpulseResponse(QPainter& painter, const QRect& rect)
painter.drawPath(path);
}
void DVBDemodScope::paintHistory(QPainter& painter, const QRect& rect)
void DTVScope::paintHistory(QPainter& painter, const QRect& rect)
{
const float merTop = 40.0f, iterationsTop = 50.0f;
const double dx = (double) rect.width() / (m_historyLength - 1);

12
plugins/channelrx/demoddvb/dvbdemodscope.h → sdrgui/dtv/dtvscope.h

@ -16,8 +16,8 @@ @@ -16,8 +16,8 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_DVBDEMODSCOPE_H
#define INCLUDE_DVBDEMODSCOPE_H
#ifndef INCLUDE_DTVSCOPE_H
#define INCLUDE_DTVSCOPE_H
#include <complex>
#include <deque>
@ -27,17 +27,19 @@ @@ -27,17 +27,19 @@
#include <QImage>
#include <QWidget>
#include "export.h"
// Constellation of the equalised data cells at the left, and at the right, chosen by right-clicking: the channel
// frequency response across the carriers, the response over time as a waterfall, the impulse response, or a history
// of MER, LDPC iterations and uncorrected errors
class DVBDemodScope : public QWidget
class SDRGUI_API DTVScope : public QWidget
{
Q_OBJECT
public:
enum View { Response, Waterfall, ImpulseResponse, History };
explicit DVBDemodScope(QWidget *parent = nullptr);
explicit DTVScope(QWidget *parent = nullptr);
//! cells have unit average power. constellationSize is 4, 16, 64 or 256, or 0 if not known. alpha is of DVB-T's
//! hierarchical modes: the points nearest the axes are alpha - 1 further from them than in a uniform constellation.
@ -112,4 +114,4 @@ private: @@ -112,4 +114,4 @@ private:
static const QColor m_errorsColour;
};
#endif // INCLUDE_DVBDEMODSCOPE_H
#endif // INCLUDE_DTVSCOPE_H

240
sdrgui/dtv/dtvstreamplayback.cpp

@ -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();
}
}

97
sdrgui/dtv/dtvstreamplayback.h

@ -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

289
sdrgui/dtv/dtvstreamremuxer.cpp

@ -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);
}

74
sdrgui/dtv/dtvstreamremuxer.h

@ -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

574
plugins/channelrx/demoddvb/dvbdemodvideoplayer.cpp → sdrgui/dtv/dtvvideoplayer.cpp

File diff suppressed because it is too large Load Diff

53
plugins/channelrx/demoddvb/dvbdemodvideoplayer.h → sdrgui/dtv/dtvvideoplayer.h

@ -16,8 +16,8 @@ @@ -16,8 +16,8 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_DVBDEMODVIDEOPLAYER_H
#define INCLUDE_DVBDEMODVIDEOPLAYER_H
#ifndef INCLUDE_DTVVIDEOPLAYER_H
#define INCLUDE_DTVVIDEOPLAYER_H
#include <atomic>
#include <chrono>
@ -52,13 +52,15 @@ struct AVFilterGraph; @@ -52,13 +52,15 @@ struct AVFilterGraph;
struct AVFilterContext;
struct AVHWFramesContext;
struct AVSubtitle;
struct AVFrameSideData;
#include "gui/glvideoframe.h"
#include "dvbdemodpsi.h"
#include "dtv/dtvpsi.h"
#include "export.h"
class AudioFifo;
class DVBDemodTSFifo;
class DTVTSFifo;
// Demultiplexes the transport stream with FFmpeg, decodes the selected service and displays it. The player's
// thread demultiplexes and decodes the audio. Video is decoded and shown in another thread, as frames wait there
@ -66,7 +68,7 @@ class DVBDemodTSFifo; @@ -66,7 +68,7 @@ class DVBDemodTSFifo;
// display as GLVideoFrames: decoded by the GPU, they stay there (deinterlaced by FFmpeg's GPU filters, or the
// display's for D3D11) if the display can show them, else are copied to memory (after FFmpeg's GPU filter has
// deinterlaced them, if there is one for them, sparing the CPU bwdif)
class DVBDemodVideoPlayer : public QThread
class SDRGUI_API DTVVideoPlayer : public QThread
{
Q_OBJECT
@ -122,7 +124,7 @@ public: @@ -122,7 +124,7 @@ public:
SubtitlesHardOfHearing
};
int m_pid;
int m_pid; //!< m_captionPid for closed captions in the video (ATSC's)
QString m_language; //!< ISO 639-2 code, e.g. "eng", or empty
Type m_type;
};
@ -143,14 +145,16 @@ public: @@ -143,14 +145,16 @@ public:
typedef std::function<bool(int type)> CanShowCallback;
//! audioFifo may be null, for no audio
DVBDemodVideoPlayer(DVBDemodTSFifo *tsFifo, AudioFifo *audioFifo, QObject *parent = nullptr);
~DVBDemodVideoPlayer();
DTVVideoPlayer(DTVTSFifo *tsFifo, AudioFifo *audioFifo, QObject *parent = nullptr);
~DTVVideoPlayer();
void stopPlayer();
void setService(int id) { m_requestedService = id; }
void setAudioMute(bool mute) { m_audioMute = mute; }
void setAudioVolume(int volume); //!< 0..100
void setDeinterlace(bool deinterlace) { m_deinterlace = deinterlace; }
//! This build can deinterlace (FFmpeg's libavfilter was found)
static bool canDeinterlace();
//! Decode video with the GPU, if FFmpeg can for the codec on this platform. Takes effect straight away
void setHardwareDecoding(bool hardware);
void setAVOffset(int ms) { m_avOffset = ms / 1000.0; } //!< Delay of the picture relative to the sound
@ -171,9 +175,9 @@ public: @@ -171,9 +175,9 @@ public:
Info getInfo();
signals:
void servicesChanged(const QList<DVBDemodVideoPlayer::Service>& services);
void servicesChanged(const QList<DTVVideoPlayer::Service>& services);
void serviceSelected(int id, bool hasVideo, bool hasAudio); //!< Whether the service has streams that can be decoded
void tracksChanged(const DVBDemodVideoPlayer::Tracks& tracks);
void tracksChanged(const DTVVideoPlayer::Tracks& tracks);
protected:
void run() override;
@ -205,6 +209,8 @@ private: @@ -205,6 +209,8 @@ private:
static SwsContext *createConverter(int width, int height, int format);
static SwrContext *createResampler(const AVFrame *frame, int rate, bool mono);
static GLVideoSubtitlePtr makeSubtitle(const AVSubtitle& sub, int canvasWidth, int canvasHeight);
//! Of a Track of closed captions, which aren't in a stream of their own
static constexpr int m_captionPid = 0x10000;
static bool getTrack(const AVStream *stream, Track& track);
static int findTrack(const QList<Track>& tracks, std::initializer_list<Track::Type> types, const QString& language);
static int findTrackInLanguage(const QList<Track>& tracks, Track::Type type, const QString& language);
@ -219,6 +225,15 @@ private: @@ -219,6 +225,15 @@ private:
void closeDecoders();
void selectTracks();
void closeTrackDecoders();
//! A frame's closed captions (A/53, CEA-608), decoded into a page shown from its timestamp. In the video thread
void decodeCaptions(const AVFrameSideData *captions, int64_t timestamp);
void closeCaptions();
//! Caption text (lines apart by newlines) as a page, white on black boxes at the bottom of the picture
static GLVideoSubtitlePtr makeCaptions(const QString& text);
//! The text of an ASS event, as FFmpeg's text subtitle decoders give it: its fields and override codes removed
static QString assText(const char *ass);
//! Captions were found in the video: listed as a track, and played if they're preferred
void addCaptionTrack();
void decodeAudioDescription();
void mixAudioDescription(int16_t *samples, int count, double pts, float gain, bool mute);
void parseADDescriptors(const uint8_t *buf, int size);
@ -265,7 +280,7 @@ private: @@ -265,7 +280,7 @@ private:
bool getAudioClock(double& clock);
void closeDeinterlacer();
DVBDemodTSFifo *m_tsFifo;
DTVTSFifo *m_tsFifo;
FrameCallback m_frameCallback;
CanShowCallback m_canShowCallback;
AudioFifo *m_audioFifo;
@ -279,7 +294,7 @@ private: @@ -279,7 +294,7 @@ private:
int m_selectedRequest; //!< m_requestedService when the current service was selected
QList<Service> m_services; //!< As last signalled
std::chrono::steady_clock::time_point m_servicesChecked;
DVBDemodPSI m_psi;
DTVPSI m_psi;
int m_transportStreamId = -1; //!< Of the stream opened, to see when the multiplex changes, -1 until known
AVFormatContext *m_formatCtx;
@ -449,6 +464,14 @@ private: @@ -449,6 +464,14 @@ private:
std::deque<SubtitlePage> m_subtitlePages;
SubtitlePage m_subtitleShown; //!< In the video thread
// Closed captions, in the video's user data (A/53: CEA-608 in CEA-708's cc_data), as ATSC sends them: listed as a
// subtitle track once seen, decoded in the video thread (as FFmpeg gives them with the video frames)
std::atomic<bool> m_captionsSeen{false}; //!< Found in the video of the service, since it was selected
bool m_captionsListed = false; //!< In m_tracks
std::atomic<bool> m_captionsEnabled{false}; //!< Chosen as the subtitles
AVCodecContext *m_captionCtx = nullptr; //!< FFmpeg's CEA-608 decoder, in the video thread
Tracks m_tracks; //!< As last signalled
// Video packets waiting for the video thread
std::thread m_videoThread;
std::mutex m_videoMutex;
@ -540,7 +563,7 @@ private: @@ -540,7 +563,7 @@ private:
Info m_info;
};
Q_DECLARE_METATYPE(DVBDemodVideoPlayer::Service)
Q_DECLARE_METATYPE(DVBDemodVideoPlayer::Tracks)
Q_DECLARE_METATYPE(DTVVideoPlayer::Service)
Q_DECLARE_METATYPE(DTVVideoPlayer::Tracks)
#endif // INCLUDE_DVBDEMODVIDEOPLAYER_H
#endif // INCLUDE_DTVVIDEOPLAYER_H

5
sdrgui/gui/glvideorenderer.cpp

@ -515,14 +515,15 @@ QRect GLVideoRenderer::subtitleRect(const GLVideoSubtitle& subtitle, const QRect @@ -515,14 +515,15 @@ QRect GLVideoRenderer::subtitleRect(const GLVideoSubtitle& subtitle, const QRect
return QRect(x0, y0, x1 - x0, y1 - y0);
}
bool GLVideoRenderer::drawFrame(const GLVideoFramePtr& frame, int width, int height, bool keepAspect, bool deinterlace)
bool GLVideoRenderer::drawFrame(const GLVideoFramePtr& frame, int width, int height, bool keepAspect, bool deinterlace, const QRect& area)
{
if (!m_initialized || !frame || (frame->m_width <= 0) || (frame->m_height <= 0)) {
return false;
}
m_deinterlacing = deinterlace;
const QRect r = videoRect(*frame, width, height, keepAspect);
const QRect r = area.isValid() ? videoRect(*frame, area.width(), area.height(), keepAspect).translated(area.topLeft())
: videoRect(*frame, width, height, keepAspect);
glViewport(r.x(), height - r.y() - r.height(), r.width(), r.height());
glDisable(GL_BLEND);
QOpenGLShaderProgram *p = nullptr;

3
sdrgui/gui/glvideorenderer.h

@ -56,7 +56,8 @@ public: @@ -56,7 +56,8 @@ public:
bool canShow(GLVideoFrame::Type type) const;
//! Draw the frame into the current framebuffer (width x height pixels), letterboxed to its aspect ratio if
//! keepAspect, deinterlacing GPU frames that need it if deinterlace. False if it couldn't be shown
bool drawFrame(const GLVideoFramePtr& frame, int width, int height, bool keepAspect, bool deinterlace);
//! area: where in the width by height viewport the picture's drawn (its aspect kept within it), null for all of it
bool drawFrame(const GLVideoFramePtr& frame, int width, int height, bool keepAspect, bool deinterlace, const QRect& area = QRect());
//! Draw an image, blended, at rect (pixels from the top left) of the framebuffer of width x height pixels
void drawImage(const QImage& image, const QRect& rect, int width, int height);
//! Where the frame is drawn

15
sdrgui/gui/glvideowidget.cpp

@ -17,6 +17,7 @@ @@ -17,6 +17,7 @@
///////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <cmath>
#include <QFontMetrics>
#include <QOpenGLContext>
@ -179,6 +180,15 @@ void GLVideoWidget::setDeinterlace(bool deinterlace) @@ -179,6 +180,15 @@ void GLVideoWidget::setDeinterlace(bool deinterlace)
m_deinterlace = deinterlace;
}
void GLVideoWidget::setVideoArea(const QRectF& area)
{
if (area != m_videoArea)
{
m_videoArea = area;
update();
}
}
QSize GLVideoWidget::getFrameSize() const
{
return m_frameSize;
@ -256,7 +266,10 @@ void GLVideoWidget::paintGL() @@ -256,7 +266,10 @@ void GLVideoWidget::paintGL()
else if (m_current)
{
m_frameSize = QSize(m_current->m_width, m_current->m_height);
m_renderer.drawFrame(m_current, width, height, m_keepAspect, m_deinterlace);
const QRect area = m_videoArea.isNull() ? QRect()
: QRect((int) std::lround(m_videoArea.x() * width), (int) std::lround(m_videoArea.y() * height),
std::max(1, (int) std::lround(m_videoArea.width() * width)), std::max(1, (int) std::lround(m_videoArea.height() * height)));
m_renderer.drawFrame(m_current, width, height, m_keepAspect, m_deinterlace, area);
// The guide shows what the overlay would
if (!m_overlay.isEmpty() && m_guide.isNull())

4
sdrgui/gui/glvideowidget.h

@ -54,6 +54,9 @@ public: @@ -54,6 +54,9 @@ public:
QSize pixelSize() const; //!< Of the widget, in device pixels
void setKeepAspectRatio(bool keep);
void setDeinterlace(bool deinterlace); //!< Of GPU frames the renderer deinterlaces (D3D11)
//! Where the picture's drawn, as fractions of the widget (its aspect kept within it), as an application's video
//! window: null for all of the widget
void setVideoArea(const QRectF& area);
QSize getFrameSize() const; //!< Of the last frame, empty if none
protected:
@ -81,6 +84,7 @@ private: @@ -81,6 +84,7 @@ private:
QImage m_guide;
bool m_keepAspect;
bool m_deinterlace;
QRectF m_videoArea;
QSize m_frameSize;
};

66
swagger/sdrangel/api/swagger/include/DVBDemod.yaml

@ -74,6 +74,11 @@ DVBDemodSettings: @@ -74,6 +74,11 @@ DVBDemodSettings:
type: integer
minimum: 0
maximum: 1
hbbtv:
description: "Run the service's HbbTV applications (the red button) over the video, in the GUI (1 for yes, 0 for no)."
type: integer
minimum: 0
maximum: 1
avOffset:
description: "Milliseconds to delay the picture relative to the sound, for lip sync. Negative to show it earlier."
type: integer
@ -364,6 +369,16 @@ DVBDemodReport: @@ -364,6 +369,16 @@ DVBDemodReport:
description: "A service's schedule, in order, from an hour ago, when epgReport is 2."
items:
$ref: "http://swgserver:8081/api/swagger/include/DVBDemod.yaml#/DVBDemodEPGEvent"
interactiveApps:
type: array
description: "The interactive applications (HbbTV's and others, from the AIT) of the service the report's of."
items:
$ref: "http://swgserver:8081/api/swagger/include/DVBDemod.yaml#/DVBDemodApp"
carousels:
type: array
description: "The object carousels (MHEG-5's and HbbTV's) of the service the report's of, and how much of each has been received."
items:
$ref: "http://swgserver:8081/api/swagger/include/DVBDemod.yaml#/DVBDemodCarousel"
recording:
type: integer
description: Number of recordings in progress
@ -484,6 +499,57 @@ DVBDemodActions: @@ -484,6 +499,57 @@ DVBDemodActions:
format: int64
description: "Downlink frequency, Hz, the scan ends at."
DVBDemodApp:
description: An interactive application of a service, from its application information table (AIT)
properties:
applicationId:
type: string
description: "organisation_id.application_id, in hex."
type:
type: string
description: "HbbTV, DVB-J, DVB-HTML, or the application_type in hex."
controlCode:
type: string
description: "AUTOSTART (started with the service), PRESENT (started by the user, as from the red button), KILL..."
name:
type: string
url:
type: string
description: "Where it starts: an HTTP URL, or a dvb: URL of a file in an object carousel."
carouselPid:
type: integer
description: "PID of the object carousel it's in, -1 if it isn't in one of this service's."
DVBDemodCarousel:
description: An object carousel of a service
properties:
pid:
type: integer
componentTag:
type: integer
carouselId:
type: integer
format: int64
kind:
type: string
description: "MHEG-5, HbbTV (or both, as a broadcaster may send them in one carousel), or DSM-CC."
received:
type: integer
description: "1 if its DSI has been received, so it's being received."
modules:
type: integer
modulesComplete:
type: integer
bytes:
type: integer
format: int64
bytesComplete:
type: integer
format: int64
files:
type: integer
description: "Files received."
DVBDemodEPGService:
description: A service in the DVB programme guide
properties:

233
swagger/sdrangel/code/qt5/client/SWGDVBDemodApp.cpp

@ -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;
}
}

89
swagger/sdrangel/code/qt5/client/SWGDVBDemodApp.h

@ -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_ */

317
swagger/sdrangel/code/qt5/client/SWGDVBDemodCarousel.cpp

@ -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;
}
}

113
swagger/sdrangel/code/qt5/client/SWGDVBDemodCarousel.h

@ -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_ */

138
swagger/sdrangel/code/qt5/client/SWGDVBDemodReport.cpp

@ -66,6 +66,8 @@ SWGDVBDemodReport::SWGDVBDemodReport() { @@ -66,6 +66,8 @@ SWGDVBDemodReport::SWGDVBDemodReport() {
m_ts_bit_rate_isSet = false;
ts_packets = 0L;
m_ts_packets_isSet = false;
search_text = nullptr;
m_search_text_isSet = false;
scan_transponders = 0;
m_scan_transponders_isSet = false;
rs_corrected = 0L;
@ -122,6 +124,10 @@ SWGDVBDemodReport::SWGDVBDemodReport() { @@ -122,6 +124,10 @@ SWGDVBDemodReport::SWGDVBDemodReport() {
m_epg_schedule_network_id_isSet = false;
epg_schedule = nullptr;
m_epg_schedule_isSet = false;
interactive_apps = nullptr;
m_interactive_apps_isSet = false;
carousels = nullptr;
m_carousels_isSet = false;
recording = 0;
m_recording_isSet = false;
recording_file = nullptr;
@ -140,8 +146,6 @@ SWGDVBDemodReport::SWGDVBDemodReport() { @@ -140,8 +146,6 @@ SWGDVBDemodReport::SWGDVBDemodReport() {
m_modcod_isSet = false;
stream_type = nullptr;
m_stream_type_isSet = false;
search_text = nullptr;
m_search_text_isSet = false;
pilots = 0;
m_pilots_isSet = false;
frame_size = nullptr;
@ -206,6 +210,8 @@ SWGDVBDemodReport::init() { @@ -206,6 +210,8 @@ SWGDVBDemodReport::init() {
m_ts_bit_rate_isSet = false;
ts_packets = 0L;
m_ts_packets_isSet = false;
search_text = new QString("");
m_search_text_isSet = false;
scan_transponders = 0;
m_scan_transponders_isSet = false;
rs_corrected = 0L;
@ -262,6 +268,10 @@ SWGDVBDemodReport::init() { @@ -262,6 +268,10 @@ SWGDVBDemodReport::init() {
m_epg_schedule_network_id_isSet = false;
epg_schedule = new QList<SWGDVBDemodEPGEvent*>();
m_epg_schedule_isSet = false;
interactive_apps = new QList<SWGDVBDemodApp*>();
m_interactive_apps_isSet = false;
carousels = new QList<SWGDVBDemodCarousel*>();
m_carousels_isSet = false;
recording = 0;
m_recording_isSet = false;
recording_file = new QString("");
@ -280,8 +290,6 @@ SWGDVBDemodReport::init() { @@ -280,8 +290,6 @@ SWGDVBDemodReport::init() {
m_modcod_isSet = false;
stream_type = new QString("");
m_stream_type_isSet = false;
search_text = new QString("");
m_search_text_isSet = false;
pilots = 0;
m_pilots_isSet = false;
frame_size = new QString("");
@ -337,6 +345,11 @@ SWGDVBDemodReport::cleanup() { @@ -337,6 +345,11 @@ SWGDVBDemodReport::cleanup() {
if(search_text != nullptr) {
delete search_text;
}
if(pilot_pattern != nullptr) {
@ -389,24 +402,46 @@ SWGDVBDemodReport::cleanup() { @@ -389,24 +402,46 @@ SWGDVBDemodReport::cleanup() {
}
delete epg_schedule;
}
if(interactive_apps != nullptr) {
auto arr = interactive_apps;
for(auto o: *arr) {
delete o;
}
delete interactive_apps;
}
if(carousels != nullptr) {
auto arr = carousels;
for(auto o: *arr) {
delete o;
}
delete carousels;
}
if(recording_file != nullptr) {
delete recording_file;
}
if(modcod != nullptr) {
delete modcod;
}
if(stream_type != nullptr) {
delete stream_type;
}
if(search_text != nullptr) {
delete search_text;
}
if(frame_size != nullptr) {
delete frame_size;
}
}
SWGDVBDemodReport*
@ -458,6 +493,8 @@ SWGDVBDemodReport::fromJsonObject(QJsonObject &pJson) { @@ -458,6 +493,8 @@ SWGDVBDemodReport::fromJsonObject(QJsonObject &pJson) {
::SWGSDRangel::setValue(&ts_packets, pJson["tsPackets"], "qint64", "");
::SWGSDRangel::setValue(&search_text, pJson["searchText"], "QString", "QString");
::SWGSDRangel::setValue(&scan_transponders, pJson["scanTransponders"], "qint32", "");
::SWGSDRangel::setValue(&rs_corrected, pJson["rsCorrected"], "qint64", "");
@ -514,6 +551,10 @@ SWGDVBDemodReport::fromJsonObject(QJsonObject &pJson) { @@ -514,6 +551,10 @@ SWGDVBDemodReport::fromJsonObject(QJsonObject &pJson) {
::SWGSDRangel::setValue(&epg_schedule, pJson["epgSchedule"], "QList", "SWGDVBDemodEPGEvent");
::SWGSDRangel::setValue(&interactive_apps, pJson["interactiveApps"], "QList", "SWGDVBDemodApp");
::SWGSDRangel::setValue(&carousels, pJson["carousels"], "QList", "SWGDVBDemodCarousel");
::SWGSDRangel::setValue(&recording, pJson["recording"], "qint32", "");
::SWGSDRangel::setValue(&recording_file, pJson["recordingFile"], "QString", "QString");
@ -529,10 +570,8 @@ SWGDVBDemodReport::fromJsonObject(QJsonObject &pJson) { @@ -529,10 +570,8 @@ SWGDVBDemodReport::fromJsonObject(QJsonObject &pJson) {
::SWGSDRangel::setValue(&roll_off, pJson["rollOff"], "float", "");
::SWGSDRangel::setValue(&modcod, pJson["modcod"], "QString", "QString");
::SWGSDRangel::setValue(&stream_type, pJson["streamType"], "QString", "QString");
::SWGSDRangel::setValue(&search_text, pJson["searchText"], "QString", "QString");
::SWGSDRangel::setValue(&stream_type, pJson["streamType"], "QString", "QString");
::SWGSDRangel::setValue(&pilots, pJson["pilots"], "qint32", "");
@ -625,6 +664,9 @@ SWGDVBDemodReport::asJsonObject() { @@ -625,6 +664,9 @@ SWGDVBDemodReport::asJsonObject() {
if(m_ts_packets_isSet){
obj->insert("tsPackets", QJsonValue(ts_packets));
}
if(search_text != nullptr && *search_text != QString("")){
toJsonValue(QString("searchText"), search_text, obj, QString("QString"));
}
if(m_scan_transponders_isSet){
obj->insert("scanTransponders", QJsonValue(scan_transponders));
}
@ -709,6 +751,12 @@ SWGDVBDemodReport::asJsonObject() { @@ -709,6 +751,12 @@ SWGDVBDemodReport::asJsonObject() {
if(epg_schedule && epg_schedule->size() > 0){
toJsonArray((QList<void*>*)epg_schedule, obj, "epgSchedule", "SWGDVBDemodEPGEvent");
}
if(interactive_apps && interactive_apps->size() > 0){
toJsonArray((QList<void*>*)interactive_apps, obj, "interactiveApps", "SWGDVBDemodApp");
}
if(carousels && carousels->size() > 0){
toJsonArray((QList<void*>*)carousels, obj, "carousels", "SWGDVBDemodCarousel");
}
if(m_recording_isSet){
obj->insert("recording", QJsonValue(recording));
}
@ -721,61 +769,45 @@ SWGDVBDemodReport::asJsonObject() { @@ -721,61 +769,45 @@ SWGDVBDemodReport::asJsonObject() {
if(m_scheduled_recordings_isSet){
obj->insert("scheduledRecordings", QJsonValue(scheduled_recordings));
}
if(m_symbol_rate_isSet){
obj->insert("symbolRate", QJsonValue(symbol_rate));
}
if(m_measured_symbol_rate_isSet){
obj->insert("measuredSymbolRate", QJsonValue(measured_symbol_rate));
}
if(m_roll_off_isSet){
obj->insert("rollOff", QJsonValue(roll_off));
}
if(modcod != nullptr && *modcod != QString("")){
toJsonValue(QString("modcod"), modcod, obj, QString("QString"));
}
if(stream_type != nullptr && *stream_type != QString("")){
toJsonValue(QString("streamType"), stream_type, obj, QString("QString"));
}
if(search_text != nullptr && *search_text != QString("")){
toJsonValue(QString("searchText"), search_text, obj, QString("QString"));
}
if(m_pilots_isSet){
obj->insert("pilots", QJsonValue(pilots));
}
if(frame_size != nullptr && *frame_size != QString("")){
toJsonValue(QString("frameSize"), frame_size, obj, QString("QString"));
}
if(m_isi_isSet){
obj->insert("isi", QJsonValue(isi));
}
if(m_isi_count_isSet){
obj->insert("isiCount", QJsonValue(isi_count));
}
if(m_es_n0_isSet){
obj->insert("esN0", QJsonValue(es_n0));
}
if(m_pl_frames_isSet){
obj->insert("plFrames", QJsonValue(pl_frames));
}
if(m_dummy_frames_isSet){
obj->insert("dummyFrames", QJsonValue(dummy_frames));
}
if(m_pl_header_misses_isSet){
obj->insert("plHeaderMisses", QJsonValue(pl_header_misses));
}
if(m_reacquisitions_isSet){
obj->insert("reacquisitions", QJsonValue(reacquisitions));
}
@ -973,6 +1005,16 @@ SWGDVBDemodReport::setTsPackets(qint64 ts_packets) { @@ -973,6 +1005,16 @@ SWGDVBDemodReport::setTsPackets(qint64 ts_packets) {
this->m_ts_packets_isSet = true;
}
QString*
SWGDVBDemodReport::getSearchText() {
return search_text;
}
void
SWGDVBDemodReport::setSearchText(QString* search_text) {
this->search_text = search_text;
this->m_search_text_isSet = true;
}
qint32
SWGDVBDemodReport::getScanTransponders() {
return scan_transponders;
@ -1253,6 +1295,26 @@ SWGDVBDemodReport::setEpgSchedule(QList<SWGDVBDemodEPGEvent*>* epg_schedule) { @@ -1253,6 +1295,26 @@ SWGDVBDemodReport::setEpgSchedule(QList<SWGDVBDemodEPGEvent*>* epg_schedule) {
this->m_epg_schedule_isSet = true;
}
QList<SWGDVBDemodApp*>*
SWGDVBDemodReport::getInteractiveApps() {
return interactive_apps;
}
void
SWGDVBDemodReport::setInteractiveApps(QList<SWGDVBDemodApp*>* interactive_apps) {
this->interactive_apps = interactive_apps;
this->m_interactive_apps_isSet = true;
}
QList<SWGDVBDemodCarousel*>*
SWGDVBDemodReport::getCarousels() {
return carousels;
}
void
SWGDVBDemodReport::setCarousels(QList<SWGDVBDemodCarousel*>* carousels) {
this->carousels = carousels;
this->m_carousels_isSet = true;
}
qint32
SWGDVBDemodReport::getRecording() {
return recording;
@ -1293,7 +1355,6 @@ SWGDVBDemodReport::setScheduledRecordings(qint32 scheduled_recordings) { @@ -1293,7 +1355,6 @@ SWGDVBDemodReport::setScheduledRecordings(qint32 scheduled_recordings) {
this->m_scheduled_recordings_isSet = true;
}
qint32
SWGDVBDemodReport::getSymbolRate() {
return symbol_rate;
@ -1344,16 +1405,6 @@ SWGDVBDemodReport::setStreamType(QString* stream_type) { @@ -1344,16 +1405,6 @@ SWGDVBDemodReport::setStreamType(QString* stream_type) {
this->m_stream_type_isSet = true;
}
QString*
SWGDVBDemodReport::getSearchText() {
return search_text;
}
void
SWGDVBDemodReport::setSearchText(QString* search_text) {
this->search_text = search_text;
this->m_search_text_isSet = true;
}
qint32
SWGDVBDemodReport::getPilots() {
return pilots;
@ -1444,6 +1495,7 @@ SWGDVBDemodReport::setReacquisitions(qint64 reacquisitions) { @@ -1444,6 +1495,7 @@ SWGDVBDemodReport::setReacquisitions(qint64 reacquisitions) {
this->m_reacquisitions_isSet = true;
}
bool
SWGDVBDemodReport::isSet(){
bool isObjectUpdated = false;
@ -1505,6 +1557,9 @@ SWGDVBDemodReport::isSet(){ @@ -1505,6 +1557,9 @@ SWGDVBDemodReport::isSet(){
if(m_ts_packets_isSet){
isObjectUpdated = true; break;
}
if(search_text && *search_text != QString("")){
isObjectUpdated = true; break;
}
if(m_scan_transponders_isSet){
isObjectUpdated = true; break;
}
@ -1589,6 +1644,12 @@ SWGDVBDemodReport::isSet(){ @@ -1589,6 +1644,12 @@ SWGDVBDemodReport::isSet(){
if(epg_schedule && (epg_schedule->size() > 0)){
isObjectUpdated = true; break;
}
if(interactive_apps && (interactive_apps->size() > 0)){
isObjectUpdated = true; break;
}
if(carousels && (carousels->size() > 0)){
isObjectUpdated = true; break;
}
if(m_recording_isSet){
isObjectUpdated = true; break;
}
@ -1616,9 +1677,6 @@ SWGDVBDemodReport::isSet(){ @@ -1616,9 +1677,6 @@ SWGDVBDemodReport::isSet(){
if(stream_type && *stream_type != QString("")){
isObjectUpdated = true; break;
}
if(search_text && *search_text != QString("")){
isObjectUpdated = true; break;
}
if(m_pilots_isSet){
isObjectUpdated = true; break;
}

28
swagger/sdrangel/code/qt5/client/SWGDVBDemodReport.h

@ -22,6 +22,8 @@ @@ -22,6 +22,8 @@
#include <QJsonObject>
#include "SWGDVBDemodApp.h"
#include "SWGDVBDemodCarousel.h"
#include "SWGDVBDemodEPGEvent.h"
#include "SWGDVBDemodEPGService.h"
#include <QList>
@ -102,6 +104,9 @@ public: @@ -102,6 +104,9 @@ public:
qint64 getTsPackets();
void setTsPackets(qint64 ts_packets);
QString* getSearchText();
void setSearchText(QString* search_text);
qint32 getScanTransponders();
void setScanTransponders(qint32 scan_transponders);
@ -186,6 +191,12 @@ public: @@ -186,6 +191,12 @@ public:
QList<SWGDVBDemodEPGEvent*>* getEpgSchedule();
void setEpgSchedule(QList<SWGDVBDemodEPGEvent*>* epg_schedule);
QList<SWGDVBDemodApp*>* getInteractiveApps();
void setInteractiveApps(QList<SWGDVBDemodApp*>* interactive_apps);
QList<SWGDVBDemodCarousel*>* getCarousels();
void setCarousels(QList<SWGDVBDemodCarousel*>* carousels);
qint32 getRecording();
void setRecording(qint32 recording);
@ -198,7 +209,6 @@ public: @@ -198,7 +209,6 @@ public:
qint32 getScheduledRecordings();
void setScheduledRecordings(qint32 scheduled_recordings);
qint32 getSymbolRate();
void setSymbolRate(qint32 symbol_rate);
@ -214,9 +224,6 @@ public: @@ -214,9 +224,6 @@ public:
QString* getStreamType();
void setStreamType(QString* stream_type);
QString* getSearchText();
void setSearchText(QString* search_text);
qint32 getPilots();
void setPilots(qint32 pilots);
@ -244,6 +251,7 @@ public: @@ -244,6 +251,7 @@ public:
qint64 getReacquisitions();
void setReacquisitions(qint64 reacquisitions);
virtual bool isSet() override;
private:
@ -304,6 +312,9 @@ private: @@ -304,6 +312,9 @@ private:
qint64 ts_packets;
bool m_ts_packets_isSet;
QString* search_text;
bool m_search_text_isSet;
qint32 scan_transponders;
bool m_scan_transponders_isSet;
@ -388,6 +399,12 @@ private: @@ -388,6 +399,12 @@ private:
QList<SWGDVBDemodEPGEvent*>* epg_schedule;
bool m_epg_schedule_isSet;
QList<SWGDVBDemodApp*>* interactive_apps;
bool m_interactive_apps_isSet;
QList<SWGDVBDemodCarousel*>* carousels;
bool m_carousels_isSet;
qint32 recording;
bool m_recording_isSet;
@ -415,9 +432,6 @@ private: @@ -415,9 +432,6 @@ private:
QString* stream_type;
bool m_stream_type_isSet;
QString* search_text;
bool m_search_text_isSet;
qint32 pilots;
bool m_pilots_isSet;

590
swagger/sdrangel/code/qt5/client/SWGDVBDemodSettings.cpp

@ -38,6 +38,24 @@ SWGDVBDemodSettings::SWGDVBDemodSettings() { @@ -38,6 +38,24 @@ SWGDVBDemodSettings::SWGDVBDemodSettings() {
m_plp_id_isSet = false;
low_priority = 0;
m_low_priority_isSet = false;
symbol_rate = 0;
m_symbol_rate_isSet = false;
roll_off = 0;
m_roll_off_isSet = false;
code_rate = 0;
m_code_rate_isSet = false;
isi = 0;
m_isi_isSet = false;
pl_scrambling_code = 0;
m_pl_scrambling_code_isSet = false;
equaliser = 0;
m_equaliser_isSet = false;
freesat_region = 0;
m_freesat_region_isSet = false;
record_retune = 0;
m_record_retune_isSet = false;
record_follow_running = 0;
m_record_follow_running_isSet = false;
udp_enabled = 0;
m_udp_enabled_isSet = false;
udp_address = nullptr;
@ -50,6 +68,8 @@ SWGDVBDemodSettings::SWGDVBDemodSettings() { @@ -50,6 +68,8 @@ SWGDVBDemodSettings::SWGDVBDemodSettings() {
m_service_id_isSet = false;
deinterlace = 0;
m_deinterlace_isSet = false;
hbbtv = 0;
m_hbbtv_isSet = false;
av_offset = 0;
m_av_offset_isSet = false;
hardware_decoding = 0;
@ -58,6 +78,12 @@ SWGDVBDemodSettings::SWGDVBDemodSettings() { @@ -58,6 +78,12 @@ SWGDVBDemodSettings::SWGDVBDemodSettings() {
m_audio_language_isSet = false;
audio_description = 0;
m_audio_description_isSet = false;
audio_description_mixed = 0;
m_audio_description_mixed_isSet = false;
clean_audio = 0;
m_clean_audio_isSet = false;
subtitles_hard_of_hearing = 0;
m_subtitles_hard_of_hearing_isSet = false;
subtitles = 0;
m_subtitles_isSet = false;
subtitle_language = nullptr;
@ -102,30 +128,6 @@ SWGDVBDemodSettings::SWGDVBDemodSettings() { @@ -102,30 +128,6 @@ SWGDVBDemodSettings::SWGDVBDemodSettings() {
m_channel_marker_isSet = false;
rollup_state = nullptr;
m_rollup_state_isSet = false;
symbol_rate = 0;
m_symbol_rate_isSet = false;
roll_off = 0;
m_roll_off_isSet = false;
code_rate = 0;
m_code_rate_isSet = false;
isi = 0;
m_isi_isSet = false;
pl_scrambling_code = 0;
m_pl_scrambling_code_isSet = false;
equaliser = 0;
m_equaliser_isSet = false;
audio_description_mixed = 0;
m_audio_description_mixed_isSet = false;
clean_audio = 0;
m_clean_audio_isSet = false;
subtitles_hard_of_hearing = 0;
m_subtitles_hard_of_hearing_isSet = false;
record_retune = 0;
m_record_retune_isSet = false;
record_follow_running = 0;
m_record_follow_running_isSet = false;
freesat_region = 0;
m_freesat_region_isSet = false;
}
SWGDVBDemodSettings::~SWGDVBDemodSettings() {
@ -144,6 +146,24 @@ SWGDVBDemodSettings::init() { @@ -144,6 +146,24 @@ SWGDVBDemodSettings::init() {
m_plp_id_isSet = false;
low_priority = 0;
m_low_priority_isSet = false;
symbol_rate = 0;
m_symbol_rate_isSet = false;
roll_off = 0;
m_roll_off_isSet = false;
code_rate = 0;
m_code_rate_isSet = false;
isi = 0;
m_isi_isSet = false;
pl_scrambling_code = 0;
m_pl_scrambling_code_isSet = false;
equaliser = 0;
m_equaliser_isSet = false;
freesat_region = 0;
m_freesat_region_isSet = false;
record_retune = 0;
m_record_retune_isSet = false;
record_follow_running = 0;
m_record_follow_running_isSet = false;
udp_enabled = 0;
m_udp_enabled_isSet = false;
udp_address = new QString("");
@ -156,6 +176,8 @@ SWGDVBDemodSettings::init() { @@ -156,6 +176,8 @@ SWGDVBDemodSettings::init() {
m_service_id_isSet = false;
deinterlace = 0;
m_deinterlace_isSet = false;
hbbtv = 0;
m_hbbtv_isSet = false;
av_offset = 0;
m_av_offset_isSet = false;
hardware_decoding = 0;
@ -164,6 +186,12 @@ SWGDVBDemodSettings::init() { @@ -164,6 +186,12 @@ SWGDVBDemodSettings::init() {
m_audio_language_isSet = false;
audio_description = 0;
m_audio_description_isSet = false;
audio_description_mixed = 0;
m_audio_description_mixed_isSet = false;
clean_audio = 0;
m_clean_audio_isSet = false;
subtitles_hard_of_hearing = 0;
m_subtitles_hard_of_hearing_isSet = false;
subtitles = 0;
m_subtitles_isSet = false;
subtitle_language = new QString("");
@ -208,30 +236,6 @@ SWGDVBDemodSettings::init() { @@ -208,30 +236,6 @@ SWGDVBDemodSettings::init() {
m_channel_marker_isSet = false;
rollup_state = new SWGRollupState();
m_rollup_state_isSet = false;
symbol_rate = 0;
m_symbol_rate_isSet = false;
roll_off = 0;
m_roll_off_isSet = false;
code_rate = 0;
m_code_rate_isSet = false;
isi = 0;
m_isi_isSet = false;
pl_scrambling_code = 0;
m_pl_scrambling_code_isSet = false;
equaliser = 0;
m_equaliser_isSet = false;
audio_description_mixed = 0;
m_audio_description_mixed_isSet = false;
clean_audio = 0;
m_clean_audio_isSet = false;
subtitles_hard_of_hearing = 0;
m_subtitles_hard_of_hearing_isSet = false;
record_retune = 0;
m_record_retune_isSet = false;
record_follow_running = 0;
m_record_follow_running_isSet = false;
freesat_region = 0;
m_freesat_region_isSet = false;
}
void
@ -242,6 +246,15 @@ SWGDVBDemodSettings::cleanup() { @@ -242,6 +246,15 @@ SWGDVBDemodSettings::cleanup() {
if(udp_address != nullptr) {
delete udp_address;
}
@ -251,11 +264,15 @@ SWGDVBDemodSettings::cleanup() { @@ -251,11 +264,15 @@ SWGDVBDemodSettings::cleanup() {
if(audio_language != nullptr) {
delete audio_language;
}
if(subtitle_language != nullptr) {
delete subtitle_language;
}
@ -314,6 +331,24 @@ SWGDVBDemodSettings::fromJsonObject(QJsonObject &pJson) { @@ -314,6 +331,24 @@ SWGDVBDemodSettings::fromJsonObject(QJsonObject &pJson) {
::SWGSDRangel::setValue(&low_priority, pJson["lowPriority"], "qint32", "");
::SWGSDRangel::setValue(&symbol_rate, pJson["symbolRate"], "qint32", "");
::SWGSDRangel::setValue(&roll_off, pJson["rollOff"], "qint32", "");
::SWGSDRangel::setValue(&code_rate, pJson["codeRate"], "qint32", "");
::SWGSDRangel::setValue(&isi, pJson["isi"], "qint32", "");
::SWGSDRangel::setValue(&pl_scrambling_code, pJson["plScramblingCode"], "qint32", "");
::SWGSDRangel::setValue(&equaliser, pJson["equaliser"], "qint32", "");
::SWGSDRangel::setValue(&freesat_region, pJson["freesatRegion"], "qint32", "");
::SWGSDRangel::setValue(&record_retune, pJson["recordRetune"], "qint32", "");
::SWGSDRangel::setValue(&record_follow_running, pJson["recordFollowRunning"], "qint32", "");
::SWGSDRangel::setValue(&udp_enabled, pJson["udpEnabled"], "qint32", "");
::SWGSDRangel::setValue(&udp_address, pJson["udpAddress"], "QString", "QString");
@ -326,6 +361,8 @@ SWGDVBDemodSettings::fromJsonObject(QJsonObject &pJson) { @@ -326,6 +361,8 @@ SWGDVBDemodSettings::fromJsonObject(QJsonObject &pJson) {
::SWGSDRangel::setValue(&deinterlace, pJson["deinterlace"], "qint32", "");
::SWGSDRangel::setValue(&hbbtv, pJson["hbbtv"], "qint32", "");
::SWGSDRangel::setValue(&av_offset, pJson["avOffset"], "qint32", "");
::SWGSDRangel::setValue(&hardware_decoding, pJson["hardwareDecoding"], "qint32", "");
@ -334,6 +371,12 @@ SWGDVBDemodSettings::fromJsonObject(QJsonObject &pJson) { @@ -334,6 +371,12 @@ SWGDVBDemodSettings::fromJsonObject(QJsonObject &pJson) {
::SWGSDRangel::setValue(&audio_description, pJson["audioDescription"], "qint32", "");
::SWGSDRangel::setValue(&audio_description_mixed, pJson["audioDescriptionMixed"], "qint32", "");
::SWGSDRangel::setValue(&clean_audio, pJson["cleanAudio"], "qint32", "");
::SWGSDRangel::setValue(&subtitles_hard_of_hearing, pJson["subtitlesHardOfHearing"], "qint32", "");
::SWGSDRangel::setValue(&subtitles, pJson["subtitles"], "qint32", "");
::SWGSDRangel::setValue(&subtitle_language, pJson["subtitleLanguage"], "QString", "QString");
@ -378,25 +421,6 @@ SWGDVBDemodSettings::fromJsonObject(QJsonObject &pJson) { @@ -378,25 +421,6 @@ SWGDVBDemodSettings::fromJsonObject(QJsonObject &pJson) {
::SWGSDRangel::setValue(&rollup_state, pJson["rollupState"], "SWGRollupState", "SWGRollupState");
::SWGSDRangel::setValue(&symbol_rate, pJson["symbolRate"], "qint32", "");
::SWGSDRangel::setValue(&roll_off, pJson["rollOff"], "qint32", "");
::SWGSDRangel::setValue(&code_rate, pJson["codeRate"], "qint32", "");
::SWGSDRangel::setValue(&isi, pJson["isi"], "qint32", "");
::SWGSDRangel::setValue(&pl_scrambling_code, pJson["plScramblingCode"], "qint32", "");
::SWGSDRangel::setValue(&equaliser, pJson["equaliser"], "qint32", "");
::SWGSDRangel::setValue(&audio_description_mixed, pJson["audioDescriptionMixed"], "qint32", "");
::SWGSDRangel::setValue(&clean_audio, pJson["cleanAudio"], "qint32", "");
::SWGSDRangel::setValue(&subtitles_hard_of_hearing, pJson["subtitlesHardOfHearing"], "qint32", "");
::SWGSDRangel::setValue(&record_retune, pJson["recordRetune"], "qint32", "");
::SWGSDRangel::setValue(&record_follow_running, pJson["recordFollowRunning"], "qint32", "");
::SWGSDRangel::setValue(&freesat_region, pJson["freesatRegion"], "qint32", "");
}
QString
@ -428,6 +452,33 @@ SWGDVBDemodSettings::asJsonObject() { @@ -428,6 +452,33 @@ SWGDVBDemodSettings::asJsonObject() {
if(m_low_priority_isSet){
obj->insert("lowPriority", QJsonValue(low_priority));
}
if(m_symbol_rate_isSet){
obj->insert("symbolRate", QJsonValue(symbol_rate));
}
if(m_roll_off_isSet){
obj->insert("rollOff", QJsonValue(roll_off));
}
if(m_code_rate_isSet){
obj->insert("codeRate", QJsonValue(code_rate));
}
if(m_isi_isSet){
obj->insert("isi", QJsonValue(isi));
}
if(m_pl_scrambling_code_isSet){
obj->insert("plScramblingCode", QJsonValue(pl_scrambling_code));
}
if(m_equaliser_isSet){
obj->insert("equaliser", QJsonValue(equaliser));
}
if(m_freesat_region_isSet){
obj->insert("freesatRegion", QJsonValue(freesat_region));
}
if(m_record_retune_isSet){
obj->insert("recordRetune", QJsonValue(record_retune));
}
if(m_record_follow_running_isSet){
obj->insert("recordFollowRunning", QJsonValue(record_follow_running));
}
if(m_udp_enabled_isSet){
obj->insert("udpEnabled", QJsonValue(udp_enabled));
}
@ -446,6 +497,9 @@ SWGDVBDemodSettings::asJsonObject() { @@ -446,6 +497,9 @@ SWGDVBDemodSettings::asJsonObject() {
if(m_deinterlace_isSet){
obj->insert("deinterlace", QJsonValue(deinterlace));
}
if(m_hbbtv_isSet){
obj->insert("hbbtv", QJsonValue(hbbtv));
}
if(m_av_offset_isSet){
obj->insert("avOffset", QJsonValue(av_offset));
}
@ -458,6 +512,15 @@ SWGDVBDemodSettings::asJsonObject() { @@ -458,6 +512,15 @@ SWGDVBDemodSettings::asJsonObject() {
if(m_audio_description_isSet){
obj->insert("audioDescription", QJsonValue(audio_description));
}
if(m_audio_description_mixed_isSet){
obj->insert("audioDescriptionMixed", QJsonValue(audio_description_mixed));
}
if(m_clean_audio_isSet){
obj->insert("cleanAudio", QJsonValue(clean_audio));
}
if(m_subtitles_hard_of_hearing_isSet){
obj->insert("subtitlesHardOfHearing", QJsonValue(subtitles_hard_of_hearing));
}
if(m_subtitles_isSet){
obj->insert("subtitles", QJsonValue(subtitles));
}
@ -525,48 +588,6 @@ SWGDVBDemodSettings::asJsonObject() { @@ -525,48 +588,6 @@ SWGDVBDemodSettings::asJsonObject() {
toJsonValue(QString("rollupState"), rollup_state, obj, QString("SWGRollupState"));
}
if(m_symbol_rate_isSet){
obj->insert("symbolRate", QJsonValue(symbol_rate));
}
if(m_roll_off_isSet){
obj->insert("rollOff", QJsonValue(roll_off));
}
if(m_code_rate_isSet){
obj->insert("codeRate", QJsonValue(code_rate));
}
if(m_isi_isSet){
obj->insert("isi", QJsonValue(isi));
}
if(m_pl_scrambling_code_isSet){
obj->insert("plScramblingCode", QJsonValue(pl_scrambling_code));
}
if(m_equaliser_isSet){
obj->insert("equaliser", QJsonValue(equaliser));
}
if(m_audio_description_mixed_isSet){
obj->insert("audioDescriptionMixed", QJsonValue(audio_description_mixed));
}
if(m_clean_audio_isSet){
obj->insert("cleanAudio", QJsonValue(clean_audio));
}
if(m_subtitles_hard_of_hearing_isSet){
obj->insert("subtitlesHardOfHearing", QJsonValue(subtitles_hard_of_hearing));
}
if(m_record_retune_isSet){
obj->insert("recordRetune", QJsonValue(record_retune));
}
if(m_record_follow_running_isSet){
obj->insert("recordFollowRunning", QJsonValue(record_follow_running));
}
if(m_freesat_region_isSet){
obj->insert("freesatRegion", QJsonValue(freesat_region));
}
return obj;
}
@ -621,28 +642,118 @@ SWGDVBDemodSettings::setLowPriority(qint32 low_priority) { @@ -621,28 +642,118 @@ SWGDVBDemodSettings::setLowPriority(qint32 low_priority) {
}
qint32
SWGDVBDemodSettings::getUdpEnabled() {
return udp_enabled;
SWGDVBDemodSettings::getSymbolRate() {
return symbol_rate;
}
void
SWGDVBDemodSettings::setUdpEnabled(qint32 udp_enabled) {
this->udp_enabled = udp_enabled;
this->m_udp_enabled_isSet = true;
SWGDVBDemodSettings::setSymbolRate(qint32 symbol_rate) {
this->symbol_rate = symbol_rate;
this->m_symbol_rate_isSet = true;
}
QString*
SWGDVBDemodSettings::getUdpAddress() {
return udp_address;
qint32
SWGDVBDemodSettings::getRollOff() {
return roll_off;
}
void
SWGDVBDemodSettings::setUdpAddress(QString* udp_address) {
this->udp_address = udp_address;
this->m_udp_address_isSet = true;
SWGDVBDemodSettings::setRollOff(qint32 roll_off) {
this->roll_off = roll_off;
this->m_roll_off_isSet = true;
}
qint32
SWGDVBDemodSettings::getUdpPort() {
return udp_port;
SWGDVBDemodSettings::getCodeRate() {
return code_rate;
}
void
SWGDVBDemodSettings::setCodeRate(qint32 code_rate) {
this->code_rate = code_rate;
this->m_code_rate_isSet = true;
}
qint32
SWGDVBDemodSettings::getIsi() {
return isi;
}
void
SWGDVBDemodSettings::setIsi(qint32 isi) {
this->isi = isi;
this->m_isi_isSet = true;
}
qint32
SWGDVBDemodSettings::getPlScramblingCode() {
return pl_scrambling_code;
}
void
SWGDVBDemodSettings::setPlScramblingCode(qint32 pl_scrambling_code) {
this->pl_scrambling_code = pl_scrambling_code;
this->m_pl_scrambling_code_isSet = true;
}
qint32
SWGDVBDemodSettings::getEqualiser() {
return equaliser;
}
void
SWGDVBDemodSettings::setEqualiser(qint32 equaliser) {
this->equaliser = equaliser;
this->m_equaliser_isSet = true;
}
qint32
SWGDVBDemodSettings::getFreesatRegion() {
return freesat_region;
}
void
SWGDVBDemodSettings::setFreesatRegion(qint32 freesat_region) {
this->freesat_region = freesat_region;
this->m_freesat_region_isSet = true;
}
qint32
SWGDVBDemodSettings::getRecordRetune() {
return record_retune;
}
void
SWGDVBDemodSettings::setRecordRetune(qint32 record_retune) {
this->record_retune = record_retune;
this->m_record_retune_isSet = true;
}
qint32
SWGDVBDemodSettings::getRecordFollowRunning() {
return record_follow_running;
}
void
SWGDVBDemodSettings::setRecordFollowRunning(qint32 record_follow_running) {
this->record_follow_running = record_follow_running;
this->m_record_follow_running_isSet = true;
}
qint32
SWGDVBDemodSettings::getUdpEnabled() {
return udp_enabled;
}
void
SWGDVBDemodSettings::setUdpEnabled(qint32 udp_enabled) {
this->udp_enabled = udp_enabled;
this->m_udp_enabled_isSet = true;
}
QString*
SWGDVBDemodSettings::getUdpAddress() {
return udp_address;
}
void
SWGDVBDemodSettings::setUdpAddress(QString* udp_address) {
this->udp_address = udp_address;
this->m_udp_address_isSet = true;
}
qint32
SWGDVBDemodSettings::getUdpPort() {
return udp_port;
}
void
SWGDVBDemodSettings::setUdpPort(qint32 udp_port) {
@ -680,6 +791,16 @@ SWGDVBDemodSettings::setDeinterlace(qint32 deinterlace) { @@ -680,6 +791,16 @@ SWGDVBDemodSettings::setDeinterlace(qint32 deinterlace) {
this->m_deinterlace_isSet = true;
}
qint32
SWGDVBDemodSettings::getHbbtv() {
return hbbtv;
}
void
SWGDVBDemodSettings::setHbbtv(qint32 hbbtv) {
this->hbbtv = hbbtv;
this->m_hbbtv_isSet = true;
}
qint32
SWGDVBDemodSettings::getAvOffset() {
return av_offset;
@ -720,6 +841,36 @@ SWGDVBDemodSettings::setAudioDescription(qint32 audio_description) { @@ -720,6 +841,36 @@ SWGDVBDemodSettings::setAudioDescription(qint32 audio_description) {
this->m_audio_description_isSet = true;
}
qint32
SWGDVBDemodSettings::getAudioDescriptionMixed() {
return audio_description_mixed;
}
void
SWGDVBDemodSettings::setAudioDescriptionMixed(qint32 audio_description_mixed) {
this->audio_description_mixed = audio_description_mixed;
this->m_audio_description_mixed_isSet = true;
}
qint32
SWGDVBDemodSettings::getCleanAudio() {
return clean_audio;
}
void
SWGDVBDemodSettings::setCleanAudio(qint32 clean_audio) {
this->clean_audio = clean_audio;
this->m_clean_audio_isSet = true;
}
qint32
SWGDVBDemodSettings::getSubtitlesHardOfHearing() {
return subtitles_hard_of_hearing;
}
void
SWGDVBDemodSettings::setSubtitlesHardOfHearing(qint32 subtitles_hard_of_hearing) {
this->subtitles_hard_of_hearing = subtitles_hard_of_hearing;
this->m_subtitles_hard_of_hearing_isSet = true;
}
qint32
SWGDVBDemodSettings::getSubtitles() {
return subtitles;
@ -941,126 +1092,6 @@ SWGDVBDemodSettings::setRollupState(SWGRollupState* rollup_state) { @@ -941,126 +1092,6 @@ SWGDVBDemodSettings::setRollupState(SWGRollupState* rollup_state) {
}
qint32
SWGDVBDemodSettings::getSymbolRate() {
return symbol_rate;
}
void
SWGDVBDemodSettings::setSymbolRate(qint32 symbol_rate) {
this->symbol_rate = symbol_rate;
this->m_symbol_rate_isSet = true;
}
qint32
SWGDVBDemodSettings::getRollOff() {
return roll_off;
}
void
SWGDVBDemodSettings::setRollOff(qint32 roll_off) {
this->roll_off = roll_off;
this->m_roll_off_isSet = true;
}
qint32
SWGDVBDemodSettings::getCodeRate() {
return code_rate;
}
void
SWGDVBDemodSettings::setCodeRate(qint32 code_rate) {
this->code_rate = code_rate;
this->m_code_rate_isSet = true;
}
qint32
SWGDVBDemodSettings::getIsi() {
return isi;
}
void
SWGDVBDemodSettings::setIsi(qint32 isi) {
this->isi = isi;
this->m_isi_isSet = true;
}
qint32
SWGDVBDemodSettings::getPlScramblingCode() {
return pl_scrambling_code;
}
void
SWGDVBDemodSettings::setPlScramblingCode(qint32 pl_scrambling_code) {
this->pl_scrambling_code = pl_scrambling_code;
this->m_pl_scrambling_code_isSet = true;
}
qint32
SWGDVBDemodSettings::getEqualiser() {
return equaliser;
}
void
SWGDVBDemodSettings::setEqualiser(qint32 equaliser) {
this->equaliser = equaliser;
this->m_equaliser_isSet = true;
}
qint32
SWGDVBDemodSettings::getAudioDescriptionMixed() {
return audio_description_mixed;
}
void
SWGDVBDemodSettings::setAudioDescriptionMixed(qint32 audio_description_mixed) {
this->audio_description_mixed = audio_description_mixed;
this->m_audio_description_mixed_isSet = true;
}
qint32
SWGDVBDemodSettings::getCleanAudio() {
return clean_audio;
}
void
SWGDVBDemodSettings::setCleanAudio(qint32 clean_audio) {
this->clean_audio = clean_audio;
this->m_clean_audio_isSet = true;
}
qint32
SWGDVBDemodSettings::getSubtitlesHardOfHearing() {
return subtitles_hard_of_hearing;
}
void
SWGDVBDemodSettings::setSubtitlesHardOfHearing(qint32 subtitles_hard_of_hearing) {
this->subtitles_hard_of_hearing = subtitles_hard_of_hearing;
this->m_subtitles_hard_of_hearing_isSet = true;
}
qint32
SWGDVBDemodSettings::getRecordRetune() {
return record_retune;
}
void
SWGDVBDemodSettings::setRecordRetune(qint32 record_retune) {
this->record_retune = record_retune;
this->m_record_retune_isSet = true;
}
qint32
SWGDVBDemodSettings::getRecordFollowRunning() {
return record_follow_running;
}
void
SWGDVBDemodSettings::setRecordFollowRunning(qint32 record_follow_running) {
this->record_follow_running = record_follow_running;
this->m_record_follow_running_isSet = true;
}
qint32
SWGDVBDemodSettings::getFreesatRegion() {
return freesat_region;
}
void
SWGDVBDemodSettings::setFreesatRegion(qint32 freesat_region) {
this->freesat_region = freesat_region;
this->m_freesat_region_isSet = true;
}
bool
SWGDVBDemodSettings::isSet(){
bool isObjectUpdated = false;
@ -1080,6 +1111,33 @@ SWGDVBDemodSettings::isSet(){ @@ -1080,6 +1111,33 @@ SWGDVBDemodSettings::isSet(){
if(m_low_priority_isSet){
isObjectUpdated = true; break;
}
if(m_symbol_rate_isSet){
isObjectUpdated = true; break;
}
if(m_roll_off_isSet){
isObjectUpdated = true; break;
}
if(m_code_rate_isSet){
isObjectUpdated = true; break;
}
if(m_isi_isSet){
isObjectUpdated = true; break;
}
if(m_pl_scrambling_code_isSet){
isObjectUpdated = true; break;
}
if(m_equaliser_isSet){
isObjectUpdated = true; break;
}
if(m_freesat_region_isSet){
isObjectUpdated = true; break;
}
if(m_record_retune_isSet){
isObjectUpdated = true; break;
}
if(m_record_follow_running_isSet){
isObjectUpdated = true; break;
}
if(m_udp_enabled_isSet){
isObjectUpdated = true; break;
}
@ -1098,6 +1156,9 @@ SWGDVBDemodSettings::isSet(){ @@ -1098,6 +1156,9 @@ SWGDVBDemodSettings::isSet(){
if(m_deinterlace_isSet){
isObjectUpdated = true; break;
}
if(m_hbbtv_isSet){
isObjectUpdated = true; break;
}
if(m_av_offset_isSet){
isObjectUpdated = true; break;
}
@ -1110,6 +1171,15 @@ SWGDVBDemodSettings::isSet(){ @@ -1110,6 +1171,15 @@ SWGDVBDemodSettings::isSet(){
if(m_audio_description_isSet){
isObjectUpdated = true; break;
}
if(m_audio_description_mixed_isSet){
isObjectUpdated = true; break;
}
if(m_clean_audio_isSet){
isObjectUpdated = true; break;
}
if(m_subtitles_hard_of_hearing_isSet){
isObjectUpdated = true; break;
}
if(m_subtitles_isSet){
isObjectUpdated = true; break;
}
@ -1176,42 +1246,6 @@ SWGDVBDemodSettings::isSet(){ @@ -1176,42 +1246,6 @@ SWGDVBDemodSettings::isSet(){
if(rollup_state && rollup_state->isSet()){
isObjectUpdated = true; break;
}
if(m_symbol_rate_isSet){
isObjectUpdated = true; break;
}
if(m_roll_off_isSet){
isObjectUpdated = true; break;
}
if(m_code_rate_isSet){
isObjectUpdated = true; break;
}
if(m_isi_isSet){
isObjectUpdated = true; break;
}
if(m_pl_scrambling_code_isSet){
isObjectUpdated = true; break;
}
if(m_equaliser_isSet){
isObjectUpdated = true; break;
}
if(m_audio_description_mixed_isSet){
isObjectUpdated = true; break;
}
if(m_clean_audio_isSet){
isObjectUpdated = true; break;
}
if(m_subtitles_hard_of_hearing_isSet){
isObjectUpdated = true; break;
}
if(m_record_retune_isSet){
isObjectUpdated = true; break;
}
if(m_record_follow_running_isSet){
isObjectUpdated = true; break;
}
if(m_freesat_region_isSet){
isObjectUpdated = true; break;
}
}while(false);
return isObjectUpdated;
}

150
swagger/sdrangel/code/qt5/client/SWGDVBDemodSettings.h

@ -59,6 +59,33 @@ public: @@ -59,6 +59,33 @@ public:
qint32 getLowPriority();
void setLowPriority(qint32 low_priority);
qint32 getSymbolRate();
void setSymbolRate(qint32 symbol_rate);
qint32 getRollOff();
void setRollOff(qint32 roll_off);
qint32 getCodeRate();
void setCodeRate(qint32 code_rate);
qint32 getIsi();
void setIsi(qint32 isi);
qint32 getPlScramblingCode();
void setPlScramblingCode(qint32 pl_scrambling_code);
qint32 getEqualiser();
void setEqualiser(qint32 equaliser);
qint32 getFreesatRegion();
void setFreesatRegion(qint32 freesat_region);
qint32 getRecordRetune();
void setRecordRetune(qint32 record_retune);
qint32 getRecordFollowRunning();
void setRecordFollowRunning(qint32 record_follow_running);
qint32 getUdpEnabled();
void setUdpEnabled(qint32 udp_enabled);
@ -77,6 +104,9 @@ public: @@ -77,6 +104,9 @@ public:
qint32 getDeinterlace();
void setDeinterlace(qint32 deinterlace);
qint32 getHbbtv();
void setHbbtv(qint32 hbbtv);
qint32 getAvOffset();
void setAvOffset(qint32 av_offset);
@ -89,6 +119,15 @@ public: @@ -89,6 +119,15 @@ public:
qint32 getAudioDescription();
void setAudioDescription(qint32 audio_description);
qint32 getAudioDescriptionMixed();
void setAudioDescriptionMixed(qint32 audio_description_mixed);
qint32 getCleanAudio();
void setCleanAudio(qint32 clean_audio);
qint32 getSubtitlesHardOfHearing();
void setSubtitlesHardOfHearing(qint32 subtitles_hard_of_hearing);
qint32 getSubtitles();
void setSubtitles(qint32 subtitles);
@ -156,42 +195,6 @@ public: @@ -156,42 +195,6 @@ public:
void setRollupState(SWGRollupState* rollup_state);
qint32 getSymbolRate();
void setSymbolRate(qint32 symbol_rate);
qint32 getRollOff();
void setRollOff(qint32 roll_off);
qint32 getCodeRate();
void setCodeRate(qint32 code_rate);
qint32 getIsi();
void setIsi(qint32 isi);
qint32 getPlScramblingCode();
void setPlScramblingCode(qint32 pl_scrambling_code);
qint32 getEqualiser();
void setEqualiser(qint32 equaliser);
qint32 getAudioDescriptionMixed();
void setAudioDescriptionMixed(qint32 audio_description_mixed);
qint32 getCleanAudio();
void setCleanAudio(qint32 clean_audio);
qint32 getSubtitlesHardOfHearing();
void setSubtitlesHardOfHearing(qint32 subtitles_hard_of_hearing);
qint32 getRecordRetune();
void setRecordRetune(qint32 record_retune);
qint32 getRecordFollowRunning();
void setRecordFollowRunning(qint32 record_follow_running);
qint32 getFreesatRegion();
void setFreesatRegion(qint32 freesat_region);
virtual bool isSet() override;
private:
@ -210,6 +213,33 @@ private: @@ -210,6 +213,33 @@ private:
qint32 low_priority;
bool m_low_priority_isSet;
qint32 symbol_rate;
bool m_symbol_rate_isSet;
qint32 roll_off;
bool m_roll_off_isSet;
qint32 code_rate;
bool m_code_rate_isSet;
qint32 isi;
bool m_isi_isSet;
qint32 pl_scrambling_code;
bool m_pl_scrambling_code_isSet;
qint32 equaliser;
bool m_equaliser_isSet;
qint32 freesat_region;
bool m_freesat_region_isSet;
qint32 record_retune;
bool m_record_retune_isSet;
qint32 record_follow_running;
bool m_record_follow_running_isSet;
qint32 udp_enabled;
bool m_udp_enabled_isSet;
@ -228,6 +258,9 @@ private: @@ -228,6 +258,9 @@ private:
qint32 deinterlace;
bool m_deinterlace_isSet;
qint32 hbbtv;
bool m_hbbtv_isSet;
qint32 av_offset;
bool m_av_offset_isSet;
@ -240,6 +273,15 @@ private: @@ -240,6 +273,15 @@ private:
qint32 audio_description;
bool m_audio_description_isSet;
qint32 audio_description_mixed;
bool m_audio_description_mixed_isSet;
qint32 clean_audio;
bool m_clean_audio_isSet;
qint32 subtitles_hard_of_hearing;
bool m_subtitles_hard_of_hearing_isSet;
qint32 subtitles;
bool m_subtitles_isSet;
@ -306,42 +348,6 @@ private: @@ -306,42 +348,6 @@ private:
SWGRollupState* rollup_state;
bool m_rollup_state_isSet;
qint32 symbol_rate;
bool m_symbol_rate_isSet;
qint32 roll_off;
bool m_roll_off_isSet;
qint32 code_rate;
bool m_code_rate_isSet;
qint32 isi;
bool m_isi_isSet;
qint32 pl_scrambling_code;
bool m_pl_scrambling_code_isSet;
qint32 equaliser;
bool m_equaliser_isSet;
qint32 audio_description_mixed;
bool m_audio_description_mixed_isSet;
qint32 clean_audio;
bool m_clean_audio_isSet;
qint32 subtitles_hard_of_hearing;
bool m_subtitles_hard_of_hearing_isSet;
qint32 record_retune;
bool m_record_retune_isSet;
qint32 record_follow_running;
bool m_record_follow_running_isSet;
qint32 freesat_region;
bool m_freesat_region_isSet;
};
}

12
swagger/sdrangel/code/qt5/client/SWGModelFactory.h

@ -115,6 +115,8 @@ @@ -115,6 +115,8 @@
#include "SWGDABProgram.h"
#include "SWGDATVDemodReport.h"
#include "SWGDVBDemodReport.h"
#include "SWGDVBDemodApp.h"
#include "SWGDVBDemodCarousel.h"
#include "SWGDVBDemodEPGService.h"
#include "SWGDVBDemodEPGEvent.h"
#include "SWGDATVDemodSettings.h"
@ -958,6 +960,16 @@ namespace SWGSDRangel { @@ -958,6 +960,16 @@ namespace SWGSDRangel {
obj->init();
return obj;
}
if(QString("SWGDVBDemodApp").compare(type) == 0) {
SWGDVBDemodApp *obj = new SWGDVBDemodApp();
obj->init();
return obj;
}
if(QString("SWGDVBDemodCarousel").compare(type) == 0) {
SWGDVBDemodCarousel *obj = new SWGDVBDemodCarousel();
obj->init();
return obj;
}
if(QString("SWGDVBDemodEPGService").compare(type) == 0) {
SWGDVBDemodEPGService *obj = new SWGDVBDemodEPGService();
obj->init();

Loading…
Cancel
Save