obs-ffmpeg-srt.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. /*
  2. * The following code is a port of FFmpeg/avformat/libsrt.c for obs-studio.
  3. * Port by [email protected].
  4. *
  5. * Permission to use, copy, modify, and distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  12. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  15. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. */
  17. #pragma once
  18. #include <obs-module.h>
  19. #include "obs-ffmpeg-url.h"
  20. #include <srt/srt.h>
  21. #include <libavformat/avformat.h>
  22. #ifdef _WIN32
  23. #include <sys/timeb.h>
  24. #endif
  25. #define POLLING_TIME 100 /// Time in milliseconds between interrupt check
  26. /* This is for MPEG-TS (7 TS packets) */
  27. #ifndef SRT_LIVE_DEFAULT_PAYLOAD_SIZE
  28. #define SRT_LIVE_DEFAULT_PAYLOAD_SIZE 1316
  29. #endif
  30. enum SRTMode { SRT_MODE_CALLER = 0, SRT_MODE_LISTENER = 1, SRT_MODE_RENDEZVOUS = 2 };
  31. typedef struct SRTContext {
  32. SRTSOCKET fd;
  33. int eid;
  34. int64_t rw_timeout;
  35. int64_t listen_timeout;
  36. int recv_buffer_size;
  37. int send_buffer_size;
  38. int64_t maxbw;
  39. int pbkeylen;
  40. char *passphrase;
  41. #if SRT_VERSION_VALUE >= 0x010302
  42. int enforced_encryption;
  43. int kmrefreshrate;
  44. int kmpreannounce;
  45. int64_t snddropdelay;
  46. #endif
  47. int mss;
  48. int ffs;
  49. int ipttl;
  50. int iptos;
  51. int64_t inputbw;
  52. int oheadbw;
  53. int64_t latency;
  54. int tlpktdrop;
  55. int nakreport;
  56. int64_t connect_timeout;
  57. int payload_size;
  58. int64_t rcvlatency;
  59. int64_t peerlatency;
  60. enum SRTMode mode;
  61. int sndbuf;
  62. int rcvbuf;
  63. int lossmaxttl;
  64. int minversion;
  65. char *streamid;
  66. char *smoother;
  67. int messageapi;
  68. SRT_TRANSTYPE transtype;
  69. char *localip;
  70. char *localport;
  71. int linger;
  72. int tsbpd;
  73. double time; // time in s in order to post logs at definite intervals
  74. } SRTContext;
  75. static int libsrt_neterrno(URLContext *h)
  76. {
  77. SRTContext *s = (SRTContext *)h->priv_data;
  78. int os_errno;
  79. int err = srt_getlasterror(&os_errno);
  80. blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: %s", srt_getlasterror_str());
  81. if (err == SRT_EASYNCRCV || err == SRT_EASYNCSND)
  82. return AVERROR(EAGAIN);
  83. if (err == SRT_ECONNREJ) {
  84. int errj = srt_getrejectreason(s->fd);
  85. if (errj == SRT_REJ_BADSECRET)
  86. blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: Wrong password");
  87. else
  88. blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: Connection rejected, %s",
  89. srt_rejectreason_str(errj));
  90. }
  91. return os_errno ? AVERROR(os_errno) : AVERROR_UNKNOWN;
  92. }
  93. static int libsrt_getsockopt(URLContext *h, SRTSOCKET fd, SRT_SOCKOPT optname, const char *optnamestr, void *optval,
  94. int *optlen)
  95. {
  96. UNUSED_PARAMETER(h);
  97. if (srt_getsockopt(fd, 0, optname, optval, optlen) < 0) {
  98. blog(LOG_INFO, "[obs-ffmpeg mpegts muxer / libsrt]: Failed to get option %s on socket: %s", optnamestr,
  99. srt_getlasterror_str());
  100. return AVERROR(EIO);
  101. }
  102. return 0;
  103. }
  104. static int libsrt_socket_nonblock(SRTSOCKET socket, int enable)
  105. {
  106. int ret, blocking = enable ? 0 : 1;
  107. /* Setting SRTO_{SND,RCV}SYN options to 1 enable blocking mode, setting them to 0 enable non-blocking mode. */
  108. ret = srt_setsockopt(socket, 0, SRTO_SNDSYN, &blocking, sizeof(blocking));
  109. if (ret < 0)
  110. return ret;
  111. return srt_setsockopt(socket, 0, SRTO_RCVSYN, &blocking, sizeof(blocking));
  112. }
  113. static int libsrt_epoll_create(URLContext *h, SRTSOCKET fd, int write)
  114. {
  115. int modes = SRT_EPOLL_ERR | (write ? SRT_EPOLL_OUT : SRT_EPOLL_IN);
  116. int eid = srt_epoll_create();
  117. if (eid < 0)
  118. return libsrt_neterrno(h);
  119. if (srt_epoll_add_usock(eid, fd, &modes) < 0) {
  120. srt_epoll_release(eid);
  121. return libsrt_neterrno(h);
  122. }
  123. return eid;
  124. }
  125. static int libsrt_network_wait_fd(URLContext *h, int eid, int write)
  126. {
  127. int ret, len = 1, errlen = 1;
  128. SRTSOCKET ready[1];
  129. SRTSOCKET error[1];
  130. SRTContext *s = (SRTContext *)h->priv_data;
  131. if (write) {
  132. ret = srt_epoll_wait(eid, error, &errlen, ready, &len, POLLING_TIME, 0, 0, 0, 0);
  133. } else {
  134. ret = srt_epoll_wait(eid, ready, &len, error, &errlen, POLLING_TIME, 0, 0, 0, 0);
  135. }
  136. if (len == 1 && errlen == 1 && s->mode == SRT_MODE_CALLER) {
  137. /* Socket reported in wsock AND rsock signifies an error. */
  138. int reason = srt_getrejectreason(*ready);
  139. if (reason == SRT_REJ_BADSECRET || reason == SRT_REJ_UNSECURE || reason == SRT_REJ_TIMEOUT) {
  140. blog(LOG_ERROR,
  141. "[obs-ffmpeg mpegts muxer / libsrt]: Connection rejected, wrong password or invalid URL");
  142. return OBS_OUTPUT_INVALID_STREAM;
  143. } else {
  144. blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: Connection rejected, %s",
  145. srt_rejectreason_str(reason));
  146. }
  147. }
  148. if (ret < 0) {
  149. if (srt_getlasterror(NULL) == SRT_ETIMEOUT)
  150. ret = AVERROR(EAGAIN);
  151. else
  152. ret = libsrt_neterrno(h);
  153. } else {
  154. ret = errlen ? AVERROR(EIO) : 0;
  155. }
  156. return ret;
  157. }
  158. int check_interrupt(AVIOInterruptCB *cb)
  159. {
  160. if (cb && cb->callback)
  161. return cb->callback(cb->opaque);
  162. return 0;
  163. }
  164. static int libsrt_network_wait_fd_timeout(URLContext *h, int eid, int write, int64_t timeout, AVIOInterruptCB *int_cb)
  165. {
  166. int ret;
  167. int64_t wait_start = 0;
  168. while (1) {
  169. if (check_interrupt(int_cb))
  170. return AVERROR_EXIT;
  171. ret = libsrt_network_wait_fd(h, eid, write);
  172. if (ret != AVERROR(EAGAIN))
  173. return ret;
  174. if (timeout > 0) {
  175. if (!wait_start)
  176. wait_start = av_gettime_relative();
  177. else if (av_gettime_relative() - wait_start > timeout)
  178. return AVERROR(ETIMEDOUT);
  179. }
  180. }
  181. }
  182. static int libsrt_listen(int eid, SRTSOCKET fd, const struct sockaddr *addr, socklen_t addrlen, URLContext *h,
  183. int64_t timeout)
  184. {
  185. int ret;
  186. int reuse = 1;
  187. /* Max streamid length plus an extra space for the terminating null character */
  188. char streamid[513];
  189. int streamid_len = sizeof(streamid);
  190. if (srt_setsockopt(fd, SOL_SOCKET, SRTO_REUSEADDR, &reuse, sizeof(reuse))) {
  191. blog(LOG_WARNING, "[obs-ffmpeg mpegts muxer / libsrt]: setsockopt(SRTO_REUSEADDR) failed");
  192. }
  193. if (srt_bind(fd, addr, addrlen))
  194. return libsrt_neterrno(h);
  195. if (srt_listen(fd, 1))
  196. return libsrt_neterrno(h);
  197. ret = libsrt_network_wait_fd_timeout(h, eid, 0, timeout, &h->interrupt_callback);
  198. if (ret < 0)
  199. return ret;
  200. ret = srt_accept(fd, NULL, NULL);
  201. if (ret < 0)
  202. return libsrt_neterrno(h);
  203. if (libsrt_socket_nonblock(ret, 1) < 0)
  204. blog(LOG_DEBUG, "[obs-ffmpeg mpegts muxer / libsrt]: libsrt_socket_nonblock failed");
  205. if (!libsrt_getsockopt(h, ret, SRTO_STREAMID, "SRTO_STREAMID", streamid, &streamid_len))
  206. /* Note: returned streamid_len doesn't count the terminating null character */
  207. blog(LOG_INFO, "[obs-ffmpeg mpegts muxer / libsrt]: Accept streamid [%s], length %d", streamid,
  208. streamid_len);
  209. return ret;
  210. }
  211. static int libsrt_listen_connect(int eid, SRTSOCKET fd, const struct sockaddr *addr, socklen_t addrlen, int64_t timeout,
  212. URLContext *h, int will_try_next)
  213. {
  214. int ret;
  215. if (srt_connect(fd, addr, addrlen) < 0)
  216. return libsrt_neterrno(h);
  217. ret = libsrt_network_wait_fd_timeout(h, eid, 1, timeout, &h->interrupt_callback);
  218. if (ret < 0) {
  219. if (will_try_next) {
  220. blog(LOG_WARNING,
  221. "[obs-ffmpeg mpegts muxer / libsrt]: Connection to %s failed (%s), trying next address",
  222. h->url, av_err2str(ret));
  223. } else {
  224. blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: Connection to %s failed: %s", h->url,
  225. av_err2str(ret));
  226. }
  227. }
  228. return ret;
  229. }
  230. static int libsrt_setsockopt(URLContext *h, SRTSOCKET fd, SRT_SOCKOPT optname, const char *optnamestr,
  231. const void *optval, int optlen)
  232. {
  233. UNUSED_PARAMETER(h);
  234. if (srt_setsockopt(fd, 0, optname, optval, optlen) < 0) {
  235. blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: Failed to set option %s on socket: %s", optnamestr,
  236. srt_getlasterror_str());
  237. return AVERROR(EIO);
  238. }
  239. return 0;
  240. }
  241. /* - The "POST" options can be altered any time on a connected socket.
  242. They MAY have also some meaning when set prior to connecting; such
  243. option is SRTO_RCVSYN, which makes connect/accept call asynchronous.
  244. Because of that this option is treated special way in this app. */
  245. static int libsrt_set_options_post(URLContext *h, SRTSOCKET fd)
  246. {
  247. SRTContext *s = (SRTContext *)h->priv_data;
  248. if ((s->inputbw >= 0 &&
  249. libsrt_setsockopt(h, fd, SRTO_INPUTBW, "SRTO_INPUTBW", &s->inputbw, sizeof(s->inputbw)) < 0) ||
  250. (s->oheadbw >= 0 &&
  251. libsrt_setsockopt(h, fd, SRTO_OHEADBW, "SRTO_OHEADBW", &s->oheadbw, sizeof(s->oheadbw)) < 0)) {
  252. return AVERROR(EIO);
  253. }
  254. return 0;
  255. }
  256. /* - The "PRE" options must be set prior to connecting and can't be altered
  257. on a connected socket, however if set on a listening socket, they are
  258. derived by accept-ed socket. */
  259. static int libsrt_set_options_pre(URLContext *h, SRTSOCKET fd)
  260. {
  261. SRTContext *s = (SRTContext *)h->priv_data;
  262. int yes = 1;
  263. int latency = (int)(s->latency / 1000);
  264. int rcvlatency = (int)(s->rcvlatency / 1000);
  265. int peerlatency = (int)(s->peerlatency / 1000);
  266. #if SRT_VERSION_VALUE >= 0x010302
  267. int snddropdelay = s->snddropdelay > 0 ? (int)(s->snddropdelay / 1000) : (int)(s->snddropdelay);
  268. #endif
  269. int connect_timeout = (int)(s->connect_timeout);
  270. if ((s->mode == SRT_MODE_RENDEZVOUS &&
  271. libsrt_setsockopt(h, fd, SRTO_RENDEZVOUS, "SRTO_RENDEZVOUS", &yes, sizeof(yes)) < 0) ||
  272. (s->transtype != SRTT_INVALID &&
  273. libsrt_setsockopt(h, fd, SRTO_TRANSTYPE, "SRTO_TRANSTYPE", &s->transtype, sizeof(s->transtype)) < 0) ||
  274. (s->maxbw >= 0 && libsrt_setsockopt(h, fd, SRTO_MAXBW, "SRTO_MAXBW", &s->maxbw, sizeof(s->maxbw)) < 0) ||
  275. (s->pbkeylen >= 0 &&
  276. libsrt_setsockopt(h, fd, SRTO_PBKEYLEN, "SRTO_PBKEYLEN", &s->pbkeylen, sizeof(s->pbkeylen)) < 0) ||
  277. (s->passphrase && libsrt_setsockopt(h, fd, SRTO_PASSPHRASE, "SRTO_PASSPHRASE", s->passphrase,
  278. (int)strlen(s->passphrase)) < 0) ||
  279. #if SRT_VERSION_VALUE >= 0x010302
  280. #if SRT_VERSION_VALUE >= 0x010401
  281. (s->enforced_encryption >= 0 &&
  282. libsrt_setsockopt(h, fd, SRTO_ENFORCEDENCRYPTION, "SRTO_ENFORCEDENCRYPTION", &s->enforced_encryption,
  283. sizeof(s->enforced_encryption)) < 0) ||
  284. #else
  285. /* SRTO_STRICTENC == SRTO_ENFORCEDENCRYPTION (53), but for compatibility, we used SRTO_STRICTENC */
  286. (s->enforced_encryption >= 0 &&
  287. libsrt_setsockopt(h, fd, SRTO_STRICTENC, "SRTO_STRICTENC", &s->enforced_encryption,
  288. sizeof(s->enforced_encryption)) < 0) ||
  289. #endif
  290. (s->kmrefreshrate >= 0 && libsrt_setsockopt(h, fd, SRTO_KMREFRESHRATE, "SRTO_KMREFRESHRATE",
  291. &s->kmrefreshrate, sizeof(s->kmrefreshrate)) < 0) ||
  292. (s->kmpreannounce >= 0 && libsrt_setsockopt(h, fd, SRTO_KMPREANNOUNCE, "SRTO_KMPREANNOUNCE",
  293. &s->kmpreannounce, sizeof(s->kmpreannounce)) < 0) ||
  294. (s->snddropdelay >= -1 && libsrt_setsockopt(h, fd, SRTO_SNDDROPDELAY, "SRTO_SNDDROPDELAY", &snddropdelay,
  295. sizeof(snddropdelay)) < 0) ||
  296. #endif
  297. (s->mss >= 0 && libsrt_setsockopt(h, fd, SRTO_MSS, "SRTO_MSS", &s->mss, sizeof(s->mss)) < 0) ||
  298. (s->ffs >= 0 && libsrt_setsockopt(h, fd, SRTO_FC, "SRTO_FC", &s->ffs, sizeof(s->ffs)) < 0) ||
  299. (s->ipttl >= 0 && libsrt_setsockopt(h, fd, SRTO_IPTTL, "SRTO_IPTTL", &s->ipttl, sizeof(s->ipttl)) < 0) ||
  300. (s->iptos >= 0 && libsrt_setsockopt(h, fd, SRTO_IPTOS, "SRTO_IPTOS", &s->iptos, sizeof(s->iptos)) < 0) ||
  301. (s->latency >= 0 &&
  302. libsrt_setsockopt(h, fd, SRTO_LATENCY, "SRTO_LATENCY", &latency, sizeof(latency)) < 0) ||
  303. (s->rcvlatency >= 0 &&
  304. libsrt_setsockopt(h, fd, SRTO_RCVLATENCY, "SRTO_RCVLATENCY", &rcvlatency, sizeof(rcvlatency)) < 0) ||
  305. (s->peerlatency >= 0 &&
  306. libsrt_setsockopt(h, fd, SRTO_PEERLATENCY, "SRTO_PEERLATENCY", &peerlatency, sizeof(peerlatency)) < 0) ||
  307. (s->tlpktdrop >= 0 &&
  308. libsrt_setsockopt(h, fd, SRTO_TLPKTDROP, "SRTO_TLPKTDROP", &s->tlpktdrop, sizeof(s->tlpktdrop)) < 0) ||
  309. (s->nakreport >= 0 &&
  310. libsrt_setsockopt(h, fd, SRTO_NAKREPORT, "SRTO_NAKREPORT", &s->nakreport, sizeof(s->nakreport)) < 0) ||
  311. (connect_timeout >= 0 && libsrt_setsockopt(h, fd, SRTO_CONNTIMEO, "SRTO_CONNTIMEO", &connect_timeout,
  312. sizeof(connect_timeout)) < 0) ||
  313. (s->sndbuf >= 0 &&
  314. libsrt_setsockopt(h, fd, SRTO_SNDBUF, "SRTO_SNDBUF", &s->sndbuf, sizeof(s->sndbuf)) < 0) ||
  315. (s->rcvbuf >= 0 &&
  316. libsrt_setsockopt(h, fd, SRTO_RCVBUF, "SRTO_RCVBUF", &s->rcvbuf, sizeof(s->rcvbuf)) < 0) ||
  317. (s->lossmaxttl >= 0 &&
  318. libsrt_setsockopt(h, fd, SRTO_LOSSMAXTTL, "SRTO_LOSSMAXTTL", &s->lossmaxttl, sizeof(s->lossmaxttl)) < 0) ||
  319. (s->minversion >= 0 &&
  320. libsrt_setsockopt(h, fd, SRTO_MINVERSION, "SRTO_MINVERSION", &s->minversion, sizeof(s->minversion)) < 0) ||
  321. (s->streamid &&
  322. libsrt_setsockopt(h, fd, SRTO_STREAMID, "SRTO_STREAMID", s->streamid, (int)strlen(s->streamid)) < 0) ||
  323. #if SRT_VERSION_VALUE >= 0x010401
  324. (s->smoother &&
  325. libsrt_setsockopt(h, fd, SRTO_CONGESTION, "SRTO_CONGESTION", s->smoother, (int)strlen(s->smoother)) < 0) ||
  326. #else
  327. (s->smoother &&
  328. libsrt_setsockopt(h, fd, SRTO_SMOOTHER, "SRTO_SMOOTHER", s->smoother, (int)strlen(s->smoother)) < 0) ||
  329. #endif
  330. (s->messageapi >= 0 &&
  331. libsrt_setsockopt(h, fd, SRTO_MESSAGEAPI, "SRTO_MESSAGEAPI", &s->messageapi, sizeof(s->messageapi)) < 0) ||
  332. (s->payload_size >= 0 && libsrt_setsockopt(h, fd, SRTO_PAYLOADSIZE, "SRTO_PAYLOADSIZE", &s->payload_size,
  333. sizeof(s->payload_size)) < 0) ||
  334. (/*(h->flags & AVIO_FLAG_WRITE) &&*/
  335. libsrt_setsockopt(h, fd, SRTO_SENDER, "SRTO_SENDER", &yes, sizeof(yes)) < 0) ||
  336. (s->tsbpd >= 0 &&
  337. libsrt_setsockopt(h, fd, SRTO_TSBPDMODE, "SRTO_TSBPDMODE", &s->tsbpd, sizeof(s->tsbpd)) < 0)) {
  338. return AVERROR(EIO);
  339. }
  340. if (s->linger >= 0) {
  341. struct linger lin;
  342. lin.l_linger = s->linger;
  343. lin.l_onoff = lin.l_linger > 0 ? 1 : 0;
  344. if (libsrt_setsockopt(h, fd, SRTO_LINGER, "SRTO_LINGER", &lin, sizeof(lin)) < 0)
  345. return AVERROR(EIO);
  346. }
  347. return 0;
  348. }
  349. static int libsrt_setup(URLContext *h, const char *uri)
  350. {
  351. struct addrinfo hints = {0}, *ai, *cur_ai;
  352. int port;
  353. SRTSOCKET fd;
  354. SRTContext *s = (SRTContext *)h->priv_data;
  355. const char *p;
  356. char buf[1024];
  357. int ret;
  358. char hostname[1024], proto[1024], path[1024];
  359. char portstr[10];
  360. int64_t open_timeout = 0;
  361. int eid;
  362. struct sockaddr_in la;
  363. av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port, path, sizeof(path), uri);
  364. if (strcmp(proto, "srt")) // should not happen !
  365. return AVERROR(EINVAL);
  366. if (port <= 0 || port >= 65536) {
  367. blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: Port missing in uri");
  368. return OBS_OUTPUT_CONNECT_FAILED;
  369. }
  370. p = strchr(uri, '?');
  371. if (p) {
  372. if (av_find_info_tag(buf, sizeof(buf), "timeout", p)) {
  373. s->rw_timeout = strtoll(buf, NULL, 10);
  374. }
  375. if (av_find_info_tag(buf, sizeof(buf), "listen_timeout", p)) {
  376. s->listen_timeout = strtoll(buf, NULL, 10);
  377. }
  378. }
  379. if (s->rw_timeout >= 0) {
  380. open_timeout = h->rw_timeout = s->rw_timeout;
  381. }
  382. hints.ai_family = AF_UNSPEC;
  383. hints.ai_socktype = SOCK_DGRAM;
  384. snprintf(portstr, sizeof(portstr), "%d", port);
  385. if (s->mode == SRT_MODE_LISTENER)
  386. hints.ai_flags |= AI_PASSIVE;
  387. ret = getaddrinfo(hostname[0] ? hostname : NULL, portstr, &hints, &ai);
  388. if (ret) {
  389. blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: Failed to resolve hostname %s: %s", hostname,
  390. #ifdef _WIN32
  391. gai_strerrorA(ret)
  392. #else
  393. gai_strerror(ret)
  394. #endif
  395. );
  396. return OBS_OUTPUT_CONNECT_FAILED;
  397. }
  398. cur_ai = ai;
  399. if (s->mode == SRT_MODE_RENDEZVOUS) {
  400. if (s->localip == NULL || s->localport == NULL) {
  401. blog(LOG_ERROR, "Invalid adapter configuration\n");
  402. return OBS_OUTPUT_CONNECT_FAILED;
  403. }
  404. blog(LOG_DEBUG, "[obs-ffmpeg mpegts muxer / libsrt]: Adapter options %s:%s\n", s->localip,
  405. s->localport);
  406. int lp = strtol(s->localport, NULL, 10);
  407. if (lp <= 0 || lp >= 65536) {
  408. blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: Local port missing in URL\n");
  409. return OBS_OUTPUT_CONNECT_FAILED;
  410. }
  411. la.sin_family = AF_INET;
  412. la.sin_port = htons(port);
  413. inet_pton(AF_INET, s->localip, &la.sin_addr.s_addr);
  414. }
  415. restart:
  416. fd = srt_create_socket();
  417. if (fd < 0) {
  418. ret = libsrt_neterrno(h);
  419. goto fail;
  420. }
  421. if ((ret = libsrt_set_options_pre(h, fd)) < 0) {
  422. goto fail;
  423. }
  424. /* Set the socket's send or receive buffer sizes, if specified.
  425. If unspecified or setting fails, system default is used. */
  426. if (s->recv_buffer_size > 0) {
  427. srt_setsockopt(fd, SOL_SOCKET, SRTO_UDP_RCVBUF, &s->recv_buffer_size, sizeof(s->recv_buffer_size));
  428. }
  429. if (s->send_buffer_size > 0) {
  430. srt_setsockopt(fd, SOL_SOCKET, SRTO_UDP_SNDBUF, &s->send_buffer_size, sizeof(s->send_buffer_size));
  431. }
  432. if (libsrt_socket_nonblock(fd, 1) < 0)
  433. blog(LOG_DEBUG, "[obs-ffmpeg mpegts muxer / libsrt]: libsrt_socket_nonblock failed");
  434. if (s->mode == SRT_MODE_LISTENER) {
  435. int read_eid = ret = libsrt_epoll_create(h, fd, 0);
  436. if (ret < 0)
  437. goto fail1;
  438. // multi-client
  439. ret = libsrt_listen(read_eid, fd, cur_ai->ai_addr, (socklen_t)cur_ai->ai_addrlen, h, s->listen_timeout);
  440. srt_epoll_release(read_eid);
  441. if (ret < 0)
  442. goto fail1;
  443. srt_close(fd);
  444. fd = ret;
  445. } else {
  446. int write_eid = ret = libsrt_epoll_create(h, fd, 1);
  447. if (ret < 0)
  448. goto fail1;
  449. if (s->mode == SRT_MODE_RENDEZVOUS) {
  450. if (srt_bind(fd, (struct sockaddr *)&la, sizeof(struct sockaddr_in))) {
  451. ret = libsrt_neterrno(h);
  452. srt_epoll_release(write_eid);
  453. goto fail1;
  454. }
  455. }
  456. ret = libsrt_listen_connect(write_eid, fd, cur_ai->ai_addr, (socklen_t)(cur_ai->ai_addrlen),
  457. open_timeout, h, !!cur_ai->ai_next);
  458. srt_epoll_release(write_eid);
  459. if (ret < 0) {
  460. if (ret == AVERROR_EXIT)
  461. goto fail1;
  462. else
  463. goto fail;
  464. }
  465. }
  466. if ((ret = libsrt_set_options_post(h, fd)) < 0) {
  467. goto fail;
  468. }
  469. int packet_size = 0;
  470. int optlen = sizeof(packet_size);
  471. ret = libsrt_getsockopt(h, fd, SRTO_PAYLOADSIZE, "SRTO_PAYLOADSIZE", &packet_size, &optlen);
  472. if (ret < 0)
  473. goto fail1;
  474. if (packet_size > 0)
  475. h->max_packet_size = packet_size;
  476. ret = eid = libsrt_epoll_create(h, fd, 1 /*flags & AVIO_FLAG_WRITE*/);
  477. if (eid < 0)
  478. goto fail1;
  479. s->fd = fd;
  480. s->eid = eid;
  481. freeaddrinfo(ai);
  482. return 0;
  483. fail:
  484. if (cur_ai->ai_next) {
  485. /* Retry with the next sockaddr */
  486. cur_ai = cur_ai->ai_next;
  487. if (fd >= 0)
  488. srt_close(fd);
  489. ret = 0;
  490. goto restart;
  491. }
  492. fail1:
  493. if (fd >= 0)
  494. srt_close(fd);
  495. freeaddrinfo(ai);
  496. return ret;
  497. }
  498. static void libsrt_set_defaults(SRTContext *s)
  499. {
  500. s->rw_timeout = -1;
  501. s->listen_timeout = -1;
  502. s->send_buffer_size = -1;
  503. s->recv_buffer_size = -1;
  504. s->payload_size = SRT_LIVE_DEFAULT_PAYLOAD_SIZE;
  505. s->maxbw = -1;
  506. s->pbkeylen = -1;
  507. s->mss = -1;
  508. s->ffs = -1;
  509. s->ipttl = -1;
  510. s->iptos = -1;
  511. s->inputbw = -1;
  512. s->oheadbw = -1;
  513. s->latency = -1;
  514. s->rcvlatency = -1;
  515. s->peerlatency = -1;
  516. s->tlpktdrop = -1;
  517. s->nakreport = -1;
  518. s->connect_timeout = -1;
  519. s->mode = SRT_MODE_CALLER;
  520. s->sndbuf = -1;
  521. s->rcvbuf = -1;
  522. s->lossmaxttl = -1;
  523. s->minversion = -1;
  524. s->smoother = NULL;
  525. s->messageapi = -1;
  526. s->transtype = SRTT_LIVE;
  527. s->linger = -1;
  528. s->tsbpd = -1;
  529. }
  530. static int libsrt_open(URLContext *h, const char *uri)
  531. {
  532. SRTContext *s = (SRTContext *)h->priv_data;
  533. const char *p;
  534. char buf[1024];
  535. int ret = 0;
  536. if (srt_startup() < 0) {
  537. blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: libsrt failed to load");
  538. return OBS_OUTPUT_CONNECT_FAILED;
  539. } else {
  540. blog(LOG_INFO, "[obs-ffmpeg mpegts muxer / libsrt]: libsrt version %s loaded", SRT_VERSION_STRING);
  541. }
  542. libsrt_set_defaults(s);
  543. /* SRT options (srt/srt.h) */
  544. p = strchr(uri, '?');
  545. if (p) {
  546. if (av_find_info_tag(buf, sizeof(buf), "maxbw", p)) {
  547. s->maxbw = strtoll(buf, NULL, 10);
  548. }
  549. if (av_find_info_tag(buf, sizeof(buf), "pbkeylen", p)) {
  550. s->pbkeylen = strtol(buf, NULL, 10);
  551. }
  552. if (av_find_info_tag(buf, sizeof(buf), "passphrase", p)) {
  553. av_freep(&s->passphrase);
  554. s->passphrase = av_strndup(buf, strlen(buf));
  555. }
  556. #if SRT_VERSION_VALUE >= 0x010302
  557. if (av_find_info_tag(buf, sizeof(buf), "enforced_encryption", p)) {
  558. s->enforced_encryption = strtol(buf, NULL, 10);
  559. }
  560. if (av_find_info_tag(buf, sizeof(buf), "kmrefreshrate", p)) {
  561. s->kmrefreshrate = strtol(buf, NULL, 10);
  562. }
  563. if (av_find_info_tag(buf, sizeof(buf), "kmpreannounce", p)) {
  564. s->kmpreannounce = strtol(buf, NULL, 10);
  565. }
  566. if (av_find_info_tag(buf, sizeof(buf), "snddropdelay", p)) {
  567. s->snddropdelay = strtoll(buf, NULL, 10);
  568. }
  569. #endif
  570. if (av_find_info_tag(buf, sizeof(buf), "mss", p)) {
  571. s->mss = strtol(buf, NULL, 10);
  572. }
  573. if (av_find_info_tag(buf, sizeof(buf), "ffs", p)) {
  574. s->ffs = strtol(buf, NULL, 10);
  575. }
  576. if (av_find_info_tag(buf, sizeof(buf), "ipttl", p)) {
  577. s->ipttl = strtol(buf, NULL, 10);
  578. }
  579. if (av_find_info_tag(buf, sizeof(buf), "iptos", p)) {
  580. s->iptos = strtol(buf, NULL, 10);
  581. }
  582. if (av_find_info_tag(buf, sizeof(buf), "inputbw", p)) {
  583. s->inputbw = strtoll(buf, NULL, 10);
  584. }
  585. if (av_find_info_tag(buf, sizeof(buf), "oheadbw", p)) {
  586. s->oheadbw = strtol(buf, NULL, 10);
  587. }
  588. if (av_find_info_tag(buf, sizeof(buf), "latency", p)) {
  589. s->latency = strtoll(buf, NULL, 10);
  590. }
  591. if (av_find_info_tag(buf, sizeof(buf), "tsbpddelay", p)) {
  592. s->latency = strtoll(buf, NULL, 10);
  593. }
  594. if (av_find_info_tag(buf, sizeof(buf), "rcvlatency", p)) {
  595. s->rcvlatency = strtoll(buf, NULL, 10);
  596. }
  597. if (av_find_info_tag(buf, sizeof(buf), "peerlatency", p)) {
  598. s->peerlatency = strtoll(buf, NULL, 10);
  599. }
  600. if (av_find_info_tag(buf, sizeof(buf), "tlpktdrop", p)) {
  601. s->tlpktdrop = strtol(buf, NULL, 10);
  602. }
  603. if (av_find_info_tag(buf, sizeof(buf), "nakreport", p)) {
  604. s->nakreport = strtol(buf, NULL, 10);
  605. }
  606. if (av_find_info_tag(buf, sizeof(buf), "connect_timeout", p)) {
  607. s->connect_timeout = strtoll(buf, NULL, 10);
  608. }
  609. if (av_find_info_tag(buf, sizeof(buf), "payload_size", p) ||
  610. av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
  611. s->payload_size = strtol(buf, NULL, 10);
  612. }
  613. if (av_find_info_tag(buf, sizeof(buf), "mode", p)) {
  614. if (!strcmp(buf, "caller")) {
  615. s->mode = SRT_MODE_CALLER;
  616. } else if (!strcmp(buf, "listener")) {
  617. s->mode = SRT_MODE_LISTENER;
  618. } else if (!strcmp(buf, "rendezvous")) {
  619. s->mode = SRT_MODE_RENDEZVOUS;
  620. } else {
  621. ret = AVERROR(EINVAL);
  622. goto err;
  623. }
  624. }
  625. if (av_find_info_tag(buf, sizeof(buf), "sndbuf", p)) {
  626. s->sndbuf = strtol(buf, NULL, 10);
  627. }
  628. if (av_find_info_tag(buf, sizeof(buf), "rcvbuf", p)) {
  629. s->rcvbuf = strtol(buf, NULL, 10);
  630. }
  631. if (av_find_info_tag(buf, sizeof(buf), "lossmaxttl", p)) {
  632. s->lossmaxttl = strtol(buf, NULL, 10);
  633. }
  634. if (av_find_info_tag(buf, sizeof(buf), "minversion", p)) {
  635. s->minversion = strtol(buf, NULL, 0);
  636. }
  637. if (av_find_info_tag(buf, sizeof(buf), "streamid", p)) {
  638. av_freep(&s->streamid);
  639. s->streamid = av_strdup(buf);
  640. if (!s->streamid) {
  641. ret = AVERROR(ENOMEM);
  642. goto err;
  643. }
  644. }
  645. if (av_find_info_tag(buf, sizeof(buf), "smoother", p)) {
  646. av_freep(&s->smoother);
  647. s->smoother = av_strdup(buf);
  648. if (!s->smoother) {
  649. ret = AVERROR(ENOMEM);
  650. goto err;
  651. }
  652. }
  653. if (av_find_info_tag(buf, sizeof(buf), "messageapi", p)) {
  654. s->messageapi = strtol(buf, NULL, 10);
  655. }
  656. if (av_find_info_tag(buf, sizeof(buf), "transtype", p)) {
  657. if (!strcmp(buf, "live")) {
  658. s->transtype = SRTT_LIVE;
  659. } else if (!strcmp(buf, "file")) {
  660. s->transtype = SRTT_FILE;
  661. } else {
  662. ret = AVERROR(EINVAL);
  663. goto err;
  664. }
  665. }
  666. if (av_find_info_tag(buf, sizeof(buf), "linger", p)) {
  667. s->linger = strtol(buf, NULL, 10);
  668. }
  669. if (av_find_info_tag(buf, sizeof(buf), "localip", p)) {
  670. s->localip = av_strndup(buf, strlen(buf));
  671. }
  672. if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
  673. s->localport = av_strndup(buf, strlen(buf));
  674. }
  675. }
  676. ret = libsrt_setup(h, uri);
  677. if (ret < 0)
  678. goto err;
  679. #ifdef _WIN32
  680. struct timeb timebuffer;
  681. ftime(&timebuffer);
  682. s->time = (double)timebuffer.time + 0.001 * (double)timebuffer.millitm;
  683. #else
  684. struct timespec timesp;
  685. clock_gettime(CLOCK_REALTIME, &timesp);
  686. s->time = (double)timesp.tv_sec + 0.000000001 * (double)timesp.tv_nsec;
  687. #endif
  688. return 0;
  689. err:
  690. av_freep(&s->smoother);
  691. av_freep(&s->streamid);
  692. srt_cleanup();
  693. return ret;
  694. }
  695. static int libsrt_write(URLContext *h, const uint8_t *buf, int size)
  696. {
  697. SRTContext *s = (SRTContext *)h->priv_data;
  698. int ret;
  699. SRT_TRACEBSTATS perf;
  700. ret = libsrt_network_wait_fd_timeout(h, s->eid, 1, h->rw_timeout, &h->interrupt_callback);
  701. if (ret)
  702. return ret;
  703. ret = srt_send(s->fd, (char *)buf, size);
  704. if (ret < 0) {
  705. ret = libsrt_neterrno(h);
  706. } else {
  707. /* log every 60 seconds the rtt and link bandwidth
  708. * rtt: round-trip time
  709. * link bandwidth: bandwidth from ingest to egress
  710. */
  711. #ifdef _WIN32
  712. struct timeb timebuffer;
  713. ftime(&timebuffer);
  714. double time = (double)timebuffer.time + 0.001 * (double)timebuffer.millitm;
  715. #else
  716. struct timespec timesp;
  717. clock_gettime(CLOCK_REALTIME, &timesp);
  718. double time = (double)timesp.tv_sec + 0.000000001 * (double)timesp.tv_nsec;
  719. #endif
  720. if (time > (s->time + 60.0)) {
  721. srt_bistats(s->fd, &perf, 0, 1);
  722. blog(LOG_DEBUG, "[obs-ffmpeg mpegts muxer / libsrt]: RTT [%.2f ms], Link Bandwidth [%.1f Mbps]",
  723. perf.msRTT, perf.mbpsBandwidth);
  724. s->time = time;
  725. }
  726. }
  727. return ret;
  728. }
  729. static int libsrt_close(URLContext *h)
  730. {
  731. SRTContext *s = (SRTContext *)h->priv_data;
  732. if (!s)
  733. return 0;
  734. if (s->streamid)
  735. av_freep(&s->streamid);
  736. if (s->passphrase)
  737. av_freep(&s->passphrase);
  738. /* Log stream stats. */
  739. SRT_TRACEBSTATS perf = {0};
  740. srt_bstats(s->fd, &perf, 1);
  741. blog(LOG_INFO, "---------------------------------");
  742. blog(LOG_INFO,
  743. "[obs-ffmpeg mpegts muxer / libsrt]: Session Summary\n"
  744. "\ttime elapsed [%.1f sec]\n"
  745. "\tmean speed [%.1f Mbp]\n"
  746. "\ttotal bytes sent [%.1f MB]\n"
  747. "\tbytes retransmitted [%.1f %%]\n"
  748. "\tbytes dropped [%.1f %%]\n",
  749. (double)perf.msTimeStamp / 1000.0, perf.mbpsSendRate, (double)perf.byteSentTotal / 1000000.0,
  750. perf.byteSentTotal ? perf.byteRetransTotal / perf.byteSentTotal * 100.0 : 0,
  751. perf.byteSentTotal ? perf.byteSndDropTotal / perf.byteSentTotal * 100.0 : 0);
  752. srt_epoll_release(s->eid);
  753. int err = srt_close(s->fd);
  754. if (err < 0) {
  755. blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: %s", srt_getlasterror_str());
  756. return -1;
  757. }
  758. srt_cleanup();
  759. blog(LOG_INFO, "[obs-ffmpeg mpegts muxer / libsrt]: SRT connection closed");
  760. return 0;
  761. }