Debian Codegraph @

apps/transmitmedia.cpp

raw
1 /*
2 * SRT - Secure, Reliable, Transport
3 * Copyright (c) 2018 Haivision Systems Inc.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 *
9 */
10
11 // Just for formality. This file should be used
12 #include <iostream>
13 #include <iomanip>
14 #include <fstream>
15 #include <sstream>
16 #include <memory>
17 #include <string>
18 #include <stdexcept>
19 #include <iterator>
20 #include <map>
21 #include <srt.h>
22 #if !defined(_WIN32)
23 #include <sys/ioctl.h>
24 #else
25 #include <fcntl.h>
26 #include <io.h>
27 #endif
28 #if defined(SUNOS)
29 #include <sys/filio.h>
30 #endif
31
32 #include "netinet_any.h"
33 #include "apputil.hpp"
34 #include "socketoptions.hpp"
35 #include "uriparser.hpp"
36 #include "transmitmedia.hpp"
37 #include "srt_compat.h"
38 #include "verbose.hpp"
39
40 using namespace std;
41 using namespace srt;
42
43 bool g_stats_are_printed_to_stdout = false;
44 bool transmit_total_stats = false;
45 unsigned long transmit_bw_report = 0;
46 unsigned long transmit_stats_report = 0;
47 unsigned long transmit_chunk_size = SRT_LIVE_MAX_PLSIZE;
48
49 class FileSource: public Source
50 {
51 ifstream ifile;
52 string filename_copy;
53 public:
54
55 FileSource(const string& path): ifile(path, ios::in | ios::binary), filename_copy(path)
56 {
57 if ( !ifile )
58 throw std::runtime_error(path + ": Can't open file for reading");
59 }
60
61 int Read(size_t chunk, MediaPacket& pkt, ostream & ignored SRT_ATR_UNUSED = cout) override
62 {
63 if (pkt.payload.size() < chunk)
64 pkt.payload.resize(chunk);
65
66 pkt.time = 0;
67 ifile.read(pkt.payload.data(), chunk);
68 size_t nread = ifile.gcount();
69 if (nread < pkt.payload.size())
70 pkt.payload.resize(nread);
71
72 if (pkt.payload.empty())
73 {
74 return 0;
75 }
76
77 return (int) nread;
78 }
79
80 bool IsOpen() override { return bool(ifile); }
81 bool End() override { return ifile.eof(); }
82 };
83
84 class FileTarget: public Target
85 {
86 ofstream ofile;
87 public:
88
89 FileTarget(const string& path): ofile(path, ios::out | ios::trunc | ios::binary) {}
90
91 int Write(const char* data, size_t size, int64_t time SRT_ATR_UNUSED, ostream & ignored SRT_ATR_UNUSED = cout) override
92 {
93 ofile.write(data, size);
94 return !(ofile.bad()) ? (int) size : 0;
95 }
96
97 bool IsOpen() override { return !!ofile; }
98 bool Broken() override { return !ofile.good(); }
99 //~FileTarget() { ofile.close(); }
100 void Close() override { ofile.close(); }
101 };
102
103 template <class Iface> struct File;
104 template <> struct File<Source> { typedef FileSource type; };
105 template <> struct File<Target> { typedef FileTarget type; };
106
107 template <class Iface>
108 Iface* CreateFile(const string& name) { return new typename File<Iface>::type (name); }
109
110 shared_ptr<SrtStatsWriter> transmit_stats_writer;
111
112 void SrtCommon::InitParameters(string host, map<string,string> par)
113 {
114 // Application-specific options: mode, blocking, timeout, adapter
115 if (Verbose::on && !par.empty())
116 {
117 Verb() << "SRT parameters specified:\n";
118 for (map<string,string>::iterator i = par.begin(); i != par.end(); ++i)
119 {
120 cerr << "\t" << i->first << " = '" << i->second << "'\n";
121 }
122 }
123
124 if (par.count("bind"))
125 {
126 string bindspec = par.at("bind");
127 UriParser u (bindspec, UriParser::EXPECT_HOST);
128 if ( u.scheme() != ""
129 || u.path() != ""
130 || !u.parameters().empty()
131 || u.portno() == 0)
132 {
133 Error("Invalid syntax in 'bind' option");
134 }
135
136 if (u.host() != "")
137 par["adapter"] = u.host();
138 par["port"] = u.port();
139 par.erase("bind");
140 }
141
142 string adapter;
143 if (par.count("adapter"))
144 {
145 adapter = par.at("adapter");
146 }
147
148 m_mode = "default";
149 if (par.count("mode"))
150 {
151 m_mode = par.at("mode");
152 }
153 SocketOption::Mode mode = SrtInterpretMode(m_mode, host, adapter);
154 if (mode == SocketOption::FAILURE)
155 {
156 Error("Invalid mode");
157 }
158
159 // Fix the mode name after successful interpretation
160 m_mode = SocketOption::mode_names[mode];
161
162 par.erase("mode");
163
164 if (par.count("timeout"))
165 {
166 m_timeout = stoi(par.at("timeout"), 0, 0);
167 par.erase("timeout");
168 }
169
170 if (par.count("adapter"))
171 {
172 m_adapter = par.at("adapter");
173 par.erase("adapter");
174 }
175 else if (m_mode == "listener")
176 {
177 // For listener mode, adapter is taken from host,
178 // if 'adapter' parameter is not given
179 m_adapter = host;
180 }
181
182 if (par.count("tsbpd") && false_names.count(par.at("tsbpd")))
183 {
184 m_tsbpdmode = false;
185 }
186
187 if (par.count("port"))
188 {
189 m_outgoing_port = stoi(par.at("port"), 0, 0);
190 par.erase("port");
191 }
192
193 // That's kinda clumsy, but it must rely on the defaults.
194 // Default mode is live, so check if the file mode was enforced
195 if ((par.count("transtype") == 0 || par["transtype"] != "file")
196 && transmit_chunk_size > SRT_LIVE_DEF_PLSIZE)
197 {
198 if (transmit_chunk_size > SRT_LIVE_MAX_PLSIZE)
199 throw std::runtime_error("Chunk size in live mode exceeds 1456 bytes; this is not supported");
200
201 par["payloadsize"] = Sprint(transmit_chunk_size);
202 }
203
204 // Assign the others here.
205 m_options = par;
206 }
207
208 void SrtCommon::PrepareListener(string host, int port, int backlog)
209 {
210 m_bindsock = srt_create_socket();
211 if ( m_bindsock == SRT_ERROR )
212 Error("srt_create_socket");
213
214 int stat = ConfigurePre(m_bindsock);
215 if ( stat == SRT_ERROR )
216 Error("ConfigurePre");
217
218 sockaddr_any sa = CreateAddr(host, port);
219 sockaddr* psa = sa.get();
220 Verb() << "Binding a server on " << host << ":" << port << " ...";
221
222 stat = srt_bind(m_bindsock, psa, sizeof sa);
223 if ( stat == SRT_ERROR )
224 {
225 srt_close(m_bindsock);
226 Error("srt_bind");
227 }
228
229 Verb() << " listen...";
230
231 stat = srt_listen(m_bindsock, backlog);
232 if ( stat == SRT_ERROR )
233 {
234 srt_close(m_bindsock);
235 Error("srt_listen");
236 }
237 }
238
239 void SrtCommon::StealFrom(SrtCommon& src)
240 {
241 // This is used when SrtCommon class designates a listener
242 // object that is doing Accept in appropriate direction class.
243 // The new object should get the accepted socket.
244 m_output_direction = src.m_output_direction;
245 m_timeout = src.m_timeout;
246 m_tsbpdmode = src.m_tsbpdmode;
247 m_options = src.m_options;
248 m_bindsock = SRT_INVALID_SOCK; // no listener
249 m_sock = src.m_sock;
250 src.m_sock = SRT_INVALID_SOCK; // STEALING
251 }
252
253 bool SrtCommon::AcceptNewClient()
254 {
255 sockaddr_any scl;
256 Verb() << " accept... ";
257
258 m_sock = srt_accept(m_bindsock, scl.get(), &scl.len);
259 if ( m_sock == SRT_INVALID_SOCK )
260 {
261 srt_close(m_bindsock);
262 m_bindsock = SRT_INVALID_SOCK;
263 Error("srt_accept");
264 }
265
266 // we do one client connection at a time,
267 // so close the listener.
268 srt_close(m_bindsock);
269 m_bindsock = SRT_INVALID_SOCK;
270
271 Verb() << " connected.";
272
273 // ConfigurePre is done on bindsock, so any possible Pre flags
274 // are DERIVED by sock. ConfigurePost is done exclusively on sock.
275 int stat = ConfigurePost(m_sock);
276 if ( stat == SRT_ERROR )
277 Error("ConfigurePost");
278
279 return true;
280 }
281
282 void SrtCommon::Init(string host, int port, map<string,string> par, bool dir_output)
283 {
284 m_output_direction = dir_output;
285 InitParameters(host, par);
286
287 Verb() << "Opening SRT " << (dir_output ? "target" : "source") << " " << m_mode
288 << " on " << host << ":" << port;
289
290 if ( m_mode == "caller" )
291 OpenClient(host, port);
292 else if ( m_mode == "listener" )
293 OpenServer(m_adapter, port);
294 else if ( m_mode == "rendezvous" )
295 OpenRendezvous(m_adapter, host, port);
296 else
297 {
298 throw std::invalid_argument("Invalid 'mode'. Use 'client' or 'server'");
299 }
300 }
301
302 int SrtCommon::ConfigurePost(SRTSOCKET sock)
303 {
304 bool no = false;
305 int result = 0;
306 if ( m_output_direction )
307 {
308 result = srt_setsockopt(sock, 0, SRTO_SNDSYN, &no, sizeof no);
309 if ( result == -1 )
310 return result;
311
312 if ( m_timeout )
313 return srt_setsockopt(sock, 0, SRTO_SNDTIMEO, &m_timeout, sizeof m_timeout);
314 }
315 else
316 {
317 result = srt_setsockopt(sock, 0, SRTO_RCVSYN, &no, sizeof no);
318 if ( result == -1 )
319 return result;
320
321 if ( m_timeout )
322 return srt_setsockopt(sock, 0, SRTO_RCVTIMEO, &m_timeout, sizeof m_timeout);
323 }
324
325 SrtConfigurePost(sock, m_options);
326
327 for (const auto &o: srt_options)
328 {
329 if ( o.binding == SocketOption::POST && m_options.count(o.name) )
330 {
331 string value = m_options.at(o.name);
332 bool ok = o.apply<SocketOption::SRT>(sock, value);
333 if ( !ok )
334 Verb() << "WARNING: failed to set '" << o.name << "' (post, "
335 << (m_output_direction? "target":"source") << ") to "
336 << value;
337 else
338 Verb() << "NOTE: SRT/post::" << o.name << "=" << value;
339 }
340 }
341
342 return 0;
343 }
344
345 int SrtCommon::ConfigurePre(SRTSOCKET sock)
346 {
347 int result = 0;
348
349 bool no = false;
350 if ( !m_tsbpdmode )
351 {
352 result = srt_setsockopt(sock, 0, SRTO_TSBPDMODE, &no, sizeof no);
353 if ( result == -1 )
354 return result;
355 }
356
357 result = srt_setsockopt(sock, 0, SRTO_RCVSYN, &no, sizeof no);
358 if ( result == -1 )
359 return result;
360
361
362 // host is only checked for emptiness and depending on that the connection mode is selected.
363 // Here we are not exactly interested with that information.
364 vector<string> failures;
365
366 // NOTE: here host = "", so the 'connmode' will be returned as LISTENER always,
367 // but it doesn't matter here. We don't use 'connmode' for anything else than
368 // checking for failures.
369 SocketOption::Mode conmode = SrtConfigurePre(sock, "", m_options, &failures);
370
371 if ( conmode == SocketOption::FAILURE )
372 {
373 if ( Verbose::on )
374 {
375 cerr << "WARNING: failed to set options: ";
376 copy(failures.begin(), failures.end(), ostream_iterator<string>(cerr, ", "));
377 cerr << endl;
378 }
379
380 return SRT_ERROR;
381 }
382
383 return 0;
384 }
385
386 void SrtCommon::SetupAdapter(const string& host, int port)
387 {
388 sockaddr_any localsa = CreateAddr(host, port);
389 sockaddr* psa = localsa.get();
390 int stat = srt_bind(m_sock, psa, sizeof localsa);
391 if ( stat == SRT_ERROR )
392 Error("srt_bind");
393 }
394
395 void SrtCommon::OpenClient(string host, int port)
396 {
397 PrepareClient();
398
399 if (m_outgoing_port || m_adapter != "")
400 {
401 SetupAdapter(m_adapter, m_outgoing_port);
402 }
403
404 ConnectClient(host, port);
405 }
406
407 void SrtCommon::PrepareClient()
408 {
409 m_sock = srt_create_socket();
410 if ( m_sock == SRT_ERROR )
411 Error("srt_create_socket");
412
413 int stat = ConfigurePre(m_sock);
414 if ( stat == SRT_ERROR )
415 Error("ConfigurePre");
416 }
417
418
419 void SrtCommon::ConnectClient(string host, int port)
420 {
421
422 sockaddr_any sa = CreateAddr(host, port);
423 sockaddr* psa = sa.get();
424
425 Verb() << "Connecting to " << host << ":" << port;
426
427 int stat = srt_connect(m_sock, psa, sizeof sa);
428 if ( stat == SRT_ERROR )
429 {
430 srt_close(m_sock);
431 Error("srt_connect");
432 }
433
434 stat = ConfigurePost(m_sock);
435 if ( stat == SRT_ERROR )
436 Error("ConfigurePost");
437 }
438
439 void SrtCommon::Error(string src)
440 {
441 int errnov = 0;
442 int result = srt_getlasterror(&errnov);
443 string message = srt_getlasterror_str();
444 Verb() << "\nERROR #" << result << "." << errnov << ": " << message;
445
446 throw TransmissionError("error: " + src + ": " + message);
447 }
448
449 void SrtCommon::OpenRendezvous(string adapter, string host, int port)
450 {
451 m_sock = srt_create_socket();
452 if ( m_sock == SRT_ERROR )
453 Error("srt_create_socket");
454
455 bool yes = true;
456 srt_setsockopt(m_sock, 0, SRTO_RENDEZVOUS, &yes, sizeof yes);
457
458 int stat = ConfigurePre(m_sock);
459 if ( stat == SRT_ERROR )
460 Error("ConfigurePre");
461
462 sockaddr_any sa = CreateAddr(host, port);
463 if (sa.family() == AF_UNSPEC)
464 {
465 Error("OpenRendezvous: invalid target host specification: " + host);
466 }
467
468 const int outport = m_outgoing_port ? m_outgoing_port : port;
469
470 sockaddr_any localsa = CreateAddr(adapter, outport, sa.family());
471
472 Verb() << "Binding a server on " << adapter << ":" << outport;
473
474 stat = srt_bind(m_sock, localsa.get(), sizeof localsa);
475 if ( stat == SRT_ERROR )
476 {
477 srt_close(m_sock);
478 Error("srt_bind");
479 }
480
481 Verb() << "Connecting to " << host << ":" << port;
482
483 stat = srt_connect(m_sock, sa.get(), sizeof sa);
484 if ( stat == SRT_ERROR )
485 {
486 srt_close(m_sock);
487 Error("srt_connect");
488 }
489
490 stat = ConfigurePost(m_sock);
491 if ( stat == SRT_ERROR )
492 Error("ConfigurePost");
493 }
494
495 void SrtCommon::Close()
496 {
497 Verb() << "SrtCommon: DESTROYING CONNECTION, closing sockets (rt%" << m_sock << " ls%" << m_bindsock << ")...";
498
499 if ( m_sock != SRT_INVALID_SOCK )
500 {
501 srt_close(m_sock);
502 m_sock = SRT_INVALID_SOCK;
503 }
504
505 if ( m_bindsock != SRT_INVALID_SOCK )
506 {
507 srt_close(m_bindsock);
508 m_bindsock = SRT_INVALID_SOCK ;
509 }
510
511 Verb() << "SrtCommon: ... done.";
512 }
513
514 SrtCommon::~SrtCommon()
515 {
516 Close();
517 }
518
519 SrtSource::SrtSource(string host, int port, const map<string,string>& par)
520 {
521 Init(host, port, par, false);
522
523 ostringstream os;
524 os << host << ":" << port;
525 hostport_copy = os.str();
526 }
527
528 int SrtSource::Read(size_t chunk, MediaPacket& pkt, ostream &out_stats)
529 {
530 static unsigned long counter = 1;
531
532 if (pkt.payload.size() < chunk)
533 pkt.payload.resize(chunk);
534
535 SRT_MSGCTRL ctrl;
536 const int stat = srt_recvmsg2(m_sock, pkt.payload.data(), (int) chunk, &ctrl);
537 if (stat <= 0)
538 {
539 pkt.payload.clear();
540 return stat;
541 }
542
543 pkt.time = ctrl.srctime;
544
545 chunk = size_t(stat);
546 if (chunk < pkt.payload.size())
547 pkt.payload.resize(chunk);
548
549 const bool need_bw_report = transmit_bw_report && (counter % transmit_bw_report) == transmit_bw_report - 1;
550 const bool need_stats_report = transmit_stats_report && (counter % transmit_stats_report) == transmit_stats_report - 1;
551
552 if (need_bw_report || need_stats_report)
553 {
554 CBytePerfMon perf;
555 srt_bstats(m_sock, &perf, need_stats_report && !transmit_total_stats);
556 if (transmit_stats_writer != nullptr)
557 {
558 if (need_bw_report)
559 cerr << transmit_stats_writer->WriteBandwidth(perf.mbpsBandwidth) << std::flush;
560 if (need_stats_report)
561 out_stats << transmit_stats_writer->WriteStats(m_sock, perf) << std::flush;
562 }
563 }
564 ++counter;
565 return stat;
566 }
567
568 int SrtTarget::ConfigurePre(SRTSOCKET sock)
569 {
570 int result = SrtCommon::ConfigurePre(sock);
571 if ( result == -1 )
572 return result;
573
574 int yes = 1;
575 // This is for the HSv4 compatibility; if both parties are HSv5
576 // (min. version 1.2.1), then this setting simply does nothing.
577 // In HSv4 this setting is obligatory; otherwise the SRT handshake
578 // extension will not be done at all.
579 result = srt_setsockopt(sock, 0, SRTO_SENDER, &yes, sizeof yes);
580 if ( result == -1 )
581 return result;
582
583 return 0;
584 }
585
586 int SrtTarget::Write(const char* data, size_t size, int64_t src_time, ostream &out_stats)
587 {
588 static unsigned long counter = 1;
589
590 SRT_MSGCTRL ctrl = srt_msgctrl_default;
591 ctrl.srctime = src_time;
592 int stat = srt_sendmsg2(m_sock, data, (int) size, &ctrl);
593 if (stat == SRT_ERROR)
594 {
595 return stat;
596 }
597
598 const bool need_bw_report = transmit_bw_report && (counter % transmit_bw_report) == transmit_bw_report - 1;
599 const bool need_stats_report = transmit_stats_report && (counter % transmit_stats_report) == transmit_stats_report - 1;
600
601 if (need_bw_report || need_stats_report)
602 {
603 CBytePerfMon perf;
604 srt_bstats(m_sock, &perf, need_stats_report && !transmit_total_stats);
605 if (transmit_stats_writer != nullptr)
606 {
607 if (need_bw_report)
608 cerr << transmit_stats_writer->WriteBandwidth(perf.mbpsBandwidth) << std::flush;
609 if (need_stats_report)
610 out_stats << transmit_stats_writer->WriteStats(m_sock, perf) << std::flush;
611 }
612 }
613 ++counter;
614 return stat;
615 }
616
617
618 SrtModel::SrtModel(string host, int port, map<string,string> par)
619 {
620 InitParameters(host, par);
621 if (m_mode == "caller")
622 is_caller = true;
623 else if (m_mode != "listener")
624 throw std::invalid_argument("Only caller and listener modes supported");
625
626 m_host = host;
627 m_port = port;
628 }
629
630 void SrtModel::Establish(std::string& w_name)
631 {
632 // This does connect or accept.
633 // When this returned true, the caller should create
634 // a new SrtSource or SrtTaget then call StealFrom(*this) on it.
635
636 // If this is a connector and the peer doesn't have a corresponding
637 // medium, it should send back a single byte with value 0. This means
638 // that agent should stop connecting.
639
640 if (is_caller)
641 {
642 // Establish a connection
643
644 PrepareClient();
645
646 if (w_name != "")
647 {
648 Verb() << "Connect with requesting stream [" << w_name << "]";
649 srt::setstreamid(m_sock, w_name);
650 }
651 else
652 {
653 Verb() << "NO STREAM ID for SRT connection";
654 }
655
656 if (m_outgoing_port)
657 {
658 Verb() << "Setting outgoing port: " << m_outgoing_port;
659 SetupAdapter("", m_outgoing_port);
660 }
661
662 ConnectClient(m_host, m_port);
663
664 if (m_outgoing_port == 0)
665 {
666 // Must rely on a randomly selected one. Extract the port
667 // so that it will be reused next time.
668 sockaddr_any s(AF_INET);
669 int namelen = s.size();
670 if ( srt_getsockname(Socket(), s.get(), &namelen) == SRT_ERROR )
671 {
672 Error("srt_getsockname");
673 }
674
675 m_outgoing_port = s.hport();
676 Verb() << "Extracted outgoing port: " << m_outgoing_port;
677 }
678 }
679 else
680 {
681 // Listener - get a socket by accepting.
682 // Check if the listener is already created first
683 if (Listener() == SRT_INVALID_SOCK)
684 {
685 Verb() << "Setting up listener: port=" << m_port << " backlog=5";
686 PrepareListener(m_adapter, m_port, 5);
687 }
688
689 Verb() << "Accepting a client...";
690 AcceptNewClient();
691 // This rewrites m_sock with a new SRT socket ("accepted" socket)
692 w_name = srt::getstreamid(m_sock);
693 Verb() << "... GOT CLIENT for stream [" << w_name << "]";
694 }
695 }
696
697
698 template <class Iface> struct Srt;
699 template <> struct Srt<Source> { typedef SrtSource type; };
700 template <> struct Srt<Target> { typedef SrtTarget type; };
701
702 template <class Iface>
703 Iface* CreateSrt(const string& host, int port, const map<string,string>& par) { return new typename Srt<Iface>::type (host, port, par); }
704
705 class ConsoleSource: public Source
706 {
707 const bool may_block = true;
708 public:
709
710 ConsoleSource()
711 #ifdef _WIN32
712 : may_block(true)
713 #else
714 : may_block(fcntl(fileno(stdin), F_SETFL, fcntl(fileno(stdin), F_GETFL) | O_NONBLOCK) < 0)
715 #endif
716 {
717 #ifdef _WIN32
718 // The default stdin mode on windows is text.
719 // We have to set it to the binary mode
720 _setmode(_fileno(stdin), _O_BINARY);
721 #endif
722 }
723
724 int Read(size_t chunk, MediaPacket& pkt, ostream & ignored SRT_ATR_UNUSED = cout) override
725 {
726 if (pkt.payload.size() < chunk)
727 pkt.payload.resize(chunk);
728
729 const int ret = ::read(GetSysSocket(), pkt.payload.data(), chunk);
730 if (ret <= 0)
731 {
732 pkt.payload.clear();
733 return 0;
734 }
735
736 // Save this time to potentially use it for SRT target.
737 pkt.time = srt_time_now();
738 if (chunk < pkt.payload.size())
739 pkt.payload.resize(ret);
740
741 return ret;
742 }
743
744 bool IsOpen() override { return cin.good(); }
745 bool MayBlock() const final { return may_block; }
746 bool End() override { return cin.eof(); }
747 int GetSysSocket() const override { return fileno(stdin); };
748 };
749
750 class ConsoleTarget: public Target
751 {
752 public:
753
754 ConsoleTarget()
755 {
756 #ifdef _WIN32
757 // The default stdout mode on windows is text.
758 // We have to set it to the binary mode
759 _setmode(_fileno(stdout), _O_BINARY);
760 #endif
761 }
762
763 virtual ~ConsoleTarget()
764 {
765 cout.flush();
766 }
767
768 int Write(const char* data, size_t len, int64_t src_time SRT_ATR_UNUSED, ostream & ignored SRT_ATR_UNUSED = cout) override
769 {
770 cout.write(data, len);
771 return (int) len;
772 }
773
774 bool IsOpen() override { return cout.good(); }
775 bool Broken() override { return cout.eof(); }
776 int GetSysSocket() const override { return fileno(stdout); };
777 };
778
779 template <class Iface> struct Console;
780 template <> struct Console<Source> { typedef ConsoleSource type; };
781 template <> struct Console<Target> { typedef ConsoleTarget type; };
782
783 template <class Iface>
784 Iface* CreateConsole() { return new typename Console<Iface>::type (); }
785
786
787 // More options can be added in future.
788 SocketOption udp_options [] {
789 { "iptos", IPPROTO_IP, IP_TOS, SocketOption::PRE, SocketOption::INT, nullptr },
790 // IP_TTL and IP_MULTICAST_TTL are handled separately by a common option, "ttl".
791 { "mcloop", IPPROTO_IP, IP_MULTICAST_LOOP, SocketOption::PRE, SocketOption::INT, nullptr },
792 { "sndbuf", SOL_SOCKET, SO_SNDBUF, SocketOption::PRE, SocketOption::INT, nullptr},
793 { "rcvbuf", SOL_SOCKET, SO_RCVBUF, SocketOption::PRE, SocketOption::INT, nullptr}
794 };
795
796 static inline bool IsMulticast(in_addr adr)
797 {
798 unsigned char* abytes = (unsigned char*)&adr.s_addr;
799 unsigned char c = abytes[0];
800 return c >= 224 && c <= 239;
801 }
802
803
804 class UdpCommon
805 {
806 protected:
807 int m_sock = -1;
808 string adapter;
809 sockaddr_any interface_addr;
810 sockaddr_any target_addr;
811 bool is_multicast = false;
812 map<string, string> m_options;
813
814 void Setup(string host, int port, map<string,string> attr)
815 {
816 m_sock = (int)socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
817 if (m_sock == -1)
818 Error(SysError(), "UdpCommon::Setup: socket");
819
820 int yes = 1;
821 ::setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yes, sizeof yes);
822
823 // set non-blocking mode
824 #if defined(_WIN32)
825 unsigned long ulyes = 1;
826 const bool ioctl_error = (ioctlsocket(m_sock, FIONBIO, &ulyes) == SOCKET_ERROR);
827 #else
828 const bool ioctl_error = (ioctl(m_sock, FIONBIO, (const char *)&yes) == -1);
829 #endif
830 if (ioctl_error)
831 {
832 Error(SysError(), "UdpCommon::Setup: ioctl FIONBIO");
833 }
834
835 interface_addr = CreateAddr("", port, AF_INET);
836 target_addr = CreateAddr(host, port);
837
838 is_multicast = false;
839
840 if (attr.count("multicast"))
841 {
842 // XXX: Here provide support for IPv6 multicast #1479
843 if (target_addr.family() != AF_INET)
844 {
845 throw std::runtime_error("UdpCommon: Multicast on IPv6 is not yet supported");
846 }
847
848 if (!IsMulticast(target_addr.sin.sin_addr))
849 {
850 throw std::runtime_error("UdpCommon: requested multicast for a non-multicast-type IP address");
851 }
852 is_multicast = true;
853 }
854 else if (target_addr.family() == AF_INET && IsMulticast(target_addr.sin.sin_addr))
855 {
856 is_multicast = true;
857 }
858
859 if (is_multicast)
860 {
861 ip_mreq mreq;
862 int opt_name;
863 const char* mreq_arg_ptr;
864 socklen_t mreq_arg_size;
865
866 adapter = attr.count("adapter") ? attr.at("adapter") : string();
867 if (adapter == "")
868 {
869 Verb() << "Multicast: home address: INADDR_ANY:" << port;
870 }
871 else
872 {
873 Verb() << "Multicast: home address: " << adapter << ":" << port;
874 interface_addr = CreateAddr(adapter, port);
875 }
876
877 if (attr.count("source"))
878 {
879 #ifdef IP_ADD_SOURCE_MEMBERSHIP
880 ip_mreq_source mreq_ssm;
881 /* this is an ssm. we need to use the right struct and opt */
882 opt_name = IP_ADD_SOURCE_MEMBERSHIP;
883 mreq_ssm.imr_multiaddr.s_addr = target_addr.sin.sin_addr.s_addr;
884 mreq_ssm.imr_interface.s_addr = interface_addr.sin.sin_addr.s_addr;
885 inet_pton(AF_INET, attr.at("source").c_str(), &mreq_ssm.imr_sourceaddr);
886 mreq_arg_size = sizeof(mreq_ssm);
887 mreq_arg_ptr = (const char*)&mreq_ssm;
888 #else
889 throw std::runtime_error("UdpCommon: source-filter multicast not supported by OS");
890 #endif
891 }
892 else
893 {
894 opt_name = IP_ADD_MEMBERSHIP;
895 mreq.imr_multiaddr.s_addr = target_addr.sin.sin_addr.s_addr;
896 mreq.imr_interface.s_addr = interface_addr.sin.sin_addr.s_addr;
897 mreq_arg_size = sizeof(mreq);
898 mreq_arg_ptr = (const char*)&mreq;
899 }
900
901 #ifdef _WIN32
902 const auto status_error = SOCKET_ERROR;
903 #else
904 const auto status_error = -1;
905 #endif
906 auto res = setsockopt(m_sock, IPPROTO_IP, opt_name, mreq_arg_ptr, mreq_arg_size);
907
908 if (res == status_error)
909 {
910 Error(errno, "adding to multicast membership failed");
911 }
912
913 attr.erase("multicast");
914 attr.erase("adapter");
915 }
916
917 // The "ttl" options is handled separately, it maps to both IP_TTL
918 // and IP_MULTICAST_TTL so that TTL setting works for both uni- and multicast.
919 if (attr.count("ttl"))
920 {
921 int ttl = stoi(attr.at("ttl"));
922 int res = setsockopt(m_sock, IPPROTO_IP, IP_TTL, (const char*)&ttl, sizeof ttl);
923 if (res == -1)
924 Verb() << "WARNING: failed to set 'ttl' (IP_TTL) to " << ttl;
925 res = setsockopt(m_sock, IPPROTO_IP, IP_MULTICAST_TTL, (const char*)&ttl, sizeof ttl);
926 if (res == -1)
927 Verb() << "WARNING: failed to set 'ttl' (IP_MULTICAST_TTL) to " << ttl;
928
929 attr.erase("ttl");
930 }
931
932 m_options = attr;
933
934 for (auto o: udp_options)
935 {
936 // Ignore "binding" - for UDP there are no post options.
937 if ( m_options.count(o.name) )
938 {
939 string value = m_options.at(o.name);
940 bool ok = o.apply<SocketOption::SYSTEM>(m_sock, value);
941 if ( !ok )
942 Verb() << "WARNING: failed to set '" << o.name << "' to " << value;
943 }
944 }
945 }
946
947 void Error(int err, string src)
948 {
949 char buf[512];
950 string message = SysStrError(err, buf, 512u);
951
952 cerr << "\nERROR #" << err << ": " << message << endl;
953
954 throw TransmissionError("error: " + src + ": " + message);
955 }
956
957 ~UdpCommon()
958 {
959 #ifdef _WIN32
960 if (m_sock != -1)
961 {
962 shutdown(m_sock, SD_BOTH);
963 closesocket(m_sock);
964 m_sock = -1;
965 }
966 #else
967 close(m_sock);
968 #endif
969 }
970 };
971
972
973 class UdpSource: public Source, public UdpCommon
974 {
975 protected:
976 bool eof = true;
977 public:
978
979 UdpSource(string host, int port, const map<string,string>& attr)
980 {
981 Setup(host, port, attr);
982
983 // On Windows it somehow doesn't work when bind()
984 // is called with multicast address. Write the address
985 // that designates the network device here, always.
986
987 // Hance we have two fields holding the address:
988 // * target_addr: address from which reading will be done
989 // * unicast: local address of the interface
990 // * multicast: the IGMP address
991 // * interface_addr: address of the local interface
992 // (same as target_addr for unicast)
993
994 // In case of multicast, binding should be done:
995 // On most POSIX systems, to the multicast address (target_addr in this case)
996 // On Windows, to a local address (hence use interface_addr, as in this
997 // case it differs to target_addr).
998
999 #if defined(_WIN32) || defined(__CYGWIN__)
1000 sockaddr_any baddr = is_multicast ? interface_addr : target_addr;
1001 static const char* const sysname = "Windows";
1002 #else
1003 static const char* const sysname = "POSIX";
1004 sockaddr_any baddr = target_addr;
1005 #endif
1006 Verb("UDP:", is_multicast ? "Multicast" : "Unicast", "(", sysname,
1007 "): will bind to: ", baddr.str());
1008 int stat = ::bind(m_sock, baddr.get(), baddr.size());
1009
1010 if (stat == -1)
1011 Error(SysError(), "Binding address for UDP");
1012 eof = false;
1013 }
1014
1015 int Read(size_t chunk, MediaPacket& pkt, ostream & ignored SRT_ATR_UNUSED = cout) override
1016 {
1017 if (pkt.payload.size() < chunk)
1018 pkt.payload.resize(chunk);
1019
1020 sockaddr_any sa(target_addr.family());
1021 socklen_t si = sa.size();
1022 int stat = recvfrom(m_sock, pkt.payload.data(), (int) chunk, 0, sa.get(), &si);
1023 if (stat < 1)
1024 {
1025 if (SysError() != EWOULDBLOCK)
1026 eof = true;
1027 pkt.payload.clear();
1028 return stat;
1029 }
1030 sa.len = si;
1031
1032 // Save this time to potentially use it for SRT target.
1033 pkt.time = srt_time_now();
1034 chunk = size_t(stat);
1035 if (chunk < pkt.payload.size())
1036 pkt.payload.resize(chunk);
1037
1038 return stat;
1039 }
1040
1041 bool IsOpen() override { return m_sock != -1; }
1042 bool End() override { return eof; }
1043
1044 int GetSysSocket() const override { return m_sock; };
1045 };
1046
1047 class UdpTarget: public Target, public UdpCommon
1048 {
1049 public:
1050 UdpTarget(string host, int port, const map<string,string>& attr )
1051 {
1052 if (host.empty())
1053 cerr << "\nWARN Host for UDP target is not provided. Will send to localhost:" << port << ".\n";
1054
1055 Setup(host, port, attr);
1056 if (is_multicast && interface_addr.isany() == false)
1057 {
1058 if (interface_addr.family() != AF_INET)
1059 {
1060 Error(0, "UDP/target: IPv6 multicast not supported in the application");
1061 }
1062
1063 in_addr addr = interface_addr.sin.sin_addr;
1064
1065 int res = setsockopt(m_sock, IPPROTO_IP, IP_MULTICAST_IF, reinterpret_cast<const char*>(&addr), sizeof(addr));
1066 if (res == -1)
1067 {
1068 Error(SysError(), "setsockopt/IP_MULTICAST_IF: " + adapter);
1069 }
1070 }
1071
1072 }
1073
1074 int Write(const char* data, size_t len, int64_t src_time SRT_ATR_UNUSED, ostream & ignored SRT_ATR_UNUSED = cout) override
1075 {
1076 int stat = sendto(m_sock, data, (int)len, 0, target_addr.get(), target_addr.size());
1077 if ( stat == -1 )
1078 {
1079 if ((false))
1080 Error(SysError(), "UDP Write/sendto");
1081 return stat;
1082 }
1083 return stat;
1084 }
1085
1086 bool IsOpen() override { return m_sock != -1; }
1087 bool Broken() override { return false; }
1088
1089 int GetSysSocket() const override { return m_sock; };
1090 };
1091
1092 template <class Iface> struct Udp;
1093 template <> struct Udp<Source> { typedef UdpSource type; };
1094 template <> struct Udp<Target> { typedef UdpTarget type; };
1095
1096 template <class Iface>
1097 Iface* CreateUdp(const string& host, int port, const map<string,string>& par) { return new typename Udp<Iface>::type (host, port, par); }
1098
1099 class RtpSource: public UdpSource
1100 {
1101 // for now, make no effort to parse the header, just assume it is always
1102 // fixed length and either a user-configurable value, or twelve bytes.
1103 const int MINIMUM_RTP_HEADER_SIZE = 12;
1104 int bytes_to_skip = MINIMUM_RTP_HEADER_SIZE;
1105 public:
1106 RtpSource(string host, int port, const map<string,string>& attr) :
1107 UdpSource { host, port, attr }
1108 {
1109 if (attr.count("rtpheadersize"))
1110 {
1111 const int header_size = stoi(attr.at("rtpheadersize"), 0, 0);
1112 if (header_size < MINIMUM_RTP_HEADER_SIZE)
1113 {
1114 cerr << "Invalid RTP header size provided: " << header_size
1115 << ", minimum allowed is " << MINIMUM_RTP_HEADER_SIZE
1116 << endl;
1117 throw invalid_argument("Invalid RTP header size");
1118 }
1119 bytes_to_skip = header_size;
1120 }
1121 }
1122
1123 int Read(size_t chunk, MediaPacket& pkt, ostream & ignored SRT_ATR_UNUSED = cout) override
1124 {
1125 const int length = UdpSource::Read(chunk, pkt);
1126
1127 if (length < 1 || !bytes_to_skip)
1128 {
1129 // something went wrong, or we're not skipping bytes for some
1130 // reason, just return the length read via the base method
1131 return length;
1132 }
1133
1134 // we got some data and we're supposed to skip some of it
1135 // check there's enough bytes for our intended skip
1136 if (length < bytes_to_skip)
1137 {
1138 // something went wrong here
1139 cerr << "RTP packet too short (" << length
1140 << " bytes) to remove headers (needed "
1141 << bytes_to_skip << ")" << endl;
1142 throw std::runtime_error("Unexpected RTP packet length");
1143 }
1144
1145 pkt.payload.erase(
1146 pkt.payload.begin(),
1147 pkt.payload.begin() + bytes_to_skip
1148 );
1149
1150 return length - bytes_to_skip;
1151 }
1152 };
1153
1154 class RtpTarget : public UdpTarget {
1155 public:
1156 RtpTarget(string host, int port, const map<string,string>& attr ) :
1157 UdpTarget { host, port, attr } {}
1158 };
1159
1160 template <class Iface> struct Rtp;
1161 template <> struct Rtp<Source> { typedef RtpSource type; };
1162 template <> struct Rtp<Target> { typedef RtpTarget type; };
1163
1164 template <class Iface>
1165 Iface* CreateRtp(const string& host, int port, const map<string,string>& par) { return new typename Rtp<Iface>::type (host, port, par); }
1166
1167 template<class Base>
1168 inline bool IsOutput() { return false; }
1169
1170 template<>
1171 inline bool IsOutput<Target>() { return true; }
1172
1173 template <class Base>
1174 extern unique_ptr<Base> CreateMedium(const string& uri)
1175 {
1176 unique_ptr<Base> ptr;
1177
1178 UriParser u(uri);
1179
1180 int iport = 0;
1181 switch ( u.type() )
1182 {
1183 default:
1184 break; // do nothing, return nullptr
1185 case UriParser::FILE:
1186 if (u.host() == "con" || u.host() == "console")
1187 {
1188 if (IsOutput<Base>() && (
1189 (Verbose::on && Verbose::cverb == &cout)
1190 || g_stats_are_printed_to_stdout))
1191 {
1192 cerr << "ERROR: file://con with -v or -r or -s would result in mixing the data and text info.\n";
1193 cerr << "ERROR: HINT: you can stream through a FIFO (named pipe)\n";
1194 throw invalid_argument("incorrect parameter combination");
1195 }
1196 ptr.reset(CreateConsole<Base>());
1197 }
1198 // Disable regular file support for the moment
1199 #if 0
1200 else
1201 ptr.reset( CreateFile<Base>(u.path()));
1202 #endif
1203 break;
1204
1205 case UriParser::SRT:
1206 iport = atoi(u.port().c_str());
1207 if ( iport < 1024 )
1208 {
1209 cerr << "Port value invalid: " << iport << " - must be >=1024\n";
1210 throw invalid_argument("Invalid port number");
1211 }
1212 ptr.reset( CreateSrt<Base>(u.host(), iport, u.parameters()) );
1213 break;
1214
1215
1216 case UriParser::UDP:
1217 iport = atoi(u.port().c_str());
1218 if ( iport < 1024 )
1219 {
1220 cerr << "Port value invalid: " << iport << " - must be >=1024\n";
1221 throw invalid_argument("Invalid port number");
1222 }
1223 ptr.reset( CreateUdp<Base>(u.host(), iport, u.parameters()) );
1224 break;
1225
1226 case UriParser::RTP:
1227 if (IsOutput<Base>())
1228 {
1229 cerr << "RTP not supported as an output\n";
1230 throw invalid_argument("Invalid output protocol: RTP");
1231 }
1232 iport = atoi(u.port().c_str());
1233 if ( iport < 1024 )
1234 {
1235 cerr << "Port value invalid: " << iport << " - must be >=1024\n";
1236 throw invalid_argument("Invalid port number");
1237 }
1238 ptr.reset( CreateRtp<Base>(u.host(), iport, u.parameters()) );
1239 break;
1240 }
1241
1242 if (ptr.get())
1243 ptr->uri = std::move(u);
1244
1245 return ptr;
1246 }
1247
1248
1249 std::unique_ptr<Source> Source::Create(const std::string& url)
1250 {
1251 return CreateMedium<Source>(url);
1252 }
1253
1254 std::unique_ptr<Target> Target::Create(const std::string& url)
1255 {
1256 return CreateMedium<Target>(url);
1257 }