]> git.sesse.net Git - cubemap/blob - input.cpp
d7c2b774d79fd66cbcb8a41d923c12af33c49029
[cubemap] / input.cpp
1 #include <stddef.h>
2 #include <string.h>
3 #include <string>
4
5 #include "httpinput.h"
6 #include "input.h"
7 #include "state.pb.h"
8 #include "udpinput.h"
9
10 using namespace std;
11
12 // Extremely rudimentary URL parsing.
13 bool parse_url(const string &url, string *protocol, string *host, string *port, string *path)
14 {
15         size_t split = url.find("://");
16         if (split == string::npos) {
17                 return false;
18         }
19         *protocol = string(url.begin(), url.begin() + split);
20
21         string rest = string(url.begin() + split + 3, url.end());
22         split = rest.find_first_of(":/");
23         if (split == string::npos) {
24                 // http://foo
25                 *host = rest;
26                 *port = *protocol;
27                 *path = "/";
28                 return true;
29         }
30
31         *host = string(rest.begin(), rest.begin() + split);
32         char ch = rest[split];  // Colon or slash.
33         rest = string(rest.begin() + split + 1, rest.end());
34
35         if (ch == ':') {
36                 // Parse the port.
37                 split = rest.find_first_of('/');
38                 if (split == string::npos) {
39                         // http://foo:1234
40                         *port = rest;
41                         *path = "/";
42                         return true;
43                 } else {
44                         // http://foo:1234/bar
45                         *port = string(rest.begin(), rest.begin() + split);
46                         *path = string(rest.begin() + split, rest.end());
47                         return true;
48                 }
49         }
50
51         // http://foo/bar
52         *port = *protocol;
53         *path = rest;
54         return true;
55 }
56
57 Input *create_input(const std::string &stream_id, const std::string &url)
58 {
59         string protocol, host, port, path;
60         if (!parse_url(url, &protocol, &host, &port, &path)) {
61                 return NULL;
62         }
63         if (protocol == "http") {
64                 return new HTTPInput(stream_id, url);
65         }
66         if (protocol == "udp") {
67                 return new UDPInput(stream_id, url);
68         }
69         return NULL;
70 }
71
72 Input *create_input(const InputProto &serialized)
73 {
74         string protocol, host, port, path;
75         if (!parse_url(serialized.url(), &protocol, &host, &port, &path)) {
76                 return NULL;
77         }
78         if (protocol == "http") {
79                 return new HTTPInput(serialized);
80         }
81         if (protocol == "udp") {
82                 return new UDPInput(serialized);
83         }
84         return NULL;
85 }
86
87 Input::~Input() {}
88