diff --git a/plugins/channelrx/demoddvb/CMakeLists.txt b/plugins/channelrx/demoddvb/CMakeLists.txt index 4bde4a8ae..4cea7f550 100644 --- a/plugins/channelrx/demoddvb/CMakeLists.txt +++ b/plugins/channelrx/demoddvb/CMakeLists.txt @@ -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 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( ) 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 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}) diff --git a/plugins/channelrx/demoddvb/dvbdemod.cpp b/plugins/channelrx/demoddvb/dvbdemod.cpp index 238d47538..9b1d5ed18 100644 --- a/plugins/channelrx/demoddvb/dvbdemod.cpp +++ b/plugins/channelrx/demoddvb/dvbdemod.cpp @@ -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() { 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) 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& 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() { 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( 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 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) } } +// 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 *report->getSearchText() = getSearchText(); report->setScanTransponders(getScanTransponders()); webapiFormatEPGReport(report); + webapiFormatAppsReport(report); if (status.m_standard == S::StandardDVBT2) { @@ -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); } diff --git a/plugins/channelrx/demoddvb/dvbdemod.h b/plugins/channelrx/demoddvb/dvbdemod.h index 39b409e52..729a59654 100644 --- a/plugins/channelrx/demoddvb/dvbdemod.h +++ b/plugins/channelrx/demoddvb/dvbdemod.h @@ -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: 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: bool isRecording() const { return m_manualRecording >= 0; } std::vector 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 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 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 getSeriesRecordings() const { return m_settings.m_seriesRecordings; } + bool isSeriesScheduled(int networkId, int serviceId, int eventId) const override; + QList 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: void webapiFormatSatelliteReport(const DVBDemodSink::Status& status, SWGSDRangel::SWGDVBDemodReport *report); void webapiFormatEPGReport(SWGSDRangel::SWGDVBDemodReport *report); void webapiFormatEPGLists(SWGSDRangel::SWGDVBDemodReport *report, std::vector services, int serviceId); + void webapiFormatAppsReport(SWGSDRangel::SWGDVBDemodReport *report); void webapiReverseSendSettings(const QList& channelSettingsKeys, const DVBDemodSettings& settings, bool force); void webapiFormatChannelSettings( const QList& channelSettingsKeys, diff --git a/plugins/channelrx/demoddvb/dvbdemod.qrc b/plugins/channelrx/demoddvb/dvbdemod.qrc index dc746baaf..7a793dd23 100644 --- a/plugins/channelrx/demoddvb/dvbdemod.qrc +++ b/plugins/channelrx/demoddvb/dvbdemod.qrc @@ -3,5 +3,6 @@ images/angeltv.png icons/deinterlace.png icons/gpu.png + hbbtv/oipf.js diff --git a/plugins/channelrx/demoddvb/dvbdemodbaseband.h b/plugins/channelrx/demoddvb/dvbdemodbaseband.h index b78af36d7..f1b946d4f 100644 --- a/plugins/channelrx/demoddvb/dvbdemodbaseband.h +++ b/plugins/channelrx/demoddvb/dvbdemodbaseband.h @@ -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: //! 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); } diff --git a/plugins/channelrx/demoddvb/dvbdemodepg.cpp b/plugins/channelrx/demoddvb/dvbdemodepg.cpp index 1a6e2135b..dfca9cd84 100644 --- a/plugins/channelrx/demoddvb/dvbdemodepg.cpp +++ b/plugins/channelrx/demoddvb/dvbdemodepg.cpp @@ -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() // 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) return QString(); } - return QString((networkId == 0x233A ? ukNames : names)[(genre >> 4) & 0x0F]); + if (networkId != 0x233A) { + return DTVGuide::genreText(genre); + } + + return QString(ukNames[(genre >> 4) & 0x0F]); } diff --git a/plugins/channelrx/demoddvb/dvbdemodepg.h b/plugins/channelrx/demoddvb/dvbdemodepg.h index ebcda3eee..4012df4a1 100644 --- a/plugins/channelrx/demoddvb/dvbdemodepg.h +++ b/plugins/channelrx/demoddvb/dvbdemodepg.h @@ -29,101 +29,29 @@ #include #include -#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 getServices() const; + std::vector getServices() const override; std::vector getTransportStreams() const; //! False if its frequency isn't known bool getTransportStream(int networkId, int transportStreamId, TransportStream& transportStream) const; @@ -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 getEvents(int networkId, int serviceId) const; + std::vector getEvents(int networkId, int serviceId) const override; //! The same for many services (network and service ids) at once, in their order - std::vector> getEvents(const std::vector>& services) const; + std::vector> getEvents(const std::vector>& 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 getServiceRevisions(const std::vector>& services) const; - int getEventCount() const; + std::vector getServiceRevisions(const std::vector>& 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: //! 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: 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 { diff --git a/plugins/channelrx/demoddvb/dvbdemodgui.cpp b/plugins/channelrx/demoddvb/dvbdemodgui.cpp index a00dfdf36..3593ffe79 100644 --- a/plugins/channelrx/demoddvb/dvbdemodgui.cpp +++ b/plugins/channelrx/demoddvb/dvbdemodgui.cpp @@ -62,6 +62,11 @@ #include "gui/buttonswitch.h" #include "gui/glvideowidget.h" #include "dvbdemodgui.h" +#ifdef DVBDEMOD_HBBTV +#include +#include "dtv/dtvstreamplayback.h" +#include "dvbdemodhbbtv.h" +#endif #ifdef _WIN32 #ifndef NOMINMAX @@ -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() 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() { 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() 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 channels; + std::vector 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& 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 dialog = m_epgDialog; + QPointer 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) // 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) 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) 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) { 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() { 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) 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) { 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 return m_player && (sender() == m_player); } -void DVBDemodGUI::servicesChanged(const QList& services) +void DVBDemodGUI::servicesChanged(const QList& services) { if (!fromPlayer()) { return; @@ -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 m_dvbDemod = reinterpret_cast(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 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 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() 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() 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() 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() } updateAbsoluteCenterFrequency(); + updateHbbTV(); blockApplySettings(false); } @@ -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() 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() 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) 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(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(event))) { return true; @@ -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(event))) { + return true; + } + + if ((type == QEvent::KeyRelease) && m_hbbtv->keyRelease(static_cast(event))) { + return true; + } + } +#endif + if ((type == QEvent::KeyPress) && m_guideOverlay->handleKey(static_cast(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) #endif m_fullScreenTV->activateWindow(); m_fullScreenTV->setFocus(); + updateHbbTVGeometry(); if (!m_videoMessage.isEmpty()) { showVideoMessage(m_videoMessage); @@ -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() // 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) // 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() QObject::connect(ui->videoEnabled, &ButtonSwitch::toggled, this, &DVBDemodGUI::on_videoEnabled_toggled); QObject::connect(ui->service, QOverload::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); diff --git a/plugins/channelrx/demoddvb/dvbdemodgui.h b/plugins/channelrx/demoddvb/dvbdemodgui.h index 7ac9acd20..8607f6b7f 100644 --- a/plugins/channelrx/demoddvb/dvbdemodgui.h +++ b/plugins/channelrx/demoddvb/dvbdemodgui.h @@ -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: 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: //! 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 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 m_services; + QList 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 m_epgDialog; + QPointer m_epgDialog; + QPointer 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: 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: 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& 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: 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& services); + void servicesChanged(const QList& services); void serviceSelected(int id, bool hasVideo, bool hasAudio); void onWidgetRolled(QWidget* widget, bool rollDown); void onSplitterMoved(int pos, int index); diff --git a/plugins/channelrx/demoddvb/dvbdemodgui.ui b/plugins/channelrx/demoddvb/dvbdemodgui.ui index b410da2b4..5cfaf8632 100644 --- a/plugins/channelrx/demoddvb/dvbdemodgui.ui +++ b/plugins/channelrx/demoddvb/dvbdemodgui.ui @@ -686,7 +686,7 @@ - + 0 @@ -975,6 +975,29 @@ + + + + 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 + + + Apps + + + + + + + The red button: the service's interactive application (HbbTV), as R on the video + + + QToolButton { color: #e62928; font-weight: bold; } + + + Red + + + @@ -1029,9 +1052,9 @@
gui/buttonswitch.h
- DVBDemodScope + DTVScope QWidget -
dvbdemodscope.h
+
dtv/dtvscope.h
1
diff --git a/plugins/channelrx/demoddvb/dvbdemodhbbtv.cpp b/plugins/channelrx/demoddvb/dvbdemodhbbtv.cpp new file mode 100644 index 000000000..29c380b95 --- /dev/null +++ b/plugins/channelrx/demoddvb/dvbdemodhbbtv.cpp @@ -0,0 +1,1257 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) +#include +#include +#else +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dtv/dtvcarouselserver.h" + +#include "dvbdemodhbbtv.h" + +namespace { + +const QString m_messagePrefix = QStringLiteral("\u0001sdrangel:"); +const QString m_scriptName = QStringLiteral("sdrangel-oipf"); +constexpr int m_checkMs = 250; +constexpr int m_retryMs = 30000; //!< Before a failed AUTOSTART application's tried again +constexpr int m_applicationTypeHbbTV = 0x10; +constexpr int m_autostart = 1; +constexpr int m_destroy = 3; +constexpr int m_kill = 4; + +// Keyset bits (OIPF DAE 7.2.5) +constexpr int m_keysetRed = 0x1; +constexpr int m_keysetGreen = 0x2; +constexpr int m_keysetYellow = 0x4; +constexpr int m_keysetBlue = 0x8; +constexpr int m_keysetNavigation = 0x10; +constexpr int m_keysetVCR = 0x20; +constexpr int m_keysetScroll = 0x40; +constexpr int m_keysetInfo = 0x80; +constexpr int m_keysetNumeric = 0x100; + +} // namespace + +// Blocks requests to the internet, when applications aren't allowed it: those of the carousels (the loopback +// interface) and of the page itself are let through. A carousel's application's requests to the internet have the +// origin it has on a TV, its service's dvb: URL (dvb://onid.tsid.sid), rather than the server's, which broadcasters' +// servers refuse. Called in WebEngine's IO thread +class DVBDemodHbbTVInterceptor : public QWebEngineUrlRequestInterceptor +{ +public: + explicit DVBDemodHbbTVInterceptor(QObject *parent) : QWebEngineUrlRequestInterceptor(parent) {} + + void interceptRequest(QWebEngineUrlRequestInfo& info) override + { + const QUrl url = info.requestUrl(); + const QString scheme = url.scheme(); + const bool local = url.host().endsWith(".localhost") || (scheme == "data") || (scheme == "about") || (scheme == "blob"); + + if (!m_networkAllowed && !local) + { + info.block(true); + return; + } + + const QString initiator = info.initiator().host(); + + if (!local && initiator.startsWith("dvb-") && initiator.endsWith(".localhost")) + { + const QStringList parts = initiator.mid(4, initiator.size() - 4 - 10).split('-'); + + if ((parts.size() == 4) && (parts[0] != "x") && (parts[1] != "x")) { + info.setHttpHeader("Origin", QString("dvb://%1.%2.%3").arg(parts[0]).arg(parts[1]).arg(parts[2]).toLatin1()); + } + } + } + + std::atomic m_networkAllowed{true}; +}; + +// The page: its console messages are the application's messages, and its own; no windows are opened +class DVBDemodHbbTVPage : public QWebEnginePage +{ +public: + DVBDemodHbbTVPage(QWebEngineProfile *profile, DVBDemodHbbTV *owner) : + QWebEnginePage(profile, owner), + m_owner(owner) + { + } + +protected: + void javaScriptConsoleMessage(JavaScriptConsoleMessageLevel level, const QString& message, int line, const QString& source) override + { + m_owner->consoleMessage((int) level, message, line, source); + } + + bool acceptNavigationRequest(const QUrl& url, NavigationType type, bool isMainFrame) override + { + (void) type; + + // A dvb: link: the carousel's file, or an application of the AIT + if (url.scheme() == "dvb") + { + if (isMainFrame) { + QMetaObject::invokeMethod(m_owner, [owner = m_owner, uri = url.toString()]() { owner->createApplication(uri); }, Qt::QueuedConnection); + } + + return false; + } + + return true; + } + + QWebEnginePage *createWindow(WebWindowType type) override + { + (void) type; + return nullptr; + } + +private: + DVBDemodHbbTV *m_owner; +}; + +DVBDemodHbbTV::DVBDemodHbbTV(DTVApps *apps, QObject *parent) : + QObject(parent), + m_apps(apps), + m_server(new DTVCarouselServer(apps, this)), + m_profile(acquireProfile()), + m_page(nullptr), + m_interceptor(new DVBDemodHbbTVInterceptor(this)), + m_network(new QNetworkAccessManager(this)), + m_idType(12), + m_organisationId(0), + m_applicationId(0), + m_autostartApp(false), + m_autostartDisabled(false), + m_autostartRetryAt(0), + m_visible(false), + m_loaded(false), + m_suppressed(false), + m_keyset(0), + m_pendingRed(false), + m_mediaId(0), + m_appCarouselPid(-1), + m_loadsStarted(0), + m_keysetSinceLoad(false) +{ + m_server->start(); + connect(m_server, &DTVCarouselServer::served, this, [this](const QString& path, int status) { + emit log(QString("Carousel: %1 %2").arg(path).arg(status)); + }); + + QFile script(":/demoddvb/hbbtv/oipf.js"); + + if (script.open(QIODevice::ReadOnly)) { + m_oipfScript = QString::fromUtf8(script.readAll()); + } else { + qWarning("DVBDemodHbbTV::DVBDemodHbbTV: no oipf.js"); + } + + QString agent = qEnvironmentVariable("DTV_HBBTV_USER_AGENT"); + if (agent.isEmpty()) { + agent = "Mozilla/5.0 (Web0S; Linux/SmartTV) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 HbbTV/1.4.1 (+DRM; LGE; 55UJ670V-ZD; WEBOS3.5 06.10.50; W3_K3LP; W3_K3LP;)"; + } + setUserAgent(agent); + // Downloads: of this page's only, as the profile's shared +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + connect(m_profile, &QWebEngineProfile::downloadRequested, this, [this](QWebEngineDownloadRequest *download) { +#else + connect(m_profile, &QWebEngineProfile::downloadRequested, this, [this](QWebEngineDownloadItem *download) { +#endif + if (download->page() == m_page) + { + const QUrl url = download->url(); + const QString mimeType = download->mimeType(); + download->cancel(); + downloadRequested(url, mimeType); + } + }); + + m_page = new DVBDemodHbbTVPage(m_profile, this); + m_page->setUrlRequestInterceptor(m_interceptor); + m_page->setBackgroundColor(Qt::transparent); +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + connect(m_page, &QWebEnginePage::loadingChanged, this, [this](const QWebEngineLoadingInfo& info) { + if (info.status() == QWebEngineLoadingInfo::LoadSucceededStatus) { + loadFinished(true); + } else if (info.status() == QWebEngineLoadingInfo::LoadFailedStatus) { + emit log(QString("Load failed: %1: %2").arg(info.url().toString()).arg(info.errorString())); + loadFinished(false); + } + }); +#else + // Qt 5 says a load's failed when it's replaced by another (as when a page goes to another as it loads): only a + // load not followed by another is taken to have failed + connect(m_page, &QWebEnginePage::loadStarted, this, [this]() { m_loadsStarted++; }); + connect(m_page, &QWebEnginePage::loadFinished, this, [this](bool ok) { + if (ok) + { + loadFinished(true); + return; + } + + const int loads = m_loadsStarted; + QTimer::singleShot(500, this, [this, loads]() { + if (loads == m_loadsStarted) + { + emit log(QString("Load failed: %1").arg(m_page->url().toString())); + loadFinished(false); + } + }); + }); +#endif + + connect(&m_timer, &QTimer::timeout, this, &DVBDemodHbbTV::check); + m_timer.start(m_checkMs); +} + +DVBDemodHbbTV::~DVBDemodHbbTV() +{ + // The page before its profile + delete m_view; + delete m_page; + releaseProfile(); +} + +namespace { +QWebEngineProfile *s_profile = nullptr; +int s_profileUsers = 0; +} + +QWebEngineProfile *DVBDemodHbbTV::acquireProfile() +{ + if (!s_profile) + { + // In the application's data directory, as QtWebEngine/sdrangel-hbbtv + s_profile = new QWebEngineProfile("sdrangel-hbbtv"); + s_profile->setPersistentCookiesPolicy(QWebEngineProfile::ForcePersistentCookies); + QWebEngineSettings *settings = s_profile->settings(); + settings->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, false); + settings->setAttribute(QWebEngineSettings::LocalStorageEnabled, true); + settings->setAttribute(QWebEngineSettings::PluginsEnabled, false); + settings->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture, false); + settings->setAttribute(QWebEngineSettings::ShowScrollBars, false); + settings->setAttribute(QWebEngineSettings::ErrorPageEnabled, false); + settings->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, false); + } + + s_profileUsers++; + return s_profile; +} + +void DVBDemodHbbTV::releaseProfile() +{ + if ((--s_profileUsers == 0) && s_profile) + { + delete s_profile; + s_profile = nullptr; + } +} + +void DVBDemodHbbTV::clearData() +{ + QWebEngineProfile *profile = acquireProfile(); + profile->cookieStore()->deleteAllCookies(); + profile->clearHttpCache(); + profile->clearAllVisitedLinks(); + releaseProfile(); +} + +QWebEngineView *DVBDemodHbbTV::createView(QWidget *parent) +{ + if (!m_view) + { + m_view = new QWebEngineView(parent); + m_view->setPage(m_page); + m_view->setAttribute(Qt::WA_TranslucentBackground); + m_view->setAttribute(Qt::WA_TransparentForMouseEvents); + m_view->setFocusPolicy(Qt::NoFocus); + m_view->setContextMenuPolicy(Qt::NoContextMenu); + makeTransparent(); + showView(); + } + + return m_view; +} + +// Composited over the video (a QOpenGLWidget) with its transparency: the view draws with a QQuickWidget, which is +// otherwise composited under other widgets' contents +void DVBDemodHbbTV::makeTransparent() +{ + if (!m_view) { + return; + } + + for (QQuickWidget *widget : m_view->findChildren()) + { + widget->setAttribute(Qt::WA_AlwaysStackOnTop); + widget->setAttribute(Qt::WA_TransparentForMouseEvents); + widget->setFocusPolicy(Qt::NoFocus); + widget->setClearColor(Qt::transparent); + widget->removeEventFilter(this); + widget->installEventFilter(this); + } + + m_view->removeEventFilter(this); + m_view->installEventFilter(this); + + if (m_view->focusProxy()) + { + m_view->focusProxy()->removeEventFilter(this); + m_view->focusProxy()->installEventFilter(this); + } +} + +void DVBDemodHbbTV::takeFocus() +{ + if (!m_view) { + return; + } + + if (m_view->isVisible()) + { + QWidget *widget = m_view->focusProxy() ? m_view->focusProxy() : m_view.data(); + widget->setFocus(Qt::OtherFocusReason); + } + else if (m_view->parentWidget()) + { + m_view->parentWidget()->setFocus(Qt::OtherFocusReason); + } +} + +// The page's keys: the application's, given to it as keyPress() does (as a TV's remote's, with their codes), the +// others to the video widget, as when it has the focus +bool DVBDemodHbbTV::eventFilter(QObject *object, QEvent *event) +{ + const QEvent::Type type = event->type(); + + if ((type == QEvent::KeyPress) || (type == QEvent::KeyRelease) || (type == QEvent::ShortcutOverride)) + { + QKeyEvent *key = static_cast(event); + + // Not shortcuts of the window's: the keys are the video's + if (type == QEvent::ShortcutOverride) + { + event->accept(); + return true; + } + + const bool taken = type == QEvent::KeyPress ? keyPress(key) : keyRelease(key); + + if (!taken && m_view && m_view->parentWidget()) + { + QKeyEvent copy(type, key->key(), key->modifiers(), key->text(), key->isAutoRepeat(), key->count()); + QCoreApplication::sendEvent(m_view->parentWidget(), ©); + } + + return true; + } + + return QObject::eventFilter(object, event); +} + +void DVBDemodHbbTV::setViewGeometry(const QRect& geometry) +{ + if (!m_view) { + return; + } + + m_view->setGeometry(geometry); + // Applications are laid out for 1280 by 720 pixels + m_page->setZoomFactor(std::max(0.25, std::min(5.0, geometry.width() / 1280.0))); +} + +void DVBDemodHbbTV::setViewParent(QWidget *parent) +{ + if (m_view && (m_view->parentWidget() != parent)) + { + m_view->setParent(parent); + makeTransparent(); + showView(); + } +} + +void DVBDemodHbbTV::setSuppressed(bool suppressed) +{ + if (suppressed != m_suppressed) + { + m_suppressed = suppressed; + showView(); + } +} + +void DVBDemodHbbTV::showView() +{ + if (m_view) + { + const bool show = isRunning() && m_visible && m_loaded && !m_suppressed; + + if (show != m_view->isVisible()) + { + QWidget *parent = m_view->parentWidget(); + QWidget *focus = QApplication::focusWidget(); + const bool hadFocus = focus && ((focus == m_view) || m_view->isAncestorOf(focus)); + const bool parentHadFocus = parent && (focus == parent); + m_view->setVisible(show); + + if (show) + { + m_view->raise(); + makeTransparent(); + + if (parentHadFocus) { + takeFocus(); + } + } + else if (hadFocus && parent) + { + parent->setFocus(Qt::OtherFocusReason); + } + } + } +} + +void DVBDemodHbbTV::setUserAgent(const QString& userAgent) +{ + if (!userAgent.isEmpty()) + { + m_profile->setHttpUserAgent(userAgent); + emit log(QString("User agent: %1").arg(userAgent)); + updateProxy(); + return; + } + + // As a TV's: HbbTV/1.5.1 is HbbTV 2.0.2 (TS 102 796 7.3.2.4) + QWebEngineProfile defaultProfile; + m_profile->setHttpUserAgent(defaultProfile.httpUserAgent() + + QString(" HbbTV/1.5.1 (; SDRangel; DVBDemod; %1; ; SDRangel; )").arg(QCoreApplication::applicationVersion())); + updateProxy(); +} + +QString DVBDemodHbbTV::getUserAgent() const +{ + return m_profile->httpUserAgent(); +} + +void DVBDemodHbbTV::setNetworkAllowed(bool allowed) +{ + m_interceptor->m_networkAllowed = allowed; + updateProxy(); +} + +// Qt 5's WebEngine sends the page's origin whatever the interceptor says, which broadcasters' servers refuse: a +// carousel's application's requests to other sites go by the carousel server, which makes them with its TV origin +void DVBDemodHbbTV::updateProxy() +{ +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + m_server->setProxy(m_interceptor->m_networkAllowed, m_profile->httpUserAgent()); +#endif +} + +bool DVBDemodHbbTV::keyCode(int qtKey, int& code, int& keysetBit) +{ + switch (qtKey) + { + case Qt::Key_R: case Qt::Key_F1: code = 403; keysetBit = m_keysetRed; return true; + case Qt::Key_G: case Qt::Key_F2: code = 404; keysetBit = m_keysetGreen; return true; + case Qt::Key_Y: case Qt::Key_F3: code = 405; keysetBit = m_keysetYellow; return true; + case Qt::Key_B: case Qt::Key_F4: code = 406; keysetBit = m_keysetBlue; return true; + case Qt::Key_Left: code = 37; keysetBit = m_keysetNavigation; return true; + case Qt::Key_Up: code = 38; keysetBit = m_keysetNavigation; return true; + case Qt::Key_Right: code = 39; keysetBit = m_keysetNavigation; return true; + case Qt::Key_Down: code = 40; keysetBit = m_keysetNavigation; return true; + case Qt::Key_Return: case Qt::Key_Enter: code = 13; keysetBit = m_keysetNavigation; return true; + case Qt::Key_Backspace: case Qt::Key_Back: code = 461; keysetBit = m_keysetNavigation; return true; + case Qt::Key_PageUp: code = 33; keysetBit = m_keysetScroll; return true; + case Qt::Key_PageDown: code = 34; keysetBit = m_keysetScroll; return true; + case Qt::Key_MediaPlay: code = 415; keysetBit = m_keysetVCR; return true; + case Qt::Key_MediaPause: code = 19; keysetBit = m_keysetVCR; return true; + case Qt::Key_MediaTogglePlayPause: code = 402; keysetBit = m_keysetVCR; return true; + case Qt::Key_MediaStop: code = 413; keysetBit = m_keysetVCR; return true; + case Qt::Key_MediaNext: code = 425; keysetBit = m_keysetVCR; return true; + case Qt::Key_MediaPrevious: code = 424; keysetBit = m_keysetVCR; return true; + case Qt::Key_Info: code = 457; keysetBit = m_keysetInfo; return true; + default: + if ((qtKey >= Qt::Key_0) && (qtKey <= Qt::Key_9)) + { + code = 48 + (qtKey - Qt::Key_0); + keysetBit = m_keysetNumeric; + return true; + } + + return false; + } +} + +bool DVBDemodHbbTV::keyPress(QKeyEvent *event) +{ + int code, bit; + + if ((event->modifiers() & (Qt::ControlModifier | Qt::AltModifier)) || !keyCode(event->key(), code, bit)) { + return false; + } + + // Red with no application running starts the service's again + if ((bit == m_keysetRed) && !isRunning() && !event->isAutoRepeat()) { + return pressRed(); + } + + if (!isRunning() || !m_loaded || !(m_keyset & bit)) { + return false; + } + + m_userRequest.start(); + + if (bit == m_keysetRed) { + m_redDelivered.start(); + } + + m_page->runJavaScript(QString("window.__sdrangelHbbTV && window.__sdrangelHbbTV.key(%1, true)").arg(code)); + return true; +} + +bool DVBDemodHbbTV::keyRelease(QKeyEvent *event) +{ + int code, bit; + + if (!isRunning() || !m_loaded || !keyCode(event->key(), code, bit) || !(m_keyset & bit) || event->isAutoRepeat()) { + return false; + } + + m_page->runJavaScript(QString("window.__sdrangelHbbTV && window.__sdrangelHbbTV.key(%1, false)").arg(code)); + return true; +} + +bool DVBDemodHbbTV::pressRed() +{ + m_userRequest.start(); + + if (isRunning() && m_loaded && (m_keyset & m_keysetRed)) + { + m_page->runJavaScript("window.__sdrangelHbbTV && (window.__sdrangelHbbTV.key(403, true), window.__sdrangelHbbTV.key(403, false))"); + m_redDelivered.start(); + return true; + } + + if (!isRunning() && hasAutostartApp()) + { + emit log("Red: starting the AUTOSTART application"); + m_autostartDisabled = false; + m_autostartRetryAt = 0; + m_pendingRed = true; + m_pendingRedTimer.start(); + check(); + return true; + } + + // Loading, or it's not asked for red yet: given to it when it does + if (isRunning()) + { + m_pendingRed = true; + m_pendingRedTimer.start(); + return true; + } + + return false; +} + +QString DVBDemodHbbTV::getStatus() const +{ + if (!m_userRequest.isValid() || (m_userRequest.elapsed() > 60000)) { + return QString(); + } + + if (m_failed.isValid() && (m_failed.elapsed() < 5000)) { + return "Red button: not available"; + } + + if (!isRunning()) { + return m_pendingRed && (m_userRequest.elapsed() < 30000) ? QString("Red button: starting...") : QString(); + } + + if (m_loaded) + { + // Loaded, but getting what it shows (as from the internet) until it's asked for keys; and just after red's + // given to it, before it starts what it's for + if ((!m_keysetSinceLoad && m_loadedAt.isValid() && (m_loadedAt.elapsed() < 8000) && m_visible) + || (m_redDelivered.isValid() && (m_redDelivered.elapsed() < 1500))) { + return "Red button: loading..."; + } + + return QString(); + } + + // From a carousel: as far as it's been received + if (m_appCarouselPid >= 0) + { + for (const DTVApps::Carousel& carousel : m_apps->getCarousels(m_channel.m_serviceId)) + { + if ((carousel.m_pid == m_appCarouselPid) && !carousel.m_complete) + { + const int percent = carousel.m_progress.m_bytes > 0 ? (int) (100 * carousel.m_progress.m_bytesComplete / carousel.m_progress.m_bytes) : 0; + return QString("Red button: loading from the broadcast (%1%)").arg(percent); + } + } + } + + return "Red button: loading..."; +} + +void DVBDemodHbbTV::mediaEvent(int id, const QString& type, const QJsonObject& data) +{ + if (id == 0) { + return; + } + + const QString json = QString::fromUtf8(QJsonDocument(data).toJson(QJsonDocument::Compact)); + m_page->runJavaScript(QString("window.__sdrangelHbbTV && window.__sdrangelHbbTV.media(%1, '%2', %3)").arg(id).arg(type).arg(json)); +} + +bool DVBDemodHbbTV::hasAutostartApp() const +{ + if (m_channel.m_serviceId == 0) { + return false; + } + + for (const DTVApps::App& app : m_apps->getApps(m_channel.m_serviceId)) + { + if ((app.m_applicationType == m_applicationTypeHbbTV) && (app.m_controlCode == m_autostart) && !appUrl(app).isEmpty()) { + return true; + } + } + + return false; +} + +void DVBDemodHbbTV::setService(const Channel& channel, const std::vector& channels, const std::vector& programmes) +{ + const bool changed = (channel.m_serviceId != m_channel.m_serviceId) || (channel.m_transportStreamId != m_channel.m_transportStreamId); + m_channel = channel; + m_channels = channels; + m_programmes = programmes; + + if (changed) + { + // The application keeps running if the new service signals it too and it isn't bound to the old one + // (TS 102 796 6.2.2.2) + bool keep = false; + + if (isRunning() && (channel.m_serviceId != 0)) + { + for (const DTVApps::App& app : m_apps->getApps(channel.m_serviceId)) + { + keep |= (app.m_organisationId == m_organisationId) && (app.m_applicationId == m_applicationId) + && (m_applicationId != 0) && !app.m_serviceBound && (app.m_controlCode != m_kill) && (app.m_controlCode != m_destroy); + } + } + + if (!keep && isRunning()) + { + emit log("Service changed: application stopped"); + destroyApplication(); + } + + m_autostartDisabled = false; + m_autostartRetryAt = 0; + m_pendingRed = false; + } + + updateScript(); + + if (isRunning()) + { + const QString json = QString::fromUtf8(QJsonDocument(configuration()).toJson(QJsonDocument::Compact)); + m_page->runJavaScript(QString("window.__sdrangelHbbTV && window.__sdrangelHbbTV.update(%1)").arg(json)); + } + + check(); +} + +void DVBDemodHbbTV::channelChangeResult(bool ok) +{ + // OIPF's errorState 5: "cannot tune" (as no transport stream's been found) + m_page->runJavaScript(QString("window.__sdrangelHbbTV && window.__sdrangelHbbTV.channelChanged(%1, %2)").arg(ok ? "true" : "false").arg(ok ? 0 : 5)); +} + +void DVBDemodHbbTV::stop() +{ + if (isRunning()) { + destroyApplication(); + } + + m_autostartDisabled = true; +} + +// The service's AUTOSTART application started when there's none running; one the AIT kills, stopped +void DVBDemodHbbTV::showStatus() +{ + const QString status = isRunning() && m_loaded ? getStatus() : QString(); + + if (status != m_pageStatus) + { + m_pageStatus = status; + QString quoted = status; + quoted.replace('\\', "\\\\").replace('\'', "\\'"); + m_page->runJavaScript(QString("window.__sdrangelHbbTV && window.__sdrangelHbbTV.status('%1')").arg(quoted)); + } +} + +void DVBDemodHbbTV::check() +{ + showStatus(); + + if (m_channel.m_serviceId == 0) { + return; + } + + const std::vector apps = m_apps->getApps(m_channel.m_serviceId); + + if (isRunning()) + { + for (const DTVApps::App& app : apps) + { + if ((app.m_organisationId == m_organisationId) && (app.m_applicationId == m_applicationId) && (m_applicationId != 0) + && ((app.m_controlCode == m_kill) || (app.m_controlCode == m_destroy))) + { + emit log(QString("The AIT stops application %1").arg(app.idText())); + destroyApplication(); + return; + } + } + + return; + } + + if (m_autostartDisabled || ((m_autostartRetryAt > 0) && (QDateTime::currentMSecsSinceEpoch() < m_autostartRetryAt))) { + return; + } + + // Not until the service's network and transport stream are known: a carousel's application's origin is of them + // (dvb://onid.tsid.sid), and broadcasters' servers refuse others + const int networkId = m_channel.m_networkId >= 0 ? m_channel.m_networkId : m_apps->getOriginalNetworkId(); + const int transportStreamId = m_channel.m_transportStreamId >= 0 ? m_channel.m_transportStreamId : m_apps->getTransportStreamId(); + + if ((networkId < 0) || (transportStreamId < 0)) { + return; + } + + const DTVApps::App *best = nullptr; + + for (const DTVApps::App& app : apps) + { + if ((app.m_applicationType == m_applicationTypeHbbTV) && (app.m_controlCode == m_autostart) && !appUrl(app).isEmpty() + && (!best || (app.m_priority > best->m_priority))) { + best = &app; + } + } + + if (best) { + launch(*best, QString()); + } +} + +// Where an application's loaded from: its carousel, if it's in one of the service's (being received), else its URL +QString DVBDemodHbbTV::appUrl(const DTVApps::App& app) const +{ + const int networkId = m_channel.m_networkId >= 0 ? m_channel.m_networkId : m_apps->getOriginalNetworkId(); + const int transportStreamId = m_channel.m_transportStreamId >= 0 ? m_channel.m_transportStreamId : m_apps->getTransportStreamId(); + + if ((app.m_componentTag >= 0) && (app.m_carouselPid >= 0)) { + return m_server->httpUrl(app.url(networkId, transportStreamId)); + } + + if (!app.m_urlBases.isEmpty()) + { + DTVApps::App broadband = app; + broadband.m_componentTag = -1; + return broadband.url(networkId, transportStreamId); + } + + return QString(); +} + +void DVBDemodHbbTV::launch(const DTVApps::App& app, const QString& suffix) +{ + QString url = appUrl(app); + + if (url.isEmpty()) + { + emit log(QString("Application %1 can't be loaded: it's in another service's carousel").arg(app.idText())); + return; + } + + // Parameters given to it, after its location's own + if (suffix.startsWith('?') && url.contains('?') && !url.contains('#')) { + url += "&" + suffix.mid(1); + } else { + url += suffix; + } + + navigate(url, app.m_name, app.m_organisationId, app.m_applicationId, app.m_controlCode == m_autostart); + m_appCarouselPid = (app.m_componentTag >= 0) && m_server->isServerUrl(url) ? app.m_carouselPid : -1; +} + +void DVBDemodHbbTV::navigate(const QString& url, const QString& name, uint32_t organisationId, int applicationId, bool autostart) +{ + m_appUrl = url; + m_appName = name; + m_organisationId = organisationId; + m_applicationId = applicationId; + m_autostartApp = autostart; + m_appCarouselPid = -1; + m_keyset = 0; + m_loaded = false; + m_keysetSinceLoad = false; + m_pageStatus.clear(); + + if (m_mediaId != 0) + { + emit mediaRequest("stop", m_mediaId, QString(), QMap(), 0.0); + m_mediaId = 0; + } + + m_visible = true; // Until it hides itself + updateScript(); + + showView(); + emit log(QString("Starting \"%1\": %2%3").arg(name).arg(url) + .arg(m_server->isServerUrl(url) ? QString(" (%1)").arg(m_server->dvbUrl(url)) : QString())); + emit appStarted(url, name); + m_page->load(QUrl(url)); +} + +void DVBDemodHbbTV::loadFinished(bool ok) +{ + if (!isRunning()) { + return; + } + + if (!ok) + { + m_failed.start(); + + // An AUTOSTART application that can't be loaded is tried again later, not over and over + if (m_autostartApp) { + m_autostartRetryAt = QDateTime::currentMSecsSinceEpoch() + m_retryMs; + } + + const bool autostart = m_autostartApp; + destroyApplication(); + m_autostartDisabled = false; + + if (!autostart) { + check(); + } + + return; + } + + m_loaded = true; + m_loadedAt.start(); + makeTransparent(); + showView(); +} + +void DVBDemodHbbTV::destroyApplication() +{ + if (m_mediaId != 0) + { + emit mediaRequest("stop", m_mediaId, QString(), QMap(), 0.0); + m_mediaId = 0; + } + + const bool wasRunning = isRunning(); + const bool wasAutostart = m_autostartApp; + m_appUrl.clear(); + m_appName.clear(); + m_organisationId = 0; + m_applicationId = 0; + m_autostartApp = false; + m_keyset = 0; + m_loaded = false; + setVisible(false); + m_page->setUrl(QUrl("about:blank")); + + if (!m_videoArea.isNull()) + { + m_videoArea = QRectF(); + emit videoAreaChanged(m_videoArea); + } + + if (wasRunning) { + emit appStopped(); + } + + // An application other than the AUTOSTART one exiting starts that again (TS 102 796 6.2.2.6); the AUTOSTART one + // exiting itself isn't started again until the service changes + m_autostartDisabled = wasAutostart; +} + +void DVBDemodHbbTV::setVisible(bool visible) +{ + if (visible == m_visible) { + return; + } + + m_visible = visible; + showView(); + emit visibleChanged(visible); +} + +void DVBDemodHbbTV::consoleMessage(int level, const QString& message, int line, const QString& source) +{ + if (message.startsWith(m_messagePrefix)) + { + const QJsonDocument document = QJsonDocument::fromJson(message.mid(m_messagePrefix.size()).toUtf8()); + + if (document.isObject()) { + this->message(document.object()); + } + + return; + } + + emit log(QString("Console%1: %2 (%3:%4)").arg(level >= 2 ? " error" : "").arg(message).arg(source).arg(line)); +} + +// From oipf.js +void DVBDemodHbbTV::message(const QJsonObject& message) +{ + const QString type = message.value("t").toString(); + + if (type == "keyset") + { + m_keyset = message.value("v").toInt(); + + if (m_loaded) { + m_keysetSinceLoad = true; + } + + emit log(QString("Keyset 0x%1").arg(m_keyset, 0, 16)); + + // Red pressed to start it: given now it's asked for, if that's soon after + if (m_pendingRed && (m_keyset & m_keysetRed)) + { + m_pendingRed = false; + + if (m_pendingRedTimer.elapsed() < 30000) { + QTimer::singleShot(300, this, [this]() { pressRed(); }); + } + } + } + else if (type == "show") + { + setVisible(true); + } + else if (type == "hide") + { + setVisible(false); + } + else if (type == "destroy") + { + emit log("Application destroyed itself"); + // Not from within the page's own call + QTimer::singleShot(0, this, [this]() { + const bool autostart = m_autostartApp; + destroyApplication(); + + if (!autostart) { + check(); + } + }); + } + else if (type == "create") + { + const QString uri = message.value("uri").toString(); + QTimer::singleShot(0, this, [this, uri]() { createApplication(uri); }); + } + else if (type == "setChannel") + { + emit log(QString("setChannel %1.%2.%3").arg(message.value("onid").toInt()).arg(message.value("tsid").toInt()).arg(message.value("sid").toInt())); + emit channelChangeRequested(message.value("onid").toInt(-1), message.value("tsid").toInt(-1), message.value("sid").toInt()); + } + else if (type == "step") + { + emit channelStepRequested(message.value("d").toInt()); + } + else if (type == "video") + { + QRectF area; + + if (!message.value("full").toBool() && !message.value("hidden").toBool()) + { + area = QRectF(message.value("x").toDouble(), message.value("y").toDouble(), message.value("w").toDouble(), message.value("h").toDouble()) + .intersected(QRectF(0.0, 0.0, 1.0, 1.0)); + } + + if (area != m_videoArea) + { + m_videoArea = area; + emit videoAreaChanged(area); + } + } + else if (type == "media") + { + const QString command = message.value("cmd").toString(); + const int id = message.value("id").toInt(); + QString url = message.value("url").toString(); + QMap options; + + if (command == "load") + { + // FFmpeg fetches it as the page would: with its user agent, and a carousel's file from the server by the + // loopback address (FFmpeg's resolver doesn't know *.localhost), its host given in the header + options["user_agent"] = m_profile->httpUserAgent(); + QString headers = QString("Referer: %1\r\n").arg(m_page->url().toString()); + + if (m_server->isServerUrl(url)) + { + QUrl u(url); + headers += QString("Host: %1:%2\r\n").arg(u.host()).arg(u.port()); + u.setHost("127.0.0.1"); + url = u.toString(); + } + + options["headers"] = headers; + + // One at a time: another element's stopped + if ((m_mediaId != 0) && (m_mediaId != id)) { + emit mediaRequest("stop", m_mediaId, QString(), QMap(), 0.0); + } + + m_mediaId = id; + } + else if (id != m_mediaId) + { + return; // Of media no longer played + } + + emit log(QString("Media %1 %2%3").arg(id).arg(command).arg(command == "load" ? " " + url + : command == "seek" ? QString(" %1 s").arg(message.value("position").toDouble()) : QString())); + emit mediaRequest(command, id, url, options, message.value("position").toDouble()); + + if (command == "stop") { + m_mediaId = 0; + } + } + else if (type == "loaded") + { + emit log(QString("Loaded %1").arg(message.value("url").toString())); + } + else if (type == "error") + { + emit log(QString("Script error: %1 (%2:%3)").arg(message.value("message").toString()) + .arg(message.value("source").toString()).arg(message.value("line").toInt())); + } +} + +// Application.createApplication(): an application of the AIT, by its ids (dvb://current.ait/org.app, TS 102 851), +// a file of a carousel, or a URL +void DVBDemodHbbTV::createApplication(const QString& uri) +{ + emit log(QString("createApplication %1").arg(uri)); + const QString aitPrefix = "dvb://current.ait/"; + + if (uri.startsWith(aitPrefix, Qt::CaseInsensitive)) + { + const QString rest = uri.mid(aitPrefix.size()); + int end = rest.size(); + + for (QChar c : QString("?#/")) + { + const int i = rest.indexOf(c); + + if (i >= 0) { + end = std::min(end, i); + } + } + + const QStringList ids = rest.left(end).split('.'); + bool orgOK = false, appOK = false; + const uint32_t organisationId = ids.size() == 2 ? ids[0].toUInt(&orgOK, 16) : 0; + const int applicationId = ids.size() == 2 ? ids[1].toInt(&appOK, 16) : 0; + + if (orgOK && appOK) + { + for (const DTVApps::App& app : m_apps->getApps(m_channel.m_serviceId)) + { + if ((app.m_organisationId == organisationId) && (app.m_applicationId == applicationId)) + { + launch(app, rest.mid(end).startsWith('/') ? QString() : rest.mid(end)); + return; + } + } + } + + emit log(QString("createApplication: %1 isn't in the AIT").arg(uri)); + return; + } + + if (uri.startsWith("dvb://", Qt::CaseInsensitive)) + { + const QString url = m_server->httpUrl(uri); + + if (!url.isEmpty()) { + navigate(url, QString(), 0, 0, false); + } else { + emit log(QString("createApplication: can't load %1").arg(uri)); + } + + return; + } + + const QUrl url(uri); + + if ((url.scheme() == "http") || (url.scheme() == "https")) { + navigate(uri, QString(), 0, 0, false); + } else if (url.isRelative() && isRunning()) { + navigate(QUrl(m_appUrl).resolved(url).toString(), QString(), 0, 0, false); + } else { + emit log(QString("createApplication: can't load %1").arg(uri)); + } +} + +// An HbbTV application served as application/vnd.hbbtv.xhtml+xml, which the browser would download rather than show: +// fetched, and given to it as HTML +void DVBDemodHbbTV::downloadRequested(const QUrl& url, const QString& mimeType) +{ + if (!isRunning() || (url != QUrl(m_appUrl)) || !(mimeType.contains("hbbtv") || mimeType.contains("xhtml") || mimeType.contains("cehtml"))) + { + emit log(QString("Download of %1 (%2) refused").arg(url.toString()).arg(mimeType)); + return; + } + + QNetworkRequest request(url); + request.setHeader(QNetworkRequest::UserAgentHeader, m_profile->httpUserAgent()); + QNetworkReply *reply = m_network->get(request); + + connect(reply, &QNetworkReply::finished, this, [this, reply, url]() { + reply->deleteLater(); + + if ((reply->error() != QNetworkReply::NoError) || !isRunning() || (QUrl(m_appUrl) != url)) + { + emit log(QString("Can't load %1: %2").arg(url.toString()).arg(reply->errorString())); + return; + } + + m_page->setContent(reply->readAll(), "text/html", url); + }); +} + +QJsonObject DVBDemodHbbTV::channelJson(const Channel& channel) const +{ + QJsonObject json; + json.insert("onid", channel.m_networkId >= 0 ? channel.m_networkId : m_apps->getOriginalNetworkId()); + json.insert("tsid", channel.m_transportStreamId >= 0 ? channel.m_transportStreamId : m_apps->getTransportStreamId()); + json.insert("sid", channel.m_serviceId); + json.insert("name", channel.m_name); + json.insert("lcn", channel.m_lcn); + json.insert("radio", channel.m_radio); + json.insert("hd", channel.m_hd); + json.insert("idType", m_idType); + return json; +} + +QJsonObject DVBDemodHbbTV::configuration() const +{ + QJsonObject config; + config.insert("channel", m_channel.m_serviceId != 0 ? QJsonValue(channelJson(m_channel)) : QJsonValue()); + QJsonArray channels; + + for (const Channel& channel : m_channels) { + channels.append(channelJson(channel)); + } + + config.insert("channels", channels); + QJsonArray programmes; + + for (const Programme& programme : m_programmes) + { + QJsonObject p; + p.insert("id", programme.m_eventId); + p.insert("name", programme.m_name); + p.insert("description", programme.m_description); + p.insert("start", (double) programme.m_start); + p.insert("duration", programme.m_duration); + programmes.append(p); + } + + config.insert("programmes", programmes); + config.insert("language", "eng"); + config.insert("country", "GBR"); + config.insert("version", QCoreApplication::applicationVersion()); + config.insert("serverPort", m_server->getPort()); +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + config.insert("proxy", m_server->getProxyPath()); +#endif + return config; +} + +// oipf.js, with the TV's state, in each page before its scripts +void DVBDemodHbbTV::updateScript() +{ + QWebEngineScriptCollection& scripts = m_page->scripts(); + +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + const QList oldScripts = scripts.find(m_scriptName); +#else + const QList oldScripts = scripts.findScripts(m_scriptName); +#endif + + for (const QWebEngineScript& old : oldScripts) { + scripts.remove(old); + } + + QWebEngineScript script; + script.setName(m_scriptName); + script.setInjectionPoint(QWebEngineScript::DocumentCreation); + script.setWorldId(QWebEngineScript::MainWorld); + script.setRunsOnSubFrames(true); + // Not by arg(): the script has %s of its own + script.setSourceCode("window.__sdrangelHbbTVConfig = " + QString::fromUtf8(QJsonDocument(configuration()).toJson(QJsonDocument::Compact)) + + ";\n" + m_oipfScript); + scripts.insert(script); +} diff --git a/plugins/channelrx/demoddvb/dvbdemodhbbtv.h b/plugins/channelrx/demoddvb/dvbdemodhbbtv.h new file mode 100644 index 000000000..9cefb3a3f --- /dev/null +++ b/plugins/channelrx/demoddvb/dvbdemodhbbtv.h @@ -0,0 +1,216 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DVBDEMODHBBTV_H +#define INCLUDE_DVBDEMODHBBTV_H + +#include + +#include +#include +#include +#include +#include +#include +#include + +#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& channels, const std::vector& 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& 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 m_view; + DVBDemodHbbTVInterceptor *m_interceptor; + QNetworkAccessManager *m_network; + QString m_oipfScript; + QTimer m_timer; + int m_idType; + + Channel m_channel; + std::vector m_channels; + std::vector 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 diff --git a/plugins/channelrx/demoddvb/dvbdemodsettings.cpp b/plugins/channelrx/demoddvb/dvbdemodsettings.cpp index 7ac582a98..c0eedd293 100644 --- a/plugins/channelrx/demoddvb/dvbdemodsettings.cpp +++ b/plugins/channelrx/demoddvb/dvbdemodsettings.cpp @@ -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 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) 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 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 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)); } diff --git a/plugins/channelrx/demoddvb/dvbdemodsettings.h b/plugins/channelrx/demoddvb/dvbdemodsettings.h index dace36d68..ea315a059 100644 --- a/plugins/channelrx/demoddvb/dvbdemodsettings.h +++ b/plugins/channelrx/demoddvb/dvbdemodsettings.h @@ -24,6 +24,8 @@ #include #include +#include "dtv/dtvguide.h" + class Serializable; 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 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 diff --git a/plugins/channelrx/demoddvb/dvbdemodsink.cpp b/plugins/channelrx/demoddvb/dvbdemodsink.cpp index 56964c0df..1b0527428 100644 --- a/plugins/channelrx/demoddvb/dvbdemodsink.cpp +++ b/plugins/channelrx/demoddvb/dvbdemodsink.cpp @@ -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() 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 recorder(new DVBDemodRecorder()); + std::unique_ptr recorder(new DTVRecorder()); if (!recorder->start(fileName, mode, serviceId, error)) { return -1; @@ -1012,7 +1013,7 @@ int DVBDemodSink::startRecording(const QString& fileName, DVBDemodRecorder::Mode void DVBDemodSink::stopRecording(int id) { - std::shared_ptr recorder; + std::shared_ptr recorder; { QMutexLocker locker(&m_recordersMutex); diff --git a/plugins/channelrx/demoddvb/dvbdemodsink.h b/plugins/channelrx/demoddvb/dvbdemodsink.h index 9f0431d56..0d64a3f9d 100644 --- a/plugins/channelrx/demoddvb/dvbdemodsink.h +++ b/plugins/channelrx/demoddvb/dvbdemodsink.h @@ -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: //! 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: std::deque> 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>> m_recorders; + std::vector>> m_recorders; int m_nextRecordingId; std::vector> m_stoppingRecorders; //!< Stopped, finishing their files std::vector m_packetBlock; //!< Packets delivered, not flushed yet diff --git a/plugins/channelrx/demoddvb/hbbtv/oipf.js b/plugins/channelrx/demoddvb/hbbtv/oipf.js new file mode 100644 index 000000000..dfbf0bb5e --- /dev/null +++ b/plugins/channelrx/demoddvb/hbbtv/oipf.js @@ -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 = 'true' + + 'true' + + 'urn:dvb:broadcast:ird:video:25_Hz_H.264_AVC_HDTV_IRD'; + 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 , 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 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 }); + }); +})(); diff --git a/plugins/channelrx/demoddvb/readme.md b/plugins/channelrx/demoddvb/readme.md index 2ec8a8ad2..b9ac73960 100644 --- a/plugins/channelrx/demoddvb/readme.md +++ b/plugins/channelrx/demoddvb/readme.md @@ -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

Sample rate

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

Satellite reception

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

5: RO - Roll-off

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.

6: Rate - Code rate

@@ -190,7 +190,7 @@ Average power of the signal in the channel, in dB.

12: UDP

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

Signal and Video

-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. 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".

3: HD

@@ -350,7 +350,7 @@ When the programme playing is also available in HD, click the button to switch t

4: Deinterlace

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.

5: Hardware decoding

@@ -378,7 +378,7 @@ The button mutes the audio, and is green while audio is playing. Right click it

9: Audio service

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 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. ![On screen EPG](../../../doc/img/DVBDemod_onscreen_epg.png) +

Apps

+ +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. +

Scan

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

Video

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: 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). 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. - -

Testing with recordings

- -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. diff --git a/sdrbase/CMakeLists.txt b/sdrbase/CMakeLists.txt index 6a799958a..ac3ed3636 100644 --- a/sdrbase/CMakeLists.txt +++ b/sdrbase/CMakeLists.txt @@ -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 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 diff --git a/sdrbase/dtv/dtvapps.cpp b/sdrbase/dtv/dtvapps.cpp new file mode 100644 index 000000000..585f6ac78 --- /dev/null +++ b/sdrbase/dtv/dtvapps.cpp @@ -0,0 +1,964 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include + +#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& 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 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 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 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 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 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::getApps(int serviceId) const +{ + QMutexLocker locker(&m_mutex); + std::vector apps; + + for (const auto& service : m_services) + { + if ((serviceId != 0) && (service.first != serviceId)) { + continue; + } + + std::set> 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::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 apps = getApps(); + QMutexLocker locker(&m_mutex); + std::vector carousels; + std::map 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 DTVApps::getServices() const +{ + QMutexLocker locker(&m_mutex); + std::vector 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 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(); +} + +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 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(); +} diff --git a/sdrbase/dtv/dtvapps.h b/sdrbase/dtv/dtvapps.h new file mode 100644 index 000000000..bdc3b2baf --- /dev/null +++ b/sdrbase/dtv/dtvapps.h @@ -0,0 +1,181 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DTVAPPS_H +#define INCLUDE_DTVAPPS_H + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#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 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 getApps(int serviceId = 0) const; + //! The object carousels of a service, or all of them (0), signalled in the PMT or received + std::vector getCarousels(int serviceId = 0) const; + std::vector 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 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 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 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 m_streams; + }; + + struct AIT { + int m_version = -1; + std::map> 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> m_assemblers; //!< By PID: of the PIDs read + std::vector m_wanted; //!< By PID: those read + int m_transportStreamId; + int m_originalNetworkId; + std::map m_programs; //!< From the PAT: program number to PMT PID + std::map m_services; //!< By program number (service id) + std::map, AIT> m_aits; //!< By PID and application type + std::map> m_carousels; //!< By PID of its DSI + std::map m_carouselServices; //!< Carousel PID to its service + std::map> m_carouselPids; //!< PID to the carousels (by DSI PID) fed from it + std::atomic m_carouselService; + int m_carouselServiceApplied; + std::atomic m_revision; +}; + +#endif // INCLUDE_DTVAPPS_H diff --git a/sdrbase/dtv/dtvcarousel.cpp b/sdrbase/dtv/dtvcarousel.cpp new file mode 100644 index 000000000..9bedea766 --- /dev/null +++ b/sdrbase/dtv/dtvcarousel.cpp @@ -0,0 +1,784 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +#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 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 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(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 current; + + for (const auto& dii : m_diiModules) { + current.insert(dii.second.begin(), dii.second.end()); + } + + std::vector 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().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 *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(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& visited, + std::vector *entries, std::map *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::getEntries() const +{ + std::vector entries; + std::set 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 files; + std::set 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 DTVCarousel::getFiles() const +{ + std::map files; + std::set visited; + walk(m_gateway, "", 0, visited, nullptr, &files, nullptr); + return files; +} diff --git a/sdrbase/dtv/dtvcarousel.h b/sdrbase/dtv/dtvcarousel.h new file mode 100644 index 000000000..15570fea2 --- /dev/null +++ b/sdrbase/dtv/dtvcarousel.h @@ -0,0 +1,150 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DTVCAROUSEL_H +#define INCLUDE_DTVCAROUSEL_H + +#include +#include +#include +#include + +#include +#include + +#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& 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 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 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 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 m_data; + std::vector 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 *tags); + static Kind kindFromId(const uint8_t *id, int length); + void walk(const ObjectRef& directory, const QString& path, int depth, std::set& visited, + std::vector *entries, std::map *files, const QString *wanted) const; + + const int m_pid; + int64_t m_carouselId; + ObjectRef m_gateway; + std::set m_associationTags; + std::map m_modules; //!< By module id + std::map> m_diiModules; //!< By the DIIs' identification: the modules each lists + std::map m_objects; //!< From the modules complete + int m_revision; +}; + +#endif // INCLUDE_DTVCAROUSEL_H diff --git a/sdrbase/dtv/dtvcarouselserver.cpp b/sdrbase/dtv/dtvcarouselserver.cpp new file mode 100644 index 000000000..8153e7d2b --- /dev/null +++ b/sdrbase/dtv/dtvcarouselserver.cpp @@ -0,0 +1,500 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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 lines = header.left(end).split('\n'); + const QList 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(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& 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 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(); +} diff --git a/sdrbase/dtv/dtvcarouselserver.h b/sdrbase/dtv/dtvcarouselserver.h new file mode 100644 index 000000000..31a33fc13 --- /dev/null +++ b/sdrbase/dtv/dtvcarouselserver.h @@ -0,0 +1,98 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DTVCAROUSELSERVER_H +#define INCLUDE_DTVCAROUSELSERVER_H + +#include +#include +#include +#include +#include + +#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 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& 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 diff --git a/sdrbase/dtv/dtvguide.cpp b/sdrbase/dtv/dtvguide.cpp new file mode 100644 index 000000000..5f77ee3b3 --- /dev/null +++ b/sdrbase/dtv/dtvguide.cpp @@ -0,0 +1,59 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#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]); +} diff --git a/sdrbase/dtv/dtvguide.h b/sdrbase/dtv/dtvguide.h new file mode 100644 index 000000000..416948de4 --- /dev/null +++ b/sdrbase/dtv/dtvguide.h @@ -0,0 +1,215 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DTVGUIDE_H +#define INCLUDE_DTVGUIDE_H + +#include +#include + +#include +#include +#include + +#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 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 getEvents(int networkId, int serviceId) const = 0; + //! The same for many services (network and service ids) at once, in their order + virtual std::vector> getEvents(const std::vector>& 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 getServiceRevisions(const std::vector>& 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 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 getSeriesRecordings() const = 0; + //! Scheduled recordings may retune to their service's multiplex + virtual bool recordRetune() const = 0; +}; + +#endif // INCLUDE_DTVGUIDE_H diff --git a/plugins/channelrx/demoddvb/dvbdemodpsi.cpp b/sdrbase/dtv/dtvpsi.cpp similarity index 91% rename from plugins/channelrx/demoddvb/dvbdemodpsi.cpp rename to sdrbase/dtv/dtvpsi.cpp index 5581bc174..cfb371bbf 100644 --- a/plugins/channelrx/demoddvb/dvbdemodpsi.cpp +++ b/sdrbase/dtv/dtvpsi.cpp @@ -1,5 +1,6 @@ /////////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 @@ #include -#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() m_channels.clear(); } -const std::map& DVBDemodPSI::getChannels() const +const std::map& DTVPSI::getChannels() const { static const std::map 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) } } -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) } } -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) } // 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; diff --git a/plugins/channelrx/demoddvb/dvbdemodpsi.h b/sdrbase/dtv/dtvpsi.h similarity index 90% rename from plugins/channelrx/demoddvb/dvbdemodpsi.h rename to sdrbase/dtv/dtvpsi.h index 369560b12..70ee5e892 100644 --- a/plugins/channelrx/demoddvb/dvbdemodpsi.h +++ b/sdrbase/dtv/dtvpsi.h @@ -1,5 +1,6 @@ /////////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 @@ // along with this program. If not, see . // /////////////////////////////////////////////////////////////////////////////////// -#ifndef INCLUDE_DVBDEMODPSI_H -#define INCLUDE_DVBDEMODPSI_H +#ifndef INCLUDE_DTVPSI_H +#define INCLUDE_DTVPSI_H #include #include #include -#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: void nit(const uint8_t *data, int length); std::vector 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> m_channels; //!< By transport stream id (the NIT's): service id to number }; -#endif // INCLUDE_DVBDEMODPSI_H +#endif // INCLUDE_DTVPSI_H diff --git a/plugins/channelrx/demoddvb/dvbdemodrecorder.cpp b/sdrbase/dtv/dtvrecorder.cpp similarity index 91% rename from plugins/channelrx/demoddvb/dvbdemodrecorder.cpp rename to sdrbase/dtv/dtvrecorder.cpp index ebb15f2d6..d1efd3dd0 100644 --- a/plugins/channelrx/demoddvb/dvbdemodrecorder.cpp +++ b/sdrbase/dtv/dtvrecorder.cpp @@ -21,9 +21,9 @@ #include #include -#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() : 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, 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() m_running = false; } -DVBDemodRecorder::Status DVBDemodRecorder::getStatus() const +DTVRecorder::Status DTVRecorder::getStatus() const { std::lock_guard lock(m_mutex); Status status; @@ -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() } // 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) 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) 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) // 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& 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) } } -void DVBDemodRecorder::forgetService() +void DTVRecorder::forgetService() { m_pids.reset(); m_pmtPid = -1; @@ -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) } // 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() 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; diff --git a/plugins/channelrx/demoddvb/dvbdemodrecorder.h b/sdrbase/dtv/dtvrecorder.h similarity index 85% rename from plugins/channelrx/demoddvb/dvbdemodrecorder.h rename to sdrbase/dtv/dtvrecorder.h index 37331c3ef..14cc8b38b 100644 --- a/plugins/channelrx/demoddvb/dvbdemodrecorder.h +++ b/sdrbase/dtv/dtvrecorder.h @@ -16,8 +16,8 @@ // along with this program. If not, see . // /////////////////////////////////////////////////////////////////////////////////// -#ifndef INCLUDE_DVBDEMODRECORDER_H -#define INCLUDE_DVBDEMODRECORDER_H +#ifndef INCLUDE_DTVRECORDER_H +#define INCLUDE_DTVRECORDER_H #include #include @@ -32,14 +32,16 @@ #include #include -#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: 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& 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: 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: 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: bool m_running; }; -#endif // INCLUDE_DVBDEMODRECORDER_H +#endif // INCLUDE_DTVRECORDER_H diff --git a/plugins/channelrx/demoddvb/dvbdemodsections.cpp b/sdrbase/dtv/dtvsections.cpp similarity index 88% rename from plugins/channelrx/demoddvb/dvbdemodsections.cpp rename to sdrbase/dtv/dtvsections.cpp index 19e67eff8..4134e96fa 100644 --- a/plugins/channelrx/demoddvb/dvbdemodsections.cpp +++ b/sdrbase/dtv/dtvsections.cpp @@ -18,9 +18,9 @@ #include -#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 } }; -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() // 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; diff --git a/plugins/channelrx/demoddvb/dvbdemodsections.h b/sdrbase/dtv/dtvsections.h similarity index 87% rename from plugins/channelrx/demoddvb/dvbdemodsections.h rename to sdrbase/dtv/dtvsections.h index 9adddbe39..9a473617f 100644 --- a/plugins/channelrx/demoddvb/dvbdemodsections.h +++ b/sdrbase/dtv/dtvsections.h @@ -16,29 +16,31 @@ // along with this program. If not, see . // /////////////////////////////////////////////////////////////////////////////////// -#ifndef INCLUDE_DVBDEMODSECTIONS_H -#define INCLUDE_DVBDEMODSECTIONS_H +#ifndef INCLUDE_DTVSECTIONS_H +#define INCLUDE_DTVSECTIONS_H #include #include #include +#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: uint8_t m_last[188]; //!< The last packet, to recognise a duplicate of it }; -#endif // INCLUDE_DVBDEMODSECTIONS_H +#endif // INCLUDE_DTVSECTIONS_H diff --git a/plugins/channelrx/demoddvb/dvbdemodtsfifo.cpp b/sdrbase/dtv/dtvtsfifo.cpp similarity index 84% rename from plugins/channelrx/demoddvb/dvbdemodtsfifo.cpp rename to sdrbase/dtv/dtvtsfifo.cpp index 7e0769ca1..d409f5833 100644 --- a/plugins/channelrx/demoddvb/dvbdemodtsfifo.cpp +++ b/sdrbase/dtv/dtvtsfifo.cpp @@ -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) : } } -void DVBDemodTSFifo::attachLocked() +void DTVTSFifo::attachLocked() { if (m_buffer.size() != m_size) { m_buffer.resize(m_size); @@ -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() std::vector().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) 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) } } -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) 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) 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) return length; } -void DVBDemodTSFifo::reset() +void DTVTSFifo::reset() { QMutexLocker locker(&m_mutex); m_readPos = 0; @@ -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; diff --git a/plugins/channelrx/demoddvb/dvbdemodtsfifo.h b/sdrbase/dtv/dtvtsfifo.h similarity index 91% rename from plugins/channelrx/demoddvb/dvbdemodtsfifo.h rename to sdrbase/dtv/dtvtsfifo.h index 0d30d2d3b..84140e7c3 100644 --- a/plugins/channelrx/demoddvb/dvbdemodtsfifo.h +++ b/sdrbase/dtv/dtvtsfifo.h @@ -16,8 +16,8 @@ // along with this program. If not, see . // /////////////////////////////////////////////////////////////////////////////////// -#ifndef INCLUDE_DVBDEMODTSFIFO_H -#define INCLUDE_DVBDEMODTSFIFO_H +#ifndef INCLUDE_DTVTSFIFO_H +#define INCLUDE_DTVTSFIFO_H #include #include @@ -26,16 +26,17 @@ #include #include #include +#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: QElapsedTimer m_sinceRead; //!< With needsReader: since the reader last read }; -#endif // INCLUDE_DVBDEMODTSFIFO_H +#endif // INCLUDE_DTVTSFIFO_H diff --git a/plugins/channelrx/demoddvb/dvbdemodudp.cpp b/sdrbase/dtv/dtvudp.cpp similarity index 89% rename from plugins/channelrx/demoddvb/dvbdemodudp.cpp rename to sdrbase/dtv/dtvudp.cpp index 528cb01e8..87c887ddc 100644 --- a/plugins/channelrx/demoddvb/dvbdemodudp.cpp +++ b/sdrbase/dtv/dtvudp.cpp @@ -21,9 +21,9 @@ #include #include -#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() : { } -DVBDemodUDP::~DVBDemodUDP() +DTVUDP::~DTVUDP() { { std::lock_guard lock(m_mutex); @@ -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) 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 lock(m_mutex); @@ -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() } } -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) } } -void DVBDemodUDP::send() +void DTVUDP::send() { m_datagramFill = 0; diff --git a/plugins/channelrx/demoddvb/dvbdemodudp.h b/sdrbase/dtv/dtvudp.h similarity index 94% rename from plugins/channelrx/demoddvb/dvbdemodudp.h rename to sdrbase/dtv/dtvudp.h index 718162fe9..7c8dfa40a 100644 --- a/plugins/channelrx/demoddvb/dvbdemodudp.h +++ b/sdrbase/dtv/dtvudp.h @@ -16,8 +16,8 @@ // along with this program. If not, see . // /////////////////////////////////////////////////////////////////////////////////// -#ifndef INCLUDE_DVBDEMODUDP_H -#define INCLUDE_DVBDEMODUDP_H +#ifndef INCLUDE_DTVUDP_H +#define INCLUDE_DTVUDP_H #include #include @@ -29,14 +29,15 @@ #include #include #include +#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: std::thread m_lookupThread; //!< Started for the first host name }; -#endif // INCLUDE_DVBDEMODUDP_H +#endif // INCLUDE_DTVUDP_H diff --git a/sdrbase/resources/webapi/doc/swagger/include/DVBDemod.yaml b/sdrbase/resources/webapi/doc/swagger/include/DVBDemod.yaml index 7c35bb7d7..cfabf39ba 100644 --- a/sdrbase/resources/webapi/doc/swagger/include/DVBDemod.yaml +++ b/sdrbase/resources/webapi/doc/swagger/include/DVBDemod.yaml @@ -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: 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: 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: diff --git a/sdrgui/CMakeLists.txt b/sdrgui/CMakeLists.txt index 0b7847d0d..3359b1bb3 100644 --- a/sdrgui/CMakeLists.txt +++ b/sdrgui/CMakeLists.txt @@ -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 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 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 ${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 diff --git a/sdrgui/dtv/dtvappsdialog.cpp b/sdrgui/dtv/dtvappsdialog.cpp new file mode 100644 index 000000000..3042961ce --- /dev/null +++ b/sdrgui/dtv/dtvappsdialog.cpp @@ -0,0 +1,331 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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 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 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))); + } +} diff --git a/sdrgui/dtv/dtvappsdialog.h b/sdrgui/dtv/dtvappsdialog.h new file mode 100644 index 000000000..818dd2cd2 --- /dev/null +++ b/sdrgui/dtv/dtvappsdialog.h @@ -0,0 +1,67 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DTVAPPSDIALOG_H +#define INCLUDE_DTVAPPSDIALOG_H + +#include + +#include +#include + +#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 m_expanded; //!< Of the carousels' items: by PID, and path + QTimer m_timer; +}; + +#endif // INCLUDE_DTVAPPSDIALOG_H diff --git a/plugins/channelrx/demoddvb/dvbdemodepgdialog.cpp b/sdrgui/dtv/dtvepgdialog.cpp similarity index 83% rename from plugins/channelrx/demoddvb/dvbdemodepgdialog.cpp rename to sdrgui/dtv/dtvepgdialog.cpp index e4e96d233..69e8ed6e7 100644 --- a/plugins/channelrx/demoddvb/dvbdemodepgdialog.cpp +++ b/sdrgui/dtv/dtvepgdialog.cpp @@ -34,14 +34,13 @@ #include #include -#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) : 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) : 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) : 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) : 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) } } -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 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() 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() m_servicesRevision = revision; m_servicesOthers = others; - std::vector services = m_epg->getServices(); + std::vector 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() 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() } // 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() return; } - std::vector> events = m_epg->getEvents(ids); - std::vector rows; + std::vector> events = m_epg->getEvents(ids); + std::vector 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() } // 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() 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() 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 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 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() 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() 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() 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() 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) .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 += "  " + genre.toHtmlEscaped(); @@ -579,7 +581,7 @@ QString DVBDemodEPGDialog::describe(const DVBDemodEPG::Event& e, int networkId) html += "
" + e.m_guidance.toHtmlEscaped() + ""; } - DVBDemodEPG::Service linked; + DTVGuide::Service linked; if (linkedService(e, linked)) { html += "
Also on " + linked.m_name.toHtmlEscaped(); @@ -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() } } -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) // 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 : 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 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 // 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 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 } 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 } // 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 schedule = m_demod->getScheduledRecordings(); - std::sort(schedule.begin(), schedule.end(), [](const DVBDemodSettings::ScheduledRecording& a, const DVBDemodSettings::ScheduledRecording& b) { + QList 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 series = m_demod->getSeriesRecordings(); + const QList series = m_schedule->getSeriesRecordings(); if (schedule.isEmpty() && series.isEmpty()) { @@ -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() .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(); diff --git a/plugins/channelrx/demoddvb/dvbdemodepgdialog.h b/sdrgui/dtv/dtvepgdialog.h similarity index 83% rename from plugins/channelrx/demoddvb/dvbdemodepgdialog.h rename to sdrgui/dtv/dtvepgdialog.h index 7067154c7..b1062c644 100644 --- a/plugins/channelrx/demoddvb/dvbdemodepgdialog.h +++ b/sdrgui/dtv/dtvepgdialog.h @@ -16,17 +16,17 @@ // along with this program. If not, see . // /////////////////////////////////////////////////////////////////////////////////// -#ifndef INCLUDE_DVBDEMODEPGDIALOG_H -#define INCLUDE_DVBDEMODEPGDIALOG_H +#ifndef INCLUDE_DTVEPGDIALOG_H +#define INCLUDE_DTVEPGDIALOG_H #include #include #include -#include "dvbdemodepg.h" +#include "dtv/dtvguide.h" +#include "export.h" -class DVBDemod; class QCheckBox; class QToolButton; class QComboBox; @@ -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: 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: QLabel *m_status; QTableWidget *m_events; QTabWidget *m_views; - DVBDemodEPGGrid *m_grid; - std::vector m_gridServices; //!< Rows of the grid + DTVEPGGrid *m_grid; + std::vector m_gridServices; //!< Rows of the grid QString m_gridKey; //!< The grid's rows and start std::vector m_gridServiceRevisions; //!< Their services' revisions QTextBrowser *m_description; QTimer m_timer; std::vector m_listed; - std::vector m_shown; //!< Events in the table, in its order + std::vector 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: QString m_eventsKey; //!< which would lose the scroll position }; -#endif // INCLUDE_DVBDEMODEPGDIALOG_H +#endif // INCLUDE_DTVEPGDIALOG_H diff --git a/plugins/channelrx/demoddvb/dvbdemodepggrid.cpp b/sdrgui/dtv/dtvepggrid.cpp similarity index 88% rename from plugins/channelrx/demoddvb/dvbdemodepggrid.cpp rename to sdrgui/dtv/dtvepggrid.cpp index f760e650f..3fd0a00bb 100644 --- a/plugins/channelrx/demoddvb/dvbdemodepggrid.cpp +++ b/sdrgui/dtv/dtvepggrid.cpp @@ -28,9 +28,9 @@ #include #include -#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) : 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& rows, qint64 start, qint64 now) +void DTVEPGGrid::setRows(const std::vector& 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& 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& 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) } } -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) } } -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() 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 } const qint64 t = timeAt(position.x()); - const std::vector& events = m_rows[row].m_events; + const std::vector& 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 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) } } -void DVBDemodEPGGrid::mousePressEvent(QMouseEvent *event) +void DTVEPGGrid::mousePressEvent(QMouseEvent *event) { int row, e; @@ -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) } } -void DVBDemodEPGGrid::contextMenuEvent(QContextMenuEvent *event) +void DTVEPGGrid::contextMenuEvent(QContextMenuEvent *event) { int row, e; @@ -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) return; } - const std::vector& events = m_rows[m_selectedRow].m_events; - const DVBDemodEPG::Event& current = events[m_selectedEvent]; + const std::vector& 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) for (int r = row + step; (r >= 0) && (r < (int) m_rows.size()); r += step) { - const std::vector& other = m_rows[r].m_events; + const std::vector& 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) 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) 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) 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) 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 *) // 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 *) 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)); diff --git a/plugins/channelrx/demoddvb/dvbdemodepggrid.h b/sdrgui/dtv/dtvepggrid.h similarity index 91% rename from plugins/channelrx/demoddvb/dvbdemodepggrid.h rename to sdrgui/dtv/dtvepggrid.h index 538494fc2..9a5d35737 100644 --- a/plugins/channelrx/demoddvb/dvbdemodepggrid.h +++ b/sdrgui/dtv/dtvepggrid.h @@ -16,20 +16,21 @@ // along with this program. If not, see . // /////////////////////////////////////////////////////////////////////////////////// -#ifndef INCLUDE_DVBDEMODEPGGRID_H -#define INCLUDE_DVBDEMODEPGGRID_H +#ifndef INCLUDE_DTVEPGGRID_H +#define INCLUDE_DTVEPGGRID_H #include #include #include -#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: 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 m_events; //!< In time order + std::vector 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& 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: static constexpr double m_pixelsPerHour = 240.0; }; -#endif // INCLUDE_DVBDEMODEPGGRID_H +#endif // INCLUDE_DTVEPGGRID_H diff --git a/plugins/channelrx/demoddvb/dvbdemodguideoverlay.cpp b/sdrgui/dtv/dtvguideoverlay.cpp similarity index 87% rename from plugins/channelrx/demoddvb/dvbdemodguideoverlay.cpp rename to sdrgui/dtv/dtvguideoverlay.cpp index 784ae212b..c86d5723a 100644 --- a/plugins/channelrx/demoddvb/dvbdemodguideoverlay.cpp +++ b/sdrgui/dtv/dtvguideoverlay.cpp @@ -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) // 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) 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) } // 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, 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) : 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) : }); } -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) } } -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 // 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() const std::pair 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() } } -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 // 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 DVBDemodGuideOverlay::events(int row) const +std::vector DTVGuideOverlay::events(int row) const { if ((row < 0) || (row >= (int) m_services.size())) { return {}; } - const DVBDemodEPG::Service& s = m_services[row]; - std::vector events = m_epg->getEvents(s.m_networkId, s.m_serviceId); - DVBDemodEPG::Event present, following; + const DTVGuide::Service& s = m_services[row]; + std::vector 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() 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() render(); } -void DVBDemodGuideOverlay::showGuide() +void DTVGuideOverlay::showGuide() { if (m_mode != Ribbon) { @@ -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() 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) 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) } } -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) } // 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) 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) } } -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) 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) } // 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) 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) } } -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) 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 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() } // 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 evs = events(m_row); + const std::vector evs = events(m_row); m_guideEventId = -1; for (const auto& e : evs) @@ -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) } // 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 evs = events(m_row); + const std::vector 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) 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) } } -void DVBDemodGuideOverlay::keepGuideSelectionVisible() +void DTVGuideOverlay::keepGuideSelectionVisible() { if (m_row < m_firstRow) { m_firstRow = m_row; @@ -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 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 } // 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 } // 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) 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) } 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) } // 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) } // 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 } // 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() 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) 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 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 } // 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 } // 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 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 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 painter.fillRect(QRectF(divider1, bar.y() + pad, std::max(1.0, u), height - 2 * pad), m_dividerColor); // Programmes that haven't ended - std::vector 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 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 } 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 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 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 } // 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 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 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 } 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 // 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 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 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 nameMetrics.elidedText(s.m_name, Qt::ElideRight, (int) (labelWidth - 84 * u))); // Programmes - const std::vector evs = row == m_row ? selectedRow : events(row); + const std::vector evs = row == m_row ? selectedRow : events(row); bool any = false; for (const auto& e : evs) diff --git a/plugins/channelrx/demoddvb/dvbdemodguideoverlay.h b/sdrgui/dtv/dtvguideoverlay.h similarity index 88% rename from plugins/channelrx/demoddvb/dvbdemodguideoverlay.h rename to sdrgui/dtv/dtvguideoverlay.h index 16e3b5e5e..43fe43a7f 100644 --- a/plugins/channelrx/demoddvb/dvbdemodguideoverlay.h +++ b/sdrgui/dtv/dtvguideoverlay.h @@ -1,5 +1,6 @@ /////////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 @@ // along with this program. If not, see . // /////////////////////////////////////////////////////////////////////////////////// -#ifndef INCLUDE_DVBDEMODGUIDEOVERLAY_H -#define INCLUDE_DVBDEMODGUIDEOVERLAY_H +#ifndef INCLUDE_DTVGUIDEOVERLAY_H +#define INCLUDE_DTVGUIDEOVERLAY_H #include #include @@ -29,7 +30,8 @@ #include #include -#include "dvbdemodepg.h" +#include "dtv/dtvguide.h" +#include "export.h" class QKeyEvent; class QMouseEvent; @@ -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: typedef std::function IsScheduled; typedef std::function 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: 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: //! 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: //! 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 events(int row) const; + std::vector events(int row) const; qint64 now() const; void render(); void paintRibbon(QPainter& painter, const QSize& size, qint64 t); @@ -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: void restartHideTimer(); void showMessage(const QString& message); - DVBDemodEPG *m_epg; + DTVGuide *m_epg; IsScheduled m_isScheduled; ToggleRecording m_toggleRecording; QPointer 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 m_services; //!< By channel number + std::vector 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: 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 diff --git a/plugins/channelrx/demoddvb/dvbdemodscope.cpp b/sdrgui/dtv/dtvscope.cpp similarity index 91% rename from plugins/channelrx/demoddvb/dvbdemodscope.cpp rename to sdrgui/dtv/dtvscope.cpp index ddcb29786..2bca02064 100644 --- a/plugins/channelrx/demoddvb/dvbdemodscope.cpp +++ b/sdrgui/dtv/dtvscope.cpp @@ -26,17 +26,17 @@ #include #include -#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) : 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) update(); } -void DVBDemodScope::setData(const std::vector>& cells, const std::vector& responseDb, int constellationSize, int alpha) +void DTVScope::setData(const std::vector>& cells, const std::vector& responseDb, int constellationSize, int alpha) { if (!responseDb.empty() && (responseDb != m_responseDb)) { addWaterfallRow(responseDb); @@ -83,12 +83,12 @@ void DVBDemodScope::setData(const std::vector>& cells, const update(); } -void DVBDemodScope::setPoints(const std::vector>& points) +void DTVScope::setPoints(const std::vector>& 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) } } -void DVBDemodScope::setImpulseResponse(const std::vector& powerDb, double resolution, int guard, double sampleRate) +void DTVScope::setImpulseResponse(const std::vector& powerDb, double resolution, int guard, double sampleRate) { m_impulseDb = powerDb; m_impulseResolution = resolution; @@ -110,7 +110,7 @@ void DVBDemodScope::setImpulseResponse(const std::vector& 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 } } -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) } } -void DVBDemodScope::paintEvent(QPaintEvent *event) +void DTVScope::paintEvent(QPaintEvent *event) { (void) event; QPainter painter(this); @@ -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 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) 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) } // 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) (int) (stops[i][2] + f * (stops[i + 1][2] - stops[i][2]))); } -void DVBDemodScope::addWaterfallRow(const std::vector& responseDb) +void DTVScope::addWaterfallRow(const std::vector& responseDb) { const int width = (int) responseDb.size(); @@ -356,7 +356,7 @@ void DVBDemodScope::addWaterfallRow(const std::vector& 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) } } -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) 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); diff --git a/plugins/channelrx/demoddvb/dvbdemodscope.h b/sdrgui/dtv/dtvscope.h similarity index 96% rename from plugins/channelrx/demoddvb/dvbdemodscope.h rename to sdrgui/dtv/dtvscope.h index fe365cc49..344b6ad57 100644 --- a/plugins/channelrx/demoddvb/dvbdemodscope.h +++ b/sdrgui/dtv/dtvscope.h @@ -16,8 +16,8 @@ // along with this program. If not, see . // /////////////////////////////////////////////////////////////////////////////////// -#ifndef INCLUDE_DVBDEMODSCOPE_H -#define INCLUDE_DVBDEMODSCOPE_H +#ifndef INCLUDE_DTVSCOPE_H +#define INCLUDE_DTVSCOPE_H #include #include @@ -27,17 +27,19 @@ #include #include +#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: static const QColor m_errorsColour; }; -#endif // INCLUDE_DVBDEMODSCOPE_H +#endif // INCLUDE_DTVSCOPE_H diff --git a/sdrgui/dtv/dtvstreamplayback.cpp b/sdrgui/dtv/dtvstreamplayback.cpp new file mode 100644 index 000000000..f1d30b483 --- /dev/null +++ b/sdrgui/dtv/dtvstreamplayback.cpp @@ -0,0 +1,240 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include + +#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 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& 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(); + } +} diff --git a/sdrgui/dtv/dtvstreamplayback.h b/sdrgui/dtv/dtvstreamplayback.h new file mode 100644 index 000000000..476d41fc9 --- /dev/null +++ b/sdrgui/dtv/dtvstreamplayback.h @@ -0,0 +1,97 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DTVSTREAMPLAYBACK_H +#define INCLUDE_DTVSTREAMPLAYBACK_H + +#include +#include +#include + +#include +#include +#include +#include + +#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 configure, QObject *parent = nullptr); + ~DTVStreamPlayback(); + + //! options: FFmpeg's, as user_agent and headers + void load(const QString& url, const QMap& 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 m_configure; + QString m_url; + QMap m_options; + double m_position; //!< Where the stream's started from (when paused, where it's paused) + bool m_playing; + std::unique_ptr m_fifo; + DTVStreamRemuxer *m_remuxer; + DTVVideoPlayer *m_player; + std::atomic m_frameTime; //!< Timestamp of the last picture shown, NaN if none yet + std::atomic m_frameAt; //!< When, ms since epoch + std::atomic m_playingSignalled; + double m_duration; + QTimer m_timer; +}; + +#endif // INCLUDE_DTVSTREAMPLAYBACK_H diff --git a/sdrgui/dtv/dtvstreamremuxer.cpp b/sdrgui/dtv/dtvstreamremuxer.cpp new file mode 100644 index 000000000..db4e64127 --- /dev/null +++ b/sdrgui/dtv/dtvstreamremuxer.cpp @@ -0,0 +1,289 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include + +extern "C" { +#include +#include +} + +#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& 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(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(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::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); +} diff --git a/sdrgui/dtv/dtvstreamremuxer.h b/sdrgui/dtv/dtvstreamremuxer.h new file mode 100644 index 000000000..529dd5280 --- /dev/null +++ b/sdrgui/dtv/dtvstreamremuxer.h @@ -0,0 +1,74 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DTVSTREAMREMUXER_H +#define INCLUDE_DTVSTREAMREMUXER_H + +#include + +#include +#include +#include + +#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& 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 m_options; + const double m_start; + std::atomic m_stop; + std::atomic m_duration; + std::atomic m_offset; + std::atomic m_finished; +}; + +#endif // INCLUDE_DTVSTREAMREMUXER_H diff --git a/plugins/channelrx/demoddvb/dvbdemodvideoplayer.cpp b/sdrgui/dtv/dtvvideoplayer.cpp similarity index 86% rename from plugins/channelrx/demoddvb/dvbdemodvideoplayer.cpp rename to sdrgui/dtv/dtvvideoplayer.cpp index 76f3b2319..f783299e1 100644 --- a/plugins/channelrx/demoddvb/dvbdemodvideoplayer.cpp +++ b/sdrgui/dtv/dtvvideoplayer.cpp @@ -23,6 +23,12 @@ #include #include +#include +#include +#include +#include +#include +#include // C++ headers FFmpeg's hardware contexts include, which can't be in extern "C" #if defined(_WIN32) @@ -57,7 +63,7 @@ typedef struct CUstream_st *CUstream; #include #include #include -#ifdef DVBDEMOD_DEINTERLACE +#ifdef DTV_DEINTERLACE #include #include #include @@ -67,15 +73,15 @@ typedef struct CUstream_st *CUstream; // FFmpeg's APIs that differ between the versions built with (4.4 on). AVChannelLayout from FFmpeg 5.1 (the channel // masks deprecated then, and gone in 7) #if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) -#define DVBDEMOD_CH_LAYOUT +#define DTV_CH_LAYOUT #endif // AVFrame's interlacing flags from 6.1 (its fields deprecated then) #if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(58, 7, 100) -#define DVBDEMOD_FRAME_FLAGS +#define DTV_FRAME_FLAGS #endif // Threaded conversion with sws_scale_frame(), used from 7 (it's in 5, but its threads were new) #if LIBSWSCALE_VERSION_INT >= AV_VERSION_INT(8, 0, 100) -#define DVBDEMOD_SWS_THREADS +#define DTV_SWS_THREADS #endif #include "audio/audiofifo.h" @@ -86,16 +92,16 @@ typedef struct CUstream_st *CUstream; #include #endif -#include "dvbdemodtsfifo.h" -#include "dvbdemodvideoplayer.h" +#include "dtv/dtvtsfifo.h" +#include "dtv/dtvvideoplayer.h" -std::chrono::steady_clock::duration DVBDemodVideoPlayer::seconds(double s) +std::chrono::steady_clock::duration DTVVideoPlayer::seconds(double s) { return std::chrono::duration_cast(std::chrono::duration(s)); } // A PES header's PTS (33 bits, 90 kHz), from its 5 bytes -int64_t DVBDemodVideoPlayer::pesPTS(const uint8_t *h) +int64_t DTVVideoPlayer::pesPTS(const uint8_t *h) { return ((int64_t) ((h[0] >> 1) & 7) << 30) | ((int64_t) h[1] << 22) | ((int64_t) (h[2] >> 1) << 15) | ((int64_t) h[3] << 7) | (h[4] >> 1); @@ -104,7 +110,7 @@ int64_t DVBDemodVideoPlayer::pesPTS(const uint8_t *h) // Whether TS packets of a PID were lost before this one: the continuity counter of a good packet isn't one more than // the last good one's, allowing for those with errors between (whose counters can't be trusted), nor the same (a // duplicate), without a discontinuity signalled. Updates the last good counter, and the count of those with errors -bool DVBDemodVideoPlayer::continuityLost(const uint8_t *p, bool discontinuity, int& lastCC, int& errorPackets) +bool DTVVideoPlayer::continuityLost(const uint8_t *p, bool discontinuity, int& lastCC, int& errorPackets) { const bool error = (p[1] & 0x80) != 0; const int cc = p[3] & 0x0f; @@ -123,7 +129,7 @@ bool DVBDemodVideoPlayer::continuityLost(const uint8_t *p, bool discontinuity, i return lost; } -DVBDemodVideoPlayer::DVBDemodVideoPlayer(DVBDemodTSFifo *tsFifo, AudioFifo *audioFifo, QObject *parent) : +DTVVideoPlayer::DTVVideoPlayer(DTVTSFifo *tsFifo, AudioFifo *audioFifo, QObject *parent) : QThread(parent), m_tsFifo(tsFifo), m_audioFifo(audioFifo), @@ -215,10 +221,10 @@ DVBDemodVideoPlayer::DVBDemodVideoPlayer(DVBDemodTSFifo *tsFifo, AudioFifo *audi m_avOffset(0.0), m_info{0, "", "", "", 0, 0, 0, 0, 0, 0, false, 0, 0, false, 0, 0, 0} { - setObjectName("DVBDemodVideoPlayer"); - qRegisterMetaType(); - qRegisterMetaType>(); - qRegisterMetaType(); + setObjectName("DTVVideoPlayer"); + qRegisterMetaType(); + qRegisterMetaType>(); + qRegisterMetaType(); // FFmpeg's log level is the process's: set once. Received streams have errors, which the decoders would log for // each damaged picture or packet, flooding the log @@ -226,18 +232,27 @@ DVBDemodVideoPlayer::DVBDemodVideoPlayer(DVBDemodTSFifo *tsFifo, AudioFifo *audi std::call_once(logLevel, []() { av_log_set_level(AV_LOG_FATAL); }); } -DVBDemodVideoPlayer::~DVBDemodVideoPlayer() +bool DTVVideoPlayer::canDeinterlace() +{ +#ifdef DTV_DEINTERLACE + return true; +#else + return false; +#endif +} + +DTVVideoPlayer::~DTVVideoPlayer() { stopPlayer(); } -void DVBDemodVideoPlayer::stopPlayer() +void DTVVideoPlayer::stopPlayer() { m_stop = true; wait(); } -void DVBDemodVideoPlayer::setAudioOutput(int sampleRate, double latency) +void DTVVideoPlayer::setAudioOutput(int sampleRate, double latency) { if (sampleRate > 0) { m_audioSampleRate = sampleRate; @@ -246,14 +261,14 @@ void DVBDemodVideoPlayer::setAudioOutput(int sampleRate, double latency) m_audioLatency = std::max(0.0, std::min(1.0, latency)); } -void DVBDemodVideoPlayer::setAudioVolume(int volume) +void DTVVideoPlayer::setAudioVolume(int volume) { volume = std::max(0, std::min(100, volume)); // 0.01 to 1, logarithmic, and 0 silent m_audioGain = volume == 0 ? 0.0f : (float) std::pow(10.0, volume * 0.02 - 2.0); } -void DVBDemodVideoPlayer::setTrackPreferences(const QString& audioLanguage, Track::Type audioType, bool subtitles, +void DTVVideoPlayer::setTrackPreferences(const QString& audioLanguage, Track::Type audioType, bool subtitles, const QString& subtitleLanguage, Track::Type subtitleType) { QMutexLocker locker(&m_tracksMutex); @@ -270,13 +285,13 @@ void DVBDemodVideoPlayer::setTrackPreferences(const QString& audioLanguage, Trac } } -DVBDemodVideoPlayer::Info DVBDemodVideoPlayer::getInfo() +DTVVideoPlayer::Info DTVVideoPlayer::getInfo() { QMutexLocker locker(&m_infoMutex); return m_info; } -void DVBDemodVideoPlayer::run() +void DTVVideoPlayer::run() { m_frame = av_frame_alloc(); m_videoFrame = av_frame_alloc(); @@ -310,9 +325,9 @@ void DVBDemodVideoPlayer::run() } // FFmpeg reads the transport stream from the FIFO, waiting for the demodulator as needed -int DVBDemodVideoPlayer::readPacket(void *opaque, uint8_t *buf, int size) +int DTVVideoPlayer::readPacket(void *opaque, uint8_t *buf, int size) { - DVBDemodVideoPlayer *player = static_cast(opaque); + DTVVideoPlayer *player = static_cast(opaque); while (!player->m_stop) { @@ -326,7 +341,7 @@ int DVBDemodVideoPlayer::readPacket(void *opaque, uint8_t *buf, int size) PROFILER_START() int n = player->m_tsFifo->read(buf, size, 100); - PROFILER_STOP("DVBDemod video waiting for TS") + PROFILER_STOP("DTV video waiting for TS") if (n > 0) { @@ -347,7 +362,7 @@ int DVBDemodVideoPlayer::readPacket(void *opaque, uint8_t *buf, int size) return AVERROR_EOF; } -bool DVBDemodVideoPlayer::open() +bool DTVVideoPlayer::open() { m_formatCtx = avformat_alloc_context(); m_psi.reset(); @@ -357,7 +372,7 @@ bool DVBDemodVideoPlayer::open() m_transportStreamId = -1; m_timestampRefValid = false; uint8_t *ioBuffer = (uint8_t *) av_malloc(m_ioBufferSize); - m_ioCtx = avio_alloc_context(ioBuffer, m_ioBufferSize, 0, this, &DVBDemodVideoPlayer::readPacket, nullptr, nullptr); + m_ioCtx = avio_alloc_context(ioBuffer, m_ioBufferSize, 0, this, &DTVVideoPlayer::readPacket, nullptr, nullptr); m_formatCtx->pb = m_ioCtx; m_formatCtx->flags |= AVFMT_FLAG_CUSTOM_IO; @@ -371,7 +386,7 @@ bool DVBDemodVideoPlayer::open() if (ret < 0) { - qDebug() << "DVBDemodVideoPlayer::open: avformat_open_input failed:" << ret; + qDebug() << "DTVVideoPlayer::open: avformat_open_input failed:" << ret; close(); return false; } @@ -387,12 +402,12 @@ bool DVBDemodVideoPlayer::open() // Reading goes on from where probing stopped m_ioCtx->eof_reached = 0; m_ioCtx->error = 0; - qDebug("DVBDemodVideoPlayer::open: probing stopped after %.0f s of data: some streams gave no packets (scrambled?)", maxProbeSeconds); + qDebug("DTVVideoPlayer::open: probing stopped after %.0f s of data: some streams gave no packets (scrambled?)", maxProbeSeconds); } if ((ret < 0) && !m_probeStopped) { - qDebug() << "DVBDemodVideoPlayer::open: avformat_find_stream_info failed"; + qDebug() << "DTVVideoPlayer::open: avformat_find_stream_info failed"; close(); return false; } @@ -401,7 +416,7 @@ bool DVBDemodVideoPlayer::open() m_transportStreamId = m_psi.getTransportStreamId(); m_services = getServices(); m_servicesChecked = std::chrono::steady_clock::now(); - qDebug() << "DVBDemodVideoPlayer::open:" << m_services.size() << "services"; + qDebug() << "DTVVideoPlayer::open:" << m_services.size() << "services"; emit servicesChanged(m_services); m_selectedRequest = -1; @@ -409,7 +424,7 @@ bool DVBDemodVideoPlayer::open() } // The services of the multiplex, named from the SDT if it's been received -QList DVBDemodVideoPlayer::getServices() const +QList DTVVideoPlayer::getServices() const { QList services; @@ -439,7 +454,7 @@ QList DVBDemodVideoPlayer::getServices() const return services; } -void DVBDemodVideoPlayer::updateServices() +void DTVVideoPlayer::updateServices() { QList services = getServices(); bool changed = services.size() != m_services.size(); @@ -536,7 +551,7 @@ void DVBDemodVideoPlayer::updateServices() } // What decides a stream's track and decoder, copied (FFmpeg changes the stream in place) -std::vector DVBDemodVideoPlayer::signaturesOf(const std::vector& streams) const +std::vector DTVVideoPlayer::signaturesOf(const std::vector& streams) const { std::vector signatures; @@ -558,7 +573,7 @@ std::vector DVBDemodVideoPlayer::signaturesOf(const std::vectorcodecpar->codec_id); @@ -647,7 +665,7 @@ AVCodecContext *DVBDemodVideoPlayer::openDecoder(AVStream *stream) return ctx; } -void DVBDemodVideoPlayer::setHardwareDecoding(bool hardware) +void DTVVideoPlayer::setHardwareDecoding(bool hardware) { if (hardware != m_hardwareDecoding) { @@ -683,7 +701,7 @@ static AVPixelFormat getHardwareFormat(AVCodecContext *ctx, const AVPixelFormat } // Hardware decoding with the platform's usual API, if FFmpeg was built with it and the codec supports it -bool DVBDemodVideoPlayer::setupHardwareDecoding(const AVCodec *codec, AVCodecContext *ctx) +bool DTVVideoPlayer::setupHardwareDecoding(const AVCodec *codec, AVCodecContext *ctx) { // NVDEC first, as its frames can be deinterlaced with bwdif, as in software static const AVHWDeviceType types[] = { @@ -696,8 +714,14 @@ bool DVBDemodVideoPlayer::setupHardwareDecoding(const AVCodec *codec, AVCodecCon #endif }; - // DVBDEMOD_HWDEVICE in the environment chooses one (e.g. cuda, d3d11va, vaapi), as for testing - const QByteArray forced = qgetenv("DVBDEMOD_HWDEVICE"); + // DTV_HWDEVICE (or, as before, DVBDEMOD_HWDEVICE) in the environment chooses one (e.g. cuda, d3d11va, vaapi), as + // for testing + QByteArray forced = qgetenv("DTV_HWDEVICE"); + + if (forced.isEmpty()) { + forced = qgetenv("DVBDEMOD_HWDEVICE"); + } + const AVHWDeviceType forcedType = forced.isEmpty() ? AV_HWDEVICE_TYPE_NONE : av_hwdevice_find_type_by_name(forced.constData()); for (AVHWDeviceType type : types) @@ -743,7 +767,7 @@ bool DVBDemodVideoPlayer::setupHardwareDecoding(const AVCodec *codec, AVCodecCon return false; } -AVCodecContext *DVBDemodVideoPlayer::openVideoDecoder(AVStream *stream) +AVCodecContext *DTVVideoPlayer::openVideoDecoder(AVStream *stream) { const AVCodec *codec = avcodec_find_decoder(stream->codecpar->codec_id); @@ -774,7 +798,7 @@ AVCodecContext *DVBDemodVideoPlayer::openVideoDecoder(AVStream *stream) } // Choose the requested service, or the first with video, its first video stream, and its audio and subtitles -void DVBDemodVideoPlayer::selectService(bool reselect) +void DTVVideoPlayer::selectService(bool reselect) { int requested = m_requestedService; m_selectedRequest = requested; @@ -898,7 +922,7 @@ void DVBDemodVideoPlayer::selectService(bool reselect) } m_selectedSignatures = signaturesOf(m_selectedStreams); - qDebug() << "DVBDemodVideoPlayer::selectService: requested" << requested << "selected" << id + qDebug() << "DTVVideoPlayer::selectService: requested" << requested << "selected" << id << "video stream" << m_videoStream << "audio stream" << m_audioStream; { @@ -913,7 +937,7 @@ void DVBDemodVideoPlayer::selectService(bool reselect) emit serviceSelected(id, m_videoCtx != nullptr, m_audioCtx != nullptr); } -bool DVBDemodVideoPlayer::readAndDecode() +bool DTVVideoPlayer::readAndDecode() { const bool reselect = m_reselect.exchange(false); @@ -921,6 +945,8 @@ bool DVBDemodVideoPlayer::readAndDecode() selectService(reselect); } else if (m_tracksChanged.exchange(false)) { selectTracks(); + } else if (m_captionsSeen && !m_captionsListed && (m_programIndex >= 0)) { + addCaptionTrack(); } PROFILER_START() @@ -943,7 +969,7 @@ bool DVBDemodVideoPlayer::readAndDecode() } else if ((transportStreamId >= 0) && (transportStreamId != m_transportStreamId)) { - qDebug("DVBDemodVideoPlayer::readAndDecode: transport stream id changed from %d to %d: reopening", + qDebug("DTVVideoPlayer::readAndDecode: transport stream id changed from %d to %d: reopening", m_transportStreamId, transportStreamId); av_packet_unref(m_packet); return false; @@ -953,7 +979,7 @@ bool DVBDemodVideoPlayer::readAndDecode() m_servicesChecked = now; } - PROFILER_STOP("DVBDemod video demux (including waiting for TS)") + PROFILER_STOP("DTV video demux (including waiting for TS)") if ((m_packet->stream_index == m_videoStream) || (m_packet->stream_index == m_audioStream) || (m_packet->stream_index == m_adStream) || (m_packet->stream_index == m_subtitleStream)) @@ -966,15 +992,15 @@ bool DVBDemodVideoPlayer::readAndDecode() } else if ((m_packet->stream_index == m_audioStream) && m_audioCtx) { PROFILER_RESTART() decodeAudio(); - PROFILER_STOP("DVBDemod audio decode and output") + PROFILER_STOP("DTV audio decode and output") } else if (m_packet->stream_index == m_adStream) { PROFILER_RESTART() decodeAudioDescription(); - PROFILER_STOP("DVBDemod audio description decode") + PROFILER_STOP("DTV audio description decode") } else if ((m_packet->stream_index == m_subtitleStream) && m_subtitleCtx) { PROFILER_RESTART() decodeSubtitle(); - PROFILER_STOP("DVBDemod subtitle decode") + PROFILER_STOP("DTV subtitle decode") } av_packet_unref(m_packet); @@ -987,7 +1013,7 @@ bool DVBDemodVideoPlayer::readAndDecode() // between them (as on Sky's, each programme with its own PTS base) can change for another's streams mid-stream: the // video's timestamps fell 2^33 (26.5 hours) behind the audio's, so every frame restarted the clock. What FFmpeg added // doesn't matter here -void DVBDemodVideoPlayer::unwrapTimestamps(AVPacket *packet) +void DTVVideoPlayer::unwrapTimestamps(AVPacket *packet) { const AVRational timeBase = m_formatCtx->streams[packet->stream_index]->time_base; @@ -1029,7 +1055,7 @@ void DVBDemodVideoPlayer::unwrapTimestamps(AVPacket *packet) // Pass a video packet to the video thread. If it has fallen far behind, rather than wait for it (which would hold up // the audio, and the TS, which would overflow), the video waiting is dropped, and what follows up to a keyframe, where // the video thread decodes from again -void DVBDemodVideoPlayer::queueVideoPacket() +void DTVVideoPlayer::queueVideoPacket() { if (videoFrameDamaged(m_packet)) { m_packet->flags |= AV_PKT_FLAG_CORRUPT; @@ -1053,7 +1079,7 @@ void DVBDemodVideoPlayer::queueVideoPacket() m_videoBytes = 0; m_videoPackets.push_back(nullptr); // The discontinuity, for the video thread m_videoResync = true; - qDebug("DVBDemodVideoPlayer::queueVideoPacket: video fell behind: %llu packets dropped", (unsigned long long) dropped); + qDebug("DTVVideoPlayer::queueVideoPacket: video fell behind: %llu packets dropped", (unsigned long long) dropped); } if (m_videoResync && !key) @@ -1079,17 +1105,17 @@ void DVBDemodVideoPlayer::queueVideoPacket() } } -void DVBDemodVideoPlayer::startVideoThread() +void DTVVideoPlayer::startVideoThread() { if (!m_videoCtx) { return; } m_videoStop = false; - m_videoThread = std::thread(&DVBDemodVideoPlayer::videoThread, this); + m_videoThread = std::thread(&DTVVideoPlayer::videoThread, this); } -void DVBDemodVideoPlayer::stopVideoThread() +void DTVVideoPlayer::stopVideoThread() { if (m_videoThread.joinable()) { @@ -1113,7 +1139,7 @@ void DVBDemodVideoPlayer::stopVideoThread() m_videoResync = false; } -void DVBDemodVideoPlayer::videoThread() +void DTVVideoPlayer::videoThread() { #ifdef _WIN32 // Frames are timed by sleeping, which by default is in 15.6 ms steps on Windows: uneven at 25 or 50 frames/s. @@ -1152,20 +1178,20 @@ void DVBDemodVideoPlayer::videoThread() } } -const AVHWFramesContext *DVBDemodVideoPlayer::framesContext(const AVFrame *frame) +const AVHWFramesContext *DTVVideoPlayer::framesContext(const AVFrame *frame) { return frame->hw_frames_ctx ? reinterpret_cast(frame->hw_frames_ctx->data) : nullptr; } // If FFmpeg has a filter to deinterlace GPU frames of the format, without copying them to memory (setupDeinterlacer) -#ifdef DVBDEMOD_DEINTERLACE -bool DVBDemodVideoPlayer::hasGPUDeinterlacer(int format) +#ifdef DTV_DEINTERLACE +bool DTVVideoPlayer::hasGPUDeinterlacer(int format) { return (format == AV_PIX_FMT_CUDA) || (format == AV_PIX_FMT_VAAPI) || (format == AV_PIX_FMT_VIDEOTOOLBOX); } #endif -void DVBDemodVideoPlayer::decodeVideo(AVPacket *packet) +void DTVVideoPlayer::decodeVideo(AVPacket *packet) { // GPU decoders aren't as robust against damaged data as FFmpeg's own: NVDEC read thousands of bytes beyond a // corrupt slice's data, and crashed (also in an MPEG-2 keyframe FFmpeg hadn't flagged). So packets flagged with @@ -1270,7 +1296,7 @@ void DVBDemodVideoPlayer::decodeVideo(AVPacket *packet) return; } - PROFILER_STOP("DVBDemod video decode") + PROFILER_STOP("DTV video decode") // Kept from the keyframe on, for software decoding to replay if the GOP's damaged if (gpuDecoding && m_videoSoftwareCtx) @@ -1301,7 +1327,7 @@ void DVBDemodVideoPlayer::decodeVideo(AVPacket *packet) } } -void DVBDemodVideoPlayer::clearGOP() +void DTVVideoPlayer::clearGOP() { for (AVPacket *packet : m_gopPackets) { av_packet_free(&packet); @@ -1314,7 +1340,7 @@ void DVBDemodVideoPlayer::clearGOP() // Damage, with the GPU decoding: FFmpeg decodes in software from the GOP's keyframe, those frames the GPU had shown // replayed without being shown again, those it hadn't put out not lost. Counted -void DVBDemodVideoPlayer::startSoftwareGOP() +void DTVVideoPlayer::startSoftwareGOP() { avcodec_flush_buffers(m_videoSoftwareCtx); avcodec_flush_buffers(m_videoCtx); @@ -1333,9 +1359,9 @@ void DVBDemodVideoPlayer::startSoftwareGOP() // FFmpeg fell back to software in the GPU's context: m_videoSoftwareCtx decodes from now on, from the GOP's keyframe // (as for damage), the frames already shown not again. The GPU's context isn't used again for the service, so if a // later sequence could be decoded by the GPU, it isn't (the service selected again would) -void DVBDemodVideoPlayer::startSoftwareFallback() +void DTVVideoPlayer::startSoftwareFallback() { - qDebug("DVBDemodVideoPlayer::startSoftwareFallback: FFmpeg decodes in software: its decoder with threads takes over"); + qDebug("DTVVideoPlayer::startSoftwareFallback: FFmpeg decodes in software: its decoder with threads takes over"); avcodec_flush_buffers(m_videoSoftwareCtx); avcodec_flush_buffers(m_videoCtx); // Its frames let go of m_videoFallback = true; @@ -1349,7 +1375,7 @@ void DVBDemodVideoPlayer::startSoftwareFallback() // The GOP's packets kept, from its keyframe, into the software decoder. The pictures already shown that nothing refers // to aren't decoded (AVDISCARD_NONREF), so it catches up sooner, rather than the picture freezing then rushing on -void DVBDemodVideoPlayer::replayGOP() +void DTVVideoPlayer::replayGOP() { std::vector packets; packets.swap(m_gopPackets); @@ -1372,7 +1398,7 @@ void DVBDemodVideoPlayer::replayGOP() // The video before was dropped, as the video thread fell far behind: the next packet is a keyframe, which a GPU's // decoder waits for (as after damage), and the GOP kept for software decoding no longer leads to it -void DVBDemodVideoPlayer::videoDiscontinuity() +void DTVVideoPlayer::videoDiscontinuity() { if (!m_videoCtx) { return; @@ -1386,9 +1412,9 @@ void DVBDemodVideoPlayer::videoDiscontinuity() } // The decoders skip pictures nothing refers to (AVDISCARD_NONREF), or not (AVDISCARD_DEFAULT) -void DVBDemodVideoPlayer::setVideoDiscard(int discard) +void DTVVideoPlayer::setVideoDiscard(int discard) { - qDebug("DVBDemodVideoPlayer::setVideoDiscard: %s", discard == AVDISCARD_DEFAULT ? "decoding every picture again" + qDebug("DTVVideoPlayer::setVideoDiscard: %s", discard == AVDISCARD_DEFAULT ? "decoding every picture again" : "frames late: skipping pictures nothing refers to"); m_videoDiscard = discard; m_videoCtx->skip_frame = (AVDiscard) discard; @@ -1401,7 +1427,7 @@ void DVBDemodVideoPlayer::setVideoDiscard(int discard) // Shed decoding work while frames are consistently late (the decoder can't keep up), rather than decode pictures to // drop them, until they've been on time for some seconds. A late frame now and then, as when the timestamps jump, // doesn't -void DVBDemodVideoPlayer::updateShedding(bool late) +void DTVVideoPlayer::updateShedding(bool late) { m_lateScore = m_lateScore * m_lateScoreDecay + (late ? 1.0 : 0.0); m_onTimeFrames = late ? 0 : m_onTimeFrames + 1; @@ -1413,7 +1439,7 @@ void DVBDemodVideoPlayer::updateShedding(bool late) } } -void DVBDemodVideoPlayer::decodeVideoSoftware(AVPacket *packet) +void DTVVideoPlayer::decodeVideoSoftware(AVPacket *packet) { PROFILER_START() @@ -1424,12 +1450,12 @@ void DVBDemodVideoPlayer::decodeVideoSoftware(AVPacket *packet) return; } - PROFILER_STOP("DVBDemod video software decode") + PROFILER_STOP("DTV video software decode") receiveVideoFrames(m_videoSoftwareCtx); } // After the handover to the GPU: the software decoder's last frames (those before the keyframe), then the GPU's -void DVBDemodVideoPlayer::endSoftwareGOP() +void DTVVideoPlayer::endSoftwareGOP() { avcodec_send_packet(m_videoSoftwareCtx, nullptr); receiveVideoFrames(m_videoSoftwareCtx); @@ -1439,7 +1465,7 @@ void DVBDemodVideoPlayer::endSoftwareGOP() } // The frames a decoder has ready, deinterlaced and shown -void DVBDemodVideoPlayer::receiveVideoFrames(AVCodecContext *ctx) +void DTVVideoPlayer::receiveVideoFrames(AVCodecContext *ctx) { PROFILER_START() @@ -1451,7 +1477,7 @@ void DVBDemodVideoPlayer::receiveVideoFrames(AVCodecContext *ctx) break; } - PROFILER_STOP("DVBDemod video decode") + PROFILER_STOP("DTV video decode") // Those already shown, as when a GOP's replayed for software decoding, not again const int64_t timestamp = m_videoFrame->best_effort_timestamp != AV_NOPTS_VALUE ? m_videoFrame->best_effort_timestamp : m_videoFrame->pts; @@ -1481,6 +1507,21 @@ void DVBDemodVideoPlayer::receiveVideoFrames(AVCodecContext *ctx) m_lastVideoPts = pts; } + // Closed captions (A/53), from the picture's user data: the frames come in presentation order, as the + // captions are sent. Before deinterlacing, which can make two frames of one + if (const AVFrameSideData *captions = av_frame_get_side_data(m_videoFrame, AV_FRAME_DATA_A53_CC)) + { + m_captionsSeen = true; + + if (m_captionsEnabled && (timestamp != AV_NOPTS_VALUE)) { + decodeCaptions(captions, timestamp); + } + } + + if (!m_captionsEnabled && m_captionCtx) { + closeCaptions(); + } + // GPU frames the display can show stay there, else are copied to memory const bool gpu = (m_hwPixelFormat != AV_PIX_FMT_NONE) && (m_videoFrame->format == m_hwPixelFormat); const int type = gpu ? gpuFrameType(m_videoFrame) : -1; @@ -1494,7 +1535,7 @@ void DVBDemodVideoPlayer::receiveVideoFrames(AVCodecContext *ctx) m_info.m_videoDecoder = gpu ? m_hwName : QString(); } -#ifdef DVBDEMOD_DEINTERLACE +#ifdef DTV_DEINTERLACE // Without the GPU's deinterlacer, frames are deinterlaced in memory if (keepOnGPU && m_deinterlace && m_gpuDeinterlaceFailed && (m_videoFrame->format != AV_PIX_FMT_D3D11)) { keepOnGPU = false; @@ -1511,7 +1552,7 @@ void DVBDemodVideoPlayer::receiveVideoFrames(AVCodecContext *ctx) continue; } -#ifdef DVBDEMOD_DEINTERLACE +#ifdef DTV_DEINTERLACE // D3D11 frames are deinterlaced by the display if (m_deinterlace && !(keepOnGPU && (m_videoFrame->format == AV_PIX_FMT_D3D11))) { @@ -1544,7 +1585,7 @@ void DVBDemodVideoPlayer::receiveVideoFrames(AVCodecContext *ctx) { while (av_buffersink_get_frame(m_bufferSink, m_filtered) >= 0) { - PROFILER_STOP("DVBDemod video deinterlace") + PROFILER_STOP("DTV video deinterlace") if (!copyAfter || !m_filtered->hw_frames_ctx || transferFromGPU(m_filtered)) { renderFrame(m_filtered); @@ -1555,7 +1596,7 @@ void DVBDemodVideoPlayer::receiveVideoFrames(AVCodecContext *ctx) } } - PROFILER_STOP("DVBDemod video deinterlace") + PROFILER_STOP("DTV video deinterlace") av_frame_unref(m_videoFrame); continue; @@ -1576,7 +1617,7 @@ void DVBDemodVideoPlayer::receiveVideoFrames(AVCodecContext *ctx) } } -bool DVBDemodVideoPlayer::getPooledBuffer(FramePool& pool, AVFrame *frame) +bool DTVVideoPlayer::getPooledBuffer(FramePool& pool, AVFrame *frame) { if (!pool.m_pool || (frame->format != pool.m_format) || (frame->width != pool.m_width) || (frame->height != pool.m_height)) { @@ -1637,7 +1678,7 @@ bool DVBDemodVideoPlayer::getPooledBuffer(FramePool& pool, AVFrame *frame) return true; } -void DVBDemodVideoPlayer::freePool(FramePool& pool) +void DTVVideoPlayer::freePool(FramePool& pool) { av_buffer_pool_uninit(&pool.m_pool); pool.m_format = -1; @@ -1647,7 +1688,7 @@ void DVBDemodVideoPlayer::freePool(FramePool& pool) // Copy a GPU frame to memory, in its place, into a buffer from m_transferPool. False, with the frame released, if it // couldn't be -bool DVBDemodVideoPlayer::transferFromGPU(AVFrame *frame) +bool DTVVideoPlayer::transferFromGPU(AVFrame *frame) { PROFILER_START() av_frame_unref(m_transferFrame); @@ -1684,15 +1725,15 @@ bool DVBDemodVideoPlayer::transferFromGPU(AVFrame *frame) m_transferFrame->height = frame->height; av_frame_unref(frame); av_frame_move_ref(frame, m_transferFrame); - PROFILER_STOP("DVBDemod video transfer from GPU") + PROFILER_STOP("DTV video transfer from GPU") return true; } // bwdif only processes frames that are marked as interlaced, outputting a frame for each frame -bool DVBDemodVideoPlayer::setupDeinterlacer(const AVFrame *frame) +bool DTVVideoPlayer::setupDeinterlacer(const AVFrame *frame) { closeDeinterlacer(); -#ifdef DVBDEMOD_DEINTERLACE +#ifdef DTV_DEINTERLACE AVRational timeBase = AVRational{m_videoTimeBaseNum, m_videoTimeBaseDen}; AVRational sar = frame->sample_aspect_ratio; @@ -1757,7 +1798,7 @@ bool DVBDemodVideoPlayer::setupDeinterlacer(const AVFrame *frame) if (!ok) { - qWarning() << "DVBDemodVideoPlayer::setupDeinterlacer: failed:" << filter << args; + qWarning() << "DTVVideoPlayer::setupDeinterlacer: failed:" << filter << args; avfilter_graph_free(&m_filterGraph); m_bufferSrc = nullptr; m_bufferSink = nullptr; @@ -1774,9 +1815,9 @@ bool DVBDemodVideoPlayer::setupDeinterlacer(const AVFrame *frame) // The deinterlacer's last frame (bwdif holds one until the next comes), shown rather than lost, before it's set up // again for frames of another format or size: as each time software decodes a damaged GOP in place of the GPU, and // the GPU takes over again -void DVBDemodVideoPlayer::flushDeinterlacer() +void DTVVideoPlayer::flushDeinterlacer() { -#ifdef DVBDEMOD_DEINTERLACE +#ifdef DTV_DEINTERLACE if (!m_filterGraph || (av_buffersrc_add_frame_flags(m_bufferSrc, nullptr, 0) < 0)) { return; } @@ -1796,9 +1837,9 @@ void DVBDemodVideoPlayer::flushDeinterlacer() #endif } -void DVBDemodVideoPlayer::closeDeinterlacer() +void DTVVideoPlayer::closeDeinterlacer() { -#ifdef DVBDEMOD_DEINTERLACE +#ifdef DTV_DEINTERLACE avfilter_graph_free(&m_filterGraph); #endif m_filterGraph = nullptr; @@ -1810,7 +1851,7 @@ void DVBDemodVideoPlayer::closeDeinterlacer() // The timestamp of the audio being played: of the end of the last audio written, less what is still queued. Muted // audio is written too (silent), so the clock runs on -bool DVBDemodVideoPlayer::getAudioClock(double& clock) +bool DTVVideoPlayer::getAudioClock(double& clock) { std::lock_guard lock(m_audioClockMutex); @@ -1831,7 +1872,7 @@ bool DVBDemodVideoPlayer::getAudioClock(double& clock) // Give up waiting if the timestamps jump, as when the receiver reacquires. // Returns false for a frame too late to show, as showing the frames that have fallen behind in quick succession // looks worse than skipping them. late: it was too late, or so late the clock restarted (for shedding decoding work) -bool DVBDemodVideoPlayer::waitForPresentation(const AVFrame *frame, bool& late) +bool DTVVideoPlayer::waitForPresentation(const AVFrame *frame, bool& late) { late = false; @@ -1878,7 +1919,7 @@ bool DVBDemodVideoPlayer::waitForPresentation(const AVFrame *frame, bool& late) { late = wait < 0.0; m_clockValid = false; // Restart the clock from the next frame - PROFILER_ADD("DVBDemod video clock restart (count)", 0) + PROFILER_ADD("DTV video clock restart (count)", 0) QMutexLocker locker(&m_infoMutex); m_info.m_clockRestarts++; return true; @@ -1886,7 +1927,7 @@ bool DVBDemodVideoPlayer::waitForPresentation(const AVFrame *frame, bool& late) if (wait < 0.0) { - PROFILER_ADD("DVBDemod video frame late (by)", (qint64) (-wait * 1e9)) + PROFILER_ADD("DTV video frame late (by)", (qint64) (-wait * 1e9)) late = wait <= -maxLateness; // Without audio to keep to, frames late are the clock's fault (the stream came late, or slower than real time): @@ -1896,7 +1937,7 @@ bool DVBDemodVideoPlayer::waitForPresentation(const AVFrame *frame, bool& late) { m_clockPts = pts; m_clockTime = now + seconds(m_latency); - PROFILER_ADD("DVBDemod video clock restart (count)", 0) + PROFILER_ADD("DTV video clock restart (count)", 0) QMutexLocker locker(&m_infoMutex); m_info.m_clockRestarts++; return true; @@ -1923,7 +1964,7 @@ bool DVBDemodVideoPlayer::waitForPresentation(const AVFrame *frame, bool& late) if ((wait > maxWait) || (wait < -m_maxVideoLag)) { m_clockValid = false; - PROFILER_ADD("DVBDemod video clock restart (count)", 0) + PROFILER_ADD("DTV video clock restart (count)", 0) QMutexLocker locker(&m_infoMutex); m_info.m_clockRestarts++; return true; @@ -1959,7 +2000,7 @@ public: } // namespace // The GLVideoFrame type of a GPU frame the display might show (NV12 only), -1 if none -int DVBDemodVideoPlayer::gpuFrameType(const AVFrame *frame) const +int DTVVideoPlayer::gpuFrameType(const AVFrame *frame) const { const AVHWFramesContext *frames = framesContext(frame); @@ -1980,12 +2021,12 @@ int DVBDemodVideoPlayer::gpuFrameType(const AVFrame *frame) const // A converter from frames of the format to YUV 4:2:0 of the same size. As it doesn't scale, a 4:2:0 format (10 bits, // or semi-planar) needs nothing but the nearest sample, which is exact and fastest; 4:2:2's chroma is halved vertically, // by a bilinear filter. With threads where FFmpeg has them for sws_scale_frame() -SwsContext *DVBDemodVideoPlayer::createConverter(int width, int height, int format) +SwsContext *DTVVideoPlayer::createConverter(int width, int height, int format) { const AVPixFmtDescriptor *descriptor = av_pix_fmt_desc_get((AVPixelFormat) format); const bool is420 = descriptor && (descriptor->log2_chroma_w == 1) && (descriptor->log2_chroma_h == 1); const int flags = is420 ? SWS_POINT : SWS_FAST_BILINEAR; -#ifdef DVBDEMOD_SWS_THREADS +#ifdef DTV_SWS_THREADS SwsContext *ctx = sws_alloc_context(); if (ctx) @@ -2010,7 +2051,7 @@ SwsContext *DVBDemodVideoPlayer::createConverter(int width, int height, int form } // The frame as the display takes it: YUV 4:2:0 in memory (converted if in another format), or a GPU frame's handles -GLVideoFramePtr DVBDemodVideoPlayer::makeFrame(AVFrame *frame) +GLVideoFramePtr DTVVideoPlayer::makeFrame(AVFrame *frame) { std::shared_ptr out; const int format = frame->format; @@ -2140,7 +2181,7 @@ GLVideoFramePtr DVBDemodVideoPlayer::makeFrame(AVFrame *frame) } PROFILER_START() -#ifdef DVBDEMOD_SWS_THREADS +#ifdef DTV_SWS_THREADS // With the converter's threads if (sws_scale_frame(m_swsCtx, converted, frame) < 0) { @@ -2150,7 +2191,7 @@ GLVideoFramePtr DVBDemodVideoPlayer::makeFrame(AVFrame *frame) #else sws_scale(m_swsCtx, frame->data, frame->linesize, 0, frame->height, converted->data, converted->linesize); #endif - PROFILER_STOP("DVBDemod video format conversion") + PROFILER_STOP("DTV video format conversion") av_frame_copy_props(converted, frame); out = std::make_shared(converted); av_frame_free(&converted); @@ -2193,7 +2234,7 @@ GLVideoFramePtr DVBDemodVideoPlayer::makeFrame(AVFrame *frame) : frame->chroma_location == AVCHROMA_LOC_TOPLEFT ? GLVideoFrame::ChromaTopLeft : GLVideoFrame::ChromaLeft; out->m_fullRange = (frame->color_range == AVCOL_RANGE_JPEG) || (format == AV_PIX_FMT_YUVJ420P); -#ifdef DVBDEMOD_FRAME_FLAGS +#ifdef DTV_FRAME_FLAGS out->m_interlaced = (frame->flags & AV_FRAME_FLAG_INTERLACED) != 0; out->m_topFieldFirst = (frame->flags & AV_FRAME_FLAG_TOP_FIELD_FIRST) != 0; #else @@ -2205,12 +2246,12 @@ GLVideoFramePtr DVBDemodVideoPlayer::makeFrame(AVFrame *frame) return out; } -void DVBDemodVideoPlayer::renderFrame(AVFrame *frame) +void DTVVideoPlayer::renderFrame(AVFrame *frame) { PROFILER_START() bool late; bool show = waitForPresentation(frame, late); - PROFILER_STOP("DVBDemod video waiting to present") + PROFILER_STOP("DTV video waiting to present") updateShedding(late); if (!show) @@ -2231,7 +2272,7 @@ void DVBDemodVideoPlayer::renderFrame(AVFrame *frame) PROFILER_RESTART() GLVideoFramePtr out = makeFrame(frame); - PROFILER_STOP("DVBDemod video frame for display") + PROFILER_STOP("DTV video frame for display") if (!out) { return; @@ -2245,14 +2286,14 @@ void DVBDemodVideoPlayer::renderFrame(AVFrame *frame) m_frameCallback(out); } - PROFILER_STOP("DVBDemod video display callback") + PROFILER_STOP("DTV video display callback") #ifdef ENABLE_PROFILER // Even intervals between frames mean smooth video: the maximum shows the worst stall auto shown = std::chrono::steady_clock::now(); if (m_profileLastFrame.time_since_epoch().count() != 0) { - PROFILER_ADD("DVBDemod video interval between frames", (qint64) std::chrono::duration_cast(shown - m_profileLastFrame).count()) + PROFILER_ADD("DTV video interval between frames", (qint64) std::chrono::duration_cast(shown - m_profileLastFrame).count()) } m_profileLastFrame = shown; @@ -2296,10 +2337,10 @@ void DVBDemodVideoPlayer::renderFrame(AVFrame *frame) } // A resampler from a decoded frame's format to 16-bit samples at rate, stereo or mono -SwrContext *DVBDemodVideoPlayer::createResampler(const AVFrame *frame, int rate, bool mono) +SwrContext *DTVVideoPlayer::createResampler(const AVFrame *frame, int rate, bool mono) { SwrContext *swr = swr_alloc(); -#ifndef DVBDEMOD_CH_LAYOUT +#ifndef DTV_CH_LAYOUT av_opt_set_int(swr, "in_channel_layout", frame->channel_layout ? frame->channel_layout : av_get_default_channel_layout(frame->channels), 0); av_opt_set_int(swr, "out_channel_layout", mono ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO, 0); #else @@ -2320,12 +2361,12 @@ SwrContext *DVBDemodVideoPlayer::createResampler(const AVFrame *frame, int rate, return swr; } -SwrContext *DVBDemodVideoPlayer::resamplerFor(SwrContext *&swr, ResamplerInput& input, int rate, bool mono, bool damaged) +SwrContext *DTVVideoPlayer::resamplerFor(SwrContext *&swr, ResamplerInput& input, int rate, bool mono, bool damaged) { ResamplerInput frameInput; frameInput.m_format = m_frame->format; frameInput.m_rate = m_frame->sample_rate; -#ifndef DVBDEMOD_CH_LAYOUT +#ifndef DTV_CH_LAYOUT frameInput.m_channels = m_frame->channels; frameInput.m_layout = m_frame->channel_layout; #else @@ -2362,13 +2403,13 @@ SwrContext *DVBDemodVideoPlayer::resamplerFor(SwrContext *&swr, ResamplerInput& } // Resample to stereo at the audio device's rate, from the next frame's format -void DVBDemodVideoPlayer::setupResampler() +void DTVVideoPlayer::setupResampler() { swr_free(&m_swrCtx); m_swrRate = m_audioSampleRate; } -void DVBDemodVideoPlayer::decodeAudio() +void DTVVideoPlayer::decodeAudio() { if (m_audioCtx && (m_swrRate != m_audioSampleRate)) { setupResampler(); @@ -2482,7 +2523,7 @@ void DVBDemodVideoPlayer::decodeAudio() // The audio description is decoded as it arrives, and kept until the main audio of the same time is decoded. Its // codec isn't known until FFmpeg has seen some of its packets, which only come while a programme has a description -void DVBDemodVideoPlayer::decodeAudioDescription() +void DTVVideoPlayer::decodeAudioDescription() { if (!m_adCtx) { @@ -2498,7 +2539,7 @@ void DVBDemodVideoPlayer::decodeAudioDescription() return; } - qDebug() << "DVBDemodVideoPlayer::decodeAudioDescription:" << m_adCtx->codec->long_name; + qDebug() << "DTVVideoPlayer::decodeAudioDescription:" << m_adCtx->codec->long_name; } if (m_swrRate <= 0) { @@ -2571,7 +2612,7 @@ void DVBDemodVideoPlayer::decodeAudioDescription() // Applies the volume (gain) to a block of stereo samples, starting at pts seconds, mixing in the audio description // of the same time, if there is one, faded and panned as its descriptors say. The fade is ramped across the block. // If mute, the block fades out in a millisecond, as it may be corrupt; after a muted block, the audio fades in -void DVBDemodVideoPlayer::mixAudioDescription(int16_t *samples, int count, double pts, float gain, bool mute) +void DTVVideoPlayer::mixAudioDescription(int16_t *samples, int count, double pts, float gain, bool mute) { const bool active = (m_adStream >= 0) && !std::isnan(pts) && (m_adSwrRate == m_swrRate) && (std::chrono::steady_clock::now() - m_adTime < seconds(m_audioClockStale)); @@ -2671,14 +2712,14 @@ void DVBDemodVideoPlayer::mixAudioDescription(int16_t *samples, int count, doubl // A good packet's adaptation field's discontinuity_indicator: its continuity counter may jump (ISO/IEC 13818-1 // 2.4.3.5), so a jump there isn't packets lost. Not trusted in a packet with errors -bool DVBDemodVideoPlayer::signalledDiscontinuity(const uint8_t *p) +bool DTVVideoPlayer::signalledDiscontinuity(const uint8_t *p) { return !(p[1] & 0x80) && (p[3] & 0x20) && (p[4] > 0) && (p[5] & 0x80); } // Note the PES of the main audio, and which of their payload bytes came in TS packets with errors // (transport_error_indicator), or were lost (the continuity counter jumped, without a discontinuity signalled) -void DVBDemodVideoPlayer::trackAudioPES(const uint8_t *buf, int size) +void DTVVideoPlayer::trackAudioPES(const uint8_t *buf, int size) { if (m_audioPid < 0) { return; @@ -2761,7 +2802,7 @@ void DVBDemodVideoPlayer::trackAudioPES(const uint8_t *buf, int size) // Whether each video PES had TS packets with errors, or lost packets (pictures are a PES each in broadcasts), for // every PID found carrying video (a PES of stream id 0xE0 to 0xEF), from the stream's opening -void DVBDemodVideoPlayer::trackVideoPES(const uint8_t *buf, int size) +void DTVVideoPlayer::trackVideoPES(const uint8_t *buf, int size) { for (int i = 0; i + 188 <= size; i += 188) { @@ -2840,7 +2881,7 @@ void DVBDemodVideoPlayer::trackVideoPES(const uint8_t *buf, int size) // If a picture's PES (that with its PTS) was damaged. Its whole PES has been read by the time the demuxer returns it. // A picture whose PTS isn't found, when a PES whose header had errors (so whose PTS isn't known) came after the last // matched, is that one's: damaged (the parser's own flag would be on the next picture) -bool DVBDemodVideoPlayer::videoFrameDamaged(const AVPacket *packet) +bool DTVVideoPlayer::videoFrameDamaged(const AVPacket *packet) { auto track = m_videoTracks.find(m_videoPid); @@ -2878,7 +2919,7 @@ bool DVBDemodVideoPlayer::videoFrameDamaged(const AVPacket *packet) } // The TS as read, for what's parsed from it besides FFmpeg: whole packets -void DVBDemodVideoPlayer::parseTS(const uint8_t *buf, int size) +void DTVVideoPlayer::parseTS(const uint8_t *buf, int size) { const uint8_t *data = buf; int length = size; @@ -2900,7 +2941,7 @@ void DVBDemodVideoPlayer::parseTS(const uint8_t *buf, int size) // Whether the service's video (or its audio, if it has none) is scrambled, from its packets' transport_scrambling_control: // then it's encrypted (pay TV), can't be decoded, and the display says so, rather than that none is being received -void DVBDemodVideoPlayer::trackScrambling(const uint8_t *buf, int size) +void DTVVideoPlayer::trackScrambling(const uint8_t *buf, int size) { const int pid = m_videoPid >= 0 ? m_videoPid : m_audioPid; @@ -2929,7 +2970,7 @@ void DVBDemodVideoPlayer::trackScrambling(const uint8_t *buf, int size) } } -uint32_t DVBDemodVideoPlayer::writeAudio(const int16_t *samples, int nbSamples) +uint32_t DTVVideoPlayer::writeAudio(const int16_t *samples, int nbSamples) { // The oldest dropped rather than the newest lost: after an open, the audio FFmpeg read probing comes all at once, // and DVB-T2's in a frame's burst. Writing past the FIFO's end lost the newest, mid frame, and left the clock @@ -2959,7 +3000,7 @@ uint32_t DVBDemodVideoPlayer::writeAudio(const int16_t *samples, int nbSamples) // If an audio frame was in a damaged part of its PES, or of the next where it ran on into that (frames needn't be // aligned to PES), or ran on past a PES header with errors. If where it was can't be told, as when its PES header had // errors, it was damaged if the demuxer flagged it -bool DVBDemodVideoPlayer::audioFrameDamaged(const AVPacket *packet, bool flagged) +bool DTVVideoPlayer::audioFrameDamaged(const AVPacket *packet, bool flagged) { if (packet->pts == AV_NOPTS_VALUE) { return flagged; @@ -3051,7 +3092,7 @@ bool DVBDemodVideoPlayer::audioFrameDamaged(const AVPacket *packet, bool flagged // The fade of the main audio and pan of the description, from the PES headers of an MPEG audio description: the // AD_descriptor in the PES private data (ETSI TS 101 154 E.1). Read from the TS, as FFmpeg skips PES private data, // for any PID that has them -void DVBDemodVideoPlayer::parseADDescriptors(const uint8_t *buf, int size) +void DTVVideoPlayer::parseADDescriptors(const uint8_t *buf, int size) { for (int i = 0; i + 188 <= size; i += 188) { @@ -3105,7 +3146,7 @@ void DVBDemodVideoPlayer::parseADDescriptors(const uint8_t *buf, int size) } // All the bitmaps of a page in one image, on the decoder's display (720x576 unless a display definition says) -GLVideoSubtitlePtr DVBDemodVideoPlayer::makeSubtitle(const AVSubtitle& sub, int canvasWidth, int canvasHeight) +GLVideoSubtitlePtr DTVVideoPlayer::makeSubtitle(const AVSubtitle& sub, int canvasWidth, int canvasHeight) { int x0 = INT_MAX, y0 = INT_MAX, x1 = INT_MIN, y1 = INT_MIN; @@ -3166,7 +3207,7 @@ GLVideoSubtitlePtr DVBDemodVideoPlayer::makeSubtitle(const AVSubtitle& sub, int } // A page replaces the last, until its time out. An empty page clears the screen -void DVBDemodVideoPlayer::decodeSubtitle() +void DTVVideoPlayer::decodeSubtitle() { AVSubtitle sub; int got = 0; @@ -3195,8 +3236,205 @@ void DVBDemodVideoPlayer::decodeSubtitle() m_info.m_subtitlePages++; } +// FFmpeg's CEA-608 decoder, in real time mode (each change to the screen given as it's made, as roll-up captions are +// shown): a page shown from the frame's time until the next. Only CEA-608 (in CEA-708's cc_data, as US broadcasters +// send both): CEA-708's own services aren't decoded +void DTVVideoPlayer::decodeCaptions(const AVFrameSideData *captions, int64_t timestamp) +{ + if (!m_captionCtx) + { + const AVCodec *codec = avcodec_find_decoder(AV_CODEC_ID_EIA_608); + + if (!codec) { + return; + } + + m_captionCtx = avcodec_alloc_context3(codec); + m_captionCtx->pkt_timebase = AVRational{m_videoTimeBaseNum, m_videoTimeBaseDen}; + AVDictionary *options = nullptr; + av_dict_set(&options, "real_time", "1", 0); + const int opened = avcodec_open2(m_captionCtx, codec, &options); + av_dict_free(&options); + + if (opened < 0) + { + qWarning("DTVVideoPlayer::decodeCaptions: FFmpeg's CEA-608 decoder couldn't be opened"); + avcodec_free_context(&m_captionCtx); + m_captionsEnabled = false; + return; + } + } + + AVPacket *packet = av_packet_alloc(); + + if (!packet || (av_new_packet(packet, (int) captions->size) < 0)) + { + av_packet_free(&packet); + return; + } + + memcpy(packet->data, captions->data, captions->size); + packet->pts = timestamp; + AVSubtitle sub; + int got = 0; + + if ((avcodec_decode_subtitle2(m_captionCtx, &sub, &got, packet) >= 0) && got) + { + QString text; + + for (unsigned int i = 0; i < sub.num_rects; i++) + { + if ((sub.rects[i]->type == SUBTITLE_ASS) && sub.rects[i]->ass) { + text += assText(sub.rects[i]->ass); + } + } + + SubtitlePage page; + page.m_start = timestamp * av_q2d(AVRational{m_videoTimeBaseNum, m_videoTimeBaseDen}); + page.m_end = INFINITY; + page.m_subtitle = text.trimmed().isEmpty() ? nullptr : makeCaptions(text); + + { + std::lock_guard lock(m_subtitleMutex); + m_subtitlePages.push_back(page); + + if (m_subtitlePages.size() > 100) { + m_subtitlePages.pop_front(); + } + } + + avsubtitle_free(&sub); + QMutexLocker locker(&m_infoMutex); + m_info.m_subtitlePages++; + } + + av_packet_free(&packet); +} + +void DTVVideoPlayer::closeCaptions() +{ + avcodec_free_context(&m_captionCtx); +} + +// "ReadOrder,Layer,Style,Name,MarginL,MarginR,MarginV,Effect,Text": the text, without override codes ({...}), its +// line breaks (\N) as newlines and hard spaces (\h) as spaces +QString DTVVideoPlayer::assText(const char *ass) +{ + QString event = QString::fromUtf8(ass); + int commas = 0, start = 0; + + for (int i = 0; (i < event.size()) && (commas < 8); i++) + { + if (event[i] == ',') + { + commas++; + start = i + 1; + } + } + + QString text = commas == 8 ? event.mid(start) : event; + QString out; + bool code = false; + + for (int i = 0; i < text.size(); i++) + { + const QChar c = text[i]; + + if (c == '{') { + code = true; + } else if (c == '}') { + code = false; + } else if (code) { + continue; + } else if ((c == '\\') && (i + 1 < text.size()) && ((text[i + 1] == 'N') || (text[i + 1] == 'n'))) { + out += '\n'; + i++; + } else if ((c == '\\') && (i + 1 < text.size()) && (text[i + 1] == 'h')) { + out += ' '; + i++; + } else { + out += c; + } + } + + return out; +} + +// As TVs show CEA-608: white monospaced text on black boxes, the lines left aligned in a block centred at the bottom +// of a 4:3 safe area (the decoder's rows and columns aren't kept, so roll-up and pop-on captions are both there) +GLVideoSubtitlePtr DTVVideoPlayer::makeCaptions(const QString& text) +{ + static constexpr int canvasWidth = 640; + static constexpr int canvasHeight = 480; + QStringList lines = text.split('\n', Qt::SkipEmptyParts); + + for (QString& line : lines) { + line = line.trimmed(); + } + + lines.removeAll(QString()); + + if (lines.isEmpty()) { + return nullptr; + } + + // Fonts need a GUI application: without one (as in a test), just the boxes, at a monospaced font's size + const bool fonts = qobject_cast(QCoreApplication::instance()) != nullptr; + QFont font("Consolas"); + font.setStyleHint(QFont::Monospace); + font.setPixelSize(22); + auto lineWidth = [&](const QString& line) { + return (fonts ? QFontMetrics(font).horizontalAdvance(line) : 12 * (int) line.size()) + 16; + }; + const int lineHeight = (fonts ? QFontMetrics(font).height() : 26) + 4; + int width = 0; + + for (const QString& line : lines) { + width = std::max(width, lineWidth(line)); + } + + width = std::min(width, canvasWidth); + const int height = lineHeight * (int) lines.size(); + QImage image(width, height, QImage::Format_RGBA8888_Premultiplied); + image.fill(Qt::transparent); + QPainter painter(&image); + + if (fonts) { + painter.setFont(font); + } + + for (int i = 0; i < (int) lines.size(); i++) + { + const int w = std::min(width, lineWidth(lines[i])); + const QRect box(0, i * lineHeight, w, lineHeight); // Left aligned, as the rows of a caption are + painter.fillRect(box, QColor(0, 0, 0, 220)); + + if (fonts) + { + painter.setPen(Qt::white); + painter.drawText(box, Qt::AlignCenter, lines[i]); + } + } + + painter.end(); + auto subtitle = std::make_shared(); + subtitle->m_canvasWidth = canvasWidth; + subtitle->m_canvasHeight = canvasHeight; + subtitle->m_width = width; + subtitle->m_height = height; + subtitle->m_x = (canvasWidth - width) / 2; + subtitle->m_y = canvasHeight - 32 - height; + subtitle->m_rgba.resize((size_t) width * height * 4); + + for (int y = 0; y < height; y++) { + memcpy(subtitle->m_rgba.data() + (size_t) y * width * 4, image.constScanLine(y), (size_t) width * 4); + } + + return subtitle; +} + // The subtitle due with a video frame (pts seconds), in the video thread -GLVideoSubtitlePtr DVBDemodVideoPlayer::currentSubtitle(double pts) +GLVideoSubtitlePtr DTVVideoPlayer::currentSubtitle(double pts) { std::lock_guard lock(m_subtitleMutex); @@ -3222,7 +3460,7 @@ GLVideoSubtitlePtr DVBDemodVideoPlayer::currentSubtitle(double pts) return m_subtitleShown.m_subtitle; } -void DVBDemodVideoPlayer::closeTrackDecoders() +void DTVVideoPlayer::closeTrackDecoders() { avcodec_free_context(&m_audioCtx); avcodec_free_context(&m_adCtx); @@ -3232,6 +3470,7 @@ void DVBDemodVideoPlayer::closeTrackDecoders() m_audioStream = -1; m_adStream = -1; m_subtitleStream = -1; + m_captionsEnabled = false; m_adPid = -1; m_adSamples.clear(); m_adControl = ADControl{0.0, 0, 0}; @@ -3260,7 +3499,7 @@ void DVBDemodVideoPlayer::closeTrackDecoders() } // The track a stream is, if it's audio or subtitles that can be shown -bool DVBDemodVideoPlayer::getTrack(const AVStream *stream, DVBDemodVideoPlayer::Track& track) +bool DTVVideoPlayer::getTrack(const AVStream *stream, DTVVideoPlayer::Track& track) { const int disposition = stream->disposition; const AVMediaType type = stream->codecpar->codec_type; @@ -3274,8 +3513,8 @@ bool DVBDemodVideoPlayer::getTrack(const AVStream *stream, DVBDemodVideoPlayer:: return false; // Teletext, which isn't used for subtitles in the UK } - track.m_type = (disposition & AV_DISPOSITION_HEARING_IMPAIRED) ? DVBDemodVideoPlayer::Track::SubtitlesHardOfHearing - : DVBDemodVideoPlayer::Track::Subtitles; + track.m_type = (disposition & AV_DISPOSITION_HEARING_IMPAIRED) ? DTVVideoPlayer::Track::SubtitlesHardOfHearing + : DTVVideoPlayer::Track::Subtitles; return true; } @@ -3290,19 +3529,19 @@ bool DVBDemodVideoPlayer::getTrack(const AVStream *stream, DVBDemodVideoPlayer:: } if (description) { - track.m_type = (disposition & AV_DISPOSITION_DEPENDENT) ? DVBDemodVideoPlayer::Track::AudioDescription - : DVBDemodVideoPlayer::Track::AudioDescriptionMixed; + track.m_type = (disposition & AV_DISPOSITION_DEPENDENT) ? DTVVideoPlayer::Track::AudioDescription + : DTVVideoPlayer::Track::AudioDescriptionMixed; } else if (disposition & AV_DISPOSITION_HEARING_IMPAIRED) { - track.m_type = DVBDemodVideoPlayer::Track::CleanAudio; + track.m_type = DTVVideoPlayer::Track::CleanAudio; } else { - track.m_type = DVBDemodVideoPlayer::Track::Main; + track.m_type = DTVVideoPlayer::Track::Main; } return true; } // The first track of one of the types, in the language if there is one -int DVBDemodVideoPlayer::findTrack(const QList& tracks, std::initializer_list types, +int DTVVideoPlayer::findTrack(const QList& tracks, std::initializer_list types, const QString& language) { for (int pass = 0; pass < 2; pass++) @@ -3320,7 +3559,7 @@ int DVBDemodVideoPlayer::findTrack(const QList& trac } // The first track of the type in the language (any language if it's empty), -1 if none -int DVBDemodVideoPlayer::findTrackInLanguage(const QList& tracks, DVBDemodVideoPlayer::Track::Type type, +int DTVVideoPlayer::findTrackInLanguage(const QList& tracks, DTVVideoPlayer::Track::Type type, const QString& language) { for (int i = 0; i < tracks.size(); i++) @@ -3337,7 +3576,7 @@ int DVBDemodVideoPlayer::findTrackInLanguage(const QList= 0) + if ((subtitle >= 0) && (subtitleStreams[subtitle] < 0)) + { + m_captionsEnabled = true; + tracks.m_subtitlePid = m_captionPid; + } + else if (subtitle >= 0) { m_subtitleStream = subtitleStreams[subtitle]; m_subtitleCtx = openDecoder(m_formatCtx->streams[m_subtitleStream]); tracks.m_subtitlePid = tracks.m_subtitles[subtitle].m_pid; } - qDebug() << "DVBDemodVideoPlayer::selectTracks:" << tracks.m_audio.size() << "audio tracks," << tracks.m_subtitles.size() + qDebug() << "DTVVideoPlayer::selectTracks:" << tracks.m_audio.size() << "audio tracks," << tracks.m_subtitles.size() << "subtitle tracks. Playing audio" << tracks.m_audioPid << "description" << tracks.m_adPid << "subtitles" << tracks.m_subtitlePid; { QMutexLocker locker(&m_infoMutex); m_info.m_audioCodec = m_audioCtx ? QString(m_audioCtx->codec->long_name) : QString(); m_info.m_audioDescription = m_adStream >= 0; - m_info.m_subtitles = m_subtitleCtx != nullptr; + m_info.m_subtitles = (m_subtitleCtx != nullptr) || m_captionsEnabled; } + m_tracks = tracks; emit tracksChanged(tracks); } + +// Captions found in the video after the tracks were chosen: listed, and played if preferred (and no subtitles are) +void DTVVideoPlayer::addCaptionTrack() +{ + m_captionsListed = true; + m_tracks.m_subtitles.append(Track{m_captionPid, QString(), Track::Subtitles}); + QString audioLanguage, subtitleLanguage; + Track::Type audioType, subtitleType; + bool subtitles; + + { + QMutexLocker locker(&m_tracksMutex); + audioLanguage = m_audioLanguage; + audioType = m_audioType; + subtitles = m_subtitles; + subtitleLanguage = m_subtitleLanguage; + subtitleType = m_subtitleType; + } + + int audio, description, subtitle; + chooseTracks(m_tracks, audioLanguage, audioType, subtitles, subtitleLanguage, subtitleType, audio, description, subtitle); + + if ((subtitle >= 0) && (m_tracks.m_subtitles[subtitle].m_pid == m_captionPid) && !m_subtitleCtx) + { + m_captionsEnabled = true; + m_tracks.m_subtitlePid = m_captionPid; + QMutexLocker locker(&m_infoMutex); + m_info.m_subtitles = true; + } + + emit tracksChanged(m_tracks); +} diff --git a/plugins/channelrx/demoddvb/dvbdemodvideoplayer.h b/sdrgui/dtv/dtvvideoplayer.h similarity index 92% rename from plugins/channelrx/demoddvb/dvbdemodvideoplayer.h rename to sdrgui/dtv/dtvvideoplayer.h index 6eeb7057e..9947e3700 100644 --- a/plugins/channelrx/demoddvb/dvbdemodvideoplayer.h +++ b/sdrgui/dtv/dtvvideoplayer.h @@ -16,8 +16,8 @@ // along with this program. If not, see . // /////////////////////////////////////////////////////////////////////////////////// -#ifndef INCLUDE_DVBDEMODVIDEOPLAYER_H -#define INCLUDE_DVBDEMODVIDEOPLAYER_H +#ifndef INCLUDE_DTVVIDEOPLAYER_H +#define INCLUDE_DTVVIDEOPLAYER_H #include #include @@ -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; // 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: 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: typedef std::function 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: Info getInfo(); signals: - void servicesChanged(const QList& services); + void servicesChanged(const QList& 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: 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& tracks, std::initializer_list types, const QString& language); static int findTrackInLanguage(const QList& tracks, Track::Type type, const QString& language); @@ -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: 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: int m_selectedRequest; //!< m_requestedService when the current service was selected QList 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: std::deque 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 m_captionsSeen{false}; //!< Found in the video of the service, since it was selected + bool m_captionsListed = false; //!< In m_tracks + std::atomic 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: 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 diff --git a/sdrgui/gui/glvideorenderer.cpp b/sdrgui/gui/glvideorenderer.cpp index 44875dba1..873f6fc77 100644 --- a/sdrgui/gui/glvideorenderer.cpp +++ b/sdrgui/gui/glvideorenderer.cpp @@ -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; diff --git a/sdrgui/gui/glvideorenderer.h b/sdrgui/gui/glvideorenderer.h index 4618e0eac..afb5a39ad 100644 --- a/sdrgui/gui/glvideorenderer.h +++ b/sdrgui/gui/glvideorenderer.h @@ -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 diff --git a/sdrgui/gui/glvideowidget.cpp b/sdrgui/gui/glvideowidget.cpp index d1dcc40a8..cd2162093 100644 --- a/sdrgui/gui/glvideowidget.cpp +++ b/sdrgui/gui/glvideowidget.cpp @@ -17,6 +17,7 @@ /////////////////////////////////////////////////////////////////////////////////// #include +#include #include #include @@ -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() 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()) diff --git a/sdrgui/gui/glvideowidget.h b/sdrgui/gui/glvideowidget.h index f3d63ffee..3251b67ea 100644 --- a/sdrgui/gui/glvideowidget.h +++ b/sdrgui/gui/glvideowidget.h @@ -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: QImage m_guide; bool m_keepAspect; bool m_deinterlace; + QRectF m_videoArea; QSize m_frameSize; }; diff --git a/swagger/sdrangel/api/swagger/include/DVBDemod.yaml b/swagger/sdrangel/api/swagger/include/DVBDemod.yaml index 956a1b753..7c0c178e6 100644 --- a/swagger/sdrangel/api/swagger/include/DVBDemod.yaml +++ b/swagger/sdrangel/api/swagger/include/DVBDemod.yaml @@ -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: 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: 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: diff --git a/swagger/sdrangel/code/qt5/client/SWGDVBDemodApp.cpp b/swagger/sdrangel/code/qt5/client/SWGDVBDemodApp.cpp new file mode 100644 index 000000000..489777f2d --- /dev/null +++ b/swagger/sdrangel/code/qt5/client/SWGDVBDemodApp.cpp @@ -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 +#include +#include +#include + +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; +} +} + diff --git a/swagger/sdrangel/code/qt5/client/SWGDVBDemodApp.h b/swagger/sdrangel/code/qt5/client/SWGDVBDemodApp.h new file mode 100644 index 000000000..5ba33500c --- /dev/null +++ b/swagger/sdrangel/code/qt5/client/SWGDVBDemodApp.h @@ -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 + + +#include + +#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_ */ diff --git a/swagger/sdrangel/code/qt5/client/SWGDVBDemodCarousel.cpp b/swagger/sdrangel/code/qt5/client/SWGDVBDemodCarousel.cpp new file mode 100644 index 000000000..13a00fc6a --- /dev/null +++ b/swagger/sdrangel/code/qt5/client/SWGDVBDemodCarousel.cpp @@ -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 +#include +#include +#include + +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; +} +} + diff --git a/swagger/sdrangel/code/qt5/client/SWGDVBDemodCarousel.h b/swagger/sdrangel/code/qt5/client/SWGDVBDemodCarousel.h new file mode 100644 index 000000000..a627e32a8 --- /dev/null +++ b/swagger/sdrangel/code/qt5/client/SWGDVBDemodCarousel.h @@ -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 + + +#include + +#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_ */ diff --git a/swagger/sdrangel/code/qt5/client/SWGDVBDemodReport.cpp b/swagger/sdrangel/code/qt5/client/SWGDVBDemodReport.cpp index e11a18ab5..10ffce15b 100644 --- a/swagger/sdrangel/code/qt5/client/SWGDVBDemodReport.cpp +++ b/swagger/sdrangel/code/qt5/client/SWGDVBDemodReport.cpp @@ -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() { 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() { 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() { 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() { m_epg_schedule_network_id_isSet = false; epg_schedule = new QList(); m_epg_schedule_isSet = false; + interactive_apps = new QList(); + m_interactive_apps_isSet = false; + carousels = new QList(); + m_carousels_isSet = false; recording = 0; m_recording_isSet = false; recording_file = new QString(""); @@ -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() { + if(search_text != nullptr) { + delete search_text; + } + + if(pilot_pattern != nullptr) { @@ -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) { ::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) { ::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) { ::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() { 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() { if(epg_schedule && epg_schedule->size() > 0){ toJsonArray((QList*)epg_schedule, obj, "epgSchedule", "SWGDVBDemodEPGEvent"); } + if(interactive_apps && interactive_apps->size() > 0){ + toJsonArray((QList*)interactive_apps, obj, "interactiveApps", "SWGDVBDemodApp"); + } + if(carousels && carousels->size() > 0){ + toJsonArray((QList*)carousels, obj, "carousels", "SWGDVBDemodCarousel"); + } if(m_recording_isSet){ obj->insert("recording", QJsonValue(recording)); } @@ -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) { 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* epg_schedule) { this->m_epg_schedule_isSet = true; } +QList* +SWGDVBDemodReport::getInteractiveApps() { + return interactive_apps; +} +void +SWGDVBDemodReport::setInteractiveApps(QList* interactive_apps) { + this->interactive_apps = interactive_apps; + this->m_interactive_apps_isSet = true; +} + +QList* +SWGDVBDemodReport::getCarousels() { + return carousels; +} +void +SWGDVBDemodReport::setCarousels(QList* carousels) { + this->carousels = carousels; + this->m_carousels_isSet = true; +} + qint32 SWGDVBDemodReport::getRecording() { return recording; @@ -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) { 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) { this->m_reacquisitions_isSet = true; } + bool SWGDVBDemodReport::isSet(){ bool isObjectUpdated = false; @@ -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(){ 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(){ 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; } diff --git a/swagger/sdrangel/code/qt5/client/SWGDVBDemodReport.h b/swagger/sdrangel/code/qt5/client/SWGDVBDemodReport.h index 8ff3606a1..3c695d348 100644 --- a/swagger/sdrangel/code/qt5/client/SWGDVBDemodReport.h +++ b/swagger/sdrangel/code/qt5/client/SWGDVBDemodReport.h @@ -22,6 +22,8 @@ #include +#include "SWGDVBDemodApp.h" +#include "SWGDVBDemodCarousel.h" #include "SWGDVBDemodEPGEvent.h" #include "SWGDVBDemodEPGService.h" #include @@ -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: QList* getEpgSchedule(); void setEpgSchedule(QList* epg_schedule); + QList* getInteractiveApps(); + void setInteractiveApps(QList* interactive_apps); + + QList* getCarousels(); + void setCarousels(QList* carousels); + qint32 getRecording(); void setRecording(qint32 recording); @@ -198,7 +209,6 @@ public: qint32 getScheduledRecordings(); void setScheduledRecordings(qint32 scheduled_recordings); - qint32 getSymbolRate(); void setSymbolRate(qint32 symbol_rate); @@ -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: qint64 getReacquisitions(); void setReacquisitions(qint64 reacquisitions); + virtual bool isSet() override; 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: QList* epg_schedule; bool m_epg_schedule_isSet; + QList* interactive_apps; + bool m_interactive_apps_isSet; + + QList* carousels; + bool m_carousels_isSet; + qint32 recording; bool m_recording_isSet; @@ -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; diff --git a/swagger/sdrangel/code/qt5/client/SWGDVBDemodSettings.cpp b/swagger/sdrangel/code/qt5/client/SWGDVBDemodSettings.cpp index 27753ff03..ce6b2b707 100644 --- a/swagger/sdrangel/code/qt5/client/SWGDVBDemodSettings.cpp +++ b/swagger/sdrangel/code/qt5/client/SWGDVBDemodSettings.cpp @@ -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() { 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() { 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() { 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() { 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() { 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() { 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() { 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() { + + + + + + + + + if(udp_address != nullptr) { delete udp_address; } @@ -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) { ::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) { ::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) { ::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) { ::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() { 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() { 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() { 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() { 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) { } 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) { 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) { 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) { } -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(){ 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(){ 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(){ 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(){ 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; } diff --git a/swagger/sdrangel/code/qt5/client/SWGDVBDemodSettings.h b/swagger/sdrangel/code/qt5/client/SWGDVBDemodSettings.h index ec8d6cf72..56a965f43 100644 --- a/swagger/sdrangel/code/qt5/client/SWGDVBDemodSettings.h +++ b/swagger/sdrangel/code/qt5/client/SWGDVBDemodSettings.h @@ -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: qint32 getDeinterlace(); void setDeinterlace(qint32 deinterlace); + qint32 getHbbtv(); + void setHbbtv(qint32 hbbtv); + qint32 getAvOffset(); void setAvOffset(qint32 av_offset); @@ -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: 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: 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: 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: 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: 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; - }; } diff --git a/swagger/sdrangel/code/qt5/client/SWGModelFactory.h b/swagger/sdrangel/code/qt5/client/SWGModelFactory.h index c7d28d421..8996aa82f 100644 --- a/swagger/sdrangel/code/qt5/client/SWGModelFactory.h +++ b/swagger/sdrangel/code/qt5/client/SWGModelFactory.h @@ -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 { 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();