aboutsummaryrefslogtreecommitdiff
path: root/src/VideoPlayer.cpp
blob: 88e234096212bb74a4a97bdfcacafb5cf0dfee35 (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
#include "../include/VideoPlayer.hpp"
#include <SFML/Window/Mouse.hpp>
#include <mpv/client.h>
#include <mpv/opengl_cb.h>
#include <SFML/OpenGL.hpp>
#include <clocale>

namespace QuickMedia {
    static void* getProcAddressMpv(void *funcContext, const char *name) {
        return (void*)sf::Context::getFunction(name);
    }
    
    static void onMpvRedraw(void *rawVideo) {
        VideoPlayer *video_player = (VideoPlayer*)rawVideo;
        ++video_player->redrawCounter;
    }

    static void check_error(int status) {
        if(status < 0)
            fprintf(stderr, "mpv api error: %s\n", mpv_error_string(status));
    }

    static void mpv_set_option_bool(mpv_handle *mpv, const char *option, bool value) {
        int int_value = value;
        check_error(mpv_set_option(mpv, option, MPV_FORMAT_FLAG, &int_value));
    }

    static void mpv_set_option_int64(mpv_handle *mpv, const char *option, int64_t value) {
        check_error(mpv_set_option(mpv, option, MPV_FORMAT_INT64, &value));
    }
    
    VideoPlayer::VideoPlayer(unsigned int width, unsigned int height, sf::WindowHandle window_handle, const char *file, bool loop) : 
        redrawCounter(0),
        onPlaybackEndedCallback(nullptr),
        mpv(nullptr),
        mpvGl(nullptr),
        context(std::make_unique<sf::Context>(sf::ContextSettings(), width, height)),
        textureBuffer(nullptr),
        desired_size(width, height)
    {
        context->setActive(true);
        texture.setSmooth(true);
        
        // mpv_create requires LC_NUMERIC to be set to "C" for some reason, see mpv_create documentation
        std::setlocale(LC_NUMERIC, "C");
        mpv = mpv_create();
        if(!mpv)
            throw VideoInitializationException("Failed to create mpv handle");

        //check_error(mpv_set_option_string(mpv, "input-default-bindings", "yes"));
        //check_error(mpv_set_option_string(mpv, "input-vo-keyboard", "yes"));
        check_error(mpv_set_option_string(mpv, "cache-secs", "120"));
        check_error(mpv_set_option_string(mpv, "demuxer-max-bytes", "20M"));
        check_error(mpv_set_option_string(mpv, "demuxer-max-back-bytes", "10M"));

        //mpv_set_option_bool(mpv, "osc", true);
        //mpv_set_option_int64(mpv, "wid", window_handle);
        
        if(mpv_initialize(mpv) < 0)
            throw VideoInitializationException("Failed to initialize mpv");

        check_error(mpv_set_option_string(mpv, "vo", "opengl-cb"));
        check_error(mpv_set_option_string(mpv, "hwdec", "auto"));

        if(loop)
            check_error(mpv_set_option_string(mpv, "loop", "inf"));

        mpvGl = (mpv_opengl_cb_context*)mpv_get_sub_api(mpv, MPV_SUB_API_OPENGL_CB);
        if(!mpvGl)
            throw VideoInitializationException("Failed to initialize mpv opengl render context");
        
        mpv_opengl_cb_set_update_callback(mpvGl, onMpvRedraw, this);
        if(mpv_opengl_cb_init_gl(mpvGl, nullptr, getProcAddressMpv, nullptr) < 0)
            throw VideoInitializationException("Failed to initialize mpv gl callback func");
        
        context->setActive(false);
        
        seekbar.setFillColor(sf::Color::White);
        seekbar_background.setFillColor(sf::Color(0, 0, 0, 150));
        load_file(file);
    }
    
    VideoPlayer::~VideoPlayer() {
        if(mpvGl)
            mpv_opengl_cb_set_update_callback(mpvGl, nullptr, nullptr);
        
        free(textureBuffer);
        mpv_opengl_cb_uninit_gl(mpvGl);
        mpv_detach_destroy(mpv);
    }
    
    void VideoPlayer::setPosition(float x, float y) {
        sprite.setPosition(x, y);
    }

    // TODO: Fix this, it's incorrect
    static void wrap_sprite_to_size(sf::Sprite &sprite, sf::Vector2i texture_size, const sf::Vector2f &size) {
        auto image_size = sf::Vector2f(texture_size.x, texture_size.y);

        double overflow_x  = image_size.x - size.x;
        double overflow_y  = image_size.y - size.y;

        auto scale = sprite.getScale();
        float scale_ratio = scale.x / scale.y;
        bool reverse = overflow_x < 0.0f && overflow_y < 0.0f;

        if((reverse && overflow_x * scale_ratio < overflow_y) || overflow_x * scale_ratio > overflow_y) {
            float overflow_ratio = overflow_x / image_size.x;
            float scale_x = 1.0f - overflow_ratio;
            sprite.setScale(scale_x, scale_x * scale_ratio);
        } else {
            float overflow_ratio = overflow_y / image_size.y;
            float scale_y = 1.0f - overflow_ratio;
            sprite.setScale(scale_y * scale_ratio, scale_y);
        }
    }

    void VideoPlayer::resize(const sf::Vector2i &size) {
        desired_size = size;
        if(!textureBuffer)
            return;
        wrap_sprite_to_size(sprite, video_size, sf::Vector2f(desired_size.x, desired_size.y));
        auto image_scale = sprite.getScale();
        auto image_size = sf::Vector2f(video_size.x, video_size.y);
        image_size.x *= image_scale.x;
        image_size.y *= image_scale.y;
        sprite.setPosition(desired_size.x * 0.5f - image_size.x * 0.5f, desired_size.y * 0.5f - image_size.y * 0.5f);
    }
    
    void VideoPlayer::draw(sf::RenderWindow &window) {
        while(true) {
            mpv_event *mpvEvent = mpv_wait_event(mpv, 0.0);
            if(mpvEvent->event_id == MPV_EVENT_NONE)
                break;
            else if(mpvEvent->event_id == MPV_EVENT_SHUTDOWN)
                return;
            else if(mpvEvent->event_id == MPV_EVENT_VIDEO_RECONFIG) {
                int64_t w, h;
                if (mpv_get_property(mpv, "dwidth", MPV_FORMAT_INT64, &w) >= 0 &&
                    mpv_get_property(mpv, "dheight", MPV_FORMAT_INT64, &h) >= 0 &&
                    w > 0 && h > 0 && (w != video_size.x || h != video_size.y))
                {
                    video_size.x = w;
                    video_size.y = h;
                    // TODO: Verify if it's valid to re-create the texture like this,
                    // instead of using deconstructor
                    if(texture.create(w, h)) {
                        void *newTextureBuf = realloc(textureBuffer, w * h * 4);
                        if(newTextureBuf)
                            textureBuffer = (sf::Uint8*)newTextureBuf;
                    }
                    context.reset(new sf::Context(sf::ContextSettings(), w, h));
                    context->setActive(true);
                    glViewport(0, 0, w, h);
                    context->setActive(false);
                    resize(desired_size);
                }
            } else if(mpvEvent->event_id == MPV_EVENT_END_FILE) {
                if(onPlaybackEndedCallback)
                    onPlaybackEndedCallback();
            } else {
                //printf("Mpv event: %s\n", mpv_event_name(mpvEvent->event_id));
            }
        }
        
        if(redrawCounter > 0 && textureBuffer) {
            --redrawCounter;
            auto textureSize = texture.getSize();
            context->setActive(true);
            //mpv_render_context_render(mpvGl, params);
            mpv_opengl_cb_draw(mpvGl, 0, textureSize.x, textureSize.y);
            // TODO: Instead of copying video to cpu buffer and then to texture, copy directly from video buffer to texture buffer
            glReadPixels(0, 0, textureSize.x, textureSize.y, GL_RGBA, GL_UNSIGNED_BYTE, textureBuffer);
            texture.update(textureBuffer);
            sprite.setTexture(texture, true);
            mpv_opengl_cb_report_flip(mpvGl, 0);
            context->setActive(false);
        }
        window.draw(sprite);

        double pos = 0.0;
        mpv_get_property(mpv, "percent-pos", MPV_FORMAT_DOUBLE, &pos);
        pos *= 0.01;

        auto textureSize = sprite.getTextureRect();
        auto scale = sprite.getScale();
        auto video_size = sf::Vector2f(textureSize.width * scale.x, textureSize.height * scale.y);

        const float seekbar_height = video_size.y * 0.025f;
        seekbar.setPosition(sprite.getPosition() + sf::Vector2f(0.0f, video_size.y - seekbar_height));
        seekbar.setSize(sf::Vector2f(video_size.x * pos, seekbar_height));
        window.draw(seekbar);
        seekbar_background.setPosition(seekbar.getPosition() + sf::Vector2f(video_size.x * pos, 0.0f));
        seekbar_background.setSize(sf::Vector2f(video_size.x - video_size.x * pos, seekbar_height));
        window.draw(seekbar_background);

        if(sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
            auto mouse_pos = sf::Mouse::getPosition(window);
            auto seekbar_pos = seekbar.getPosition();
            float diff_x = mouse_pos.x - seekbar_pos.x;
            if(diff_x >= 0.0f && diff_x <= video_size.x && mouse_pos.y >= seekbar_pos.y && mouse_pos.y <= seekbar_pos.y + seekbar_height) {
                double new_pos = ((double)diff_x / video_size.x) * 100.0;
                mpv_set_property(mpv, "percent-pos", MPV_FORMAT_DOUBLE, &new_pos);
            }
        }
    }

    void VideoPlayer::load_file(const std::string &path) {
        const char *cmd[] = { "loadfile", path.c_str(), nullptr };
        mpv_command(mpv, cmd);
    }
}