VLCThumbnailer.cpp 7.47 KB
Newer Older
1
2
3
#include "VLCThumbnailer.h"

#include <cstring>
4
#include <jpeglib.h>
5
#include <setjmp.h>
6
7

#include "IFile.h"
8
#include "logging/Logger.h"
9
10
11

VLCThumbnailer::VLCThumbnailer(const VLC::Instance &vlc)
    : m_instance( vlc )
12
13
    , m_snapshotRequired( false )
    , m_height( 0 )
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
{
}

bool VLCThumbnailer::initialize(IMetadataServiceCb *callback, IMediaLibrary *ml)
{
    m_cb = callback;
    m_ml = ml;
    return true;
}

unsigned int VLCThumbnailer::priority() const
{
    // This needs to be lower than the VLCMetadataService, since we want to know the file type.
    return 50;
}

bool VLCThumbnailer::run( FilePtr file, void *data )
{
    if ( file->type() == IFile::Type::UnknownType )
    {
        // If we don't know the file type yet, it actually looks more like a bug
        // since this should run after file type deduction, and not run in case
        // that step fails.
        m_cb->done( file, StatusError, data );
        return false;
    }
    else if ( file->type() != IFile::Type::VideoType )
    {
        // There's no point in generating a thumbnail for a non-video file.
        m_cb->done( file, StatusSuccess, data );
        return true;
    }

    VLC::Media media( m_instance, file->mrl(), VLC::Media::FromPath );
    media.addOption( ":no-audio" );
    VLC::MediaPlayer mp( media );

    setupVout( mp );

    if ( startPlayback( file, mp, data ) == false )
        return false;

    // Seek ahead to have a significant preview
    if ( seekAhead( file, mp, data ) == false )
        return false;

60
    if ( takeSnapshot( file, mp, data ) == false )
61
62
63
64
65
66
67
68
69
70
        return false;
    return true;
}

bool VLCThumbnailer::startPlayback( FilePtr file, VLC::MediaPlayer &mp, void* data )
{
    bool failed = true;

    std::unique_lock<std::mutex> lock( m_mutex );

71
    mp.eventManager().onPlaying([this, &failed]() {
72
73
74
75
76
77
78
79
80
        std::unique_lock<std::mutex> lock( m_mutex );
        failed = false;
        m_cond.notify_all();
    });
    mp.eventManager().onEncounteredError([this]() {
        std::unique_lock<std::mutex> lock( m_mutex );
        m_cond.notify_all();
    });
    mp.play();
81
82
    bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [&mp]() {
        return mp.state() == libvlc_Playing || mp.state() == libvlc_Error;
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
    });
    if ( success == false || failed == true )
    {
        // In case of timeout or error, don't go any further
        m_cb->done( file, StatusError, data );
        return false;
    }
    return true;
}

bool VLCThumbnailer::seekAhead( FilePtr file, VLC::MediaPlayer& mp, void* data )
{
    std::unique_lock<std::mutex> lock( m_mutex );
    float pos = .0f;
    auto event = mp.eventManager().onPositionChanged([this, &pos](float p) {
        std::unique_lock<std::mutex> lock( m_mutex );
        pos = p;
        m_cond.notify_all();
    });
102
    mp.setPosition( .4f );
103
104
105
106
107
108
109
110
111
112
113
114
115
    bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [&pos]() {
        return pos >= .1f;
    });
    // Since we're locking a mutex for each position changed, let's unregister ASAP
    event->unregister();
    if ( success == false )
    {
        m_cb->done( file, StatusError, data );
        return false;
    }
    return true;
}

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
void VLCThumbnailer::setupVout( VLC::MediaPlayer& mp )
{
    mp.setVideoFormatCallbacks(
        // Setup
        [this, &mp](char* chroma, unsigned int* width, unsigned int *height, unsigned int *pitches, unsigned int *lines) {
            strcpy( chroma, "RV32" );

            const float inputAR = (float)*width / *height;

            *width = Width;
            auto prevHeight = m_height;
            m_height = (float)Width / inputAR + 1;
            // If our buffer isn't enough anymore, reallocate a new one.
            if ( m_height > prevHeight )
                m_buff.reset( new uint8_t[Width * m_height * Bpp] );
            *height = m_height;
            *pitches = Width * Bpp;
            *lines = m_height;
            return 1;
        },
        // Cleanup
        nullptr);
    mp.setVideoCallbacks(
        // Lock
        [this](void** pp_buff) {
            *pp_buff = m_buff.get();
            return nullptr;
        },
        //unlock
        [this](void*, void*const*) {
            std::unique_lock<std::mutex> lock(m_mutex);
            if ( m_snapshotRequired == true )
            {
                m_snapshotRequired = false;
                m_cond.notify_all();
            }
        }
        ,
        //display
        nullptr
    );
}

bool VLCThumbnailer::takeSnapshot(FilePtr file, VLC::MediaPlayer &mp, void *data)
160
{
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
    std::unique_ptr<uint8_t[]> buff;
    // lock, signal that we want a snapshot, and wait.
    {
        std::unique_lock<std::mutex> lock( m_mutex );
        m_snapshotRequired = true;
        bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [this]() {
            // Keep waiting if the vmem thread hasn't restored m_snapshotRequired to false
            return m_snapshotRequired == true;
        });
        if ( success == false )
        {
            m_cb->done( file, StatusError, data );
            return false;
        }
        // Prevent the vmem from screwing our snapshot over.
        buff = std::move( m_buff );
        // set a new buffer for next snapshot, and to avoid crashing while we stop the media player
        m_buff.reset( new uint8_t[Width * m_height * Bpp] );
    }
    mp.stop();
    return compress( buff.get(), file, data );
}

184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#ifdef WITH_JPEG

struct jpegError : public jpeg_error_mgr
{
    jmp_buf buff;
    char message[JMSG_LENGTH_MAX];

    static void jpegErrorHandler(j_common_ptr common)
    {
        auto error = reinterpret_cast<jpegError*>(common->err);
        (*error->format_message)( common, error->message );
        longjmp(error->buff, 1);
    }
};

#endif

201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
bool VLCThumbnailer::compress(uint8_t* buff, FilePtr file, void *data)
{
    auto path = m_ml->snapshotPath();
    path += "/";
    path += std::to_string( file->id() ) + ".jpg";

    //FIXME: Abstract this away, though libjpeg requires a FILE*...
    auto fOut = fopen(path.c_str(), "wb");
    // ensure we always close the file.
    auto fOutPtr = std::unique_ptr<FILE, int(*)(FILE*)>( fOut, &fclose );
    if ( fOut == nullptr )
    {
        LOG_ERROR("Failed to open snapshot file ", path);
        m_cb->done( file, StatusError, data );
        return false;
    }
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236

#ifdef WITH_JPEG
    jpeg_compress_struct compInfo;
    JSAMPROW row_pointer[1];

    jpeg_create_compress(&compInfo);
    //libjpeg's default error handling is to call exit(), which would
    //be slightly problematic...
    jpegError err;
    compInfo.err = jpeg_std_error(&err);
    err.error_exit = jpegError::jpegErrorHandler;

    if ( setjmp( err.buff ) )
    {
        LOG_ERROR("JPEG failure: ", err.message);
        jpeg_destroy_compress(&compInfo);
        m_cb->done( file, StatusError, data );
        return false;
    }

237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
    jpeg_stdio_dest(&compInfo, fOut);

    compInfo.image_width = Width;
    compInfo.image_height = m_height;
    compInfo.input_components = Bpp;
    compInfo.in_color_space = JCS_EXT_BGRX;
    jpeg_set_defaults( &compInfo );
    jpeg_set_quality( &compInfo, 85, TRUE );

    jpeg_start_compress( &compInfo, TRUE );

    auto stride = compInfo.image_width * Bpp;

    while (compInfo.next_scanline < compInfo.image_height) {
      row_pointer[0] = &buff[compInfo.next_scanline * stride];
      jpeg_write_scanlines(&compInfo, row_pointer, 1);
    }
    jpeg_finish_compress(&compInfo);
    jpeg_destroy_compress(&compInfo);
256
257
258
#else
#error FIXME
#endif
259
260
261
262

    m_cb->done( file, StatusSuccess, data );
    file->setSnapshot( path );
    return true;
263
}