forked from haasn/libplacebo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plplay.c
1589 lines (1360 loc) · 62 KB
/
plplay.c
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Very basic video player based on ffmpeg. All it does is render a single
* video stream to completion, and then exits. It exits on most errors, rather
* than gracefully trying to recreate the context.
*
* The timing code is also rather naive, due to the current lack of
* presentation feedback. That being said, an effort is made to time the video
* stream to the system clock, using frame mixing for mismatches.
*
* License: CC0 / Public Domain
*/
#include <pthread.h>
#include <libgen.h>
#include <libavutil/cpu.h>
#include <libavutil/file.h>
#include <libavutil/pixdesc.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include "common.h"
#include "utils.h"
#include "window.h"
#ifdef HAVE_NUKLEAR
#include "ui.h"
#else
struct ui;
static void ui_destroy(struct ui **ui) {}
static bool ui_draw(struct ui *ui, const struct pl_swapchain_frame *frame) { return true; };
#endif
#include <libplacebo/renderer.h>
#include <libplacebo/shaders/lut.h>
#include <libplacebo/utils/libav.h>
#include <libplacebo/utils/frame_queue.h>
#define MAX_FRAME_PASSES 256
#define MAX_BLEND_PASSES 8
#define MAX_BLEND_FRAMES 8
#define MIN(x, y) ((x) < (y) ? (x) : (y))
struct pass_info {
struct pl_dispatch_info pass;
char *name;
};
struct plplay {
struct window *win;
struct ui *ui;
// libplacebo
pl_log log;
pl_renderer renderer;
pl_queue queue;
// libav*
AVFormatContext *format;
AVCodecContext *codec;
const AVStream *stream; // points to first video stream of `format`
pthread_t decoder_thread;
bool decoder_thread_created;
bool exit_thread;
// settings / ui state
const struct pl_filter_preset *upscaler, *downscaler, *plane_scaler, *frame_mixer;
struct pl_render_params params;
struct pl_deband_params deband_params;
struct pl_sigmoid_params sigmoid_params;
struct pl_color_adjustment color_adjustment;
struct pl_peak_detect_params peak_detect_params;
struct pl_color_map_params color_map_params;
struct pl_dither_params dither_params;
struct pl_deinterlace_params deinterlace_params;
struct pl_icc_params icc_params;
struct pl_cone_params cone_params;
struct pl_color_space target_color;
struct pl_color_repr target_repr;
struct pl_icc_profile target_icc;
char *target_icc_name;
pl_rotation target_rot;
bool target_override;
bool levels_override;
bool ignore_dovi;
bool colorspace_hint;
bool reset_colorspace;
bool reset_levels;
// custom shaders
const struct pl_hook **shader_hooks;
char **shader_paths;
size_t shader_num;
size_t shader_size;
// pass metadata
struct pass_info blend_info[MAX_BLEND_FRAMES][MAX_BLEND_PASSES];
struct pass_info frame_info[MAX_FRAME_PASSES];
int num_frame_passes;
int num_blend_passes[MAX_BLEND_FRAMES];
};
static void uninit(struct plplay *p)
{
if (p->decoder_thread_created) {
p->exit_thread = true;
pl_queue_push(p->queue, NULL); // Signal EOF to wake up thread
pthread_join(p->decoder_thread, NULL);
}
pl_queue_destroy(&p->queue);
pl_renderer_destroy(&p->renderer);
for (int i = 0; i < p->shader_num; i++) {
pl_mpv_user_shader_destroy(&p->shader_hooks[i]);
free(p->shader_paths[i]);
}
free(p->shader_hooks);
free(p->shader_paths);
free(p->target_icc_name);
av_file_unmap((void *) p->target_icc.data, p->target_icc.len);
// Free this before destroying the window to release associated GPU buffers
avcodec_free_context(&p->codec);
avformat_free_context(p->format);
ui_destroy(&p->ui);
window_destroy(&p->win);
pl_log_destroy(&p->log);
memset(p, 0, sizeof(*p));
}
static bool open_file(struct plplay *p, const char *filename)
{
printf("Opening file: '%s'\n", filename);
if (avformat_open_input(&p->format, filename, NULL, NULL) != 0) {
fprintf(stderr, "libavformat: Failed opening file!\n");
return false;
}
printf("Format: %s\n", p->format->iformat->name);
if (p->format->duration != AV_NOPTS_VALUE)
printf("Duration: %.3f s\n", p->format->duration / 1e6);
if (avformat_find_stream_info(p->format, NULL) < 0) {
fprintf(stderr, "libavformat: Failed finding stream info!\n");
return false;
}
// Find "best" video stream
int stream_idx =
av_find_best_stream(p->format, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
if (stream_idx < 0) {
fprintf(stderr, "plplay: File contains no video streams?\n");
return false;
}
const AVStream *stream = p->format->streams[stream_idx];
const AVCodecParameters *par = stream->codecpar;
printf("Found video track (stream %d)\n", stream_idx);
printf("Resolution: %d x %d\n", par->width, par->height);
if (stream->avg_frame_rate.den && stream->avg_frame_rate.num)
printf("FPS: %f\n", av_q2d(stream->avg_frame_rate));
if (stream->r_frame_rate.den && stream->r_frame_rate.num)
printf("TBR: %f\n", av_q2d(stream->r_frame_rate));
if (stream->time_base.den && stream->time_base.num)
printf("TBN: %f\n", av_q2d(stream->time_base));
if (par->bit_rate)
printf("Bitrate: %"PRIi64" kbps\n", par->bit_rate / 1000);
printf("Format: %s\n", av_get_pix_fmt_name(par->format));
p->stream = stream;
return true;
}
static inline bool is_file_hdr(struct plplay *p)
{
assert(p->stream);
enum AVColorTransferCharacteristic trc = p->stream->codecpar->color_trc;
if (pl_color_transfer_is_hdr(pl_transfer_from_av(trc)))
return true;
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 16, 100)
if (av_stream_get_side_data(p->stream, AV_PKT_DATA_DOVI_CONF, NULL))
return true;
#endif
return false;
}
static bool init_codec(struct plplay *p)
{
assert(p->stream);
assert(p->win->gpu);
const AVCodec *codec = avcodec_find_decoder(p->stream->codecpar->codec_id);
if (!codec) {
fprintf(stderr, "libavcodec: Failed finding matching codec\n");
return false;
}
p->codec = avcodec_alloc_context3(codec);
if (!p->codec) {
fprintf(stderr, "libavcodec: Failed allocating codec\n");
return false;
}
if (avcodec_parameters_to_context(p->codec, p->stream->codecpar) < 0) {
fprintf(stderr, "libavcodec: Failed copying codec parameters to codec\n");
return false;
}
printf("Codec: %s (%s)\n", codec->name, codec->long_name);
const AVCodecHWConfig *hwcfg;
for (int i = 0; (hwcfg = avcodec_get_hw_config(codec, i)); i++) {
if (!pl_test_pixfmt(p->win->gpu, hwcfg->pix_fmt))
continue;
if (!(hwcfg->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
continue;
int ret = av_hwdevice_ctx_create(&p->codec->hw_device_ctx,
hwcfg->device_type,
NULL, NULL, 0);
if (ret < 0) {
fprintf(stderr, "libavcodec: Failed opening HW device context, skipping\n");
continue;
}
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hwcfg->pix_fmt);
printf("Using hardware frame format: %s\n", desc->name);
p->codec->extra_hw_frames = 4;
break;
}
if (!hwcfg)
printf("Using software decoding\n");
p->codec->thread_count = av_cpu_count();
p->codec->get_buffer2 = pl_get_buffer2;
p->codec->opaque = &p->win->gpu;
#if LIBAVCODEC_VERSION_MAJOR < 60
AV_NOWARN_DEPRECATED({
p->codec->thread_safe_callbacks = 1;
});
#endif
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(58, 113, 100)
p->codec->export_side_data |= AV_CODEC_EXPORT_DATA_FILM_GRAIN;
#endif
if (avcodec_open2(p->codec, codec, NULL) < 0) {
fprintf(stderr, "libavcodec: Failed opening codec\n");
return false;
}
return true;
}
static bool map_frame(pl_gpu gpu, pl_tex *tex,
const struct pl_source_frame *src,
struct pl_frame *out_frame)
{
AVFrame *frame = src->frame_data;
struct plplay *p = frame->opaque;
bool ok = pl_map_avframe_ex(gpu, out_frame, pl_avframe_params(
.frame = frame,
.tex = tex,
.map_dovi = !p->ignore_dovi,
));
av_frame_free(&frame); // references are preserved by `out_frame`
if (!ok) {
fprintf(stderr, "Failed mapping AVFrame!\n");
return false;
}
pl_frame_copy_stream_props(out_frame, p->stream);
return true;
}
static void unmap_frame(pl_gpu gpu, struct pl_frame *frame,
const struct pl_source_frame *src)
{
pl_unmap_avframe(gpu, frame);
}
static void discard_frame(const struct pl_source_frame *src)
{
AVFrame *frame = src->frame_data;
av_frame_free(&frame);
printf("Dropped frame with PTS %.3f\n", src->pts);
}
static void *decode_loop(void *arg)
{
int ret;
struct plplay *p = arg;
AVPacket *packet = av_packet_alloc();
AVFrame *frame = av_frame_alloc();
if (!frame || !packet)
goto done;
float frame_duration = av_q2d(av_inv_q(p->stream->avg_frame_rate));
double first_pts = 0.0, base_pts = 0.0, last_pts = 0.0;
uint64_t num_frames = 0;
while (!p->exit_thread) {
switch ((ret = av_read_frame(p->format, packet))) {
case 0:
if (packet->stream_index != p->stream->index) {
// Ignore unrelated packets
av_packet_unref(packet);
continue;
}
ret = avcodec_send_packet(p->codec, packet);
av_packet_unref(packet);
break;
case AVERROR_EOF:
// Send empty input to flush decoder
ret = avcodec_send_packet(p->codec, NULL);
break;
default:
fprintf(stderr, "libavformat: Failed reading packet: %s\n",
av_err2str(ret));
goto done;
}
if (ret < 0) {
fprintf(stderr, "libavcodec: Failed sending packet to decoder: %s\n",
av_err2str(ret));
goto done;
}
// Decode all frames from this packet
while ((ret = avcodec_receive_frame(p->codec, frame)) == 0) {
last_pts = frame->pts * av_q2d(p->stream->time_base);
if (num_frames++ == 0)
first_pts = last_pts;
frame->opaque = p;
pl_queue_push_block(p->queue, UINT64_MAX, &(struct pl_source_frame) {
.pts = last_pts - first_pts + base_pts,
.duration = frame_duration,
.map = map_frame,
.unmap = unmap_frame,
.discard = discard_frame,
.frame_data = frame,
// allow soft-disabling deinterlacing at the source frame level
.first_field = p->params.deinterlace_params
? pl_field_from_avframe(frame)
: PL_FIELD_NONE,
});
frame = av_frame_alloc();
}
switch (ret) {
case AVERROR(EAGAIN):
continue;
case AVERROR_EOF:
if (num_frames <= 1)
goto done; // still image or empty file
// loop infinitely
ret = av_seek_frame(p->format, p->stream->index, 0, AVSEEK_FLAG_BACKWARD);
if (ret < 0) {
fprintf(stderr, "libavformat: Failed seeking in stream: %s\n",
av_err2str(ret));
goto done;
}
avcodec_flush_buffers(p->codec);
base_pts += last_pts;
num_frames = 0;
continue;
default:
fprintf(stderr, "libavcodec: Failed decoding frame: %s\n",
av_err2str(ret));
goto done;
}
}
done:
pl_queue_push(p->queue, NULL); // Signal EOF to flush queue
av_packet_free(&packet);
av_frame_free(&frame);
return NULL;
}
static void update_settings(struct plplay *p);
static void update_colorspace_hint(struct plplay *p, const struct pl_frame_mix *mix)
{
const struct pl_frame *frame = NULL;
for (int i = 0; i < mix->num_frames; i++) {
if (mix->timestamps[i] > 0.0)
break;
frame = mix->frames[i];
}
if (!frame)
return;
struct pl_color_space hint = {0};
if (p->colorspace_hint)
pl_color_space_from_avframe(&hint, frame->user_data);
if (p->reset_colorspace)
p->target_color = hint;
if (p->reset_levels) {
p->target_color.hdr = hint.hdr;
p->target_color.nominal_max = hint.nominal_max;
p->target_color.nominal_min = hint.nominal_min;
}
if (p->levels_override) {
hint.nominal_max = p->target_color.nominal_max;
hint.nominal_min = p->target_color.nominal_min;
}
pl_swapchain_colorspace_hint(p->win->swapchain, &hint);
}
static bool render_frame(struct plplay *p, const struct pl_swapchain_frame *frame,
const struct pl_frame_mix *mix)
{
struct pl_frame target;
pl_frame_from_swapchain(&target, frame);
update_settings(p);
// Update the global settings based on this swapchain frame, then use those
pl_color_space_merge(&p->target_color, &target.color);
pl_color_repr_merge(&p->target_repr, &target.repr);
if (p->target_override) {
target.color = p->target_color;
target.repr = p->target_repr;
target.profile = p->target_icc;
}
assert(mix->num_frames);
const AVFrame *avframe = mix->frames[0]->user_data;
double dar = pl_rect2df_aspect(&mix->frames[0]->crop);
if (avframe->sample_aspect_ratio.num)
dar *= av_q2d(avframe->sample_aspect_ratio);
target.rotation = p->target_rot;
pl_rect2df_aspect_set_rot(&target.crop, dar,
mix->frames[0]->rotation - target.rotation,
0.0);
if (!pl_render_image_mix(p->renderer, mix, &target, &p->params))
return false;
if (!ui_draw(p->ui, frame))
return false;
return true;
}
static bool render_loop(struct plplay *p)
{
struct pl_queue_params qparams = {
.interpolation_threshold = 0.01,
.timeout = UINT64_MAX,
};
// Initialize the frame queue, blocking indefinitely until done
struct pl_frame_mix mix;
switch (pl_queue_update(p->queue, &mix, &qparams)) {
case PL_QUEUE_OK: break;
case PL_QUEUE_EOF: return true;
case PL_QUEUE_ERR: goto error;
default: abort();
}
struct pl_swapchain_frame frame;
update_colorspace_hint(p, &mix);
if (!pl_swapchain_start_frame(p->win->swapchain, &frame))
goto error;
// Disable background transparency by default if the swapchain does not
// appear to support alpha transaprency
if (frame.color_repr.alpha == PL_ALPHA_UNKNOWN)
p->params.background_transparency = 0.0;
if (!render_frame(p, &frame, &mix))
goto error;
if (!pl_swapchain_submit_frame(p->win->swapchain))
goto error;
// Wait until rendering is complete. Do this before measuring the time
// start, to ensure we don't count initialization overhead as part of the
// first vsync.
pl_gpu_finish(p->win->gpu);
double ts, ts_prev;
if (!utils_gettime(&ts_prev))
goto error;
pl_swapchain_swap_buffers(p->win->swapchain);
window_poll(p->win, false);
double pts = 0.0;
bool stuck = false;
while (!p->win->window_lost) {
if (window_get_key(p->win, KEY_ESC))
break;
update_colorspace_hint(p, &mix);
if (!pl_swapchain_start_frame(p->win->swapchain, &frame)) {
// Window stuck/invisible? Block for events and try again.
window_poll(p->win, true);
continue;
}
retry:
if (!utils_gettime(&ts))
goto error;
if (!stuck) {
pts += (ts - ts_prev);
}
ts_prev = ts;
qparams.radius = pl_frame_mix_radius(&p->params);
qparams.timeout = 50000000; // 50 ms
qparams.pts = pts;
switch (pl_queue_update(p->queue, &mix, &qparams)) {
case PL_QUEUE_ERR: goto error;
case PL_QUEUE_EOF: return true;
case PL_QUEUE_OK:
if (!render_frame(p, &frame, &mix))
goto error;
stuck = false;
break;
case PL_QUEUE_MORE:
stuck = true;
goto retry;
}
if (!pl_swapchain_submit_frame(p->win->swapchain)) {
fprintf(stderr, "libplacebo: failed presenting frame!\n");
goto error;
}
pl_swapchain_swap_buffers(p->win->swapchain);
window_poll(p->win, false);
}
return true;
error:
fprintf(stderr, "Render loop failed, exiting early...\n");
return false;
}
static void info_callback(void *priv, const struct pl_render_info *info)
{
struct plplay *p = priv;
struct pass_info *pass = NULL;
switch (info->stage) {
case PL_RENDER_STAGE_FRAME:
if (info->index >= MAX_FRAME_PASSES)
return;
p->num_frame_passes = info->index + 1;
pass = &p->frame_info[info->index];
break;
case PL_RENDER_STAGE_BLEND:
if (info->index >= MAX_BLEND_PASSES || info->count >= MAX_BLEND_FRAMES)
return;
p->num_blend_passes[info->count] = info->index + 1;
pass = &p->blend_info[info->count][info->index];
break;
case PL_RENDER_STAGE_COUNT: abort();
}
free(pass->name);
pass->name = strdup(info->pass->shader->description);
pass->pass = *info->pass;
}
static struct plplay state;
int main(int argc, char **argv)
{
const char *filename;
enum pl_log_level log_level = PL_LOG_INFO;
if (argc == 3 && strcmp(argv[1], "-v") == 0) {
filename = argv[2];
log_level = PL_LOG_DEBUG;
av_log_set_level(AV_LOG_VERBOSE);
} else if (argc == 2) {
filename = argv[1];
av_log_set_level(AV_LOG_INFO);
} else {
fprintf(stderr, "Usage: ./%s [-v] <filename>\n", argv[0]);
return -1;
}
state = (struct plplay) {
.params = pl_render_default_params,
.deband_params = pl_deband_default_params,
.sigmoid_params = pl_sigmoid_default_params,
.color_adjustment = pl_color_adjustment_neutral,
.peak_detect_params = pl_peak_detect_default_params,
.color_map_params = pl_color_map_default_params,
.dither_params = pl_dither_default_params,
.icc_params = pl_icc_default_params,
.cone_params = pl_vision_normal,
.deinterlace_params = pl_deinterlace_default_params,
.target_override = true,
};
// Redirect all of the pointers in `params.default` to instead point to the
// structs inside `struct plplay`, so we can adjust them using the UI
#define DEFAULT_PARAMS(field) \
state.params.field = state.params.field ? &state.field : NULL
DEFAULT_PARAMS(deband_params);
DEFAULT_PARAMS(sigmoid_params);
DEFAULT_PARAMS(peak_detect_params);
DEFAULT_PARAMS(dither_params);
DEFAULT_PARAMS(deinterlace_params);
state.params.color_adjustment = &state.color_adjustment;
state.params.color_map_params = &state.color_map_params;
state.params.cone_params = &state.cone_params;
state.params.icc_params = &state.icc_params;
// Enable dynamic parameters by default, due to plplay's heavy reliance on
// GUI controls for dynamically adjusting render parameters.
state.params.dynamic_constants = true;
// Hook up our pass info callback
state.params.info_callback = info_callback;
state.params.info_priv = &state;
struct plplay *p = &state;
if (!open_file(p, filename))
goto error;
const AVCodecParameters *par = p->stream->codecpar;
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(par->format);
if (!desc)
goto error;
struct window_params params = {
.title = "plplay",
.width = par->width,
.height = par->height,
};
if (p->colorspace_hint) {
params.colors = (struct pl_swapchain_colors) {
.primaries = pl_primaries_from_av(par->color_primaries),
.transfer = pl_transfer_from_av(par->color_trc),
// HDR metadata will come from AVFrame side data
};
}
if (desc->flags & AV_PIX_FMT_FLAG_ALPHA) {
params.alpha = true;
state.params.background_transparency = 1.0;
}
p->log = pl_log_create(PL_API_VER, pl_log_params(
.log_cb = pl_log_color,
.log_level = log_level,
));
p->win = window_create(p->log, ¶ms);
if (!p->win)
goto error;
// Test the AVPixelFormat against the GPU capabilities
if (!pl_test_pixfmt(p->win->gpu, par->format)) {
fprintf(stderr, "Unsupported AVPixelFormat: %s\n", desc->name);
goto error;
}
#ifdef HAVE_NUKLEAR
p->ui = ui_create(p->win->gpu);
if (!p->ui)
goto error;
// Find the right named filter entries for the defaults
const struct pl_filter_preset *f;
for (f = pl_scale_filters; f->name; f++) {
if (p->params.upscaler == f->filter)
p->upscaler = f;
if (p->params.downscaler == f->filter)
p->downscaler = f;
if (p->params.plane_upscaler == f->filter)
p->plane_scaler = f;
}
for (f = pl_frame_mixers; f->name; f++) {
if (p->params.frame_mixer == f->filter)
p->frame_mixer = f;
}
assert(p->upscaler && p->downscaler && p->frame_mixer);
#endif
if (!init_codec(p))
goto error;
p->queue = pl_queue_create(p->win->gpu);
int ret = pthread_create(&p->decoder_thread, NULL, decode_loop, p);
if (ret != 0) {
fprintf(stderr, "Failed creating decode thread: %s\n", strerror(errno));
goto error;
}
p->decoder_thread_created = true;
p->renderer = pl_renderer_create(p->log, p->win->gpu);
if (!render_loop(p))
goto error;
printf("Exiting...\n");
uninit(p);
return 0;
error:
uninit(p);
return 1;
}
#ifdef HAVE_NUKLEAR
static void add_hook(struct plplay *p, const struct pl_hook *hook, const char *path)
{
if (!hook)
return;
if (p->shader_num == p->shader_size) {
// Grow array if needed
size_t new_size = p->shader_size ? p->shader_size * 2 : 16;
void *new_hooks = realloc(p->shader_hooks, new_size * sizeof(void *));
if (!new_hooks)
goto error;
p->shader_hooks = new_hooks;
char **new_paths = realloc(p->shader_paths, new_size * sizeof(char *));
if (!new_paths)
goto error;
p->shader_paths = new_paths;
p->shader_size = new_size;
}
// strip leading path
while (true) {
const char *fname = strchr(path, '/');
if (!fname)
break;
path = fname + 1;
}
char *path_copy = strdup(path);
if (!path_copy)
goto error;
p->shader_hooks[p->shader_num] = hook;
p->shader_paths[p->shader_num] = path_copy;
p->shader_num++;
return;
error:
pl_mpv_user_shader_destroy(&hook);
}
static const char *pscale_desc(const struct pl_filter_preset *f)
{
return f->filter ? f->description : "None (Use regular upscaler)";
}
static void update_settings(struct plplay *p)
{
struct nk_context *nk = ui_get_context(p->ui);
enum nk_panel_flags win_flags = NK_WINDOW_BORDER | NK_WINDOW_MOVABLE |
NK_WINDOW_SCALABLE | NK_WINDOW_MINIMIZABLE |
NK_WINDOW_TITLE;
ui_update_input(p->ui, p->win);
const char *dropped_file = window_get_file(p->win);
struct pl_render_params *par = &p->params;
if (nk_begin(nk, "Settings", nk_rect(100, 100, 600, 600), win_flags)) {
if (nk_tree_push(nk, NK_TREE_NODE, "Window settings", NK_MAXIMIZED)) {
struct nk_colorf bg = {
par->background_color[0],
par->background_color[1],
par->background_color[2],
1.0 - par->background_transparency,
};
nk_layout_row_dynamic(nk, 24, 2);
nk_label(nk, "Background color:", NK_TEXT_LEFT);
if (nk_combo_begin_color(nk, nk_rgb_cf(bg), nk_vec2(nk_widget_width(nk), 300))) {
nk_layout_row_dynamic(nk, 200, 1);
nk_color_pick(nk, &bg, NK_RGBA);
nk_combo_end(nk);
par->background_color[0] = bg.r;
par->background_color[1] = bg.g;
par->background_color[2] = bg.b;
par->background_transparency = 1.0 - bg.a;
}
nk_layout_row_dynamic(nk, 24, 2);
par->blend_against_tiles = nk_check_label(nk, "Blend against tiles", par->blend_against_tiles);
nk_property_int(nk, "Tile size", 2, &par->tile_size, 256, 1, 1);
nk_layout_row(nk, NK_DYNAMIC, 24, 3, (float[]){ 0.4, 0.3, 0.3 });
nk_label(nk, "Tile colors:", NK_TEXT_LEFT);
for (int i = 0; i < 2; i++) {
bg = (struct nk_colorf) {
par->tile_colors[i][0],
par->tile_colors[i][1],
par->tile_colors[i][2],
};
if (nk_combo_begin_color(nk, nk_rgb_cf(bg), nk_vec2(nk_widget_width(nk), 300))) {
nk_layout_row_dynamic(nk, 200, 1);
nk_color_pick(nk, &bg, NK_RGB);
nk_combo_end(nk);
par->tile_colors[i][0] = bg.r;
par->tile_colors[i][1] = bg.g;
par->tile_colors[i][2] = bg.b;
}
}
static const char *rotations[4] = {
[PL_ROTATION_0] = "0°",
[PL_ROTATION_90] = "90°",
[PL_ROTATION_180] = "180°",
[PL_ROTATION_270] = "270°",
};
nk_layout_row_dynamic(nk, 24, 2);
nk_label(nk, "Display orientation:", NK_TEXT_LEFT);
p->target_rot = nk_combo(nk, rotations, 4, p->target_rot,
16, nk_vec2(nk_widget_width(nk), 100));
nk_tree_pop(nk);
}
if (nk_tree_push(nk, NK_TREE_NODE, "Image scaling", NK_MAXIMIZED)) {
const struct pl_filter_preset *f;
nk_layout_row(nk, NK_DYNAMIC, 24, 2, (float[]){ 0.3, 0.7 });
nk_label(nk, "Upscaler:", NK_TEXT_LEFT);
if (nk_combo_begin_label(nk, p->upscaler->description, nk_vec2(nk_widget_width(nk), 500))) {
nk_layout_row_dynamic(nk, 16, 1);
for (f = pl_scale_filters; f->name; f++) {
if (!f->description)
continue;
if (nk_combo_item_label(nk, f->description, NK_TEXT_LEFT))
p->upscaler = f;
}
par->upscaler = p->upscaler->filter;
nk_combo_end(nk);
}
nk_label(nk, "Downscaler:", NK_TEXT_LEFT);
if (nk_combo_begin_label(nk, p->downscaler->description, nk_vec2(nk_widget_width(nk), 500))) {
nk_layout_row_dynamic(nk, 16, 1);
for (f = pl_scale_filters; f->name; f++) {
if (!f->description)
continue;
if (nk_combo_item_label(nk, f->description, NK_TEXT_LEFT))
p->downscaler = f;
}
par->downscaler = p->downscaler->filter;
nk_combo_end(nk);
}
nk_label(nk, "Plane scaler:", NK_TEXT_LEFT);
if (nk_combo_begin_label(nk, pscale_desc(p->plane_scaler), nk_vec2(nk_widget_width(nk), 500))) {
nk_layout_row_dynamic(nk, 16, 1);
for (f = pl_scale_filters; f->name; f++) {
if (!f->description)
continue;
if (nk_combo_item_label(nk, pscale_desc(f), NK_TEXT_LEFT))
p->plane_scaler = f;
}
par->plane_upscaler = p->plane_scaler->filter;
nk_combo_end(nk);
}
nk_label(nk, "Frame mixing:", NK_TEXT_LEFT);
if (nk_combo_begin_label(nk, p->frame_mixer->description, nk_vec2(nk_widget_width(nk), 300))) {
nk_layout_row_dynamic(nk, 16, 1);
for (f = pl_frame_mixers; f->name; f++) {
if (!f->description)
continue;
if (nk_combo_item_label(nk, f->description, NK_TEXT_LEFT))
p->frame_mixer = f;
}
par->frame_mixer = p->frame_mixer->filter;
nk_combo_end(nk);
}
nk_layout_row_dynamic(nk, 24, 2);
par->skip_anti_aliasing = !nk_check_label(nk, "Anti-aliasing", !par->skip_anti_aliasing);
nk_property_float(nk, "Antiringing", 0, &par->antiringing_strength, 1.0, 0.1, 0.01);
nk_property_int(nk, "LUT precision", 0, &par->lut_entries, 256, 1, 1);
float cutoff = par->polar_cutoff * 100.0;
nk_property_float(nk, "Polar cutoff (%)", 0.0, &cutoff, 100.0, 0.1, 0.01);
par->polar_cutoff = cutoff / 100.0;
struct pl_sigmoid_params *spar = &p->sigmoid_params;
nk_layout_row_dynamic(nk, 24, 2);
par->sigmoid_params = nk_check_label(nk, "Sigmoidization", par->sigmoid_params) ? spar : NULL;
if (nk_button_label(nk, "Default values"))
*spar = pl_sigmoid_default_params;
nk_property_float(nk, "Sigmoid center", 0, &spar->center, 1, 0.1, 0.01);
nk_property_float(nk, "Sigmoid slope", 0, &spar->slope, 100, 1, 0.1);
nk_tree_pop(nk);
}
if (nk_tree_push(nk, NK_TREE_NODE, "Deinterlacing", NK_MINIMIZED)) {
struct pl_deinterlace_params *dpar = &p->deinterlace_params;
nk_layout_row_dynamic(nk, 24, 2);
par->deinterlace_params = nk_check_label(nk, "Enable", par->deinterlace_params) ? dpar : NULL;
if (nk_button_label(nk, "Reset settings"))
*dpar = pl_deinterlace_default_params;
static const char *deint_algos[PL_DEINTERLACE_ALGORITHM_COUNT] = {
[PL_DEINTERLACE_WEAVE] = "Field weaving (no-op)",
[PL_DEINTERLACE_BOB] = "Naive bob (line doubling)",
[PL_DEINTERLACE_YADIF] = "Yadif (\"yet another deinterlacing filter\")",
};
nk_label(nk, "Deinterlacing algorithm", NK_TEXT_LEFT);
dpar->algo = nk_combo(nk, deint_algos, PL_DEINTERLACE_ALGORITHM_COUNT,
dpar->algo, 16, nk_vec2(nk_widget_width(nk), 300));
switch (dpar->algo) {
case PL_DEINTERLACE_WEAVE:
case PL_DEINTERLACE_BOB:
break;
case PL_DEINTERLACE_YADIF:
nk_checkbox_label(nk, "Skip spatial check", &dpar->skip_spatial_check);
break;
default: abort();
}
nk_tree_pop(nk);
}
if (nk_tree_push(nk, NK_TREE_NODE, "Debanding", NK_MINIMIZED)) {
struct pl_deband_params *dpar = &p->deband_params;
nk_layout_row_dynamic(nk, 24, 2);
par->deband_params = nk_check_label(nk, "Enable", par->deband_params) ? dpar : NULL;
if (nk_button_label(nk, "Reset settings"))
*dpar = pl_deband_default_params;
nk_property_int(nk, "Iterations", 0, &dpar->iterations, 8, 1, 0);
nk_property_float(nk, "Threshold", 0, &dpar->threshold, 256, 1, 0.5);
nk_property_float(nk, "Radius", 0, &dpar->radius, 256, 1, 0.2);
nk_property_float(nk, "Grain", 0, &dpar->grain, 512, 1, 0.5);
nk_tree_pop(nk);
}
if (nk_tree_push(nk, NK_TREE_NODE, "Color adjustment", NK_MINIMIZED)) {
struct pl_color_adjustment *adj = &p->color_adjustment;
nk_layout_row_dynamic(nk, 24, 2);
par->color_adjustment = nk_check_label(nk, "Enable", par->color_adjustment) ? adj : NULL;
if (nk_button_label(nk, "Default values"))
*adj = pl_color_adjustment_neutral;
nk_property_float(nk, "Brightness", -1, &adj->brightness, 1, 0.1, 0.005);
nk_property_float(nk, "Contrast", 0, &adj->contrast, 10, 0.1, 0.005);
// Convert to (cyclical) degrees for display
int deg = roundf(adj->hue * 180.0 / M_PI);
nk_property_int(nk, "Hue (°)", -50, °, 400, 1, 1);
adj->hue = ((deg + 360) % 360) * M_PI / 180.0;
nk_property_float(nk, "Saturation", 0, &adj->saturation, 10, 0.1, 0.005);
nk_property_float(nk, "Gamma", 0, &adj->gamma, 10, 0.1, 0.005);
// Convert to human-friendly temperature values for display
int temp = (int) roundf(adj->temperature * 3500) + 6500;
nk_property_int(nk, "Temperature (K)", 3000, &temp, 10000, 10, 5);
adj->temperature = (temp - 6500) / 3500.0;
struct pl_cone_params *cpar = &p->cone_params;
nk_layout_row_dynamic(nk, 24, 2);
par->cone_params = nk_check_label(nk, "Color blindness", par->cone_params) ? cpar : NULL;
if (nk_button_label(nk, "Default values"))
*cpar = pl_vision_normal;
nk_layout_row(nk, NK_DYNAMIC, 24, 5, (float[]){ 0.25, 0.25/3, 0.25/3, 0.25/3, 0.5 });
nk_label(nk, "Cone model:", NK_TEXT_LEFT);