aboutsummaryrefslogtreecommitdiff
path: root/video_player/src/main.cpp
blob: 74898737c610e49a5d5c53bbfd879376e53d4ad8 (plain)
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
#include "../include/Args.hpp"
#include "../include/Utils.hpp"
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#include <unistd.h>

#include <thread>
#include <mutex>
#include <optional>
#include <set>

#include <mpv/client.h>
#include <json/json.h>

#define COMMAND_BUFFER_MAX_SIZE 2048

static size_t ipc_handler(mpv_handle *mpv_ctx, int fd, char *buffer, size_t buffer_size, bool &disconnected) {
    ssize_t bytes_read = read_eintr(fd, buffer, buffer_size);
    if(bytes_read < 0) {
        fprintf(stderr, "Error: ipc read failed, error: %s\n", strerror(errno));
        //exit(3);
        disconnected = false;
        return 0;
    }

    mpv_wakeup(mpv_ctx);
    disconnected = (bytes_read == 0);
    return bytes_read;
}

static Json::Value handle_json_command_time_pos(mpv_handle *mpv_ctx) {
    double time_pos = 0.0;
    const int res = mpv_get_property(mpv_ctx, "time-pos", MPV_FORMAT_DOUBLE, &time_pos);

    Json::Value response_json(Json::objectValue);
    if(res < 0) {
        response_json["status"] = "error";
        response_json["message"] = mpv_error_string(res);
    } else {
        response_json["status"] = "success";
        response_json["data"] = time_pos;
    }
    return response_json;
}

static Json::Value handle_json_command_sub_add(mpv_handle *mpv_ctx, const Json::Value &json_root) {
    Json::Value response_json(Json::objectValue);

    const Json::Value &data_json = json_root["data"];
    if(!data_json.isObject()) {
        response_json["status"] = "error";
        response_json["message"] = "expected \"data\" to be an object";
        return response_json;
    }

    const Json::Value &file_json = data_json["file"];
    const Json::Value &title_json = data_json["title"];
    const Json::Value &language_json = data_json["language"];

    if(!file_json.isString()) {
        response_json["status"] = "error";
        response_json["message"] = "expected \"data.file\" to be a string";
        return response_json;
    }

    if(!title_json.isString() && !title_json.isNull()) {
        response_json["status"] = "error";
        response_json["message"] = "expected optional field \"data.title\" to be a string or omitted";
        return response_json;
    }

    if(!language_json.isString() && !language_json.isNull()) {
        response_json["status"] = "error";
        response_json["message"] = "expected optional field \"data.language\" to be a string or omitted";
        return response_json;
    }

    std::vector<const char*> args;
    args.push_back("sub-add");
    args.push_back(file_json.asCString());
    args.push_back("auto");
    if(title_json.isString())
        args.push_back(title_json.asCString());
    if(language_json.isString()) {
        if(!title_json.isString())
            args.push_back(language_json.asCString());
        args.push_back(language_json.asCString());
    }
    args.push_back(nullptr);
    
    const int res = mpv_command_async(mpv_ctx, 0, args.data());
    if(res < 0) {
        response_json["status"] = "error";
        response_json["message"] = mpv_error_string(res);
    } else {
        response_json["status"] = "success";
    }
    return response_json;
}

static void send_error(const std::string &err_msg, std::optional<int64_t> request_id, int fd) {
    fprintf(stderr, "Error: %s\n", err_msg.c_str());

    Json::Value json_root(Json::objectValue);
    json_root["status"] = "error";
    json_root["message"] = err_msg;
    if(request_id)
        json_root["request_id"] = *request_id;

    Json::StreamWriterBuilder builder;
    builder["commentStyle"] = "None";
    builder["indentation"] = "";
    const std::string response_str = Json::writeString(builder, json_root) + "\n";

    ssize_t bytes_written = write_all(fd, response_str.data(), response_str.size());
    if(bytes_written < 0) {
        fprintf(stderr, "Error: ipc write failed, error: %s\n", strerror(errno));
        //exit(3);
        return;
    }
}

static void handle_json_command(mpv_handle *mpv_ctx, const Json::Value &json_root, int fd) {
    if(!json_root.isObject()) {
        send_error("expected command json root to be an object", std::nullopt, fd);
        return;
    }

    const Json::Value &command_json = json_root["command"];
    if(!command_json.isString()) {
        send_error("command json is missing field \"command\" or it's not a string", std::nullopt, fd);
        return;
    }

    std::optional<int64_t> request_id = std::nullopt;
    const Json::Value &request_id_json = json_root["request_id"];
    if(!request_id_json.isNull()) {
        if(request_id_json.isInt64()) {
            request_id = request_id_json.asInt64();
        } else {
            send_error("request_id was provided but its not an integer", std::nullopt, fd);
            return;
        }
    }

    Json::Value response_json;
    if(strcmp(command_json.asCString(), "time-pos") == 0) {
        response_json = handle_json_command_time_pos(mpv_ctx);
    } else if(strcmp(command_json.asCString(), "sub-add") == 0) {
        response_json = handle_json_command_sub_add(mpv_ctx, json_root);
    } else {
        response_json = Json::Value(Json::objectValue);
        response_json["status"] = "error";
        response_json["message"] = "invalid command " + command_json.asString() + ", expected time-pos or sub-add";
    }

    if(request_id)
        response_json["request_id"] = *request_id;

    Json::StreamWriterBuilder builder;
    builder["commentStyle"] = "None";
    builder["indentation"] = "";
    const std::string response_str = Json::writeString(builder, response_json) + "\n";

    ssize_t bytes_written = write_all(fd, response_str.data(), response_str.size());
    if(bytes_written < 0) {
        fprintf(stderr, "Error: ipc write failed, error: %s\n", strerror(errno));
        //exit(3);
        return;
    }
}

static void handle_request_commands_line_by_line(mpv_handle *mpv_ctx, int fd, char *command_buffer, size_t &command_buffer_size, Json::Value &json_root, std::string &json_errors) {
    size_t command_offset = 0;
    while(command_offset < command_buffer_size) {
        const void *space_p = memchr(command_buffer + command_offset, '\n', command_buffer_size - command_offset);
        if(!space_p)
            space_p = command_buffer + command_buffer_size;

        Json::CharReaderBuilder json_builder;
        std::unique_ptr<Json::CharReader> json_reader(json_builder.newCharReader());
        json_errors.clear();
        if(json_reader->parse(command_buffer + command_offset, (const char*)space_p, &json_root, &json_errors)) {
            handle_json_command(mpv_ctx, json_root, fd);
        } else {
            send_error("failed to parse command as json, error: " + json_errors, std::nullopt, fd);
        }
        command_offset = ((const char*)space_p + 1) - command_buffer;
    }
    command_buffer_size = 0;
}

static void send_event(const char *event_name, int fd) {
    Json::Value json_root(Json::objectValue);
    json_root["event"] = event_name;

    Json::StreamWriterBuilder builder;
    builder["commentStyle"] = "None";
    builder["indentation"] = "";
    const std::string response_str = Json::writeString(builder, json_root) + "\n";

    ssize_t bytes_written = write_all(fd, response_str.data(), response_str.size());
    if(bytes_written < 0) {
        fprintf(stderr, "Error: ipc write failed, error: %s\n", strerror(errno));
        //exit(3);
        return;
    }
}

static inline void check_error(int status, const char *prefix) {
    if (status < 0) {
        fprintf(stderr, "Error: %s mpv error: %s\n", prefix, mpv_error_string(status));
        exit(2);
    }
}

static bool is_num(char c) {
    return c >= '0' && c <= '9';
}

static bool string_looks_like_int(const char *str, size_t size) {
    for(size_t i = 0; i < size; ++i) {
        char c = str[i];
        if(!is_num(c) && c != '-')
            return false;
    }
    return true;
}

static bool string_looks_like_double(const char *str, size_t size) {
    for(size_t i = 0; i < size; ++i) {
        char c = str[i];
        if(!is_num(c) && c != '-' && c != '.')
            return false;
    }
    return true;
}

static void mpv_set_before_init_options(mpv_handle *mpv_ctx, const Args &args) {
    long value_long = 0;
    double value_double = 0;

    std::set<std::string> known_string_properties = { "start", "force-media-title" };

    for(const MpvProperty &property : args.mpv_properties) {
        const bool is_string_property = known_string_properties.find(property.key) != known_string_properties.end();

        if(!is_string_property && string_looks_like_int(property.value.c_str(), property.value.size()) && string_to_long(property.value.c_str(), value_long))
            check_error(mpv_set_option(mpv_ctx, property.key.c_str(), MPV_FORMAT_INT64, &value_long), property.key.c_str());
        else if(!is_string_property && string_looks_like_double(property.value.c_str(), property.value.size()) && string_to_double(property.value.c_str(), value_double))
            check_error(mpv_set_option(mpv_ctx, property.key.c_str(), MPV_FORMAT_DOUBLE, &value_double), property.key.c_str());
        else
            check_error(mpv_set_option_string(mpv_ctx, property.key.c_str(), property.value.c_str()), property.key.c_str());
    }
}

static void mpv_set_after_load_options(mpv_handle *mpv_ctx, const Args &args) {
    if(args.audio_file) {
        const char* cmd_args[] = { "audio-add", args.audio_file, "select", "Default track", nullptr };
        check_error(mpv_command_async(mpv_ctx, 0, cmd_args), "audio-add");
    }
}

int main(int argc, char **argv) {
    // This is needed for mpv_create or it will fail
    setlocale(LC_ALL, "C");

    Args args = parse_args(argc, argv);

    mpv_handle *mpv_ctx = mpv_create();
    if (!mpv_ctx) {
        fprintf(stderr, "Error: failed to create mpv context\n");
        return 1;
    }

    mpv_set_before_init_options(mpv_ctx, args);
    check_error(mpv_initialize(mpv_ctx), "mpv_initialize");

    const char *cmd[] = { "loadfile", args.file_to_play, NULL };
    check_error(mpv_command(mpv_ctx, cmd), "loadfile");

    check_error(mpv_observe_property(mpv_ctx, 0, "idle-active", MPV_FORMAT_FLAG), "observe idle-active");

    char command_buffer[COMMAND_BUFFER_MAX_SIZE];
    size_t command_buffer_size = 0;
    std::mutex command_mutex;
    bool ipc_disconnected = false;

    bool running = true;
    // TODO: Clean cleanup instead of terminating... To make that possible we need to find a way to wake up the read call that is waiting for data
    if(args.ipc_fd) {
        std::thread([&]() mutable {
            while(running) {
                command_buffer_size = ipc_handler(mpv_ctx, args.ipc_fd_num, command_buffer, COMMAND_BUFFER_MAX_SIZE, ipc_disconnected);
                std::lock_guard<std::mutex> lock(command_mutex); // Wait until the command has been handled in the main loop in the main thread
            }
        }).detach();
    }

    Json::Value json_root;
    std::string json_errors;

    bool file_started = false;

    while (running) {
        mpv_event *event = mpv_wait_event(mpv_ctx, -1.0);

        if(args.ipc_fd && event->event_id != MPV_EVENT_NONE)
            send_event(mpv_event_name(event->event_id), args.ipc_fd_num);

        if(event->event_id == MPV_EVENT_START_FILE && !file_started) {
            file_started = true;
            mpv_set_after_load_options(mpv_ctx, args);
        } else if(event->event_id == MPV_EVENT_SHUTDOWN) {
            running = false;
            break;
        } else if(event->event_id == MPV_EVENT_PROPERTY_CHANGE && file_started) {
            // End of file (idle)
            mpv_event_property *property = (mpv_event_property*)event->data;
            if(strcmp(property->name, "idle-active") == 0 && *(int*)property->data == 1) {
                running = false;
                break;
            }
        }

        if(args.ipc_fd) {
            std::lock_guard<std::mutex> lock(command_mutex);
            // Other end of the ipc socket has disconnected
            if(ipc_disconnected) {
                fprintf(stderr, "Warning: the other end of the ipc fd was closed, closing the video player...\n");
                running = false;
                break;
            }
            handle_request_commands_line_by_line(mpv_ctx, args.ipc_fd_num, command_buffer, command_buffer_size, json_root, json_errors);
        }
    }

    mpv_terminate_destroy(mpv_ctx);
    return 0;
}