diff options
115 files changed, 26881 insertions, 1181 deletions
@@ -115,7 +115,11 @@ ui_*.h *.qmlc *.jsc Makefile.in* -*build-* +# Qt Creator shadow build directories. The trailing slash restricts this to +# directories and the missing leading * makes it an anchor rather than a +# substring - as plain *build-* it also swallowed any file with "build-" +# anywhere in its name, deb_packaging/build-*.sh among them. +build-*/ # Qt unit tests target_wrapper.* diff --git a/Makefile.am b/Makefile.am index be01e97..ee18901 100644 --- a/Makefile.am +++ b/Makefile.am @@ -2,16 +2,93 @@ bin_PROGRAMS = CLEANFILES = +# Everything that goes into the tarball but is not a source of a program or an +# installed data file. The packaging directories are listed file by file on +# purpose: naming the directory itself makes automake copy whatever happens to +# be in it at "make dist" time, which for windows/ would mean the multi-gigabyte +# mxe/ build tree, and for the others the generated files (configure output, +# build leftovers). The lists below are the files under version control, so a +# tarball built from a dirty work tree is the same as one built from a fresh +# checkout. Files generated by configure - windows/*.exe.manifest and the +# windows/installer*.nsi - are deliberately absent; their *.in templates are +# here instead. EXTRA_DIST = iniparser/LICENSE \ COPYING \ README \ - debian \ - gentoo \ - windows \ - apple \ - pica-client/icons + debian/changelog \ + debian/control \ + debian/copyright \ + debian/docs \ + debian/pica-client.install \ + debian/pica-client.menu \ + debian/pica-client.postinst \ + debian/pica-client.postrm \ + debian/pica-client.preinst \ + debian/pica-client.prerm \ + debian/pica-node.default \ + debian/pica-node.dirs \ + debian/pica-node.init \ + debian/pica-node.install \ + debian/pica-node.postinst \ + debian/pica-node.postrm \ + debian/pica-node.preinst \ + debian/pica-node.prerm \ + debian/rules \ + debian/source/format \ + gentoo/gentoo_initscript \ + gentoo/pica-pica-9999.ebuild \ + windows/cross_build_mxe.sh \ + windows/installer32.nsi.in \ + windows/installer64.nsi.in \ + windows/mxe_ffmpeg_strip_excess_deps.patch \ + windows/mxe_qtbase_strip_excess_deps.patch \ + windows/pica-client.exe.manifest.in \ + windows/pica-client.nsi \ + windows/pica-client.rc \ + windows/pica-node.exe.manifest.in \ + windows/pica-node.nsi \ + windows/pica-node.rc \ + windows/picapica.ico \ + apple/Info.plist \ + apple/picapica.icns \ + pica-client/icons/icon_16x16.png \ + pica-client/icons/icon_32x32.png \ + pica-client/icons/icon_48x48.png ##################################### +# Windows resources. Each program gets the program icon and the application +# manifest compiled into a linkable object by windres, which is then added to +# its LDADD below. Only the Windows build has a use for these, but the suffix +# itself is declared unconditionally so that make knows .rc is a source suffix +# and not the name of a file. +SUFFIXES = .rc + +if TARGET_WINDOWS + +# The icon lives in the source directory while the manifest is generated by +# configure into the build directory, so both have to be on the include path +# windres resolves the file names in the resource script against. The version +# is handed to the VERSIONINFO resource on the command line instead of the +# resource script being generated, in the two spellings the numeric and the +# string fields need. The quotes around the string one are escaped twice on +# purpose: windres passes its own command line to the preprocessor through a +# shell, so one round of quoting is eaten there and one here. +.rc.o: + $(WINDRES) -I $(srcdir)/windows -I windows \ + -DPICA_WINDOWS_VERSION_COMMAS=$(PICA_WINDOWS_VERSION_COMMAS) \ + -DPICA_WINDOWS_VERSION_STRING=\\\"$(VERSION)\\\" \ + -i $< -o $@ + +windows/pica-node.o: windows/pica-node.rc windows/picapica.ico \ + windows/pica-node.exe.manifest + +windows/pica-client.o: windows/pica-client.rc windows/picapica.ico \ + windows/pica-client.exe.manifest + +CLEANFILES += windows/pica-node.o windows/pica-client.o + +endif +##################################### if PICA_NODE bin_PROGRAMS += pica-node @@ -30,6 +107,11 @@ dist_man_MANS = pica-node.8 pica-node.conf.5 pica_node_CPPFLAGS = -DPICA_INSTALLPREFIX=\"$(prefix)\" -DPICA_SYSCONFDIR=\"$(sysconfdir)\" -DPICA_LOCALSTATEDIR=\"$(localstatedir)\" pica_node_LDADD = $(PICA_NODE_LIBS) + +if TARGET_WINDOWS +pica_node_LDADD += windows/pica-node.o +endif + pkglocalstatedir = $(localstatedir)/pica-node dist_pkglocalstate_DATA = nodelist.db @@ -61,6 +143,10 @@ pica-client/askpassword.cpp \ pica-client/askpassword.h \ pica-client/chatwindow.cpp \ pica-client/chatwindow.h \ +pica-client/callwindow.cpp \ +pica-client/callwindow.h \ +pica-client/audiovideocallcontroller.cpp \ +pica-client/audiovideocallcontroller.h \ pica-client/contactlistwidget.cpp \ pica-client/contactlistwidget.h \ pica-client/contacts.cpp \ @@ -74,8 +160,8 @@ pica-client/msguirouter.cpp \ pica-client/msguirouter.h \ pica-client/nodes.cpp \ pica-client/nodes.h \ -pica-client/openssltool.cpp \ -pica-client/openssltool.h \ +pica-client/openssllib.cpp \ +pica-client/openssllib.h \ pica-client/picaactioncenter.cpp \ pica-client/picaactioncenter.h \ pica-client/pica-client.pro \ @@ -83,6 +169,9 @@ pica-client/picasystray.cpp \ pica-client/picasystray.h \ pica-client/skynet.cpp \ pica-client/skynet.h \ +pica-client/directlistener.cpp \ +pica-client/directlistener.h \ +pica-client/directc2csettings.h \ pica-client/history.h \ pica-client/history.cpp \ pica-client/dhparam.h \ @@ -91,8 +180,28 @@ pica-client/filetransfercontroller.cpp \ pica-client/filetransfercontroller.h \ pica-client/sound.cpp \ pica-client/sound.h \ +pica-client/toneplayer/toneplayer.cpp \ +pica-client/toneplayer/toneplayer.h \ pica-client/settings.cpp \ pica-client/settings.h \ +pica-client/callsettings.cpp \ +pica-client/callsettings.h \ +pica-client/mediadevice.cpp \ +pica-client/mediadevice.h \ +pica-client/audiodevice.cpp \ +pica-client/audiodevice.h \ +pica-client/audioring.h \ +pica-client/echocanceller.cpp \ +pica-client/echocanceller.h \ +pica-client/nativeaudio.cpp \ +pica-client/nativeaudio.h \ +pica-client/nativeaudio_wasapi.cpp \ +pica-client/nativeaudio_coreaudio.cpp \ +pica-client/videodevice.cpp \ +pica-client/videodevice.h \ +pica-client/videoscaler.cpp \ +pica-client/videoscaler.h \ +pica-client/videodshow.cpp \ \ pica-client/dialogs/addaccountdialog.cpp \ pica-client/dialogs/addaccountdialog.h \ @@ -111,7 +220,9 @@ pica-client/dialogs/settingsdialog.h \ pica-client/dialogs/nodesdialog.cpp \ pica-client/dialogs/nodesdialog.h \ PICA_client.c \ +PICA_media.c \ PICA_client.h \ +PICA_media.h \ PICA_msgproc.c \ PICA_msgproc.h \ PICA_common.h PICA_proto.h \ @@ -125,28 +236,44 @@ moc_accountswindow.cpp \ moc_addaccountdialog.cpp \ moc_askpassword.cpp \ moc_chatwindow.cpp \ +moc_callwindow.cpp \ moc_contactlistwidget.cpp \ moc_forgedcertdialog.cpp \ moc_mainwindow.cpp \ moc_msguirouter.cpp \ +moc_openssllib.cpp \ moc_picaactioncenter.cpp \ moc_picasystray.cpp \ moc_registeraccountdialog.cpp \ moc_filetransferdialog.cpp \ +moc_audiovideocallcontroller.cpp \ moc_skynet.cpp \ +moc_directlistener.cpp \ moc_settingsdialog.cpp \ moc_viewcertdialog.cpp \ moc_showpicaiddialog.cpp \ moc_dhparam.cpp \ moc_filetransfercontroller.cpp \ moc_nodesdialog.cpp \ +moc_toneplayer.cpp \ +moc_audiodevice.cpp \ +moc_videodevice.cpp \ ui_mainwindow.h +# moc runs its own preprocessor and sees none of the compiler's defines, so +# any define that a header's signals or slots are conditional on has to be +# repeated here - otherwise moc skips those declarations and the signals end +# up declared but never generated, failing at link time. +MOCFLAGS = + moc_%.cpp: pica-client/%.h - $(MOC) $< -o $@ + $(MOC) $(MOCFLAGS) $< -o $@ moc_%.cpp: pica-client/dialogs/%.h - $(MOC) $< -o $@ + $(MOC) $(MOCFLAGS) $< -o $@ + +moc_%.cpp: pica-client/toneplayer/%.h + $(MOC) $(MOCFLAGS) $< -o $@ pica-client/mainwindow.cpp: ui_mainwindow.h @@ -156,9 +283,55 @@ pica-client/mainwindow.cpp: ui_mainwindow.h ui_%.h: pica-client/%.ui $(UIC) $< -o $@ - -pica_client_pica_client_CPPFLAGS = -DPICA_INSTALLPREFIX=\"$(prefix)\" $(QT_DEPENDENCIES_CFLAGS) -pica_client_pica_client_LDADD = $(QT_DEPENDENCIES_LIBS) + +pica_client_pica_client_CPPFLAGS = -DPICA_INSTALLPREFIX=\"$(prefix)\" $(QT_DEPENDENCIES_CFLAGS) $(FFMPEG_CFLAGS) $(PLATFORM_DEPS_CFLAGS) $(WEBRTC_AUDIO_PROCESSING_CFLAGS) +pica_client_pica_client_LDADD = $(QT_DEPENDENCIES_LIBS) $(FFMPEG_LIBS) $(PLATFORM_DEPS_LIBS) $(WEBRTC_AUDIO_PROCESSING_LIBS) + +if TARGET_WINDOWS +pica_client_pica_client_LDADD += windows/pica-client.o +endif + +# Listing PulseAudio sources and sinks in the settings dialog. The two +# native backend sources above are compiled unconditionally and are empty +# preprocessor-wise on the platforms they are not for, but libpulse is a +# real dependency and only linked when configure found it. +if PICA_PULSE +pica_client_pica_client_CPPFLAGS += $(PULSE_CFLAGS) +pica_client_pica_client_LDADD += $(PULSE_LIBS) +MOCFLAGS += -DHAVE_LIBPULSE +endif + +# VAAPI accelerated encoding, decoding and rendering. Everything below is left +# out of the build entirely when configure did not find libva/EGL or was told +# not to look - the code itself is additionally guarded by #ifdef HAVE_VAAPI. +if PICA_VAAPI +pica_client_pica_client_SOURCES += \ +pica-client/vaapi.cpp \ +pica-client/vaapi.h \ +pica-client/vaapivideowidget.cpp \ +pica-client/vaapivideowidget.h + +nodist_pica_client_pica_client_SOURCES += moc_vaapivideowidget.cpp + +pica_client_pica_client_CPPFLAGS += $(VAAPI_CFLAGS) +pica_client_pica_client_LDADD += $(VAAPI_LIBS) -lGL +MOCFLAGS += -DHAVE_VAAPI +endif + +# Drawing a decoded surface in an X11 session, where Qt's OpenGL contexts come +# from GLX and cannot import DMA-BUF handles: the driver draws the surface +# straight onto the widget's X window instead. +if PICA_VAAPI_X11 +pica_client_pica_client_SOURCES += \ +pica-client/vaapix11widget.cpp \ +pica-client/vaapix11widget.h + +nodist_pica_client_pica_client_SOURCES += moc_vaapix11widget.cpp + +pica_client_pica_client_CPPFLAGS += $(VAAPI_X11_CFLAGS) +pica_client_pica_client_LDADD += $(VAAPI_X11_LIBS) +MOCFLAGS += -DHAVE_VAAPI_X11 +endif pkgpicaclientdir = ${datarootdir}/pica-client dist_pkgpicaclient_DATA = \ diff --git a/PICA_client.c b/PICA_client.c index 69e3da0..19110d9 100644 --- a/PICA_client.c +++ b/PICA_client.c @@ -16,10 +16,12 @@ */ #include "PICA_security.h" #include "PICA_client.h" +#include "PICA_media.h" #include "PICA_proto.h" #include "PICA_msgproc.h" #include "PICA_common.h" #include "PICA_signverify.h" +#include "PICA_netconf.h" #include <openssl/dh.h> #include <string.h> #include <time.h> @@ -76,7 +78,19 @@ static unsigned int procmsg_PICA_PROTO_DIRECTC2C_ADDRLIST(unsigned char*, unsign static unsigned int procmsg_PICA_PROTO_DIRECTC2C_FAILED(unsigned char*, unsigned int, void*); static unsigned int procmsg_PICA_PROTO_DIRECTC2C_SWITCH(unsigned char*, unsigned int, void*); static unsigned int procmsg_MULTILOGIN(unsigned char*, unsigned int, void*); - +static unsigned int procmsg_CALLREQ(unsigned char*, unsigned int, void*); +static unsigned int procmsg_CALLANS(unsigned char*, unsigned int, void*); +static unsigned int procmsg_CALLREJ(unsigned char*, unsigned int, void*); +static unsigned int procmsg_CALLFIN(unsigned char*, unsigned int, void*); +static unsigned int procmsg_CALL_AUDIOPARAM(unsigned char*, unsigned int, void*); +static unsigned int procmsg_CALL_VIDEOPARAM(unsigned char*, unsigned int, void*); +static unsigned int procmsg_CALL_AUDIO_PACKET(unsigned char*, unsigned int, void*); +static unsigned int procmsg_CALL_VIDEO_PACKET(unsigned char*, unsigned int, void*); +static unsigned int procmsg_MEDIA_PINGREQ(unsigned char*, unsigned int, void*); +static unsigned int procmsg_MEDIA_PINGREP(unsigned char*, unsigned int, void*); +static unsigned int procmsg_MYTCPADDR(unsigned char*, unsigned int, void*); +static unsigned int procmsg_MYUDPADDRTOKEN(unsigned char*, unsigned int, void*); +static unsigned int procmsg_MYUDPADDR(unsigned char*, unsigned int, void*); static struct PICA_proto_msg* c2n_writebuf_push(struct PICA_c2n *ci, unsigned int msgid, unsigned int size); static struct PICA_proto_msg* c2c_writebuf_push(struct PICA_c2c *chn, unsigned int msgid, unsigned int size); @@ -102,13 +116,25 @@ const struct PICA_msginfo c2n_messages[] = {PICA_PROTO_PINGREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_PINGREQ_SIZE, procmsg_PINGREQ}, {PICA_PROTO_INITRESPOK, PICA_MSG_FIXED_SIZE, PICA_PROTO_INITRESPOK_SIZE, procmsg_INITRESP}, {PICA_PROTO_VERDIFFER, PICA_MSG_FIXED_SIZE, PICA_PROTO_VERDIFFER_SIZE, procmsg_INITRESP}, - {PICA_PROTO_MULTILOGIN, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_MULTILOGIN} + {PICA_PROTO_MULTILOGIN, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_MULTILOGIN}, + {PICA_PROTO_MYTCPADDR_IPV4, PICA_MSG_FIXED_SIZE, PICA_PROTO_MYTCPADDR_IPV4_SIZE, procmsg_MYTCPADDR}, + {PICA_PROTO_MYTCPADDR_IPV6, PICA_MSG_FIXED_SIZE, PICA_PROTO_MYTCPADDR_IPV6_SIZE, procmsg_MYTCPADDR}, + {PICA_PROTO_MYUDPADDRTOKEN, PICA_MSG_FIXED_SIZE, PICA_PROTO_MYUDPADDRTOKEN_SIZE, procmsg_MYUDPADDRTOKEN}, + {PICA_PROTO_MYUDPADDR, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT8, procmsg_MYUDPADDR} }; const struct PICA_msginfo c2c_messages[] = { {PICA_PROTO_MSGUTF8, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_MSGUTF8}, {PICA_PROTO_MSGOK, PICA_MSG_FIXED_SIZE, PICA_PROTO_MSGOK_SIZE, procmsg_MSGOK}, + {PICA_PROTO_CALLREQ, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_CALLREQ}, + {PICA_PROTO_CALLANS, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_CALLANS}, + {PICA_PROTO_CALLREJ, PICA_MSG_FIXED_SIZE, PICA_PROTO_CALLREJ_SIZE, procmsg_CALLREJ}, + {PICA_PROTO_CALLFIN, PICA_MSG_FIXED_SIZE, PICA_PROTO_CALLFIN_SIZE, procmsg_CALLFIN}, + {PICA_PROTO_CALL_AUDIOPARAM, PICA_MSG_FIXED_SIZE, PICA_PROTO_CALL_AUDIOPARAM_SIZE, procmsg_CALL_AUDIOPARAM}, + {PICA_PROTO_CALL_VIDEOPARAM, PICA_MSG_FIXED_SIZE, PICA_PROTO_CALL_VIDEOPARAM_SIZE, procmsg_CALL_VIDEOPARAM}, + {PICA_PROTO_CALL_AUDIO_PACKET, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_CALL_AUDIO_PACKET}, + {PICA_PROTO_CALL_VIDEO_PACKET, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_CALL_VIDEO_PACKET}, {PICA_PROTO_SENDFILEREQUEST, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_SENDFILEREQUEST}, {PICA_PROTO_ACCEPTEDFILE, PICA_MSG_FIXED_SIZE, PICA_PROTO_ACCEPTEDFILE_SIZE, procmsg_ACCEPTEDFILE}, {PICA_PROTO_DENIEDFILE, PICA_MSG_FIXED_SIZE, PICA_PROTO_DENIEDFILE_SIZE, procmsg_DENIEDFILE}, @@ -127,6 +153,53 @@ struct PICA_msginfo c2c_init_messages[] = }; +/* What a datagram of a mediac2c connection can carry, see PICA_media.h */ +const struct PICA_msginfo media_messages[] = +{ + {PICA_PROTO_CALL_AUDIO_PACKET, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_CALL_AUDIO_PACKET}, + {PICA_PROTO_CALL_VIDEO_PACKET, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_CALL_VIDEO_PACKET}, + {PICA_PROTO_PINGREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_PINGREQ_SIZE, procmsg_MEDIA_PINGREQ}, + {PICA_PROTO_PINGREP, PICA_MSG_FIXED_SIZE, PICA_PROTO_PINGREP_SIZE, procmsg_MEDIA_PINGREP} +}; + +unsigned int PICA_media_process_messages(unsigned char *buf, unsigned int *read_pos, struct PICA_c2c *c2c) +{ + return PICA_processdatastream(buf, read_pos, c2c, media_messages, MSGINFO_MSGSNUM(media_messages)); +} + +void PICA_media_transport_changed(struct PICA_c2c *c2c, int transport, const char *ciphersuitename) +{ + if (callbacks.call_media_transport_cb) + callbacks.call_media_transport_cb(c2c->peer_id, transport, ciphersuitename, + PICA_media_max_payload(c2c)); +} + +int PICA_media_send_ping(struct PICA_c2c *c2c, int reply) +{ + unsigned char buf[PICA_PROTO_PINGREQ_SIZE]; + + buf[0] = buf[1] = reply ? PICA_PROTO_PINGREP : PICA_PROTO_PINGREQ; + RAND_pseudo_bytes(buf + 2, 2); + + return PICA_media_send(c2c, buf, sizeof(buf)); +} + +static unsigned int procmsg_MEDIA_PINGREQ(unsigned char* buf, unsigned int nb, void* p) +{ + PICA_media_send_ping((struct PICA_c2c *)p, 1); + + return 1; +} + +static unsigned int procmsg_MEDIA_PINGREP(unsigned char* buf, unsigned int nb, void* p) +{ + /* Nothing to do: a ping reply is only interesting as a sign that the + * connection still works, and receiving it already updated the time the + * last datagram arrived at. + */ + return 1; +} + int PICA_get_id_from_cert_file(const char *cert_file, unsigned char *id) { X509 *x; @@ -172,7 +245,7 @@ int PICA_get_id_from_cert_string(const char *cert_pem, unsigned char *id) return PICA_id_from_X509(x, id); } -static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx) +int PICA_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) { //return 1 for self-signed certificates char buf[256]; @@ -209,6 +282,7 @@ static int c2n_alloc_c2c(struct PICA_c2n *ci, struct PICA_c2c **chn, const unsig chnl->conn = ci; chnl->outgoing = is_outgoing; + chnl->directc2c_config = ci->directc2c_config; memcpy(chnl->peer_id, peer_id, PICA_ID_SIZE); chnl->acc = ci->acc; @@ -327,7 +401,7 @@ static int c2c_stage5_starttls(struct PICA_c2c *chnl) return PICA_ERRSSL; } - SSL_set_verify(chnl->ssl, SSL_VERIFY_PEER, verify_callback); + SSL_set_verify(chnl->ssl, SSL_VERIFY_PEER, PICA_verify_callback); SSL_set_verify_depth(chnl->ssl, 1);//peer certificate and one CA if (chnl->outgoing) @@ -351,7 +425,7 @@ static int c2c_stage5_starttls(struct PICA_c2c *chnl) return PICA_OK; } -static int verify_peer_cert_common(X509 **peer_cert, SSL *ssl, const unsigned char *peer_id) +int PICA_verify_peer_cert_common(X509 **peer_cert, SSL *ssl, const unsigned char *peer_id) { unsigned char idbuf[PICA_ID_SIZE]; EVP_PKEY *pubkey; @@ -411,7 +485,7 @@ static int verify_peer_cert_common(X509 **peer_cert, SSL *ssl, const unsigned ch static int c2c_verify_peer_cert(struct PICA_c2c *chnl) { - return verify_peer_cert_common(&chnl->peer_cert, chnl->ssl, chnl->peer_id); + return PICA_verify_peer_cert_common(&chnl->peer_cert, chnl->ssl, chnl->peer_id); } static int c2c_stage6_sendc2cconnreq(struct PICA_c2c *chnl) @@ -435,10 +509,18 @@ static int c2c_start(struct PICA_c2c *chnl) { int ret, err_ret; + /* Defensive: c2c_start() opens a new socket and resets the channel to + * CONNECTING without touching chnl->ssl or the write buffer. Running it + * on a channel that is past NEW would strand the existing session and + * reroute buffered data, so refuse unless the channel is still new. + */ + if (chnl->state != PICA_C2C_STATE_NEW) + return PICA_ERRINVARG; chnl->sck_data = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); IOCTLSETNONBLOCKINGSOCKET(chnl->sck_data, 1); + SETTCPNODELAY(chnl->sck_data); { struct sockaddr_in addr = chnl->conn->srv_addr; @@ -497,7 +579,7 @@ static unsigned int procmsg_C2CCONNREQ(unsigned char* buf, unsigned int nb, void callbacks.c2c_established_cb(cc->peer_id, SSL_get_cipher_name(cc->ssl)); - if (cc->conn->directc2c_config == PICA_DIRECTC2C_CFG_ALLOWINCOMING) + if (cc->directc2c_config == PICA_DIRECTC2C_CFG_ALLOWINCOMING) PICA_send_directc2caddrlist(cc); } else @@ -533,7 +615,7 @@ static unsigned int procmsg_INITRESP_c2c(unsigned char* buf, unsigned int nb, vo cc->state = PICA_C2C_STATE_ACTIVE; callbacks.c2c_established_cb(cc->peer_id, SSL_get_cipher_name(cc->ssl)); - if (cc->conn->directc2c_config == PICA_DIRECTC2C_CFG_ALLOWINCOMING) + if (cc->directc2c_config == PICA_DIRECTC2C_CFG_ALLOWINCOMING) PICA_send_directc2caddrlist(cc); break; @@ -550,9 +632,25 @@ static unsigned int procmsg_INITRESP_c2c(unsigned char* buf, unsigned int nb, vo return 1; } +/* "address:port", for the log; buf has PICA_DIRECTC2C_ADDRSTRSIZE octets */ +#define PICA_DIRECTC2C_ADDRSTRSIZE (INET6_ADDRSTRLEN + 6) + +static const char *directc2c_addrstr(const struct sockaddr_in *a, char *buf) +{ + char ip[INET6_ADDRSTRLEN]; + + if (!inet_ntop(AF_INET, &a->sin_addr, ip, sizeof(ip))) + strcpy(ip, "?"); + + sprintf(buf, "%s:%u", ip, (unsigned int)ntohs(a->sin_port)); + + return buf; +} + static int directc2c_connect_next(struct PICA_directc2c *dc2c, struct PICA_c2c *c2c) { PICA_TRACEFUNC + char addrstr[PICA_DIRECTC2C_ADDRSTRSIZE]; int ret; if (dc2c->ssl) @@ -562,24 +660,39 @@ static int directc2c_connect_next(struct PICA_directc2c *dc2c, struct PICA_c2c * CLOSE(dc2c->sck); dc2c->sck = -1; + /* the list holds IPv4 elements only, behind a length field in host byte + * order - see procmsg_PICA_PROTO_DIRECTC2C_ADDRLIST() + */ if (dc2c->addrpos == 0) dc2c->addrpos += 2; - if (dc2c->addrpos >= *(uint16_t*)dc2c->addrlist) + if (dc2c->addrpos + PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE > *(uint16_t*)dc2c->addrlist + 2) + { + fprintf(stderr, "directc2c: no more addresses to try\n"); return PICA_ERRNOTFOUND; + } switch(dc2c->addrlist[dc2c->addrpos]) { case PICA_PROTO_DIRECTC2C_IPV4: dc2c->sck = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); IOCTLSETNONBLOCKINGSOCKET(dc2c->sck, 1); + SETTCPNODELAY(dc2c->sck); memset(&dc2c->addr, 0, sizeof(dc2c->addr)); dc2c->addr.sin_family = AF_INET; dc2c->addr.sin_addr.s_addr = *((in_addr_t*)(dc2c->addrlist + dc2c->addrpos + 1)); dc2c->addr.sin_port = *((uint16_t*)(dc2c->addrlist + dc2c->addrpos + 5)); - printf("received direct IPv4 addr %s port %i\n", inet_ntoa(dc2c->addr.sin_addr), ntohs(dc2c->addr.sin_port)); + /* the list only holds private addresses of a network this host is + * on, see directc2c_addrlist_ipv4() */ + dc2c->attempt_started = PICA_media_now(); + dc2c->attempt_deadline = dc2c->attempt_started + + (PICA_is_private_addr_ipv4(dc2c->addr.sin_addr.s_addr) + ? PICA_DIRECTC2C_LAN_CONNECT_TIMEOUT : PICA_DIRECTC2C_CONNECT_TIMEOUT); + + fprintf(stderr, "directc2c: connecting to %s, timeout %u ms\n", directc2c_addrstr(&dc2c->addr, addrstr), + (unsigned int)(dc2c->attempt_deadline - dc2c->attempt_started)); dc2c->state = PICA_DIRECTC2C_CONNSTATE_CONNECTING; @@ -588,31 +701,164 @@ static int directc2c_connect_next(struct PICA_directc2c *dc2c, struct PICA_c2c * ret = process_first_async_connect_result(ret); if (ret != PICA_OK) + { + fprintf(stderr, "directc2c: connection to %s failed\n", addrstr); dc2c->state = PICA_DIRECTC2C_CONNSTATE_FAILED; + } dc2c->addrpos += PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE; break; - case PICA_PROTO_DIRECTC2C_IPV6: - break; - + default: + return PICA_ERRNOTFOUND; } return PICA_OK; } +/* Whether an IPv4 address of a received address list is worth connecting + * to. A private one is only if it is on a private network this host is on: + * anywhere else it is some other network's address, which leads nowhere or + * to the wrong host. Logs the decision. + */ +static int directc2c_addr_usable(const struct sockaddr_in *a, const in_addr_t *ifaddrs, + const in_addr_t *ifmasks, int ifcount) +{ + char addrstr[PICA_DIRECTC2C_ADDRSTRSIZE]; + char ifaddr[INET6_ADDRSTRLEN], ifmask[INET6_ADDRSTRLEN]; + int i; + + directc2c_addrstr(a, addrstr); + + if (!PICA_is_private_addr_ipv4(a->sin_addr.s_addr)) + { + fprintf(stderr, "directc2c: 0x0B address %s - public, will be tried\n", addrstr); + return 1; + } + + if (ifcount == 0) + { + fprintf(stderr, "directc2c: 0x0B address %s - private, ignored: this host is on no private network\n", addrstr); + return 0; + } + + i = PICA_find_subnet_ipv4(a->sin_addr.s_addr, ifaddrs, ifmasks, ifcount); + + if (i < 0) + { + fprintf(stderr, "directc2c: 0x0B address %s - private, ignored: not on a private network of this host\n", + addrstr); + return 0; + } + + if (!inet_ntop(AF_INET, &ifaddrs[i], ifaddr, sizeof(ifaddr))) + strcpy(ifaddr, "?"); + + if (!inet_ntop(AF_INET, &ifmasks[i], ifmask, sizeof(ifmask))) + strcpy(ifmask, "?"); + + fprintf(stderr, "directc2c: 0x0B address %s - private, on the network of local address %s netmask %s, will be tried\n", + addrstr, ifaddr, ifmask); + + return 1; +} + +/* Picks the IPv4 elements out of a received address list, in their order, + * into list, behind a length field in host byte order - those worth + * connecting to, see directc2c_addr_usable(). + * Elements of the other types are stepped over by their size, see the 0xA4 + * message. An element of an unknown type ends the list, as there is no + * knowing where it ends; so does a truncated one. + * \return size of what was written to list + */ +static unsigned int directc2c_addrlist_ipv4(const unsigned char *items, unsigned int len, uint8_t *list) +{ + in_addr_t ifaddrs[PICA_IFADDRS_MAX], ifmasks[PICA_IFADDRS_MAX]; + int ifcount; + unsigned int pos = 0; + uint16_t n = 0; + + ifcount = PICA_get_private_ifaddrs_ipv4(ifaddrs, ifmasks, PICA_IFADDRS_MAX); + + fprintf(stderr, "directc2c: received 0x0B, %u octets of addresses\n", len); + + while (pos < len && n < PICA_DIRECTC2C_MAX_ADDRS) + { + switch (items[pos]) + { + case PICA_PROTO_DIRECTC2C_IPV4: + { + struct sockaddr_in a; + + if (pos + PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE > len) + { + fprintf(stderr, "directc2c: 0x0B truncated IPv4 address, end of list\n"); + goto end; + } + + memset(&a, 0, sizeof(a)); + a.sin_family = AF_INET; + memcpy(&a.sin_addr.s_addr, items + pos + 1, 4); + memcpy(&a.sin_port, items + pos + 5, 2); + + if (directc2c_addr_usable(&a, ifaddrs, ifmasks, ifcount)) + { + memcpy(list + 2 + n * PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE, + items + pos, PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE); + n++; + } + + pos += PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE; + break; + } + + case PICA_PROTO_DIRECTC2C_IPV6: + fprintf(stderr, "directc2c: 0x0B IPv6 address - ignored, not supported\n"); + pos += PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV6_SIZE; + break; + + case PICA_PROTO_DIRECTC2C_DNS: + if (pos + 1 >= len) + { + fprintf(stderr, "directc2c: 0x0B truncated DNS name, end of list\n"); + goto end; + } + + fprintf(stderr, "directc2c: 0x0B DNS name - ignored, not supported\n"); + pos += 2 + items[pos + 1] + 2; + break; + + default: + fprintf(stderr, "directc2c: 0x0B unknown address type 0x%02X, end of list\n", items[pos]); + goto end; + } + } + + if (pos < len) + fprintf(stderr, "directc2c: 0x0B more than %i usable addresses, the rest is ignored\n", PICA_DIRECTC2C_MAX_ADDRS); + +end: + *(uint16_t*)list = n * PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE; + + return 2 + n * PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE; +} + static unsigned int procmsg_PICA_PROTO_DIRECTC2C_ADDRLIST(unsigned char* buf, unsigned int nb, void* p) { PICA_TRACEFUNC struct PICA_c2c *cc = (struct PICA_c2c *)p; int ret; - if (cc->conn->directc2c_config != PICA_DIRECTC2C_CFG_DISABLED) + if (cc->directc2c_config != PICA_DIRECTC2C_CFG_DISABLED) { if (cc->directc2c_state != PICA_DIRECTC2C_STATE_INACTIVE && cc->directc2c_state != PICA_DIRECTC2C_STATE_WAITINGINCOMING) return 0; - if (cc->outgoing == PICA_C2C_OUTGOING || cc->conn->directc2c_config == PICA_DIRECTC2C_CFG_CONNECTONLY) + /* the peer announces its addresses once */ + if (cc->direct) + return 1; + + if (cc->outgoing == PICA_C2C_OUTGOING || cc->directc2c_config == PICA_DIRECTC2C_CFG_CONNECTONLY) cc->directc2c_state = PICA_DIRECTC2C_STATE_CONNECTING; cc->direct = calloc(1, sizeof(struct PICA_directc2c)); @@ -623,16 +869,15 @@ static unsigned int procmsg_PICA_PROTO_DIRECTC2C_ADDRLIST(unsigned char* buf, un cc->direct->is_outgoing = PICA_DIRECTC2C_OUTGOING; cc->direct->state = PICA_DIRECTC2C_CONNSTATE_NEW; cc->direct->sck = -1; - cc->direct->addrlist = malloc(nb - 2 + 1); + cc->direct->addrlist = malloc(2 + PICA_DIRECTC2C_MAX_ADDRS * PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE); if (!cc->direct->addrlist) return 1; - memcpy(cc->direct->addrlist, buf + 2, nb - 2);// copy size and address list - cc->direct->addrlist[nb - 2] = 0; + directc2c_addrlist_ipv4(buf + 4, nb - 4, cc->direct->addrlist); cc->direct->addrpos = 0; - if (cc->outgoing == PICA_C2C_INCOMING && cc->conn->directc2c_config == PICA_DIRECTC2C_CFG_ALLOWINCOMING) + if (cc->outgoing == PICA_C2C_INCOMING && cc->directc2c_config == PICA_DIRECTC2C_CFG_ALLOWINCOMING) return 1;//connect later, if no incoming connection is accepted and DIRECTC2C_FAILED is received ret = directc2c_connect_next(cc->direct, cc); @@ -655,20 +900,25 @@ static unsigned int procmsg_PICA_PROTO_DIRECTC2C_FAILED(unsigned char* buf, unsi if (cc->directc2c_state != PICA_DIRECTC2C_STATE_WAITINGINCOMING) return 0; - if (cc->conn->directc2c_config == PICA_DIRECTC2C_CFG_DISABLED) + if (cc->directc2c_config == PICA_DIRECTC2C_CFG_DISABLED) return 0; if (cc->outgoing != PICA_C2C_INCOMING) return 0; + /* FAILED tells us to connect to the peer instead, but we can only do + * that if the peer actually sent us its address list (which allocates + * cc->direct). Without it there is nothing to connect to. + */ + if (!cc->direct) + return 0; + ret = directc2c_connect_next(cc->direct, cc); if (ret == PICA_ERRNOTFOUND) - { cc->directc2c_state = PICA_DIRECTC2C_STATE_FAILEDTOCONNECT; - } - - cc->directc2c_state = PICA_DIRECTC2C_STATE_CONNECTING; + else + cc->directc2c_state = PICA_DIRECTC2C_STATE_CONNECTING; return 1; } @@ -679,12 +929,19 @@ unsigned int procmsg_PICA_PROTO_DIRECTC2C_SWITCH(unsigned char* buf, unsigned in struct PICA_c2c *cc = (struct PICA_c2c *)p; int ret; - if (cc->conn->directc2c_config == PICA_DIRECTC2C_CFG_DISABLED) + if (cc->directc2c_config == PICA_DIRECTC2C_CFG_DISABLED) return 0; if (cc->directc2c_state != PICA_DIRECTC2C_STATE_ACTIVE && cc->directc2c_state != PICA_DIRECTC2C_STATE_CONNECTING) return 0; + /* A SWITCH may legitimately arrive while our own direct link is still + * CONNECTING, but switching reads to it before its SSL object exists + * would hand SSL_read() a NULL. Refuse until the direct session is there. + */ + if (!cc->direct || !cc->direct->ssl) + return 0; + cc->switched_to_directc2c_read = 1; return 1; @@ -782,7 +1039,12 @@ static unsigned int procmsg_NOTFOUND(unsigned char* buf, unsigned int nb, void* ipt = ci->chan_list_end; while(ipt) { - if (memcmp(ipt->peer_id, peer_id, PICA_ID_SIZE) == 0) + /* Same guard as procmsg_FOUND(): act only on a channel still waiting + * for the search result, so a spurious NOTFOUND from the node cannot + * tear down an already established channel found by peer_id alone. + */ + if (ipt->outgoing && ipt->state == PICA_C2C_STATE_NEW + && memcmp(ipt->peer_id, peer_id, PICA_ID_SIZE) == 0) { rq = ipt; break; @@ -812,7 +1074,13 @@ static unsigned int procmsg_FOUND(unsigned char* buf, unsigned int nb, void* p) ipt = ci->chan_list_end; while(ipt) { - if (memcmp(ipt->peer_id, peer_id, PICA_ID_SIZE) == 0) + /* Only a freshly requested outgoing channel is waiting for FOUND. + * Matching on peer_id alone would also pick up an already ACTIVE + * channel and let c2c_start() tear it back down to an anonymous + * session, flushing any buffered end-to-end message to the node. + */ + if (ipt->outgoing && ipt->state == PICA_C2C_STATE_NEW + && memcmp(ipt->peer_id, peer_id, PICA_ID_SIZE) == 0) { rq = ipt; break; @@ -926,6 +1194,13 @@ static unsigned int procmsg_MSGOK(unsigned char* buf, unsigned int nb, void* p) { struct PICA_c2c *chan = (struct PICA_c2c *)p; + /* A delivery receipt is only meaningful once the channel is active, same + * as procmsg_MSGUTF8 - the c2c stream is also parsed in the pre-active + * WAITINGREP/WAITINGC2CPROTOVER states. + */ + if (chan->state != PICA_C2C_STATE_ACTIVE) + return 0; + callbacks.msgok_cb(chan -> peer_id); return 1; } @@ -948,6 +1223,208 @@ unsigned int procmsg_PINGREQ(unsigned char* buf, unsigned int nb, void* p) return 1; } +/* Reads the address and the port following it, both in network byte order, + * for one of the "my address" callbacks. addr_str has to have room for + * INET6_ADDRSTRLEN characters. + */ +static int myaddr_parse(int af, const unsigned char *addr, char *addr_str, uint16_t *port) +{ + if (!inet_ntop(af, addr, addr_str, INET6_ADDRSTRLEN)) + return 0; + + memcpy(port, addr + (af == AF_INET6 ? 16 : 4), 2); + *port = ntohs(*port); + + return 1; +} + +static unsigned int procmsg_MYTCPADDR(unsigned char* buf, unsigned int nb, void* p) +{ + PICA_TRACEFUNC + struct PICA_c2n *c2n = (struct PICA_c2n *)p; + char addr_str[INET6_ADDRSTRLEN]; + uint16_t port; + + /* not something we asked for */ + if (!c2n->tcpaddr_requested) + return 1; + + c2n->tcpaddr_requested = 0; + + /* the message size is fixed for each of the two types, see c2n_messages[] */ + if (!myaddr_parse(buf[0] == PICA_PROTO_MYTCPADDR_IPV6 ? AF_INET6 : AF_INET, buf + 2, addr_str, &port)) + return 0; + + if (callbacks.tcp_address_cb) + callbacks.tcp_address_cb(c2n, buf[0], buf + 2, addr_str, port); + + return 1; +} + +static void udpaddr_send_probe(struct PICA_c2n *c2n) +{ + unsigned char probe[PICA_PROTO_MYUDPADDRPROBE_SIZE]; + + probe[0] = probe[1] = PICA_PROTO_MYUDPADDRPROBE; + memcpy(probe + 2, c2n->udpaddr_token, PICA_PROTO_MYUDPADDR_TOKENSIZE); + + /* The node's UDP port has the same number as the TCP port the c2n + * connection was made to. A failed send is treated like a lost datagram. + */ + sendto(c2n->udpaddr_sck, (const char*)probe, sizeof(probe), 0, + (const struct sockaddr*)&c2n->srv_addr, sizeof(c2n->srv_addr)); + + c2n->udpaddr_last_probe = time(0); + c2n->udpaddr_probes_sent++; +} + +static unsigned int procmsg_MYUDPADDRTOKEN(unsigned char* buf, unsigned int nb, void* p) +{ + PICA_TRACEFUNC + struct PICA_c2n *c2n = (struct PICA_c2n *)p; + + /* not something we asked for, or the answer to a request already given up on */ + if (c2n->udpaddr_state == PICA_UDPADDR_STATE_IDLE) + return 1; + + /* A token arriving while an earlier one is being sent belongs to a + * request that restarted this one - the node has dropped the earlier + * token by now, so the new one is the one to use. + */ + memcpy(c2n->udpaddr_token, buf + 2, PICA_PROTO_MYUDPADDR_TOKENSIZE); + c2n->udpaddr_state = PICA_UDPADDR_STATE_PROBING; + c2n->udpaddr_probes_sent = 0; + + udpaddr_send_probe(c2n); + + return 1; +} + +static unsigned int procmsg_MYUDPADDR(unsigned char* buf, unsigned int nb, void* p) +{ + PICA_TRACEFUNC + struct PICA_c2n *c2n = (struct PICA_c2n *)p; + char addr_str[INET6_ADDRSTRLEN]; + uint16_t port; + int af; + + if (c2n->udpaddr_state != PICA_UDPADDR_STATE_PROBING) + return 1; + + /* buf[2] is the length of the address that starts with its type at buf[3] */ + if (nb < 4) + return 0; + + if (buf[3] == PICA_PROTO_MYUDPADDR_IPV4 && buf[2] == PICA_PROTO_MYUDPADDR_IPV4_SIZE) + af = AF_INET; + else if (buf[3] == PICA_PROTO_MYUDPADDR_IPV6 && buf[2] == PICA_PROTO_MYUDPADDR_IPV6_SIZE) + af = AF_INET6; + else + return 0; + + if (!myaddr_parse(af, buf + 4, addr_str, &port)) + return 0; + + /* before the callback, which is free to make another request */ + c2n->udpaddr_state = PICA_UDPADDR_STATE_IDLE; + + if (c2n->udpaddr_c2c) + { + struct PICA_c2c *c2c = c2n->udpaddr_c2c; + + c2n->udpaddr_c2c = NULL; + PICA_media_call_learned(c2c, PICA_OK, buf + 4, buf[3], port); + } + else if (callbacks.udp_address_cb) + callbacks.udp_address_cb(c2n, PICA_OK, buf[3], buf + 4, addr_str, port); + + return 1; +} + +/* resends the datagram of a request in progress, and gives up on one that + * was not answered in time + */ +static void process_udpaddr(struct PICA_c2n *c2n) +{ + time_t now; + + if (c2n->udpaddr_state == PICA_UDPADDR_STATE_IDLE) + return; + + now = time(0); + + if (now - c2n->udpaddr_started > PICA_UDPADDR_TIMEOUT || now < c2n->udpaddr_started) + { + c2n->udpaddr_state = PICA_UDPADDR_STATE_IDLE; + + if (c2n->udpaddr_c2c) + { + struct PICA_c2c *c2c = c2n->udpaddr_c2c; + + c2n->udpaddr_c2c = NULL; + PICA_media_call_learned(c2c, PICA_ERRTIMEDOUT, NULL, 0, 0); + } + else if (callbacks.udp_address_cb) + callbacks.udp_address_cb(c2n, PICA_ERRTIMEDOUT, 0, NULL, NULL, 0); + + return; + } + + if (c2n->udpaddr_state == PICA_UDPADDR_STATE_PROBING + && c2n->udpaddr_probes_sent < PICA_UDPADDR_PROBES + && now != c2n->udpaddr_last_probe) + udpaddr_send_probe(c2n); +} + +int PICA_request_tcp_address(struct PICA_c2n *c2n) +{ + struct PICA_proto_msg *mp; + + if (!c2n || c2n->state != PICA_C2N_STATE_CONNECTED) + return PICA_ERRINVARG; + + mp = c2n_writebuf_push(c2n, PICA_PROTO_MYTCPADDRREQ, PICA_PROTO_MYTCPADDRREQ_SIZE); + + if (!mp) + return PICA_ERRNOMEM; + + RAND_pseudo_bytes(mp->tail, 2); + + c2n->tcpaddr_requested = 1; + + return PICA_OK; +} + +int PICA_request_udp_address(struct PICA_c2n *c2n, SOCKET udp_sck) +{ + struct PICA_proto_msg *mp; + + if (!c2n || c2n->state != PICA_C2N_STATE_CONNECTED || udp_sck == (SOCKET)-1) + return PICA_ERRINVARG; + + mp = c2n_writebuf_push(c2n, PICA_PROTO_MYUDPADDRREQ, PICA_PROTO_MYUDPADDRREQ_SIZE); + + if (!mp) + return PICA_ERRNOMEM; + + RAND_pseudo_bytes(mp->tail, 2); + + c2n->udpaddr_sck = udp_sck; + c2n->udpaddr_started = time(0); + c2n->udpaddr_probes_sent = 0; + c2n->udpaddr_state = PICA_UDPADDR_STATE_WAITINGTOKEN; + /* a request of the application replaces one the library made for a + * call, which then sends its address list without that address + */ + if (c2n->udpaddr_c2c) + { + PICA_media_call_learned(c2n->udpaddr_c2c, PICA_ERRTIMEDOUT, NULL, 0, 0); + c2n->udpaddr_c2c = NULL; + } + + return PICA_OK; +} + int PICA_deny_file(struct PICA_c2c *chan) { struct PICA_proto_msg *mp; @@ -1001,6 +1478,10 @@ static int validate_file_name(const char *buf, unsigned int len) { int ret = PICA_OK; char *str = malloc(len + 1); + + if (!str) + return PICA_ERRNOMEM; + memcpy(str, buf, len); str[len] = '\0'; @@ -1023,11 +1504,24 @@ static unsigned int procmsg_SENDFILEREQUEST(unsigned char* buf, unsigned int nb, int ret; char *filename = buf + 12; - unsigned int filenamesize = *(uint16_t*)(buf + 2) - 8; + uint16_t payload_len = *(uint16_t*)(buf + 2); + unsigned int filenamesize; if (chan->recvfilestate != PICA_CHANRECVFILESTATE_IDLE) return 0; + /* payload = 8-byte file size + file name. Guard the subtraction so a + * short length field cannot underflow filenamesize to ~4 GB, and hold + * the sender to the documented name-length limit. + */ + if (payload_len < 8) + return 0; + + filenamesize = payload_len - 8; + + if (filenamesize == 0 || filenamesize > PICA_PROTO_C2CMSG_MAXFILENAMESIZE) + return 0; + if (validate_file_name(filename, filenamesize) != PICA_OK) return 0; @@ -1169,8 +1663,14 @@ static unsigned int procmsg_FILECONTROL(unsigned char* buf, unsigned int nb, voi case PICA_PROTO_FILECONTROL_CANCEL: case PICA_PROTO_FILECONTROL_IOERROR: chan->recvfilestate = PICA_CHANRECVFILESTATE_IDLE; - fclose(chan->recvfile_stream); - chan->recvfile_stream = NULL; + /* The stream exists only once the offer was accepted; a CANCEL in + * WAITACCEPT (sender withdrew a pending offer) leaves it NULL. + */ + if (chan->recvfile_stream) + { + fclose(chan->recvfile_stream); + chan->recvfile_stream = NULL; + } break; case PICA_PROTO_FILECONTROL_VOID: @@ -1199,8 +1699,12 @@ static unsigned int procmsg_FILECONTROL(unsigned char* buf, unsigned int nb, voi case PICA_PROTO_FILECONTROL_CANCEL: case PICA_PROTO_FILECONTROL_IOERROR: chan->sendfilestate = PICA_CHANSENDFILESTATE_IDLE; - fclose(chan->sendfile_stream); - chan->sendfile_stream = NULL; + /* Symmetric guard: only close a stream that was actually opened. */ + if (chan->sendfile_stream) + { + fclose(chan->sendfile_stream); + chan->sendfile_stream = NULL; + } break; case PICA_PROTO_FILECONTROL_VOID: @@ -1334,14 +1838,13 @@ static int check_pkey_passphrase(const char *pkey_file, } -int PICA_new_listener(const struct PICA_acc *acc, const char *public_addr, int public_port, int local_port, struct PICA_listener **l) +int PICA_new_listener(const struct PICA_acc *acc, int local_port, struct PICA_listener **l) { - int ret, ret_err, flag; + int ret, ret_err; struct PICA_listener *lst = NULL; struct sockaddr_in s; - - if (!acc || !public_addr || public_port <= 0 || public_port > 65535 || local_port <= 0 || local_port > 65535 || !l) + if (!acc || local_port <= 0 || local_port > 65535 || !l) return PICA_ERRINVARG; lst = *l = (struct PICA_listener*)calloc(sizeof(struct PICA_listener), 1); @@ -1349,18 +1852,7 @@ int PICA_new_listener(const struct PICA_acc *acc, const char *public_addr, int p if (!lst) return PICA_ERRNOMEM; - lst->public_addr_dns = strdup(public_addr); - - if (!lst->public_addr_dns) - { - ret_err = PICA_ERRNOMEM; - goto error_ret_0; - } - - lst->public_addr_ipv4 = inet_addr(public_addr); - lst->acc = acc; - lst->public_port = public_port; lst->local_port = local_port; lst->sck_listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //(1) @@ -1368,11 +1860,21 @@ int PICA_new_listener(const struct PICA_acc *acc, const char *public_addr, int p if (lst->sck_listener == SOCKET_ERROR) { ret_err = PICA_ERRSOCK; - goto error_ret_1; + goto error_ret_0; } - flag = 1; - setsockopt(lst->sck_listener, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)); +#ifndef WIN32 + { + int flag = 1; + + /* Lets the port be listened on again right after a restart, while + * connections of the previous run linger in TIME_WAIT. On Windows the + * same option lets a socket take over a port that another one is + * listening on, which would hide that the port is taken. + */ + setsockopt(lst->sck_listener, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)); + } +#endif IOCTLSETNONBLOCKINGSOCKET(lst->sck_listener, 1); @@ -1386,7 +1888,7 @@ int PICA_new_listener(const struct PICA_acc *acc, const char *public_addr, int p if (ret == SOCKET_ERROR) { ret_err = PICA_ERRSOCK; - goto error_ret_2; + goto error_ret_1; } ret = listen(lst->sck_listener, 10); @@ -1394,18 +1896,29 @@ int PICA_new_listener(const struct PICA_acc *acc, const char *public_addr, int p if (ret == SOCKET_ERROR) { ret_err = PICA_ERRSOCK; - goto error_ret_2; + goto error_ret_1; } - return PICA_OK; + /* The UDP port with the same number carries call media, see PICA_media.h. + * The announced port numbers are used for both protocols, so a listener + * that has only one of them is no good - the caller can try another + * number instead. + */ + ret = PICA_media_listener_new(acc, local_port, local_port, &lst->media); -error_ret_2: //(2) + if (ret != PICA_OK) + { + fprintf(stderr, "failed to open UDP port %i for call media\n", local_port); + lst->media = NULL; + ret_err = ret; + goto error_ret_1; + } - CLOSE(lst->sck_listener); + return PICA_OK; error_ret_1: //(1) - free(lst->public_addr_dns); + CLOSE(lst->sck_listener); error_ret_0: //(0) @@ -1415,6 +1928,85 @@ error_ret_0: //(0) return ret_err; } +/* IPv4 address of an address string, resolving a DNS name if it is one. */ +static int resolve_ipv4(const char *name, in_addr_t *addr) +{ + struct addrinfo h, *r; + + *addr = inet_addr(name); + + if (*addr != INADDR_NONE) + return PICA_OK; + + memset(&h, 0, sizeof(h)); + h.ai_family = AF_INET; + h.ai_socktype = SOCK_STREAM; + h.ai_protocol = IPPROTO_TCP; + + if (getaddrinfo(name, NULL, &h, &r) != 0) + return PICA_ERRDNSRESOLVE; + + *addr = ((struct sockaddr_in*)r->ai_addr)->sin_addr.s_addr; + + freeaddrinfo(r); + + return PICA_OK; +} + +int PICA_listener_set_addrlist(struct PICA_listener *l, const char *const *addrs, const int *ports, int count) +{ + struct PICA_listener_addr list[PICA_DIRECTC2C_MAX_ADDRS]; + int i, ret; + + if (!l || count < 0 || count > PICA_DIRECTC2C_MAX_ADDRS || (count > 0 && (!addrs || !ports))) + return PICA_ERRINVARG; + + for (i = 0; i < count; i++) + { + if (ports[i] <= 0 || ports[i] > 65535) + return PICA_ERRINVARG; + + list[i].port = htons((uint16_t)ports[i]); + list[i].is_upnp = addrs[i] == NULL; + list[i].addr = INADDR_ANY; + + if (addrs[i]) + { + ret = resolve_ipv4(addrs[i], &list[i].addr); + + if (ret != PICA_OK) + return ret; + } + } + + memcpy(l->addrs, list, count * sizeof(list[0])); + l->addrs_count = count; + l->addrs_manual = count > 0; + + return PICA_OK; +} + +int PICA_listener_set_upnp_addr(struct PICA_listener *l, const char *addr, int port) +{ + if (!l) + return PICA_ERRINVARG; + + if (!addr) + { + l->upnp_addr = 0; + l->upnp_port = 0; + return PICA_OK; + } + + if (port <= 0 || port > 65535 || inet_addr(addr) == INADDR_NONE) + return PICA_ERRINVARG; + + l->upnp_addr = inet_addr(addr); + l->upnp_port = htons((uint16_t)port); + + return PICA_OK; +} + int PICA_open_acc(const char *cert_file, const char *pkey_file, const char *dh_param_file, @@ -1439,7 +2031,11 @@ int PICA_open_acc(const char *cert_file, a->cert_file = strdup(cert_file); a->password_cb = password_cb; +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + a->ctx = SSL_CTX_new(TLS_method());//(2) +#else a->ctx = SSL_CTX_new(TLSv1_2_method());//(2) +#endif if (!a->ctx) { @@ -1447,7 +2043,11 @@ int PICA_open_acc(const char *cert_file, goto error_ret_1; } +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + a->anon_ctx = SSL_CTX_new(TLS_method());//(3) +#else a->anon_ctx = SSL_CTX_new(TLSv1_2_method());//(3) +#endif if (!a->anon_ctx) { @@ -1455,6 +2055,34 @@ int PICA_open_acc(const char *cert_file, goto error_ret_2; } +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + /* TLS_method() on its own would negotiate the highest version both ends + * know. Narrowing it back to 1.2 is what keeps this the same protocol + * TLSv1_2_method() used to give - see PICA_TLS_MINVERSION for why the + * ceiling matters as much as the floor. + */ + if (!SSL_CTX_set_min_proto_version(a->ctx, PICA_TLS_MINVERSION) || + !SSL_CTX_set_max_proto_version(a->ctx, PICA_TLS_MAXVERSION) || + !SSL_CTX_set_min_proto_version(a->anon_ctx, PICA_TLS_MINVERSION) || + !SSL_CTX_set_max_proto_version(a->anon_ctx, PICA_TLS_MAXVERSION)) + { + ret_err = PICA_ERRSSL; + goto error_ret_3; + } +#endif + + /* mediac2c connections, see PICA_media.h. Not fatal if it cannot be + * created - calls then keep their media on the c2c connection. + */ +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + a->dtls_ctx = SSL_CTX_new(DTLS_method()); + + if (a->dtls_ctx) + SSL_CTX_set_min_proto_version(a->dtls_ctx, DTLS1_2_VERSION); +#else + a->dtls_ctx = SSL_CTX_new(DTLSv1_2_method()); +#endif + /* Available since openssl 1.1.0 SSL_CTX_set_security_level(a->ctx, PICA_OPENSSL_SECURUTY_LEVEL); */ @@ -1478,11 +2106,23 @@ int PICA_open_acc(const char *cert_file, goto error_ret_3; } + /* The ciphersuites Pica Pica uses are all DHE, so the DTLS context needs + * the parameters as well or it cannot take the server role. + */ + if (a->dtls_ctx && 1 != SSL_CTX_set_tmp_dh(a->dtls_ctx, dh)) + { + SSL_CTX_free(a->dtls_ctx); + a->dtls_ctx = NULL; + } + DH_free(dh); SSL_CTX_set_options(a->ctx, SSL_OP_SINGLE_DH_USE); SSL_CTX_set_options(a->anon_ctx, SSL_OP_SINGLE_DH_USE); + if (a->dtls_ctx) + SSL_CTX_set_options(a->dtls_ctx, SSL_OP_SINGLE_DH_USE); + if (!PICA_get_id_from_cert_file(cert_file, a->id)) { ret_err = PICA_ERRINVCERT; @@ -1533,9 +2173,34 @@ int PICA_open_acc(const char *cert_file, goto error_ret_3; } + /* The DTLS context authenticates the same way as a directc2c connection, + * with the same certificate, key and ciphersuites. Anything going wrong + * here only costs calls their UDP transport, so it is not reported as an + * error - the media stays on the c2c connection instead. + */ + if (a->dtls_ctx) + { + if (password_cb) + { + SSL_CTX_set_default_passwd_cb(a->dtls_ctx, password_cb); + SSL_CTX_set_default_passwd_cb_userdata(a->dtls_ctx, a->id); + } + + if (1 != SSL_CTX_use_certificate_file(a->dtls_ctx, cert_file, SSL_FILETYPE_PEM) + || 1 != SSL_CTX_use_PrivateKey_file(a->dtls_ctx, pkey_file, SSL_FILETYPE_PEM) + || 1 != SSL_CTX_set_cipher_list(a->dtls_ctx, PICA_TLS_CIPHERLIST)) + { + fprintf(stderr, "failed to set up the DTLS context, calls will not use UDP\n"); + SSL_CTX_free(a->dtls_ctx); + a->dtls_ctx = NULL; + } + } + return PICA_OK; error_ret_3: + if (a->dtls_ctx) + SSL_CTX_free(a->dtls_ctx); SSL_CTX_free(a->anon_ctx);//(3) error_ret_2: //(2) SSL_CTX_free(a->ctx); @@ -1673,6 +2338,22 @@ static unsigned int procmsg_MULTILOGIN(unsigned char *buf, unsigned int nb, void return 1; } + /* The per-connection last-timestamp check above resets to 0 on every + * reconnect, so on its own it cannot stop a captured (validly signed) + * MULTILOGIN from being replayed later. Require the timestamp to be within + * PICA_TIMETOLERANCE of now as well, bounding any replay to that window. + */ + { + uint64_t now = (uint64_t) time(NULL); + + if (timestamp > now + PICA_TIMETOLERANCE + || timestamp + PICA_TIMETOLERANCE < now) + { + fprintf(stderr, "MULTILOGIN timestamp out of tolerance, ignoring\n"); + return 1; + } + } + f = fopen(c2n->acc->cert_file, "r"); if (!f) @@ -1749,6 +2430,317 @@ multilogin_err1: return 1; } +/* Everything a call held, given back when it ends. */ +static void call_release(struct PICA_c2c *chn) +{ + chn->call_state = PICA_CALL_STATE_IDLE; + + PICA_media_close(chn); + PICA_media_call_free(chn); + + chn->call_audio_params_are_set = 0; + chn->call_video_params_are_set = 0; +} + +/* Sends 0x70 or 0x71 with the probe token and the addresses of the call + * socket. */ +static int call_send_info(struct PICA_c2c *chn, unsigned int msgid) +{ + struct PICA_proto_msg *mp; + unsigned char info[PICA_MEDIA_CALL_INFO_MAXSIZE]; + unsigned int len; + + len = PICA_media_call_write_info(chn, info); + + mp = c2c_writebuf_push(chn, msgid, 4 + len); + + if (!mp) + return PICA_ERRNOMEM; + + mp->tail[0] = len & 0xFF; + mp->tail[1] = (len >> 8) & 0xFF; + memcpy(mp->tail + 2, info, len); + + if (chn->media_call) + chn->media_call->pending_msg = 0; + + return PICA_OK; +} + +static int call_send_audio_params(struct PICA_c2c *chn, const char *codec_name, uint16_t sample_rate); +static int call_send_video_params(struct PICA_c2c *chn, const char *codec_name, uint16_t width, uint16_t height); + +/* 0x71 is out, the call is active for the callee now. */ +static int call_answered(struct PICA_c2c *chn) +{ + struct PICA_media_call *mc = chn->media_call; + int ret; + + ret = call_send_info(chn, PICA_PROTO_CALLANS); + + if (ret != PICA_OK) + return ret; + + chn->call_state = PICA_CALL_STATE_ACTIVE; + + /* the parameters set while 0x71 was waiting, which the caller must not + * see before it + */ + if (mc && mc->audio_params_pending) + call_send_audio_params(chn, mc->audio_codec, mc->audio_sample_rate); + + if (mc && mc->video_params_pending) + call_send_video_params(chn, mc->video_codec, mc->video_width, mc->video_height); + + if (mc) + mc->audio_params_pending = mc->video_params_pending = 0; + + PICA_media_start(chn); + + return PICA_OK; +} + +/* Sends 0x70 and 0x71 that were waiting for the address of the call socket + * once it is known, or once waiting for it is over. + */ +static void process_calls(struct PICA_c2n *c2n) +{ + struct PICA_c2c *c2c; + + for (c2c = c2n->chan_list_head; c2c; c2c = c2c->next) + { + struct PICA_media_call *mc = c2c->media_call; + + if (!mc || !mc->pending_msg || !PICA_media_call_ready(c2c)) + continue; + + if (mc->pending_msg == PICA_PROTO_CALLREQ && c2c->call_state == PICA_CALL_STATE_CALLING) + call_send_info(c2c, PICA_PROTO_CALLREQ); + else if (mc->pending_msg == PICA_PROTO_CALLANS && c2c->call_state == PICA_CALL_STATE_ANSWERING) + call_answered(c2c); + else + mc->pending_msg = 0; + } +} + +static unsigned int procmsg_CALLREQ(unsigned char* buf, unsigned int nb, void *p) +{ + struct PICA_c2c *chan = (struct PICA_c2c *)p; + + if (chan->call_state != PICA_CALL_STATE_IDLE) + // busy, send reject + { + struct PICA_proto_msg *mp; + mp = c2c_writebuf_push( chan, PICA_PROTO_CALLREJ, PICA_PROTO_CALLREJ_SIZE); + + if (mp) + { + RAND_pseudo_bytes( mp->tail, 2); + } + else + return 0; + + return 1; + } + + /* The callee starts finding out the address of its call socket now, + * while the call rings, so that answering is not held up by it. A call + * that cannot have it still rings. + */ + PICA_media_call_prepare(chan, 0, buf + 4, nb - 4); + + chan->call_state = PICA_CALL_STATE_INCOMINGCALL; + callbacks.incoming_call_cb(chan->peer_id); + + return 1; +} + +static unsigned int procmsg_CALLANS(unsigned char* buf, unsigned int nb, void *p) +{ + struct PICA_c2c *chan = (struct PICA_c2c *)p; + + if (chan->call_state != PICA_CALL_STATE_CALLING) + { + fprintf(stderr, "unexpected CALLANS, we did not initiate a call"); + return 0; + } + + /* a malformed list only costs the call its hole punching */ + PICA_media_call_read_info(chan, buf + 4, nb - 4); + + chan->call_state = PICA_CALL_STATE_ACTIVE; + callbacks.call_picked_up_cb(chan->peer_id); + + PICA_media_start(chan); + + return 1; +} + +static unsigned int procmsg_CALLREJ(unsigned char* buf, unsigned int nb, void *p) +{ + struct PICA_c2c *chan = (struct PICA_c2c *)p; + + if (chan->call_state != PICA_CALL_STATE_CALLING) + { + fprintf(stderr, "unexpected CALLREJ, we did not initiate a call"); + return 0; + } + + call_release(chan); + + callbacks.call_rejected_cb(chan->peer_id); + + return 1; +} + +static unsigned int procmsg_CALLFIN(unsigned char* buf, unsigned int nb, void *p) +{ + struct PICA_c2c *chan = (struct PICA_c2c *)p; + + if (chan->call_state == PICA_CALL_STATE_IDLE) + { + fprintf(stderr, "unexpected CALLFIN, no call in progress"); + return 0; + } + + call_release(chan); + + callbacks.call_hangup_cb(chan->peer_id); + + return 1; +} + +static unsigned int procmsg_CALL_AUDIOPARAM(unsigned char* buf, unsigned int nb, void *p) +{ + struct PICA_c2c *chan = (struct PICA_c2c *)p; + char codecnamebuf[24]; + uint16_t sample_rate; + + if (chan->call_state != PICA_CALL_STATE_ACTIVE) + { + fprintf(stderr, "unexpected AUDIOPARAM, no call in progress"); + return 0; + } + + chan->call_audio_params_are_set = 1; + + codecnamebuf[0] = '\0'; + strncat(codecnamebuf, buf + 2, PICA_PROTO_CALL_CODECNAMESIZE); + + sample_rate = *(uint16_t*)(buf + 2 + PICA_PROTO_CALL_CODECNAMESIZE); + callbacks.call_audio_params_cb(chan->peer_id, codecnamebuf, sample_rate); + + return 1; +} + +static unsigned int procmsg_CALL_VIDEOPARAM(unsigned char* buf, unsigned int nb, void *p) +{ + struct PICA_c2c *chan = (struct PICA_c2c *)p; + char codecnamebuf[24]; + uint16_t width, height; + + if (chan->call_state != PICA_CALL_STATE_ACTIVE) + { + fprintf(stderr, "unexpected VIDEOPARAM, no call in progress"); + return 0; + } + + chan->call_video_params_are_set = 1; + + codecnamebuf[0] = '\0'; + strncat(codecnamebuf, buf + 2, PICA_PROTO_CALL_CODECNAMESIZE); + + width = *(uint16_t*)(buf + 2 + PICA_PROTO_CALL_CODECNAMESIZE); + height = *(uint16_t*)(buf + 2 + PICA_PROTO_CALL_CODECNAMESIZE + 2); + callbacks.call_video_params_cb(chan->peer_id, codecnamebuf, width, height); + + return 1; +} + +/* A media packet is dropped rather than treated as a protocol error breaking + * the connection. It can legitimately arrive when the receiving side is not + * ready for it: over a mediac2c connection it can overtake the 0x74/0x75 + * message describing its stream, which travels over the c2c connection, and + * it can also arrive after a call has already been hung up locally. A + * malformed packet is dropped for the same reason - over UDP it says nothing + * about the peer. + */ +static unsigned int procmsg_CALL_AUDIO_PACKET(unsigned char *buf, unsigned int nb, void* p) +{ + struct PICA_c2c *chan = (struct PICA_c2c *)p; + + if (chan->call_state != PICA_CALL_STATE_ACTIVE) + { + fprintf(stderr, "unexpected CALL_AUDIO_PACKET, no call in progress\n"); + return 1; + } + + if (!chan->call_audio_params_are_set) + { + fprintf(stderr, "no AUDIOPARAM was set, can't process AUDIO_PACKET\n"); + return 1; + } + + + if (*(uint16_t*)(buf + 2) != (nb - 4)) + { + return 1; + } + + uint16_t tail_size = *(uint16_t*)(buf + 2); + + if (tail_size < PICA_PROTO_CALL_PACKET_HDRSIZE) + { + return 1; + } + + uint16_t seq_num = *(uint16_t*)(buf + 4); + uint32_t timestamp = *(uint32_t*)(buf + 4 + PICA_PROTO_CALL_PACKET_SEQNUM_SIZE); + uint16_t pkt_size = tail_size - PICA_PROTO_CALL_PACKET_HDRSIZE; + + callbacks.call_audio_packet_cb(chan->peer_id, seq_num, timestamp, pkt_size, buf + 4 + PICA_PROTO_CALL_PACKET_HDRSIZE); + + return 1; +} + +static unsigned int procmsg_CALL_VIDEO_PACKET(unsigned char *buf, unsigned int nb, void *p) +{ + struct PICA_c2c *chan = (struct PICA_c2c *)p; + + if (chan->call_state != PICA_CALL_STATE_ACTIVE) + { + fprintf(stderr, "unexpected CALL_VIDEO_PACKET, no call in progress\n"); + return 1; + } + + if (!chan->call_video_params_are_set) + { + fprintf(stderr, "no VIDEOPARAM was set, can't process VIDEO_PACKET\n"); + return 1; + } + + + if (*(uint16_t*)(buf + 2) != (nb - 4)) + { + return 1; + } + + uint16_t tail_size = *(uint16_t*)(buf + 2); + + if (tail_size < PICA_PROTO_CALL_PACKET_HDRSIZE) + { + return 1; + } + + uint16_t seq_num = *(uint16_t*)(buf + 4); + uint32_t timestamp = *(uint32_t*)(buf + 4 + PICA_PROTO_CALL_PACKET_SEQNUM_SIZE); + uint16_t pkt_size = tail_size - PICA_PROTO_CALL_PACKET_HDRSIZE; + + callbacks.call_video_packet_cb(chan->peer_id, seq_num, timestamp, pkt_size, buf + 4 + PICA_PROTO_CALL_PACKET_HDRSIZE); + + return 1; +} + static int c2n_optstage7_multilogin(struct PICA_c2n *c2n) { struct PICA_proto_msg *mp; @@ -1880,7 +2872,7 @@ static int directc2c_stage2_starttls(struct PICA_directc2c *d, struct PICA_c2c * d->ssl = SSL_new(c2c->acc->ctx); SSL_set_fd(d->ssl, d->sck); - SSL_set_verify(d->ssl, SSL_VERIFY_PEER, verify_callback); + SSL_set_verify(d->ssl, SSL_VERIFY_PEER, PICA_verify_callback); SSL_set_verify_depth(d->ssl, 1); ret = SSL_connect(d->ssl); @@ -1902,6 +2894,13 @@ static int directc2c_stage2_starttls(struct PICA_directc2c *d, struct PICA_c2c * } +void PICA_c2n_set_directc2c(struct PICA_c2n *c2n, enum PICA_directc2c_config direct_c2c_mode, + struct PICA_listener *l) +{ + c2n->directc2c_config = direct_c2c_mode; + c2n->directc2c_listener = direct_c2c_mode == PICA_DIRECTC2C_CFG_ALLOWINCOMING ? l : NULL; +} + int PICA_new_c2n(const struct PICA_acc *acc, const char *nodeaddr, unsigned int port, enum PICA_directc2c_config direct_c2c_mode, int multilogin, struct PICA_listener *l, struct PICA_c2n **ci) @@ -1922,14 +2921,9 @@ int PICA_new_c2n(const struct PICA_acc *acc, const char *nodeaddr, unsigned int cid->acc = acc; - cid->directc2c_config = direct_c2c_mode; + PICA_c2n_set_directc2c(cid, direct_c2c_mode, l); cid->multilogin_policy = multilogin; - if (direct_c2c_mode == PICA_DIRECTC2C_CFG_ALLOWINCOMING) - { - cid->directc2c_listener = l; - } - cid->read_buf = calloc(PICA_CONNREADBUFSIZE, 1);//(2) if (!cid->read_buf) { @@ -1988,6 +2982,7 @@ int PICA_new_c2n(const struct PICA_acc *acc, const char *nodeaddr, unsigned int } IOCTLSETNONBLOCKINGSOCKET(cid->sck_comm, 1); + SETTCPNODELAY(cid->sck_comm); cid->state = PICA_C2N_STATE_CONNECTING; @@ -2421,7 +3416,7 @@ static struct PICA_c2c * find_matching_c2c(struct PICA_c2n *c2n, struct PICA_dir static int directc2c_verify_peer_cert(struct PICA_directc2c *d, struct PICA_c2c *c2c) { PICA_TRACEFUNC - return verify_peer_cert_common(&d->peer_cert, d->ssl, c2c->peer_id); + return PICA_verify_peer_cert_common(&d->peer_cert, d->ssl, c2c->peer_id); } static void process_directc2c(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds) @@ -2440,10 +3435,25 @@ static void process_directc2c(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds) while(d) { + struct PICA_directc2c *dnext = d->next; + if (d->state == PICA_DIRECTC2C_CONNSTATE_ACTIVE) { - if ((c2c = find_matching_c2c(c2n, d)) && (verify_peer_cert_common(&d->peer_cert, d->ssl, c2c->peer_id) == PICA_OK)) + /* d leaves the listener list either way - adopted by a c2c or + * closed. Splice it out first, using the next pointer captured + * above, so nothing is read back out of a freed node. + */ + *pdprev = dnext; + d->next = NULL; + + char addrstr[PICA_DIRECTC2C_ADDRSTRSIZE]; + + directc2c_addrstr(&d->addr, addrstr); + + if ((c2c = find_matching_c2c(c2n, d)) && (PICA_verify_peer_cert_common(&d->peer_cert, d->ssl, c2c->peer_id) == PICA_OK)) { + fprintf(stderr, "directc2c: incoming connection from %s accepted\n", addrstr); + if (c2c->direct) PICA_close_directc2c(c2c->direct); @@ -2454,6 +3464,7 @@ static void process_directc2c(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds) if (ret != PICA_OK) { PICA_close_directc2c(d); + c2c->direct = NULL; c2c->directc2c_state = PICA_DIRECTC2C_STATE_INACTIVE; } else @@ -2461,21 +3472,21 @@ static void process_directc2c(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds) callbacks.direct_c2c_established_cb(c2c->peer_id, SSL_get_cipher_name(d->ssl)); c2c->directc2c_state = PICA_DIRECTC2C_STATE_ACTIVE; } - - //remove from listener's list - *pdprev = d->next; - d->next = 0; } else { - //close and remove from listener's list - *pdprev = d->next; + fprintf(stderr, "directc2c: incoming connection from %s rejected: %s\n", addrstr, + c2c ? "the certificate is not the peer's" : "no connection is waiting for it"); PICA_close_directc2c(d); } + /* pdprev stays put: d was spliced out above */ + } + else + { + pdprev = &d->next; } - pdprev = &d->next; - d = d->next; - //-- killptr? + + d = dnext; } } //process outgoing connections @@ -2484,7 +3495,7 @@ static void process_directc2c(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds) { if (c2c->directc2c_state == PICA_DIRECTC2C_STATE_FAILEDTOCONNECT) { - if (c2c->outgoing == PICA_C2C_OUTGOING && c2c->conn->directc2c_config == PICA_DIRECTC2C_CFG_ALLOWINCOMING) + if (c2c->outgoing == PICA_C2C_OUTGOING && c2c->directc2c_config == PICA_DIRECTC2C_CFG_ALLOWINCOMING) { ret = PICA_send_directc2cfailed(c2c); @@ -2499,9 +3510,28 @@ static void process_directc2c(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds) if (c2c->directc2c_state == PICA_DIRECTC2C_STATE_CONNECTING) { + char addrstr[PICA_DIRECTC2C_ADDRSTRSIZE]; + d = c2c->direct; ret = PICA_OK; + directc2c_addrstr(&d->addr, addrstr); + + /* On to the next address, see PICA_DIRECTC2C_CONNECT_TIMEOUT - + * unless the socket has something for us: the event loop may + * not have run for a while, and a connection that has made it + * meanwhile is not a late one. + */ + if ((d->state == PICA_DIRECTC2C_CONNSTATE_CONNECTING || d->state == PICA_DIRECTC2C_CONNSTATE_WAITINGTLS) + && PICA_media_now() >= d->attempt_deadline + && !FD_ISSET(d->sck, wfds) && !FD_ISSET(d->sck, rfds)) + { + fprintf(stderr, "directc2c: connection to %s failed: %s timed out after %u ms\n", addrstr, + d->state == PICA_DIRECTC2C_CONNSTATE_CONNECTING ? "TCP connection" : "TLS handshake", + (unsigned int)(PICA_media_now() - d->attempt_started)); + d->state = PICA_DIRECTC2C_CONNSTATE_FAILED; + } + switch(d->state) { case PICA_DIRECTC2C_CONNSTATE_CONNECTING: @@ -2512,10 +3542,26 @@ static void process_directc2c(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds) if (ret == PICA_OK) { + fprintf(stderr, "directc2c: TCP connection to %s made in %u ms, TLS handshake\n", addrstr, + (unsigned int)(PICA_media_now() - d->attempt_started)); + + /* the TLS handshake gets the rest of the full timeout, + * also for a private address, see + * PICA_DIRECTC2C_LAN_CONNECT_TIMEOUT */ + d->attempt_deadline = d->attempt_started + PICA_DIRECTC2C_CONNECT_TIMEOUT; + ret = directc2c_stage2_starttls(d, c2c); + + if (ret != PICA_OK) + { + fprintf(stderr, "directc2c: connection to %s failed: TLS could not be started\n", addrstr); + d->state = PICA_DIRECTC2C_CONNSTATE_FAILED; + } } else { + fprintf(stderr, "directc2c: connection to %s failed: TCP connection refused or unreachable\n", + addrstr); d->state = PICA_DIRECTC2C_CONNSTATE_FAILED; } } @@ -2532,6 +3578,7 @@ static void process_directc2c(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds) if (ret != PICA_OK) { + fprintf(stderr, "directc2c: connection to %s failed: TLS handshake failed\n", addrstr); d->state = PICA_DIRECTC2C_CONNSTATE_FAILED; } @@ -2542,6 +3589,7 @@ static void process_directc2c(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds) if (ret != PICA_OK) { + fprintf(stderr, "directc2c: connection to %s failed: the certificate is not the peer's\n", addrstr); d->state = PICA_DIRECTC2C_CONNSTATE_FAILED; break; } @@ -2550,10 +3598,14 @@ static void process_directc2c(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds) if (ret != PICA_OK) { + fprintf(stderr, "directc2c: connection to %s failed: could not send 0x0D\n", addrstr); d->state = PICA_DIRECTC2C_CONNSTATE_FAILED; break; } + fprintf(stderr, "directc2c: connection to %s established in %u ms\n", addrstr, + (unsigned int)(PICA_media_now() - d->attempt_started)); + d->state = PICA_DIRECTC2C_CONNSTATE_ACTIVE; } @@ -2591,38 +3643,68 @@ static void process_directc2c(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds) } } -static void listener_add_connection(struct PICA_listener *lst, SOCKET s) +static void listener_add_connection(struct PICA_listener *lst, SOCKET s, const struct sockaddr_in *peer_addr) { PICA_TRACEFUNC struct PICA_directc2c *nc; + unsigned int count = 0; int ret; + /* Bound the number of half-open incoming connections, so a peer cannot + * exhaust memory/descriptors by opening many and never finishing them. + */ + for (nc = lst->accepted_connections; nc; nc = nc->next) + if (++count >= PICA_DIRECTC2C_MAX_ACCEPTED) + { + CLOSE(s); + return; + } + nc = calloc(1, sizeof(struct PICA_directc2c)); + if (!nc) + { + CLOSE(s); + return; + } + nc->is_outgoing = PICA_DIRECTC2C_INCOMING; nc->sck = s; + /* Kept for the media connection: it is the only place the peer's address + * is known on this side, and datagrams arriving from anywhere else + * cannot belong to a call with this peer. The port number is the peer's + * outgoing TCP port and is not used. + */ + nc->addr = *peer_addr; nc->ssl = SSL_new(lst->acc->ctx); nc->state = PICA_DIRECTC2C_CONNSTATE_NEW; + nc->accepted_tmst = time(0); + + if (!nc->ssl) + { + CLOSE(s); + free(nc); + return; + } SSL_set_fd(nc->ssl, nc->sck); - SSL_set_verify(nc->ssl, SSL_VERIFY_PEER, verify_callback); + SSL_set_verify(nc->ssl, SSL_VERIFY_PEER, PICA_verify_callback); SSL_set_verify_depth(nc->ssl, 1); ret = SSL_accept(nc->ssl); - if (ret == 0) + if (ret <= 0) { - free(nc); - return; - } - - if (ret < 0) - { - ret = SSL_get_error(nc->ssl, ret); - - if (ret != SSL_ERROR_WANT_READ && ret != SSL_ERROR_WANT_WRITE) + /* Only a WANT_READ/WANT_WRITE means the handshake is merely unfinished; + * anything else is a real failure. Free the SSL object and close the + * socket on the failure path - dropping only the struct would leak both. + */ + if (!(ret < 0 && (SSL_get_error(nc->ssl, ret) == SSL_ERROR_WANT_READ + || SSL_get_error(nc->ssl, ret) == SSL_ERROR_WANT_WRITE))) { + SSL_free(nc->ssl); + CLOSE(nc->sck); free(nc); return; } @@ -2690,7 +3772,8 @@ static int process_listener(struct PICA_listener *lst, fd_set *rfds, fd_set *wfd if (s >= 0) { IOCTLSETNONBLOCKINGSOCKET(s, 1); - listener_add_connection(lst, s); + SETTCPNODELAY(s); + listener_add_connection(lst, s, &addr); } } @@ -2706,6 +3789,14 @@ static int process_listener(struct PICA_listener *lst, fd_set *rfds, fd_set *wfd { kill_ptr = conn; } + else if (conn->peer_cert == NULL + && (time(0) - conn->accepted_tmst) > PICA_DIRECTC2C_ACCEPT_TIMEOUT) + { + /* peer_cert is set only once the handshake completes, so a NULL + * one past the timeout is a connection that never finished TLS. + */ + kill_ptr = conn; + } if (!kill_ptr) pprevconn = &conn->next; @@ -2813,6 +3904,8 @@ int PICA_event_loop(struct PICA_c2n **connections, int timeout) ic2c = ic2c->next; } + PICA_media_fdset(*ic2n, &rfds, &nfds); + ic2n++; } @@ -2890,11 +3983,17 @@ int PICA_event_loop(struct PICA_c2n **connections, int timeout) } } - //processing direct c2c connections associated with current c2n - if ((*ic2n)->directc2c_config != PICA_DIRECTC2C_CFG_DISABLED) - { - process_directc2c(*ic2n, &rfds, &wfds); - } + /* processing direct c2c connections associated with current c2n - + * even with them disabled now, those of c2c connections made + * before that */ + process_directc2c(*ic2n, &rfds, &wfds); + + //processing media connections of calls in progress + PICA_media_process(*ic2n, &rfds); + + process_calls(*ic2n); + + process_udpaddr(*ic2n); } ic2n++; } @@ -2950,10 +4049,16 @@ int PICA_write_c2c(struct PICA_c2c *chn) { int ret = PICA_ERRINVARG; - if (chn->state != PICA_C2C_STATE_ACTIVE && chn->state != PICA_C2C_STATE_CONNID && chn->state != PICA_C2C_STATE_WAITINGREP) + if (chn->state != PICA_C2C_STATE_ACTIVE && chn->state != PICA_C2C_STATE_CONNID + && chn->state != PICA_C2C_STATE_WAITINGREP && chn->state != PICA_C2C_STATE_WAITINGC2CPROTOVER) { + /* WAITINGC2CPROTOVER is a legitimate write state: the callee sends + * VERDIFFER from there on a protocol-version mismatch. Any state that + * really is unexpected closes this one channel - a library must not + * take the whole host process down over a peer-driven condition. + */ fputs("PICA_write_c2c() was called for incorrect state!\n", stderr); - exit(-1); + return PICA_ERRSERV; } { @@ -3021,8 +4126,9 @@ int PICA_read_c2c(struct PICA_c2c *chn) if (chn->state != PICA_C2C_STATE_WAITINGREP && chn->state != PICA_C2C_STATE_WAITINGC2CPROTOVER && chn->state != PICA_C2C_STATE_ACTIVE) { + /* Close this one channel rather than exit()-ing the host process. */ fputs("PICA_read_c2c() was called for incorrect state!\n", stderr); - exit(-1); + return PICA_ERRSERV; } if (chn->switched_to_directc2c_read) @@ -3126,21 +4232,96 @@ struct PICA_proto_msg* c2c_writebuf_push(struct PICA_c2c *chn, unsigned int msgi return mp; } +/* Adds an address to a list under construction, unless it is in it already + * - an interface address that is public is what UPnP reports too, when the + * IGD runs on this very machine. + */ +static void addrlist_add(struct PICA_listener_addr *list, int *count, in_addr_t addr, uint16_t port) +{ + int i; + + if (addr == INADDR_ANY || port == 0 || *count >= PICA_DIRECTC2C_MAX_ADDRS) + return; + + for (i = 0; i < *count; i++) + if (list[i].addr == addr && list[i].port == port) + return; + + list[*count].addr = addr; + list[*count].port = port; + list[*count].is_upnp = 0; + (*count)++; +} + +/* The addresses to announce in 0x0B, see the description of the message: + * private ones first, then public ones. Built when it is sent rather than + * once, since interfaces come and go - a VPN connected, a laptop moved to + * another network. + */ +static int listener_addrlist(const struct PICA_listener *l, struct PICA_listener_addr *list) +{ + int count = 0; + int i; + + if (l->addrs_manual) + { + for (i = 0; i < l->addrs_count; i++) + { + if (l->addrs[i].is_upnp) + addrlist_add(list, &count, l->upnp_addr, l->upnp_port); + else + addrlist_add(list, &count, l->addrs[i].addr, l->addrs[i].port); + } + } + else + { + in_addr_t ifaddrs[PICA_IFADDRS_MAX]; + int n; + + n = PICA_get_ifaddrs_ipv4(ifaddrs, PICA_IFADDRS_MAX); + + for (i = 0; i < n; i++) + addrlist_add(list, &count, ifaddrs[i], htons((uint16_t)l->local_port)); + + addrlist_add(list, &count, l->upnp_addr, l->upnp_port); + } + + return count; +} + int PICA_send_directc2caddrlist(struct PICA_c2c *chn) { PICA_TRACEFUNC - if (chn->conn->directc2c_config == PICA_DIRECTC2C_CFG_ALLOWINCOMING && chn->conn->directc2c_listener) + if (chn->directc2c_config == PICA_DIRECTC2C_CFG_ALLOWINCOMING && chn->conn->directc2c_listener) { struct PICA_proto_msg *mp; - //TODO send all possible interface addresses, not one - unsigned int len = PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE; + struct PICA_listener_addr list[PICA_DIRECTC2C_MAX_ADDRS]; + int count, i; + unsigned int len; + unsigned char *p; + + count = listener_addrlist(chn->conn->directc2c_listener, list); + + /* nothing a peer could connect to */ + if (count == 0) + return PICA_OK; + + len = count * PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE; if ((mp = c2c_writebuf_push(chn, PICA_PROTO_DIRECTC2C_ADDRLIST, len + 4))) { - *((uint16_t*)mp->tail) = len; - *((uint8_t*)mp->tail + 2) = PICA_PROTO_DIRECTC2C_IPV4; - *((uint32_t*)(mp->tail + 3)) = chn->conn->directc2c_listener->public_addr_ipv4; - *((uint16_t*)(mp->tail + 7)) = htons(chn->conn->directc2c_listener->public_port); + mp->tail[0] = len & 0xFF; + mp->tail[1] = (len >> 8) & 0xFF; + + p = mp->tail + 2; + + for (i = 0; i < count; i++) + { + *p++ = PICA_PROTO_DIRECTC2C_IPV4; + memcpy(p, &list[i].addr, 4); + memcpy(p + 4, &list[i].port, 2); + p += 6; + } chn->directc2c_state = PICA_DIRECTC2C_STATE_WAITINGINCOMING; } @@ -3403,6 +4584,256 @@ int PICA_send_file_fragment(struct PICA_c2c *chn) return PICA_OK; } + +int PICA_start_call(struct PICA_c2c *chn) +{ + int ret; + + if (chn->call_state != PICA_CALL_STATE_IDLE) + return PICA_ERRCALLINPROGRESS; + + ret = PICA_media_call_prepare(chn, 1, NULL, 0); + + if (ret != PICA_OK) + return ret; + + chn->call_state = PICA_CALL_STATE_CALLING; + + /* 0x70 carries the address the node sees the call socket at, so it + * waits for the node's answer - normally one round trip - for a limited + * time, see process_calls() + */ + chn->media_call->pending_deadline = PICA_media_now() + PICA_MEDIA_LEARN_TIMEOUT; + + if (!PICA_media_call_ready(chn)) + { + chn->media_call->pending_msg = PICA_PROTO_CALLREQ; + return PICA_OK; + } + + ret = call_send_info(chn, PICA_PROTO_CALLREQ); + + if (ret != PICA_OK) + call_release(chn); + + return ret; +} + +int PICA_pickup_call(struct PICA_c2c *chn) +{ + int ret; + + if (chn->call_state != PICA_CALL_STATE_INCOMINGCALL) + return PICA_ERRCALLNOTINPROGRESS; + + /* The address of the call socket has been asked for since the call + * started ringing and is usually known by now. If it is not, 0x71 waits + * for it a little longer; the call counts as answered for the user + * meanwhile. + */ + if (chn->media_call) + chn->media_call->pending_deadline = PICA_media_now() + PICA_MEDIA_LEARN_TIMEOUT; + + if (!PICA_media_call_ready(chn)) + { + chn->media_call->pending_msg = PICA_PROTO_CALLANS; + chn->call_state = PICA_CALL_STATE_ANSWERING; + return PICA_OK; + } + + ret = call_answered(chn); + + return ret; +} + +int PICA_reject_call(struct PICA_c2c *chn) +{ + struct PICA_proto_msg *mp; + + if (chn->call_state != PICA_CALL_STATE_INCOMINGCALL) + return PICA_ERRCALLNOTINPROGRESS; + + if ((mp = c2c_writebuf_push(chn, PICA_PROTO_CALLREJ, PICA_PROTO_CALLREJ_SIZE))) + { + RAND_pseudo_bytes(mp->tail, 2); + } + else + { + return PICA_ERRNOMEM; + } + + call_release(chn); + + return PICA_OK; +} + +int PICA_hangup_call(struct PICA_c2c *chn) +{ + struct PICA_proto_msg *mp; + + if (chn->call_state == PICA_CALL_STATE_IDLE) + return PICA_ERRCALLNOTINPROGRESS; + + /* A call whose 0x70 is still waiting to be sent does not exist for the + * peer yet, and a 0x73 would be a protocol error to it. + */ + if (chn->call_state == PICA_CALL_STATE_CALLING && chn->media_call + && chn->media_call->pending_msg == PICA_PROTO_CALLREQ) + { + call_release(chn); + return PICA_OK; + } + + if ((mp = c2c_writebuf_push(chn, PICA_PROTO_CALLFIN, PICA_PROTO_CALLFIN_SIZE))) + { + RAND_pseudo_bytes(mp->tail, 2); + } + else + { + return PICA_ERRNOMEM; + } + + // handle incoming last stream packets? + call_release(chn); + + return PICA_OK; +} + +static int call_send_audio_params(struct PICA_c2c *chn, const char *codec_name, uint16_t sample_rate) +{ + struct PICA_proto_msg *mp; + + if ((mp = c2c_writebuf_push(chn, PICA_PROTO_CALL_AUDIOPARAM, PICA_PROTO_CALL_AUDIOPARAM_SIZE))) + { + strncpy(mp->tail, codec_name, PICA_PROTO_CALL_CODECNAMESIZE); + *((uint16_t*)(mp->tail + PICA_PROTO_CALL_CODECNAMESIZE)) = sample_rate; + + } + else + { + return PICA_ERRNOMEM; + } + + return PICA_OK; +} + +int PICA_set_call_audio_params(struct PICA_c2c *chn, const char *codec_name, uint16_t sample_rate) +{ + struct PICA_media_call *mc = chn->media_call; + + /* kept until 0x71 is out, see call_answered() */ + if (chn->call_state == PICA_CALL_STATE_ANSWERING && mc) + { + snprintf(mc->audio_codec, sizeof(mc->audio_codec), "%s", codec_name); + mc->audio_sample_rate = sample_rate; + mc->audio_params_pending = 1; + return PICA_OK; + } + + if (chn->call_state != PICA_CALL_STATE_ACTIVE) + return PICA_ERRCALLNOTINPROGRESS; + + return call_send_audio_params(chn, codec_name, sample_rate); +} + +static int call_send_video_params(struct PICA_c2c *chn, const char *codec_name, uint16_t width, uint16_t height) +{ + struct PICA_proto_msg *mp; + + if ((mp = c2c_writebuf_push(chn, PICA_PROTO_CALL_VIDEOPARAM, PICA_PROTO_CALL_VIDEOPARAM_SIZE))) + { + strncpy(mp->tail, codec_name, PICA_PROTO_CALL_CODECNAMESIZE); + *((uint16_t*)(mp->tail + PICA_PROTO_CALL_CODECNAMESIZE)) = width; + *((uint16_t*)(mp->tail + PICA_PROTO_CALL_CODECNAMESIZE + sizeof(width))) = height; + + } + else + { + return PICA_ERRNOMEM; + } + + return PICA_OK; +} + +int PICA_set_call_video_params(struct PICA_c2c *chn, const char *codec_name, uint16_t width, uint16_t height) +{ + struct PICA_media_call *mc = chn->media_call; + + if (chn->call_state == PICA_CALL_STATE_ANSWERING && mc) + { + snprintf(mc->video_codec, sizeof(mc->video_codec), "%s", codec_name); + mc->video_width = width; + mc->video_height = height; + mc->video_params_pending = 1; + return PICA_OK; + } + + if (chn->call_state != PICA_CALL_STATE_ACTIVE) + return PICA_ERRCALLNOTINPROGRESS; + + return call_send_video_params(chn, codec_name, width, height); +} + +static int PICA_send_call_packet(struct PICA_c2c *chn, unsigned int msgid, uint16_t seq_num, + uint32_t timestamp, const char *buf, unsigned int len) +{ + struct PICA_proto_msg *mp; + + if (chn->call_state != PICA_CALL_STATE_ACTIVE) + return PICA_ERRCALLNOTINPROGRESS; + + if (len > PICA_media_max_payload(chn)) + return PICA_ERRMSGSIZE; + + if (PICA_media_is_active(chn)) + { + /* Written to the socket here and now instead of being appended to + * the write buffer the event loop drains: a datagram never blocks + * for long, and waiting for the next pass of the event loop would + * add more delay to every packet than the rest of the call path + * costs together. + */ + unsigned char pkt[PICA_MEDIA_LINK_MTU]; + unsigned int pktlen = 4 + PICA_PROTO_CALL_PACKET_HDRSIZE + len; + + if (pktlen > sizeof(pkt)) + return PICA_ERRMSGSIZE; + + pkt[0] = pkt[1] = msgid; + *((uint16_t*)(pkt + 2)) = len + PICA_PROTO_CALL_PACKET_HDRSIZE; + *((uint16_t*)(pkt + 4)) = seq_num; + *((uint32_t*)(pkt + 4 + PICA_PROTO_CALL_PACKET_SEQNUM_SIZE)) = timestamp; + memcpy(pkt + 4 + PICA_PROTO_CALL_PACKET_HDRSIZE, buf, len); + + return PICA_media_send(chn, pkt, pktlen); + } + + if ((mp = c2c_writebuf_push(chn, msgid, len + 4 + PICA_PROTO_CALL_PACKET_HDRSIZE))) + { + *((uint16_t*)mp->tail) = len + PICA_PROTO_CALL_PACKET_HDRSIZE; + *((uint16_t*)(mp->tail + 2)) = seq_num; + *((uint32_t*)(mp->tail + 2 + PICA_PROTO_CALL_PACKET_SEQNUM_SIZE)) = timestamp; + memcpy(mp->tail + 2 + PICA_PROTO_CALL_PACKET_HDRSIZE, buf, len); + + } + else + { + return PICA_ERRNOMEM; + } + + return PICA_OK; +} + +int PICA_send_audio_packet(struct PICA_c2c *chn, uint16_t seq_num, uint32_t timestamp, const char *buf, unsigned int len) +{ + return PICA_send_call_packet(chn, PICA_PROTO_CALL_AUDIO_PACKET, seq_num, timestamp, buf, len); +} + +int PICA_send_video_packet(struct PICA_c2c *chn, uint16_t seq_num, uint32_t timestamp, const char *buf, unsigned int len) +{ + return PICA_send_call_packet(chn, PICA_PROTO_CALL_VIDEO_PACKET, seq_num, timestamp, buf, len); +} + void PICA_close_directc2c(struct PICA_directc2c *d) { PICA_TRACEFUNC @@ -3450,6 +4881,9 @@ void PICA_close_c2c(struct PICA_c2c *chn) //puts("PICA_close_c2c_chkp1");//debug + PICA_media_close(chn); + PICA_media_call_free(chn); + if (chn -> sendfile_stream) fclose(chn -> sendfile_stream); @@ -3523,7 +4957,9 @@ void PICA_close_acc(struct PICA_acc *a) void PICA_close_listener(struct PICA_listener *l) { CLOSE(l->sck_listener); - free(l->public_addr_dns); + + if (l->media) + PICA_media_listener_close(l->media); while(l->accepted_connections) { diff --git a/PICA_client.h b/PICA_client.h index 88bb52c..655f671 100644 --- a/PICA_client.h +++ b/PICA_client.h @@ -20,6 +20,7 @@ #include <time.h> #include "PICA_id.h" +#include "PICA_proto.h" #ifdef WIN32 @@ -50,6 +51,7 @@ typedef u_short in_port_t; #include <sys/socket.h> #include <sys/ioctl.h> #include <netinet/in.h> +#include <netinet/tcp.h> #include <arpa/inet.h> #include <netdb.h> #include <signal.h> @@ -118,6 +120,9 @@ typedef u_short in_port_t; #define PICA_ERRINVPKEYFILE -23 #define PICA_ERRTIMEDOUT -24 +#define PICA_ERRCALLINPROGRESS -25 +#define PICA_ERRCALLNOTINPROGRESS -26 + //#define PICA_CHNMSGBUFLEN 104 #define PICA_CHANREADBUFSIZE 65536 @@ -138,6 +143,40 @@ typedef u_short in_port_t; #define PICA_C2C_ACTIVATE_TIMEOUT 30 +/* PICA_request_udp_address(): how long the node's answer is waited for, and + * how many datagrams are sent to the node, one per second, until it comes. + */ +#define PICA_UDPADDR_TIMEOUT 10 +#define PICA_UDPADDR_PROBES 3 + +/* How long an incoming direct connection may take to finish its TLS handshake + * before it is reaped, and how many half-open incoming connections may sit in + * a listener at once - both bound a peer's ability to tie up the listener. + */ +#define PICA_DIRECTC2C_ACCEPT_TIMEOUT 30 +#define PICA_DIRECTC2C_MAX_ACCEPTED 32 + +/* How long an outgoing direct connection may take to connect and finish its + * TLS handshake before the next announced address is tried, in milliseconds. + * Without it, an address that silently drops the packets would hold up the + * addresses after it for as long as the system keeps retrying the + * connection, minutes. + */ +#define PICA_DIRECTC2C_CONNECT_TIMEOUT 5000 + +/* How long the TCP connection to a private address may take, in + * milliseconds. Only one on a private network this host is on is tried at + * all, and there the round trip is a matter of a few milliseconds; the TLS + * handshake, which can take longer on a slow machine, then gets the rest of + * PICA_DIRECTC2C_CONNECT_TIMEOUT. + */ +#define PICA_DIRECTC2C_LAN_CONNECT_TIMEOUT 200 + +/* Most addresses of a received 0x0B message that are tried, and most that + * a listener announces. + */ +#define PICA_DIRECTC2C_MAX_ADDRS 32 + #define PICA_C2C_INCOMING 0 #define PICA_C2C_OUTGOING 1 @@ -146,6 +185,8 @@ typedef u_short in_port_t; struct PICA_c2n; struct PICA_c2c; +struct PICA_media_channel; +struct PICA_media_listener; struct PICA_acc { @@ -155,6 +196,8 @@ struct PICA_acc unsigned char id[PICA_ID_SIZE]; SSL_CTX* ctx; SSL_CTX* anon_ctx; + /** used for mediac2c connections, see PICA_media.h */ + SSL_CTX* dtls_ctx; const char *pkey_file; const char *cert_file; int (*password_cb)(char *buf, int size, int rwflag, void *userdata); @@ -171,6 +214,15 @@ enum PICA_c2n_state PICA_C2N_STATE_CONNECTED }; +enum PICA_udpaddr_state +{ + PICA_UDPADDR_STATE_IDLE = 0, + /* request sent, waiting for the node to issue a token */ + PICA_UDPADDR_STATE_WAITINGTOKEN, + /* sending the token to the node's UDP port, waiting for the address */ + PICA_UDPADDR_STATE_PROBING +}; + enum PICA_directc2c_config { PICA_DIRECTC2C_CFG_DISABLED, @@ -206,6 +258,21 @@ struct PICA_c2n unsigned char node_ver_major, node_ver_minor; int disconnect_on_empty_write_buf; int want_write; + + int tcpaddr_requested; + + /* request made by PICA_request_udp_address() */ + enum PICA_udpaddr_state udpaddr_state; + SOCKET udpaddr_sck; + unsigned char udpaddr_token[PICA_PROTO_MYUDPADDR_TOKENSIZE]; + time_t udpaddr_started; + time_t udpaddr_last_probe; + int udpaddr_probes_sent; + /* The call the request was made for by the library itself, or NULL when + * the application made it. The answer goes to that call instead of + * udp_address_cb. + */ + struct PICA_c2c *udpaddr_c2c; }; enum PICA_c2c_state @@ -239,6 +306,20 @@ enum PICA_directc2c_connection_state PICA_DIRECTC2C_CONNSTATE_FAILED }; +enum PICA_call_state +{ + PICA_CALL_STATE_IDLE = 0, + PICA_CALL_STATE_CALLING, + PICA_CALL_STATE_INCOMINGCALL, + /* Answered by the user, but 0x71 not sent yet: it waits for the node to + * report the address of the media socket, see PICA_media_call. Call + * parameters set meanwhile are sent right after 0x71, media packets are + * dropped. + */ + PICA_CALL_STATE_ANSWERING, + PICA_CALL_STATE_ACTIVE +}; + struct PICA_directc2c { int is_outgoing; @@ -254,6 +335,20 @@ struct PICA_directc2c enum PICA_directc2c_connection_state state; + /* PICA_media_now() when the connection to the current address was + * started, and when it has to be connected by - the TCP connection, or + * in PICA_DIRECTC2C_CONNSTATE_WAITINGTLS the TLS handshake as well, see + * PICA_DIRECTC2C_CONNECT_TIMEOUT + */ + uint64_t attempt_started; + uint64_t attempt_deadline; + + /* When this incoming connection was accepted, used to reap it if its TLS + * handshake never completes. Only meaningful for accepted (incoming) + * connections held in a listener's accepted_connections list. + */ + time_t accepted_tmst; + struct PICA_directc2c *next; }; @@ -280,6 +375,10 @@ struct PICA_c2c struct PICA_c2c *next; struct PICA_c2c *prev; enum PICA_c2c_state state; + /* the c2n connection's directc2c_config when this connection was made; + * the direct connection is negotiated by it, whatever the setting is + * changed to later on */ + enum PICA_directc2c_config directc2c_config; enum PICA_directc2c_state directc2c_state; time_t timestamp; int sendfilestate; @@ -301,6 +400,26 @@ struct PICA_c2c int want_write; unsigned int directc2c_write_barrier_pos; unsigned int directc2c_write_before_barrier_pos; + + enum PICA_call_state call_state; + int call_audio_params_are_set; + int call_video_params_are_set; + /** media connection of the call in progress, see PICA_media.h */ + struct PICA_media_channel *media; + /** what the call in progress needs for UDP hole punching, see PICA_media.h */ + struct PICA_media_call *media_call; +}; + +/* One entry of a manually configured address list, see + * PICA_listener_set_addrlist() + */ +struct PICA_listener_addr +{ + in_addr_t addr; + /** network byte order */ + uint16_t port; + /** stands for the external address and port of the UPnP port mapping */ + int is_upnp; }; struct PICA_listener @@ -308,13 +427,28 @@ struct PICA_listener const struct PICA_acc *acc; SOCKET sck_listener; - int public_port; + /** TCP and UDP port listened on */ int local_port; - in_addr_t public_addr_ipv4; - const char *public_addr_dns; + /** The addresses announced in 0x0B. Automatic configuration when 0: the + * addresses of the network interfaces with local_port, then the UPnP + * mapping. Otherwise the list below, in its order. + */ + int addrs_manual; + struct PICA_listener_addr addrs[PICA_DIRECTC2C_MAX_ADDRS]; + int addrs_count; + + /** external address and port of the UPnP port mapping made for this + * listener, network byte order; 0 when there is none */ + in_addr_t upnp_addr; + uint16_t upnp_port; struct PICA_directc2c *accepted_connections; + + /** listens on the UDP port with the same number, see PICA_media.h. + * NULL if that port could not be opened. + */ + struct PICA_media_listener *media; }; struct PICA_client_callbacks @@ -396,6 +530,60 @@ struct PICA_client_callbacks void (*multilogin_cb)(uint64_t timestamp, void *addr_bin, const char *addr_str, uint16_t port); void (*direct_c2c_established_cb)(const unsigned char *peer_id, const char *ciphersuitename); + + void (*incoming_call_cb)(const unsigned char *peer_id); + + void (*call_picked_up_cb)(const unsigned char *peer_id); + + void (*call_rejected_cb)(const unsigned char *peer_id); + + void (*call_hangup_cb)(const unsigned char *peer_id); + + void (*call_audio_params_cb)(const unsigned char *peer_id, const char *codec, uint16_t sample_rate); + + void (*call_video_params_cb)(const unsigned char *peer_id, const char *codec, uint16_t width, uint16_t height); + + void (*call_audio_packet_cb)(const unsigned char *peer_id, uint16_t seq_num, uint32_t timestamp, uint16_t size, const char *pkt_data); + + void (*call_video_packet_cb)(const unsigned char *peer_id, uint16_t seq_num, uint32_t timestamp, uint16_t size, const char *pkt_data); + + /** + * The media packets of the call in progress started or stopped being + * carried over a mediac2c connection. + * \param transport PICA_CALL_TRANSPORT_C2C or PICA_CALL_TRANSPORT_MEDIAC2C + * \param ciphersuitename ciphersuite of the media connection, NULL when + * the transport is not mediac2c + * \param max_payload largest amount of data that can be passed to + * PICA_send_audio_packet()/PICA_send_video_packet() from now on + */ + void (*call_media_transport_cb)(const unsigned char *peer_id, int transport, + const char *ciphersuitename, unsigned int max_payload); + + /* The callbacks below are optional and can be left NULL. */ + + /** + * The node's answer to PICA_request_tcp_address(): the address and port + * the c2n connection comes from, as the node sees them. + * \param type address type, PICA_PROTO_MYTCPADDR_{IPV4,IPV6} + * \param addr_bin address in binary form, network byte order + * \param addr_str address in string format, zero-terminated + * \param port port number, in host byte order + */ + void (*tcp_address_cb)(struct PICA_c2n *c2n, int type, void *addr_bin, const char *addr_str, uint16_t port); + + /** + * The outcome of PICA_request_udp_address(). + * \param status PICA_OK - the node saw a datagram from the socket coming + * from the address described by the remaining arguments, which have the + * same meaning as in tcp_address_cb, except that type is + * PICA_PROTO_MYUDPADDR_{IPV4,IPV6}. PICA_ERRTIMEDOUT - no answer; the + * node does not offer this, or UDP does not get through to it. The + * remaining arguments are zero then. + * + * The address is what the node saw, and is not authenticated: it is only + * good as a place for a peer to try, never as a proof of who is there. + */ + void (*udp_address_cb)(struct PICA_c2n *c2n, int status, int type, void *addr_bin, const char *addr_str, uint16_t port); }; @@ -422,17 +610,54 @@ int PICA_new_c2n(const struct PICA_acc *acc, const char *nodeaddr, unsigned int struct PICA_listener *l, struct PICA_c2n **ci); int PICA_new_c2c(struct PICA_c2n *ci, const unsigned char *peer_id, struct PICA_listener *l, struct PICA_c2c **chn); - /** - * Opens socket to listen for incoming direct c2c connections bypassing nodes + +/** + * Changes the direct connection setting of an established or connecting c2n + * connection, as given to PICA_new_c2n(). It applies to the c2c connections + * made from then on; those already there carry on as they were negotiated. + * \param l the listener for PICA_DIRECTC2C_CFG_ALLOWINCOMING, ignored + * otherwise. A listener taken away from every c2n connection can be closed. + */ +void PICA_c2n_set_directc2c(struct PICA_c2n *c2n, enum PICA_directc2c_config direct_c2c_mode, + struct PICA_listener *l); +/** + * Opens the TCP port for incoming direct c2c connections bypassing nodes, and + * the UDP port with the same number for the media of calls. + * + * The addresses announced to peers are configured automatically until + * PICA_listener_set_addrlist() says otherwise: the addresses of the network + * interfaces, private ones first, with local_port, followed by the UPnP + * mapping once PICA_listener_set_upnp_addr() reports one. + * * \param acc - pointer to opened account instance - * \param public_addr - DNS name or IP address string, - * it is an address that will be used for connecting from global Internet. - * Should be set to router's external IP if computer running pica-client is located behind the NAT. - * \param public_port - TCP port for incoming connections from global Internet - * \param local_port - TCP port that will be actually opened on computer listening for direct c2c connections + * \param local_port - port number to listen on, TCP and UDP * \param l - address of pointer that will be filled with address of created PICA_listener structure + * \retval PICA_ERRSOCK one of the two ports could not be opened, e.g. it is + * in use already */ -int PICA_new_listener(const struct PICA_acc *acc, const char *public_addr, int public_port, int local_port, struct PICA_listener **l); +int PICA_new_listener(const struct PICA_acc *acc, int local_port, struct PICA_listener **l); + +/** + * Sets the addresses announced to peers manually, in the order given. + * \param addrs IPv4 addresses or DNS names, the latter resolved here, which + * can block. A NULL entry stands for the external address of the UPnP port + * mapping, see PICA_listener_set_upnp_addr(), and is left out while there is + * none. + * \param ports the external port number of each address; for the UPnP entry + * the mapped port is announced instead + * \param count number of entries, up to PICA_DIRECTC2C_MAX_ADDRS; 0 goes + * back to automatic configuration + * \retval PICA_ERRDNSRESOLVE an address could not be resolved; the list is + * left as it was + */ +int PICA_listener_set_addrlist(struct PICA_listener *l, const char *const *addrs, const int *ports, int count); + +/** + * Reports the external address and port of a UPnP port mapping made for + * this listener, or that there is none any more when addr is NULL. Takes + * effect for the 0x0B messages sent from then on. + */ +int PICA_listener_set_upnp_addr(struct PICA_listener *l, const char *addr, int port); int PICA_open_acc(const char *cert_file, const char *pkey_file, @@ -444,6 +669,24 @@ int PICA_open_acc(const char *cert_file, // timeout - timeout in milliseconds int PICA_event_loop(struct PICA_c2n **connections, int timeout); +/** + * Asks the node which address and TCP port the c2n connection comes from. + * The answer is delivered to tcp_address_cb. + */ +int PICA_request_tcp_address(struct PICA_c2n *c2n); +/** + * Asks the node which address and port the datagrams sent from udp_sck come + * from, i.e. what the NAT in front of this host maps that socket to. The + * outcome is delivered to udp_address_cb. + * \param udp_sck bound, unconnected IPv4 UDP socket - the one the address is + * wanted for. It is only sent from, and has to stay open until the callback + * is called. The mapping learned is only useful with this same socket. + * + * One request per c2n connection can be in progress; another call restarts + * it. A node serves only a few of these in a row from one client. + */ +int PICA_request_udp_address(struct PICA_c2n *c2n, SOCKET udp_sck); + int PICA_send_msg(struct PICA_c2c *chn, char *buf, unsigned int len); //filename - ASCII or UTF-8 encoded string @@ -455,6 +698,15 @@ int PICA_pause_file(struct PICA_c2c *chan, int sending); int PICA_resume_file(struct PICA_c2c *chan, int sending); int PICA_cancel_file(struct PICA_c2c *chan, int sending); +int PICA_start_call(struct PICA_c2c *chn); +int PICA_pickup_call(struct PICA_c2c *chn); +int PICA_reject_call(struct PICA_c2c *chn); +int PICA_hangup_call(struct PICA_c2c *chn); +int PICA_set_call_audio_params(struct PICA_c2c *chn, const char *codec_name, uint16_t sample_rate); +int PICA_set_call_video_params(struct PICA_c2c *chn, const char *codec_name, uint16_t width, uint16_t height); +int PICA_send_audio_packet(struct PICA_c2c *chn, uint16_t seq_num, uint32_t timestamp, const char *buf, unsigned int len); +int PICA_send_video_packet(struct PICA_c2c *chn, uint16_t seq_num, uint32_t timestamp, const char *buf, unsigned int len); + void PICA_close_c2c(struct PICA_c2c *chn); void PICA_close_c2n(struct PICA_c2n *cid); void PICA_close_directc2c(struct PICA_directc2c *d); diff --git a/PICA_common.h b/PICA_common.h index ee1fc54..8f35cf6 100644 --- a/PICA_common.h +++ b/PICA_common.h @@ -21,10 +21,18 @@ #define CLOSE closesocket #define SHUTDOWN(s) shutdown(s,SD_BOTH) #define IOCTLSETNONBLOCKINGSOCKET(s, a) {unsigned long arg = (a); ioctlsocket(s, FIONBIO, (unsigned long*)&arg); } +/* Winsock takes the option value as char*, unlike the BSD sockets API */ +#define SETTCPNODELAY(s) {int arg = 1; setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (const char*)&arg, sizeof(arg)); } #else #define CLOSE close #define SHUTDOWN(s) shutdown(s,SHUT_RDWR) #define IOCTLSETNONBLOCKINGSOCKET(s, a) {int arg = (a); ioctl(s, FIONBIO, (int*)&arg); } +/* Disables Nagle's algorithm. Every Pica Pica protocol message is small and + * is meant to be delivered as soon as it is written - holding one back until + * the previous one is acknowledged adds delay to chat messages and, much more + * noticeably, to the audio and video packets of a call. + */ +#define SETTCPNODELAY(s) {int arg = 1; setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &arg, sizeof(arg)); } #endif #if defined(WIN32) || defined (__APPLE__) diff --git a/PICA_media.c b/PICA_media.c new file mode 100644 index 0000000..745b0e4 --- /dev/null +++ b/PICA_media.c @@ -0,0 +1,1339 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#include "PICA_security.h" +#include "PICA_client.h" +#include "PICA_media.h" +#include "PICA_proto.h" +#include "PICA_common.h" +#include "PICA_netconf.h" +#include <openssl/err.h> +#include <openssl/rand.h> +#include <string.h> +#include <time.h> +#ifndef WIN32 +#include <errno.h> +#endif + +#define PICA_DEBUG + +#ifdef PICA_DEBUG +#define PICA_TRACEFUNC fprintf(stderr, "%s()\n", __PRETTY_FUNCTION__); +#else +#define PICA_TRACEFUNC +#endif + +static void media_fail(struct PICA_media_channel *m); +static void media_handshake(struct PICA_media_channel *m); +static int media_punch_start(struct PICA_c2c *c2c); + +#ifdef WIN32 +uint64_t PICA_media_now(void) +{ + /* GetTickCount64() would be simpler, but needs Vista as the minimum + * target and the headers are set up for XP + */ + static LARGE_INTEGER freq; + LARGE_INTEGER count; + + if (freq.QuadPart == 0) + QueryPerformanceFrequency(&freq); + + QueryPerformanceCounter(&count); + + return (uint64_t)(count.QuadPart / (freq.QuadPart / 1000)); +} +#else +uint64_t PICA_media_now(void) +{ + struct timespec ts; + + clock_gettime(CLOCK_MONOTONIC, &ts); + + return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; +} +#endif + +static int media_socket_open(SOCKET *s, int local_port) +{ + struct sockaddr_in a; + + *s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + + if (*s == SOCKET_ERROR) + return PICA_ERRSOCK; + + /* No SO_REUSEADDR: UDP has no TIME_WAIT for it to get around, while for + * UDP it lets a second socket bind to a port another one already uses - + * and the listener has to find out when its port is taken, so that it + * can try the next one instead of sharing it. + */ + memset(&a, 0, sizeof(a)); + a.sin_family = AF_INET; + a.sin_addr.s_addr = INADDR_ANY; + /* local_port 0 asks the system for an unused port, which is what the + * connecting side wants - only the accepting side needs a port number + * known to the peer in advance. + */ + a.sin_port = htons(local_port); + + if (bind(*s, (const struct sockaddr*)&a, sizeof(a)) == SOCKET_ERROR) + { + CLOSE(*s); + *s = -1; + return PICA_ERRSOCK; + } + + IOCTLSETNONBLOCKINGSOCKET(*s, 1); + + return PICA_OK; +} + +int PICA_media_listener_new(const struct PICA_acc *acc, int public_port, int local_port, + struct PICA_media_listener **ml) +{ + struct PICA_media_listener *l; + int ret; + + PICA_TRACEFUNC + + if (!acc || !ml || public_port <= 0 || public_port > 65535 || local_port <= 0 || local_port > 65535) + return PICA_ERRINVARG; + + l = *ml = (struct PICA_media_listener*)calloc(sizeof(struct PICA_media_listener), 1); + + if (!l) + return PICA_ERRNOMEM; + + l->acc = acc; + l->public_port = public_port; + l->local_port = local_port; + + ret = media_socket_open(&l->sck, local_port); + + if (ret != PICA_OK) + { + free(l); + *ml = 0; + return ret; + } + + return PICA_OK; +} + +void PICA_media_listener_close(struct PICA_media_listener *ml) +{ + PICA_TRACEFUNC + + if (!ml) + return; + + /* A call using the socket keeps it until it ends, as if it had opened + * it itself: closing the listener stops new connections, not this one. + */ + if (ml->channel) + { + ml->channel->listener = NULL; + ml->channel->owns_sck = 1; + ml->channel = NULL; + ml->sck = -1; + } + + if (ml->sck >= 0) + CLOSE(ml->sck); + + free(ml); +} + +/* The listener's socket gets connect()ed to the peer for the duration of a + * call, so that the system drops everything coming from anywhere else. It has + * to be given back in its original, unconnected state afterwards; recreating + * it is the one way of doing that which behaves the same everywhere. + */ +static void media_listener_rearm(struct PICA_media_listener *ml) +{ + PICA_TRACEFUNC + + if (ml->sck >= 0) + CLOSE(ml->sck); + + if (media_socket_open(&ml->sck, ml->local_port) != PICA_OK) + { + fprintf(stderr, "failed to reopen the media listening socket on port %i\n", ml->local_port); + ml->sck = -1; + } +} + +static int media_ssl_new(struct PICA_media_channel *m) +{ + BIO *bio; + + m->ssl = SSL_new(m->c2c->acc->dtls_ctx); + + if (!m->ssl) + return PICA_ERRSSL; + + bio = BIO_new_dgram(m->sck, BIO_NOCLOSE); + + if (!bio) + { + SSL_free(m->ssl); + m->ssl = NULL; + return PICA_ERRSSL; + } + + /* The socket is connected, so the system already knows where the + * datagrams go; the BIO has to be told as well, otherwise it has no + * peer address to hand to sendto(). + */ + BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_CONNECTED, 0, (char*)&m->peer_addr); + + SSL_set_bio(m->ssl, bio, bio); + + SSL_set_verify(m->ssl, SSL_VERIFY_PEER, PICA_verify_callback); + SSL_set_verify_depth(m->ssl, 1); + + /* OpenSSL performs no path MTU discovery of its own: off Linux it cannot + * even read the value the system discovered, and falls back to a 228 + * octet floor that would fragment every handshake message. Telling it + * the MTU explicitly, and stopping it from asking the BIO + * (SSL_OP_NO_QUERY_MTU), gives the same behaviour everywhere. It also + * keeps OpenSSL from shrinking the value on its own after two handshake + * retransmissions, which it never undoes. + * This has to happen before the handshake starts: with + * SSL_OP_NO_QUERY_MTU set and no MTU, writing a handshake message fails. + */ + SSL_set_options(m->ssl, SSL_OP_NO_QUERY_MTU); +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + DTLS_set_link_mtu(m->ssl, PICA_MEDIA_LINK_MTU); +#else + SSL_set_mtu(m->ssl, PICA_MEDIA_LINK_MTU - PICA_MEDIA_IPUDP_OVERHEAD); +#endif + + return PICA_OK; +} + +static struct PICA_media_channel *media_channel_new(struct PICA_c2c *c2c) +{ + struct PICA_media_channel *m; + + m = (struct PICA_media_channel*)calloc(sizeof(struct PICA_media_channel), 1); + + if (!m) + return NULL; + + m->c2c = c2c; + m->sck = -1; + m->started = time(0); + m->last_tx = m->started; + + return m; +} + +/* "address:port", for the log; buf has PICA_MEDIA_ADDRSTRSIZE octets */ +#define PICA_MEDIA_ADDRSTRSIZE (INET6_ADDRSTRLEN + 6) + +static const char *media_addrstr(const struct sockaddr_in *a, char *buf) +{ + const unsigned char *ip = (const unsigned char*)&a->sin_addr.s_addr; + + sprintf(buf, "%u.%u.%u.%u:%u", ip[0], ip[1], ip[2], ip[3], (unsigned int)ntohs(a->sin_port)); + + return buf; +} + +/* Whether an address from the peer's 0x70/0x71 is one worth sending probes + * to: a unicast address of a host, and a port. A private one only if it is + * on one of the private networks this host is on, given by ifaddrs/ifmasks + * - anywhere else it belongs to some other network, as for 0x0B. Logs the + * decision. + */ +static int is_probe_target(const struct sockaddr_in *a, const in_addr_t *ifaddrs, + const in_addr_t *ifmasks, int ifcount) +{ + in_addr_t addr = a->sin_addr.s_addr; + char addrstr[PICA_MEDIA_ADDRSTRSIZE]; + int i; + + media_addrstr(a, addrstr); + + if (a->sin_port == 0) + { + fprintf(stderr, "media: call address %s - ignored: no port number\n", addrstr); + return 0; + } + + if (!PICA_is_private_addr_ipv4(addr)) + { + if (PICA_is_reserved_addr_ipv4(addr)) + { + fprintf(stderr, "media: call address %s - ignored: reserved address\n", addrstr); + return 0; + } + + fprintf(stderr, "media: call address %s - public, will be probed for %u ms\n", addrstr, + PICA_MEDIA_PUNCH_TIMEOUT); + return 1; + } + + if (ifcount == 0) + { + fprintf(stderr, "media: call address %s - private, ignored: this host is on no private network\n", addrstr); + return 0; + } + + i = PICA_find_subnet_ipv4(addr, ifaddrs, ifmasks, ifcount); + + if (i < 0) + { + fprintf(stderr, "media: call address %s - private, ignored: not on a private network of this host\n", + addrstr); + return 0; + } + + { + const unsigned char *ip = (const unsigned char*)&ifaddrs[i]; + const unsigned char *mask = (const unsigned char*)&ifmasks[i]; + + fprintf(stderr, "media: call address %s - private, on the network of local address %u.%u.%u.%u " + "netmask %u.%u.%u.%u, will be probed for %u ms\n", addrstr, + ip[0], ip[1], ip[2], ip[3], mask[0], mask[1], mask[2], mask[3], PICA_MEDIA_LAN_PROBE_TIMEOUT); + } + + return 1; +} + +/* Stops a request for the call socket's address still waiting for the node, + * so that a late answer is not delivered to a call that no longer wants it. + */ +static void media_call_stop_learning(struct PICA_c2c *c2c) +{ + struct PICA_media_call *mc = c2c->media_call; + + if (!mc->learning) + return; + + mc->learning = 0; + + if (c2c->conn->udpaddr_c2c == c2c) + { + c2c->conn->udpaddr_c2c = NULL; + c2c->conn->udpaddr_state = PICA_UDPADDR_STATE_IDLE; + } +} + +int PICA_media_call_prepare(struct PICA_c2c *c2c, int is_caller, + const unsigned char *peer_info, unsigned int peer_info_len) +{ + struct PICA_media_call *mc; + struct sockaddr_in a; +#ifdef WIN32 + int alen = sizeof(a); +#else + socklen_t alen = sizeof(a); +#endif + + PICA_TRACEFUNC + + PICA_media_call_free(c2c); + + mc = (struct PICA_media_call*)calloc(sizeof(struct PICA_media_call), 1); + + if (!mc) + return PICA_ERRNOMEM; + + mc->sck = -1; + mc->is_caller = is_caller; + + if (RAND_bytes(mc->token, sizeof(mc->token)) != 1) + { + free(mc); + return PICA_ERRSSL; + } + + c2c->media_call = mc; + + if (peer_info) + PICA_media_call_read_info(c2c, peer_info, peer_info_len); + + /* Hole punching reveals this client's addresses to the peer, which the + * user has not agreed to with direct connections disabled. A callee + * whose caller sent no addresses could not punch anywhere either. + */ + if (c2c->conn->directc2c_config == PICA_DIRECTC2C_CFG_DISABLED || !c2c->acc->dtls_ctx) + return PICA_OK; + + if (!is_caller && mc->peer_addrs_count == 0) + return PICA_OK; + + if (media_socket_open(&mc->sck, 0) != PICA_OK) + return PICA_OK; + + if (getsockname(mc->sck, (struct sockaddr*)&a, &alen) == SOCKET_ERROR) + { + CLOSE(mc->sck); + mc->sck = -1; + return PICA_OK; + } + + mc->local_port = ntohs(a.sin_port); + + /* What the node sees is what the NAT in front of us maps this socket to + * - the one address a peer outside the local network can punch through + * to. Without it, only the interface addresses are announced. + */ + if (PICA_request_udp_address(c2c->conn, mc->sck) == PICA_OK) + { + c2c->conn->udpaddr_c2c = c2c; + mc->learning = 1; + mc->learn_started = PICA_media_now(); + } + + return PICA_OK; +} + +void PICA_media_call_learned(struct PICA_c2c *c2c, int status, const unsigned char *addr_bin, int type, uint16_t port) +{ + struct PICA_media_call *mc = c2c->media_call; + + PICA_TRACEFUNC + + if (!mc || !mc->learning) + return; + + mc->learning = 0; + + if (status != PICA_OK || type != PICA_PROTO_MYUDPADDR_IPV4) + return; + + memset(&mc->learned_addr, 0, sizeof(mc->learned_addr)); + mc->learned_addr.sin_family = AF_INET; + memcpy(&mc->learned_addr.sin_addr.s_addr, addr_bin, 4); + mc->learned_addr.sin_port = htons(port); + mc->learned = 1; +} + +int PICA_media_call_ready(struct PICA_c2c *c2c) +{ + struct PICA_media_call *mc = c2c->media_call; + + if (!mc || !mc->learning) + return 1; + + return PICA_media_now() >= mc->pending_deadline; +} + +static unsigned char *write_addr_ipv4(unsigned char *p, in_addr_t addr, uint16_t port_netorder) +{ + *p++ = PICA_PROTO_DIRECTC2C_IPV4; + memcpy(p, &addr, 4); + p += 4; + memcpy(p, &port_netorder, 2); + + return p + 2; +} + +unsigned int PICA_media_call_write_info(struct PICA_c2c *c2c, unsigned char *buf) +{ + struct PICA_media_call *mc = c2c->media_call; + unsigned char *p = buf; + in_addr_t ifaddrs[PICA_IFADDRS_MAX]; + int n, i, count = 0; + int learned_is_ifaddr = 0; + + PICA_TRACEFUNC + + if (!mc) + return 0; + + /* whatever the node did not answer in time stays unknown */ + media_call_stop_learning(c2c); + + memcpy(p, mc->token, PICA_PROTO_CALL_TOKENSIZE); + p += PICA_PROTO_CALL_TOKENSIZE; + + if (mc->sck < 0) + return (unsigned int)(p - buf); + + /* The interface addresses first, so that two clients on the same local + * network reach each other inside it, which works whether or not their + * router can loop traffic for its own external address back in. One + * place is kept for the address the node reported. + */ + n = PICA_get_ifaddrs_ipv4(ifaddrs, PICA_IFADDRS_MAX); + + for (i = 0; i < n && count < PICA_PROTO_CALL_MAXADDRS - 1; i++) + { + if (mc->learned && ifaddrs[i] == mc->learned_addr.sin_addr.s_addr + && ntohs(mc->learned_addr.sin_port) == mc->local_port) + learned_is_ifaddr = 1; + + p = write_addr_ipv4(p, ifaddrs[i], htons((uint16_t)mc->local_port)); + count++; + } + + /* the same as an interface address when there is no NAT on the way */ + if (mc->learned && !learned_is_ifaddr) + p = write_addr_ipv4(p, mc->learned_addr.sin_addr.s_addr, mc->learned_addr.sin_port); + + return (unsigned int)(p - buf); +} + +int PICA_media_call_read_info(struct PICA_c2c *c2c, const unsigned char *buf, unsigned int len) +{ + struct PICA_media_call *mc = c2c->media_call; + in_addr_t ifaddrs[PICA_IFADDRS_MAX], ifmasks[PICA_IFADDRS_MAX]; + int ifcount; + unsigned int pos; + int addresses = 0; + + if (!mc) + return 0; + + mc->peer_info_received = 1; + mc->peer_addrs_count = 0; + + if (len < PICA_PROTO_CALL_TOKENSIZE) + return 0; + + memcpy(mc->peer_token, buf, PICA_PROTO_CALL_TOKENSIZE); + pos = PICA_PROTO_CALL_TOKENSIZE; + + ifcount = PICA_get_private_ifaddrs_ipv4(ifaddrs, ifmasks, PICA_IFADDRS_MAX); + + while (pos < len && addresses < PICA_PROTO_CALL_MAXADDRS) + { + struct sockaddr_in *a; + + switch (buf[pos]) + { + case PICA_PROTO_DIRECTC2C_IPV4: + if (pos + PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE > len) + goto malformed; + + addresses++; + a = &mc->peer_addrs[mc->peer_addrs_count]; + memset(a, 0, sizeof(*a)); + a->sin_family = AF_INET; + memcpy(&a->sin_addr.s_addr, buf + pos + 1, 4); + memcpy(&a->sin_port, buf + pos + 5, 2); + + if (is_probe_target(a, ifaddrs, ifmasks, ifcount)) + mc->peer_addrs_count++; + + pos += PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE; + break; + + case PICA_PROTO_DIRECTC2C_IPV6: + /* counts as an address, but the media sockets are IPv4 ones */ + if (pos + PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV6_SIZE > len) + goto malformed; + + addresses++; + pos += PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV6_SIZE; + break; + + case PICA_PROTO_DIRECTC2C_DNS: + if (pos + 1 >= len || pos + 2 + buf[pos + 1] + 2 > len) + goto malformed; + + pos += 2 + buf[pos + 1] + 2; + break; + + default: + /* no way of knowing where an element of an unknown type ends */ + goto malformed; + } + } + + return 1; + +malformed: + /* An address list that does not parse cannot be relied on in any of its + * parts. The call goes ahead, only without hole punching. + */ + mc->peer_addrs_count = 0; + return 0; +} + +void PICA_media_call_free(struct PICA_c2c *c2c) +{ + struct PICA_media_call *mc = c2c->media_call; + + if (!mc) + return; + + /* the media connection of attempt 2 uses the call socket */ + if (c2c->media && c2c->media->attempt == 2) + PICA_media_close(c2c); + + media_call_stop_learning(c2c); + + if (mc->sck >= 0) + CLOSE(mc->sck); + + c2c->media_call = NULL; + free(mc); +} + +/* Attempt 1, over the address of the directc2c connection. It goes first + * because that address is known to work already - the port behind it is + * public or forwarded, whatever the NATs on the way do with UDP. + */ +static int media_direct_start(struct PICA_c2c *c2c) +{ + struct PICA_media_channel *m; + int ret; + + PICA_TRACEFUNC + + if (c2c->directc2c_state != PICA_DIRECTC2C_STATE_ACTIVE || !c2c->direct) + return PICA_ERRNOTFOUND; + + m = media_channel_new(c2c); + + if (!m) + return PICA_ERRNOMEM; + + m->attempt = 1; + m->deadline = PICA_media_now() + PICA_MEDIA_DIRECT_TIMEOUT; + + if (c2c->direct->is_outgoing == PICA_DIRECTC2C_OUTGOING) + { + /* We reached the peer over TCP at this address, so we are the one + * that can reach it over UDP as well - the peer's announced port + * number is used for both. + */ + m->is_dtls_client = 1; + m->peer_addr = c2c->direct->addr; + + ret = media_socket_open(&m->sck, 0); + + if (ret != PICA_OK) + { + free(m); + return ret; + } + + m->owns_sck = 1; + + if (connect(m->sck, (struct sockaddr*)&m->peer_addr, sizeof(m->peer_addr)) == SOCKET_ERROR) + { + CLOSE(m->sck); + free(m); + return PICA_ERRSOCK; + } + + if (media_ssl_new(m) != PICA_OK) + { + CLOSE(m->sck); + free(m); + return PICA_ERRSSL; + } + + SSL_set_connect_state(m->ssl); + + m->state = PICA_MEDIA_STATE_HANDSHAKE; + c2c->media = m; + + /* can fail, and start attempt 2 from there */ + media_handshake(m); + } + else + { + struct PICA_media_listener *ml; + + if (!c2c->conn->directc2c_listener || !c2c->conn->directc2c_listener->media) + { + free(m); + return PICA_ERRNOTFOUND; + } + + ml = c2c->conn->directc2c_listener->media; + + if (ml->sck < 0 || ml->channel) + { + free(m); + return PICA_ERRSOCK; + } + + /* Nothing to do until the peer sends its first datagram: the source + * address it arrives from is the only way to learn which port its + * NAT gave it. + */ + m->listener = ml; + m->sck = ml->sck; + m->owns_sck = 0; + m->state = PICA_MEDIA_STATE_LISTENING; + + ml->channel = m; + c2c->media = m; + } + + return PICA_OK; +} + +static void media_send_probe_to(struct PICA_media_channel *m, const struct sockaddr_in *to) +{ + unsigned char probe[PICA_PROTO_MEDIAPROBE_SIZE]; + + probe[0] = probe[1] = PICA_PROTO_MEDIAPROBE; + memcpy(probe + 2, m->c2c->media_call->peer_token, PICA_PROTO_CALL_TOKENSIZE); + + /* A failed send is the same as a datagram lost on the way. Once an + * address is selected the socket is connected to it, and sendto() with + * an address is not allowed on a connected socket everywhere. + */ + if (to) + sendto(m->sck, (const char*)probe, sizeof(probe), 0, (const struct sockaddr*)to, sizeof(*to)); + else + send(m->sck, (const char*)probe, sizeof(probe), 0); +} + +/* Sends the probes that are due: to every address of the peer until one is + * selected, to the selected one afterwards until the peer's first DTLS + * datagram shows that it has selected us too. + */ +static void media_send_probes(struct PICA_media_channel *m, uint64_t now) +{ + struct PICA_media_call *mc = m->c2c->media_call; + int lan_due, public_due; + int i; + + if (m->dtls_seen) + return; + + public_due = now - m->last_probe >= PICA_MEDIA_PROBE_INTERVAL; + + if (m->state != PICA_MEDIA_STATE_PUNCHING) + { + if (public_due) + { + m->last_probe = now; + media_send_probe_to(m, NULL); + } + + return; + } + + /* the private addresses only at first, see PICA_MEDIA_LAN_PROBE_TIMEOUT */ + lan_due = now - m->punch_started <= PICA_MEDIA_LAN_PROBE_TIMEOUT + && now - m->last_lan_probe >= PICA_MEDIA_LAN_PROBE_INTERVAL; + + if (lan_due) + m->last_lan_probe = now; + + if (public_due) + m->last_probe = now; + + for (i = 0; i < mc->peer_addrs_count; i++) + if (PICA_is_private_addr_ipv4(mc->peer_addrs[i].sin_addr.s_addr) ? lan_due : public_due) + media_send_probe_to(m, &mc->peer_addrs[i]); +} + +/* Attempt 2, by hole punching between the call sockets. */ +static int media_punch_start(struct PICA_c2c *c2c) +{ + struct PICA_media_call *mc = c2c->media_call; + struct PICA_media_channel *m; + + PICA_TRACEFUNC + + if (c2c->media || !mc || mc->sck < 0 || mc->peer_addrs_count == 0) + return PICA_ERRNOTFOUND; + + m = media_channel_new(c2c); + + if (!m) + return PICA_ERRNOMEM; + + m->attempt = 2; + m->sck = mc->sck; + m->owns_sck = 0; + m->is_dtls_client = mc->is_caller; + m->state = PICA_MEDIA_STATE_PUNCHING; + m->punch_started = PICA_media_now(); + m->deadline = m->punch_started + PICA_MEDIA_PUNCH_TIMEOUT; + + c2c->media = m; + + fprintf(stderr, "media: hole punching, probing %i addresses of the peer\n", mc->peer_addrs_count); + + media_send_probes(m, m->punch_started); + + return PICA_OK; +} + +void PICA_media_start(struct PICA_c2c *c2c) +{ + PICA_TRACEFUNC + + if (c2c->media || !c2c->acc->dtls_ctx) + return; + + if (media_direct_start(c2c) == PICA_OK) + return; + + media_punch_start(c2c); +} + +void PICA_media_close(struct PICA_c2c *c2c) +{ + struct PICA_media_channel *m = c2c->media; + + PICA_TRACEFUNC + + if (!m) + return; + + c2c->media = NULL; + + if (m->peer_cert) + X509_free(m->peer_cert); + + if (m->ssl) + SSL_free(m->ssl); + + if (m->owns_sck && m->sck >= 0) + CLOSE(m->sck); + + if (m->listener) + { + m->listener->channel = NULL; + + /* the socket was connected to the peer while the call lasted */ + if (m->state != PICA_MEDIA_STATE_LISTENING) + media_listener_rearm(m->listener); + } + + free(m); +} + +static void media_fail(struct PICA_media_channel *m) +{ + struct PICA_c2c *c2c = m->c2c; + /* attempt 2 follows attempt 1 that did not succeed, see PICA_media.h */ + int try_punching = m->attempt == 1 && m->state != PICA_MEDIA_STATE_ACTIVE; + + PICA_TRACEFUNC + + PICA_media_close(c2c); + + if (try_punching && media_punch_start(c2c) == PICA_OK) + return; + + /* the call carries on, its media goes back to the c2c connection */ + PICA_media_transport_changed(c2c, PICA_CALL_TRANSPORT_C2C, NULL); +} + +int PICA_media_is_active(const struct PICA_c2c *c2c) +{ + return c2c->media && c2c->media->state == PICA_MEDIA_STATE_ACTIVE; +} + +unsigned int PICA_media_max_payload(const struct PICA_c2c *c2c) +{ + unsigned int mtu; + + if (!PICA_media_is_active(c2c)) + return PICA_PROTO_C2CMSG_MAXDATASIZE - PICA_PROTO_CALL_PACKET_HDRSIZE; + + mtu = c2c->media->max_payload; + + if (mtu <= 4 + PICA_PROTO_CALL_PACKET_HDRSIZE) + return 0; + + /* the message header, its length field and the media packet header all + * have to fit into the same datagram + */ + return mtu - 4 - PICA_PROTO_CALL_PACKET_HDRSIZE; +} + +int PICA_media_send(struct PICA_c2c *c2c, const unsigned char *buf, unsigned int len) +{ + struct PICA_media_channel *m = c2c->media; + int ret; + + if (!PICA_media_is_active(c2c)) + return PICA_ERRINVARG; + + ret = SSL_write(m->ssl, buf, len); + + if (ret > 0) + { + m->last_tx = time(0); + return PICA_OK; + } + + /* The send buffer is full, or the system reports an error such as an + * ICMP message caused by an earlier datagram - either way the packet is + * dropped rather than queued. Delaying live media is worse than losing + * a frame of it, and the receiving side is built to cope with losses + * anyway. DTLS drops a record that could not be written and carries on + * with the next one, so none of this ends the connection. + */ + ERR_clear_error(); + + return PICA_OK; +} + +static void media_activate(struct PICA_media_channel *m) +{ + int ret; + + PICA_TRACEFUNC + + ret = PICA_verify_peer_cert_common(&m->peer_cert, m->ssl, m->c2c->peer_id); + + if (ret != PICA_OK) + { + fprintf(stderr, "media connection peer certificate verification failed: %i\n", ret); + media_fail(m); + return; + } + +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + m->max_payload = (unsigned int)DTLS_get_data_mtu(m->ssl); +#else + /* DTLS record header, explicit nonce and authentication tag of the + * ciphersuites Pica Pica uses + */ + m->max_payload = PICA_MEDIA_LINK_MTU - PICA_MEDIA_IPUDP_OVERHEAD - 13 - 8 - 16; +#endif + + m->state = PICA_MEDIA_STATE_ACTIVE; + + { + char addrstr[PICA_MEDIA_ADDRSTRSIZE]; + + fprintf(stderr, "media: connection with %s established by attempt %i\n", + media_addrstr(&m->peer_addr, addrstr), m->attempt); + } + + PICA_media_transport_changed(m->c2c, PICA_CALL_TRANSPORT_MEDIAC2C, SSL_get_cipher_name(m->ssl)); +} + +static void media_handshake(struct PICA_media_channel *m) +{ + int ret; + + ret = SSL_do_handshake(m->ssl); + + if (ret == 1) + { + media_activate(m); + return; + } + + switch (SSL_get_error(m->ssl, ret)) + { + case SSL_ERROR_WANT_READ: + case SSL_ERROR_WANT_WRITE: + break; + + default: + fprintf(stderr, "media connection DTLS handshake failed\n"); + media_fail(m); + } +} + +/* The first datagram of a call arrives at the listening socket from a source + * port only the peer's NAT knows. Once it is seen, the socket is connected to + * that address for the rest of the call. + */ +static void media_accept(struct PICA_media_channel *m) +{ + struct sockaddr_in from; +#ifdef WIN32 + int fromlen = sizeof(from); +#else + socklen_t fromlen = sizeof(from); +#endif + /* Large enough for any datagram the peer can send us, so that the peek + * never truncates: a truncated peek is reported as an error on Windows. + */ + unsigned char peekbuf[PICA_MEDIA_READBUFSIZE]; + int ret; + + PICA_TRACEFUNC + + ret = recvfrom(m->sck, (char*)peekbuf, sizeof(peekbuf), MSG_PEEK, (struct sockaddr*)&from, &fromlen); + + if (ret < 0) + return; + + /* The peer of the call is already known - it is the client on the other + * end of the directc2c connection - so a datagram from any other address + * cannot belong to this call. Only the address is checked here, the port + * number is whatever the peer's system picked. + */ + if (from.sin_addr.s_addr != m->c2c->direct->addr.sin_addr.s_addr) + { + /* consume it, otherwise it is peeked again on every pass */ + recvfrom(m->sck, (char*)peekbuf, sizeof(peekbuf), 0, (struct sockaddr*)&from, &fromlen); + fprintf(stderr, "dropped a datagram from an address the call is not with\n"); + return; + } + + m->peer_addr = from; + + if (connect(m->sck, (struct sockaddr*)&m->peer_addr, sizeof(m->peer_addr)) == SOCKET_ERROR) + { + media_fail(m); + return; + } + + if (media_ssl_new(m) != PICA_OK) + { + media_fail(m); + return; + } + + SSL_set_accept_state(m->ssl); + + m->state = PICA_MEDIA_STATE_HANDSHAKE; + + media_handshake(m); +} + +/* Whether a datagram is a probe carrying our own token, i.e. one that comes + * from the peer of this call. + */ +static int is_our_probe(struct PICA_media_channel *m, const unsigned char *buf, int len) +{ + return len == PICA_PROTO_MEDIAPROBE_SIZE + && buf[0] == PICA_PROTO_MEDIAPROBE && buf[1] == PICA_PROTO_MEDIAPROBE + && memcmp(buf + 2, m->c2c->media_call->token, PICA_PROTO_CALL_TOKENSIZE) == 0; +} + +/* The peer's probe came from this address, so this is where its NAT lets + * our datagrams through to it. From now on the socket only talks to it. + */ +static void media_punch_select(struct PICA_media_channel *m, const struct sockaddr_in *from) +{ + char addrstr[PICA_MEDIA_ADDRSTRSIZE]; + + PICA_TRACEFUNC + + fprintf(stderr, "media: hole punching, the peer's probe arrived from %s after %u ms, selected\n", + media_addrstr(from, addrstr), (unsigned int)(PICA_media_now() - m->punch_started)); + + m->peer_addr = *from; + + if (connect(m->sck, (const struct sockaddr*)&m->peer_addr, sizeof(m->peer_addr)) == SOCKET_ERROR) + { + media_fail(m); + return; + } + + m->deadline = PICA_media_now() + PICA_MEDIA_PUNCH_HANDSHAKE_TIMEOUT; + + if (!m->is_dtls_client) + { + /* the caller learns that it can reach us from our probes */ + m->state = PICA_MEDIA_STATE_SELECTED; + m->last_probe = 0; + media_send_probes(m, PICA_media_now()); + return; + } + + if (media_ssl_new(m) != PICA_OK) + { + media_fail(m); + return; + } + + SSL_set_connect_state(m->ssl); + + m->state = PICA_MEDIA_STATE_HANDSHAKE; + m->last_probe = 0; + media_send_probes(m, PICA_media_now()); + + media_handshake(m); +} + +/* Reads what has arrived while no address is selected yet. Only a probe + * with our token counts; a DTLS datagram arriving this early is dropped and + * retransmitted by the peer later on, anything else is not from the peer. + */ +static void media_punch_read(struct PICA_media_channel *m) +{ + unsigned char buf[PICA_MEDIA_READBUFSIZE]; + struct sockaddr_in from; +#ifdef WIN32 + int fromlen; +#else + socklen_t fromlen; +#endif + int ret; + + while (1) + { + fromlen = sizeof(from); + + ret = recvfrom(m->sck, (char*)buf, sizeof(buf), 0, (struct sockaddr*)&from, &fromlen); + + if (ret < 0) + { +#ifdef WIN32 + /* Windows reports an ICMP port unreachable, caused by a probe + * sent to an address where nothing listens, on the next + * recvfrom() of the socket - which says nothing about the + * datagrams queued behind it. + */ + if (WSAGetLastError() == WSAECONNRESET) + continue; +#endif + return; + } + + if (from.sin_family == AF_INET && is_our_probe(m, buf, ret)) + { + /* can free m */ + media_punch_select(m, &from); + return; + } + } +} + +/* Takes off the socket, before DTLS gets to read it: + * - the probes that are still arriving after an address was selected - a + * DTLS record never starts with the octet of a probe; + * - errors the system reports for earlier datagrams, e.g. an ICMP port + * unreachable from the peer's NAT. Reading one clears it, and left to DTLS + * it would be taken for the end of the connection. + * \return 1 if a datagram other than a probe is waiting + */ +static int media_skip_probes(struct PICA_media_channel *m) +{ + unsigned char buf[PICA_MEDIA_READBUFSIZE]; + /* an error that does not clear itself must not keep us here */ + int errors = 0; + int ret; + + while (1) + { + /* Large enough for any datagram, so that the peek never truncates: + * a truncated peek is reported as an error on Windows. + */ + ret = recv(m->sck, (char*)buf, sizeof(buf), MSG_PEEK); + + if (ret < 0) + { +#ifdef WIN32 + if (WSAGetLastError() == WSAEWOULDBLOCK) + return 0; +#else + if (errno == EAGAIN || errno == EWOULDBLOCK) + return 0; +#endif + if (++errors > 16) + return 0; + + continue; + } + + if (ret == 0 || buf[0] == PICA_PROTO_MEDIAPROBE) + { + recv(m->sck, (char*)buf, sizeof(buf), 0); + continue; + } + + m->dtls_seen = 1; + + return 1; + } +} + +/* Attempt 2, the callee: the caller's handshake has started arriving. */ +static void media_punch_accept(struct PICA_media_channel *m) +{ + PICA_TRACEFUNC + + if (media_ssl_new(m) != PICA_OK) + { + media_fail(m); + return; + } + + SSL_set_accept_state(m->ssl); + + m->state = PICA_MEDIA_STATE_HANDSHAKE; + + media_handshake(m); +} + +static void media_read(struct PICA_media_channel *m) +{ + struct PICA_c2c *c2c = m->c2c; + int ret; + + /* One SSL_read() per datagram, so this loop runs until the socket has + * nothing left for us. + */ + while (1) + { + /* a late probe of a hole punched connection, or a socket error */ + if (SSL_pending(m->ssl) == 0 && !media_skip_probes(m)) + return; + + ret = SSL_read(m->ssl, m->read_buf, PICA_MEDIA_READBUFSIZE); + + if (ret <= 0) + { + switch (SSL_get_error(m->ssl, ret)) + { + case SSL_ERROR_WANT_READ: + case SSL_ERROR_WANT_WRITE: + return; + + case SSL_ERROR_SYSCALL: + /* A socket error that arrived after media_skip_probes() + * looked. It says nothing about the connection, the same as + * a lost datagram. + */ + ERR_clear_error(); + return; + + default: + /* the peer closed the connection or sent a fatal alert */ + fprintf(stderr, "media connection read failed\n"); + media_fail(m); + return; + } + } + + m->read_pos = (unsigned int)ret; + + /* A datagram carries exactly one message. Anything that does not + * parse is dropped together with the rest of the datagram - unlike + * on a c2c connection, bad data here says nothing about the peer, + * anyone able to reach the port can send it. + */ + PICA_media_process_messages(m->read_buf, &m->read_pos, c2c); + + /* Processing a datagram can close this media channel (e.g. a failed + * ping reply calls media_fail(), which frees m). If it did, m is now + * dangling - stop before touching it again. m is only compared as an + * address here, never dereferenced. + */ + if (c2c->media != m) + return; + + m->read_pos = 0; + } +} + +void PICA_media_fdset(struct PICA_c2n *c2n, fd_set *rfds, int *nfds) +{ + struct PICA_c2c *c2c = c2n->chan_list_head; + + while (c2c) + { + if (c2c->media && c2c->media->sck >= 0) + { + FD_SET(c2c->media->sck, rfds); + + if (c2c->media->sck > *nfds) + *nfds = c2c->media->sck; + } + + c2c = c2c->next; + } +} + +void PICA_media_process(struct PICA_c2n *c2n, fd_set *rfds) +{ + struct PICA_c2c *chan = c2n->chan_list_head; + time_t now = time(0); + uint64_t now_ms = PICA_media_now(); + + while (chan) + { + struct PICA_c2c *c2c = chan; + struct PICA_media_channel *m = c2c->media; + int readable; + + chan = chan->next; + + if (!m) + continue; + + if (m->state != PICA_MEDIA_STATE_ACTIVE && now_ms >= m->deadline) + { + fprintf(stderr, "media connection attempt %i was not completed in time\n", m->attempt); + media_fail(m); + continue; + } + + readable = m->sck >= 0 && FD_ISSET(m->sck, rfds); + + /* Anything below that can close the media connection - which frees m, + * and can start another attempt in its place - is the last thing + * done with m in this pass, or is followed by a check through c2c, + * which stays valid. + */ + switch (m->state) + { + case PICA_MEDIA_STATE_LISTENING: + if (readable) + media_accept(m); + break; + + case PICA_MEDIA_STATE_PUNCHING: + media_send_probes(m, now_ms); + + if (readable) + media_punch_read(m); + break; + + case PICA_MEDIA_STATE_SELECTED: + media_send_probes(m, now_ms); + + if (readable && media_skip_probes(m)) + media_punch_accept(m); + break; + + case PICA_MEDIA_STATE_HANDSHAKE: + if (m->attempt == 2) + media_send_probes(m, now_ms); + + /* Lost handshake messages are retransmitted by OpenSSL, but + * only when it is told that its timer has expired. + */ + DTLSv1_handle_timeout(m->ssl); + + if (readable && (m->attempt != 2 || media_skip_probes(m))) + media_handshake(m); + break; + + case PICA_MEDIA_STATE_ACTIVE: + if (readable) + media_read(m); + + if (!PICA_media_is_active(c2c)) + break; + + if ((now - m->last_tx) >= PICA_MEDIA_KEEPALIVE_INTERVAL) + PICA_media_send_ping(c2c, 0); + + break; + + default: + break; + } + } +} diff --git a/PICA_media.h b/PICA_media.h new file mode 100644 index 0000000..f17b6ce --- /dev/null +++ b/PICA_media.h @@ -0,0 +1,308 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ + +/* mediac2c connections - call media over UDP, protected by DTLS. + * + * A mediac2c connection exists only while a call is in progress. When the + * call becomes active, up to two attempts are made, one after another - see + * "Establishing the media connection" in doc/proto-doc-latest.txt: + * + * 1. Over the directc2c connection's address and port number, with UDP + * instead of TCP, if the call's c2c connection has an established directc2c + * one: the client that made the outgoing directc2c connection is the DTLS + * client, the one that accepted it is the DTLS server, listening on its + * PICA_media_listener. + * + * 2. By UDP hole punching between the media sockets the two clients opened + * for the call (PICA_media_call), over the addresses exchanged in 0x70 and + * 0x71. The caller is the DTLS client. + * + * Media packets are sent over this connection whenever it is established and + * over the c2c/directc2c connection otherwise; the receiving side accepts + * them over either transport at any time, so there is no moment where the + * media stops while the transport changes. + */ + +#ifndef PICA_MEDIA_H +#define PICA_MEDIA_H + +#include "PICA_client.h" + +/* Link MTU assumed for a mediac2c connection until path MTU discovery + * (RFC 8899) is implemented. 1200 octets is the value QUIC uses as the size + * every path is expected to carry. + */ +#define PICA_MEDIA_LINK_MTU 1200 +/* IPv4 + UDP headers */ +#define PICA_MEDIA_IPUDP_OVERHEAD 28 + +/* Amount of media data that certainly fits into one datagram of a mediac2c + * connection: the assumed link MTU less a generous allowance for the IP, UDP, + * DTLS record and protocol message headers, whose exact sizes depend on the + * ciphersuite that ends up being negotiated. + * It lets the media be produced in datagram sized pieces from the start of a + * call, before it is known whether a media connection will come up at all, + * rather than having to change size in the middle of one. + */ +#define PICA_MEDIA_SAFE_PAYLOAD (PICA_MEDIA_LINK_MTU - 100) + +/* The time limits of the two attempts, in milliseconds. A failed attempt 1 + * is followed by attempt 2; once that fails too, the media stays on the c2c + * connection for the rest of the call. + */ +/* attempt 1, from the call becoming active to the handshake completing */ +#define PICA_MEDIA_DIRECT_TIMEOUT 5000 +/* attempt 2: probes are sent this often... */ +#define PICA_MEDIA_PROBE_INTERVAL 200 +/* ...for at most this long, until an address is selected */ +#define PICA_MEDIA_PUNCH_TIMEOUT 10000 +/* and the handshake has this long to complete once it is */ +#define PICA_MEDIA_PUNCH_HANDSHAKE_TIMEOUT 10000 +/* A private address of the peer is only probed if it is on a private network + * this host is on, and there for this long from the start of attempt 2, as + * often as given below: a probe that gets through at all does so within a few + * milliseconds on a local network. One arriving at the peer's socket before + * the peer starts sending probes waits there for it, so a peer starting late + * still selects the address - and answers from it. + */ +#define PICA_MEDIA_LAN_PROBE_TIMEOUT 200 +#define PICA_MEDIA_LAN_PROBE_INTERVAL 50 + +/* How long 0x70 and 0x71 wait for the node to report the address of the + * media socket before they are sent without it, in milliseconds. + */ +#define PICA_MEDIA_LEARN_TIMEOUT 2000 + +/* Ping is sent over an established media connection after this many seconds + * without anything being sent, to hold NAT and firewall state open. + * An established media connection is kept for the rest of the call however + * long nothing arrives over it: loss on the path does not mean the c2c + * connection would carry the media any better. + */ +#define PICA_MEDIA_KEEPALIVE_INTERVAL 4 + +#define PICA_MEDIA_READBUFSIZE 4096 + +/* largest tail of 0x70/0x71 after the length field: the token and the + * addresses, IPv4 ones being the only kind sent + */ +#define PICA_MEDIA_CALL_INFO_MAXSIZE (PICA_PROTO_CALL_TOKENSIZE + PICA_PROTO_CALL_MAXADDRS * PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE) + +/* transport of the media packets of a call, reported by call_media_transport_cb */ +#define PICA_CALL_TRANSPORT_C2C 0 +#define PICA_CALL_TRANSPORT_MEDIAC2C 1 + +enum PICA_media_state +{ + PICA_MEDIA_STATE_NEW = 0, + /* attempt 1, DTLS server role, socket bound, waiting for the first + * datagram */ + PICA_MEDIA_STATE_LISTENING, + /* attempt 2, sending probes to every address of the peer, waiting for + * one of its probes to arrive */ + PICA_MEDIA_STATE_PUNCHING, + /* attempt 2, DTLS server role, address selected, waiting for the first + * datagram of the handshake from it */ + PICA_MEDIA_STATE_SELECTED, + PICA_MEDIA_STATE_HANDSHAKE, + PICA_MEDIA_STATE_ACTIVE, + PICA_MEDIA_STATE_FAILED +}; + +struct PICA_media_listener +{ + const struct PICA_acc *acc; + SOCKET sck; + int public_port; + int local_port; + + /* The media connection currently using this listener's socket, if any. + * Only one call can be in progress at a time, so there is at most one. + */ + struct PICA_media_channel *channel; +}; + +/* Everything a call needs for hole punching, from the moment it starts to + * ring until it ends. Created by PICA_media_call_prepare(), freed by + * PICA_media_call_free(). + */ +struct PICA_media_call +{ + /* the call socket, -1 if this side does not take part in hole punching */ + SOCKET sck; + /* its port number, host byte order */ + int local_port; + int is_caller; + + unsigned char token[PICA_PROTO_CALL_TOKENSIZE]; + + /* the node is being asked for the address of sck */ + int learning; + uint64_t learn_started; + /* what it answered, valid when learned is set */ + int learned; + struct sockaddr_in learned_addr; + + /* PICA_PROTO_CALLREQ or PICA_PROTO_CALLANS while that message waits for + * the address, 0 otherwise */ + int pending_msg; + uint64_t pending_deadline; + + /* from the peer's 0x70 or 0x71 */ + int peer_info_received; + unsigned char peer_token[PICA_PROTO_CALL_TOKENSIZE]; + struct sockaddr_in peer_addrs[PICA_PROTO_CALL_MAXADDRS]; + int peer_addrs_count; + + /* call parameters set while the call was PICA_CALL_STATE_ANSWERING */ + int audio_params_pending; + char audio_codec[PICA_PROTO_CALL_CODECNAMESIZE + 1]; + uint16_t audio_sample_rate; + int video_params_pending; + char video_codec[PICA_PROTO_CALL_CODECNAMESIZE + 1]; + uint16_t video_width; + uint16_t video_height; +}; + +struct PICA_media_channel +{ + struct PICA_c2c *c2c; + /* 1 - over the directc2c address, 2 - by hole punching */ + int attempt; + /* set when this side has the DTLS server role */ + struct PICA_media_listener *listener; + + SOCKET sck; + /* 0 when sck belongs to the listener and must not be closed with the + * channel + */ + int owns_sck; + struct sockaddr_in peer_addr; + + SSL *ssl; + X509 *peer_cert; + int is_dtls_client; + + enum PICA_media_state state; + time_t started; + /* when the current stage of setting the connection up has to be + * complete, PICA_media_now() milliseconds */ + uint64_t deadline; + + /* attempt 2 */ + uint64_t last_probe; + /* when the probes started, and the last one to a private address */ + uint64_t punch_started; + uint64_t last_lan_probe; + /* the first DTLS datagram has arrived from the selected address, the + * peer no longer needs probes */ + int dtls_seen; + time_t last_tx; + + unsigned int max_payload; + + unsigned char read_buf[PICA_MEDIA_READBUFSIZE]; + unsigned int read_pos; +}; + +#ifdef __cplusplus +extern "C" { +#endif + +/* implemented in PICA_media.c */ + +int PICA_media_listener_new(const struct PICA_acc *acc, int public_port, int local_port, + struct PICA_media_listener **ml); +void PICA_media_listener_close(struct PICA_media_listener *ml); + +/** Milliseconds from an arbitrary point, never going backwards. */ +uint64_t PICA_media_now(void); + +/** + * Starts preparing for hole punching: opens the call socket and asks the + * node for its address - for the caller before it sends 0x70, for the + * callee when 0x70 arrives. Without hole punching, e.g. with direct + * connections disabled, only creates c2c->media_call, whose address list is + * then empty. + * \param peer_info for the callee, the tail of the caller's 0x70 after the + * length field, see PICA_media_call_read_info(); NULL for the caller + */ +int PICA_media_call_prepare(struct PICA_c2c *c2c, int is_caller, + const unsigned char *peer_info, unsigned int peer_info_len); + +/** The node's answer about the call socket's address; status as in + * udp_address_cb. */ +void PICA_media_call_learned(struct PICA_c2c *c2c, int status, const unsigned char *addr_bin, int type, uint16_t port); + +/** Whether 0x70/0x71 can be sent now: the address is known, or will not be. */ +int PICA_media_call_ready(struct PICA_c2c *c2c); + +/** + * Writes the probe token and the address list of 0x70/0x71 to buf. + * \return number of octets written, at most PICA_MEDIA_CALL_INFO_MAXSIZE + */ +unsigned int PICA_media_call_write_info(struct PICA_c2c *c2c, unsigned char *buf); + +/** + * Takes the probe token and the address list from the tail of the peer's + * 0x70/0x71, after the length field. + * \return 0 if it is malformed + */ +int PICA_media_call_read_info(struct PICA_c2c *c2c, const unsigned char *buf, unsigned int len); + +/** Releases everything PICA_media_call_prepare() made. */ +void PICA_media_call_free(struct PICA_c2c *c2c); + +/** + * Brings up a media connection for a call that has just become active, see + * the two attempts above. Does nothing if neither of them can be made - the + * media then stays on the c2c connection. + */ +void PICA_media_start(struct PICA_c2c *c2c); +void PICA_media_close(struct PICA_c2c *c2c); + +int PICA_media_is_active(const struct PICA_c2c *c2c); +/** + * Largest amount of data one media packet can carry over this c2c connection, + * i.e. what has to fit into one datagram once a media connection is up. + */ +unsigned int PICA_media_max_payload(const struct PICA_c2c *c2c); + +/** + * Sends one already formatted protocol message over the media connection. + * The message is dropped, and PICA_OK returned, if the send would block or + * the system reports an error for it (e.g. an ICMP error caused by an + * earlier datagram) - for real time media that is the wanted behaviour. + */ +int PICA_media_send(struct PICA_c2c *c2c, const unsigned char *buf, unsigned int len); + +void PICA_media_fdset(struct PICA_c2n *c2n, fd_set *rfds, int *nfds); +void PICA_media_process(struct PICA_c2n *c2n, fd_set *rfds); + +/* implemented in PICA_client.c, used by PICA_media.c */ + +int PICA_verify_callback(int preverify_ok, X509_STORE_CTX *ctx); +int PICA_verify_peer_cert_common(X509 **peer_cert, SSL *ssl, const unsigned char *peer_id); +unsigned int PICA_media_process_messages(unsigned char *buf, unsigned int *read_pos, struct PICA_c2c *c2c); +void PICA_media_transport_changed(struct PICA_c2c *c2c, int transport, const char *ciphersuitename); +int PICA_media_send_ping(struct PICA_c2c *c2c, int reply); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/PICA_netconf.c b/PICA_netconf.c index 03c12ff..2ada9c3 100644 --- a/PICA_netconf.c +++ b/PICA_netconf.c @@ -1,5 +1,5 @@ /* - (c) Copyright 2012 - 2018 Anton Sviridenko + (c) Copyright 2012 - 2026 Anton Sviridenko https://picapica.im This program is free software: you can redistribute it and/or modify @@ -16,13 +16,14 @@ */ #include "PICA_netconf.h" #include <stddef.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> #ifdef HAVE_LIBMINIUPNPC #include <miniupnpc/miniupnpc.h> -#include <miniupnpc/miniwget.h> #include <miniupnpc/upnpcommands.h> #include <miniupnpc/upnperrors.h> -#include <stdio.h> #endif #ifndef WIN32 @@ -33,6 +34,7 @@ #define PREFIX4 htonl(0xf0000000U) #define PREFIX8 htonl(0xff000000U) +#define PREFIX10 htonl(0xffc00000U) #define PREFIX12 htonl(0xfff00000U) #define PREFIX16 htonl(0xffff0000U) #define PREFIX24 htonl(0xffffff00U) @@ -44,6 +46,7 @@ int PICA_is_reserved_addr_ipv4(in_addr_t addr) { if ((addr & PREFIX8) == 0 //0.0.0.0/8 || (addr & PREFIX8) == MAKEIP(10, 0, 0, 0) //10.0.0.0/8 + || (addr & PREFIX10) == MAKEIP(100, 64, 0, 0) //100.64.0.0/10 || (addr & PREFIX8) == MAKEIP(127, 0, 0, 0)//127.0.0.0/8 || (addr & PREFIX16) == MAKEIP(169, 254, 0, 0) //169.254.0.0/16 || (addr & PREFIX12) == MAKEIP(172, 16, 0, 0) //172.16.0.0/12 @@ -57,22 +60,178 @@ int PICA_is_reserved_addr_ipv4(in_addr_t addr) return 0; } -in_addr_t PICA_guess_listening_addr_ipv4() +int PICA_is_private_addr_ipv4(in_addr_t addr) +{ + return (addr & PREFIX8) == MAKEIP(10, 0, 0, 0) + || (addr & PREFIX12) == MAKEIP(172, 16, 0, 0) + || (addr & PREFIX16) == MAKEIP(192, 168, 0, 0) + || (addr & PREFIX10) == MAKEIP(100, 64, 0, 0); +} + +/* Whether an interface address is worth telling a peer about at all: either + * a private one, reachable from the same network, or a public one. + */ +static int is_usable_ifaddr_ipv4(in_addr_t addr) { - in_addr_t retaddr = INADDR_ANY; - int found_global = 0; + return PICA_is_private_addr_ipv4(addr) || !PICA_is_reserved_addr_ipv4(addr); +} + +/* Collects the usable addresses into addrs, the private ones (want_private) + * or the public ones, skipping the ones already there. + */ +static void ifaddr_add(in_addr_t *addrs, int maxcount, int *count, in_addr_t a, int want_private) +{ + int i; + + if (!is_usable_ifaddr_ipv4(a) || PICA_is_private_addr_ipv4(a) != want_private) + return; + + for (i = 0; i < *count; i++) + if (addrs[i] == a) + return; + + if (*count < maxcount) + addrs[(*count)++] = a; +} + #ifndef WIN32 +int PICA_get_ifaddrs_ipv4(in_addr_t *addrs, int maxcount) +{ struct ifaddrs *ifaddr, *ifa; + int count = 0; + int want_private; + + if (!addrs || maxcount <= 0) + return 0; if (getifaddrs(&ifaddr) == -1) - return INADDR_ANY; + return 0; - for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) + /* two passes: the private addresses go first, see the 0x0B message */ + for (want_private = 1; want_private >= 0; want_private--) + for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) + { + if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET) + continue; + + if (ifa->ifa_flags & IFF_LOOPBACK) + continue; + + if (!((ifa->ifa_flags & IFF_RUNNING) && (ifa->ifa_flags & IFF_UP))) + continue; + + ifaddr_add(addrs, maxcount, &count, + ((struct sockaddr_in*)ifa->ifa_addr)->sin_addr.s_addr, want_private); + } + + freeifaddrs(ifaddr); + + return count; +} +#else +int PICA_get_ifaddrs_ipv4(in_addr_t *addrs, int maxcount) +{ + PIP_ADAPTER_ADDRESSES buf = NULL, ap; + PIP_ADAPTER_UNICAST_ADDRESS ua; + ULONG size = 16384; + ULONG ret; + int count = 0; + int want_private; + int tries; + + if (!addrs || maxcount <= 0) + return 0; + + /* The size needed is only known by trying, and can grow between the + * attempts if an adapter appears meanwhile. + */ + for (tries = 0; tries < 3; tries++) { - if (ifa->ifa_addr == NULL) - continue; + buf = (PIP_ADAPTER_ADDRESSES)malloc(size); + + if (!buf) + return 0; + + ret = GetAdaptersAddresses(AF_INET, + GAA_FLAG_SKIP_ANYCAST + | GAA_FLAG_SKIP_MULTICAST + | GAA_FLAG_SKIP_DNS_SERVER + | GAA_FLAG_SKIP_FRIENDLY_NAME, + NULL, buf, &size); + + if (ret == NO_ERROR) + break; + + free(buf); + buf = NULL; - if (ifa->ifa_addr->sa_family != AF_INET) + if (ret != ERROR_BUFFER_OVERFLOW) + return 0; + } + + if (!buf) + return 0; + + for (want_private = 1; want_private >= 0; want_private--) + for (ap = buf; ap; ap = ap->Next) + { + if (ap->OperStatus != IfOperStatusUp || ap->IfType == IF_TYPE_SOFTWARE_LOOPBACK) + continue; + + for (ua = ap->FirstUnicastAddress; ua; ua = ua->Next) + { + if (ua->Address.lpSockaddr->sa_family != AF_INET) + continue; + + ifaddr_add(addrs, maxcount, &count, + ((struct sockaddr_in*)ua->Address.lpSockaddr)->sin_addr.s_addr, want_private); + } + } + + free(buf); + + return count; +} +#endif + +/* Stores a private interface address with its mask, skipping duplicates + * and masks that would make every address look local. + */ +static void private_ifaddr_add(in_addr_t *addrs, in_addr_t *masks, int maxcount, int *count, + in_addr_t a, in_addr_t mask) +{ + int i; + + if (!PICA_is_private_addr_ipv4(a) || mask == 0) + return; + + for (i = 0; i < *count; i++) + if (addrs[i] == a) + return; + + if (*count < maxcount) + { + addrs[*count] = a; + masks[*count] = mask; + (*count)++; + } +} + +#ifndef WIN32 +int PICA_get_private_ifaddrs_ipv4(in_addr_t *addrs, in_addr_t *masks, int maxcount) +{ + struct ifaddrs *ifaddr, *ifa; + int count = 0; + + if (!addrs || !masks || maxcount <= 0) + return 0; + + if (getifaddrs(&ifaddr) == -1) + return 0; + + for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) + { + if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET || ifa->ifa_netmask == NULL) continue; if (ifa->ifa_flags & IFF_LOOPBACK) @@ -81,102 +240,678 @@ in_addr_t PICA_guess_listening_addr_ipv4() if (!((ifa->ifa_flags & IFF_RUNNING) && (ifa->ifa_flags & IFF_UP))) continue; - if (!found_global) - { - retaddr = ((struct sockaddr_in*)ifa->ifa_addr)->sin_addr.s_addr; - - if (!PICA_is_reserved_addr_ipv4(retaddr)) - found_global = 1; - } + private_ifaddr_add(addrs, masks, maxcount, &count, + ((struct sockaddr_in*)ifa->ifa_addr)->sin_addr.s_addr, + ((struct sockaddr_in*)ifa->ifa_netmask)->sin_addr.s_addr); } freeifaddrs(ifaddr); + + return count; +} #else - char databuf[16384]; - ULONG size = sizeof databuf; - ULONG ret; - PIP_ADAPTER_ADDRESSES addrs = (PIP_ADAPTER_ADDRESSES)databuf; - PIP_ADAPTER_ADDRESSES ap; - - ret = GetAdaptersAddresses(AF_INET, - GAA_FLAG_SKIP_ANYCAST - | GAA_FLAG_SKIP_MULTICAST - | GAA_FLAG_SKIP_DNS_SERVER - | GAA_FLAG_SKIP_FRIENDLY_NAME, - NULL, - addrs, &size); - - if (ret != NO_ERROR) - return INADDR_ANY; +#ifndef MIB_IPADDR_DISCONNECTED +#define MIB_IPADDR_DISCONNECTED 0x0008 +#endif +#ifndef MIB_IPADDR_DELETED +#define MIB_IPADDR_DELETED 0x0040 +#endif - ap = addrs; - while(ap) +/* GetAdaptersAddresses() only reports the prefix length from Vista on, and + * only to code built for Vista; GetIpAddrTable() has the mask on every + * version. + */ +int PICA_get_private_ifaddrs_ipv4(in_addr_t *addrs, in_addr_t *masks, int maxcount) +{ + PMIB_IPADDRTABLE table = NULL; + ULONG size = 0; + DWORD ret; + DWORD i; + int count = 0; + int tries; + + if (!addrs || !masks || maxcount <= 0) + return 0; + + /* as in PICA_get_ifaddrs_ipv4(), the size needed is only known by + * trying */ + for (tries = 0; tries < 3; tries++) { - retaddr = ((struct sockaddr_in*)ap->FirstUnicastAddress->Address.lpSockaddr)->sin_addr.s_addr; - if (!PICA_is_reserved_addr_ipv4(retaddr)) + ret = GetIpAddrTable(table, &size, FALSE); + + if (ret == NO_ERROR) break; - ap = ap->Next; + + free(table); + table = NULL; + + if (ret != ERROR_INSUFFICIENT_BUFFER) + return 0; + + table = (PMIB_IPADDRTABLE)malloc(size); + + if (!table) + return 0; } + if (ret != NO_ERROR || !table) + { + free(table); + return 0; + } + + for (i = 0; i < table->dwNumEntries; i++) + { + if (table->table[i].wType & (MIB_IPADDR_DISCONNECTED | MIB_IPADDR_DELETED)) + continue; + + private_ifaddr_add(addrs, masks, maxcount, &count, + (in_addr_t)table->table[i].dwAddr, (in_addr_t)table->table[i].dwMask); + } + + free(table); + + return count; +} #endif - return retaddr; + +int PICA_find_subnet_ipv4(in_addr_t addr, const in_addr_t *addrs, const in_addr_t *masks, int count) +{ + int i; + + for (i = 0; i < count; i++) + if ((addr & masks[i]) == (addrs[i] & masks[i])) + return i; + + return -1; +} + +in_addr_t PICA_guess_listening_addr_ipv4() +{ + in_addr_t addrs[PICA_IFADDRS_MAX]; + int n, i; + + n = PICA_get_ifaddrs_ipv4(addrs, PICA_IFADDRS_MAX); + + if (n == 0) + return INADDR_ANY; + + /* the first public address if there is one, the first private one + * otherwise + */ + for (i = 0; i < n; i++) + if (!PICA_is_private_addr_ipv4(addrs[i])) + return addrs[i]; + + return addrs[0]; } #ifdef HAVE_LIBMINIUPNPC -int PICA_upnp_autoconfigure_ipv4(int public_port, int local_port, char *public_ip) + +/* UPnP error codes this code acts on, rather than just reporting */ +#define UPNP_ERR_CONFLICT 718 +#define UPNP_ERR_PERMONLY 725 +#define UPNP_ERR_CONFLICTOTHERMECH 729 + +/* sizes the IGD's mapping table entries are read into, from + * UPNP_GetSpecificPortMappingEntry() + */ +#define ENTRY_CLIENT_SIZE 16 +#define ENTRY_PORT_SIZE 6 +#define ENTRY_DESC_SIZE 80 +#define ENTRY_FLAG_SIZE 4 +#define ENTRY_LEASE_SIZE 16 + +struct PICA_upnp_ctx { - struct UPNPDev *devlist = NULL; - int error = 0; struct UPNPUrls urls; struct IGDdatas data; + /* our address on the side the IGD is on - what mappings point at */ char lanaddr[64]; - char wanaddr[64]; - char ppstr[8]; - char lpstr[8]; + int discover_timeout_ms; + + /* the mapping held through this context, if any */ + int mapped; + int port; + /* lease asked for, 0 for a permanent mapping */ + unsigned int lease_asked; + /* lease the IGD granted, which can be less */ + unsigned int lease; + char desc[ENTRY_DESC_SIZE]; +}; + +static void portstr(char *buf, size_t buflen, int port) +{ + snprintf(buf, buflen, "%d", port); +} + +/* Whether the request reached the IGD at all. miniupnpc answers its own + * problems - the control URL not responding, a reply that did not parse - + * with negative values, and anything the device itself refused with the + * positive UPnP error code it sent. + */ +static int comm_error(int ret) +{ + return ret < 0; +} + +static int is_conflict(int ret) +{ + return ret == UPNP_ERR_CONFLICT || ret == UPNP_ERR_CONFLICTOTHERMECH; +} + +static void drop_igd(struct PICA_upnp_ctx *ctx) +{ + if (ctx->urls.controlURL) + { + FreeUPNPUrls(&ctx->urls); + memset(&ctx->urls, 0, sizeof(ctx->urls)); + } +} + +static int find_igd(struct PICA_upnp_ctx *ctx) +{ + struct UPNPDev *devlist; + int error = 0; int ret; +#if MINIUPNPC_API_VERSION >= 18 + char wanaddr[64]; +#endif + + drop_igd(ctx); #if MINIUPNPC_API_VERSION < 14 - devlist = upnpDiscover(2000, 0, 0, 0, 0, &error); + devlist = upnpDiscover(ctx->discover_timeout_ms, 0, 0, 0, 0, &error); #else - devlist = upnpDiscover(2000, 0, 0, 0, 0, 2, &error); + devlist = upnpDiscover(ctx->discover_timeout_ms, 0, 0, 0, 0, 2, &error); #endif + if (!devlist) + return PICA_UPNP_ERRNOIGD; + #if MINIUPNPC_API_VERSION < 18 - ret = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); + ret = UPNP_GetValidIGD(devlist, &ctx->urls, &ctx->data, ctx->lanaddr, sizeof(ctx->lanaddr)); #else - ret = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr), wanaddr, sizeof(wanaddr)); + ret = UPNP_GetValidIGD(devlist, &ctx->urls, &ctx->data, ctx->lanaddr, sizeof(ctx->lanaddr), + wanaddr, sizeof(wanaddr)); #endif - if (ret != 1) + + freeUPNPDevlist(devlist); + + if (ret == 1) + return PICA_UPNP_OK; + + /* Every outcome but "nothing found" leaves the URLs allocated, usable or + * not. + */ + drop_igd(ctx); + + /* The meaning of the other values changed when the wanaddr parameter + * appeared: before that there were three of them, now there are four and + * an IGD whose own external address is private has one of its own. + */ +#if MINIUPNPC_API_VERSION < 18 + if (ret == 2) + return PICA_UPNP_ERRNOTCONN; +#else + if (ret == 2) + return PICA_UPNP_ERRPRIVADDR; + + if (ret == 3) + return PICA_UPNP_ERRNOTCONN; +#endif + + return PICA_UPNP_ERRNOIGD; +} + +/* The control URLs are gone when an earlier attempt to find the IGD again + * failed - after it rebooted, say - and have to be looked for once more + * before anything can be asked of it. + */ +static int ensure_igd(struct PICA_upnp_ctx *ctx) +{ + if (ctx->urls.controlURL) + return PICA_UPNP_OK; + + return find_igd(ctx); +} + +/* Reads the IGD's mapping table entry for this port. + * \return PICA_UPNP_OK and whether the entry points at the same port of this + * very machine - i.e. whether it is ours, made by this client now or by an + * earlier run of it - through ours, and the remaining lease through lease; + * otherwise the UPnP error (714 NoSuchEntryInArray when there is none) + */ +static int read_entry(struct PICA_upnp_ctx *ctx, const char *proto, int port, int *ours, unsigned int *lease) +{ + char portbuf[8]; + char client[ENTRY_CLIENT_SIZE] = ""; + char intport[ENTRY_PORT_SIZE] = ""; + char desc[ENTRY_DESC_SIZE] = ""; + char enabled[ENTRY_FLAG_SIZE] = ""; + char leasebuf[ENTRY_LEASE_SIZE] = ""; + int ret; + + portstr(portbuf, sizeof(portbuf), port); + + ret = UPNP_GetSpecificPortMappingEntry(ctx->urls.controlURL, ctx->data.first.servicetype, + portbuf, proto, NULL, + client, intport, desc, enabled, leasebuf); + + if (ret != UPNPCOMMAND_SUCCESS) + return comm_error(ret) ? PICA_UPNP_ERRIGD : ret; + + if (ours) + *ours = strcmp(client, ctx->lanaddr) == 0 && atoi(intport) == port; + + if (lease) + *lease = (unsigned int)strtoul(leasebuf, NULL, 10); + + return PICA_UPNP_OK; +} + +static int entry_is_ours(struct PICA_upnp_ctx *ctx, const char *proto, int port) +{ + int ours = 0; + + return read_entry(ctx, proto, port, &ours, NULL) == PICA_UPNP_OK && ours; +} + +static void del_mapping(struct PICA_upnp_ctx *ctx, const char *proto, int port) +{ + char portbuf[8]; + + if (!ctx->urls.controlURL) + return; + + portstr(portbuf, sizeof(portbuf), port); + + UPNP_DeletePortMapping(ctx->urls.controlURL, ctx->data.first.servicetype, + portbuf, proto, NULL); +} + +/* One AddPortMapping, external and internal port the same, with the lease + * this context settled on. A device that only supports permanent mappings + * says so with 725 instead of mapping anything; the context remembers that + * and stops asking for a lease. + */ +static int add_mapping(struct PICA_upnp_ctx *ctx, const char *proto, int port) +{ + char portbuf[8], leasebuf[16]; + int ret; + + portstr(portbuf, sizeof(portbuf), port); + snprintf(leasebuf, sizeof(leasebuf), "%u", ctx->lease_asked); + + ret = UPNP_AddPortMapping(ctx->urls.controlURL, ctx->data.first.servicetype, + portbuf, portbuf, ctx->lanaddr, ctx->desc, proto, NULL, leasebuf); + + if (ret == UPNP_ERR_PERMONLY && ctx->lease_asked != 0) { - freeUPNPDevlist(devlist); - return 0; + ctx->lease_asked = 0; + snprintf(leasebuf, sizeof(leasebuf), "0"); + + ret = UPNP_AddPortMapping(ctx->urls.controlURL, ctx->data.first.servicetype, + portbuf, portbuf, ctx->lanaddr, ctx->desc, proto, NULL, leasebuf); } - ret = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, public_ip); + /* A conflict with a mapping that is ours anyway - this client having been + * killed before it could delete it, or a renewal on a device that does + * not let a mapping be added over itself - is no conflict. Taking it out + * and making it again is what gets it a fresh lease. + */ + if (is_conflict(ret) && entry_is_ours(ctx, proto, port)) + { + del_mapping(ctx, proto, port); - if (ret != UPNPCOMMAND_SUCCESS) + ret = UPNP_AddPortMapping(ctx->urls.controlURL, ctx->data.first.servicetype, + portbuf, portbuf, ctx->lanaddr, ctx->desc, proto, NULL, leasebuf); + } + + if (ret == UPNPCOMMAND_SUCCESS) + return PICA_UPNP_OK; + + if (comm_error(ret)) + return PICA_UPNP_ERRIGD; + + return is_conflict(ret) ? PICA_UPNP_ERRCONFLICT : ret; +} + +/* Maps the port number for both protocols, or for none: a pair where only + * one half could be had is of no use and is given back. A failure of the + * second half after the first one succeeded means that this port number is + * not to be had, whatever the device answered, so it is reported as a + * conflict - the next number may well do. + */ +static int map_pair(struct PICA_upnp_ctx *ctx, int port) +{ + int ret; + unsigned int granted = 0; + + ret = ensure_igd(ctx); + + if (ret != PICA_UPNP_OK) + return ret; + + ret = add_mapping(ctx, "TCP", port); + + if (ret != PICA_UPNP_OK) + return ret; + + ret = add_mapping(ctx, "UDP", port); + + if (ret != PICA_UPNP_OK) { - freeUPNPDevlist(devlist); - FreeUPNPUrls(&urls); - return 0; + del_mapping(ctx, "TCP", port); + return ret == PICA_UPNP_ERRIGD ? ret : PICA_UPNP_ERRCONFLICT; + } + + /* A device is free to grant a shorter lease than the one asked for - + * IGD:2 ones clamp it to a week at most - and renewal has to be timed by + * what it actually granted. Devices that do not report it are assumed to + * have granted the request. + */ + ctx->lease = ctx->lease_asked; + + if (read_entry(ctx, "TCP", port, NULL, &granted) == PICA_UPNP_OK + && granted > 0 && (ctx->lease == 0 || granted < ctx->lease)) + ctx->lease = granted; + + ctx->port = port; + ctx->mapped = 1; + + return PICA_UPNP_OK; +} + +int PICA_upnp_discover(int timeout_ms, struct PICA_upnp_ctx **ctx) +{ + struct PICA_upnp_ctx *c; + int ret; + + if (!ctx || timeout_ms <= 0) + return PICA_UPNP_ERRINVARG; + + c = (struct PICA_upnp_ctx*)calloc(1, sizeof(struct PICA_upnp_ctx)); + + if (!c) + return PICA_UPNP_ERRNOMEM; + + c->discover_timeout_ms = timeout_ms; + + ret = find_igd(c); + + if (ret != PICA_UPNP_OK) + { + free(c); + return ret; } - sprintf(ppstr, "%u", public_port); - sprintf(lpstr, "%u", local_port); + *ctx = c; - ret = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, - ppstr, lpstr, lanaddr, "Pica Pica", "TCP", 0, "0"); + return PICA_UPNP_OK; +} +void PICA_upnp_free(struct PICA_upnp_ctx *ctx) +{ + if (!ctx) + return; + + PICA_upnp_unmap(ctx); + drop_igd(ctx); + free(ctx); +} + +int PICA_upnp_external_addr(struct PICA_upnp_ctx *ctx, char *addr, size_t addrlen) +{ + /* UPNP_GetExternalIPAddress() writes an address of up to 16 octets and + * nothing else, so it gets a buffer that is known to be big enough. + */ + char buf[64] = ""; + int ret; + + if (!ctx || !addr || addrlen < 16) + return PICA_UPNP_ERRINVARG; + + ret = ensure_igd(ctx); + + if (ret != PICA_UPNP_OK) + return ret; + + ret = UPNP_GetExternalIPAddress(ctx->urls.controlURL, ctx->data.first.servicetype, buf); if (ret != UPNPCOMMAND_SUCCESS) - ret = 0; - else - ret = 1; + return comm_error(ret) ? PICA_UPNP_ERRIGD : ret; - freeUPNPDevlist(devlist); - FreeUPNPUrls(&urls); - return ret; + if (inet_addr(buf) == INADDR_NONE) + return PICA_UPNP_ERRIGD; + + /* Behind a second NAT - the provider's, usually - the IGD's external + * address is private too, and a mapping on it leads nowhere from the + * Internet. + */ + if (PICA_is_reserved_addr_ipv4(inet_addr(buf))) + return PICA_UPNP_ERRPRIVADDR; + + snprintf(addr, addrlen, "%s", buf); + + return PICA_UPNP_OK; } -#endif +const char *PICA_upnp_lan_addr(const struct PICA_upnp_ctx *ctx) +{ + return ctx ? ctx->lanaddr : ""; +} + +int PICA_upnp_map(struct PICA_upnp_ctx *ctx, int port, unsigned int lease_secs, const char *desc) +{ + if (!ctx || port <= 0 || port > 65535) + return PICA_UPNP_ERRINVARG; + + PICA_upnp_unmap(ctx); + + ctx->lease_asked = lease_secs; + snprintf(ctx->desc, sizeof(ctx->desc), "%s", desc ? desc : "Pica Pica"); + + return map_pair(ctx, port); +} + +int PICA_upnp_refresh(struct PICA_upnp_ctx *ctx) +{ + int ret, ours = 0; + int port; + + if (!ctx || !ctx->mapped) + return PICA_UPNP_ERRINVARG; + + port = ctx->port; + + ret = ensure_igd(ctx); + + if (ret != PICA_UPNP_OK) + { + ctx->mapped = 0; + return ret; + } + /* Either the mapping is there and ours, or it is gone (714), or the port + * now points somewhere else, or the IGD does not answer at all - which of + * them it is decides what to do, so it has to be read rather than guessed. + */ + ret = read_entry(ctx, "TCP", port, &ours, NULL); + + if (ret == PICA_UPNP_ERRIGD) + { + /* The control URLs are an address and a path the IGD handed out + * once; after it rebooted, or changed address, they lead nowhere + * and the device has to be looked for again. + */ + ret = find_igd(ctx); + + if (ret != PICA_UPNP_OK) + { + ctx->mapped = 0; + return ret; + } + } + else if (ret == PICA_UPNP_OK && !ours) + { + /* Something else behind this IGD took the port over - another + * instance, another machine, or a different program altogether. + * Many devices let that happen silently instead of reporting a + * conflict. The mapping is not ours to renew any more. + */ + fprintf(stderr, "UPnP: external port %i has been taken over by another host\n", port); + ctx->mapped = 0; + return PICA_UPNP_ERRCONFLICT; + } + + /* Adding the mapping again is what renews its lease; it also puts it back + * when the IGD has dropped or forgotten it in the meantime. + */ + ctx->mapped = 0; + + return map_pair(ctx, port); +} + +void PICA_upnp_unmap(struct PICA_upnp_ctx *ctx) +{ + if (!ctx || !ctx->mapped) + return; + + del_mapping(ctx, "TCP", ctx->port); + del_mapping(ctx, "UDP", ctx->port); + + ctx->mapped = 0; + ctx->port = 0; +} + +int PICA_upnp_mapped(const struct PICA_upnp_ctx *ctx) +{ + return ctx && ctx->mapped; +} + +int PICA_upnp_port(const struct PICA_upnp_ctx *ctx) +{ + return (ctx && ctx->mapped) ? ctx->port : 0; +} + +unsigned int PICA_upnp_lease(const struct PICA_upnp_ctx *ctx) +{ + return ctx ? ctx->lease : 0; +} + +const char *PICA_upnp_strerror(int ret) +{ + const char *s; + + switch (ret) + { + case PICA_UPNP_OK: + return "success"; + + case PICA_UPNP_ERRNOIGD: + return "no UPnP internet gateway device found on the local network"; + + case PICA_UPNP_ERRNOTCONN: + return "the UPnP gateway reports that it has no internet connection"; + + case PICA_UPNP_ERRNOMEM: + return "out of memory"; + + case PICA_UPNP_ERRINVARG: + return "invalid argument"; + + case PICA_UPNP_ERRCONFLICT: + return "the port is already forwarded to another host"; + + case PICA_UPNP_ERRPRIVADDR: + return "the UPnP gateway itself has a private address, it is behind another NAT"; + + case PICA_UPNP_ERRIGD: + return "the UPnP gateway did not answer or answered something unusable"; + + case PICA_UPNP_ERRNOSUPPORT: + return "this build has no UPnP support"; + + default: + break; + } + + s = strupnperror(ret); + + return s ? s : "unknown UPnP error"; +} + +#else /* !HAVE_LIBMINIUPNPC */ + +int PICA_upnp_discover(int timeout_ms, struct PICA_upnp_ctx **ctx) +{ + (void)timeout_ms; + (void)ctx; + return PICA_UPNP_ERRNOSUPPORT; +} + +void PICA_upnp_free(struct PICA_upnp_ctx *ctx) +{ + (void)ctx; +} + +int PICA_upnp_external_addr(struct PICA_upnp_ctx *ctx, char *addr, size_t addrlen) +{ + (void)ctx; + (void)addr; + (void)addrlen; + return PICA_UPNP_ERRNOSUPPORT; +} + +const char *PICA_upnp_lan_addr(const struct PICA_upnp_ctx *ctx) +{ + (void)ctx; + return ""; +} + +int PICA_upnp_map(struct PICA_upnp_ctx *ctx, int port, unsigned int lease_secs, const char *desc) +{ + (void)ctx; + (void)port; + (void)lease_secs; + (void)desc; + return PICA_UPNP_ERRNOSUPPORT; +} + +int PICA_upnp_refresh(struct PICA_upnp_ctx *ctx) +{ + (void)ctx; + return PICA_UPNP_ERRNOSUPPORT; +} + +void PICA_upnp_unmap(struct PICA_upnp_ctx *ctx) +{ + (void)ctx; +} + +int PICA_upnp_mapped(const struct PICA_upnp_ctx *ctx) +{ + (void)ctx; + return 0; +} + +int PICA_upnp_port(const struct PICA_upnp_ctx *ctx) +{ + (void)ctx; + return 0; +} + +unsigned int PICA_upnp_lease(const struct PICA_upnp_ctx *ctx) +{ + (void)ctx; + return 0; +} + +const char *PICA_upnp_strerror(int ret) +{ + (void)ret; + return "this build has no UPnP support"; +} + +#endif diff --git a/PICA_netconf.h b/PICA_netconf.h index c9bc767..02a9afd 100644 --- a/PICA_netconf.h +++ b/PICA_netconf.h @@ -1,5 +1,5 @@ /* - (c) Copyright 2012 - 2018 Anton Sviridenko + (c) Copyright 2012 - 2026 Anton Sviridenko https://picapica.im This program is free software: you can redistribute it and/or modify @@ -17,6 +17,8 @@ #ifndef PICA_NETCONF_H #define PICA_NETCONF_H +#include <stddef.h> + #ifndef WIN32 #include <netinet/in.h> @@ -24,8 +26,13 @@ #else +#ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 +#endif +/* PICA_client.c and PICA_media.c include this after the system headers */ +#ifndef _WIN32_WINNT #define _WIN32_WINNT 0x501 +#endif #include <winsock2.h> #include <ws2ipdef.h> #include <wincrypt.h> @@ -36,21 +43,183 @@ typedef u_long in_addr_t; typedef u_short in_port_t; #endif +/* Most interface addresses PICA_get_ifaddrs_ipv4() reports. */ +#define PICA_IFADDRS_MAX 32 + +/* UPnP return values. Negative ones are detected here, zero is success, and + * positive ones are UPnP error codes answered by the device, as listed in + * miniupnpc's upnpcommands.h. PICA_upnp_strerror() turns any of them into + * something printable. + */ +#define PICA_UPNP_OK 0 +/** nothing answered the discovery, or what did is not an IGD */ +#define PICA_UPNP_ERRNOIGD -1 +/** an IGD, but its WAN connection is down */ +#define PICA_UPNP_ERRNOTCONN -2 +#define PICA_UPNP_ERRNOMEM -3 +#define PICA_UPNP_ERRINVARG -4 +/** the port number is taken on the IGD, for TCP or for UDP, by another host + * or another program - the next number may still be free */ +#define PICA_UPNP_ERRCONFLICT -5 +/** the IGD's own external address is private - carrier NAT behind the NAT, + * nothing mapped there can be reached from the Internet */ +#define PICA_UPNP_ERRPRIVADDR -6 +/** the request did not reach the IGD, or it answered something unusable */ +#define PICA_UPNP_ERRIGD -7 +/** this build has no UPnP support */ +#define PICA_UPNP_ERRNOSUPPORT -8 + +/* Lease to ask for. Short enough that a mapping left behind by a client that + * died without deleting it disappears on its own; long enough that renewing + * it, at half of whatever the device granted, is a rare event. + */ +#define PICA_UPNP_LEASE_DEFAULT 3600 + +/* How long PICA_upnp_discover() waits for devices to answer. */ +#define PICA_UPNP_DISCOVER_TIMEOUT 2000 + +/* A port mapping on a UPnP IGD. + * + * The context holds the result of finding the IGD together with the mapping + * held through it, so that discovery - a multicast search that has to wait + * for devices to answer - is paid once, and the mapping can be renewed and + * deleted later on with the same control URLs. + * + * A mapping always covers TCP and UDP with the same port number, and the + * external port number is the same as the local one: the directc2c + * connection is made over TCP and the media of a call over UDP to the same + * announced port, see the 0x0B message in doc/proto-doc-latest.txt. + * + * A mapping is never permanent, whatever lease is asked for: IGD:2 devices + * clamp a request for an infinite lease to a week, and any device loses its + * mappings when it reboots. A mapping that is meant to stay up has to be + * renewed - see PICA_upnp_refresh(). + * + * Every call blocks for as long as the device takes to answer, discovery for + * the whole timeout, so a context belongs on a thread that can afford to + * wait - never on one carrying media. Nothing here is thread safe; one + * context belongs to one thread. + * + * Without miniupnpc every function is still there and fails with + * PICA_UPNP_ERRNOSUPPORT, so that callers need no conditional code. + */ +struct PICA_upnp_ctx; + #ifdef __cplusplus extern "C" { #endif +/** 0.0.0.0/8, loopback, link-local, multicast, the reserved 240.0.0.0/4, + * broadcast, and the private ranges of PICA_is_private_addr_ipv4() */ int PICA_is_reserved_addr_ipv4(in_addr_t); +/** 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 and the shared address space + * 100.64.0.0/10 - addresses only reachable from the same local network, + * VPN or provider network */ +int PICA_is_private_addr_ipv4(in_addr_t); + +/** + * IPv4 addresses of the network interfaces that are up, other than loopback + * and link-local ones: the private addresses first, then the public ones, in + * the order the system lists the interfaces in. + * \param addrs filled with the addresses, network byte order + * \param maxcount size of addrs + * \return number of addresses stored, 0 if there are none or the system + * cannot be asked + */ +int PICA_get_ifaddrs_ipv4(in_addr_t *addrs, int maxcount); + +/** + * The private addresses (see PICA_is_private_addr_ipv4()) of the network + * interfaces that are up, with their netmasks, i.e. the private networks + * this host is on. + * \param addrs, masks filled with the addresses and their netmasks, network + * byte order + * \param maxcount size of addrs and masks + * \return number of addresses stored, 0 if there are none or the system + * cannot be asked + */ +int PICA_get_private_ifaddrs_ipv4(in_addr_t *addrs, in_addr_t *masks, int maxcount); + +/** + * Looks for the interface address of PICA_get_private_ifaddrs_ipv4() whose + * network addr is on. + * \return its index, or -1 if addr is on none of them + */ +int PICA_find_subnet_ipv4(in_addr_t addr, const in_addr_t *addrs, const in_addr_t *masks, int count); + in_addr_t PICA_guess_listening_addr_ipv4(); -#ifdef HAVE_LIBMINIUPNPC -int PICA_upnp_autoconfigure_ipv4(int public_port, int local_port, char *public_ip); -#endif +/** + * Looks for an IGD on the local network and, having found one, returns a + * context to use it with. + * \param timeout_ms how long to wait for devices to answer, + * PICA_UPNP_DISCOVER_TIMEOUT is sensible + * \param ctx filled with the new context on success, untouched otherwise + */ +int PICA_upnp_discover(int timeout_ms, struct PICA_upnp_ctx **ctx); + +/** Deletes the mapping the context holds, if any, and frees it. */ +void PICA_upnp_free(struct PICA_upnp_ctx *ctx); + +/** + * The IGD's address on the Internet side, as it reports it itself. + * Fails with PICA_UPNP_ERRPRIVADDR if that address is a private one, since + * announcing it would be of no use to anybody. + * \param addr buffer for the address as a string, at least 16 octets + */ +int PICA_upnp_external_addr(struct PICA_upnp_ctx *ctx, char *addr, size_t addrlen); + +/** Our own address on the side the IGD is on, i.e. the address mappings made + * through this context point at. */ +const char *PICA_upnp_lan_addr(const struct PICA_upnp_ctx *ctx); + +/** + * Maps the external port number port, TCP and UDP both, to the same port + * number of this machine. Either both protocols are mapped or neither is. + * + * A mapping left behind by an earlier run of this same client (same machine, + * same port) is recognised as ours and replaced rather than treated as a + * conflict. A context holds one mapping; mapping again replaces it. + * + * \param lease_secs lease to ask for, 0 for a permanent mapping + * \param desc description for the IGD's mapping table, may be NULL + * \retval PICA_UPNP_ERRCONFLICT the port number is taken by somebody else, + * for one of the protocols at least; the next number may be free + */ +int PICA_upnp_map(struct PICA_upnp_ctx *ctx, int port, unsigned int lease_secs, const char *desc); + +/** + * Renews the lease of the mapping this context holds, also putting it back + * if the IGD dropped it in the meantime, and finding the IGD again if its + * control URLs stopped working (it rebooted or changed address). + * + * \retval PICA_UPNP_ERRCONFLICT the external port has been taken over by + * another host or program; the context no longer holds a mapping + */ +int PICA_upnp_refresh(struct PICA_upnp_ctx *ctx); + +/** Deletes the mapping the context holds. The context stays usable. */ +void PICA_upnp_unmap(struct PICA_upnp_ctx *ctx); + +/** Whether the context currently holds a mapping. */ +int PICA_upnp_mapped(const struct PICA_upnp_ctx *ctx); + +/** Port number of the mapping the context holds, 0 if it holds none. */ +int PICA_upnp_port(const struct PICA_upnp_ctx *ctx); + +/** + * Lease the IGD granted for the mapping, in seconds; 0 when it only supports + * permanent mappings. A device is free to grant less than was asked for, so + * this is what renewal has to be timed by. + */ +unsigned int PICA_upnp_lease(const struct PICA_upnp_ctx *ctx); + +/** Printable form of any of the UPnP return values. Never NULL. */ +const char *PICA_upnp_strerror(int ret); #ifdef __cplusplus } #endif #endif - diff --git a/PICA_node.c b/PICA_node.c index 4a59102..ab7da94 100644 --- a/PICA_node.c +++ b/PICA_node.c @@ -60,14 +60,31 @@ typedef u_short uint16_t; #define NOREPLY_TIMEOUT 15 #define KEEPALIVE_TIMEOUT 60 +//"Get my UDP address": how long an issued token is accepted from the UDP socket +#define UDPADDR_TOKEN_TIMEOUT 10 //sec +//A client is served this many MYUDPADDRREQ messages in a row, and one more +//for every UDPADDR_REQ_PERIOD seconds after that +#define UDPADDR_REQ_BURST 4 +#define UDPADDR_REQ_PERIOD 5 //sec +#define UDPADDR_TOKEN_BUCKETS 1024 +//datagrams taken from the UDP socket per event, so that a flood of them does +//not keep the event loop away from the connections +#define UDP_READ_BATCH 64 + time_t skynet_refresh_tmst; -clock_t TMO_CCLINK_WAITACTIVE = 15; //CONF +time_t TMO_CCLINK_WAITACTIVE = 15; //CONF char *my_addr;//TEMP CONF FIXME static struct event_base *pica_event_base; SOCKET listen_comm_sck;//* +//UDP socket on the port with the same number as listen_comm_sck, -1 if it +//could not be opened. Nothing is ever sent from it. +SOCKET listen_udp_sck = -1; + +//clients with an issued "get my UDP address" token, hashed by the token +static struct client *udpaddr_tokens[UDPADDR_TOKEN_BUCKETS]; static int stop_node_loop = 0; @@ -119,6 +136,8 @@ unsigned int procmsg_PINGREP_node(unsigned char* buf, unsigned int size, void* p unsigned int procmsg_dummy_multi_c2n(unsigned char* buf, unsigned int size, void* ptr); unsigned int procmsg_MULTILOGIN_client(unsigned char* buf, unsigned int size, void* ptr); unsigned int procmsg_MULTILOGIN_node(unsigned char* buf, unsigned int size, void* ptr); +unsigned int procmsg_MYTCPADDRREQ(unsigned char* buf, unsigned int size, void* ptr); +unsigned int procmsg_MYUDPADDRREQ(unsigned char* buf, unsigned int size, void* ptr); struct cclink* cclink_list_add(struct client *clr, struct client *cle); struct cclink* cclink_list_search(const unsigned char *caller_id, const unsigned char *callee_id); @@ -164,6 +183,7 @@ void process_n2n_read(evutil_socket_t s, short event, void *arg); void process_n2n_write(evutil_socket_t s, short event, void *arg); void process_c2c_read(evutil_socket_t s, short event, void *arg); void process_c2c_write(evutil_socket_t s, short event, void *arg); +void process_udp_read(evutil_socket_t s, short event, void *arg); void process_nodewait(); #define MSGINFO_MSGSNUM(arr) (sizeof(arr)/sizeof(struct PICA_msginfo)) @@ -176,7 +196,9 @@ struct PICA_msginfo _msginfo_comm[] = {PICA_PROTO_CLNODELISTREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_CLNODELISTREQ_SIZE, procmsg_NODELISTREQ}, {PICA_PROTO_PINGREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_PINGREQ_SIZE, procmsg_PINGREQ_client}, {PICA_PROTO_PINGREP, PICA_MSG_FIXED_SIZE, PICA_PROTO_PINGREP_SIZE, procmsg_PINGREP_client}, - {PICA_PROTO_MULTILOGIN, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_MULTILOGIN_client} + {PICA_PROTO_MULTILOGIN, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_MULTILOGIN_client}, + {PICA_PROTO_MYTCPADDRREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_MYTCPADDRREQ_SIZE, procmsg_MYTCPADDRREQ}, + {PICA_PROTO_MYUDPADDRREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_MYUDPADDRREQ_SIZE, procmsg_MYUDPADDRREQ} }; struct PICA_msginfo _msginfo_node[] = @@ -214,7 +236,9 @@ struct PICA_msginfo _msginfo_multi[] = {PICA_PROTO_CLNODELISTREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_CLNODELISTREQ_SIZE, procmsg_NODELISTREQ}, {PICA_PROTO_PINGREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_PINGREQ_SIZE, procmsg_PINGREQ_client}, {PICA_PROTO_PINGREP, PICA_MSG_FIXED_SIZE, PICA_PROTO_PINGREP_SIZE, procmsg_PINGREP_client}, - {PICA_PROTO_MULTILOGIN, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_MULTILOGIN_client} + {PICA_PROTO_MULTILOGIN, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_MULTILOGIN_client}, + {PICA_PROTO_MYTCPADDRREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_MYTCPADDRREQ_SIZE, procmsg_MYTCPADDRREQ}, + {PICA_PROTO_MYUDPADDRREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_MYUDPADDRREQ_SIZE, procmsg_MYUDPADDRREQ} }; static int process_async_ssl_readwrite(SSL *ssl, int ret) @@ -268,6 +292,13 @@ unsigned int procmsg_INITREQ(unsigned char* buf, unsigned int size, void* ptr) PICA_debug1("received INITREQ"); + /* Exactly one request message per newconn. A second (e.g. two INITREQs in + * one record) would create a second client on the same socket and orphan + * the first, which later closes a socket it no longer owns. + */ + if (nc->type != NEWCONN_UNKNOWN) + return 0; + nc->type = NEWCONN_C2N; if (buf[2] == PICA_PROTO_VER_HIGH && buf[3] == PICA_PROTO_VER_LOW) @@ -350,6 +381,10 @@ unsigned int procmsg_CONNID(unsigned char* buf, unsigned int size, void* ptr) PICA_debug1("received CONNID"); + /* One request message per newconn - see procmsg_INITREQ(). */ + if (nc->type != NEWCONN_UNKNOWN) + return 0; + nc->type = NEWCONN_C2C; caller_id = buf + 2; @@ -405,6 +440,10 @@ unsigned int procmsg_NODECONNREQ(unsigned char* buf, unsigned int size, void* pt PICA_debug1("received NODECONNREQ"); + /* One request message per newconn - see procmsg_INITREQ(). */ + if (nc->type != NEWCONN_UNKNOWN) + return 0; + nc->type = NEWCONN_N2N; if (buf[2] == PICA_PROTO_VER_HIGH && @@ -645,6 +684,136 @@ unsigned int procmsg_PINGREP_client(unsigned char* buf, unsigned int size, void* return 1; } +unsigned int procmsg_MYTCPADDRREQ(unsigned char* buf, unsigned int size, void* ptr) +{ + struct client *c = (struct client*)ptr; + struct PICA_proto_msg *mp; + + PICA_debug3("MYTCPADDRREQ"); + + //IPv6 + if ((mp = client_wbuf_push(c, PICA_PROTO_MYTCPADDR_IPV4, PICA_PROTO_MYTCPADDR_IPV4_SIZE))) + { + memcpy(mp->tail, &c->addr.sin_addr.s_addr, 4); + memcpy(mp->tail + 4, &c->addr.sin_port, 2); + } + else + return 0; + + return 1; +} + +static unsigned int udpaddr_token_bucket(const unsigned char *token) +{ + //tokens are random and are generated by the node itself, so any part of + //one is as good a hash as any other, and a client has no say in which + //bucket it ends up in + return (token[0] | (token[1] << 8)) % UDPADDR_TOKEN_BUCKETS; +} + +static void client_udpaddr_token_drop(struct client *c) +{ + struct client **pp; + + if (!c->udpaddr_token_issued) + return; + + pp = &udpaddr_tokens[udpaddr_token_bucket(c->udpaddr_token)]; + + while(*pp && *pp != c) + pp = &(*pp)->udpaddr_token_next; + + if (*pp) + *pp = c->udpaddr_token_next; + + c->udpaddr_token_next = NULL; + c->udpaddr_token_issued = 0; +} + +static struct client *udpaddr_token_search(const unsigned char *token) +{ + struct client *c = udpaddr_tokens[udpaddr_token_bucket(token)]; + + while(c && CRYPTO_memcmp(c->udpaddr_token, token, PICA_PROTO_MYUDPADDR_TOKENSIZE) != 0) + c = c->udpaddr_token_next; + + return c; +} + +static int client_udpaddr_req_allowed(struct client *c) +{ + time_t now = time(0); + time_t periods; + + if (now < c->udpaddr_req_tmst)//the clock was set back + c->udpaddr_req_tmst = now; + + periods = (now - c->udpaddr_req_tmst) / UDPADDR_REQ_PERIOD; + + if (periods >= (time_t)(UDPADDR_REQ_BURST - c->udpaddr_req_allowance)) + { + c->udpaddr_req_allowance = UDPADDR_REQ_BURST; + c->udpaddr_req_tmst = now; + } + else + { + c->udpaddr_req_allowance += periods; + c->udpaddr_req_tmst += periods * UDPADDR_REQ_PERIOD; + } + + if (!c->udpaddr_req_allowance) + return 0; + + c->udpaddr_req_allowance--; + + return 1; +} + +//The reply to this message is a token, which the client then sends to the UDP +//socket - see process_udp_read() for what makes that exchange safe to offer. +unsigned int procmsg_MYUDPADDRREQ(unsigned char* buf, unsigned int size, void* ptr) +{ + struct client *c = (struct client*)ptr; + struct PICA_proto_msg *mp; + unsigned char token[PICA_PROTO_MYUDPADDR_TOKENSIZE]; + + PICA_debug3("MYUDPADDRREQ"); + + //A request that is not served is ignored rather than answered: the client + //has to cope with its datagrams being lost anyway, and gives up by timeout. + if (listen_udp_sck == -1) + return 1; + + if (!client_udpaddr_req_allowed(c)) + { + PICA_debug2("too many MYUDPADDRREQ from client %p, ignoring", (void*)c); + return 1; + } + + if (RAND_bytes(token, sizeof token) != 1) + { + PICA_error("RAND_bytes() failed, unable to issue a token for MYUDPADDRREQ"); + return 1; + } + + if (!(mp = client_wbuf_push(c, PICA_PROTO_MYUDPADDRTOKEN, PICA_PROTO_MYUDPADDRTOKEN_SIZE))) + return 0; + + memcpy(mp->tail, token, sizeof token); + + //one outstanding token per connection, a new request replaces the old one + client_udpaddr_token_drop(c); + + memcpy(c->udpaddr_token, token, sizeof token); + c->udpaddr_token_tmst = time(0); + c->udpaddr_token_issued = 1; + + c->udpaddr_token_next = udpaddr_tokens[udpaddr_token_bucket(token)]; + udpaddr_tokens[udpaddr_token_bucket(token)] = c; + + return 1; +} + unsigned int procmsg_MULTILOGIN_client(unsigned char* buf, unsigned int size, void* ptr) { struct client *other, *me = (struct client*)ptr; @@ -769,7 +938,7 @@ unsigned int procmsg_MULTILOGIN_node(unsigned char* buf, unsigned int size, void if (mp) { - memcpy(mp, buf, size); + memcpy(mp->tail, buf + 2, size - 2); } c = c->next_multi; @@ -957,7 +1126,7 @@ unsigned int procmsg_NODELISTREQ(unsigned char* buf, unsigned int size, void* pt switch(nlp->addr_type) { case PICA_PROTO_NEWNODE_IPV4: - if ( PICA_PROTO_NODELISTREQ == buf[0] && + if ( PICA_PROTO_NODELISTREQ == buf[0] && n->node_addr && ((struct PICA_nodeaddr_ipv4*)nlp->node_addr)->addr == ((struct PICA_nodeaddr_ipv4*)n->node_addr)->addr && ((struct PICA_nodeaddr_ipv4*)nlp->node_addr)->port == ((struct PICA_nodeaddr_ipv4*)n->node_addr)->port ) break;//exclude requester's address @@ -1004,68 +1173,72 @@ unsigned int procmsg_NODELIST(unsigned char* buf, unsigned int size, void* ptr) while(listleft) { -#warning "strict error checking!!! -- listleft overflow, unknown list items, check listleft >= possible item size" - if (listleft == listsize) //first entry, sender node's address + unsigned char item_type = buf[size - listleft]; + + /* The IPv6 and DNS list item types are defined by the protocol but + * are not produced or parsed yet (see procmsg_NODELISTREQ, which only + * emits IPv4 items). Their on-wire length is therefore not handled + * here, so the parse cannot advance past one and has to stop. + */ + if (item_type == PICA_PROTO_NEWNODE_IPV6 || item_type == PICA_PROTO_NEWNODE_DNS) { - switch(buf[size - listleft]) - { - case PICA_PROTO_NEWNODE_IPV4: - na_ipv4.magick = PICA_PROTO_NEWNODE_IPV4; - na_ipv4.addr = *(in_addr_t*)(buf + size - listleft + 1); - na_ipv4.port = *(in_port_t*)(buf + size - listleft + 5); - nodelink_attach_nodeaddr(n, na_ipv4.magick, &na_ipv4, sizeof(struct PICA_nodeaddr_ipv4)); + PICA_warn("NODELIST contains a %s address item, which is not implemented yet, aborting parse", + item_type == PICA_PROTO_NEWNODE_IPV6 ? "IPv6" : "DNS"); + return 0; + } - listleft -= PICA_PROTO_NODELIST_ITEM_IPV4_SIZE; - break; - } - continue; + /* Any other type byte is not a list item type at all: its length is + * unknown, so parsing cannot safely continue. Without bailing here + * the loop would spin forever on a byte it never decrements past. + */ + if (item_type != PICA_PROTO_NEWNODE_IPV4) + { + PICA_warn("NODELIST contains unknown address type 0x%02X, aborting parse", item_type); + return 0; + } + + /* Bounds check before reading the 4-byte address and 2-byte port, + * so a short trailing item cannot read past the packet or underflow + * listleft on the subtraction below. + */ + if (listleft < PICA_PROTO_NODELIST_ITEM_IPV4_SIZE) + { + PICA_warn("Unexpected end of nodelist packet"); + return 0; + } + + na_ipv4.magick = PICA_PROTO_NEWNODE_IPV4; + na_ipv4.addr = *(in_addr_t*)(buf + size - listleft + 1); + na_ipv4.port = *(in_port_t*)(buf + size - listleft + 5); + + if (listleft == listsize) //first entry, sender node's address + { + nodelink_attach_nodeaddr(n, na_ipv4.magick, &na_ipv4, sizeof(struct PICA_nodeaddr_ipv4)); } else { struct PICA_nodeaddr na; - //char addr[256]; - struct newconn nc; - struct nodelink *nlp; - int skip_save = 0; memset(na.addr, 0, 256); - memset(&nc, 0, sizeof(struct newconn)); - switch(buf[size - listleft]) + sprintf(na.addr, "%.16s", inet_ntoa(*(struct in_addr*)&na_ipv4.addr)); + na.port = ntohs(na_ipv4.port); + + PICA_debug3("NODELIST item %.16s:%hu", inet_ntoa(*(struct in_addr*)&na_ipv4.addr), ntohs(na_ipv4.port)); + + if (nodecfg.disable_reserved_addrs && PICA_is_reserved_addr_ipv4(na_ipv4.addr)) { - case PICA_PROTO_NEWNODE_IPV4: - na_ipv4.magick = PICA_PROTO_NEWNODE_IPV4; - na_ipv4.addr = *(in_addr_t*)(buf + size - listleft + 1); - na_ipv4.port = *(in_port_t*)(buf + size - listleft + 5); - - sprintf(na.addr, "%.16s", inet_ntoa(*(struct in_addr*)&na_ipv4.addr)); - na.port = ntohs(na_ipv4.port); - - //nodewait_start_connection(&na); -// if (try_connect_to_node(na.addr,ntohs(na_ipv4.port),&nc)) -// if (try_get_reply(&nc)) -// { -// nlp=nodelink_list_addnew(&nc); -// send_newnode(nlp,my_addr); -// nodelink_attach_nodeaddr(nlp,na_ipv4.magick,&na_ipv4,sizeof(struct PICA_nodeaddr_ipv4)); -// PICA_debug1("LINKED NODE:%s\n",inet_ntoa(*(struct in_addr*)&na_ipv4.addr)); -// } - - PICA_debug3("NODELIST item %.16s:%hu", inet_ntoa(*(struct in_addr*)&na_ipv4.addr), ntohs(na_ipv4.port)); - - if (nodecfg.disable_reserved_addrs && PICA_is_reserved_addr_ipv4(na_ipv4.addr)) - { - skip_save = 1; - PICA_debug1("Received NODELIST item %.16s:%hu is in private range, skipping", - inet_ntoa(*(struct in_addr*)&na_ipv4.addr), ntohs(na_ipv4.port) - ); - } - listleft -= PICA_PROTO_NODELIST_ITEM_IPV4_SIZE; - break; + PICA_debug1("Received NODELIST item %.16s:%hu is in private range, skipping", + inet_ntoa(*(struct in_addr*)&na_ipv4.addr), ntohs(na_ipv4.port) + ); } - if (!skip_save) + else + { PICA_nodeaddr_save(nodecfg.nodes_db_file, &na);//CONF filename + } } + + listleft -= PICA_PROTO_NODELIST_ITEM_IPV4_SIZE; } return 1; @@ -1157,7 +1330,14 @@ unsigned int procmsg_N2NALLOW(unsigned char* buf, unsigned int size, void* ptr) cc = cclink_list_search(caller_id, callee_id); - if (cc) + /* N2NALLOW is the reply this (caller's) node awaits in N2NCLR_WAITREP. + * That state only exists on caller-local links, which always have a + * non-NULL p1 - gating on it both prevents a client_wbuf_push(NULL) on a + * callee-local (p1 == NULL) link an attacker can create with + * N2NCONNREQOUTG, and stops a stray N2NALLOW from disturbing other links. + * callee_node == n ties the reply to the node that answered the search. + */ + if (cc && cc->state == PICA_CCLINK_N2NCLR_WAITREP && cc->callee_node == n) { if ((mp = client_wbuf_push(cc->p1, PICA_PROTO_FOUND, PICA_PROTO_FOUND_SIZE))) { @@ -1182,7 +1362,12 @@ unsigned int procmsg_N2NNOTFOUND(unsigned char* buf, unsigned int size, void* pt cc = cclink_list_search(caller_id, callee_id); - if (cc) + /* Same gate as N2NALLOW: act only on the caller-local link awaiting this + * reply, so a callee-local link (p1 == NULL) cannot crash client_wbuf_push + * and a stray N2NNOTFOUND cannot delete an unrelated link. callee_node == n + * ties the reply to the node that answered the search. + */ + if (cc && cc->state == PICA_CCLINK_N2NCLR_WAITREP && cc->callee_node == n) { if ((mp = client_wbuf_push(cc->p1, PICA_PROTO_NOTFOUND, PICA_PROTO_NOTFOUND_SIZE))) { @@ -1215,7 +1400,11 @@ unsigned int procmsg_N2NMSG(unsigned char* buf, unsigned int size, void* ptr) cc = cclink_list_search(sender_id, receiver_id); - if (cc && cc->state == PICA_CCLINK_N2NCLE_ACTIVE) + /* Accept relayed data only from the node that owns the remote (caller) + * half of this link, so a third node cannot inject into or overflow a + * relay between two other users' clients. + */ + if (cc && cc->state == PICA_CCLINK_N2NCLE_ACTIVE && cc->caller_node == n) { if (datalen + cc->bufpos_p1p2 > cc->buflen_p1p2) { @@ -1230,7 +1419,8 @@ unsigned int procmsg_N2NMSG(unsigned char* buf, unsigned int size, void* ptr) /////////////// cc = cclink_list_search(receiver_id, sender_id); - if (cc && cc->state == PICA_CCLINK_N2NCLR_ACTIVE) + /* Likewise, only from the node that owns the remote (callee) half. */ + if (cc && cc->state == PICA_CCLINK_N2NCLR_ACTIVE && cc->callee_node == n) { if (datalen + cc->bufpos_p2p1 > cc->buflen_p2p1) { @@ -1285,6 +1475,41 @@ struct cclink* cclink_list_search(const unsigned char *caller_id, const unsigned void cclink_list_delete(struct cclink *l) { PICA_debug1("cclink_list_delete(%p)", (void*)l); + + /* A CONNID connection may still be mid anon-TLS-shutdown with its socket + * handed to this link (sck_p1/sck_p2) and nc->iconn.cc pointing here. If + * the link is torn down first (WAITACTIVE timeout, or a client + * disconnecting), that newconn would later double-close the socket and + * re-delete this freed link from newconn_close(). Retire it now: drop its + * event and anon SSL and relinquish the fd, which is closed below. + */ + { + int i; + for (i = 0; i < MAX_NEWCONNS; i++) + { + struct newconn *nc = &newconns[i]; + + if (nc->type == NEWCONN_C2C && nc->iconn.cc == l) + { + if (nc->ev) + { + event_del(nc->ev); + event_free(nc->ev); + nc->ev = NULL; + } + if (nc->anonssl) + { + SSL_free(nc->anonssl); + nc->anonssl = NULL; + } + nc->iconn.cc = NULL; + nc->sck = -1; /* owned and closed by the link below */ + nc->pos = 0; + nc->type = NEWCONN_UNKNOWN; + } + } + } + //удаление из глобального списка if (l->prev) l->prev->next = l->next; @@ -1525,18 +1750,21 @@ void cclink_setwaitconn(struct cclink *ccl) int cclink_allocbufs(struct cclink *ccl) { - ccl->buf_p1p2 = malloc(DEFAULT_BUF_SIZE); - ccl->buf_p2p1 = malloc(DEFAULT_BUF_SIZE); + ccl->buf_p1p2 = malloc(C2C_BUF_SIZE); + ccl->buf_p2p1 = malloc(C2C_BUF_SIZE); if (!ccl->buf_p1p2 || !ccl->buf_p2p1) { if (ccl->buf_p1p2) free(ccl->buf_p1p2); if (ccl->buf_p2p1) free(ccl->buf_p2p1); + //cclink_list_delete() frees these again on the way out + ccl->buf_p1p2 = NULL; + ccl->buf_p2p1 = NULL; return 0; } - ccl->buflen_p1p2 = DEFAULT_BUF_SIZE; - ccl->buflen_p2p1 = DEFAULT_BUF_SIZE; + ccl->buflen_p1p2 = C2C_BUF_SIZE; + ccl->buflen_p2p1 = C2C_BUF_SIZE; return 1; } @@ -1729,17 +1957,62 @@ int PICA_node_init() event_add(listener_event, /*&tv*/ NULL); + //The UDP socket clients use to learn the address their NAT gives them, on + //the port with the same number as the TCP one. A node works without it. + listen_udp_sck = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + + if (listen_udp_sck != -1 && bind(listen_udp_sck, (struct sockaddr*)&sd, sizeof(sd)) == -1) + { + CLOSE(listen_udp_sck); + listen_udp_sck = -1; + } + + if (listen_udp_sck != -1) + { + struct event *udp_event; + + IOCTLSETNONBLOCKINGSOCKET(listen_udp_sck, 1); + + udp_event = event_new(pica_event_base, listen_udp_sck, EV_READ|EV_PERSIST, process_udp_read, NULL); + + if (!udp_event) + PICA_fatal("failed to allocate UDP socket event"); + + event_add(udp_event, NULL); + } + else + PICA_error("unable to open UDP port %u, clients will not be able to learn their UDP addresses from this node - %s", + (unsigned int)ntohs(sd.sin_port), strerror(errno)); + timeout_event = event_new(pica_event_base, -1, EV_TIMEOUT|EV_PERSIST, process_timeout_event, NULL); event_add(timeout_event, &tv); +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + ctx = SSL_CTX_new(TLS_method()); + anon_ctx = SSL_CTX_new(TLS_method()); +#else ctx = SSL_CTX_new(TLSv1_2_method()); anon_ctx = SSL_CTX_new(TLSv1_2_method()); +#endif if (!ctx || !anon_ctx) PICA_fatal("unable to create SSL_CTX object"); +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + /* TLS_method() on its own would negotiate the highest version both ends + * know. Narrowing it back to 1.2 is what keeps this the same protocol + * TLSv1_2_method() used to give - see PICA_TLS_MINVERSION for why the + * ceiling matters as much as the floor. + */ + if (!SSL_CTX_set_min_proto_version(ctx, PICA_TLS_MINVERSION) || + !SSL_CTX_set_max_proto_version(ctx, PICA_TLS_MAXVERSION) || + !SSL_CTX_set_min_proto_version(anon_ctx, PICA_TLS_MINVERSION) || + !SSL_CTX_set_max_proto_version(anon_ctx, PICA_TLS_MAXVERSION)) + PICA_fatal("failed to restrict the TLS version range to 1.2"); +#endif + ret = SSL_CTX_set_cipher_list(ctx, PICA_TLS_CIPHERLIST); if (!ret) @@ -1755,7 +2028,7 @@ int PICA_node_init() fclose(dh_file); } else - PICA_fatal("Unable to open DH parameters file %", nodecfg.dh_param_file); + PICA_fatal("Unable to open DH parameters file %s", nodecfg.dh_param_file); ret = SSL_CTX_set_tmp_dh(anon_ctx, dh); @@ -2021,9 +2294,14 @@ void client_tree_remove(struct client* ci) if (lm != ci->right) { lm->up->left = lm->right; + if (lm->right) + lm->right->up = lm->up; // FIX 1 lm->right = ci->right; + ci->right->up = lm; // FIX 2 } lm->left = ci->left; + if (ci->left) + ci->left->up = lm; // FIX 3 lm->up = ci->up; *p_link = lm; } @@ -2037,6 +2315,14 @@ struct client *client_list_addnew(struct newconn *nc) if (!ci) return 0; + ci->r_buf = calloc(1, DEFAULT_BUF_SIZE); + if (!ci->r_buf) + { + free(ci); + return 0; + } + ci->buflen_r = DEFAULT_BUF_SIZE; + ci->ssl_comm = SSL_new (ctx); if (!ci->ssl_comm) @@ -2063,16 +2349,11 @@ struct client *client_list_addnew(struct newconn *nc) SSL_set_fd(ci->ssl_comm, ci->sck_comm); - ci->r_buf = calloc(1, DEFAULT_BUF_SIZE); - if (!ci->r_buf) - { - free(ci); - return 0; - } - ci->buflen_r = DEFAULT_BUF_SIZE; - ci->tmst = time(0); + ci->udpaddr_req_allowance = UDPADDR_REQ_BURST; + ci->udpaddr_req_tmst = ci->tmst; + ci->ev_read = event_new(pica_event_base, ci->sck_comm, EV_READ | EV_PERSIST, process_c2n_read, ci); ci->ev_write = event_new(pica_event_base, ci->sck_comm, EV_WRITE, process_c2n_write, ci); @@ -2157,6 +2438,8 @@ void client_list_delete(struct client* ci) cclink_list_delete_by_client(ci); + client_udpaddr_token_drop(ci); + if (ci->r_buf) free(ci->r_buf); @@ -2242,6 +2525,14 @@ struct nodelink *nodelink_list_addnew(struct newconn *nc) if (!nl) return 0; + nl->r_buf = calloc(1, DEFAULT_BUF_SIZE); + if (!nl->r_buf) + { + free(nl); + return 0; + } + nl->buflen_r = DEFAULT_BUF_SIZE; + if (nodelink_list_end) { nodelink_list_end->next = nl; @@ -2259,14 +2550,6 @@ struct nodelink *nodelink_list_addnew(struct newconn *nc) nl->anonssl = nc->anonssl; nc->anonssl = NULL; - nl->r_buf = calloc(1, DEFAULT_BUF_SIZE); - if (!nl->r_buf) - { - free(nl); - return 0; - } - nl->buflen_r = DEFAULT_BUF_SIZE; - nl->tmst = time(0); nl->ev_read = event_new(pica_event_base, nl->sck, EV_READ | EV_PERSIST, process_n2n_read, nl); @@ -2521,7 +2804,7 @@ void process_timeouts_c2n() if (kill_ptr) { - PICA_info("Disconnecting user %s due to noreply timeout", PICA_id_to_base64(kill_ptr -> id, NULL)); + PICA_info("Disconnecting user %s due to noreply timeout", PICA_id_to_base64(kill_ptr->id, NULL)); client_list_delete(kill_ptr); kill_ptr = 0; } @@ -2659,6 +2942,10 @@ void process_listen_read(evutil_socket_t listener, short event, void *arg) nc->state = PICA_NEWCONN_WAITANONTLSACCEPT; IOCTLSETNONBLOCKINGSOCKET(s, 1); + /* the node relays c2c data, so Nagle delays here are added to + * the delay of every message between the two clients + */ + SETTCPNODELAY(s); PICA_debug1("accepted connection from %.16s, new socket %i", inet_ntoa(addr.sin_addr), s);//IPv6 @@ -2685,6 +2972,88 @@ void process_listen_read(evutil_socket_t listener, short event, void *arg) //IPv6 } +//Tells a client the address and port its datagram came from - the address its +//NAT gave to the socket the datagram was sent from. +// +//Anyone can send anything to this socket, with any source address, so: +// - nothing is ever sent from it. The answer goes over the c2n connection of +// the client that asked, which leaves nothing to reflect or amplify; +// - a datagram is acted upon only if it carries a token this node issued over +// an authenticated c2n connection moments ago. The token is random, so it +// cannot be guessed, and is good for one datagram, so a client is sent one +// answer per request it made itself and duplicates are dropped; +// - a datagram that is not acted upon costs a table lookup and leaves no +// state behind, and it is not logged. +//The source address itself cannot be verified, and does not need to be: it +//is only reported back to the client the token belongs to. +void process_udp_read(evutil_socket_t s, short event, void *arg) +{ + //one octet more than a valid datagram has, so that a longer one does not + //pass for a valid one after being truncated + unsigned char buf[PICA_PROTO_MYUDPADDRPROBE_SIZE + 1]; + int i; + + for (i = 0; i < UDP_READ_BATCH; i++) + { + struct sockaddr_in from; +#ifdef WIN32 + int fromlen = sizeof(from); +#else + socklen_t fromlen = sizeof(from); +#endif + struct client *c; + struct PICA_proto_msg *mp; + time_t now; + int ret; + + ret = recvfrom(s, (char*)buf, sizeof(buf), 0, (struct sockaddr*)&from, &fromlen); + + if (ret == -1) + { +#ifdef WIN32 + if (WSAGetLastError() == WSAEWOULDBLOCK) + break; +#else + if (errno == EAGAIN || errno == EWOULDBLOCK) + break; +#endif + //anything else is about the one datagram, e.g. it did not fit + //into the buffer on Windows + continue; + } + + if (ret != PICA_PROTO_MYUDPADDRPROBE_SIZE || buf[0] != PICA_PROTO_MYUDPADDRPROBE || buf[1] != PICA_PROTO_MYUDPADDRPROBE) + continue; + + if (fromlen < sizeof(from) || from.sin_family != AF_INET) + continue; + + c = udpaddr_token_search(buf + 2); + + if (!c) + continue; + + now = time(0); + ret = (now >= c->udpaddr_token_tmst && now - c->udpaddr_token_tmst <= UDPADDR_TOKEN_TIMEOUT); + + client_udpaddr_token_drop(c); + + if (!ret) + continue; + + PICA_debug3("MYUDPADDRPROBE for client %p from %.16s:%hu", (void*)c, inet_ntoa(from.sin_addr), ntohs(from.sin_port)); + + //IPv6 + if ((mp = client_wbuf_push(c, PICA_PROTO_MYUDPADDR, 2 + PICA_MSG_VARSIZE_INT8 + PICA_PROTO_MYUDPADDR_IPV4_SIZE))) + { + mp->tail[0] = PICA_PROTO_MYUDPADDR_IPV4_SIZE; + mp->tail[1] = PICA_PROTO_MYUDPADDR_IPV4; + memcpy(mp->tail + 2, &from.sin_addr.s_addr, 4); + memcpy(mp->tail + 6, &from.sin_port, 2); + } + } +} + void process_newconn_write(struct newconn *nc) { int ret; @@ -3153,6 +3522,8 @@ void process_c2c_write(evutil_socket_t s, short event, void *arg) if (cc->bufpos_p1p2) { + int attempted = 1; + if (cc->state == PICA_CCLINK_N2NCLR_ACTIVE) //receiver is on remote node { int sendlen; @@ -3171,53 +3542,64 @@ void process_c2c_write(evutil_socket_t s, short event, void *arg) else ret = 0; } - else if (s == cc->sck_p2) + else if (cc->sck_p2 != -1) ret = send(cc->sck_p2, cc->buf_p1p2, cc->bufpos_p1p2, MSG_NOSIGNAL); + else + attempted = 0; //no local p2 socket to flush into, leave the buffer untouched - PICA_debug3("process_c2c_write: send p1p2: ret=%i", ret); - if (ret > 0) + //ret is only meaningful when one of the branches above ran - this + //callback is shared by ev_write_p1/ev_write_p2 and is also invoked + //directly with s == -1, so it is routinely entered for a direction + //that cannot be flushed on this pass + if (attempted) { - if (ret < cc->bufpos_p1p2) - memmove(cc->buf_p1p2, cc->buf_p1p2 + ret, cc->bufpos_p1p2 - ret); //may be it's better to implement ring buffer here - cc->bufpos_p1p2 -= ret; + PICA_debug3("process_c2c_write: send p1p2: ret=%i", ret); + if (ret > 0) + { + if (ret < cc->bufpos_p1p2) + memmove(cc->buf_p1p2, cc->buf_p1p2 + ret, cc->bufpos_p1p2 - ret); //may be it's better to implement ring buffer here + cc->bufpos_p1p2 -= ret; - if (cc->bufpos_p1p2 == 0 && cc->sck_p1 != -1) - event_add(cc->ev_read_p1, NULL); + if (cc->bufpos_p1p2 == 0 && cc->sck_p1 != -1) + event_add(cc->ev_read_p1, NULL); - cc->jam_p1p2 = 0; - } + cc->jam_p1p2 = 0; + } - if (ret == 0) - { - kill_ptr = cc; - } - if (ret == -1) - { -#ifdef WIN32 - ret = WSAGetLastError(); - if (ret == WSAEWOULDBLOCK || ret == WSAENOBUFS) - cc->jam_p1p2 = 1; - else + if (ret == 0) { kill_ptr = cc; } -#else - ret = errno; - if (ret == EAGAIN || ret == ENOBUFS) - cc->jam_p1p2 = 1; - else + if (ret == -1) { - kill_ptr = cc; - } +#ifdef WIN32 + ret = WSAGetLastError(); + if (ret == WSAEWOULDBLOCK || ret == WSAENOBUFS) + cc->jam_p1p2 = 1; + else + { + kill_ptr = cc; + } +#else + ret = errno; + if (ret == EAGAIN || ret == ENOBUFS) + cc->jam_p1p2 = 1; + else + { + kill_ptr = cc; + } #endif + } } - if (!kill_ptr && cc->bufpos_p1p2 && s != -1) + if (!kill_ptr && cc->bufpos_p1p2 && cc->ev_write_p2) event_add(cc->ev_write_p2, NULL); } if (cc->bufpos_p2p1 /*&& (cc->state==PICA_CCLINK_LOCAL_ACTIVE || cc->state==PICA_CCLINK_N2NCLR_ACTIVE)*/) { + int attempted = 1; + if (cc->state == PICA_CCLINK_N2NCLE_ACTIVE) //receiver is on remote node { int sendlen; @@ -3236,49 +3618,54 @@ void process_c2c_write(evutil_socket_t s, short event, void *arg) else ret = 0; } - else if (s == cc->sck_p1) + else if (cc->sck_p1 != -1) ret = send(cc->sck_p1, cc->buf_p2p1, cc->bufpos_p2p1, MSG_NOSIGNAL); + else + attempted = 0; //no local p1 socket to flush into, leave the buffer untouched - PICA_debug3("process_c2c_write: send p2p1: ret=%i", ret); - if (ret > 0) + if (attempted) { - if (ret < cc->bufpos_p2p1) - memmove(cc->buf_p2p1, cc->buf_p2p1 + ret, cc->bufpos_p2p1 - ret); //may be it's better to implement ring buffer here - cc->bufpos_p2p1 -= ret; + PICA_debug3("process_c2c_write: send p2p1: ret=%i", ret); + if (ret > 0) + { + if (ret < cc->bufpos_p2p1) + memmove(cc->buf_p2p1, cc->buf_p2p1 + ret, cc->bufpos_p2p1 - ret); //may be it's better to implement ring buffer here + cc->bufpos_p2p1 -= ret; - if (cc->bufpos_p2p1 == 0 && cc->sck_p2 != -1) - event_add(cc->ev_read_p2, NULL); + if (cc->bufpos_p2p1 == 0 && cc->sck_p2 != -1) + event_add(cc->ev_read_p2, NULL); - cc->jam_p2p1 = 0; - } + cc->jam_p2p1 = 0; + } - if (ret == 0) - { - kill_ptr = cc; - } - if (ret == -1) - { -#ifdef WIN32 - ret = WSAGetLastError(); - if (ret == WSAEWOULDBLOCK || ret == WSAENOBUFS) - cc->jam_p2p1 = 1; - else + if (ret == 0) { kill_ptr = cc; } -#else - ret = errno; - if (ret == EAGAIN || ret == ENOBUFS) - cc->jam_p2p1 = 1; - else + if (ret == -1) { - kill_ptr = cc; - } +#ifdef WIN32 + ret = WSAGetLastError(); + if (ret == WSAEWOULDBLOCK || ret == WSAENOBUFS) + cc->jam_p2p1 = 1; + else + { + kill_ptr = cc; + } +#else + ret = errno; + if (ret == EAGAIN || ret == ENOBUFS) + cc->jam_p2p1 = 1; + else + { + kill_ptr = cc; + } #endif + } } - if (!kill_ptr && cc->bufpos_p2p1 && s != -1) + if (!kill_ptr && cc->bufpos_p2p1 && cc->ev_write_p1) event_add(cc->ev_write_p1, NULL); } @@ -3451,7 +3838,7 @@ Options:\n\ void print_version() { - puts("Pica Pica Node v"PACKAGE_VERSION" \nCopyright (c) 2012 - 2018 Anton Sviridenko\n"); + puts("Pica Pica Node v"PACKAGE_VERSION" \nCopyright (c) 2012 - 2026 Anton Sviridenko\n"); puts("protocol version "PICA_PROTO_VER_STRING"\n"); puts("License GPLv3: GNU GPL version 3 <http://gnu.org/licenses/gpl.html>\n\ This is free software: you are free to change and redistribute it.\n\ @@ -3612,6 +3999,88 @@ void ReportSvcStatus( DWORD dwCurrentState, } #endif +#ifdef HAVE_LIBMINIUPNPC +/* The port mapping made for the node's listening port, kept for as long as + * the node runs so that its lease can be renewed. + */ +static struct PICA_upnp_ctx *upnp_ctx; +static struct event *upnp_refresh_event; + +static void upnp_schedule_refresh(void); + +static void upnp_refresh_cb(evutil_socket_t fd, short event, void *arg) +{ + int ret; + + /* Blocks the event loop for as long as the IGD takes to answer, normally + * a few milliseconds, once in half a lease. + */ + ret = PICA_upnp_refresh(upnp_ctx); + + if (ret != PICA_UPNP_OK) + { + PICA_error("UPnP: failed to renew the port mapping, the node may become unreachable from the Internet - %s", + PICA_upnp_strerror(ret)); + return; + } + + upnp_schedule_refresh(); +} + +static void upnp_schedule_refresh(void) +{ + struct timeval tv; + unsigned int lease = PICA_upnp_lease(upnp_ctx); + + /* a permanent mapping still disappears when the IGD reboots */ + if (lease == 0) + lease = PICA_UPNP_LEASE_DEFAULT; + + tv.tv_sec = lease / 2; + tv.tv_usec = 0; + + if (!upnp_refresh_event) + upnp_refresh_event = evtimer_new(pica_event_base, upnp_refresh_cb, NULL); + + if (upnp_refresh_event) + evtimer_add(upnp_refresh_event, &tv); +} + +/* Forwards the listening port, TCP and UDP - the latter carries the "get my + * UDP address" datagrams - and reports the IGD's external address. + * \return 1 on success + */ +static int upnp_forward_listen_port(int port, char *public_ip, size_t public_ip_size) +{ + int ret; + + ret = PICA_upnp_discover(PICA_UPNP_DISCOVER_TIMEOUT, &upnp_ctx); + + if (ret != PICA_UPNP_OK) + { + PICA_info("UPnP: %s", PICA_upnp_strerror(ret)); + return 0; + } + + ret = PICA_upnp_external_addr(upnp_ctx, public_ip, public_ip_size); + + if (ret == PICA_UPNP_OK) + ret = PICA_upnp_map(upnp_ctx, port, PICA_UPNP_LEASE_DEFAULT, "Pica Pica node"); + + if (ret != PICA_UPNP_OK) + { + PICA_info("UPnP: failed to forward port %i - %s", port, PICA_upnp_strerror(ret)); + PICA_upnp_free(upnp_ctx); + upnp_ctx = NULL; + return 0; + } + + upnp_schedule_refresh(); + + return 1; +} +#endif + int pica_node_main(int argc, char** argv) { uint32_t pid; @@ -3671,12 +4140,10 @@ int pica_node_main(int argc, char** argv) if (PICA_is_reserved_addr_ipv4(guess) && nodecfg.disable_reserved_addrs) { char public_ip[64]; - int ret; PICA_info("trying to get global IP with UPnP..."); - ret = PICA_upnp_autoconfigure_ipv4(atoi(nodecfg.listen_port), atoi(nodecfg.listen_port), public_ip); - if (ret) + if (upnp_forward_listen_port(atoi(nodecfg.listen_port), public_ip, sizeof(public_ip))) { free(nodecfg.announced_addr); nodecfg.announced_addr = strdup(public_ip); diff --git a/PICA_node.h b/PICA_node.h index 78cb997..82ddb32 100644 --- a/PICA_node.h +++ b/PICA_node.h @@ -27,6 +27,7 @@ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> +#include <netinet/tcp.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/select.h> @@ -51,6 +52,7 @@ #include <time.h> #include "PICA_nodeaddrlist.h" #include "PICA_id.h" +#include "PICA_proto.h" #include <event2/event.h> @@ -102,6 +104,15 @@ #define DEFAULT_BUF_SIZE 4096 +//Relay buffers of a c2c link. procmsg_N2NMSG() drops the whole link when an +//incoming N2NMSG does not fit into the free space left in these, and the +//announced payload length of an N2NMSG is a 16 bit field less the two peer ids +//(65535 - 2 * PICA_ID_SIZE), so anything below 64K makes that a routine event +//instead of an exceptional one - a link carrying a call has a backlog in both +//directions most of the time. Deliberately not DEFAULT_BUF_SIZE: that one is +//also the r_buf/w_buf granularity paid for by every connected client. +#define C2C_BUF_SIZE 65536 + struct nodelink; struct client @@ -132,6 +143,16 @@ struct client int disconnect_ticking;//on sending message TO client this var is set to 1, on receiving some message FROM client this var is reset to 0 struct event *ev_read; struct event *ev_write; + + //Pending "get my UDP address" request. The token is what ties a datagram + //arriving at the UDP socket to this connection, see process_udp_read() + unsigned char udpaddr_token[PICA_PROTO_MYUDPADDR_TOKENSIZE]; + int udpaddr_token_issued; + time_t udpaddr_token_tmst; + struct client *udpaddr_token_next;//next client in the same bucket of udpaddr_tokens[] + //how many more MYUDPADDRREQ messages are served right now, see client_udpaddr_req_allowed() + unsigned int udpaddr_req_allowance; + time_t udpaddr_req_tmst; }; struct cclink //структура, описывающая соединение двух клиентов между собой через сервер diff --git a/PICA_proto.h b/PICA_proto.h index a1bb3cb..6529392 100644 --- a/PICA_proto.h +++ b/PICA_proto.h @@ -21,10 +21,10 @@ #define PICA_PROTO_VER_HIGH 0 -#define PICA_PROTO_VER_LOW 5 +#define PICA_PROTO_VER_LOW 6 #define PICA_C2CPROTO_VER_HIGH 0 -#define PICA_C2CPROTO_VER_LOW 1 +#define PICA_C2CPROTO_VER_LOW 2 #define PICA_PROTO_CLIENT_VER_STRING PICA_STRINGIFY2(PICA_C2CPROTO_VER_HIGH, PICA_C2CPROTO_VER_LOW) #define PICA_PROTO_VER_STRING PICA_STRINGIFY2(PICA_PROTO_VER_HIGH, PICA_PROTO_VER_LOW) @@ -44,6 +44,19 @@ #define PICA_PROTO_CLNODELISTREQ 0x09 #define PICA_PROTO_CLNODELIST 0x0A +#define PICA_PROTO_MYTCPADDRREQ 0x0F +#define PICA_PROTO_MYTCPADDR_IPV4 0xA0 +#define PICA_PROTO_MYTCPADDR_IPV6 0xA1 +#define PICA_PROTO_MYUDPADDRREQ 0x10 +#define PICA_PROTO_MYUDPADDRTOKEN 0x11 +#define PICA_PROTO_MYUDPADDR 0x12 +// type octet of the address carried by PICA_PROTO_MYUDPADDR +#define PICA_PROTO_MYUDPADDR_IPV4 0xA0 +#define PICA_PROTO_MYUDPADDR_IPV6 0xA1 +// The only message that is sent to a node as a UDP datagram, outside of any +// connection. It carries the token from PICA_PROTO_MYUDPADDRTOKEN. +#define PICA_PROTO_MYUDPADDRPROBE 0x10 + #define PICA_PROTO_CONNID 0x20 #define PICA_PROTO_C2CCONNREQ 0xCC @@ -91,6 +104,17 @@ #define PICA_PROTO_N2NNOTFOUND 0xB8 #define PICA_PROTO_N2NMSG 0xD0 +#define PICA_PROTO_CALLREQ 0x70 +#define PICA_PROTO_CALLANS 0x71 +#define PICA_PROTO_CALLREJ 0x72 +#define PICA_PROTO_CALLFIN 0x73 +#define PICA_PROTO_CALL_AUDIOPARAM 0x74 +#define PICA_PROTO_CALL_VIDEOPARAM 0x75 +#define PICA_PROTO_CALL_AUDIO_PACKET 0x76 +#define PICA_PROTO_CALL_VIDEO_PACKET 0x77 +// The only datagram of a call sent outside of DTLS, see "Establishing the +// media connection" in doc/proto-doc-latest.txt. +#define PICA_PROTO_MEDIAPROBE 0x78 //size #define PICA_PROTO_INITREQ_SIZE 4 @@ -105,6 +129,17 @@ #define PICA_PROTO_CONNDENY_SIZE 30 #define PICA_PROTO_CLNODELISTREQ_SIZE 4 +#define PICA_PROTO_MYTCPADDRREQ_SIZE 4 +#define PICA_PROTO_MYTCPADDR_IPV4_SIZE 8 +#define PICA_PROTO_MYTCPADDR_IPV6_SIZE 20 +#define PICA_PROTO_MYUDPADDRREQ_SIZE 4 +#define PICA_PROTO_MYUDPADDR_TOKENSIZE 16 +#define PICA_PROTO_MYUDPADDRTOKEN_SIZE (2 + PICA_PROTO_MYUDPADDR_TOKENSIZE) +#define PICA_PROTO_MYUDPADDRPROBE_SIZE (2 + PICA_PROTO_MYUDPADDR_TOKENSIZE) +// address carried by PICA_PROTO_MYUDPADDR: type octet, address, port +#define PICA_PROTO_MYUDPADDR_IPV4_SIZE 7 +#define PICA_PROTO_MYUDPADDR_IPV6_SIZE 19 + #define PICA_PROTO_CONNID_SIZE 58 #define PICA_PROTO_C2CCONNREQ_SIZE 4 @@ -139,6 +174,16 @@ #define PICA_PROTO_N2NALLOW_SIZE 58 #define PICA_PROTO_N2NNOTFOUND_SIZE 58 +// 0x70 and 0x71: probe token, then a list of up to this many addresses in the +// 0xA4 format that the receiver uses +#define PICA_PROTO_CALL_TOKENSIZE 8 +#define PICA_PROTO_CALL_MAXADDRS 8 +#define PICA_PROTO_MEDIAPROBE_SIZE (2 + PICA_PROTO_CALL_TOKENSIZE) +#define PICA_PROTO_CALLREJ_SIZE 4 +#define PICA_PROTO_CALLFIN_SIZE 4 +#define PICA_PROTO_CALL_AUDIOPARAM_SIZE 24 +#define PICA_PROTO_CALL_VIDEOPARAM_SIZE 26 + #define PICA_PROTO_N2NMSG_MAXDATASIZE 65476 #define PICA_PROTO_C2CMSG_MAXDATASIZE 65532 #define PICA_PROTO_C2CMSG_MAXFILENAMESIZE 255 @@ -149,6 +194,15 @@ #define PICA_MULTILOGIN_REPLACE 1 #define PICA_MULTILOGIN_ALLOW 2 +#define PICA_PROTO_CALL_CODECNAMESIZE 20 + +// Sequence number (2 octets) + capture timestamp in milliseconds (4 +// octets), little-endian, prepended to the payload in the 0x76/0x77 packet +// tail, ahead of the codec data. +#define PICA_PROTO_CALL_PACKET_SEQNUM_SIZE 2 +#define PICA_PROTO_CALL_PACKET_TIMESTAMP_SIZE 4 +#define PICA_PROTO_CALL_PACKET_HDRSIZE (PICA_PROTO_CALL_PACKET_SEQNUM_SIZE + PICA_PROTO_CALL_PACKET_TIMESTAMP_SIZE) + struct PICA_proto_msg { unsigned char head[2]; diff --git a/PICA_security.h b/PICA_security.h index df260b2..6678602 100644 --- a/PICA_security.h +++ b/PICA_security.h @@ -26,5 +26,31 @@ #define PICA_OPENSSL_SECURUTY_LEVEL 3 #define PICA_CERTDIGESTALGO "-sha256" #define PICA_PRIVKEYENCALGO "-aes256" +#define PICA_TIMETOLERANCE 600 + +/* The TLS version range, pinned to exactly 1.2 at both ends. + * + * The upper end is deliberate and load bearing, not tidiness. Both cipher + * lists above name TLS 1.2 suites, and the anonymous one has no TLS 1.3 + * counterpart at all - 1.3 dropped anonymous key exchange entirely. On top of + * that, SSL_CTX_set_cipher_list() has no say over which TLS 1.3 suites a + * connection ends up using; that is a separate call + * (SSL_CTX_set_ciphersuites). So letting 1.3 be negotiated would quietly + * ignore PICA_TLS_CIPHERLIST and leave PICA_TLS_ANONDHCIPHERLIST with nothing + * to offer. + * + * Moving the ceiling therefore means naming TLS 1.3 suites explicitly and + * finding another way to do the anonymous handshake - it is a protocol + * decision, not a configuration change. + * + * Applied with SSL_CTX_set_min_proto_version()/SSL_CTX_set_max_proto_version() + * on OpenSSL 1.1.0 and later. Those replaced TLSv1_2_method(), which was + * deprecated in 1.1.0 and removed in 4.0. + * + * These expand to <openssl/ssl.h> constants, so they are only usable in a + * translation unit that includes it. + */ +#define PICA_TLS_MINVERSION TLS1_2_VERSION +#define PICA_TLS_MAXVERSION TLS1_2_VERSION #endif diff --git a/PICA_signverify.c b/PICA_signverify.c index e9d4878..95a5b12 100644 --- a/PICA_signverify.c +++ b/PICA_signverify.c @@ -101,7 +101,10 @@ int PICA_do_signature(EVP_PKEY *privkey, void **datapointers, size_t *datalength if (ret == 1) ret = 1; else + { free(*sig); + *sig = NULL; + } sig_exit: EVP_MD_CTX_destroy(mdctx); diff --git a/apple/Info.plist b/apple/Info.plist index b259c6a..bcf705b 100644 --- a/apple/Info.plist +++ b/apple/Info.plist @@ -5,7 +5,7 @@ <key>CFBundleName</key> <string>Pica Pica Messenger</string> - + <key>CFBundleDisplayName</key> <string>Pica Pica Messenger</string> @@ -16,13 +16,18 @@ <string>APPL</string> <key>CFBundleGetInfoString</key> - <string>0.7.1, Copyright © 2012 - 2019 Anton Sviridenko</string> + <string>0.9.0dev, Copyright © 2012 - 2026 Anton Sviridenko</string> + <!-- + Launch Services only accepts up to three period separated integers here, + so the "dev" of the upstream version lives in CFBundleGetInfoString above + rather than in these two. + --> <key>CFBundleShortVersionString</key> - <string>0.7.1</string> + <string>0.9.0</string> <key>CFBundleVersion</key> - <string>0.7</string> + <string>0.9.0</string> <key>CFBundleSignature</key> <string>????</string> @@ -33,5 +38,37 @@ <key>CFBundleIdentifier</key> <string>im.picapica.pica-client</string> + <!-- + Without these two, macOS 10.14 and later kills the process the moment it + opens the microphone or the camera rather than asking the user - so audio + and video calls do not merely fail, they take the application with them. + The strings are what the permission prompt shows as the reason. + + NSMicrophoneUsageDescription covers the capture side of a call, which on + this platform means the VoiceProcessingIO audio unit (see + nativeaudio_coreaudio.cpp). Note that the unit captures and renders + together, so this is also needed for call playback - though not for + ringtones, which deliberately use a plain output unit. + --> + <key>NSMicrophoneUsageDescription</key> + <string>Pica Pica needs the microphone so the person you are calling can hear you.</string> + + <key>NSCameraUsageDescription</key> + <string>Pica Pica needs the camera so the person you are calling can see you.</string> + + <!-- + Qt draws through its own windows rather than the system's, so the app has + to say it is high resolution capable or macOS scales a low resolution + backing store up and everything looks soft on a Retina display. + --> + <key>NSHighResolutionCapable</key> + <true/> + + <key>LSMinimumSystemVersion</key> + <string>10.13</string> + + <key>NSPrincipalClass</key> + <string>NSApplication</string> + </dict> </plist> diff --git a/configure.ac b/configure.ac index 52e9b24..4a72a59 100644 --- a/configure.ac +++ b/configure.ac @@ -2,7 +2,7 @@ # Process this file with autoconf to produce a configure script. AC_PREREQ([2.68]) -AC_INIT([Pica Pica Messenger], [0.7.1], [http://picapica.im/bugzilla/], [pica-pica], [http://picapica.im]) +AC_INIT([Pica Pica Messenger], [0.9.0dev], [http://picapica.im/bugzilla/], [pica-pica], [http://picapica.im]) AM_INIT_AUTOMAKE([-Wall foreign subdir-objects]) AC_CONFIG_SRCDIR([PICA_node.c]) @@ -82,8 +82,49 @@ AS_IF([test "x$enable_client" != "xno"], [ PICA_CLIENT_ENABLED=yes ]) +#checking if VAAPI hardware acceleration is wanted +#unspecified means autodetect: use it when the libraries are there, do without +#them when they are not. --enable-vaapi makes their absence a hard error, +#--disable-vaapi skips looking for them at all. +AC_ARG_ENABLE([vaapi], + AS_HELP_STRING([--enable-vaapi], + [Enable VAAPI accelerated video encoding, decoding and rendering (default: autodetect)]) + AS_HELP_STRING([--disable-vaapi], + [Disable VAAPI accelerated video encoding, decoding and rendering])) + +#checking if Direct3D 12 hardware encoding and decoding is wanted. The Windows +#counterpart of the VAAPI path above - there is no libva there, but FFmpeg can +#reach the same GPU encoders and decoders through D3D12 Video. Autodetected the +#same way, and only ever looked for when building for Windows. +AC_ARG_ENABLE([d3d12va], + AS_HELP_STRING([--enable-d3d12va], + [Enable Direct3D 12 accelerated video encoding and decoding, Windows only (default: autodetect)]) + AS_HELP_STRING([--disable-d3d12va], + [Disable Direct3D 12 accelerated video encoding and decoding])) + +#checking if PulseAudio device enumeration is wanted. Only affects what the +#settings dialog can list; see the check further down. +AC_ARG_ENABLE([pulse], + AS_HELP_STRING([--enable-pulse], + [Enable listing of PulseAudio/PipeWire capture and playback devices (default: autodetect)]) + AS_HELP_STRING([--disable-pulse], + [Disable listing of PulseAudio/PipeWire devices])) + +#checking if the X11 rendering path is wanted +#Qt gives widgets a GLX context by default in an X11 session, and a GLX +#context has no way to import the DMA-BUF handles a VA surface is exported +#as - that path needs EGL. vaPutSurface() leaves OpenGL out of it altogether +#and has the driver draw the surface straight onto an X11 window, which is +#what makes hardware rendering work in such a session. Autodetected like +#VAAPI itself, and pointless without it. +AC_ARG_ENABLE([vaapi-x11], + AS_HELP_STRING([--enable-vaapi-x11], + [Enable vaPutSurface() rendering, for X11 sessions where Qt uses GLX rather than EGL (default: autodetect)]) + AS_HELP_STRING([--disable-vaapi-x11], + [Disable vaPutSurface() rendering])) + #at least one program must be enabled -AS_IF([test "x$PICA_NODE_ENABLED" != "xyes" && test "x$PICA_CLIENT_ENABLED" != "xyes" ], +AS_IF([test "x$PICA_NODE_ENABLED" != "xyes" && test "x$PICA_CLIENT_ENABLED" != "xyes" ], AC_MSG_ERROR(["Either pica-node or pica-client must be enabled"]) ) @@ -107,7 +148,31 @@ AS_IF([test "x$PICA_CLIENT_ENABLED" = "xyes"],[ #AC_PROG_CXX PKG_CHECK_MODULES([QT_DEPENDENCIES], [$QT_MODULES]) AS_CASE([$host], - [*-w64-mingw*], [QT_DEPENDENCIES_LIBS="$QT_DEPENDENCIES_LIBS -mwindows"] + [*-linux-*], + [ + PKG_CHECK_MODULES([PLATFORM_DEPS],["alsa"]) + ], + [*-w64-mingw*], + [ + TARGET_OS=windows + QT_DEPENDENCIES_LIBS="$QT_DEPENDENCIES_LIBS -mwindows" + #the WASAPI backend is COM: ole32 for CoCreateInstance and the + #task allocator, oleaut32 for PROPVARIANT. + PLATFORM_DEPS_LIBS="$PLATFORM_DEPS_LIBS -lole32 -loleaut32" + AC_PATH_TOOL(WINDRES, windres, none) + if test x$WINDRES = xnone; then + AC_MSG_ERROR("windres not found") + fi + ], + [*-apple-darwin*], + [ + TARGET_OS=darwin + #the CoreAudio backend: the HAL for device enumeration, + #AudioUnit/AudioToolbox for the VoiceProcessingIO unit that does + #the echo cancellation, CoreFoundation for the CFString handling + #the HAL's names come back as. + PLATFORM_DEPS_LIBS="$PLATFORM_DEPS_LIBS -framework CoreAudio -framework AudioUnit -framework AudioToolbox -framework CoreFoundation" + ], [] ) AC_SUBST([QT_DEPENDENCIES_CFLAGS]) @@ -118,12 +183,200 @@ AC_CHECK_PROGS([MOC], [$QT_MOC_NAMES], [notfound]) AS_IF([test "x$UIC" = xnotfound],[AC_MSG_ERROR(["uic program not found. Please install Qt development package"])]) AS_IF([test "x$MOC" = xnotfound],[AC_MSG_ERROR(["moc program not found. Please install Qt development package"])]) -#check for openssl command line tool +#check for FFmpeg libraries +PKG_CHECK_MODULES([FFMPEG],["libavcodec libavdevice libavformat libavutil libswresample libswscale"]) +AC_SUBST([FFMPEG_CFLAGS]) +AC_SUBST([FFMPEG_LIBS]) + +#check for webrtc-audio-processing, which provides AEC3 - the acoustic echo +#cancellation pica-client runs itself. Not optional: on Linux there is no +#other cancellation in the picture unless the user has set their sound server +#up for it, and on the platforms that have their own this is still what the +#"use own echo cancellation" setting selects. +# +#Either the 1.x or the 2.x ABI will do. They install in parallel under +#separate pkg-config names, and pica-client/echocanceller.cpp carries the few +#conditionals the API break between them needs. 0.x is not a candidate at any +#price: it predates AEC3 entirely, and its whole API is different. +# +#1.x is preferred when both are installed, only because it is the one this has +#had the most hours on. --with-webrtc-audio-processing=2 forces the other, +#which is how the 2.x path gets exercised deliberately rather than by accident +#of what is on the build machine. +AC_ARG_WITH([webrtc-audio-processing], + [AS_HELP_STRING([--with-webrtc-audio-processing=@<:@auto|1|2@:>@], + [webrtc-audio-processing major version to build against (default: auto, preferring 1)])], + [], [with_webrtc_audio_processing=auto]) + +AS_CASE([$with_webrtc_audio_processing], + [auto], [webrtc_audio_processing_try="1 2"], + [1], [webrtc_audio_processing_try="1"], + [2], [webrtc_audio_processing_try="2"], + [AC_MSG_ERROR([--with-webrtc-audio-processing must be auto, 1 or 2])]) + +WEBRTC_AUDIO_PROCESSING_MAJOR= +for webrtc_audio_processing_major in $webrtc_audio_processing_try; do + AS_IF([test "x$WEBRTC_AUDIO_PROCESSING_MAJOR" = x], + [PKG_CHECK_MODULES([WEBRTC_AUDIO_PROCESSING], + [webrtc-audio-processing-$webrtc_audio_processing_major], + [WEBRTC_AUDIO_PROCESSING_MAJOR=$webrtc_audio_processing_major], + [:])]) +done + +AS_IF([test "x$WEBRTC_AUDIO_PROCESSING_MAJOR" = x], + [AC_MSG_ERROR(["webrtc-audio-processing 1.x or 2.x was not found. It provides the acoustic echo cancellation used in calls. On Debian 13 and Ubuntu 25.10 or newer it is libwebrtc-audio-processing-dev; the same name on Ubuntu 24.04 is version 0.3, which predates AEC3 and will not do. On Gentoo it is media-libs/webrtc-audio-processing:1"])]) + +AC_MSG_NOTICE([using webrtc-audio-processing-$WEBRTC_AUDIO_PROCESSING_MAJOR]) + +#echocanceller.cpp can work this out from the headers on its own, but only the +#check above knows which one was picked when both are installed. +AC_DEFINE_UNQUOTED([PICA_WEBRTC_AUDIO_PROCESSING_MAJOR], + [$WEBRTC_AUDIO_PROCESSING_MAJOR], + [Major version of the webrtc-audio-processing library being built against]) + +AC_SUBST([WEBRTC_AUDIO_PROCESSING_CFLAGS]) +AC_SUBST([WEBRTC_AUDIO_PROCESSING_LIBS]) + +#the WebRTC headers, and the abseil ones they include, refuse to compile as +#anything older. Recent compilers default to C++17 or later and need nothing +#added; older ones have to be told. +AC_LANG_PUSH([C++]) +AC_MSG_CHECKING([whether $CXX compiles C++17 without help]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#if __cplusplus < 201703L +#error C++17 is not the default +#endif]], [])], + [AC_MSG_RESULT([yes])], + [ + AC_MSG_RESULT([no]) + pica_saved_cxxflags="$CXXFLAGS" + CXXFLAGS="$CXXFLAGS -std=c++17" + AC_MSG_CHECKING([whether $CXX accepts -std=c++17]) + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#if __cplusplus < 201703L +#error C++17 is not enabled +#endif]], [])], + [AC_MSG_RESULT([yes])], + [ + AC_MSG_RESULT([no]) + CXXFLAGS="$pica_saved_cxxflags" + AC_MSG_ERROR(["A C++17 compiler is required to build pica-client"]) + ]) + ]) +AC_LANG_POP([C++]) + +#check for libpulse, used only to list PulseAudio sources and sinks in the +#settings dialog - playing and capturing through PulseAudio goes via FFmpeg's +#own "pulse" device and needs nothing from us. Without it the "PulseAudio / +#PipeWire" driver still works, but offers only the server's default device. +AS_IF([test "x$enable_pulse" != "xno"], [ + PKG_CHECK_MODULES([PULSE], [libpulse], + [ + PICA_PULSE_ENABLED=yes + AC_DEFINE([HAVE_LIBPULSE], [1], [Define to 1 if PulseAudio device enumeration is available]) + AC_SUBST([PULSE_CFLAGS]) + AC_SUBST([PULSE_LIBS]) + ], + [ + AS_IF([test "x$enable_pulse" = "xyes"], + [AC_MSG_ERROR(["PulseAudio support was requested but libpulse was not found"])], + [AC_MSG_WARN(["libpulse not found - the PulseAudio driver will only offer the default device"])]) + ]) +]) -AC_CHECK_PROG([OPENSSL_TOOL], [openssl], [yes], [no]) -AS_IF([test "x$OPENSSL_TOOL" != xyes],[AC_MSG_WARN(["openssl command line tool not found. This is a runtime dependency for pica-client!"])]) +#check for VAAPI libraries, unless explicitly disabled +#libva is the accelerator itself, libva-drm opens it through a DRM render node, +#and EGL is what lets a decoded surface be handed to OpenGL without a copy. +AS_IF([test "x$enable_vaapi" != "xno"], [ + PKG_CHECK_MODULES([VAAPI], [libva libva-drm egl], + [ + PICA_VAAPI_ENABLED=yes + AC_DEFINE([HAVE_VAAPI], [1], [Define to 1 if VAAPI accelerated video is available]) + AC_SUBST([VAAPI_CFLAGS]) + AC_SUBST([VAAPI_LIBS]) + ], + [ + AS_IF([test "x$enable_vaapi" = "xyes"], + [AC_MSG_ERROR(["VAAPI support was requested but libva, libva-drm or EGL was not found"])], + [AC_MSG_WARN(["libva, libva-drm or EGL not found - building without VAAPI acceleration"])]) + ]) ]) +#check for libva's X11 rendering support, needed to draw a decoded surface in +#an X11 session, where Qt's OpenGL contexts are GLX rather than EGL ones. +#libGL comes along because working out which of the two a session gives means +#asking GLX whether it owns the context. +AS_IF([test "x$enable_vaapi_x11" = "xyes" && test "x$PICA_VAAPI_ENABLED" != "xyes"], + [AC_MSG_ERROR(["X11 rendering was requested but VAAPI support is not enabled"])]) + +AS_IF([test "x$PICA_VAAPI_ENABLED" = "xyes" && test "x$enable_vaapi_x11" != "xno"], [ + PKG_CHECK_MODULES([VAAPI_X11], [libva-x11 x11 gl], + [ + PICA_VAAPI_X11_ENABLED=yes + AC_DEFINE([HAVE_VAAPI_X11], [1], [Define to 1 if libva X11 rendering support is available]) + AC_SUBST([VAAPI_X11_CFLAGS]) + AC_SUBST([VAAPI_X11_LIBS]) + ], + [ + AS_IF([test "x$enable_vaapi_x11" = "xyes"], + [AC_MSG_ERROR(["X11 rendering was requested but libva-x11, libX11 or libGL was not found"])], + [AC_MSG_WARN(["libva-x11, libX11 or libGL not found - building without X11 rendering, hardware rendering will need an EGL session"])]) + ]) +]) + +#check whether FFmpeg knows how to encode and decode through Direct3D 12, one +#of the ways a Windows build reaches the GPU: libva is not part of that +#platform, but the hwcontext machinery the VAAPI path uses carries a D3D12 +#device type as well, and libavcodec has h264_d3d12va and hevc_d3d12va encoders +#and D3D12 hwaccels for its decoders to go with it. +# +#Nothing is linked for this - libavutil loads d3d12.dll itself when a device is +#created - so all there is to check is that the headers are new enough to name +#the device type and the pixel format. Whether those encoders and hwaccels were +#compiled into the libavcodec being built against, and whether the machine the +#client ends up running on has a GPU that can use them, are both runtime +#questions, answered by falling back to software. +# +#The other Windows paths - Media Foundation encoding, Direct3D 11 and DXVA2 +#decoding - need no check of their own: FFmpeg's headers have named them for +#far longer than any FFmpeg this builds against, so they are compiled in on +#every Windows build and left to the runtime to find out whether they work. +AS_IF([test "x$TARGET_OS" = "xwindows" && test "x$enable_d3d12va" != "xno"], [ + AC_MSG_CHECKING([whether FFmpeg supports Direct3D 12 video encoding and decoding]) + + pica_save_CPPFLAGS="$CPPFLAGS" + CPPFLAGS="$CPPFLAGS $FFMPEG_CFLAGS" + + AC_COMPILE_IFELSE( + [AC_LANG_PROGRAM( + [[#include <libavutil/hwcontext.h> + #include <libavutil/pixfmt.h>]], + [[enum AVHWDeviceType device = AV_HWDEVICE_TYPE_D3D12VA; + enum AVPixelFormat format = AV_PIX_FMT_D3D12; + (void)device; (void)format;]])], + [ + PICA_D3D12VA_ENABLED=yes + AC_DEFINE([HAVE_D3D12VA], [1], [Define to 1 if FFmpeg can encode and decode video through Direct3D 12]) + AC_MSG_RESULT([yes]) + ], + [ + AC_MSG_RESULT([no]) + AS_IF([test "x$enable_d3d12va" = "xyes"], + [AC_MSG_ERROR(["Direct3D 12 acceleration was requested but this FFmpeg has no D3D12 hardware context"])], + [AC_MSG_WARN(["this FFmpeg has no D3D12 hardware context - building without Direct3D 12 acceleration"])]) + ]) + + CPPFLAGS="$pica_save_CPPFLAGS" +]) + +AS_IF([test "x$TARGET_OS" != "xwindows" && test "x$enable_d3d12va" = "xyes"], + [AC_MSG_ERROR(["Direct3D 12 acceleration was requested but it only exists on Windows"])]) +]) + +AM_CONDITIONAL([PICA_PULSE], [test "x$PICA_PULSE_ENABLED" = "xyes"]) +AM_CONDITIONAL([PICA_VAAPI], [test "x$PICA_VAAPI_ENABLED" = "xyes"]) +AM_CONDITIONAL([PICA_VAAPI_X11], [test "x$PICA_VAAPI_X11_ENABLED" = "xyes"]) + +AC_SUBST([PLATFORM_DEPS_CFLAGS]) +AC_SUBST([PLATFORM_DEPS_LIBS]) # Checks for header files. AC_CHECK_HEADERS([arpa/inet.h limits.h netdb.h netinet/in.h stdlib.h string.h sys/ioctl.h sys/socket.h sys/time.h unistd.h]) @@ -134,5 +387,28 @@ AC_TYPE_UINT16_T # Checks for library functions. AC_CHECK_FUNCS([getcwd inet_ntoa memmove memset select socket strchr strstr strtol]) -AC_CONFIG_FILES([Makefile]) +VERSION=$PACKAGE_VERSION +AC_SUBST([VERSION]) + +# Both the assemblyIdentity element of a Windows application manifest and the +# FILEVERSION field of a VERSIONINFO resource only accept a version of exactly +# four numbers, which the package version ("0.9.0dev") is not. Cut it at the +# first character that is neither a digit nor a dot and pad the rest with ".0" +# up to four components. The manifest wants them separated by dots and +# VERSIONINFO by commas, so both spellings are substituted. +AC_MSG_CHECKING([for the Windows binary version number]) +PICA_WINDOWS_VERSION=`echo "$PACKAGE_VERSION" | sed -e ['s/[^0-9.].*$//'] -e ['s/\.*$//']` +AS_IF([test -z "$PICA_WINDOWS_VERSION"], [PICA_WINDOWS_VERSION=0]) +while test `echo "$PICA_WINDOWS_VERSION" | tr -dc . | wc -c` -lt 3 +do + PICA_WINDOWS_VERSION="$PICA_WINDOWS_VERSION.0" +done +PICA_WINDOWS_VERSION_COMMAS=`echo "$PICA_WINDOWS_VERSION" | tr . ,` +AC_MSG_RESULT([$PICA_WINDOWS_VERSION]) +AC_SUBST([PICA_WINDOWS_VERSION]) +AC_SUBST([PICA_WINDOWS_VERSION_COMMAS]) + +AM_CONDITIONAL([TARGET_WINDOWS], [test x$TARGET_OS = xwindows]) +AM_CONDITIONAL([TARGET_DARWIN], [test x$TARGET_OS = xdarwin]) +AC_CONFIG_FILES([Makefile windows/installer32.nsi windows/installer64.nsi windows/pica-client.exe.manifest windows/pica-node.exe.manifest]) AC_OUTPUT diff --git a/deb_packaging/README.md b/deb_packaging/README.md new file mode 100644 index 0000000..c87fd15 --- /dev/null +++ b/deb_packaging/README.md @@ -0,0 +1,138 @@ +# Debian and Ubuntu packaging + +Builds the pica-pica packages for every distribution we support, each in its +own podman container, and assembles the results into a signed apt repository. + +## Scripts + +| | | +|---|---| +| `build-pica-packages.sh` | The one to run. Installs podman, builds every target, assembles and signs the repository. | +| `build-webrtc-audio-processing.sh` | Backports Debian's webrtc-audio-processing 1.3 to a distribution that has no 1.x of its own. Usable on its own; the orchestrator calls it per container. | +| `container-build.sh` | The in-container worker. Not run by hand. | + +## Usage + +Make a source tarball the usual way, then hand it over: + +```sh +cd /path/to/pica-pica && ./configure && make dist +cd deb_packaging +./build-pica-packages.sh --gpg-key packaging@picapica.im \ + ../pica-pica-0.9.0dev.tar.gz +``` + +That leaves a repository in `repo/` and the raw `.deb` files in `out/`. + +Useful while iterating: + +```sh +./build-pica-packages.sh --only 'noble/*' --no-sign ../pica-pica-*.tar.gz +./build-pica-packages.sh --skip-build -k KEYID # re-sign what is in out/ +``` + +A `make dist` tarball is self-contained: it already carries the generated +`configure` and `Makefile.in`, so the containers have nothing to bootstrap. +They will fall back to `autoreconf -i -f` if handed a tarball made some other +way, and `autoconf`/`automake` are installed regardless — if the tarball's +timestamps leave `Makefile.am` looking newer than `Makefile.in`, automake's +own rebuild rules fire during the build and want them. + +Whatever the tarball is called and however it is compressed, it is bind +mounted into each container under one fixed name; `tar` works the compression +out from the content. + +## Build matrix + +| Distribution | Codename | amd64 | i386 | webrtc-audio-processing | +|---|---|---|---|---| +| Ubuntu 24.04 LTS | noble | yes | **no** | backported by us (archive has 0.3.1) | +| Ubuntu 26.04 LTS | resolute | yes | **no** | from the archive (1.3-3build2) | +| Debian 13 | trixie | yes | yes | from the archive (1.3-3) | + +### Why there is no Ubuntu i386 + +Ubuntu dropped i386 as an architecture after 18.04. What is left is a small +multiarch compatibility subset with no installable base system: there is no +i386 Ubuntu container image (`docker.io/i386/ubuntu` stops at `18.04`) and no +i386 Qt to build against. Debian still carries i386 as a full architecture, +including `qtbase5-dev`, so the 32 bit build is done there. + +## The webrtc-audio-processing backport + +pica-client needs AEC3, which arrived in webrtc-audio-processing 1.x. Ubuntu +24.04 ships 0.3.1, which predates it and has an entirely different API, so +noble needs a backport of Debian's 1.3-3. Nothing else does — the check is +made inside each container, and the script exits without doing anything where +the archive is already good enough. + +Debian's packaging is taken unmodified except for two things: + +1. **The `-dev` package is renamed** to `libwebrtc-audio-processing-1-dev`, + which is the name Debian itself used for 1.3-1. Debian renamed it to the + unversioned `libwebrtc-audio-processing-dev` in 1.3-2, after dropping 0.3 + from the archive — but noble still ships 0.3.1 under exactly that name, and + taking it over would replace a package other things build against. + + Nothing else collides. Upstream already versions everything that matters: + + | | 0.3.1 (noble) | 1.3 (ours) | + |---|---|---| + | headers | `/usr/include/webrtc_audio_processing/` | `/usr/include/webrtc-audio-processing-1/` | + | library | `libwebrtc_audio_processing.so.1` | `libwebrtc-audio-processing-1.so.3` | + | pkg-config | `webrtc-audio-processing` | `webrtc-audio-processing-1` | + | runtime deb | `libwebrtc-audio-processing1` | `libwebrtc-audio-processing-1-3` | + + So the four packages we produce — `libwebrtc-audio-processing-1-dev`, + `libwebrtc-audio-processing-1-3`, `libwebrtc-audio-coding-dev`, + `libwebrtc-audio-coding-1-3` — are all collision-free on noble. + +2. **Debian's rename-era `Breaks`/`Replaces` are dropped.** With the old name + back they say nothing, and the pair on `libwebrtc-audio-coding-dev` would + otherwise declare `Replaces: libwebrtc-audio-processing-dev (<< 1.3-2~)`, + which on noble matches the distribution's own 0.3 package — the exact thing + this is trying not to disturb. The unrelated relationship between the two + runtime packages is kept. + +The version is `1.3-3~noble1`. The `~` sorts it *below* plain `1.3-3`, so if +Ubuntu ever ships 1.3 itself, apt upgrades away from the backport rather than +being held back by it. + +## Signing + +The GPG key never enters a container. Containers produce `.deb` files; +the repository is assembled and signed on the host. Both `InRelease` +(what modern apt fetches) and `Release.gpg` are produced, and the public key +is exported to `repo/pica-pica-archive-keyring.asc`. + +Packages themselves are not signed with `debsigs` — apt does not check that; +repository trust comes from the signed `Release`. + +## Repository layout + +One pool per codename rather than a shared one. Indices are per suite, and a +shared pool would let noble's `Packages` list trixie's binaries — apt would +offer them and they would not install. + +``` +repo/ +├── dists/<codename>/ +│ ├── Release, Release.gpg, InRelease +│ └── main/binary-<arch>/{Packages,Packages.gz,Release} +├── pool/<codename>/main/<letter>/<source>/*.deb +└── pica-pica-archive-keyring.asc +``` + +## Client setup + +```sh +sudo install -d /usr/share/keyrings +sudo curl -fsSL https://YOUR.HOST/pica-pica-archive-keyring.asc \ + -o /usr/share/keyrings/pica-pica-archive-keyring.asc + +echo "deb [signed-by=/usr/share/keyrings/pica-pica-archive-keyring.asc] \ +https://YOUR.HOST $(lsb_release -cs) main" \ + | sudo tee /etc/apt/sources.list.d/pica-pica.list + +sudo apt update && sudo apt install pica-client +``` diff --git a/deb_packaging/build-pica-packages.sh b/deb_packaging/build-pica-packages.sh new file mode 100755 index 0000000..d8f7599 --- /dev/null +++ b/deb_packaging/build-pica-packages.sh @@ -0,0 +1,418 @@ +#!/bin/bash +# +# Builds the pica-pica Debian packages for every distribution we support, each +# in its own podman container, and assembles the results into a signed apt +# repository. +# +# Takes a source tarball as produced by "make dist" - a self contained +# autotools distribution, which already carries the generated configure, so +# the containers have nothing to bootstrap. +# +# Meant to be run on an Ubuntu 24.04 host, but the only thing that is host +# specific is installing podman; give it podman by hand and it will run +# anywhere. +# +# The build matrix is at the top of the script. Note what is NOT in it: +# Ubuntu i386. Ubuntu has had no i386 architecture since 19.10 - what remains +# is a small multiarch compatibility subset with no installable base system, +# so there is no i386 Ubuntu container image to build in (docker.io/i386/ubuntu +# stops at 18.04) and no i386 Qt to build against. Debian still has i386 as a +# full architecture, so the 32 bit build happens there. +# +# The GPG key never enters a container. Containers produce .deb files; the +# repository is assembled and signed here on the host. +# +# (c) Copyright 2012 - 2026 Anton Sviridenko +# https://picapica.im +# +# 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, version 3. + +set -euo pipefail + +# codename | container image | dpkg arch | podman platform +TARGETS=( + "noble|docker.io/library/ubuntu:24.04|amd64|linux/amd64" + "resolute|docker.io/library/ubuntu:26.04|amd64|linux/amd64" + "trixie|docker.io/library/debian:trixie|amd64|linux/amd64" + "trixie|docker.io/i386/debian:trixie|i386|linux/386" +) + +SCRIPTDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +TARBALL="" +OUTDIR="$SCRIPTDIR/out" +REPODIR="$SCRIPTDIR/repo" +GPGKEY="" +SIGN=1 +ONLY="" +SKIP_BUILD=0 + +ORIGIN="Pica Pica" +LABEL="Pica Pica" + +progname=$(basename "$0") + +usage() +{ + cat <<EOF +Usage: $progname [OPTIONS] TARBALL + +Build the pica-pica packages in containers and assemble a signed apt +repository from the results. + +TARBALL is a source tarball as produced by "make dist" in the pica-pica tree, +e.g. pica-pica-0.9.0dev.tar.gz. Not needed with --skip-build. + +Options: + -k, --gpg-key KEYID Key to sign the repository's Release files with. Any + form gpg accepts - key id, fingerprint, or the email + address on the uid. Required unless --no-sign. + --no-sign Build the repository but leave it unsigned. apt will + refuse it without extra configuration; for testing. + -o, --output DIR Where the containers leave their .deb files. + Default: $OUTDIR + -r, --repo DIR Where to assemble the apt repository. + Default: $REPODIR + --only PATTERN Only build targets whose "codename/arch" matches this + shell pattern, e.g. --only 'noble/*' or --only '*/i386'. + --skip-build Do not build anything; just assemble and sign the + repository from whatever is already in the output + directory. + -h, --help This message. + +Targets: +EOF + + local t cn img arch plat + for t in "${TARGETS[@]}"; do + IFS='|' read -r cn img arch plat <<<"$t" + printf ' %-16s %-34s %s\n' "$cn/$arch" "$img" "$plat" + done + + cat <<'EOF' + +There is no Ubuntu i386 target and there cannot be: Ubuntu dropped i386 as an +architecture after 18.04, so there is no i386 Ubuntu base image and no i386 Qt +to build against. The 32 bit build is done on Debian, which still carries i386 +as a full architecture. +EOF +} + +die() +{ + echo "$progname: error: $*" >&2 + exit 1 +} + +note() +{ + echo + echo "=== $*" +} + +while [ $# -gt 0 ]; do + case "$1" in + -k|--gpg-key) GPGKEY="${2:?--gpg-key needs a value}"; shift 2 ;; + --no-sign) SIGN=0; shift ;; + -o|--output) OUTDIR="${2:?--output needs a value}"; shift 2 ;; + -r|--repo) REPODIR="${2:?--repo needs a value}"; shift 2 ;; + --only) ONLY="${2:?--only needs a value}"; shift 2 ;; + --skip-build) SKIP_BUILD=1; shift ;; + -h|--help) usage; exit 0 ;; + -*) die "unknown option $1 (try --help)" ;; + *) break ;; + esac +done + +if [ $# -gt 1 ]; then + die "expected at most one tarball, got: $*" +elif [ $# -eq 1 ]; then + TARBALL=$(readlink -f "$1") +fi + +if [ "$SIGN" -eq 1 ] && [ -z "$GPGKEY" ]; then + die "no signing key given. Pass --gpg-key KEYID, or --no-sign to skip signing" +fi + +if [ "$SKIP_BUILD" -eq 0 ]; then + [ -n "$TARBALL" ] || + die "no source tarball given. Run \"make dist\" in the pica-pica tree and pass the result (try --help)" + [ -f "$TARBALL" ] || + die "$TARBALL does not exist" + tar -tf "$TARBALL" >/dev/null 2>&1 || + die "$TARBALL is not a readable tar archive" +fi + +if [ "$(id -u)" -eq 0 ]; then + SUDO="" +elif command -v sudo >/dev/null; then + SUDO="sudo" +else + # Not fatal on its own. Nothing may need installing, which is the normal + # case on a signing-only machine; ensure_tool() complains if something + # actually is missing. + SUDO="" +fi + +# Installs a package, but only if the tool it provides is not already there - +# and says plainly why it cannot when it has no way to become root, rather +# than letting apt-get fail with something less obvious. +ensure_tool() +{ + local tool="$1" package="$2" + + command -v "$tool" >/dev/null && return 0 + + if [ "$(id -u)" -ne 0 ] && [ -z "$SUDO" ]; then + die "$tool is missing and would come from the $package package, but this is not root and there is no sudo" + fi + + note "installing $package, for $tool" + $SUDO apt-get install -y "$package" +} + +# --- tools ---------------------------------------------------------------- + +# podman only when there is something to build. --skip-build exists so that +# the repository can be assembled and signed on a machine that holds the key +# and does nothing else; installing a container runtime on that machine would +# be exactly backwards. +if [ "$SKIP_BUILD" -eq 0 ]; then + if command -v podman >/dev/null; then + note "podman is already installed: $(podman --version)" + else + if [ "$(id -u)" -ne 0 ] && [ -z "$SUDO" ]; then + die "podman is missing and this is not root and there is no sudo - install podman yourself and re-run" + fi + note "installing podman" + $SUDO apt-get update + $SUDO apt-get install -y podman + fi +fi + +# apt-ftparchive builds the repository indices, so it is needed in both +# modes. gpg only matters when there is something to sign. +ensure_tool apt-ftparchive apt-utils + +if [ "$SIGN" -eq 1 ]; then + ensure_tool gpg gnupg +fi + +if [ "$SIGN" -eq 1 ]; then + gpg --list-keys "$GPGKEY" >/dev/null 2>&1 || + die "gpg does not know a key called '$GPGKEY'" + gpg --list-secret-keys "$GPGKEY" >/dev/null 2>&1 || + die "no SECRET key for '$GPGKEY' - the repository cannot be signed with it" +fi + +# --- work area ------------------------------------------------------------ + +WORKDIR=$(mktemp -d /tmp/pica-packaging.XXXXXX) +trap 'rm -rf "$WORKDIR"' EXIT + +if [ "$SKIP_BUILD" -eq 0 ]; then + note "source tarball" + echo " $TARBALL" + echo " $(du -h "$TARBALL" | cut -f1), top level: $(tar -tf "$TARBALL" | head -1)" +fi + +# --- build ---------------------------------------------------------------- + +mkdir -p "$OUTDIR" + +BUILT=() +FAILED=() + +if [ "$SKIP_BUILD" -eq 0 ]; then + for target in "${TARGETS[@]}"; do + IFS='|' read -r codename image arch platform <<<"$target" + + if [ -n "$ONLY" ]; then + # shellcheck disable=SC2254 + case "$codename/$arch" in + $ONLY) ;; + *) echo " skipping $codename/$arch (does not match --only '$ONLY')"; continue ;; + esac + fi + + note "$codename/$arch ($image)" + + if ! podman pull --platform "$platform" "$image"; then + FAILED+=("$codename/$arch: could not pull $image") + continue + fi + + # --userns=keep-id is deliberately not used: the build wants to be + # root inside the container to install packages, and in rootless + # podman that still maps back to this user on the way out. + # The tarball is bind mounted as a single file under a fixed name, so + # container-build.sh does not have to be told what it is called. tar + # works out the compression from the content, so the missing .gz or + # .xz on that name costs nothing. + if podman run --rm \ + --platform "$platform" \ + -v "$TARBALL:/src/pica-source.tar:ro" \ + -v "$SCRIPTDIR:/scripts:ro" \ + -v "$OUTDIR:/out" \ + -e PICA_DISTRO="$codename" \ + -e PICA_ARCH="$arch" \ + -w / \ + "$image" \ + /bin/bash /scripts/container-build.sh + then + BUILT+=("$codename/$arch") + else + FAILED+=("$codename/$arch: build failed") + fi + done + + note "build summary" + for b in "${BUILT[@]:-}"; do [ -n "$b" ] && echo " ok $b"; done + for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAILED $f"; done + + [ ${#BUILT[@]} -gt 0 ] || die "nothing built - not assembling a repository" +fi + +# --- repository ----------------------------------------------------------- +# +# Laid out with a pool per codename rather than one shared pool. The indices +# are per suite, and a shared pool would let noble's Packages list trixie's +# binaries - apt would happily offer them and they would not install. + +note "assembling the repository in $REPODIR" + +rm -rf "$REPODIR" +mkdir -p "$REPODIR" + +CODENAMES=() + +for distdir in "$OUTDIR"/*/; do + [ -d "$distdir" ] || continue + codename=$(basename "$distdir") + + arches=() + + for archdir in "$distdir"*/; do + [ -d "$archdir" ] || continue + arch=$(basename "$archdir") + + compgen -G "$archdir*.deb" >/dev/null || continue + arches+=("$arch") + + for deb in "$archdir"*.deb; do + # Pool path by source package, the way Debian lays it out, so + # that the binaries of one source sit together. + src=$(dpkg-deb -f "$deb" Source 2>/dev/null | awk '{print $1}') + [ -n "$src" ] || src=$(dpkg-deb -f "$deb" Package) + case "$src" in + lib*) letter="${src:0:4}" ;; + *) letter="${src:0:1}" ;; + esac + + pool="$REPODIR/pool/$codename/main/$letter/$src" + mkdir -p "$pool" + cp "$deb" "$pool/" + done + done + + [ ${#arches[@]} -gt 0 ] || continue + CODENAMES+=("$codename") + + # Deduplicate: a codename built for two architectures appears twice above. + mapfile -t arches < <(printf '%s\n' "${arches[@]}" | sort -u) + + echo " $codename: ${arches[*]}" + + for arch in "${arches[@]}"; do + bindir="$REPODIR/dists/$codename/main/binary-$arch" + mkdir -p "$bindir" + + # Run from the repository root so that the Filename fields come out + # relative to it, which is what apt expects. + ( cd "$REPODIR" && + apt-ftparchive --arch "$arch" packages "pool/$codename" \ + > "dists/$codename/main/binary-$arch/Packages" ) + + gzip -9 -k -f "$bindir/Packages" + + cat > "$bindir/Release" <<EOF +Archive: $codename +Suite: $codename +Component: main +Origin: $ORIGIN +Label: $LABEL +Architecture: $arch +EOF + done + + # The suite Release, carrying the checksums of everything above. Written + # to a temporary file first - apt-ftparchive walks the directory it is + # indexing, and would otherwise hash a half-written Release. + ( cd "$REPODIR" && + apt-ftparchive \ + -o APT::FTPArchive::Release::Origin="$ORIGIN" \ + -o APT::FTPArchive::Release::Label="$LABEL" \ + -o APT::FTPArchive::Release::Suite="$codename" \ + -o APT::FTPArchive::Release::Codename="$codename" \ + -o APT::FTPArchive::Release::Components="main" \ + -o APT::FTPArchive::Release::Architectures="${arches[*]}" \ + -o APT::FTPArchive::Release::Description="Pica Pica Messenger packages" \ + release "dists/$codename" > "$WORKDIR/Release.$codename" ) + + mv "$WORKDIR/Release.$codename" "$REPODIR/dists/$codename/Release" + + if [ "$SIGN" -eq 1 ]; then + echo " signing $codename with $GPGKEY" + rm -f "$REPODIR/dists/$codename/Release.gpg" \ + "$REPODIR/dists/$codename/InRelease" + + # Both forms: InRelease is what modern apt fetches, Release.gpg is + # the detached signature older clients look for. + gpg --batch --yes --default-key "$GPGKEY" \ + --armor --detach-sign \ + -o "$REPODIR/dists/$codename/Release.gpg" \ + "$REPODIR/dists/$codename/Release" + + gpg --batch --yes --default-key "$GPGKEY" \ + --clearsign \ + -o "$REPODIR/dists/$codename/InRelease" \ + "$REPODIR/dists/$codename/Release" + fi +done + +[ ${#CODENAMES[@]} -gt 0 ] || die "no packages found under $OUTDIR" + +if [ "$SIGN" -eq 1 ]; then + gpg --armor --export "$GPGKEY" > "$REPODIR/pica-pica-archive-keyring.asc" +fi + +# --- how to use it -------------------------------------------------------- + +note "done" +cat <<EOF + +Repository: $REPODIR +Suites: ${CODENAMES[*]} + +Serve that directory over HTTP, then on a client: + + sudo install -d /usr/share/keyrings + sudo curl -fsSL https://YOUR.HOST/pica-pica-archive-keyring.asc \\ + -o /usr/share/keyrings/pica-pica-archive-keyring.asc + + echo "deb [signed-by=/usr/share/keyrings/pica-pica-archive-keyring.asc] \\ +https://YOUR.HOST \$(lsb_release -cs) main" \\ + | sudo tee /etc/apt/sources.list.d/pica-pica.list + + sudo apt update && sudo apt install pica-client +EOF + +if [ "$SIGN" -eq 0 ]; then + cat <<'EOF' + +The repository is NOT signed. apt will reject it unless clients add +[trusted=yes] to the sources.list entry, which disables authentication - +do that for local testing only. +EOF +fi diff --git a/deb_packaging/build-webrtc-audio-processing.sh b/deb_packaging/build-webrtc-audio-processing.sh new file mode 100755 index 0000000..8837bd7 --- /dev/null +++ b/deb_packaging/build-webrtc-audio-processing.sh @@ -0,0 +1,379 @@ +#!/bin/bash +# +# Build a backported webrtc-audio-processing 1.3 for a distribution whose +# archive does not carry it. +# +# pica-client needs AEC3, which arrived in the 1.x series. Ubuntu 24.04 still +# ships 0.3.1, which predates it entirely and has a different API. Debian 13 +# and Ubuntu 25.10 or newer already have 1.3, so on those this script does +# nothing unless forced. +# +# Debian's own packaging is taken as-is and given a two-part delta: +# +# - The -dev binary package is renamed back to the name Debian itself used +# for 1.3-1, libwebrtc-audio-processing-1-dev. Debian renamed it to the +# unversioned libwebrtc-audio-processing-dev in 1.3-2, after dropping 0.3 +# from the archive - but on a distribution that still ships 0.3 under +# that unversioned name, taking it over would replace a package other +# things build against. Nothing else collides: the runtime package +# (libwebrtc-audio-processing-1-3), the SONAME, the include directory and +# the pkg-config name are all versioned by upstream already. +# +# - The Breaks/Replaces relationships that record Debian's own rename are +# dropped. They are meaningless once the package carries the old name +# again, and on the audio-coding package they would otherwise declare a +# Replaces on the distribution's 0.3 -dev package, which is the exact +# thing this is trying not to disturb. +# +# Run this inside the target distribution - a container from +# build-pica-packages.sh, an sbuild chroot, or a machine running it. It uses +# apt, so it has to be somewhere that apt describes the target archive. +# +# (c) Copyright 2012 - 2026 Anton Sviridenko +# https://picapica.im +# +# 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, version 3. + +set -euo pipefail + +UPSTREAM_VERSION=1.3 +DEBIAN_REVISION=3 +DEBIAN_MIRROR=https://deb.debian.org/debian +POOL="$DEBIAN_MIRROR/pool/main/w/webrtc-audio-processing" + +# The version below which the distribution's own package is no good to us. +# 0.3 has no AEC3; see the note at the top. +MINIMUM_USABLE_VERSION=1.3 + +ARCH="" +OUTDIR="$PWD/out" +FORCE=0 +RENAME_DEV=1 +KEEP_BUILD=0 + +progname=$(basename "$0") + +usage() +{ + cat <<EOF +Usage: $progname [OPTIONS] DISTRO + +Build webrtc-audio-processing $UPSTREAM_VERSION-$DEBIAN_REVISION as a backport for DISTRO. + +DISTRO is the target distribution codename - noble, resolute, trixie. It is +used in the package version (${UPSTREAM_VERSION}-${DEBIAN_REVISION}~DISTRO1) and the changelog entry, so that +the distribution's own package supersedes this one if it ever gains a newer +version. + +Options: + -a, --arch ARCH Architecture to build for. Accepts either dpkg names + (amd64, arm64, i386) or uname names (x86_64, aarch64, + i686), which are normalised. Defaults to the + architecture this is running on. Anything else is a + cross build and needs crossbuild-essential-ARCH, which + this will install. + -o, --output DIR Where to put the resulting .deb files. + Default: $OUTDIR + -f, --force Build even when the distribution already has a good + enough webrtc-audio-processing. + --no-rename-dev Keep Debian's unversioned libwebrtc-audio-processing-dev + name. Only correct where the distribution has no 0.3 of + its own to collide with. + --keep-build Leave the build tree behind for inspection. + -h, --help This message. + +Exit status: + 0 packages built, or the distribution already has a good enough one + 1 something went wrong +EOF +} + +die() +{ + echo "$progname: error: $*" >&2 + exit 1 +} + +note() +{ + echo "==> $*" +} + +# dpkg and uname disagree about architecture names, and people reach for +# whichever they saw last. Take both. +normalise_arch() +{ + case "$1" in + x86_64|amd64) echo amd64 ;; + aarch64|arm64) echo arm64 ;; + i386|i486|i586|i686) echo i386 ;; + armv7l|armhf) echo armhf ;; + ppc64le|ppc64el) echo ppc64el ;; + *) echo "$1" ;; + esac +} + +while [ $# -gt 0 ]; do + case "$1" in + -a|--arch) ARCH=$(normalise_arch "${2:?--arch needs a value}"); shift 2 ;; + -o|--output) OUTDIR="${2:?--output needs a value}"; shift 2 ;; + -f|--force) FORCE=1; shift ;; + --no-rename-dev) RENAME_DEV=0; shift ;; + --keep-build) KEEP_BUILD=1; shift ;; + -h|--help) usage; exit 0 ;; + -*) die "unknown option $1 (try --help)" ;; + *) break ;; + esac +done + +[ $# -eq 1 ] || { usage >&2; exit 1; } +DISTRO="$1" + +[ "$(id -u)" -eq 0 ] || die "this installs build dependencies, so it needs to run as root" + +command -v apt-get >/dev/null || die "no apt-get - this has to run inside the target distribution" + +HOST_ARCH=$(dpkg --print-architecture) +BUILD_ARCH="${ARCH:-$HOST_ARCH}" +CROSS=0 +[ "$BUILD_ARCH" = "$HOST_ARCH" ] || CROSS=1 + +VERSION="${UPSTREAM_VERSION}-${DEBIAN_REVISION}~${DISTRO}1" + +export DEBIAN_FRONTEND=noninteractive + +# Is it needed at all? +# +# apt-cache policy reports the candidate the target archive would install. +# Anything from 1.x on is fine and there is no reason to ship our own. +if [ "$FORCE" -eq 0 ]; then + apt-get update -qq + + candidate=$(apt-cache policy libwebrtc-audio-processing-dev 2>/dev/null | + sed -n 's/^ Candidate: //p') + + if [ -n "$candidate" ] && [ "$candidate" != "(none)" ] && + dpkg --compare-versions "$candidate" ge "$MINIMUM_USABLE_VERSION"; then + note "$DISTRO already has libwebrtc-audio-processing-dev $candidate - nothing to build" + note "(pass --force to build the backport anyway)" + exit 0 + fi + + if [ -n "$candidate" ] && [ "$candidate" != "(none)" ]; then + note "$DISTRO has libwebrtc-audio-processing-dev $candidate, which predates AEC3 - backporting $VERSION" + else + note "$DISTRO has no libwebrtc-audio-processing-dev at all - backporting $VERSION" + fi +fi + +note "building webrtc-audio-processing $VERSION for $BUILD_ARCH" + +# Just enough to fetch and unpack a Debian source package. The build +# dependencies proper come from the extracted debian/control further down, +# via apt-get build-dep, so that this does not have to be kept in step with +# Debian's packaging by hand. +# +# devscripts is deliberately not installed: the changelog entry below is +# written directly, so this works without DEBEMAIL or DEBFULLNAME being set. +note "installing the tools needed to fetch the source" +apt-get install -qq -y --no-install-recommends \ + build-essential \ + ca-certificates \ + curl \ + dpkg-dev \ + xz-utils + +if [ "$CROSS" -eq 1 ]; then + note "cross building for $BUILD_ARCH from $HOST_ARCH" + dpkg --add-architecture "$BUILD_ARCH" + apt-get update -qq + apt-get install -qq -y --no-install-recommends \ + "crossbuild-essential-$BUILD_ARCH" +fi + +BUILDROOT=$(mktemp -d /tmp/webrtc-backport.XXXXXX) +cleanup() +{ + [ "$KEEP_BUILD" -eq 1 ] && { note "build tree left at $BUILDROOT"; return; } + rm -rf "$BUILDROOT" +} +trap cleanup EXIT + +cd "$BUILDROOT" + +DSC="webrtc-audio-processing_${UPSTREAM_VERSION}-${DEBIAN_REVISION}.dsc" + +note "fetching Debian's source package" +for f in "$DSC" \ + "webrtc-audio-processing_${UPSTREAM_VERSION}.orig.tar.gz" \ + "webrtc-audio-processing_${UPSTREAM_VERSION}-${DEBIAN_REVISION}.debian.tar.xz"; do + curl -fsSL --retry 3 -o "$f" "$POOL/$f" || die "could not fetch $f from $POOL" +done + +# dpkg-source checks the tarballs against the checksums in the .dsc as it +# extracts, so a corrupted or substituted tarball fails here. It does not +# check the .dsc's own OpenPGP signature; dscverify from devscripts does that +# and needs the Debian keyring, so it is done only when both are present. +if command -v dscverify >/dev/null && [ -d /usr/share/keyrings ]; then + if dscverify --keyring /usr/share/keyrings/debian-keyring.gpg "$DSC" >/dev/null 2>&1; then + note "the .dsc signature verifies against the Debian keyring" + else + note "WARNING: could not verify the .dsc signature (keyring missing or untrusted signer)" + fi +fi + +note "extracting" +dpkg-source -x "$DSC" src >/dev/null +cd src + +# Straight out of the extracted debian/control, so Debian's own list is the +# source of truth rather than a copy of it kept here. +note "installing Debian's build dependencies for it" +if [ "$CROSS" -eq 1 ]; then + apt-get build-dep -qq -y -a "$BUILD_ARCH" ./ || + die "could not satisfy the build dependencies for $BUILD_ARCH" +else + apt-get build-dep -qq -y ./ || + die "could not satisfy the build dependencies from debian/control" +fi + +# --- the delta ------------------------------------------------------------ + +if [ "$RENAME_DEV" -eq 1 ]; then + note "renaming libwebrtc-audio-processing-dev to libwebrtc-audio-processing-1-dev" + + # Only the -dev package is renamed. The runtime package keeps Debian's + # name (libwebrtc-audio-processing-1-3), which does not collide with + # 0.3's libwebrtc-audio-processing1 and is what pica-client will depend + # on through shlibs. + sed -i 's/^Package: libwebrtc-audio-processing-dev$/Package: libwebrtc-audio-processing-1-dev/' \ + debian/control + + grep -q '^Package: libwebrtc-audio-processing-1-dev$' debian/control || + die "the -dev package rename did not apply - has Debian's control changed?" + + # debhelper locates a binary package's configuration by file name - + # debian/<package>.install and the rest of that family - so renaming the + # package in debian/control and stopping there leaves dh_install with + # nothing matching the new name. The package builds empty, and then + # dh_missing aborts the build because every header, the .so symlink and + # the .pc file are unaccounted for. + # + # A glob rather than the one file Debian has today, so that a .links or a + # .lintian-overrides appearing later comes along on its own. + renamed=0 + for f in debian/libwebrtc-audio-processing-dev.*; do + [ -e "$f" ] || continue + mv "$f" "debian/libwebrtc-audio-processing-1-dev.${f#debian/libwebrtc-audio-processing-dev.}" + renamed=$((renamed + 1)) + done + + [ "$renamed" -gt 0 ] || + die "found no debian/libwebrtc-audio-processing-dev.* files to rename alongside the package - has Debian's packaging changed?" + + note "renamed $renamed per-package debhelper file(s) to match" +fi + +# Drop the Breaks/Replaces that record Debian's 1.3-1 -> 1.3-2 rename. +# +# With the -dev package carrying its old name again these say nothing useful, +# and the pair on libwebrtc-audio-coding-dev is actively wrong here: it +# declares Breaks/Replaces on libwebrtc-audio-processing-dev (<< 1.3-2~), +# which on a distribution still shipping 0.3 under that name matches the +# distribution's own package. +note "dropping Debian's rename-era Breaks/Replaces" +# perl rather than python3: a minimal Debian or Ubuntu container has no +# python3, but debhelper depends on perl so it is always here. +# +# A deb822 field runs from its name to the next line starting in column zero, +# continuation lines being those that start with whitespace - hence the +# (?:\n[ \t][^\n]*)* . Only the relationships naming the -dev packages are +# dropped; anything else Debian declares is left alone. +perl -0777 -i -pe ' + s{^((?:Breaks|Replaces):[^\n]*(?:\n[ \t][^\n]*)*\n)}{ + $1 =~ /libwebrtc-audio-(?:processing|coding)(?:-1)?-dev/ ? q{} : $1 + }gme; +' debian/control + +# A changelog entry written directly rather than through dch, so that this +# does not depend on DEBEMAIL/DEBFULLNAME being set in the container. +# +# The ~DISTRO1 suffix sorts BELOW the plain Debian version, so if the +# distribution ever ships 1.3-3 itself, apt upgrades away from this backport +# rather than being held back by it. +note "adding the changelog entry for $VERSION" +{ + cat <<EOF +webrtc-audio-processing ($VERSION) $DISTRO; urgency=medium + + * Rebuild of Debian's ${UPSTREAM_VERSION}-${DEBIAN_REVISION} for $DISTRO, which has no + webrtc-audio-processing 1.x of its own. pica-client needs it for AEC3. +EOF + + if [ "$RENAME_DEV" -eq 1 ]; then + cat <<'EOF' + * Keep the versioned libwebrtc-audio-processing-1-dev name that Debian used + for 1.3-1, so that this coexists with the 0.3 that the distribution ships + as libwebrtc-audio-processing-dev instead of replacing it + * Drop the Breaks/Replaces recording Debian's rename of that package; with + the old name back they say nothing, and on libwebrtc-audio-coding-dev the + pair would match the distribution's own 0.3 -dev package +EOF + fi + + cat <<EOF + + -- Pica Pica packaging <anton@picapica.im> $(date -R) + +EOF + cat debian/changelog +} > debian/changelog.new +mv debian/changelog.new debian/changelog + +note "the delta applied to Debian's packaging:" +sed -n '1,20p' debian/changelog | sed 's/^/ /' + +# --- sanity check --------------------------------------------------------- +# +# debhelper only notices a package with no per-package configuration at +# dh_missing, right at the end of a build that takes minutes. This is the same +# check, up front: every binary package this control file declares should have +# something telling dh_install what goes in it. +# +# A warning rather than an error - a package can legitimately be populated by +# other means - but for this source all four have a .install, so anything +# reported here means the delta above and Debian's packaging have drifted +# apart. +for p in $(sed -n 's/^Package: //p' debian/control); do + [ -e "debian/$p.install" ] && continue + note "WARNING: no debian/$p.install - $p will be built empty unless something else fills it" +done + +# --- build ---------------------------------------------------------------- + +note "building" +if [ "$CROSS" -eq 1 ]; then + dpkg-buildpackage --host-arch "$BUILD_ARCH" -b -us -uc +else + dpkg-buildpackage -b -us -uc +fi + +cd "$BUILDROOT" + +mkdir -p "$OUTDIR" +found=0 +for deb in *.deb; do + [ -e "$deb" ] || continue + cp -v "$deb" "$OUTDIR/" + found=1 +done +for changes in *.changes; do + [ -e "$changes" ] || continue + cp "$changes" "$OUTDIR/" +done + +[ "$found" -eq 1 ] || die "the build produced no .deb files" + +note "done - packages are in $OUTDIR" diff --git a/deb_packaging/container-build.sh b/deb_packaging/container-build.sh new file mode 100755 index 0000000..f8ef801 --- /dev/null +++ b/deb_packaging/container-build.sh @@ -0,0 +1,136 @@ +#!/bin/bash +# +# Builds the pica-pica packages inside one container. Not meant to be run by +# hand - build-pica-packages.sh starts a container per target and runs this +# as its entry point. +# +# What it expects to find, all put there by the orchestrator: +# +# /src/pica-source.tar the pica-pica source tarball, as produced by +# "make dist" - bind mounted under that fixed name +# whatever it is really called, and whatever it is +# compressed with +# /scripts/ this directory, so that the backport script is +# reachable +# /out/ writable; artifacts are left in +# /out/<codename>/<arch>/ +# +# and in the environment: PICA_DISTRO (codename) and PICA_ARCH (dpkg name). +# +# (c) Copyright 2012 - 2026 Anton Sviridenko +# https://picapica.im +# +# 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, version 3. + +set -euo pipefail + +DISTRO="${PICA_DISTRO:?PICA_DISTRO is not set}" +ARCH="${PICA_ARCH:-$(dpkg --print-architecture)}" + +export DEBIAN_FRONTEND=noninteractive + +note() +{ + echo "==> [$DISTRO/$ARCH] $*" +} + +die() +{ + echo "[$DISTRO/$ARCH] error: $*" >&2 + exit 1 +} + +note "starting, $(. /etc/os-release && echo "$PRETTY_NAME"), dpkg arch $(dpkg --print-architecture)" + +note "refreshing the package lists" +apt-get update -qq + +# autoconf/automake because the pica-pica tree does not carry a generated +# configure - it is not in git, so the tree has to be bootstrapped here. +note "installing the base build tooling" +apt-get install -qq -y --no-install-recommends \ + build-essential \ + ca-certificates \ + curl \ + dpkg-dev \ + debhelper \ + autoconf \ + automake \ + pkgconf + +# webrtc-audio-processing, if this distribution has nothing new enough. +# The script decides that for itself and exits without doing anything when +# the archive already has 1.x, so it is safe to call unconditionally. +note "checking whether webrtc-audio-processing needs backporting" +WEBRTC_OUT=/tmp/webrtc-backport-out +mkdir -p "$WEBRTC_OUT" + +bash /scripts/build-webrtc-audio-processing.sh --output "$WEBRTC_OUT" "$DISTRO" + +if compgen -G "$WEBRTC_OUT/*.deb" >/dev/null; then + note "installing the backported webrtc-audio-processing" + apt-get install -qq -y --no-install-recommends "$WEBRTC_OUT"/*.deb + + # These go into the repository too - without them the pica-client + # package would be uninstallable on this distribution. + mkdir -p "/out/$DISTRO/$ARCH" + cp -v "$WEBRTC_OUT"/*.deb "/out/$DISTRO/$ARCH/" +else + note "the archive's own webrtc-audio-processing is good enough" +fi + +# --- pica-pica ------------------------------------------------------------ + +note "unpacking the source" +rm -rf /build +mkdir -p /build +tar -xf /src/pica-source.tar -C /build + +# "make dist" produces exactly one top level directory, pica-pica-<version>. +SRCDIR=$(find /build -maxdepth 1 -mindepth 1 -type d | head -1) +[ -n "$SRCDIR" ] || die "the source tarball did not contain a directory" +cd "$SRCDIR" +note "source is $(basename "$SRCDIR")" + +[ -f debian/control ] || + die "no debian/control in the tarball - was it made by \"make dist\" in a tree that has debian/?" + +note "installing pica-pica's build dependencies" +# Reading them straight out of debian/control means the alternative +# "libwebrtc-audio-processing-dev (>= 1.3) | libwebrtc-audio-processing-1-dev" +# is resolved by apt rather than second-guessed here. +apt-get build-dep -qq -y ./ || + die "could not satisfy the build dependencies from debian/control" + +# A "make dist" tarball already carries the generated configure, so there is +# normally nothing to do here. The fallback is for a tarball made some other +# way; autoconf and automake are installed above either way, because if the +# tarball's timestamps make Makefile.am look newer than Makefile.in, automake's +# own rebuild rules fire during the build and want them. +if [ -x configure ]; then + note "the tarball carries a generated configure - not bootstrapping" +else + note "no configure in the tarball - bootstrapping the build system" + autoreconf -i -f +fi + +note "building the packages" +# Binary-only: dpkg-source is not involved, so this does not need an .orig +# tarball alongside a 3.0 (quilt) source format. +dpkg-buildpackage -b -us -uc + +note "collecting artifacts" +mkdir -p "/out/$DISTRO/$ARCH" +cd /build +found=0 +for f in *.deb *.changes *.buildinfo; do + [ -e "$f" ] || continue + cp -v "$f" "/out/$DISTRO/$ARCH/" + case "$f" in *.deb) found=1 ;; esac +done + +[ "$found" -eq 1 ] || die "the build produced no .deb files" + +note "done" diff --git a/debian/changelog b/debian/changelog index 0fd6945..e7328e3 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,30 @@ +pica-pica (0.9.0dev-1) UNRELEASED; urgency=low + + * Audio/video calls: new build dependencies on FFmpeg (libavcodec, + libavdevice, libavformat, libavutil, libswresample, libswscale), + webrtc-audio-processing for acoustic echo cancellation, ALSA, + libpulse for PulseAudio/PipeWire device enumeration, and + libva/EGL/GL/X11 for VAAPI accelerated encoding, decoding and + rendering + * The echo canceller needs webrtc-audio-processing 1.x or newer, for + AEC3. The 0.3 that Ubuntu 24.04 still ships predates it, so the + build dependency is versioned and 24.04 needs a backport + * Build-depend on pkg-config, sqlite3 and zlib1g-dev, which configure + has always required but which were only pulled in indirectly + * Configure VAAPI, its X11 rendering path and PulseAudio device + enumeration explicitly instead of relying on autodetection + * pica-client: recommend va-driver-all, depend on openssl - the + command line tool is used to generate keys and certificates + * Move to debhelper compat 13, declared through debhelper-compat in + Build-Depends rather than debian/compat, and drop the now redundant + autotools-dev build dependency + * pica-node: install the manual pages from the staged build tree + rather than listing them in debian/pica-node.manpages. Compat 13 + makes dh_missing fatal and dh_installman reject a page that is both + staged and listed, and "make install" already stages both pages + + -- Anton Sviridenko <anton@picapica.im> Fri, 28 Aug 2026 12:00:00 +0400 + pica-pica (0.7.1-1) unstable; urgency=low * Release 0.7.1 diff --git a/debian/compat b/debian/compat deleted file mode 100644 index 45a4fb7..0000000 --- a/debian/compat +++ /dev/null @@ -1 +0,0 @@ -8 diff --git a/debian/control b/debian/control index 85021d4..e9ad93a 100644 --- a/debian/control +++ b/debian/control @@ -2,16 +2,40 @@ Source: pica-pica Section: net Priority: optional Maintainer: Anton Sviridenko <anton@picapica.im> -Build-Depends: debhelper (>= 8.0.0), autotools-dev, libssl-dev, qtbase5-dev, libminiupnpc-dev, libevent-dev, libsqlite3-dev +Build-Depends: debhelper-compat (= 13), + pkg-config, + libssl-dev, + zlib1g-dev, + qtbase5-dev, + libminiupnpc-dev, + libevent-dev, + libsqlite3-dev, + sqlite3, + libasound2-dev, + libavcodec-dev, + libavdevice-dev, + libavformat-dev, + libavutil-dev, + libswresample-dev, + libswscale-dev, + libwebrtc-audio-processing-dev (>= 1.3) | libwebrtc-audio-processing-1-dev, + libpulse-dev, + libva-dev, + libegl-dev, + libgl-dev, + libx11-dev Standards-Version: 3.9.2 Homepage: http://picapica.im Package: pica-client Architecture: any -Depends: ${shlibs:Depends}, ${misc:Depends},alsa-utils,libqt5sql5-sqlite +Depends: ${shlibs:Depends}, ${misc:Depends}, alsa-utils, libqt5sql5-sqlite +Recommends: va-driver-all Description: Pica Pica instant messaging client - Client for secure distributed instant messaging system + Client for secure distributed instant messaging system Pica Pica. + . + Supports encrypted text chat, file transfers and audio/video calls. Package: pica-node Architecture: any @@ -20,4 +44,4 @@ Description: node component for Pica Pica IM system Pica Pica node serves Pica Pica distributed IM network. It authenticates users, provides info about other existing nodes and online users, routes encrypted connections between - users. + users. diff --git a/debian/pica-node.install b/debian/pica-node.install index 63b9a80..1a9f5a7 100644 --- a/debian/pica-node.install +++ b/debian/pica-node.install @@ -1,5 +1,6 @@ debian/tmp/etc/pica-node.conf debian/tmp/usr/bin/pica-node debian/tmp/usr/share/pica-node/* +debian/tmp/usr/share/man/* debian/tmp/var/lib/pica-node/* diff --git a/debian/pica-node.manpages b/debian/pica-node.manpages deleted file mode 100644 index 3324407..0000000 --- a/debian/pica-node.manpages +++ /dev/null @@ -1,3 +0,0 @@ -pica-node.8 -pica-node.conf.5 - diff --git a/debian/rules b/debian/rules index a66a4ef..85c4951 100755 --- a/debian/rules +++ b/debian/rules @@ -16,8 +16,13 @@ export DH_VERBOSE=1 # This has to be exported to make some magic below work. export DH_OPTIONS=-v +# VAAPI, its X11 rendering path and PulseAudio device enumeration are +# autodetected by configure, which means a missing build dependency would +# silently produce a package without them. All three are in Build-Depends, +# so ask for them explicitly and let the build fail if they are not there. override_dh_auto_configure: - dh_auto_configure -- --localstatedir=/var/lib + dh_auto_configure -- --localstatedir=/var/lib \ + --enable-vaapi --enable-vaapi-x11 --enable-pulse %: dh $@ diff --git a/doc/pica-client-tutorial/gettingstarted.html b/doc/pica-client-tutorial/gettingstarted.html index 1148fbb..71290ca 100644 --- a/doc/pica-client-tutorial/gettingstarted.html +++ b/doc/pica-client-tutorial/gettingstarted.html @@ -80,6 +80,12 @@ and select "Show Pica Pica ID"), then read them your ID and make them verify it reduces risk of silently replacing ID by some adversary. However, I don't think that government agencies are totally uncapable of imitating voice of selected person in real-time :) </p> +<p> +Upd (2026): real-time voice and face imitation is no longer limited to government agencies, it can now be done with AI models on consumer hardware. +An adversary who controls the call could replace only the moments when the ID is read aloud, leaving the rest of the conversation genuine, so a voice call alone +is no longer reliable verification. Prefer a video call where your contact also points the camera at the screen showing the ID, as this is harder (though not impossible) to fake. +Also compare IDs over several independent channels, such as other messengers, email or a personal website, so that an adversary would have to compromise all of them. +</p> <h3>Sending and receiving files.</h3> <p> You can exchange files using Pica Pica. Needless to say, file transfers are encrypted too. To send file, right-click on contact and diff --git a/doc/proto-doc-audiovideo.txt b/doc/proto-doc-audiovideo.txt new file mode 100644 index 0000000..4ccc667 --- /dev/null +++ b/doc/proto-doc-audiovideo.txt @@ -0,0 +1,38 @@ +Audio and Video Calls. + +Call request (ring) +[0x70 0x70] +[2 pseudo-random octets] + +Call answer (pick up) +[0x71 0x71] +[2 pseudo-random octets] + +Call reject +[0x72 0x72] +[2 pseudo-random octets] + +Call hang up (finished) +[0x73 0x73] +[2 pseudo-random octets] + +Audio stream parameters +[0x74 0x74] +[codec - 20 octet string, left-aligned, padded with zeroes, +"opus", "adpcm_g722", "pcm_alaw" named as in ffmpeg] +[sample rate, uint16_t little-endian] + +Video stream parameters +[0x75 0x75] +[codec - 20 octet string, left-aligned, padded with zeroes, e.g. +"hevc", "h264", "mjpeg", "vp9", named as in ffmpeg] +[width, uint16_t, little-endian] +[height, uint16_t, little-endian] + +Voice (audio) packet +[0x76 0x76][length 2 octets][data] + +Video packet +[0x77 0x77][length 2 octets][data] + + diff --git a/doc/proto-doc-latest.txt b/doc/proto-doc-latest.txt new file mode 100644 index 0000000..ac71d38 --- /dev/null +++ b/doc/proto-doc-latest.txt @@ -0,0 +1,822 @@ +Protocol Specification. + +Terminology. + +Client - a software instance that interacts with human users and lets them send +and receive encrypted messages over Pica Pica. + +Node - a software instance that coordinates the Pica Pica network, maintains a +list of all active nodes and provides connectivity to clients. + +UH - user hash - the SHA224 hash of a user certificate in DER format, 28 +octets. It is used as a user identifier. + +Connections. +There are 5 types of connections between Pica Pica nodes and clients. +Apart from them, a node accepts single UDP datagrams from clients, see the "Get +my UDP address" messages. + +-client to node (c2n) - a control connection from client to node + +-client to client (c2c) - a data connection between clients through a node +acting as a proxy + +-node to node (n2n) - a control & data connection between nodes + +-direct client to client (directc2c) - a direct connection between clients, +using the IPv4/IPv6/DNS address of the accepting client previously +communicated over a c2c connection. + +-media client to client (mediac2c) - a direct connection between clients +carrying the real time media of an audio/video call. It uses UDP transport +and DTLS 1.2 with mutual certificate authentication. + +A mediac2c connection is established only while a call is in progress. It is +made in one of two ways, see "Establishing the media connection" in the Audio +and Video Calls section: + +-over the address of an established directc2c connection, with UDP instead +of TCP: the client that made the outgoing directc2c connection acts as the +DTLS client and connects to the address and port number that connection was +made to, the client that accepted it acts as the DTLS server and listens on +the UDP port with the same number as its directc2c listening port; + +-by UDP hole punching, between the media sockets the two clients opened for +the call, over the addresses exchanged in the 0x70 and 0x71 messages: the +caller acts as the DTLS client, the callee as the DTLS server. No directc2c +connection is needed for this. + +Either way, each side verifies that the certificate presented by the peer +hashes to the UH of the peer of the c2c connection the call belongs to, +exactly as it does on a directc2c connection. + +Media packets are carried over the mediac2c connection whenever it is +established, and over the c2c or directc2c connection otherwise. There is +no message announcing the change: the receiving side accepts media packets +over either transport for the whole duration of a call. + +The first 4 connection types use TCP transport. The first 3 connection types start +with a TLS 1.2 handshake using an anonymous Diffie-Hellman ciphersuite; the +connecting host acts as the TLS client, the accepting host as the TLS server. +After the connection type is identified by the accepting node, the anonymous +TLS session is gracefully closed in the case of c2n and c2c connections. In the +case of c2n the node starts a new TLS session with the client, where the node +acts as the TLS client and the client acts as the TLS server, using the +client's RSA certificate. In the case of a c2c connection the node acts as a +transparent proxy, sending chunks of data received from the first client to the +second one and vice versa. The clients establish a mutually authenticated TLS +session over the proxied connection; the initiator client is the TLS client, +the accepting client has the TLS server role. +An n2n connection continues to operate in the ADH TLS session, as by design +nodes do not store any state that identifies them other than their network +address. + + +Packet Format. + +A Pica Pica protocol message packet contains a header and a tail. + +[Header][Tail] + +The header is a 2-octet sequence that identifies the packet. The first and +second octets are always equal to each other. +The tail is the remaining part of the packet and can be empty. The tail can +have a fixed predefined length or, in the case of a variable length packet, it +begins with a 1- or 2-octet sequence containing an unsigned integer that +defines the length in octets of the remaining part of the tail, not including +the length octets. The length field is stored in little-endian format, least +significant octet first. +The whole packet length is limited to 65536 octets, so the length field value +is within the 0..65532 range. + +Example: + +0x55 0x55 0x03 0x00 0xAA 0xBB 0xCC +[0x55 0x55] - header +[0x03 0x00] - tail length, 2 octets +[0xAA 0xBB 0xCC] - payload, 3 octets + + +C2N Messages. +==================================================== +C2N connection initialization request. +Sent by the client. +ANON TLS + +[0xCA 0xCA][VER_MAJOR][VER_MINOR] + +4 octets + +VER_MAJOR, VER_MINOR - the Pica Pica protocol version supported by the client + +==================================================== +C2N connection initialization success. +Sent by the node. +ANON TLS + +[0x01 0x01]['O']['K'] + +4 octets + +After this message the client and the node initiate an ANON TLS session +shutdown, and after a successful shutdown they initiate a new authenticated TLS +session over the same TCP connection. The client acts as the TLS server and +presents the client certificate; the node acts as the TLS client and does not +present a certificate. +==================================================== +Protocol version mismatch. +Sent by the node. +ANON TLS + +[0x02 0x02][VER_MAJOR][VER_MINOR] + +4 octets + +VER_MAJOR, VER_MINOR - the Pica Pica protocol version supported by the node + +This message is sent if the node's and the client's protocol versions do not +match. After this message is sent and received, the TCP connection is closed by +both hosts. +==================================================== + + The messages below are transmitted over the secure c2n control + connection between a client and a node. + +==================================================== +Request to establish a connection with a peer. +Sent by the client. + +[0x03 0x03][UH of the called user] + +30 octets +==================================================== +Incoming connection permission request. +Sent by the node. + +[0x04 0x04][UH of the initiator] + +30 octets +==================================================== +The user with the given UH was not found (offline, or refused to talk). +Sent by the node. + +[0x05 0x05][UH of the called user] + +30 octets +==================================================== +Connection allowed by the called user. +Sent by the called client. + +[0x06 0x06][UH of the calling user] + +30 octets + +After sending this message, the called client connects to the node's data +exchange port (_DATA_PORT) and sends message 0x20 - new connection +identification - over that connection. +==================================================== +The user with the given UH was found and is ready to talk. +Sent by the node to the calling client. + +[0x07 0x07][UH of the called user] + +30 octets +==================================================== +Connection denied. +Sent by the called client. + +[0x08 0x08][UH of the calling user] + +30 octets +==================================================== +Node list request. +Sent by the client. + +[0x09 0x09][2 pseudo-random octets] + +4 octets +==================================================== +Node list. +Sent by the node. + +[0x0A 0x0A] - see the 0xA4 message format +==================================================== +Multilogin notification. +Sent by a client that has logged in. Relayed to other nodes. +Delivered to the existing connected client instance. + +[0x0E 0x0E][length 2 octets][timestamp][node address][signature from UH, timestamp, node +address] + +timestamp - the time when the client logged in, a 64-bit Unix timestamp in the +UTC timezone + +node address - one of the 0xA0, 0xA1, 0xA2 messages; the announced address of +the node the sending client is connected to. + +signature - a digital signature using the SHA224 hash and the private RSA key +of the sending client. The signature is calculated from the sender's +concatenated UH, timestamp and node address = Sign(UH|timestamp|node address) + +==================================================== +Get my TCP address. + +Sent by a client. Requests the node to respond with the client +address and TCP port as seen by the node. The response should +be one packet of the type A0 or A1 corresponding to protocol used for this +TCP connection - IPv4 or IPv6 + +[0x0F 0x0F][2 pseudo-random octets] + +4 octets +==================================================== +My TCP address. +Sent by the node in reply to 0x0F. + +[0xA0 0xA0][IP address - 4 octets, network byte order][port number - 2 octets, network byte order] + +8 octets + +or + +[0xA1 0xA1][IPv6 address - 16 octets, network byte order][port number - 2 octets, network byte order] + +20 octets + +A client must ignore this message unless it is waiting for it. +==================================================== +Get my UDP address. +Sent by a client. + +[0x10 0x10][2 pseudo-random octets] + +4 octets + +Requests a token that lets the client learn the address and port its UDP +datagrams arrive at the node from, i.e. what the NAT in front of the client +maps one of its UDP sockets to. The exchange is: + + c2n client -> node 0x10 request + c2n node -> client 0x11 token + UDP client -> node 0x10 the token, from the socket in question + c2n node -> client 0x12 source address and port of that datagram + +A node serves only a limited number of these requests in a row from one +client, and may not serve them at all (e.g. it has no UDP port open); a request +that is not served is not answered. The client gives up by timeout. +==================================================== +UDP address token. +Sent by the node in reply to 0x10. + +[0x11 0x11][token, 16 octets] + +18 octets + +token - random octets from a cryptographically secure generator, chosen by the +node. It is valid for a short time (10 seconds) and for one datagram. A client +has at most one valid token: a new 0x10 request invalidates the token issued +for the previous one. +==================================================== +UDP address probe. +Sent by a client to the node as a UDP datagram, not over a connection. + +[0x10 0x10][token, 16 octets] + +18 octets, the whole datagram + +Sent to the UDP port with the same number as the TCP port the c2n connection +was made to, from the socket whose external address the client wants to learn. +Datagrams can be lost, so the client sends it a few times, about a second +apart, until 0x12 arrives. + +The node never answers over UDP, whatever it receives. A datagram that is not +exactly 18 octets long, or does not carry a currently valid token, is silently +dropped. When a valid token arrives, the node invalidates it and sends 0x12 +over the c2n connection the token was issued on. Copies of the datagram that +arrive afterwards are therefore dropped as well. +==================================================== +My UDP address. +Sent by the node over the c2n connection. + +[0x12 0x12][length, 1 octet][address] + +address - the source address and port of the datagram that carried the token, +in network byte order: +[0xA0][IP address - 4 octets][port number - 2 octets], length 7, or +[0xA1][IPv6 address - 16 octets][port number - 2 octets], length 19. + +A client must ignore this message unless it is waiting for it. + +Security considerations. +The token only ties a datagram to an authenticated c2n connection. The source +address the node reports cannot be authenticated - it is not known to the +client, and is rewritten on the way by design - so somebody able to observe the +datagram can send a copy of it from another address, and have that address +reported if the copy arrives first. The reported address must therefore be +treated only as a place where the client might be reachable, never as proof of +who is reachable there: a connection made to it has to authenticate the peer +on its own, as directc2c and mediac2c connections do. +==================================================== + + The message below is transmitted over the connection between a node + and a client which is used for data transfer. + +==================================================== +New connection identification. +Sent by the client. + +[0x20 0x20][UH of the calling user][UH of the called user] + +58 octets + +Upon receiving this message the node checks the UHs. If they do not match, the +connection is closed. After the check the node switches into data relaying mode +between the two clients. The calling client initiates TLS connection +establishment. +==================================================== + + +C2C Messages. +The messaging protocol between clients through node(s). +==================================================== +C2C connection initialization request. +Sent by a client to another client. + +[0xCC 0xCC][VER_MAJOR][VER_MINOR] + +4 octets + +VER_MAJOR, VER_MINOR - the c2c protocol version supported by the client + +Possible responses - 0x01, 0x02 +==================================================== +Client direct address list. + +[0x0B 0x0B] - see the 0xA4 message format +0xA0, 0xA1, 0xA2 - the same as in n2n messages + +If a client is configured to accept incoming direct client to client +connections (bypassing the node), it can send a list of its own addresses. +The list can contain any number of addresses, e.g. one for every network +interface of the client and the external address of a port forwarded to it. +Local network addresses (if there are any) from the 192.168.0.0/16, +172.16.0.0/12 and 10.0.0.0/8 subnets must be placed first in the list, so that +clients residing in the same local network are able to connect directly. Public +internet addresses follow them. +If the client is behind NAT and forwards an open port to its local address, the +external port number must be specified in the address. +The connecting client tries the addresses one at a time, in the order of the +list. It skips the elements of a type it does not connect to (e.g. 0xA1 without +IPv6 connectivity), stepping over them by their size as given in the 0xA4 +description; such elements are not an error. +A private address (the subnets above, and 100.64.0.0/10) is only tried if it +is on the network of a private address of one of the connecting client's own +network interfaces, as given by that interface's netmask; any other private +address belongs to some other network and is skipped without a connection +attempt. Since such an address is on the local network, the TCP connection to +it is given up after 200 milliseconds, while the TLS handshake that follows +has as long as for any other address. +Having received the announcement, the other client can create a connection to +that address and close the connection through the node. +The announced port numbers are used both for TCP directc2c connections and for +UDP mediac2c connections, so a client behind NAT has to forward the port for +both protocols. +==================================================== +Direct connection attempts failed. + +[0x0C 0x0C][2 pseudo-random octets] + +4 octets + +Sent by the initiator if it has received a direct address list from the called +client and all connection attempts to the received addresses were unsuccessful. +After receiving this message, the called client starts connection attempts to +the direct addresses of the initiator, if an address list was received from the +initiator and direct connections are allowed by the called client's settings. +==================================================== +Switch to direct connection. + +[0x0D 0x0D][2 pseudo-random octets] + +4 octets + +Sent by each side over the connection through the node after a successful TLS +handshake on the direct connection. After sending this message, all subsequent +messages are sent over the direct connection; the receiver of the message +correspondingly expects subsequent messages over the direct connection. +==================================================== +Message - UTF-8 encoded text. + +[0x30 0x30][length 2 octets][UTF-8 encoded message] +==================================================== +Delivery report for the previous message. + +[0x40 0x40][2 pseudo-random octets] + +4 octets +==================================================== +File sending request. + +[0x50 0x50][length 2 octets, 9..263][file size, 8 octets][file name in UTF-8, 1 - 255 octets] +==================================================== +File accepted. + +[0x51 0x51][2 pseudo-random octets] + +4 octets + +After receiving this message, the sender starts sending the file. +==================================================== +File rejected. + +[0x52 0x52][2 pseudo-random octets] + +4 octets +==================================================== +File fragment. + +[0x53 0x53][fragment length, 2 octets, 0 - 65532][file fragment] +==================================================== +File transfer control. + +[0x54 0x54][sender command][receiver command] + +4 octets + +Commands: +00 - void command (no action) +01 - pause +02 - resume +03 - cancel +04 - cancel because of a file read/write error +==================================================== + + +Audio and Video Calls. +The call control messages (0x70 - 0x75) are sent between clients over a c2c or +directc2c connection. +The media packets (0x76, 0x77) are sent over a mediac2c connection when one is +established, and over the c2c or directc2c connection otherwise. Over a +mediac2c connection every datagram contains exactly one message, and messages +can be lost, reordered or duplicated; the receiving side must be prepared for +that and must not treat a malformed or unexpected packet as a protocol error +breaking the connection. In particular, a media packet can arrive before the +0x74 or 0x75 message describing the stream it belongs to, because those travel +over a different connection; such a packet is discarded. +The media connection probe is not a message of any connection: it is a UDP +datagram sent while the media connection is being established, see below. +==================================================== +Call request (ring) + +[0x70 0x70][length, 2 octets][probe token, 8 octets][address list] + +length - covers everything following it: 8 + the size of the address list. + +probe token - random octets from a cryptographically secure generator, chosen +anew for every call. The peer puts it into the media connection probes it sends +to the sender of this message. + +address list - the addresses where the sender's media socket for this call may +be reachable, as elements of the 0xA4 format, of types 0xA0 and 0xA1 only: +first the socket's port number with each of the sender's own interface +addresses, then the address and port the node reported for that socket in a +0x12 message, if the sender got one. The list is empty if the sender does not +take part in hole punching, e.g. because direct connections are disabled in its +settings. + +Before sending this message the caller opens its media socket and asks the node +for the socket's address (0x10 - 0x12), waiting for the answer at most 2 +seconds; when it does not come in time, the message is sent without that +address. + +The receiver skips elements of other types and uses at most the first 8 +addresses of the list. +==================================================== +Call answer (pick up) + +[0x71 0x71][length, 2 octets][probe token, 8 octets][address list] + +The same format and meaning as in 0x70, for the callee's media socket. + +The callee opens its media socket and asks the node for its address when the +0x70 message arrives, while the call is ringing, so that sending 0x71 is not +delayed by it when the user answers; if the address has still not arrived by +then, 0x71 waits for it at most 2 seconds. The callee's addresses are revealed +only by this message, i.e. only if the call is answered. The list can be empty +when the caller's list was. +==================================================== +Call reject + +[0x72 0x72] +[2 pseudo-random octets] + +4 octets +==================================================== +Call hang up (finished) + +[0x73 0x73] +[2 pseudo-random octets] + +4 octets +==================================================== +Audio stream parameters + +[0x74 0x74] +[codec - a 20 octet string, left-aligned, padded with zeroes; +"opus", "adpcm_g722", "pcm_alaw", named as in ffmpeg] +[sample rate, uint16_t, little-endian] + +24 octets +==================================================== +Video stream parameters + +[0x75 0x75] +[codec - a 20 octet string, left-aligned, padded with zeroes, e.g. +"hevc", "h264", "mjpeg", "vp9", named as in ffmpeg] +[width, uint16_t, little-endian] +[height, uint16_t, little-endian] + +26 octets +==================================================== +Voice (audio) packet + +[0x76 0x76][length 2 octets][sequence number, uint16_t, little-endian][timestamp, uint32_t, little-endian, milliseconds since the start of the call][data] + +length - covers everything following it: the 2-octet sequence number, the +4-octet timestamp and the data, i.e. data length + 6. + +sequence number - incremented by one for every audio packet sent over this +call, wraps around at 65536. It lets the receiving side detect encoder-side +gaps (e.g. a dropped capture buffer) and, over a mediac2c connection, put +the received packets back in order, detect losses and discard duplicates. + +timestamp - the capture timestamp of the packet's first sample, in +milliseconds, relative to the moment the call became active (the 0x71 +message was processed). Used by the receiver for playout-buffer timing and +audio/video synchronization. +==================================================== +Video packet + +[0x77 0x77][length 2 octets][sequence number, uint16_t, little-endian][timestamp, uint32_t, little-endian, milliseconds since the start of the call][data] + +length - covers everything following it: the 2-octet sequence number, the +4-octet timestamp and the data, i.e. data length + 6. + +sequence number - the most significant bit (0x8000) is the last fragment +marker, see the fragmentation description below. The remaining 15 bits are a +counter incremented by one for every video packet sent over this call, +wrapping around at 32768. The counter serves the same purpose as in the 0x76 +message: gap detection and future unordered/lossy transport support. + +timestamp - the capture timestamp of the encoded video frame, in +milliseconds, relative to the moment the call became active. Used by the +receiver for playout timing and audio/video synchronization. All fragments +of one encoded frame carry the same timestamp, see below. + +Fragmentation. + +The length field limits the data carried by a single 0x77 message to 65526 +octets, while an encoded video frame - an intra-coded (key) frame in +particular - can be larger than that. Such a frame is split into several +consecutive 0x77 messages. + +All fragments of one encoded frame carry the same timestamp; the 15-bit +counter part of the sequence number is incremented for every fragment, as it +is for every other video packet. The last fragment of a frame has the last +fragment marker bit (0x8000) set in its sequence number; every preceding +fragment of the same frame has that bit cleared. A frame that fits into a +single message is sent as one message with the marker bit set. + +Over a c2c or directc2c connection a single 0x77 message can carry up to +65526 octets of data. Over a mediac2c connection the whole message has to +fit into one datagram, so the amount of data a fragment carries is limited +by the path MTU instead, and an encoded frame is normally split into many +more fragments. + +The receiving side concatenates the data of the received fragments and +passes the result to the video decoder once a message with the marker bit +set has been received. + +Since fragments can be lost over a mediac2c connection, the receiving side +must also check that the fragments it concatenates are consecutive: a +fragment may only start a new frame if the previously accepted message had +the last fragment marker bit set and the counter part of the sequence +number of the new one follows it without a gap. If a gap is detected, the +partially assembled frame is discarded and the receiving side skips +fragments until a message with the last fragment marker bit set is +received, resuming assembly with the message following it. Without this +rule, losing the first fragment of a frame would make the receiving side +treat the second one as the beginning of a frame and pass a truncated frame +to the decoder. +==================================================== +Establishing the media connection. + +When a call becomes active - for the callee when it sends 0x71, for the +caller when 0x71 arrives - each side makes up to two attempts to establish a +mediac2c connection, one after another. Until one succeeds, and for the rest +of the call if neither does, the media packets travel over the c2c or +directc2c connection. Once established, the mediac2c connection carries the +media until the call ends: lost datagrams, a time without any arriving, or +errors the system reports for datagrams sent (e.g. ICMP port unreachable) do +not end it. Only the DTLS session ending - a close_notify or a fatal alert +from the peer - does. + +Attempt 1, over the directc2c address. Made only if the c2c connection the +call belongs to has an established directc2c connection, as described in the +Connections section. Given up when the DTLS handshake fails, or when the +connection is not established 5 seconds after the call became active. + +Attempt 2, by UDP hole punching. Made when attempt 1 is not made or is given +up, and only if both the 0x70 and the 0x71 message carried a non-empty address +list. Each side uses its media socket for the call - the one its address list +was made for - and the caller acts as the DTLS client. + +1. Each side sends a media connection probe to every address of the peer's +list, repeating every 200 milliseconds. A private address in the list is +handled as in the 0x0B message: it is skipped unless it is on the network of +a private address of one of the side's own network interfaces. One that is +not skipped is local, and is sent probes only during the first 200 +milliseconds, every 50 milliseconds. A probe that arrives before the +receiving side has started sending its own waits on that side's media +socket, so a side starting later than the other still selects the address in +step 2 and answers from it. +2. When a side receives a probe carrying its own probe token, it selects the +address the probe came from. That address need not be in the peer's list: a +NAT can map the peer's socket to another port for this destination than for +the node. From then on the side sends probes to the selected address only and +accepts datagrams only from it. +3. The caller starts the DTLS handshake as soon as it has selected an address, +and keeps sending probes to it until the first datagram of the handshake +arrives from the callee. The callee keeps sending probes until the first +datagram of the handshake arrives from the caller. DTLS datagrams that arrive +before the receiving side has selected an address are discarded; the DTLS +retransmission takes care of them. +4. The attempt is given up if no address has been selected 10 seconds after +the side started sending probes, or if the handshake fails or is not complete +10 seconds after that. + +A side starting attempt 2 late - having given up attempt 1, or having become +active later than the peer - is still within the 10 seconds the peer keeps +sending probes for. + +Security considerations. +The probe token, sent over the authenticated c2c connection, keeps a host +that does not see the probes from steering the choice of the address. One that +does see them can send copies from another address, the same as with the 0x10 +datagram; the DTLS handshake authenticates the peer regardless, and a failed +handshake only leaves the media on the c2c connection. +The addresses in a peer's list are not checked, so a peer can make a client +send probes to any host. This is bounded by the limits above: 8 addresses, +5 probes a second each, 10 seconds - at most 400 datagrams of 10 octets per +call. +==================================================== +Media connection probe. +Sent as a UDP datagram from the media socket of a call, outside of DTLS. + +[0x78 0x78][probe token, 8 octets] + +10 octets, the whole datagram + +probe token - the token the receiver of the probe sent in its 0x70 or 0x71 +message. + +A probe carries nothing but the token and is discarded after it has been +looked at. One that is exactly 10 octets long, carries the receiver's token +and arrives before the receiver has selected an address makes the receiver +select the address it came from, see step 2 above; all others have no effect. +A DTLS record never starts with the octet 0x78, so probes are told apart from +DTLS records by their first octet at any stage of the connection. +==================================================== + + +Ping. +Can be sent by either side, both over the c2n control connection and over a +connection between clients. +Over a mediac2c connection it is also used as a keepalive, to hold open the +NAT and firewall state the connection depends on while neither side is +sending media, and to detect that the connection has stopped working. +==================================================== +Ping request. + +[0x68 0x68][2 pseudo-random octets] + +4 octets +==================================================== +Ping reply. + +[0x69 0x69][2 pseudo-random octets] + +4 octets +==================================================== + + +N2N Messages. +The inter-node interaction protocol. +==================================================== +Node connection request. +Sent by one node to another. + +[0xCB 0xCB][VER_MAJOR][VER_MINOR] + +4 octets + +VER_MAJOR, VER_MINOR - the Pica Pica protocol version supported by the node + +Possible responses - 0x01, 0x02 - the same as for a client +==================================================== +New node announcement - IPv4 address. + +[0xA0 0xA0][IP address of the new node - 4 octets, network byte order][port number - 2 octets, network byte order] + +8 octets +==================================================== +New node announcement - IPv6 address. + +[0xA1 0xA1][IPv6 address of the new node - 16 octets, network byte order][port number - 2 octets, network byte order] + +20 octets +==================================================== +New node announcement - DNS address. + +[0xA2 0xA2][address length - 1 octet][DNS address of the new node][port number - 2 octets, network byte order] +==================================================== + +The address declared in the announcement must match the address from which the +connection was made. The node that receives the announcement must verify this. + +==================================================== +Node list. + +[0xA4 0xA4][address list size in octets, 2 octets - 0..65532][address list] + +The address list is a sequence of elements of 3 possible types +[0xA0][IP address - 4 octets][port number - 2 octets] - 7 octets +[0xA1][IPv6 address][port number - 2 octets] - 19 octets +[0xA2][address length - 1 octet][DNS address][port number - 2 octets] - 4 ... 259 octets + +The sending node's own address (in the given address space) always goes first +in the list. +A message can contain only a part of the node list instead of the whole list; +in that case the whole list is sent in parts. Addresses and port numbers are in +"network" byte order. +The whole packet size does not exceed 64kb. +==================================================== +Node list request. + +[0x90 0x90][2 pseudo-random octets] + +4 octets +==================================================== +Client search. +Sent to all nodes. The receiving node replies to this message only if the +requested UH is found among its local clients or in its cache. + +[0xA5 0xA5][UH of the called user] + +30 octets +==================================================== +Client search result - client found. +Sent by a node that received 0xA5, if the requested UH is found among its local +connected clients. + +[0xA8 0xA8][UH of the called user] + +30 octets +==================================================== +Client search result - client found in cache. +Sent by a node that received 0xA5, if the requested UH is found in its cache +(i.e. there is information that the client being searched for is connected to +another node). + +[0xA9 0xA9][size, 2 octets, 32..287][UH of the called user][address of the node where the requested UH may be located, in A0|A1|A2 format, see the 0xA4 description] +==================================================== +Request to allow a connection with a client of the receiving node. + +[0xAA 0xAA][UH of the initiator][UH of the called user] + +58 octets +==================================================== +Connection allowed by the called user. +Sent after the called local client has replied with a 0x06 message and created +a new connection for message exchange. + +[0xAB 0xAB][UH of the initiator][UH of the called user] + +58 octets +==================================================== +Client not found (offline, or refused to talk). + +[0xB8 0xB8][UH of the initiator][UH of the called user] + +58 octets + +Sent by a node in reply to a 0xD0 message addressed to this UH, if that user +has already disconnected or is not in the list of local clients, or in reply to +0xAA, if the called client denied the connection. +==================================================== +Message transmitted between nodes on behalf of clients. + +[0xD0 0xD0][embedded message length in octets, 56..65532, 2 octets little-endian][UH of the local sending user][UH of the user on another node][embedded data] + +embedded data - data transmitted over the CLIENT-CLIENT connection +==================================================== diff --git a/gentoo/pica-client-0.6.ebuild b/gentoo/pica-client-0.6.ebuild deleted file mode 100644 index 36b263b..0000000 --- a/gentoo/pica-client-0.6.ebuild +++ /dev/null @@ -1,54 +0,0 @@ - # Copyright 1999-2012 Gentoo Foundation -# Distributed under the terms of the GNU General Public License v2 -# $Header: $ - -EAPI=4 - -inherit eutils - -DESCRIPTION="Pica Pica Messenger" -HOMEPAGE="http://picapica.im/" -SRC_URI="http://picapica.im/pica-pica-${PV}.tar.gz" - -LICENSE="GPL-3+" -SLOT="0" - -KEYWORDS="~amd64 ~x86" -IUSE="" - -DEPEND=">=dev-libs/openssl-0.9.8 - >dev-qt/qtcore-4.0.0 - >dev-qt/qtgui-4.0.0 - >dev-qt/qtsql-4.0.0[sqlite] - virtual/pkgconfig - x11-misc/xdg-utils" - -RDEPEND="${DEPEND}" - -S="${WORKDIR}/pica-pica-${PV}" - -src_configure() { - econf --disable-node --disable-menuitem -} - -src_install() { - emake DESTDIR="${D}" install || die "Install failed" - #dodoc README || die -} - -pkg_postinst() { - xdg-icon-resource install --size 32 "${S}/pica-client/picapica-icon-sit.png" pica-client - xdg-icon-resource install --size 22 "${S}/pica-client/picapica-icon-sit.png" pica-client - xdg-icon-resource install --size 64 "${S}/pica-client/picapica-icon-sit.png" pica-client - - xdg-desktop-menu install "${S}/pica-client/pica-client.desktop" -} - -pkg_postrm() { - xdg-icon-resource uninstall --size 32 pica-client - xdg-icon-resource uninstall --size 22 pica-client - xdg-icon-resource uninstall --size 64 pica-client - - xdg-desktop-menu uninstall pica-client.desktop -} - diff --git a/gentoo/pica-node-0.6.ebuild b/gentoo/pica-node-0.6.ebuild deleted file mode 100644 index 35ac482..0000000 --- a/gentoo/pica-node-0.6.ebuild +++ /dev/null @@ -1,49 +0,0 @@ - # Copyright 1999-2012 Gentoo Foundation -# Distributed under the terms of the GNU General Public License v2 -# $Header: $ - -EAPI=4 - -inherit eutils - -DESCRIPTION="Node for Pica Pica distributed decentralized IM system" -HOMEPAGE="http://picapica.im/" -SRC_URI="http://picapica.im/pica-pica-${PV}.tar.gz" - -LICENSE="GPL-3+" -SLOT="0" - -KEYWORDS="~amd64 ~x86" -IUSE="" - -DEPEND=">=dev-libs/openssl-0.9.8 - >=dev-db/sqlite-3.7.0" - -RDEPEND="${DEPEND}" - -S="${WORKDIR}/pica-pica-${PV}" - -src_configure() { - # We have optional perl, python and ruby support - econf --disable-client --localstatedir=/var -} - -src_install() { - emake DESTDIR="${D}" install || die "Install failed" - newinitd "${S}/gentoo/gentoo_initscript" ${PN} - #dodoc README || die -} - -pkg_preinst() { -# enewgroup pica-node - enewuser pica-node - fowners -R pica-node:pica-node "/var/lib/pica-node" - - dodir "/var/log/pica-node" - fowners -R pica-node:pica-node "/var/log/pica-node" -} - -pkg_postinst() { - - elog "Set announced_addr value to your IP address in config file before running pica-node" -} diff --git a/gentoo/pica-pica-9999.ebuild b/gentoo/pica-pica-9999.ebuild new file mode 100755 index 0000000..b78a3d6 --- /dev/null +++ b/gentoo/pica-pica-9999.ebuild @@ -0,0 +1,137 @@ +# Copyright 1999-2012 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 +# $Header: $ + +EAPI=8 + +inherit autotools desktop git-r3 + +if [[ ${PV} == "9999" ]] ; then + EGIT_REPO_URI="https://github.com/antonsviridenko/pica-pica.git" + SRC_URI="" +else + SRC_URI="http://picapica.im/pica-pica-${PV}.tar.gz" + KEYWORDS="~amd64 ~x86" +fi + +DESCRIPTION="Pica Pica Messenger and Node" +HOMEPAGE="http://picapica.im/" + +LICENSE="GPL-3" +SLOT="0" + +IUSE="+client node qt4 +qt5 upnp +vaapi pulseaudio X" + +DEPEND=">=dev-libs/openssl-1.0.2r + upnp? ( >=net-libs/miniupnpc-2.0 ) + !net-im/pica-node + !net-im/pica-client + + node? ( + >=dev-db/sqlite-3.7.0 + >=dev-libs/libevent-2.1.6 + ) + + client? ( + qt4? ( + >dev-qt/qtgui-4.0.0 + >dev-qt/qtcore-4.0.0 + >dev-qt/qtsql-4.0.0[sqlite] + ) + qt5? ( + >dev-qt/qtcore-5.10.0 + >dev-qt/qtwidgets-5.10.0 + >dev-qt/qtgui-5.10.0 + >dev-qt/qtnetwork-5.10.0 + >dev-qt/qtsql-5.10.0[sqlite] + ) + virtual/pkgconfig + x11-misc/xdg-utils + media-sound/alsa-utils + dev-qt/qtchooser + + media-libs/alsa-lib + || ( + media-libs/webrtc-audio-processing:1 + media-libs/webrtc-audio-processing:2 + ) + + # audio and video calls: FFmpeg does the capturing, encoding, + # decoding and playback. v4l for cameras, alsa for the ALSA + # driver, opus for the audio codec and x264 for the video one - + # there is no native H.264 encoder to fall back on, so without + # it software video encoding is not possible at all. + >=media-video/ffmpeg-4.2:=[alsa,opus,v4l,x264,pulseaudio?,vaapi?] + + pulseaudio? ( media-libs/libpulse ) + + vaapi? ( + media-libs/libva:=[drm(+),X?] + media-libs/libglvnd[X?] + X? ( x11-libs/libX11 ) + ) + )" + +RDEPEND="${DEPEND} + node? ( + acct-user/pica-node + acct-group/pica-node + )" + +S="${WORKDIR}/pica-pica-${PV}" + +if [[ ${PV} == "9999" ]] ; then +src_prepare() { + eapply_user + eautoreconf -i +} +fi + +src_configure() { + qtflags="--with-qt=qt5" + if use qt5; then + qtflags=$(use_with qt5 qt qt5) + elif use qt4; then + qtflags=$(use_with qt4 qt qt4) + fi + + # VAAPI and the PulseAudio device listing are autodetected by + # configure, so they have to be asked for explicitly - otherwise the + # USE flags would only say what may be linked, not what is. The X11 + # rendering path is part of VAAPI and configure refuses it on its own. + local vaapiflags="--disable-vaapi --disable-vaapi-x11" + if use vaapi; then + vaapiflags="--enable-vaapi $(use_enable X vaapi-x11)" + fi + + econf $(use_with upnp miniupnpc) $(use_enable client) $(use_enable node) $qtflags \ + ${vaapiflags} $(use_enable pulseaudio pulse) +} + +src_install() { + emake DESTDIR="${D}" install || die "Install failed" + use node && newinitd "${FILESDIR}/pica-node-initd" pica-node + use node && newconfd "${FILESDIR}/pica-node-confd" pica-node + domenu "${S}/pica-client/pica-client.desktop" + newicon -s 16 "${S}/pica-client/icons/icon_16x16.png" pica-client.png + newicon -s 32 "${S}/pica-client/icons/icon_32x32.png" pica-client.png + newicon -s 48 "${S}/pica-client/icons/icon_48x48.png" pica-client.png + newicon -s 256 "${S}/pica-client/picapica-icon-fly.png" pica-client.png +} + +pkg_preinst() { + + if use node; then + fowners -R pica-node:pica-node "/var/lib/pica-node" + + dodir "/var/log/pica-node" + fowners -R pica-node:pica-node "/var/log/pica-node" + fi +} + +pkg_postinst() { + + use node && elog "Set the announced_addr value to your IP address in a config file before running the pica-node" +} + + diff --git a/pica-client/accounts.h b/pica-client/accounts.h index 36d155f..de718f0 100644 --- a/pica-client/accounts.h +++ b/pica-client/accounts.h @@ -21,6 +21,7 @@ #include <QtSql> #include <QSqlDatabase> #include <QStringList> +#include <QMetaType> class Accounts { @@ -55,4 +56,6 @@ private: }; +Q_DECLARE_METATYPE(Accounts::AccountRecord) + #endif // ACCOUNTS_H diff --git a/pica-client/accountswindow.cpp b/pica-client/accountswindow.cpp index bf8dc76..aeae51f 100644 --- a/pica-client/accountswindow.cpp +++ b/pica-client/accountswindow.cpp @@ -23,7 +23,7 @@ #include "dialogs/showpicaiddialog.h" #include "../PICA_client.h" #include "skynet.h" -#include "openssltool.h" +#include "openssllib.h" #include <QMessageBox> #include <QApplication> #include <cstring> @@ -146,7 +146,7 @@ void AccountsWindow::CreateAccount(QString CertFilename, QString PkeyFilename, b return; } - QString name = OpenSSLTool::NameFromCertFile(CertFilename); + QString name = OpenSSLLib::NameFromCertFile(CertFilename); Accounts::AccountRecord rec; QString certfilename, pkeyfilename; diff --git a/pica-client/audiodevice.cpp b/pica-client/audiodevice.cpp new file mode 100644 index 0000000..19ce04e --- /dev/null +++ b/pica-client/audiodevice.cpp @@ -0,0 +1,1634 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#include "audiodevice.h" +#include "callsettings.h" +#include "nativeaudio.h" + +#include <QDebug> +#include <QMutexLocker> +#include <QVector> +#include <cmath> +#include <cstring> + +#ifdef Q_OS_LINUX +#include <alsa/asoundlib.h> +#endif + +#ifdef HAVE_LIBPULSE +#include <pulse/pulseaudio.h> +#endif + +// FFmpeg headers +extern "C" { +#include <libavformat/avformat.h> +#include <libavdevice/avdevice.h> +#include <libavcodec/avcodec.h> +#include <libavutil/opt.h> +#include <libavutil/channel_layout.h> +#include <libavutil/samplefmt.h> +#include <libavutil/audio_fifo.h> +#include <libavutil/frame.h> +#include <libavutil/mem.h> +#include <libavutil/error.h> +#include <libswresample/swresample.h> +} + +// See toneplayer.cpp for the rationale - FFmpeg 5.1 (libavutil 57.24.100) +// replaced the channels/channel_layout fields with the AVChannelLayout +// ch_layout API; the legacy branch keeps us building on FFmpeg 4.x. +#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 24, 100) +# define AD_HAVE_CH_LAYOUT 1 +#else +# define AD_HAVE_CH_LAYOUT 0 +#endif + +// FFmpeg 7.1 (libavcodec 61.13.100) added avcodec_get_supported_config() and +// deprecated the AVCodec fields listing what a codec supports; FFmpeg 9.0 +// removed those fields. See chooseEncoderSampleFmt(). +#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(61, 13, 100) +# define AD_HAVE_SUPPORTED_CONFIG 1 +#else +# define AD_HAVE_SUPPORTED_CONFIG 0 +#endif + +// Every call this codebase currently negotiates is mono - matches +// TonePlayer's design and keeps the resampling/framing code below simple. +static const int kChannels = 1; + +// Bitrate an encoder runs at when configureCapture() was given none, and the +// one the "Audio Bitrate" setting defaults to: a reasonable rate for a single +// speech channel of Opus. +static const int64_t kOpusBitrate = kDefaultAudioBitrateKbps * 1000; + +// The FFmpeg driver name used on Linux. Kept in a process wide variable +// rather than read from the settings database on demand, because the audio +// loops run on their own threads and QSqlDatabase connections belong to the +// thread that opened them. SetLinuxDriverName() is called from the GUI +// thread; see main.cpp and SettingsDialog::storeSettings(). +static QMutex s_driverMutex; +static QString s_linuxDriver = QStringLiteral("alsa"); + +// The configured echo cancellation, published to the audio threads the same +// way and for the same reason. The initial value only stands until main() +// has read the setting, and is the one that cannot make things worse if it +// somehow does not. +static QMutex s_echoCancellationMutex; +static EchoCancellationMode s_echoCancellation = EchoCancellationNone; + +static QString ff_errstr(int err) +{ + char buf[256] = {0}; + av_strerror(err, buf, sizeof(buf)); + return QString::fromLocal8Bit(buf); +} + +static void applyMonoLayout(AVCodecContext *ctx) +{ +#if AD_HAVE_CH_LAYOUT + av_channel_layout_default(&ctx->ch_layout, kChannels); +#else + ctx->channels = kChannels; + ctx->channel_layout = av_get_default_channel_layout(kChannels); +#endif +} + +static void applyMonoLayout(AVFrame *frame) +{ +#if AD_HAVE_CH_LAYOUT + av_channel_layout_default(&frame->ch_layout, kChannels); +#else + frame->channels = kChannels; + frame->channel_layout = av_get_default_channel_layout(kChannels); +#endif +} + +static SwrContext *makeMonoResampler(AVSampleFormat inFmt, int inRate, AVSampleFormat outFmt, int outRate) +{ + SwrContext *swr = nullptr; + +#if AD_HAVE_CH_LAYOUT + AVChannelLayout layout; + av_channel_layout_default(&layout, kChannels); + int ret = swr_alloc_set_opts2(&swr, &layout, outFmt, outRate, &layout, inFmt, inRate, 0, nullptr); + av_channel_layout_uninit(&layout); + if (ret < 0) + return nullptr; +#else + swr = swr_alloc_set_opts(nullptr, AV_CH_LAYOUT_MONO, outFmt, outRate, AV_CH_LAYOUT_MONO, inFmt, inRate, 0, nullptr); + if (!swr) + return nullptr; +#endif + + if (swr_init(swr) < 0) + { + swr_free(&swr); + return nullptr; + } + + return swr; +} + +// The AVCodecID behind one of the names the 0x74 message carries. +// +// Those are FFmpeg *codec* names (see doc/proto-doc-latest.txt), which are not +// always the name of an encoder or decoder for them: FFmpeg names each +// implementation after itself, so the G.722 codec is "adpcm_g722" while the +// only encoder and decoder for it are both called "g722". Going through the +// codec descriptor rather than through the implementation name is what makes +// the protocol's names work for all three. +static AVCodecID callAudioCodecId(const QString &codec) +{ + const AVCodecDescriptor *desc = avcodec_descriptor_get_by_name(codec.toLatin1().constData()); + + if (!desc || desc->type != AVMEDIA_TYPE_AUDIO) + return AV_CODEC_ID_NONE; + + return desc->id; +} + +// The encoder for one of the call audio codecs. Only "opus" needs a word of +// its own, because FFmpeg has two Opus encoders and libopus is both the better +// one and the only one offering the interleaved 16 bit format the echo +// canceller wants. +static const AVCodec *findCallAudioEncoder(const QString &codec) +{ + if (codec == QLatin1String("opus")) + { + const AVCodec *enc = avcodec_find_encoder_by_name("libopus"); + + if (enc) + return enc; + } + + const AVCodecID id = callAudioCodecId(codec); + + // AV_CODEC_ID_NONE covers a name that is not a codec at all, and one that + // names a video codec - which would otherwise be opened as one here and + // produce something no audio decoder on the far side can read. + return id == AV_CODEC_ID_NONE ? nullptr : avcodec_find_encoder(id); +} + +// The decoder counterpart, for whatever codec the peer announced. Resolved by +// name for the same reason VideoDevice::Play() does it: the 0x74 message names +// the codec the way FFmpeg does, so a peer that picks a different one of the +// three needs no codec list kept in step here. +static const AVCodec *findCallAudioDecoder(const QString &codec) +{ + if (codec == QLatin1String("opus")) + { + const AVCodec *dec = avcodec_find_decoder_by_name("libopus"); + + if (dec) + return dec; + } + + const AVCodecID id = callAudioCodecId(codec); + + return id == AV_CODEC_ID_NONE ? nullptr : avcodec_find_decoder(id); +} + +// Which sample format to run the Opus encoder in. Interleaved 16 bit is +// preferred over whatever the encoder lists first, because that is the format +// the echo canceller works in - taking it means the microphone samples can go +// through the canceller in place on their way to the encoder rather than +// being converted twice around it. libopus offers it; the native "opus" +// encoder does not, and on that one the AEC has to convert. +static AVSampleFormat chooseEncoderSampleFmt(const AVCodec *enc) +{ + if (!enc) + return AV_SAMPLE_FMT_S16; + + const enum AVSampleFormat *fmts = nullptr; + +#if AD_HAVE_SUPPORTED_CONFIG + // FFmpeg 7.1 (libavcodec 61.13.100) replaced AVCodec's arrays of + // supported formats with this query and deprecated the fields; 9.0 + // removed the fields outright, which is what MXE builds against. + const void *configs = nullptr; + if (avcodec_get_supported_config(nullptr, enc, AV_CODEC_CONFIG_SAMPLE_FORMAT, + 0, &configs, nullptr) < 0) + return AV_SAMPLE_FMT_S16; + + fmts = (const enum AVSampleFormat *)configs; +#else + fmts = enc->sample_fmts; +#endif + + // No list at all means the encoder takes whatever it is given - so it + // takes the one we would rather have. + if (!fmts || fmts[0] == AV_SAMPLE_FMT_NONE) + return AV_SAMPLE_FMT_S16; + + for (int i = 0; fmts[i] != AV_SAMPLE_FMT_NONE; i++) + { + if (fmts[i] == AV_SAMPLE_FMT_S16) + return AV_SAMPLE_FMT_S16; + } + + return fmts[0]; +} + +AudioDevice::AudioDevice(QObject *parent) + : QObject(parent), m_sampleRate(48000), m_bitrate(kOpusBitrate), m_reconfigure(0), + m_pendingSampleRate(48000), + m_clipCount(0), m_levelCount(0), m_levelPeak(0), + m_lastPlayedSeq(0), m_havePlayedSeq(false) +{ +} + +void AudioDevice::resetCaptureLevel() +{ + m_clipCount = 0; + m_levelCount = 0; + m_levelPeak = 0; +} + +void AudioDevice::checkCaptureLevel(const qint16 *pcm, int nsamples) +{ + for (int i = 0; i < nsamples; i++) + { + // qint16 promotes to int, so negating -32768 is well defined here. + int v = pcm[i] < 0 ? -(int)pcm[i] : (int)pcm[i]; + + if (v > m_levelPeak) + m_levelPeak = v; + if (v >= kClipThreshold) + m_clipCount++; + } + + m_levelCount += nsamples; + + if (m_levelCount < qint64(m_sampleRate) * kLevelReportSec) + return; + + double pinned = 100.0 * double(m_clipCount) / double(m_levelCount); + + if (pinned >= kClipWarnPercent) + { + double peakDb = m_levelPeak > 0 ? 20.0 * log10(double(m_levelPeak) / 32768.0) : -120.0; + emit captureClipping(pinned, peakDb); + } + + resetCaptureLevel(); +} + +AudioDevice::~AudioDevice() +{ + Close(); +} + +void AudioDevice::configureCapture(QString deviceName, QString codec, int sampleRate, int bitrate, + QByteArray caller_id, QByteArray callee_id) +{ + m_caller_id = caller_id; + m_callee_id = callee_id; + m_deviceName = deviceName; + m_codec = codec; + m_sampleRate = sampleRate; + m_bitrate = bitrate > 0 ? bitrate : kOpusBitrate; +} + +void AudioDevice::configurePlayback(QString deviceName, QString codec, int sampleRate, + QByteArray caller_id, QByteArray callee_id) +{ + m_caller_id = caller_id; + m_callee_id = callee_id; + m_deviceName = deviceName; + m_codec = codec; + m_sampleRate = sampleRate; +} + +void AudioDevice::openSession(QByteArray caller_id, QByteArray callee_id) +{ + m_openSession.open(caller_id, callee_id); +} + +void AudioDevice::changePlayback(QString deviceName, QString codec, int sampleRate) +{ + { + QMutexLocker locker(&m_queueMutex); + m_pendingDeviceName = deviceName; + m_pendingCodec = codec; + m_pendingSampleRate = sampleRate; + m_reconfigure.storeRelaxed(1); + /* encoded with the parameters being replaced */ + m_playQueue.clear(); + } + m_queueCond.wakeAll(); +} + +void AudioDevice::setEchoCanceller(EchoCancellerPtr ec) +{ + m_echoCanceller = ec; +} + +// Difference between two sequence numbers, correct across the point where +// they wrap around: positive if a comes after b. +static inline int seq_diff(quint16 a, quint16 b) +{ + return (qint16)(a - b); +} + +void AudioDevice::enqueuePacket(quint16 seq_num, QByteArray data) +{ + QMutexLocker locker(&m_queueMutex); + int i; + + // Too late to be of any use - the audio it belongs to has already been + // played. This also throws away duplicates of packets already played. + if (m_havePlayedSeq && seq_diff(seq_num, m_lastPlayedSeq) <= 0) + return; + + // Insertion point, and duplicates of packets still waiting. + for (i = m_playQueue.size(); i > 0; i--) + { + int d = seq_diff(seq_num, m_playQueue[i - 1].seq); + + if (d == 0) + return; + + if (d > 0) + break; + } + + while (m_playQueue.size() >= kMaxQueueDepth) + { + m_playQueue.removeFirst(); + + if (i > 0) + i--; + else + return; // the packet just dropped was this one's place + } + + PlaybackPacket p = { seq_num, data }; + m_playQueue.insert(i, p); + + m_queueCond.wakeAll(); +} + +void AudioDevice::Close() +{ + m_openSession.close(); + + { + QMutexLocker locker(&m_queueMutex); + m_reconfigure.storeRelaxed(0); + m_playQueue.clear(); + /* the next call starts its own numbering */ + m_havePlayedSeq = false; + } + m_queueCond.wakeAll(); +} + +void AudioDevice::waitForPreroll() +{ + // Preroll: wait for a small cushion of buffered packets before writing + // the first one, so ordinary arrival jitter doesn't immediately drain + // the queue and starve the device buffer (heard as crackling/xruns). + QMutexLocker locker(&m_queueMutex); + + while (m_playQueue.size() < kPrerollDepth && !stopRequested()) + m_queueCond.wait(&m_queueMutex, 100); +} + +bool AudioDevice::nextPacket(QByteArray *out) +{ + QMutexLocker locker(&m_queueMutex); + + while (m_playQueue.isEmpty() && !stopRequested()) + m_queueCond.wait(&m_queueMutex, 100); + + if (stopRequested()) + return false; + + if (m_playQueue.isEmpty()) + return true; + + PlaybackPacket p = m_playQueue.takeFirst(); + + *out = p.data; + m_lastPlayedSeq = p.seq; + m_havePlayedSeq = true; + + return true; +} + +void AudioDevice::Capture() +{ + /* closed before it got to start */ + if (sessionClosed()) + return; + + resetCaptureLevel(); + + const QString driver = AudioDevice::PlatformDriverName(CAPTURE); + + if (AudioDevice::IsPlatformDriver(driver)) + captureNative(AudioDevice::PlatformApiName(driver)); + else + captureFFmpeg(driver); +} + +void AudioDevice::Play() +{ + const QString driver = AudioDevice::PlatformDriverName(PLAYBACK); + + // More than one pass only when changePlayback() interrupts the one that is + // running. Also covers being closed before getting to start. + while (!sessionClosed()) + { + { + QMutexLocker locker(&m_queueMutex); + + if (m_reconfigure.loadRelaxed()) + { + m_deviceName = m_pendingDeviceName; + m_codec = m_pendingCodec; + m_sampleRate = m_pendingSampleRate; + m_reconfigure.storeRelaxed(0); + } + } + + if (AudioDevice::IsPlatformDriver(driver)) + playNative(AudioDevice::PlatformApiName(driver)); + else + playFFmpeg(driver); + + /* closed, or gave up on an error */ + if (!m_reconfigure.loadRelaxed()) + break; + } +} + +void AudioDevice::captureFFmpeg(const QString &driver) +{ + avdevice_register_all(); +#if LIBAVFORMAT_VERSION_MAJOR < 58 + av_register_all(); + avcodec_register_all(); +#endif + + const QByteArray deviceUtf8 = m_deviceName.toUtf8(); + const QByteArray driverUtf8 = driver.toUtf8(); + const AVInputFormat *ifmt = av_find_input_format(driverUtf8.constData()); + if (!ifmt) + { + QString msg = QString("Could not find '%1' input driver").arg(driver); + qWarning() << msg; + emit errorOccurred(msg); + return; + } + + AVDictionary *opts = nullptr; + av_dict_set(&opts, "sample_rate", QString::number(m_sampleRate).toUtf8().constData(), 0); + av_dict_set(&opts, "channels", QString::number(kChannels).toUtf8().constData(), 0); + + AVFormatContext *ifmt_ctx = nullptr; + int ret = avformat_open_input(&ifmt_ctx, deviceUtf8.constData(), ifmt, &opts); + av_dict_free(&opts); + if (ret < 0) + { + QString msg = QString("Could not open capture device '%1': %2").arg(m_deviceName, ff_errstr(ret)); + qWarning() << msg; + emit errorOccurred(msg); + return; + } + + if ((ret = avformat_find_stream_info(ifmt_ctx, nullptr)) < 0 || ifmt_ctx->nb_streams < 1) + { + QString msg = QString("Could not determine capture stream parameters: %1").arg(ff_errstr(ret)); + qWarning() << msg; + emit errorOccurred(msg); + avformat_close_input(&ifmt_ctx); + return; + } + + AVStream *in_st = ifmt_ctx->streams[0]; + + emit deviceFormatInUse(QString("%1 in %2 Hz %3 ch %4 -> %5 Hz %6 ch") + .arg(driver) + .arg(in_st->codecpar->sample_rate) +#if AD_HAVE_CH_LAYOUT + .arg(in_st->codecpar->ch_layout.nb_channels) +#else + .arg(in_st->codecpar->channels) +#endif + .arg(QLatin1String(avcodec_get_name(in_st->codecpar->codec_id))) + .arg(m_sampleRate).arg(kChannels)); + + const AVCodec *pcm_dec = avcodec_find_decoder(in_st->codecpar->codec_id); + AVCodecContext *dec_ctx = pcm_dec ? avcodec_alloc_context3(pcm_dec) : nullptr; + if (!pcm_dec || !dec_ctx || + avcodec_parameters_to_context(dec_ctx, in_st->codecpar) < 0 || + avcodec_open2(dec_ctx, pcm_dec, nullptr) < 0) + { + QString msg = "Could not open capture format decoder"; + qWarning() << msg; + emit errorOccurred(msg); + if (dec_ctx) avcodec_free_context(&dec_ctx); + avformat_close_input(&ifmt_ctx); + return; + } + + const AVCodec *enc = findCallAudioEncoder(m_codec); + AVCodecContext *enc_ctx = enc ? avcodec_alloc_context3(enc) : nullptr; + if (!enc || !enc_ctx) + { + QString msg = QString("No %1 encoder available").arg(m_codec); + qWarning() << msg; + emit errorOccurred(msg); + if (enc_ctx) avcodec_free_context(&enc_ctx); + avcodec_free_context(&dec_ctx); + avformat_close_input(&ifmt_ctx); + return; + } + + enc_ctx->sample_rate = m_sampleRate; + enc_ctx->sample_fmt = chooseEncoderSampleFmt(enc); + enc_ctx->bit_rate = m_bitrate; + enc_ctx->time_base = AVRational{1, m_sampleRate}; + applyMonoLayout(enc_ctx); + + // "voip" favors speech intelligibility over faithfulness and has lower + // algorithmic delay than the default "audio" mode - a better fit for a + // live call than for e.g. music. Only libopus exposes this private + // option; the other codecs have no private options at all, and a PCM + // encoder has no priv_data to pass here in the first place. + if (m_codec == QLatin1String("opus") && enc_ctx->priv_data) + av_opt_set(enc_ctx->priv_data, "application", "voip", 0); + + if ((ret = avcodec_open2(enc_ctx, enc, nullptr)) < 0) + { + QString msg = QString("Could not open the %1 encoder: %2").arg(m_codec, ff_errstr(ret)); + qWarning() << msg; + emit errorOccurred(msg); + avcodec_free_context(&enc_ctx); + avcodec_free_context(&dec_ctx); + avformat_close_input(&ifmt_ctx); + return; + } + + SwrContext *swr = makeMonoResampler(dec_ctx->sample_fmt, dec_ctx->sample_rate, enc_ctx->sample_fmt, enc_ctx->sample_rate); + if (!swr) + { + QString msg = "Could not set up capture resampler"; + qWarning() << msg; + emit errorOccurred(msg); + avcodec_free_context(&enc_ctx); + avcodec_free_context(&dec_ctx); + avformat_close_input(&ifmt_ctx); + return; + } + + AVAudioFifo *fifo = av_audio_fifo_alloc(enc_ctx->sample_fmt, kChannels, 1); + // An encoder that takes any number of samples per packet - a PCM one - + // leaves this at zero and the packet size is ours to pick. 20ms is what + // the other two produce and what the playback side's jitter buffer is + // sized in, so it is what everything here already assumes. + int frame_size = enc_ctx->frame_size > 0 ? enc_ctx->frame_size : m_sampleRate / 50; + + // The canceller only gets to work in place when the encoder is taking + // interleaved 16 bit, which libopus does. On the native encoder, whose + // only format is planar float, cancelling would mean converting to 16 bit + // and back around every frame; not worth it for a fallback path. + EchoCancellerPtr ec = m_echoCanceller; + if (ec && (!ec->isValid() || enc_ctx->sample_fmt != AV_SAMPLE_FMT_S16 || + ec->sampleRate() != m_sampleRate)) + { + if (ec->isValid()) + qWarning() << "Echo cancellation disabled: encoder format" << av_get_sample_fmt_name(enc_ctx->sample_fmt) + << "at" << m_sampleRate << "Hz is not what the canceller was built for"; + ec.clear(); + } + + AVPacket *in_pkt = av_packet_alloc(); + AVFrame *dec_frame = av_frame_alloc(); + AVPacket *out_pkt = av_packet_alloc(); + int64_t pts = 0; + bool loggedDecodeError = false; + bool loggedEncodeError = false; + + while (!stopRequested()) + { + ret = av_read_frame(ifmt_ctx, in_pkt); + if (ret < 0) + { + if (ret == AVERROR(EAGAIN)) + continue; + if (!loggedDecodeError) + { + qWarning() << QString("Capture device read failed: %1").arg(ff_errstr(ret)); + loggedDecodeError = true; + } + break; + } + + ret = avcodec_send_packet(dec_ctx, in_pkt); + av_packet_unref(in_pkt); + if (ret < 0) + { + if (!loggedDecodeError) + { + qWarning() << QString("Capture format decode failed: %1").arg(ff_errstr(ret)); + loggedDecodeError = true; + } + continue; + } + + while (avcodec_receive_frame(dec_ctx, dec_frame) == 0) + { + uint8_t **converted = nullptr; + int out_samples = (int)av_rescale_rnd(swr_get_delay(swr, dec_frame->sample_rate) + dec_frame->nb_samples, + enc_ctx->sample_rate, dec_frame->sample_rate, AV_ROUND_UP); + + if (out_samples > 0 && + av_samples_alloc_array_and_samples(&converted, nullptr, kChannels, out_samples, enc_ctx->sample_fmt, 0) >= 0) + { + int converted_samples = swr_convert(swr, converted, out_samples, + (const uint8_t **)dec_frame->data, dec_frame->nb_samples); + + if (converted_samples > 0 && + av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + converted_samples) >= 0) + { + av_audio_fifo_write(fifo, (void **)converted, converted_samples); + } + + av_freep(&converted[0]); + av_freep(&converted); + } + av_frame_unref(dec_frame); + + while (av_audio_fifo_size(fifo) >= frame_size) + { + AVFrame *enc_frame = av_frame_alloc(); + enc_frame->format = enc_ctx->sample_fmt; + enc_frame->sample_rate = enc_ctx->sample_rate; + enc_frame->nb_samples = frame_size; + applyMonoLayout(enc_frame); + av_frame_get_buffer(enc_frame, 0); + + av_audio_fifo_read(fifo, (void **)enc_frame->data, frame_size); + + // Both of these want interleaved 16 bit. That is what libopus + // takes, so it is the normal path; the native "opus" encoder + // fallback runs in planar float and gets neither. + if (enc_ctx->sample_fmt == AV_SAMPLE_FMT_S16) + checkCaptureLevel((const qint16 *)enc_frame->data[0], frame_size); + + // Take the echo of what the playback direction has been + // feeding the speaker back out of the microphone signal, + // before it is encoded and sent. + if (ec) + ec->processNearEnd((qint16 *)enc_frame->data[0], frame_size); + + enc_frame->pts = pts; + pts += frame_size; + + if (avcodec_send_frame(enc_ctx, enc_frame) == 0) + { + while (avcodec_receive_packet(enc_ctx, out_pkt) == 0) + { + emit packetReady(QByteArray((const char *)out_pkt->data, out_pkt->size)); + av_packet_unref(out_pkt); + } + } + else if (!loggedEncodeError) + { + qWarning() << QString("%1 encode failed").arg(m_codec); + loggedEncodeError = true; + } + av_frame_free(&enc_frame); + } + } + } + + av_packet_free(&in_pkt); + av_packet_free(&out_pkt); + av_frame_free(&dec_frame); + av_audio_fifo_free(fifo); + swr_free(&swr); + avcodec_free_context(&enc_ctx); + avcodec_free_context(&dec_ctx); + avformat_close_input(&ifmt_ctx); +} + +void AudioDevice::captureNative(const QString &api) +{ + NativeAudioBackend *backend = NativeAudioBackend::create(api); + if (!backend) + { + QString msg = QString("No '%1' audio backend in this build").arg(api); + qWarning() << msg; + emit errorOccurred(msg); + return; + } + + // Ask the platform for its voice processing only when it is the one + // meant to be cancelling. Either of the other two settings wants the + // microphone as the hardware delivers it: EchoCanceller cannot model an + // echo path that something below it is already subtracting from, and + // "off" means off. + const NativeAudioMode mode = (AudioDevice::EchoCancellation() == EchoCancellationPlatform) + ? NativeAudioVoiceCall : NativeAudioVoiceCallRaw; + + QString err; + if (!backend->openCapture(m_deviceName, m_sampleRate, kChannels, mode, &err)) + { + qWarning() << err; + emit errorOccurred(err); + delete backend; + return; + } + + emit deviceFormatInUse(backend->formatDescription()); + + const AVCodec *enc = findCallAudioEncoder(m_codec); + AVCodecContext *enc_ctx = enc ? avcodec_alloc_context3(enc) : nullptr; + if (!enc || !enc_ctx) + { + QString msg = QString("No %1 encoder available").arg(m_codec); + qWarning() << msg; + emit errorOccurred(msg); + if (enc_ctx) avcodec_free_context(&enc_ctx); + backend->close(); + delete backend; + return; + } + + enc_ctx->sample_rate = m_sampleRate; + enc_ctx->sample_fmt = chooseEncoderSampleFmt(enc); + enc_ctx->bit_rate = m_bitrate; + enc_ctx->time_base = AVRational{1, m_sampleRate}; + applyMonoLayout(enc_ctx); + + // See captureFFmpeg() for why this is guarded. + if (m_codec == QLatin1String("opus") && enc_ctx->priv_data) + av_opt_set(enc_ctx->priv_data, "application", "voip", 0); + + int ret = avcodec_open2(enc_ctx, enc, nullptr); + if (ret < 0) + { + QString msg = QString("Could not open the %1 encoder: %2").arg(m_codec, ff_errstr(ret)); + qWarning() << msg; + emit errorOccurred(msg); + avcodec_free_context(&enc_ctx); + backend->close(); + delete backend; + return; + } + + // The backend delivers interleaved 16 bit at our rate. Anything but an + // encoder that takes the same needs a converter in between. + SwrContext *swr = nullptr; + if (enc_ctx->sample_fmt != AV_SAMPLE_FMT_S16) + { + swr = makeMonoResampler(AV_SAMPLE_FMT_S16, m_sampleRate, enc_ctx->sample_fmt, m_sampleRate); + if (!swr) + { + QString msg = "Could not set up capture converter"; + qWarning() << msg; + emit errorOccurred(msg); + avcodec_free_context(&enc_ctx); + backend->close(); + delete backend; + return; + } + } + + // Nothing for us to do when the platform has already taken the echo out + // below us - running a second canceller over an already cancelled signal + // only gives it a near silent reference to chase and can chew holes in + // the speech. + EchoCancellerPtr ec = m_echoCanceller; + if (backend->hasPlatformEchoCancellation()) + { + if (ec) + qDebug() << api << "provides echo cancellation - not running ours as well"; + ec.clear(); + } + else if (ec && (!ec->isValid() || ec->sampleRate() != m_sampleRate)) + { + ec.clear(); + } + + // Same reasoning as in captureFFmpeg(). + const int frame_size = enc_ctx->frame_size > 0 ? enc_ctx->frame_size : m_sampleRate / 50; + + QVector<qint16> pending; + QVector<qint16> scratch(frame_size * 4); + QVector<qint16> block(frame_size); + + AVPacket *out_pkt = av_packet_alloc(); + int64_t pts = 0; + bool loggedEncodeError = false; + + while (!stopRequested()) + { + int got = backend->read(scratch.data(), scratch.size(), 100); + if (got < 0) + { + qWarning() << "Native capture read failed"; + break; + } + if (got == 0) + continue; + + int base = pending.size(); + pending.resize(base + got); + memcpy(pending.data() + base, scratch.constData(), got * sizeof(qint16)); + + int consumed = 0; + while (pending.size() - consumed >= frame_size) + { + memcpy(block.data(), pending.constData() + consumed, frame_size * sizeof(qint16)); + consumed += frame_size; + + // The backend always delivers interleaved 16 bit, so unlike the + // FFmpeg path this needs no format check. + checkCaptureLevel(block.constData(), frame_size); + + if (ec) + ec->processNearEnd(block.data(), frame_size); + + AVFrame *enc_frame = av_frame_alloc(); + enc_frame->format = enc_ctx->sample_fmt; + enc_frame->sample_rate = enc_ctx->sample_rate; + enc_frame->nb_samples = frame_size; + applyMonoLayout(enc_frame); + + if (av_frame_get_buffer(enc_frame, 0) < 0) + { + av_frame_free(&enc_frame); + continue; + } + + if (swr) + { + const uint8_t *in[1] = { (const uint8_t *)block.constData() }; + if (swr_convert(swr, enc_frame->data, frame_size, in, frame_size) <= 0) + { + av_frame_free(&enc_frame); + continue; + } + } + else + { + memcpy(enc_frame->data[0], block.constData(), frame_size * sizeof(qint16)); + } + + enc_frame->pts = pts; + pts += frame_size; + + if (avcodec_send_frame(enc_ctx, enc_frame) == 0) + { + while (avcodec_receive_packet(enc_ctx, out_pkt) == 0) + { + emit packetReady(QByteArray((const char *)out_pkt->data, out_pkt->size)); + av_packet_unref(out_pkt); + } + } + else if (!loggedEncodeError) + { + qWarning() << QString("%1 encode failed").arg(m_codec); + loggedEncodeError = true; + } + + av_frame_free(&enc_frame); + } + + if (consumed > 0) + pending.remove(0, consumed); + } + + av_packet_free(&out_pkt); + if (swr) swr_free(&swr); + avcodec_free_context(&enc_ctx); + backend->close(); + delete backend; +} + +void AudioDevice::playFFmpeg(const QString &driver) +{ + avdevice_register_all(); +#if LIBAVFORMAT_VERSION_MAJOR < 58 + av_register_all(); + avcodec_register_all(); +#endif + + AVFormatContext *oc = nullptr; + const QByteArray deviceUtf8 = m_deviceName.toUtf8(); + const QByteArray driverUtf8 = driver.toUtf8(); + + int ret = avformat_alloc_output_context2(&oc, nullptr, driverUtf8.constData(), deviceUtf8.constData()); + if (ret < 0 || !oc) + { + QString msg = QString("Could not allocate '%1' output context: %2").arg(driver, ff_errstr(ret)); + qWarning() << msg; + emit errorOccurred(msg); + return; + } + + const AVCodec *out_codec = avcodec_find_encoder(AV_CODEC_ID_PCM_S16LE); + AVCodecContext *out_ctx = out_codec ? avcodec_alloc_context3(out_codec) : nullptr; + if (!out_codec || !out_ctx) + { + QString msg = "PCM encoder not found"; + qWarning() << msg; + emit errorOccurred(msg); + avformat_free_context(oc); + return; + } + + out_ctx->sample_fmt = AV_SAMPLE_FMT_S16; + out_ctx->sample_rate = m_sampleRate; + out_ctx->time_base = AVRational{1, m_sampleRate}; + applyMonoLayout(out_ctx); + + if ((ret = avcodec_open2(out_ctx, out_codec, nullptr)) < 0) + { + QString msg = QString("Could not open playback codec: %1").arg(ff_errstr(ret)); + qWarning() << msg; + emit errorOccurred(msg); + avcodec_free_context(&out_ctx); + avformat_free_context(oc); + return; + } + + AVStream *st = avformat_new_stream(oc, nullptr); + if (!st || avcodec_parameters_from_context(st->codecpar, out_ctx) < 0) + { + QString msg = "Could not create playback stream"; + qWarning() << msg; + emit errorOccurred(msg); + avcodec_free_context(&out_ctx); + avformat_free_context(oc); + return; + } + st->time_base = out_ctx->time_base; + + if (!(oc->oformat->flags & AVFMT_NOFILE)) + { + if ((ret = avio_open(&oc->pb, deviceUtf8.constData(), AVIO_FLAG_WRITE)) < 0) + { + QString msg = QString("Could not open '%1' device '%2': %3").arg(driver, m_deviceName, ff_errstr(ret)); + qWarning() << msg; + emit errorOccurred(msg); + avcodec_free_context(&out_ctx); + avformat_free_context(oc); + return; + } + } + + if ((ret = avformat_write_header(oc, nullptr)) < 0) + { + QString msg = QString("Error writing playback header: %1").arg(ff_errstr(ret)); + qWarning() << msg; + emit errorOccurred(msg); + if (!(oc->oformat->flags & AVFMT_NOFILE)) avio_closep(&oc->pb); + avcodec_free_context(&out_ctx); + avformat_free_context(oc); + return; + } + + // Whatever the peer announced in its 0x74 message, looked up by the name + // it used - the peer's choice of codec is its own and need not match ours. + const AVCodec *in_codec = findCallAudioDecoder(m_codec); + AVCodecContext *dec_ctx = in_codec ? avcodec_alloc_context3(in_codec) : nullptr; + if (dec_ctx) + { + // A PCM decoder is told nothing by the bitstream and has to be given + // both of these; the others work them out for themselves. + dec_ctx->sample_rate = m_sampleRate; + applyMonoLayout(dec_ctx); + } + if (!in_codec || !dec_ctx || avcodec_open2(dec_ctx, in_codec, nullptr) < 0) + { + QString msg = QString("Unsupported call audio codec: %1").arg(m_codec); + qWarning() << msg; + emit errorOccurred(msg); + if (dec_ctx) avcodec_free_context(&dec_ctx); + if (!(oc->oformat->flags & AVFMT_NOFILE)) avio_closep(&oc->pb); + avcodec_free_context(&out_ctx); + avformat_free_context(oc); + return; + } + + // A rate mismatch is not a reason to drop it any more - pushFarEnd() + // resamples. The two directions genuinely can disagree: we capture at the + // rate AudioVideoCallController picked, but play back at whatever the + // peer announced. + EchoCancellerPtr ec = m_echoCanceller; + if (ec && !ec->isValid()) + ec.clear(); + + SwrContext *swr = nullptr; + AVPacket *out_pkt = av_packet_alloc(); + AVFrame *dec_frame = av_frame_alloc(); + int64_t pts = 0; + bool loggedDecodeError = false; + bool loggedResamplerError = false; + bool loggedEncodeError = false; + + waitForPreroll(); + + while (true) + { + QByteArray pktData; + if (!nextPacket(&pktData)) + break; + if (pktData.isEmpty()) + continue; + + AVPacket *in_pkt = av_packet_alloc(); + if (av_new_packet(in_pkt, pktData.size()) < 0) + { + av_packet_free(&in_pkt); + continue; + } + memcpy(in_pkt->data, pktData.constData(), pktData.size()); + + ret = avcodec_send_packet(dec_ctx, in_pkt); + av_packet_free(&in_pkt); + if (ret < 0) + { + if (!loggedDecodeError) + { + qWarning() << QString("%1 decode failed: %2").arg(m_codec, ff_errstr(ret)); + loggedDecodeError = true; + } + continue; + } + + while (avcodec_receive_frame(dec_ctx, dec_frame) == 0) + { + if (!swr) + { + swr = makeMonoResampler((AVSampleFormat)dec_frame->format, dec_frame->sample_rate, out_ctx->sample_fmt, out_ctx->sample_rate); + if (!swr) + { + if (!loggedResamplerError) + { + qWarning() << "Could not set up playback resampler"; + loggedResamplerError = true; + } + av_frame_unref(dec_frame); + continue; + } + } + + int out_samples = (int)av_rescale_rnd(swr_get_delay(swr, dec_frame->sample_rate) + dec_frame->nb_samples, + out_ctx->sample_rate, dec_frame->sample_rate, AV_ROUND_UP); + + AVFrame *out_frame = av_frame_alloc(); + out_frame->format = out_ctx->sample_fmt; + out_frame->sample_rate = out_ctx->sample_rate; + out_frame->nb_samples = out_samples; + applyMonoLayout(out_frame); + + if (out_samples > 0 && av_frame_get_buffer(out_frame, 0) == 0) + { + int converted_samples = swr_convert(swr, out_frame->data, out_samples, + (const uint8_t **)dec_frame->data, dec_frame->nb_samples); + if (converted_samples > 0) + { + out_frame->nb_samples = converted_samples; + out_frame->pts = pts; + pts += converted_samples; + + // Hand the canceller the far end signal at the same + // moment the sound card gets it, so the delay it has to + // model is only the device buffer plus the room. + if (ec) + ec->pushFarEnd((const qint16 *)out_frame->data[0], converted_samples, m_sampleRate); + + if (avcodec_send_frame(out_ctx, out_frame) == 0) + { + while (avcodec_receive_packet(out_ctx, out_pkt) == 0) + { + out_pkt->stream_index = st->index; + av_interleaved_write_frame(oc, out_pkt); + av_packet_unref(out_pkt); + } + } + else if (!loggedEncodeError) + { + qWarning() << "Playback PCM encode failed"; + loggedEncodeError = true; + } + } + } + av_frame_free(&out_frame); + av_frame_unref(dec_frame); + } + } + + av_packet_free(&out_pkt); + av_frame_free(&dec_frame); + if (swr) swr_free(&swr); + avcodec_free_context(&dec_ctx); + + av_write_trailer(oc); + if (!(oc->oformat->flags & AVFMT_NOFILE)) avio_closep(&oc->pb); + avcodec_free_context(&out_ctx); + avformat_free_context(oc); +} + +void AudioDevice::playNative(const QString &api) +{ + NativeAudioBackend *backend = NativeAudioBackend::create(api); + if (!backend) + { + QString msg = QString("No '%1' audio backend in this build").arg(api); + qWarning() << msg; + emit errorOccurred(msg); + return; + } + + // Same choice as captureNative(), and it has to be the same answer: on + // macOS the platform canceller is one audio unit doing both directions, + // so asking for it here and not there would open a second unit on the + // same device. + const NativeAudioMode mode = (AudioDevice::EchoCancellation() == EchoCancellationPlatform) + ? NativeAudioVoiceCall : NativeAudioVoiceCallRaw; + + QString err; + if (!backend->openPlayback(m_deviceName, m_sampleRate, kChannels, mode, &err)) + { + qWarning() << err; + emit errorOccurred(err); + delete backend; + return; + } + + emit deviceFormatInUse(backend->formatDescription()); + + // Same as in playFFmpeg(): the codec the peer announced, by its name. + const AVCodec *in_codec = findCallAudioDecoder(m_codec); + AVCodecContext *dec_ctx = in_codec ? avcodec_alloc_context3(in_codec) : nullptr; + if (dec_ctx) + { + dec_ctx->sample_rate = m_sampleRate; + applyMonoLayout(dec_ctx); + } + if (!in_codec || !dec_ctx || avcodec_open2(dec_ctx, in_codec, nullptr) < 0) + { + QString msg = QString("Unsupported call audio codec: %1").arg(m_codec); + qWarning() << msg; + emit errorOccurred(msg); + if (dec_ctx) avcodec_free_context(&dec_ctx); + backend->close(); + delete backend; + return; + } + + // On a platform that cancels for us, the far end signal it needs is the + // one it is rendering itself - there is nothing to hand to ours, and + // nothing for ours to do. A rate mismatch is handled by pushFarEnd() + // rather than by dropping the canceller, see playFFmpeg(). + EchoCancellerPtr ec = m_echoCanceller; + if (ec && !ec->isValid()) + ec.clear(); + + SwrContext *swr = nullptr; + AVFrame *dec_frame = av_frame_alloc(); + QVector<qint16> out; + bool loggedDecodeError = false; + bool loggedResamplerError = false; + + waitForPreroll(); + + while (true) + { + QByteArray pktData; + if (!nextPacket(&pktData)) + break; + if (pktData.isEmpty()) + continue; + + AVPacket *in_pkt = av_packet_alloc(); + if (av_new_packet(in_pkt, pktData.size()) < 0) + { + av_packet_free(&in_pkt); + continue; + } + memcpy(in_pkt->data, pktData.constData(), pktData.size()); + + int ret = avcodec_send_packet(dec_ctx, in_pkt); + av_packet_free(&in_pkt); + if (ret < 0) + { + if (!loggedDecodeError) + { + qWarning() << QString("%1 decode failed: %2").arg(m_codec, ff_errstr(ret)); + loggedDecodeError = true; + } + continue; + } + + while (avcodec_receive_frame(dec_ctx, dec_frame) == 0) + { + if (!swr) + { + swr = makeMonoResampler((AVSampleFormat)dec_frame->format, dec_frame->sample_rate, + AV_SAMPLE_FMT_S16, m_sampleRate); + if (!swr) + { + if (!loggedResamplerError) + { + qWarning() << "Could not set up playback resampler"; + loggedResamplerError = true; + } + av_frame_unref(dec_frame); + continue; + } + } + + int out_samples = (int)av_rescale_rnd(swr_get_delay(swr, dec_frame->sample_rate) + dec_frame->nb_samples, + m_sampleRate, dec_frame->sample_rate, AV_ROUND_UP); + if (out_samples > 0) + { + out.resize(out_samples * kChannels); + + uint8_t *outPlanes[1] = { (uint8_t *)out.data() }; + int converted = swr_convert(swr, outPlanes, out_samples, + (const uint8_t **)dec_frame->data, dec_frame->nb_samples); + if (converted > 0) + { + if (ec) + ec->pushFarEnd(out.constData(), converted * kChannels, m_sampleRate); + + if (backend->write(out.constData(), converted * kChannels, 100) < 0) + { + qWarning() << "Native playback write failed"; + av_frame_unref(dec_frame); + goto done; + } + } + } + + av_frame_unref(dec_frame); + } + } + +done: + av_frame_free(&dec_frame); + if (swr) swr_free(&swr); + avcodec_free_context(&dec_ctx); + backend->close(); + delete backend; +} + +#ifdef HAVE_LIBPULSE + +// PulseAudio's introspection API is asynchronous, so a one-shot enumeration +// means running a private mainloop until the callbacks below have said they +// are done. Doing it on the caller's thread with its own context keeps this +// self contained - nothing else in pica-client talks to PulseAudio. +struct PulseEnumState +{ + QList<MediaDeviceInfo> *result; + int *index; + // The introspection callback has reported the end of the list, so + // whatever happens to the connection afterwards is just teardown. + bool completed; + bool done; + bool failed; +}; + +static void pulse_source_cb(pa_context *, const pa_source_info *info, int eol, void *userdata) +{ + PulseEnumState *st = (PulseEnumState *)userdata; + + if (eol) + { + st->completed = true; + st->done = true; + return; + } + + if (!info) + return; + + // Monitor sources are the loopback of an output, not a microphone; they + // would show up in the capture list as duplicates of every speaker. + if (info->monitor_of_sink != PA_INVALID_INDEX) + return; + + MediaDeviceInfo d; + d.device = QString::fromUtf8(info->name); + d.humanReadable = QString::fromUtf8(info->description); + d.index = (*st->index)++; + *st->result << d; +} + +static void pulse_sink_cb(pa_context *, const pa_sink_info *info, int eol, void *userdata) +{ + PulseEnumState *st = (PulseEnumState *)userdata; + + if (eol) + { + st->completed = true; + st->done = true; + return; + } + + if (!info) + return; + + MediaDeviceInfo d; + d.device = QString::fromUtf8(info->name); + d.humanReadable = QString::fromUtf8(info->description); + d.index = (*st->index)++; + *st->result << d; +} + +static void pulse_state_cb(pa_context *ctx, void *userdata) +{ + PulseEnumState *st = (PulseEnumState *)userdata; + + // READY is handled by the loop in enumeratePulse(), which is where the + // introspection request gets issued; only the ways this can end early + // need noticing here. + switch (pa_context_get_state(ctx)) + { + case PA_CONTEXT_FAILED: + case PA_CONTEXT_TERMINATED: + if (!st->completed) + st->failed = true; + st->done = true; + break; + + default: + break; + } +} + +static QList<MediaDeviceInfo> enumeratePulse(enum MediaDeviceStreamDirection dir) +{ + QList<MediaDeviceInfo> result; + int index = 0; + + // PulseAudio's own idea of the default, which follows the user moving + // their default device in the desktop's sound settings. + { + MediaDeviceInfo d; + d.device = QStringLiteral("default"); + d.humanReadable = (dir == PLAYBACK) + ? QObject::tr("Default output (PulseAudio)") + : QObject::tr("Default input (PulseAudio)"); + d.index = index++; + result << d; + } + + pa_mainloop *mainloop = pa_mainloop_new(); + if (!mainloop) + return result; + + pa_context *ctx = pa_context_new(pa_mainloop_get_api(mainloop), "pica-client"); + if (!ctx) + { + pa_mainloop_free(mainloop); + return result; + } + + PulseEnumState st; + st.result = &result; + st.index = &index; + st.completed = false; + st.done = false; + st.failed = false; + + pa_context_set_state_callback(ctx, pulse_state_cb, &st); + + if (pa_context_connect(ctx, nullptr, PA_CONTEXT_NOFLAGS, nullptr) < 0) + { + pa_context_unref(ctx); + pa_mainloop_free(mainloop); + return result; + } + + pa_operation *op = nullptr; + bool requested = false; + + // Bounded so a server that never answers cannot hang the settings dialog. + // One iteration is at most the 50ms below, so this is a 5 second ceiling. + for (int iterations = 0; iterations < 100 && !st.done; iterations++) + { + if (pa_mainloop_prepare(mainloop, 50 * 1000) < 0) + break; + if (pa_mainloop_poll(mainloop) < 0) + break; + if (pa_mainloop_dispatch(mainloop) < 0) + break; + + if (!requested && pa_context_get_state(ctx) == PA_CONTEXT_READY) + { + if (dir == PLAYBACK) + op = pa_context_get_sink_info_list(ctx, pulse_sink_cb, &st); + else + op = pa_context_get_source_info_list(ctx, pulse_source_cb, &st); + + requested = true; + + if (!op) + break; + } + } + + if (op) + pa_operation_unref(op); + + pa_context_disconnect(ctx); + pa_context_unref(ctx); + pa_mainloop_free(mainloop); + + if (st.failed) + qWarning() << "Could not enumerate PulseAudio devices - is a sound server running?"; + + return result; +} + +#endif // HAVE_LIBPULSE + +#ifdef Q_OS_LINUX + +static QList<MediaDeviceInfo> enumerateAlsa(enum MediaDeviceStreamDirection dir) +{ + QList<MediaDeviceInfo> result; + int index = 0; + + void **hints, **n; + char *name = NULL, *descr = NULL, *io = NULL; + const char *direction = (dir == PLAYBACK) ? "Output" : "Input"; + + if (snd_device_name_hint(-1, "pcm", &hints) < 0) + return result; + n = hints; + while(*n) + { + MediaDeviceInfo d; + + name = snd_device_name_get_hint(*n, "NAME"); + descr = snd_device_name_get_hint(*n, "DESC"); + io = snd_device_name_get_hint(*n, "IOID"); + + if (io && strcmp(io, direction)) + goto release_resources; + + d.device = QLatin1String(name); + d.humanReadable = QLatin1String(descr); + d.index = index++; + if (strstr(name, "default") == name) + result.prepend(d); + else + result << d; + + release_resources: + free(io); + free(descr); + free(name); + n++; + } + snd_device_name_free_hint(hints); + + return result; +} + +#endif // Q_OS_LINUX + +QList<MediaDeviceInfo> AudioDevice::Enumerate(enum MediaDeviceStreamDirection dir) +{ + const QString driver = AudioDevice::PlatformDriverName(dir); + + if (AudioDevice::IsPlatformDriver(driver)) + return NativeAudioBackend::enumerate(AudioDevice::PlatformApiName(driver), dir); + +#ifdef HAVE_LIBPULSE + if (driver == QLatin1String("pulse")) + return enumeratePulse(dir); +#endif + +#ifdef Q_OS_LINUX + if (driver == QLatin1String("alsa")) + return enumerateAlsa(dir); +#endif + + // Anything else - "oss", or "pulse" in a build without libpulse - has no + // enumeration of its own worth writing, so the caller gets the one name + // that always works. + QList<MediaDeviceInfo> result; + MediaDeviceInfo d; + d.device = QStringLiteral("default"); + d.humanReadable = QObject::tr("Default device"); + d.index = 0; + result << d; + + return result; +} + +void AudioDevice::SetLinuxDriverName(const QString &driver) +{ + QMutexLocker locker(&s_driverMutex); + + if (driver == QLatin1String("pulse")) + s_linuxDriver = QStringLiteral("pulse"); + else + s_linuxDriver = QStringLiteral("alsa"); +} + +QString AudioDevice::LinuxDriverName() +{ + QMutexLocker locker(&s_driverMutex); + return s_linuxDriver; +} + +void AudioDevice::SetEchoCancellation(EchoCancellationMode mode) +{ + QMutexLocker locker(&s_echoCancellationMutex); + s_echoCancellation = mode; +} + +EchoCancellationMode AudioDevice::EchoCancellation() +{ + QMutexLocker locker(&s_echoCancellationMutex); + return s_echoCancellation; +} + +bool AudioDevice::PlatformEchoCancellationAvailable(const QString &driver) +{ + // Windows and macOS both have one, and both are reached through the + // native backends rather than through libavdevice - which is why those + // backends exist at all. + if (AudioDevice::IsPlatformDriver(driver)) + return NativeAudioBackend::isAvailable(AudioDevice::PlatformApiName(driver)); + + // On Linux nothing is provided per stream. What there is instead is a + // sound server that can be made to hand out an already cancelled source - + // PulseAudio's module-echo-cancel, or PipeWire's equivalent - which the + // user then picks from the microphone list like any other device. Raw + // ALSA has nothing of the sort. + if (driver == QLatin1String("pulse")) + return true; + + return false; +} + +bool AudioDevice::PlatformEchoCancellationAvailable() +{ + return PlatformEchoCancellationAvailable(AudioDevice::PlatformDriverName(CAPTURE)); +} + +QString AudioDevice::PlatformDriverName(enum MediaDeviceStreamDirection dir) +{ + Q_UNUSED(dir) + +#if defined(Q_OS_LINUX) + // Both directions come from the same setting. ALSA is the default because + // it is the one interface guaranteed to be there; "pulse" is worth + // choosing on a desktop, where it (or PipeWire wearing its face) is what + // actually owns the sound card, and where module-echo-cancel can take the + // job off our hands entirely. + return AudioDevice::LinuxDriverName(); +#elif defined(Q_OS_MACOS) || defined(Q_OS_MAC) + // Not libavdevice's "audiotoolbox". CoreAudio's echo cancellation lives + // in the VoiceProcessingIO audio unit, which renders and captures + // together, and there is no way to reach it through a demuxer and a muxer + // that know nothing about each other. + return QStringLiteral("platform-coreaudio"); +#elif defined(Q_OS_WIN) + // DirectSound is a compatibility shim over + // WASAPI these days and cannot mark a stream as belonging to a call, + // which is the only way to get Windows' own echo cancellation. + return QStringLiteral("platform-wasapi"); +#else + return QStringLiteral("oss"); +#endif +} + +bool AudioDevice::IsPlatformDriver(const QString &driver) +{ + return driver.startsWith(QLatin1String("platform-")); +} + +QString AudioDevice::PlatformApiName(const QString &driver) +{ + if (!IsPlatformDriver(driver)) + return QString(); + + return driver.mid(sizeof("platform-") - 1); +} diff --git a/pica-client/audiodevice.h b/pica-client/audiodevice.h new file mode 100644 index 0000000..fde45db --- /dev/null +++ b/pica-client/audiodevice.h @@ -0,0 +1,319 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#ifndef AUDIODEVICE_H +#define AUDIODEVICE_H + +#include "mediadevice.h" +#include "echocanceller.h" +#include <QObject> +#include <QString> +#include <QByteArray> +#include <QQueue> +#include <QMutex> +#include <QWaitCondition> +#include <QAtomicInt> + +class NativeAudioBackend; + +// A single AudioDevice instance is dedicated to one direction - either +// capture+encode (via Capture(), fed from a local hardware input device) or +// decode+playback (via Play(), fed from the network via enqueuePacket()). +// Each instance is meant to live on its own QThread (see +// AudioVideoCallController), since both Capture() and Play() block the +// calling thread in a device I/O loop until Close() is called - the same +// pattern TonePlayer already uses for tone playback. +class AudioDevice : public QObject, public MediaDevice +{ + Q_OBJECT +public: + AudioDevice(QObject *parent = nullptr); + ~AudioDevice(); + + // Configure before invoking Capture()/Play(). deviceName is a platform + // device identifier as accepted by the driver named by + // PlatformDriverName() (e.g. an ALSA PCM name, a PulseAudio source name, + // a WASAPI endpoint id, a CoreAudio device UID), or "default". + // + // codec is the FFmpeg name of the codec, which is also the name the 0x74 + // message carries - "opus", "adpcm_g722" or "pcm_alaw". bitrate is in bits + // per second and only reaches an encoder with a rate to control: G.722 and + // A-law code a fixed number of bits per sample and simply ignore it. + // + // caller_id and callee_id name the call the loop is going to run for, and + // have to be the pair openSession() was given - see there. + Q_INVOKABLE void configureCapture(QString deviceName, QString codec, int sampleRate, int bitrate, + QByteArray caller_id, QByteArray callee_id); + Q_INVOKABLE void configurePlayback(QString deviceName, QString codec, int sampleRate, + QByteArray caller_id, QByteArray callee_id); + + // Allows Capture()/Play() to run for this call, until Close(). To be + // called directly, before the calls that configure and start the device + // are queued: a Capture()/Play() configured for a call that is no longer + // the open one returns at once, so a Close() that lands before a queued + // start has begun is not lost. Safe to call from any thread. + void openSession(QByteArray caller_id, QByteArray callee_id); + + // New playback parameters for a Play() that is already running: the peer + // may change what it sends in the middle of a call, by sending another + // 0x74. The loop closes its decoder and output device and opens them + // again for these. Safe to call from any thread, and has to be called + // directly - the device's own thread is busy inside Play(). + // + // Whatever is still waiting in the jitter buffer is dropped, since it was + // encoded with the previous parameters. + void changePlayback(QString deviceName, QString codec, int sampleRate); + + // Give this device the call's echo canceller. The capture direction runs + // the microphone signal through it, the playback direction feeds it the + // far end signal; both directions of one call must be given the same + // object or there is nothing to cancel against. + // + // Null unless EchoCancellation() is EchoCancellationOwn - see + // AudioVideoCallController::startAudioPipeline(), which is where that is + // decided. + // + // To be invoked through the device's own thread, like configureCapture(): + // the loop of the previous call may still be on its way out and reading + // the canceller it was given. + Q_INVOKABLE void setEchoCanceller(EchoCancellerPtr ec); + + // Push a codec packet received from the network into the playback + // jitter buffer. Safe to call from any thread. Drops the oldest queued + // packet if the buffer is full, favoring low latency over completeness. + // + // seq_num is the packet's 0x76 sequence number. Over a mediac2c + // connection packets can arrive out of order or twice, so the buffer is + // ordered by it, and a packet that arrives after one further along the + // stream has already been played is dropped rather than played out of + // place. + Q_INVOKABLE void enqueuePacket(quint16 seq_num, QByteArray data); + +public slots: + // Blocking capture+encode loop: opens the configured local input + // device, encodes captured audio with the configured codec, and emits + // packetReady() for each encoded packet. Returns once Close() is + // called. + virtual void Capture() override; + + // Blocking decode+playback loop: opens the configured local output + // device, decodes packets pulled from the internal queue (see + // enqueuePacket()) and writes the resulting audio to the device. + // Returns once Close() is called. + virtual void Play() override; + + // Signals a running Capture()/Play() loop to stop and return. Safe to + // call from any thread, and safe to call even if nothing is running. + virtual void Close() override; + +signals: + // One encoded packet produced by Capture(), ready to be sent over the + // network. + void packetReady(QByteArray data); + + void errorOccurred(QString message); + + // Emitted once a device is open, describing the format it settled on. + // Counterpart of VideoDevice::accelerationInUse(). + void deviceFormatInUse(QString description); + + // The capture device is delivering samples pinned at full scale, with the + // share of them in the last window and the peak that was seen. Not an + // error in the errorOccurred() sense - the call carries on - but it wants + // acting on, because nothing downstream can undo it. Numbers rather than + // a message because the receiver drives the gain control with them; see + // AudioVideoCallController::capture_clipping(). + void captureClipping(double pinnedPercent, double peakDb); + +public: + virtual QList<MediaDeviceInfo> Enumerate(enum MediaDeviceStreamDirection dir); + + // Name of the driver to use for one direction of audio. + // + // Two kinds of name come back. A bare name - "alsa", "pulse", "oss" - is + // an FFmpeg libavdevice muxer/demuxer, opened through libavformat the way + // the rest of this codebase opens things. A name starting with + // "platform-" is not an FFmpeg driver at all: what follows the prefix + // names a platform audio API that the caller has to drive itself through + // NativeAudioBackend, because libavdevice cannot express what we need + // from it. + // + // That is how Windows and macOS are handled. Both provide acoustic echo + // cancellation, but only to streams that declare themselves part of a + // voice call - AudioCategory_Communications on WASAPI, the + // VoiceProcessingIO audio unit on CoreAudio - and libavdevice's + // and "audiotoolbox" wrappers have no way to ask for either. Rather than + // open the sound card the plain way and then cancel the echo ourselves on + // platforms that would have done a better job of it below us, we talk to + // those APIs directly. + // + // The direction matters because the answer can differ between them: it is + // the capture side that Windows attaches its processing to, and on Linux + // the two directions can sit on different servers. + static QString PlatformDriverName(enum MediaDeviceStreamDirection dir); + + // True if the driver name is a "platform-<api>" one rather than an FFmpeg + // driver, and the API name out of such a string. + static bool IsPlatformDriver(const QString &driver); + static QString PlatformApiName(const QString &driver); + + // The FFmpeg driver Linux should use, "alsa" or "pulse", from the + // "audio.driver" setting. Meaningless on the other platforms, which have + // exactly one audio API worth using. + // + // The value is cached in a process wide variable rather than read from + // the settings database on demand, because Capture() and Play() run on + // their own threads and a QSqlDatabase connection belongs to the thread + // that opened it. Call the setter from the GUI thread at startup and + // whenever the setting changes. + static void SetLinuxDriverName(const QString &driver); + static QString LinuxDriverName(); + + // Whether anything below us would cancel the acoustic echo, so that + // EchoCancellationPlatform is worth offering at all. + // + // The overload taking a driver answers for that driver rather than the + // configured one, which is what the settings dialog needs: on Linux the + // answer depends on the audio system, and the radio button has to follow + // the combo box before either has been applied. + static bool PlatformEchoCancellationAvailable(const QString &driver); + static bool PlatformEchoCancellationAvailable(); + + // Which of the three cancellers a call should use. Cached in a process + // wide variable for the same reason LinuxDriverName() is - the capture + // and playback loops run on their own threads and cannot reach the + // settings database. Set it from the GUI thread at startup and whenever + // the setting changes. + static void SetEchoCancellation(EchoCancellationMode mode); + static EchoCancellationMode EchoCancellation(); + +private: + QString m_deviceName; + QString m_codec; + int m_sampleRate; + // Capture direction only; see configureCapture(). + int m_bitrate; + + // The call that is allowed to run, set by openSession() and Close(), and + // the one this thread's loop was configured for. + MediaCallSession m_openSession; + QByteArray m_caller_id; + QByteArray m_callee_id; + + // Set by changePlayback(), with the parameters it was given kept under + // m_queueMutex until Play() picks them up. + QAtomicInt m_reconfigure; + QString m_pendingDeviceName; + QString m_pendingCodec; + int m_pendingSampleRate; + + // The call this loop belongs to is over. + bool sessionClosed() const { return !m_openSession.isOpenFor(m_caller_id, m_callee_id); } + // What the loops check: either that, or Play() has to start over with new + // parameters. + bool stopRequested() const { return m_reconfigure.loadRelaxed() || sessionClosed(); } + + // Shared with the other direction of the same call, and held by shared + // pointer because AudioVideoCallController tears a call down without + // joining either thread. + EchoCancellerPtr m_echoCanceller; + + // Watches the microphone for samples pinned at the rail and warns once + // every kLevelReportSec of audio if too many of them are. + // + // Detection only - there is deliberately no gain applied here. Clipping + // happens in the converter, before we see anything, and scaling a clipped + // buffer down just produces a quieter clipped buffer: the flattened peaks, + // the harmonics they generate and the non-linearity that stops the echo + // canceller converging are all still in it. The only fix is less gain + // ahead of the ADC, which means the capture device's own mixer control. + void resetCaptureLevel(); + void checkCaptureLevel(const qint16 *pcm, int nsamples); + + qint64 m_clipCount; + qint64 m_levelCount; + int m_levelPeak; + + // |sample| at or above this counts as pinned. 32512 is -0.13 dBFS: low + // enough to catch a converter that rails slightly short of 0x7fff, high + // enough that ordinary loud speech does not trip it. + static const int kClipThreshold = 32512; + + // Fraction of pinned samples in a window that is worth complaining about, + // in percent. A stray sample at full scale is normal; a twentieth of a + // percent of them is not. + static constexpr double kClipWarnPercent = 0.05; + + static const int kLevelReportSec = 2; + + // The FFmpeg and the native halves of each direction. Which one runs is + // decided by PlatformDriverName(). + void captureFFmpeg(const QString &driver); + void captureNative(const QString &api); + void playFFmpeg(const QString &driver); + void playNative(const QString &api); + + // Jitter buffer for the playback direction: Play() blocks pulling from + // here, enqueuePacket() (called from the controller on delivery of an + // incoming network packet) pushes into it. + QMutex m_queueMutex; + QWaitCondition m_queueCond; + + struct PlaybackPacket + { + quint16 seq; + QByteArray data; + }; + + // Kept ordered by sequence number, oldest first. + QList<PlaybackPacket> m_playQueue; + // Sequence number of the last packet handed to the decoder, once one has + // been; anything not newer than it has missed its turn. + quint16 m_lastPlayedSeq; + bool m_havePlayedSeq; + + // Shared by both playback paths. waitForPreroll() blocks until the jitter + // buffer has a cushion or the call ends; nextPacket() pops the next + // packet, returning false once the loop has to stop. A true return with an + // empty *out is a spurious wakeup - carry on. + void waitForPreroll(); + bool nextPacket(QByteArray *out); + + // Ceiling on the queue, in packets of 20ms each - one second. This is a + // runaway guard, not a latency control: Play() pops as fast as it can and + // the standing latency ends up in the sound card's buffer, not here, so + // the queue only grows when the peer sends a burst or our playback thread + // is not being scheduled. It has to be well clear of kPrerollDepth, + // because overflow is handled by dropping the OLDEST packet + // (enqueuePacket()) - that is, by throwing away audio that was about to + // be played. At the previous value of 8 that was only 160ms, close enough + // to the preroll that ordinary reordering over the direct UDP transport + // could reach it and punch holes in the speech. + static const int kMaxQueueDepth = 50; + + // Number of packets Play() waits to have buffered before writing the + // first one, to build up a cushion against arrival jitter (packets + // this call apart arrive roughly every 20ms - see + // AudioVideoCallController::startAudioPipeline()). + // + // This is standing latency: whatever is prerolled here is audio the + // listener hears that much later, for the whole call. 100ms buys a + // useful margin over the 60ms this used to be while staying inside the + // range where a conversation still feels immediate. + static const int kPrerollDepth = 5; +}; + +#endif // AUDIODEVICE_H diff --git a/pica-client/audioring.h b/pica-client/audioring.h new file mode 100644 index 0000000..cbc987f --- /dev/null +++ b/pica-client/audioring.h @@ -0,0 +1,181 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#ifndef AUDIORING_H +#define AUDIORING_H + +#include <QVector> +#include <QAtomicInt> +#include <cstring> + +// Lock-free single-producer / single-consumer ring of 16 bit samples. +// +// The native audio backends (WASAPI, CoreAudio) deliver and ask for audio +// from a callback running on a real time thread owned by the OS. That thread +// must never block, so it cannot take the same mutex as the AudioDevice +// capture/playback loop it is exchanging samples with. Only two threads ever +// touch one ring - the callback on one end, the AudioDevice loop on the +// other - which is exactly the case this structure is safe for. +// +// Overflow (producer faster than consumer) and underflow (the reverse) are +// both normal in an audio path that has just started or has been starved, so +// they are counted rather than treated as errors: the caller decides whether +// to pad with silence or drop. +class AudioRing +{ +public: + // capacity is in samples and is rounded up to a power of two, so the + // index arithmetic below is a mask rather than a modulo. + explicit AudioRing(int capacity = 48000) + : m_read(0), m_write(0), m_overruns(0), m_underruns(0) + { + int cap = 1; + while (cap < capacity) + cap <<= 1; + m_buf.resize(cap); + m_mask = cap - 1; + } + + void clear() + { + m_read.storeRelease(0); + m_write.storeRelease(0); + m_overruns.storeRelaxed(0); + m_underruns.storeRelaxed(0); + } + + int capacity() const { return m_buf.size(); } + + // Samples waiting to be read. Safe to call from either side; the answer + // is a lower bound for the consumer and an upper bound for the producer, + // which is the direction each of them needs it to be conservative in. + int available() const + { + return m_write.loadAcquire() - m_read.loadAcquire(); + } + + int freeSpace() const { return m_buf.size() - available(); } + + int overruns() const { return m_overruns.loadRelaxed(); } + int underruns() const { return m_underruns.loadRelaxed(); } + + // Producer side. Writes as much as fits and drops the rest, counting one + // overrun if anything had to be dropped. Returns the number written. + int write(const qint16 *src, int nsamples) + { + const int w = m_write.loadRelaxed(); + int space = m_buf.size() - (w - m_read.loadAcquire()); + int n = nsamples < space ? nsamples : space; + + if (n < nsamples) + m_overruns.fetchAndAddRelaxed(1); + + for (int i = 0; i < n; ) + { + int idx = (w + i) & m_mask; + int chunk = m_buf.size() - idx; + if (chunk > n - i) + chunk = n - i; + memcpy(m_buf.data() + idx, src + i, chunk * sizeof(qint16)); + i += chunk; + } + + m_write.storeRelease(w + n); + return n; + } + + // Producer side, for a playback ring the render callback drains: fill + // with nsamples of silence, used to keep the timeline moving when there + // is nothing to play. + int writeSilence(int nsamples) + { + const int w = m_write.loadRelaxed(); + int space = m_buf.size() - (w - m_read.loadAcquire()); + int n = nsamples < space ? nsamples : space; + + for (int i = 0; i < n; ) + { + int idx = (w + i) & m_mask; + int chunk = m_buf.size() - idx; + if (chunk > n - i) + chunk = n - i; + memset(m_buf.data() + idx, 0, chunk * sizeof(qint16)); + i += chunk; + } + + m_write.storeRelease(w + n); + return n; + } + + // Consumer side. Returns the number of samples actually read; the caller + // gets no padding, see readOrSilence() for that. + int read(qint16 *dst, int nsamples) + { + const int r = m_read.loadRelaxed(); + int avail = m_write.loadAcquire() - r; + int n = nsamples < avail ? nsamples : avail; + + if (n < nsamples) + m_underruns.fetchAndAddRelaxed(1); + + for (int i = 0; i < n; ) + { + int idx = (r + i) & m_mask; + int chunk = m_buf.size() - idx; + if (chunk > n - i) + chunk = n - i; + memcpy(dst + i, m_buf.constData() + idx, chunk * sizeof(qint16)); + i += chunk; + } + + m_read.storeRelease(r + n); + return n; + } + + // Consumer side. Always fills the whole buffer, padding the tail with + // silence if the ring ran dry - what an output callback needs, since it + // has to hand back a full buffer no matter what. + void readOrSilence(qint16 *dst, int nsamples) + { + int got = read(dst, nsamples); + if (got < nsamples) + memset(dst + got, 0, (nsamples - got) * sizeof(qint16)); + } + + // Consumer side. Throws away everything older than the newest nsamples, + // used to bound the latency of a ring whose producer has outrun it. + void trimTo(int nsamples) + { + int avail = available(); + if (avail > nsamples) + m_read.fetchAndAddRelease(avail - nsamples); + } + +private: + QVector<qint16> m_buf; + int m_mask; + + // Free running counts of samples read and written. They only ever grow, + // so the difference is the fill level; wrapping at 2^31 samples is a bit + // over 12 hours of a 48kHz call and would cost one bad read at worst. + QAtomicInt m_read; + QAtomicInt m_write; + + QAtomicInt m_overruns; + QAtomicInt m_underruns; +}; + +#endif // AUDIORING_H diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp new file mode 100644 index 0000000..62cb0e0 --- /dev/null +++ b/pica-client/audiovideocallcontroller.cpp @@ -0,0 +1,785 @@ +/* + (c) Copyright 2012 - 2018 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#include "audiovideocallcontroller.h" +#include "globals.h" +#include "skynet.h" +#include "settings.h" +#include "callsettings.h" +#include "accounts.h" +#include <QByteArray> +#include <QDebug> +#include <QMetaObject> + + +AudioVideoCallController::AudioVideoCallController(QObject *parent) + : QObject(parent), callwindow(0), ringdevice(0), m_state(CallIdle), + m_audioPlaybackStarted(false), m_videoPlaybackStarted(false), + m_audioSeq(0), + m_videoSeq(0), m_videoFrameTimestamp(0), m_videoFrameStarted(false), + m_requestedFrameRate(0) +{ + connect(skynet, SIGNAL(IncomingCall(QByteArray)), this, SLOT(call_from(QByteArray))); + connect(skynet, SIGNAL(CallFailed(QByteArray,QString)), this, SLOT(call_failed(QByteArray,QString))); + connect(skynet, SIGNAL(CallAccepted(QByteArray)), this, SLOT(call_accepted(QByteArray))); + connect(skynet, SIGNAL(CallRejected(QByteArray)), this, SLOT(call_rejected(QByteArray))); + connect(skynet, SIGNAL(CallHungup(QByteArray)), this, SLOT(call_hungup(QByteArray))); + connect(skynet, SIGNAL(c2cClosed(QByteArray)), this, SLOT(peer_disconnected(QByteArray))); + + // setEchoCanceller() is invoked through the audio threads' event queues + qRegisterMetaType<EchoCancellerPtr>("EchoCancellerPtr"); + + connect(skynet, SIGNAL(IncomingAudioParams(QByteArray,QString,quint16)), this, SLOT(incoming_audio_params(QByteArray,QString,quint16))); + connect(skynet, SIGNAL(IncomingAudioPacket(QByteArray,quint16,quint32,QByteArray)), this, SLOT(incoming_audio_packet(QByteArray,quint16,quint32,QByteArray))); + + connect(skynet, SIGNAL(IncomingVideoParams(QByteArray,QString,quint16,quint16)), this, SLOT(incoming_video_params(QByteArray,QString,quint16,quint16))); + connect(skynet, SIGNAL(IncomingVideoPacket(QByteArray,quint16,quint32,QByteArray)), this, SLOT(incoming_video_packet(QByteArray,quint16,quint32,QByteArray))); + + connect(skynet, SIGNAL(CallMediaTransportChanged(QByteArray,bool,QString,quint32)), this, SLOT(media_transport_changed(QByteArray,bool,QString,quint32))); + + // Earpiece tones (ringback/busy/unreachable) and the incoming call bell + // are played by two TonePlayer instances, each living on its own + // QThread since TonePlayer::play() blocks the calling thread for the + // duration of the tone sequence. + toneplayer = new TonePlayer(); + toneplayer->moveToThread(&toneplayer_thread); + toneplayer_thread.start(); + + ringtoneplayer = new TonePlayer(); + ringtoneplayer->moveToThread(&ringtoneplayer_thread); + ringtoneplayer_thread.start(); + + // Mic capture+encode and remote-audio decode+playback - same + // one-object-per-thread pattern as the tone players above, since + // AudioDevice::Capture()/Play() block their thread for the call's + // duration too. + microphone = new AudioDevice(); + microphone->moveToThread(µphone_thread); + connect(microphone, SIGNAL(packetReady(QByteArray)), this, SLOT(send_audio_packet(QByteArray))); + + // Queued rather than direct: this crosses from the capture thread, and + // warn_capture_clipping() only logs today but is where a UI notice would + // go. + connect(microphone, SIGNAL(captureClipping(double,double)), this, + SLOT(capture_clipping(double,double)), Qt::QueuedConnection); + microphone_thread.start(); + + output = new AudioDevice(); + output->moveToThread(&output_thread); + output_thread.start(); + + // Camera capture+encode and remote video decode - same arrangement as + // the audio devices above. + cam = new VideoDevice(); + cam->moveToThread(&cam_thread); + connect(cam, SIGNAL(captureStarted(QString,int,int,double)), this, SLOT(video_capture_started(QString,int,int,double))); + connect(cam, SIGNAL(packetReady(QByteArray,bool)), this, SLOT(send_video_packet(QByteArray,bool))); + cam_thread.start(); + + remotevideo = new VideoDevice(); + remotevideo->moveToThread(&remotevideo_thread); + remotevideo_thread.start(); +} + +AudioVideoCallController::~AudioVideoCallController() +{ + stopTones(); + stopAudioPipeline(); + stopVideoPipeline(); + + toneplayer_thread.quit(); + toneplayer_thread.wait(); + delete toneplayer; + + ringtoneplayer_thread.quit(); + ringtoneplayer_thread.wait(); + delete ringtoneplayer; + + microphone_thread.quit(); + microphone_thread.wait(); + delete microphone; + + output_thread.quit(); + output_thread.wait(); + delete output; + + cam_thread.quit(); + cam_thread.wait(); + delete cam; + + remotevideo_thread.quit(); + remotevideo_thread.wait(); + delete remotevideo; +} + +void AudioVideoCallController::playEarpieceTone(void (TonePlayer::*tone)()) +{ + Settings st(config_dbname); + QString dev = st.loadValue("audio.playback_device", "default").toString(); + + toneplayer->stop(); + QMetaObject::invokeMethod(toneplayer, "setDeviceName", Qt::QueuedConnection, Q_ARG(QString, dev)); + if (tone == &TonePlayer::playCallInProgress) + QMetaObject::invokeMethod(toneplayer, "playCallInProgress", Qt::QueuedConnection); + else if (tone == &TonePlayer::playUnreachable) + QMetaObject::invokeMethod(toneplayer, "playUnreachable", Qt::QueuedConnection); + else if (tone == &TonePlayer::playBusy) + QMetaObject::invokeMethod(toneplayer, "playBusy", Qt::QueuedConnection); +} + +void AudioVideoCallController::playRingTone() +{ + Settings st(config_dbname); + QString dev = st.loadValue("audio.ring_device", "default").toString(); + + ringtoneplayer->stop(); + QMetaObject::invokeMethod(ringtoneplayer, "setDeviceName", Qt::QueuedConnection, Q_ARG(QString, dev)); + QMetaObject::invokeMethod(ringtoneplayer, "playClassicRingtone", Qt::QueuedConnection); +} + +void AudioVideoCallController::stopTones() +{ + toneplayer->stop(); + ringtoneplayer->stop(); +} + +void AudioVideoCallController::startAudioPipeline() +{ + Settings st(config_dbname); + QString capDev = st.loadValue("audio.capture_device", "default").toString(); + const CallSettings cs = CallSettings::load(); + + // What we capture and encode at, announced to the peer in the 0x74 + // message. It follows from the codec - see callAudioSampleRate(). + // + // The playback direction is NOT this: it follows whatever the peer + // announces in its own 0x74 (see incoming_audio_params()), so a call with + // a peer that picked a different codec or rate keeps working. + const int sampleRate = callAudioSampleRate(cs.audioCodec); + + // G.722 and A-law spend a fixed number of bits per sample and have no rate + // to ask for; the setting only means anything to Opus. + const int bitrate = callAudioBitrateAdjustable(cs.audioCodec) + ? cs.audioBitrateKbps * 1000 + : 0; + + m_audioSeq = 0; + m_callClock.start(); + m_audioPlaybackStarted = false; + + // Before anything is queued for them - see MediaCallSession. output is + // opened here as well, although it is only started once the peer's 0x74 + // arrives. + microphone->openSession(m_caller_id, m_callee_id); + output->openSession(m_caller_id, m_callee_id); + + // One canceller for the call, shared by both directions: the playback + // side feeds it what it is about to play, the capture side subtracts the + // echo of that from the microphone. Ownership is shared because + // stopAudioPipeline() does not join either thread, so this has to outlive + // whichever of them returns last. + // + // Only for EchoCancellationOwn. The other two settings mean something + // below us is doing the job or nobody is, and either way running this as + // well would only take a second bite out of the speech - the devices are + // opened accordingly, see AudioDevice::captureNative(). + // + // Built at the rate the codec runs at rather than at a fixed one, so that + // choosing a codec does not quietly switch cancellation off: the capture + // side drops a canceller whose rate does not match its own. + if (AudioDevice::EchoCancellation() == EchoCancellationOwn) + m_echoCanceller = EchoCancellerPtr(new EchoCanceller(sampleRate)); + else + m_echoCanceller.clear(); + + if (m_echoCanceller && !m_echoCanceller->isValid()) + m_echoCanceller.clear(); + + // Queued like the calls that start the loops, and ahead of them: the + // loops of the previous call may still be on their way out, and they read + // the canceller they were given on their own threads. + QMetaObject::invokeMethod(microphone, "setEchoCanceller", Qt::QueuedConnection, + Q_ARG(EchoCancellerPtr, m_echoCanceller)); + QMetaObject::invokeMethod(output, "setEchoCanceller", Qt::QueuedConnection, + Q_ARG(EchoCancellerPtr, m_echoCanceller)); + + // Declare our outgoing codec to the peer, then start capturing and + // encoding right away - the peer's decoder is only ready once it has + // processed this 0x74 message, but since the call is carried over TCP, + // packets sent immediately after are guaranteed to arrive after it. + skynet->SendAudioParams(m_peer_id, cs.audioCodec, (quint16)sampleRate); + + QMetaObject::invokeMethod(microphone, "configureCapture", Qt::QueuedConnection, + Q_ARG(QString, capDev), Q_ARG(QString, cs.audioCodec), + Q_ARG(int, sampleRate), Q_ARG(int, bitrate), + Q_ARG(QByteArray, m_caller_id), Q_ARG(QByteArray, m_callee_id)); + QMetaObject::invokeMethod(microphone, "Capture", Qt::QueuedConnection); + + // output is configured lazily, once the peer's own 0x74 (see + // incoming_audio_params()) tells us what codec/rate it is sending. +} + +void AudioVideoCallController::stopAudioPipeline() +{ + // Close() only touches a QAtomicInt and wakes a QWaitCondition, both + // safe to reach from any thread - it must be called directly rather + // than via invokeMethod()/QueuedConnection: microphone/output's own + // thread is blocked inside Capture()/Play() for the call's duration, + // so its event loop cannot deliver a queued call back to itself until + // that blocking call returns - which is exactly what Close() is + // supposed to make happen. Routing it through the event queue would + // deadlock (the thread would never quit, and the app would hang on + // exit after a call). + microphone->Close(); + output->Close(); + + // Drop our reference. The two audio threads still hold theirs until they + // come out of Capture()/Play(), and the canceller goes away with the last + // of them. + m_echoCanceller.clear(); +} + +void AudioVideoCallController::startVideoPipeline() +{ + Settings st(config_dbname); + QString camDev = st.loadValue("video.capture_device", QString()).toString(); + const CallSettings cs = CallSettings::load(); + + // Before anything is queued for them - see MediaCallSession. And before + // the check for a camera below: remotevideo does not depend on having one. + m_videoPlaybackStarted = false; + cam->openSession(m_caller_id, m_callee_id); + remotevideo->openSession(m_caller_id, m_callee_id); + + // Unlike the audio devices, which fall back to the platform's "default" + // device, there is no such name for cameras - so with nothing configured + // yet (the setting is only written once the settings dialog has been + // visited) pick the first camera found. + if (camDev.isEmpty()) + { + VideoDevice enumerator; + QList<MediaDeviceInfo> cams = enumerator.Enumerate(CAPTURE); + + if (!cams.isEmpty()) + camDev = cams.first().device; + } + + // No camera at all - the call simply carries no outgoing video. Incoming + // video is unaffected, it only depends on what the peer sends. + if (camDev.isEmpty()) + return; + + m_videoSeq = 0; + m_videoFrameTimestamp = 0; + m_videoFrameStarted = false; + + // Datagram sized from the start, even though the call begins on the c2c + // connection where a 0x77 message could hold far more: a media connection + // may come up at any moment during the call, and frames whose fragments + // were cut before that would not fit into a datagram. Over TCP this only + // costs a few more message headers. + cam->setMaxFragmentSize(PICA_MEDIA_SAFE_PAYLOAD); + + bool preferCompressed = st.loadValue("video.prefer_compressed", 0).toBool(); + + // Kept so that video_capture_started() can tell whether the camera + // honoured it, which is not something the camera reports. + m_requestedFrameRate = cs.captureFrameRate; + + // The peer is told what we are sending only once the camera is open and + // the format is settled - with a compressed camera stream being forwarded + // as-is, the codec is the camera's choice, not ours (see + // video_capture_started()). + QMetaObject::invokeMethod(cam, "configureCapture", Qt::QueuedConnection, + Q_ARG(QString, camDev), + Q_ARG(int, cs.captureWidth), Q_ARG(int, cs.captureHeight), + Q_ARG(int, cs.captureFrameRate), + Q_ARG(bool, preferCompressed), + Q_ARG(QString, cs.videoCodec), Q_ARG(int, cs.videoBitrateKbps * 1000), + Q_ARG(int, cs.videoEncodingAcceleration), + Q_ARG(QByteArray, m_caller_id), Q_ARG(QByteArray, m_callee_id)); + QMetaObject::invokeMethod(cam, "Capture", Qt::QueuedConnection); + + // remotevideo is configured lazily, once the peer's own 0x75 (see + // incoming_video_params()) tells us what it is sending. +} + +void AudioVideoCallController::stopVideoPipeline() +{ + // Direct calls, for the same reason stopAudioPipeline() uses them. + cam->Close(); + remotevideo->Close(); + + m_videoAssembler.reset(); +} + +void AudioVideoCallController::finishCall(bool notify_peer) +{ + const CallState state = m_state; + + m_state = CallIdle; + + stopTones(); + stopAudioPipeline(); + stopVideoPipeline(); + + if (!notify_peer) + return; + + if (state == CallDialing || state == CallActive) + skynet->HangupCall(m_peer_id); + else if (state == CallRinging) + skynet->RejectCall(m_peer_id); +} + +void AudioVideoCallController::call_failed(QByteArray peer_id, QString reason) +{ + qDebug() << "Call failed: " << reason << "\n"; + + /* Only starting a call and answering one can fail in a way that matters + here; anything else arrives when the call is already over. */ + if (peer_id != m_peer_id || (m_state != CallDialing && m_state != CallActive)) + return; + + const bool was_active = (m_state == CallActive); + + finishCall(false); + + /* After a failed attempt to call the window is left as it is, so that + "Call" can be pressed again. */ + if (was_active && callwindow) + callwindow->call_ended(); + + /* play unreachable */ + playEarpieceTone(&TonePlayer::playUnreachable); +} + +void AudioVideoCallController::call_accepted(QByteArray peer_id) +{ + /* SkyNet lives in its own thread, so this signal is queued: by the time + it is delivered the local side may have already hung up and closed the + call window, or moved on to a different peer entirely. Either way the + call it refers to is gone - do not bring the audio pipeline up for it. */ + if (peer_id != m_peer_id || m_state != CallDialing || !callwindow) + return; + + stopTones(); + m_state = CallActive; + callwindow->call_started(); + startAudioPipeline(); + startVideoPipeline(); +} + +void AudioVideoCallController::call_rejected(QByteArray peer_id) +{ + if (peer_id != m_peer_id || m_state != CallDialing) + return; + + finishCall(false); + + /* play busy tone */ + playEarpieceTone(&TonePlayer::playBusy); +} + +void AudioVideoCallController::call_hungup(QByteArray peer_id) +{ + /* queued from the SkyNet thread - the call may already be over here */ + if (peer_id != m_peer_id || m_state == CallIdle) + return; + + const bool was_ringing = (m_state == CallRinging); + + finishCall(false); + + if (was_ringing) + { + /* The caller gave up before the call was answered. Nothing is left + for the window to offer. */ + if (callwindow) + callwindow->close(); + + return; + } + + if (callwindow) + callwindow->call_ended(); + + /* play busy tone */ + playEarpieceTone(&TonePlayer::playBusy); +} + +void AudioVideoCallController::peer_disconnected(QByteArray peer_id) +{ + if (peer_id != m_peer_id || m_state == CallIdle) + return; + + if (m_state == CallDialing) + { + finishCall(false); + playEarpieceTone(&TonePlayer::playUnreachable); + return; + } + + /* No hangup message is going to come over a connection that is gone, and + for the call it amounts to the same thing. */ + call_hungup(peer_id); +} + +void AudioVideoCallController::start_call(QByteArray peer_id) +{ + if (callwindow) + { + callwindow->show(); + + /* one call at a time, and this one is not over yet */ + if (m_state != CallIdle) + { + callwindow->raise(); + return; + } + + /* re-create callwindow for a new call */ + callwindow->close(); + } + + m_peer_id = peer_id; + m_caller_id = Accounts::GetCurrentAccount().id; + m_callee_id = peer_id; + callwindow = new CallWindow(peer_id, false); + connect(callwindow, SIGNAL(start_call_pressed()), this, SLOT(initiate_call())); + connect(callwindow, SIGNAL(hang_call_pressed()), this, SLOT(end_call())); + connect(callwindow, SIGNAL(callwindow_closed(CallWindow*)), this, SLOT(callwindow_closed(CallWindow*))); + /* decoded frames arrive from remotevideo's thread, so this is a queued + connection; it dies with the window, which is deleted on close */ + connect(remotevideo, SIGNAL(frameReady(QImage)), callwindow, SLOT(showRemoteFrame(QImage))); + connect(callwindow, SIGNAL(video_area_changed(QSize)), this, SLOT(video_area_changed(QSize))); +#ifdef HAVE_VAAPI + connect(remotevideo, SIGNAL(hwFrameReady(AVFramePtr)), callwindow, SLOT(showRemoteHwFrame(AVFramePtr))); + connect(callwindow, SIGNAL(video_rendering_failed()), this, SLOT(video_rendering_failed())); +#endif + callwindow->show(); +} + +void AudioVideoCallController::call_from(QByteArray peer_id) +{ + /* One call at a time: busy. The peer hears the busy tone and our own call + is not disturbed. */ + if (m_state != CallIdle) + { + skynet->RejectCall(peer_id); + return; + } + + /* A window left open with no call in it - one where "Call" has not been + pressed, or whose call is over - gives way to the incoming call. */ + if (callwindow) + callwindow->close(); + + m_state = CallRinging; + m_peer_id = peer_id; + m_caller_id = peer_id; + m_callee_id = Accounts::GetCurrentAccount().id; + callwindow = new CallWindow(peer_id, true); + connect(callwindow, SIGNAL(accept_call_pressed()), this, SLOT(accept_call())); + connect(callwindow, SIGNAL(hang_call_pressed()), this, SLOT(end_call())); + connect(callwindow, SIGNAL(callwindow_closed(CallWindow*)), this, SLOT(callwindow_closed(CallWindow*))); + /* see the same connections in start_call() */ + connect(remotevideo, SIGNAL(frameReady(QImage)), callwindow, SLOT(showRemoteFrame(QImage))); + connect(callwindow, SIGNAL(video_area_changed(QSize)), this, SLOT(video_area_changed(QSize))); +#ifdef HAVE_VAAPI + connect(remotevideo, SIGNAL(hwFrameReady(AVFramePtr)), callwindow, SLOT(showRemoteHwFrame(AVFramePtr))); + connect(callwindow, SIGNAL(video_rendering_failed()), this, SLOT(video_rendering_failed())); +#endif + callwindow->show(); + + /* play ring tone */ + playRingTone(); +} + +void AudioVideoCallController::initiate_call() +{ + /* "Call" pressed again while the first press is still ringing */ + if (m_state != CallIdle) + return; + + m_state = CallDialing; + skynet->StartCall(m_peer_id); + /* play ringing tone */ + playEarpieceTone(&TonePlayer::playCallInProgress); +} + +void AudioVideoCallController::accept_call() +{ + if (m_state != CallRinging) + return; + + stopTones(); + skynet->AcceptCall(m_peer_id); + m_state = CallActive; + callwindow->call_started(); + startAudioPipeline(); + startVideoPipeline(); +} + +void AudioVideoCallController::end_call() +{ + /* the call ends with its window, see callwindow_closed() */ + if (callwindow) + callwindow->close(); +} + +void AudioVideoCallController::callwindow_closed(CallWindow *sender_window) +{ + if (sender_window != callwindow) + return; + + /* However the window got closed - "Hang Up", its close button, or being + replaced for a new call - whatever call was in it goes with it. */ + finishCall(true); + callwindow = 0; +} + +void AudioVideoCallController::send_audio_packet(QByteArray data) +{ + if (m_state != CallActive) + return; + + quint16 seq = m_audioSeq++; + quint32 timestamp = (quint32)m_callClock.elapsed(); + + skynet->SendAudioPacket(m_peer_id, seq, timestamp, data); +} + +// Rate limited by AudioDevice, which reports at most once every couple of +// seconds of audio, so this can log unconditionally. +// +// Only a warning, and deliberately: clipping happens in the converter, before +// anything here sees a sample, so nothing in this process can undo it. The +// fix is less gain ahead of the ADC, which is the capture device's own mixer +// control and the user's to set. +void AudioVideoCallController::capture_clipping(double pinnedPercent, double peakDb) +{ + qWarning("Microphone is clipping: %.2f%% of samples at full scale, peak %.1f dBFS - " + "turn the recording level down, it distorts the speech and stops the echo " + "canceller converging", + pinnedPercent, peakDb); +} + + +void AudioVideoCallController::incoming_audio_params(QByteArray peer_id, QString codec, quint16 sample_rate) +{ + if (m_state != CallActive || peer_id != m_peer_id) + return; + + // The codec name is peer-supplied and would otherwise be handed straight + // to the FFmpeg decoder - accept only the ones the client itself sends. + if (!callAudioCodecAccepted(codec)) + { + qWarning() << "rejecting unsupported call audio codec from peer:" << codec; + return; + } + + Settings st(config_dbname); + QString playDev = st.loadValue("audio.playback_device", "default").toString(); + + if (!m_audioPlaybackStarted) + { + m_audioPlaybackStarted = true; + QMetaObject::invokeMethod(output, "configurePlayback", Qt::QueuedConnection, + Q_ARG(QString, playDev), Q_ARG(QString, codec), Q_ARG(int, (int)sample_rate), + Q_ARG(QByteArray, m_caller_id), Q_ARG(QByteArray, m_callee_id)); + } + else + { + // The peer changed what it is sending in the middle of the call. + // Direct call, not invokeMethod()/QueuedConnection - see the comment + // in stopAudioPipeline(): output's thread is blocked inside Play(), + // which starts over with the new parameters. + output->changePlayback(playDev, codec, (int)sample_rate); + } + + // Queued in both cases. If Play() is running, this one only gets its turn + // when the call is over and returns at once; but if Play() has given up - + // on a codec that would not open, say - this is what starts it again for + // the new parameters. + QMetaObject::invokeMethod(output, "Play", Qt::QueuedConnection); +} + +void AudioVideoCallController::incoming_audio_packet(QByteArray peer_id, quint16 seq_num, quint32 timestamp, QByteArray data) +{ + Q_UNUSED(timestamp); + + if (m_state != CallActive || peer_id != m_peer_id) + return; + + // Direct call, not invokeMethod()/QueuedConnection - see the comment in + // stopAudioPipeline(). enqueuePacket() is mutex-protected and safe to + // call from any thread; queuing it behind output's own blocking Play() + // call would mean it's never delivered, and Play() would sit forever + // pulling from an empty jitter buffer. + output->enqueuePacket(seq_num, data); +} + +void AudioVideoCallController::video_capture_started(QString codec, int width, int height, + double frameRate) +{ + if (m_state != CallActive) + return; + + // Logged rather than announced: the 0x74 message has no field for it, and + // the peer does not need one - every frame carries its own timestamp. It + // is worth a line in the log all the same, since a camera that quietly + // substituted a lower rate than was asked for is otherwise invisible from + // the other end of a complaint about choppy video. + if (frameRate > 0.0 && frameRate < m_requestedFrameRate - 0.5) + qWarning() << QString("Camera delivering %1 fps, not the %2 that was requested") + .arg(frameRate, 0, 'f', 1).arg(m_requestedFrameRate); + + // Announced only now, because what the camera turned out to deliver + // decides it: a compressed camera stream is forwarded in the camera's own + // codec and at the camera's own size, rather than in ours. + skynet->SendVideoParams(m_peer_id, codec, (quint16)width, (quint16)height); +} + +void AudioVideoCallController::send_video_packet(QByteArray data, bool is_last_fragment) +{ + if (m_state != CallActive) + return; + + // Every fragment of one encoded frame carries the timestamp taken when + // that frame's first fragment was sent, so the receiving side can tell + // the fragments of one frame from those of the next. + if (!m_videoFrameStarted) + { + m_videoFrameTimestamp = (quint32)m_callClock.elapsed(); + m_videoFrameStarted = true; + } + + quint16 seq = m_videoSeq & VideoFrameAssembler::SeqNumMask; + m_videoSeq = (m_videoSeq + 1) & VideoFrameAssembler::SeqNumMask; + + if (is_last_fragment) + { + seq |= VideoFrameAssembler::LastFragmentFlag; + // The next fragment emitted belongs to a new frame. + m_videoFrameStarted = false; + } + + skynet->SendVideoPacket(m_peer_id, seq, m_videoFrameTimestamp, data); +} + +void AudioVideoCallController::media_transport_changed(QByteArray peer_id, bool direct_udp, QString ciphersuitename, quint32 max_payload) +{ + if (peer_id != m_peer_id) + return; + + // Fragments stay datagram sized for the whole call (see + // startVideoPipeline()); this only lowers the size further, for when the + // media connection turns out to carry less than was assumed. Direct call, + // not invokeMethod()/QueuedConnection - see the comment in + // stopAudioPipeline(): cam's thread is blocked inside Capture(). + cam->setMaxFragmentSize(qMin((int)max_payload, (int)PICA_MEDIA_SAFE_PAYLOAD)); + + if (callwindow) + callwindow->setMediaTransport(direct_udp, ciphersuitename); + + qDebug() << "call media transport:" << (direct_udp ? "direct UDP/DTLS" : "c2c connection") + << ciphersuitename << "max payload" << max_payload; +} + +void AudioVideoCallController::incoming_video_params(QByteArray peer_id, QString codec, quint16 width, quint16 height) +{ + if (m_state != CallActive || peer_id != m_peer_id) + return; + + // As in incoming_audio_params(): the peer-supplied codec name must be one + // we actually send before it reaches avcodec_find_decoder_by_name(). + if (!callVideoCodecAccepted(codec)) + { + qWarning() << "rejecting unsupported call video codec from peer:" << codec; + return; + } + + Settings st(config_dbname); + const CallSettings cs = CallSettings::load(); + bool vaapiRendering = st.loadValue("video.vaapi_rendering", 0).toBool(); + +#ifdef HAVE_VAAPI + // A call started after one where drawing GPU frames turned out not to work + // would otherwise begin with a blank video area all over again. + if (VaapiRenderWidget::renderingKnownBroken()) + vaapiRendering = false; +#endif + + if (!m_videoPlaybackStarted) + { + m_videoPlaybackStarted = true; + QMetaObject::invokeMethod(remotevideo, "configurePlayback", Qt::QueuedConnection, + Q_ARG(QString, codec), Q_ARG(int, (int)width), Q_ARG(int, (int)height), + Q_ARG(int, cs.videoDecodingAcceleration), Q_ARG(bool, vaapiRendering), + Q_ARG(QByteArray, m_caller_id), Q_ARG(QByteArray, m_callee_id)); + } + else + { + // The peer changed what it is sending in the middle of the call - as + // in incoming_audio_params(). A fragment of a frame in the old format + // that is still being put together is of no use to the new decoder. + m_videoAssembler.reset(); + remotevideo->changePlayback(codec, (int)width, (int)height, + cs.videoDecodingAcceleration, vaapiRendering); + } + + // Queued in both cases, see incoming_audio_params(). + QMetaObject::invokeMethod(remotevideo, "Play", Qt::QueuedConnection); +} + +void AudioVideoCallController::incoming_video_packet(QByteArray peer_id, quint16 seq_num, quint32 timestamp, QByteArray data) +{ + if (m_state != CallActive || peer_id != m_peer_id) + return; + + QByteArray frame = m_videoAssembler.addFragment(seq_num, timestamp, data); + + // Still waiting for the rest of this frame's fragments. + if (frame.isEmpty()) + return; + + // Direct call, not invokeMethod()/QueuedConnection - same reason as in + // incoming_audio_packet(). + remotevideo->enqueueFrame(frame); +} + +void AudioVideoCallController::video_area_changed(QSize area) +{ + // Direct call rather than invokeMethod() - same reason as in + // incoming_video_packet(): remotevideo's thread is blocked inside Play(). + remotevideo->setDisplaySize(area); +} + +#ifdef HAVE_VAAPI +void AudioVideoCallController::video_rendering_failed() +{ + // The window cannot draw frames that stayed in GPU memory, so stop keeping + // them there: the decoder brings them down into system memory instead and + // the window's label shows them. Decoding itself is unaffected and the + // call carries on. + // + // Direct call rather than invokeMethod() - same reason as in + // incoming_video_packet(): remotevideo's thread is blocked inside Play(). + remotevideo->disableHardwareRendering(); +} +#endif + diff --git a/pica-client/audiovideocallcontroller.h b/pica-client/audiovideocallcontroller.h new file mode 100644 index 0000000..ae1d422 --- /dev/null +++ b/pica-client/audiovideocallcontroller.h @@ -0,0 +1,177 @@ +/* + (c) Copyright 2012 - 2021 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#ifndef AUDIOVIDEOCALLCONTROLLER_H +#define AUDIOVIDEOCALLCONTROLLER_H + +#include <QObject> +#include <QThread> +#include <QElapsedTimer> +#include "callwindow.h" +#include "audiodevice.h" +#include "videodevice.h" +#include "toneplayer/toneplayer.h" + +class AudioVideoCallController : public QObject +{ + Q_OBJECT +public: + explicit AudioVideoCallController(QObject *parent = nullptr); + ~AudioVideoCallController(); + // is call active (i.e. are voice/video packets exchanged now) + bool const isActive() {return m_state == CallActive;} + void processCall(); +public slots: + void start_call(QByteArray peer_id); + void call_from(QByteArray peer_id); + void call_failed(QByteArray peer_id, QString reason); + void call_accepted(QByteArray peer_id); + void call_rejected(QByteArray peer_id); + void call_hungup(QByteArray peer_id); + // the connection to the peer is gone, and whatever call it carried with it + void peer_disconnected(QByteArray peer_id); +signals: +private: + // There is one call at a time. While it is anything but CallIdle, calls + // coming in from other peers are rejected and the user cannot start + // another one. + enum CallState + { + // No call. The window may still be open: before "Call" is pressed, and + // after a call that failed, was rejected or was ended by the peer. + CallIdle, + // We are calling, the peer has not answered yet. + CallDialing, + // The peer is calling, we have not answered yet. + CallRinging, + // Answered - audio/video packets are being exchanged. + CallActive + }; + + CallWindow *callwindow; + AudioDevice *ringdevice; + AudioDevice *microphone; + AudioDevice *output; + // Local camera capture+encode. + VideoDevice *cam; + // Decoding of the video stream received from the peer. + VideoDevice *remotevideo; + CallState m_state; + QByteArray m_peer_id; + // What identifies the call: who started it and who was called, one of them + // being m_peer_id and the other this account. The media devices only run + // for the call they were started for - see MediaCallSession. + QByteArray m_caller_id; + QByteArray m_callee_id; + + // Whether output/remotevideo have been started for the peer's first + // 0x74/0x75 of this call. The ones after it change the parameters of a + // decoder that is already running. + bool m_audioPlaybackStarted; + bool m_videoPlaybackStarted; + + // Earpiece tones (ringback, busy, special information/unreachable), + // played through the "audio.playback_device" setting. + TonePlayer *toneplayer; + QThread toneplayer_thread; + + // Incoming call bell, played through the "audio.ring_device" setting. + TonePlayer *ringtoneplayer; + QThread ringtoneplayer_thread; + + // Mic capture+encode and remote-audio decode+playback, each blocking + // its own thread for the duration of the call (see AudioDevice). + QThread microphone_thread; + QThread output_thread; + + // Camera capture+encode and remote-video decode, same arrangement as + // the audio devices above (see VideoDevice). + QThread cam_thread; + QThread remotevideo_thread; + + // Acoustic echo cancellation for the current call, shared by microphone + // and output. Null unless the "audio.echo_cancellation" setting is + // EchoCancellationOwn, and between calls. + EchoCancellerPtr m_echoCanceller; + + // Sequence number / capture-clock timestamp stamped onto outgoing + // 0x76 audio packets (see PICA_PROTO_CALL_PACKET_HDRSIZE). + quint16 m_audioSeq; + QElapsedTimer m_callClock; + + // Outgoing 0x77 video packets. The counter occupies the low 15 bits of + // the wire sequence number, the top bit being the last fragment marker. + // All fragments of one encoded frame share m_videoFrameTimestamp, which + // is re-read from m_callClock only when a new frame starts - tracked by + // m_videoFrameStarted, set false again after emitting a last fragment. + quint16 m_videoSeq; + quint32 m_videoFrameTimestamp; + bool m_videoFrameStarted; + + // Reassembly of incoming 0x77 fragments into whole encoded frames. + VideoFrameAssembler m_videoAssembler; + + // The capture frame rate this call asked the camera for, so that + // video_capture_started() can say when the camera delivered less. Zero + // before the video pipeline has been started. + int m_requestedFrameRate; + + void playEarpieceTone(void (TonePlayer::*tone)()); + void playRingTone(); + void stopTones(); + + void startAudioPipeline(); + void stopAudioPipeline(); + + void startVideoPipeline(); + void stopVideoPipeline(); + + // The one way out of a call, whichever state it is in and whoever ends it: + // stops the tones and the media devices and leaves the state CallIdle. + // With notify_peer the peer is told as well, in the way the state calls + // for - a hangup for a call we started or answered, a reject for one that + // is still ringing here. + void finishCall(bool notify_peer); + +private slots: + // button handlers + void initiate_call(); + void accept_call(); + void end_call(); + void callwindow_closed(CallWindow *sender_window); + + void send_audio_packet(QByteArray data); + void incoming_audio_params(QByteArray peer_id, QString codec, quint16 sample_rate); + void capture_clipping(double pinnedPercent, double peakDb); + void incoming_audio_packet(QByteArray peer_id, quint16 seq_num, quint32 timestamp, QByteArray data); + + void video_capture_started(QString codec, int width, int height, double frameRate); + void send_video_packet(QByteArray data, bool is_last_fragment); + void incoming_video_params(QByteArray peer_id, QString codec, quint16 width, quint16 height); + void incoming_video_packet(QByteArray peer_id, quint16 seq_num, quint32 timestamp, QByteArray data); + + void media_transport_changed(QByteArray peer_id, bool direct_udp, QString ciphersuitename, quint32 max_payload); + + // Passes the window's video area on to the decoder, which produces frames + // at that size rather than leaving the window to resize each one. + void video_area_changed(QSize area); +#ifdef HAVE_VAAPI + void video_rendering_failed(); +#endif + +}; + +#endif // AUDIOVIDEOCALLCONTROLLER_H diff --git a/pica-client/callsettings.cpp b/pica-client/callsettings.cpp new file mode 100644 index 0000000..dff72f4 --- /dev/null +++ b/pica-client/callsettings.cpp @@ -0,0 +1,172 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#include "callsettings.h" +#include "settings.h" +#include "globals.h" + +const CallCodecInfo kCallVideoCodecs[] = +{ + { "h264", "H.264" }, + { "hevc", "H.265/HEVC" }, + { "vp9", "VP9" } +}; + +const int kCallVideoCodecCount = sizeof(kCallVideoCodecs) / sizeof(kCallVideoCodecs[0]); + +const CallCodecInfo kCallAudioCodecs[] = +{ + { "opus", "Opus" }, + { "adpcm_g722", "G.722" }, + { "pcm_alaw", "G.711 A-law" } +}; + +const int kCallAudioCodecCount = sizeof(kCallAudioCodecs) / sizeof(kCallAudioCodecs[0]); + +bool callAudioCodecAccepted(const QString &codec) +{ + for (int i = 0; i < kCallAudioCodecCount; i++) + if (codec == QLatin1String(kCallAudioCodecs[i].name)) + return true; + + return false; +} + +bool callVideoCodecAccepted(const QString &codec) +{ + for (int i = 0; i < kCallVideoCodecCount; i++) + if (codec == QLatin1String(kCallVideoCodecs[i].name)) + return true; + + // A camera's own compressed stream is forwarded untouched, so a sender may + // legitimately name a capture format that is not in the encode list. + if (codec == QLatin1String("mjpeg")) + return true; + + return false; +} + +int callAudioSampleRate(const QString &codec) +{ + // G.722 is a 16kHz codec by definition - it subband-codes a 7kHz audio + // bandwidth and there is no other rate to run it at. + if (codec == QLatin1String("adpcm_g722")) + return 16000; + + // A-law is the telephone network's codec and 8kHz is what it is for. + // Running it at anything else would only spend twice the bandwidth on a + // codec chosen for costing as little as possible. + if (codec == QLatin1String("pcm_alaw")) + return 8000; + + // Opus, and anything unrecognised: 16kHz rather than 48kHz because it is + // what the echo canceller wants. AEC3 does its filtering in the 0-8kHz + // band whatever it is handed; at 48kHz it splits the signal into four + // bands, cancels in the lowest and gates the rest, which is more work for + // a result that is no better on speech. + // + // Costs nothing worth having for speech: Opus codes this as wideband, an + // 8kHz audio bandwidth, which is well past telephone quality and past + // where voice intelligibility stops improving. + // + // Note that this is the capture direction only. Playback follows whatever + // the peer announced in its own 0x74 message (see + // AudioVideoCallController::incoming_audio_params()), so a call with a + // peer that picked a different codec or rate keeps working. + return 16000; +} + +bool callAudioBitrateAdjustable(const QString &codec) +{ + // Opus is the only one of the three with a rate control worth the name; + // the other two are fixed bits per sample. + return codec == QLatin1String("opus") || codec.isEmpty(); +} + +int callAudioFixedBitrateKbps(const QString &codec) +{ + // G.722 is 4 bits per sample at 16kHz, A-law 8 bits per sample at 8kHz - + // 64 kbit/s either way, which is no coincidence. + if (codec == QLatin1String("adpcm_g722")) + return 16000 * 4 / 1000; + + if (codec == QLatin1String("pcm_alaw")) + return 8000 * 8 / 1000; + + return kDefaultAudioBitrateKbps; +} + +CallSettings CallSettings::load() +{ + Settings st(config_dbname); + CallSettings cs; + + cs.videoCodec = st.loadValue("call.video_codec", QLatin1String(kCallVideoCodecs[0].name)).toString(); + cs.audioCodec = st.loadValue("call.audio_codec", QLatin1String(kCallAudioCodecs[0].name)).toString(); + + cs.videoBitrateKbps = st.loadValue("call.video_bitrate_kbps", kDefaultVideoBitrateKbps).toInt(); + cs.audioBitrateKbps = st.loadValue("call.audio_bitrate_kbps", kDefaultAudioBitrateKbps).toInt(); + + cs.captureWidth = st.loadValue("video.capture_width", kDefaultCaptureWidth).toInt(); + cs.captureHeight = st.loadValue("video.capture_height", kDefaultCaptureHeight).toInt(); + cs.captureFrameRate = st.loadValue("video.capture_framerate", kDefaultCaptureFrameRate).toInt(); + + // Only the keys this build has checkboxes for: a database carried over + // from another platform must not switch on a path that cannot exist here. + cs.videoEncodingAcceleration = 0; + cs.videoDecodingAcceleration = 0; +#ifdef HAVE_VAAPI + if (st.loadValue("video.vaapi_encoding", 0).toBool()) + cs.videoEncodingAcceleration |= VideoAccelerationVaapi; + if (st.loadValue("video.vaapi_decoding", 0).toBool()) + cs.videoDecodingAcceleration |= VideoAccelerationVaapi; +#endif +#ifdef HAVE_D3D12VA + if (st.loadValue("video.d3d12va_encoding", 0).toBool()) + cs.videoEncodingAcceleration |= VideoAccelerationD3d12va; + if (st.loadValue("video.d3d12va_decoding", 0).toBool()) + cs.videoDecodingAcceleration |= VideoAccelerationD3d12va; +#endif +#ifdef Q_OS_WIN + if (st.loadValue("video.mediafoundation_encoding", 0).toBool()) + cs.videoEncodingAcceleration |= VideoAccelerationMediaFoundation; + if (st.loadValue("video.d3d11va_decoding", 0).toBool()) + cs.videoDecodingAcceleration |= VideoAccelerationD3d11va; + if (st.loadValue("video.dxva2_decoding", 0).toBool()) + cs.videoDecodingAcceleration |= VideoAccelerationDxva2; +#endif + + // A stored value that makes no sense - a hand-edited database, or a + // setting written by a build that offered something this one does not - + // would otherwise be passed to the encoder and fail the call rather than + // the setting. + if (cs.videoBitrateKbps <= 0) + cs.videoBitrateKbps = kDefaultVideoBitrateKbps; + + if (cs.audioBitrateKbps <= 0) + cs.audioBitrateKbps = kDefaultAudioBitrateKbps; + + if (cs.captureWidth <= 0 || cs.captureHeight <= 0) + { + cs.captureWidth = kDefaultCaptureWidth; + cs.captureHeight = kDefaultCaptureHeight; + } + + if (cs.captureFrameRate <= 0) + cs.captureFrameRate = kDefaultCaptureFrameRate; + + return cs; +} diff --git a/pica-client/callsettings.h b/pica-client/callsettings.h new file mode 100644 index 0000000..76a36b0 --- /dev/null +++ b/pica-client/callsettings.h @@ -0,0 +1,141 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#ifndef CALLSETTINGS_H +#define CALLSETTINGS_H + +#include <QString> + +// The parameters an audio/video call is started with: what the settings +// dialog's "Call Settings" and "Video Devices" tabs write, and what +// AudioVideoCallController reads when a call begins. Both sides go through +// this one place so they cannot drift apart, and so that "never configured" +// means the same thing to each of them. +// +// Codec names are FFmpeg names throughout. That is also how the 0x74 and 0x75 +// protocol messages name them (see doc/proto-doc-latest.txt), so what is +// stored here goes both onto the wire and into +// avcodec_find_encoder_by_name() with no translation table in between. + +// One entry of the codec lists the settings dialog offers. +struct CallCodecInfo +{ + // The FFmpeg name, which is what gets stored and what goes on the wire. + const char *name; + // What the settings dialog shows for it. + const char *displayName; +}; + +// Video codecs offered by the "Video Codec" setting, in the order they are +// listed. Every one of them is a codec the 0x75 message can name and that the +// receiving side hands to avcodec_find_decoder_by_name(), so no peer needs to +// know in advance which one we picked. +extern const CallCodecInfo kCallVideoCodecs[]; +extern const int kCallVideoCodecCount; + +// Audio codecs offered by the "Audio Codec" setting - the three the protocol +// names for the 0x74 message. +extern const CallCodecInfo kCallAudioCodecs[]; +extern const int kCallAudioCodecCount; + +// What a call uses when nothing has ever been configured: the values that were +// compiled in before any of this became a setting, so an install that has +// never opened the settings dialog behaves exactly as it did. +const int kDefaultVideoBitrateKbps = 600; +const int kDefaultAudioBitrateKbps = 32; +const int kDefaultCaptureWidth = 640; +const int kDefaultCaptureHeight = 480; +const int kDefaultCaptureFrameRate = 15; + +// The hardware paths video may be encoded or decoded through, as flags to +// combine - one per checkbox on the "Video Devices" tab, and named after the +// FFmpeg component behind each. Which of them a build offers depends on the +// platform: VAAPI where there is libva, the rest on Windows only, and Direct3D +// 12 only with an FFmpeg new enough to have it (HAVE_D3D12VA). +// +// Each is a request rather than a guarantee. A path FFmpeg was built without, +// one with no usable device, or one that will not open for the stream at hand +// is passed over for the next one enabled, and with none left the work is +// done in software - see VideoDevice for the order they are tried in. +enum VideoAcceleration +{ + // Encoding and decoding. + VideoAccelerationVaapi = 0x01, + VideoAccelerationD3d12va = 0x02, + // Encoding only: FFmpeg has no Media Foundation decoders. + VideoAccelerationMediaFoundation = 0x04, + // Decoding only: FFmpeg has no Direct3D 11 or DXVA2 encoders. + VideoAccelerationD3d11va = 0x08, + VideoAccelerationDxva2 = 0x10 +}; + +struct CallSettings +{ + // FFmpeg codec names, e.g. "h264" and "opus". + QString videoCodec; + QString audioCodec; + + // As the user enters them, in kbit/s. + int videoBitrateKbps; + int audioBitrateKbps; + + // What the camera is asked for. Not necessarily what it delivers - see + // VideoDevice::Capture(), which loosens these a step at a time rather than + // failing when a camera will not honour them. + int captureWidth; + int captureHeight; + int captureFrameRate; + + // VideoAcceleration flags for the two directions, out of the checkboxes + // this build offers. Rendering straight from GPU memory is not among them: + // it belongs to the window drawing the frames rather than to the decoder. + int videoEncodingAcceleration; + int videoDecodingAcceleration; + + // Reads the stored settings, filling in the defaults above for anything + // that was never set. Must be called from a thread that may touch the + // settings database - not from a capture or playback loop, see + // AudioDevice::SetLinuxDriverName() for why. + static CallSettings load(); +}; + +// The rate a given audio codec is captured and encoded at, and announced at in +// the 0x74 message. +// +// It is a property of the codec rather than a setting: G.722 is defined at +// 16kHz and nowhere else, and A-law is a telephony codec whose whole point is +// 8kHz. Opus would take any of them and uses 16kHz for the reason spelled out +// in callsettings.cpp. +int callAudioSampleRate(const QString &codec); + +// Whether the codec's bitrate is the caller's to choose. Opus is; G.722 and +// A-law each pack a fixed number of bits per sample, so their bitrate follows +// from the sample rate and nothing can be asked of the encoder. +bool callAudioBitrateAdjustable(const QString &codec); + +// The bitrate a fixed rate codec ends up at, in kbit/s, for showing in the +// settings dialog. Meaningless for a codec callAudioBitrateAdjustable() is +// true for, which returns the configured value instead. +int callAudioFixedBitrateKbps(const QString &codec); + +// Whether a codec name received in a 0x74/0x75 message is one we will hand to +// the FFmpeg decoder. Restricting this to the codecs the client itself sends +// keeps a peer from selecting an arbitrary (possibly buggy) decoder out of the +// whole FFmpeg build. +bool callAudioCodecAccepted(const QString &codec); +bool callVideoCodecAccepted(const QString &codec); + +#endif // CALLSETTINGS_H diff --git a/pica-client/callwindow.cpp b/pica-client/callwindow.cpp new file mode 100644 index 0000000..1874006 --- /dev/null +++ b/pica-client/callwindow.cpp @@ -0,0 +1,347 @@ +/* + (c) Copyright 2012 - 2020 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ + +#include "callwindow.h" +#include <QHBoxLayout> +#include <QVBoxLayout> +#include <QCloseEvent> +#include <QEvent> +#include <QGuiApplication> +#include <QScreen> +#include <QDebug> + +// Smallest the video area is allowed to become. Low enough that the window +// stays freely resizable - the video area is the part that gives, so a floor +// here is a floor under the whole window - while still leaving something +// recognizable on screen. +static const QSize kMinVideoSize(160, 120); + +// Style sheet for the call control buttons, with the colours filled in. Many +// native styles ignore a background-color unless the border is set by the +// style sheet too, so the whole frame is given here. The disabled state matters +// for "Hang Up", which call_ended() leaves disabled in the window. +static QString callButtonStyle(const char *normal, const char *hover, const char *pressed) +{ + return QString( + "QPushButton { background-color: %1; color: white; font-weight: bold;" + " border: 1px solid %3; border-radius: 4px; padding: 4px 16px; }" + "QPushButton:hover { background-color: %2; }" + "QPushButton:pressed { background-color: %3; }" + "QPushButton:disabled { background-color: #a0a0a0; border-color: #909090; color: #e0e0e0; }"). + arg(normal).arg(hover).arg(pressed); +} + +CallWindow::CallWindow(QByteArray peer_id, bool incoming) + : m_peer_id(peer_id), is_incoming(incoming), videoAreaOpened(false) +{ + setAttribute(Qt::WA_DeleteOnClose); + + QVBoxLayout *lv = new QVBoxLayout(this); + QHBoxLayout *lh = new QHBoxLayout(); + + pbAccept = new QPushButton(tr("Accept"), this); + pbCall = new QPushButton(tr("Call"), this); + pbHang = new QPushButton(tr("Hang Up"), this); + pbAccept->setStyleSheet(callButtonStyle("#2e9e3e", "#36b548", "#237a30")); + pbCall->setStyleSheet(callButtonStyle("#2e9e3e", "#36b548", "#237a30")); + pbHang->setStyleSheet(callButtonStyle("#d03030", "#e04040", "#a52424")); + lbTimer = new QLabel(this); + lbTimer->setAlignment(Qt::AlignCenter); + lbTimer->hide(); + lbTransport = new QLabel(this); + lbTransport->setAlignment(Qt::AlignCenter); + lbTransport->hide(); + lbVideo = new QLabel(this); + lbVideo->setAlignment(Qt::AlignCenter); + // A label holding a pixmap reports that pixmap's size as both its + // preferred and its minimum size, which would make the video area's size + // depend on the picture currently in it: the window could not be made + // smaller than the last frame drawn, and the layout would be recomputed on + // every frame. Ignored breaks that - the label is given whatever space the + // stretch factors below say and never asks for any. + lbVideo->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); + // Small enough to let the window be resized freely; the size the video + // area actually opens at is set once by openVideoArea(). + lbVideo->setMinimumSize(kMinVideoSize); + lbVideo->hide(); +#ifdef HAVE_VAAPI + videoGpu = VaapiRenderWidget::create(this); + videoGpu->widget()->setMinimumSize(kMinVideoSize); + videoGpu->widget()->hide(); + connect(videoGpu->widget(), SIGNAL(renderingFailed(QString)), this, SLOT(gpu_rendering_failed(QString))); +#endif + callTimer = new QTimer(this); + callElapsedSeconds = 0; + + // Only the video gets a stretch factor, so it takes all the height the + // rows around it do not need. Left at the default of zero, every item + // whose size policy allows it to grow gets an equal share of the spare + // height instead - which for two QLabels and the video meant the video + // got about a third of it and the timer and the transport line sat in + // tall empty bands. + // + // Only one of the two video widgets is ever visible and a hidden widget is + // given no space, so both can be stretched. + lv->addWidget(lbTimer, 0); + lv->addWidget(lbTransport, 0); + lv->addWidget(lbVideo, 1); +#ifdef HAVE_VAAPI + lv->addWidget(videoGpu->widget(), 1); +#endif + + // Note that the second argument of addWidget() is a stretch factor and not + // an alignment - passing Qt::AlignLeft here, as this did, compiles, since + // Qt::Alignment converts to int, and quietly means a stretch of 1. A + // spacer does what the alignment was meant to. + lh->addWidget(pbAccept); + lh->addWidget(pbCall); + lh->addStretch(1); + lh->addWidget(pbHang); + lv->addLayout(lh, 0); + setLayout(lv); + + lbVideo->installEventFilter(this); + + connect(pbCall, SIGNAL(clicked()), this, SLOT(call())); + connect(pbHang, SIGNAL(clicked()), this, SLOT(hang())); + connect(pbAccept, SIGNAL(clicked()), this, SLOT(accept())); + connect(callTimer, SIGNAL(timeout()), this, SLOT(update_call_timer())); + + if (is_incoming) + { + pbCall->hide(); + } + else + { + pbAccept->hide(); + } +} + +void CallWindow::call_started() +{ + pbCall->hide(); + pbAccept->hide(); + + callElapsedSeconds = 0; + lbTimer->setText("00:00"); + lbTimer->show(); + callTimer->start(1000); +} + +void CallWindow::call_ended() +{ + callTimer->stop(); + pbHang->setDisabled(true); + lbTransport->hide(); +} + +void CallWindow::setMediaTransport(bool direct_udp, QString ciphersuitename) +{ + if (direct_udp) + lbTransport->setText(tr("🔐 media: direct UDP, %1").arg(ciphersuitename)); + else + lbTransport->setText(tr("media: through the chat connection")); + + lbTransport->show(); +} + +void CallWindow::showRemoteFrame(QImage frame) +{ + if (frame.isNull()) + return; + + lastRemoteFrame = frame; + + if (lbVideo->isHidden()) + { + openVideoArea(frame.size()); + lbVideo->show(); + reportVideoArea(); + } + + updateRemoteFrame(); +} + +void CallWindow::updateRemoteFrame() +{ + if (lastRemoteFrame.isNull() || lbVideo->isHidden()) + return; + + // Normally a no-op: the decoder was told the size of this area and the + // frame already arrived at it, and scale() returns the frame untouched + // when there is nothing to do. It earns its place across a resize, when + // the frames already decoded at the old size have still to be drawn at + // the new one. + QImage scaled = videoScaler.scale(lastRemoteFrame, lbVideo->size()); + + if (scaled.isNull()) + return; + + lbVideo->setPixmap(QPixmap::fromImage(scaled)); +} + +void CallWindow::reportVideoArea() +{ + // While the label is hidden there is nothing to size frames for, and its + // geometry is meaningless anyway. isHidden() rather than isVisible(): what + // matters is whether this label is the renderer in use, not whether the + // window happens to be on screen right now. When the GPU widget has the + // video area it scales frames itself, on the GPU, and wants them at their + // own resolution - see showRemoteHwFrame(). + if (lbVideo->isHidden()) + return; + + emit video_area_changed(lbVideo->size()); +} + +void CallWindow::openVideoArea(QSize frame) +{ + if (videoAreaOpened || frame.isEmpty()) + return; + + videoAreaOpened = true; + + // The window has been sized for a call with no video in it, so the video + // area is about to appear into whatever the layout can spare - which is + // its minimum. Grow the window by what the video needs on top of that. + // + // Only the first frame does this. After it the window's size is the user's + // business, and a later frame must not undo a deliberate resize. + QSize wanted = frame; + QScreen *screen = QGuiApplication::primaryScreen(); + + if (screen) + { + // Leave the rows above and below the video the height they have + // now - a peer sending 1080p to a 1080 high screen should not open + // a window taller than the desktop. + QSize available = screen->availableGeometry().size() - QSize(0, height()); + + wanted = VideoScaler::fitted(frame, available.expandedTo(kMinVideoSize)); + } + + resize(qMax(width(), wanted.width()), + height() + qMax(0, wanted.height() - lbVideo->height())); +} + +#ifdef HAVE_VAAPI +void CallWindow::showRemoteHwFrame(AVFramePtr frame) +{ + if (!frame) + return; + + // The widget has given up on drawing - ask again for frames the label can + // show, and keep the video area with it. + if (!videoGpu->isWorking()) + { + emit video_rendering_failed(); + return; + } + + // These frames hold a GPU surface rather than pixels, so the label cannot + // show them - the GL widget takes over the video area instead. + if (videoGpu->widget()->isHidden()) + { + openVideoArea(QSize(frame->width, frame->height)); + lbVideo->hide(); + videoGpu->widget()->show(); + + // The widget scales the surface itself, on the GPU, so the decoder + // has no reason to produce frames at any particular size - and it + // is not producing these ones at all. + emit video_area_changed(QSize()); + } + + videoGpu->setFrame(frame); +} + +void CallWindow::gpu_rendering_failed(QString message) +{ + // Nothing will ever appear in the GL widget now, so hand the video area + // back to the label and ask for frames it can actually show. Without this + // the rest of the call would be spent looking at an empty black rectangle. + qWarning() << message; + + videoGpu->widget()->hide(); + lbVideo->show(); + + // Frames are about to start arriving in system memory, so the decoder + // needs the size to produce them at. Sent explicitly rather than left to + // the label's resize, which does not fire if showing it did not change its + // geometry. + reportVideoArea(); + + emit video_rendering_failed(); +} +#endif + +void CallWindow::update_call_timer() +{ + int hours, minutes, seconds; + QString text; + + callElapsedSeconds++; + + hours = callElapsedSeconds / 3600; + minutes = (callElapsedSeconds % 3600) / 60; + seconds = callElapsedSeconds % 60; + + if (hours > 0) + text = QString("%1:%2:%3"). + arg(hours, 2, 10, QChar('0')). + arg(minutes, 2, 10, QChar('0')). + arg(seconds, 2, 10, QChar('0')); + else + text = QString("%1:%2"). + arg(minutes, 2, 10, QChar('0')). + arg(seconds, 2, 10, QChar('0')); + + lbTimer->setText(text); +} + +void CallWindow::call() +{ + emit start_call_pressed(); +} + +void CallWindow::hang() +{ + emit hang_call_pressed(); +} + +void CallWindow::accept() +{ + emit accept_call_pressed(); +} + +bool CallWindow::eventFilter(QObject *watched, QEvent *event) +{ + if (watched == lbVideo && event->type() == QEvent::Resize) + { + reportVideoArea(); + updateRemoteFrame(); + } + + return QWidget::eventFilter(watched, event); +} + +void CallWindow::closeEvent(QCloseEvent *e) +{ + emit callwindow_closed(this); + + e->accept(); +} diff --git a/pica-client/callwindow.h b/pica-client/callwindow.h new file mode 100644 index 0000000..548b391 --- /dev/null +++ b/pica-client/callwindow.h @@ -0,0 +1,133 @@ + +/* + (c) Copyright 2012 - 2018 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#ifndef CALLWINDOW_H +#define CALLWINDOW_H + +#include <QWidget> +#include <QPushButton> +#include <QLabel> +#include <QTimer> +#include <QImage> +#include <QSize> +#include "videoscaler.h" +#ifdef HAVE_VAAPI +#include "vaapi.h" +#endif + +class QEvent; + +class CallWindow : public QWidget +{ + Q_OBJECT +public: + explicit CallWindow(QByteArray peer_id, bool incoming); +signals: + void start_call_pressed(); + void accept_call_pressed(); + void hang_call_pressed(); + void callwindow_closed(CallWindow *sender_window); + + // The area the remote video has to be drawn in, whenever it changes. The + // decoder produces frames at this size directly rather than the window + // resizing them after the fact - see VideoScaler for why that is worth + // routing across threads for. + void video_area_changed(QSize area); +#ifdef HAVE_VAAPI + // Drawing frames straight out of GPU memory did not work on this system. + // The call controller answers by having them decoded into system memory + // instead, which the label below can show. + void video_rendering_failed(); +#endif +private: + QByteArray m_peer_id; + bool is_incoming; + QPushButton *pbAccept; + QPushButton *pbCall; + QPushButton *pbHang; + QLabel *lbTimer; + // How the call's media is being carried, and under which ciphersuite. + // Hidden until that is known. + QLabel *lbTransport; + // Displays the remote side's video. Stays hidden until the first frame + // arrives, so an audio-only call keeps the compact window it had before. + QLabel *lbVideo; +#ifdef HAVE_VAAPI + // Used instead of lbVideo when frames arrive still living in GPU memory; + // only one of the two is ever visible. Which of the two renderers this is + // depends on the session - see VaapiRenderWidget::create(). + VaapiRenderWidget *videoGpu; +#endif + QTimer *callTimer; + int callElapsedSeconds; + + // The last frame received, kept so that the picture can follow a resize + // instead of staying as it was until the next frame arrives. + QImage lastRemoteFrame; + + // Resizes a frame that does not already match the video area. Normally + // does nothing: the decoder is told what size to produce, and only the + // frames in flight across a resize arrive at another size. + VideoScaler videoScaler; + + // Whether the video area has been given room yet, see showRemoteFrame(). + bool videoAreaOpened; + + // Draws lastRemoteFrame at the size the video area is now. + void updateRemoteFrame(); + + // Tells the decoder what size to produce frames at, if that has changed. + void reportVideoArea(); + + // Enlarges the window to fit the first frame's own resolution, once. An + // audio call keeps the compact window it had before, so when video does + // turn up there is no room for it; without this it would appear in + // whatever few pixels the layout could spare. + void openVideoArea(QSize frame); + + void closeEvent(QCloseEvent *e); + + // Watches lbVideo for its own resizes, which is where the video area's + // size is really decided. Doing this from the window's resizeEvent() + // instead would read the label's geometry before the layout has had a + // chance to update it, and would miss the resizes the layout causes by + // itself - lbTransport appearing shortens the video area without the + // window changing size at all. + bool eventFilter(QObject *watched, QEvent *event) override; + +public slots: + void call_started(); + void call_ended(); + // direct_udp tells whether the media is being carried over a direct + // mediac2c connection or over the c2c connection the call was set up on. + void setMediaTransport(bool direct_udp, QString ciphersuitename); + void showRemoteFrame(QImage frame); +#ifdef HAVE_VAAPI + void showRemoteHwFrame(AVFramePtr frame); +#endif +private slots: + void call(); + void accept(); + void hang(); + void update_call_timer(); +#ifdef HAVE_VAAPI + void gpu_rendering_failed(QString message); +#endif +}; + +#endif + diff --git a/pica-client/chatwindow.cpp b/pica-client/chatwindow.cpp index a135c19..af86ae7 100644 --- a/pica-client/chatwindow.cpp +++ b/pica-client/chatwindow.cpp @@ -87,6 +87,9 @@ ChatWindow::ChatWindow(QByteArray peer_id, QString status) : QHBoxLayout *hl = new QHBoxLayout(); lbAddCtQuestion = new QLabel(tr("Do you want to add \"%1\" to your contact list?").arg(peer_name_)); + // peer_name_ comes from the peer's certificate; keep it literal so it + // cannot be interpreted as rich text. + lbAddCtQuestion->setTextFormat(Qt::PlainText); btAddCtYes = new QPushButton(tr("Yes")); btAddCtNo = new QPushButton(tr("No")); btAddCtBlacklist = new QPushButton(tr("Add to blacklist")); @@ -189,8 +192,8 @@ int ChatWindow::draw_message(QString msg, QString nickname, QString datetime, QS QString("<b><font color=%1>%2(%3) %4 : </font></b>"). arg(color). arg(delivered_mark). - arg(datetime). - arg(nickname) + arg(datetime.toHtmlEscaped()). + arg(nickname.toHtmlEscaped()) ); chatw->setCurrentCharFormat(fmt); chatw->insertPlainText(msg + '\n'); @@ -251,8 +254,10 @@ void ChatWindow::msg_delivered() QByteArray my_id = Accounts::GetCurrentAccount().id; QMap<QByteArray, QList<QString> > undl = hist.GetUndeliveredMessages(); - if (!undl[my_id].isEmpty()) - put_message(undl[my_id].first(), my_id, true); + // GetUndeliveredMessages() is keyed by the peer's contact_id, not by + // our own id, so this must look up peer_id_ to find anything. + if (!undl[peer_id_].isEmpty()) + put_message(undl[peer_id_].first(), my_id, true); } if (!undelivered_msgs.isEmpty()) diff --git a/pica-client/contactlistwidget.cpp b/pica-client/contactlistwidget.cpp index 0e19bb6..eed4abf 100644 --- a/pica-client/contactlistwidget.cpp +++ b/pica-client/contactlistwidget.cpp @@ -21,6 +21,7 @@ #include "dialogs/filetransferdialog.h" #include "msguirouter.h" #include "filetransfercontroller.h" +#include "audiovideocallcontroller.h" #include <QMenu> #include <QMessageBox> #include <QContextMenuEvent> @@ -42,6 +43,9 @@ ContactListWidget::ContactListWidget(QWidget *parent) : startchatAct = new QAction(tr("Start &Chat"), this); connect(startchatAct, SIGNAL(triggered()), this, SLOT(start_chat())); + startcallAct = new QAction(tr("Start Ca&ll 📞"), this); + connect(startcallAct, SIGNAL(triggered()), this, SLOT(start_call())); + viewcertAct = new QAction(tr("&View Certificate"), this); connect(viewcertAct, SIGNAL(triggered()), this, SLOT(view_cert())); @@ -84,6 +88,7 @@ void ContactListWidget::contextMenuEvent(QContextMenuEvent *event) if (this->itemAt(event->pos()) && wgitem_to_recs.contains(this->itemAt(event->pos()))) { menu.addAction(startchatAct); + menu.addAction(startcallAct); menu.addAction(viewcertAct); menu.addAction(showidAct); menu.addAction(sendfileAct); @@ -227,6 +232,11 @@ void ContactListWidget::start_chat() msguirouter->start_chat(wgitem_to_recs[currentItem()]->id); } +void ContactListWidget::start_call() +{ + avctrl->start_call(wgitem_to_recs[currentItem()]->id); +} + void ContactListWidget::view_cert() { QString cert_pem = storage->GetContactCert(wgitem_to_recs[currentItem()]->id); diff --git a/pica-client/contactlistwidget.h b/pica-client/contactlistwidget.h index b58fdfe..4800b46 100644 --- a/pica-client/contactlistwidget.h +++ b/pica-client/contactlistwidget.h @@ -33,6 +33,7 @@ public: QAction *addcontactAct; QAction *delcontactAct; QAction *startchatAct; + QAction *startcallAct; QAction *viewcertAct; QAction *showidAct; QAction *sendfileAct; @@ -59,6 +60,7 @@ private slots: void add_contact(); void del_contact(); void start_chat(); + void start_call(); void view_cert(); void show_id(); void send_file(); diff --git a/pica-client/contacts.cpp b/pica-client/contacts.cpp index ec57c8c..0fd259a 100644 --- a/pica-client/contacts.cpp +++ b/pica-client/contacts.cpp @@ -19,10 +19,10 @@ //#include <QMessageBox> -Contacts::Contacts(QString storage, QByteArray user_account_id) +Contacts::Contacts(QString storage, QByteArray user_account_id, QString connectionName) : account_id_(user_account_id) { - dbconn = QSqlDatabase::database(); + dbconn = connectionName.isEmpty() ? QSqlDatabase::database() : QSqlDatabase::database(connectionName); dbconn.setDatabaseName(storage); if (!dbconn.open()) @@ -34,7 +34,7 @@ Contacts::Contacts(QString storage, QByteArray user_account_id) //check if table contacts exists //... - QSqlQuery query; + QSqlQuery query(dbconn); query.exec("PRAGMA foreign_keys=ON;"); @@ -53,7 +53,7 @@ QString Contacts::GetLastError() bool Contacts::Exists(QByteArray id) { - QSqlQuery query; + QSqlQuery query(dbconn); query.setForwardOnly(true); query.prepare("select count(*) from contacts where account_id=:account_id and id=:id"); @@ -71,7 +71,7 @@ bool Contacts::Exists(QByteArray id) void Contacts::Add(QByteArray id, ContactType type) { - QSqlQuery query; + QSqlQuery query(dbconn); if (!Exists(id)) { @@ -95,7 +95,7 @@ void Contacts::Add(QByteArray id, ContactType type) void Contacts::Delete(QByteArray id) { - QSqlQuery query; + QSqlQuery query(dbconn); query.prepare("delete from contacts where id=:id and account_id=:account_id"); query.bindValue(":id", id); @@ -109,7 +109,7 @@ QList<Contacts::ContactRecord> Contacts::GetContacts(ContactType type) { QList<ContactRecord> L; ContactRecord r; - QSqlQuery query; + QSqlQuery query(dbconn); query.setForwardOnly(true); query.prepare("select id, name from contacts where account_id=:account_id and type=:type"); @@ -135,7 +135,7 @@ QList<Contacts::ContactRecord> Contacts::GetContacts(ContactType type) QString Contacts::GetContactCert(QByteArray id) { - QSqlQuery query; + QSqlQuery query(dbconn); query.prepare("select cert_pem from contacts where id=:id and account_id=:account_id"); query.bindValue(":id", id); @@ -154,7 +154,7 @@ QString Contacts::GetContactCert(QByteArray id) QString Contacts::GetContactName(QByteArray id) { - QSqlQuery query; + QSqlQuery query(dbconn); query.prepare("select name from contacts where id=:id and account_id=:account_id"); query.bindValue(":id", id); @@ -173,7 +173,7 @@ QString Contacts::GetContactName(QByteArray id) void Contacts::SetContactCert(QByteArray id, QString &cert_pem) { - QSqlQuery query; + QSqlQuery query(dbconn); query.prepare("update contacts set cert_pem=:cert_pem where id=:id and account_id=:account_id"); query.bindValue(":cert_pem", cert_pem); @@ -187,7 +187,7 @@ void Contacts::SetContactCert(QByteArray id, QString &cert_pem) void Contacts::SetContactName(QByteArray id, QString name) { - QSqlQuery query; + QSqlQuery query(dbconn); query.prepare("update contacts set name=:name where id=:id and account_id=:account_id"); query.bindValue(":name", name); @@ -200,7 +200,7 @@ void Contacts::SetContactName(QByteArray id, QString name) void Contacts::SetContactType(QByteArray id, ContactType type) { - QSqlQuery query; + QSqlQuery query(dbconn); query.prepare("update contacts set type=:type where id=:id and account_id=:account_id"); query.bindValue(":type", type); diff --git a/pica-client/contacts.h b/pica-client/contacts.h index e460ad3..03a2e14 100644 --- a/pica-client/contacts.h +++ b/pica-client/contacts.h @@ -41,7 +41,8 @@ public: ContactType type; }; - Contacts(QString storage, QByteArray user_account_id); + // See Nodes::Nodes() for what connectionName selects and why. + Contacts(QString storage, QByteArray user_account_id, QString connectionName = QString()); bool Exists(QByteArray id); void Add(QByteArray id, ContactType type = regular); diff --git a/pica-client/dhparam.cpp b/pica-client/dhparam.cpp index 3708334..c2d8b56 100644 --- a/pica-client/dhparam.cpp +++ b/pica-client/dhparam.cpp @@ -76,7 +76,7 @@ bool DHParam::StartNewDHParamGeneration(QString *errormsg) QFile::remove(tempdhfile); return dhparamgenerator -> osslt.GenDHParamSignal(PICA_CLIENT_DHPARAMBITS, - tempdhfile, dhparamgenerator, SLOT(DHParamGenFinished(int, QProcess::ExitStatus))); + tempdhfile, dhparamgenerator, SLOT(DHParamGenFinished(int))); } QString DHParam::GetDHParamFilename() @@ -92,7 +92,7 @@ QString DHParam::GetDHParamFilename() return current_dhparam_file; } -void DHParam::DHParamGenFinished(int retval, QProcess::ExitStatus) +void DHParam::DHParamGenFinished(int retval) { if (retval == 0) { @@ -104,7 +104,12 @@ void DHParam::DHParamGenFinished(int retval, QProcess::ExitStatus) current_dhparam_file = config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE; - delete dhparamgenerator; + /* + * deleteLater, not delete: we are inside a slot the generator's own + * OpenSSLLib member is emitting to, and it still has to return + * through it. + */ + dhparamgenerator->deleteLater(); dhparamgenerator = NULL; } diff --git a/pica-client/dhparam.h b/pica-client/dhparam.h index ce49f44..930c277 100644 --- a/pica-client/dhparam.h +++ b/pica-client/dhparam.h @@ -20,7 +20,7 @@ #include <QObject> #include <QString> #include "globals.h" -#include "openssltool.h" +#include "openssllib.h" class DHParam : public QObject { @@ -42,10 +42,10 @@ private: static DHParam *dhparamgenerator; static QString current_dhparam_file; - OpenSSLTool osslt; + OpenSSLLib osslt; private slots: - void DHParamGenFinished(int retval, QProcess::ExitStatus); + void DHParamGenFinished(int retval); }; #endif // DHPARAM_H diff --git a/pica-client/dialogs/filetransferdialog.cpp b/pica-client/dialogs/filetransferdialog.cpp index ef431ec..8ee6d3b 100644 --- a/pica-client/dialogs/filetransferdialog.cpp +++ b/pica-client/dialogs/filetransferdialog.cpp @@ -44,6 +44,10 @@ FileTransferDialog::FileTransferDialog(QByteArray peer_id, QString filename, qui lbFilename = new QLabel(this); lbPeer = new QLabel(this); + // Both carry peer-supplied text (file name, certificate-derived name), + // so keep them literal rather than letting Qt render them as rich text. + lbFilename->setTextFormat(Qt::PlainText); + lbPeer->setTextFormat(Qt::PlainText); lbProgressStatus = new QLabel(this); lbTransferSpeed = new QLabel(this); lbRemainingTime = new QLabel(this); diff --git a/pica-client/dialogs/registeraccountdialog.cpp b/pica-client/dialogs/registeraccountdialog.cpp index ff77951..cf92a06 100644 --- a/pica-client/dialogs/registeraccountdialog.cpp +++ b/pica-client/dialogs/registeraccountdialog.cpp @@ -178,10 +178,10 @@ void RegisterAccountDialog::Register() btRegister->setEnabled(false); ost.GenRSAKeySignal(config_dir + QDir::separator() + "privkey.pem", cbSetPassword->isChecked(), - password->text(), rand, this, SLOT(stageSignCert(int, QProcess::ExitStatus))); + password->text(), rand, this, SLOT(stageSignCert(int))); } -void RegisterAccountDialog::stageSignCert(int retval, QProcess::ExitStatus) +void RegisterAccountDialog::stageSignCert(int retval) { if (retval != 0) { @@ -196,10 +196,10 @@ void RegisterAccountDialog::stageSignCert(int retval, QProcess::ExitStatus) ost.GenCertSignal(config_dir + QDir::separator() + "cert.pem", config_dir + QDir::separator() + "privkey.pem", password->text(), nickname->text(), - this, SLOT(stageFinished(int, QProcess::ExitStatus))); + this, SLOT(stageFinished(int))); } -void RegisterAccountDialog::stageFinished(int retval, QProcess::ExitStatus) +void RegisterAccountDialog::stageFinished(int retval) { if (retval != 0) { diff --git a/pica-client/dialogs/registeraccountdialog.h b/pica-client/dialogs/registeraccountdialog.h index 447d181..2e4fe22 100644 --- a/pica-client/dialogs/registeraccountdialog.h +++ b/pica-client/dialogs/registeraccountdialog.h @@ -23,7 +23,7 @@ #include <QLabel> #include <QCheckBox> #include <QRegExpValidator> -#include "../openssltool.h" +#include "../openssllib.h" class RegisterAccountDialog : public QDialog { @@ -46,7 +46,7 @@ private: QCheckBox *cbUseDevRandom; QRegExpValidator *vld; - OpenSSLTool ost; + OpenSSLLib ost; QByteArray cert_buf; QString CertFilename_; @@ -59,8 +59,8 @@ private slots: void setPasswordClick(); void useDevRandomClick(); - void stageSignCert(int retval, QProcess::ExitStatus); - void stageFinished(int retval, QProcess::ExitStatus); + void stageSignCert(int retval); + void stageFinished(int retval); }; #endif // REGISTERACCOUNTDIALOG_H diff --git a/pica-client/dialogs/settingsdialog.cpp b/pica-client/dialogs/settingsdialog.cpp index 2253778..2df521d 100644 --- a/pica-client/dialogs/settingsdialog.cpp +++ b/pica-client/dialogs/settingsdialog.cpp @@ -17,82 +17,241 @@ #include "settingsdialog.h" #include "../settings.h" #include "../globals.h" +#include "../audiodevice.h" +#include "../videodevice.h" +#include "../callsettings.h" +#include "../directc2csettings.h" #include "../../PICA_netconf.h" #include "../../PICA_proto.h" #include <QGroupBox> #include <QVBoxLayout> #include <QHBoxLayout> +#include <QGridLayout> +#include <QFormLayout> #include <QLabel> +#include <QDebug> #include <QVariant> #include <QListWidget> #include <QNetworkInterface> #include <QHostAddress> +#include <QSize> +#include <QEvent> #include <QTabWidget> +#include <QTimer> +#include <QHeaderView> +#include <QMessageBox> +#include <QHostAddress> +#include <memory> + +// The device tests are not part of any call, but the devices only run for an +// open call session (see MediaCallSession) - so each test is one, under a name +// no account id can take, with the dialog on both ends of it. +static QByteArray testSessionId() +{ + return QByteArrayLiteral("settings dialog device test"); +} + +// Audio pipeline test: how long the microphone is recorded for. The codec and +// the rate come from the "Call Settings" tab, so the test runs the same path a +// call would - see toggleAudioTest(). +static const int kAudioTestRecordMs = 5000; + +// One encoded packet covers this much audio (the Opus encoder produces +// 20 ms frames at 48 kHz), so feeding one packet per this many milliseconds +// replays the recording at its natural rate. +static const int kAudioTestPacketMs = 20; + +// How long to wait for the microphone to produce its first packet before +// giving up on it. Opening a capture device is not instant - on Windows, +// COM plus WASAPI endpoint activation can take the better part of a second - +// so the recording window below is only started once audio is actually +// arriving, and this is the separate limit on getting that far at all. +static const int kAudioTestStartTimeoutMs = 4000; + +// Grace period after the last packet has been handed over, for the jitter +// buffer and the sound card's own buffer to drain before closing the device. +static const int kAudioTestDrainMs = 500; + +// Sizes and frame rates offered when the camera will not say what it supports +// - a platform where they cannot be queried, or a camera that will not answer. +// The camera is free to refuse any of them, the same way it may refuse +// anything else it was asked for; VideoDevice::Capture() loosens the request +// rather than failing. +static const struct +{ + int width; + int height; +} kFallbackResolutions[] = +{ + { 1920, 1080 }, { 1280, 720 }, { 800, 600 }, { 640, 480 }, + { 640, 360 }, { 352, 288 }, { 320, 240 }, { 160, 120 } +}; + +static const int kFallbackFrameRates[] = { 30, 25, 24, 20, 15, 10, 5 }; + +// Range the bitrate spin boxes accept, in kbit/s. Wide enough not to argue +// with anyone: the low end is where a codec still produces something, the high +// end well past what a call over a home connection can carry. +static const int kMinVideoBitrateKbps = 50; +static const int kMaxVideoBitrateKbps = 20000; +static const int kMinAudioBitrateKbps = 6; +static const int kMaxAudioBitrateKbps = 510; SettingsDialog::SettingsDialog(QWidget *parent) : QDialog(parent) { + // The video tab's format lists follow the camera selection, and + // fillVideoDevices() below changes that before they have been built - so + // they have to be readable as "not there yet" from the moment anything can + // reach them. + videoRes = nullptr; + videoFps = nullptr; + + // Same problem, one step further along: videoPreview is watched for its own + // resizes and answers them by telling testDecoder what size to decode to, + // but the preview is built - and the layout that can resize it applied - + // before the decoder exists. + testDecoder = nullptr; + videoTestRunning = false; + videoTestGpuRendering = false; + videoCapturedFrames = 0; + videoDisplayedFrames = 0; + videoCaptureFps = 0.0; + videoDisplayFps = 0.0; + QVBoxLayout *settingsLayout = new QVBoxLayout(); QTabWidget *tabW = new QTabWidget(this); QWidget* directc2ctab = new QWidget(0); QWidget* soundstab = new QWidget(0); QWidget* multilogintab = new QWidget(0); + QWidget* audiodevtab = new QWidget(0); + QWidget* videodevtab = new QWidget(0); + QWidget* calltab = new QWidget(0); QVBoxLayout *directc2cLayout = new QVBoxLayout(); QVBoxLayout *multiloginlayout = new QVBoxLayout(); + QVBoxLayout *audiodevlayout = new QVBoxLayout(); + QVBoxLayout *videodevLayout = new QVBoxLayout(); + QVBoxLayout *callLayout = new QVBoxLayout(); //Direct connections rbDisableDirectConns = new QRadioButton(tr("Disable direct connections"), this); rbEnableOutgoingConns = new QRadioButton(tr("Connect to the remote peer directly if possible"), this); rbEnableIncomingConns = new QRadioButton(tr("Enable incoming direct connections"), this); + rbEnableIncomingConns->setChecked(true); + + // Indented under "Enable incoming direct connections", which it all + // depends on. A widget of its own also keeps its radio buttons out of the + // exclusive group of the three above, QRadioButton grouping by parent. + incomingBox = new QWidget(); + QVBoxLayout *incomingLayout = new QVBoxLayout(); + incomingLayout->setContentsMargins(20, 0, 0, 0); + + cbEnableUPnP = nullptr; #ifdef HAVE_LIBMINIUPNPC cbEnableUPnP = new QCheckBox(tr("Enable UPnP")); + cbEnableUPnP->setToolTip(tr("Ask the router to forward the port for incoming direct connections, TCP and UDP, " + "and announce the router's external address to peers")); cbEnableUPnP->setChecked(true); + incomingLayout->addWidget(cbEnableUPnP); #endif - rbEnableIncomingConns->setChecked(true); - connect(rbEnableIncomingConns, SIGNAL(toggled(bool)), this, SLOT(toggleIncomingConnections(bool))); + rbAddrAuto = new QRadioButton(tr("Automatic address configuration")); + rbAddrManual = new QRadioButton(tr("Manual")); + rbAddrAuto->setChecked(true); - QLabel *lbAddr = new QLabel(tr("Public address for incoming connections"), this); - addr = new QComboBox(this); - QLabel *lbPubPort = new QLabel(tr("External TCP port for incoming connections"), this); - publicPort = new QSpinBox(this); - QLabel *lbLocPort = new QLabel(tr("Local TCP port for incoming connections"), this); - localPort = new QSpinBox(this); + lbAutoAddrs = new QLabel(); + lbAutoAddrs->setWordWrap(true); + lbAutoAddrs->setContentsMargins(20, 0, 0, 0); - addr->setEditable(true); - - publicPort->setRange(1, 65535); - localPort->setRange(1, 65535); + incomingLayout->addWidget(rbAddrAuto); + incomingLayout->addWidget(lbAutoAddrs); + incomingLayout->addWidget(rbAddrManual); - publicPort->setValue(2298); - localPort->setValue(2298); + manualBox = new QWidget(); + QVBoxLayout *manualLayout = new QVBoxLayout(); + manualLayout->setContentsMargins(20, 0, 0, 0); - QList<QHostAddress> hostIfAddrs = QNetworkInterface::allAddresses(); - QHostAddress ifAddr; - - addr->addItem(QString("autoconfigure")); + QHBoxLayout *portRow = new QHBoxLayout(); + localPort = new QSpinBox(); + localPort->setRange(1, 65535); + localPort->setValue(DirectC2CSettings::DefaultPort); + portRow->addWidget(new QLabel(tr("Local TCP and UDP port"))); + portRow->addWidget(localPort); + portRow->addStretch(1); + manualLayout->addLayout(portRow); + + manualLayout->addWidget(new QLabel(tr("Addresses announced to peers, tried by them in this order. " + "Put the external address and port of a port forwarded " + "on your router here."))); + + addrTable = new QTableWidget(0, 2); + addrTable->setHorizontalHeaderLabels(QStringList() << tr("Address") << tr("Port")); + addrTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); + addrTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); + addrTable->verticalHeader()->setVisible(false); + addrTable->setSelectionBehavior(QAbstractItemView::SelectRows); + addrTable->setSelectionMode(QAbstractItemView::SingleSelection); + manualLayout->addWidget(addrTable); + + QHBoxLayout *addrButtons = new QHBoxLayout(); + QPushButton *btAddrAdd = new QPushButton(tr("Add")); + QPushButton *btAddrRemove = new QPushButton(tr("Remove")); + QPushButton *btAddrUp = new QPushButton(tr("Move up")); + QPushButton *btAddrDown = new QPushButton(tr("Move down")); + addrButtons->addWidget(btAddrAdd); + addrButtons->addWidget(btAddrRemove); + addrButtons->addWidget(btAddrUp); + addrButtons->addWidget(btAddrDown); + addrButtons->addStretch(1); + manualLayout->addLayout(addrButtons); + + QHBoxLayout *addrButtons2 = new QHBoxLayout(); + QPushButton *btAddrIfaces = new QPushButton(tr("Add interface addresses")); + btAddrIfaces->setToolTip(tr("Add the addresses of this computer's network interfaces, with the local port")); + btAddrUpnp = new QPushButton(tr("Add UPnP address")); + btAddrUpnp->setToolTip(tr("Add an entry for the external address of the UPnP router, " + "filled in with the forwarded port when Pica Pica runs")); + btUpnpQuery = new QPushButton(tr("Ask router for external address")); + btUpnpQuery->setToolTip(tr("Get the router's external address through UPnP now and add it with the local port")); + addrButtons2->addWidget(btAddrIfaces); + addrButtons2->addWidget(btAddrUpnp); + addrButtons2->addWidget(btUpnpQuery); + addrButtons2->addStretch(1); + manualLayout->addLayout(addrButtons2); + + lbUpnpInfo = new QLabel(); + lbUpnpInfo->setWordWrap(true); + manualLayout->addWidget(lbUpnpInfo); + +#ifndef HAVE_LIBMINIUPNPC + btAddrUpnp->hide(); + btUpnpQuery->hide(); +#endif - foreach (ifAddr, hostIfAddrs) - if (ifAddr.protocol() == QAbstractSocket::IPv4Protocol) - addr->addItem(ifAddr.toString()); + manualBox->setLayout(manualLayout); + incomingLayout->addWidget(manualBox); + incomingBox->setLayout(incomingLayout); + connect(rbEnableIncomingConns, SIGNAL(toggled(bool)), this, SLOT(toggleIncomingConnections(bool))); + connect(rbAddrManual, SIGNAL(toggled(bool)), this, SLOT(toggleIncomingConnections(bool))); + if (cbEnableUPnP) + connect(cbEnableUPnP, SIGNAL(toggled(bool)), this, SLOT(toggleIncomingConnections(bool))); + connect(btAddrAdd, SIGNAL(clicked()), this, SLOT(addAddr())); + connect(btAddrRemove, SIGNAL(clicked()), this, SLOT(removeAddr())); + connect(btAddrUp, SIGNAL(clicked()), this, SLOT(moveAddrUp())); + connect(btAddrDown, SIGNAL(clicked()), this, SLOT(moveAddrDown())); + connect(btAddrIfaces, SIGNAL(clicked()), this, SLOT(addInterfaceAddrs())); + connect(btAddrUpnp, SIGNAL(clicked()), this, SLOT(addUpnpAddrRow())); + connect(btUpnpQuery, SIGNAL(clicked()), this, SLOT(queryUpnpAddr())); directc2cLayout->addWidget(rbDisableDirectConns); directc2cLayout->addWidget(rbEnableOutgoingConns); directc2cLayout->addWidget(rbEnableIncomingConns); -#ifdef HAVE_LIBMINIUPNPC - directc2cLayout->addWidget(cbEnableUPnP); -#endif - directc2cLayout->addWidget(lbAddr); - directc2cLayout->addWidget(addr); - directc2cLayout->addWidget(lbPubPort); - directc2cLayout->addWidget(publicPort); - directc2cLayout->addWidget(lbLocPort); - directc2cLayout->addWidget(localPort); + directc2cLayout->addWidget(incomingBox); directc2cLayout->addStretch(1); directc2ctab->setLayout(directc2cLayout); @@ -113,8 +272,408 @@ SettingsDialog::SettingsDialog(QWidget *parent) : multilogintab->setLayout(multiloginlayout); +// Audio Devices + audioDriver = nullptr; +#ifdef Q_OS_LINUX + QLabel *lbAudioDriver = new QLabel(tr("Audio system")); + + // ALSA is always there; PulseAudio is what a desktop session normally + // runs (PipeWire included, through its PulseAudio interface) and is the + // one that can hand us a device with the echo already cancelled. + audioDriver = new QComboBox(this); + audioDriver->addItem(tr("ALSA"), QStringLiteral("alsa")); + audioDriver->addItem(tr("PulseAudio / PipeWire"), QStringLiteral("pulse")); + + // Set before the device lists are filled, since Enumerate() asks it which + // driver's names to go looking for. + { + Settings drvst(config_dbname); + QString drv = drvst.loadValue("audio.driver", "alsa").toString(); + AudioDevice::SetLinuxDriverName(drv); + int drvItem = audioDriver->findData(drv); + if (drvItem >= 0) + audioDriver->setCurrentIndex(drvItem); + } + + connect(audioDriver, SIGNAL(currentIndexChanged(int)), this, SLOT(audioDriverChanged(int))); +#endif + + QLabel *lbAudioCaptureDev = new QLabel(tr("Microphone Device 🎙️")); + QLabel *lbAudioPlaybackDev = new QLabel(tr("Playback device 🎧")); + QLabel *lbAudioRingDev = new QLabel(tr("Ring device 🔔☎️")); + + audioCaptureDev = new QComboBox(this); + audioCaptureDev->setMinimumHeight(audioCaptureDev->height() * 2); + fillAudioCaptureDevices(); + + audioPlaybackDev = new QComboBox(this); + audioPlaybackDev->setMinimumHeight(audioPlaybackDev->height() * 2); + fillAudioPlaybackDevices(); + + audioRingDev = new QComboBox(this); + audioRingDev->setMinimumHeight(audioRingDev->height() * 2); + fillAudioRingDevices(); + + btAudioTest = new QPushButton(tr("Test 🎙️"), this); + connect(btAudioTest, SIGNAL(clicked()), this, SLOT(toggleAudioTest())); + + audioTestStatus = new QLabel(this); + audioTestStatus->setAlignment(Qt::AlignCenter); + + // Echo cancellation: removing the sound of the other person coming back + // out of the microphone, which is what makes them hear themselves when + // the call is on speakers. Exactly one of the three - two cancellers in + // series is worse than either alone, since the second one is left + // chasing a reference that is no longer in the signal. + QGroupBox *gbEchoCancel = new QGroupBox(tr("Audio echo cancellation"), this); + QVBoxLayout *echoCancelLayout = new QVBoxLayout(); + + // Parented to the group box, not the dialog: QRadioButton's automatic + // exclusivity groups by parent widget, and these three must not join the + // direct connection or multiple login buttons. + rbEchoCancelOwn = new QRadioButton(tr("Use own echo cancellation"), gbEchoCancel); + rbEchoCancelOwn->setToolTip(tr("Cancels the echo inside Pica Pica, using WebRTC's AEC3. " + "Works with any microphone and any sound system, and is the " + "only option where the platform provides nothing.")); + + rbEchoCancelPlatform = new QRadioButton(tr("Use platform provided echo cancellation"), gbEchoCancel); + + rbEchoCancelNone = new QRadioButton(tr("Disable echo cancellation"), gbEchoCancel); + rbEchoCancelNone->setToolTip(tr("Nothing is removed from the microphone signal. Right with a " + "headset, where there is no echo to cancel, and worth trying " + "if cancellation is cutting into your speech.")); + + echoCancelLayout->addWidget(rbEchoCancelOwn); + echoCancelLayout->addWidget(rbEchoCancelPlatform); + echoCancelLayout->addWidget(rbEchoCancelNone); + gbEchoCancel->setLayout(echoCancelLayout); + + // Fills in the platform option's tooltip and greys it out where there is + // no such thing. loadSettings() runs afterwards and is what actually + // picks one of the three. + updateEchoCancellationChoices(); + + btRingTest = new QPushButton(tr("Test ring 🔔"), this); + connect(btRingTest, SIGNAL(clicked()), this, SLOT(toggleRingTest())); + + ringTestStatus = new QLabel(this); + ringTestStatus->setAlignment(Qt::AlignCenter); + + // The microphone test covers the capture and playback devices, so it sits + // with them, above the unrelated ring device below. +#ifdef Q_OS_LINUX + audiodevlayout->addWidget(lbAudioDriver); + audiodevlayout->addWidget(audioDriver); +#endif + audiodevlayout->addWidget(lbAudioCaptureDev); + audiodevlayout->addWidget(audioCaptureDev); + audiodevlayout->addWidget(lbAudioPlaybackDev); + audiodevlayout->addWidget(audioPlaybackDev); + audiodevlayout->addWidget(gbEchoCancel); + audiodevlayout->addWidget(btAudioTest); + audiodevlayout->addWidget(audioTestStatus); + audiodevlayout->addWidget(lbAudioRingDev); + audiodevlayout->addWidget(audioRingDev); + audiodevlayout->addWidget(btRingTest); + audiodevlayout->addWidget(ringTestStatus); + audiodevlayout->addStretch(1); + + audiodevtab->setLayout(audiodevlayout); + + // Capture+encode and decode+playback ends of the test, each blocking its + // own thread while running, exactly as they do during a call. They stay + // idle until the Test button is pressed. + audioTestState = AudioTestIdle; + audioTestPlaybackPos = 0; + + audioTestRecordTimer = new QTimer(this); + audioTestRecordTimer->setSingleShot(true); + connect(audioTestRecordTimer, SIGNAL(timeout()), this, SLOT(audioTestRecordingFinished())); + + audioTestPlaybackTimer = new QTimer(this); + // A coarse timer is no use at this interval. Windows' default system + // timer granularity is 15.6 ms, so a coarse 20 ms timer really fires + // about every 31 ms; PreciseTimer asks for a multimedia timer instead. + // audioTestFeedPacket() does not rely on this being exact, but the closer + // it is the smoother the playback. + audioTestPlaybackTimer->setTimerType(Qt::PreciseTimer); + connect(audioTestPlaybackTimer, SIGNAL(timeout()), this, SLOT(audioTestFeedPacket())); + + audioTestDrainTimer = new QTimer(this); + audioTestDrainTimer->setSingleShot(true); + connect(audioTestDrainTimer, SIGNAL(timeout()), this, SLOT(audioTestPlaybackFinished())); + + testMic = new AudioDevice(); + testMic->moveToThread(&testMicThread); + connect(testMic, SIGNAL(packetReady(QByteArray)), this, SLOT(audioTestPacket(QByteArray))); + connect(testMic, SIGNAL(errorOccurred(QString)), this, SLOT(audioTestError(QString))); + connect(testMic, SIGNAL(deviceFormatInUse(QString)), this, SLOT(audioTestPath(QString))); + testMicThread.start(); + + testSpeaker = new AudioDevice(); + testSpeaker->moveToThread(&testSpeakerThread); + connect(testSpeaker, SIGNAL(errorOccurred(QString)), this, SLOT(audioTestError(QString))); + connect(testSpeaker, SIGNAL(deviceFormatInUse(QString)), this, SLOT(audioTestPath(QString))); + testSpeakerThread.start(); + + ringTestRunning = false; + ringTestPlayer = new TonePlayer(); + ringTestPlayer->moveToThread(&ringTestPlayerThread); + connect(ringTestPlayer, SIGNAL(finishedPlaying()), this, SLOT(ringTestFinished())); + connect(ringTestPlayer, SIGNAL(errorOccured(QString)), this, SLOT(ringTestError(QString))); + ringTestPlayerThread.start(); + +//Video Devices + videoDev = new QComboBox(this); + videoDev->setMinimumHeight(videoDev->height() * 2); + fillVideoDevices(); + videoDevRefresh = new QPushButton(tr("Refresh 🔄"), this); + connect(videoDevRefresh, SIGNAL(clicked()), this, SLOT(fillVideoDevices())); + + QLabel *lbVideoRes = new QLabel(tr("Resolution"), this); + videoRes = new QComboBox(this); + videoRes->setToolTip(tr("Picture sizes the selected camera offers. A size the camera can " + "deliver already compressed lists the formats in brackets; those " + "are the ones the \"prefer compressed formats\" setting below can " + "forward untouched, without decoding and re-encoding them here.")); + + QLabel *lbVideoFps = new QLabel(tr("Frame rate"), this); + videoFps = new QComboBox(this); + videoFps->setToolTip(tr("Frame rates the camera offers at the selected size.")); + + // Filled from the camera the device list above has selected, so the two + // have to follow it - and each other. + fillVideoResolutions(); + connect(videoDev, SIGNAL(currentIndexChanged(int)), this, SLOT(fillVideoResolutions())); + connect(videoRes, SIGNAL(currentIndexChanged(int)), this, SLOT(fillVideoFrameRates())); + + QHBoxLayout *videoFormatLayout = new QHBoxLayout(); + videoFormatLayout->addWidget(lbVideoRes); + videoFormatLayout->addWidget(videoRes, 1); + videoFormatLayout->addWidget(lbVideoFps); + videoFormatLayout->addWidget(videoFps); + + cbPreferCompressed = new QCheckBox(tr("Prefer compressed formats if provided by the camera"), this); + +#ifdef HAVE_VAAPI + cbVaapiEncoding = new QCheckBox(tr("enable VAAPI-accelerated hardware encoding"), this); + cbVaapiDecoding = new QCheckBox(tr("enable VAAPI-accelerated hardware decoding"), this); + cbVaapiRendering = new QCheckBox(tr("enable VAAPI accelerated hardware rendering"), this); + // Drawing a VA surface means having decoded into one first, so rendering + // brings decoding along with it whether or not it was asked for. + cbVaapiRendering->setToolTip(tr("Requires hardware decoding, which is enabled along with it")); + offerAcceleration(cbVaapiEncoding, VideoAccelerationVaapi, true); + offerAcceleration(cbVaapiDecoding, VideoAccelerationVaapi, false); +#endif + +#ifdef Q_OS_WIN + // Encoding and decoding side by side rather than one checkbox per line: + // five lines of them would push the preview below off a small screen. + QGroupBox *gbHwAccel = new QGroupBox(tr("GPU acceleration"), this); + QGridLayout *hwAccelLayout = new QGridLayout(); + int encodingRow = 1; + int decodingRow = 1; + + hwAccelLayout->addWidget(new QLabel(tr("Encoding:"), this), 0, 0); + hwAccelLayout->addWidget(new QLabel(tr("Decoding:"), this), 0, 1); + + // Listed in the order VideoDevice tries them, which is what decides the + // one used when several are ticked. +#ifdef HAVE_D3D12VA + cbD3d12vaEncoding = new QCheckBox(tr("Direct3D 12"), this); + cbD3d12vaEncoding->setToolTip(tr("Encodes on the GPU through Direct3D 12 Video. Needs a " + "recent Windows and a GPU driver that implements Direct3D " + "12 video encoding.\n" + "Tried before Media Foundation when both are ticked.")); + offerAcceleration(cbD3d12vaEncoding, VideoAccelerationD3d12va, true); + hwAccelLayout->addWidget(cbD3d12vaEncoding, encodingRow++, 0); +#endif + + cbMediaFoundationEncoding = new QCheckBox(tr("Media Foundation"), this); + cbMediaFoundationEncoding->setToolTip(tr("Encodes on the GPU through the hardware encoder " + "the GPU driver registers with Windows. Works with " + "older GPUs and drivers too. Microsoft's software " + "encoder is never used through this - without a " + "hardware one, encoding falls back to libx264.")); + offerAcceleration(cbMediaFoundationEncoding, VideoAccelerationMediaFoundation, true); + hwAccelLayout->addWidget(cbMediaFoundationEncoding, encodingRow++, 0); + + cbD3d11vaDecoding = new QCheckBox(tr("Direct3D 11"), this); + cbD3d11vaDecoding->setToolTip(tr("Decodes on the GPU through Direct3D 11 Video, the most " + "widely supported way on Windows 8 and later.\n" + "Tried first when several are ticked.")); + offerAcceleration(cbD3d11vaDecoding, VideoAccelerationD3d11va, false); + hwAccelLayout->addWidget(cbD3d11vaDecoding, decodingRow++, 1); + +#ifdef HAVE_D3D12VA + cbD3d12vaDecoding = new QCheckBox(tr("Direct3D 12"), this); + cbD3d12vaDecoding->setToolTip(tr("Decodes on the GPU through Direct3D 12 Video.\n" + "Tried after Direct3D 11 when both are ticked.")); + offerAcceleration(cbD3d12vaDecoding, VideoAccelerationD3d12va, false); + hwAccelLayout->addWidget(cbD3d12vaDecoding, decodingRow++, 1); +#endif + + cbDxva2Decoding = new QCheckBox(tr("DXVA2"), this); + cbDxva2Decoding->setToolTip(tr("Decodes on the GPU through DirectX Video Acceleration 2, " + "on top of Direct3D 9 - for GPUs and drivers too old for " + "the others.\nTried last when several are ticked.")); + offerAcceleration(cbDxva2Decoding, VideoAccelerationDxva2, false); + hwAccelLayout->addWidget(cbDxva2Decoding, decodingRow++, 1); + + gbHwAccel->setLayout(hwAccelLayout); +#endif + + btVideoTest = new QPushButton(tr("Test 📷"), this); + connect(btVideoTest, SIGNAL(clicked()), this, SLOT(toggleVideoTest())); + + videoPreview = new QLabel(this); + videoPreview->setAlignment(Qt::AlignCenter); + videoPreview->setMinimumSize(320, 240); + videoPreview->setFrameShape(QFrame::StyledPanel); + // A label holding a pixmap reports that pixmap's size as its minimum, which + // would stop the dialog being made smaller than the last frame drawn - and + // since each frame is drawn at the size of this label, the label could then + // never shrink either. Ignored breaks that: the label takes the space the + // layout gives it and asks for none. The status text it shows between tests + // has the 320x240 minimum above to sit in. + videoPreview->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); + videoPreview->installEventFilter(this); + + videoTestStatus = new QLabel(this); + // Left aligned, not centred: this line grows and shrinks as the frame + // rate is measured and re-measured, and centring it makes the whole text + // jump sideways every time it changes length. + videoTestStatus->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); + +#ifdef HAVE_VAAPI + videoPreviewGpu = VaapiRenderWidget::create(this); + // Letterboxes the surface itself, so it only needs to be given the room. + videoPreviewGpu->widget()->setMinimumSize(320, 240); + videoPreviewGpu->widget()->hide(); + connect(videoPreviewGpu->widget(), SIGNAL(renderingFailed(QString)), this, SLOT(videoTestRenderFailed(QString))); +#endif + + videodevLayout->addWidget(videoDev); + videodevLayout->addWidget(videoDevRefresh); + videodevLayout->addLayout(videoFormatLayout); + videodevLayout->addWidget(cbPreferCompressed); +#ifdef HAVE_VAAPI + videodevLayout->addWidget(cbVaapiEncoding); + videodevLayout->addWidget(cbVaapiDecoding); + videodevLayout->addWidget(cbVaapiRendering); +#endif +#ifdef Q_OS_WIN + videodevLayout->addWidget(gbHwAccel); +#endif + videodevLayout->addWidget(btVideoTest); + // The preview takes the tab's spare height, where it used to go to a spacer + // at the bottom. Only one of the two preview widgets is ever visible and a + // hidden widget is given no space, so both can be stretched. + videodevLayout->addWidget(videoPreview, 1); +#ifdef HAVE_VAAPI + videodevLayout->addWidget(videoPreviewGpu->widget(), 1); +#endif + videodevLayout->addWidget(videoTestStatus); + + videodevtab->setLayout(videodevLayout); + + // Recomputes the frame rates in the status line once a second, which is + // long enough for the number to sit still and be read. + videoFpsTimer = new QTimer(this); + videoFpsTimer->setInterval(1000); + connect(videoFpsTimer, SIGNAL(timeout()), this, SLOT(videoFpsTick())); + + // Capture+encode and decode ends of the test pipeline, each blocking its + // own thread while running, exactly as they do during a call. They stay + // idle until the Test button is pressed. videoTestRunning is already false + // from the top of this constructor, where the preview needed it. + testVideoSeq = 0; + + testCam = new VideoDevice(); + testCam->moveToThread(&testCamThread); + connect(testCam, SIGNAL(captureStarted(QString,int,int,double)), this, SLOT(videoTestCaptureStarted(QString,int,int,double))); + connect(testCam, SIGNAL(packetReady(QByteArray,bool)), this, SLOT(videoTestFragment(QByteArray,bool))); + connect(testCam, SIGNAL(errorOccurred(QString)), this, SLOT(videoTestError(QString))); + connect(testCam, SIGNAL(accelerationInUse(QString)), this, SLOT(videoTestPath(QString))); + testCamThread.start(); + + testDecoder = new VideoDevice(); + testDecoder->moveToThread(&testDecoderThread); + connect(testDecoder, SIGNAL(frameReady(QImage)), this, SLOT(videoTestFrame(QImage))); + connect(testDecoder, SIGNAL(errorOccurred(QString)), this, SLOT(videoTestError(QString))); + connect(testDecoder, SIGNAL(accelerationInUse(QString)), this, SLOT(videoTestPath(QString))); +#ifdef HAVE_VAAPI + connect(testDecoder, SIGNAL(hwFrameReady(AVFramePtr)), this, SLOT(videoTestHwFrame(AVFramePtr))); +#endif + testDecoderThread.start(); + +//Call Settings + // What a call encodes with. The codec names stored here are FFmpeg names, + // which is also how the 0x74 and 0x75 messages name them - see + // callsettings.h. + callVideoCodec = new QComboBox(this); + + for (int i = 0; i < kCallVideoCodecCount; i++) + callVideoCodec->addItem(QLatin1String(kCallVideoCodecs[i].displayName), + QLatin1String(kCallVideoCodecs[i].name)); + + callVideoCodec->setToolTip(tr("What outgoing video is encoded with. The peer is told which " + "codec is in use, so it does not have to be one it was " + "configured for.\n\n" + "This applies to video encoded here. With \"prefer compressed " + "formats\" switched on and a camera that delivers a compressed " + "stream itself, that stream is forwarded as it comes and the " + "camera's format is what the peer receives - this setting then " + "only decides which of the camera's formats is preferred.")); + + callAudioCodec = new QComboBox(this); + + for (int i = 0; i < kCallAudioCodecCount; i++) + callAudioCodec->addItem(QLatin1String(kCallAudioCodecs[i].displayName), + QLatin1String(kCallAudioCodecs[i].name)); + + callAudioCodec->setToolTip(tr("What outgoing audio is encoded with. Opus is the one to want " + "for a voice call; G.722 and G.711 A-law are the telephony " + "codecs, fixed at 64 kbit/s and there for compatibility.")); + + callVideoBitrate = new QSpinBox(this); + callVideoBitrate->setRange(kMinVideoBitrateKbps, kMaxVideoBitrateKbps); + callVideoBitrate->setSuffix(tr(" kbps")); + callVideoBitrate->setValue(kDefaultVideoBitrateKbps); + + callAudioBitrate = new QSpinBox(this); + callAudioBitrate->setRange(kMinAudioBitrateKbps, kMaxAudioBitrateKbps); + callAudioBitrate->setSuffix(tr(" kbps")); + callAudioBitrate->setValue(kDefaultAudioBitrateKbps); + audioBitrateKbps = kDefaultAudioBitrateKbps; + + connect(callAudioCodec, SIGNAL(currentIndexChanged(int)), this, SLOT(callAudioCodecChanged())); + + QFormLayout *callFormLayout = new QFormLayout(); + callFormLayout->addRow(tr("Video Codec"), callVideoCodec); + callFormLayout->addRow(tr("Video Bitrate"), callVideoBitrate); + callFormLayout->addRow(tr("Audio Codec"), callAudioCodec); + callFormLayout->addRow(tr("Audio Bitrate"), callAudioBitrate); + + // The other half of what a call is started with lives on the video tab, + // next to the camera that has to deliver it; say so rather than leaving + // this tab looking like the whole story. + QLabel *lbCallHint = new QLabel(tr("The picture size and frame rate a call is started with are " + "on the Video Devices tab, next to the camera that has to " + "deliver them."), this); + lbCallHint->setWordWrap(true); + + callLayout->addLayout(callFormLayout); + callLayout->addWidget(lbCallHint); + callLayout->addStretch(1); + + calltab->setLayout(callLayout); + tabW->addTab(directc2ctab, tr("Direct Connections")); tabW->addTab(multilogintab, tr("Multiple logins")); + tabW->addTab(audiodevtab, tr("Audio Devices")); + tabW->addTab(videodevtab, tr("Video Devices")); + tabW->addTab(calltab, tr("Call Settings")); tabW->addTab(soundstab, tr("Sounds")); settingsLayout->addWidget(tabW); @@ -139,14 +698,1295 @@ SettingsDialog::SettingsDialog(QWidget *parent) : setWindowTitle(tr("Pica Pica Messenger Settings")); } -void SettingsDialog::toggleIncomingConnections(bool checked) +SettingsDialog::~SettingsDialog() { - addr->setEnabled(checked); - publicPort->setEnabled(checked); - localPort->setEnabled(checked); -#ifdef HAVE_LIBMINIUPNPC - cbEnableUPnP->setEnabled(checked); + // Stops the loops first - the threads cannot finish while Capture()/Play() + // are still running inside them. + testCam->Close(); + testDecoder->Close(); + testMic->Close(); + testSpeaker->Close(); + + testCamThread.quit(); + testCamThread.wait(); + delete testCam; + + testDecoderThread.quit(); + testDecoderThread.wait(); + delete testDecoder; + + testMicThread.quit(); + testMicThread.wait(); + delete testMic; + + testSpeakerThread.quit(); + testSpeakerThread.wait(); + delete testSpeaker; + + // Same reasoning: stop() first, since the thread cannot finish while + // TonePlayer::play() is still running inside it. + ringTestPlayer->stop(); + ringTestPlayerThread.quit(); + ringTestPlayerThread.wait(); + delete ringTestPlayer; +} + +void SettingsDialog::toggleRingTest() +{ + if (ringTestRunning) + { + // stop() only sets an atomic flag, so it is safe to call directly on + // a TonePlayer whose thread is blocked inside play(). + ringTestPlayer->stop(); + ringTestRunning = false; + btRingTest->setText(tr("Test ring 🔔")); + ringTestStatus->clear(); + return; + } + + QString dev = audioRingDev->itemData(audioRingDev->currentIndex()).toString(); + + if (dev.isEmpty()) + { + ringTestStatus->setText(tr("No ring device selected")); + return; + } + + ringTestRunning = true; + btRingTest->setText(tr("Stop ⏹")); + ringTestStatus->setText(tr("Ringing...")); + + // Same sequence AudioVideoCallController::playRingTone() uses for a real + // incoming call: clear any tone still playing, point the player at the + // configured device, then start the bell. + ringTestPlayer->stop(); + QMetaObject::invokeMethod(ringTestPlayer, "setDeviceName", Qt::QueuedConnection, Q_ARG(QString, dev)); + QMetaObject::invokeMethod(ringTestPlayer, "playClassicRingtone", Qt::QueuedConnection); +} + +void SettingsDialog::ringTestFinished() +{ + if (!ringTestRunning) + return; + + ringTestRunning = false; + btRingTest->setText(tr("Test ring 🔔")); + ringTestStatus->clear(); +} + +void SettingsDialog::ringTestError(QString message) +{ + ringTestRunning = false; + btRingTest->setText(tr("Test ring 🔔")); + ringTestStatus->setText(message); +} + +void SettingsDialog::toggleAudioTest() +{ + if (audioTestState != AudioTestIdle) + { + stopAudioTest(); + audioTestStatus->setText(tr("Stopped")); + return; + } + + QString dev = audioCaptureDev->itemData(audioCaptureDev->currentIndex()).toString(); + + if (dev.isEmpty()) + { + audioTestStatus->setText(tr("No microphone selected")); + return; + } + + audioTestPackets.clear(); + audioTestPlaybackPos = 0; + audioTestPathReport.clear(); + audioTestState = AudioTestRecording; + btAudioTest->setText(tr("Stop ⏹")); + audioTestStatus->setText(tr("Recording, say something...")); + + // The codec selected on the "Call Settings" tab, at the rate a call with + // it would run at - same as the video test, this exercises what the + // current selections do rather than a fixed pipeline of its own. + const QString codec = callAudioCodec->itemData(callAudioCodec->currentIndex()).toString(); + const int rate = callAudioSampleRate(codec); + const int bitrate = callAudioBitrateAdjustable(codec) ? callAudioBitrate->value() * 1000 : 0; + + testMic->openSession(testSessionId(), testSessionId()); + QMetaObject::invokeMethod(testMic, "configureCapture", Qt::QueuedConnection, + Q_ARG(QString, dev), Q_ARG(QString, codec), + Q_ARG(int, rate), Q_ARG(int, bitrate), + Q_ARG(QByteArray, testSessionId()), Q_ARG(QByteArray, testSessionId())); + QMetaObject::invokeMethod(testMic, "Capture", Qt::QueuedConnection); + + // Only a watchdog for the device failing to open at all. The recording + // window proper starts in audioTestPacket(), when the first packet shows + // up - otherwise the device's startup time comes out of the five seconds + // and the user gets a noticeably short recording. + audioTestRecordTimer->start(kAudioTestStartTimeoutMs); +} + +void SettingsDialog::audioTestPacket(QByteArray data) +{ + // Packets still in flight from the microphone thread after the recording + // phase ended are not part of the recording. + if (audioTestState != AudioTestRecording) + return; + + // First packet: the microphone is live, so start the recording window now + // rather than when the device was merely asked to open. + if (audioTestPackets.isEmpty()) + audioTestRecordTimer->start(kAudioTestRecordMs); + + audioTestPackets.append(data); +} + +void SettingsDialog::audioTestRecordingFinished() +{ + // The test may have been stopped, or have failed, while the timer ran. + if (audioTestState != AudioTestRecording) + return; + + // Direct call: the microphone thread is blocked inside Capture(), so a + // queued call would never reach it (see the comments in + // AudioVideoCallController::stopAudioPipeline()). + testMic->Close(); + + if (audioTestPackets.isEmpty()) + { + stopAudioTest(); + audioTestStatus->setText(tr("Nothing was captured")); + return; + } + + startAudioTestPlayback(); +} + +void SettingsDialog::startAudioTestPlayback() +{ + QString dev = audioPlaybackDev->itemData(audioPlaybackDev->currentIndex()).toString(); + + if (dev.isEmpty()) + { + stopAudioTest(); + audioTestStatus->setText(tr("No playback device selected")); + return; + } + + audioTestState = AudioTestPlaying; + audioTestPlaybackPos = 0; + + // The packet count is worth showing, not just decoration. Capture emits + // one packet per kAudioTestPacketMs of audio it actually received, so a + // count well under kAudioTestRecordMs/kAudioTestPacketMs means the + // recording lost samples on the way in, and anything wrong with the sound + // is a capture problem. A full count with bad sound means the samples all + // arrived and something downstream is mangling them. + QString summary = tr("Playing back %1 of %2 packets (%3 s)...") + .arg(audioTestPackets.size()) + .arg(kAudioTestRecordMs / kAudioTestPacketMs) + .arg(audioTestPackets.size() * kAudioTestPacketMs / 1000.0, 0, 'f', 1); + + if (!audioTestPathReport.isEmpty()) + summary += QLatin1String("\n") + audioTestPathReport; + + audioTestStatus->setText(summary); + + // Decoded with what it was encoded with, exactly as the receiving end of a + // call decodes with whatever the peer announced. + const QString codec = callAudioCodec->itemData(callAudioCodec->currentIndex()).toString(); + + testSpeaker->openSession(testSessionId(), testSessionId()); + QMetaObject::invokeMethod(testSpeaker, "configurePlayback", Qt::QueuedConnection, + Q_ARG(QString, dev), Q_ARG(QString, codec), + Q_ARG(int, callAudioSampleRate(codec)), + Q_ARG(QByteArray, testSessionId()), Q_ARG(QByteArray, testSessionId())); + QMetaObject::invokeMethod(testSpeaker, "Play", Qt::QueuedConnection); + + // The recording has to be handed over at the rate it plays at, not all at + // once: AudioDevice's jitter buffer holds only a few packets and drops + // the oldest when full, so dumping the whole recording into it would + // discard everything but the tail. + audioTestPlaybackClock.start(); + audioTestPlaybackTimer->start(kAudioTestPacketMs); +} + +void SettingsDialog::audioTestFeedPacket() +{ + if (audioTestState != AudioTestPlaying) + return; + + // Pace against the clock, not against the number of times this has been + // called. A QTimer asked for 20 ms does not necessarily deliver every + // 20 ms - on Windows the system timer granularity is 15.6 ms, so even a + // precise timer can run late - and handing over one packet per tick + // regardless would play the recording back at whatever rate the timer + // happened to run at. Late ticks stretched it out and left the sound card + // with nothing to play in between, which sounded like the recording was + // both slowed down and chopped up. + // + // The real call path has no equivalent problem: there the packets are + // paced by the peer sending them, not by a timer here. + const qint64 due = audioTestPlaybackClock.elapsed() / kAudioTestPacketMs + 1; + + while (audioTestPlaybackPos < audioTestPackets.size() && + (qint64)audioTestPlaybackPos < due) + { + // Direct call, for the same reason as in the call controller. Nothing + // here loses or reorders packets, so the sequence numbers are simply + // the order they were recorded in. + testSpeaker->enqueuePacket((quint16)audioTestPlaybackPos, + audioTestPackets.at(audioTestPlaybackPos)); + audioTestPlaybackPos++; + } + + if (audioTestPlaybackPos >= audioTestPackets.size()) + { + audioTestPlaybackTimer->stop(); + // Let what is already queued, plus the sound card's own buffer, play + // out before tearing the playback device down. + audioTestDrainTimer->start(kAudioTestDrainMs); + } +} + +void SettingsDialog::audioTestPlaybackFinished() +{ + if (audioTestState != AudioTestPlaying) + return; + + stopAudioTest(); + audioTestStatus->setText(tr("Done")); +} + +void SettingsDialog::stopAudioTest() +{ + audioTestRecordTimer->stop(); + audioTestPlaybackTimer->stop(); + audioTestDrainTimer->stop(); + + // Direct calls: both devices may be blocked inside their capture/playback + // loops, where a queued call would never reach them. + testMic->Close(); + testSpeaker->Close(); + + audioTestPackets.clear(); + audioTestPlaybackPos = 0; + audioTestState = AudioTestIdle; + btAudioTest->setText(tr("Test 🎙️")); + audioTestStatus->clear(); +} + +void SettingsDialog::audioTestPath(QString description) +{ + if (description.isEmpty()) + return; + + if (!audioTestPathReport.isEmpty()) + audioTestPathReport += QLatin1String("\n"); + audioTestPathReport += description; +} + +void SettingsDialog::audioTestError(QString message) +{ + if (audioTestState == AudioTestIdle) + return; + + stopAudioTest(); + audioTestStatus->setText(message); +} + +void SettingsDialog::toggleVideoTest() +{ + if (videoTestRunning) + { + stopVideoTest(); + return; + } + + QString dev = videoDev->itemData(videoDev->currentIndex()).toString(); + + if (dev.isEmpty()) + { + videoPreview->setText(tr("No camera selected")); + return; + } + + testAssembler.reset(); + testVideoSeq = 0; + videoTestRunning = true; + btVideoTest->setText(tr("Stop ⏹")); + videoPreview->setText(tr("Starting...")); + + // Before the decoder is started, so that its very first frame comes back + // at the size the preview wants rather than the camera's own. + reportVideoPreviewArea(); + + videoTestGpuRendering = false; + videoCapturedFrames = 0; + videoDisplayedFrames = 0; + videoCaptureFps = 0.0; + videoDisplayFps = 0.0; + videoFpsElapsed.start(); + videoFpsTimer->start(); + + videoTestPathReport.clear(); + + // The settings as they stand in the dialog, not as they were last stored: + // the point of the test is to see what the current selections do before + // committing to them. + testCam->openSession(testSessionId(), testSessionId()); + QMetaObject::invokeMethod(testCam, "configureCapture", Qt::QueuedConnection, + Q_ARG(QString, dev), + Q_ARG(int, selectedVideoWidth()), Q_ARG(int, selectedVideoHeight()), + Q_ARG(int, selectedVideoFrameRate()), + Q_ARG(bool, cbPreferCompressed->isChecked()), + Q_ARG(QString, callVideoCodec->itemData(callVideoCodec->currentIndex()).toString()), + Q_ARG(int, callVideoBitrate->value() * 1000), + Q_ARG(int, selectedVideoEncodingAcceleration()), + Q_ARG(QByteArray, testSessionId()), Q_ARG(QByteArray, testSessionId())); + QMetaObject::invokeMethod(testCam, "Capture", Qt::QueuedConnection); + + // The decoder is only started once the camera has settled on a format, + // which is what captureStarted() reports - the same order a call follows, + // where the peer's 0x75 message arrives before its first video packet. +} + +void SettingsDialog::videoTestCaptureStarted(QString codec, int width, int height, + double frameRate) +{ + if (!videoTestRunning) + return; + + // Says which path the test is exercising: the camera's own compressed + // stream forwarded untouched, or frames decoded and re-encoded here. + // + // The rate is the one the camera settled on, and is shown whether or not + // it is the one that was asked for - a camera substituting a lower rate + // does so silently, so seeing it here is the whole point. It is not the + // same figure as the measured rate in the status line: this is what the + // camera agreed to, that is what actually arrived, and the two differing + // means something is dropping frames rather than never producing them. + videoTestFormat = frameRate > 0.0 + ? tr("%1 %2x%3 @%4").arg(codec).arg(width).arg(height) + .arg(frameRate, 0, 'f', frameRate < 10.0 ? 1 : 0) + : tr("%1 %2x%3").arg(codec).arg(width).arg(height); + videoPreview->setText(tr("Capturing %1...").arg(videoTestFormat)); + + bool vaapiRendering = false; +#ifdef HAVE_VAAPI + // Asking for frames to be kept in GPU memory once it is known that they + // cannot be drawn from there would only mean starting each test with a + // blank preview until it failed again. + vaapiRendering = cbVaapiRendering->isChecked() && !VaapiRenderWidget::renderingKnownBroken(); +#endif + + testDecoder->openSession(testSessionId(), testSessionId()); + QMetaObject::invokeMethod(testDecoder, "configurePlayback", Qt::QueuedConnection, + Q_ARG(QString, codec), + Q_ARG(int, width), Q_ARG(int, height), + Q_ARG(int, selectedVideoDecodingAcceleration()), + Q_ARG(bool, vaapiRendering), + Q_ARG(QByteArray, testSessionId()), Q_ARG(QByteArray, testSessionId())); + QMetaObject::invokeMethod(testDecoder, "Play", Qt::QueuedConnection); +} + +void SettingsDialog::videoTestPath(QString description) +{ + if (!videoTestRunning) + return; + + // Capture and playback each report once; both lines are kept so the whole + // path is visible, since either end can quietly fall back to software. + if (!videoTestPathReport.isEmpty()) + videoTestPathReport += QLatin1String(", "); + videoTestPathReport += description; +} + +void SettingsDialog::stopVideoTest() +{ + // Direct calls: both devices are blocked inside their capture/decode + // loops, so a queued call would never reach them (see the comments in + // AudioVideoCallController::stopAudioPipeline()). + testCam->Close(); + testDecoder->Close(); + + testAssembler.reset(); + testVideoSeq = 0; + videoTestRunning = false; + videoTestFormat.clear(); + videoTestPathReport.clear(); + videoTestGpuRendering = false; + videoFpsTimer->stop(); + videoCaptureFps = 0.0; + videoDisplayFps = 0.0; + btVideoTest->setText(tr("Test 📷")); + videoPreview->clear(); + videoTestStatus->clear(); + lastTestFrame = QImage(); +#ifdef HAVE_VAAPI + videoPreviewGpu->clearFrame(); + videoPreviewGpu->widget()->hide(); + videoPreview->show(); +#endif + + // Last, once the preview label is back in place: drops the display size so + // that a test started again does not begin against whatever the previous + // one left behind. videoTestRunning is already false, which is what makes + // this clear it rather than set it. + reportVideoPreviewArea(); +} + +void SettingsDialog::videoTestFragment(QByteArray data, bool is_last_fragment) +{ + if (!videoTestRunning) + return; + + // The encoder emits fragments exactly as they would go onto the wire, so + // feed them through the same assembler the receiving end of a call uses. + // The sequence number is rebuilt here the way send_video_packet() builds + // it - the counter has to be kept as well, since the assembler uses it to + // tell a fragment that follows the previous one from one that comes after + // a loss. The timestamp is constant, as nothing here can lose a fragment + // and only frame boundaries matter. + quint16 seq = testVideoSeq & VideoFrameAssembler::SeqNumMask; + + testVideoSeq = (testVideoSeq + 1) & VideoFrameAssembler::SeqNumMask; + + if (is_last_fragment) + { + seq |= VideoFrameAssembler::LastFragmentFlag; + + // One encoded frame has just been completed, which in steady state is + // one frame off the camera. Counted here rather than at the camera + // because this is also what a call would be putting on the wire. + videoCapturedFrames++; + } + + QByteArray frame = testAssembler.addFragment(seq, 0, data); + + if (frame.isEmpty()) + return; + + // Direct call, for the same reason as in the call controller. + testDecoder->enqueueFrame(frame); +} + +void SettingsDialog::videoTestFrame(QImage frame) +{ + if (!videoTestRunning || frame.isNull()) + return; + + videoDisplayedFrames++; + + // The preview itself is showing pixels now, so what format came off the + // camera and which of the GPU or CPU did the work goes underneath it. + updateVideoTestStatus(); + + lastTestFrame = frame; + updateVideoPreview(); +} + +void SettingsDialog::videoFpsTick() +{ + const qint64 elapsed = videoFpsElapsed.restart(); + + if (elapsed <= 0) + return; + + videoCaptureFps = videoCapturedFrames * 1000.0 / elapsed; + videoDisplayFps = videoDisplayedFrames * 1000.0 / elapsed; + videoCapturedFrames = 0; + videoDisplayedFrames = 0; + + updateVideoTestStatus(); +} + +void SettingsDialog::updateVideoTestStatus() +{ + if (!videoTestRunning) + return; + + QString text = videoTestFormat; + + if (!videoTestPathReport.isEmpty()) + text = tr("%1 - %2").arg(text, videoTestPathReport); + + if (videoTestGpuRendering) + text += tr(", GPU rendering"); + + // Nothing to say until the first second is up and a rate has been + // measured, and saying "0.0 fps" in the meantime would read as a fault. + if (videoCaptureFps > 0.0 || videoDisplayFps > 0.0) + { + const int asked = selectedVideoFrameRate(); + + // The two rates are usually the same, and printing both every time + // would bury the case that matters. They part company when the + // pipeline cannot keep up with the camera - frames are then dropped + // between the two, see VideoDevice::enqueueFrame(). + if (qAbs(videoCaptureFps - videoDisplayFps) > 1.0) + text += tr(", %1 fps captured, %2 shown") + .arg(videoCaptureFps, 0, 'f', 1).arg(videoDisplayFps, 0, 'f', 1); + else + text += tr(", %1 fps").arg(videoCaptureFps, 0, 'f', 1); + + // A camera asked for more than it can deliver is not obliged to say + // so - it just sends fewer frames - so the shortfall is spelled out + // rather than left for the user to notice against the setting they + // chose. Half a frame of slack, since a camera holding its rate + // still reads a little under on any one second. + if (asked > 0 && videoCaptureFps < asked - 0.5) + text += tr(" of %1 requested").arg(asked); + } + + videoTestStatus->setText(text); +} + +void SettingsDialog::updateVideoPreview() +{ + // Only while the test is running: with it stopped the preview is showing + // status text instead, and putting the last frame back over that on a + // resize would be wrong. + if (!videoTestRunning || lastTestFrame.isNull() || videoPreview->isHidden()) + return; + + // Normally a no-op - testDecoder was told the size of this area and the + // frame arrived at it already. It earns its place across a resize, when + // frames converted at the old size have still to be drawn at the new one. + QImage scaled = videoTestScaler.scale(lastTestFrame, videoPreview->size()); + + if (scaled.isNull()) + return; + + videoPreview->setPixmap(QPixmap::fromImage(scaled)); +} + +void SettingsDialog::reportVideoPreviewArea() +{ + // The preview can be resized by the layout before the decoder has been + // built; see the note at the top of the constructor. + // + // isHidden() rather than isVisible(): what matters is whether this label is + // the renderer in use, not whether the dialog is on screen. When the GPU + // widget has the preview it scales frames itself, on the GPU, and wants + // them at their own resolution - see videoTestHwFrame(). + if (!testDecoder || videoPreview->isHidden()) + return; + + // Direct call rather than invokeMethod() - testDecoder's thread is blocked + // inside Play(), so a queued call would sit behind the very loop it is + // meant to reach. Same rule as the Close() calls in stopVideoTest(). + testDecoder->setDisplaySize(videoTestRunning ? videoPreview->size() : QSize()); +} + +bool SettingsDialog::eventFilter(QObject *watched, QEvent *event) +{ + if (watched == videoPreview && event->type() == QEvent::Resize) + { + reportVideoPreviewArea(); + updateVideoPreview(); + } + + return QDialog::eventFilter(watched, event); +} + +#ifdef HAVE_VAAPI +void SettingsDialog::videoTestHwFrame(AVFramePtr frame) +{ + if (!videoTestRunning) + return; + + // The widget has given up on drawing; leave the preview area with the + // label and get the decoder to produce frames it can show. + if (!videoPreviewGpu->isWorking()) + { + testDecoder->disableHardwareRendering(); + return; + } + + // Frames arriving here never went through system memory, so the label has + // nothing to show - the GL widget takes over the preview area. + if (videoPreviewGpu->widget()->isHidden()) + { + videoPreview->hide(); + videoPreviewGpu->widget()->show(); + + // The widget scales the surface itself, on the GPU, so the decoder + // has no reason to produce frames at any particular size - and it is + // not producing these ones at all. + testDecoder->setDisplaySize(QSize()); + } + + videoDisplayedFrames++; + videoTestGpuRendering = true; + updateVideoTestStatus(); + + videoPreviewGpu->setFrame(frame); +} + +void SettingsDialog::videoTestRenderFailed(QString message) +{ + // Drawing straight from GPU memory did not work out. The decoder is still + // running, so leave the test going rather than killing it: ask it to bring + // frames back into system memory, which the label can show. The reason + // stands in the label until the first of those frames replaces it. + qWarning() << message; + + videoPreviewGpu->widget()->hide(); + videoPreview->show(); + videoPreview->setText(message); + + // The status line must stop claiming GPU rendering; frames are about to + // start coming back through system memory instead. + videoTestGpuRendering = false; + updateVideoTestStatus(); + + // Frames are about to start arriving in system memory, so the decoder needs + // the size to produce them at. Sent explicitly rather than left to the + // label's resize, which does not fire if showing it did not change its + // geometry. + reportVideoPreviewArea(); + + // Direct call, for the same reason as in videoTestFragment(). + testDecoder->disableHardwareRendering(); +} +#endif + +void SettingsDialog::videoTestError(QString message) +{ + if (!videoTestRunning) + return; + + stopVideoTest(); + videoPreview->setText(message); +} + +void SettingsDialog::fillDevicesComboBox(QComboBox *cb, MediaDevice *dev, enum MediaDeviceStreamDirection dir) +{ + cb->clear(); + QList<MediaDeviceInfo> md = dev->Enumerate(dir); + for (int i = 0; i < md.size(); i++) + { + QString item = QString(QLatin1String("%2\n(%1)")) + .arg(md.at(i).device) + .arg(md.at(i).humanReadable); + + // A camera's compressed formats are not listed here but in the + // resolution list, which is where they actually mean something: a + // camera offers them at some of its sizes and not at others, so + // naming them against the camera as a whole said less than it + // appeared to. + + cb->addItem(item, md.at(i).device); + } +} + +void SettingsDialog::fillVideoDevices() +{ + VideoDevice vd; + + // Refilling walks the current index through -1 and back, and each step + // of that would otherwise ask a camera what it can do - which is not + // free, on Windows it means instantiating the capture filter. So the + // format lists below are rebuilt once, at the end. + const QString previous = videoDev->itemData(videoDev->currentIndex()).toString(); + + videoDev->blockSignals(true); + fillDevicesComboBox(videoDev, &vd, CAPTURE); + + // Refresh is for picking up a camera that was plugged in, not for + // moving the selection off the one already chosen. + int item = videoDev->findData(previous); + if (item >= 0) + videoDev->setCurrentIndex(item); + + videoDev->blockSignals(false); + + fillVideoResolutions(); +} + +void SettingsDialog::fillVideoResolutions() +{ + // Nothing to fill into yet while the constructor is still building the + // tab - fillVideoDevices() runs before these exist. + if (!videoRes || !videoFps) + return; + + const QString dev = videoDev->itemData(videoDev->currentIndex()).toString(); + + videoFormats = dev.isEmpty() ? QList<VideoCaptureFormat>() + : VideoDevice::CaptureFormats(dev); + + // Refilling moves the current index about; the frame rate list is rebuilt + // once at the end rather than on every one of those intermediate changes. + videoRes->blockSignals(true); + videoRes->clear(); + + if (videoFormats.isEmpty()) + { + // Either the camera would not say or this platform cannot ask. Offer + // the common sizes rather than an empty list - a camera that cannot + // produce one of them is handled the same way as any other request it + // will not honour, see VideoDevice::Capture(). + for (unsigned int i = 0; i < sizeof(kFallbackResolutions) / sizeof(kFallbackResolutions[0]); i++) + { + const int w = kFallbackResolutions[i].width; + const int h = kFallbackResolutions[i].height; + + videoRes->addItem(QString(QLatin1String("%1x%2")).arg(w).arg(h), QSize(w, h)); + } + } + else + { + for (int i = 0; i < videoFormats.size(); i++) + { + const VideoCaptureFormat &f = videoFormats.at(i); + QString item = QString(QLatin1String("%1x%2")).arg(f.width).arg(f.height); + + // The formats this camera can hand over ready-made at this size, + // which is what "prefer compressed formats" below acts on. + if (!f.compressedFormats.isEmpty()) + item += QString(QLatin1String(" [%1]")).arg(f.compressedFormats.join(QLatin1String(", "))); + + videoRes->addItem(item, QSize(f.width, f.height)); + } + } + + // Keep the configured size selected across a device change where the new + // camera offers it too, rather than silently moving the setting to + // whatever happens to be first in the new list. + Settings st(config_dbname); + QSize wanted(st.loadValue("video.capture_width", kDefaultCaptureWidth).toInt(), + st.loadValue("video.capture_height", kDefaultCaptureHeight).toInt()); + + int item = videoRes->findData(wanted); + + if (item < 0) + item = videoRes->findData(QSize(kDefaultCaptureWidth, kDefaultCaptureHeight)); + + if (item >= 0) + videoRes->setCurrentIndex(item); + + videoRes->blockSignals(false); + + fillVideoFrameRates(); +} + +void SettingsDialog::fillVideoFrameRates() +{ + if (!videoFps) + return; + + const QSize size = videoRes->itemData(videoRes->currentIndex()).toSize(); + QList<int> rates; + + for (int i = 0; i < videoFormats.size(); i++) + { + if (videoFormats.at(i).width == size.width() && videoFormats.at(i).height == size.height()) + { + rates = videoFormats.at(i).frameRates; + break; + } + } + + videoFps->blockSignals(true); + videoFps->clear(); + + if (rates.isEmpty()) + { + // Same reasoning as for the sizes: a camera that named its sizes but + // not its rates, or one we could not ask at all. + for (unsigned int i = 0; i < sizeof(kFallbackFrameRates) / sizeof(kFallbackFrameRates[0]); i++) + rates << kFallbackFrameRates[i]; + } + + for (int i = 0; i < rates.size(); i++) + videoFps->addItem(tr("%1 fps").arg(rates.at(i)), rates.at(i)); + + Settings st(config_dbname); + int wanted = st.loadValue("video.capture_framerate", kDefaultCaptureFrameRate).toInt(); + + int item = videoFps->findData(wanted); + + if (item < 0) + item = videoFps->findData(kDefaultCaptureFrameRate); + + // Neither the configured rate nor the default is on offer at this size - + // take the highest the camera does offer, which is the first in the list. + if (item < 0 && videoFps->count() > 0) + item = 0; + + if (item >= 0) + videoFps->setCurrentIndex(item); + + videoFps->blockSignals(false); +} + +int SettingsDialog::selectedVideoWidth() const +{ + const QSize size = videoRes->itemData(videoRes->currentIndex()).toSize(); + + return size.isValid() ? size.width() : kDefaultCaptureWidth; +} + +int SettingsDialog::selectedVideoHeight() const +{ + const QSize size = videoRes->itemData(videoRes->currentIndex()).toSize(); + + return size.isValid() ? size.height() : kDefaultCaptureHeight; +} + +int SettingsDialog::selectedVideoFrameRate() const +{ + bool ok = false; + const int fps = videoFps->itemData(videoFps->currentIndex()).toInt(&ok); + + return (ok && fps > 0) ? fps : kDefaultCaptureFrameRate; +} + +void SettingsDialog::offerAcceleration(QCheckBox *cb, VideoAcceleration acceleration, bool encoding) +{ + if (VideoDevice::AccelerationBuiltIn(acceleration, encoding)) + return; + + cb->setEnabled(false); + cb->setToolTip(encoding + ? tr("Not available: the FFmpeg this program runs with was built without " + "these encoders.") + : tr("Not available: the FFmpeg this program runs with was built without " + "support for these decoders.")); +} + +int SettingsDialog::selectedVideoEncodingAcceleration() const +{ + int flags = 0; + + // isEnabled() as well, so that a path greyed out by offerAcceleration() + // but ticked in a stored setting is not passed on - it would only be + // skipped with a warning further down. +#ifdef HAVE_VAAPI + if (cbVaapiEncoding->isEnabled() && cbVaapiEncoding->isChecked()) + flags |= VideoAccelerationVaapi; +#endif +#ifdef HAVE_D3D12VA + if (cbD3d12vaEncoding->isEnabled() && cbD3d12vaEncoding->isChecked()) + flags |= VideoAccelerationD3d12va; #endif +#ifdef Q_OS_WIN + if (cbMediaFoundationEncoding->isEnabled() && cbMediaFoundationEncoding->isChecked()) + flags |= VideoAccelerationMediaFoundation; +#endif + + return flags; +} + +int SettingsDialog::selectedVideoDecodingAcceleration() const +{ + int flags = 0; + +#ifdef HAVE_VAAPI + if (cbVaapiDecoding->isEnabled() && cbVaapiDecoding->isChecked()) + flags |= VideoAccelerationVaapi; +#endif +#ifdef HAVE_D3D12VA + if (cbD3d12vaDecoding->isEnabled() && cbD3d12vaDecoding->isChecked()) + flags |= VideoAccelerationD3d12va; +#endif +#ifdef Q_OS_WIN + if (cbD3d11vaDecoding->isEnabled() && cbD3d11vaDecoding->isChecked()) + flags |= VideoAccelerationD3d11va; + if (cbDxva2Decoding->isEnabled() && cbDxva2Decoding->isChecked()) + flags |= VideoAccelerationDxva2; +#endif + + return flags; +} + +void SettingsDialog::callAudioCodecChanged() +{ + const QString codec = callAudioCodec->itemData(callAudioCodec->currentIndex()).toString(); + + if (callAudioBitrateAdjustable(codec)) + { + // Coming back from a fixed rate codec, whose rate is showing in the + // box; the user's own choice is in audioBitrateKbps. + if (!callAudioBitrate->isEnabled()) + { + callAudioBitrate->setEnabled(true); + callAudioBitrate->setValue(audioBitrateKbps); + callAudioBitrate->setToolTip(QString()); + } + + return; + } + + if (callAudioBitrate->isEnabled()) + audioBitrateKbps = callAudioBitrate->value(); + + // Show what the codec will actually run at rather than leaving a number + // behind that has nothing to do with it. + callAudioBitrate->setEnabled(false); + callAudioBitrate->setValue(callAudioFixedBitrateKbps(codec)); + callAudioBitrate->setToolTip(tr("This codec codes a fixed number of bits per sample, so its " + "bitrate follows from the sample rate and cannot be chosen.")); +} + +void SettingsDialog::audioDriverChanged(int index) +{ + Q_UNUSED(index) + + if (!audioDriver) + return; + + // Take effect straight away rather than on OK, so the device lists below + // show the right names and the Test button uses them. + AudioDevice::SetLinuxDriverName(audioDriver->itemData(audioDriver->currentIndex()).toString()); + + fillAudioCaptureDevices(); + fillAudioPlaybackDevices(); + fillAudioRingDevices(); + + // ALSA has no echo cancellation of its own and PulseAudio does, so the + // platform option comes and goes with this choice. + updateEchoCancellationChoices(); +} + +void SettingsDialog::updateEchoCancellationChoices() +{ + // PlatformDriverName() reads the driver SetLinuxDriverName() published, + // which audioDriverChanged() has already updated by the time it calls + // this - so the answer follows the combo box rather than the saved + // setting. + const QString driver = AudioDevice::PlatformDriverName(CAPTURE); + const bool available = AudioDevice::PlatformEchoCancellationAvailable(driver); + + rbEchoCancelPlatform->setEnabled(available); + + if (available) + { + rbEchoCancelPlatform->setToolTip(tr("Lets the operating system or sound server cancel the " + "echo instead. Where it exists this is the better " + "one: it sits below Pica Pica and can see the real " + "speaker signal and the real clock.\n\n" + "With PulseAudio or PipeWire it also means picking an " + "echo cancelling source as the microphone above - a " + "plain input device is not processed.")); + } + else + { + rbEchoCancelPlatform->setToolTip(tr("Not available: the audio system in use does not " + "cancel echo for us.")); + + // A disabled button that is still the checked one would leave the + // group showing a choice that is not in effect. + if (rbEchoCancelPlatform->isChecked()) + rbEchoCancelOwn->setChecked(true); + } +} + +void SettingsDialog::fillAudioCaptureDevices() +{ + AudioDevice acd; + fillDevicesComboBox(audioCaptureDev, &acd, CAPTURE); +} + +void SettingsDialog::fillAudioPlaybackDevices() +{ + AudioDevice apd; + fillDevicesComboBox(audioPlaybackDev, &apd, PLAYBACK); +} + +void SettingsDialog::fillAudioRingDevices() +{ + AudioDevice ard; + fillDevicesComboBox(audioRingDev, &ard, PLAYBACK); +} + +void SettingsDialog::toggleIncomingConnections(bool checked) +{ + Q_UNUSED(checked); + + updateDirectConnWidgets(); +} + +void SettingsDialog::updateDirectConnWidgets() +{ + bool upnp = cbEnableUPnP && cbEnableUPnP->isChecked(); + + incomingBox->setEnabled(rbEnableIncomingConns->isChecked()); + lbAutoAddrs->setEnabled(rbAddrAuto->isChecked()); + manualBox->setEnabled(rbAddrManual->isChecked()); + btAddrUpnp->setEnabled(upnp); + + updateAutoAddrsLabel(); +} + +void SettingsDialog::updateAutoAddrsLabel() +{ + in_addr_t ifaddrs[PICA_IFADDRS_MAX]; + QStringList addrs; + int n; + + n = PICA_get_ifaddrs_ipv4(ifaddrs, PICA_IFADDRS_MAX); + + for (int i = 0; i < n; i++) + { + struct in_addr in; + + in.s_addr = ifaddrs[i]; + addrs.append(QString::fromLatin1(inet_ntoa(in))); + } + + QString text = addrs.isEmpty() + ? tr("No network interface address found.") + : tr("Announced to peers: %1, port %2 or the next free one") + .arg(addrs.join(", ")).arg(DirectC2CSettings::DefaultPort); + + if (cbEnableUPnP && cbEnableUPnP->isChecked()) + text += tr(", followed by the external address of the UPnP router with the forwarded port."); + else + text += "."; + + lbAutoAddrs->setText(text); +} + +void SettingsDialog::addAddrRow(const QString &host, int port, bool upnp) +{ + int row = addrTable->rowCount(); + QTableWidgetItem *hostItem, *portItem; + + addrTable->insertRow(row); + + if (upnp) + { + // Filled in at run time, so there is nothing to edit; the role marks + // it as the UPnP entry. + hostItem = new QTableWidgetItem(tr("UPnP router's external address")); + portItem = new QTableWidgetItem(tr("forwarded port")); + hostItem->setData(Qt::UserRole, true); + hostItem->setFlags(hostItem->flags() & ~Qt::ItemIsEditable); + portItem->setFlags(portItem->flags() & ~Qt::ItemIsEditable); + } + else + { + hostItem = new QTableWidgetItem(host); + portItem = new QTableWidgetItem(QString::number(port)); + } + + addrTable->setItem(row, 0, hostItem); + addrTable->setItem(row, 1, portItem); +} + +bool SettingsDialog::addrRowIsUpnp(int row) const +{ + QTableWidgetItem *item = addrTable->item(row, 0); + + return item && item->data(Qt::UserRole).toBool(); +} + +void SettingsDialog::addAddr() +{ + addAddrRow(QString(), localPort->value(), false); + + addrTable->setCurrentCell(addrTable->rowCount() - 1, 0); + addrTable->editItem(addrTable->item(addrTable->rowCount() - 1, 0)); +} + +void SettingsDialog::removeAddr() +{ + int row = addrTable->currentRow(); + + if (row >= 0) + addrTable->removeRow(row); +} + +static void swapTableRows(QTableWidget *t, int a, int b) +{ + for (int col = 0; col < t->columnCount(); col++) + { + QTableWidgetItem *ia = t->takeItem(a, col); + QTableWidgetItem *ib = t->takeItem(b, col); + + t->setItem(a, col, ib); + t->setItem(b, col, ia); + } +} + +void SettingsDialog::moveAddrUp() +{ + int row = addrTable->currentRow(); + + if (row <= 0) + return; + + swapTableRows(addrTable, row, row - 1); + addrTable->setCurrentCell(row - 1, addrTable->currentColumn()); +} + +void SettingsDialog::moveAddrDown() +{ + int row = addrTable->currentRow(); + + if (row < 0 || row + 1 >= addrTable->rowCount()) + return; + + swapTableRows(addrTable, row, row + 1); + addrTable->setCurrentCell(row + 1, addrTable->currentColumn()); +} + +void SettingsDialog::addInterfaceAddrs() +{ + in_addr_t ifaddrs[PICA_IFADDRS_MAX]; + int n; + + // private addresses come first already, as they should in the list + n = PICA_get_ifaddrs_ipv4(ifaddrs, PICA_IFADDRS_MAX); + + for (int i = 0; i < n; i++) + { + struct in_addr in; + QString host; + bool present = false; + + in.s_addr = ifaddrs[i]; + host = QString::fromLatin1(inet_ntoa(in)); + + for (int row = 0; row < addrTable->rowCount(); row++) + if (!addrRowIsUpnp(row) && addrTable->item(row, 0)->text().trimmed() == host + && addrTable->item(row, 1)->text().trimmed().toInt() == localPort->value()) + present = true; + + if (!present) + addAddrRow(host, localPort->value(), false); + } + + if (n == 0) + lbUpnpInfo->setText(tr("No network interface address found.")); +} + +void SettingsDialog::addUpnpAddrRow() +{ + for (int row = 0; row < addrTable->rowCount(); row++) + if (addrRowIsUpnp(row)) + { + addrTable->setCurrentCell(row, 0); + return; + } + + addAddrRow(QString(), 0, true); +} + +void SettingsDialog::queryUpnpAddr() +{ + std::shared_ptr<int> status = std::make_shared<int>(PICA_UPNP_ERRNOIGD); + std::shared_ptr<QString> result = std::make_shared<QString>(); + + btUpnpQuery->setEnabled(false); + lbUpnpInfo->setText(tr("Asking the UPnP router...")); + + // Parentless and deleting itself when done: the dialog may be closed + // before the router answers, and a QThread must not be destroyed while it + // runs. The answer only reaches the dialog if it is still there. + QThread *t = QThread::create([status, result]() + { + struct PICA_upnp_ctx *ctx = nullptr; + char addr[64]; + int ret; + + ret = PICA_upnp_discover(PICA_UPNP_DISCOVER_TIMEOUT, &ctx); + + if (ret == PICA_UPNP_OK) + { + ret = PICA_upnp_external_addr(ctx, addr, sizeof(addr)); + + if (ret == PICA_UPNP_OK) + *result = QString::fromLatin1(addr); + + PICA_upnp_free(ctx); + } + + *status = ret; + }); + + connect(t, &QThread::finished, t, &QObject::deleteLater); + connect(t, &QThread::finished, this, [this, status, result]() + { + upnpQueryFinished(*status, *result); + }); + + t->start(); +} + +void SettingsDialog::upnpQueryFinished(int status, QString addr) +{ + btUpnpQuery->setEnabled(true); + + if (status != PICA_UPNP_OK) + { + lbUpnpInfo->setText(tr("UPnP: %1").arg(PICA_upnp_strerror(status))); + return; + } + + lbUpnpInfo->setText(tr("The router's external address is %1. Unless UPnP is enabled above, " + "the port has to be forwarded on the router by hand.").arg(addr)); + + for (int row = 0; row < addrTable->rowCount(); row++) + if (!addrRowIsUpnp(row) && addrTable->item(row, 0)->text().trimmed() == addr) + return; + + addAddrRow(addr, localPort->value(), false); +} + +bool SettingsDialog::validateAddrTable() +{ + bool upnp = cbEnableUPnP && cbEnableUPnP->isChecked(); + int usable = 0; + + if (!rbEnableIncomingConns->isChecked() || !rbAddrManual->isChecked()) + return true; + + for (int row = 0; row < addrTable->rowCount(); row++) + { + QString host; + bool ok = false; + int port; + + if (addrRowIsUpnp(row)) + { + usable += upnp ? 1 : 0; + continue; + } + + host = addrTable->item(row, 0) ? addrTable->item(row, 0)->text().trimmed() : QString(); + port = addrTable->item(row, 1) ? addrTable->item(row, 1)->text().trimmed().toInt(&ok) : 0; + + // ';' and ':' would not survive DirectC2CSettings' stored form + if (host.isEmpty() || host.contains(';') || host.contains(':')) + { + QMessageBox::warning(this, tr("Direct connections"), + tr("Row %1 of the address list has no valid IPv4 address or host name.").arg(row + 1)); + return false; + } + + if (!ok || port <= 0 || port > 65535) + { + QMessageBox::warning(this, tr("Direct connections"), + tr("Row %1 of the address list has no valid port number.").arg(row + 1)); + return false; + } + + usable++; + } + + if (usable == 0 && !upnp) + { + QMessageBox::warning(this, tr("Direct connections"), + tr("The address list is empty, so peers would have nowhere to connect to. " + "Add an address, or use the automatic configuration.")); + return false; + } + + return true; } void SettingsDialog::toggleMultipleLogins(bool checked) @@ -156,6 +1996,9 @@ void SettingsDialog::toggleMultipleLogins(bool checked) void SettingsDialog::OK() { + if (!validateAddrTable()) + return; + storeSettings(); done(1); } @@ -171,8 +2014,10 @@ void SettingsDialog::loadSettings() //Direct c2c connections int c2c_state; + DirectC2CSettings dcs; - c2c_state = st.loadValue("direct_c2c.state", 1).toInt(); + dcs.load(st); + c2c_state = dcs.state; switch (c2c_state) { @@ -192,40 +2037,22 @@ void SettingsDialog::loadSettings() break; } -#ifdef HAVE_LIBMINIUPNPC - cbEnableUPnP->setChecked(st.loadValue("direct_c2c.upnp_enabled", 1).toBool()); -#endif + if (cbEnableUPnP) + cbEnableUPnP->setChecked(dcs.upnp); - addr->lineEdit()->setText(st.loadValue("direct_c2c.public_addr", "autoconfigure").toString()); + if (dcs.addrConfig == DirectC2CSettings::AddrConfigManual) + rbAddrManual->setChecked(true); + else + rbAddrAuto->setChecked(true); - if (addr->lineEdit()->text().contains(QString("autoconfigure"))) - { - in_addr_t guess; - struct in_addr in; + localPort->setValue(dcs.localPort); - guess = PICA_guess_listening_addr_ipv4(); - in.s_addr = guess; - addr->lineEdit()->setText(QString("autoconfigured(%1)").arg(inet_ntoa(in))); + addrTable->setRowCount(0); -#ifdef HAVE_LIBMINIUPNPC - if (cbEnableUPnP->isChecked() && PICA_is_reserved_addr_ipv4(guess)) - { - int ret; - char public_ip[64]; - ret = PICA_upnp_autoconfigure_ipv4(st.loadValue("direct_c2c.public_port", 2298).toInt(), - st.loadValue("direct_c2c.local_port", 2298).toInt(), - public_ip); - - if (ret) - { - addr->lineEdit()->setText(QString("autoconfigured(%1)").arg(public_ip)); - } - } -#endif - } + foreach (const DirectC2CSettings::Addr &a, dcs.addrs) + addAddrRow(a.host, a.port, a.upnp); - publicPort->setValue(st.loadValue("direct_c2c.public_port", 2298).toInt()); - localPort->setValue(st.loadValue("direct_c2c.local_port", 2298).toInt()); + updateDirectConnWidgets(); //multiple logins int mlpstate; @@ -249,6 +2076,94 @@ void SettingsDialog::loadSettings() break; } + QString videoCapDevVal = st.loadValue("video.capture_device", QString()).toString(); + int videoDevItem = videoDev->findData(videoCapDevVal); + if (videoDevItem >= 0) + videoDev->setCurrentIndex(videoDevItem); + + // The resolution and frame rate lists pick the stored size and rate out of + // what the selected camera offers as they are filled, which the line above + // has just triggered where it changed the camera - see + // fillVideoResolutions(). + + cbPreferCompressed->setChecked(st.loadValue("video.prefer_compressed", 0).toBool()); + + // Call encoding parameters. Read through CallSettings rather than from st + // directly, so that the dialog and a call that is started without ever + // opening it agree on what "not configured" means. + const CallSettings cs = CallSettings::load(); + + int callVideoCodecItem = callVideoCodec->findData(cs.videoCodec); + if (callVideoCodecItem >= 0) + callVideoCodec->setCurrentIndex(callVideoCodecItem); + + callVideoBitrate->setValue(qBound(kMinVideoBitrateKbps, cs.videoBitrateKbps, kMaxVideoBitrateKbps)); + + // Before the codec is selected: selecting one whose bitrate is fixed puts + // that codec's rate in the box and keeps this as the value to come back + // to, see callAudioCodecChanged(). + audioBitrateKbps = qBound(kMinAudioBitrateKbps, cs.audioBitrateKbps, kMaxAudioBitrateKbps); + callAudioBitrate->setValue(audioBitrateKbps); + + int callAudioCodecItem = callAudioCodec->findData(cs.audioCodec); + if (callAudioCodecItem >= 0) + callAudioCodec->setCurrentIndex(callAudioCodecItem); + + // Explicitly, because setCurrentIndex() above only emits when the index + // actually changes - and the stored codec is often the one already showing. + callAudioCodecChanged(); + +#ifdef HAVE_VAAPI + cbVaapiEncoding->setChecked(st.loadValue("video.vaapi_encoding", 0).toBool()); + cbVaapiDecoding->setChecked(st.loadValue("video.vaapi_decoding", 0).toBool()); + cbVaapiRendering->setChecked(st.loadValue("video.vaapi_rendering", 0).toBool()); +#endif +#ifdef HAVE_D3D12VA + cbD3d12vaEncoding->setChecked(st.loadValue("video.d3d12va_encoding", 0).toBool()); + cbD3d12vaDecoding->setChecked(st.loadValue("video.d3d12va_decoding", 0).toBool()); +#endif +#ifdef Q_OS_WIN + cbMediaFoundationEncoding->setChecked(st.loadValue("video.mediafoundation_encoding", 0).toBool()); + cbD3d11vaDecoding->setChecked(st.loadValue("video.d3d11va_decoding", 0).toBool()); + cbDxva2Decoding->setChecked(st.loadValue("video.dxva2_decoding", 0).toBool()); +#endif + + QString audioCapDevVal = st.loadValue("audio.capture_device", "default").toString(); + int audioCapDevItem = audioCaptureDev->findData(audioCapDevVal); + if (audioCapDevItem >= 0) + audioCaptureDev->setCurrentIndex(audioCapDevItem); + + QString audioPlaybackDevVal = st.loadValue("audio.playback_device", "default").toString(); + int audioPlaybackDevItem = audioPlaybackDev->findData(audioPlaybackDevVal); + if (audioPlaybackDevItem >= 0) + audioPlaybackDev->setCurrentIndex(audioPlaybackDevItem); + + // Not read from st directly: the setting has a default that depends on the + // platform, and an older on/off setting to fall back on. + switch (loadEchoCancellationSetting()) + { + case EchoCancellationPlatform: + rbEchoCancelPlatform->setChecked(true); + break; + + case EchoCancellationNone: + rbEchoCancelNone->setChecked(true); + break; + + case EchoCancellationOwn: + default: + rbEchoCancelOwn->setChecked(true); + break; + } + + // Covers a saved "platform" on a machine where it is no longer on offer - + // a Linux install whose audio system has since been moved to ALSA. + updateEchoCancellationChoices(); + + QString audioRingDevVal = st.loadValue("audio.ring_device", "default").toString(); + int audioRingDevItem = audioRingDev->findData(audioRingDevVal); + if (audioRingDevItem >= 0) + audioRingDev->setCurrentIndex(audioRingDevItem); } void SettingsDialog::storeSettings() @@ -256,24 +2171,37 @@ void SettingsDialog::storeSettings() Settings st(config_dbname); //Direct c2c connections - int c2c_state; + DirectC2CSettings dcs; + + dcs.state = 1; if (rbDisableDirectConns->isChecked()) - c2c_state = 0; + dcs.state = 0; else if (rbEnableOutgoingConns->isChecked()) - c2c_state = 1; + dcs.state = 1; else if (rbEnableIncomingConns->isChecked()) - c2c_state = 2; + dcs.state = 2; - st.storeValue("direct_c2c.state", QString::number(c2c_state)); + dcs.upnp = cbEnableUPnP ? cbEnableUPnP->isChecked() : false; + dcs.addrConfig = rbAddrManual->isChecked() ? DirectC2CSettings::AddrConfigManual + : DirectC2CSettings::AddrConfigAuto; + dcs.localPort = localPort->value(); -#ifdef HAVE_LIBMINIUPNPC - st.storeValue("direct_c2c.upnp_enabled", cbEnableUPnP->isChecked() ? "1" : "0"); -#endif + // Kept even when the automatic configuration is selected, so that + // switching back to the manual one finds it as it was. + for (int row = 0; row < addrTable->rowCount(); row++) + { + DirectC2CSettings::Addr a; + + a.upnp = addrRowIsUpnp(row); + a.host = a.upnp ? QString() : addrTable->item(row, 0)->text().trimmed(); + a.port = a.upnp ? 0 : addrTable->item(row, 1)->text().trimmed().toInt(); + + if (a.upnp || (!a.host.isEmpty() && a.port > 0 && a.port <= 65535)) + dcs.addrs.append(a); + } - st.storeValue("direct_c2c.public_addr", addr->lineEdit()->text()); - st.storeValue("direct_c2c.public_port", QString::number(publicPort->value())); - st.storeValue("direct_c2c.local_port", QString::number(localPort->value())); + dcs.store(st); //multiple logins int mlpstate; @@ -286,4 +2214,62 @@ void SettingsDialog::storeSettings() mlpstate = PICA_MULTILOGIN_ALLOW; st.storeValue("multiple_logins.state", QString::number(mlpstate)); + + st.storeValue("video.capture_device", videoDev->itemData(videoDev->currentIndex()).toString()); + st.storeValue("video.capture_width", QString::number(selectedVideoWidth())); + st.storeValue("video.capture_height", QString::number(selectedVideoHeight())); + st.storeValue("video.capture_framerate", QString::number(selectedVideoFrameRate())); + st.storeValue("video.prefer_compressed", cbPreferCompressed->isChecked() ? "1" : "0"); + + st.storeValue("call.video_codec", callVideoCodec->itemData(callVideoCodec->currentIndex()).toString()); + st.storeValue("call.audio_codec", callAudioCodec->itemData(callAudioCodec->currentIndex()).toString()); + st.storeValue("call.video_bitrate_kbps", QString::number(callVideoBitrate->value())); + + // The box shows a fixed rate codec's own bitrate while such a codec is + // selected; what gets stored is the user's choice either way, so that + // switching back to Opus finds it again on the next visit. + if (callAudioBitrate->isEnabled()) + audioBitrateKbps = callAudioBitrate->value(); + + st.storeValue("call.audio_bitrate_kbps", QString::number(audioBitrateKbps)); +#ifdef HAVE_VAAPI + st.storeValue("video.vaapi_encoding", cbVaapiEncoding->isChecked() ? "1" : "0"); + st.storeValue("video.vaapi_decoding", cbVaapiDecoding->isChecked() ? "1" : "0"); + st.storeValue("video.vaapi_rendering", cbVaapiRendering->isChecked() ? "1" : "0"); +#endif +#ifdef HAVE_D3D12VA + st.storeValue("video.d3d12va_encoding", cbD3d12vaEncoding->isChecked() ? "1" : "0"); + st.storeValue("video.d3d12va_decoding", cbD3d12vaDecoding->isChecked() ? "1" : "0"); +#endif +#ifdef Q_OS_WIN + st.storeValue("video.mediafoundation_encoding", cbMediaFoundationEncoding->isChecked() ? "1" : "0"); + st.storeValue("video.d3d11va_decoding", cbD3d11vaDecoding->isChecked() ? "1" : "0"); + st.storeValue("video.dxva2_decoding", cbDxva2Decoding->isChecked() ? "1" : "0"); +#endif + st.storeValue("audio.capture_device", audioCaptureDev->itemData(audioCaptureDev->currentIndex()).toString()); + st.storeValue("audio.playback_device", audioPlaybackDev->itemData(audioPlaybackDev->currentIndex()).toString()); + st.storeValue("audio.ring_device", audioRingDev->itemData(audioRingDev->currentIndex()).toString()); + + if (audioDriver) + { + QString drv = audioDriver->itemData(audioDriver->currentIndex()).toString(); + st.storeValue("audio.driver", drv); + AudioDevice::SetLinuxDriverName(drv); + } + + // After the driver, since on Linux that is what decides whether the + // platform option means anything - and updateEchoCancellationChoices() + // has already moved the selection off it if it does not. + EchoCancellationMode echoMode = EchoCancellationOwn; + + if (rbEchoCancelPlatform->isChecked()) + echoMode = EchoCancellationPlatform; + else if (rbEchoCancelNone->isChecked()) + echoMode = EchoCancellationNone; + + storeEchoCancellationSetting(echoMode); + + // Publish it to the audio threads, the same way the driver above is + // published - see AudioDevice::SetEchoCancellation(). + AudioDevice::SetEchoCancellation(echoMode); } diff --git a/pica-client/dialogs/settingsdialog.h b/pica-client/dialogs/settingsdialog.h index 84a075e..ab1c7e7 100644 --- a/pica-client/dialogs/settingsdialog.h +++ b/pica-client/dialogs/settingsdialog.h @@ -24,12 +24,36 @@ #include <QRadioButton> #include <QComboBox> #include <QCheckBox> +#include <QLabel> +#include <QTableWidget> +#include <QThread> +#include <QImage> +#include <QList> +#include <QTimer> +#include <QElapsedTimer> +#include "../mediadevice.h" +#include "../audiodevice.h" +#include "../videodevice.h" +#include "../videoscaler.h" +#include "../toneplayer/toneplayer.h" +#ifdef HAVE_VAAPI +#include "../vaapi.h" +#endif class SettingsDialog : public QDialog { Q_OBJECT public: explicit SettingsDialog(QWidget *parent = 0); + ~SettingsDialog(); + + // Watches videoPreview for its own resizes, which is where the size the + // test's frames should be decoded to is decided. Doing this from the + // dialog's resizeEvent() instead would read the label's geometry before + // the layout has updated it, and would miss the resizes the layout causes + // on its own - the tab's other rows changing height moves the preview + // without the dialog changing size at all. + bool eventFilter(QObject *watched, QEvent *event) override; signals: @@ -40,29 +64,322 @@ private: QRadioButton *rbDisableDirectConns; QRadioButton *rbEnableOutgoingConns; QRadioButton *rbEnableIncomingConns; -#ifdef HAVE_LIBMINIUPNPC + // Everything below "Enable incoming direct connections", disabled + // together with it. + QWidget *incomingBox; + // Null in a build without UPnP support, where offering it would only + // lead to an error message later on. QCheckBox *cbEnableUPnP; -#endif - QComboBox *addr; - QSpinBox *publicPort; + // direct_c2c.addr_config - which addresses go into the 0x0B message + QRadioButton *rbAddrAuto; + QRadioButton *rbAddrManual; + // what the automatic configuration would announce right now + QLabel *lbAutoAddrs; + + // The manual configuration: the port listened on, and the announced + // addresses in the order peers try them. A row of the table can also + // stand for the UPnP router's external address, which is only known + // once the client runs - see addUpnpAddrRow(). + QWidget *manualBox; QSpinBox *localPort; + QTableWidget *addrTable; + QPushButton *btAddrUpnp; + QPushButton *btUpnpQuery; + QLabel *lbUpnpInfo; + + void updateDirectConnWidgets(); + void updateAutoAddrsLabel(); + void addAddrRow(const QString &host, int port, bool upnp); + bool addrRowIsUpnp(int row) const; + // Checks the manual address list before it is stored; false, having + // told the user why, if it cannot be. + bool validateAddrTable(); QRadioButton *rbMLPProhibit; QRadioButton *rbMLPReplace; QRadioButton *rbMLPAllowMultiple; + QComboBox *audioCaptureDev; + QComboBox *audioPlaybackDev; + QComboBox *audioRingDev; + + // Which audio API to go through. Only Linux has a choice worth offering + // (ALSA or PulseAudio, the latter covering PipeWire's PulseAudio + // interface too), so elsewhere this stays null and no widget is built. + // The member and its slot are declared unconditionally all the same: + // moc runs its own preprocessor and would not see a platform #ifdef, so + // a slot hidden behind one ends up declared but never generated. + QComboBox *audioDriver; + + // Who takes the echo of the other person back out of the microphone + // signal: EchoCanceller, the platform, or nobody. See + // EchoCancellationMode - one of the three, never two at once. + // + // The platform option is only offered where there is something to offer; + // on Linux that depends on the audio system chosen above it, so it is + // enabled and disabled as that combo box changes rather than once at + // startup. + QRadioButton *rbEchoCancelOwn; + QRadioButton *rbEchoCancelPlatform; + QRadioButton *rbEchoCancelNone; + void updateEchoCancellationChoices(); + + QComboBox *videoDev; + QPushButton *videoDevRefresh; + + // Picture size and frame rate to ask the selected camera for. Both are + // filled from what the camera says it can do - the sizes from the camera, + // the rates from the size selected next to them - so they are refilled + // whenever the selection above them changes. + QComboBox *videoRes; + QComboBox *videoFps; + + // What the selected camera reported, kept so that changing the resolution + // can refill the frame rates without asking the camera again. Enumerating + // is not free - on Windows it means instantiating the capture filter. + QList<VideoCaptureFormat> videoFormats; + + // Encoding parameters for a call, on the "Call Settings" tab. The codec + // combo boxes carry the FFmpeg codec name as item data, which is what gets + // stored and what goes into the 0x74/0x75 messages. + QComboBox *callVideoCodec; + QComboBox *callAudioCodec; + QSpinBox *callVideoBitrate; + QSpinBox *callAudioBitrate; + + // The audio bitrate the user chose, which is not always what + // callAudioBitrate shows: selecting a fixed rate codec puts that codec's + // rate in the box and disables it, and the chosen value has to survive + // that to come back when an adjustable codec is selected again. + int audioBitrateKbps; + + // Local audio pipeline test: a few seconds of the selected microphone are + // captured and encoded, then decoded again and played back through the + // selected playback device - the same path a call takes, minus the + // network. Recording and playback are deliberately kept apart in time + // rather than looped back live, which would howl with acoustic feedback + // when the test runs on speakers. + QPushButton *btAudioTest; + QLabel *audioTestStatus; + AudioDevice *testMic; + AudioDevice *testSpeaker; + QThread testMicThread; + QThread testSpeakerThread; + + enum AudioTestState + { + AudioTestIdle, + AudioTestRecording, + AudioTestPlaying + }; + + AudioTestState audioTestState; + // What the microphone and playback devices reported negotiating, shown + // with the result. Same idea as videoTestPathReport. + QString audioTestPathReport; + // The recording, as encoded packets, and how far playback has fed it. + QList<QByteArray> audioTestPackets; + int audioTestPlaybackPos; + // Members rather than QTimer::singleShot() calls so that stopping a test + // cancels them - otherwise a timer left over from an aborted run would + // fire into the next one. + QTimer *audioTestRecordTimer; + QTimer *audioTestPlaybackTimer; + // Playback is paced against this rather than against the number of times + // the timer has fired - see audioTestFeedPacket(). + QElapsedTimer audioTestPlaybackClock; + QTimer *audioTestDrainTimer; + + void stopAudioTest(); + void startAudioTestPlayback(); + + // Ring device test: plays the incoming call bell through the selected + // ring device, using the same TonePlayer an actual incoming call uses. + // TonePlayer::play() blocks its thread for the length of the tone + // sequence, hence the dedicated thread. + QPushButton *btRingTest; + QLabel *ringTestStatus; + TonePlayer *ringTestPlayer; + QThread ringTestPlayerThread; + bool ringTestRunning; + + // Local video pipeline test: frames from the selected camera are + // encoded, split into protocol sized fragments, reassembled and decoded + // again, then shown in videoPreview - the same path a call takes, minus + // the network, so the whole chain can be checked from this dialog. + QPushButton *btVideoTest; + QLabel *videoPreview; + // Shown under the preview: the format the camera settled on, and whether + // the GPU or the CPU ended up doing the encoding and decoding. + QLabel *videoTestStatus; + QString videoTestFormat; + QString videoTestPathReport; + QCheckBox *cbPreferCompressed; +#ifdef HAVE_VAAPI + QCheckBox *cbVaapiEncoding; + QCheckBox *cbVaapiDecoding; + QCheckBox *cbVaapiRendering; + // Shown in place of videoPreview while frames are being drawn straight + // from GPU memory; only one of the two is ever visible. + VaapiRenderWidget *videoPreviewGpu; +#endif + // One checkbox per Windows GPU path, encoding and decoding separately, + // since which of them works depends on the GPU and its driver and is only + // found out by trying - see VideoAcceleration. When several are ticked + // VideoDevice tries them in a fixed order, so each one can also be tested + // on its own by unticking the others. +#ifdef HAVE_D3D12VA + QCheckBox *cbD3d12vaEncoding; + QCheckBox *cbD3d12vaDecoding; +#endif +#ifdef Q_OS_WIN + QCheckBox *cbMediaFoundationEncoding; + QCheckBox *cbD3d11vaDecoding; + QCheckBox *cbDxva2Decoding; +#endif + // Greys out a checkbox for a path the FFmpeg the client runs with was + // built without, saying so in its tooltip, rather than letting it be + // ticked and then quietly fall back to software. + void offerAcceleration(QCheckBox *cb, VideoAcceleration acceleration, bool encoding); + + // VideoAcceleration flags out of the checkboxes as they stand, for the + // local pipeline test - which runs on what the dialog shows rather than + // on what was last stored. + int selectedVideoEncodingAcceleration() const; + int selectedVideoDecodingAcceleration() const; + + VideoDevice *testCam; + VideoDevice *testDecoder; + QThread testCamThread; + QThread testDecoderThread; + VideoFrameAssembler testAssembler; + // Counter part of the sequence number handed to testAssembler, kept the + // same way AudioVideoCallController keeps it for a real call. + quint16 testVideoSeq; + bool videoTestRunning; + + // The last frame the preview drew, kept so that it can follow a resize of + // the dialog rather than staying as it was until the next frame. Cleared + // when the test stops, since the preview goes back to showing status text + // and must not have a stale picture put back over it. + QImage lastTestFrame; + + // Resizes a frame that does not already match the preview. Normally does + // nothing: testDecoder is told what size to produce - see + // reportVideoPreviewArea() - and only the frames in flight across a resize + // arrive at another size. Same arrangement as CallWindow's; the reasoning + // is in videoscaler.h. + VideoScaler videoTestScaler; + + // Measured frame rates for the status line. Two of them, because they + // answer different questions: whether the camera is actually delivering + // the rate it was asked for, and whether the rest of the pipeline keeps up + // with what it delivers. A camera asked for more than it can manage is not + // told so - it quietly delivers fewer frames instead - so the only way to + // know is to count them. + QTimer *videoFpsTimer; + QElapsedTimer videoFpsElapsed; + int videoCapturedFrames; + int videoDisplayedFrames; + double videoCaptureFps; + double videoDisplayFps; + // Whether the preview is being drawn straight from GPU memory, which the + // status line says and which only the frames themselves reveal. + bool videoTestGpuRendering; + + void stopVideoTest(); + + // Builds the line under the preview out of everything known about the + // running test - format, which end did the encoding and decoding, whether + // the preview is drawn on the GPU, and the measured frame rates. One place + // for it, since the frame rates change it once a second while frames + // arriving change the rest of it. + void updateVideoTestStatus(); + + // Draws lastTestFrame at the size the preview is now. + void updateVideoPreview(); + + // Tells testDecoder what size to decode frames to, so that the resize + // happens inside the colour conversion it already runs instead of in a + // second pass here. The preview is smaller than the camera's picture, so + // this is the case that gains most - nothing gets converted only to be + // thrown away. + void reportVideoPreviewArea(); + QPushButton *btOk; QPushButton *btCancel; void loadSettings(); void storeSettings(); + void fillDevicesComboBox(QComboBox *cb, MediaDevice *dev, enum MediaDeviceStreamDirection dir); + + // The picture size and frame rate the video tab currently has selected, + // used both by the local pipeline test and when the settings are stored. + int selectedVideoWidth() const; + int selectedVideoHeight() const; + int selectedVideoFrameRate() const; + private slots: void OK(); void Cancel(); void toggleIncomingConnections(bool checked); + // The manual address list's buttons. Declared unconditionally, see + // the note at audioDriver for why slots must not depend on a define. + void addAddr(); + void removeAddr(); + void moveAddrUp(); + void moveAddrDown(); + void addInterfaceAddrs(); + void addUpnpAddrRow(); + // Asks the UPnP router for its external address on a thread of its own - + // discovery alone takes two seconds - and adds it to the list. + void queryUpnpAddr(); + void upnpQueryFinished(int status, QString addr); void toggleMultipleLogins(bool checked); + void fillVideoDevices(); + // Asks the newly selected camera what it can do and refills the two lists + // below it. fillVideoFrameRates() alone when only the size changed. + void fillVideoResolutions(); + void fillVideoFrameRates(); + // Greys out the audio bitrate box for a codec whose bitrate is not ours to + // choose - see audioBitrateKbps. + void callAudioCodecChanged(); + // Device names are driver specific, so all three lists have to be filled + // again when the driver changes. Only ever connected on Linux. + void audioDriverChanged(int index); + void fillAudioCaptureDevices(); + void fillAudioPlaybackDevices(); + void fillAudioRingDevices(); + + void toggleRingTest(); + void ringTestFinished(); + void ringTestError(QString message); + + void toggleAudioTest(); + void audioTestPacket(QByteArray data); + void audioTestRecordingFinished(); + void audioTestFeedPacket(); + void audioTestPlaybackFinished(); + void audioTestError(QString message); + void audioTestPath(QString description); + + void toggleVideoTest(); + void videoTestCaptureStarted(QString codec, int width, int height, double frameRate); + void videoTestPath(QString description); + void videoTestFragment(QByteArray data, bool is_last_fragment); + void videoTestFrame(QImage frame); + // Turns the frames counted since the last tick into the rates the status + // line shows. On a timer rather than computed as frames arrive, so that a + // pipeline that has stalled reads as 0 fps instead of staying at whatever + // it managed last. + void videoFpsTick(); +#ifdef HAVE_VAAPI + void videoTestHwFrame(AVFramePtr frame); + void videoTestRenderFailed(QString message); +#endif + void videoTestError(QString message); }; diff --git a/pica-client/dialogs/showpicaiddialog.cpp b/pica-client/dialogs/showpicaiddialog.cpp index dbcf814..5395aa2 100644 --- a/pica-client/dialogs/showpicaiddialog.cpp +++ b/pica-client/dialogs/showpicaiddialog.cpp @@ -25,7 +25,7 @@ ShowPicaIdDialog::ShowPicaIdDialog(QString name, QByteArray id, QString caption, setWindowTitle(caption); QVBoxLayout *layout = new QVBoxLayout(this); - lbname_ = new QLabel(tr("Account: <b>%1</b>").arg(name)); + lbname_ = new QLabel(tr("Account: <b>%1</b>").arg(name.toHtmlEscaped())); lbname_ ->setTextFormat(Qt::RichText); picaid_ = new QLineEdit(); diff --git a/pica-client/dialogs/viewcertdialog.cpp b/pica-client/dialogs/viewcertdialog.cpp index f2cc918..6237ac4 100644 --- a/pica-client/dialogs/viewcertdialog.cpp +++ b/pica-client/dialogs/viewcertdialog.cpp @@ -15,7 +15,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "viewcertdialog.h" -#include "../openssltool.h" +#include "../openssllib.h" #include <QVBoxLayout> #include <QMessageBox> #include <QFile> @@ -53,7 +53,7 @@ ViewCertDialog::ViewCertDialog(QWidget *parent) : void ViewCertDialog::SetCert(QString cert_pem) { - cert_text->setPlainText(OpenSSLTool::CertTextFromString(cert_pem)); + cert_text->setPlainText(OpenSSLLib::CertTextFromString(cert_pem)); } void ViewCertDialog::OK() diff --git a/pica-client/directc2csettings.h b/pica-client/directc2csettings.h new file mode 100644 index 0000000..dfd59ff --- /dev/null +++ b/pica-client/directc2csettings.h @@ -0,0 +1,158 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#ifndef DIRECTC2CSETTINGS_H +#define DIRECTC2CSETTINGS_H + +#include "settings.h" +#include <QString> +#include <QStringList> +#include <QList> + +// The settings of the "Direct connections" tab, read and written in one place +// because the settings dialog and SkyNet both need them, and because of the +// single address earlier versions stored instead of a list. +struct DirectC2CSettings +{ + // direct_c2c.addr_config + enum AddrConfig + { + // interface addresses, then the UPnP mapping; the port is looked for + // starting at DefaultPort + AddrConfigAuto = 0, + // the list below, listening on localPort + AddrConfigManual = 1 + }; + + enum + { + DefaultPort = 2299 + }; + + // One announced address. The UPnP entry stands for the external address + // of the UPnP port mapping, which is only known at run time. + struct Addr + { + QString host; + int port; + bool upnp; + }; + + // PICA_directc2c_config + int state; + bool upnp; + int addrConfig; + int localPort; + QList<Addr> addrs; + + void load(Settings &st) + { + state = st.loadValue("direct_c2c.state", 1).toInt(); + upnp = st.loadValue("direct_c2c.upnp_enabled", 1).toBool(); + localPort = st.loadValue("direct_c2c.local_port", (int)DefaultPort).toInt(); + addrConfig = st.loadValue("direct_c2c.addr_config", -1).toInt(); + addrs = parseAddrs(st.loadValue("direct_c2c.addr_list", QString()).toString()); + + if (addrConfig == AddrConfigAuto || addrConfig == AddrConfigManual) + return; + + // Never stored: either a fresh installation, or one from before the + // address list, whose single public address - "autoconfigure" + // unless the user typed one in - becomes a manual list of one. + QString oldAddr = st.loadValue("direct_c2c.public_addr", "autoconfigure").toString(); + + addrConfig = AddrConfigAuto; + + if (!oldAddr.isEmpty() && !oldAddr.contains("autoconfigure")) + { + Addr a; + + a.host = oldAddr; + a.port = st.loadValue("direct_c2c.public_port", localPort).toInt(); + a.upnp = false; + + addrConfig = AddrConfigManual; + addrs.clear(); + addrs.append(a); + } + } + + // Whether a listener set up for o would be set up the same way for these + // settings: the port and the list only matter in manual configuration. + bool sameListener(const DirectC2CSettings &o) const + { + if (upnp != o.upnp || addrConfig != o.addrConfig) + return false; + + if (addrConfig != AddrConfigManual) + return true; + + return localPort == o.localPort && formatAddrs(addrs) == formatAddrs(o.addrs); + } + + void store(Settings &st) const + { + st.storeValue("direct_c2c.state", QString::number(state)); + st.storeValue("direct_c2c.upnp_enabled", upnp ? "1" : "0"); + st.storeValue("direct_c2c.addr_config", QString::number(addrConfig)); + st.storeValue("direct_c2c.local_port", QString::number(localPort)); + st.storeValue("direct_c2c.addr_list", formatAddrs(addrs)); + } + + // "host:port;host:port;upnp" + static QList<Addr> parseAddrs(const QString &s) + { + QList<Addr> l; + + foreach (const QString &item, s.split(';', QString::SkipEmptyParts)) + { + Addr a; + QString entry = item.trimmed(); + int colon = entry.lastIndexOf(':'); + + a.upnp = entry == "upnp"; + a.port = 0; + + if (!a.upnp) + { + if (colon <= 0) + continue; + + a.host = entry.left(colon); + a.port = entry.mid(colon + 1).toInt(); + + if (a.port <= 0 || a.port > 65535) + continue; + } + + l.append(a); + } + + return l; + } + + static QString formatAddrs(const QList<Addr> &l) + { + QStringList items; + + foreach (const Addr &a, l) + items.append(a.upnp ? QString("upnp") : QString("%1:%2").arg(a.host).arg(a.port)); + + return items.join(';'); + } +}; + +#endif // DIRECTC2CSETTINGS_H diff --git a/pica-client/directlistener.cpp b/pica-client/directlistener.cpp new file mode 100644 index 0000000..d2a1fc7 --- /dev/null +++ b/pica-client/directlistener.cpp @@ -0,0 +1,285 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#include "directlistener.h" +#include "directc2csettings.h" +#include "../PICA_client.h" +#include "../PICA_netconf.h" +#include <QByteArray> +#include <QList> +#include <vector> + +// How soon a lost mapping is tried again, in seconds. +static const int kUpnpRetryInterval = 300; + +DirectListener::DirectListener(QObject *parent) + : QObject(parent), upnp(nullptr), upnpPort(0), upnpLost(false), refreshTimer(nullptr) +{ +} + +DirectListener::~DirectListener() +{ + // release() is expected to have run on this object's own thread already; + // this is only for a mapping left behind when it did not + PICA_upnp_free(upnp); +} + +bool DirectListener::discoverUpnp() +{ + char addr[64]; + int ret; + + ret = PICA_upnp_discover(PICA_UPNP_DISCOVER_TIMEOUT, &upnp); + + if (ret != PICA_UPNP_OK) + { + upnp = nullptr; + emit statusMsg(tr("UPnP: %1").arg(PICA_upnp_strerror(ret)), false); + return false; + } + + // An external address that is private - the router is behind the + // provider's NAT - would lead nowhere; better not to forward anything + // than to announce it. + ret = PICA_upnp_external_addr(upnp, addr, sizeof(addr)); + + if (ret != PICA_UPNP_OK) + { + emit statusMsg(tr("UPnP: %1").arg(PICA_upnp_strerror(ret)), false); + dropUpnp(); + return false; + } + + upnpAddr = QString::fromLatin1(addr); + + return true; +} + +void DirectListener::dropUpnp() +{ + PICA_upnp_free(upnp); + upnp = nullptr; + upnpAddr.clear(); + upnpPort = 0; +} + +void DirectListener::setup(quintptr accp, int addrConfig, bool useUpnp, int localPort, QString addrList) +{ + const struct PICA_acc *acc = (const struct PICA_acc*)accp; + struct PICA_listener *l = nullptr; + bool manual = addrConfig == DirectC2CSettings::AddrConfigManual; + QList<DirectC2CSettings::Addr> addrs = DirectC2CSettings::parseAddrs(addrList); + // In automatic configuration a port that cannot be had is not worth a + // word: the next one is tried. The port of the manual one is the user's + // choice and is used as it is. + int firstPort = manual ? localPort : (int)DirectC2CSettings::DefaultPort; + int tries = manual ? 1 : (int)PortTries; + bool mapped = false; + int port = 0; + int i, ret; + + // the mapping made for a listener set up before, if it was not released + release(); + + if (useUpnp) + discoverUpnp(); + + for (i = 0; i < tries && firstPort + i <= 65535; i++) + { + port = firstPort + i; + + if (PICA_new_listener(acc, port, &l) != PICA_OK) + { + l = nullptr; + continue; + } + + if (!upnp) + break; + + ret = PICA_upnp_map(upnp, port, PICA_UPNP_LEASE_DEFAULT, "Pica Pica"); + + if (ret == PICA_UPNP_OK) + { + mapped = true; + break; + } + + // somebody else behind the router has this port number forwarded + if (ret == PICA_UPNP_ERRCONFLICT && i + 1 < tries) + { + PICA_close_listener(l); + l = nullptr; + continue; + } + + emit statusMsg(tr("UPnP: failed to forward port %1 - %2").arg(port).arg(PICA_upnp_strerror(ret)), false); + dropUpnp(); + break; + } + + if (!l) + { + if (manual) + emit statusMsg(tr("Failed to open port %1 for incoming direct connections").arg(firstPort), true); + else + emit statusMsg(tr("Failed to open any of the ports %1 - %2 for incoming direct connections") + .arg(firstPort).arg(firstPort + tries - 1), true); + + dropUpnp(); + emit ready(0, QString(), 0); + return; + } + + if (!mapped) + dropUpnp(); + + if (manual) + { + QList<QByteArray> hosts; + std::vector<const char *> hostPtrs; + std::vector<int> ports; + bool hasUpnpEntry = false; + + foreach (const DirectC2CSettings::Addr &a, addrs) + { + hosts.append(a.upnp ? QByteArray() : a.host.toUtf8()); + ports.push_back(a.upnp ? port : a.port); + hasUpnpEntry = hasUpnpEntry || a.upnp; + } + + // A mapping with nowhere to announce it goes at the end. + if (mapped && !hasUpnpEntry) + { + hosts.append(QByteArray()); + ports.push_back(port); + addrs.append(DirectC2CSettings::Addr {QString(), port, true}); + } + + for (int j = 0; j < hosts.size(); j++) + hostPtrs.push_back(addrs[j].upnp ? nullptr : hosts[j].constData()); + + // An empty list would make the listener fall back to automatic + // configuration, announcing addresses the user did not choose. + if (hostPtrs.empty()) + { + emit statusMsg(tr("No addresses are configured for incoming direct connections"), true); + PICA_close_listener(l); + dropUpnp(); + emit ready(0, QString(), 0); + return; + } + + ret = PICA_listener_set_addrlist(l, hostPtrs.data(), ports.data(), (int)hostPtrs.size()); + + if (ret != PICA_OK) + { + emit statusMsg(tr("Unable to resolve the addresses configured for incoming direct connections"), true); + PICA_close_listener(l); + dropUpnp(); + emit ready(0, QString(), 0); + return; + } + } + + if (mapped) + { + upnpPort = port; + upnpLost = false; + scheduleRefresh(); + + emit statusMsg(tr("Port %1 is forwarded by the UPnP router, external address %2").arg(port).arg(upnpAddr), false); + } + + emit statusMsg(tr("Listening for incoming direct connections on port %1").arg(port), false); + + emit ready((quintptr)l, mapped ? upnpAddr : QString(), mapped ? port : 0); +} + +void DirectListener::scheduleRefresh() +{ + unsigned int lease = PICA_upnp_lease(upnp); + int secs; + + if (!refreshTimer) + { + refreshTimer = new QTimer(this); + refreshTimer->setSingleShot(true); + connect(refreshTimer, SIGNAL(timeout()), this, SLOT(refresh())); + } + + // Renewed at half the lease the router granted. A permanent mapping is + // checked just as often: the router forgets it when it reboots. + if (upnpLost) + secs = kUpnpRetryInterval; + else if (lease == 0) + secs = PICA_UPNP_LEASE_DEFAULT / 2; + else + secs = (int)(lease / 2); + + if (secs < 30) + secs = 30; + + refreshTimer->start(secs * 1000); +} + +void DirectListener::refresh() +{ + char addr[64]; + int ret; + + if (!upnp) + return; + + if (PICA_upnp_mapped(upnp)) + ret = PICA_upnp_refresh(upnp); + else + ret = PICA_upnp_map(upnp, upnpPort, PICA_UPNP_LEASE_DEFAULT, "Pica Pica"); + + // The router's external address can change on a renewal of its own + // lease with the provider, and is read again every time. + if (ret == PICA_UPNP_OK) + ret = PICA_upnp_external_addr(upnp, addr, sizeof(addr)); + + if (ret == PICA_UPNP_OK) + { + QString newAddr = QString::fromLatin1(addr); + + if (upnpLost || newAddr != upnpAddr) + { + upnpAddr = newAddr; + emit upnpChanged(upnpAddr, upnpPort); + } + + upnpLost = false; + } + else if (!upnpLost) + { + upnpLost = true; + emit upnpChanged(QString(), 0); + emit statusMsg(tr("UPnP: the forwarding of port %1 was lost - %2").arg(upnpPort).arg(PICA_upnp_strerror(ret)), false); + } + + scheduleRefresh(); +} + +void DirectListener::release() +{ + if (refreshTimer) + refreshTimer->stop(); + + dropUpnp(); +} diff --git a/pica-client/directlistener.h b/pica-client/directlistener.h new file mode 100644 index 0000000..0e69d16 --- /dev/null +++ b/pica-client/directlistener.h @@ -0,0 +1,85 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#ifndef DIRECTLISTENER_H +#define DIRECTLISTENER_H + +#include <QObject> +#include <QString> +#include <QTimer> + +struct PICA_upnp_ctx; + +// Opens the listener for incoming direct connections and keeps its UPnP port +// mapping up for as long as the client runs. +// +// Talking to a UPnP router blocks - discovery for two seconds, every request +// for as long as the router takes to answer - so this lives on a thread of +// its own instead of SkyNet's, which carries the media of calls. The +// listener it opens is handed over to SkyNet and used on SkyNet's thread +// only; what changes about the mapping later on is reported with +// upnpChanged(), for SkyNet to pass on to the listener. +class DirectListener : public QObject +{ + Q_OBJECT +public: + // Ports tried in automatic configuration, from DirectC2CSettings::DefaultPort + // on, until one can be opened for TCP and UDP and - with UPnP - forwarded. + enum + { + PortTries = 16 + }; + + explicit DirectListener(QObject *parent = 0); + ~DirectListener(); + +public slots: + // Opens the listener as the "Direct connections" settings say and reports + // the outcome with ready(). addrList is DirectC2CSettings' stored form. + void setup(quintptr acc, int addrConfig, bool useUpnp, int localPort, QString addrList); + + // Deletes the port mapping. Called once, at shutdown. + void release(); + +signals: + // listener is a struct PICA_listener *, 0 if none could be opened. + // upnpAddr is empty when no port mapping was made. + void ready(quintptr listener, QString upnpAddr, int upnpPort); + + // The external address or port of the mapping changed - the router got a + // new address from the provider - or the mapping was lost, in which case + // upnpAddr is empty. + void upnpChanged(QString upnpAddr, int upnpPort); + + void statusMsg(QString msg, bool isCritical); + +private slots: + void refresh(); + +private: + struct PICA_upnp_ctx *upnp; + QString upnpAddr; + // the port the mapping is for, the same number as the listening port + int upnpPort; + bool upnpLost; + QTimer *refreshTimer; + + bool discoverUpnp(); + void dropUpnp(); + void scheduleRefresh(); +}; + +#endif // DIRECTLISTENER_H diff --git a/pica-client/echocanceller.cpp b/pica-client/echocanceller.cpp new file mode 100644 index 0000000..ad5b122 --- /dev/null +++ b/pica-client/echocanceller.cpp @@ -0,0 +1,516 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#include "echocanceller.h" +#include "audiodevice.h" +#include "settings.h" +#include "globals.h" + +#include <QDebug> +#include <QMutexLocker> +#include <cmath> +#include <cstring> + +// Which major version of webrtc-audio-processing this is being built against. +// 1.x and 2.x are separate parallel-installable libraries with separate +// pkg-config names, and 2.x broke the API in a few places - the conditionals +// on this below are the whole of what differs as far as this file is +// concerned. +// +// configure defines it, and so does the qmake build. The fallback is for +// anything that builds this file without either: api/audio/audio_processing.h +// is where 2.x moved the header that 1.x only had under modules/, so its +// presence is the version. +#ifndef PICA_WEBRTC_AUDIO_PROCESSING_MAJOR +# if defined(__has_include) && __has_include(<api/audio/audio_processing.h>) +# define PICA_WEBRTC_AUDIO_PROCESSING_MAJOR 2 +# else +# define PICA_WEBRTC_AUDIO_PROCESSING_MAJOR 1 +# endif +#endif + +// Still the right include on 2.x, where it is a stub forwarding to +// api/audio/audio_processing.h - and it is installed there, so there is +// nothing to switch on here. +#include <modules/audio_processing/include/audio_processing.h> + +// Must come after the above, and not only as a matter of taste: on 2.x this +// header declares parameters as absl::Nullable/absl::Nonnull without +// including the abseil header that defines them, so on its own it does not +// compile. audio_processing.h is what pulls that in. Both versions include +// this themselves anyway; it is named here so that the scoped_refptr below is +// not silently relying on somebody else's include. +#include <api/scoped_refptr.h> + +extern "C" { +#include <libswresample/swresample.h> +#include <libavutil/channel_layout.h> +#include <libavutil/samplefmt.h> +#include <libavutil/mathematics.h> +#include <libavutil/opt.h> +} + +// Same split as audiodevice.cpp - FFmpeg 5.1 replaced the channel count and +// layout fields with the AVChannelLayout API. +#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 24, 100) +# define EC_HAVE_CH_LAYOUT 1 +#else +# define EC_HAVE_CH_LAYOUT 0 +#endif + +// Setting values. Words rather than numbers because this is a three way +// choice that will be read by whoever is looking at a user's config, and a +// stray "2" says nothing. +static const char kEchoCancellationOwn[] = "own"; +static const char kEchoCancellationPlatform[] = "platform"; +static const char kEchoCancellationNone[] = "off"; + +EchoCancellationMode loadEchoCancellationSetting() +{ + Settings st(config_dbname); + + const QString value = st.loadValue("audio.echo_cancellation", QString()).toString(); + + if (value == QLatin1String(kEchoCancellationOwn)) + return EchoCancellationOwn; + + if (value == QLatin1String(kEchoCancellationPlatform)) + { + // The stored choice can stop being available underneath the user - + // the audio system moved from PulseAudio to ALSA, say. Leaving it as + // it stands would mean nobody cancelling and nothing saying so. + if (AudioDevice::PlatformEchoCancellationAvailable()) + return EchoCancellationPlatform; + + qWarning() << "Echo cancellation is set to the platform's own, but the audio system in " + "use does not provide one - falling back to ours"; + return EchoCancellationOwn; + } + + if (value == QLatin1String(kEchoCancellationNone)) + return EchoCancellationNone; + + // Nothing stored under the current key. An install that predates it may + // still have the on/off setting this replaced, and someone who turned + // cancellation off did mean it. + if (!st.loadValue("audio.echo_cancel", 1).toBool()) + return EchoCancellationNone; + + // The platform's own is the better one where it exists, so it is the + // default there; elsewhere the default is ours, which is what the plain + // on/off setting used to mean. + return AudioDevice::PlatformEchoCancellationAvailable() + ? EchoCancellationPlatform + : EchoCancellationOwn; +} + +void storeEchoCancellationSetting(EchoCancellationMode mode) +{ + Settings st(config_dbname); + + switch (mode) + { + case EchoCancellationPlatform: + st.storeValue("audio.echo_cancellation", QLatin1String(kEchoCancellationPlatform)); + break; + + case EchoCancellationNone: + st.storeValue("audio.echo_cancellation", QLatin1String(kEchoCancellationNone)); + break; + + case EchoCancellationOwn: + default: + st.storeValue("audio.echo_cancellation", QLatin1String(kEchoCancellationOwn)); + break; + } +} + +// Holds everything that needs the WebRTC headers, so that echocanceller.h - +// which audiodevice.h includes, and so half the client with it - does not. +struct EchoCancellerPrivate +{ + rtc::scoped_refptr<webrtc::AudioProcessing> apm; + + // Both directions are mono at our rate. The integer interface requires + // the capture, playback and render rates to be the same, which is why + // pushFarEnd() resamples rather than passing the peer's rate through. + webrtc::StreamConfig stream; +}; + +bool EchoCanceller::isNativeRate(int rate) +{ + return rate == 8000 || rate == 16000 || rate == 32000 || rate == 48000; +} + +EchoCanceller::EchoCanceller(int sampleRate) + : m_sampleRate(sampleRate), + m_frameSize(0), + m_d(nullptr), + m_farSwr(nullptr), + m_farSwrRate(0), + m_nearEnergy(0.0), + m_farEnergy(0.0), + m_processedSamples(0), + m_nextReportSamples(0), + m_renderBlocks(0), + m_captureBlocks(0) +{ + if (!isNativeRate(m_sampleRate)) + { + qWarning() << "Echo canceller:" << m_sampleRate + << "Hz is not one of AEC3's rates (8/16/32/48 kHz) - not cancelling"; + return; + } + + // AEC3 works on 10ms of audio at a time, everywhere, at every rate. + m_frameSize = m_sampleRate / 100; + + webrtc::AudioProcessing::Config cfg; + + cfg.echo_canceller.enabled = true; + // AEC3 proper. The mobile mode is the cut down fixed point canceller for + // phones, and is worse anywhere that can afford not to use it. + cfg.echo_canceller.mobile_mode = false; + cfg.echo_canceller.enforce_high_pass_filtering = true; + + cfg.high_pass_filter.enabled = true; + + // Costs little next to the filter, and a lower noise floor is what lets + // the residual echo suppressor tell echo from room noise. + cfg.noise_suppression.enabled = true; + cfg.noise_suppression.level = webrtc::AudioProcessing::Config::NoiseSuppression::kModerate; + + // Both AGCs stay off. The call has no level control anywhere else, and a + // gain riding the microphone moves the echo path, which is the one thing + // an adaptive filter cannot follow. + cfg.gain_controller1.enabled = false; + cfg.gain_controller2.enabled = false; + + cfg.transient_suppression.enabled = false; + +#if PICA_WEBRTC_AUDIO_PROCESSING_MAJOR < 2 + // All three were dropped in 2.x. The first two only gate statistics we + // never read; the third is a second, statistical echo estimator whose + // output we do not use either. Switching them off on 1.x is therefore + // the same configuration 2.x gives us for nothing. + cfg.voice_detection.enabled = false; + cfg.level_estimation.enabled = false; + cfg.residual_echo_detector.enabled = false; +#endif + + m_d = new EchoCancellerPrivate; + m_d->stream = webrtc::StreamConfig(m_sampleRate, 1); + +#if PICA_WEBRTC_AUDIO_PROCESSING_MAJOR >= 2 + m_d->apm = webrtc::AudioProcessingBuilder().Create(); +#else + // 1.x hands back a raw pointer to an object whose reference count is + // still zero - the scoped_refptr is what takes it to one, and dropping + // the result on the floor would leak rather than free. + m_d->apm = rtc::scoped_refptr<webrtc::AudioProcessing>(webrtc::AudioProcessingBuilder().Create()); +#endif + + if (!m_d->apm) + { + qWarning() << "Could not create the WebRTC audio processing module"; + delete m_d; + m_d = nullptr; + return; + } + + m_d->apm->ApplyConfig(cfg); + + // Mono at our rate in both directions, which the integer interface + // requires anyway. Spelled out through a ProcessingConfig rather than the + // shorter Initialize() overload taking channel layouts, because that + // overload and the ChannelLayout enum it needs are gone in 2.x. + webrtc::ProcessingConfig streams; + streams.input_stream() = m_d->stream; + streams.output_stream() = m_d->stream; + streams.reverse_input_stream() = m_d->stream; + streams.reverse_output_stream() = m_d->stream; + + const int err = m_d->apm->Initialize(streams); + if (err != webrtc::AudioProcessing::kNoError) + { + qWarning() << "Could not initialise the WebRTC audio processing module:" << err; + delete m_d; + m_d = nullptr; + return; + } + + // Hold off the first report until there is a window's worth of audio + // behind the averages, otherwise it only says the call just started. + m_nextReportSamples = qint64(m_sampleRate) * kReportIntervalSec; + + // The library version is in there because it is otherwise invisible which + // of the two parallel-installable ones got linked, and they behave + // differently enough to be worth knowing about from a log alone. + qDebug("Echo canceller: WebRTC AEC3 (webrtc-audio-processing-%d), %d Hz, frame %d samples", + PICA_WEBRTC_AUDIO_PROCESSING_MAJOR, m_sampleRate, m_frameSize); +} + +EchoCanceller::~EchoCanceller() +{ + delete m_d; + + if (m_farSwr) + swr_free(&m_farSwr); +} + +bool EchoCanceller::isValid() const +{ + return m_d != nullptr; +} + +void EchoCanceller::pushFarEnd(const qint16 *pcm, int nsamples, int srcRate) +{ + if (!m_d || !pcm || nsamples <= 0) + return; + + QMutexLocker locker(&m_renderMutex); + + if (srcRate > 0 && srcRate != m_sampleRate) + { + if (m_farSwr && m_farSwrRate != srcRate) + { + swr_free(&m_farSwr); + m_farSwrRate = 0; + } + + if (!m_farSwr) + { +#if EC_HAVE_CH_LAYOUT + AVChannelLayout mono; + av_channel_layout_default(&mono, 1); + int ret = swr_alloc_set_opts2(&m_farSwr, &mono, AV_SAMPLE_FMT_S16, m_sampleRate, + &mono, AV_SAMPLE_FMT_S16, srcRate, 0, nullptr); + av_channel_layout_uninit(&mono); + if (ret < 0) + m_farSwr = nullptr; +#else + m_farSwr = swr_alloc_set_opts(nullptr, AV_CH_LAYOUT_MONO, AV_SAMPLE_FMT_S16, m_sampleRate, + AV_CH_LAYOUT_MONO, AV_SAMPLE_FMT_S16, srcRate, 0, nullptr); +#endif + if (m_farSwr && swr_init(m_farSwr) < 0) + swr_free(&m_farSwr); + + if (!m_farSwr) + { + qWarning() << "Echo canceller: cannot resample" << srcRate << "Hz far end to" + << m_sampleRate << "Hz - echo cancellation will not work"; + return; + } + + m_farSwrRate = srcRate; + qDebug() << "Echo canceller: far end is" << srcRate << "Hz, resampling to" << m_sampleRate << "Hz"; + } + + // Upper bound on what this many input samples can become, plus + // whatever the converter is still holding from last time. + int room = (int)av_rescale_rnd(swr_get_delay(m_farSwr, srcRate) + nsamples, + m_sampleRate, srcRate, AV_ROUND_UP); + if (room <= 0) + return; + + m_farScratch.resize(room); + + uint8_t *out[1] = { (uint8_t *)m_farScratch.data() }; + const uint8_t *in[1] = { (const uint8_t *)pcm }; + + int got = swr_convert(m_farSwr, out, room, in, nsamples); + if (got <= 0) + return; + + pcm = m_farScratch.constData(); + nsamples = got; + } + + int base = m_farPending.size(); + m_farPending.resize(base + nsamples); + memcpy(m_farPending.data() + base, pcm, nsamples * sizeof(qint16)); + + double farEnergy = 0.0; + int blocks = m_farPending.size() / m_frameSize; + + for (int b = 0; b < blocks; b++) + { + qint16 *farBlock = m_farPending.data() + b * m_frameSize; + + for (int i = 0; i < m_frameSize; i++) + farEnergy += double(farBlock[i]) * double(farBlock[i]); + + // In place: the module is happy for source and destination to be the + // same buffer, and nothing downstream wants the processed render + // signal - handing it over is only how AEC3 learns what is about to + // come back through the microphone. + m_d->apm->ProcessReverseStream(farBlock, m_d->stream, m_d->stream, farBlock); + } + + if (blocks > 0) + { + m_farPending.remove(0, blocks * m_frameSize); + + QMutexLocker statLocker(&m_statMutex); + m_farEnergy = m_farEnergy * 0.95 + (farEnergy / (blocks * m_frameSize)) * 0.05; + m_renderBlocks += blocks; + } +} + +void EchoCanceller::processNearEnd(qint16 *pcm, int nsamples) +{ + if (!m_d || !pcm || nsamples < m_frameSize) + return; + + double nearEnergy = 0.0; + int blocks = nsamples / m_frameSize; + + { + QMutexLocker locker(&m_captureMutex); + + for (int b = 0; b < blocks; b++) + { + // Not called "near" - windef.h still defines that as an empty + // macro on the mingw-w64 builds. + qint16 *nearBlock = pcm + b * m_frameSize; + + for (int i = 0; i < m_frameSize; i++) + nearEnergy += double(nearBlock[i]) * double(nearBlock[i]); + + m_d->apm->ProcessStream(nearBlock, m_d->stream, m_d->stream, nearBlock); + } + } + + // At least one whole block, guaranteed by the nsamples check on entry. + const int used = blocks * m_frameSize; + bool report = false; + + { + QMutexLocker statLocker(&m_statMutex); + + // Exponential forgetting, so the levels reflect the last few seconds + // rather than the whole call. Per sample, so a change in the capture + // path's block size does not move them. + m_nearEnergy = m_nearEnergy * 0.95 + (nearEnergy / used) * 0.05; + + m_processedSamples += used; + m_captureBlocks += blocks; + if (m_processedSamples >= m_nextReportSamples) + { + m_nextReportSamples = m_processedSamples + qint64(m_sampleRate) * kReportIntervalSec; + report = true; + } + } + + // Outside the lock: the accessors below take it themselves, and qDebug() + // does I/O that has no business happening with a mutex held on the + // capture thread. The values can shift by one block in between, which + // does not matter for a log line. + if (report) + { + int delayMs = 0; + double erleDb = 0.0; + double erlDb = 0.0; + bool haveErl = false; + + { + QMutexLocker locker(&m_captureMutex); + webrtc::AudioProcessingStats stats = m_d->apm->GetStatistics(); + + if (stats.delay_ms.has_value()) + delayMs = *stats.delay_ms; + if (stats.echo_return_loss_enhancement.has_value()) + erleDb = *stats.echo_return_loss_enhancement; + if (stats.echo_return_loss.has_value()) + { + erlDb = *stats.echo_return_loss; + haveErl = true; + } + } + + qint64 lead = 0; + { + QMutexLocker statLocker(&m_statMutex); + lead = m_renderBlocks - m_captureBlocks; + } + + // erl says how strongly the speaker couples back into the microphone, + // which is whether there is anything worth cancelling at all. AEC3 + // reports it negated (echo_remover.cc: -10*log10(erl)), so the more + // negative it is the weaker the coupling - a headset reads well down, + // speakers in a small room read close to zero. + // + // erle is how much of that coupling the filter is actually removing. + // It sits at its 0 dB floor (Erle::min = 1.f) until the filter + // converges, so a call that never leaves +0.2 dB is a call where the + // linear filter never got anywhere. + // + // The delay is what AEC3 has aligned the two streams at. Zero is not + // a delay: block_processor.cc reports 0 when the estimator has no + // value, so it means the filter is running unaligned and the erle + // beside it cannot be anything but the floor. + QString delayText = delayMs > 0 + ? QString("echo delay %1 ms").arg(delayMs) + : QStringLiteral("NOT ALIGNED"); + + QString erlText = haveErl + ? QString("erl %1 dB").arg(erlDb, 0, 'f', 1) + : QStringLiteral("erl n/a"); + + qDebug("AEC: erle %+.1f dB %s mic %.1f dBFS far %.1f dBFS %s render lead %d ms", + erleDb, qPrintable(erlText), nearEndLevelDb(), farEndLevelDb(), + qPrintable(delayText), (int)(lead * 10)); // a block is 10ms, always + } +} + +double EchoCanceller::erle() +{ + if (!m_d) + return 0.0; + + QMutexLocker locker(&m_captureMutex); + + webrtc::AudioProcessingStats stats = m_d->apm->GetStatistics(); + + return stats.echo_return_loss_enhancement.has_value() + ? *stats.echo_return_loss_enhancement + : 0.0; +} + +// Mean square of 16 bit samples to dBFS, with a floor so digital silence +// prints as a number rather than -inf. +static double level_db(double meanSquare) +{ + static const double kFullScale = 32768.0 * 32768.0; + + if (meanSquare <= 0.0) + return -120.0; + + double db = 10.0 * log10(meanSquare / kFullScale); + return db < -120.0 ? -120.0 : db; +} + +double EchoCanceller::nearEndLevelDb() +{ + QMutexLocker locker(&m_statMutex); + return level_db(m_nearEnergy); +} + +double EchoCanceller::farEndLevelDb() +{ + QMutexLocker locker(&m_statMutex); + return level_db(m_farEnergy); +} diff --git a/pica-client/echocanceller.h b/pica-client/echocanceller.h new file mode 100644 index 0000000..33e1584 --- /dev/null +++ b/pica-client/echocanceller.h @@ -0,0 +1,196 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#ifndef ECHOCANCELLER_H +#define ECHOCANCELLER_H + +#include <QString> +#include <QMutex> +#include <QVector> +#include <QSharedPointer> +#include <QMetaType> + +struct EchoCancellerPrivate; +struct SwrContext; + +// Where the acoustic echo of a call is taken out of the microphone signal. +// One of these three, never two at once: running a second canceller over an +// already cancelled signal gives it a near silent reference to chase and it +// chews holes in the speech. +enum EchoCancellationMode +{ + // EchoCanceller below - WebRTC's AEC3, in process. + EchoCancellationOwn, + + // Whatever the operating system or sound server does below us, which is + // better where it exists: it sees the real speaker signal and the real + // clock. Not offered everywhere - see + // AudioDevice::PlatformEchoCancellationAvailable(). + EchoCancellationPlatform, + + // Nothing cancels. Correct with a headset, and the only honest answer + // when both of the above make things worse. + EchoCancellationNone +}; + +// The "audio.echo_cancellation" setting. Both must be called from a thread +// that may touch the settings database - see AudioDevice::SetLinuxDriverName() +// for why the audio threads may not. +// +// Nothing stored yet means the default for this platform: the platform's own +// where there is one, ours otherwise. The setting this replaced +// ("audio.echo_cancel", a plain on/off) is still honoured when it is all +// there is, so an existing install that had it switched off stays that way. +EchoCancellationMode loadEchoCancellationSetting(); +void storeEchoCancellationSetting(EchoCancellationMode mode); + +// Acoustic echo cancellation for a call, using WebRTC's AEC3 through the +// audio processing module. +// +// One instance is shared by the two AudioDevice objects of a call - the +// playback one feeds it the far end signal it is about to hand to the sound +// card via pushFarEnd(), the capture one runs the microphone signal through +// processNearEnd() before encoding. Both run on their own thread, which is +// what AEC3 expects: one render thread, one capture thread. +// +// Because AudioVideoCallController tears a call down without joining those +// two threads (see stopAudioPipeline()), ownership is shared: hold this +// through a QSharedPointer so the object outlives whichever thread leaves +// last. +// +// One per call, built when the call starts and dropped when it ends. There is +// nothing worth carrying over: the previous call's room response is not this +// call's, and the module is cheap enough to build. +// +// Nothing here tries to line the two signals up. AEC3 has its own delay +// estimator and a render buffer to hold the far end audio until the echo of +// it arrives, which is the whole reason it copes with an application that +// hands over playback audio some way ahead of the speaker actually making a +// sound - and with that lead changing when the sound card's buffer does. +class EchoCanceller +{ +public: + // sampleRate must be one of AEC3's native rates - 8000, 16000, 32000 or + // 48000. Anything else leaves isValid() false rather than silently + // processing at the wrong rate; the caller then runs without + // cancellation. + explicit EchoCanceller(int sampleRate); + ~EchoCanceller(); + + bool isValid() const; + int sampleRate() const { return m_sampleRate; } + + // The block AEC3 works on: 10ms, always. Audio handed to + // processNearEnd() should be a whole number of these. + int frameSize() const { return m_frameSize; } + + // Playback side: the audio about to be written to the output device. + // + // srcRate is what pcm is sampled at, and may differ from sampleRate(): + // we capture at a rate of our choosing but play back at whatever the peer + // announced, so a call with a build that negotiates a different rate ends + // up with the two directions disagreeing. Passing 0 means "same as ours". + // Anything else is resampled on the way in. + void pushFarEnd(const qint16 *pcm, int nsamples, int srcRate = 0); + + // Capture side: removes the echo of what pushFarEnd() was given, in + // place. nsamples should be a whole number of frameSize() blocks; a + // partial trailing block is passed through untouched. + void processNearEnd(qint16 *pcm, int nsamples); + + // Echo return loss enhancement in dB, as AEC3 measures it: how much + // quieter the echo is after cancellation than before. Zero until the + // filter has had far end audio to work on. + // + // Only meaningful while the far end is actually talking, which is what + // farEndLevelDb() is for: with nothing coming out of the speaker there is + // no echo to remove and the figure means nothing. + double erle(); + + // Recent signal levels in dBFS, averaged over a few seconds. + // nearEndLevelDb() is the microphone before cancellation - a floor-level + // reading there means the capture path is dead and nothing else in the + // numbers is worth reading. + double nearEndLevelDb(); + double farEndLevelDb(); + +private: + Q_DISABLE_COPY(EchoCanceller) + + int m_sampleRate; + int m_frameSize; + + // The audio processing module and the stream configurations handed to it, + // kept out of this header so that the WebRTC headers - which want C++17 + // and drag in abseil - are only seen by echocanceller.cpp. + EchoCancellerPrivate *m_d; + + // Guards the render direction: the far end accumulator, the resampler, + // and ProcessReverseStream(). Only the playback thread takes it. + QMutex m_renderMutex; + + // Guards the capture direction: ProcessStream() and the statistics read + // alongside it. Taken by the capture thread, and by whoever calls the + // erle() accessor. + QMutex m_captureMutex; + + // Far end audio that did not fill a whole 10ms block, waiting for the + // samples that will complete it. + QVector<qint16> m_farPending; + + // Rate conversion for a far end that is not running at our rate, built on + // first use and rebuilt if the rate changes. + SwrContext *m_farSwr; + int m_farSwrRate; + QVector<qint16> m_farScratch; + + // Exponentially averaged mean square of the near end (microphone) and of + // the far end reference, for the level readings. Per sample rather than + // per call, so they stay comparable whatever block size the capture path + // hands us. + double m_nearEnergy; + double m_farEnergy; + QMutex m_statMutex; + + // Drives the periodic qDebug() in processNearEnd(). Counted in samples + // rather than wall clock so the report interval does not depend on how + // punctually the capture thread is scheduled. Guarded by m_statMutex. + qint64 m_processedSamples; + qint64 m_nextReportSamples; + + // 10ms blocks handed to each direction. AEC3 lines the two streams up by + // counting API calls, not by any clock, so the gap between these is what + // its alignment is measured in. In a healthy call it settles at the depth + // of the sound card's output buffer and stays there; a gap that keeps + // growing or shrinking means capture and playback are running off + // different clocks and the alignment is being dragged out from under the + // filter. Guarded by m_statMutex. + qint64 m_renderBlocks; + qint64 m_captureBlocks; + + // How often the canceller reports how it is doing, in seconds. + static const int kReportIntervalSec = 2; + + // True if rate is one of the rates AEC3's integer interface accepts. + static bool isNativeRate(int rate); +}; + +typedef QSharedPointer<EchoCanceller> EchoCancellerPtr; +// Handed to the audio threads through their event queues, see +// AudioDevice::setEchoCanceller(). +Q_DECLARE_METATYPE(EchoCancellerPtr) + +#endif // ECHOCANCELLER_H diff --git a/pica-client/globals.h b/pica-client/globals.h index 1817f3c..ab359d6 100644 --- a/pica-client/globals.h +++ b/pica-client/globals.h @@ -42,6 +42,7 @@ extern class QIcon picapica_ico_fly; extern class PicaActionCenter *action_center; extern class PicaSysTray *systray; extern class FileTransferController *ftctrl; +extern class AudioVideoCallController *avctrl; extern class QString snd_newmessage; extern class AccountsWindow *accwindow; #endif // GLOBALS_H diff --git a/pica-client/history.cpp b/pica-client/history.cpp index 6daa862..1ae0b9d 100644 --- a/pica-client/history.cpp +++ b/pica-client/history.cpp @@ -17,10 +17,10 @@ #include "history.h" #include <QDebug> -History::History(QString storage, QByteArray my_id) +History::History(QString storage, QByteArray my_id, QString connectionName) : me_(my_id) { - dbconn = QSqlDatabase::database(); + dbconn = connectionName.isEmpty() ? QSqlDatabase::database() : QSqlDatabase::database(connectionName); dbconn.setDatabaseName(storage); if (!dbconn.open()) @@ -29,7 +29,7 @@ History::History(QString storage, QByteArray my_id) return; } - QSqlQuery query; + QSqlQuery query(dbconn); query.exec("PRAGMA foreign_keys=ON;"); @@ -38,7 +38,7 @@ History::History(QString storage, QByteArray my_id) void History::Add(QByteArray peer_id, QString message, bool is_me) { - QSqlQuery query; + QSqlQuery query(dbconn); query.prepare( "insert into \"history\" (\"contact_id\", \"account_id\", \"is_me\", \"is_delivered\", \"message\", \"id\", \"timestamp\") \ @@ -68,7 +68,7 @@ void History::Add(QByteArray peer_id, QString message, bool is_me) void History::SetDelivered(QByteArray peer_id) { - QSqlQuery query; + QSqlQuery query(dbconn); query.prepare("update history set is_delivered=1 where id in \ (select id from history where \ @@ -86,7 +86,7 @@ QList<History::HistoryRecord> History::GetMessages(QByteArray peer_id, QString k { QList<HistoryRecord> L; HistoryRecord r; - QSqlQuery query; + QSqlQuery query(dbconn); query.setForwardOnly(true); query.prepare("select contact_id, is_me, is_delivered, timestamp, message from history \ @@ -121,7 +121,7 @@ QList<History::HistoryRecord> History::GetMessages(QByteArray peer_id, quint32 s { QList<HistoryRecord> L; HistoryRecord r; - QSqlQuery query; + QSqlQuery query(dbconn); query.setForwardOnly(true); query.prepare("select contact_id, is_me, is_delivered, timestamp, message from history \ @@ -156,7 +156,7 @@ QList<History::HistoryRecord> History::GetMessages(QByteArray peer_id, quint32 s QMap<QByteArray, QList<QString> > History::GetUndeliveredMessages() { QMap<QByteArray, QList<QString> > M; - QSqlQuery query; + QSqlQuery query(dbconn); query.setForwardOnly(true); query.prepare("select contact_id, message from history \ diff --git a/pica-client/history.h b/pica-client/history.h index c1c7615..53f8ff7 100644 --- a/pica-client/history.h +++ b/pica-client/history.h @@ -35,7 +35,8 @@ public: QString message; }; - History(QString storage, QByteArray my_id); + // See Nodes::Nodes() for what connectionName selects and why. + History(QString storage, QByteArray my_id, QString connectionName = QString()); void Add(QByteArray peer_id, QString message, bool is_me);//is_me - true - message from me to peer, false - from peer to me void SetDelivered(QByteArray peer_id); //mark first undelivered message from me to peer as delivered QList<HistoryRecord> GetMessages(QByteArray peer_id, quint32 start_timestamp, quint32 end_timestamp); diff --git a/pica-client/main.cpp b/pica-client/main.cpp index c021209..684af8f 100644 --- a/pica-client/main.cpp +++ b/pica-client/main.cpp @@ -17,6 +17,7 @@ //#include <QtGui/QApplication> #include <QCoreApplication> #include <QApplication> +#include <QThread> #include "mainwindow.h" #include "accountswindow.h" #include "globals.h" @@ -24,8 +25,10 @@ #include "skynet.h" #include "msguirouter.h" #include "filetransfercontroller.h" +#include "audiovideocallcontroller.h" #include "picaactioncenter.h" #include "picasystray.h" +#include "vaapi.h" #include <QDir> #include <QMessageBox> #include <QString> @@ -34,6 +37,7 @@ #include "dhparam.h" #include "settings.h" #include "dialogs/settingsdialog.h" +#include "audiodevice.h" //globals @@ -51,6 +55,7 @@ QIcon picapica_ico_fly; class PicaActionCenter *action_center; class PicaSysTray *systray; class FileTransferController *ftctrl; +class AudioVideoCallController *avctrl; class AccountsWindow *accwindow; QString config_defaultDHParam; @@ -443,9 +448,25 @@ static bool create_config_dir() update_database(); QFile::setPermissions(config_dbname, QFile::ReadOwner | QFile::WriteOwner); + + // Publish the audio driver choice and the echo cancellation setting to the + // audio threads while we are still the only thread and the settings + // database is reachable - see AudioDevice::SetLinuxDriverName() for why + // they cannot be read on demand. + // + // The driver first: on Linux it is what decides whether the platform has + // any cancellation to offer, which loadEchoCancellationSetting() needs in + // order to work out the default. + { + Settings audiost(config_dbname); + AudioDevice::SetLinuxDriverName(audiost.loadValue("audio.driver", "alsa").toString()); + } + + AudioDevice::SetEchoCancellation(loadEchoCancellationSetting()); + /*if (!QFile::exists(config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE)) { - OpenSSLTool osslt; + OpenSSLLib osslt; msgBox.setText(QString(QObject::tr("Diffie-Hellman parameters will be generated. Please wait. This process can take several minutes..."))); msgBox.exec(); @@ -495,8 +516,24 @@ static bool create_config_dir() int main(int argc, char *argv[]) { +#ifdef HAVE_VAAPI + // Before Qt opens its X connection, which is the only time Xlib will + // listen - see the comment on the function itself. + VaapiContext::initX11Threading(); +#endif + QApplication a(argc, argv); +#ifdef HAVE_VAAPI + // Decoded hardware frames travel from the decoding thread to the widget + // drawing them through queued signals, which needs their type registered. + VaapiContext::registerMetaTypes(); + + // Settles how a decoded surface will be drawn in this session, which has + // to be known before the first one is created. + VaapiContext::detectX11Display(); +#endif + #ifdef WIN32 config_resourceDir = QLatin1String("share\\"); #elif defined(__APPLE__) @@ -544,9 +581,59 @@ int main(int argc, char *argv[]) FileTransferController ftc; ftctrl = &ftc; + AudioVideoCallController avc; + avctrl = &avc; + + // SkyNet owns all the protocol/network state (PICA_c2n/PICA_c2c + // connections, the timer-driven PICA_event_loop() polling, and every + // protocol callback dispatch). It's moved off the GUI thread onto its + // own network thread so that GUI-thread stalls (blocked X11/graphics + // calls, a locked screen suspending the process, etc.) can no longer + // starve the network connection and cause disconnects. Its public + // methods remain safe to call from any thread - see SkyNet::init() and + // the do_*() wrapper pattern in skynet.cpp/h. + // + // Done last, after every controller above has already connected its + // signal/slot listeners to skynet while it was still on the GUI + // thread, so there is no window during which a listener could miss a + // signal skynet emits from its new thread. + QThread networkThread; + networkThread.setObjectName("SkyNetThread"); + + skynet->moveToThread(&networkThread); + QObject::connect(&networkThread, SIGNAL(started()), skynet, SLOT(init())); + networkThread.start(); + aw.show(); a.setQuitOnLastWindowClosed(false); - return a.exec(); + int ret = a.exec(); + + // skynet's thread affinity needs to move back to the main thread + // before it (and everything else declared above) gets destroyed as + // main() returns - otherwise QObject's destructor can't clean up its + // still-registered timers (event_loop_timer_id, c2c_reconnect_timer_id, + // ...) and prints "Timers cannot be stopped from another thread". + // + // QObject::moveToThread() only succeeds when called from the thread + // the object is currently on - it can be pushed out from its own + // thread, but not pulled in from a different one. So this can't be a + // plain skynet->moveToThread(...) call made from here (the main + // thread); it has to run as code executing on the network thread + // itself, which is what moveBackToMainThread() is for. Using a + // blocking queued call guarantees it has actually completed before + // the network thread is stopped below - if it ran after quit()/wait(), + // there would be no event loop left on that thread to process it. + QMetaObject::invokeMethod(skynet, "moveBackToMainThread", Qt::BlockingQueuedConnection); + + // Now stop and join the network thread before any of the objects + // above - skynet in particular - start being destroyed as main() + // unwinds. Otherwise the network thread could still be executing + // SkyNet code while its destructor (and the destructors of objects it + // signals) runs concurrently on this thread. + networkThread.quit(); + networkThread.wait(); + + return ret; } diff --git a/pica-client/mainwindow.cpp b/pica-client/mainwindow.cpp index 2bbecb5..2e7fed6 100644 --- a/pica-client/mainwindow.cpp +++ b/pica-client/mainwindow.cpp @@ -26,7 +26,8 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), - ui(new Ui::MainWindow) + ui(new Ui::MainWindow), + self_aware_cached(false) { ui->setupUi(this); @@ -73,11 +74,13 @@ MainWindow::~MainWindow() void MainWindow::set_offline() { + self_aware_cached = false; SetStatus(false); } void MainWindow::set_online() { + self_aware_cached = true; SetStatus(true); } @@ -86,12 +89,11 @@ void MainWindow::status_changed(int index) if (status_change_disable_flag) return; - if (index == 0 && !skynet->isSelfAware()) + if (index == 0 && !self_aware_cached) { - Accounts::AccountRecord curr_acc = skynet->CurrentAccount(); - skynet->Join(curr_acc); + skynet->Join(Accounts::GetCurrentAccount()); } - if (1 == index && skynet->isSelfAware()) + if (1 == index && self_aware_cached) skynet->Exit(); } diff --git a/pica-client/mainwindow.h b/pica-client/mainwindow.h index 6360723..378cdf0 100644 --- a/pica-client/mainwindow.h +++ b/pica-client/mainwindow.h @@ -62,6 +62,12 @@ private: void SetStatus(bool connected); bool status_notifications_hidden; + // Mirrors SkyNet's online/offline state, kept in sync via the + // BecameSelfAware()/LostSelfAwareness() signals instead of querying + // skynet->isSelfAware() synchronously (that accessor was removed since + // SkyNet's state must only ever be read on the thread that owns it). + bool self_aware_cached; + private slots: void set_online(); void set_offline(); diff --git a/pica-client/mediadevice.cpp b/pica-client/mediadevice.cpp new file mode 100644 index 0000000..42a661b --- /dev/null +++ b/pica-client/mediadevice.cpp @@ -0,0 +1,12 @@ +#include "mediadevice.h" + +MediaDevice::MediaDevice() +{ + +} + +MediaDevice::~MediaDevice() +{ + +} + diff --git a/pica-client/mediadevice.h b/pica-client/mediadevice.h new file mode 100644 index 0000000..432d457 --- /dev/null +++ b/pica-client/mediadevice.h @@ -0,0 +1,77 @@ +#ifndef MEDIADEVICE_H +#define MEDIADEVICE_H + +#include <QString> +#include <QStringList> +#include <QList> +#include <QByteArray> +#include <QMutex> +#include <QMutexLocker> + +enum MediaDeviceStreamDirection +{ + CAPTURE, + PLAYBACK +}; + +struct MediaDeviceInfo +{ + QString device; + QString humanReadable; + int index; +}; + +// Which call a device is currently allowed to work for. A call is identified +// by the pair of its caller's and its callee's id. +// +// The loops of AudioDevice and VideoDevice are started through their thread's +// event queue and stopped by a direct call from another thread, so the two can +// arrive in either order. A plain stop flag that the loop clears on entry +// loses a stop that came first, and the loop then runs with nobody left to +// stop it. Instead the owner opens the session before it queues the start and +// closes it to stop, and a loop only runs while the session that is open is +// the one it was configured for. All of it is safe to call from any thread. +class MediaCallSession +{ +public: + MediaCallSession() : m_open(false) {} + + void open(const QByteArray &caller_id, const QByteArray &callee_id) + { + QMutexLocker locker(&m_mutex); + m_caller_id = caller_id; + m_callee_id = callee_id; + m_open = true; + } + + void close() + { + QMutexLocker locker(&m_mutex); + m_open = false; + } + + bool isOpenFor(const QByteArray &caller_id, const QByteArray &callee_id) const + { + QMutexLocker locker(&m_mutex); + return m_open && m_caller_id == caller_id && m_callee_id == callee_id; + } + +private: + mutable QMutex m_mutex; + bool m_open; + QByteArray m_caller_id; + QByteArray m_callee_id; +}; + +class MediaDevice +{ +public: + MediaDevice(); + virtual ~MediaDevice(); + virtual QList<MediaDeviceInfo> Enumerate(enum MediaDeviceStreamDirection) = 0; + virtual void Capture() = 0; + virtual void Play() = 0; + virtual void Close() = 0; +}; + +#endif // MEDIADEVICE_H diff --git a/pica-client/msguirouter.cpp b/pica-client/msguirouter.cpp index 88a272c..20897fd 100644 --- a/pica-client/msguirouter.cpp +++ b/pica-client/msguirouter.cpp @@ -23,15 +23,7 @@ #include "globals.h" #include "sound.h" -/* - этот класс должен обеспечивать связь между приёмом-отправкой сообщений и их отображением в пользовательском интерфейсе. - Класс SkyNet отвечает только за прием и отправку сообщений, пересылку через сеть и работу с протоколом, ему пофиг, - как они показываются юзеру. Данный класс должен работать с GUI, например, по приходу нового сообщения (через сигнал от - класса SkyNet) либо помигать иконкой в трее, либо создать новое окно чата, либо развернуть уже имеющееся, либо помигать - свернутым окном на таскбаре. Это поведение может настраиваться, настройки хранить в базе и загружать в конструкторе из - базы sqlite. Например, данный класс должен управлять экземплярами ChatWindow, создавать новые при необходимости либо - активировать имеющиеся. - */ + MsgUIRouter::MsgUIRouter(QObject *parent) : QObject(parent) { diff --git a/pica-client/nativeaudio.cpp b/pica-client/nativeaudio.cpp new file mode 100644 index 0000000..499aad6 --- /dev/null +++ b/pica-client/nativeaudio.cpp @@ -0,0 +1,77 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#include "nativeaudio.h" + +#include <QtGlobal> + +// Per platform factories, defined next to the backends themselves. +#ifdef Q_OS_WIN +NativeAudioBackend *pica_create_wasapi_backend(); +QList<MediaDeviceInfo> pica_enumerate_wasapi(enum MediaDeviceStreamDirection dir); +#endif + +#if defined(Q_OS_MACOS) || defined(Q_OS_MAC) +NativeAudioBackend *pica_create_coreaudio_backend(); +QList<MediaDeviceInfo> pica_enumerate_coreaudio(enum MediaDeviceStreamDirection dir); +#endif + +NativeAudioBackend::~NativeAudioBackend() +{ +} + +bool NativeAudioBackend::isAvailable(const QString &api) +{ +#ifdef Q_OS_WIN + if (api == QLatin1String("wasapi")) + return true; +#endif +#if defined(Q_OS_MACOS) || defined(Q_OS_MAC) + if (api == QLatin1String("coreaudio")) + return true; +#endif + Q_UNUSED(api) + return false; +} + +NativeAudioBackend *NativeAudioBackend::create(const QString &api) +{ +#ifdef Q_OS_WIN + if (api == QLatin1String("wasapi")) + return pica_create_wasapi_backend(); +#endif +#if defined(Q_OS_MACOS) || defined(Q_OS_MAC) + if (api == QLatin1String("coreaudio")) + return pica_create_coreaudio_backend(); +#endif + Q_UNUSED(api) + return nullptr; +} + +QList<MediaDeviceInfo> NativeAudioBackend::enumerate(const QString &api, enum MediaDeviceStreamDirection dir) +{ +#ifdef Q_OS_WIN + if (api == QLatin1String("wasapi")) + return pica_enumerate_wasapi(dir); +#endif +#if defined(Q_OS_MACOS) || defined(Q_OS_MAC) + if (api == QLatin1String("coreaudio")) + return pica_enumerate_coreaudio(dir); +#endif + Q_UNUSED(api) + Q_UNUSED(dir) + return QList<MediaDeviceInfo>(); +} diff --git a/pica-client/nativeaudio.h b/pica-client/nativeaudio.h new file mode 100644 index 0000000..3e364c6 --- /dev/null +++ b/pica-client/nativeaudio.h @@ -0,0 +1,119 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#ifndef NATIVEAUDIO_H +#define NATIVEAUDIO_H + +#include "mediadevice.h" +#include <QString> +#include <QList> + +// Audio input/output through a platform API directly, bypassing FFmpeg's +// libavdevice. +// +// FFmpeg's audio device wrappers open the sound card the plain way, which on +// Windows and macOS means no acoustic echo cancellation: both platforms only +// run their own AEC for streams that were opened declaring themselves part of +// a voice call, and libavdevice has no way to say that. Since that AEC is +// better than anything we can do in process - it sits below us in the audio +// stack and can see the real speaker signal and the real clock - it is worth +// talking to those APIs ourselves. +// +// AudioDevice picks between this and the FFmpeg path on the strength of the +// driver string PlatformDriverName() returns: a name prefixed with +// "platform-" means the rest of it is an apiName() below. +// +// One instance drives one direction. Whether the two directions of a call end +// up sharing anything underneath is the backend's business - on macOS they +// have to, because the AEC there lives in a single audio unit that renders +// and captures at once. + +// What a stream is going to be used for. +// +// The two call modes differ in one thing only: whether the platform is asked +// for its voice processing, echo cancellation above all. Which of them a call +// uses is the "audio.echo_cancellation" setting - see EchoCancellationMode. +// They agree on everything else, device selection included: a call belongs on +// the endpoint the user nominated for calls whoever ends up cancelling the +// echo. +// +// A plain stream is not a call at all, and must not ask for voice processing: +// on macOS the echo canceller is an audio unit that captures as well as +// renders, so asking for it to play a ringtone would open the microphone, +// prompt for permission and light the recording indicator, all to make a +// telephone noise. +enum NativeAudioMode +{ + NativeAudioVoiceCall, + NativeAudioVoiceCallRaw, + NativeAudioPlain +}; + +class NativeAudioBackend +{ +public: + virtual ~NativeAudioBackend(); + + // The platform API this backend speaks, matching what follows the + // "platform-" prefix in a driver name. + virtual QString apiName() const = 0; + + // device is one of the MediaDeviceInfo::device strings enumerate() + // returned, or "default". On failure *error, if given, is filled in with + // something worth showing the user. + virtual bool openCapture(const QString &device, int sampleRate, int channels, + NativeAudioMode mode, QString *error) = 0; + virtual bool openPlayback(const QString &device, int sampleRate, int channels, + NativeAudioMode mode, QString *error) = 0; + + // Reads up to maxSamples interleaved 16 bit samples, waiting at most + // timeoutMs for the first of them. Returns the number of samples read, + // which may be zero if the timeout ran out, or negative on error. + virtual int read(qint16 *buf, int maxSamples, int timeoutMs) = 0; + + // Hands nsamples interleaved 16 bit samples to the device, waiting up to + // timeoutMs for room. Returns the number accepted - short writes happen + // when the timeout expires with the device buffer still full - or + // negative on error. + virtual int write(const qint16 *buf, int nsamples, int timeoutMs) = 0; + + virtual void close() = 0; + + // One line describing what the stream actually negotiated, for the + // settings dialog to show next to the test result. What a device really + // gave us, as opposed to what we asked it for, is otherwise invisible + // from outside - and it is the first thing worth knowing when a recording + // comes out wrong. Empty when a backend has nothing to add. + virtual QString formatDescription() const { return QString(); } + + // Whether the stream was opened in a mode the platform documents as + // running its own acoustic echo cancellation, in which case the caller + // should not add ours on top. Note this reports what we asked for and + // were granted, which on Windows is not the same as a promise that the + // endpoint's driver actually implements the effect. + virtual bool hasPlatformEchoCancellation() const = 0; + + // True if this build knows the named API at all. + static bool isAvailable(const QString &api); + + // Caller owns the result. Returns null for an API this build has no + // implementation of. + static NativeAudioBackend *create(const QString &api); + + static QList<MediaDeviceInfo> enumerate(const QString &api, enum MediaDeviceStreamDirection dir); +}; + +#endif // NATIVEAUDIO_H diff --git a/pica-client/nativeaudio_coreaudio.cpp b/pica-client/nativeaudio_coreaudio.cpp new file mode 100644 index 0000000..6dc9ad7 --- /dev/null +++ b/pica-client/nativeaudio_coreaudio.cpp @@ -0,0 +1,896 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#include "nativeaudio.h" + +#if defined(Q_OS_MACOS) || defined(Q_OS_MAC) + +#include "audioring.h" + +#include <QDebug> +#include <QObject> +#include <QMutex> +#include <QMutexLocker> +#include <QVector> + +#include <time.h> +#include <string.h> + +#include <CoreAudio/CoreAudio.h> +#include <AudioUnit/AudioUnit.h> +#include <AudioToolbox/AudioToolbox.h> +#include <CoreFoundation/CoreFoundation.h> + +// Bus numbering for an output-type audio unit, which is what both the +// VoiceProcessingIO and the plain HAL output unit are: bus 0 faces the +// speaker, bus 1 the microphone. +static const AudioUnitElement kOutputBus = 0; +static const AudioUnitElement kInputBus = 1; + +// Largest slice a unit will ever hand us. The default is 1156 frames; ask for +// a round number above it and size the scratch buffers to match. +static const UInt32 kMaxFramesPerSlice = 4096; + +static QString cfStringToQString(CFStringRef s) +{ + if (!s) + return QString(); + + CFIndex length = CFStringGetLength(s); + CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1; + QVector<char> buf(maxSize); + + if (!CFStringGetCString(s, buf.data(), maxSize, kCFStringEncodingUTF8)) + return QString(); + + return QString::fromUtf8(buf.constData()); +} + +static QString osStatusString(OSStatus err) +{ + return QString::number((int)err); +} + +// Number of channels a device offers on one scope. Zero means it does not do +// that direction at all, which is how an input-only or output-only device is +// told apart. +static int deviceChannelCount(AudioDeviceID dev, bool input) +{ + AudioObjectPropertyAddress addr; + addr.mSelector = kAudioDevicePropertyStreamConfiguration; + addr.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; + addr.mElement = kAudioObjectPropertyElementMaster; + + UInt32 size = 0; + if (AudioObjectGetPropertyDataSize(dev, &addr, 0, nullptr, &size) != noErr || size == 0) + return 0; + + QVector<char> raw(size); + AudioBufferList *list = (AudioBufferList *)raw.data(); + if (AudioObjectGetPropertyData(dev, &addr, 0, nullptr, &size, list) != noErr) + return 0; + + int channels = 0; + for (UInt32 i = 0; i < list->mNumberBuffers; i++) + channels += list->mBuffers[i].mNumberChannels; + + return channels; +} + +static QString deviceUid(AudioDeviceID dev) +{ + AudioObjectPropertyAddress addr; + addr.mSelector = kAudioDevicePropertyDeviceUID; + addr.mScope = kAudioObjectPropertyScopeGlobal; + addr.mElement = kAudioObjectPropertyElementMaster; + + CFStringRef uid = nullptr; + UInt32 size = sizeof(uid); + if (AudioObjectGetPropertyData(dev, &addr, 0, nullptr, &size, &uid) != noErr || !uid) + return QString(); + + QString result = cfStringToQString(uid); + CFRelease(uid); + return result; +} + +static QString deviceName(AudioDeviceID dev) +{ + AudioObjectPropertyAddress addr; + addr.mSelector = kAudioObjectPropertyName; + addr.mScope = kAudioObjectPropertyScopeGlobal; + addr.mElement = kAudioObjectPropertyElementMaster; + + CFStringRef name = nullptr; + UInt32 size = sizeof(name); + if (AudioObjectGetPropertyData(dev, &addr, 0, nullptr, &size, &name) != noErr || !name) + return QString(); + + QString result = cfStringToQString(name); + CFRelease(name); + return result; +} + +static QVector<AudioDeviceID> allDevices() +{ + QVector<AudioDeviceID> devices; + + AudioObjectPropertyAddress addr; + addr.mSelector = kAudioHardwarePropertyDevices; + addr.mScope = kAudioObjectPropertyScopeGlobal; + addr.mElement = kAudioObjectPropertyElementMaster; + + UInt32 size = 0; + if (AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &addr, 0, nullptr, &size) != noErr) + return devices; + + devices.resize(size / sizeof(AudioDeviceID)); + if (devices.isEmpty()) + return devices; + + if (AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, 0, nullptr, &size, devices.data()) != noErr) + devices.clear(); + + return devices; +} + +// The system's current default input or output device. +// +// Needed because kAudioUnitSubType_HALOutput left alone follows the default +// OUTPUT device on both of its buses, so an input only unit that is never +// bound to a device tries to capture from the speakers. VoiceProcessingIO has +// no such problem, which is why nothing needed this until there was a plain +// capture path. +static AudioDeviceID defaultDevice(bool input) +{ + AudioObjectPropertyAddress addr; + addr.mSelector = input ? kAudioHardwarePropertyDefaultInputDevice + : kAudioHardwarePropertyDefaultOutputDevice; + addr.mScope = kAudioObjectPropertyScopeGlobal; + addr.mElement = kAudioObjectPropertyElementMaster; + + AudioDeviceID dev = kAudioObjectUnknown; + UInt32 size = sizeof(dev); + + if (AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, 0, nullptr, &size, &dev) != noErr) + return kAudioObjectUnknown; + + return dev; +} + +// Looks up a device by the UID string enumerate() handed out. +static AudioDeviceID deviceForUid(const QString &uid, bool input) +{ + QVector<AudioDeviceID> devices = allDevices(); + + for (int i = 0; i < devices.size(); i++) + { + if (deviceChannelCount(devices[i], input) <= 0) + continue; + if (deviceUid(devices[i]) == uid) + return devices[i]; + } + + return kAudioObjectUnknown; +} + +// An output-type audio unit and the rings that connect its real time callbacks +// to the AudioDevice loops. +// +// Two shapes of it exist, and the difference is the whole reason this file is +// here. A voice unit is kAudioUnitSubType_VoiceProcessingIO: it renders and +// captures at once and subtracts what it is about to play from what it just +// heard, which is macOS's acoustic echo canceller and is better than anything +// we could run in process. Because that only works when both directions go +// through the same unit, and AudioDevice keeps one object per direction on its +// own thread, the voice unit is a refcounted singleton the two of them share. +// +// A plain unit is kAudioUnitSubType_HALOutput with no voice processing, one +// per caller, running one direction only. Ringtones and earpiece tones use +// the output flavour: they are not part of a call, and opening a voice unit +// to play one would switch the microphone on, prompt for permission and light +// the recording indicator. The input flavour is for a call that cancels its +// own echo, or none of it - see NativeAudioVoiceCallRaw. +// +// One consequence of the singleton worth knowing about: an audio unit is +// bound to one device, so capture and playback cannot be on different sound +// cards while the AEC is in use. When the two selections disagree, the one +// that got there first wins and a warning is logged. +class CoreAudioUnit +{ +public: + // The shared voice unit. forCapture says which direction is attaching; + // release() must later be called with the same value. + static CoreAudioUnit *acquireVoice(const QString &device, int sampleRate, int channels, + bool forCapture, QString *error); + + // A private output only unit with no voice processing. The caller owns + // it and releases it the same way. + static CoreAudioUnit *createPlain(const QString &device, int sampleRate, int channels, + QString *error); + + // The same, input only: a microphone opened without the voice unit, for a + // call whose echo is cancelled somewhere else - by EchoCanceller, or not + // at all. Owned by the caller like createPlain(). + static CoreAudioUnit *createPlainCapture(const QString &device, int sampleRate, int channels, + QString *error); + + void release(bool forCapture); + + AudioRing captureRing; + AudioRing playbackRing; + + bool voiceProcessing() const { return m_voiceProcessing; } + +private: + CoreAudioUnit(int sampleRate, int channels, bool voiceProcessing, + bool wantInput, bool wantOutput) + : captureRing(sampleRate * 2), playbackRing(sampleRate * 2), + m_unit(nullptr), m_sampleRate(sampleRate), m_channels(channels), + m_voiceProcessing(voiceProcessing), m_wantInput(wantInput), + m_wantOutput(wantOutput), m_captureRefs(0), m_playbackRefs(0), + m_started(false) + { + } + + ~CoreAudioUnit(); + + bool setUp(const QString &device, QString *error); + void tearDown(); + + static OSStatus inputCallback(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, + const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, + UInt32 inNumberFrames, AudioBufferList *ioData); + static OSStatus renderCallback(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, + const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, + UInt32 inNumberFrames, AudioBufferList *ioData); + + AudioUnit m_unit; + int m_sampleRate; + int m_channels; + bool m_voiceProcessing; + bool m_wantInput; + bool m_wantOutput; + + QString m_device; + + int m_captureRefs; + int m_playbackRefs; + bool m_started; + + // Scratch buffers used only from the audio callbacks, sized once at set + // up time so the real time threads never allocate. + QVector<float> m_inputScratch; + QVector<qint16> m_pcmScratch; + QVector<char> m_inputListStorage; + + // Guards the singleton below and the two refcounts. Plain units are + // reached by one thread only but take it too, which costs nothing. + static QMutex s_mutex; + static CoreAudioUnit *s_voiceInstance; +}; + +QMutex CoreAudioUnit::s_mutex; +CoreAudioUnit *CoreAudioUnit::s_voiceInstance = nullptr; + +CoreAudioUnit::~CoreAudioUnit() +{ + tearDown(); +} + +bool CoreAudioUnit::setUp(const QString &device, QString *error) +{ + AudioComponentDescription desc; + desc.componentType = kAudioUnitType_Output; + desc.componentSubType = m_voiceProcessing ? kAudioUnitSubType_VoiceProcessingIO + : kAudioUnitSubType_HALOutput; + desc.componentManufacturer = kAudioUnitManufacturer_Apple; + desc.componentFlags = 0; + desc.componentFlagsMask = 0; + + AudioComponent comp = AudioComponentFindNext(nullptr, &desc); + if (!comp) + { + if (error) + *error = m_voiceProcessing + ? QStringLiteral("The VoiceProcessingIO audio unit is not available") + : QStringLiteral("The HAL output audio unit is not available"); + return false; + } + + OSStatus err = AudioComponentInstanceNew(comp, &m_unit); + if (err != noErr || !m_unit) + { + if (error) + *error = QString("Could not create the audio unit: %1").arg(osStatusString(err)); + m_unit = nullptr; + return false; + } + + UInt32 one = 1; + UInt32 zero = 0; + + err = AudioUnitSetProperty(m_unit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, + kInputBus, m_wantInput ? &one : &zero, sizeof(one)); + if (err != noErr && m_wantInput) + { + if (error) + *error = QString("Could not enable audio input: %1").arg(osStatusString(err)); + return false; + } + + err = AudioUnitSetProperty(m_unit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, + kOutputBus, m_wantOutput ? &one : &zero, sizeof(one)); + if (err != noErr && m_wantOutput) + { + if (error) + *error = QString("Could not enable audio output: %1").arg(osStatusString(err)); + return false; + } + + // Bind to a specific device when one was asked for. Left alone, the unit + // follows the system default input and output, which is what most users + // want and what keeps working when they unplug a headset mid-call. + // + // With one exception: a HAL unit follows the default OUTPUT device on + // both of its buses, so an input only one has to be pointed at the + // default input by hand or it captures from nothing. + AudioDeviceID devId = kAudioObjectUnknown; + + if (!device.isEmpty() && device != QLatin1String("default")) + { + devId = deviceForUid(device, m_wantInput); + if (devId == kAudioObjectUnknown) + devId = deviceForUid(device, !m_wantInput); + + if (devId == kAudioObjectUnknown) + qWarning() << "CoreAudio: device" << device << "not found - using the system default"; + } + + if (devId == kAudioObjectUnknown && m_wantInput && !m_wantOutput) + { + devId = defaultDevice(true); + if (devId == kAudioObjectUnknown) + { + if (error) + *error = QStringLiteral("There is no default audio input device"); + return false; + } + } + + if (devId != kAudioObjectUnknown) + { + err = AudioUnitSetProperty(m_unit, kAudioOutputUnitProperty_CurrentDevice, + kAudioUnitScope_Global, kOutputBus, &devId, sizeof(devId)); + if (err != noErr) + qWarning() << "CoreAudio: could not bind the audio unit to device" << device + << osStatusString(err) << "- using the system default"; + } + m_device = device; + + UInt32 maxFrames = kMaxFramesPerSlice; + AudioUnitSetProperty(m_unit, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, + 0, &maxFrames, sizeof(maxFrames)); + + // The client side format on both buses. The unit's own converters deal + // with whatever the hardware is really running at, including the sample + // rate, so we can ask for the 48 kHz mono the rest of the call uses. + // Float32 because that is what these units work in natively; going + // through Int16 here would only add a conversion the unit undoes. + AudioStreamBasicDescription fmt; + memset(&fmt, 0, sizeof(fmt)); + fmt.mSampleRate = m_sampleRate; + fmt.mFormatID = kAudioFormatLinearPCM; + fmt.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked; + fmt.mFramesPerPacket = 1; + fmt.mChannelsPerFrame = m_channels; + fmt.mBitsPerChannel = 32; + fmt.mBytesPerFrame = 4 * m_channels; + fmt.mBytesPerPacket = fmt.mBytesPerFrame; + + if (m_wantInput) + { + // Output scope of the input bus is what AudioUnitRender() gives us. + err = AudioUnitSetProperty(m_unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, + kInputBus, &fmt, sizeof(fmt)); + if (err != noErr) + { + if (error) + *error = QString("Could not set the capture format: %1").arg(osStatusString(err)); + return false; + } + } + + if (m_wantOutput) + { + // Input scope of the output bus is what our render callback supplies. + err = AudioUnitSetProperty(m_unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, + kOutputBus, &fmt, sizeof(fmt)); + if (err != noErr) + { + if (error) + *error = QString("Could not set the playback format: %1").arg(osStatusString(err)); + return false; + } + } + + if (m_voiceProcessing) + { + // Make sure the echo cancellation and the rest of the voice + // processing is actually switched on. It is by default, but a bypass + // left set by an earlier instance of the unit would silently cost us + // the whole point of using it. + UInt32 bypass = 0; + AudioUnitSetProperty(m_unit, kAUVoiceIOProperty_BypassVoiceProcessing, + kAudioUnitScope_Global, 0, &bypass, sizeof(bypass)); + + // Leave the unit's automatic gain control off, for the same reason + // EchoCanceller leaves WebRTC's off: a moving gain in front of a + // call that has no level control anywhere else is more trouble than + // it is worth. + UInt32 agc = 0; + AudioUnitSetProperty(m_unit, kAUVoiceIOProperty_VoiceProcessingEnableAGC, + kAudioUnitScope_Global, 0, &agc, sizeof(agc)); + } + + AURenderCallbackStruct cb; + + if (m_wantInput) + { + cb.inputProc = &CoreAudioUnit::inputCallback; + cb.inputProcRefCon = this; + err = AudioUnitSetProperty(m_unit, kAudioOutputUnitProperty_SetInputCallback, + kAudioUnitScope_Global, kInputBus, &cb, sizeof(cb)); + if (err != noErr) + { + if (error) + *error = QString("Could not install the capture callback: %1").arg(osStatusString(err)); + return false; + } + } + + if (m_wantOutput) + { + cb.inputProc = &CoreAudioUnit::renderCallback; + cb.inputProcRefCon = this; + err = AudioUnitSetProperty(m_unit, kAudioUnitProperty_SetRenderCallback, + kAudioUnitScope_Input, kOutputBus, &cb, sizeof(cb)); + if (err != noErr) + { + if (error) + *error = QString("Could not install the playback callback: %1").arg(osStatusString(err)); + return false; + } + } + + m_inputScratch.resize(kMaxFramesPerSlice * m_channels); + m_pcmScratch.resize(kMaxFramesPerSlice * m_channels); + m_inputListStorage.resize(sizeof(AudioBufferList) + sizeof(AudioBuffer)); + + err = AudioUnitInitialize(m_unit); + if (err != noErr) + { + if (error) + *error = QString("Could not initialise the audio unit: %1").arg(osStatusString(err)); + return false; + } + + err = AudioOutputUnitStart(m_unit); + if (err != noErr) + { + if (error) + *error = QString("Could not start the audio unit: %1").arg(osStatusString(err)); + return false; + } + m_started = true; + + qDebug() << "CoreAudio:" << (m_voiceProcessing ? "VoiceProcessingIO" : "HALOutput") + << "started on" << (m_device.isEmpty() ? QStringLiteral("default") : m_device) + << m_sampleRate << "Hz" << m_channels << "ch"; + + return true; +} + +void CoreAudioUnit::tearDown() +{ + if (!m_unit) + return; + + if (m_started) + { + AudioOutputUnitStop(m_unit); + m_started = false; + } + + AudioUnitUninitialize(m_unit); + AudioComponentInstanceDispose(m_unit); + m_unit = nullptr; +} + +OSStatus CoreAudioUnit::inputCallback(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, + const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, + UInt32 inNumberFrames, AudioBufferList *ioData) +{ + Q_UNUSED(ioData) + + CoreAudioUnit *self = (CoreAudioUnit *)inRefCon; + if (!self->m_unit || inNumberFrames == 0 || inNumberFrames > kMaxFramesPerSlice) + return noErr; + + AudioBufferList *list = (AudioBufferList *)self->m_inputListStorage.data(); + list->mNumberBuffers = 1; + list->mBuffers[0].mNumberChannels = self->m_channels; + list->mBuffers[0].mDataByteSize = inNumberFrames * self->m_channels * sizeof(float); + list->mBuffers[0].mData = self->m_inputScratch.data(); + + OSStatus err = AudioUnitRender(self->m_unit, ioActionFlags, inTimeStamp, + inBusNumber, inNumberFrames, list); + if (err != noErr) + return err; + + const int samples = inNumberFrames * self->m_channels; + const float *src = self->m_inputScratch.constData(); + qint16 *dst = self->m_pcmScratch.data(); + + for (int i = 0; i < samples; i++) + { + float v = src[i] * 32767.0f; + if (v > 32767.0f) v = 32767.0f; + else if (v < -32768.0f) v = -32768.0f; + dst[i] = (qint16)v; + } + + // A full ring means the capture loop has stalled; the ring counts the + // overrun and drops what does not fit, which is the right trade for a + // live call. + self->captureRing.write(dst, samples); + + return noErr; +} + +OSStatus CoreAudioUnit::renderCallback(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, + const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, + UInt32 inNumberFrames, AudioBufferList *ioData) +{ + Q_UNUSED(ioActionFlags) + Q_UNUSED(inTimeStamp) + Q_UNUSED(inBusNumber) + + CoreAudioUnit *self = (CoreAudioUnit *)inRefCon; + if (!ioData || ioData->mNumberBuffers < 1) + return noErr; + + const int samples = inNumberFrames * self->m_channels; + if (samples > self->m_pcmScratch.size()) + { + for (UInt32 b = 0; b < ioData->mNumberBuffers; b++) + memset(ioData->mBuffers[b].mData, 0, ioData->mBuffers[b].mDataByteSize); + return noErr; + } + + // Silence for anything the playback loop has not produced yet. Between + // calls, and whenever the peer is quiet, this is all the callback does - + // and a voice unit still wants it, because its echo canceller needs to + // know that nothing is being played. + qint16 *pcm = self->m_pcmScratch.data(); + self->playbackRing.readOrSilence(pcm, samples); + + float *out = (float *)ioData->mBuffers[0].mData; + for (int i = 0; i < samples; i++) + out[i] = pcm[i] / 32768.0f; + + ioData->mBuffers[0].mDataByteSize = samples * sizeof(float); + + // A non-interleaved layout would give us one buffer per channel; the + // format set in setUp() is packed, so anything past the first is not ours + // to fill and is zeroed to be safe. + for (UInt32 b = 1; b < ioData->mNumberBuffers; b++) + memset(ioData->mBuffers[b].mData, 0, ioData->mBuffers[b].mDataByteSize); + + return noErr; +} + +CoreAudioUnit *CoreAudioUnit::acquireVoice(const QString &device, int sampleRate, int channels, + bool forCapture, QString *error) +{ + QMutexLocker locker(&s_mutex); + + if (!s_voiceInstance) + { + CoreAudioUnit *unit = new CoreAudioUnit(sampleRate, channels, true, true, true); + if (!unit->setUp(device, error)) + { + delete unit; + return nullptr; + } + s_voiceInstance = unit; + } + else + { + if (s_voiceInstance->m_sampleRate != sampleRate || s_voiceInstance->m_channels != channels) + { + // Both directions of a call are negotiated together, so this + // would mean two calls at once, which nothing above supports. + if (error) + *error = QStringLiteral("The voice audio unit is already running at another format"); + return nullptr; + } + + if (s_voiceInstance->m_device != device) + { + qWarning() << "CoreAudio: the voice unit is bound to" << s_voiceInstance->m_device + << "so" << device << "cannot also be used - see the note on CoreAudioUnit"; + } + } + + if (forCapture) + { + s_voiceInstance->captureRing.clear(); + s_voiceInstance->m_captureRefs++; + } + else + { + s_voiceInstance->playbackRing.clear(); + s_voiceInstance->m_playbackRefs++; + } + + return s_voiceInstance; +} + +CoreAudioUnit *CoreAudioUnit::createPlain(const QString &device, int sampleRate, int channels, + QString *error) +{ + CoreAudioUnit *unit = new CoreAudioUnit(sampleRate, channels, false, false, true); + if (!unit->setUp(device, error)) + { + delete unit; + return nullptr; + } + + unit->m_playbackRefs = 1; + return unit; +} + +CoreAudioUnit *CoreAudioUnit::createPlainCapture(const QString &device, int sampleRate, int channels, + QString *error) +{ + CoreAudioUnit *unit = new CoreAudioUnit(sampleRate, channels, false, true, false); + if (!unit->setUp(device, error)) + { + delete unit; + return nullptr; + } + + unit->m_captureRefs = 1; + return unit; +} + +void CoreAudioUnit::release(bool forCapture) +{ + QMutexLocker locker(&s_mutex); + + if (forCapture) + { + if (m_captureRefs > 0) + m_captureRefs--; + } + else + { + if (m_playbackRefs > 0) + m_playbackRefs--; + } + + if (m_captureRefs == 0 && m_playbackRefs == 0) + { + if (s_voiceInstance == this) + s_voiceInstance = nullptr; + delete this; + } +} + +// Waits a millisecond. The units fill and drain their rings from threads we +// do not own and have nothing to signal on, so there is nothing to block on +// but the clock. +static void sleepOneMs() +{ + struct timespec ts = { 0, 1000000 }; + nanosleep(&ts, nullptr); +} + +class CoreAudioBackend : public NativeAudioBackend +{ +public: + CoreAudioBackend() + : m_unit(nullptr), m_isCapture(false), m_channels(1), m_platformAec(false) + { + } + + ~CoreAudioBackend() override + { + close(); + } + + QString apiName() const override { return QStringLiteral("coreaudio"); } + + bool openCapture(const QString &device, int sampleRate, int channels, + NativeAudioMode mode, QString *error) override + { + close(); + + // The voice unit is the whole point of this backend, but it is not + // the only thing it can open: a call that cancels its own echo wants + // the microphone as the hardware delivers it, with nothing having + // been subtracted from it first. + if (mode == NativeAudioVoiceCall) + m_unit = CoreAudioUnit::acquireVoice(device, sampleRate, channels, true, error); + else + m_unit = CoreAudioUnit::createPlainCapture(device, sampleRate, channels, error); + + m_isCapture = true; + m_channels = channels; + m_platformAec = (m_unit != nullptr && m_unit->voiceProcessing()); + + return m_unit != nullptr; + } + + bool openPlayback(const QString &device, int sampleRate, int channels, + NativeAudioMode mode, QString *error) override + { + close(); + + if (mode == NativeAudioVoiceCall) + m_unit = CoreAudioUnit::acquireVoice(device, sampleRate, channels, false, error); + else + m_unit = CoreAudioUnit::createPlain(device, sampleRate, channels, error); + + m_isCapture = false; + m_channels = channels; + m_platformAec = false; + + return m_unit != nullptr; + } + + int read(qint16 *buf, int maxSamples, int timeoutMs) override + { + if (!m_unit || !m_isCapture) + return -1; + + int waited = 0; + for (;;) + { + int avail = m_unit->captureRing.available(); + if (avail > 0) + { + int n = avail < maxSamples ? avail : maxSamples; + return m_unit->captureRing.read(buf, n); + } + + if (timeoutMs >= 0 && waited >= timeoutMs) + return 0; + + sleepOneMs(); + waited++; + } + } + + int write(const qint16 *buf, int nsamples, int timeoutMs) override + { + if (!m_unit || m_isCapture) + return -1; + + int done = 0; + int waited = 0; + + while (done < nsamples) + { + done += m_unit->playbackRing.write(buf + done, nsamples - done); + + if (done >= nsamples) + break; + + if (timeoutMs >= 0 && waited >= timeoutMs) + break; + + sleepOneMs(); + waited++; + } + + return done; + } + + void close() override + { + if (m_unit) + { + m_unit->release(m_isCapture); + m_unit = nullptr; + } + m_platformAec = false; + } + + // The whole reason this backend exists. The voice unit's canceller is + // unconditional once the unit is running and not bypassed. + bool hasPlatformEchoCancellation() const override { return m_platformAec; } + + QString formatDescription() const override + { + if (!m_unit) + return QString(); + + return QString("CoreAudio %1 %2, %3 ch%4") + .arg(m_isCapture ? "in" : "out") + .arg(m_unit->voiceProcessing() ? "VoiceProcessingIO" : "HALOutput") + .arg(m_channels) + .arg(m_platformAec ? ", platform AEC" : ""); + } + +private: + CoreAudioUnit *m_unit; + bool m_isCapture; + int m_channels; + bool m_platformAec; +}; + +NativeAudioBackend *pica_create_coreaudio_backend() +{ + return new CoreAudioBackend(); +} + +QList<MediaDeviceInfo> pica_enumerate_coreaudio(enum MediaDeviceStreamDirection dir) +{ + QList<MediaDeviceInfo> result; + int index = 0; + + // The system default first, under the same "default" name every other + // driver in this codebase uses for it. On macOS it is also the only + // selection that lets the voice unit follow the user switching headsets + // during a call. + { + MediaDeviceInfo d; + d.device = QStringLiteral("default"); + d.humanReadable = (dir == PLAYBACK) + ? QObject::tr("System default output") + : QObject::tr("System default input"); + d.index = index++; + result << d; + } + + const bool wantInput = (dir != PLAYBACK); + QVector<AudioDeviceID> devices = allDevices(); + + for (int i = 0; i < devices.size(); i++) + { + if (deviceChannelCount(devices[i], wantInput) <= 0) + continue; + + QString uid = deviceUid(devices[i]); + if (uid.isEmpty()) + continue; + + MediaDeviceInfo d; + d.device = uid; + d.humanReadable = deviceName(devices[i]); + if (d.humanReadable.isEmpty()) + d.humanReadable = uid; + d.index = index++; + + result << d; + } + + return result; +} + +#endif // Q_OS_MACOS diff --git a/pica-client/nativeaudio_wasapi.cpp b/pica-client/nativeaudio_wasapi.cpp new file mode 100644 index 0000000..c0f5130 --- /dev/null +++ b/pica-client/nativeaudio_wasapi.cpp @@ -0,0 +1,976 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#include "nativeaudio.h" + +#ifdef Q_OS_WIN + +#include <QDebug> +#include <QObject> +#include <QVector> +#include <cstring> + +// INITGUID has to come first so the CLSIDs and IIDs used below get defined +// here rather than expecting a separate GUID library at link time. +#define INITGUID +#include <initguid.h> + +#include <windows.h> +#include <objbase.h> +#include <mmreg.h> +#include <mmdeviceapi.h> +#include <audioclient.h> +#include <functiondiscoverykeys_devpkey.h> + +extern "C" { +#include <libavutil/channel_layout.h> +#include <libavutil/mathematics.h> +#include <libavutil/samplefmt.h> +#include <libswresample/swresample.h> +} + +#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 24, 100) +# define NA_HAVE_CH_LAYOUT 1 +#else +# define NA_HAVE_CH_LAYOUT 0 +#endif + +// How much of a buffer to ask WASAPI for. Shared mode rounds this up to the +// engine period anyway; 40 ms is two of our 20 ms call packets, enough that a +// scheduling hiccup does not turn into a glitch without adding audible delay. +static const REFERENCE_TIME kBufferDuration = 400000; // in 100ns units + +static QString hrString(HRESULT hr) +{ + return QString("0x%1").arg((quint32)hr, 8, 16, QLatin1Char('0')); +} + +static QString wideToQString(LPCWSTR s) +{ + return s ? QString::fromWCharArray(s) : QString(); +} + +// Recovers the WAVE_FORMAT_* tag from a WAVEFORMATEXTENSIBLE subformat GUID. +// +// The subformats a shared mode mix format uses are the generic ones derived +// from a wave format tag: the tag sits in Data1 and everything after it is a +// fixed suffix. Reading it out that way rather than comparing against +// KSDATAFORMAT_SUBTYPE_PCM and KSDATAFORMAT_SUBTYPE_IEEE_FLOAT is deliberate - +// mingw-w64 declares those two but does not define them, the definitions +// being in ksuser, and INITGUID does not help because they are spelled with +// DEFINE_GUIDSTRUCT rather than DEFINE_GUID. Not worth a link dependency for +// two constants whose value is this predictable. +// +// Returns false for a subformat that is not one of the generic family, which +// is a codec (AC-3 and such) rather than something we could hand PCM to. +static bool ksSubFormatTag(const GUID *g, WORD *tag) +{ + static const unsigned char suffix[8] = + { 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 }; + + if (g->Data2 != 0x0000 || g->Data3 != 0x0010) + return false; + + if (memcmp(g->Data4, suffix, sizeof(suffix)) != 0) + return false; + + if (g->Data1 > 0xFFFF) + return false; + + *tag = (WORD)g->Data1; + return true; +} + +// Works out which AVSampleFormat a WASAPI mix format corresponds to. +// Shared mode engines are float32 in practice, but integer formats turn up on +// some drivers and cost nothing to support. Returns AV_SAMPLE_FMT_NONE for +// anything we cannot describe, which sends the caller back to reporting a +// plain unsupported-format failure. +static AVSampleFormat waveFormatToAv(const WAVEFORMATEX *wfx) +{ + WORD tag = wfx->wFormatTag; + + if (tag == WAVE_FORMAT_EXTENSIBLE && wfx->cbSize >= 22) + { + const WAVEFORMATEXTENSIBLE *ext = (const WAVEFORMATEXTENSIBLE *)wfx; + if (!ksSubFormatTag(&ext->SubFormat, &tag)) + return AV_SAMPLE_FMT_NONE; + } + + if (tag == WAVE_FORMAT_IEEE_FLOAT) + return wfx->wBitsPerSample == 64 ? AV_SAMPLE_FMT_DBL : AV_SAMPLE_FMT_FLT; + + if (tag == WAVE_FORMAT_PCM) + { + switch (wfx->wBitsPerSample) + { + case 16: return AV_SAMPLE_FMT_S16; + case 32: return AV_SAMPLE_FMT_S32; + default: return AV_SAMPLE_FMT_NONE; + } + } + + return AV_SAMPLE_FMT_NONE; +} + +static SwrContext *makeResampler(AVSampleFormat inFmt, int inRate, int inCh, + AVSampleFormat outFmt, int outRate, int outCh) +{ + SwrContext *swr = nullptr; + +#if NA_HAVE_CH_LAYOUT + AVChannelLayout inLayout, outLayout; + av_channel_layout_default(&inLayout, inCh); + av_channel_layout_default(&outLayout, outCh); + int ret = swr_alloc_set_opts2(&swr, &outLayout, outFmt, outRate, + &inLayout, inFmt, inRate, 0, nullptr); + av_channel_layout_uninit(&inLayout); + av_channel_layout_uninit(&outLayout); + if (ret < 0) + return nullptr; +#else + swr = swr_alloc_set_opts(nullptr, + av_get_default_channel_layout(outCh), outFmt, outRate, + av_get_default_channel_layout(inCh), inFmt, inRate, + 0, nullptr); + if (!swr) + return nullptr; +#endif + + if (swr_init(swr) < 0) + { + swr_free(&swr); + return nullptr; + } + + return swr; +} + +class WasapiBackend : public NativeAudioBackend +{ +public: + WasapiBackend() + : m_comInitialized(false), m_client(nullptr), m_capture(nullptr), + m_render(nullptr), m_event(nullptr), m_mixFormat(nullptr), + m_isCapture(false), m_sampleRate(48000), m_channels(1), + m_devSampleRate(48000), m_devChannels(1), m_devFormat(AV_SAMPLE_FMT_S16), + m_devBytesPerFrame(2), m_swr(nullptr), m_bufferFrames(0), + m_platformAec(false), m_started(false), m_spillOffset(0) + { + } + + ~WasapiBackend() override + { + close(); + } + + QString apiName() const override { return QStringLiteral("wasapi"); } + + bool openCapture(const QString &device, int sampleRate, int channels, + NativeAudioMode mode, QString *error) override + { + return open(device, sampleRate, channels, true, mode, error); + } + + bool openPlayback(const QString &device, int sampleRate, int channels, + NativeAudioMode mode, QString *error) override + { + return open(device, sampleRate, channels, false, mode, error); + } + + int read(qint16 *buf, int maxSamples, int timeoutMs) override; + int write(const qint16 *buf, int nsamples, int timeoutMs) override; + void close() override; + + bool hasPlatformEchoCancellation() const override { return m_platformAec; } + + QString formatDescription() const override + { + if (!m_client) + return QString(); + + return QString("WASAPI %1 %2 Hz %3 ch %4 -> %5 Hz %6 ch s16, buffer %7 fr%8") + .arg(m_isCapture ? "in" : "out") + .arg(m_devSampleRate).arg(m_devChannels) + .arg(QLatin1String(av_get_sample_fmt_name(m_devFormat))) + .arg(m_sampleRate).arg(m_channels) + .arg(m_bufferFrames) + .arg(m_platformAec ? ", platform AEC" : ""); + } + +private: + bool open(const QString &device, int sampleRate, int channels, bool isCapture, + NativeAudioMode mode, QString *error); + bool initCom(); + IMMDevice *resolveDevice(const QString &device, bool isCapture, NativeAudioMode mode, QString *error); + void requestCommunicationsCategory(); + int appendConverted(const BYTE *deviceData, int deviceFrames, bool silent, + qint16 *buf, int maxSamples, int written); + + bool m_comInitialized; + IAudioClient *m_client; + IAudioCaptureClient *m_capture; + IAudioRenderClient *m_render; + HANDLE m_event; + WAVEFORMATEX *m_mixFormat; + + bool m_isCapture; + + // What our own pipeline speaks: interleaved 16 bit, m_channels wide. + int m_sampleRate; + int m_channels; + + // What the stream was actually opened with. Equal to the above whenever + // WASAPI accepted our format directly, which is the normal case; when it + // did not, m_swr bridges the two. + int m_devSampleRate; + int m_devChannels; + AVSampleFormat m_devFormat; + int m_devBytesPerFrame; + SwrContext *m_swr; + + UINT32 m_bufferFrames; + bool m_platformAec; + bool m_started; + + // WASAPI hands capture audio over one packet at a time and will not let a + // packet be released partially, so whatever the caller did not have room + // for is kept here until the next read(). + QVector<qint16> m_spill; + int m_spillOffset; + + // Scratch space for format conversion, kept between calls so the audio + // loop does not allocate. + QVector<qint16> m_convIn; + QVector<quint8> m_convOut; +}; + +bool WasapiBackend::initCom() +{ + // Every thread that touches COM has to initialise it, and Capture() and + // Play() each run on their own QThread. MULTITHREADED is what the WASAPI + // samples use and what suits a worker thread with no message loop. + HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); + if (hr == RPC_E_CHANGED_MODE) + { + // Somebody else already put this thread in a single threaded + // apartment. That is still usable, but it is not ours to undo. + return true; + } + if (FAILED(hr)) + return false; + + m_comInitialized = true; + return true; +} + +IMMDevice *WasapiBackend::resolveDevice(const QString &device, bool isCapture, + NativeAudioMode mode, QString *error) +{ + IMMDeviceEnumerator *devEnum = nullptr; + HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, + IID_IMMDeviceEnumerator, (void **)&devEnum); + if (FAILED(hr) || !devEnum) + { + if (error) + *error = QString("Could not create the audio endpoint enumerator: %1").arg(hrString(hr)); + return nullptr; + } + + IMMDevice *dev = nullptr; + if (device.isEmpty() || device == QLatin1String("default")) + { + // eCommunications rather than eConsole for a call: this is the + // endpoint the user nominated for calls, and asking for it by that + // role is part of what tells Windows to treat the stream as voice. + // A ringtone is not a call and belongs on the console endpoint, so + // that it is heard on the speakers rather than in a headset the user + // is not wearing yet. + // + // Both call modes take the communications endpoint. Cancelling the + // echo ourselves is a reason not to ask for the endpoint's voice + // processing, not a reason to move the call to a different device. + const ERole role = (mode != NativeAudioPlain) ? eCommunications : eConsole; + hr = devEnum->GetDefaultAudioEndpoint(isCapture ? eCapture : eRender, role, &dev); + } + else + { + hr = devEnum->GetDevice((LPCWSTR)device.utf16(), &dev); + } + + devEnum->Release(); + + if (FAILED(hr) || !dev) + { + if (error) + *error = QString("Could not open audio endpoint '%1': %2").arg(device, hrString(hr)); + return nullptr; + } + + return dev; +} + +void WasapiBackend::requestCommunicationsCategory() +{ +#ifdef __IAudioClient2_INTERFACE_DEFINED__ + // This is the part that buys us the platform's echo cancellation. Marking + // the stream AudioCategory_Communications before Initialize() puts it + // through the communications signal processing chain, which is where the + // AEC, noise suppression and gain control that Windows (or the endpoint's + // own APO) provides live. Without it we get the raw capture stream and + // have to cancel the echo ourselves. + // + // Whether an AEC is actually in that chain depends on the driver, so this + // is a request, not a guarantee - see hasPlatformEchoCancellation(). + IAudioClient2 *client2 = nullptr; + if (SUCCEEDED(m_client->QueryInterface(IID_IAudioClient2, (void **)&client2)) && client2) + { + AudioClientProperties props; + // ZeroMemory also covers Options, which only exists from the Windows + // 8.1 SDK on and whose "none" value is zero in every version that has + // it - so this compiles against either header. + ZeroMemory(&props, sizeof(props)); + props.cbSize = sizeof(props); + props.bIsOffload = FALSE; + props.eCategory = AudioCategory_Communications; + + HRESULT phr = client2->SetClientProperties(&props); + if (SUCCEEDED(phr)) + m_platformAec = true; + else + qWarning() << "WASAPI: SetClientProperties failed" << hrString(phr) + << "- no platform echo cancellation on this stream"; + + client2->Release(); + } + else + { + qWarning() << "WASAPI: IAudioClient2 not available - no platform echo cancellation on this stream"; + } +#else + qWarning() << "WASAPI: built without IAudioClient2 - no platform echo cancellation on this stream"; +#endif +} + +bool WasapiBackend::open(const QString &device, int sampleRate, int channels, bool isCapture, + NativeAudioMode mode, QString *error) +{ + close(); + + if (!initCom()) + { + if (error) + *error = QStringLiteral("Could not initialise COM on the audio thread"); + return false; + } + + m_isCapture = isCapture; + m_sampleRate = sampleRate; + m_channels = channels; + + IMMDevice *dev = resolveDevice(device, isCapture, mode, error); + if (!dev) + { + close(); + return false; + } + + HRESULT hr = dev->Activate(IID_IAudioClient, CLSCTX_ALL, nullptr, (void **)&m_client); + dev->Release(); + if (FAILED(hr) || !m_client) + { + if (error) + *error = QString("Could not activate the audio client: %1").arg(hrString(hr)); + close(); + return false; + } + + // Capture only, deliberately. + // + // On Windows the echo canceller lives in the capture endpoint's + // processing chain and takes its reference from the render endpoint + // itself, not from any particular render stream - so a render stream + // gains nothing from the communications category, while still paying for + // whatever the endpoint's communications APO does to it. Which endpoint a + // call plays to is a separate question, settled by the eCommunications + // role in resolveDevice(). + // + // Asking for it on render as well is what made the settings dialog's + // microphone test come out chopped while the ring test, which opens a + // plain stream, was clean. + // + // NativeAudioVoiceCallRaw is a call that cancels its own echo, so it does + // not want the endpoint's processing either - this is the one place where + // it differs from NativeAudioVoiceCall. + if (mode == NativeAudioVoiceCall && isCapture) + requestCommunicationsCategory(); + + // Always run on the engine's own mix format and convert on this side, + // rather than asking WASAPI to hand us mono 16 bit through + // AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM. + // + // The flag is documented to insert a channel matrixer and a rate + // converter, and Initialize() reports success when it is set - but there + // is no way afterwards to ask what format the stream really ended up in, + // so a driver that quietly ignores it leaves us reading a stereo buffer + // as if it were mono. That takes half the samples of every packet, + // discards the rest with ReleaseBuffer(), and renders interleaved L,R + // pairs as consecutive mono samples: audio that is both chopped and + // running at half speed, which is exactly what the microphone test did. + // + // The mix format is the one format shared mode is guaranteed to accept, + // GetMixFormat() tells us exactly what it is, and libswresample is + // already linked and already doing this work on every other platform. + // One code path, no trust required. + hr = m_client->GetMixFormat(&m_mixFormat); + if (FAILED(hr) || !m_mixFormat) + { + if (error) + *error = QString("Could not query the audio engine mix format: %1").arg(hrString(hr)); + close(); + return false; + } + + m_devFormat = waveFormatToAv(m_mixFormat); + if (m_devFormat == AV_SAMPLE_FMT_NONE) + { + if (error) + *error = QString("The audio engine mix format is not one we can convert (tag %1, %2 bits)") + .arg(m_mixFormat->wFormatTag).arg(m_mixFormat->wBitsPerSample); + close(); + return false; + } + + m_devSampleRate = (int)m_mixFormat->nSamplesPerSec; + m_devChannels = (int)m_mixFormat->nChannels; + m_devBytesPerFrame = (int)m_mixFormat->nBlockAlign; + + hr = m_client->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, + kBufferDuration, 0, m_mixFormat, nullptr); + if (FAILED(hr)) + { + if (error) + *error = QString("Could not initialise the audio client: %1").arg(hrString(hr)); + close(); + return false; + } + + if (isCapture) + m_swr = makeResampler(m_devFormat, m_devSampleRate, m_devChannels, + AV_SAMPLE_FMT_S16, m_sampleRate, m_channels); + else + m_swr = makeResampler(AV_SAMPLE_FMT_S16, m_sampleRate, m_channels, + m_devFormat, m_devSampleRate, m_devChannels); + + if (!m_swr) + { + if (error) + *error = QStringLiteral("Could not set up the audio format converter"); + close(); + return false; + } + + m_event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!m_event) + { + if (error) + *error = QStringLiteral("Could not create the audio event"); + close(); + return false; + } + + hr = m_client->SetEventHandle(m_event); + if (FAILED(hr)) + { + if (error) + *error = QString("Could not attach the audio event: %1").arg(hrString(hr)); + close(); + return false; + } + + hr = m_client->GetBufferSize(&m_bufferFrames); + if (FAILED(hr)) + { + if (error) + *error = QString("Could not query the audio buffer size: %1").arg(hrString(hr)); + close(); + return false; + } + + if (isCapture) + hr = m_client->GetService(IID_IAudioCaptureClient, (void **)&m_capture); + else + hr = m_client->GetService(IID_IAudioRenderClient, (void **)&m_render); + + if (FAILED(hr)) + { + if (error) + *error = QString("Could not get the audio %1 service: %2") + .arg(isCapture ? "capture" : "render", hrString(hr)); + close(); + return false; + } + + // Deliberately not pre-filling a render stream with silence here. It + // would buy nothing - the engine plays silence for an empty buffer by + // itself, and for a call the jitter buffer's own preroll has emptied it + // again long before the first packet arrives - while costing a whole + // buffer of added latency on every stream, and making the first write of + // a tone wait for a buffer of silence to drain before anything is heard. + + hr = m_client->Start(); + if (FAILED(hr)) + { + if (error) + *error = QString("Could not start the audio stream: %1").arg(hrString(hr)); + close(); + return false; + } + m_started = true; + + qDebug() << "WASAPI:" << (isCapture ? "capture" : "playback") << "on" << device + << "- engine" << m_devSampleRate << "Hz" << m_devChannels << "ch" + << av_get_sample_fmt_name(m_devFormat) + << "<->" << m_sampleRate << "Hz" << m_channels << "ch s16" + << ", buffer" << m_bufferFrames << "frames" + << (m_platformAec ? ", platform echo cancellation requested" : ""); + + return true; +} + +// Turns one captured packet into our own format and distributes it between +// the caller's buffer and the spill buffer. Returns the new written count. +int WasapiBackend::appendConverted(const BYTE *deviceData, int deviceFrames, bool silent, + qint16 *buf, int maxSamples, int written) +{ + const qint16 *src = nullptr; + int samples = 0; + + if (!m_swr) + { + samples = deviceFrames * m_channels; + if (silent) + { + m_convIn.resize(samples); + memset(m_convIn.data(), 0, samples * sizeof(qint16)); + src = m_convIn.constData(); + } + else + { + src = (const qint16 *)deviceData; + } + } + else + { + // Worst case output length, allowing for whatever the resampler is + // still holding on to. + int outFrames = (int)av_rescale_rnd(swr_get_delay(m_swr, m_devSampleRate) + deviceFrames, + m_sampleRate, m_devSampleRate, AV_ROUND_UP); + if (outFrames <= 0) + return written; + + m_convIn.resize(outFrames * m_channels); + + QVector<quint8> silence; + const quint8 *in = deviceData; + if (silent) + { + silence.resize(deviceFrames * m_devBytesPerFrame); + memset(silence.data(), 0, silence.size()); + in = silence.constData(); + } + + uint8_t *outPlanes[1] = { (uint8_t *)m_convIn.data() }; + const uint8_t *inPlanes[1] = { (const uint8_t *)in }; + + int got = swr_convert(m_swr, outPlanes, outFrames, inPlanes, deviceFrames); + if (got <= 0) + return written; + + samples = got * m_channels; + src = m_convIn.constData(); + } + + const int room = maxSamples - written; + const int n = samples < room ? samples : room; + + if (n > 0) + memcpy(buf + written, src, n * sizeof(qint16)); + + if (samples > n) + { + int extra = samples - n; + int base = m_spill.size(); + m_spill.resize(base + extra); + memcpy(m_spill.data() + base, src + n, extra * sizeof(qint16)); + } + + return written + n; +} + +int WasapiBackend::read(qint16 *buf, int maxSamples, int timeoutMs) +{ + if (!m_capture || !m_event) + return -1; + + int written = 0; + + // Anything a previous read() could not fit goes out first. + if (m_spillOffset < m_spill.size()) + { + int avail = m_spill.size() - m_spillOffset; + int n = avail < maxSamples ? avail : maxSamples; + memcpy(buf, m_spill.constData() + m_spillOffset, n * sizeof(qint16)); + m_spillOffset += n; + written += n; + + if (m_spillOffset >= m_spill.size()) + { + m_spill.clear(); + m_spillOffset = 0; + } + + if (written >= maxSamples) + return written; + } + + DWORD wait = WaitForSingleObject(m_event, timeoutMs < 0 ? INFINITE : (DWORD)timeoutMs); + if (wait == WAIT_TIMEOUT) + return written; + if (wait != WAIT_OBJECT_0) + return written > 0 ? written : -1; + + for (;;) + { + UINT32 packetFrames = 0; + HRESULT hr = m_capture->GetNextPacketSize(&packetFrames); + if (FAILED(hr)) + return written > 0 ? written : -1; + if (packetFrames == 0) + break; + + BYTE *data = nullptr; + UINT32 frames = 0; + DWORD flags = 0; + hr = m_capture->GetBuffer(&data, &frames, &flags, nullptr, nullptr); + if (hr == AUDCLNT_S_BUFFER_EMPTY) + { + // A success code, so the buffer is still ours to give back even + // though it holds nothing. Walking away without releasing it + // makes every later GetBuffer fail with AUDCLNT_E_OUT_OF_ORDER, + // which would kill capture for the rest of the call. + m_capture->ReleaseBuffer(0); + break; + } + if (FAILED(hr)) + return written > 0 ? written : -1; + + written = appendConverted(data, (int)frames, (flags & AUDCLNT_BUFFERFLAGS_SILENT) != 0, + buf, maxSamples, written); + + // The packet has to be released whole, which is why anything that did + // not fit went to the spill buffer rather than being left behind. + m_capture->ReleaseBuffer(frames); + + if (written >= maxSamples) + break; + } + + return written; +} + +int WasapiBackend::write(const qint16 *buf, int nsamples, int timeoutMs) +{ + if (!m_render || !m_client || !m_event) + return -1; + + const BYTE *deviceBytes = nullptr; + int framesWanted = 0; + + if (!m_swr) + { + deviceBytes = (const BYTE *)buf; + framesWanted = nsamples / m_channels; + } + else + { + int inFrames = nsamples / m_channels; + int outFrames = (int)av_rescale_rnd(swr_get_delay(m_swr, m_sampleRate) + inFrames, + m_devSampleRate, m_sampleRate, AV_ROUND_UP); + if (outFrames <= 0) + return nsamples; + + m_convOut.resize(outFrames * m_devBytesPerFrame); + + uint8_t *outPlanes[1] = { (uint8_t *)m_convOut.data() }; + const uint8_t *inPlanes[1] = { (const uint8_t *)buf }; + + int got = swr_convert(m_swr, outPlanes, outFrames, inPlanes, inFrames); + if (got <= 0) + return nsamples; + + deviceBytes = (const BYTE *)m_convOut.constData(); + framesWanted = got; + } + + int framesDone = 0; + + // Deadline rather than a per-wait timeout. One WaitForSingleObject() + // returns after a single device period, which is smaller than the block + // the caller hands us, so filling a block normally takes several waits - + // an earlier version of this allowed only one and silently dropped the + // remainder of every block, which sounds like the tone being chopped up. + // Subtracting tick counts is wrap safe as long as it is done in DWORD. + const DWORD start = GetTickCount(); + + while (framesDone < framesWanted) + { + UINT32 padding = 0; + HRESULT hr = m_client->GetCurrentPadding(&padding); + if (FAILED(hr)) + return framesDone > 0 ? nsamples : -1; + + UINT32 freeFrames = m_bufferFrames > padding ? m_bufferFrames - padding : 0; + if (freeFrames == 0) + { + DWORD remaining; + + if (timeoutMs < 0) + { + remaining = INFINITE; + } + else + { + DWORD elapsed = GetTickCount() - start; + if (elapsed >= (DWORD)timeoutMs) + break; + remaining = (DWORD)timeoutMs - elapsed; + } + + DWORD wait = WaitForSingleObject(m_event, remaining); + if (wait == WAIT_TIMEOUT) + break; + if (wait != WAIT_OBJECT_0) + return framesDone > 0 ? nsamples : -1; + continue; + } + + UINT32 chunk = (UINT32)(framesWanted - framesDone); + if (chunk > freeFrames) + chunk = freeFrames; + + BYTE *data = nullptr; + hr = m_render->GetBuffer(chunk, &data); + if (FAILED(hr) || !data) + return framesDone > 0 ? nsamples : -1; + + memcpy(data, deviceBytes + (size_t)framesDone * m_devBytesPerFrame, + (size_t)chunk * m_devBytesPerFrame); + m_render->ReleaseBuffer(chunk, 0); + + framesDone += (int)chunk; + } + + // Report against what the caller gave us, not against the post-conversion + // frame count, since a short write here is a dropped tail either way. + if (framesDone >= framesWanted) + return nsamples; + + return (int)((qint64)nsamples * framesDone / (framesWanted > 0 ? framesWanted : 1)); +} + +void WasapiBackend::close() +{ + if (m_client && m_started) + { + // Stop() cuts off whatever is still in the buffer, which for a tone + // means losing its last few tens of milliseconds. Give the device a + // chance to play out what it has first - bounded, because a stream + // that has stopped advancing must not hold up the call teardown. + if (m_render && m_event) + { + const DWORD start = GetTickCount(); + const DWORD limit = 300; + + for (;;) + { + UINT32 padding = 0; + if (FAILED(m_client->GetCurrentPadding(&padding)) || padding == 0) + break; + + DWORD elapsed = GetTickCount() - start; + if (elapsed >= limit) + break; + + if (WaitForSingleObject(m_event, limit - elapsed) != WAIT_OBJECT_0) + break; + } + } + + m_client->Stop(); + m_started = false; + } + + if (m_capture) + { + m_capture->Release(); + m_capture = nullptr; + } + if (m_render) + { + m_render->Release(); + m_render = nullptr; + } + if (m_client) + { + m_client->Release(); + m_client = nullptr; + } + if (m_event) + { + CloseHandle(m_event); + m_event = nullptr; + } + if (m_mixFormat) + { + CoTaskMemFree(m_mixFormat); + m_mixFormat = nullptr; + } + if (m_swr) + { + swr_free(&m_swr); + m_swr = nullptr; + } + + m_spill.clear(); + m_spillOffset = 0; + m_convIn.clear(); + m_convOut.clear(); + m_platformAec = false; + + if (m_comInitialized) + { + CoUninitialize(); + m_comInitialized = false; + } +} + +NativeAudioBackend *pica_create_wasapi_backend() +{ + return new WasapiBackend(); +} + +QList<MediaDeviceInfo> pica_enumerate_wasapi(enum MediaDeviceStreamDirection dir) +{ + QList<MediaDeviceInfo> result; + + // The settings dialog calls this from the GUI thread, which Qt has + // already put into an apartment; the extra reference is still ours to + // balance, hence the matching CoUninitialize() below. + bool didInit = false; + HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); + if (SUCCEEDED(hr)) + didInit = true; + else if (hr != RPC_E_CHANGED_MODE) + return result; + + IMMDeviceEnumerator *devEnum = nullptr; + hr = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, + IID_IMMDeviceEnumerator, (void **)&devEnum); + if (FAILED(hr) || !devEnum) + { + qWarning() << "WASAPI: could not create the endpoint enumerator" << hrString(hr); + if (didInit) + CoUninitialize(); + return result; + } + + int index = 0; + + // The system default first, under the same "default" name every other + // driver in this codebase uses for it. + // + // Deliberately not named after a particular endpoint role. The same list + // fills the call devices and the ring device, and "default" resolves to a + // different endpoint for each: a call takes the communications one, a + // ringtone the console one, so that the bell is heard on the speakers + // rather than in a headset nobody is wearing yet. See resolveDevice(). + { + MediaDeviceInfo d; + d.device = QStringLiteral("default"); + d.humanReadable = (dir == PLAYBACK) + ? QObject::tr("System default output") + : QObject::tr("System default input"); + d.index = index++; + result << d; + } + + IMMDeviceCollection *collection = nullptr; + hr = devEnum->EnumAudioEndpoints(dir == PLAYBACK ? eRender : eCapture, + DEVICE_STATE_ACTIVE, &collection); + if (SUCCEEDED(hr) && collection) + { + UINT count = 0; + collection->GetCount(&count); + + for (UINT i = 0; i < count; i++) + { + IMMDevice *dev = nullptr; + if (FAILED(collection->Item(i, &dev)) || !dev) + continue; + + LPWSTR id = nullptr; + if (SUCCEEDED(dev->GetId(&id)) && id) + { + MediaDeviceInfo d; + d.device = wideToQString(id); + d.humanReadable = d.device; + + IPropertyStore *props = nullptr; + if (SUCCEEDED(dev->OpenPropertyStore(STGM_READ, &props)) && props) + { + PROPVARIANT name; + PropVariantInit(&name); + if (SUCCEEDED(props->GetValue(PKEY_Device_FriendlyName, &name)) && + name.vt == VT_LPWSTR) + { + d.humanReadable = wideToQString(name.pwszVal); + } + PropVariantClear(&name); + props->Release(); + } + + d.index = index++; + result << d; + + CoTaskMemFree(id); + } + + dev->Release(); + } + + collection->Release(); + } + + devEnum->Release(); + + if (didInit) + CoUninitialize(); + + return result; +} + +#endif // Q_OS_WIN diff --git a/pica-client/nodes.cpp b/pica-client/nodes.cpp index 048d2cc..cf6cadb 100644 --- a/pica-client/nodes.cpp +++ b/pica-client/nodes.cpp @@ -16,9 +16,9 @@ */ #include "nodes.h" -Nodes::Nodes(QString storage) +Nodes::Nodes(QString storage, QString connectionName) { - dbconn = QSqlDatabase::database(); + dbconn = connectionName.isEmpty() ? QSqlDatabase::database() : QSqlDatabase::database(connectionName); dbconn.setDatabaseName(storage); if (!dbconn.open()) @@ -31,7 +31,7 @@ Nodes::Nodes(QString storage) void Nodes::Add(NodeRecord &n) { - QSqlQuery query; + QSqlQuery query(dbconn); query.prepare("insert into nodes (address, port, last_active, inactive_count) values (:addr, :port, strftime('%s','now'), 0)"); query.bindValue(":addr", n.address); @@ -43,7 +43,7 @@ void Nodes::Add(NodeRecord &n) void Nodes::Delete(NodeRecord &n) { - QSqlQuery query; + QSqlQuery query(dbconn); query.prepare("delete from nodes where address = :addr and port = :port"); query.bindValue(":addr", n.address); @@ -57,7 +57,7 @@ QList<Nodes::NodeRecord> Nodes::GetNodes() { QList<NodeRecord> L; NodeRecord r; - QSqlQuery query; + QSqlQuery query(dbconn); query.setForwardOnly(true); query.exec("select address, port from nodes order by inactive_count asc, last_active desc"); @@ -79,7 +79,7 @@ QList<Nodes::NodeRecord> Nodes::GetNodes() void Nodes::MakeClean() { - QSqlQuery query; + QSqlQuery query(dbconn); quint32 count = 0; query.exec("select count(*) from nodes"); @@ -115,7 +115,7 @@ void Nodes::MakeClean() void Nodes::UpdateStatus(NodeRecord &n, bool alive) { - QSqlQuery query; + QSqlQuery query(dbconn); if (alive) query.prepare("update nodes set last_active = strftime('%s','now'), inactive_count = 0 where address = :addr and port = :port"); diff --git a/pica-client/nodes.h b/pica-client/nodes.h index 63b09a8..2cd2c1e 100644 --- a/pica-client/nodes.h +++ b/pica-client/nodes.h @@ -31,7 +31,12 @@ public: quint16 port; }; - Nodes(QString storage); + // connectionName selects which QSqlDatabase connection to use (see + // QSqlDatabase::database()). A connection can only be used from the + // thread that created it, so callers running on a thread other than + // the GUI thread must pass the name of a connection opened on their + // own thread. Empty (the default) uses Qt's default connection. + Nodes(QString storage, QString connectionName = QString()); void Add(NodeRecord &n); void Delete(NodeRecord &n); QList<NodeRecord> GetNodes(); diff --git a/pica-client/nodethread.cpp b/pica-client/nodethread.cpp deleted file mode 100644 index bf93e83..0000000 --- a/pica-client/nodethread.cpp +++ /dev/null @@ -1,118 +0,0 @@ -#include "nodethread.h" -#include "mainwindow.h" -#include "../PICA_proto.h" -#include "globals.h" -#include "dhparam.h" - -QMutex NodeThread::finished_mutex; - -NodeThread::NodeThread(Nodes::NodeRecord &addr, bool *completed, PICA_acc *acc, PICA_c2n **pica_conn, QMutex *wm) : - QThread(0) -{ - node_addr = addr; - finished_flag = completed; - user_account = acc; - connection = pica_conn; - write_mutex = wm; - exit = 0; - start(); -} - -void NodeThread::run() -{ - int ret; - exit = 0; - - /*ret = PICA_new_c2n(node_addr.address.toUtf8().constData(), - node_addr.port, - user_account.CA_file.toUtf8().constData(), - user_account.cert_file.toUtf8().constData(), - user_account.pkey_file.toUtf8().constData(), - DHParam::GetDHParamFilename().toUtf8().constData(), - AskPassword::ask_password_cb, - &ci);*/ - ret = PICA_new_c2n(user_account, node_addr.address.toUtf8().constData(), node_addr.port, &ci); - - switch(ret) - { - case PICA_OK: - - emit NodeStatusChanged(node_addr.address, node_addr.port, true); - - finished_mutex.lock(); - if (*finished_flag) - { - PICA_close_c2n(ci); - exit = 1; - } - else - { - *finished_flag = true; - *connection = ci; - emit ConnectedToNode(node_addr.address, node_addr.port, this); - } - finished_mutex.unlock(); - - - - break; - - case PICA_ERRSOCK: - case PICA_ERRDNSRESOLVE: - - emit NodeStatusChanged(node_addr.address, node_addr.port, false); - - exit = 1; - break; - - case PICA_ERRSSL: - exit = 1; - break; - - case PICA_ERRPROTONEW: - - emit ErrorMsg(QString("Node %1:%2 has newer protocol version. Please check if update for pica-client is available") - .arg(node_addr.address) - .arg(node_addr.port) - ); - exit = 1; - break; - - case PICA_ERRPROTOOLD: - - emit ErrorMsg(QString("Node %1:%2 has older protocol. Disconnected.") - .arg(node_addr.address) - .arg(node_addr.port) - ); - - exit = 1; - break; - - default: - exit = 1; - } - - if (exit) - return; - - do - { - write_mutex->lock(); - if (PICA_read(ci, 10000) != PICA_OK || PICA_write(ci) != PICA_OK) - exit = 1; - write_mutex->unlock(); - msleep(300); - } - while (!exit); - - write_mutex->lock(); - PICA_close_c2n(ci); - *connection = NULL; - write_mutex->unlock(); -} - -void NodeThread::CloseThread() -{ - exit = 1; -} - diff --git a/pica-client/nodethread.h b/pica-client/nodethread.h deleted file mode 100644 index d7154a1..0000000 --- a/pica-client/nodethread.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef NODETHREAD_H -#define NODETHREAD_H - -#include <QThread> -#include <QMutex> -#include "nodes.h" -#include "../PICA_client.h" -#include "accounts.h" - - -class NodeThread : public QThread -{ - Q_OBJECT -public: - explicit NodeThread( Nodes::NodeRecord &addr, bool *completed, PICA_acc *acc, struct PICA_c2n **pica_conn, QMutex *wm); - void CloseThread(); -private: - void run(); - static QMutex finished_mutex; - - QMutex *write_mutex; - - bool *finished_flag; - Nodes::NodeRecord node_addr; - struct PICA_c2n *ci; - struct PICA_acc *user_account; - struct PICA_c2n **connection; - - int exit; - - -signals: - void NodeStatusChanged(QString addr, quint16 port, bool alive); - void ConnectedToNode(QString addr, quint16 port, NodeThread *thread); - void ErrorMsg(QString msg); -public slots: - -}; - -#endif // NODETHREAD_H diff --git a/pica-client/openssllib.cpp b/pica-client/openssllib.cpp new file mode 100644 index 0000000..1dc5ad1 --- /dev/null +++ b/pica-client/openssllib.cpp @@ -0,0 +1,846 @@ +/* + (c) Copyright 2012 - 2018 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#include "openssllib.h" +#include "../PICA_security.h" + +#include <openssl/asn1.h> +#include <openssl/bio.h> +#include <openssl/bn.h> +#include <openssl/err.h> +#include <openssl/evp.h> +#include <openssl/pem.h> +#include <openssl/rand.h> +#include <openssl/rsa.h> +#include <openssl/x509.h> +#include <openssl/x509v3.h> +#include <openssl/dh.h> + +#include <QFile> +#include <QRegExp> +#include <QThread> + +#define REGEXOLD "CN = [0-9]+\\#([^\\#\\$&\"\'=\\(\\)\\\\/\\|`!<>\\{\\}\\[\\]\\+\r\n]+)" +#define REGEXNEW "CN = ([^\\#\\$&\"\'=\\(\\)\\\\/\\|`!<>\\{\\}\\[\\]\\+\r\n]+)" + +/* "-days 3680", as it was spelled on the openssl command line. */ +#define PICA_CERT_VALIDITY_DAYS 3680 + +/* + * The serial number width "openssl req -x509" picks when it is not given one + * (SERIAL_RAND_BITS in apps/lib/apps.c). + */ +#define PICA_CERT_SERIAL_BITS 159 + +#if OPENSSL_VERSION_NUMBER < 0x10100000L +#define X509_getm_notBefore(x) X509_get_notBefore(x) +#define X509_getm_notAfter(x) X509_get_notAfter(x) +#endif + +/* + * "oneline,-esc_msb,utf8" and "multiline,-esc_msb,utf8", the two -nameopt + * arguments OpenSSLTool used, worked out the way the command line program's + * option parser works them out: "oneline" and "multiline" clear every other + * bit before setting their own, the two that follow set and clear a single + * bit each. + */ +static const unsigned long ONELINE_NAMEOPT = + (XN_FLAG_ONELINE & ~ASN1_STRFLGS_ESC_MSB) | ASN1_STRFLGS_UTF8_CONVERT; + +static const unsigned long MULTILINE_NAMEOPT = + (XN_FLAG_MULTILINE & ~ASN1_STRFLGS_ESC_MSB) | ASN1_STRFLGS_UTF8_CONVERT; + +static QString BioToString(BIO *bio) +{ + char *data = 0; + long len; + + len = BIO_get_mem_data(bio, &data); + + if (len <= 0 || !data) + return QString(); + + return QString::fromUtf8(data, (int)len); +} + +static QByteArray BioToByteArray(BIO *bio) +{ + char *data = 0; + long len; + + len = BIO_get_mem_data(bio, &data); + + if (len <= 0 || !data) + return QByteArray(); + + return QByteArray(data, (int)len); +} + +static X509 *CertFromPEM(const QByteArray &cert_pem) +{ + BIO *mem; + X509 *cert; + + if (cert_pem.isEmpty()) + return 0; + + mem = BIO_new_mem_buf((void*)cert_pem.constData(), cert_pem.size()); + + if (!mem) + return 0; + + cert = PEM_read_bio_X509(mem, NULL, NULL, NULL); + + BIO_free(mem); + ERR_clear_error(); + + return cert; +} + +/* + * The whole file is read through QFile rather than handed to BIO_new_file(): + * config_dir can hold characters that do not survive the trip through the + * local 8 bit encoding a C file name would have to be, and Qt already knows + * how to open those paths on every platform we build for. + */ +static QByteArray ReadWholeFile(const QString &name) +{ + QFile f(name); + + if (!f.open(QIODevice::ReadOnly)) + return QByteArray(); + + return f.readAll(); +} + +/* + * The name as the "-subject -nameopt oneline,-esc_msb,utf8" output of the + * command line program spelled it, prefix and trailing newline included, so + * that the two regular expressions below see exactly what they used to see. + */ +static QString SubjectLine(X509 *cert) +{ + BIO *mem; + QString line; + + mem = BIO_new(BIO_s_mem()); + + if (!mem) + return QString(); + + BIO_puts(mem, "subject="); + X509_NAME_print_ex(mem, X509_get_subject_name(cert), 0, ONELINE_NAMEOPT); + BIO_puts(mem, "\n"); + + line = BioToString(mem); + + BIO_free(mem); + + return line; +} + +static QString NameFromSubjectLine(QString subject_line) +{ + QRegExp rxOld(REGEXOLD); + QRegExp rx(REGEXNEW); + + QString name = subject_line; + + if (name.contains(rxOld)) + { + name = rxOld.cap(1); + } + else if (name.contains(rx)) + { + name = rx.cap(1); + } + + return name; +} + +/* + * The generating half of the class. RSA key generation takes seconds and DH + * parameter generation at PICA_CLIENT_DHPARAMBITS takes minutes, and the + * thread calling is the one drawing the dialog that shows the progress, so + * the work happens here instead. + * + * No Q_OBJECT: the only signal needed is QThread::finished(), which QThread + * already declares. + */ +class OpenSSLLibWorker : public QThread +{ +public: + enum Job + { + JobGenRSAKey, + JobGenCert, + JobGenDHParam + }; + + OpenSSLLibWorker(Job job, QObject *parent) + : QThread(parent), setpassword_(false), numbits_(0), job_(job), retval_(1) + { + } + + /* Set by the caller before start(), read by it after finished(). */ + QString keyfile_; + QString certfile_; + QString outfile_; + QString password_; + QString rand_; + QString subject_; + bool setpassword_; + quint32 numbits_; + + int retval() const + { + return retval_; + } + + QString errors() const + { + return errors_; + } + +protected: + void run(); + +private: + void RunGenRSAKey(); + void RunGenCert(); + void RunGenDHParam(); + + bool WriteFile(const QString &name, const QByteArray &data); + void Fail(const char *what); + + Job job_; + QString errors_; + int retval_; +}; + +void OpenSSLLibWorker::Fail(const char *what) +{ + BIO *mem = BIO_new(BIO_s_mem()); + + errors_ += QString::fromLatin1(what); + errors_ += QLatin1String("\n"); + + if (mem) + { + ERR_print_errors(mem); + errors_ += BioToString(mem); + BIO_free(mem); + } + + ERR_clear_error(); + + retval_ = 1; +} + +bool OpenSSLLibWorker::WriteFile(const QString &name, const QByteArray &data) +{ + QFile f(name); + + if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) + { + errors_ += QString("Failed to open %1 for writing: %2\n").arg(name).arg(f.errorString()); + retval_ = 1; + return false; + } + + if (f.write(data) != data.size() || !f.flush()) + { + errors_ += QString("Failed to write %1: %2\n").arg(name).arg(f.errorString()); + retval_ = 1; + return false; + } + + return true; +} + +void OpenSSLLibWorker::run() +{ + retval_ = 1; + + switch (job_) + { + case JobGenRSAKey: + RunGenRSAKey(); + break; + + case JobGenCert: + RunGenCert(); + break; + + case JobGenDHParam: + RunGenDHParam(); + break; + } +} + +void OpenSSLLibWorker::RunGenRSAKey() +{ + EVP_PKEY_CTX *ctx = 0; + EVP_PKEY *pkey = 0; + BIO *mem = 0; + const EVP_CIPHER *cipher = 0; + QByteArray password; + unsigned char rndchar; + quint32 numbits; + + /* + * Generate random-sized key with min size 4096 and multiply of 8. + * Max size is limited to 4096 + 99*8. + * See https://blog.josefsson.org/2016/11/03/why-i-dont-use-2048-or-4096-rsa-key-sizes/ + * "Why I don’t Use 2048 or 4096 RSA Key Sizes" + */ + numbits = PICA_RSA_MINKEYSIZE; + + if (RAND_bytes(&rndchar, 1) != 1) + { + Fail("Random number generator failure"); + return; + } + + numbits += 8 * (rndchar % 100); + + /* + * What "-rand <file>" did: an extra seeding source, /dev/random when the + * account dialog offers it and the user wants it. RAND_load_file() reads + * a small fixed amount from anything that is not a regular file, so this + * does not sit on the device draining it. + */ + if (!rand_.isEmpty()) + { + if (RAND_load_file(QFile::encodeName(rand_).constData(), -1) <= 0) + { + Fail("Failed to seed the random number generator from the requested source"); + return; + } + } + + if (setpassword_) + { + cipher = EVP_get_cipherbyname(PICA_PRIVKEYENCALGO + 1); /* skip the leading '-' */ + + if (!cipher) + { + Fail("Unknown private key encryption algorithm " PICA_PRIVKEYENCALGO); + return; + } + + /* + * UTF-8 rather than the Latin-1 OpenSSLTool wrote down the pipe: + * AskPassword hands the passphrase to OpenSSL as UTF-8 when the + * account is opened later, so anything outside ASCII produced a key + * that could be created but never unlocked again. + */ + password = password_.toUtf8(); + } + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL); + + if (!ctx) + { + Fail("Failed to create an RSA key generation context"); + goto end; + } + + if (EVP_PKEY_keygen_init(ctx) <= 0) + { + Fail("Failed to initialize RSA key generation"); + goto end; + } + + if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, (int)numbits) <= 0) + { + Fail("Failed to set the RSA key size"); + goto end; + } + + if (EVP_PKEY_keygen(ctx, &pkey) <= 0) + { + Fail("Failed to generate the RSA keypair"); + goto end; + } + + mem = BIO_new(BIO_s_mem()); + + if (!mem) + { + Fail("Out of memory"); + goto end; + } + + if (!PEM_write_bio_PrivateKey(mem, pkey, cipher, NULL, 0, NULL, + setpassword_ ? (void*)password.constData() : NULL)) + { + Fail("Failed to encode the private key"); + goto end; + } + + if (WriteFile(keyfile_, BioToByteArray(mem))) + retval_ = 0; + +end: + + if (mem) + BIO_free(mem); + + if (pkey) + EVP_PKEY_free(pkey); + + if (ctx) + EVP_PKEY_CTX_free(ctx); +} + +void OpenSSLLibWorker::RunGenCert() +{ + EVP_PKEY *pkey = 0; + X509 *cert = 0; + X509_NAME *name = 0; + BIGNUM *serial = 0; + BIO *keymem = 0; + BIO *mem = 0; + const EVP_MD *digest; + X509V3_CTX extctx; + QByteArray keydata; + QByteArray password; + QByteArray subject; + + /* + * The extensions "openssl req -x509" picked up from the [ v3_ca ] section + * of openssl.cnf. Spelled out here so that a certificate no longer + * depends on which openssl.cnf the machine happens to have - the Windows + * build used to have to ship one of its own next to the executable. + * + * Order matters: "keyid:always" reads the subject key identifier of the + * issuer, which for a self signed certificate is the extension added just + * above it. + */ + static const struct + { + int nid; + const char *value; + } extensions[] = + { + { NID_subject_key_identifier, "hash" }, + { NID_authority_key_identifier, "keyid:always,issuer" }, + { NID_basic_constraints, "critical,CA:true" } + }; + + unsigned int i; + + digest = EVP_get_digestbyname(PICA_CERTDIGESTALGO + 1); /* skip the leading '-' */ + + if (!digest) + { + Fail("Unknown certificate digest algorithm " PICA_CERTDIGESTALGO); + return; + } + + keydata = ReadWholeFile(keyfile_); + + if (keydata.isEmpty()) + { + errors_ += QString("Failed to read the private key file %1\n").arg(keyfile_); + retval_ = 1; + return; + } + + keymem = BIO_new_mem_buf((void*)keydata.constData(), keydata.size()); + + if (!keymem) + { + Fail("Out of memory"); + goto end; + } + + password = password_.toUtf8(); + + pkey = PEM_read_bio_PrivateKey(keymem, NULL, NULL, (void*)password.constData()); + + if (!pkey) + { + Fail("Failed to read the private key"); + goto end; + } + + cert = X509_new(); + + if (!cert) + { + Fail("Out of memory"); + goto end; + } + + if (!X509_set_version(cert, 2)) /* X.509 v3 */ + { + Fail("Failed to set the certificate version"); + goto end; + } + + serial = BN_new(); + + if (!serial + || !BN_rand(serial, PICA_CERT_SERIAL_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY) + || !BN_to_ASN1_INTEGER(serial, X509_get_serialNumber(cert))) + { + Fail("Failed to generate the certificate serial number"); + goto end; + } + + name = X509_NAME_new(); + + subject = subject_.toUtf8(); + + if (!name + || !X509_NAME_add_entry_by_NID(name, NID_commonName, MBSTRING_UTF8, + (unsigned char*)subject.data(), subject.size(), -1, 0)) + { + Fail("Failed to build the certificate subject name"); + goto end; + } + + if (!X509_set_subject_name(cert, name) || !X509_set_issuer_name(cert, name)) + { + Fail("Failed to set the certificate subject name"); + goto end; + } + + if (!X509_gmtime_adj(X509_getm_notBefore(cert), 0) + || !X509_time_adj_ex(X509_getm_notAfter(cert), PICA_CERT_VALIDITY_DAYS, 0, NULL)) + { + Fail("Failed to set the certificate validity period"); + goto end; + } + + if (!X509_set_pubkey(cert, pkey)) + { + Fail("Failed to set the certificate public key"); + goto end; + } + + X509V3_set_ctx_nodb(&extctx); + X509V3_set_ctx(&extctx, cert, cert, NULL, NULL, 0); + + for (i = 0; i < sizeof(extensions) / sizeof(extensions[0]); i++) + { + X509_EXTENSION *ext; + QByteArray value(extensions[i].value); + + ext = X509V3_EXT_conf_nid(NULL, &extctx, extensions[i].nid, value.data()); + + if (!ext) + { + Fail("Failed to build a certificate extension"); + goto end; + } + + if (!X509_add_ext(cert, ext, -1)) + { + X509_EXTENSION_free(ext); + Fail("Failed to add a certificate extension"); + goto end; + } + + X509_EXTENSION_free(ext); + } + + if (!X509_sign(cert, pkey, digest)) + { + Fail("Failed to sign the certificate"); + goto end; + } + + mem = BIO_new(BIO_s_mem()); + + if (!mem) + { + Fail("Out of memory"); + goto end; + } + + if (!PEM_write_bio_X509(mem, cert)) + { + Fail("Failed to encode the certificate"); + goto end; + } + + if (WriteFile(certfile_, BioToByteArray(mem))) + retval_ = 0; + +end: + + if (mem) + BIO_free(mem); + + if (name) + X509_NAME_free(name); + + if (serial) + BN_free(serial); + + if (cert) + X509_free(cert); + + if (pkey) + EVP_PKEY_free(pkey); + + if (keymem) + BIO_free(keymem); +} + +void OpenSSLLibWorker::RunGenDHParam() +{ + EVP_PKEY_CTX *ctx = 0; + EVP_PKEY *pkey = 0; + BIO *mem = 0; + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_DH, NULL); + + if (!ctx) + { + Fail("Failed to create a Diffie-Hellman parameter generation context"); + goto end; + } + + if (EVP_PKEY_paramgen_init(ctx) <= 0) + { + Fail("Failed to initialize Diffie-Hellman parameter generation"); + goto end; + } + + if (EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, (int)numbits_) <= 0) + { + Fail("Failed to set the Diffie-Hellman prime length"); + goto end; + } + + /* "-5", the generator OpenSSLTool asked the command line program for. */ + if (EVP_PKEY_CTX_set_dh_paramgen_generator(ctx, 5) <= 0) + { + Fail("Failed to set the Diffie-Hellman generator"); + goto end; + } + + if (EVP_PKEY_paramgen(ctx, &pkey) <= 0) + { + Fail("Failed to generate the Diffie-Hellman parameters"); + goto end; + } + + mem = BIO_new(BIO_s_mem()); + + if (!mem) + { + Fail("Out of memory"); + goto end; + } + + if (!PEM_write_bio_Parameters(mem, pkey)) + { + Fail("Failed to encode the Diffie-Hellman parameters"); + goto end; + } + + if (WriteFile(outfile_, BioToByteArray(mem))) + retval_ = 0; + +end: + + if (mem) + BIO_free(mem); + + if (pkey) + EVP_PKEY_free(pkey); + + if (ctx) + EVP_PKEY_CTX_free(ctx); +} + +OpenSSLLib::OpenSSLLib(QObject *parent) : + QObject(parent), worker_(0) +{ +} + +OpenSSLLib::~OpenSSLLib() +{ + if (worker_) + { + worker_->disconnect(this); + worker_->wait(); + } +} + +static QString NameFromCertBytes(const QByteArray &cert_pem) +{ + X509 *cert; + QString name; + + cert = CertFromPEM(cert_pem); + + if (!cert) + return QString(); + + name = NameFromSubjectLine(SubjectLine(cert)); + + X509_free(cert); + + return name; +} + +QString OpenSSLLib::NameFromCertFile(QString cert_file) +{ + return NameFromCertBytes(ReadWholeFile(cert_file)); +} + +QString OpenSSLLib::NameFromCertString(QString cert_pem) +{ + return NameFromCertBytes(cert_pem.toLatin1()); +} + +QString OpenSSLLib::CertTextFromString(QString cert_pem) +{ + X509 *cert; + BIO *mem; + QString text; + + cert = CertFromPEM(cert_pem.toLatin1()); + + if (!cert) + return QString(); + + mem = BIO_new(BIO_s_mem()); + + if (!mem) + { + X509_free(cert); + return QString(); + } + + if (X509_print_ex(mem, cert, MULTILINE_NAMEOPT, 0)) + text = BioToString(mem); + + BIO_free(mem); + X509_free(cert); + ERR_clear_error(); + + return text; +} + +bool OpenSSLLib::StartWorker(OpenSSLLibWorker *worker, QObject *receiver, const char *finished_slot) +{ + if (worker_) + { + delete worker; + return false; + } + + worker_ = worker; + + errors_.clear(); + output_.clear(); + + disconnect(this, SIGNAL(finished(int)), 0, 0); + connect(this, SIGNAL(finished(int)), receiver, finished_slot); + + /* + * Queued, because QThread::finished() is emitted on the worker thread and + * this object lives on the one that called - so WorkerFinished(), and the + * receiver's slot after it, run where the caller expects them to. + */ + connect(worker_, SIGNAL(finished()), this, SLOT(WorkerFinished())); + + worker_->start(); + + return true; +} + +void OpenSSLLib::WorkerFinished() +{ + OpenSSLLibWorker *worker = worker_; + int retval; + + if (!worker) + return; + + retval = worker->retval(); + errors_ = worker->errors(); + + worker_ = 0; + worker->wait(); /* returns at once - run() is over by the time this is delivered */ + worker->deleteLater(); + + /* + * Last thing done here: the receiver is allowed to delete us from its + * slot, the way DHParam disposes of its generator. + */ + emit finished(retval); +} + +bool OpenSSLLib::GenRSAKeySignal(QString keyfile, bool setpassword, QString password, QString rand, QObject *receiver, const char *finished_slot) +{ + OpenSSLLibWorker *worker = new OpenSSLLibWorker(OpenSSLLibWorker::JobGenRSAKey, this); + + worker->keyfile_ = keyfile; + worker->setpassword_ = setpassword; + worker->password_ = password; + worker->rand_ = rand; + + return StartWorker(worker, receiver, finished_slot); +} + +bool OpenSSLLib::GenCertSignal(QString cert_file, QString keyfile, QString keypassword, + QString subject, QObject *receiver, const char *finished_slot) +{ + OpenSSLLibWorker *worker = new OpenSSLLibWorker(OpenSSLLibWorker::JobGenCert, this); + + worker->certfile_ = cert_file; + worker->keyfile_ = keyfile; + worker->password_ = keypassword; + worker->subject_ = subject; + + return StartWorker(worker, receiver, finished_slot); +} + +bool OpenSSLLib::GenDHParamSignal(quint32 numbits, QString output_file, QObject *receiver, const char *finished_slot) +{ + OpenSSLLibWorker *worker = new OpenSSLLibWorker(OpenSSLLibWorker::JobGenDHParam, this); + + worker->numbits_ = numbits; + worker->outfile_ = output_file; + + return StartWorker(worker, receiver, finished_slot); +} + +QString OpenSSLLib::ReadStdErr() +{ + QString errors = errors_; + + errors_.clear(); + + return errors; +} + +QString OpenSSLLib::ReadStdOut() +{ + QString output = output_; + + output_.clear(); + + return output; +} diff --git a/pica-client/openssllib.h b/pica-client/openssllib.h new file mode 100644 index 0000000..2c58820 --- /dev/null +++ b/pica-client/openssllib.h @@ -0,0 +1,81 @@ +/* + (c) Copyright 2012 - 2018 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#ifndef OPENSSLLIB_H +#define OPENSSLLIB_H + +#include <QObject> +#include <QString> + +/* + * Key, certificate and Diffie-Hellman parameter generation, and the reading + * of certificates for display, done through libcrypto. + * + * This is the replacement for OpenSSLTool, which drove the "openssl" command + * line program through QProcess and parsed its output. The results are meant + * to be the same down to the encoding of the files produced - see + * tests/test_openssllib.cpp, which compares them against the command line + * program - but the binary is no longer a runtime dependency, there is no + * openssl.cnf to ship next to the executable, and passphrases no longer + * travel through a pipe. + * + * The three generating methods keep the shape of their OpenSSLTool + * counterparts: they return immediately and call the receiver's slot when the + * work is over. The work itself happens on a worker thread, because it is the + * GUI thread calling - RSA key generation takes seconds and DH parameter + * generation at PICA_CLIENT_DHPARAMBITS takes minutes. The slot signature is + * the one difference from OpenSSLTool: there is no process any more, so it is + * finished(int retval) rather than finished(int, QProcess::ExitStatus). + * retval keeps its old meaning - zero on success. + */ + +class OpenSSLLibWorker; + +class OpenSSLLib : public QObject +{ + Q_OBJECT +public: + explicit OpenSSLLib(QObject *parent = 0); + ~OpenSSLLib(); + + static QString NameFromCertFile(QString cert_file); + static QString NameFromCertString(QString cert_pem); + static QString CertTextFromString(QString cert_pem); + + bool GenRSAKeySignal(QString keyfile, bool setpassword, + QString password, QString rand, QObject *receiver, const char *finished_slot); + bool GenCertSignal(QString cert_file, QString keyfile, QString keypassword, QString subject, QObject *receiver, const char *finished_slot); + + bool GenDHParamSignal(quint32 numbits, QString output_file, QObject *receiver, const char *finished_slot); + + QString ReadStdErr(); + QString ReadStdOut(); + +signals: + void finished(int retval); + +private slots: + void WorkerFinished(); + +private: + bool StartWorker(OpenSSLLibWorker *worker, QObject *receiver, const char *finished_slot); + + OpenSSLLibWorker *worker_; + QString errors_; + QString output_; +}; + +#endif // OPENSSLLIB_H diff --git a/pica-client/openssltool.cpp b/pica-client/openssltool.cpp deleted file mode 100644 index ec7a547..0000000 --- a/pica-client/openssltool.cpp +++ /dev/null @@ -1,222 +0,0 @@ -/* - (c) Copyright 2012 - 2018 Anton Sviridenko - https://picapica.im - - 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, version 3. - - 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 for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ -#include "openssltool.h" -#include "../PICA_security.h" -#include <openssl/rand.h> -#include <QProcess> -#include <QRegExp> -#include <QMessageBox> - -#define REGEXOLD "CN = [0-9]+\\#([^\\#\\$&\"\'=\\(\\)\\\\/\\|`!<>\\{\\}\\[\\]\\+\r\n]+)" -#define REGEXNEW "CN = ([^\\#\\$&\"\'=\\(\\)\\\\/\\|`!<>\\{\\}\\[\\]\\+\r\n]+)" - -OpenSSLTool::OpenSSLTool() -{ -} - -QString OpenSSLTool::NameFromCertFile(QString cert_file) -{ - // - QProcess openssl; - - openssl.start("openssl", QStringList() << "x509" << "-in" << cert_file << "-subject" << "-nameopt" << "oneline,-esc_msb,utf8" << "-noout"); - if (!openssl.waitForStarted()) - return QString(); - - if (!openssl.waitForFinished()) - return QString(); - - QByteArray result = openssl.readAll(); - QRegExp rxOld(REGEXOLD); - QRegExp rx(REGEXNEW); - - QString name = QString::fromUtf8( result.constData()); - - if (name.contains(rxOld)) - { - name = rxOld.cap(1); - } - else if (name.contains(rx)) - { - name = rx.cap(1); - } - - // - return name; -} - -QString OpenSSLTool::NameFromCertString(QString cert_pem) -{ - QProcess openssl; - - openssl.start("openssl", QStringList() << "x509" << "-subject" << "-nameopt" << "oneline,-esc_msb,utf8" << "-noout"); - if (!openssl.waitForStarted()) - return QString(); - - openssl.write(cert_pem.toLatin1()); - - if (!openssl.waitForFinished()) - return QString(); - - QByteArray result = openssl.readAll(); - QRegExp rxOld(REGEXOLD); - QRegExp rx(REGEXNEW); - - QString name = QString::fromUtf8( result.constData()); - - if (name.contains(rxOld)) - { - name = rxOld.cap(1); - } - else if (name.contains(rx)) - { - name = rx.cap(1); - } - - // - return name; -} - -QString OpenSSLTool::CertTextFromString(QString cert_pem) -{ - QProcess openssl; - qint64 ret; - char *data; - QByteArray ba; - - openssl.start("openssl", QStringList() << "x509" << "-noout" << "-text" << "-nameopt" << "multiline,-esc_msb,utf8"); - - if (!openssl.waitForStarted()) - return QString(); - - ba = cert_pem.toLatin1(); - ret = openssl.write(data = (char*)ba.constData()); - openssl.closeWriteChannel(); - - if (!openssl.waitForFinished()) - return QString(); - - return QString::fromUtf8(openssl.readAllStandardOutput().constData()); -} - -bool OpenSSLTool::GenRSAKeySignal(QString keyfile, bool setpassword, QString password, QString rand, QObject *receiver, const char *finished_slot) -{ - QStringList args; - quint32 numbits; - unsigned char rndchar; - - args << "genrsa" << "-out" << keyfile; - - if (setpassword) - args << "-passout" << "stdin" << PICA_PRIVKEYENCALGO; - - if (!rand.isEmpty()) - args << "-rand" << rand; - - /* - * Generate random-sized key with min size 4096 and multiply of 8. - * Max size is limited to 4096 + 99*8. - * See https://blog.josefsson.org/2016/11/03/why-i-dont-use-2048-or-4096-rsa-key-sizes/ - * "Why I don’t Use 2048 or 4096 RSA Key Sizes" - */ - numbits = PICA_RSA_MINKEYSIZE; - - RAND_pseudo_bytes(&rndchar, 1); - - numbits += 8 * (rndchar % 100); - - args << QString::number(numbits); - - openssl_.start("openssl", args); - - - if (!openssl_.waitForStarted()) - return false; - - if (setpassword) - { - openssl_.write((password + "\n").toLatin1().constData()); - } - - openssl_.disconnect(&openssl_, SIGNAL(finished(int, QProcess::ExitStatus)), 0, 0); - openssl_.connect(&openssl_, SIGNAL(finished(int, QProcess::ExitStatus)), receiver, finished_slot); - - return true; -} - -bool OpenSSLTool::GenCertSignal(QString cert_file, QString keyfile, QString keypassword, - QString subject, QObject *receiver, const char *finished_slot) -{ - openssl_.start("openssl", - QStringList() - << "req" -#ifdef WIN32 - << "-config" << "openssl.cnf" -#endif - << "-out" << cert_file - << "-key" << keyfile - << "-subj" << "/CN=" + subject - << "-new" - << "-x509" - << "-days" << "3680" - << "-utf8" - << "-batch" - << PICA_CERTDIGESTALGO - << "-passin" - << "stdin"); - - if (!openssl_.waitForStarted()) - return false; - - openssl_.write((keypassword + "\n").toLatin1().constData()); - - openssl_.disconnect(&openssl_, SIGNAL(finished(int, QProcess::ExitStatus)), 0, 0); - openssl_.connect(&openssl_, SIGNAL(finished(int, QProcess::ExitStatus)), receiver, finished_slot); - - return true; -} - -QString OpenSSLTool::ReadStdErr() -{ - return QString::fromUtf8(openssl_.readAllStandardError().constData()); -} - -QString OpenSSLTool::ReadStdOut() -{ - return QString::fromUtf8(openssl_.readAllStandardOutput().constData()); -} - -bool OpenSSLTool::GenDHParamSignal(quint32 numbits, QString output_file, QObject *receiver, const char *finished_slot) -{ - //openssl dhparam -5 4096 - openssl_.start("openssl", - QStringList() - << "dhparam" - << "-out" << output_file - << "-5" - << QString::number(numbits)); - - if (!openssl_.waitForStarted()) - return false; - - openssl_.disconnect(&openssl_, SIGNAL(finished(int, QProcess::ExitStatus)), 0, 0); - openssl_.connect(&openssl_, SIGNAL(finished(int, QProcess::ExitStatus)), receiver, finished_slot); - - return true; -} - - diff --git a/pica-client/openssltool.h b/pica-client/openssltool.h deleted file mode 100644 index 8d59860..0000000 --- a/pica-client/openssltool.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - (c) Copyright 2012 - 2018 Anton Sviridenko - https://picapica.im - - 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, version 3. - - 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 for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ -#ifndef OPENSSLTOOL_H -#define OPENSSLTOOL_H - -#include <QString> -#include <QProcess> - -class OpenSSLTool -{ -public: - OpenSSLTool(); - - static QString NameFromCertFile(QString cert_file); - static QString NameFromCertString(QString cert_pem); - static QString CertTextFromString(QString cert_pem); - - bool GenRSAKeySignal(QString keyfile, bool setpassword, - QString password, QString rand, QObject *receiver, const char *finished_slot); - bool GenCertSignal(QString cert_file, QString keyfile, QString keypassword, QString subject, QObject *receiver, const char *finished_slot); - - bool GenDHParamSignal(quint32 numbits, QString output_file, QObject *receiver, const char *finished_slot); - - QString ReadStdErr(); - QString ReadStdOut(); - -private: - QProcess openssl_; -}; - -#endif // OPENSSLTOOL_H diff --git a/pica-client/pica-client.pro b/pica-client/pica-client.pro index 61662fc..2838890 100644 --- a/pica-client/pica-client.pro +++ b/pica-client/pica-client.pro @@ -11,13 +11,23 @@ TEMPLATE = app SOURCES += main.cpp\ + audiodevice.cpp \ + echocanceller.cpp \ + nativeaudio.cpp \ + nativeaudio_wasapi.cpp \ + nativeaudio_coreaudio.cpp \ + audiovideocallcontroller.cpp \ mainwindow.cpp \ chatwindow.cpp \ + callwindow.cpp \ contacts.cpp \ ../PICA_client.c \ + ../PICA_media.c \ ../PICA_msgproc.c \ contactlistwidget.cpp \ + mediadevice.cpp \ skynet.cpp \ + directlistener.cpp \ nodes.cpp \ accountswindow.cpp \ accounts.cpp \ @@ -29,7 +39,7 @@ SOURCES += main.cpp\ dialogs/viewcertdialog.cpp \ dialogs/forgedcertdialog.cpp \ dialogs/registeraccountdialog.cpp \ - openssltool.cpp \ + openssllib.cpp \ history.cpp \ ../PICA_id.c \ dhparam.cpp \ @@ -39,17 +49,30 @@ SOURCES += main.cpp\ sound.cpp \ dialogs/settingsdialog.cpp \ settings.cpp \ + callsettings.cpp \ ../PICA_netconf.c \ ../PICA_signverify.c \ - dialogs/nodesdialog.cpp + dialogs/nodesdialog.cpp \ + videodevice.cpp \ + videodshow.cpp HEADERS += mainwindow.h \ + directlistener.h \ + directc2csettings.h \ + audiodevice.h \ + audioring.h \ + echocanceller.h \ + nativeaudio.h \ + audiovideocallcontroller.h \ chatwindow.h \ + callwindow.h \ contacts.h \ globals.h \ ../PICA_client.h \ + ../PICA_media.h \ ../PICA_msgproc.h \ contactlistwidget.h \ + mediadevice.h \ skynet.h \ nodes.h \ accountswindow.h \ @@ -64,7 +87,7 @@ HEADERS += mainwindow.h \ ../PICA_common.h \ ../PICA_proto.h \ dialogs/registeraccountdialog.h \ - openssltool.h \ + openssllib.h \ history.h \ ../PICA_id.h \ dhparam.h \ @@ -74,10 +97,12 @@ HEADERS += mainwindow.h \ sound.h \ dialogs/settingsdialog.h \ settings.h \ + callsettings.h \ ../PICA_netconf.h \ ../PICA_security.h \ ../PICA_signverify.h \ - dialogs/nodesdialog.h + dialogs/nodesdialog.h \ + videodevice.h DEFINES = PICA_MULTITHREADED @@ -94,3 +119,44 @@ unix: CONFIG += link_pkgconfig unix: PKGCONFIG += libcrypto unix|win32: LIBS += -lminiupnpc + +# Acoustic echo cancellation - WebRTC's AEC3, through the audio processing +# module. Required everywhere: it is what the "use own echo cancellation" +# setting selects, and on Linux it is usually the only cancellation in the +# picture at all. +# +# Its headers, and the abseil ones they include, refuse to compile as anything +# older than C++17, so the whole target is built that way. +CONFIG += c++17 + +# Through pkg-config on macOS too, unlike the libraries above: the headers sit +# in a versioned include directory and the library needs several abseil ones +# alongside it, so the flags are not worth writing out by hand. +# +# 1.x and 2.x install in parallel under separate pkg-config names and differ +# in a few API details that echocanceller.cpp handles; 1.x wins when both are +# there, matching what configure does. The macro is only a hint - the file +# falls back to working the version out from the headers - but a build that +# has both installed is exactly where the hint earns its keep. +unix: CONFIG += link_pkgconfig +unix { + packagesExist(webrtc-audio-processing-1) { + PKGCONFIG += webrtc-audio-processing-1 + DEFINES += PICA_WEBRTC_AUDIO_PROCESSING_MAJOR=1 + } else { + PKGCONFIG += webrtc-audio-processing-2 + DEFINES += PICA_WEBRTC_AUDIO_PROCESSING_MAJOR=2 + } +} + +# Listing PulseAudio sources and sinks in the settings dialog. Optional - +# playing and capturing through PulseAudio goes via FFmpeg's own "pulse" +# device and needs nothing from us. +unix:!macx: PKGCONFIG += libpulse +unix:!macx: DEFINES += HAVE_LIBPULSE + +# The native audio backends. Both source files compile to nothing on the +# platforms they are not for, so they can stay in SOURCES unconditionally; +# what they link against cannot. +win32: LIBS += -lole32 -loleaut32 +macx: LIBS += -framework CoreAudio -framework AudioUnit -framework AudioToolbox -framework CoreFoundation diff --git a/pica-client/picaactioncenter.cpp b/pica-client/picaactioncenter.cpp index e755ce0..9622129 100644 --- a/pica-client/picaactioncenter.cpp +++ b/pica-client/picaactioncenter.cpp @@ -96,7 +96,9 @@ void PicaActionCenter::exit() void PicaActionCenter::showsettings() { SettingsDialog sd; - sd.exec(); + + if (sd.exec()) + skynet->ApplyDirectC2CSettings(); } void PicaActionCenter::shownodes() diff --git a/pica-client/settings.cpp b/pica-client/settings.cpp index 4c7088b..e4e3004 100644 --- a/pica-client/settings.cpp +++ b/pica-client/settings.cpp @@ -16,9 +16,9 @@ */ #include "settings.h" -Settings::Settings(QString storage) +Settings::Settings(QString storage, QString connectionName) { - dbconn = QSqlDatabase::database(); + dbconn = connectionName.isEmpty() ? QSqlDatabase::database() : QSqlDatabase::database(connectionName); dbconn.setDatabaseName(storage); if (!dbconn.open()) @@ -36,7 +36,7 @@ QString Settings::GetLastError() bool Settings::isEmpty() { - QSqlQuery query; + QSqlQuery query(dbconn); query.exec("select count(*) from settings"); @@ -54,7 +54,7 @@ bool Settings::isEmpty() QVariant Settings::loadValue(QString name, QVariant defval) { - QSqlQuery query; + QSqlQuery query(dbconn); query.prepare("select value from settings where name = :name"); query.bindValue(":name", name); @@ -74,7 +74,7 @@ QVariant Settings::loadValue(QString name, QVariant defval) void Settings::storeValue(QString name, QString val) { - QSqlQuery query; + QSqlQuery query(dbconn); query.prepare("insert into settings (name, value) values (:name, :val)"); query.bindValue(":name", name); diff --git a/pica-client/settings.h b/pica-client/settings.h index be95ca2..622acfc 100644 --- a/pica-client/settings.h +++ b/pica-client/settings.h @@ -24,7 +24,8 @@ class Settings { public: - Settings(QString storage); + // See Nodes::Nodes() for what connectionName selects and why. + Settings(QString storage, QString connectionName = QString()); QVariant loadValue(QString name, QVariant defval); void storeValue(QString name, QString val); diff --git a/pica-client/skynet.cpp b/pica-client/skynet.cpp index a5c30b0..02aad9f 100644 --- a/pica-client/skynet.cpp +++ b/pica-client/skynet.cpp @@ -17,9 +17,11 @@ #include "skynet.h" #include "globals.h" #include <QMutex> +#include <QMetaType> +#include <QCoreApplication> //#include "dialogs/viewcertdialog.h" #include "contacts.h" -#include "openssltool.h" +#include "openssllib.h" //#include <QMessageBox> //debug //#include "dialogs/forgedcertdialog.h" #include <QDebug> @@ -27,13 +29,16 @@ #include "dhparam.h" #include "askpassword.h" #include "settings.h" -#include "../PICA_netconf.h" +#include "directc2csettings.h" #include <time.h> SkyNet::SkyNet() - : nodes(config_dbname), QObject(0), active_filetransfers(0) + : nodes(nullptr), QObject(0), active_filetransfers(0) { self_aware = false; + call_waiting_c2c_connect = false; + + qRegisterMetaType<Accounts::AccountRecord>("Accounts::AccountRecord"); PICA_client_callbacks cbs = { @@ -57,7 +62,17 @@ SkyNet::SkyNet() c2n_closed_cb, listener_error_cb, multilogin_cb, - direct_c2c_established_cb + direct_c2c_established_cb, + incoming_call_cb, + call_picked_up_cb, + call_rejected_cb, + call_hangup_cb, + call_audio_params_cb, + call_video_params_cb, + call_audio_packet_cb, + call_video_packet_cb, + call_media_transport_cb + }; PICA_client_init(&cbs); @@ -65,18 +80,79 @@ SkyNet::SkyNet() this->active_nodelink = NULL; this->acc = NULL; this->listener = NULL; + this->direct_listener = NULL; + listener_setup_pending = false; + listener_failed = false; + join_deferred = false; + + qRegisterMetaType<quintptr>("quintptr"); connect(this, SIGNAL(PeerCertificateReceived(QByteArray, QString, bool*)), this, SLOT(verify_peer_cert(QByteArray, QString, bool*)), Qt::DirectConnection); connect(this, SIGNAL(MultiloginMessageReceived(quint64,QString,quint16)), this, SLOT(multilogin_event(quint64,QString,quint16)), Qt::QueuedConnection); + file_transfer_timer_id = 0; + call_timer_id = 0; + call_active = false; + +} + +SkyNet::~SkyNet() +{ + if (direct_listener) + { + // the UPnP mapping is deleted rather than left to expire + QMetaObject::invokeMethod(direct_listener, "release", Qt::BlockingQueuedConnection); + direct_listener_thread.quit(); + direct_listener_thread.wait(); + delete direct_listener; + } + + delete nodes; +} + +// Name of the QSqlDatabase connection opened for this SkyNet instance's own +// (network) thread - separate from the GUI thread's default connection, +// since a QSqlDatabase connection can only be used by the thread that +// created it. +static const QString network_sql_connection_name = QStringLiteral("network_thread_connection"); + +void SkyNet::init() +{ + QSqlDatabase netdb = QSqlDatabase::addDatabase("QSQLITE", network_sql_connection_name); + netdb.setDatabaseName(config_dbname); + netdb.open(); + + nodes = new Nodes(config_dbname, network_sql_connection_name); + + direct_listener = new DirectListener(); + direct_listener->moveToThread(&direct_listener_thread); + connect(direct_listener, SIGNAL(ready(quintptr,QString,int)), + this, SLOT(listener_ready(quintptr,QString,int)), Qt::QueuedConnection); + connect(direct_listener, SIGNAL(upnpChanged(QString,int)), + this, SLOT(listener_upnp_changed(QString,int)), Qt::QueuedConnection); + connect(direct_listener, SIGNAL(statusMsg(QString,bool)), + this, SLOT(listener_status_msg(QString,bool)), Qt::QueuedConnection); + direct_listener_thread.start(); + event_loop_timer_id = startTimer(100); c2c_reconnect_timer_id = startTimer(1000); - file_transfer_timer_id = 0; +} +void SkyNet::moveBackToMainThread() +{ + moveToThread(QCoreApplication::instance()->thread()); } -void SkyNet::active_filetransfers_up() +void SkyNet::active_filetransfers_up(QByteArray peer, bool sending) { + QSet<QByteArray> &counted = sending ? counted_ft_out : counted_ft_in; + + // Idempotent: a transfer already counted (e.g. a second RESUME) must not + // be counted twice. + if (counted.contains(peer)) + return; + + counted.insert(peer); active_filetransfers++; if (active_filetransfers > 0 && file_transfer_timer_id == 0) @@ -85,11 +161,18 @@ void SkyNet::active_filetransfers_up() } } -void SkyNet::active_filetransfers_down() +void SkyNet::active_filetransfers_down(QByteArray peer, bool sending) { - active_filetransfers--; + QSet<QByteArray> &counted = sending ? counted_ft_out : counted_ft_in; + + // Idempotent: only a transfer that was actually counted can be removed. A + // cancel/ioerror for one that was never accepted (WAITACCEPT) or already + // paused is a no-op, rather than wrapping the unsigned counter past zero. + if (!counted.contains(peer)) + return; - Q_ASSERT(active_filetransfers >= 0); + counted.remove(peer); + active_filetransfers--; if (active_filetransfers == 0 && file_transfer_timer_id != 0) { @@ -98,8 +181,47 @@ void SkyNet::active_filetransfers_down() } } +void SkyNet::call_active_set(bool active, QByteArray peer) +{ + if (active) + { + call_active_peer = peer; + } + else + { + // A c2c connection to some other contact going down says nothing + // about the call in progress. + if (!peer.isEmpty() && !call_active_peer.isEmpty() && peer != call_active_peer) + return; + + call_active_peer.clear(); + } + + if (active == call_active) + return; + + call_active = active; + + // Same trick as active_filetransfers_up(): a zero interval timer is not + // a busy loop here, because PICA_event_loop() spends its time blocked + // inside select(). Without it the network thread only enters select() + // once per event_loop_timer_id tick, and an incoming media packet waits + // for the rest of that interval before it is read. + if (active && call_timer_id == 0) + { + call_timer_id = startTimer(0); + } + else if (!active && call_timer_id != 0) + { + killTimer(call_timer_id); + call_timer_id = 0; + } +} + void SkyNet::active_filetransfers_reset() { + counted_ft_in.clear(); + counted_ft_out.clear(); active_filetransfers = 0; if (file_transfer_timer_id != 0) @@ -130,14 +252,14 @@ void SkyNet::nodelink_activated(PICA_c2n *c2n) self_aware = true; active_nodelink = c2n; - nodes.MakeClean(); + nodes->MakeClean(); emit BecameSelfAware(); //load undelivered messages from history if (msgqueues.isEmpty()) { - History h(config_dbname, Accounts::GetCurrentAccount().id); + History h(config_dbname, Accounts::GetCurrentAccount().id, network_sql_connection_name); msgqueues = h.GetUndeliveredMessages(); } @@ -192,7 +314,7 @@ void SkyNet::nodelink_failed(PICA_c2n *c2n, int error) emit StatusMsg(QString("Node %1:%2 has older protocol. Disconnected.") .arg(connecting_nodes[i].second.address) .arg(connecting_nodes[i].second.port), - false); + true); break; } @@ -224,7 +346,7 @@ void SkyNet::multilogin_event(quint64 timestamp, QString node_addr, quint16 node void SkyNet::node_status_changed(Nodes::NodeRecord nr, bool alive) { - nodes.UpdateStatus(nr, alive); + nodes->UpdateStatus(nr, alive); } void SkyNet::verify_peer_cert(QByteArray peer_id, QString cert_pem, bool *verified) @@ -232,7 +354,7 @@ void SkyNet::verify_peer_cert(QByteArray peer_id, QString cert_pem, bool *verifi // ViewCertDialog vcd; // vcd.SetCert(cert_pem); // vcd.exec(); - Contacts cnt(config_dbname, Accounts::GetCurrentAccount().id); + Contacts cnt(config_dbname, Accounts::GetCurrentAccount().id, network_sql_connection_name); QString stored_cert; @@ -244,7 +366,7 @@ void SkyNet::verify_peer_cert(QByteArray peer_id, QString cert_pem, bool *verifi { cnt.SetContactCert(peer_id, cert_pem); - QString name = OpenSSLTool::NameFromCertString(cert_pem); + QString name = OpenSSLLib::NameFromCertString(cert_pem); cnt.SetContactName(peer_id, name); @@ -339,7 +461,8 @@ void SkyNet::reconnect_c2c() void SkyNet::timerEvent(QTimerEvent *e) { - if (e->timerId() == file_transfer_timer_id || e->timerId() == event_loop_timer_id) + if (e->timerId() == file_transfer_timer_id || e->timerId() == event_loop_timer_id + || e->timerId() == call_timer_id) { if (connecting_nodes.size() > 0 || self_aware) { @@ -356,7 +479,12 @@ void SkyNet::timerEvent(QTimerEvent *e) nodelinks.append(NULL); - ret = PICA_event_loop(nodelinks.data(), 25); + // A shorter select() timeout while a call is in progress: the + // audio and video threads hand their packets over with a queued + // invokeMethod(), and Qt cannot deliver those to this thread + // while it sits inside select(). The timeout is therefore the + // worst case delay added to every outgoing media packet. + ret = PICA_event_loop(nodelinks.data(), call_active ? 5 : 25); while(!connected_nodes_to_close.empty()) { @@ -376,8 +504,7 @@ void SkyNet::timerEvent(QTimerEvent *e) if (!self_aware && e->timerId() == nodelink_reconnect_timer_id) { killTimer(nodelink_reconnect_timer_id); - Accounts::AccountRecord acc = this->CurrentAccount(); - Join(acc); + Join(skynet_account); } } @@ -407,15 +534,21 @@ bool SkyNet::open_account() return true; } -void SkyNet::Join(Accounts::AccountRecord &accrec) +void SkyNet::Join(const Accounts::AccountRecord &accrec) +{ + QMetaObject::invokeMethod(this, "do_Join", Qt::AutoConnection, + Q_ARG(Accounts::AccountRecord, accrec)); +} + +void SkyNet::do_Join(const Accounts::AccountRecord &accrec) { PICA_directc2c_config directc2c_cfg = PICA_DIRECTC2C_CFG_DISABLED; int multilogin = PICA_MULTILOGIN_PROHIBIT; - Settings st(config_dbname); + Settings st(config_dbname, network_sql_connection_name); skynet_account = accrec; - QList<Nodes::NodeRecord> noderecords = nodes.GetNodes(); + QList<Nodes::NodeRecord> noderecords = nodes->GetNodes(); if (!acc) { @@ -429,50 +562,22 @@ void SkyNet::Join(Accounts::AccountRecord &accrec) return; } - directc2c_cfg = (PICA_directc2c_config)st.loadValue("direct_c2c.state", 1).toInt(); - multilogin = st.loadValue("multiple_logins.state", PICA_MULTILOGIN_PROHIBIT).toInt(); - - if (!listener && directc2c_cfg == PICA_DIRECTC2C_CFG_ALLOWINCOMING) - { - int pub_port = st.loadValue("direct_c2c.public_port", 2298).toInt(); - int loc_port = st.loadValue("direct_c2c.local_port", 2298).toInt(); - QString public_addr = st.loadValue("direct_c2c.public_addr", "autoconfigure").toString(); + DirectC2CSettings dcs; - if (public_addr.contains("autoconfigure")) - { - in_addr_t guess; - struct in_addr in; - - guess = PICA_guess_listening_addr_ipv4(); - in.s_addr = guess; - public_addr = QString(inet_ntoa(in)); -#ifdef HAVE_LIBMINIUPNPC - if (st.loadValue("direct_c2c.upnp_enabled", 1).toBool() && PICA_is_reserved_addr_ipv4(guess)) - { - int ret; - char public_ip[64]; - ret = PICA_upnp_autoconfigure_ipv4(pub_port, loc_port, public_ip); + dcs.load(st); - if (ret) - { - public_addr = QString(public_ip); - } - } -#endif - emit StatusMsg(QString(tr("Using autoconfigured address %1 port %2 for incoming direct connections")).arg(public_addr).arg(pub_port), false); - } + multilogin = st.loadValue("multiple_logins.state", PICA_MULTILOGIN_PROHIBIT).toInt(); - int ret = PICA_new_listener(acc, - public_addr.toLatin1().constData(), - pub_port, - loc_port, &listener); - if (ret != PICA_OK) - { - emit StatusMsg(QString(tr("Failed to open port %1 for incoming direct connections")).arg(loc_port), true); - directc2c_cfg = PICA_DIRECTC2C_CFG_CONNECTONLY; - } + // joined from listener_ready(), once the listener is there + if (sync_listener(dcs, true)) + { + join_deferred = true; + return; } + join_deferred = false; + directc2c_cfg = effective_directc2c_config(dcs.state); + if (!connecting_nodes.empty()) { for (int i = 0; i < connecting_nodes.size(); i++) @@ -498,20 +603,171 @@ void SkyNet::Join(Accounts::AccountRecord &accrec) node_status_changed(noderecords[i], false); } } - /* - for (int i=0;i<nodelist.count() && !self_aware;i++) - {//TODO FIXME сделать запуск потоков порциями, а не все сразу - threads.append(new NodeThread(nodelist[i],&self_aware, acc,&nodelink, &write_mutex)); - connect(threads.last(), SIGNAL(finished()),this,SLOT(nodethread_finished())); - connect(threads.last(), SIGNAL(NodeStatusChanged(QString,quint16,bool)), this, SLOT(node_status_changed(QString,quint16,bool))); - connect(threads.last(), SIGNAL(ConnectedToNode(QString,quint16,NodeThread*)), this, SLOT(nodethread_connected(QString,quint16,NodeThread*))); - connect(threads.last(), SIGNAL(ErrorMsg(QString)), this, SIGNAL(ErrMsgFromNode(QString))); - }*/ - } void SkyNet::Exit() { + QMetaObject::invokeMethod(this, "do_Exit", Qt::AutoConnection); +} + +void SkyNet::ApplyDirectC2CSettings() +{ + QMetaObject::invokeMethod(this, "do_ApplyDirectC2CSettings", Qt::AutoConnection); +} + +void SkyNet::do_ApplyDirectC2CSettings() +{ + Settings st(config_dbname, network_sql_connection_name); + DirectC2CSettings dcs; + + dcs.load(st); + + // the user may have just fixed what made it fail + listener_failed = false; + + // Offline, do_Join() sets the listener up when it is time to. + sync_listener(dcs, online()); + + set_nodelinks_directc2c(dcs.state); +} + +bool SkyNet::online() const +{ + return self_aware || !connecting_nodes.isEmpty(); +} + +bool SkyNet::sync_listener(const DirectC2CSettings &dcs, bool start) +{ + bool wanted = dcs.state == PICA_DIRECTC2C_CFG_ALLOWINCOMING; + + if (listener && (!wanted || !dcs.sameListener(listener_cfg))) + drop_listener(); + + // One being set up for settings that have changed since is dealt with + // in listener_ready(). + if (listener_setup_pending) + return true; + + if (!wanted || listener || listener_failed || !start) + return false; + + start_listener_setup(dcs); + + return true; +} + +void SkyNet::start_listener_setup(const DirectC2CSettings &dcs) +{ + listener_cfg = dcs; + listener_setup_pending = true; + + QMetaObject::invokeMethod(direct_listener, "setup", Qt::QueuedConnection, + Q_ARG(quintptr, (quintptr)acc), + Q_ARG(int, dcs.addrConfig), + Q_ARG(bool, dcs.upnp), + Q_ARG(int, dcs.localPort), + Q_ARG(QString, DirectC2CSettings::formatAddrs(dcs.addrs))); +} + +void SkyNet::drop_listener() +{ + struct PICA_listener *l = listener; + + listener = NULL; + + // no node connection may refer to it once it is closed + set_nodelinks_directc2c(listener_cfg.state); + + PICA_close_listener(l); + + // deletes the UPnP port mapping + QMetaObject::invokeMethod(direct_listener, "release", Qt::QueuedConnection); + + emit StatusMsg(tr("Stopped listening for incoming direct connections"), false); +} + +PICA_directc2c_config SkyNet::effective_directc2c_config(int state) const +{ + if (state == PICA_DIRECTC2C_CFG_ALLOWINCOMING && !listener) + return PICA_DIRECTC2C_CFG_CONNECTONLY; + + return (PICA_directc2c_config)state; +} + +void SkyNet::set_nodelinks_directc2c(int state) +{ + PICA_directc2c_config cfg = effective_directc2c_config(state); + + if (active_nodelink) + PICA_c2n_set_directc2c(active_nodelink, cfg, listener); + + for (int i = 0; i < connecting_nodes.size(); i++) + PICA_c2n_set_directc2c(connecting_nodes[i].first, cfg, listener); +} + +void SkyNet::listener_ready(quintptr l, QString upnp_addr, int upnp_port) +{ + Settings st(config_dbname, network_sql_connection_name); + DirectC2CSettings dcs; + + listener_setup_pending = false; + + dcs.load(st); + + if (dcs.state != PICA_DIRECTC2C_CFG_ALLOWINCOMING || !dcs.sameListener(listener_cfg)) + { + // the settings changed while it was being set up + if (l) + { + PICA_close_listener((struct PICA_listener *)l); + QMetaObject::invokeMethod(direct_listener, "release", Qt::QueuedConnection); + } + + if (sync_listener(dcs, join_deferred || online())) + return; + } + else if (l) + { + listener = (struct PICA_listener *)l; + + // also when there is no mapping: a change reported for the mapping + // of a listener closed before may have arrived in between + PICA_listener_set_upnp_addr(listener, upnp_addr.isEmpty() ? NULL : upnp_addr.toLatin1().constData(), + upnp_port); + } + else + { + // connect-only until the settings are changed or the client is + // restarted, rather than failing again on every reconnection + listener_failed = true; + } + + if (join_deferred) + do_Join(skynet_account); + else + set_nodelinks_directc2c(dcs.state); +} + +void SkyNet::listener_upnp_changed(QString upnp_addr, int upnp_port) +{ + if (!listener) + return; + + if (upnp_addr.isEmpty()) + PICA_listener_set_upnp_addr(listener, NULL, 0); + else + PICA_listener_set_upnp_addr(listener, upnp_addr.toLatin1().constData(), upnp_port); +} + +void SkyNet::listener_status_msg(QString msg, bool is_critical) +{ + emit StatusMsg(msg, is_critical); +} + +void SkyNet::do_Exit() +{ + join_deferred = false; + if (self_aware && active_nodelink) { PICA_close_c2n(active_nodelink); @@ -521,6 +777,7 @@ void SkyNet::Exit() self_aware = false; active_filetransfers_reset(); + call_active_set(false, QByteArray()); msgqueues.clear(); @@ -532,12 +789,13 @@ void SkyNet::Exit() emit LostSelfAwareness(); } -bool SkyNet::isSelfAware() +void SkyNet::SendFile(QByteArray to, QString filepath) { - return self_aware; + QMetaObject::invokeMethod(this, "do_SendFile", Qt::AutoConnection, + Q_ARG(QByteArray, to), Q_ARG(QString, filepath)); } -void SkyNet::SendFile(QByteArray to, QString filepath) +void SkyNet::do_SendFile(QByteArray to, QString filepath) { int ret = PICA_OK; struct PICA_c2c *iptr; @@ -582,6 +840,12 @@ void SkyNet::SendFile(QByteArray to, QString filepath) void SkyNet::AcceptFile(QByteArray from, QString filepath) { + QMetaObject::invokeMethod(this, "do_AcceptFile", Qt::AutoConnection, + Q_ARG(QByteArray, from), Q_ARG(QString, filepath)); +} + +void SkyNet::do_AcceptFile(QByteArray from, QString filepath) +{ int ret = PICA_OK; struct PICA_c2c *iptr; @@ -596,13 +860,19 @@ void SkyNet::AcceptFile(QByteArray from, QString filepath) //show error somewhere somehow } else - active_filetransfers_up(); + active_filetransfers_up(from, false); } } void SkyNet::DenyFile(QByteArray from) { + QMetaObject::invokeMethod(this, "do_DenyFile", Qt::AutoConnection, + Q_ARG(QByteArray, from)); +} + +void SkyNet::do_DenyFile(QByteArray from) +{ int ret = PICA_OK; struct PICA_c2c *iptr; @@ -622,6 +892,12 @@ void SkyNet::DenyFile(QByteArray from) void SkyNet::PauseFile(QByteArray peer_id, bool pause_sending) { + QMetaObject::invokeMethod(this, "do_PauseFile", Qt::AutoConnection, + Q_ARG(QByteArray, peer_id), Q_ARG(bool, pause_sending)); +} + +void SkyNet::do_PauseFile(QByteArray peer_id, bool pause_sending) +{ int ret = PICA_OK; struct PICA_c2c *iptr; @@ -641,6 +917,12 @@ void SkyNet::PauseFile(QByteArray peer_id, bool pause_sending) void SkyNet::ResumeFile(QByteArray peer_id, bool resume_sending) { + QMetaObject::invokeMethod(this, "do_ResumeFile", Qt::AutoConnection, + Q_ARG(QByteArray, peer_id), Q_ARG(bool, resume_sending)); +} + +void SkyNet::do_ResumeFile(QByteArray peer_id, bool resume_sending) +{ int ret = PICA_OK; struct PICA_c2c *iptr; @@ -659,6 +941,12 @@ void SkyNet::ResumeFile(QByteArray peer_id, bool resume_sending) void SkyNet::CancelFile(QByteArray peer_id, bool cancel_sending) { + QMetaObject::invokeMethod(this, "do_CancelFile", Qt::AutoConnection, + Q_ARG(QByteArray, peer_id), Q_ARG(bool, cancel_sending)); +} + +void SkyNet::do_CancelFile(QByteArray peer_id, bool cancel_sending) +{ int ret = PICA_OK; struct PICA_c2c *iptr; @@ -677,6 +965,12 @@ void SkyNet::CancelFile(QByteArray peer_id, bool cancel_sending) void SkyNet::SendMessage(QByteArray to, QString msg) { + QMetaObject::invokeMethod(this, "do_SendMessage", Qt::AutoConnection, + Q_ARG(QByteArray, to), Q_ARG(QString, msg)); +} + +void SkyNet::do_SendMessage(QByteArray to, QString msg) +{ int ret = PICA_OK; struct PICA_c2c *iptr; @@ -718,6 +1012,221 @@ void SkyNet::SendMessage(QByteArray to, QString msg) } +void SkyNet::AcceptCall(QByteArray from) +{ + QMetaObject::invokeMethod(this, "do_AcceptCall", Qt::AutoConnection, + Q_ARG(QByteArray, from)); +} + +void SkyNet::do_AcceptCall(QByteArray from) +{ + int ret = PICA_OK; + struct PICA_c2c *iptr; + + if ((iptr = find_active_chan(from))) + { + ret = PICA_pickup_call(iptr); + + if (ret != PICA_OK) + emit CallFailed(from, QString(tr("Failed to pickup the call: %1")).arg(ret)); + else + call_active_set(true, from); + + return; + } + + /* the connection the call came in on is gone */ + emit CallFailed(from, QString(tr("Failed to pickup the call: not connected"))); +} + +void SkyNet::RejectCall(QByteArray from) +{ + QMetaObject::invokeMethod(this, "do_RejectCall", Qt::AutoConnection, + Q_ARG(QByteArray, from)); +} + +void SkyNet::do_RejectCall(QByteArray from) +{ + int ret = PICA_OK; + struct PICA_c2c *iptr; + + if ((iptr = find_active_chan(from))) + { + ret = PICA_reject_call(iptr); + + /* the caller gave up first - nothing left to reject */ + if (ret != PICA_OK && ret != PICA_ERRCALLNOTINPROGRESS) + emit CallFailed(from, QString(tr("Failed to reject the call: %1")).arg(ret)); + + call_active_set(false, from); + + return; + } + +} + +void SkyNet::HangupCall(QByteArray with) +{ + QMetaObject::invokeMethod(this, "do_HangupCall", Qt::AutoConnection, + Q_ARG(QByteArray, with)); +} + +void SkyNet::do_HangupCall(QByteArray with) +{ + int ret = PICA_OK; + struct PICA_c2c *iptr; + + /* hung up while still connecting to the peer - do not start the call + once the connection is there */ + if (is_call_waiting_for(with)) + call_waiting_c2c_connect = false; + + if ((iptr = find_active_chan(with))) + { + ret = PICA_hangup_call(iptr); + + /* the other side ended the call first - nothing left to hang up */ + if (ret != PICA_OK && ret != PICA_ERRCALLNOTINPROGRESS) + emit CallFailed(with, QString(tr("Failed to hang up the call: %1")).arg(ret)); + + call_active_set(false, with); + + return; + } + +} + +void SkyNet::SendAudioParams(QByteArray to, QString codec, quint16 sample_rate) +{ + QMetaObject::invokeMethod(this, "do_SendAudioParams", Qt::AutoConnection, + Q_ARG(QByteArray, to), Q_ARG(QString, codec), Q_ARG(quint16, sample_rate)); +} + +void SkyNet::do_SendAudioParams(QByteArray to, QString codec, quint16 sample_rate) +{ + struct PICA_c2c *iptr; + + if ((iptr = find_active_chan(to))) + { + PICA_set_call_audio_params(iptr, codec.toLatin1().constData(), sample_rate); + } +} + +void SkyNet::SendAudioPacket(QByteArray to, quint16 seq_num, quint32 timestamp, QByteArray data) +{ + QMetaObject::invokeMethod(this, "do_SendAudioPacket", Qt::AutoConnection, + Q_ARG(QByteArray, to), Q_ARG(quint16, seq_num), Q_ARG(quint32, timestamp), Q_ARG(QByteArray, data)); +} + +void SkyNet::do_SendAudioPacket(QByteArray to, quint16 seq_num, quint32 timestamp, QByteArray data) +{ + struct PICA_c2c *iptr; + + if ((iptr = find_active_chan(to))) + { + PICA_send_audio_packet(iptr, seq_num, timestamp, data.constData(), data.size()); + } +} + +void SkyNet::SendVideoParams(QByteArray to, QString codec, quint16 width, quint16 height) +{ + QMetaObject::invokeMethod(this, "do_SendVideoParams", Qt::AutoConnection, + Q_ARG(QByteArray, to), Q_ARG(QString, codec), Q_ARG(quint16, width), Q_ARG(quint16, height)); +} + +void SkyNet::do_SendVideoParams(QByteArray to, QString codec, quint16 width, quint16 height) +{ + struct PICA_c2c *iptr; + + if ((iptr = find_active_chan(to))) + { + PICA_set_call_video_params(iptr, codec.toLatin1().constData(), width, height); + } +} + +void SkyNet::SendVideoPacket(QByteArray to, quint16 seq_num, quint32 timestamp, QByteArray data) +{ + QMetaObject::invokeMethod(this, "do_SendVideoPacket", Qt::AutoConnection, + Q_ARG(QByteArray, to), Q_ARG(quint16, seq_num), Q_ARG(quint32, timestamp), Q_ARG(QByteArray, data)); +} + +void SkyNet::do_SendVideoPacket(QByteArray to, quint16 seq_num, quint32 timestamp, QByteArray data) +{ + struct PICA_c2c *iptr; + + if ((iptr = find_active_chan(to))) + { + PICA_send_video_packet(iptr, seq_num, timestamp, data.constData(), data.size()); + } +} + +void SkyNet::StartCall(QByteArray to) +{ + QMetaObject::invokeMethod(this, "do_StartCall", Qt::AutoConnection, + Q_ARG(QByteArray, to)); +} + +void SkyNet::do_StartCall(QByteArray to) +{ + if (!self_aware) + { + emit CallFailed(to, QString(tr("Pica Pica client is not online"))); + return; + } + + int ret = PICA_OK; + struct PICA_c2c *iptr; + + if ((iptr = find_active_chan(to))) + { + ret = PICA_start_call(iptr); + + if (ret != PICA_OK) + emit CallFailed(to, QString(tr("Failed to initiate the call: %1")).arg(ret)); + + return; + } + + call_waiting_c2c_connect = true; + call_waiting_to = to; + + struct PICA_c2c *chan = NULL; + + ret = PICA_new_c2c(active_nodelink, (const unsigned char*)to.constData(), NULL, &chan); + + if (ret != PICA_OK) + { + call_waiting_c2c_connect = false; + emit CallFailed(to, QString(tr("Failed to create the C2C connection for the call: %1")).arg(ret)); + } +} + +bool SkyNet::is_call_waiting_for(const QByteArray &peer_id) +{ + if (call_waiting_c2c_connect && call_waiting_to == peer_id) + return true; + + return false; +} + +void SkyNet::continue_start_call() +{ + int ret = PICA_ERRCALLNOTINPROGRESS; + struct PICA_c2c *iptr; + + /* The wait is over whichever way this goes. Left set, it would start a + call again every time a connection to this peer is established. */ + call_waiting_c2c_connect = false; + + if ((iptr = find_active_chan(call_waiting_to))) + { + ret = PICA_start_call(iptr); + } + + if (ret != PICA_OK) + emit CallFailed(call_waiting_to, QString(tr("Failed to initiate the call: %1")).arg(ret)); +} + void SkyNet::flush_queues(QByteArray to) { struct PICA_c2c *chan; @@ -911,6 +1420,56 @@ void SkyNet::emit_ConnectionStatusUpdated(QByteArray peer_id, QString status) emit ConnectionStatusUpdated(peer_id, status); } +void SkyNet::emit_CallFailed(QByteArray peer_id, QString reason) +{ + emit CallFailed(peer_id, reason); +} + +void SkyNet::emit_IncomingCall(QByteArray from) +{ + emit IncomingCall(from); +} + +void SkyNet::emit_CallAccepted(QByteArray by) +{ + emit CallAccepted(by); +} + +void SkyNet::emit_CallRejected(QByteArray by) +{ + emit CallRejected(by); +} + +void SkyNet::emit_CallHungup(QByteArray by) +{ + emit CallHungup(by); +} + +void SkyNet::emit_IncomingAudioParams(QByteArray peer_id, QString codec, quint16 sample_rate) +{ + emit IncomingAudioParams(peer_id, codec, sample_rate); +} + +void SkyNet::emit_IncomingAudioPacket(QByteArray peer_id, quint16 seq_num, quint32 timestamp, QByteArray data) +{ + emit IncomingAudioPacket(peer_id, seq_num, timestamp, data); +} + +void SkyNet::emit_IncomingVideoParams(QByteArray peer_id, QString codec, quint16 width, quint16 height) +{ + emit IncomingVideoParams(peer_id, codec, width, height); +} + +void SkyNet::emit_IncomingVideoPacket(QByteArray peer_id, quint16 seq_num, quint32 timestamp, QByteArray data) +{ + emit IncomingVideoPacket(peer_id, seq_num, timestamp, data); +} + +void SkyNet::emit_CallMediaTransportChanged(QByteArray peer_id, bool direct_udp, QString ciphersuitename, quint32 max_payload) +{ + emit CallMediaTransportChanged(peer_id, direct_udp, ciphersuitename, max_payload); +} + //callbacks void SkyNet::newmsg_cb(const unsigned char *peer_id, const char *msgbuf, unsigned int nb, int type) @@ -927,16 +1486,30 @@ void SkyNet::msgok_cb(const unsigned char *peer_id) void SkyNet::c2c_established_cb(const unsigned char *peer_id, const char *ciphersuitename) { - skynet->reset_c2c_reconnect_timeout(QByteArray((const char*)peer_id, PICA_ID_SIZE)); - skynet->emit_ConnectionStatusUpdated(QByteArray((const char*)peer_id, PICA_ID_SIZE), QString("🔐: %1 c2c").arg(ciphersuitename)); - skynet->flush_queues(QByteArray((const char*)peer_id, PICA_ID_SIZE)); + QByteArray peer((const char*)peer_id, PICA_ID_SIZE); + skynet->reset_c2c_reconnect_timeout(peer); + skynet->emit_ConnectionStatusUpdated(peer, QString("🔐: %1 c2c").arg(ciphersuitename)); + skynet->flush_queues(peer); + + if (skynet->is_call_waiting_for(peer)) + { + skynet->continue_start_call(); + } } void SkyNet::c2c_failed(const unsigned char *peer_id) { - skynet->update_c2c_reconnect_timeout(QByteArray((const char*)peer_id, PICA_ID_SIZE)); - qDebug() << "c2c failed (" << QByteArray((const char*)peer_id, PICA_ID_SIZE).toBase64() << ")\n"; - skynet->emit_ConnectionStatusUpdated(QByteArray((const char*)peer_id, PICA_ID_SIZE), QString(tr("Failed to connect"))); + QByteArray peer((const char*)peer_id, PICA_ID_SIZE); + + skynet->update_c2c_reconnect_timeout(peer); + qDebug() << "c2c failed (" << peer.toBase64() << ")\n"; + skynet->emit_ConnectionStatusUpdated(peer, QString(tr("Failed to connect"))); + + if (skynet->is_call_waiting_for(peer)) + { + skynet->emit_CallFailed(peer, QString(tr("Failed to establish the C2C connection to %1")).arg(QString(peer.toBase64()))); + skynet->call_waiting_c2c_connect = false; + } } int SkyNet::accept_cb(const unsigned char *caller_id) @@ -946,20 +1519,16 @@ int SkyNet::accept_cb(const unsigned char *caller_id) void SkyNet::notfound_cb(const unsigned char *callee_id) { - skynet->update_c2c_reconnect_timeout(QByteArray((const char*)callee_id, PICA_ID_SIZE)); - qDebug() << "not found (" << QByteArray((const char*)callee_id, PICA_ID_SIZE).toBase64() << ")\n"; + QByteArray peer((const char*)callee_id, PICA_ID_SIZE); - /* - if (skynet->msgqueues.contains(callee_id)) + skynet->update_c2c_reconnect_timeout(peer); + qDebug() << "not found (" << peer.toBase64() << ")\n"; + + if (skynet->is_call_waiting_for(peer)) { - while ( ! skynet->msgqueues[callee_id].empty()) - { - skynet->emit_UnableToDeliver(callee_id, skynet->msgqueues[callee_id].last()); - skynet->msgqueues[callee_id].removeLast(); - } - // msgqueues.remove(callee_id) was forgotten + skynet->emit_CallFailed(peer, QString(tr("Requested peer was not found online in the Pica Pica network"))); + skynet->call_waiting_c2c_connect = false; } - */ } void SkyNet::c2c_closed_cb(const unsigned char *peer_id, int reason) @@ -969,12 +1538,14 @@ void SkyNet::c2c_closed_cb(const unsigned char *peer_id, int reason) skynet->emit_c2cClosed(QByteArray((const char*)peer_id, PICA_ID_SIZE)); skynet->emit_ConnectionStatusUpdated(QByteArray((const char*)peer_id, PICA_ID_SIZE), QString(tr("Disconnected"))); + /* a call carried by this connection cannot continue */ + skynet->call_active_set(false, QByteArray((const char*)peer_id, PICA_ID_SIZE)); } void SkyNet::nodelist_cb(int type, void *addr_bin, const char *addr_str, unsigned int port) { Nodes::NodeRecord nr = {addr_str, static_cast<quint16>(port)}; - skynet->nodes.Add(nr); + skynet->nodes->Add(nr); } int SkyNet::peer_cert_verify_cb(const unsigned char *peer_id, const char *cert_pem, unsigned int nb) @@ -1001,7 +1572,7 @@ void SkyNet::accepted_file_cb(const unsigned char *peer_id) { qDebug() << "FILE: file was accepted by remote side\n"; - skynet->active_filetransfers_up(); + skynet->active_filetransfers_up(QByteArray((const char *)peer_id, PICA_ID_SIZE), true); skynet->emit_OutgoingFileRequestAccepted(QByteArray((const char *)peer_id, PICA_ID_SIZE)); } @@ -1026,22 +1597,22 @@ void SkyNet::file_control(const unsigned char *peer_id, unsigned int sender_cmd, switch(sender_cmd) { case PICA_PROTO_FILECONTROL_PAUSE: - skynet->active_filetransfers_down(); + skynet->active_filetransfers_down(QByteArray((const char *)peer_id, PICA_ID_SIZE), false); skynet->emit_IncomingFilePaused(QByteArray((const char *)peer_id, PICA_ID_SIZE)); break; case PICA_PROTO_FILECONTROL_RESUME: - skynet->active_filetransfers_up(); + skynet->active_filetransfers_up(QByteArray((const char *)peer_id, PICA_ID_SIZE), false); skynet->emit_IncomingFileResumed(QByteArray((const char *)peer_id, PICA_ID_SIZE)); break; case PICA_PROTO_FILECONTROL_CANCEL: - skynet->active_filetransfers_down(); + skynet->active_filetransfers_down(QByteArray((const char *)peer_id, PICA_ID_SIZE), false); skynet->emit_IncomingFileCancelled(QByteArray((const char *)peer_id, PICA_ID_SIZE)); break; case PICA_PROTO_FILECONTROL_IOERROR: - skynet->active_filetransfers_down(); + skynet->active_filetransfers_down(QByteArray((const char *)peer_id, PICA_ID_SIZE), false); skynet->emit_IncomingFileIoError(QByteArray((const char *)peer_id, PICA_ID_SIZE)); break; } @@ -1051,22 +1622,22 @@ void SkyNet::file_control(const unsigned char *peer_id, unsigned int sender_cmd, switch(receiver_cmd) { case PICA_PROTO_FILECONTROL_PAUSE: - skynet->active_filetransfers_down(); + skynet->active_filetransfers_down(QByteArray((const char *)peer_id, PICA_ID_SIZE), true); skynet->emit_OutgoingFilePaused(QByteArray((const char *)peer_id, PICA_ID_SIZE)); break; case PICA_PROTO_FILECONTROL_RESUME: - skynet->active_filetransfers_up(); + skynet->active_filetransfers_up(QByteArray((const char *)peer_id, PICA_ID_SIZE), true); skynet->emit_OutgoingFileResumed(QByteArray((const char *)peer_id, PICA_ID_SIZE)); break; case PICA_PROTO_FILECONTROL_CANCEL: - skynet->active_filetransfers_down(); + skynet->active_filetransfers_down(QByteArray((const char *)peer_id, PICA_ID_SIZE), true); skynet->emit_OutgoingFileCancelled(QByteArray((const char *)peer_id, PICA_ID_SIZE)); break; case PICA_PROTO_FILECONTROL_IOERROR: - skynet->active_filetransfers_down(); + skynet->active_filetransfers_down(QByteArray((const char *)peer_id, PICA_ID_SIZE), true); skynet->emit_OutgoingFileIoError(QByteArray((const char *)peer_id, PICA_ID_SIZE)); break; } @@ -1077,7 +1648,7 @@ void SkyNet::file_finished(const unsigned char *peer_id, int sending) { qDebug() << "file_finished callback\n"; - skynet->active_filetransfers_down(); + skynet->active_filetransfers_down(QByteArray((const char *)peer_id, PICA_ID_SIZE), sending); if (sending) skynet->emit_OutgoingFileFinished(QByteArray((const char *)peer_id, PICA_ID_SIZE)); @@ -1114,3 +1685,66 @@ void SkyNet::direct_c2c_established_cb(const unsigned char *peer_id, const char { skynet->emit_ConnectionStatusUpdated(QByteArray((const char*)peer_id, PICA_ID_SIZE), QString("🔐: %1 direct c2c").arg(ciphersuitename)); } + +void SkyNet::incoming_call_cb(const unsigned char *peer_id) +{ + skynet->emit_IncomingCall(QByteArray((const char*)peer_id, PICA_ID_SIZE)); +} + +void SkyNet::call_picked_up_cb(const unsigned char *peer_id) +{ + QByteArray peer((const char*)peer_id, PICA_ID_SIZE); + + skynet->call_active_set(true, peer); + skynet->emit_CallAccepted(peer); +} + +void SkyNet::call_rejected_cb(const unsigned char *peer_id) +{ + QByteArray peer((const char*)peer_id, PICA_ID_SIZE); + + skynet->call_active_set(false, peer); + skynet->emit_CallRejected(peer); +} + +void SkyNet::call_hangup_cb(const unsigned char *peer_id) +{ + QByteArray peer((const char*)peer_id, PICA_ID_SIZE); + + skynet->call_active_set(false, peer); + skynet->emit_CallHungup(peer); +} + +void SkyNet::call_audio_params_cb(const unsigned char *peer_id, const char *codec, uint16_t sample_rate) +{ + skynet->emit_IncomingAudioParams(QByteArray((const char*)peer_id, PICA_ID_SIZE), QString::fromLatin1(codec), sample_rate); +} + +void SkyNet::call_video_params_cb(const unsigned char *peer_id, const char *codec, uint16_t width, uint16_t height) +{ + skynet->emit_IncomingVideoParams(QByteArray((const char*)peer_id, PICA_ID_SIZE), QString::fromLatin1(codec), width, height); +} + +void SkyNet::call_audio_packet_cb(const unsigned char *peer_id, uint16_t seq_num, uint32_t timestamp, uint16_t size, const char *pkt_data) +{ + skynet->emit_IncomingAudioPacket(QByteArray((const char*)peer_id, PICA_ID_SIZE), seq_num, timestamp, QByteArray(pkt_data, size)); +} + +void SkyNet::call_video_packet_cb(const unsigned char *peer_id, uint16_t seq_num, uint32_t timestamp, uint16_t size, const char *pkt_data) +{ + skynet->emit_IncomingVideoPacket(QByteArray((const char*)peer_id, PICA_ID_SIZE), seq_num, timestamp, QByteArray(pkt_data, size)); +} + +void SkyNet::call_media_transport_cb(const unsigned char *peer_id, int transport, const char *ciphersuitename, unsigned int max_payload) +{ + QByteArray peer((const char*)peer_id, PICA_ID_SIZE); + bool direct_udp = (transport == PICA_CALL_TRANSPORT_MEDIAC2C); + + skynet->emit_ConnectionStatusUpdated(peer, direct_udp + ? QString("🔐: %1 media").arg(ciphersuitename) + : QString(tr("call media over the c2c connection"))); + + skynet->emit_CallMediaTransportChanged(peer, direct_udp, + ciphersuitename ? QString::fromLatin1(ciphersuitename) : QString(), + max_payload); +} diff --git a/pica-client/skynet.h b/pica-client/skynet.h index 57baeba..263167a 100644 --- a/pica-client/skynet.h +++ b/pica-client/skynet.h @@ -19,12 +19,17 @@ #include "nodes.h" #include "../PICA_client.h" +#include "../PICA_media.h" #include "../PICA_proto.h" #include "accounts.h" +#include "directlistener.h" +#include "directc2csettings.h" #include <QObject> +#include <QThread> #include <QMap> #include <QVector> #include <QPair> +#include <QSet> class SkyNet : public QObject @@ -32,9 +37,12 @@ class SkyNet : public QObject Q_OBJECT public: SkyNet(); - void Join(Accounts::AccountRecord &accrec); - bool isSelfAware(); + ~SkyNet(); + void Join(const Accounts::AccountRecord &accrec); void Exit(); + // Reads the direct connection settings again, after the settings dialog + // stored them: starts, restarts or stops the listener as they say. + void ApplyDirectC2CSettings(); void SendMessage(QByteArray to, QString msg); void SendFile(QByteArray to, QString filepath); @@ -44,10 +52,16 @@ public: void ResumeFile(QByteArray peer_id, bool resume_sending); void CancelFile(QByteArray peer_id, bool cancel_sending); - Accounts::AccountRecord CurrentAccount() - { - return skynet_account; - }; + void StartCall(QByteArray to); + void AcceptCall(QByteArray from); + void RejectCall(QByteArray from); + void HangupCall(QByteArray with); + + void SendAudioParams(QByteArray to, QString codec, quint16 sample_rate); + void SendAudioPacket(QByteArray to, quint16 seq_num, quint32 timestamp, QByteArray data); + + void SendVideoParams(QByteArray to, QString codec, quint16 width, quint16 height); + void SendVideoPacket(QByteArray to, quint16 seq_num, quint32 timestamp, QByteArray data); signals: void MessageReceived(QByteArray from, QString msg); @@ -78,15 +92,50 @@ signals: void c2cClosed(QByteArray peer_id); + void CallFailed(QByteArray peer_id, QString reason); + void IncomingCall(QByteArray from); + void CallAccepted(QByteArray by); + void CallRejected(QByteArray by); + void CallHungup(QByteArray by); + + void IncomingAudioParams(QByteArray peer_id, QString codec, quint16 sample_rate); + void IncomingAudioPacket(QByteArray peer_id, quint16 seq_num, quint32 timestamp, QByteArray data); + + void IncomingVideoParams(QByteArray peer_id, QString codec, quint16 width, quint16 height); + void IncomingVideoPacket(QByteArray peer_id, quint16 seq_num, quint32 timestamp, QByteArray data); + + /** The media packets of the call started or stopped being carried over a + * direct UDP (mediac2c) connection. max_payload is the largest amount of + * data one media packet can carry from now on. + */ + void CallMediaTransportChanged(QByteArray peer_id, bool direct_udp, QString ciphersuitename, quint32 max_payload); private: - Nodes nodes; + // Constructed in init(), once this SkyNet instance is running on its + // own network thread and that thread's dedicated QSqlDatabase + // connection has been opened - see init() in skynet.cpp. + Nodes *nodes; QList<QPair<struct PICA_c2n *, Nodes::NodeRecord> > connecting_nodes; QList<struct PICA_c2n *> connected_nodes_to_close; bool self_aware; + bool call_waiting_c2c_connect; + QByteArray call_waiting_to; QString status; struct PICA_c2n *active_nodelink; struct PICA_acc *acc; struct PICA_listener *listener; + // Opens the listener and looks after its UPnP mapping on a thread of its + // own, see directlistener.h. The listener is waited for before the nodes + // are connected to, so that the first 0x0B messages already carry the + // external address. + DirectListener *direct_listener; + QThread direct_listener_thread; + bool listener_setup_pending; + bool listener_failed; + // the settings the listener was, or is being, set up for + DirectC2CSettings listener_cfg; + // do_Join() waits for the listener to be set up; cleared by Exit(), so + // that a listener arriving late does not bring the client back online + bool join_deferred; Accounts::AccountRecord skynet_account; QMap<QByteArray, QList<QString> > msgqueues; @@ -96,6 +145,7 @@ private: int event_loop_timer_id; int file_transfer_timer_id; int c2c_reconnect_timer_id; + int call_timer_id; void timerEvent(QTimerEvent * e); @@ -106,10 +156,28 @@ private: struct PICA_c2c *find_active_chan(QByteArray peer_id); QList<QByteArray> filter_existing_chans(QList<QByteArray> peer_ids); bool open_account(); - void active_filetransfers_up(); - void active_filetransfers_down(); + void active_filetransfers_up(QByteArray peer, bool sending); + void active_filetransfers_down(QByteArray peer, bool sending); void active_filetransfers_reset(); quint32 active_filetransfers; + // Peers whose incoming/outgoing transfer currently contributes to + // active_filetransfers. Membership makes up()/down() idempotent, so a + // down() for a transfer that was never counted (a cancel of an offer still + // awaiting acceptance, or a cancel after a pause) cannot underflow the + // counter and leave the zero-interval timer running forever. + QSet<QByteArray> counted_ft_in; + QSet<QByteArray> counted_ft_out; + + /* Only one call can be in progress at a time, so this is a flag and not + * a counter like active_filetransfers. + */ + void call_active_set(bool active, QByteArray peer); + bool call_active; + QByteArray call_active_peer; + + void continue_start_call(); + // check if there is a call waiting to be initiated with peer_id + bool is_call_waiting_for(const QByteArray &peer_id); void emit_MessageReceived(QByteArray from, QString msg); void emit_UnableToDeliver(QByteArray to, QString msg); @@ -136,17 +204,30 @@ private: void emit_c2cClosed(QByteArray peer_id); void emit_ConnectionStatusUpdated(QByteArray peer_id, QString status); - //получение сообщения. + void emit_CallFailed(QByteArray peer_id, QString reason); + void emit_IncomingCall(QByteArray from); + void emit_CallAccepted(QByteArray by); + void emit_CallRejected(QByteArray by); + void emit_CallHungup(QByteArray by); + + void emit_IncomingAudioParams(QByteArray peer_id, QString codec, quint16 sample_rate); + void emit_IncomingAudioPacket(QByteArray peer_id, quint16 seq_num, quint32 timestamp, QByteArray data); + + void emit_IncomingVideoParams(QByteArray peer_id, QString codec, quint16 width, quint16 height); + void emit_IncomingVideoPacket(QByteArray peer_id, quint16 seq_num, quint32 timestamp, QByteArray data); + + void emit_CallMediaTransportChanged(QByteArray peer_id, bool direct_udp, QString ciphersuitename, quint32 max_payload); + static void newmsg_cb(const unsigned char *peer_id, const char* msgbuf, unsigned int nb, int type); - //получение подтверждения о доставке сообщения + static void msgok_cb(const unsigned char *peer_id); - //создание канала с собеседником + static void c2c_established_cb(const unsigned char *peer_id, const char *ciphersuitename); - //создать канал не удалось + static void c2c_failed(const unsigned char *peer_id); - //входящий запрос на создание канала от пользователя с номером caller_id + static int accept_cb(const unsigned char *caller_id); - //запрошенный пользователь не найден, в оффлайне или отказался от общения + static void notfound_cb(const unsigned char *callee_id); static void c2c_closed_cb(const unsigned char *peer_id, int reason); @@ -179,6 +260,36 @@ private: static void direct_c2c_established_cb(const unsigned char *peer_id, const char *ciphersuitename); + static void incoming_call_cb(const unsigned char *peer_id); + + static void call_picked_up_cb(const unsigned char *peer_id); + + static void call_rejected_cb(const unsigned char *peer_id); + + static void call_hangup_cb(const unsigned char *peer_id); + + static void call_audio_params_cb(const unsigned char *peer_id, const char *codec, uint16_t sample_rate); + + static void call_video_params_cb(const unsigned char *peer_id, const char *codec, uint16_t width, uint16_t height); + + static void call_audio_packet_cb(const unsigned char *peer_id, uint16_t seq_num, uint32_t timestamp, uint16_t size, const char *pkt_data); + + static void call_video_packet_cb(const unsigned char *peer_id, uint16_t seq_num, uint32_t timestamp, uint16_t size, const char *pkt_data); + + static void call_media_transport_cb(const unsigned char *peer_id, int transport, const char *ciphersuitename, unsigned int max_payload); + + bool online() const; + // Closes a listener that dcs no longer want and, with start set, begins + // setting up the one they do. Returns whether a listener is being set + // up, i.e. there will be one to wait for. + bool sync_listener(const DirectC2CSettings &dcs, bool start); + void start_listener_setup(const DirectC2CSettings &dcs); + void drop_listener(); + // what the node connections are told: connect-only while there is no + // listener for incoming connections + PICA_directc2c_config effective_directc2c_config(int state) const; + void set_nodelinks_directc2c(int state); + private slots: void nodelink_activated(PICA_c2n *c2n); void nodelink_closed(PICA_c2n *c2n, int error); @@ -186,8 +297,57 @@ private slots: void multilogin_event(quint64 timestamp, QString node_addr, quint16 node_port); void node_status_changed(Nodes::NodeRecord nr, bool alive); + + void listener_ready(quintptr l, QString upnp_addr, int upnp_port); + void listener_upnp_changed(QString upnp_addr, int upnp_port); + void listener_status_msg(QString msg, bool is_critical); void verify_peer_cert(QByteArray peer_id, QString cert_pem, bool *verified); + // Connected to the network thread's QThread::started() signal. Runs + // once, on the network thread itself, right before that thread's + // event loop starts. Anything that needs to be tied to the network + // thread rather than whatever thread constructed this SkyNet + // instance - the event-loop timers and this object's own QSqlDatabase + // connection - is set up here instead of in the constructor. + void init(); + + // QObject::moveToThread() only succeeds when called from the thread + // the object is currently affiliated with - it cannot be "pulled" in + // from a different thread. So reclaiming this object for the main + // thread at shutdown has to happen via a call executed here, on the + // network thread itself (see main.cpp, invoked with + // Qt::BlockingQueuedConnection before the network thread is stopped), + // rather than by calling moveToThread() directly from main(). + void moveBackToMainThread(); + + // Actual implementations behind the public action methods below. + // The public methods only forward here via QMetaObject::invokeMethod() + // with Qt::AutoConnection, so callers on any thread are automatically + // marshaled onto whichever thread this SkyNet instance lives on - + // direct call if already on that thread, queued otherwise. + void do_Join(const Accounts::AccountRecord &accrec); + void do_Exit(); + void do_ApplyDirectC2CSettings(); + + void do_SendMessage(QByteArray to, QString msg); + void do_SendFile(QByteArray to, QString filepath); + void do_AcceptFile(QByteArray from, QString filepath); + void do_DenyFile(QByteArray from); + void do_PauseFile(QByteArray peer_id, bool pause_sending); + void do_ResumeFile(QByteArray peer_id, bool resume_sending); + void do_CancelFile(QByteArray peer_id, bool cancel_sending); + + void do_StartCall(QByteArray to); + void do_AcceptCall(QByteArray from); + void do_RejectCall(QByteArray from); + void do_HangupCall(QByteArray with); + + void do_SendAudioParams(QByteArray to, QString codec, quint16 sample_rate); + void do_SendAudioPacket(QByteArray to, quint16 seq_num, quint32 timestamp, QByteArray data); + + void do_SendVideoParams(QByteArray to, QString codec, quint16 width, quint16 height); + void do_SendVideoPacket(QByteArray to, quint16 seq_num, quint32 timestamp, QByteArray data); + }; #endif // SKYNET_H diff --git a/pica-client/toneplayer/toneplayer.cpp b/pica-client/toneplayer/toneplayer.cpp new file mode 100644 index 0000000..298686a --- /dev/null +++ b/pica-client/toneplayer/toneplayer.cpp @@ -0,0 +1,529 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#include "toneplayer.h" +#include "../audiodevice.h" +#include "../nativeaudio.h" + +#include <QDebug> +#include <QVector> +#include <cmath> + +// FFmpeg headers +extern "C" { +#include <libavformat/avformat.h> +#include <libavdevice/avdevice.h> +#include <libavcodec/avcodec.h> +#include <libavutil/opt.h> +#include <libavutil/channel_layout.h> +#include <libavutil/samplefmt.h> +#include <libavutil/frame.h> +#include <libavutil/mem.h> +#include <libavutil/error.h> +} + +// FFmpeg 5.1 (libavutil 57.24.100) replaced AVCodecContext/AVFrame's +// channels + channel_layout fields with the AVChannelLayout ch_layout API. +// The old fields were deprecated then and removed outright in FFmpeg 7.0. +// The legacy branch keeps us building on FFmpeg 4.x (Ubuntu 20.04 / 22.04). +#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 24, 100) +# define TP_HAVE_CH_LAYOUT 1 +#else +# define TP_HAVE_CH_LAYOUT 0 +#endif + +TonePlayer::TonePlayer(QObject *parent) + : QObject(parent), + m_abort(0), + m_deviceName("default"), + m_sampleRate(48000), + m_channels(1), // mono + m_volume(0.6) +{ +} + +TonePlayer::~TonePlayer() +{ + stop(); +} + +void TonePlayer::setSequence(const QVector<Tone> &sequence) +{ + m_sequence = sequence; +} + +void TonePlayer::stop() +{ + m_abort.storeRelaxed(1); +} + +void TonePlayer::setDeviceName(const QString &deviceName) +{ + m_deviceName = deviceName; +} + +void TonePlayer::setSampleRate(int sampleRate) +{ + m_sampleRate = sampleRate; +} + +void TonePlayer::setVolume(double vol) +{ + m_volume = qBound(0.0, vol, 1.0); +} + +void TonePlayer::playSequence(const QVector<Tone> &sequence) +{ + m_sequence = sequence; + m_abort.storeRelaxed(0); + play(); +} + +void TonePlayer::playCallInProgress() +{ + // "440:1500,0:3000,440:1500,0:3000,440:1500,0:0" + QVector<Tone> seq; + seq << Tone(440.0, 1500) << Tone(0.0, 3000) + << Tone(440.0, 1500) << Tone(0.0, 3000) + << Tone(440.0, 1500) << Tone(0.0, 0); + playSequence(seq); +} + +void TonePlayer::playUnreachable() +{ + // "950:330,1400:330,1800:330,0:0" + QVector<Tone> seq; + seq << Tone(950.0, 330) << Tone(1400.0, 330) << Tone(1800.0, 330) + << Tone(0.0, 0); + playSequence(seq); +} + +void TonePlayer::playBusy() +{ + // "440:400,0:400,440:400,0:400,440:400,0:0" + QVector<Tone> seq; + seq << Tone(440.0, 400) << Tone(0.0, 400) + << Tone(440.0, 400) << Tone(0.0, 400) + << Tone(440.0, 400) << Tone(0.0, 0); + playSequence(seq); +} + +void TonePlayer::playClassicRingtone() +{ + // Unlike playCallInProgress/playUnreachable/playBusy, which are steady + // single-frequency tones heard in the earpiece, this imitates the sound + // of an electromechanical bell ringer: the clapper striking the gongs + // produces a fast warble between two close pitches rather than one pure + // tone. We approximate that by alternating two frequencies every 40 ms + // (~12.5 Hz trill) for the classic 2 s on / 4 s off cadence, 3 bursts. + const int trillSegment_ms = 40; + const int ringDuration_ms = 2000; + const int silenceDuration_ms = 4000; + const double freqA = 1000.0; + const double freqB = 1200.0; + const int bursts = 3; + + QVector<Tone> seq; + for (int burst = 0; burst < bursts; ++burst) { + for (int t = 0; t < ringDuration_ms; t += trillSegment_ms) { + int segLen = qMin(trillSegment_ms, ringDuration_ms - t); + double freq = ((t / trillSegment_ms) % 2 == 0) ? freqA : freqB; + seq << Tone(freq, segLen); + } + seq << Tone(0.0, burst == bursts - 1 ? 0 : silenceDuration_ms); + } + playSequence(seq); +} + +static QString ff_errstr(int err) +{ + char buf[256] = {0}; + av_strerror(err, buf, sizeof(buf)); + return QString::fromLocal8Bit(buf); +} + +void TonePlayer::renderBlock(const Tone &t, double &phase, int nb_samples, int channels, qint16 *out) +{ + const double two_pi = 2.0 * M_PI; + double phase_inc = 0.0; + + if (t.frequency > 0.0) + phase_inc = two_pi * t.frequency / double(m_sampleRate); + + for (int i = 0; i < nb_samples; ++i) { + double sampleVal = 0.0; + if (t.frequency > 0.0) { + sampleVal = sin(phase) * m_volume; + phase += phase_inc; + if (phase > 1e9 || phase < -1e9) phase = fmod(phase, two_pi); + } + + int16_t ival = static_cast<int16_t>(qBound(-1.0, sampleVal, 1.0) * 32767.0); + for (int ch = 0; ch < channels; ++ch) { + out[i * channels + ch] = ival; + } + } +} + +void TonePlayer::play() +{ + if (m_sequence.isEmpty()) { + emit finishedPlaying(); + return; + } + + const QString driver = AudioDevice::PlatformDriverName(PLAYBACK); + + if (AudioDevice::IsPlatformDriver(driver)) + playNative(AudioDevice::PlatformApiName(driver)); + else + playFFmpeg(driver); +} + +void TonePlayer::playNative(const QString &api) +{ + NativeAudioBackend *backend = NativeAudioBackend::create(api); + if (!backend) { + QString msg = QString("No '%1' audio backend in this build").arg(api); + qWarning() << msg; + emit errorOccured(msg); + emit finishedPlaying(); + return; + } + + QString err; + if (!backend->openPlayback(m_deviceName, m_sampleRate, m_channels, NativeAudioPlain, &err)) { + qWarning() << err; + emit errorOccured(err); + delete backend; + emit finishedPlaying(); + return; + } + + // 20 ms a time, so stop() is acted on promptly without the write loop + // spinning. + const int blockFrames = m_sampleRate / 50; + QVector<qint16> block(blockFrames * m_channels); + double phase = 0.0; + + for (int idx = 0; idx < m_sequence.size(); ++idx) { + if (m_abort.loadRelaxed()) break; + + const Tone &t = m_sequence[idx]; + if (t.frequency == 0.0 && t.duration_ms == 0) + break; + if (t.duration_ms <= 0) + continue; + + int64_t total_samples = (int64_t)qRound((m_sampleRate * t.duration_ms) / 1000.0); + int64_t samples_written = 0; + + while (samples_written < total_samples) { + if (m_abort.loadRelaxed()) break; + + int nb_samples = blockFrames; + if (nb_samples > (int)(total_samples - samples_written)) + nb_samples = int(total_samples - samples_written); + + renderBlock(t, phase, nb_samples, m_channels, block.data()); + + if (backend->write(block.constData(), nb_samples * m_channels, 200) < 0) { + qWarning() << "Native tone playback write failed"; + samples_written = total_samples; + idx = m_sequence.size(); + break; + } + + samples_written += nb_samples; + } + } + + // Let what is still sitting in the device buffer be heard rather than + // being cut off by close(). One buffer's worth is the most it can be. + if (!m_abort.loadRelaxed()) { + memset(block.data(), 0, block.size() * sizeof(qint16)); + backend->write(block.constData(), block.size(), 200); + } + + backend->close(); + delete backend; + + emit finishedPlaying(); +} + +void TonePlayer::playFFmpeg(const QString &driver) +{ + avdevice_register_all(); +#if LIBAVFORMAT_VERSION_MAJOR < 58 + av_register_all(); + avcodec_register_all(); +#endif + + AVFormatContext *oc = nullptr; + const QByteArray deviceUtf8 = m_deviceName.toUtf8(); + const char *device = deviceUtf8.constData(); + const QByteArray driverUtf8 = driver.toUtf8(); + const char *driverName = driverUtf8.constData(); + + int ret = avformat_alloc_output_context2(&oc, nullptr, driverName, device); + if (ret < 0 || !oc) { + QString msg = QString("Could not allocate '%1' output context: %2").arg(driver, ff_errstr(ret)); + qWarning() << msg; + emit errorOccured(msg); + return; + } + + const AVCodecID codec_id = AV_CODEC_ID_PCM_S16LE; + const AVCodec *codec = avcodec_find_encoder(codec_id); + if (!codec) { + QString msg = "PCM encoder not found"; + qWarning() << msg; + emit errorOccured(msg); + avformat_free_context(oc); + return; + } + + AVCodecContext *codecCtx = avcodec_alloc_context3(codec); + if (!codecCtx) { + QString msg = "Could not alloc codec context"; + qWarning() << msg; + emit errorOccured(msg); + avformat_free_context(oc); + return; + } + + codecCtx->sample_fmt = AV_SAMPLE_FMT_S16; + codecCtx->sample_rate = m_sampleRate; +#if TP_HAVE_CH_LAYOUT + av_channel_layout_default(&codecCtx->ch_layout, m_channels); +#else + codecCtx->channels = m_channels; + codecCtx->channel_layout = av_get_default_channel_layout(m_channels); +#endif + codecCtx->time_base = AVRational{1, m_sampleRate}; + + if ((ret = avcodec_open2(codecCtx, codec, nullptr)) < 0) { + QString msg = QString("Could not open codec: %1").arg(ff_errstr(ret)); + qWarning() << msg; + emit errorOccured(msg); + avcodec_free_context(&codecCtx); + avformat_free_context(oc); + return; + } + + AVStream *st = avformat_new_stream(oc, nullptr); + if (!st) { + QString msg = "Could not create stream"; + qWarning() << msg; + emit errorOccured(msg); + avcodec_free_context(&codecCtx); + avformat_free_context(oc); + return; + } + + if ((ret = avcodec_parameters_from_context(st->codecpar, codecCtx)) < 0) { + QString msg = QString("Failed to copy codec params: %1").arg(ff_errstr(ret)); + qWarning() << msg; + emit errorOccured(msg); + avcodec_free_context(&codecCtx); + avformat_free_context(oc); + return; + } + st->time_base = codecCtx->time_base; + + if (!(oc->oformat->flags & AVFMT_NOFILE)) { + if ((ret = avio_open(&oc->pb, device, AVIO_FLAG_WRITE)) < 0) { + QString msg = QString("Could not open '%1' device '%2': %3").arg(driver, m_deviceName, ff_errstr(ret)); + qWarning() << msg; + emit errorOccured(msg); + avcodec_free_context(&codecCtx); + avformat_free_context(oc); + return; + } + } + + if ((ret = avformat_write_header(oc, nullptr)) < 0) { + QString msg = QString("Error writing header: %1").arg(ff_errstr(ret)); + qWarning() << msg; + emit errorOccured(msg); + if (!(oc->oformat->flags & AVFMT_NOFILE)) avio_closep(&oc->pb); + avcodec_free_context(&codecCtx); + avformat_free_context(oc); + return; + } + + AVFrame *frame = av_frame_alloc(); + if (!frame) { + QString msg = "Could not allocate AVFrame"; + qWarning() << msg; + emit errorOccured(msg); + if (!(oc->oformat->flags & AVFMT_NOFILE)) avio_closep(&oc->pb); + avcodec_free_context(&codecCtx); + avformat_free_context(oc); + return; + } + + frame->format = codecCtx->sample_fmt; + frame->sample_rate = codecCtx->sample_rate; +#if TP_HAVE_CH_LAYOUT + if ((ret = av_channel_layout_copy(&frame->ch_layout, &codecCtx->ch_layout)) < 0) { + QString msg = QString("Could not copy channel layout to frame: %1").arg(ff_errstr(ret)); + qWarning() << msg; + emit errorOccured(msg); + if (!(oc->oformat->flags & AVFMT_NOFILE)) avio_closep(&oc->pb); + av_frame_free(&frame); + avcodec_free_context(&codecCtx); + avformat_free_context(oc); + return; + } +#else + frame->channels = codecCtx->channels; + frame->channel_layout = codecCtx->channel_layout; +#endif + + int frame_size = codecCtx->frame_size; + if (frame_size <= 0) frame_size = 1024; + + frame->nb_samples = frame_size; + if ((ret = av_frame_get_buffer(frame, 0)) < 0) { + QString msg = QString("Could not allocate initial frame buffer: %1 (frame_size=%2)") + .arg(ff_errstr(ret)).arg(frame_size); + qWarning() << msg; + emit errorOccured(msg); + if (!(oc->oformat->flags & AVFMT_NOFILE)) avio_closep(&oc->pb); + av_frame_free(&frame); + avcodec_free_context(&codecCtx); + avformat_free_context(oc); + return; + } + + int64_t pts = 0; + double phase = 0.0; + +#if TP_HAVE_CH_LAYOUT + int chs = codecCtx->ch_layout.nb_channels; +#else + int chs = codecCtx->channels; +#endif + if (chs <= 0) chs = 1; + + for (int idx = 0; idx < m_sequence.size(); ++idx) { + if (m_abort.loadRelaxed()) break; + + const Tone &t = m_sequence[idx]; + if (t.frequency == 0.0 && t.duration_ms == 0) { + break; + } + + if (t.duration_ms <= 0) continue; + + int64_t total_samples = (int64_t)qRound((m_sampleRate * t.duration_ms) / 1000.0); + int64_t samples_written = 0; + + while (samples_written < total_samples) { + if (m_abort.loadRelaxed()) break; + + int nb_samples = frame_size; + if (nb_samples > (int)(total_samples - samples_written)) + nb_samples = int(total_samples - samples_written); + + if ((ret = av_frame_make_writable(frame)) < 0) { + QString msg = QString("av_frame_make_writable failed: %1").arg(ff_errstr(ret)); + qWarning() << msg; + emit errorOccured(msg); + break; + } + frame->nb_samples = nb_samples; + + renderBlock(t, phase, nb_samples, chs, reinterpret_cast<int16_t*>(frame->data[0])); + + frame->pts = pts; + pts += frame->nb_samples; + + ret = avcodec_send_frame(codecCtx, frame); + if (ret < 0) { + QString msg = QString("Error sending frame to encoder: %1").arg(ff_errstr(ret)); + qWarning() << msg; + emit errorOccured(msg); + break; + } + + while (ret >= 0) { + AVPacket *pkt = av_packet_alloc(); + if (!pkt) { + QString msg = "av_packet_alloc failed"; + qWarning() << msg; + emit errorOccured(msg); + ret = AVERROR(ENOMEM); + break; + } + + ret = avcodec_receive_packet(codecCtx, pkt); + if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { + av_packet_free(&pkt); + break; + } else if (ret < 0) { + QString msg = QString("Error encoding audio frame: %1").arg(ff_errstr(ret)); + qWarning() << msg; + emit errorOccured(msg); + av_packet_free(&pkt); + break; + } + + pkt->stream_index = st->index; + + ret = av_interleaved_write_frame(oc, pkt); + if (ret < 0) { + QString msg = QString("Error writing packet to device: %1").arg(ff_errstr(ret)); + qWarning() << msg; + emit errorOccured(msg); + av_packet_free(&pkt); + break; + } + + av_packet_free(&pkt); + } + samples_written += nb_samples; + } + if (m_abort.loadRelaxed()) break; + } + + avcodec_send_frame(codecCtx, nullptr); + while (true) { + AVPacket *pkt = av_packet_alloc(); + if (!pkt) break; + ret = avcodec_receive_packet(codecCtx, pkt); + if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN)) { + av_packet_free(&pkt); + break; + } else if (ret < 0) { + av_packet_free(&pkt); + break; + } + pkt->stream_index = st->index; + av_interleaved_write_frame(oc, pkt); + av_packet_free(&pkt); + } + + av_write_trailer(oc); + + if (!(oc->oformat->flags & AVFMT_NOFILE)) avio_closep(&oc->pb); + av_frame_free(&frame); + avcodec_free_context(&codecCtx); + avformat_free_context(oc); + + emit finishedPlaying(); +} diff --git a/pica-client/toneplayer/toneplayer.h b/pica-client/toneplayer/toneplayer.h new file mode 100644 index 0000000..5c70e15 --- /dev/null +++ b/pica-client/toneplayer/toneplayer.h @@ -0,0 +1,94 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#pragma once + +#include <QObject> +#include <QVector> +#include <QAtomicInt> +#include <QtGlobal> +#include <QString> + +// Simple tone descriptor: frequency in Hz, duration in milliseconds. +struct Tone { + double frequency; // Hz + int duration_ms; // milliseconds + Tone(double f = 0.0, int d = 0): frequency(f), duration_ms(d) {} +}; + +class TonePlayer : public QObject +{ + Q_OBJECT +public: + explicit TonePlayer(QObject *parent = nullptr); + ~TonePlayer() override; + + // Replace the sequence to play. Call before play(). + void setSequence(const QVector<Tone> &sequence); + + // Stop playback early. This will cause play() to return. + Q_INVOKABLE void stop(); + + // Set the platform playback device name (e.g. "default" or "hw:0" on + // ALSA, a CoreAudio/DirectSound device name on macOS/Windows). Default: + // "default". Typically set from the "audio.playback_device" or + // "audio.ring_device" setting (see SettingsDialog). Q_INVOKABLE so it + // can be queued across threads via QMetaObject::invokeMethod(), the + // same way play() is invoked when TonePlayer lives on its own QThread. + Q_INVOKABLE void setDeviceName(const QString &deviceName); + + // Set playback parameters (optional before play) + void setSampleRate(int sampleRate); + void setVolume(double vol); // 0.0 .. 1.0 + +signals: + void finishedPlaying(); + void errorOccured(const QString &err); + +public slots: + void play(); + + // Standard telephony tone sequences. Each replaces the current sequence + // and plays it to completion (blocking, like play()). + void playCallInProgress(); // ringing tone: 440 Hz, 1.5 s on / 3 s off, 3 bursts + void playUnreachable(); // special information tone: 950/1400/1800 Hz, 330 ms each + void playBusy(); // busy tone: 440 Hz, 400 ms on / 400 ms off, 3 bursts + void playClassicRingtone(); // electromechanical bell: warbling trill, 2 s on / 4 s off, 3 bursts + +private: + // Set the sequence, clear any pending stop request and play it. + void playSequence(const QVector<Tone> &sequence); + + // The two ways of getting samples to the speaker, picked apart by + // AudioDevice::PlatformDriverName(PLAYBACK) - see the comment on it. + // Tones always ask for a plain stream rather than a call one: a ringtone + // is not a call, and on macOS asking for the voice processing would open + // the microphone to play it. + void playFFmpeg(const QString &driver); + void playNative(const QString &api); + + // Fills out with nb_samples frames of a sine at the tone's frequency + // (silence when it is zero), carrying phase across calls so consecutive + // blocks of one tone do not click at the seam. + void renderBlock(const Tone &t, double &phase, int nb_samples, int channels, qint16 *out); + + QVector<Tone> m_sequence; + QAtomicInt m_abort; + QString m_deviceName; + int m_sampleRate; + int m_channels; // always 1 (mono) by design + double m_volume; +}; diff --git a/pica-client/vaapi.cpp b/pica-client/vaapi.cpp new file mode 100644 index 0000000..d5dd2f5 --- /dev/null +++ b/pica-client/vaapi.cpp @@ -0,0 +1,330 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#include "vaapi.h" + +#ifdef HAVE_VAAPI + +#include "vaapivideowidget.h" +#ifdef HAVE_VAAPI_X11 +#include "vaapix11widget.h" +#endif + +#include <QMutex> +#include <QMutexLocker> +#include <QDebug> +#ifdef HAVE_VAAPI_X11 +#include <QGuiApplication> +#include <QOffscreenSurface> +#include <QOpenGLContext> +#endif + +extern "C" { +#include <libavutil/hwcontext.h> +#include <libavutil/hwcontext_vaapi.h> +#include <libavutil/error.h> +} + +#ifdef HAVE_VAAPI_X11 +// Included after the Qt headers, since Xlib defines a handful of names as +// macros that Qt also uses as ordinary identifiers. +#include <X11/Xlib.h> +#include <GL/glx.h> +#include <va/va_x11.h> +#undef Bool +#undef Status +#undef None +#undef Success +#undef Always +#undef CursorShape +#undef KeyPress +#undef KeyRelease +#undef FocusIn +#undef FocusOut +#undef Expose +#undef Unsorted +#endif + +namespace +{ + QMutex g_mutex; + // Created on first use and kept for the lifetime of the process: opening a + // VAAPI device is not cheap, and every user of it has to share the one + // display anyway. + AVBufferRef *g_device = nullptr; + bool g_tried = false; + bool g_usesX11 = false; + +#ifdef HAVE_VAAPI_X11 + // Qt's own X connection, found at startup by detectX11Display(), and only + // when Qt's OpenGL contexts turned out to be GLX ones. Owned by Qt. + // + // Using Qt's connection rather than one of our own means the windows the + // driver is asked to draw on are already known to the server on the same + // connection, with nothing to flush or synchronise first. + Display *g_x11Display = nullptr; + + // Hands an already opened VADisplay to FFmpeg. Unlike + // av_hwdevice_ctx_create() this leaves the display in our hands rather + // than opening one of its own, which is the whole point here: the renderer + // has to draw surfaces on the very same display the decoder made them on. + AVBufferRef *wrapVaDisplay(VADisplay va_display) + { + AVBufferRef *ref = av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_VAAPI); + + if (!ref) + return nullptr; + + AVHWDeviceContext *devctx = (AVHWDeviceContext *)ref->data; + AVVAAPIDeviceContext *vactx = (AVVAAPIDeviceContext *)devctx->hwctx; + + vactx->display = va_display; + + if (av_hwdevice_ctx_init(ref) < 0) + { + av_buffer_unref(&ref); + return nullptr; + } + + return ref; + } + + // Opens the VAAPI device on the X connection, so that decoded surfaces can + // later be drawn with vaPutSurface(). Returns null when that is not the way + // this session draws - under Wayland, or under X11 with Qt on EGL, where a + // surface is drawn through its DMA-BUF handles instead - and on any + // failure, leaving the caller to open the device through a DRM render node. + AVBufferRef *createX11Device() + { + if (!g_x11Display) + return nullptr; + + // libva's X11 backend prefers DRI3, which gets it a DRM file + // descriptor and nothing else. That is all decoding needs, but drawing + // is another matter: i965's vaPutSurface() draws into DRI2 buffers and + // answers VA_STATUS_ERROR_UNKNOWN, silently and with nothing logged at + // any verbosity, for every frame when the display was not opened that + // way. So ask libva for DRI2. + // + // Set for the rest of the process rather than just around the calls + // below, and deliberately so: libva reads it in + // va_dri_get_rendering_buffer(), which is called while a surface is + // being put on a window - restoring the environment after + // vaInitialize() would leave the variable unset exactly when it is + // consulted. Nothing else in the client opens an X11 VA display, and a + // value the user set is left alone. + // + // Should DRI2 turn out not to be available, opening fails and the + // caller falls back to a DRM render node, which never looks at this. + if (!qEnvironmentVariableIsSet("LIBVA_DRI3_DISABLE")) + qputenv("LIBVA_DRI3_DISABLE", "1"); + + VADisplay va_display = vaGetDisplay(g_x11Display); + + if (!va_display) + { + qWarning() << "VAAPI: this libva build has no X11 support"; + return nullptr; + } + + int major = 0, minor = 0; + VAStatus st = vaInitialize(va_display, &major, &minor); + + if (st != VA_STATUS_SUCCESS) + { + qWarning() << "VAAPI: vaInitialize() on the X display failed:" << vaErrorStr(st); + vaTerminate(va_display); + return nullptr; + } + + AVBufferRef *ref = wrapVaDisplay(va_display); + + if (!ref) + { + qWarning() << "VAAPI: the X display could not be handed to FFmpeg"; + vaTerminate(va_display); + return nullptr; + } + + g_usesX11 = true; + + return ref; + } +#endif + + // Must be called with g_mutex held. + void ensureDevice() + { + if (g_tried) + return; + + g_tried = true; + +#ifdef HAVE_VAAPI_X11 + // Where the widgets will be drawn on by the driver, the display has to + // be opened on that same X connection - a surface belongs to the + // display it was made on. Encoding and decoding work the same either + // way, so nothing is given up by preferring it here. + g_device = createX11Device(); + + if (g_device) + return; +#endif + + // A null device name lets FFmpeg find a usable DRM render node + // (/dev/dri/renderD128 and friends) by itself. + int ret = av_hwdevice_ctx_create(&g_device, AV_HWDEVICE_TYPE_VAAPI, nullptr, nullptr, 0); + if (ret < 0) + { + char buf[256] = {0}; + av_strerror(ret, buf, sizeof(buf)); + qWarning() << "VAAPI is not usable, falling back to software video:" << buf; + g_device = nullptr; + } + } +} + +AVFramePtr wrapAVFrame(AVFrame *frame) +{ + return AVFramePtr(frame, [](AVFrame *f) { av_frame_free(&f); }); +} + +AVBufferRef *VaapiContext::deviceRef() +{ + QMutexLocker locker(&g_mutex); + ensureDevice(); + + return g_device ? av_buffer_ref(g_device) : nullptr; +} + +VADisplay VaapiContext::display() +{ + QMutexLocker locker(&g_mutex); + ensureDevice(); + + if (!g_device) + return nullptr; + + AVHWDeviceContext *devctx = (AVHWDeviceContext *)g_device->data; + AVVAAPIDeviceContext *vactx = (AVVAAPIDeviceContext *)devctx->hwctx; + + return vactx->display; +} + +bool VaapiContext::isAvailable() +{ + QMutexLocker locker(&g_mutex); + ensureDevice(); + + return g_device != nullptr; +} + +bool VaapiContext::usesX11() +{ + QMutexLocker locker(&g_mutex); + ensureDevice(); + + return g_usesX11; +} + +void *VaapiContext::x11Display() +{ +#ifdef HAVE_VAAPI_X11 + QMutexLocker locker(&g_mutex); + ensureDevice(); + + return g_usesX11 ? (void *)g_x11Display : nullptr; +#else + return nullptr; +#endif +} + +void VaapiContext::registerMetaTypes() +{ + qRegisterMetaType<AVFramePtr>("AVFramePtr"); +} + +void VaapiContext::initX11Threading() +{ +#ifdef HAVE_VAAPI_X11 + // Qt's X connection ends up being used from two threads: the GUI thread + // drawing, and the decoding thread talking to libva, which talks to the + // driver over that same connection. Xlib only handles that if it is told + // before the connection is opened - hence being called ahead of + // QApplication - and it is harmless when the session turns out not to be + // an X11 one at all. + XInitThreads(); +#endif +} + +void VaapiContext::detectX11Display() +{ +#ifdef HAVE_VAAPI_X11 + QMutexLocker locker(&g_mutex); + + // Nothing to arrange once the device has been opened - it would be too + // late to change which display its surfaces live on. + if (g_tried || g_x11Display) + return; + + if (QGuiApplication::platformName() != QLatin1String("xcb")) + return; + + // A throwaway context, made only to see what Qt's OpenGL contexts are: + // under X11 Qt uses GLX by default but EGL when asked to, and the two need + // entirely different ways of getting a decoded surface onto the screen. + // Every context in the process is made on the same X connection, so the + // widget that draws video later will be on the one found here. + // + // A GLX context means the EGL import path is unavailable, and that is what + // decides this: the surfaces have to go onto an X window instead. + QOffscreenSurface surface; + surface.create(); + + if (!surface.isValid()) + return; + + QOpenGLContext ctx; + + if (!ctx.create() || !ctx.makeCurrent(&surface)) + return; + + Display *dpy = glXGetCurrentDisplay(); + + ctx.doneCurrent(); + + // Null means an EGL context, where the DMA-BUF path applies and there is + // nothing to prepare. + if (dpy) + g_x11Display = dpy; +#endif +} + +bool VaapiRenderWidget::s_renderingBroken = false; + +VaapiRenderWidget *VaapiRenderWidget::create(QWidget *parent) +{ +#ifdef HAVE_VAAPI_X11 + // Only when the display was opened on an X connection, which is also the + // only case where a surface can be put onto a window. + if (VaapiContext::usesX11()) + return new VaapiX11Widget(parent); +#endif + + return new VaapiVideoWidget(parent); +} + +#endif // HAVE_VAAPI diff --git a/pica-client/vaapi.h b/pica-client/vaapi.h new file mode 100644 index 0000000..888a9d6 --- /dev/null +++ b/pica-client/vaapi.h @@ -0,0 +1,143 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#ifndef VAAPI_H +#define VAAPI_H + +#ifdef HAVE_VAAPI + +#include <QSharedPointer> +#include <QMetaType> +#include <va/va.h> + +extern "C" { +#include <libavutil/buffer.h> +#include <libavutil/frame.h> +} + +// A decoded hardware frame holds a VA surface, not pixels, and has to travel +// from the decoding thread to the widget that draws it. Reference counting it +// this way keeps the surface alive exactly as long as someone still needs it, +// and lets it cross threads through an ordinary queued signal. +typedef QSharedPointer<AVFrame> AVFramePtr; + +// Wraps an AVFrame that the caller is handing over, freeing it once the last +// reference goes away. +AVFramePtr wrapAVFrame(AVFrame *frame); + +// The one VAAPI device the whole client shares. Encoder, decoder and renderer +// must all work against the same VADisplay - surfaces created on one display +// cannot be used on another - so the device is created once, on first use, and +// handed out from here. +class VaapiContext +{ +public: + // A new reference to the shared device context, for an encoder's or + // decoder's hw_device_ctx. The caller owns the returned reference and + // unrefs it as usual. Null if VAAPI is unavailable. + static AVBufferRef *deviceRef(); + + // The underlying VADisplay, needed to export a decoded surface for + // display. Null if VAAPI is unavailable. + static VADisplay display(); + + // Whether a VAAPI device could be opened at all. Callers use this to fall + // back to software rather than each probing for themselves. + static bool isAvailable(); + + // Whether the display was opened on an X11 connection rather than a DRM + // render node. That is decided once, when the device is created, and + // decides how a decoded surface can be drawn: only an X11 display can be + // drawn with vaPutSurface(), which is the only option left when Qt's + // OpenGL contexts come from GLX. Always false in a build without X11 + // rendering support. + static bool usesX11(); + + // The X connection the display was opened on, as a Display*, or null when + // it was not opened on one. Untyped to keep the Xlib headers, and the + // names they take over, out of everything that includes this. + static void *x11Display(); + + // Registers the metatype for AVFramePtr, so hardware frames can be passed + // through queued signal connections. Call once at startup. + static void registerMetaTypes(); + + // Tells Xlib that its connection will be used from more than one thread, + // which it only accepts before that connection is opened - so this has to + // run before QApplication is constructed. Does nothing in a build without + // X11 rendering support. + static void initX11Threading(); + + // Works out whether this session needs the X11 drawing path - that is, + // whether Qt's OpenGL contexts come from GLX, leaving no way to import a + // surface as an EGL image - and if so remembers Qt's X connection to open + // the VAAPI display on. Call once at startup, after QApplication exists + // and before any video starts. Does nothing outside an X11 session, or + // when Qt is using EGL there. + static void detectX11Display(); +}; + +class QWidget; + +// The common face of the two widgets that can draw a decoded surface: the +// OpenGL one, which imports it as EGL images, and the X11 one, which has the +// driver put it on screen. Which of them a session can use is not known until +// it runs, and nothing outside create() should care which it got. +class VaapiRenderWidget +{ +public: + virtual ~VaapiRenderWidget() {} + + // The widget to lay out, show and hide, and to connect to: both carry a + // renderingFailed(QString) signal. + virtual QWidget *widget() = 0; + + // Takes the frame to draw next, replacing any previous one not yet drawn - + // for live video the newest frame is the one that matters. + virtual void setFrame(AVFramePtr frame) = 0; + + // Drops the current frame and clears the widget. + virtual void clearFrame() = 0; + + // Whether frames are still being drawn. False once drawing has failed, so + // a caller can fall back to the software path rather than leave a blank + // widget. + virtual bool isWorking() const = 0; + + // The renderer this session can use. Never null - it falls back to the + // OpenGL one, which reports the reason it cannot draw if it cannot. + static VaapiRenderWidget *create(QWidget *parent); + + // Whether drawing GPU frames has already been found not to work in this + // session. Nothing about that changes while the client runs - it follows + // from the kind of OpenGL context Qt provides and what the driver can do + // with it - so once one widget has failed, the next will fail the same + // way. Callers use this to stop asking for GPU frames at all rather than + // to fail again for every window they open. + static bool renderingKnownBroken() { return s_renderingBroken; } + +protected: + static void markRenderingBroken() { s_renderingBroken = true; } + +private: + static bool s_renderingBroken; +}; + +Q_DECLARE_METATYPE(AVFramePtr) + +#endif // HAVE_VAAPI + +#endif // VAAPI_H diff --git a/pica-client/vaapivideowidget.cpp b/pica-client/vaapivideowidget.cpp new file mode 100644 index 0000000..1f3f3a6 --- /dev/null +++ b/pica-client/vaapivideowidget.cpp @@ -0,0 +1,412 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#include "vaapivideowidget.h" + +#ifdef HAVE_VAAPI + +#include <QDebug> +#include <unistd.h> + +#include <EGL/egl.h> +#include <EGL/eglext.h> +#include <GL/gl.h> +#include <drm/drm_fourcc.h> + +extern "C" { +#include <libavutil/pixfmt.h> +} + +#include <va/va_drmcommon.h> + + +namespace +{ + // Extension entry points, resolved once at first use: they are not + // linkable symbols, only reachable through eglGetProcAddress. + PFNEGLCREATEIMAGEKHRPROC g_eglCreateImageKHR = nullptr; + PFNEGLDESTROYIMAGEKHRPROC g_eglDestroyImageKHR = nullptr; + PFNGLEGLIMAGETARGETTEXTURE2DOESPROC g_glEGLImageTargetTexture2DOES = nullptr; + bool g_resolved = false; + + bool resolveEglExtensions() + { + if (g_resolved) + return g_eglCreateImageKHR && g_eglDestroyImageKHR && g_glEGLImageTargetTexture2DOES; + + g_resolved = true; + g_eglCreateImageKHR = + (PFNEGLCREATEIMAGEKHRPROC)eglGetProcAddress("eglCreateImageKHR"); + g_eglDestroyImageKHR = + (PFNEGLDESTROYIMAGEKHRPROC)eglGetProcAddress("eglDestroyImageKHR"); + g_glEGLImageTargetTexture2DOES = + (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)eglGetProcAddress("glEGLImageTargetTexture2DOES"); + + return g_eglCreateImageKHR && g_eglDestroyImageKHR && g_glEGLImageTargetTexture2DOES; + } + + const char *kVertexShader = + "attribute highp vec2 vertex;\n" + "attribute highp vec2 texcoord;\n" + "varying highp vec2 uv;\n" + "void main() {\n" + " uv = texcoord;\n" + " gl_Position = vec4(vertex, 0.0, 1.0);\n" + "}\n"; + + // NV12 arrives as a full resolution luma plane and a half resolution + // plane of interleaved Cb/Cr. The BT.601 limited range coefficients below + // match what the decoders in this pipeline produce for camera video. + const char *kFragmentShader = + "varying highp vec2 uv;\n" + "uniform sampler2D planeY;\n" + "uniform sampler2D planeUV;\n" + "void main() {\n" + " highp float y = texture2D(planeY, uv).r;\n" + " highp vec2 c = texture2D(planeUV, uv).rg;\n" + " y = 1.1643 * (y - 0.0625);\n" + " highp float u = c.r - 0.5;\n" + " highp float v = c.g - 0.5;\n" + " highp float r = y + 1.5958 * v;\n" + " highp float g = y - 0.39173 * u - 0.81290 * v;\n" + " highp float b = y + 2.017 * u;\n" + " gl_FragColor = vec4(r, g, b, 1.0);\n" + "}\n"; +} + +VaapiVideoWidget::VaapiVideoWidget(QWidget *parent) + : QOpenGLWidget(parent), m_program(nullptr), m_numFds(0), + m_frameWidth(0), m_frameHeight(0), m_working(true), m_reportedFailure(false), + m_describedSurface(false) +{ + m_textures[0] = m_textures[1] = 0; + m_images[0] = m_images[1] = EGL_NO_IMAGE_KHR; + for (int i = 0; i < 4; i++) + m_dmabufFds[i] = -1; +} + +VaapiVideoWidget::~VaapiVideoWidget() +{ + // The GL objects belong to this widget's context, so it has to be current + // while they are destroyed. + makeCurrent(); + releaseImports(); + if (m_textures[0]) + glDeleteTextures(2, m_textures); + delete m_program; + doneCurrent(); +} + +void VaapiVideoWidget::reportFailure(const QString &message) +{ + m_working = false; + markRenderingBroken(); + + if (m_reportedFailure) + return; + + m_reportedFailure = true; + qWarning() << message; + emit renderingFailed(message); +} + +void VaapiVideoWidget::setFrame(AVFramePtr frame) +{ + if (!m_working) + return; + + m_frame = frame; + update(); +} + +void VaapiVideoWidget::clearFrame() +{ + m_frame.clear(); + update(); +} + +void VaapiVideoWidget::initializeGL() +{ + initializeOpenGLFunctions(); + + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glDisable(GL_DEPTH_TEST); + + // Importing a surface as an EGL image needs an EGL context to import it + // into. eglGetCurrentDisplay() is the telling call: under GLX it answers + // EGL_NO_DISPLAY, and there is no display to create an image on. + if (eglGetCurrentContext() == EGL_NO_CONTEXT || eglGetCurrentDisplay() == EGL_NO_DISPLAY) + { +#ifdef HAVE_VAAPI_X11 + // An X11 session should have been given the other renderer, so the + // display cannot have been opened on an X connection either. + reportFailure(tr("The OpenGL context is not an EGL one and the VAAPI display was not " + "opened on an X connection, so decoded frames cannot be drawn")); +#else + reportFailure(tr("The OpenGL context is not an EGL one, so decoded frames cannot be " + "drawn. An X11 session gives Qt a GLX context unless told otherwise; " + "rebuild with --enable-vaapi-x11, or start the client with " + "QT_XCB_GL_INTEGRATION=xcb_egl")); +#endif + return; + } + + if (!resolveEglExtensions()) + { + reportFailure(tr("EGL does not offer the extensions needed to draw GPU frames")); + return; + } + + m_program = new QOpenGLShaderProgram(this); + if (!m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, kVertexShader) || + !m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, kFragmentShader) || + !m_program->link()) + { + reportFailure(tr("Could not build the video shader: %1").arg(m_program->log())); + return; + } + + glGenTextures(2, m_textures); + for (int i = 0; i < 2; i++) + { + glBindTexture(GL_TEXTURE_2D, m_textures[i]); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } + glBindTexture(GL_TEXTURE_2D, 0); +} + +void VaapiVideoWidget::releaseImports() +{ + for (int i = 0; i < 2; i++) + { + if (m_images[i] != EGL_NO_IMAGE_KHR) + { + if (g_eglDestroyImageKHR) + g_eglDestroyImageKHR(eglGetCurrentDisplay(), (EGLImageKHR)m_images[i]); + m_images[i] = EGL_NO_IMAGE_KHR; + } + } + + for (int i = 0; i < m_numFds; i++) + { + if (m_dmabufFds[i] >= 0) + { + ::close(m_dmabufFds[i]); + m_dmabufFds[i] = -1; + } + } + m_numFds = 0; +} + +bool VaapiVideoWidget::importFrame() +{ + VADisplay va_display = VaapiContext::display(); + if (!va_display || !m_frame) + return false; + + // The surface id lives in data[3] for AV_PIX_FMT_VAAPI frames. + VASurfaceID surface = (VASurfaceID)(uintptr_t)m_frame->data[3]; + + // Everything still queued on the surface has to have finished before its + // memory can be handed to another API. + if (vaSyncSurface(va_display, surface) != VA_STATUS_SUCCESS) + return false; + + VADRMPRIMESurfaceDescriptor desc; + memset(&desc, 0, sizeof desc); + + VAStatus st = vaExportSurfaceHandle(va_display, surface, + VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2, + VA_EXPORT_SURFACE_READ_ONLY | VA_EXPORT_SURFACE_SEPARATE_LAYERS, + &desc); + if (st != VA_STATUS_SUCCESS) + return false; + + // Held so they can be closed again after drawing; the export hands over + // ownership of every one of them. + m_numFds = desc.num_objects > 4 ? 4 : (int)desc.num_objects; + for (int i = 0; i < m_numFds; i++) + m_dmabufFds[i] = desc.objects[i].fd; + + m_frameWidth = desc.width; + m_frameHeight = desc.height; + + // Logged once: how the driver actually laid the surface out is the first + // thing worth knowing when the picture comes out wrong. + if (!m_describedSurface) + { + m_describedSurface = true; + + QString layers; + for (uint32_t i = 0; i < desc.num_layers; i++) + { + uint32_t object = desc.layers[i].object_index[0]; + layers += QString(" layer%1[fourcc=0x%2 offset=%3 pitch=%4 modifier=0x%5]") + .arg(i) + .arg(desc.layers[i].drm_format, 0, 16) + .arg(desc.layers[i].offset[0]) + .arg(desc.layers[i].pitch[0]) + .arg(desc.objects[object].drm_format_modifier, 0, 16); + } + + qDebug() << QString("VAAPI surface for display: %1x%2 fourcc=0x%3 objects=%4 layers=%5%6") + .arg(desc.width).arg(desc.height) + .arg(desc.fourcc, 0, 16) + .arg(desc.num_objects).arg(desc.num_layers) + .arg(layers); + } + + // Two layers for NV12: the luma plane, then the interleaved chroma plane + // at half size in both directions. + if (desc.num_layers < 2) + { + releaseImports(); + return false; + } + + EGLDisplay egl_display = eglGetCurrentDisplay(); + + for (int i = 0; i < 2; i++) + { + uint32_t object = desc.layers[i].object_index[0]; + int planeWidth = (i == 0) ? desc.width : desc.width / 2; + int planeHeight = (i == 0) ? desc.height : desc.height / 2; + uint64_t modifier = desc.objects[object].drm_format_modifier; + + EGLint attribs[16]; + int n = 0; + + attribs[n++] = EGL_WIDTH; attribs[n++] = planeWidth; + attribs[n++] = EGL_HEIGHT; attribs[n++] = planeHeight; + attribs[n++] = EGL_LINUX_DRM_FOURCC_EXT; attribs[n++] = (EGLint)desc.layers[i].drm_format; + attribs[n++] = EGL_DMA_BUF_PLANE0_FD_EXT; attribs[n++] = desc.objects[object].fd; + attribs[n++] = EGL_DMA_BUF_PLANE0_OFFSET_EXT; attribs[n++] = (EGLint)desc.layers[i].offset[0]; + attribs[n++] = EGL_DMA_BUF_PLANE0_PITCH_EXT; attribs[n++] = (EGLint)desc.layers[i].pitch[0]; + + // Without this the import is assumed to be a plain linear buffer. GPUs + // hand out tiled surfaces instead, and reading one as linear is what + // produces a picture in bands with the colour gone - so the modifier + // the driver reported has to be passed along whenever it has one. + if (modifier != DRM_FORMAT_MOD_INVALID) + { + attribs[n++] = EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT; + attribs[n++] = (EGLint)(modifier & 0xFFFFFFFF); + attribs[n++] = EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT; + attribs[n++] = (EGLint)(modifier >> 32); + } + + attribs[n++] = EGL_NONE; + + m_images[i] = g_eglCreateImageKHR(egl_display, EGL_NO_CONTEXT, + EGL_LINUX_DMA_BUF_EXT, nullptr, attribs); + if (m_images[i] == EGL_NO_IMAGE_KHR) + { + qWarning() << QString("eglCreateImageKHR failed for plane %1: 0x%2") + .arg(i).arg(eglGetError(), 0, 16); + releaseImports(); + return false; + } + + glBindTexture(GL_TEXTURE_2D, m_textures[i]); + g_glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, (GLeglImageOES)m_images[i]); + } + + glBindTexture(GL_TEXTURE_2D, 0); + + return true; +} + +void VaapiVideoWidget::paintGL() +{ + glClear(GL_COLOR_BUFFER_BIT); + + if (!m_working || !m_program || !m_frame) + return; + + if (!importFrame()) + { + reportFailure(tr("Could not hand the decoded GPU frame to OpenGL for drawing")); + return; + } + + // Letterbox rather than stretch, matching what the software path does + // with Qt::KeepAspectRatio. + float widgetAspect = float(width()) / float(height() ? height() : 1); + float frameAspect = float(m_frameWidth) / float(m_frameHeight ? m_frameHeight : 1); + float sx = 1.0f, sy = 1.0f; + + if (frameAspect > widgetAspect) + sy = widgetAspect / frameAspect; + else + sx = frameAspect / widgetAspect; + + const GLfloat vertices[] = + { + -sx, -sy, + sx, -sy, + -sx, sy, + sx, sy + }; + // Flipped vertically: video rows run top to bottom, OpenGL's origin is at + // the bottom left. + const GLfloat texcoords[] = + { + 0.0f, 1.0f, + 1.0f, 1.0f, + 0.0f, 0.0f, + 1.0f, 0.0f + }; + + m_program->bind(); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, m_textures[0]); + m_program->setUniformValue("planeY", 0); + + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, m_textures[1]); + m_program->setUniformValue("planeUV", 1); + + int vertexLocation = m_program->attributeLocation("vertex"); + int texcoordLocation = m_program->attributeLocation("texcoord"); + + m_program->enableAttributeArray(vertexLocation); + m_program->enableAttributeArray(texcoordLocation); + m_program->setAttributeArray(vertexLocation, vertices, 2); + m_program->setAttributeArray(texcoordLocation, texcoords, 2); + + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + + m_program->disableAttributeArray(vertexLocation); + m_program->disableAttributeArray(texcoordLocation); + m_program->release(); + + glActiveTexture(GL_TEXTURE0); + + // Done with this frame's handles - holding on to them would leak a set of + // file descriptors for every frame drawn. + releaseImports(); +} + +void VaapiVideoWidget::resizeGL(int w, int h) +{ + glViewport(0, 0, w, h); +} + +#endif // HAVE_VAAPI diff --git a/pica-client/vaapivideowidget.h b/pica-client/vaapivideowidget.h new file mode 100644 index 0000000..9ea7a50 --- /dev/null +++ b/pica-client/vaapivideowidget.h @@ -0,0 +1,95 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#ifndef VAAPIVIDEOWIDGET_H +#define VAAPIVIDEOWIDGET_H + +#ifdef HAVE_VAAPI + +#include "vaapi.h" + +#include <QOpenGLWidget> +#include <QOpenGLFunctions> +#include <QOpenGLShaderProgram> +#include <QString> + +// Draws frames that are still sitting in GPU memory as VA surfaces, without +// bringing them back through system memory on the way. +// +// The surface is exported as DMA-BUF file descriptors, imported into EGL as +// images, and bound to OpenGL textures - one for the luma plane and one for +// the interleaved chroma plane of an NV12 frame - which a fragment shader then +// converts to RGB while drawing. Nothing copies the picture; the GPU keeps it +// where the decoder left it. This needs an EGL context, which is what a +// Wayland session gives, and what X11 gives when asked +// (QT_XCB_GL_INTEGRATION=xcb_egl). +// +// An X11 session where Qt uses GLX instead gives a context that cannot import +// a DMA-BUF at all; VaapiX11Widget covers that case, and VaapiRenderWidget's +// factory decides between the two. +class VaapiVideoWidget : public QOpenGLWidget, protected QOpenGLFunctions, public VaapiRenderWidget +{ + Q_OBJECT +public: + explicit VaapiVideoWidget(QWidget *parent = nullptr); + ~VaapiVideoWidget() override; + + virtual QWidget *widget() override { return this; } + virtual bool isWorking() const override { return m_working; } + +public slots: + virtual void setFrame(AVFramePtr frame) override; + virtual void clearFrame() override; + +signals: + // Raised once if the frame cannot be imported for drawing, carrying the + // reason. The widget stops trying after that. + void renderingFailed(QString message); + +protected: + void initializeGL() override; + void paintGL() override; + void resizeGL(int w, int h) override; + +private: + // Builds the two textures for the current frame out of the surface's + // DMA-BUF handles. Returns false and leaves nothing bound on failure. + bool importFrame(); + + // Releases the EGL images and the file descriptors the export handed + // over. Not closing those descriptors leaks them once per frame, which + // exhausts the process's descriptors within minutes. + void releaseImports(); + + // Reports a failure that stops the widget drawing, once. + void reportFailure(const QString &message); + + AVFramePtr m_frame; + QOpenGLShaderProgram *m_program; + unsigned int m_textures[2]; + void *m_images[2]; + int m_dmabufFds[4]; + int m_numFds; + int m_frameWidth; + int m_frameHeight; + bool m_working; + bool m_reportedFailure; + bool m_describedSurface; +}; + +#endif // HAVE_VAAPI + +#endif // VAAPIVIDEOWIDGET_H diff --git a/pica-client/vaapix11widget.cpp b/pica-client/vaapix11widget.cpp new file mode 100644 index 0000000..0788577 --- /dev/null +++ b/pica-client/vaapix11widget.cpp @@ -0,0 +1,237 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#include "vaapix11widget.h" + +#ifdef HAVE_VAAPI_X11 + +#include <QDebug> +#include <QPaintEvent> +#include <QResizeEvent> +#include <QShowEvent> + +// Included after the Qt headers, since Xlib defines a handful of names as +// macros that Qt also uses as ordinary identifiers. +#include <X11/Xlib.h> +#include <va/va_x11.h> +#undef Bool +#undef Status +#undef None +#undef Success +#undef Always +#undef CursorShape +#undef KeyPress +#undef KeyRelease +#undef FocusIn +#undef FocusOut +#undef Expose +#undef Unsorted + +VaapiX11Widget::VaapiX11Widget(QWidget *parent) + : QWidget(parent), m_working(true), m_reportedFailure(false), + m_describedSurface(false), m_everDrew(false), m_failuresInARow(0) +{ + // The driver draws onto this window itself, which means it has to be a + // window of its own rather than a region of its parent's, and Qt has to + // keep out of it: no background filling, no double buffering, no clearing + // before a paint event. + setAttribute(Qt::WA_NativeWindow); + setAttribute(Qt::WA_PaintOnScreen); + setAttribute(Qt::WA_NoSystemBackground); + setAttribute(Qt::WA_OpaquePaintEvent); + setAutoFillBackground(false); +} + +VaapiX11Widget::~VaapiX11Widget() +{ +} + +void VaapiX11Widget::reportFailure(const QString &message) +{ + m_working = false; + markRenderingBroken(); + + if (m_reportedFailure) + return; + + m_reportedFailure = true; + qWarning() << message; + emit renderingFailed(message); +} + +void VaapiX11Widget::setFrame(AVFramePtr frame) +{ + if (!m_working) + return; + + m_frame = frame; + + // repaint() rather than update(): the frame is only held until the next + // one replaces it, and a posted paint event could easily be delivered + // after that has happened. + repaint(); +} + +void VaapiX11Widget::clearFrame() +{ + m_frame.clear(); + clearWindow(); +} + +void VaapiX11Widget::clearWindow() +{ + Display *dpy = (Display *)VaapiContext::x11Display(); + + if (!dpy || !isVisible()) + return; + + XClearWindow(dpy, (Window)winId()); + XFlush(dpy); +} + +void VaapiX11Widget::showEvent(QShowEvent *event) +{ + QWidget::showEvent(event); + + Display *dpy = (Display *)VaapiContext::x11Display(); + + if (!dpy) + return; + + // Black, so that the bars beside a letterboxed picture, and the window + // before the first frame arrives, are not left showing whatever the + // server last had there. + XSetWindowBackground(dpy, (Window)winId(), BlackPixel(dpy, DefaultScreen(dpy))); + XClearWindow(dpy, (Window)winId()); + XFlush(dpy); +} + +void VaapiX11Widget::resizeEvent(QResizeEvent *event) +{ + QWidget::resizeEvent(event); + + // The picture is about to be drawn at a different size, and what the old + // one left outside it would otherwise stay on screen. + clearWindow(); +} + +void VaapiX11Widget::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event); + + if (!m_working || !m_frame) + return; + + // Nothing to draw onto until the window is on screen, and asking the + // driver to draw on one that is not would fail for a reason that says + // nothing about whether this path works. + if (!isVisible()) + return; + + if (putFrame()) + { + m_everDrew = true; + m_failuresInARow = 0; + return; + } + + m_failuresInARow++; + + // Frames keep arriving, so one failure proves nothing - give the window + // time to settle before writing the path off. Once something has been + // drawn successfully, a later failure is treated the same way: only a + // sustained run of them counts. + if (m_failuresInARow < kMaxFailuresInARow) + return; + + reportFailure(m_everDrew + ? tr("Stopped being able to put decoded GPU frames on screen") + : tr("Could not put the decoded GPU frame on screen")); +} + +bool VaapiX11Widget::putFrame() +{ + VADisplay va_display = VaapiContext::display(); + + if (!va_display || !m_frame) + return false; + + int frameWidth = m_frame->width; + int frameHeight = m_frame->height; + + if (frameWidth <= 0 || frameHeight <= 0) + return false; + + // Letterbox rather than stretch, matching what the software path does with + // Qt::KeepAspectRatio. Everything the picture does not cover keeps the + // window's black background. + int windowWidth = width(); + int windowHeight = height(); + int destWidth = windowWidth; + int destHeight = (int)((qint64)windowWidth * frameHeight / frameWidth); + + if (destHeight > windowHeight) + { + destHeight = windowHeight; + destWidth = (int)((qint64)windowHeight * frameWidth / frameHeight); + } + + int destX = (windowWidth - destWidth) / 2; + int destY = (windowHeight - destHeight) / 2; + + // The surface id lives in data[3] for AV_PIX_FMT_VAAPI frames. + VASurfaceID surface = (VASurfaceID)(uintptr_t)m_frame->data[3]; + + Display *dpy = (Display *)VaapiContext::x11Display(); + + // Before the first frame goes out, make sure the server has caught up with + // Qt's own requests for this window - it is created and mapped on the same + // connection, but not necessarily processed by the time a frame arrives, + // and the driver cannot draw on a window the server does not have yet. + if (dpy && !m_everDrew) + XSync(dpy, False); + + if (!m_describedSurface) + { + m_describedSurface = true; + qDebug() << QString("Putting VAAPI surfaces on an X11 window: %1x%2") + .arg(frameWidth).arg(frameHeight); + } + + // VA_SRC_BT601 to match the coefficients the software path and the EGL + // renderer use for camera video; VA_FRAME_PICTURE because nothing in this + // pipeline is interlaced. + VAStatus st = vaPutSurface(va_display, surface, (Drawable)winId(), + 0, 0, frameWidth, frameHeight, + destX, destY, destWidth, destHeight, + nullptr, 0, + VA_FRAME_PICTURE | VA_SRC_BT601); + + if (st != VA_STATUS_SUCCESS) + { + // Only the first one, and then only every so often: at video rate a + // line per frame would bury everything else in the log. + if (m_failuresInARow == 0 || m_failuresInARow == kMaxFailuresInARow - 1) + qWarning() << QString("vaPutSurface failed: %1 (0x%2)") + .arg(QLatin1String(vaErrorStr(st))).arg((uint)st, 0, 16); + + return false; + } + + return true; +} + +#endif // HAVE_VAAPI_X11 diff --git a/pica-client/vaapix11widget.h b/pica-client/vaapix11widget.h new file mode 100644 index 0000000..53b6135 --- /dev/null +++ b/pica-client/vaapix11widget.h @@ -0,0 +1,97 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#ifndef VAAPIX11WIDGET_H +#define VAAPIX11WIDGET_H + +#ifdef HAVE_VAAPI_X11 + +#include "vaapi.h" + +#include <QWidget> +#include <QString> + +// Draws decoded frames by handing the surface to the driver with the widget's +// own X window as the target - vaPutSurface() - rather than going through +// OpenGL at all. The picture never leaves the GPU; the driver does the colour +// conversion and the scaling. +// +// This is the path for an X11 session, where Qt's OpenGL contexts come from +// GLX and cannot import the DMA-BUF handles a surface is exported as. Since it +// touches no OpenGL, it does not care which of the two Qt picked. +// +// The cost of drawing outside Qt is that Qt must be kept away from this +// widget's area: it is given a native window of its own, Qt is told not to +// paint or clear it (WA_PaintOnScreen, WA_NoSystemBackground, a null paint +// engine), and anything drawn over it - a menu, a tooltip - will fight with +// the video underneath. +class VaapiX11Widget : public QWidget, public VaapiRenderWidget +{ + Q_OBJECT +public: + explicit VaapiX11Widget(QWidget *parent = nullptr); + ~VaapiX11Widget() override; + + virtual QWidget *widget() override { return this; } + virtual bool isWorking() const override { return m_working; } + +public slots: + virtual void setFrame(AVFramePtr frame) override; + virtual void clearFrame() override; + +signals: + // Raised once if a frame cannot be put on screen, carrying the reason. + // The widget stops trying after that. + void renderingFailed(QString message); + +protected: + // Nothing about this widget is painted by Qt, so it has no paint engine to + // offer. Returning one would have Qt draw over the video. + QPaintEngine *paintEngine() const override { return nullptr; } + + void paintEvent(QPaintEvent *event) override; + void resizeEvent(QResizeEvent *event) override; + void showEvent(QShowEvent *event) override; + +private: + // Puts the current frame on the window, letterboxed to keep its aspect + // ratio. Returns false if the driver would not draw it. + bool putFrame(); + + // Paints the whole window black, so that the bars beside a letterboxed + // picture are not left holding whatever was there before. + void clearWindow(); + + void reportFailure(const QString &message); + + AVFramePtr m_frame; + bool m_working; + bool m_reportedFailure; + bool m_describedSurface; + bool m_everDrew; + + // Putting a surface on a window can fail for reasons that pass - the + // window not being mapped yet at the moment the first frame arrives, most + // obviously - so unlike an EGL import, which either works or never will, + // this one is worth retrying. Only a long run of failures means the path + // is really unusable. + int m_failuresInARow; + static const int kMaxFailuresInARow = 30; +}; + +#endif // HAVE_VAAPI_X11 + +#endif // VAAPIX11WIDGET_H diff --git a/pica-client/videodevice.cpp b/pica-client/videodevice.cpp new file mode 100644 index 0000000..2ece29c --- /dev/null +++ b/pica-client/videodevice.cpp @@ -0,0 +1,2522 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#include "videodevice.h" +#include "callsettings.h" +// For the shared decision about what size a frame is drawn at - the decode loop +// produces frames at exactly the size CallWindow expects, see VideoScaler. +#include "videoscaler.h" +#include "../PICA_proto.h" +#include "../PICA_media.h" + +#include <QFile> +#include <QDebug> +#include <QMutexLocker> +#include <QMap> +#include <QPair> +#include <cstring> +#include <algorithm> +#include <functional> + +#ifdef Q_OS_WIN +#include <objbase.h> +#endif + +#ifdef Q_OS_LINUX +#include <linux/videodev2.h> +#include <sys/ioctl.h> +#include <unistd.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> + +// Added to the kernel headers later than the formats around it, so define it +// here when building against an older set. +#ifndef V4L2_PIX_FMT_HEVC +#define V4L2_PIX_FMT_HEVC v4l2_fourcc('H', 'E', 'V', 'C') +#endif +#endif + +// FFmpeg headers +extern "C" { +#include <libavformat/avformat.h> +#include <libavdevice/avdevice.h> +#include <libavcodec/avcodec.h> +#include <libavutil/opt.h> +#include <libavutil/imgutils.h> +#include <libavutil/frame.h> +#include <libavutil/mem.h> +#include <libavutil/error.h> +#include <libswscale/swscale.h> +#include <libavutil/hwcontext.h> +#include <libavutil/pixdesc.h> +} + +// Largest amount of encoded data one 0x77 message can carry over a c2c or +// directc2c connection: the protocol's per-message payload cap, minus the +// sequence number + timestamp header that every call media packet carries. +// Over a mediac2c connection the limit is the path MTU instead and is set +// with setMaxFragmentSize() once that connection is up. +static const int kMaxFragmentSize = PICA_PROTO_C2CMSG_MAXDATASIZE - PICA_PROTO_CALL_PACKET_HDRSIZE; + +// Largest encoded slice the software encoder is asked to produce: one that +// still fits into a single datagram of a mediac2c connection, so that losing +// a datagram costs a slice of the picture rather than a whole frame. +static const int kSliceMaxSize = PICA_MEDIA_SAFE_PAYLOAD; + +static QString ff_errstr(int err) +{ + char buf[256] = {0}; + av_strerror(err, buf, sizeof(buf)); + return QString::fromLocal8Bit(buf); +} + +#ifdef Q_OS_WIN +// Both defined in videodshow.cpp. FFmpeg's dshow demuxer can capture but can +// neither enumerate the cameras nor say what formats one offers, so both +// answers come from DirectShow itself. +QList<MediaDeviceInfo> pica_enumerate_dshow_video(); +QStringList pica_dshow_compressed_formats(const QString &device); +#endif + +#ifdef Q_OS_LINUX +// Compressed formats worth forwarding untouched, best first: HEVC gives the +// most picture per byte, H.264 is the widely supported middle ground, and +// MJPEG - every frame a standalone JPEG - costs far more bandwidth but still +// beats decoding and re-encoding. The names are FFmpeg codec names, as used +// by the v4l2 demuxer's input_format option and by the 0x75 protocol message. +static const struct +{ + unsigned int v4l2_pixelformat; + const char *ffmpeg_codec; +} kCompressedFormatPreference[] = +{ + { V4L2_PIX_FMT_HEVC, "hevc" }, + { V4L2_PIX_FMT_H264, "h264" }, + { V4L2_PIX_FMT_MJPEG, "mjpeg" }, + // Some cameras report plain JPEG rather than MJPEG for the same stream. + { V4L2_PIX_FMT_JPEG, "mjpeg" } +}; +#endif + +// Which FFmpeg encoder produces each of the codecs the "Video Codec" setting +// offers, on the GPU and in software. Several names per codec because FFmpeg +// names its external library encoders after the library rather than after the +// codec, and names a hardware one after the API that drives it - VAAPI where +// there is libva, Direct3D 12 and Media Foundation on Windows. The id as well, +// so that a build without the library named here can still fall back to +// whatever other encoder it has for the same codec. +// +// A null hardware name means that API has no encoder for the codec: neither +// D3D12 Video nor FFmpeg's Media Foundation wrapper has VP9 encoding, so a call +// set to VP9 encodes in software on Windows however the acceleration settings +// stand. +static const struct +{ + const char *codec; + AVCodecID id; + const char *vaapiEncoder; + const char *d3d12vaEncoder; + const char *mediaFoundationEncoder; + const char *swEncoder; +} kVideoEncoders[] = +{ + { "h264", AV_CODEC_ID_H264, "h264_vaapi", "h264_d3d12va", "h264_mf", "libx264" }, + { "hevc", AV_CODEC_ID_HEVC, "hevc_vaapi", "hevc_d3d12va", "hevc_mf", "libx265" }, + { "vp9", AV_CODEC_ID_VP9, "vp9_vaapi", nullptr, nullptr, "libvpx-vp9" } +}; + +#ifdef Q_OS_WIN +// The Windows GPU decoders, in the order they are tried when more than one is +// enabled. Direct3D 11 first: it is the one FFmpeg's own tools default to on +// Windows and the most exercised of the three. Direct3D 12 next, being newer +// to FFmpeg, and DXVA2 - Direct3D 9 underneath - last, for GPUs and drivers +// too old for either of the others. +// +// The pixel format is the one the decoder hands back GPU frames in when driven +// through a device of the given type - D3D11 rather than the older +// D3D11VA_VLD, which is the same API set up by hand instead of through a +// hardware context. +static const struct +{ + VideoAcceleration flag; + AVHWDeviceType deviceType; + AVPixelFormat pixelFormat; + const char *name; +} kWindowsHwDecoders[] = +{ + { VideoAccelerationD3d11va, AV_HWDEVICE_TYPE_D3D11VA, AV_PIX_FMT_D3D11, "Direct3D 11" }, +#ifdef HAVE_D3D12VA + { VideoAccelerationD3d12va, AV_HWDEVICE_TYPE_D3D12VA, AV_PIX_FMT_D3D12, "Direct3D 12" }, +#endif + { VideoAccelerationDxva2, AV_HWDEVICE_TYPE_DXVA2, AV_PIX_FMT_DXVA2_VLD, "DXVA2" } +}; +#endif + +static int videoEncoderIndex(const QString &codec) +{ + for (unsigned int i = 0; i < sizeof(kVideoEncoders) / sizeof(kVideoEncoders[0]); i++) + { + if (codec == QLatin1String(kVideoEncoders[i].codec)) + return (int)i; + } + + // An unrecognised setting - written by a build offering something this one + // does not, or by hand - falls back to the codec every peer can decode + // rather than leaving the call without video. + return 0; +} + +// Sets the private options that make an encoder suitable for a live call: +// low latency, no frame reordering, and parameter sets the receiver can pick +// up mid-stream. Each of the three encoders spells all of that differently, +// which is why this is keyed on the encoder rather than on the codec. +static void applyLiveEncoderOptions(AVCodecContext *enc_ctx, const QString &encoderName, int sliceMaxSize) +{ + if (encoderName == QLatin1String("libx264")) + { + av_opt_set(enc_ctx->priv_data, "preset", "veryfast", 0); + av_opt_set(enc_ctx->priv_data, "tune", "zerolatency", 0); + + // Keeps every slice within one datagram of a mediac2c connection, so + // that a lost fragment costs a slice of the picture rather than the + // whole frame. Harmless when the media goes over TCP instead - it + // only splits frames into more NAL units than strictly necessary. + av_opt_set(enc_ctx->priv_data, "x264opts", + QString("slice-max-size=%1").arg(sliceMaxSize).toUtf8().constData(), 0); + } + else if (encoderName == QLatin1String("libx265")) + { + av_opt_set(enc_ctx->priv_data, "preset", "ultrafast", 0); + av_opt_set(enc_ctx->priv_data, "tune", "zerolatency", 0); + + // repeat-headers is the x265 equivalent of leaving + // AV_CODEC_FLAG_GLOBAL_HEADER off below: without it the VPS/SPS/PPS go + // out once, at the start, and a receiver that joins the stream later - + // which every receiver does, the call being already running by the + // time its decoder opens - never sees them. + // + // x265 has no slice-max-size; the nearest thing is a fixed number of + // slices per frame, which does not bound their size. Fragmentation + // handles oversized frames either way, a loss just costs more of the + // picture than it does with x264. + av_opt_set(enc_ctx->priv_data, "x265-params", "repeat-headers=1:bframes=0", 0); + } + else if (encoderName == QLatin1String("libvpx-vp9")) + { + // "realtime" with a high cpu-used is libvpx's zerolatency: it caps how + // long the encoder may spend per frame rather than letting it take as + // long as the quality target needs. + av_opt_set(enc_ctx->priv_data, "deadline", "realtime", 0); + av_opt_set_int(enc_ctx->priv_data, "cpu-used", 8, 0); + // No lookahead - it would hold frames back, which is latency in a + // live call - and keep the bitstream decodable across a loss. + av_opt_set_int(enc_ctx->priv_data, "lag-in-frames", 0, 0); + av_opt_set_int(enc_ctx->priv_data, "error-resilient", 1, 0); + + // VP9 carries no parameter sets to repeat: everything a decoder needs + // is in the keyframe itself, so joining mid-stream needs nothing + // special here. + } +} + +#ifdef Q_OS_WIN +// Defined in videodshow.cpp, alongside the enumeration functions - see the +// comment on pica_enumerate_dshow_video() for why the answers come from +// DirectShow rather than from FFmpeg's demuxer. +QList<VideoCaptureFormat> pica_dshow_capture_formats(const QString &device); +#endif + +#if defined(Q_OS_LINUX) || defined(Q_OS_WIN) +// Frame rates worth offering out of a camera that reports a continuous range +// rather than a list of what it supports. Such a camera will take anything in +// between, so this is only a question of what to put in a dropdown. +static const int kStandardFrameRates[] = { 60, 50, 30, 25, 24, 20, 15, 10, 5 }; + +// Sizes offered for the same reason, out of a camera that reports a range of +// sizes rather than a list. Ones outside the range, or that the reported step +// does not land on, are dropped by the caller. +static const struct +{ + int width; + int height; +} kStandardSizes[] = +{ + { 1920, 1080 }, { 1280, 720 }, { 1024, 768 }, { 800, 600 }, + { 848, 480 }, { 640, 480 }, { 640, 360 }, { 424, 240 }, + { 352, 288 }, { 320, 240 }, { 176, 144 }, { 160, 120 } +}; + +// Largest picture first, and highest frame rate first within each. +static bool captureFormatLessThan(const VideoCaptureFormat &a, const VideoCaptureFormat &b) +{ + const qint64 areaA = (qint64)a.width * a.height; + const qint64 areaB = (qint64)b.width * b.height; + + if (areaA != areaB) + return areaA > areaB; + + return a.width > b.width; +} +#endif + +// Picks the GPU pixel format out of what the decoder offers - the one the +// device attached to the decoder produces, which Play() leaves in +// ctx->opaque. When it is not among them, the first software format is +// returned instead, which leaves the decoder working on the CPU. +// +// Software rather than simply the first entry: the list starts with every +// hwaccel the FFmpeg build has, and one other than ours would only be tried, +// found not to match the device, and taken out of the list again. The same +// happens to ours when the GPU turns out not to support the stream after all - +// FFmpeg then asks again without it, which is when the warning below is +// printed. +static AVPixelFormat hw_get_format(AVCodecContext *ctx, const AVPixelFormat *formats) +{ + const AVPixelFormat wanted = (AVPixelFormat)(intptr_t)ctx->opaque; + const AVPixelFormat *software = nullptr; + + for (const AVPixelFormat *p = formats; *p != AV_PIX_FMT_NONE; p++) + { + if (*p == wanted) + return *p; + + const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p); + + if (!software && desc && !(desc->flags & AV_PIX_FMT_FLAG_HWACCEL)) + software = p; + } + + qWarning() << "The GPU cannot decode this stream, decoding in software"; + + return software ? *software : formats[0]; +} + +QStringList VideoDevice::CompressedFormats(const QString &device) +{ + QStringList result; + +#ifdef Q_OS_LINUX + int fd = ::open(device.toLatin1().constData(), O_RDWR | O_NONBLOCK); + if (fd < 0) + return result; + + // Collect what the camera offers first, then report it in preference + // order rather than in the order the camera happens to list it. + QList<unsigned int> offered; + struct v4l2_fmtdesc fmt; + + memset(&fmt, 0, sizeof fmt); + fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + + for (fmt.index = 0; ::ioctl(fd, VIDIOC_ENUM_FMT, &fmt) == 0; fmt.index++) + { + if (fmt.flags & V4L2_FMT_FLAG_COMPRESSED) + offered << fmt.pixelformat; + } + ::close(fd); + + for (unsigned int i = 0; i < sizeof(kCompressedFormatPreference) / sizeof(kCompressedFormatPreference[0]); i++) + { + QString codec = QLatin1String(kCompressedFormatPreference[i].ffmpeg_codec); + + if (offered.contains(kCompressedFormatPreference[i].v4l2_pixelformat) && !result.contains(codec)) + result << codec; + } +#elif defined(Q_OS_WIN) + result = pica_dshow_compressed_formats(device); +#else + Q_UNUSED(device); +#endif + + return result; +} + +#ifdef Q_OS_LINUX +// Every picture size the camera offers in one pixel format. +// +// A camera answers this in one of two ways: a list of the sizes it has, or a +// range it will scale anything within. There is no list to show for the +// second, so the standard sizes that fall inside the range stand in for one. +static QList<QPair<int, int> > v4l2FrameSizes(int fd, unsigned int pixelformat) +{ + QList<QPair<int, int> > sizes; + struct v4l2_frmsizeenum fs; + + memset(&fs, 0, sizeof fs); + fs.pixel_format = pixelformat; + + for (fs.index = 0; ::ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &fs) == 0; fs.index++) + { + if (fs.type == V4L2_FRMSIZE_TYPE_DISCRETE) + { + sizes << qMakePair((int)fs.discrete.width, (int)fs.discrete.height); + continue; + } + + for (unsigned int i = 0; i < sizeof(kStandardSizes) / sizeof(kStandardSizes[0]); i++) + { + const unsigned int w = kStandardSizes[i].width; + const unsigned int h = kStandardSizes[i].height; + + if (w < fs.stepwise.min_width || w > fs.stepwise.max_width || + h < fs.stepwise.min_height || h > fs.stepwise.max_height) + continue; + + // A continuous camera reports a step of one, so this only ever + // excludes anything on a genuinely stepwise one. + if (fs.stepwise.step_width > 1 && (w - fs.stepwise.min_width) % fs.stepwise.step_width) + continue; + + if (fs.stepwise.step_height > 1 && (h - fs.stepwise.min_height) % fs.stepwise.step_height) + continue; + + sizes << qMakePair((int)w, (int)h); + } + + // A non-discrete answer is a single entry describing the whole range; + // there is no index 1 to ask for. + break; + } + + return sizes; +} + +// v4l2 reports frame intervals - seconds per frame - and we want the rate, so +// every one of these is a reciprocal. +static double v4l2IntervalToFps(const struct v4l2_fract &f) +{ + if (f.numerator == 0 || f.denominator == 0) + return 0.0; + + return (double)f.denominator / (double)f.numerator; +} + +// The frame rates the camera offers for one pixel format at one size, highest +// first. Same two shapes of answer as the sizes above, handled the same way. +static QList<int> v4l2FrameRates(int fd, unsigned int pixelformat, int width, int height) +{ + QList<int> rates; + struct v4l2_frmivalenum fi; + + memset(&fi, 0, sizeof fi); + fi.pixel_format = pixelformat; + fi.width = width; + fi.height = height; + + for (fi.index = 0; ::ioctl(fd, VIDIOC_ENUM_FRAMEINTERVALS, &fi) == 0; fi.index++) + { + if (fi.type == V4L2_FRMIVAL_TYPE_DISCRETE) + { + int fps = qRound(v4l2IntervalToFps(fi.discrete)); + + if (fps > 0 && !rates.contains(fps)) + rates << fps; + + continue; + } + + // The longest interval is the lowest rate, hence the crossed over + // names here. + const double minFps = v4l2IntervalToFps(fi.stepwise.max); + const double maxFps = v4l2IntervalToFps(fi.stepwise.min); + + for (unsigned int i = 0; i < sizeof(kStandardFrameRates) / sizeof(kStandardFrameRates[0]); i++) + { + const int fps = kStandardFrameRates[i]; + + if (fps >= minFps && fps <= maxFps && !rates.contains(fps)) + rates << fps; + } + + break; + } + + std::sort(rates.begin(), rates.end(), std::greater<int>()); + + return rates; +} +#endif + +void pica_merge_capture_rates(VideoCaptureFormat &entry, const QString &codec, + const QList<int> &rates) +{ + int existing = -1; + + for (int p = 0; p < entry.pixelFormats.size(); p++) + { + if (entry.pixelFormats.at(p).codec == codec) + { + existing = p; + break; + } + } + + // Two of a platform's pixel formats can carry the same codec name - v4l2 + // reports MJPEG and plain JPEG separately and both come out as "mjpeg" - + // so a format already seen is added to rather than started again. + if (existing < 0) + { + VideoPixelFormat pf; + + pf.codec = codec; + entry.pixelFormats << pf; + existing = entry.pixelFormats.size() - 1; + } + + VideoPixelFormat &pf = entry.pixelFormats[existing]; + + for (int r = 0; r < rates.size(); r++) + { + if (!pf.frameRates.contains(rates.at(r))) + pf.frameRates << rates.at(r); + + if (!entry.frameRates.contains(rates.at(r))) + entry.frameRates << rates.at(r); + } +} + +void pica_finish_capture_format(VideoCaptureFormat &entry) +{ + std::sort(entry.frameRates.begin(), entry.frameRates.end(), std::greater<int>()); + + // Uncompressed first, then the compressed formats in whatever order the + // platform put compressedFormats in, rather than the order the camera + // happened to list them. + QList<VideoPixelFormat> ordered; + + for (int p = 0; p < entry.pixelFormats.size(); p++) + { + if (entry.pixelFormats.at(p).codec.isEmpty()) + ordered << entry.pixelFormats.at(p); + } + + for (int c = 0; c < entry.compressedFormats.size(); c++) + { + for (int p = 0; p < entry.pixelFormats.size(); p++) + { + if (entry.pixelFormats.at(p).codec == entry.compressedFormats.at(c)) + { + ordered << entry.pixelFormats.at(p); + break; + } + } + } + + for (int p = 0; p < ordered.size(); p++) + std::sort(ordered[p].frameRates.begin(), ordered[p].frameRates.end(), + std::greater<int>()); + + entry.pixelFormats = ordered; +} + +QList<VideoCaptureFormat> VideoDevice::CaptureFormats(const QString &device) +{ + QList<VideoCaptureFormat> result; + +#ifdef Q_OS_LINUX + int fd = ::open(device.toLatin1().constData(), O_RDWR | O_NONBLOCK); + if (fd < 0) + return result; + + // Keyed on the size, because a camera reports its sizes once per pixel + // format and the same size usually comes back several times over. Each + // format it comes back in becomes an entry in pixelFormats, keeping the + // rates that format can manage with the format itself - see + // VideoPixelFormat for why that association matters. + QMap<QPair<int, int>, VideoCaptureFormat> bySize; + + struct v4l2_fmtdesc fmt; + + memset(&fmt, 0, sizeof fmt); + fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + + for (fmt.index = 0; ::ioctl(fd, VIDIOC_ENUM_FMT, &fmt) == 0; fmt.index++) + { + // What this pixel format is called in a 0x75 message, empty for an + // uncompressed one and for a compressed one we would not forward. + QString codec; + + for (unsigned int i = 0; i < sizeof(kCompressedFormatPreference) / sizeof(kCompressedFormatPreference[0]); i++) + { + if (kCompressedFormatPreference[i].v4l2_pixelformat == fmt.pixelformat) + { + codec = QLatin1String(kCompressedFormatPreference[i].ffmpeg_codec); + break; + } + } + + QList<QPair<int, int> > sizes = v4l2FrameSizes(fd, fmt.pixelformat); + + for (int s = 0; s < sizes.size(); s++) + { + VideoCaptureFormat &entry = bySize[sizes.at(s)]; + + entry.width = sizes.at(s).first; + entry.height = sizes.at(s).second; + + if (!codec.isEmpty() && !entry.compressedFormats.contains(codec)) + entry.compressedFormats << codec; + + // Kept against the format it belongs to - MJPEG at 1280x720 and + // uncompressed at 1280x720 are not the same offer - and merged + // into the size's own list as well. + pica_merge_capture_rates(entry, codec, + v4l2FrameRates(fd, fmt.pixelformat, entry.width, entry.height)); + } + } + + ::close(fd); + + for (QMap<QPair<int, int>, VideoCaptureFormat>::iterator it = bySize.begin(); it != bySize.end(); ++it) + { + VideoCaptureFormat entry = it.value(); + + // The formats were collected in whatever order the camera listed them + // in; report them in preference order, the same one + // CompressedFormats() and VideoDevice::Capture() work in. + QStringList ordered; + + for (unsigned int i = 0; i < sizeof(kCompressedFormatPreference) / sizeof(kCompressedFormatPreference[0]); i++) + { + QString codec = QLatin1String(kCompressedFormatPreference[i].ffmpeg_codec); + + if (entry.compressedFormats.contains(codec) && !ordered.contains(codec)) + ordered << codec; + } + + entry.compressedFormats = ordered; + + pica_finish_capture_format(entry); + + result << entry; + } + + std::sort(result.begin(), result.end(), captureFormatLessThan); +#elif defined(Q_OS_WIN) + result = pica_dshow_capture_formats(device); +#else + Q_UNUSED(device); +#endif + + return result; +} + +// A reassembled frame never legitimately approaches this; a stream that does +// is a peer flooding fragments that never carry the last-fragment flag, so the +// partial frame is dropped and reassembly resynchronizes at the next boundary. +static const int kMaxAssembledFrameBytes = 4 * 1024 * 1024; + +VideoFrameAssembler::VideoFrameAssembler() + : m_timestamp(0), m_lastSeq(0) +{ + // Through reset() rather than an initialiser list of its own: a fresh + // assembler and one that has been reset are the same thing, and stating + // that start-of-stream state twice is how the two came to disagree - the + // constructor's copy is what the first call after launch actually uses. + reset(); +} + +void VideoFrameAssembler::reset() +{ + m_buffer.clear(); + m_inProgress = false; + m_haveLastSeq = false; + + // The next fragment is taken to begin a frame, rather than to be the + // middle of one whose start was lost. + // + // Every caller resets a stream that is about to start, never one being + // joined in flight - a call resets before the first packet can arrive, and + // the switch to a mediac2c connection deliberately does not reset, since + // media keeps arriving over either transport for the whole call. So the + // first fragment after this really is the first one the sender sent. + // + // Assuming the opposite costs the stream's first frame, and that frame is + // the one that matters: with a camera's own compressed stream being + // forwarded untouched, it carries the parameter sets and the only keyframe + // the camera will produce for the next ten seconds, so losing it means ten + // seconds of black. If this assumption is ever wrong the cost is one + // truncated frame that the decoder rejects, and the next frame boundary + // resynchronizes as usual. + m_lastWasFrameEnd = true; +} + +QByteArray VideoFrameAssembler::addFragment(quint16 seq_num, quint32 timestamp, const QByteArray &data) +{ + const quint16 counter = seq_num & SeqNumMask; + const bool isLast = (seq_num & LastFragmentFlag) != 0; + bool contiguous = true; + + // Over a mediac2c connection fragments can be lost, so a fragment is only + // accepted if it directly follows the previous one. When it does not, + // what is in the buffer is incomplete and everything up to the end of the + // current frame has to be skipped: a fragment may only begin a frame if + // the one before it ended a frame. Without that rule, losing a frame's + // first fragment would make its second fragment look like the beginning + // of a frame and hand the decoder a truncated one. + if (m_haveLastSeq) + contiguous = (counter == ((m_lastSeq + 1) & SeqNumMask)); + + m_lastSeq = counter; + m_haveLastSeq = true; + + if (!contiguous) + { + // Resynchronize at the next frame boundary. This fragment can still + // start a frame itself, if the gap swallowed whole frames and it + // happens to be a first fragment - which is what a matching new + // timestamp on an empty buffer means. + m_buffer.clear(); + m_inProgress = false; + m_lastWasFrameEnd = false; + } + + if (!m_lastWasFrameEnd && !m_inProgress) + { + // Still in the middle of a frame whose beginning was lost. + m_lastWasFrameEnd = isLast; + return QByteArray(); + } + + // Fragments of one encoded frame all carry the same timestamp; a + // different one while a frame is still being assembled means the rest of + // that frame is never coming, so drop what was collected and start over. + if (m_inProgress && timestamp != m_timestamp) + m_buffer.clear(); + + m_buffer.append(data); + + /* Bound the partial frame: a peer that never sets the last-fragment flag + * would otherwise grow this without limit. Drop it and resync at the next + * frame boundary, exactly as for a lost fragment above. + */ + if (m_buffer.size() > kMaxAssembledFrameBytes) + { + m_buffer.clear(); + m_inProgress = false; + m_lastWasFrameEnd = false; + return QByteArray(); + } + + m_timestamp = timestamp; + m_inProgress = true; + m_lastWasFrameEnd = isLast; + + if (!isLast) + return QByteArray(); + + QByteArray frame = m_buffer; + + m_buffer.clear(); + m_inProgress = false; + + return frame; +} + +VideoDevice::VideoDevice(QObject *parent) + : QObject(parent), m_width(kDefaultCaptureWidth), m_height(kDefaultCaptureHeight), + m_frameRate(kDefaultCaptureFrameRate), m_bitrate(kDefaultVideoBitrateKbps * 1000), + m_preferCompressed(false), + m_acceleration(0), m_useVaapiRender(false), m_reconfigure(0), + m_pendingWidth(0), m_pendingHeight(0), m_pendingAcceleration(0), + m_pendingUseVaapiRender(false), + m_maxFragmentSize(kMaxFragmentSize), m_displaySize(0), m_decoderStarted(0) +{ +} + +void VideoDevice::setDisplaySize(QSize size) +{ + // Packed into one atomic so that the decode loop always reads a width and + // a height that belong together - see m_displaySize. Sizes beyond what + // half an int holds are not real displays, and clamping them is enough: + // the frame is fitted inside this area, so an area larger than the frame + // simply means no resizing. + int width = qBound(0, size.width(), 0xFFFF); + int height = qBound(0, size.height(), 0xFFFF); + + if (width == 0 || height == 0) + { + m_displaySize.storeRelaxed(0); + return; + } + + m_displaySize.storeRelaxed((width << 16) | height); +} + +QSize VideoDevice::displaySize() const +{ + int packed = m_displaySize.loadRelaxed(); + + if (packed == 0) + return QSize(); + + return QSize((packed >> 16) & 0xFFFF, packed & 0xFFFF); +} + +void VideoDevice::setMaxFragmentSize(int size) +{ + if (size <= 0 || size > kMaxFragmentSize) + size = kMaxFragmentSize; + + m_maxFragmentSize.storeRelaxed(size); +} + +VideoDevice::~VideoDevice() +{ + Close(); +} + +void VideoDevice::configureCapture(QString deviceName, int width, int height, int frameRate, + bool preferCompressed, QString codec, int bitrate, + int acceleration, + QByteArray caller_id, QByteArray callee_id) +{ + m_caller_id = caller_id; + m_callee_id = callee_id; + m_deviceName = deviceName; + m_width = width; + m_height = height; + m_frameRate = frameRate > 0 ? frameRate : kDefaultCaptureFrameRate; + m_codec = codec; + m_bitrate = bitrate > 0 ? bitrate : kDefaultVideoBitrateKbps * 1000; + m_preferCompressed = preferCompressed; + m_acceleration = acceleration; +} + +void VideoDevice::configurePlayback(QString codec, int width, int height, + int acceleration, bool useVaapiRender, + QByteArray caller_id, QByteArray callee_id) +{ + m_caller_id = caller_id; + m_callee_id = callee_id; + setPlaybackParams(codec, width, height, acceleration, useVaapiRender); + // A renderer that failed during an earlier call says nothing about this + // one - it may well be a different window. + m_hwRenderDisabled.storeRelaxed(0); +} + +void VideoDevice::setPlaybackParams(const QString &codec, int width, int height, + int acceleration, bool useVaapiRender) +{ + m_codec = codec; + m_width = width; + m_height = height; + // Drawing a VA surface requires having decoded into one in the first + // place, so asking for GPU rendering turns on VAAPI decoding regardless. + m_acceleration = acceleration | (useVaapiRender ? VideoAccelerationVaapi : 0); + m_useVaapiRender = useVaapiRender; + // A fresh decode session, so the startup queue depth applies again until + // this one's loop is consuming - see enqueueFrame(). + m_decoderStarted.storeRelaxed(0); +} + +void VideoDevice::openSession(QByteArray caller_id, QByteArray callee_id) +{ + m_openSession.open(caller_id, callee_id); +} + +void VideoDevice::changePlayback(QString codec, int width, int height, + int acceleration, bool useVaapiRender) +{ + QMutexLocker locker(&m_queueMutex); + + m_pendingCodec = codec; + m_pendingWidth = width; + m_pendingHeight = height; + m_pendingAcceleration = acceleration; + m_pendingUseVaapiRender = useVaapiRender; + m_reconfigure.storeRelaxed(1); + /* encoded with the parameters being replaced */ + m_frameQueue.clear(); + m_queueCond.wakeAll(); +} + +void VideoDevice::disableHardwareRendering() +{ + m_hwRenderDisabled.storeRelaxed(1); +} + +void VideoDevice::enqueueFrame(QByteArray encodedFrame) +{ + QMutexLocker locker(&m_queueMutex); + + // Deeper while the decoder is still starting up - see kStartupQueueDepth. + const int depth = m_decoderStarted.loadRelaxed() ? kMaxQueueDepth : kStartupQueueDepth; + + while (m_frameQueue.size() >= depth) + m_frameQueue.dequeue(); + + m_frameQueue.enqueue(encodedFrame); + m_queueCond.wakeAll(); +} + +void VideoDevice::Close() +{ + m_openSession.close(); + + { + QMutexLocker locker(&m_queueMutex); + m_reconfigure.storeRelaxed(0); + m_frameQueue.clear(); + } + m_queueCond.wakeAll(); +} + +// The string to hand avformat_open_input() for a camera. +// +// DirectShow namespaces its devices by type, so a camera has to be asked for +// as "video=<name>" - the same name behind an "audio=" prefix would be a +// microphone. v4l2 and avfoundation take the device path or index as it comes, +// so the name is stored unprefixed and decorated here, which also keeps what +// the settings dialog shows and stores readable. +static QByteArray cameraOpenUrl(const QString &device) +{ +#ifdef Q_OS_WIN + return (QStringLiteral("video=") + device).toUtf8(); +#else + return device.toUtf8(); +#endif +} + +// Compressed formats in the order to prefer them as something to decode and +// re-encode, which is not the order to prefer them for forwarding untouched - +// that one is in kCompressedFormatPreference, and ranks by bytes on the wire. +// +// Here MJPEG comes first instead of last. Every frame is a standalone JPEG, so +// there are no reference frames to track and no reordering delay, it is the +// cheapest of the three to decode, and it is the one format essentially every +// UVC camera offers. Decoding a camera's H.264 only to re-encode it costs more +// and adds the decoder's delay for nothing, since the result is re-encoded to +// the configured codec and bitrate either way. +static const char * const kTranscodeSourcePreference[] = { "mjpeg", "h264", "hevc" }; + +// One way of opening the camera: which pixel format to ask the driver for, what +// to do with the packets that come back, and how much of the request to insist +// on. Built by buildCaptureAttempts() and tried in order. +struct CaptureAttempt +{ + // v4l2 input_format / dshow codec id to ask for. Empty leaves the choice + // to the camera, which means its default - uncompressed, on every camera + // seen so far. + QString inputFormat; + + // Forward the camera's packets as they arrive instead of decoding and + // re-encoding them. Only ever set for a compressed inputFormat, and only + // when the "prefer compressed formats" setting asked for it: a compressed + // format is also worth asking for purely to get the frame rate, which is + // what the same format with this false means. + bool passthrough; + + bool constrainSize; + bool constrainRate; + + // Why this attempt is in the list, for the log when it fails. + QString reason; +}; + +// Whether a camera has said this format can manage this frame rate. +// +// An empty rate list means the camera would not say, which is not the same as +// saying no - those formats are treated as capable and left to prove it at open +// time, which is how this worked before any of it was enumerated. +static bool formatHasRate(const VideoPixelFormat &format, int frameRate) +{ + return format.frameRates.isEmpty() || frameRate <= 0 || + format.frameRates.contains(frameRate); +} + +// The orders to try opening the camera in, best first. +// +// The point of consulting the enumerated formats here is that a camera asked +// for a frame rate a format cannot carry does not fail - it opens and then +// delivers fewer frames, silently. USB 2.0 does not have the bandwidth for +// uncompressed video at 30fps much above VGA, so asking for the camera's +// default format at 1280x720@30 gets 10fps and no indication of it. Asking for +// MJPEG at the same size gets 30, and decoding it costs far less than the +// missing two thirds of the frames. +// +// Hence the order: forward a compressed stream if that was asked for, then +// uncompressed if it can carry the rate - no decode, no second generation of +// lossy compression - and then compressed as a source to decode and re-encode, +// which is what lifts the frame rate above what the bus will carry raw. +// +// Everything above only considers formats the camera has said can do the job. +// The tail then repeats the whole list with the rate and then the size dropped, +// because listing a format and delivering it at a given size and rate are +// separate claims and cameras routinely honour the first without the others. +// Whatever eventually opens is what gets announced to the peer, so relaxing +// these changes what is sent, not what is claimed. +static QList<CaptureAttempt> buildCaptureAttempts(const QString &device, int width, int height, + int frameRate, bool preferCompressed, + const QString &configuredCodec) +{ + QList<CaptureAttempt> attempts; + QStringList passthroughOrder; + + if (preferCompressed) + { + passthroughOrder = VideoDevice::CompressedFormats(device); + + // The configured codec first when the camera can produce it itself: + // forwarding that one means the peer receives exactly what was asked + // for, rather than whichever compressed format the camera happened to + // rank highest. The rest keep their preference order behind it, since + // forwarding any of them still beats decoding and re-encoding. + if (passthroughOrder.removeAll(configuredCodec) > 0) + passthroughOrder.prepend(configuredCodec); + } + + // What the camera says it can do at this size. Absent - an unsupported + // platform, or a camera that would not be enumerated - leaves every + // candidate below looking capable, which is the behaviour from before any + // of this was known. + VideoCaptureFormat atSize; + + atSize.width = 0; + atSize.height = 0; + + const QList<VideoCaptureFormat> formats = VideoDevice::CaptureFormats(device); + + for (int i = 0; i < formats.size(); i++) + { + if (formats.at(i).width == width && formats.at(i).height == height) + { + atSize = formats.at(i); + break; + } + } + + // Indexed by codec name, empty string being the uncompressed one. A format + // the camera did not list at this size is absent, and absent is not + // capable - unless nothing was enumerated at all, below. + const bool enumerated = !atSize.pixelFormats.isEmpty(); + + for (int i = 0; i < passthroughOrder.size(); i++) + { + const QString codec = passthroughOrder.at(i); + bool capable = !enumerated; + + for (int p = 0; p < atSize.pixelFormats.size(); p++) + { + if (atSize.pixelFormats.at(p).codec == codec) + { + capable = formatHasRate(atSize.pixelFormats.at(p), frameRate); + break; + } + } + + if (capable) + attempts << CaptureAttempt{ codec, true, true, true, + QStringLiteral("forwarded unchanged") }; + } + + bool uncompressedCapable = !enumerated; + + for (int p = 0; p < atSize.pixelFormats.size(); p++) + { + if (atSize.pixelFormats.at(p).codec.isEmpty()) + { + uncompressedCapable = formatHasRate(atSize.pixelFormats.at(p), frameRate); + break; + } + } + + if (uncompressedCapable) + attempts << CaptureAttempt{ QString(), false, true, true, + QStringLiteral("uncompressed, re-encoded here") }; + + for (unsigned int i = 0; i < sizeof(kTranscodeSourcePreference) / sizeof(kTranscodeSourcePreference[0]); i++) + { + const QString codec = QLatin1String(kTranscodeSourcePreference[i]); + + for (int p = 0; p < atSize.pixelFormats.size(); p++) + { + if (atSize.pixelFormats.at(p).codec == codec && + formatHasRate(atSize.pixelFormats.at(p), frameRate)) + { + attempts << CaptureAttempt{ codec, false, true, true, + QStringLiteral("compressed for the frame rate, re-encoded here") }; + break; + } + } + } + + // The loosened tail. Same candidates, in the same order, with the rate + // given up and then the size as well - and without consulting what the + // camera claimed, since by this point its claims have been wrong. + QStringList tail = passthroughOrder; + QList<bool> tailPassthrough; + + for (int i = 0; i < passthroughOrder.size(); i++) + tailPassthrough << true; + + tail << QString(); + tailPassthrough << false; + + for (unsigned int i = 0; i < sizeof(kTranscodeSourcePreference) / sizeof(kTranscodeSourcePreference[0]); i++) + { + const QString codec = QLatin1String(kTranscodeSourcePreference[i]); + + if (!atSize.compressedFormats.contains(codec)) + continue; + + tail << codec; + tailPassthrough << false; + } + + for (int i = 0; i < tail.size(); i++) + attempts << CaptureAttempt{ tail.at(i), tailPassthrough.at(i), true, false, + QStringLiteral("any rate the camera will give") }; + + attempts << CaptureAttempt{ QString(), false, false, false, + QStringLiteral("anything the camera will give") }; + + return attempts; +} + +// One attempt at opening the camera. +// +// inputFormat empty asks for whatever the camera gives; a width of zero +// drops the size and frame rate constraints as well. *ifmt_ctx is left null on +// failure - avformat_open_input() frees and clears it - so the caller can just +// try again. +static int openCamera(const AVInputFormat *ifmt, const QByteArray &url, + int width, int height, int framerate, + const QString &inputFormat, AVFormatContext **ifmt_ctx) +{ + AVDictionary *opts = nullptr; + + if (width > 0 && height > 0) + av_dict_set(&opts, "video_size", QString("%1x%2").arg(width).arg(height).toUtf8().constData(), 0); + + if (framerate > 0) + av_dict_set(&opts, "framerate", QString::number(framerate).toUtf8().constData(), 0); + + if (!inputFormat.isEmpty()) + { +#ifdef Q_OS_WIN + // dshow has no input_format option. It picks the compressed stream + // from AVFormatContext::video_codec_id instead, which is what + // "-vcodec mjpeg" ahead of "-i" sets on the command line - and that + // has to be set on a context allocated here, since + // avformat_open_input() would otherwise make one only after the point + // where the demuxer reads it. + const AVCodec *dec = avcodec_find_decoder_by_name(inputFormat.toUtf8().constData()); + + if (!dec) + { + av_dict_free(&opts); + return AVERROR(EINVAL); + } + + *ifmt_ctx = avformat_alloc_context(); + + if (!*ifmt_ctx) + { + av_dict_free(&opts); + return AVERROR(ENOMEM); + } + + (*ifmt_ctx)->video_codec_id = dec->id; +#else + av_dict_set(&opts, "input_format", inputFormat.toUtf8().constData(), 0); +#endif + } + +#ifdef Q_OS_WIN + // The dshow demuxer calls CoInitialize(0) and CoUninitialize() once each + // for every camera it opens - the latter on a failed open as well, and + // whether or not the former succeeded. Capture() keeps this thread in the + // multithreaded apartment, where dshow's CoInitialize(0) fails and counts + // for nothing, so its CoUninitialize() would take away the reference + // Capture() holds. This reference is the one for it to take instead. + // Should dshow not get as far as either call, it is merely left over, + // which keeps the thread in the apartment it should be in anyway. + CoInitializeEx(nullptr, COINIT_MULTITHREADED); +#endif + + int ret = avformat_open_input(ifmt_ctx, url.constData(), ifmt, &opts); + av_dict_free(&opts); + + return ret; +} + +#ifdef Q_OS_WIN +// Holds the calling thread in COM's multithreaded apartment for as long as it +// exists, if the thread is not already committed to the single-threaded one. +// +// Media Foundation, which the h264_mf and hevc_mf encoders go through, refuses +// a thread in the single-threaded apartment - and that is where the dshow +// demuxer puts the capture thread when it opens the camera, unless the thread +// has joined the multithreaded one first. DirectShow itself works in either. +class ComMultithreadedScope +{ +public: + ComMultithreadedScope() : m_hr(CoInitializeEx(nullptr, COINIT_MULTITHREADED)) + { + if (m_hr == RPC_E_CHANGED_MODE) + qWarning() << "The capture thread is already in COM's single-threaded apartment, " + "Media Foundation encoding will not be available"; + } + + ~ComMultithreadedScope() + { + if (SUCCEEDED(m_hr)) + CoUninitialize(); + } + +private: + HRESULT m_hr; +}; +#endif + +void VideoDevice::Capture() +{ + /* closed before it got to start */ + if (sessionClosed()) + return; + +#ifdef Q_OS_WIN + // Before the camera is opened - see ComMultithreadedScope - and for the + // whole of the capture, since the encoder is used on this thread until the + // loop below returns. + ComMultithreadedScope comApartment; +#endif + + avdevice_register_all(); +#if LIBAVFORMAT_VERSION_MAJOR < 58 + av_register_all(); + avcodec_register_all(); +#endif + + const QByteArray deviceUtf8 = cameraOpenUrl(m_deviceName); + const QByteArray driverUtf8 = VideoDevice::PlatformDriverName().toUtf8(); + const AVInputFormat *ifmt = av_find_input_format(driverUtf8.constData()); + if (!ifmt) + { + QString msg = QString("Could not find '%1' video input driver").arg(VideoDevice::PlatformDriverName()); + qWarning() << msg; + emit errorOccurred(msg); + return; + } + + // Which formats to try, in which order, and what to do with each - worked + // out from what the camera said it can deliver at this size and rate. See + // buildCaptureAttempts(). + const QList<CaptureAttempt> attempts = + buildCaptureAttempts(m_deviceName, m_width, m_height, m_frameRate, + m_preferCompressed, m_codec); + + QString passthroughCodec; + AVFormatContext *ifmt_ctx = nullptr; + int ret = AVERROR(EINVAL); + + for (int a = 0; a < attempts.size(); a++) + { + const CaptureAttempt &attempt = attempts.at(a); + + ret = openCamera(ifmt, deviceUtf8, + attempt.constrainSize ? m_width : 0, + attempt.constrainSize ? m_height : 0, + attempt.constrainRate ? m_frameRate : 0, + attempt.inputFormat, &ifmt_ctx); + + if (ret >= 0) + { + // Only a forwarding attempt makes this a passthrough; the same + // format asked for to get the frame rate goes to the transcode + // loop instead. + passthroughCodec = attempt.passthrough ? attempt.inputFormat : QString(); + break; + } + + QString asked; + + if (!attempt.constrainSize) + asked = QStringLiteral("any size or rate"); + else if (attempt.constrainRate) + asked = QString("%1x%2 @%3").arg(m_width).arg(m_height).arg(m_frameRate); + else + asked = QString("%1x%2 at any rate").arg(m_width).arg(m_height); + + qWarning() << QString("Camera '%1': no %2 at %3 - %4 (%5)") + .arg(m_deviceName, + attempt.inputFormat.isEmpty() ? QStringLiteral("stream") : attempt.inputFormat, + asked, + attempt.reason, + ff_errstr(ret)); + } + + if (ret < 0) + { + // Not fatal to the call - it simply proceeds without outgoing video. + QString msg = QString("Could not open camera '%1': %2").arg(m_deviceName, ff_errstr(ret)); + +#ifdef Q_OS_WIN + // A camera that enumerated but will not open is usually not a broken + // camera. Windows will happily list a device while refusing to + // instantiate it, which is what "Let desktop apps access your camera" + // being switched off looks like from here - and what another + // application already holding the camera looks like too. Neither is + // distinguishable from a genuine I/O error at this level, so say so + // rather than leaving the user with an error code that suggests + // hardware trouble. + msg += tr(" - check that \"Let desktop apps access your camera\" is enabled in the " + "Windows camera privacy settings, and that no other application is using it"); +#endif + + qWarning() << msg; + emit errorOccurred(msg); + return; + } + + if ((ret = avformat_find_stream_info(ifmt_ctx, nullptr)) < 0 || ifmt_ctx->nb_streams < 1) + { + QString msg = QString("Could not determine camera stream parameters: %1").arg(ff_errstr(ret)); + qWarning() << msg; + emit errorOccurred(msg); + avformat_close_input(&ifmt_ctx); + return; + } + + AVStream *in_st = ifmt_ctx->streams[0]; + + // Check what actually came back rather than trusting the request. A + // camera can list a format and then open in a different one, and asking + // for it is spelled differently per demuxer - so the one thing worth + // relying on is the stream in front of us. Handing raw frames to the + // passthrough loop would put unencoded video on the wire labelled as + // something it is not. + if (!passthroughCodec.isEmpty()) + { + const AVCodec *wanted = avcodec_find_decoder_by_name(passthroughCodec.toUtf8().constData()); + + if (!wanted || in_st->codecpar->codec_id != wanted->id) + { + qWarning() << QString("Camera '%1' opened as %2 rather than the %3 that was asked for, re-encoding") + .arg(m_deviceName, + QLatin1String(avcodec_get_name(in_st->codecpar->codec_id)), + passthroughCodec); + passthroughCodec.clear(); + } + } + + if (!passthroughCodec.isEmpty()) + runPassthroughLoop(ifmt_ctx, in_st, passthroughCodec); + else + runTranscodeLoop(ifmt_ctx, in_st); + + avformat_close_input(&ifmt_ctx); +} + +void VideoDevice::emitFragments(const unsigned char *data, int size) +{ + // One encoded frame goes out as one or more 0x77 messages; the final one + // is flagged so the receiver knows the frame is complete (see the + // fragmentation notes in the protocol doc). + int offset = 0; + // Read once per frame rather than per fragment, so that a transport + // change in the middle of a frame cannot make the receiving side see a + // frame whose fragments were sized by two different rules. + const int maxFragment = m_maxFragmentSize.loadRelaxed(); + + while (offset < size) + { + int chunk = qMin(maxFragment, size - offset); + bool isLast = (offset + chunk >= size); + + emit packetReady(QByteArray((const char *)data + offset, chunk), isLast); + offset += chunk; + } +} + +// The frame rate the camera actually settled on, which is not necessarily the +// one that was asked for - and when the open had to fall back to letting the +// camera choose, was not asked for at all. Encoding at a rate the frames do +// not arrive at gives a stream whose timestamps disagree with reality, and it +// is also what captureStarted() reports, so that the rate a camera quietly +// substituted is visible rather than having to be measured. +static AVRational cameraFrameRate(AVStream *in_st, int fallbackRate) +{ + AVRational fr = in_st->avg_frame_rate; + + if (fr.num <= 0 || fr.den <= 0) + fr = in_st->r_frame_rate; + + if (fr.num <= 0 || fr.den <= 0) + fr = AVRational{ fallbackRate, 1 }; + + return fr; +} + +void VideoDevice::runPassthroughLoop(AVFormatContext *ifmt_ctx, AVStream *in_st, const QString &codec) +{ + // The camera decides the picture size here, since nothing rescales it on + // the way out - announce what it actually produced. + int width = in_st->codecpar->width > 0 ? in_st->codecpar->width : m_width; + int height = in_st->codecpar->height > 0 ? in_st->codecpar->height : m_height; + + emit captureStarted(codec, width, height, + av_q2d(cameraFrameRate(in_st, m_frameRate))); + + // Nothing encodes here at all - the camera's own packets go out as they + // arrive - so any hardware encoding setting simply has nothing to act on. + emit accelerationInUse(QStringLiteral("no encoding, camera stream forwarded unchanged")); + + AVPacket *pkt = av_packet_alloc(); + bool loggedReadError = false; + + while (!stopRequested()) + { + int ret = av_read_frame(ifmt_ctx, pkt); + if (ret < 0) + { + if (ret == AVERROR(EAGAIN)) + continue; + if (!loggedReadError) + { + qWarning() << QString("Camera read failed: %1").arg(ff_errstr(ret)); + loggedReadError = true; + } + break; + } + + emitFragments(pkt->data, pkt->size); + av_packet_unref(pkt); + } + + av_packet_free(&pkt); +} + +// The pixel format to hand libswscale for a decoded camera frame, and whether +// that frame's values use the full 0-255 range rather than the 16-235 one. +// +// MJPEG decodes to one of the yuvj* formats, which mean "the yuv* of the same +// name, with full range values". libswscale still understands them and infers +// the range, but warns that they are deprecated - and since capturing MJPEG +// and re-encoding it is now the ordinary path for anything above VGA on USB +// 2.0, that warning would otherwise be printed for most calls. Saying the same +// thing the way libswscale asks for it keeps the range explicit instead of +// inferred, and the log readable. +static AVPixelFormat swscaleSourceFormat(AVPixelFormat format, bool *fullRange) +{ + *fullRange = true; + + switch (format) + { + case AV_PIX_FMT_YUVJ420P: + return AV_PIX_FMT_YUV420P; + case AV_PIX_FMT_YUVJ422P: + return AV_PIX_FMT_YUV422P; + case AV_PIX_FMT_YUVJ444P: + return AV_PIX_FMT_YUV444P; + case AV_PIX_FMT_YUVJ440P: + return AV_PIX_FMT_YUV440P; + case AV_PIX_FMT_YUVJ411P: + return AV_PIX_FMT_YUV411P; + default: + break; + } + + *fullRange = false; + return format; +} + +#if defined(HAVE_VAAPI) || defined(HAVE_D3D12VA) +// Opens one of FFmpeg's hardware encoders on a device that has already been +// created, and makes the pool of GPU surfaces it takes its input from. +// +// Shared by the VAAPI and the Direct3D 12 paths, which differ only in the +// device handed in here and in the pixel format naming the memory the surfaces +// live in - from the pool onwards it is the same hwcontext machinery, and the +// encoder is configured exactly as the software one is below. +// +// options are the encoder's private options, as avcodec_open2() takes them; +// null for none. +// +// Returns the opened context with the pool it draws from in *hw_frames_ref, or +// null with nothing left allocated and the reason logged, which leaves the +// caller to encode in software. +static AVCodecContext *openHwEncoder(const AVCodec *enc, AVBufferRef *hw_device_ref, + AVPixelFormat hw_pix_fmt, int width, int height, + AVRational frameRate, int64_t bitrate, int gopSize, + AVDictionary **options, AVBufferRef **hw_frames_ref) +{ + AVCodecContext *enc_ctx = avcodec_alloc_context3(enc); + + *hw_frames_ref = enc_ctx ? av_hwframe_ctx_alloc(hw_device_ref) : nullptr; + + if (!*hw_frames_ref) + { + qWarning() << QString("Could not create a surface pool for the %1 encoder, encoding in software") + .arg(QLatin1String(enc->name)); + if (enc_ctx) avcodec_free_context(&enc_ctx); + return nullptr; + } + + // The pool the encoder draws its input surfaces from. NV12 is what these + // encoders take; the frames themselves live in GPU memory, which is what + // hw_pix_fmt denotes. + AVHWFramesContext *frames_ctx = (AVHWFramesContext *)(*hw_frames_ref)->data; + frames_ctx->format = hw_pix_fmt; + frames_ctx->sw_format = AV_PIX_FMT_NV12; + frames_ctx->width = width; + frames_ctx->height = height; + frames_ctx->initial_pool_size = 20; + + int ret = av_hwframe_ctx_init(*hw_frames_ref); + + if (ret < 0) + { + qWarning() << QString("Could not initialise the surface pool for the %1 encoder (%2), encoding in software") + .arg(QLatin1String(enc->name), ff_errstr(ret)); + av_buffer_unref(hw_frames_ref); + avcodec_free_context(&enc_ctx); + return nullptr; + } + + enc_ctx->width = width; + enc_ctx->height = height; + enc_ctx->pix_fmt = hw_pix_fmt; + enc_ctx->time_base = av_inv_q(frameRate); + enc_ctx->framerate = frameRate; + enc_ctx->bit_rate = bitrate; + enc_ctx->gop_size = gopSize; + enc_ctx->max_b_frames = 0; + enc_ctx->hw_frames_ctx = av_buffer_ref(*hw_frames_ref); + + // No preset/tune here: those belong to the software encoders and mean + // nothing to a hardware one. + ret = avcodec_open2(enc_ctx, enc, options); + + if (ret < 0) + { + // Not "encoding in software" here: the caller may have another way of + // opening it left to try. + qWarning() << QString("The %1 encoder would not open (%2)") + .arg(QLatin1String(enc->name), ff_errstr(ret)); + av_buffer_unref(hw_frames_ref); + avcodec_free_context(&enc_ctx); + return nullptr; + } + + return enc_ctx; +} +#endif + +#ifdef Q_OS_WIN +// Opens one of FFmpeg's Media Foundation encoders. These reach the GPU through +// the encoder the vendor's driver registers with Windows rather than through a +// device of our own, and take their input in system memory, so unlike +// openHwEncoder() there is no device and no surface pool here: NV12 frames go +// in as they are and the driver does the upload. +// +// Returns the opened context, or null with the reason logged. +static AVCodecContext *openMediaFoundationEncoder(const AVCodec *enc, int width, int height, + AVRational frameRate, int64_t bitrate, + int gopSize) +{ + AVCodecContext *enc_ctx = avcodec_alloc_context3(enc); + + if (!enc_ctx) + return nullptr; + + enc_ctx->width = width; + enc_ctx->height = height; + // What the hardware encoders take natively; YUV420P would be converted + // inside the encoder instead of by the scaler we run anyway. + enc_ctx->pix_fmt = AV_PIX_FMT_NV12; + enc_ctx->time_base = av_inv_q(frameRate); + enc_ctx->framerate = frameRate; + enc_ctx->bit_rate = bitrate; + enc_ctx->gop_size = gopSize; + enc_ctx->max_b_frames = 0; + // Becomes CODECAPI_AVLowLatencyMode, which stops the encoder holding + // frames back to look ahead. + enc_ctx->flags |= AV_CODEC_FLAG_LOW_DELAY; + + // Hardware only. Without it FFmpeg would also accept Microsoft's own + // software H.264 encoder, which is worse at the job than the libx264 this + // falls back to when no hardware encoder opens - so "GPU encoding" in the + // status line can be taken at its word. + av_opt_set_int(enc_ctx->priv_data, "hw_encoding", 1, 0); + // Tells the driver what the stream is for, the nearest Media Foundation + // has to x264's zerolatency tune. Constant bitrate because a call has a + // fixed amount of network to fit into. Both are hints that a driver is free + // to ignore, and FFmpeg does not treat them failing as an error. + av_opt_set(enc_ctx->priv_data, "scenario", "video_conference", 0); + av_opt_set(enc_ctx->priv_data, "rate_control", "cbr", 0); + + int ret = avcodec_open2(enc_ctx, enc, nullptr); + + if (ret < 0) + { + qWarning() << QString("The %1 encoder would not open (%2) - no hardware Media Foundation " + "encoder for this codec, or it refused the settings") + .arg(QLatin1String(enc->name), ff_errstr(ret)); + avcodec_free_context(&enc_ctx); + return nullptr; + } + + return enc_ctx; +} +#endif + +void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) +{ + const AVRational frameRate = cameraFrameRate(in_st, m_frameRate); + + // Which encoder produces the configured codec. Looked up once: the GPU + // attempt and the software fallback below are two encoders for the same + // codec, so the peer is told the same thing either way. + const int encIdx = videoEncoderIndex(m_codec); + + // Two seconds between keyframes. A receiver that joins late or loses a + // packet waits this long for a picture, so it is a latency figure as much + // as a bandwidth one - hence deriving it from the real rate rather than + // from a fixed frame count. + const int gopSize = qMax(1, (int)av_q2d(frameRate) * 2); + + int ret; + + // The camera hands us either raw frames or a compressed stream that is + // not being forwarded as-is; either way it goes through a decoder here to + // get raw pictures for the encoder. + const AVCodec *cam_dec = avcodec_find_decoder(in_st->codecpar->codec_id); + AVCodecContext *dec_ctx = cam_dec ? avcodec_alloc_context3(cam_dec) : nullptr; + if (!cam_dec || !dec_ctx || + avcodec_parameters_to_context(dec_ctx, in_st->codecpar) < 0 || + avcodec_open2(dec_ctx, cam_dec, nullptr) < 0) + { + QString msg = "Could not open camera format decoder"; + qWarning() << msg; + emit errorOccurred(msg); + if (dec_ctx) avcodec_free_context(&dec_ctx); + return; + } + + // The GPU encoder is tried first when asked for, and anything that goes + // wrong on the way - no such encoder built into FFmpeg, no usable device, + // no surface pool, the encoder refusing to open - just leaves hardware + // false and takes the software path below. + bool hardware = false; + const AVCodec *enc = nullptr; + AVCodecContext *enc_ctx = nullptr; + AVBufferRef *hw_frames_ref = nullptr; + +#ifdef HAVE_VAAPI + if ((m_acceleration & VideoAccelerationVaapi) && VaapiContext::isAvailable()) + { + enc = avcodec_find_encoder_by_name(kVideoEncoders[encIdx].vaapiEncoder); + AVBufferRef *hw_device_ref = enc ? VaapiContext::deviceRef() : nullptr; + + if (hw_device_ref) + { + enc_ctx = openHwEncoder(enc, hw_device_ref, AV_PIX_FMT_VAAPI, + m_width, m_height, frameRate, m_bitrate, gopSize, + nullptr, &hw_frames_ref); + + // Newer Intel GPUs (iHD driver, Gen11+) expose only the low-power + // VAEntrypointEncSliceLP, which FFmpeg will not pick unless asked. + if (!enc_ctx) + { + AVDictionary *opts = nullptr; + av_dict_set(&opts, "low_power", "1", 0); + enc_ctx = openHwEncoder(enc, hw_device_ref, AV_PIX_FMT_VAAPI, + m_width, m_height, frameRate, m_bitrate, gopSize, + &opts, &hw_frames_ref); + av_dict_free(&opts); + } + + hardware = enc_ctx != nullptr; + + av_buffer_unref(&hw_device_ref); + } + else if (enc) + { + qWarning() << "No usable VAAPI device, encoding in software"; + } + else + { + qWarning() << QString("FFmpeg has no %1 encoder, encoding in software") + .arg(QLatin1String(kVideoEncoders[encIdx].vaapiEncoder)); + } + + if (!hardware) + enc = nullptr; + } +#endif + +#ifdef HAVE_D3D12VA + // What the same request means on Windows, where the GPU is reached + // through D3D12 Video rather than through libva. Written as a fallback + // after the VAAPI attempt rather than as its alternative so that a build + // that somehow has both - libva has a Windows port of its own - still + // gets a hardware encoder if only one of the two comes up. + // + // The device is created per capture session and dropped with it, unlike + // the VAAPI one: nothing else in the client holds a D3D12 device - the + // decoder makes its own, and rendering does not go through one. + if (!hardware && (m_acceleration & VideoAccelerationD3d12va)) + { + const char *encoderName = kVideoEncoders[encIdx].d3d12vaEncoder; + + enc = encoderName ? avcodec_find_encoder_by_name(encoderName) : nullptr; + + AVBufferRef *hw_device_ref = nullptr; + ret = enc ? av_hwdevice_ctx_create(&hw_device_ref, AV_HWDEVICE_TYPE_D3D12VA, + nullptr, nullptr, 0) + : 0; + + if (hw_device_ref) + { + // Given only a bitrate, FFmpeg picks the rate control itself and + // asks the driver for VBR and then CBR - nothing else. A driver can + // refuse both, AMD's does, so QVBR is asked for explicitly after + // that: still held to the bitrate, with a quality target on top. + // Null is FFmpeg's own choice. + static const char * const kRateControls[] = { nullptr, "QVBR" }; + + for (unsigned int r = 0; !enc_ctx && r < sizeof(kRateControls) / sizeof(kRateControls[0]); r++) + { + // The D3D12 encoders keep up to async_depth frames in flight + // and hand a packet back only once that many have gone in, so + // the default of two holds every frame back by one - a frame + // interval of latency for nothing, with one frame at a time + // coming in. + AVDictionary *options = nullptr; + + av_dict_set(&options, "async_depth", "1", 0); + if (kRateControls[r]) + av_dict_set(&options, "rc_mode", kRateControls[r], 0); + + enc_ctx = openHwEncoder(enc, hw_device_ref, AV_PIX_FMT_D3D12, + m_width, m_height, frameRate, m_bitrate, gopSize, + &options, &hw_frames_ref); + av_dict_free(&options); + } + + hardware = enc_ctx != nullptr; + + // None of the modes that follow a bitrate. Constant QP has no + // bitrate limit at all - a moving picture can take many times what + // the call was set to - so it is not used, but whether the driver + // has it is worth a line in the log: it decides whether this GPU + // could be used with rate control of our own instead. + if (!hardware) + { + AVDictionary *options = nullptr; + AVBufferRef *probe_frames_ref = nullptr; + + av_dict_set(&options, "rc_mode", "CQP", 0); + + AVCodecContext *probe = openHwEncoder(enc, hw_device_ref, AV_PIX_FMT_D3D12, + m_width, m_height, frameRate, m_bitrate, + gopSize, &options, &probe_frames_ref); + av_dict_free(&options); + + // FFmpeg's own messages above say why each attempt failed; + // this says what the attempts were, and what the probe found. + qWarning() << QString("The %1 encoder would not open with any rate control that " + "follows a bitrate (FFmpeg's choice, then QVBR); it %2 with " + "constant QP. Encoding in software") + .arg(QLatin1String(enc->name), + probe ? QStringLiteral("does open") : QStringLiteral("does not open either")); + + if (probe) + { + avcodec_free_context(&probe); + av_buffer_unref(&probe_frames_ref); + } + } + + av_buffer_unref(&hw_device_ref); + } + else if (enc) + { + // Where the GPU or the version of Windows cannot encode at all, + // which is a plain answer rather than a fault: D3D12 video + // encoding needs Windows 11, or Windows 10 with the Agility SDK + // alongside the client. + qWarning() << QString("No usable Direct3D 12 encoding device (%1), encoding in software") + .arg(ff_errstr(ret)); + } + else if (encoderName) + { + qWarning() << QString("FFmpeg has no %1 encoder, encoding in software") + .arg(QLatin1String(encoderName)); + } + else + { + qWarning() << QString("Direct3D 12 cannot encode %1, encoding in software") + .arg(QLatin1String(kVideoEncoders[encIdx].codec)); + } + + if (!hardware) + enc = nullptr; + } +#endif + +#ifdef Q_OS_WIN + // Last of the hardware paths: Media Foundation goes through whatever + // encoder the GPU vendor's driver has registered with Windows, so it also + // covers GPUs, drivers and versions of Windows that predate D3D12 video + // encoding. + if (!hardware && (m_acceleration & VideoAccelerationMediaFoundation)) + { + const char *encoderName = kVideoEncoders[encIdx].mediaFoundationEncoder; + + enc = encoderName ? avcodec_find_encoder_by_name(encoderName) : nullptr; + + if (enc) + { + enc_ctx = openMediaFoundationEncoder(enc, m_width, m_height, frameRate, + m_bitrate, gopSize); + hardware = enc_ctx != nullptr; + } + else if (encoderName) + { + qWarning() << QString("FFmpeg has no %1 encoder, encoding in software") + .arg(QLatin1String(encoderName)); + } + else + { + qWarning() << QString("Media Foundation cannot encode %1, encoding in software") + .arg(QLatin1String(kVideoEncoders[encIdx].codec)); + } + + if (!hardware) + enc = nullptr; + } +#endif + + // Named rather than taken from enc->name because the VAAPI branch above + // may have left a different encoder in enc; filled in below for the + // software path, which is the only one the private options apply to. + QString swEncoderName; + + if (!hardware) + { + enc = avcodec_find_encoder_by_name(kVideoEncoders[encIdx].swEncoder); + if (!enc) + enc = avcodec_find_encoder(kVideoEncoders[encIdx].id); + enc_ctx = enc ? avcodec_alloc_context3(enc) : nullptr; + if (!enc || !enc_ctx) + { + QString msg = QString("No %1 encoder available").arg(QLatin1String(kVideoEncoders[encIdx].codec)); + qWarning() << msg; + emit errorOccurred(msg); + if (enc_ctx) avcodec_free_context(&enc_ctx); + avcodec_free_context(&dec_ctx); + return; + } + + swEncoderName = QLatin1String(enc->name); + + enc_ctx->width = m_width; + enc_ctx->height = m_height; + enc_ctx->pix_fmt = AV_PIX_FMT_YUV420P; + enc_ctx->time_base = av_inv_q(frameRate); + enc_ctx->framerate = frameRate; + enc_ctx->bit_rate = m_bitrate; + enc_ctx->gop_size = gopSize; + // B-frames reorder output, which would cost latency in a live call. + enc_ctx->max_b_frames = 0; + + // Note the absence of AV_CODEC_FLAG_GLOBAL_HEADER: we want the parameter + // sets repeated in-band with every keyframe, since the receiving side has + // no out-of-band way to learn them and may start decoding mid-stream. + applyLiveEncoderOptions(enc_ctx, swEncoderName, kSliceMaxSize); + + if ((ret = avcodec_open2(enc_ctx, enc, nullptr)) < 0) + { + QString msg = QString("Could not open the %1 encoder: %2").arg(swEncoderName, ff_errstr(ret)); + qWarning() << msg; + emit errorOccurred(msg); + avcodec_free_context(&enc_ctx); + avcodec_free_context(&dec_ctx); + return; + } + } + + // Which format the camera is actually delivering, reported alongside the + // encoder because the two together explain the frame rate: an uncompressed + // camera stream is what caps the rate on a USB 2.0 bus, and seeing + // "mjpeg" here is what says that cap has been stepped around. See + // buildCaptureAttempts(). + const QString source = in_st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO + ? QStringLiteral("uncompressed") + : QString::fromLatin1(avcodec_get_name(in_st->codecpar->codec_id)); + + // Named from the encoder that was actually opened rather than written out + // per API: "h264_vaapi" and "hevc_d3d12va" say both which codec and which + // accelerator settled it, and cannot drift from what is running. + emit accelerationInUse(hardware + ? QString("GPU encoding (%1) from %2") + .arg(QLatin1String(enc->name), source) + : QString("CPU encoding (%1) from %2").arg(swEncoderName, source)); + + // Everything the camera sends is scaled to the encoder's size and re-encoded, + // so this is what the peer will receive regardless of what the camera + // produced. The codec name is taken from the encoder rather than written + // out literally, so that changing the encoder above cannot leave the peer + // being told something else - avcodec_get_name() yields exactly the + // FFmpeg codec names the 0x75 message is defined in terms of. + // + // The rate is the camera's, not the encoder's: the encoder is configured + // from it (see frameRate above) and encodes every frame it is given, so + // what the camera delivers is what goes out. + emit captureStarted(QLatin1String(avcodec_get_name(enc_ctx->codec_id)), + enc_ctx->width, enc_ctx->height, av_q2d(frameRate)); + + // What the camera's frames are scaled into. With an encoder that draws on + // a surface pool this is only a staging buffer in system memory - NV12, + // which is what the GPU encoders take - that gets uploaded to a GPU + // surface below; the encoder itself consumes surfaces and never sees this + // frame. Every other encoder, Media Foundation's included, takes it as it + // is. + AVPixelFormat sw_pix_fmt = enc_ctx->hw_frames_ctx ? AV_PIX_FMT_NV12 : enc_ctx->pix_fmt; + + AVFrame *enc_frame = av_frame_alloc(); + if (enc_frame) + { + enc_frame->format = sw_pix_fmt; + enc_frame->width = enc_ctx->width; + enc_frame->height = enc_ctx->height; + } + if (!enc_frame || av_frame_get_buffer(enc_frame, 0) < 0) + { + QString msg = "Could not allocate encoder frame"; + qWarning() << msg; + emit errorOccurred(msg); + if (enc_frame) av_frame_free(&enc_frame); + if (hw_frames_ref) av_buffer_unref(&hw_frames_ref); + avcodec_free_context(&enc_ctx); + avcodec_free_context(&dec_ctx); + return; + } + + SwsContext *sws = nullptr; + AVPacket *in_pkt = av_packet_alloc(); + AVFrame *cam_frame = av_frame_alloc(); + AVPacket *out_pkt = av_packet_alloc(); + int64_t pts = 0; + bool loggedReadError = false; + bool loggedScaleError = false; + bool loggedEncodeError = false; + + while (!stopRequested()) + { + ret = av_read_frame(ifmt_ctx, in_pkt); + if (ret < 0) + { + if (ret == AVERROR(EAGAIN)) + continue; + if (!loggedReadError) + { + qWarning() << QString("Camera read failed: %1").arg(ff_errstr(ret)); + loggedReadError = true; + } + break; + } + + ret = avcodec_send_packet(dec_ctx, in_pkt); + av_packet_unref(in_pkt); + if (ret < 0) + continue; + + while (avcodec_receive_frame(dec_ctx, cam_frame) == 0) + { + // Built lazily: the camera's actual frame format and size are + // only known once a frame has been decoded, and may differ from + // what was requested. + if (!sws) + { + bool srcFullRange = false; + const AVPixelFormat srcFormat = + swscaleSourceFormat((AVPixelFormat)cam_frame->format, &srcFullRange); + + sws = sws_getContext(cam_frame->width, cam_frame->height, srcFormat, + enc_ctx->width, enc_ctx->height, sw_pix_fmt, + SWS_BILINEAR, nullptr, nullptr, nullptr); + if (!sws) + { + if (!loggedScaleError) + { + qWarning() << "Could not set up capture scaler"; + loggedScaleError = true; + } + av_frame_unref(cam_frame); + continue; + } + + // The range the format name no longer carries. The encoder + // wants the studio range, so this is a real conversion and not + // just a label: without it a JPEG frame's blacks and whites + // would be clipped rather than compressed into 16-235. + if (srcFullRange) + { + const int *coefs = sws_getCoefficients(SWS_CS_DEFAULT); + + sws_setColorspaceDetails(sws, coefs, 1, coefs, 0, + 0, 1 << 16, 1 << 16); + } + } + + if (av_frame_make_writable(enc_frame) < 0) + { + av_frame_unref(cam_frame); + continue; + } + + sws_scale(sws, cam_frame->data, cam_frame->linesize, 0, cam_frame->height, + enc_frame->data, enc_frame->linesize); + av_frame_unref(cam_frame); + + enc_frame->pts = pts++; + + // What actually goes to the encoder: the staging frame itself, or + // a GPU surface holding a copy of it for an encoder that draws on + // a surface pool. + AVFrame *frame_to_encode = enc_frame; + AVFrame *hw_frame = nullptr; + + if (enc_ctx->hw_frames_ctx) + { + hw_frame = av_frame_alloc(); + + if (!hw_frame || + av_hwframe_get_buffer(enc_ctx->hw_frames_ctx, hw_frame, 0) < 0 || + av_hwframe_transfer_data(hw_frame, enc_frame, 0) < 0) + { + if (!loggedEncodeError) + { + qWarning() << "Could not upload the frame to the GPU"; + loggedEncodeError = true; + } + if (hw_frame) av_frame_free(&hw_frame); + continue; + } + + hw_frame->pts = enc_frame->pts; + frame_to_encode = hw_frame; + } + + int send_ret = avcodec_send_frame(enc_ctx, frame_to_encode); + + // An encoder with an input queue of its own - Media Foundation's + // hardware ones are - can refuse a frame until the packets it has + // ready are taken. Take them and offer the frame again, rather than + // dropping it and reporting a failure that is not one. + if (send_ret == AVERROR(EAGAIN)) + { + while (avcodec_receive_packet(enc_ctx, out_pkt) == 0) + { + emitFragments(out_pkt->data, out_pkt->size); + av_packet_unref(out_pkt); + } + + send_ret = avcodec_send_frame(enc_ctx, frame_to_encode); + } + + if (hw_frame) + av_frame_free(&hw_frame); + + if (send_ret != 0) + { + if (!loggedEncodeError) + { + qWarning() << QString("%1 encode failed").arg(QLatin1String(avcodec_get_name(enc_ctx->codec_id))); + loggedEncodeError = true; + } + continue; + } + + while (avcodec_receive_packet(enc_ctx, out_pkt) == 0) + { + emitFragments(out_pkt->data, out_pkt->size); + av_packet_unref(out_pkt); + } + } + } + + av_packet_free(&in_pkt); + av_packet_free(&out_pkt); + av_frame_free(&cam_frame); + av_frame_free(&enc_frame); + if (sws) sws_freeContext(sws); + if (hw_frames_ref) av_buffer_unref(&hw_frames_ref); + avcodec_free_context(&enc_ctx); + avcodec_free_context(&dec_ctx); +} + +void VideoDevice::Play() +{ + // More than one pass only when changePlayback() interrupts the one that is + // running. Also covers being closed before getting to start. + while (!sessionClosed()) + { + { + QMutexLocker locker(&m_queueMutex); + + if (m_reconfigure.loadRelaxed()) + { + setPlaybackParams(m_pendingCodec, m_pendingWidth, m_pendingHeight, + m_pendingAcceleration, m_pendingUseVaapiRender); + m_reconfigure.storeRelaxed(0); + } + } + + decode(); + + /* closed, or gave up on an error */ + if (!m_reconfigure.loadRelaxed()) + break; + } +} + +void VideoDevice::decode() +{ +#if LIBAVFORMAT_VERSION_MAJOR < 58 + avcodec_register_all(); +#endif + + // The peer announces its codec by FFmpeg name in the 0x75 message, which + // is exactly what avcodec_find_decoder_by_name() takes - so whatever the + // other side ends up sending (its own camera's hevc/h264/mjpeg stream + // forwarded untouched, or h264 it encoded itself) is handled here without + // a codec list to keep in step. + const AVCodec *dec = avcodec_find_decoder_by_name(m_codec.toLatin1().constData()); + if (dec && dec->type != AVMEDIA_TYPE_VIDEO) + dec = nullptr; + AVCodecContext *dec_ctx = dec ? avcodec_alloc_context3(dec) : nullptr; + + // The GPU API the decoder ended up attached to, for the status line; null + // while decoding in software. + const char *hwDecoderName = nullptr; + +#ifdef HAVE_VAAPI + // Has to be attached before opening the decoder. Unlike encoding, there is + // no separate hardware decoder to look up: the ordinary decoder is told to + // use a VAAPI device, and get_format then picks the GPU pixel format when + // the codec and hardware between them can manage it. + if ((m_acceleration & VideoAccelerationVaapi) && dec_ctx && VaapiContext::isAvailable()) + { + AVBufferRef *hw_device_ref = VaapiContext::deviceRef(); + + if (hw_device_ref) + { + // The context takes ownership of this reference. + dec_ctx->hw_device_ctx = hw_device_ref; + dec_ctx->opaque = (void *)(intptr_t)AV_PIX_FMT_VAAPI; + dec_ctx->get_format = hw_get_format; + hwDecoderName = "VAAPI"; + } + else + { + qWarning() << "No usable VAAPI device, decoding in software"; + } + } +#endif + +#ifdef Q_OS_WIN + // The same arrangement on Windows, with a device of our own per decode + // session - created here and freed with the decoder - since nothing else in + // the client holds one. The first API in kWindowsHwDecoders whose device + // comes up is the one used. + for (unsigned int i = 0; + dec_ctx && !dec_ctx->hw_device_ctx && i < sizeof(kWindowsHwDecoders) / sizeof(kWindowsHwDecoders[0]); + i++) + { + if (!(m_acceleration & kWindowsHwDecoders[i].flag)) + continue; + + AVBufferRef *hw_device_ref = nullptr; + int ret = av_hwdevice_ctx_create(&hw_device_ref, kWindowsHwDecoders[i].deviceType, + nullptr, nullptr, 0); + + if (ret < 0) + { + qWarning() << QString("No usable %1 decoding device (%2)") + .arg(QLatin1String(kWindowsHwDecoders[i].name), ff_errstr(ret)); + continue; + } + + dec_ctx->hw_device_ctx = hw_device_ref; + dec_ctx->opaque = (void *)(intptr_t)kWindowsHwDecoders[i].pixelFormat; + dec_ctx->get_format = hw_get_format; + hwDecoderName = kWindowsHwDecoders[i].name; + } +#endif + + if (!dec || !dec_ctx || avcodec_open2(dec_ctx, dec, nullptr) < 0) + { + QString msg = QString("Unsupported call video codec: %1").arg(m_codec); + qWarning() << msg; + emit errorOccurred(msg); + if (dec_ctx) avcodec_free_context(&dec_ctx); + return; + } + + SwsContext *sws = nullptr; + int sws_width = 0, sws_height = 0; + AVPixelFormat sws_fmt = AV_PIX_FMT_NONE; + // Size the scaler is producing, which is the size of the area the window + // reported through setDisplaySize() with the frame fitted into it - not + // the size of the decoded frame. + int sws_dst_width = 0, sws_dst_height = 0; + AVFrame *dec_frame = av_frame_alloc(); + bool loggedDecodeError = false; + bool loggedScaleError = false; + bool loggedTransferError = false; + // Whether the GPU is really doing the decoding is only knowable from a + // decoded frame, so the answer is reported once the first one arrives + // rather than guessed from what was asked for. + bool reportedAcceleration = false; + + while (true) + { + QByteArray frameData; + { + QMutexLocker locker(&m_queueMutex); + while (m_frameQueue.isEmpty() && !stopRequested()) + m_queueCond.wait(&m_queueMutex, 100); + + if (stopRequested()) + break; + + if (m_frameQueue.isEmpty()) + continue; + + frameData = m_frameQueue.dequeue(); + + // The codec is open and the loop is consuming, so the backlog held + // for startup is no longer wanted: from here on the newest frame + // wins. Set under the queue mutex so enqueueFrame() cannot read it + // while this frame is being taken. + m_decoderStarted.storeRelaxed(1); + } + + AVPacket *in_pkt = av_packet_alloc(); + if (av_new_packet(in_pkt, frameData.size()) < 0) + { + av_packet_free(&in_pkt); + continue; + } + memcpy(in_pkt->data, frameData.constData(), frameData.size()); + + int ret = avcodec_send_packet(dec_ctx, in_pkt); + av_packet_free(&in_pkt); + if (ret < 0) + { + if (!loggedDecodeError) + { + qWarning() << QString("%1 decode failed: %2").arg(m_codec, ff_errstr(ret)); + loggedDecodeError = true; + } + continue; + } + + while (avcodec_receive_frame(dec_ctx, dec_frame) == 0) + { + // A frame left in GPU memory carries the pool it came from, and + // only such a frame does - which settles whether the GPU really + // decoded it, whatever was asked for. + const bool decodedOnGpu = dec_frame->hw_frames_ctx != nullptr; + + if (!reportedAcceleration) + { + emit accelerationInUse(decodedOnGpu && hwDecoderName + ? QString("GPU decoding (%1)").arg(QLatin1String(hwDecoderName)) + : QStringLiteral("CPU decoding")); + reportedAcceleration = true; + } + + // The frame the rest of this iteration works from. A GPU frame + // holds no pixels, so unless it is going straight to a renderer + // that can draw it, it has to be brought down into system memory + // first. + AVFrame *display_frame = dec_frame; + AVFrame *sw_frame = nullptr; + +#ifdef HAVE_VAAPI + if (decodedOnGpu && dec_frame->format == AV_PIX_FMT_VAAPI && + m_useVaapiRender && !m_hwRenderDisabled.loadRelaxed()) + { + // Zero copy: hand the surface itself over, holding a + // reference so it stays alive until the renderer is done. + AVFrame *hw_ref = av_frame_alloc(); + + if (hw_ref && av_frame_ref(hw_ref, dec_frame) == 0) + { + emit hwFrameReady(wrapAVFrame(hw_ref)); + } + else if (hw_ref) + { + av_frame_free(&hw_ref); + } + + av_frame_unref(dec_frame); + continue; + } +#endif + + if (decodedOnGpu) + { + sw_frame = av_frame_alloc(); + + if (!sw_frame || av_hwframe_transfer_data(sw_frame, dec_frame, 0) < 0) + { + if (!loggedTransferError) + { + qWarning() << "Could not read the decoded frame back from the GPU"; + loggedTransferError = true; + } + if (sw_frame) av_frame_free(&sw_frame); + av_frame_unref(dec_frame); + continue; + } + + display_frame = sw_frame; + } + + // The picture is converted straight to the size it is going to + // be drawn at, rather than to its own size for the window to + // resize afterwards. The resize costs almost nothing here, + // inside a colour conversion that has to run regardless, and + // nothing is converted only to be discarded when the window is + // smaller than the frame - between 1.1 and 4.6 times cheaper + // over the whole pipeline, see tests/test_videoscaler. + // + // Read once per frame: the window reports a new area on every + // resize, and mid-call resolution changes move the frame size + // underneath it as well. + QSize frameSize(display_frame->width, display_frame->height); + QSize displayArea = displaySize(); + QSize target = displayArea.isEmpty() ? frameSize + : VideoScaler::fitted(frameSize, displayArea); + + if (target.isEmpty()) + target = frameSize; + + // Rebuilt whenever the incoming picture format or size changes, + // or the window is resized - including on the first frame, when + // they first become known. + if (!sws || frameSize.width() != sws_width || frameSize.height() != sws_height || + (AVPixelFormat)display_frame->format != sws_fmt || + target.width() != sws_dst_width || target.height() != sws_dst_height) + { + if (sws) sws_freeContext(sws); + sws_width = frameSize.width(); + sws_height = frameSize.height(); + sws_fmt = (AVPixelFormat)display_frame->format; + sws_dst_width = target.width(); + sws_dst_height = target.height(); + + // AV_PIX_FMT_0RGB32 is laid out exactly as + // QImage::Format_RGB32 on either endianness, so the + // window gets a 32 bit image it can draw without a + // conversion of its own - which Format_RGB888 needed. + sws = sws_getContext(sws_width, sws_height, sws_fmt, + sws_dst_width, sws_dst_height, AV_PIX_FMT_0RGB32, + SWS_BILINEAR, nullptr, nullptr, nullptr); + + if (!sws) + { + if (!loggedScaleError) + { + qWarning() << "Could not set up playback scaler"; + loggedScaleError = true; + } + if (sw_frame) av_frame_free(&sw_frame); + av_frame_unref(dec_frame); + continue; + } + } + + // Allocated per frame rather than reused, which is what lets it + // go to the GUI thread without being copied: the queued signal + // takes a reference to this buffer and the image frees itself + // once the window is done with it. A single reused buffer would + // have to be deep copied instead, since the next frame would + // overwrite it while the window was still drawing. + QImage img(target, QImage::Format_RGB32); + + if (img.isNull()) + { + if (sw_frame) av_frame_free(&sw_frame); + av_frame_unref(dec_frame); + continue; + } + + uint8_t *dst_data[4] = { img.bits(), nullptr, nullptr, nullptr }; + int dst_linesize[4] = { (int)img.bytesPerLine(), 0, 0, 0 }; + + sws_scale(sws, display_frame->data, display_frame->linesize, 0, display_frame->height, + dst_data, dst_linesize); + + emit frameReady(img); + + if (sw_frame) av_frame_free(&sw_frame); + av_frame_unref(dec_frame); + } + } + + av_frame_free(&dec_frame); + if (sws) sws_freeContext(sws); + avcodec_free_context(&dec_ctx); +} + +QList<MediaDeviceInfo> VideoDevice::Enumerate(enum MediaDeviceStreamDirection dir) +{ + QList<MediaDeviceInfo> result; + int index = 0; + +#ifdef Q_OS_WIN + Q_UNUSED(index) + + // Cameras are capture only; nothing renders video to a device here. + if (dir != PLAYBACK) + result = pica_enumerate_dshow_video(); + + return result; +#endif + + if (dir == PLAYBACK) + return result; +#ifdef Q_OS_LINUX + for (int i = 0; i < 64; i++) + { + QString device = QString(QLatin1String("/dev/video%1")).arg(i); + if (QFile::exists(device)) + { + MediaDeviceInfo d; + d.device = device; + + QFile v4l2_name(QString(QLatin1String("/sys/class/video4linux/video%1/name")).arg(i)); + if (v4l2_name.open((QIODevice::ReadOnly | QIODevice::Text))) + { + d.humanReadable = QString(v4l2_name.readLine()).trimmed(); + v4l2_name.close(); + } + /* Skip metadata device nodes introduced in latest kernels + * See: + * https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=088ead25524583e2200aa99111bea2f66a86545a + * https://bugzilla.kernel.org/show_bug.cgi?id=199575 + * Add only devices having V4L2_CAP_VIDEO_CAPTURE capability. + */ + int fd = ::open(d.device.toLatin1().constData(), O_RDWR | O_NONBLOCK); + if (fd < 0) + continue; + struct v4l2_capability cap; + memset(&cap, 0, sizeof cap); + int ret = ::ioctl(fd, VIDIOC_QUERYCAP, &cap); + ::close(fd); + if (ret == -1) + continue; + if (!(cap.device_caps & V4L2_CAP_VIDEO_CAPTURE)) + continue; + d.index = index++; + + result << d; + } + } +#endif + return result; +} + +bool VideoDevice::AccelerationBuiltIn(VideoAcceleration acceleration, bool encoding) +{ + // The device type a decoder has to support to be driven through this + // acceleration; none for one that has no decoding side. + AVHWDeviceType deviceType = AV_HWDEVICE_TYPE_NONE; + + switch (acceleration) + { + case VideoAccelerationVaapi: + deviceType = AV_HWDEVICE_TYPE_VAAPI; + break; +#ifdef HAVE_D3D12VA + case VideoAccelerationD3d12va: + deviceType = AV_HWDEVICE_TYPE_D3D12VA; + break; +#endif + case VideoAccelerationD3d11va: + deviceType = AV_HWDEVICE_TYPE_D3D11VA; + break; + case VideoAccelerationDxva2: + deviceType = AV_HWDEVICE_TYPE_DXVA2; + break; + default: + break; + } + + for (unsigned int i = 0; i < sizeof(kVideoEncoders) / sizeof(kVideoEncoders[0]); i++) + { + if (encoding) + { + const char *name = nullptr; + + if (acceleration == VideoAccelerationVaapi) + name = kVideoEncoders[i].vaapiEncoder; + else if (acceleration == VideoAccelerationD3d12va) + name = kVideoEncoders[i].d3d12vaEncoder; + else if (acceleration == VideoAccelerationMediaFoundation) + name = kVideoEncoders[i].mediaFoundationEncoder; + + if (name && avcodec_find_encoder_by_name(name)) + return true; + + continue; + } + + if (deviceType == AV_HWDEVICE_TYPE_NONE) + return false; + + // A decoder lists a hardware configuration for each hwaccel compiled + // in for it, and a hwaccel is only compiled in along with the + // hardware context it needs - so finding one here answers for both. + const AVCodec *dec = avcodec_find_decoder(kVideoEncoders[i].id); + + for (int c = 0; dec; c++) + { + const AVCodecHWConfig *config = avcodec_get_hw_config(dec, c); + + if (!config) + break; + + if (config->device_type == deviceType && + (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX)) + return true; + } + } + + return false; +} + +QString VideoDevice::PlatformDriverName() +{ +#if defined(Q_OS_LINUX) + return QStringLiteral("v4l2"); +#elif defined(Q_OS_MACOS) || defined(Q_OS_MAC) + return QStringLiteral("avfoundation"); +#elif defined(Q_OS_WIN) + return QStringLiteral("dshow"); +#else + return QStringLiteral("v4l2"); +#endif +} diff --git a/pica-client/videodevice.h b/pica-client/videodevice.h new file mode 100644 index 0000000..3193701 --- /dev/null +++ b/pica-client/videodevice.h @@ -0,0 +1,443 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#ifndef VIDEODEVICE_H +#define VIDEODEVICE_H + +#include "mediadevice.h" +#include "callsettings.h" +#include "vaapi.h" +#include <QObject> +#include <QString> +#include <QByteArray> +#include <QImage> +#include <QQueue> +#include <QMutex> +#include <QWaitCondition> +#include <QSize> +#include <QAtomicInt> + +// Reassembles the fragments of one encoded video frame, as carried by 0x77 +// protocol messages - see the fragmentation description in +// doc/proto-doc-latest.txt. Used both on the receiving end of a call and by +// the settings dialog's local pipeline test. +class VideoFrameAssembler +{ +public: + // A 0x77 sequence number is a last fragment marker in its top bit plus a + // 15 bit packet counter. + static const quint16 LastFragmentFlag = 0x8000; + static const quint16 SeqNumMask = 0x7FFF; + + VideoFrameAssembler(); + + // Adds one received fragment. Returns the complete encoded frame once + // the fragment carrying the last fragment marker has been added, and an + // empty QByteArray while the frame is still incomplete or while waiting + // to resynchronize after a loss. + QByteArray addFragment(quint16 seq_num, quint32 timestamp, const QByteArray &data); + + void reset(); + +private: + QByteArray m_buffer; + quint32 m_timestamp; + bool m_inProgress; + // Counter part of the sequence number of the last accepted fragment, and + // whether that fragment ended a frame. Together they say whether the + // fragment being added continues what came before it or whether + // something was lost on the way - see addFragment(). + quint16 m_lastSeq; + bool m_lastWasFrameEnd; + bool m_haveLastSeq; +}; + +// One pixel format a camera can deliver a particular size in, with the frame +// rates it can deliver that combination at. +// +// The rates are kept per format rather than merged across them because they +// genuinely differ, by a lot. Uncompressed video at 30fps needs more bandwidth +// than USB 2.0 has for anything much above VGA, so a camera that manages +// 1280x720 at 30fps in MJPEG manages only 10fps uncompressed, and 1920x1080 at +// 5fps. A camera asked for more than a format can carry does not refuse: it +// reports success and quietly sends fewer frames. Keeping this association is +// what lets VideoDevice::Capture() ask for a format that can actually deliver +// what was requested instead of finding out afterwards. +struct VideoPixelFormat +{ + // FFmpeg codec name - "mjpeg", "h264", "hevc" - spelled as the v4l2 + // demuxer's input_format option and the 0x75 message spell it. Empty for + // an uncompressed format, which is what a camera gives when asked for + // nothing in particular. + QString codec; + + // Frame rates available at this size in this format, in whole frames per + // second, highest first. Empty when the camera would not say - which is + // not the same as "none", see VideoDevice::Capture(). + QList<int> frameRates; +}; + +// One picture size a camera can deliver, and what it can deliver it in. +// Reported by VideoDevice::CaptureFormats() and shown by the settings dialog's +// resolution and frame rate lists. +struct VideoCaptureFormat +{ + int width; + int height; + + // Every pixel format this size is available in, uncompressed first and + // then the compressed ones in the same order as compressedFormats below. + // This is the detail the two lists after it flatten away. + QList<VideoPixelFormat> pixelFormats; + + // Frame rates the camera offers at this size in its best format for the + // purpose - the union of the rates in pixelFormats. What the size can + // manage at all, rather than what any one format can: reaching the top of + // this list may mean capturing compressed and re-encoding, which is + // Capture()'s business and not the caller's. Highest first, and empty when + // the camera would not say. + QList<int> frameRates; + + // Compressed formats available at this size, as FFmpeg codec names, most + // preferred first. The same names and the same order as + // CompressedFormats() reports for the whole camera, but per size - a + // camera routinely offers MJPEG at its larger sizes only, which is exactly + // what the "prefer compressed formats" setting turns on and what makes the + // choice of size worth showing alongside. + QStringList compressedFormats; +}; + +// Records that a size is available in `codec` - empty for uncompressed - at +// `rates`, adding to that format's entry rather than replacing it, since two +// of a platform's pixel formats can map to the same codec name. The rates go +// into the size's own union as well. +// +// Shared by the v4l2 and the DirectShow enumerator so that both build the same +// shape out of quite different source data. +void pica_merge_capture_rates(VideoCaptureFormat &entry, const QString &codec, + const QList<int> &rates); + +// Puts one size's formats into the order VideoCaptureFormat documents and sorts +// every rate list highest first. Call once per size, after all of its formats +// have been merged in and compressedFormats has been put in the platform's +// preference order - that order is what pixelFormats is then arranged to match. +void pica_finish_capture_format(VideoCaptureFormat &entry); + +// Video counterpart of AudioDevice: a single instance is dedicated to one +// direction - either capture+encode (Capture(), reading from a local camera) +// or decode (Play(), fed from the network via enqueueFrame()). Each instance +// is meant to live on its own QThread, since both Capture() and Play() block +// the calling thread in a loop until Close() is called. +// +// Note the calling rules that come with that, the same ones AudioDevice +// follows: enqueueFrame() and Close() have to reach a loop that is already +// running, so they are internally thread-safe and must be called directly +// rather than through QMetaObject::invokeMethod() - a queued call would sit +// in the event queue behind the very loop it is meant to feed or interrupt. +// configureCapture()/configurePlayback() are the exception: they only run +// before the loop starts, while the thread is still idle. +class VideoDevice : public QObject, public MediaDevice +{ + Q_OBJECT +public: + VideoDevice(QObject *parent = nullptr); + ~VideoDevice(); + + // width, height and frameRate are what the camera is asked for; a camera + // that will not honour them is opened with them loosened rather than not + // at all, see Capture(). + // + // preferCompressed asks for the camera's own compressed stream to be + // forwarded untouched when it offers one, saving the cost of decoding and + // re-encoding every frame. The codec that ends up being used is only + // known once the camera has been opened, and is reported by + // captureStarted() - it is not necessarily the one requested here. + // + // codec is the FFmpeg name of the codec to encode to - "h264", "hevc" or + // "vp9" - and bitrate the rate to encode at, in bits per second. Both + // apply to frames this class encodes itself; a camera stream being + // forwarded untouched is already encoded and neither has anything to act + // on. codec is preferred over the camera's other compressed formats when + // looking for one to forward, so choosing a codec the camera can produce + // itself gets that one rather than merely a compatible one. + // + // acceleration is a set of VideoAcceleration flags naming the hardware + // encoders that may be tried, in this order when several are set: VAAPI, + // Direct3D 12, Media Foundation. Each is a request, not a guarantee: one not + // built in, without usable hardware, or that will not open is passed over + // for the next, and with none left capture encodes in software. Flags for + // decoding-only paths are ignored. + Q_INVOKABLE void configureCapture(QString deviceName, int width, int height, int frameRate, + bool preferCompressed, QString codec, int bitrate, + int acceleration, + QByteArray caller_id, QByteArray callee_id); + + // Allows Capture()/Play() to run for the call this pair of ids names, + // until Close() - the same arrangement as AudioDevice::openSession(). To + // be called directly, before the calls that configure and start the + // device are queued; configureCapture()/configurePlayback() are then given + // the same pair. + void openSession(QByteArray caller_id, QByteArray callee_id); + + // New parameters for a Play() that is already running: the peer may change + // what it sends in the middle of a call, by sending another 0x75. The loop + // closes its decoder and opens one for these. Safe to call from any + // thread, and has to be called directly - the device's own thread is busy + // inside Play(). Frames still waiting to be decoded are dropped, since + // they were encoded with the previous parameters. + void changePlayback(QString codec, int width, int height, + int acceleration, bool useVaapiRender); + + // acceleration is the decoding counterpart of configureCapture()'s: the + // VideoAcceleration flags for the GPU decoders that may be tried, in this + // order: VAAPI, Direct3D 11, Direct3D 12, DXVA2. The first whose device + // comes up is the one used - whether the GPU can decode the particular + // stream is only found out from the stream itself, and a GPU that cannot + // leaves decoding in software rather than moving on to the next API. + // + // useVaapiRender additionally keeps the decoded frames on the GPU and emits + // them through hwFrameReady() instead of frameReady(), for a renderer that + // can draw a VA surface directly; it implies VAAPI decoding, since there is + // no surface to draw otherwise. The Windows decoders always bring their + // frames back to system memory - nothing in the client can draw a Direct3D + // surface yet. + Q_INVOKABLE void configurePlayback(QString codec, int width, int height, + int acceleration, bool useVaapiRender, + QByteArray caller_id, QByteArray callee_id); + + // Push one complete encoded frame (already reassembled from 0x77 + // fragments by the caller) into the decode queue. Safe to call from any + // thread. Drops the oldest queued frame if the buffer is full - for live + // video, showing the newest frame matters more than showing every frame. + void enqueueFrame(QByteArray encodedFrame); + + // Largest amount of encoded data one fragment emitted by packetReady() + // may carry. It changes while a call is running: a media packet sent over + // a mediac2c connection has to fit into a single datagram, which is far + // less than a 0x77 message can hold over TCP. Safe to call from any + // thread, and called directly rather than queued for the same reason + // enqueueFrame() is - the capture loop it affects is already running. + void setMaxFragmentSize(int size); + + // Stops keeping decoded frames in GPU memory, for when the renderer that + // was to draw them turns out to not be able to: decoding carries on, but + // frames come back through system memory and are emitted by frameReady() + // from then on. Safe to call from any thread, and called directly rather + // than queued for the same reason enqueueFrame() is. + void disableHardwareRendering(); + + // The size of the area the decoded frames are going to be drawn in, so + // that Play() can produce them at that size directly. A decoded frame has + // to be resized to the window either way, and doing it inside the colour + // conversion the decode loop already runs costs far less than a second + // pass over the picture afterwards - between 1.1 and 4.6 times less over + // the whole pipeline, see tests/test_videoscaler. + // + // Frames keep their aspect ratio: this is the area to fit inside, not the + // size to produce. An empty size means the display size is not known and + // frames come back at their own resolution. + // + // Changes while a call is running, on every window resize, and is safe to + // call from any thread. Called directly rather than queued for the same + // reason enqueueFrame() is - the decode loop it affects is already + // running. + void setDisplaySize(QSize size); + +public slots: + // Blocking capture+encode loop: opens the configured camera, encodes + // captured frames, and emits packetReady() for each encoded frame, split + // into fragments that fit a single 0x77 protocol message. Returns once + // Close() is called. + virtual void Capture() override; + + // Blocking decode loop: decodes frames pulled from the internal queue + // (see enqueueFrame()) and emits frameReady() for each decoded picture. + // Returns once Close() is called. + virtual void Play() override; + + // Signals a running Capture()/Play() loop to stop and return. Safe to + // call from any thread, and safe to call even if nothing is running. + virtual void Close() override; + +signals: + // Emitted by Capture() once the camera is open and the format actually + // being sent is known - either the camera's own compressed format, when + // forwarding it untouched, or the one this class encodes to. Carries the + // values to announce to the peer, before any packet is emitted. + // + // frameRate is what the camera settled on, which is not necessarily what + // configureCapture() asked for: a camera asked for a rate a pixel format + // cannot carry opens anyway and then delivers fewer frames. Fractional + // because cameras really do offer rates like 7.5fps. Falls back to the + // requested rate when the camera would not say what it is doing, so a + // shortfall it kept quiet about shows up in the measured rate instead - + // see the settings dialog's fps counter. + void captureStarted(QString codec, int width, int height, double frameRate); + + // One fragment of an encoded frame, ready to be sent over the network. + // isLastFragment marks the final fragment of a frame - it maps directly + // onto the 0x77 sequence number's last fragment marker bit. + void packetReady(QByteArray data, bool isLastFragment); + + // One decoded picture from the remote side, ready to be displayed, as a + // Format_RGB32 image - the format a widget draws without converting it + // first. + // + // Already scaled to fit the area last given to setDisplaySize(), keeping + // its aspect ratio, so the receiver can draw it as it stands. At the + // frame's own resolution while no display size has been set. A receiver + // still has to cope with the occasional frame at another size: the ones + // already decoded or in flight when the window is resized arrive at the + // size that was current when they were converted. + void frameReady(QImage frame); + +#ifdef HAVE_VAAPI + // One decoded picture still living in GPU memory as a VA surface, for a + // renderer that can draw it without a round trip through system memory. + // Emitted instead of frameReady() when GPU rendering is in use. + void hwFrameReady(AVFramePtr frame); +#endif + + void errorOccurred(QString message); + + // Says in plain words which path capture or playback actually settled on, + // for the settings dialog to show. A request for GPU work can silently + // come back as software, and forwarding a compressed camera stream skips + // encoding altogether - neither should have to be guessed at. + void accelerationInUse(QString description); + +public: + virtual QList<MediaDeviceInfo> Enumerate(enum MediaDeviceStreamDirection dir); + + // Name of the FFmpeg libavdevice demuxer for the host platform's native + // video capture API. Counterpart of AudioDevice::PlatformDriverName(). + static QString PlatformDriverName(); + + // Compressed formats the given camera can deliver by itself, as FFmpeg + // codec names, ordered by preference: the more efficient the codec, the + // earlier it comes. Empty if the camera offers none, or on platforms + // where the formats cannot be queried - in which case captured frames + // are decoded and re-encoded as usual. + static QStringList CompressedFormats(const QString &device); + + // Every picture size the given camera can deliver, largest first, with the + // frame rates and compressed formats available at each. Empty on a + // platform where the camera cannot be asked - the caller then falls back + // to offering a set of common sizes, which the camera is free to refuse + // the same way it may refuse any other request. + static QList<VideoCaptureFormat> CaptureFormats(const QString &device); + + // Whether the FFmpeg the client runs with was built with what one + // acceleration flag needs in the given direction: a hardware encoder for at + // least one of the call codecs, or the hardware context and a hwaccel for + // at least one of their decoders. Says nothing about whether this machine's + // GPU can use it - only whether there is anything to try at all, which is + // what the settings dialog needs to know before offering it. + static bool AccelerationBuiltIn(VideoAcceleration acceleration, bool encoding); + +private: + QString m_deviceName; + QString m_codec; + int m_width; + int m_height; + int m_frameRate; + int m_bitrate; + bool m_preferCompressed; + // VideoAcceleration flags; which of them apply depends on the direction + // this instance was configured for. + int m_acceleration; + bool m_useVaapiRender; + + // The call that is allowed to run, set by openSession() and Close(), and + // the one this thread's loop was configured for. + MediaCallSession m_openSession; + QByteArray m_caller_id; + QByteArray m_callee_id; + + // Set by changePlayback(), with the parameters it was given kept under + // m_queueMutex until Play() picks them up. + QAtomicInt m_reconfigure; + QString m_pendingCodec; + int m_pendingWidth; + int m_pendingHeight; + int m_pendingAcceleration; + bool m_pendingUseVaapiRender; + + // The call this loop belongs to is over. + bool sessionClosed() const { return !m_openSession.isOpenFor(m_caller_id, m_callee_id); } + // What the loops check: either that, or Play() has to start over with new + // parameters. + bool stopRequested() const { return m_reconfigure.loadRelaxed() || sessionClosed(); } + + void setPlaybackParams(const QString &codec, int width, int height, + int acceleration, bool useVaapiRender); + // One pass of Play(): opens a decoder for the current parameters and + // decodes until stopRequested(). + void decode(); + // Set from another thread by disableHardwareRendering() while the decode + // loop is running, so it has to be read atomically rather than as a plain + // bool like the settings above, which are fixed before the loop starts. + QAtomicInt m_hwRenderDisabled; + // Likewise set from another thread, by setMaxFragmentSize(), while the + // capture loop is running. + QAtomicInt m_maxFragmentSize; + + // Likewise set from another thread, by setDisplaySize(), while the decode + // loop is running. Both dimensions live in the one atomic - width in the + // upper half, height in the lower - so that the decode loop cannot read a + // new width against an old height and scale one frame to a wrong aspect + // ratio. Zero means not known yet. + QAtomicInt m_displaySize; + + QMutex m_queueMutex; + QWaitCondition m_queueCond; + QQueue<QByteArray> m_frameQueue; + + // Steady state: the newest frame wins, because for live video showing the + // current picture matters more than showing every picture. + static const int kMaxQueueDepth = 2; + + // Until the decode loop has taken its first frame it is not behind - it is + // still opening the codec, which happens only after the peer's 0x75 has + // been processed, by which time its packets are already arriving. Applying + // the rule above during that window drops the stream's first keyframe and + // then the frames that follow it, which costs every picture until the next + // keyframe: with a camera's own stream forwarded untouched that can be ten + // seconds away. So a bounded backlog is held instead - a couple of seconds + // at a typical call frame rate - and the queue reverts to the depth above + // as soon as the decoder is actually consuming. + static const int kStartupQueueDepth = 30; + + // Whether the decode loop has taken a frame yet; see enqueueFrame(). Read + // and written from both the decoding thread and whichever thread delivers + // packets, hence atomic. + QAtomicInt m_decoderStarted; + + // What setDisplaySize() was last given, unpacked; an empty size if it has + // not been called. Read by the decode loop, once per frame. + QSize displaySize() const; + + // Sends one encoded frame out as one or more protocol sized fragments. + void emitFragments(const unsigned char *data, int size); + + // The two shapes Capture() can take: forwarding the camera's own + // compressed stream as it arrives, or decoding what the camera sends and + // re-encoding it. Both emit captureStarted() before their first packet. + void runPassthroughLoop(struct AVFormatContext *ifmt_ctx, struct AVStream *in_st, const QString &codec); + void runTranscodeLoop(struct AVFormatContext *ifmt_ctx, struct AVStream *in_st); +}; + +#endif // VIDEODEVICE_H diff --git a/pica-client/videodshow.cpp b/pica-client/videodshow.cpp new file mode 100644 index 0000000..03edbd6 --- /dev/null +++ b/pica-client/videodshow.cpp @@ -0,0 +1,676 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#include "mediadevice.h" +#include "videodevice.h" + +#include <QtGlobal> + +#ifdef Q_OS_WIN + +#include <QDebug> +#include <QList> +#include <QMap> +#include <QPair> +#include <QString> +#include <QStringList> +#include <QVector> +#include <algorithm> +#include <functional> + +// INITGUID before the DirectShow headers so CLSID_SystemDeviceEnum and the +// rest get defined here rather than needing strmiids at link time. The GUIDs +// are emitted with DECLSPEC_SELECTANY, so the ones this shares with +// nativeaudio_wasapi.cpp merge rather than clashing. +#define INITGUID +#include <initguid.h> + +#include <windows.h> +#include <objbase.h> +#include <dshow.h> +// VIDEOINFOHEADER2 lives here rather than in dshow.h, which only brings in the +// FORMAT_VideoInfo2 GUID that names it. +#include <dvdmedia.h> + +static QString wideToQString(LPCWSTR s) +{ + return s ? QString::fromWCharArray(s) : QString(); +} + +// Compressed formats worth forwarding untouched, best first. Same order and +// the same FFmpeg codec names as kCompressedFormatPreference in +// videodevice.cpp - that table is keyed by v4l2 pixel format, this one by the +// FourCC DirectShow reports in BITMAPINFOHEADER::biCompression, but they mean +// the same thing and should be kept in step. +// +// Cameras are inconsistent about which FourCC they use for the same stream, +// so several map to one codec. +static const struct +{ + const char *fourcc; + const char *ffmpeg_codec; +} kDshowCompressedFormats[] = +{ + { "HEVC", "hevc" }, + { "hevc", "hevc" }, + { "H265", "hevc" }, + { "h265", "hevc" }, + { "H264", "h264" }, + { "h264", "h264" }, + { "X264", "h264" }, + { "x264", "h264" }, + { "AVC1", "h264" }, + { "avc1", "h264" }, + { "MJPG", "mjpeg" }, + { "mjpg", "mjpeg" }, + { "dmb1", "mjpeg" }, + { "JPEG", "mjpeg" }, +}; + +static QString fourccToString(DWORD fourcc) +{ + char c[5]; + c[0] = (char)(fourcc & 0xff); + c[1] = (char)((fourcc >> 8) & 0xff); + c[2] = (char)((fourcc >> 16) & 0xff); + c[3] = (char)((fourcc >> 24) & 0xff); + c[4] = 0; + + // Uncompressed types use small numbers rather than four characters - + // BI_RGB is 0 - which would otherwise come out as an unreadable string. + for (int i = 0; i < 4; i++) + { + if (c[i] < 0x20 || c[i] > 0x7e) + return QString("0x%1").arg((quint32)fourcc, 8, 16, QLatin1Char('0')); + } + + return QString::fromLatin1(c); +} + +// AM_MEDIA_TYPE owns two allocations of its own. DeleteMediaType() would do +// this, but it lives in the DirectShow base classes rather than in any library +// worth pulling in for one function. +static void freeMediaType(AM_MEDIA_TYPE *mt) +{ + if (!mt) + return; + + if (mt->cbFormat && mt->pbFormat) + CoTaskMemFree(mt->pbFormat); + if (mt->pUnk) + mt->pUnk->Release(); + + CoTaskMemFree(mt); +} + +// Finds the camera behind one of the device strings enumeration handed out, +// matching on either name for the same reason FFmpeg's demuxer does: the +// friendly name for the common case, the device path where that was not +// unique. Caller releases the moniker. +static IMoniker *findCamera(const QString &device) +{ + ICreateDevEnum *devEnum = nullptr; + if (FAILED(CoCreateInstance(CLSID_SystemDeviceEnum, nullptr, CLSCTX_INPROC_SERVER, + IID_ICreateDevEnum, (void **)&devEnum)) || !devEnum) + return nullptr; + + IEnumMoniker *enumMoniker = nullptr; + HRESULT hr = devEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &enumMoniker, 0); + devEnum->Release(); + + if (hr != S_OK || !enumMoniker) + return nullptr; + + IMoniker *moniker = nullptr; + IMoniker *found = nullptr; + + while (!found && enumMoniker->Next(1, &moniker, nullptr) == S_OK) + { + IPropertyBag *bag = nullptr; + if (SUCCEEDED(moniker->BindToStorage(nullptr, nullptr, IID_IPropertyBag, (void **)&bag)) && bag) + { + VARIANT var; + + VariantInit(&var); + if (SUCCEEDED(bag->Read(L"FriendlyName", &var, nullptr)) && var.vt == VT_BSTR && + wideToQString(var.bstrVal) == device) + { + found = moniker; + } + VariantClear(&var); + + if (!found) + { + VariantInit(&var); + if (SUCCEEDED(bag->Read(L"DevicePath", &var, nullptr)) && var.vt == VT_BSTR && + wideToQString(var.bstrVal).replace(QLatin1Char(':'), QLatin1Char('_')) == device) + { + found = moniker; + } + VariantClear(&var); + } + + bag->Release(); + } + + if (!found) + moniker->Release(); + } + + enumMoniker->Release(); + return found; +} + +// Which compressed formats a camera can hand over ready-made, best first. +// +// The counterpart of the v4l2 VIDIOC_ENUM_FMT walk in +// VideoDevice::CompressedFormats(). DirectShow has no single call for it: the +// camera has to be instantiated, its output pin found, and the pin's stream +// capabilities enumerated one media type at a time. +// +// Note this instantiates the capture filter, which is also the step that fails +// when Windows is refusing the app access to the camera - so an empty list +// here can mean either "offers nothing compressed" or "cannot be opened at +// all". Both lead to the same place, the caller simply transcodes instead. +QStringList pica_dshow_compressed_formats(const QString &device) +{ + QStringList result; + + if (device.isEmpty()) + return result; + + bool didInit = false; + HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); + if (SUCCEEDED(hr)) + didInit = true; + else if (hr != RPC_E_CHANGED_MODE) + return result; + + IMoniker *moniker = findCamera(device); + if (!moniker) + { + if (didInit) + CoUninitialize(); + return result; + } + + IBaseFilter *filter = nullptr; + hr = moniker->BindToObject(nullptr, nullptr, IID_IBaseFilter, (void **)&filter); + moniker->Release(); + + if (FAILED(hr) || !filter) + { + qWarning() << "DirectShow: could not instantiate" << device + << "to ask what formats it offers"; + if (didInit) + CoUninitialize(); + return result; + } + + QStringList offered; + + IEnumPins *enumPins = nullptr; + if (SUCCEEDED(filter->EnumPins(&enumPins)) && enumPins) + { + IPin *pin = nullptr; + + while (enumPins->Next(1, &pin, nullptr) == S_OK) + { + PIN_DIRECTION dir; + IAMStreamConfig *config = nullptr; + + if (SUCCEEDED(pin->QueryDirection(&dir)) && dir == PINDIR_OUTPUT && + SUCCEEDED(pin->QueryInterface(IID_IAMStreamConfig, (void **)&config)) && config) + { + int count = 0, size = 0; + + if (SUCCEEDED(config->GetNumberOfCapabilities(&count, &size)) && size > 0) + { + QVector<quint8> caps(size); + + for (int i = 0; i < count; i++) + { + AM_MEDIA_TYPE *mt = nullptr; + if (FAILED(config->GetStreamCaps(i, &mt, caps.data())) || !mt) + continue; + + // Only the VIDEOINFOHEADER shapes carry a + // BITMAPINFOHEADER, which is where the FourCC lives. + const BITMAPINFOHEADER *bih = nullptr; + + if (mt->formattype == FORMAT_VideoInfo && + mt->cbFormat >= sizeof(VIDEOINFOHEADER)) + bih = &((VIDEOINFOHEADER *)mt->pbFormat)->bmiHeader; + else if (mt->formattype == FORMAT_VideoInfo2 && + mt->cbFormat >= sizeof(VIDEOINFOHEADER2)) + bih = &((VIDEOINFOHEADER2 *)mt->pbFormat)->bmiHeader; + + if (bih) + { + QString fourcc = fourccToString(bih->biCompression); + if (!offered.contains(fourcc)) + offered << fourcc; + } + + freeMediaType(mt); + } + } + } + + if (config) + config->Release(); + pin->Release(); + } + + enumPins->Release(); + } + + filter->Release(); + + // Worth logging whole, not just the ones we recognise. A camera offering + // nothing but uncompressed types here - NV12, YUY2 - while advertising + // MJPEG on the same hardware under v4l2 is the signature of the Windows + // Camera Frame Server, which mediates integrated cameras and hands + // DirectShow the already-decoded output. Nothing to be done about that + // from here, but it is worth being able to tell it apart from a FourCC we + // simply failed to map. + qDebug() << "DirectShow:" << device << "offers" + << (offered.isEmpty() ? QStringLiteral("(nothing)") : offered.join(QLatin1String(", "))); + + // Report in our preference order rather than in the order the camera + // happened to list them. + for (unsigned int i = 0; i < sizeof(kDshowCompressedFormats) / sizeof(kDshowCompressedFormats[0]); i++) + { + QString codec = QLatin1String(kDshowCompressedFormats[i].ffmpeg_codec); + + if (offered.contains(QLatin1String(kDshowCompressedFormats[i].fourcc)) && !result.contains(codec)) + result << codec; + } + + if (didInit) + CoUninitialize(); + + return result; +} + +// Frame rates worth offering out of a pin that reports a range of frame +// intervals rather than one fixed rate. Same list, and the same reasoning, as +// kStandardFrameRates in videodevice.cpp. +static const int kDshowStandardFrameRates[] = { 60, 50, 30, 25, 24, 20, 15, 10, 5 }; + +// DirectShow measures a frame interval in 100 nanosecond units, and we want +// the rate, so this is a reciprocal like the v4l2 one. +static double intervalToFps(LONGLONG interval) +{ + if (interval <= 0) + return 0.0; + + return 10000000.0 / (double)interval; +} + +// Largest picture first - the same order VideoDevice::CaptureFormats() reports +// on Linux, so the settings dialog's list reads the same on both. +static bool dshowFormatLessThan(const VideoCaptureFormat &a, const VideoCaptureFormat &b) +{ + const qint64 areaA = (qint64)a.width * a.height; + const qint64 areaB = (qint64)b.width * b.height; + + if (areaA != areaB) + return areaA > areaB; + + return a.width > b.width; +} + +// Every picture size the camera can deliver, with the frame rates and +// compressed formats available at each. +// +// The counterpart of the v4l2 VIDIOC_ENUM_FRAMESIZES/VIDIOC_ENUM_FRAMEINTERVALS +// walk in VideoDevice::CaptureFormats(), and it comes off the same +// IAMStreamConfig enumeration pica_dshow_compressed_formats() uses: each media +// type carries a size and a FourCC, and the VIDEO_STREAM_CONFIG_CAPS alongside +// it carries the range of frame intervals that size can be delivered at. +// +// The same caveat applies as there: this instantiates the capture filter, so +// an empty list can mean "cannot be opened at all" as much as "offers +// nothing". Either way the caller falls back to a set of common sizes. +QList<VideoCaptureFormat> pica_dshow_capture_formats(const QString &device) +{ + QList<VideoCaptureFormat> result; + + if (device.isEmpty()) + return result; + + bool didInit = false; + HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); + if (SUCCEEDED(hr)) + didInit = true; + else if (hr != RPC_E_CHANGED_MODE) + return result; + + IMoniker *moniker = findCamera(device); + if (!moniker) + { + if (didInit) + CoUninitialize(); + return result; + } + + IBaseFilter *filter = nullptr; + hr = moniker->BindToObject(nullptr, nullptr, IID_IBaseFilter, (void **)&filter); + moniker->Release(); + + if (FAILED(hr) || !filter) + { + qWarning() << "DirectShow: could not instantiate" << device + << "to ask what sizes it offers"; + if (didInit) + CoUninitialize(); + return result; + } + + // Keyed on the size, because a camera lists one media type per size and + // format combination and the same size comes back once per format. + QMap<QPair<int, int>, VideoCaptureFormat> bySize; + + IEnumPins *enumPins = nullptr; + if (SUCCEEDED(filter->EnumPins(&enumPins)) && enumPins) + { + IPin *pin = nullptr; + + while (enumPins->Next(1, &pin, nullptr) == S_OK) + { + PIN_DIRECTION dir; + IAMStreamConfig *config = nullptr; + + if (SUCCEEDED(pin->QueryDirection(&dir)) && dir == PINDIR_OUTPUT && + SUCCEEDED(pin->QueryInterface(IID_IAMStreamConfig, (void **)&config)) && config) + { + int count = 0, size = 0; + + if (SUCCEEDED(config->GetNumberOfCapabilities(&count, &size)) && + size >= (int)sizeof(VIDEO_STREAM_CONFIG_CAPS)) + { + QVector<quint8> caps(size); + + for (int i = 0; i < count; i++) + { + AM_MEDIA_TYPE *mt = nullptr; + if (FAILED(config->GetStreamCaps(i, &mt, caps.data())) || !mt) + continue; + + const BITMAPINFOHEADER *bih = nullptr; + // The nominal interval of this particular media type, + // as opposed to the range in the caps below. + LONGLONG avgTimePerFrame = 0; + + if (mt->formattype == FORMAT_VideoInfo && + mt->cbFormat >= sizeof(VIDEOINFOHEADER)) + { + const VIDEOINFOHEADER *vih = (const VIDEOINFOHEADER *)mt->pbFormat; + bih = &vih->bmiHeader; + avgTimePerFrame = vih->AvgTimePerFrame; + } + else if (mt->formattype == FORMAT_VideoInfo2 && + mt->cbFormat >= sizeof(VIDEOINFOHEADER2)) + { + const VIDEOINFOHEADER2 *vih = (const VIDEOINFOHEADER2 *)mt->pbFormat; + bih = &vih->bmiHeader; + avgTimePerFrame = vih->AvgTimePerFrame; + } + + if (!bih || bih->biWidth <= 0 || bih->biHeight == 0) + { + freeMediaType(mt); + continue; + } + + // A bottom-up DIB states its height negative; the + // picture is the same size either way. + const int width = (int)bih->biWidth; + const int height = bih->biHeight < 0 ? (int)-bih->biHeight : (int)bih->biHeight; + + VideoCaptureFormat &entry = bySize[qMakePair(width, height)]; + entry.width = width; + entry.height = height; + + const QString fourcc = fourccToString(bih->biCompression); + + // Empty for an uncompressed media type, which is what + // pica_merge_capture_rates() wants for one. + QString codec; + + for (unsigned int f = 0; f < sizeof(kDshowCompressedFormats) / sizeof(kDshowCompressedFormats[0]); f++) + { + if (fourcc != QLatin1String(kDshowCompressedFormats[f].fourcc)) + continue; + + codec = QLatin1String(kDshowCompressedFormats[f].ffmpeg_codec); + + if (!entry.compressedFormats.contains(codec)) + entry.compressedFormats << codec; + + break; + } + + const VIDEO_STREAM_CONFIG_CAPS *scc = (const VIDEO_STREAM_CONFIG_CAPS *)caps.constData(); + + // The shortest interval is the highest rate, hence the + // crossed over names. + const double maxFps = intervalToFps(scc->MinFrameInterval); + const double minFps = intervalToFps(scc->MaxFrameInterval); + + // This media type is one size in one format, so the + // rates it offers belong to that format - an + // uncompressed pin capping out well below a compressed + // one at the same size is the whole reason they are + // kept apart, see VideoPixelFormat. + QList<int> rates; + + int nominal = qRound(intervalToFps(avgTimePerFrame)); + + if (nominal > 0) + rates << nominal; + + // A pin that accepts a range of intervals will take + // anything within it, so there is no list to show - + // the standard rates inside the range stand in for one, + // exactly as on the v4l2 side. + for (unsigned int r = 0; r < sizeof(kDshowStandardFrameRates) / sizeof(kDshowStandardFrameRates[0]); r++) + { + const int fps = kDshowStandardFrameRates[r]; + + if (fps >= minFps && fps <= maxFps && !rates.contains(fps)) + rates << fps; + } + + pica_merge_capture_rates(entry, codec, rates); + + freeMediaType(mt); + } + } + } + + if (config) + config->Release(); + pin->Release(); + } + + enumPins->Release(); + } + + filter->Release(); + + for (QMap<QPair<int, int>, VideoCaptureFormat>::iterator it = bySize.begin(); it != bySize.end(); ++it) + { + VideoCaptureFormat entry = it.value(); + + // Report the formats in our preference order rather than in the order + // the camera happened to list them, the same way + // pica_dshow_compressed_formats() does. + QStringList ordered; + + for (unsigned int f = 0; f < sizeof(kDshowCompressedFormats) / sizeof(kDshowCompressedFormats[0]); f++) + { + QString codec = QLatin1String(kDshowCompressedFormats[f].ffmpeg_codec); + + if (entry.compressedFormats.contains(codec) && !ordered.contains(codec)) + ordered << codec; + } + + entry.compressedFormats = ordered; + + pica_finish_capture_format(entry); + + result << entry; + } + + std::sort(result.begin(), result.end(), dshowFormatLessThan); + + if (didInit) + CoUninitialize(); + + return result; +} + +// Lists the cameras DirectShow knows about. +// +// Capture itself goes through FFmpeg's "dshow" demuxer rather than through +// DirectShow directly - it does the job and there is no equivalent of the +// audio situation here, where the platform had something we could not reach +// any other way. But the demuxer has no enumeration API: it can only print +// device names to the log with -list_devices, which is no use to a settings +// dialog. So the list is built here, from the same device category the +// demuxer itself walks, and the names handed back are the ones it matches on. +QList<MediaDeviceInfo> pica_enumerate_dshow_video() +{ + QList<MediaDeviceInfo> result; + + // Qt has already put the GUI thread into an apartment; the reference is + // still ours to balance, hence the matching CoUninitialize() below. + bool didInit = false; + HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); + if (SUCCEEDED(hr)) + didInit = true; + else if (hr != RPC_E_CHANGED_MODE) + return result; + + ICreateDevEnum *devEnum = nullptr; + hr = CoCreateInstance(CLSID_SystemDeviceEnum, nullptr, CLSCTX_INPROC_SERVER, + IID_ICreateDevEnum, (void **)&devEnum); + if (FAILED(hr) || !devEnum) + { + qWarning() << "DirectShow: could not create the device enumerator" + << QString("0x%1").arg((quint32)hr, 8, 16, QLatin1Char('0')); + if (didInit) + CoUninitialize(); + return result; + } + + IEnumMoniker *enumMoniker = nullptr; + hr = devEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &enumMoniker, 0); + + // S_FALSE with a null enumerator is how "no cameras at all" comes back. + if (hr != S_OK || !enumMoniker) + { + devEnum->Release(); + if (didInit) + CoUninitialize(); + return result; + } + + int index = 0; + QStringList seenNames; + IMoniker *moniker = nullptr; + + while (enumMoniker->Next(1, &moniker, nullptr) == S_OK) + { + IPropertyBag *bag = nullptr; + if (FAILED(moniker->BindToStorage(nullptr, nullptr, IID_IPropertyBag, (void **)&bag)) || !bag) + { + moniker->Release(); + continue; + } + + QString friendlyName; + QString uniqueName; + + VARIANT var; + VariantInit(&var); + if (SUCCEEDED(bag->Read(L"FriendlyName", &var, nullptr)) && var.vt == VT_BSTR) + friendlyName = wideToQString(var.bstrVal); + VariantClear(&var); + + VariantInit(&var); + if (SUCCEEDED(bag->Read(L"DevicePath", &var, nullptr)) && var.vt == VT_BSTR) + { + // FFmpeg calls this the device's "alternative name" and matches on + // it as well as on the friendly one, after replacing colons - + // which it uses as a separator in its own device strings. + uniqueName = wideToQString(var.bstrVal).replace(QLatin1Char(':'), QLatin1Char('_')); + } + VariantClear(&var); + + bag->Release(); + moniker->Release(); + + if (friendlyName.isEmpty()) + continue; + + MediaDeviceInfo d; + d.humanReadable = friendlyName; + + // The friendly name is the documented way to name a dshow device and + // the one to prefer. It is not required to be unique though, and two + // identical cameras would both answer to it - the demuxer would open + // whichever came first. Later duplicates therefore fall back to the + // device path, which is unique by construction. + if (!seenNames.contains(friendlyName)) + { + d.device = friendlyName; + seenNames << friendlyName; + } + else if (!uniqueName.isEmpty()) + { + d.device = uniqueName; + d.humanReadable += QString(" (%1)").arg(seenNames.count(friendlyName) + 1); + seenNames << friendlyName; + } + else + { + // Same name, no device path to tell them apart. Listing it again + // would just give the user two entries that open the same camera. + continue; + } + + d.index = index++; + + // Nothing here about what the camera can deliver: that means walking + // its output pin's media types, which pica_dshow_capture_formats() + // does once a camera has actually been selected rather than for every + // camera on the machine. + result << d; + } + + enumMoniker->Release(); + devEnum->Release(); + + if (didInit) + CoUninitialize(); + + return result; +} + +#endif // Q_OS_WIN diff --git a/pica-client/videoscaler.cpp b/pica-client/videoscaler.cpp new file mode 100644 index 0000000..676a78f --- /dev/null +++ b/pica-client/videoscaler.cpp @@ -0,0 +1,195 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ + +#include "videoscaler.h" + +#include <QDebug> + +// FFmpeg headers +extern "C" { +#include <libavutil/pixfmt.h> +#include <libswscale/swscale.h> +} + +// The QImage formats libswscale can be pointed at directly. Anything missing +// here is not an error - scale() just uses Qt for those frames. Premultiplied +// formats are deliberately absent: libswscale has no equivalent, and feeding +// it premultiplied pixels as if they were plain ones would wash the colours +// out. +static AVPixelFormat av_pixel_format(QImage::Format format) +{ + switch (format) + { + case QImage::Format_RGB888: + return AV_PIX_FMT_RGB24; + case QImage::Format_RGB32: + return AV_PIX_FMT_0RGB32; + case QImage::Format_ARGB32: + return AV_PIX_FMT_RGB32; + case QImage::Format_RGBX8888: + return AV_PIX_FMT_RGB0; + case QImage::Format_RGBA8888: + return AV_PIX_FMT_RGBA; + case QImage::Format_Grayscale8: + return AV_PIX_FMT_GRAY8; + default: + return AV_PIX_FMT_NONE; + } +} + +VideoScaler::VideoScaler(Backend backend) + : m_backend(backend), m_lastUsed(backend), m_sws(nullptr), + m_srcWidth(0), m_srcHeight(0), m_srcFormat(AV_PIX_FMT_NONE), + m_dstWidth(0), m_dstHeight(0), m_loggedFailure(false) +{ +} + +VideoScaler::~VideoScaler() +{ + if (m_sws) + sws_freeContext(m_sws); +} + +QSize VideoScaler::fitted(QSize frame, QSize area) +{ + if (frame.isEmpty() || area.isEmpty()) + return QSize(); + + QSize result = frame; + result.scale(area, Qt::KeepAspectRatio); + + // An odd width costs libswscale a factor of four and a half, because it + // drops off its SIMD path and converts the picture a pixel at a time - + // measured, and far and away the largest effect of any of the geometry + // here: destination stride alignment and an odd height both turned out not + // to matter at all. Window widths being whatever the user drags them to, + // half of them would land on the slow path. + // + // So the width is rounded down to even. That loses at most one pixel of + // picture and bends the aspect ratio by well under a tenth of a percent, + // which is less than the rounding above has already done. + // + // It matters that this is the one place the target size is decided. + // VideoDevice::Play() sizes the frames it produces by it and CallWindow + // checks arriving frames against it - if the two disagreed by a pixel, the + // window would resize every frame instead of none of them. + result.setWidth(result.width() & ~1); + + // A picture far thinner than the area it goes into can round down to + // nothing, and neither scaler accepts a zero sized target. + if (result.width() < 2) + result.setWidth(2); + if (result.height() < 1) + result.setHeight(1); + + return result; +} + +QImage VideoScaler::scale(const QImage &frame, QSize area) +{ + QSize target = fitted(frame.size(), area); + + if (target.isEmpty()) + return QImage(); + + if (m_backend == Swscale) + { + QImage scaled = scaleWithSwscale(frame, target); + + if (!scaled.isNull()) + { + m_lastUsed = Swscale; + return scaled; + } + } + + m_lastUsed = QtScaled; + return scaleWithQt(frame, target); +} + +QImage VideoScaler::scaleWithSwscale(const QImage &frame, QSize target) +{ + AVPixelFormat srcFormat = av_pixel_format(frame.format()); + + if (srcFormat == AV_PIX_FMT_NONE) + return QImage(); + + if (!m_sws || frame.width() != m_srcWidth || frame.height() != m_srcHeight || + (int)srcFormat != m_srcFormat || target.width() != m_dstWidth || + target.height() != m_dstHeight) + { + if (m_sws) + { + sws_freeContext(m_sws); + m_sws = nullptr; + } + + // SWS_BILINEAR to match what Qt's SmoothTransformation looks + // like, and what the playback path already converts colours + // with in videodevice.cpp. + m_sws = sws_getContext(frame.width(), frame.height(), srcFormat, + target.width(), target.height(), AV_PIX_FMT_0RGB32, + SWS_BILINEAR, nullptr, nullptr, nullptr); + + if (!m_sws) + { + if (!m_loggedFailure) + { + qWarning() << "Could not set up video display scaler, using Qt instead"; + m_loggedFailure = true; + } + return QImage(); + } + + m_srcWidth = frame.width(); + m_srcHeight = frame.height(); + m_srcFormat = (int)srcFormat; + m_dstWidth = target.width(); + m_dstHeight = target.height(); + + // AV_PIX_FMT_0RGB32 is defined to be exactly this layout on + // either endianness, so libswscale can write into the image + // without a conversion in between - and Qt draws a 32 bit + // image without one either. + m_dst = QImage(target.width(), target.height(), QImage::Format_RGB32); + + if (m_dst.isNull()) + return QImage(); + } + + const uint8_t *srcData[4] = { frame.constBits(), nullptr, nullptr, nullptr }; + int srcStride[4] = { (int)frame.bytesPerLine(), 0, 0, 0 }; + + // bits() would deep copy if m_dst were shared with anyone, which is why + // what scale() hands back only points at this buffer instead of sharing + // it. + uint8_t *dstData[4] = { m_dst.bits(), nullptr, nullptr, nullptr }; + int dstStride[4] = { (int)m_dst.bytesPerLine(), 0, 0, 0 }; + + if (sws_scale(m_sws, srcData, srcStride, 0, frame.height(), dstData, dstStride) <= 0) + return QImage(); + + return QImage(m_dst.constBits(), m_dst.width(), m_dst.height(), + m_dst.bytesPerLine(), m_dst.format()); +} + +QImage VideoScaler::scaleWithQt(const QImage &frame, QSize target) +{ + // The aspect ratio is already accounted for in target, so scaling to it + // exactly avoids rounding the size a second time. + return frame.scaled(target, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); +} diff --git a/pica-client/videoscaler.h b/pica-client/videoscaler.h new file mode 100644 index 0000000..4d05d16 --- /dev/null +++ b/pica-client/videoscaler.h @@ -0,0 +1,128 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#ifndef VIDEOSCALER_H +#define VIDEOSCALER_H + +#include <QImage> +#include <QSize> + +struct SwsContext; + +// Decides what size a video frame should be drawn at, and resizes one when +// something else has not already done it. +// +// Frames arrive at whatever resolution the sender negotiated, which has nothing +// to do with the size of the window they end up in, so each one has to be +// resized before it is drawn - at the frame rate of the call, for as long as it +// lasts. Where that resizing happens turned out to matter a great deal, and +// tests/test_videoscaler is the measurement it was settled by: +// +// - Resizing packed RGB in the window, which is what used to happen, is the +// worst of the options. libswscale is especially bad at it - it has no +// scaler for packed formats, so it unpacks to planar YUV, scales, and packs +// the result back, losing to QImage::scaled() by four to five times. +// +// - Resizing inside the colour conversion the decode loop already runs is +// between 1.1 and 4.6 times faster than the whole two pass pipeline, best +// when the picture is being shrunk, since nothing is converted only to be +// thrown away. libswscale is good at this one: the source is planar YUV, +// which is what it wants, and the resize rides along inside a pass over +// the picture that had to happen anyway. +// +// - Handing the result over without copying it saves another pass again. See +// VideoDevice::Play(), which allocates each frame's QImage rather than +// reusing one buffer, so the queued signal that carries it to the GUI +// thread only has a reference count to bump. +// +// So VideoDevice::Play() does the resizing, and this class is left with two +// jobs. fitted() is the single authority on what size to aim for, shared so +// that the decoder and the window cannot disagree about it. scale() is the +// window's fallback for the frames that arrive at the wrong size anyway - +// during a resize, there are always a few already in flight - and is a no-op +// when the size is already right, which is the steady state. +// +// The libswscale backend is kept for the benchmark to compare against, and to +// keep the conclusion above honest if any of these libraries change. It only +// understands a handful of QImage formats; anything else, and any failure to +// build a scaler, falls back to Qt rather than losing the picture. +class VideoScaler +{ +public: + // Not named after Qt itself - a value called Qt would shadow the + // namespace of the same name inside this class. + enum Backend + { + QtScaled, // QImage::scaled(), the default - measurably the faster one here + Swscale // libswscale, for comparison; falls back to the above when it cannot help + }; + + explicit VideoScaler(Backend backend = QtScaled); + ~VideoScaler(); + + // The size `frame` becomes when fitted into `area` without cropping or + // changing its aspect ratio - never larger than `area`, and never + // smaller than 2x1 so long as both arguments are valid. An empty size + // if either argument is empty. + // + // The width is always even, which is worth a factor of four and a half + // downstream; the reason is with the implementation. Every part of the + // call that needs to know the display size of a frame goes through here, + // so that they all arrive at the same answer. + static QSize fitted(QSize frame, QSize area); + + // Returns `frame` resized to fitted(frame.size(), area), ready to be + // handed to QPixmap::fromImage(). A null image means nothing could be + // produced and the previous picture should be left alone. + // + // The returned image may reference a buffer this object reuses, so it + // is only valid until the next call to scale() - copy it if it needs to + // outlive that. + QImage scale(const QImage &frame, QSize area); + + // Which implementation the last scale() actually used. Not the same as + // the backend asked for: Swscale falls back to QtScaled when it meets a + // frame format it has no mapping for. + Backend lastBackendUsed() const { return m_lastUsed; } + +private: + QImage scaleWithSwscale(const QImage &frame, QSize target); + static QImage scaleWithQt(const QImage &frame, QSize target); + + Backend m_backend; + Backend m_lastUsed; + + // Building a scaler means computing filter tables, so the context is + // kept across frames and only rebuilt when the geometry or the format + // it was built for changes - in practice on the first frame and on a + // window resize. + SwsContext *m_sws; + int m_srcWidth; + int m_srcHeight; + int m_srcFormat; // AVPixelFormat, kept as int to keep ffmpeg out of this header + int m_dstWidth; + int m_dstHeight; + + // Destination of the libswscale path, reused frame to frame. Qt images + // are copy on write, and writing through the raw pointer libswscale is + // given would go behind that, so scale() makes sure this is not shared + // before handing the pointer over. + QImage m_dst; + + bool m_loggedFailure; +}; + +#endif diff --git a/pica-node.conf b/pica-node.conf index 49fbcdc..5be5905 100644 --- a/pica-node.conf +++ b/pica-node.conf @@ -16,6 +16,9 @@ #announced_addr = "autoconfigure"; #TCP port for incoming connections that pica-node listens on. Default is 2299 +#The UDP port with the same number is opened as well: clients send a datagram to it to learn +#which address and port their NAT gives them. pica-node never sends anything from that port, +#it only needs to be reachable. # #listen_port = "2299"; diff --git a/pica-node.conf.5 b/pica-node.conf.5 index 28ed94c..29b9b43 100644 --- a/pica-node.conf.5 +++ b/pica-node.conf.5 @@ -23,12 +23,20 @@ future releases). If the computer running pica-node is behind the NAT, external configured. Default value is "autoconfigure" which makes pica-node try to guess its external IP address. If pica-node is build with miniupnpc support, it will try to employ UPnP protocol to get external IP from the router and enable port - forwarding. + forwarding of both the TCP and the UDP port, see listen_port. The forwarding + is renewed for as long as pica-node runs. .TP .I listen_port Specifies the port number that .BR pica-node (8) -listens on. The default is 2299 +listens on. The default is 2299. +The number is used for the TCP port that accepts connections, and for a UDP +port that clients send a datagram to in order to learn which address and port +their NAT gives them. +.BR pica-node (8) +never sends anything from the UDP port, but it has to be reachable for +incoming datagrams, so both have to be allowed through a firewall or forwarded +by a router. .TP .I nodes_db_file Specifies the nodes database file. This is the SQLite 3 database. It stores diff --git a/tests/test_client.c b/tests/test_client.c index d9ae35d..320e0bb 100644 --- a/tests/test_client.c +++ b/tests/test_client.c @@ -42,6 +42,10 @@ int random_message_mode = 0; int delivery_acks_count = 0; int rmm_wait_for_reply = 0; +/* -u: 1 - ask the node for our TCP and UDP addresses once connected, 2 - asked */ +int request_addresses = 0; +int udp_sck = -1; + unsigned char buf[64 * 1024]; int accept_cb(const unsigned char *id) @@ -90,7 +94,7 @@ void msgok_cb(const unsigned char *peer_id) puts("[V]"); } //создание канала с собеседником -void c2c_established_cb(const unsigned char *peer_id) +void c2c_established_cb(const unsigned char *peer_id, const char *ciphersuitename) { c2c_active = 1; c2c_in_progress = 0; @@ -217,11 +221,29 @@ void listener_error(struct PICA_listener *lst, int errorcode) l = NULL; } -void multilogin_cb(time_t timestamp, void *addr_bin, const char *addr_str, uint16_t port) +void multilogin_cb(uint64_t timestamp, void *addr_bin, const char *addr_str, uint16_t port) { printf("received MULTILOGIN\n"); } +void tcp_address_cb(struct PICA_c2n *c2n, int type, void *addr_bin, const char *addr_str, uint16_t port) +{ + printf("tcp_address_cb: type 0x%X address %s port %u\n", type, addr_str, port); +} + +void udp_address_cb(struct PICA_c2n *c2n, int status, int type, void *addr_bin, const char *addr_str, uint16_t port) +{ + if (status == PICA_OK) + printf("udp_address_cb: type 0x%X address %s port %u\n", type, addr_str, port); + else + printf("udp_address_cb: failed, status %i\n", status); +} + +void direct_c2c_established_cb(const unsigned char *peer_id, const char *ciphersuitename) +{ + printf("direct c2c connection established, %s\n", ciphersuitename); +} + struct PICA_client_callbacks cbs = { newmsg_cb, @@ -243,7 +265,10 @@ struct PICA_client_callbacks cbs = c2n_failed_cb, c2n_closed_cb, listener_error, - multilogin_cb + multilogin_cb, + .direct_c2c_established_cb = direct_c2c_established_cb, + .tcp_address_cb = tcp_address_cb, + .udp_address_cb = udp_address_cb }; int main(int argc, char** argv) @@ -264,7 +289,7 @@ int main(int argc, char** argv) int multilogin = PICA_MULTILOGIN_PROHIBIT; - while ((opt = getopt(argc, argv, "a:p:c:i:d:e:l:f:tmrM:")) != -1) + while ((opt = getopt(argc, argv, "a:p:c:i:d:e:l:f:tmruM:")) != -1) { switch(opt) { @@ -312,6 +337,10 @@ int main(int argc, char** argv) random_message_mode = 1; break; + case 'u': + request_addresses = 1; + break; + case 'M': if (strcmp(optarg, "prohibit") == 0) multilogin = PICA_MULTILOGIN_PROHIBIT; @@ -341,13 +370,14 @@ int main(int argc, char** argv) if (argc < 4 || !nodeaddr || !nodeport || !certfile) { puts("usage: test_client -a node address -p node port -c cert_filename [-i peer id]\n\ - -d local address for direct incoming c2c connections\n\ + -d local address for direct incoming c2c connections, \"auto\" for automatic configuration\n\ -e external port for incoming direct connections\n\ -l internal port to listen for incoming direct connections\n\ -t enable connect-only mode for direct c2c connections\n\ -m start in echo mode, received messages are sent back, input from stdin is not accepted\n\ -r send random test messages and exit, expects other side to be run in echo mode\n\ -M multilogin policy, one from \"prohibit\", \"replace\", \"sync\"\n\ + -u ask the node for the TCP and UDP addresses it sees this client coming from\n\ cert_filename should point to file that contains client certificate, private key and Diffie-Hellman parameters in PEM format"); return 0; } @@ -381,7 +411,33 @@ cert_filename should point to file that contains client certificate, private key printf("new listener on %s port %i external announced port %i\n", localdirectaddr, intp, extp); - ret = PICA_new_listener(acc, localdirectaddr, extp, intp, &l); + ret = PICA_new_listener(acc, intp, &l); + + /* "auto" leaves the announced addresses to the listener */ + if (ret == PICA_OK && strcmp(localdirectaddr, "auto") != 0) + { + /* a comma separated list, announced in its order */ + const char *addrs[PICA_DIRECTC2C_MAX_ADDRS]; + int ports[PICA_DIRECTC2C_MAX_ADDRS]; + char *list = strdup(localdirectaddr), *a; + int n = 0; + + for (a = strtok(list, ","); a && n < PICA_DIRECTC2C_MAX_ADDRS; a = strtok(NULL, ",")) + { + addrs[n] = a; + ports[n] = extp; + n++; + } + + ret = PICA_listener_set_addrlist(l, addrs, ports, n); + free(list); + + if (ret != PICA_OK) + { + fprintf(stderr, "failed to set the listener's address, error code: %i\n", ret); + PICA_close_listener(l); + } + } if (ret != PICA_OK) { @@ -412,6 +468,30 @@ cert_filename should point to file that contains client certificate, private key while(PICA_event_loop(c2ns, 500) == PICA_OK && c != NULL) { //puts("event loop..."); + if (request_addresses == 1 && connected_to_node == 1) + { + struct sockaddr_in any; + + request_addresses = 2; + + ret = PICA_request_tcp_address(c); + printf("PICA_request_tcp_address: ret=%i\n", ret); + + memset(&any, 0, sizeof(any)); + any.sin_family = AF_INET; + + udp_sck = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + + if (udp_sck == -1 || bind(udp_sck, (struct sockaddr*)&any, sizeof(any)) == -1) + { + perror("failed to open UDP socket"); + return 1; + } + + ret = PICA_request_udp_address(c, udp_sck); + printf("PICA_request_udp_address: ret=%i\n", ret); + } + if (peerid && connected_to_node == 1 && c2c_active == 0 && c2c_in_progress == 0) { if (PICA_id_from_base64(peerid, peer_id) == NULL) diff --git a/tests/test_client_tree.c b/tests/test_client_tree.c new file mode 100644 index 0000000..81076f8 --- /dev/null +++ b/tests/test_client_tree.c @@ -0,0 +1,436 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ + +/* Co-authored with Claude Sonnet 4.6 */ + +#include "../PICA_node.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +//extern int client_tree_add(struct client *ci); +//extern struct client *client_tree_search(const unsigned char *id); +//extern void client_tree_remove(struct client *ci); +//extern struct client *client_tree_root; +struct client *client_tree_root = NULL; + +int client_tree_add(struct client *ci) +{ + struct client *i; + if (client_tree_root) + { + i = client_tree_root; + + do + { + int cmp; + + cmp = memcmp(ci->id, i->id, PICA_ID_SIZE); + + if (cmp == 0) + return 0; + + if (cmp < 0) // ci->id < i->id + { + if (i->left) + i = i->left; + else + { + i->left = ci; + ci->up = i; + return 1; + } + } + else + { + if (i->right) + i = i->right; + else + { + i->right = ci; + ci->up = i; + return 1; + } + } + } + while(1); + } + else + client_tree_root = ci; + + return 1; +} + +struct client* client_tree_search(const unsigned char *id) +{ + struct client* i_ptr; + i_ptr = client_tree_root; + + + while(i_ptr) + { + int cmp = memcmp(id, i_ptr->id, PICA_ID_SIZE); + + if (cmp == 0) + return i_ptr; + + if (cmp < 0) //id < i_ptr->id + i_ptr = i_ptr->left; + else + i_ptr = i_ptr->right; + } + + return 0; +} + +void client_tree_print(struct client *c) +{ + char id_buf[2 * PICA_ID_SIZE]; + if (!c) + { + return; + } + + + if (c->next_multi) + client_tree_print(c->next_multi); + + if (c->left) + client_tree_print(c->left); + + if (c->right) + client_tree_print(c->right); +} + + +void client_tree_remove(struct client* ci) +{ + struct client** p_link;//указывает на left или right в родительском узле + + if (!ci->up) + { + p_link = &client_tree_root; + } + else + { + if (ci == ci->up->left) + p_link = &(ci->up->left); + else + p_link = &(ci->up->right); + } + + + if (!ci->left && !ci->right) + { + *p_link = 0; + return; + } + + if (ci->left && !ci->right) + { + ci->left->up = ci->up; + *p_link = ci->left; + return; + } + + if (!ci->left && ci->right) + { + ci->right->up = ci->up; + *p_link = ci->right; + return; + } + + + { + struct client *lm; + lm = ci->right; + while(lm->left) lm = lm->left; //поиск самого левого узла правого поддерева + + if (lm != ci->right) + { + lm->up->left = lm->right; + if (lm->right) + lm->right->up = lm->up; // FIX 1 + lm->right = ci->right; + ci->right->up = lm; // FIX 2 + } + lm->left = ci->left; + if (ci->left) + ci->left->up = lm; // FIX 3 + lm->up = ci->up; + *p_link = lm; + } +} + +/* ------------------------------------------------------------------ */ +/* Helpers */ +/* ------------------------------------------------------------------ */ + +/* Allocate a zeroed node with a single-byte key padded to PICA_ID_SIZE */ +static struct client *make_node(unsigned char key) +{ + struct client *n = calloc(1, sizeof(struct client)); + n->id[0] = key; /* remaining bytes are 0 – still unique for key != 0 */ + return n; +} + +/* Reset the global tree root */ +static void reset_tree(void) { client_tree_root = NULL; } + +/* Walk every node in the tree and verify ->up consistency */ +static int check_up_pointers(struct client *node, struct client *expected_parent) +{ + if (!node) return 1; + if (node->up != expected_parent) return 0; + return check_up_pointers(node->left, node) && + check_up_pointers(node->right, node); +} + +/* Simple test accounting */ +static int passed = 0, failed = 0; +static void report(const char *name, int ok) +{ + if (ok) { printf("[PASS] %s\n", name); passed++; } + else { printf("[FAIL] %s\n", name); failed++; } +} + + +/* ------------------------------------------------------------------ */ +/* Tests */ +/* ------------------------------------------------------------------ */ + +/* + * TEST for BUG 1 + * -------------- + * lm->right->up must be updated when lm is detached from its parent. + * + * Tree shape built: + * + * 50 (root) + * / \ + * 20 80 <- ci = 50 will be removed + * \ + * 70 <- right child of 50 + * / \ + * 60 75 <- lm = 60 (leftmost of right subtree) + * \ + * 73 <- lm->right; its ->up must point to lm->up (70) after removal + * + * After removing 50, lm (60) replaces it. + * lm->right (73) must have ->up == 70, not the stale lm. + * + * Note: to keep the shape simple we use keys so that BST ordering holds. + * (all keys are single bytes compared with memcmp over 32 bytes, so + * byte[0] alone determines order when all other bytes are 0.) + */ +static void test_fix1_lm_right_up(void) +{ + reset_tree(); + + struct client *n50 = make_node(50); + struct client *n20 = make_node(20); + struct client *n80 = make_node(80); /* unused but keeps shape symmetric */ + struct client *n70 = make_node(70); + struct client *n60 = make_node(60); + struct client *n75 = make_node(75); + struct client *n73 = make_node(73); + + client_tree_add(n50); + client_tree_add(n20); + client_tree_add(n80); + client_tree_add(n70); + client_tree_add(n60); + client_tree_add(n75); + client_tree_add(n73); + + /* + * Remove n50 (two children). + * lm = leftmost of right subtree of n50 = n60 (n50->right=n80... wait, + * we need lm to be deep enough to have a right child. + * + * Re-think: use a simpler layout where n50's right child IS the node + * whose leftmost descendant has a right child. + * + * Rebuild with clearer shape: + * root = 50 + * 50->left = 20 + * 50->right = 70 (ci->right) + * 70->left = 60 (lm – leftmost of right subtree) + * 60->right = 65 (lm->right – the node whose ->up is tested) + */ + reset_tree(); + free(n80); free(n75); free(n73); + + n50 = make_node(50); + n20 = make_node(20); + n70 = make_node(70); + n60 = make_node(60); + struct client *n65 = make_node(65); /* lm->right */ + + client_tree_add(n50); /* root */ + client_tree_add(n20); /* 50->left */ + client_tree_add(n70); /* 50->right */ + client_tree_add(n60); /* 70->left = lm */ + client_tree_add(n65); /* 60->right = lm->right */ + + /* Sanity: verify shape before removal */ + /* n50 is root, n70 is ci->right, n60 is lm, n65 is lm->right */ + + client_tree_remove(n50); + + /* + * After removal, lm (n60) is the new root (n50->up was NULL). + * lm->right should now be n70 (ci->right). + * n65 (old lm->right) was detached from n60 and re-hung under n70. + * Specifically: n70->left = n65, so n65->up must == n70. + */ + int ok = (n65->up == n70); + report("FIX1: lm->right->up updated after lm detached from parent", ok); + + free(n50); free(n20); free(n70); free(n60); free(n65); +} + +/* + * TEST for BUG 2 + * -------------- + * ci->right->up must be updated to lm when lm != ci->right. + * + * Same tree shape as above. After removing n50: + * lm (n60) takes n50's position as root. + * lm->right is set to ci->right (n70). + * Therefore n70->up must == n60 (lm). + */ +static void test_fix2_ci_right_up(void) +{ + reset_tree(); + + struct client *n50 = make_node(50); + struct client *n20 = make_node(20); + struct client *n70 = make_node(70); + struct client *n60 = make_node(60); + struct client *n65 = make_node(65); + + client_tree_add(n50); + client_tree_add(n20); + client_tree_add(n70); + client_tree_add(n60); + client_tree_add(n65); + + client_tree_remove(n50); + + /* + * lm = n60 (leftmost of n50->right = n70's subtree). + * lm != ci->right (n60 != n70), so the "lm != ci->right" branch fires. + * lm->right is then set to n70, so n70->up must be n60. + */ + int ok = (n70->up == n60); + report("FIX2: ci->right->up updated when lm replaces ci", ok); + + free(n50); free(n20); free(n70); free(n60); free(n65); +} + +/* + * TEST for BUG 3 + * -------------- + * ci->left->up must be updated to lm after lm takes ci's position. + * + * Minimal two-children removal where lm == ci->right (the simplest case – + * ci->right has no left child), to isolate Bug 3 independently of Bug 1/2. + * + * Tree: + * 50 (root, ci) + * / \ + * 20 70 lm == ci->right == 70 (no left child) + * + * After removing 50, n70 becomes root. + * n70->left = n20, so n20->up must == n70. + */ +static void test_fix3_ci_left_up(void) +{ + reset_tree(); + + struct client *n50 = make_node(50); + struct client *n20 = make_node(20); + struct client *n70 = make_node(70); + + client_tree_add(n50); + client_tree_add(n20); + client_tree_add(n70); + + client_tree_remove(n50); + + /* + * lm == n70 (== ci->right, no left child under 70). + * Code goes to the shared part: lm->left = ci->left (n20). + * ci->left->up (n20->up) must be updated to lm (n70). + */ + int ok = (n20->up == n70); + report("FIX3: ci->left->up updated when lm replaces ci", ok); + + free(n50); free(n20); free(n70); +} + +/* + * INTEGRITY TEST + * -------------- + * After a sequence of insertions and removals, verify that every ->up + * pointer in the remaining tree is consistent with the actual parent. + * This catches all three bugs simultaneously via a post-condition check. + * + * Sequence: + * Insert: 50, 30, 70, 20, 40, 60, 80, 35, 45, 65 + * Remove: 50 (two children, lm = 60, lm != 70, lm has no right child) + * 30 (two children, lm = 35) + * Expected: fully consistent ->up pointers throughout. + */ +static void test_full_up_consistency(void) +{ + reset_tree(); + + unsigned char keys[] = {50, 30, 70, 20, 40, 60, 80, 35, 45, 65}; + int n = sizeof(keys) / sizeof(keys[0]); + struct client *nodes[10]; + + for (int i = 0; i < n; i++) { + nodes[i] = make_node(keys[i]); + client_tree_add(nodes[i]); + } + + /* Remove node with key 50 (two children; lm=60 which has right child 65) */ + client_tree_remove(nodes[0]); /* n50 */ + + /* Remove node with key 30 (two children; lm=35 which has no right child) */ + client_tree_remove(nodes[1]); /* n30 */ + + int ok = check_up_pointers(client_tree_root, NULL); + report("INTEGRITY: all ->up pointers consistent after multiple removals", ok); + + for (int i = 0; i < n; i++) free(nodes[i]); +} + + +int main(void) +{ + test_fix1_lm_right_up(); + test_fix2_ci_right_up(); + test_fix3_ci_left_up(); + test_full_up_consistency(); + + printf("\n%d passed, %d failed.\n", passed, failed); + return failed ? 1 : 0; +} diff --git a/windows/cross_build_mxe.sh b/windows/cross_build_mxe.sh new file mode 100755 index 0000000..288068d --- /dev/null +++ b/windows/cross_build_mxe.sh @@ -0,0 +1,324 @@ +#!/bin/bash + +# Build script that cross-builds Pica Pica Messenger +# for Windows on a GNU/Linux or Mac host using MXE build environment + +# make sure that MXE dependencies are installed on a host system first +# see https://mxe.cc for details + +# The MXE tree (clone, patches, libraries) is set up only once and reused on +# every subsequent run, because building the MXE libraries takes hours. +# Pica Pica itself and the installers are always rebuilt from scratch. + +# Environment variables understood by this script: +# MXE_COMMIT build against another MXE commit than the pinned one +# MXE_ALLOW_COMMIT_MISMATCH=1 only warn instead of failing when the existing MXE +# clone is checked out at a different commit +# MXE_FORCE_REAPPLY_PATCHES=1 restore the MXE files touched by our patches from +# git and apply the patches again, in case a patch was +# changed after it had been applied + +set -o errexit +set -o errtrace +set -o nounset +set -o pipefail + +MXE_REPO_URL='https://github.com/mxe/mxe.git' +MXE_COMMIT=${MXE_COMMIT:-a9135e50775889ef9448cf12b72da0ea25aa04c1} +MXE_TARGETS='i686-w64-mingw32.shared x86_64-w64-mingw32.shared' +MXE_PACKAGES='cc qtbase ffmpeg openssl miniupnpc libevent sqlite webrtc-audio-processing nsis' +MXE_PATCHES='mxe_qtbase_strip_excess_deps.patch mxe_ffmpeg_strip_excess_deps.patch' + +windows_dir=$(cd "$(dirname "$0")" && pwd) +mxe_dir=$windows_dir/mxe + +function die { + echo "ERROR: $*" >&2 + exit 1 +} + +function on_error { + echo "ERROR: $0 failed at line $1 (exit code $2), build aborted" >&2 +} + +trap 'on_error $LINENO $?' ERR + +# step 1: clone the MXE repository unless it is already there +function clone_mxe { + if test -d "$mxe_dir/.git" + then + echo "*** MXE is already cloned in $mxe_dir, skipping clone" + return + fi + + test -e "$mxe_dir" && die "$mxe_dir exists but is not a git repository, remove it and run this script again" + + echo "*** cloning MXE from $MXE_REPO_URL" + git clone "$MXE_REPO_URL" "$mxe_dir" +} + +# step 2: make sure the MXE clone is checked out at the commit we build against +function checkout_mxe_commit { + local head + + head=$(git -C "$mxe_dir" rev-parse HEAD) + + if test "$head" = "$MXE_COMMIT" + then + echo "*** MXE is already checked out at $MXE_COMMIT, skipping checkout" + return + fi + + if test "${MXE_ALLOW_COMMIT_MISMATCH:-0}" = '1' + then + echo "*** WARNING: MXE is checked out at $head instead of $MXE_COMMIT, continuing anyway" >&2 + return + fi + + if ! git -C "$mxe_dir" cat-file -e "$MXE_COMMIT^{commit}" 2>/dev/null + then + echo "*** commit $MXE_COMMIT is not present in the local MXE clone, fetching" + git -C "$mxe_dir" fetch origin "$MXE_COMMIT" || git -C "$mxe_dir" fetch origin + git -C "$mxe_dir" cat-file -e "$MXE_COMMIT^{commit}" 2>/dev/null \ + || die "commit $MXE_COMMIT does not exist in $MXE_REPO_URL, fix MXE_COMMIT in $0" + fi + + if test -n "$(git -C "$mxe_dir" status --porcelain --untracked-files=no)" + then + die "$mxe_dir is checked out at $head instead of $MXE_COMMIT and has local modifications. +Checking out $MXE_COMMIT would discard them, so it is not done automatically. Either + - check out $MXE_COMMIT in $mxe_dir manually, or + - set MXE_COMMIT to the commit you want to build against, or + - run with MXE_ALLOW_COMMIT_MISMATCH=1 to keep the current checkout, or + - remove $mxe_dir to get a fresh clone (this rebuilds all MXE libraries)" + fi + + echo "*** checking out MXE commit $MXE_COMMIT" + git -C "$mxe_dir" checkout --detach "$MXE_COMMIT" +} + +# files a patch touches, as paths relative to the MXE tree +function patch_target_files { + awk '/^\+\+\+ /{sub(/^\+\+\+ /, ""); sub(/\t.*$/, ""); sub(/^b\//, ""); print}' "$1" +} + +# step 3: apply our MXE patches, but only those that are not applied yet +function apply_mxe_patches { + local patch_name patch_file + + for patch_name in $MXE_PATCHES + do + patch_file=$windows_dir/$patch_name + + test -f "$patch_file" || die "patch $patch_file not found" + + if patch -p1 -d "$mxe_dir" --dry-run --reverse --silent < "$patch_file" > /dev/null 2>&1 + then + echo "*** $patch_name is already applied, skipping" + continue + fi + + if patch -p1 -d "$mxe_dir" --dry-run --forward --silent < "$patch_file" > /dev/null 2>&1 + then + echo "*** applying $patch_name" + patch -p1 -d "$mxe_dir" --forward < "$patch_file" + continue + fi + + if test "${MXE_FORCE_REAPPLY_PATCHES:-0}" = '1' + then + echo "*** restoring $(patch_target_files "$patch_file" | tr '\n' ' ')from git and applying $patch_name again" + # shellcheck disable=SC2046 + git -C "$mxe_dir" checkout -- $(patch_target_files "$patch_file") + patch -p1 -d "$mxe_dir" --forward < "$patch_file" + continue + fi + + die "$patch_name neither applies to nor is already applied in $mxe_dir. +This usually means the patch was changed after it had been applied. Run + patch -p1 -d $mxe_dir --dry-run --forward < $patch_file +to see the details, then either resolve it by hand or run this script with +MXE_FORCE_REAPPLY_PATCHES=1 to restore the patched MXE files from git and +apply the patch again (the affected libraries will be rebuilt by MXE)." + done +} + +# MXE packages from $MXE_PACKAGES that are not built yet, as 'package (target)' +function missing_mxe_packages { + local target package + + for target in $MXE_TARGETS + do + for package in $MXE_PACKAGES + do + test -f "$mxe_dir/usr/$target/installed/$package" || echo "$package ($target)" + done + done +} + +# step 4: build the libraries provided by MXE, unless they are all built already +function build_mxe_packages { + local missing + + make -C "$mxe_dir" MXE_TARGETS="$MXE_TARGETS" check-requirements + + missing=$(missing_mxe_packages) + + if test -z "$missing" + then + echo "*** all MXE packages are already built, skipping MXE build" + return + fi + + echo "*** MXE packages that are not built yet:" + echo "$missing" | sed 's,^, ,' + + # TODO: libva for windows, enable vaapi in ffmpeg configuration + # make itself does nothing for the packages that are built already + make -C "$mxe_dir" MXE_TARGETS="$MXE_TARGETS" $MXE_PACKAGES + + missing=$(missing_mxe_packages) + test -z "$missing" || die "MXE build finished but these packages are still missing: +$(echo "$missing" | sed 's,^, ,')" +} + +# makensis for the given architecture. +# +# makensis is a program for the host system, but MXE installs it into the +# target prefix - usr/<target>/bin - because the installer stubs it carries are +# built for that target: the copy from the x86_64-w64-mingw32.shared tree emits +# 64 bit installers, the one from the i686-w64-mingw32.shared tree 32 bit ones, +# and a 64 bit installer does not run on a 32 bit Windows. So the copy +# belonging to the architecture being packaged is used when it is there, any +# other MXE built copy after that, then usr/bin/makensis for an nsis built into +# the MXE tree by hand, and finally whatever the host system has. +# +# usr/<target>/bin is deliberately not added to PATH: it is full of Windows +# executables, and configure --host=<target> looks for host programs with the +# .exe suffix as well, so a Windows uic.exe or sqlite3.exe in there could be +# picked up as if it were a host tool. +function find_makensis { + local wanted_arch=$1 + local other_arch candidate + + for candidate in "$mxe_dir/usr/$wanted_arch/bin/makensis" \ + $(for other_arch in $MXE_TARGETS; do echo "$mxe_dir/usr/$other_arch/bin/makensis"; done) \ + "$mxe_dir/usr/bin/makensis" + do + if test -x "$candidate" + then + echo "$candidate" + return + fi + done + + command -v makensis || die "makensis not found: no nsis in $mxe_dir/usr/*/bin, none on the host system" +} + +# step 5: build Pica Pica itself and the installer, always from scratch +function build_for_arch { + +arch=$1 + +PREFIX=$PWD/usr/$arch + +test -x ../../configure || die "../../configure not found, run ./autogen.sh in the Pica Pica source tree first" + +rm -rf build_pica-pica +mkdir -p build_pica-pica +cd build_pica-pica +../../../configure --host=$arch --prefix=$PREFIX --enable-d3d12va +make -j$(nproc) +make install +make clean +cd .. + +#copy exe & DLLs +rm -rf build_installer_$arch +mkdir -p build_installer_$arch +cp $PREFIX/bin/pica-client.exe build_installer_$arch/ +cp $PREFIX/bin/pica-node.exe build_installer_$arch/ + +#run copydlldeps.sh from destination dir, otherwise it recursively walks all MXE tree and copies excess DLLs + +cd build_installer_$arch +#the styles directory is what keeps the program from looking like Windows 95: +#Qt's themed look on Windows lives in the windowsvista style, which is a +#plugin, and without it QApplication falls back to the built-in Windows style +../tools/copydlldeps.sh --infile ./pica-client.exe --destdir ./ --recursivesrcdir $PREFIX --copy --enforcedir $PREFIX/qt5/plugins/platforms/ --enforcedir $PREFIX/qt5/plugins/sqldrivers/ --enforcedir $PREFIX/qt5/plugins/imageformats/ --enforcedir $PREFIX/qt5/plugins/styles/ --objdump ../usr/bin/$arch-objdump + +../tools/copydlldeps.sh --infile ./pica-node.exe --destdir ./ --recursivesrcdir $PREFIX --copy --objdump ../usr/bin/$arch-objdump + +cd .. + +#strip everything that was copied, including the Qt plugin subdirectories. +#find is used instead of globs because a glob for a plugin directory that +#copydlldeps.sh did not create would abort the whole script now that it runs +#with errexit - makensis reports a missing plugin later anyway. +find build_installer_$arch -type f \( -name '*.dll' -o -name '*.exe' \) -print0 \ + | xargs -0 -r usr/bin/$arch-strip + +#build installer +cd build_installer_$arch + +for dll in *.dll +do + echo "File $dll" >> dll_list.nsh +done + +cp ../../../COPYING ./ +cp ../../../README ./ +cp ../../../windows/picapica.ico ./ + +mkdir -p share + +cp $PREFIX/share/pica-client/dhparam4096.pem share/ +cp $PREFIX/share/pica-client/picapica-icon-fly.png share/ +cp $PREFIX/share/pica-client/picapica-icon-sit.png share/ +cp $PREFIX/share/pica-client/picapica-snd-newmessage.wav share/ + +makensis_bin=$(find_makensis $arch) +echo "*** building the installer with $makensis_bin" + +if test $arch = 'i686-w64-mingw32.shared' +then + cp ../build_pica-pica/windows/installer32.nsi ./ + "$makensis_bin" installer32.nsi +elif test $arch = 'x86_64-w64-mingw32.shared' +then + cp ../build_pica-pica/windows/installer64.nsi ./ + "$makensis_bin" installer64.nsi +else + die "unsupported architecture $arch" +fi + +cd .. +} + + +clone_mxe +checkout_mxe_commit +apply_mxe_patches +build_mxe_packages + +cd "$mxe_dir" + +export PATH=$PWD/usr/bin/:$PATH + +# resolve makensis for every architecture now, so that a missing nsis is +# reported before the hour the Pica Pica builds take, not after them +for arch in $MXE_TARGETS +do + find_makensis $arch > /dev/null +done + +for arch in $MXE_TARGETS +do + build_for_arch $arch +done + +echo "*** done, installers are in:" +for arch in $MXE_TARGETS +do + echo " $mxe_dir/build_installer_$arch" +done diff --git a/windows/installer32.nsi.in b/windows/installer32.nsi.in new file mode 100755 index 0000000..1421e2c --- /dev/null +++ b/windows/installer32.nsi.in @@ -0,0 +1,76 @@ +!include MUI2.nsh + +!define VERSION "@VERSION@" + +Name "Pica Pica Messenger" +OutFile "PicaPicaMessengerInstaller_${VERSION}_32bit.exe" +InstallDir "$PROGRAMFILES\Pica Pica Messenger" +InstallDirRegKey HKLM "Software\Pica Pica Messenger" "" +RequestExecutionLevel admin +SetCompressor /FINAL /SOLID lzma +!define MUI_ICON "picapica.ico" +!define MUI_UNICON "picapica.ico" + +!insertmacro MUI_PAGE_WELCOME +!insertmacro MUI_PAGE_LICENSE "COPYING" +!insertmacro MUI_PAGE_DIRECTORY +!insertmacro MUI_PAGE_INSTFILES +!define MUI_FINISHPAGE_RUN $INSTDIR\pica-client.exe +!define MUI_FINISHPAGE_RUN_TEXT "Run Pica Pica Messenger" +!insertmacro MUI_PAGE_FINISH + +!insertmacro MUI_UNPAGE_CONFIRM +!insertmacro MUI_UNPAGE_INSTFILES + +!insertmacro MUI_LANGUAGE "English" + +Section + SetOutPath "$INSTDIR" + SetShellVarContext all + +!include dll_list.nsh + + File "pica-client.exe" + File "picapica.ico" + File "COPYING" + File "README" + SetOutPath "$INSTDIR\share" + File "share/picapica-icon-fly.png" + File "share/picapica-icon-sit.png" + File "share/picapica-snd-newmessage.wav" + File "share/dhparam4096.pem" + SetOutPath "$INSTDIR\sqldrivers" + File "sqldrivers/qsqlite.dll" + SetOutPath "$INSTDIR\platforms" + File "platforms/qwindows.dll" + SetOutPath "$INSTDIR\imageformats" + File "imageformats/qico.dll" + ; The themed look. Qt picks the windowsvista style on Vista and later, and + ; that style is a plugin - without it the program falls back to the built-in + ; Windows style, which looks like Windows 95. + SetOutPath "$INSTDIR\styles" + File "styles/qwindowsvistastyle.dll" + WriteUninstaller "uninstall.exe" + + WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Pica Pica Messenger" "DisplayName" "Pica Pica Messenger" + WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Pica Pica Messenger" "UninstallString" '"$INSTDIR\uninstall.exe"' + WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Pica Pica Messenger" "NoModify" 1 + WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Pica Pica Messenger" "NoRepair" 1 + WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Pica Pica Messenger" "HelpLink" "https://picapica.im" + + + CreateDirectory "$SMPROGRAMS\Pica Pica Messenger" + SetOutPath $INSTDIR + CreateShortCut "$SMPROGRAMS\Pica Pica Messenger\Pica Pica Messenger.lnk" "$INSTDIR\pica-client.exe" "" "$INSTDIR\picapica.ico" + + +SectionEnd + +Section "Uninstall" + SetShellVarContext all + Delete "$INSTDIR\Uninstall.exe" + RMDir /r "$INSTDIR" + RMDir /r "$SMPROGRAMS\Pica Pica Messenger" + DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Pica Pica Messenger" +SectionEnd + diff --git a/windows/installer64.nsi.in b/windows/installer64.nsi.in new file mode 100755 index 0000000..18b59ab --- /dev/null +++ b/windows/installer64.nsi.in @@ -0,0 +1,76 @@ +!include MUI2.nsh + +!define VERSION "@VERSION@" + +Name "Pica Pica Messenger" +OutFile "PicaPicaMessengerInstaller_${VERSION}_64bit.exe" +InstallDir "$PROGRAMFILES64\Pica Pica Messenger" +InstallDirRegKey HKLM "Software\Pica Pica Messenger" "" +RequestExecutionLevel admin +SetCompressor /FINAL /SOLID lzma +!define MUI_ICON "picapica.ico" +!define MUI_UNICON "picapica.ico" + +!insertmacro MUI_PAGE_WELCOME +!insertmacro MUI_PAGE_LICENSE "COPYING" +!insertmacro MUI_PAGE_DIRECTORY +!insertmacro MUI_PAGE_INSTFILES +!define MUI_FINISHPAGE_RUN $INSTDIR\pica-client.exe +!define MUI_FINISHPAGE_RUN_TEXT "Run Pica Pica Messenger" +!insertmacro MUI_PAGE_FINISH + +!insertmacro MUI_UNPAGE_CONFIRM +!insertmacro MUI_UNPAGE_INSTFILES + +!insertmacro MUI_LANGUAGE "English" + +Section + SetOutPath "$INSTDIR" + SetShellVarContext all + +!include dll_list.nsh + + File "pica-client.exe" + File "picapica.ico" + File "COPYING" + File "README" + SetOutPath "$INSTDIR\share" + File "share/picapica-icon-fly.png" + File "share/picapica-icon-sit.png" + File "share/picapica-snd-newmessage.wav" + File "share/dhparam4096.pem" + SetOutPath "$INSTDIR\sqldrivers" + File "sqldrivers/qsqlite.dll" + SetOutPath "$INSTDIR\platforms" + File "platforms/qwindows.dll" + SetOutPath "$INSTDIR\imageformats" + File "imageformats/qico.dll" + ; The themed look. Qt picks the windowsvista style on Vista and later, and + ; that style is a plugin - without it the program falls back to the built-in + ; Windows style, which looks like Windows 95. + SetOutPath "$INSTDIR\styles" + File "styles/qwindowsvistastyle.dll" + WriteUninstaller "uninstall.exe" + + WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Pica Pica Messenger" "DisplayName" "Pica Pica Messenger" + WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Pica Pica Messenger" "UninstallString" '"$INSTDIR\uninstall.exe"' + WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Pica Pica Messenger" "NoModify" 1 + WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Pica Pica Messenger" "NoRepair" 1 + WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Pica Pica Messenger" "HelpLink" "https://picapica.im" + + + CreateDirectory "$SMPROGRAMS\Pica Pica Messenger" + SetOutPath $INSTDIR + CreateShortCut "$SMPROGRAMS\Pica Pica Messenger\Pica Pica Messenger.lnk" "$INSTDIR\pica-client.exe" "" "$INSTDIR\picapica.ico" + + +SectionEnd + +Section "Uninstall" + SetShellVarContext all + Delete "$INSTDIR\Uninstall.exe" + RMDir /r "$INSTDIR" + RMDir /r "$SMPROGRAMS\Pica Pica Messenger" + DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Pica Pica Messenger" +SectionEnd + diff --git a/windows/mxe_ffmpeg_strip_excess_deps.patch b/windows/mxe_ffmpeg_strip_excess_deps.patch new file mode 100644 index 0000000..9ed8508 --- /dev/null +++ b/windows/mxe_ffmpeg_strip_excess_deps.patch @@ -0,0 +1,82 @@ +diff --git a/src/ffmpeg.mk b/src/ffmpeg.mk +index 8dd80d8..4c7daec 100644 +--- a/src/ffmpeg.mk ++++ b/src/ffmpeg.mk +@@ -8,9 +8,7 @@ $(PKG)_CHECKSUM := cf38e0e28c7e5605942c4a77755349b0145804a397af37eb1fb4c77cb237f + $(PKG)_SUBDIR := $(PKG)-$($(PKG)_VERSION) + $(PKG)_FILE := $(PKG)-$($(PKG)_VERSION).tar.xz + $(PKG)_URL := https://ffmpeg.org/releases/$($(PKG)_FILE) +-$(PKG)_DEPS := cc bzip2 gnutls lame libass libbluray libbs2b libcaca \ +- libvpx opencore-amr $(BUILD)~nasm opus sdl2 speex theora vidstab \ +- vo-amrwbenc vorbis x264 x265 xvidcore zlib ++$(PKG)_DEPS := cc bzip2 libvpx $(BUILD)~nasm opus x264 x265 zlib + + # DO NOT ADD fdk-aac OR openssl SUPPORT. + # Although they are free softwares, their licenses are not compatible with +@@ -25,6 +23,22 @@ define $(PKG)_UPDATE + head -1 + endef + ++# Pica Pica needs a small part of what MXE's stock ffmpeg provides: the codecs ++# named in doc/proto-doc-latest.txt for the media of an audio/video call (h264, ++# hevc, vp9 and mjpeg for video, opus, adpcm_g722 and pcm_alaw for audio, both ++# directions), dshow for capture, and the hardware paths ffmpeg has for the ++# video codecs. --disable-everything turns off every component and the ++# --enable-<component>= options below turn that set back on, which is what ++# keeps libavcodec from carrying the several hundred codecs nothing here can ++# reach. ++# ++# The nvenc/nvdec/cuvid/qsv/amf components are listed as well although no MXE ++# package provides their headers yet, so configure prints a warning for each of ++# them and leaves them out. That is deliberate: adding ffnvcodec (NVIDIA), ++# libvpl (Intel QSV) or the AMF headers as a dependency is then the only change ++# needed to get them. The Media Foundation and Direct3D 12 encoders (h264_mf, ++# hevc_mf, h264_d3d12va, hevc_d3d12va) and the dxva2/d3d11va/d3d12va decoders ++# need nothing but mingw-w64 and are available right away. + define $(PKG)_BUILD + cd '$(BUILD_DIR)' && '$(SOURCE_DIR)/configure' \ + --cross-prefix='$(TARGET)'- \ +@@ -41,25 +55,28 @@ define $(PKG)_BUILD + --disable-doc \ + --enable-gpl \ + --enable-version3 \ +- --extra-libs="`'$(TARGET)-pkg-config' --libs libmpg123` -mconsole" \ +- --enable-gnutls \ +- --enable-libass \ +- --enable-libbluray \ +- --enable-libbs2b \ +- --enable-libcaca \ +- --enable-libmp3lame \ +- --enable-libopencore-amrnb \ +- --enable-libopencore-amrwb \ ++ --extra-libs="-mconsole" \ + --enable-libopus \ +- --enable-libspeex \ +- --enable-libtheora \ +- --enable-libvidstab \ +- --enable-libvo-amrwbenc \ +- --enable-libvorbis \ + --enable-libvpx \ + --enable-libx264 \ + --enable-libx265 \ +- --enable-libxvid \ ++ --disable-programs \ ++ --disable-lzma \ ++ --disable-everything \ ++ --enable-protocol=file \ ++ --enable-indev=dshow \ ++ --enable-demuxer=matroska,mjpeg,h264,hevc,ivf,wav \ ++ --enable-muxer=matroska,mjpeg,h264,hevc,ivf,wav \ ++ --enable-parser=h264,hevc,vp9,mjpeg,opus \ ++ --enable-bsf=extract_extradata,h264_mp4toannexb,hevc_mp4toannexb,vp9_superframe,vp9_superframe_split \ ++ --enable-decoder=h264,hevc,vp9,libvpx_vp9,mjpeg,rawvideo,opus,libopus,adpcm_g722,pcm_alaw,pcm_mulaw,pcm_s16le \ ++ --enable-encoder=libx264,libx265,libvpx_vp9,mjpeg,libopus,opus,adpcm_g722,pcm_alaw,pcm_mulaw,pcm_s16le \ ++ --enable-hwaccel=h264_dxva2,h264_d3d11va,h264_d3d11va2,h264_d3d12va,hevc_dxva2,hevc_d3d11va,hevc_d3d11va2,hevc_d3d12va,vp9_dxva2,vp9_d3d11va,vp9_d3d11va2,vp9_d3d12va \ ++ --enable-encoder=h264_mf,hevc_mf,h264_d3d12va,hevc_d3d12va \ ++ --enable-hwaccel=h264_nvdec,hevc_nvdec,vp9_nvdec,mjpeg_nvdec \ ++ --enable-decoder=h264_qsv,hevc_qsv,vp9_qsv,mjpeg_qsv,h264_cuvid,hevc_cuvid,vp9_cuvid,mjpeg_cuvid \ ++ --enable-encoder=h264_nvenc,hevc_nvenc,h264_qsv,hevc_qsv,h264_amf,hevc_amf \ ++ --enable-filter=scale,format,null,hwupload,hwdownload,hwmap,aresample,aformat,anull \ + --extra-ldflags="-fstack-protector" \ + $($(PKG)_CONFIGURE_OPTS) + $(MAKE) -C '$(BUILD_DIR)' -j '$(JOBS)' diff --git a/windows/mxe_qtbase_strip_excess_deps.patch b/windows/mxe_qtbase_strip_excess_deps.patch new file mode 100644 index 0000000..c62ba8f --- /dev/null +++ b/windows/mxe_qtbase_strip_excess_deps.patch @@ -0,0 +1,56 @@ +diff --git a/src/qtbase.mk b/src/qtbase.mk +index 600ff60..220c2bb 100644 +--- a/src/qtbase.mk ++++ b/src/qtbase.mk +@@ -9,9 +9,8 @@ $(PKG)_CHECKSUM := 51e91c73abacab81e64efd01bf95794e79c0e605ad80947a024769f0dd620 + $(PKG)_SUBDIR := $(PKG)-everywhere-src-$($(PKG)_VERSION) + $(PKG)_FILE := $(PKG)-everywhere-opensource-src-$($(PKG)_VERSION).tar.xz + $(PKG)_URL := https://download.qt.io/archive/qt/5.15/$($(PKG)_VERSION)/submodules/$($(PKG)_FILE) +-$(PKG)_DEPS := cc dbus fontconfig freetds freetype harfbuzz jpeg mariadb-connector-c \ +- libpng mesa openssl pcre2 postgresql sqlite zlib zstd $(BUILD)~zstd \ +- $(if $(findstring shared,$(MXE_TARGETS)), icu4c) ++$(PKG)_DEPS := cc dbus fontconfig freetype harfbuzz \ ++ libpng mesa openssl pcre2 sqlite zlib + $(PKG)_DEPS_$(BUILD) := + $(PKG)_TARGETS := $(BUILD) $(MXE_TARGETS) + +@@ -27,8 +26,6 @@ define $(PKG)_BUILD + # ICU is buggy on static builds. See #653. TODO: reenable it some time in the future. + cd '$(1)' && \ + OPENSSL_LIBS="`'$(TARGET)-pkg-config' --libs-only-l openssl`" \ +- PSQL_LIBS="-lpq -lpgport -lpgcommon -lsecur32 `'$(TARGET)-pkg-config' --libs-only-l openssl pthreads` -lws2_32" \ +- SYBASE_LIBS="-lsybdb `'$(TARGET)-pkg-config' --libs-only-l openssl` -liconv -lws2_32" \ + PKG_CONFIG="${TARGET}-pkg-config" \ + PKG_CONFIG_SYSROOT_DIR="/" \ + PKG_CONFIG_LIBDIR="$(PREFIX)/$(TARGET)/lib/pkgconfig" \ +@@ -45,27 +42,23 @@ define $(PKG)_BUILD + -release \ + $(if $(BUILD_STATIC), -static,)$(if $(BUILD_SHARED), -shared,) \ + -prefix '$(PREFIX)/$(TARGET)/qt5' \ +- $(if $(BUILD_STATIC), -no)-icu \ ++ -no-icu \ ++ -no-zstd \ + -opengl dynamic \ + -no-glib \ + -accessibility \ + -nomake examples \ + -nomake tests \ +- -plugin-sql-mysql \ + -plugin-sql-sqlite \ +- -plugin-sql-odbc \ +- -plugin-sql-psql \ +- -plugin-sql-tds -D Q_USE_SYBASE \ + -system-zlib \ + -system-libpng \ +- -system-libjpeg \ ++ -no-libjpeg \ + -system-sqlite \ + -fontconfig \ + -system-freetype \ + -system-harfbuzz \ + -system-pcre \ + -openssl-linked \ +- -dbus-linked \ + -no-pch \ + -v \ + $(PKG_CONFIGURE_OPTS) diff --git a/windows/pica-client.exe.manifest.in b/windows/pica-client.exe.manifest.in new file mode 100644 index 0000000..b30df69 --- /dev/null +++ b/windows/pica-client.exe.manifest.in @@ -0,0 +1,73 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> + + <assemblyIdentity + type="win32" + name="picapica.im.pica-pica.pica-client" + version="@PICA_WINDOWS_VERSION@" + processorArchitecture="*" + /> + + <description>Pica Pica Messenger</description> + + <!-- Use the themed version 6 common controls. Without this dependency + Windows loads the Windows 95 era comctl32.dll and Qt's native dialogs + and widget style fall back to the unthemed look. --> + <dependency> + <dependentAssembly> + <assemblyIdentity + type="win32" + name="Microsoft.Windows.Common-Controls" + version="6.0.0.0" + publicKeyToken="6595b64144ccf1df" + language="*" + processorArchitecture="*" + /> + </dependentAssembly> + </dependency> + + <!-- Run with the privileges of the invoking user. This also stops the + installer detection heuristics from asking for elevation just because + the file name or the resources contain words like "setup" or "update", + and it disables registry/file system virtualization. --> + <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> + <security> + <requestedPrivileges> + <requestedExecutionLevel level="asInvoker" uiAccess="false"/> + </requestedPrivileges> + </security> + </trustInfo> + + <!-- Declare which Windows versions this program was tested against. An + unlisted program is reported the version of the newest OS it claims + support for, and may silently get compatibility shims applied. --> + <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> + <application> + <!-- Windows Vista --> + <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/> + <!-- Windows 7 --> + <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/> + <!-- Windows 8 --> + <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/> + <!-- Windows 8.1 --> + <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/> + <!-- Windows 10 and Windows 11 --> + <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/> + </application> + </compatibility> + + <application xmlns="urn:schemas-microsoft-com:asm.v3"> + <windowsSettings> + <!-- Allow paths longer than MAX_PATH in the file transfer code. This + has no effect unless the machine also has the LongPathsEnabled + policy turned on, so it is safe on older systems. --> + <longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware> + + <!-- Deliberately no dpiAware/dpiAwareness setting here: the Qt windows + platform plugin selects the DPI awareness mode itself at startup, + and a value in the manifest would override it. Add one only + together with the matching Qt high DPI attributes. --> + </windowsSettings> + </application> + +</assembly> diff --git a/windows/pica-client.rc b/windows/pica-client.rc new file mode 100644 index 0000000..a81fcb8 --- /dev/null +++ b/windows/pica-client.rc @@ -0,0 +1,55 @@ +/* Resources linked into pica-client.exe by windres. + * + * The file names below are looked up along the windres include path, which + * Makefile.am points at both this directory and the matching build directory, + * since the manifest is generated by configure while the icon is not. + */ + +/* The name IDI_ICON1 is not arbitrary: besides being the icon Explorer shows + * for the executable, it is the one Qt's windows platform plugin loads from + * the running binary and installs as the window class icon, which is what + * appears in the title bar, in the task bar and in the Alt+Tab list. */ +IDI_ICON1 ICON "picapica.ico" + +/* The application manifest, as resource 1 (CREATEPROCESS_MANIFEST_RESOURCE_ID) + * of type 24 (RT_MANIFEST). Spelled numerically so that the resource script + * does not have to include windows.h through the cross compiler. */ +1 24 "pica-client.exe.manifest" + +/* What the Details tab of the file properties dialog shows. The two version + * macros come from the windres command line in Makefile.am: + * PICA_WINDOWS_VERSION_COMMAS is the four number form configure derives from + * the package version, which is the only thing the FILEVERSION field accepts, + * and PICA_WINDOWS_VERSION_STRING is the package version as it is written + * everywhere else, which the string fields are free to use. */ +1 VERSIONINFO +FILEVERSION PICA_WINDOWS_VERSION_COMMAS +PRODUCTVERSION PICA_WINDOWS_VERSION_COMMAS +FILEFLAGSMASK 0x3fL +FILEFLAGS 0x0L +FILEOS 0x40004L /* VOS_NT_WINDOWS32 */ +FILETYPE 0x1L /* VFT_APP */ +FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + /* 0409 is US English, 04E4 is code page 1252. The pair has to + * match the Translation value at the bottom, which is what the + * property sheet looks the block up by. */ + BLOCK "040904E4" + BEGIN + VALUE "CompanyName", "picapica.im" + VALUE "FileDescription", "Pica Pica Messenger" + VALUE "FileVersion", PICA_WINDOWS_VERSION_STRING + VALUE "InternalName", "pica-client" + VALUE "LegalCopyright", "Copyright (c) 2012 - 2026 Anton Sviridenko" + VALUE "OriginalFilename", "pica-client.exe" + VALUE "ProductName", "Pica Pica Messenger" + VALUE "ProductVersion", PICA_WINDOWS_VERSION_STRING + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END diff --git a/windows/pica-node.exe.manifest.in b/windows/pica-node.exe.manifest.in new file mode 100644 index 0000000..b3c97e9 --- /dev/null +++ b/windows/pica-node.exe.manifest.in @@ -0,0 +1,66 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> + + <assemblyIdentity + type="win32" + name="picapica.im.pica-pica.pica-node" + version="@PICA_WINDOWS_VERSION@" + processorArchitecture="*" + /> + + <description>Pica Pica node</description> + + <!-- The node has no user interface, so unlike the client it does not pull in + the themed version 6 common controls. --> + + <!-- The same binary runs both ways: started by the service control manager + it serves the SCM, and started from a console it falls back to running + in the foreground. Nothing below is specific to either mode - a manifest + cannot ask for anything of the service control manager, and the process + privileges of the service come from the account it was registered with + ("sc create ... obj= ..."), not from here. --> + + <!-- Run with the privileges of the invoking user. The service control + manager ignores this and uses the account the service was registered + with, but it is what the console mode needs: asking for administrator + rights here would make every foreground start raise a UAC prompt. + Declaring any level at all also disables registry/file system + virtualization, so that a write to the installation directory fails + visibly instead of being redirected into VirtualStore. --> + <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> + <security> + <requestedPrivileges> + <requestedExecutionLevel level="asInvoker" uiAccess="false"/> + </requestedPrivileges> + </security> + </trustInfo> + + <!-- Declare which Windows versions this program was tested against. An + unlisted program is reported the version of the newest OS it claims + support for, and may silently get compatibility shims applied. --> + <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> + <application> + <!-- Windows Vista --> + <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/> + <!-- Windows 7 --> + <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/> + <!-- Windows 8 --> + <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/> + <!-- Windows 8.1 --> + <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/> + <!-- Windows 10 and Windows 11 --> + <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/> + </application> + </compatibility> + + <application xmlns="urn:schemas-microsoft-com:asm.v3"> + <windowsSettings> + <!-- Allow the node list database and the log file to sit behind a path + longer than MAX_PATH. This has no effect unless the machine also + has the LongPathsEnabled policy turned on, so it is safe on older + systems. --> + <longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware> + </windowsSettings> + </application> + +</assembly> diff --git a/windows/pica-node.rc b/windows/pica-node.rc new file mode 100644 index 0000000..7d0df4a --- /dev/null +++ b/windows/pica-node.rc @@ -0,0 +1,54 @@ +/* Resources linked into pica-node.exe by windres. + * + * The file names below are looked up along the windres include path, which + * Makefile.am points at both this directory and the matching build directory, + * since the manifest is generated by configure while the icon is not. + */ + +/* Shown by Explorer for the executable and for shortcuts to it. */ +IDI_ICON1 ICON "picapica.ico" + +/* The application manifest, as resource 1 (CREATEPROCESS_MANIFEST_RESOURCE_ID) + * of type 24 (RT_MANIFEST). Spelled numerically so that the resource script + * does not have to include windows.h through the cross compiler. */ +1 24 "pica-node.exe.manifest" + +/* What the Details tab of the file properties dialog shows, and, because this + * binary is registered as a service, the name the Task Manager lists the + * process under: that column is the FileDescription value below, not the file + * name. The two version macros come from the windres command line in + * Makefile.am: PICA_WINDOWS_VERSION_COMMAS is the four number form configure + * derives from the package version, which is the only thing the FILEVERSION + * field accepts, and PICA_WINDOWS_VERSION_STRING is the package version as it + * is written everywhere else, which the string fields are free to use. */ +1 VERSIONINFO +FILEVERSION PICA_WINDOWS_VERSION_COMMAS +PRODUCTVERSION PICA_WINDOWS_VERSION_COMMAS +FILEFLAGSMASK 0x3fL +FILEFLAGS 0x0L +FILEOS 0x40004L /* VOS_NT_WINDOWS32 */ +FILETYPE 0x1L /* VFT_APP, there is no separate type for a service */ +FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + /* 0409 is US English, 04E4 is code page 1252. The pair has to + * match the Translation value at the bottom, which is what the + * property sheet looks the block up by. */ + BLOCK "040904E4" + BEGIN + VALUE "CompanyName", "picapica.im" + VALUE "FileDescription", "Pica Pica Node" + VALUE "FileVersion", PICA_WINDOWS_VERSION_STRING + VALUE "InternalName", "pica-node" + VALUE "LegalCopyright", "Copyright (c) 2012 - 2026 Anton Sviridenko" + VALUE "OriginalFilename", "pica-node.exe" + VALUE "ProductName", "Pica Pica Node" + VALUE "ProductVersion", PICA_WINDOWS_VERSION_STRING + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END |
