summaryrefslogtreecommitdiff
path: root/src/kitplayer.c
blob: f852e48e078f6b13eecf439154ebafb1e7d7d132 (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
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
#include <assert.h>

#include <SDL.h>

#include "kitchensink/kitplayer.h"
#include "kitchensink/kiterror.h"
#include "kitchensink/internal/kitlibstate.h"
#include "kitchensink/internal/video/kitvideo.h"
#include "kitchensink/internal/audio/kitaudio.h"
#include "kitchensink/internal/subtitle/kitsubtitle.h"
#include "kitchensink/internal/utils/kithelpers.h"
#include "kitchensink/internal/utils/kitlog.h"

enum DecoderIndex {
    KIT_VIDEO_DEC = 0,
    KIT_AUDIO_DEC,
    KIT_SUBTITLE_DEC,
    KIT_DEC_COUNT
};

// Return 0 if stream is good but nothing else to do for now
// Return -1 if there may still work to be done
// Return 1 if there was an error or stream end
static int _DemuxStream(const Kit_Player *player) {
    assert(player != NULL);
    AVFormatContext *format_ctx = player->src->format_ctx;

    // If any buffer is full, just stop here for now.
    // Since we don't know what kind of data is going to come out of av_read_frame, we really
    // want to make sure we are prepared for everything :)
    for(int i = 0; i < KIT_DEC_COUNT; i++) {
        Kit_Decoder *dec = player->decoders[i];
        if(dec == NULL)
            continue;
        if(!Kit_CanWriteDecoderInput(dec))
            return 0;
    }

    // Attempt to read frame. Just return here if it fails.
    AVPacket *packet = av_packet_alloc();
    if(av_read_frame(format_ctx, packet) < 0) {
        av_packet_free(&packet);
        return 1;
    }

    // Check if this is a packet we need to handle and pass it on
    for(int i = 0; i < KIT_DEC_COUNT; i++) {
        Kit_Decoder *dec = player->decoders[i];
        if(dec == NULL)
            continue;
        if(dec->stream_index == packet->stream_index) {
            Kit_WriteDecoderInput(player->decoders[i], packet);
            return -1;
        }
    }

    // We only get here if packet was not written to a decoder. IF that is the case,
    // disregard and free the packet.
    av_packet_free(&packet);
    return -1;
}

static bool _IsOutputEmpty(const Kit_Player *player) {
    for(int i = 0; i < KIT_DEC_COUNT; i++) {
        Kit_Decoder *dec = player->decoders[i];
        if(dec == NULL)
            continue;
        if(Kit_PeekDecoderOutput(dec))
            return false;
    }
    return true;
}

static int _RunDecoder(Kit_Player *player) {
    int got;
    bool has_room = true;

    do {
        while((got = _DemuxStream(player)) == -1);
        if(got == 1 && _IsOutputEmpty(player)) {
            return 1;
        }

        for(int i = 0; i < KIT_DEC_COUNT; i++) {
            while(Kit_RunDecoder(player->decoders[i]) == 1);
        }

        // If there is no room in any decoder input, just stop here since it likely means that
        // at least some decoder output is full.
        for(int i = 0; i < KIT_DEC_COUNT; i++) {
            Kit_Decoder *dec = player->decoders[i];
            if(dec == NULL)
                continue;
            if(!Kit_CanWriteDecoderInput(dec)) {
                has_room = false;
                break;
            }
        }
    } while(has_room);

    return 0;
}

static int _DecoderThread(void *ptr) {
    Kit_Player *player = ptr;
    bool is_running = true;
    bool is_playing = true;

    while(is_running) {
        if(player->state == KIT_CLOSED) {
            is_running = false;
            continue;
        }
        if(player->state == KIT_PLAYING) {
            is_playing = true;
        }
        while(is_running && is_playing) {
            // Grab the decoder lock, and run demuxer & decoders for a bit.
            if(SDL_LockMutex(player->dec_lock) == 0) {
                if(player->state == KIT_CLOSED) {
                    is_running = false;
                    goto end_block;
                }
                if(player->state == KIT_STOPPED) {
                    is_playing = false;
                    goto end_block;
                }
                if(_RunDecoder(player) == 1) {
                    player->state = KIT_STOPPED;
                    goto end_block;
                }

end_block:
                SDL_UnlockMutex(player->dec_lock);
            }

            // Delay to make sure this thread does not hog all cpu
            SDL_Delay(2);
        }

        // Just idle while waiting for work.
        SDL_Delay(25);
    }

    return 0;
}

Kit_Player* Kit_CreatePlayer(const Kit_Source *src,
                             int video_stream_index,
                             int audio_stream_index,
                             int subtitle_stream_index,
                             int screen_w,
                             int screen_h) {
    assert(src != NULL);
    assert(screen_w >= 0);
    assert(screen_h >= 0);
    
    if(video_stream_index < 0 && subtitle_stream_index >= 0) {
        Kit_SetError("Subtitle stream selected without video stream");
        goto exit_0;
    }

    Kit_Player *player = calloc(1, sizeof(Kit_Player));
    if(player == NULL) {
        Kit_SetError("Unable to allocate player");
        goto exit_0;
    }

    // Initialize audio decoder
    player->decoders[KIT_AUDIO_DEC] = Kit_CreateAudioDecoder(src, audio_stream_index);
    if(player->decoders[KIT_AUDIO_DEC] == NULL && audio_stream_index >= 0) {
        goto exit_1;
    }

    // Initialize video decoder
    player->decoders[KIT_VIDEO_DEC] = Kit_CreateVideoDecoder(src, video_stream_index);
    if(player->decoders[KIT_VIDEO_DEC] == NULL && video_stream_index >= 0) {
        goto exit_2;
    }

    // Initialize subtitle decoder.
    Kit_OutputFormat output;
    Kit_GetDecoderOutputFormat(player->decoders[KIT_VIDEO_DEC], &output);
    player->decoders[KIT_SUBTITLE_DEC] = Kit_CreateSubtitleDecoder(
        src, subtitle_stream_index, output.width, output.height, screen_w, screen_h);
    if(player->decoders[KIT_SUBTITLE_DEC] == NULL && subtitle_stream_index >= 0) {
        goto exit_2;
    }

    // Decoder thread lock
    player->dec_lock = SDL_CreateMutex();
    if(player->dec_lock == NULL) {
        Kit_SetError("Unable to create a decoder thread lock mutex: %s", SDL_GetError());
        goto exit_2;
    }

    // Decoder thread
    player->dec_thread = SDL_CreateThread(_DecoderThread, "Kit Decoder Thread", player);
    if(player->dec_thread == NULL) {
        Kit_SetError("Unable to create a decoder thread: %s", SDL_GetError());
        goto exit_3;
    }

    player->src = src;
    return player;

exit_3:
    SDL_DestroyMutex(player->dec_lock);
exit_2:
    for(int i = 0; i < KIT_DEC_COUNT; i++) {
        Kit_CloseDecoder(player->decoders[i]);
    }
exit_1:
    free(player);
exit_0:
    return NULL;
}

void Kit_ClosePlayer(Kit_Player *player) {
    if(player == NULL) return;

    // Kill the decoder thread and mutex
    if(SDL_LockMutex(player->dec_lock) == 0) {
        player->state = KIT_CLOSED;
        SDL_UnlockMutex(player->dec_lock);
    }
    SDL_WaitThread(player->dec_thread, NULL);
    SDL_DestroyMutex(player->dec_lock);

    // Shutdown decoders
    for(int i = 0; i < KIT_DEC_COUNT; i++) {
        Kit_CloseDecoder(player->decoders[i]);
    }

    // Free the player structure itself
    free(player);
}

void Kit_SetPlayerScreenSize(Kit_Player *player, int w, int h) {
    assert(player != NULL);
    Kit_Decoder *dec = player->decoders[KIT_SUBTITLE_DEC];
    if(dec == NULL)
        return;
    Kit_SetSubtitleDecoderSize(dec, w, h);
}

int Kit_GetPlayerVideoStream(const Kit_Player *player) {
    assert(player != NULL);
    return Kit_GetDecoderStreamIndex(player->decoders[KIT_VIDEO_DEC]);
}

int Kit_GetPlayerAudioStream(const Kit_Player *player) {
    assert(player != NULL);
    return Kit_GetDecoderStreamIndex(player->decoders[KIT_AUDIO_DEC]);
}

int Kit_GetPlayerSubtitleStream(const Kit_Player *player) {
    assert(player != NULL);
    return Kit_GetDecoderStreamIndex(player->decoders[KIT_SUBTITLE_DEC]);
}

int Kit_GetPlayerVideoData(Kit_Player *player, SDL_Texture *texture) {
    assert(player != NULL);

    Kit_Decoder *dec = player->decoders[KIT_VIDEO_DEC];
    if(dec == NULL) {
        return 0;
    }

    // If paused or stopped, do nothing
    if(player->state == KIT_PAUSED) {
        return 0;
    }
    if(player->state == KIT_STOPPED) {
        return 0;
    }

    return Kit_GetVideoDecoderData(dec, texture);
}

int Kit_GetPlayerAudioData(Kit_Player *player, unsigned char *buffer, int length) {
    assert(player != NULL);
    assert(buffer != NULL);

    Kit_Decoder *dec = player->decoders[KIT_AUDIO_DEC];
    if(dec == NULL) {
        return 0;
    }

    // If asked for nothing, don't return anything either :P
    if(length == 0) {
        return 0;
    }

    // If paused or stopped, do nothing
    if(player->state == KIT_PAUSED) {
        return 0;
    }
    if(player->state == KIT_STOPPED) {
        return 0;
    }

    return Kit_GetAudioDecoderData(dec, buffer, length);
}

int Kit_GetPlayerSubtitleData(Kit_Player *player, SDL_Texture *texture, SDL_Rect *sources, SDL_Rect *targets, int limit) {
    assert(player != NULL);
    assert(texture != NULL);
    assert(sources != NULL);
    assert(targets != NULL);
    assert(limit >= 0);

    Kit_Decoder *sub_dec = player->decoders[KIT_SUBTITLE_DEC];
    Kit_Decoder *video_dec = player->decoders[KIT_VIDEO_DEC];
    if(sub_dec == NULL || video_dec == NULL) {
        return 0;
    }

    // If paused, just return the current items
    if(player->state == KIT_PAUSED) {
        return Kit_GetSubtitleDecoderInfo(sub_dec, texture, sources, targets, limit);
    }

    // If stopped, do nothing.
    if(player->state == KIT_STOPPED) {
        return 0;
    }

    // Refresh texture, then refresh rects and return number of items in the texture.
    Kit_GetSubtitleDecoderTexture(sub_dec, texture, video_dec->clock_pos);
    return Kit_GetSubtitleDecoderInfo(sub_dec, texture, sources, targets, limit);
}

void Kit_GetPlayerInfo(const Kit_Player *player, Kit_PlayerInfo *info) {
    assert(player != NULL);
    assert(info != NULL);

    void *streams[] = {&info->video, &info->audio, &info->subtitle};
    for(int i = 0; i < KIT_DEC_COUNT; i++) {
        Kit_Decoder *dec = player->decoders[i];
        Kit_PlayerStreamInfo *stream = streams[i];
        Kit_GetDecoderCodecInfo(dec, &stream->codec);
        Kit_GetDecoderOutputFormat(dec, &stream->output);
    }
}

static void _SetClockSync(Kit_Player *player) {
    double sync = _GetSystemTime();
    for(int i = 0; i < KIT_DEC_COUNT; i++) {
        Kit_SetDecoderClockSync(player->decoders[i], sync);
    }
}

static void _ChangeClockSync(Kit_Player *player, double delta) {
    for(int i = 0; i < KIT_DEC_COUNT; i++) {
        Kit_ChangeDecoderClockSync(player->decoders[i], delta);
    }
}

Kit_PlayerState Kit_GetPlayerState(const Kit_Player *player) {
    assert(player != NULL);
    return player->state;
}

void Kit_PlayerPlay(Kit_Player *player) {
    assert(player != NULL);
    double tmp;
    if(SDL_LockMutex(player->dec_lock) == 0) {
        switch(player->state) {
            case KIT_PLAYING:
            case KIT_CLOSED:
                break;
            case KIT_PAUSED:
                tmp = _GetSystemTime() - player->pause_started;
                _ChangeClockSync(player, tmp);
                player->state = KIT_PLAYING;
                break;
            case KIT_STOPPED:
                _RunDecoder(player); // Fill some buffers before starting playback
                _SetClockSync(player);
                player->state = KIT_PLAYING;
                break;
        }
        SDL_UnlockMutex(player->dec_lock);
    }
}

void Kit_PlayerStop(Kit_Player *player) {
    assert(player != NULL);
    if(SDL_LockMutex(player->dec_lock) == 0) {
        switch(player->state) {
            case KIT_STOPPED:
            case KIT_CLOSED:
                break;
            case KIT_PLAYING:
            case KIT_PAUSED:
                player->state = KIT_STOPPED;
                for(int i = 0; i < KIT_DEC_COUNT; i++) {
                    Kit_ClearDecoderBuffers(player->decoders[i]);
                }
                break;
        }
        SDL_UnlockMutex(player->dec_lock);
    }
}

void Kit_PlayerPause(Kit_Player *player) {
    assert(player != NULL);
    player->state = KIT_PAUSED;
    player->pause_started = _GetSystemTime();
}

int Kit_PlayerSeek(Kit_Player *player, double seek_set) {
    assert(player != NULL);
    double position;
    double duration;
    int64_t seek_target;
    int flags = AVSEEK_FLAG_ANY;

    if(SDL_LockMutex(player->dec_lock) == 0) {
        duration = Kit_GetPlayerDuration(player);
        position = Kit_GetPlayerPosition(player);
        if(seek_set <= 0) {
            seek_set = 0;
        }
        if(seek_set >= duration) {
            seek_set = duration;
        }

        // Set source to timestamp
        AVFormatContext *format_ctx = player->src->format_ctx;
        seek_target = seek_set * AV_TIME_BASE;
        if(seek_set < position) {
            flags |= AVSEEK_FLAG_BACKWARD;
        }

        // First, tell ffmpeg to seek stream. If not capable, stop here.
        // Failure here probably means that stream is unseekable someway, eg. streamed media
        if(avformat_seek_file(format_ctx, -1, seek_target, seek_target, INT64_MAX, flags) < 0) {
            Kit_SetError("Unable to seek source");
            SDL_UnlockMutex(player->dec_lock);
            return 1;
        }

        // Clean old buffers and try to fill them with new data
        for(int i = 0; i < KIT_DEC_COUNT; i++) {
            Kit_ClearDecoderBuffers(player->decoders[i]);
        }
        _RunDecoder(player);

        // Try to get a precise seek position from the next audio/video frame
        // (depending on which one is used to sync)
        double precise_pts = -1.0F;
        if(player->decoders[KIT_VIDEO_DEC] != NULL) {
            precise_pts = Kit_GetVideoDecoderPTS(player->decoders[KIT_VIDEO_DEC]);
        }
        else if(player->decoders[KIT_AUDIO_DEC] != NULL) {
            precise_pts = Kit_GetAudioDecoderPTS(player->decoders[KIT_AUDIO_DEC]);
        }

        // If we got a legit looking value, set it as seek value. Otherwise use
        // the seek value we requested.
        if(precise_pts >= 0) {
            _ChangeClockSync(player, position - precise_pts);
        } else {
            _ChangeClockSync(player, position - seek_set);
        }

        // That's it. Unlock and continue.
        SDL_UnlockMutex(player->dec_lock);
    }

    return 0;
}

double Kit_GetPlayerDuration(const Kit_Player *player) {
    assert(player != NULL);

    AVFormatContext *fmt_ctx = player->src->format_ctx;
    return (fmt_ctx->duration / AV_TIME_BASE);
}

double Kit_GetPlayerPosition(const Kit_Player *player) {
    assert(player != NULL);

    if(player->decoders[KIT_VIDEO_DEC]) {
        return ((Kit_Decoder*)player->decoders[KIT_VIDEO_DEC])->clock_pos;
    }
    if(player->decoders[KIT_AUDIO_DEC]) {
        return ((Kit_Decoder*)player->decoders[KIT_AUDIO_DEC])->clock_pos;
    }
    return 0;
}