-
Notifications
You must be signed in to change notification settings - Fork 0
/
loop.h
427 lines (387 loc) · 13.2 KB
/
loop.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
#pragma once
#include <iostream>
#include "globals.h"
#include "chromecast.h"
#include "castchannel.h"
static double currentPosition()
{
if (!currentlyPlaying) {
return s_currentPosition;
}
if (s_currentPosition < 0) {
return -1;
}
double timeDelta = time(nullptr) - s_lastPositionFetched;
return std::round(timeDelta + s_currentPosition);
}
static double secondsUntilNextSegment()
{
const double current = currentPosition();
if (current < 0) {
puts("no current position");
return -1;
}
if (currentSegments.empty()) {
return -1;
}
double lowestBegin = std::numeric_limits<double>::max();
bool found = false;
for (const Segment &segment : currentSegments) {
if (segment.end < current) {
continue;
}
if (!found || segment.begin < lowestBegin) {
lowestBegin = segment.begin;
found = true;
}
}
if (!found) {
return -1;
}
return lowestBegin - current;
}
static double currentSegmentEnd()
{
const int current = std::ceil(currentPosition());
if (current < 0) {
return -1;
}
if (currentSegments.empty()) {
return -1;
}
for (const Segment &segment : currentSegments) {
if (int(segment.end) <= current) {
continue;
}
if (segment.begin < current) {
return segment.end;
}
}
return -1;
}
static void maybeSeek(Connection *connection)
{
if (currentVideo.empty()) {
return;
}
if (currentSegments.empty()) {
return;
}
const double segmentEnd = currentSegmentEnd();
if (segmentEnd < 0) {
return;
}
if (s_verbose) {
printf("Current segment ends at: %f, position at %f\n", segmentEnd, currentPosition());
}
if (!currentlyPlaying) {
return;
}
if (time(nullptr) - s_lastSeek < 1) {
return;
}
s_lastSeek = time(nullptr);
puts("Skipping sponsor...");
s_currentPosition = -1.;
nextSegmentStart = -1.;
s_lastPositionFetched = -1;
cc::seek(*connection, segmentEnd);
}
static void printTimestamp(int timestamp)
{
const int seconds = timestamp % 60;
timestamp /= 60;
const int minutes = timestamp % 60;
timestamp /= 60;
const int hours = timestamp % 60;
printf("%.2d:%.2d:%.2d", hours, minutes, seconds);
}
static void printProgress(double position, double length)
{
if (position < 0 || length < 0 || s_lastPositionFetched < 0) {
printf("%s", s_currentStatus.c_str());
fflush(stdout);
printf("\033[2K\r");
return;
}
printf("\r[");
int playedLength = position * PROGRESS_WIDTH / length;
if (playedLength > PROGRESS_WIDTH) {
playedLength = PROGRESS_WIDTH;
}
for (int i=0; i<playedLength; i++) {
printf("=");
}
if (currentlyPlaying) {
printf(">");
} else {
printf("|");
}
for (int i=playedLength; i<PROGRESS_WIDTH; i++) {
printf("-");
}
printf("] ");
printTimestamp(position);
printf("/");
printTimestamp(length);
for (const Segment &segment : currentSegments) {
int start = PROGRESS_WIDTH * segment.begin / length;
if (start >= PROGRESS_WIDTH) {
start = PROGRESS_WIDTH - 1;
}
// Seek to the start of the bar
printf("\r\033[C");
for (int i=0; i<start; i++) {
printf("\033[C");
}
const int segmentLength = std::max<int>(PROGRESS_WIDTH * (segment.end - segment.begin) / length, 1);
for (int i=0; i<segmentLength; i++) {
printf("#");
}
}
fflush(stdout);
printf("\033[2K\r");
}
static bool handleMessage(Connection *connection, const std::string &inputBuffer)
{
CastMessage message;
if (!message.parse(inputBuffer.data(), inputBuffer.size())) {
puts("Parsing message from chromecast failed");
return false;
}
const std::string payload = message._payload_utf8;
if (payload.empty()) {
puts("No string payload");
return true;
}
std::string type = regexExtract(R"--("type"\s*:\s*"([^"]+)")--", payload);
if (type != "PING" && s_verbose) {
std::cout << message._source_id << " > " << message._destination_id << " (" << message._namespace << "): \n" << payload << std::endl;
}
if (type == "CLOSE") {
s_currentStatus = "Disconnected";
cc::sendSimple(*connection, cc::msg::Connect, cc::ns::Connection);
return true;
}
if (type == "INVALID_REQUEST") {
s_currentStatus = "Error";
std::cout << message._source_id << " > " << message._destination_id << " (" << message._namespace << "): \n" << payload << std::endl;
return false;
}
if (type == "MEDIA_STATUS") {
extractNumber(R"--("duration"\s*:\s*([0-9.]+))--", payload, ¤tDuration);
if (extractNumber(R"--("currentTime"\s*:\s*([0-9.]+))--", payload, &s_currentPosition)) {
s_lastPositionFetched = time(nullptr);
}
const std::string state = regexExtract(R"--("playerState"\s*:\s*"([A-Z]+)")--", payload);
if (!state.empty()) {
currentlyPlaying = state == "PLAYING";
s_currentStatus = state;
}
const std::string mediaSession = regexExtract(R"--("mediaSessionId"\s*:\s*([0-9]+))--", payload);
if (!mediaSession.empty()) {
if (s_verbose) {
std::cout << "Got media session " << mediaSession << std::endl;
}
cc::mediaSession = mediaSession;
}
if (!s_youtube) {
return true;
}
// the ID is base64, but replaced / with - and + with _, and without padding
const std::string videoID = regexExtract(R"--("contentId"\s*:\s*"([A-Za-z0-9_-]+)")--", payload);
if (s_verbose) {
std::cout << "Video id: '" << videoID << "'" << std::endl;
}
if (!videoID.empty() && videoID != currentVideo) {
currentSegments = downloadSegments(videoID);
currentVideo = videoID;
nextSegmentStart = -1;
}
if (!currentSegments.empty()) {
double delta = secondsUntilNextSegment();
if (s_verbose) {
std::cout << "time to next segment: " << delta << std::endl;
}
if (delta >= 0) {
nextSegmentStart = time(nullptr) + delta;
}
maybeSeek(connection);
}
// If we detect that an ad is being played, try to re-open the video
// one second into the future.
const std::string customState = regexExtract(R"--("playerState"\s*:\s*(-?[0-9]+))--", payload);
if (s_verbose) {
std::cout << "Custom player state: " << customState << std::endl;
}
if (s_adblock && customState == "1081") {
std::cout << " Playing an ad, attempting to skip" << std::endl;
double position = currentPosition();
if (position < 0) {
position = 0;
}
position += 1; // attempt one second forward
cc::sendSimpleMedia(*connection, "STOP");
cc::loadMedia(*connection, currentVideo, position);
}
return true;
}
if (message._namespace == cc::ns::strings[cc::ns::Heartbeat]) {
if (type == "PING") {
cc::sendSimple(*connection, cc::msg::Pong, cc::ns::Heartbeat);
}
return true;
}
if (message._namespace == cc::ns::strings[cc::ns::Receiver]) {
if (type == "RECEIVER_STATUS") {
const std::string displayName = regexExtract(R"--("displayName"\s*:\s*"([^"]+)")--", payload);
const std::string sessionId = regexExtract(R"--("sessionId"\s*:\s*"([^"]+)")--", payload);
if (s_verbose) {
std::cout << "app display name: " << displayName << std::endl;
std::cout << "session: " << sessionId << std::endl;
}
if (!sessionId.empty()) {
cc::dest = sessionId;
}
if (displayName == "YouTube") {
s_youtube = true;
if (s_verbose) {
puts("Youtube playing");
}
} else if (!displayName.empty()) {
s_youtube = false;
s_currentStatus = "Not youtube: '" + displayName + "'";
}
if (payload.find("urn:x-cast:com.google.cast.media") != std::string::npos) {
if (s_verbose) puts("Sending get status for media");
// First reconnect with session id
cc::sendSimple(*connection, cc::msg::Connect, cc::ns::Connection);
// Then get proper media status
cc::sendSimple(*connection, cc::msg::GetStatus, cc::ns::Media);
}
}
return true;
}
if (type != "mdxSessionStatus") {
std::cerr << "Unhandled message type: " << type << std::endl;
}
return true;
}
// TODO: automatically reconnect
int loop(const sockaddr_in &address)
{
cc::dest = "";
if (s_verbose) {
puts("Opening connection");
}
Connection connection;
if (!connection.connect(address)) {
std::cerr << "Failed to connect to " << inet_ntoa(address.sin_addr) << std::endl;
return errno;
}
if (s_verbose) {
puts("Sending connection message");
}
if (!cc::sendSimple(connection, cc::msg::Connect, cc::ns::Connection)) {
puts("Failed to send connect message");
return errno;
}
puts("Connected");
if (!cc::sendSimple(connection, cc::msg::GetStatus, cc::ns::Receiver)) {
puts("Failed to send getstatus message");
return errno;
}
s_lastPing = time(nullptr);
while (s_running && !connection.eof) {
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(connection.fd, &fdset);
FD_SET(STDIN_FILENO, &fdset);
timeval timeout;
timeout.tv_sec = 1; // max 1 second so we can update the progress bar
timeout.tv_usec = 0;
const int events = select(connection.fd + 1, &fdset, 0, 0, &timeout);
printProgress(currentPosition(), currentDuration);
if (events < 0) {
perror("select()");
return errno;
}
if (errno == EINTR) {
continue;
}
if (FD_ISSET(STDIN_FILENO, &fdset)) {
const int key = getchar();
switch(key) {
case 'q':
case '\x1b':
s_running = false;
return 0;
case ' ':
if (s_currentStatus == "PLAYING") {
puts("Pausing");
cc::sendSimpleMedia(connection, "PAUSE");
} else if (s_currentStatus == "PAUSED") {
puts("Resuming playback");
cc::sendSimpleMedia(connection, "PLAY");
}
break;
default:
if (s_verbose) printf("Unhandled key 0x%x\n", key);
break;
}
}
if (events == 0) { // timeout
if (nextSegmentStart > 0 && nextSegmentStart <= time(nullptr)) {
nextSegmentStart = -1;
// Update to make sure we are in sync before we skip the sponsor
cc::sendSimple(connection, cc::msg::GetStatus, cc::ns::Media);
}
const time_t currentTime = time(nullptr);
if (currentTime - s_lastPing > PING_INTERVAL) {
if (s_verbose) {
std::cout << "Sending ping, last ping: " << s_lastPing << " current time: " << currentTime << " delta: " << (currentTime - s_lastPing) << std::endl;
}
if (!cc::sendSimple(connection, cc::msg::Ping, cc::ns::Heartbeat)) {
puts("Failed to send ping, assuming disconnected");
return ETIMEDOUT;
}
s_lastPing = time(nullptr);
}
}
if (!FD_ISSET(connection.fd, &fdset)) {
continue;
}
std::string msgLengthBuffer = connection.read(sizeof(uint32_t));
if (msgLengthBuffer.size() != 4) {
std::cerr << "Failed to read message size: '" << msgLengthBuffer << "'" << std::endl;
return EBADMSG;
}
if (connection.eof) {
puts("Connection closed");
return ECONNRESET;
}
uint32_t msgLength = 0;
memcpy(&msgLength, msgLengthBuffer.data(), sizeof msgLength);
msgLength = ntohl(msgLength);
if (msgLength > 64 * 1024) { // 64kb max according to the spec
printf("Message length out of range: %d\n", msgLength);
return EBADMSG;
}
std::string response = connection.read(msgLength);
if (response.size() < msgLength) {
std::cerr << "Short read, expected " << msgLength << " got " << response.size() << std::endl;
return EBADMSG;
}
if (!handleMessage(&connection, response)) {
puts("Failed to parse message");
return ECONNRESET;
}
if (connection.eof) {
puts("Disconnected");
return ECONNRESET;
}
// We got a valid message
s_lastPing = time(nullptr);
}
return 0;
}