Debian Codegraph @

testing/srt-test-file.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 /*****************************************************************************
12 written by
13 Haivision Systems Inc.
14 *****************************************************************************/
15
16 #ifdef _WIN32
17 #include <direct.h>
18 #endif
19 #include <iostream>
20 #include <iterator>
21 #include <vector>
22 #include <map>
23 #include <tuple>
24 #include <stdexcept>
25 #include <string>
26 #include <thread>
27 #include <chrono>
28 #include <sys/stat.h>
29 #include <srt.h>
30 #include <udt.h>
31 #include <logging.h>
32
33 #include "apputil.hpp"
34 #include "uriparser.hpp"
35 #include "logsupport.hpp"
36 #include "socketoptions.hpp"
37 #include "verbose.hpp"
38 #include "testmedia.hpp"
39
40 #ifndef S_ISDIR
41 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
42 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
43 #endif
44
45 bool Upload(UriParser& srt, UriParser& file);
46 bool Download(UriParser& srt, UriParser& file);
47
48 static size_t g_buffer_size = 1456;
49 static bool g_skip_flushing = false;
50
51 using namespace std;
52
53 srt_logging::Logger applog(SRT_LOGFA_APP, srt_logger_config, "srt-file");
54
55 int main( int argc, char** argv )
56 {
57 vector<OptionScheme> optargs;
58
59 OptionName
60 o_loglevel ((optargs), "<severity=fatal|error|note|warning|debug> Minimum severity for logs", "ll", "loglevel"),
61 o_buffer ((optargs), "<size[b]=1456> Size of the single reading operation", "b", "buffer"),
62 o_verbose ((optargs), " Print extra verbos output", "v", "verbose"),
63 o_noflush ((optargs), " Do not wait safely 5 seconds at the end to flush buffers", "sf", "skipflush"),
64 o_help ((optargs), " This help", "?", "help", "-help")
65 ;
66
67 options_t params = ProcessOptions(argv, argc, optargs);
68
69 bool need_help = OptionPresent(params, o_help);
70
71 //*
72 cerr << "OPTIONS (DEBUG)\n";
73 for (auto o: params)
74 {
75 cerr << "[" << o.first << "] ";
76 copy(o.second.begin(), o.second.end(), ostream_iterator<string>(cerr, " "));
77 cerr << endl;
78 }
79 // */
80
81 if (need_help)
82 {
83 cerr << "Usage:\n";
84 cerr << " " << argv[0] << " [options] <input> <output>\n";
85 cerr << "*** (Position of [options] is unrestricted.)\n";
86 cerr << "*** (<variadic...> option parameters can be only terminated by a next option.)\n";
87 cerr << "where:\n";
88 cerr << " <input> and <output> is specified by an URI.\n";
89 cerr << "SUPPORTED URI SCHEMES:\n";
90 cerr << " srt: use SRT connection\n";
91 cerr << " udp: read from bound UDP socket or send to given address as UDP\n";
92 cerr << " file (default if scheme not specified) specified as:\n";
93 cerr << " - empty host/port and absolute file path in the URI\n";
94 cerr << " - only a filename, also as a relative path\n";
95 cerr << " - file://con ('con' as host): designates stdin or stdout\n";
96 cerr << "OPTIONS HELP SYNTAX: -option <parameter[unit]=default[meaning]>:\n";
97 for (auto os: optargs)
98 cout << OptionHelpItem(*os.pid) << endl;
99 return 1;
100 }
101
102 vector<string> args = params[""];
103 if ( args.size() < 2 )
104 {
105 cerr << "Usage: " << argv[0] << " <source> <target>\n";
106 return 1;
107 }
108
109 string loglevel = Option<OutString>(params, "error", o_loglevel);
110 srt_logging::LogLevel::type lev = SrtParseLogLevel(loglevel);
111 srt::setloglevel(lev);
112 srt::addlogfa(SRT_LOGFA_APP);
113
114 bool verbo = OptionPresent(params, o_verbose);
115 if (verbo)
116 {
117 Verbose::on = true;
118 Verbose::cverb = &std::cout;
119 }
120
121 string bs = Option<OutString>(params, "", o_buffer);
122 if ( bs != "" )
123 {
124 ::g_buffer_size = stoi(bs);
125 }
126
127 string sf = Option<OutString>(params, "no", o_noflush);
128 if (sf == "" || !false_names.count(sf))
129 ::g_skip_flushing = true;
130
131 string source = args[0];
132 string target = args[1];
133
134 UriParser us(source), ut(target);
135
136 Verb() << "SOURCE type=" << us.scheme() << ", TARGET type=" << ut.scheme();
137
138 try
139 {
140 if (us.scheme() == "srt")
141 {
142 if (ut.scheme() != "file")
143 {
144 cerr << "SRT to FILE should be specified\n";
145 return 1;
146 }
147 Download(us, ut);
148 }
149 else if (ut.scheme() == "srt")
150 {
151 if (us.scheme() != "file")
152 {
153 cerr << "FILE to SRT should be specified\n";
154 return 1;
155 }
156 Upload(ut, us);
157 }
158 else
159 {
160 cerr << "SRT URI must be one of given media.\n";
161 return 1;
162 }
163 }
164 catch (std::exception& x)
165 {
166 cerr << "ERROR: " << x.what() << endl;
167 return 1;
168 }
169
170
171 return 0;
172 }
173
174 tuple<string, string> ExtractPath(string path)
175 {
176 //string& dir = r_dir;
177 //string& fname = r_fname;
178
179 string directory = path;
180 string filename = "";
181
182 struct stat state;
183 stat(path.c_str(), &state);
184 if (!S_ISDIR(state.st_mode))
185 {
186 // Extract directory as a butlast part of path
187 size_t pos = path.find_last_of("/");
188 if ( pos == string::npos )
189 {
190 filename = path;
191 directory = ".";
192 }
193 else
194 {
195 directory = path.substr(0, pos);
196 filename = path.substr(pos+1);
197 }
198 }
199
200 if (directory[0] != '/')
201 {
202 // Glue in the absolute prefix of the current directory
203 // to make it absolute. This is needed to properly interpret
204 // the fixed uri.
205 static const size_t s_max_path = 4096; // don't care how proper this is
206 char tmppath[s_max_path];
207 char* gwd = getcwd(tmppath, s_max_path);
208 if ( !gwd )
209 {
210 // Don't bother with that now. We need something better for that anyway.
211 throw std::invalid_argument("Path too long");
212 }
213 string wd = gwd;
214
215 directory = wd + "/" + directory;
216 }
217
218 return make_tuple(directory, filename);
219 }
220
221 bool DoUpload(UriParser& ut, string path, string filename)
222 {
223 SrtModel m(ut.host(), ut.portno(), ut.parameters());
224
225 string id = filename;
226 Verb() << "Passing '" << id << "' as stream ID\n";
227
228 m.Establish((id));
229
230 // Check if the filename was changed
231 if (id != filename)
232 {
233 cerr << "SRT caller has changed the filename '" << filename << "' to '" << id << "' - rejecting\n";
234 return false;
235 }
236
237 Verb() << "USING ID: " << id;
238
239 // SrtTarget* tp = new SrtTarget;
240 // tp->StealFrom(m);
241 // unique_ptr<Target> target(tp);
242
243 //SRTSOCKET ss = tp->Socket();
244 SRTSOCKET ss = m.Socket();
245
246 // Use a manual loop for reading from SRT
247 vector<char> buf(::g_buffer_size);
248
249 ifstream ifile(path, ios::binary);
250 if ( !ifile )
251 {
252 cerr << "Error opening file: '" << path << "'";
253 return false;
254 }
255
256 for (;;)
257 {
258 size_t n = ifile.read(buf.data(), ::g_buffer_size).gcount();
259 size_t shift = 0;
260 while (n > 0)
261 {
262 int st = srt_send(ss, buf.data()+shift, int(n));
263 Verb() << "Upload: " << n << " --> " << st << (!shift ? string() : "+" + Sprint(shift));
264 if (st == SRT_ERROR)
265 {
266 cerr << "Upload: SRT error: " << srt_getlasterror_str() << endl;
267 return false;
268 }
269
270 n -= st;
271 shift += st;
272 }
273
274 if (ifile.eof())
275 break;
276
277 if ( !ifile.good() )
278 {
279 cerr << "ERROR while reading file\n";
280 return false;
281 }
282 }
283
284 if ( !::g_skip_flushing )
285 {
286 // send-flush-loop
287
288 for (;;)
289 {
290 size_t bytes;
291 size_t blocks;
292 int st = srt_getsndbuffer(ss, &blocks, &bytes);
293 if (st == SRT_ERROR)
294 {
295 cerr << "Error in srt_getsndbuffer: " << srt_getlasterror_str() << endl;
296 return false;
297 }
298 if (bytes == 0)
299 {
300 Verb() << "Sending buffer DEPLETED - ok.";
301 break;
302 }
303 Verb() << "Sending buffer still: bytes=" << bytes << " blocks=" << blocks;
304 this_thread::sleep_for(chrono::milliseconds(250));
305 }
306 }
307
308 return true;
309 }
310
311 bool DoDownload(UriParser& us, string directory, string filename)
312 {
313 SrtModel m(us.host(), us.portno(), us.parameters());
314
315 string id = filename;
316 m.Establish((id));
317
318 // Disregard the filename, unless the destination file exists.
319
320 string path = directory + "/" + id;
321 struct stat state;
322 if ( stat(path.c_str(), &state) == -1 )
323 {
324 switch ( errno )
325 {
326 case ENOENT:
327 // This is expected, go on.
328 break;
329
330 default:
331 cerr << "Download: error '" << errno << "'when checking destination location: " << path << endl;
332 return false;
333 }
334 }
335 else
336 {
337 // Check if destination is a regular file, if so, allow to overwrite.
338 // Otherwise reject.
339 if (!S_ISREG(state.st_mode))
340 {
341 cerr << "Download: target location '" << path << "' does not designate a regular file.\n";
342 return false;
343 }
344 }
345
346 ofstream ofile(path, ios::out | ios::trunc | ios::binary);
347 if ( !ofile.good() )
348 {
349 cerr << "Download: can't create output file: " << path;
350 return false;
351 }
352 SRTSOCKET ss = m.Socket();
353
354 Verb() << "Downloading from '" << us.uri() << "' to '" << path;
355
356 vector<char> buf(::g_buffer_size);
357
358 for (;;)
359 {
360 int n = srt_recv(ss, buf.data(), int(::g_buffer_size));
361 if (n == SRT_ERROR)
362 {
363 cerr << "Download: SRT error: " << srt_getlasterror_str() << endl;
364 return false;
365 }
366
367 if (n == 0)
368 {
369 Verb() << "Download COMPLETE.";
370 break;
371 }
372
373 // Write to file any amount of data received
374
375 Verb() << "Download: --> " << n;
376 ofile.write(buf.data(), n);
377 }
378
379 return true;
380 }
381
382 bool Upload(UriParser& srt_target_uri, UriParser& fileuri)
383 {
384 if ( fileuri.scheme() != "file" )
385 {
386 cerr << "Upload: source accepted only as a file\n";
387 return false;
388 }
389 // fileuri is source-reading file
390 // srt_target_uri is SRT target
391
392 string path = fileuri.path();
393 string directory, filename;
394 tie(directory, filename) = ExtractPath(path);
395 Verb() << "Extract path '" << path << "': directory=" << directory << " filename=" << filename;
396 // Set ID to the filename.
397 // Directory will be preserved.
398
399 // Add some extra parameters.
400 srt_target_uri["transtype"] = "file";
401
402 return DoUpload(srt_target_uri, path, filename);
403 }
404
405 bool Download(UriParser& srt_source_uri, UriParser& fileuri)
406 {
407 if (fileuri.scheme() != "file" )
408 {
409 cerr << "Download: target accepted only as a file\n";
410 return false;
411 }
412
413 string path = fileuri.path(), directory, filename;
414 tie(directory, filename) = ExtractPath(path);
415
416 srt_source_uri["transtype"] = "file";
417
418 return DoDownload(srt_source_uri, directory, filename);
419 }
420