summaryrefslogtreecommitdiffstats
path: root/player/client.c
blob: 5087f89885666c0df0c6092b1df4b2dfa8b13ce4 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
/* Copyright (C) 2017 the mpv developers
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <math.h>
#include <stdatomic.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>

#include "common/common.h"
#include "common/global.h"
#include "common/msg.h"
#include "common/msg_control.h"
#include "common/global.h"
#include "input/input.h"
#include "input/cmd.h"
#include "misc/ctype.h"
#include "misc/dispatch.h"
#include "misc/node.h"
#include "misc/rendezvous.h"
#include "misc/thread_tools.h"
#include "options/m_config.h"
#include "options/m_option.h"
#include "options/m_property.h"
#include "options/path.h"
#include "options/parse_configfile.h"
#include "osdep/threads.h"
#include "osdep/timer.h"
#include "osdep/io.h"
#include "stream/stream.h"

#include "command.h"
#include "core.h"
#include "client.h"

/*
 * Locking hierarchy:
 *
 *  MPContext > mp_client_api.lock > mpv_handle.lock > * > mpv_handle.wakeup_lock
 *
 * MPContext strictly speaking has no locks, and instead is implicitly managed
 * by MPContext.dispatch, which basically stops the playback thread at defined
 * points in order to let clients access it in a synchronized manner. Since
 * MPContext code accesses the client API, it's on top of the lock hierarchy.
 *
 */

struct mp_client_api {
    struct MPContext *mpctx;

    mp_mutex lock;

    // -- protected by lock

    struct mpv_handle **clients;
    int num_clients;
    bool shutting_down; // do not allow new clients
    bool have_terminator; // a client took over the role of destroying the core
    bool terminate_core_thread; // make libmpv core thread exit
    // This is incremented whenever the clients[] array above changes. This is
    // used to safely unlock mp_client_api.lock while iterating the list of
    // clients.
    uint64_t clients_list_change_ts;
    int64_t id_alloc;

    struct mp_custom_protocol *custom_protocols;
    int num_custom_protocols;

    struct mpv_render_context *render_context;
};

struct observe_property {
    // -- immutable
    struct mpv_handle *owner;
    char *name;
    int id;                 // ==mp_get_property_id(name)
    uint64_t event_mask;    // ==mp_get_property_event_mask(name)
    int64_t reply_id;
    mpv_format format;
    const struct m_option *type;
    // -- protected by owner->lock
    size_t refcount;
    uint64_t change_ts;     // logical timestamp incremented on each change
    uint64_t value_ts;      // logical timestamp for value contents
    bool value_valid;
    union m_option_value value;
    uint64_t value_ret_ts;  // logical timestamp of value returned to user
    union m_option_value value_ret;
    bool waiting_for_hook;  // flag for draining old property changes on a hook
};

struct mpv_handle {
    // -- immutable
    char name[MAX_CLIENT_NAME];
    struct mp_log *log;
    struct MPContext *mpctx;
    struct mp_client_api *clients;
    int64_t id;

    // -- not thread-safe
    struct mpv_event *cur_event;
    struct mpv_event_property cur_property_event;
    struct observe_property *cur_property;

    mp_mutex lock;

    mp_mutex wakeup_lock;
    mp_cond wakeup;

    // -- protected by wakeup_lock
    bool need_wakeup;
    void (*wakeup_cb)(void *d);
    void *wakeup_cb_ctx;
    int wakeup_pipe[2];

    // -- protected by lock

    uint64_t event_mask;
    bool queued_wakeup;

    mpv_event *events;      // ringbuffer of max_events entries
    int max_events;         // allocated number of entries in events
    int first_event;        // events[first_event] is the first readable event
    int num_events;         // number of readable events
    int reserved_events;    // number of entries reserved for replies
    size_t async_counter;   // pending other async events
    bool choked;            // recovering from queue overflow
    bool destroying;        // pending destruction; no API accesses allowed
    bool hook_pending;      // hook events are returned after draining properties

    struct observe_property **properties;
    int num_properties;
    bool has_pending_properties; // (maybe) new property events (producer side)
    bool new_property_events; // new property events (consumer side)
    int cur_property_index; // round-robin for property events (consumer side)
    uint64_t property_event_masks; // or-ed together event masks of all properties
    // This is incremented whenever the properties[] array above changes. This
    // is used to safely unlock mpv_handle.lock while reading a property. If
    // the counter didn't change between unlock and relock, then it will assume
    // the array did not change.
    uint64_t properties_change_ts;

    bool fuzzy_initialized; // see scripting.c wait_loaded()
    bool is_weak;           // can not keep core alive on its own
    struct mp_log_buffer *messages;
    int messages_level;
};

static bool gen_log_message_event(struct mpv_handle *ctx);
static bool gen_property_change_event(struct mpv_handle *ctx);
static void notify_property_events(struct mpv_handle *ctx, int event);

// Must be called with prop->owner->lock held.
static void prop_unref(struct observe_property *prop)
{
    if (!prop)
        return;

    assert(prop->refcount > 0);
    prop->refcount -= 1;
    if (!prop->refcount)
        talloc_free(prop);
}

void mp_clients_init(struct MPContext *mpctx)
{
    mpctx->clients = talloc_ptrtype(NULL, mpctx->clients);
    *mpctx->clients = (struct mp_client_api) {
        .mpctx = mpctx,
    };
    mpctx->global->client_api = mpctx->clients;
    mp_mutex_init(&mpctx->clients->lock);
}

void mp_clients_destroy(struct MPContext *mpctx)
{
    if (!mpctx->clients)
        return;
    assert(mpctx->clients->num_clients == 0);

    // The API user is supposed to call mpv_render_context_free(). It's simply
    // not allowed not to do this.
    if (mpctx->clients->render_context) {
        MP_FATAL(mpctx, "Broken API use: mpv_render_context_free() not called.\n");
        abort();
    }

    mp_mutex_destroy(&mpctx->clients->lock);
    talloc_free(mpctx->clients);
    mpctx->clients = NULL;
}

// Test for "fuzzy" initialization of all clients. That is, all clients have
// at least called mpv_wait_event() at least once since creation (or exited).
bool mp_clients_all_initialized(struct MPContext *mpctx)
{
    bool all_ok = true;
    mp_mutex_lock(&mpctx->clients->lock);
    for (int n = 0; n < mpctx->clients->num_clients; n++) {
        struct mpv_handle *ctx = mpctx->clients->clients[n];
        mp_mutex_lock(&ctx->lock);
        all_ok &= ctx->fuzzy_initialized;
        mp_mutex_unlock(&ctx->lock);
    }
    mp_mutex_unlock(&mpctx->clients->lock);
    return all_ok;
}

static struct mpv_handle *find_client_id(struct mp_client_api *clients, int64_t id)
{
    for (int n = 0; n < clients->num_clients; n++) {
        if (clients->clients[n]->id == id)
            return clients->clients[n];
    }
    return NULL;
}

static struct mpv_handle *find_client(struct mp_client_api *clients,
                                      const char *name)
{
    if (name[0] == '@') {
        char *end;
        errno = 0;
        long long int id = strtoll(name + 1, &end, 10);
        if (errno || end[0])
            return NULL;
        return find_client_id(clients, id);
    }

    for (int n = 0; n < clients->num_clients; n++) {
        if (strcmp(clients->clients[n]->name, name) == 0)
            return clients->clients[n];
    }

    return NULL;
}

bool mp_client_id_exists(struct MPContext *mpctx, int64_t id)
{
    mp_mutex_lock(&mpctx->clients->lock);
    bool r = find_client_id(mpctx->clients, id);
    mp_mutex_unlock(&mpctx->clients->lock);
    return r;
}

struct mpv_handle *mp_new_client(struct mp_client_api *clients, const char *name)
{
    mp_mutex_lock(&clients->lock);

    char nname[MAX_CLIENT_NAME];
    for (int n = 1; n < 1000; n++) {
        if (!name)
            name = "client";
        snprintf(nname, sizeof(nname) - 3, "%s", name); // - space for number
        for (int i = 0; nname[i]; i++)
            nname[i] = mp_isalnum(nname[i]) ? nname[i] : '_';
        if (n > 1)
            mp_snprintf_cat(nname, sizeof(nname), "%d", n);
        if (!find_client(clients, nname))
            break;
        nname[0] = '\0';
    }

    if (!nname[0] || clients->shutting_down) {
        mp_mutex_unlock(&clients->lock);
        return NULL;
    }

    int num_events = 1000;

    struct mpv_handle *client = talloc_ptrtype(NULL, client);
    *client = (struct mpv_handle){
        .log = mp_log_new(client, clients->mpctx->log, nname),
        .mpctx = clients->mpctx,
        .clients = clients,
        .id = ++(clients->id_alloc),
        .cur_event = talloc_zero(client, struct mpv_event),
        .events = talloc_array(client, mpv_event, num_events),
        .max_events = num_events,
        .event_mask = (1ULL << INTERNAL_EVENT_BASE) - 1, // exclude internal events
        .wakeup_pipe = {-1, -1},
    };
    mp_mutex_init(&client->lock);
    mp_mutex_init(&client->wakeup_lock);
    mp_cond_init(&client->wakeup);

    snprintf(client->name, sizeof(client->name), "%s", nname);

    clients->clients_list_change_ts += 1;
    MP_TARRAY_APPEND(clients, clients->clients, clients->num_clients, client);

    if (clients->num_clients == 1 && !clients->mpctx->is_cli)
        client->fuzzy_initialized = true;

    mp_mutex_unlock(&clients->lock);

    mpv_request_event(client, MPV_EVENT_TICK, 0);

    return client;
}

void mp_client_set_weak(struct mpv_handle *ctx)
{
    mp_mutex_lock(&ctx->lock);
    ctx->is_weak = true;
    mp_mutex_unlock(&ctx->lock);
}

const char *mpv_client_name(mpv_handle *ctx)
{
    return ctx->name;
}

int64_t mpv_client_id(mpv_handle *ctx)
{
    return ctx->id;
}

struct mp_log *mp_client_get_log(struct mpv_handle *ctx)
{
    return ctx->log;
}

struct mpv_global *mp_client_get_global(struct mpv_handle *ctx)
{
    return ctx->mpctx->global;
}

static void wakeup_client(struct mpv_handle *ctx)
{
    mp_mutex_lock(&ctx->wakeup_lock);
    if (!ctx->need_wakeup) {
        ctx->need_wakeup = true;
        mp_cond_broadcast(&ctx->wakeup);
        if (ctx->wakeup_cb)
            ctx->wakeup_cb(ctx->wakeup_cb_ctx);
        if (ctx->wakeup_pipe[0] != -1)
            (void)write(ctx->wakeup_pipe[1], &(char){0}, 1);
    }
    mp_mutex_unlock(&ctx->wakeup_lock);
}

// Note: the caller has to deal with sporadic wakeups.
static int wait_wakeup(struct mpv_handle *ctx, int64_t end)
{
    int r = 0;
    mp_mutex_unlock(&ctx->lock);
    mp_mutex_lock(&ctx->wakeup_lock);
    if (!ctx->need_wakeup)
        r = mp_cond_timedwait_until(&ctx->wakeup, &ctx->wakeup_lock, end);
    if (r == 0)
        ctx->need_wakeup = false;
    mp_mutex_unlock(&ctx->wakeup_lock);
    mp_mutex_lock(&ctx->lock);
    return r;
}

void mpv_set_wakeup_callback(mpv_handle *ctx, void (*cb)(void *d), void *d)
{
    mp_mutex_lock(&ctx->wakeup_lock);
    ctx->wakeup_cb = cb;
    ctx->wakeup_cb_ctx = d;
    if (ctx->wakeup_cb)
        ctx->wakeup_cb(ctx->wakeup_cb_ctx);
    mp_mutex_unlock(&ctx->wakeup_lock);
}

static void lock_core(mpv_handle *ctx)
{
    mp_dispatch_lock(ctx->mpctx->dispatch);
}

static void unlock_core(mpv_handle *ctx)
{
    mp_dispatch_unlock(ctx->mpctx->dispatch);
}

void mpv_wait_async_requests(mpv_handle *ctx)
{
    mp_mutex_lock(&ctx->lock);
    while (ctx->reserved_events || ctx->async_counter)
        wait_wakeup(ctx, INT64_MAX);
    mp_mutex_unlock(&ctx->lock);
}

// Send abort signal to all matching work items.
// If type==0, destroy all of the matching ctx.
// If ctx==0, destroy all.
static void abort_async(struct MPContext *mpctx, mpv_handle *ctx,
                        int type, uint64_t id)
{
    mp_mutex_lock(&mpctx->abort_lock);

    // Destroy all => ensure any newly appearing work is aborted immediately.
    if (ctx == NULL)
        mpctx->abort_all = true;

    for (int n = 0; n < mpctx->num_abort_list; n++) {
        struct mp_abort_entry *abort = mpctx->abort_list[n];
        if (!ctx || (abort->client == ctx && (!type ||
            (abort->client_work_type == type && abort->client_work_id == id))))
        {
            mp_abort_trigger_locked(mpctx, abort);
        }
    }

    mp_mutex_unlock(&mpctx->abort_lock);
}

static void get_thread_id(void *ptr)
{
    *(mp_thread_id *)ptr = mp_thread_current_id();
}

static void mp_destroy_client(mpv_handle *ctx, bool terminate)
{
    if (!ctx)
        return;

    struct MPContext *mpctx = ctx->mpctx;
    struct mp_client_api *clients = ctx->clients;

    MP_DBG(ctx, "Exiting...\n");

    if (terminate)
        mpv_command(ctx, (const char*[]){"quit", NULL});

    mp_mutex_lock(&ctx->lock);

    ctx->destroying = true;

    for (int n = 0; n < ctx->num_properties; n++)
        prop_unref(ctx->properties[n]);
    ctx->num_properties = 0;
    ctx->properties_change_ts += 1;

    prop_unref(ctx->cur_property);
    ctx->cur_property = NULL;

    mp_mutex_unlock(&ctx->lock);

    abort_async(mpctx, ctx, 0, 0);

    // reserved_events equals the number of asynchronous requests that weren't
    // yet replied. In order to avoid that trying to reply to a removed client
    // causes a crash, block until all asynchronous requests were served.
    mpv_wait_async_requests(ctx);

    osd_set_external_remove_owner(mpctx->osd, ctx);
    mp_input_remove_sections_by_owner(mpctx->input, ctx->name);

    mp_mutex_lock(&clients->lock);

    for (int n = 0; n < clients->num_clients; n++) {
        if (clients->clients[n] == ctx) {
            clients->clients_list_change_ts += 1;
            MP_TARRAY_REMOVE_AT(clients->clients, clients->num_clients, n);
            while (ctx->num_events) {
                talloc_free(ctx->events[ctx->first_event].data);
                ctx->first_event = (ctx->first_event + 1) % ctx->max_events;
                ctx->num_events--;
            }
            mp_msg_log_buffer_destroy(ctx->messages);
            mp_cond_destroy(&ctx->wakeup);
            mp_mutex_destroy(&ctx->wakeup_lock);
            mp_mutex_destroy(&ctx->lock);
            if (ctx->wakeup_pipe[0] != -1) {
                close(ctx->wakeup_pipe[0]);
                close(ctx->wakeup_pipe[1]);
            }
            talloc_free(ctx);
            ctx = NULL;
            break;
        }
    }
    assert(!ctx);

    if (mpctx->is_cli) {
        terminate = false;
    } else {
        // If the last strong mpv_handle got destroyed, destroy the core.
        bool has_strong_ref = false;
        for (int n = 0; n < clients->num_clients; n++)
            has_strong_ref |= !clients->clients[n]->is_weak;
        if (!has_strong_ref)
            terminate = true;

        // Reserve the right to destroy mpctx for us.
        if (clients->have_terminator)
            terminate = false;
        clients->have_terminator |= terminate;
    }

    // mp_shutdown_clients() sleeps to avoid wasting CPU.
    // mp_hook_test_completion() also relies on this a bit.
    mp_wakeup_core(mpctx);

    mp_mutex_unlock(&clients->lock);

    // Note that even if num_clients==0, having set have_terminator keeps mpctx
    // and the core thread alive.
    if (terminate) {
        // Make sure the core stops playing files etc. Being able to lock the
        // dispatch queue requires that the core thread is still active.
        mp_dispatch_lock(mpctx->dispatch);
        mpctx->stop_play = PT_QUIT;
        mp_dispatch_unlock(mpctx->dispatch);

        mp_thread_id playthread;
        mp_dispatch_run(mpctx->dispatch, get_thread_id, &playthread);

        // Ask the core thread to stop.
        mp_mutex_lock(&clients->lock);
        clients->terminate_core_thread = true;
        mp_mutex_unlock(&clients->lock);
        mp_wakeup_core(mpctx);

        // Blocking wait for all clients and core thread to terminate.
        mp_thread_join_id(playthread);

        mp_destroy(mpctx);
    }
}

void mpv_destroy(mpv_handle *ctx)
{
    mp_destroy_client(ctx, false);
}

void mpv_terminate_destroy(mpv_handle *ctx)
{
    mp_destroy_client(ctx, true);
}

// Can be called on the core thread only. Idempotent.
// Also happens to take care of shutting down any async work.
void mp_shutdown_clients(struct MPContext *mpctx)
{
    struct mp_client_api *clients = mpctx->clients;

    // Forcefully abort async work after 2 seconds of waiting.
    double abort_time = mp_time_sec() + 2;

    mp_mutex_lock(&clients->lock);

    // Prevent that new clients can appear.
    clients->shutting_down = true;

    // Wait until we can terminate.
    while (clients->num_clients || mpctx->outstanding_async ||
           !(mpctx->is_cli || clients->terminate_core_thread))
    {
        mp_mutex_unlock(&clients->lock);

        double left = abort_time - mp_time_sec();
        if (left >= 0) {
            mp_set_timeout(mpctx, left);
        } else {
            // Forcefully abort any ongoing async work. This is quite rude and
            // probably not what everyone wants, so it happens only after a
            // timeout.
            abort_async(mpctx, NULL, 0, 0);
        }

        mp_client_broadcast_event(mpctx, MPV_EVENT_SHUTDOWN, NULL);
        mp_wait_events(mpctx);

        mp_mutex_lock(&clients->lock);
    }

    mp_mutex_unlock(&clients->lock);
}

bool mp_is_shutting_down(struct MPContext *mpctx)
{
    struct mp_client_api *clients = mpctx->clients;
    mp_mutex_lock(&clients->lock);
    bool res = clients->shutting_down;
    mp_mutex_unlock(&clients->lock);
    return res;
}

static MP_THREAD_VOID core_thread(void *p)
{
    struct MPContext *mpctx = p;

    mp_thread_set_name("core");

    while (!mpctx->initialized && mpctx->stop_play != PT_QUIT)
        mp_idle(mpctx);

    if (mpctx->initialized)
        mp_play_files(mpctx);

    // This actually waits until all clients are gone before actually
    // destroying mpctx. Actual destruction is done by whatever destroys
    // the last mpv_handle.
    mp_shutdown_clients(mpctx);

    MP_THREAD_RETURN();
}

mpv_handle *mpv_create(void)
{
    struct MPContext *mpctx = mp_create();
    if (!mpctx)
        return NULL;

    m_config_set_profile(mpctx->mconfig, "libmpv", 0);

    mpv_handle *ctx = mp_new_client(mpctx->clients, "main");
    if (!ctx) {
        mp_destroy(mpctx);
        return NULL;
    }

    mp_thread thread;
    if (mp_thread_create(&thread, core_thread, mpctx) != 0) {
        ctx->clients->have_terminator = true; // avoid blocking
        mpv_terminate_destroy(ctx);
        mp_destroy(mpctx);
        return NULL;
    }

    return ctx;
}

mpv_handle *mpv_create_client(mpv_handle *ctx, const char *name)
{
    if (!ctx)
        return mpv_create();
    mpv_handle *new = mp_new_client(ctx->mpctx->clients, name);
    if (new)
        mpv_wait_event(new, 0); // set fuzzy_initialized
    return new;
}

mpv_handle *mpv_create_weak_client(mpv_handle *ctx, const char *name)
{
    mpv_handle *new = mpv_create_client(ctx, name);
    if (new)
        mp_client_set_weak(new);
    return new;
}

int mpv_initialize(mpv_handle *ctx)
{
    lock_core(ctx);
    int res = mp_initialize(ctx->mpctx, NULL) ? MPV_ERROR_INVALID_PARAMETER : 0;
    mp_wakeup_core(ctx->mpctx);
    unlock_core(ctx);
    return res;
}

// set ev->data to a new copy of the original data
// (done only for message types that are broadcast)
static void dup_event_data(struct mpv_event *ev)
{
    switch (ev->event_id) {
    case MPV_EVENT_CLIENT_MESSAGE: {
        struct mpv_event_client_message *src = ev->data;
        struct mpv_event_client_message *msg =
            talloc_zero(NULL, struct mpv_event_client_message);
        for (int n = 0; n < src->num_args; n++) {
            MP_TARRAY_APPEND(msg, msg->args, msg->num_args,
                             talloc_strdup(msg, src->args[n]));
        }
        ev->data = msg;
        break;
    }
    case MPV_EVENT_START_FILE:
        ev->data = talloc_memdup(NULL, ev->data, sizeof(mpv_event_start_file));
        break;
    case MPV_EVENT_END_FILE:
        ev->data = talloc_memdup(NULL, ev->data, sizeof(mpv_event_end_file));
        break;
    default:
        // Doesn't use events with memory allocation.
        if (ev->data)
            abort();
    }
}

// Reserve an entry in the ring buffer. This can be used to guarantee that the
// reply can be made, even if the buffer becomes congested _after_ sending
// the request.
// Returns an error code if the buffer is full.
static int reserve_reply(struct mpv_handle *ctx)
{
    int res = MPV_ERROR_EVENT_QUEUE_FULL;
    mp_mutex_lock(&ctx->lock);
    if (ctx->reserved_events + ctx->num_events < ctx->max_events && !ctx->choked)
    {
        ctx->reserved_events++;
        res = 0;
    }
    mp_mutex_unlock(&ctx->lock);
    return res;
}

static int append_event(struct mpv_handle *ctx, struct mpv_event event, bool copy)
{
    if (ctx->num_events + ctx->reserved_events >= ctx->max_events)
        return -1;
    if (copy)
        dup_event_data(&event);
    ctx->events[(ctx->first_event + ctx->num_events) % ctx->max_events] = event;
    ctx->num_events++;
    wakeup_client(ctx);
    if (event.event_id == MPV_EVENT_SHUTDOWN)
        ctx->event_mask &= ctx->event_mask & ~(1ULL << MPV_EVENT_SHUTDOWN);
    return 0;
}

static int send_event(struct mpv_handle *ctx, struct mpv_event *event, bool copy)
{
    mp_mutex_lock(&ctx->lock);
    uint64_t mask = 1ULL << event->event_id;
    if (ctx->property_event_masks & mask)
        notify_property_events(ctx, event->event_id);
    int r;
    if (!(ctx->event_mask & mask)) {
        r = 0;
    } else if (ctx->choked) {
        r = -1;
    } else {
        r = append_event(ctx, *event, copy);
        if (r < 0) {
            MP_ERR(ctx, "Too many events queued.\n");
            ctx->choked = true;
        }
    }
    mp_mutex_unlock(&ctx->lock);
    return r;
}

// Send a reply; the reply must have been previously reserved with
// reserve_reply (otherwise, use send_event()).
static void send_reply(struct mpv_handle *ctx, uint64_t userdata,
                       struct mpv_event *event)
{
    event->reply_userdata = userdata;
    mp_mutex_lock(&ctx->lock);
    // If this fails, reserve_reply() probably wasn't called.
    assert(ctx->reserved_events > 0);
    ctx->reserved_events--;
    if (append_event(ctx, *event, false) < 0)
        MP_ASSERT_UNREACHABLE();
    mp_mutex_unlock(&ctx->lock);
}

void mp_client_broadcast_event(struct MPContext *mpctx, int event, void *data)
{
    struct mp_client_api *clients = mpctx->clients;

    mp_mutex_lock(&clients->lock);

    for (int n = 0; n < clients->num_clients; n++) {
        struct mpv_event event_data = {
            .event_id = event,
            .data = data,
        };
        send_event(clients->clients[n], &event_data, true);
    }

    mp_mutex_unlock(&clients->lock);
}

// Like mp_client_broadcast_event(), but can be called from any thread.
// Avoid using this.
void mp_client_broadcast_event_external(struct mp_client_api *api, int event,
                                        void *data)
{
    struct MPContext *mpctx = api->mpctx;

    mp_client_broadcast_event(mpctx, event, data);
    mp_wakeup_core(mpctx);
}

// If client_name == NULL, then broadcast and free the event.
int mp_client_send_event(struct MPContext *mpctx, const char *client_name,
                         uint64_t reply_userdata, int event, void *data)
{
    if (!client_name) {
        mp_client_broadcast_event(mpctx, event, data);
        talloc_free(data);
        return 0;
    }

    struct mp_client_api *clients = mpctx->clients;
    int r = 0;

    struct mpv_event event_data = {
        .event_id = event,
        .data = data,
        .reply_userdata = reply_userdata,
    };

    mp_mutex_lock(&clients->lock);

    struct mpv_handle *ctx = find_client(clients, client_name);
    if (ctx) {
        r = send_event(ctx, &event_data, false);
    } else {
        r = -1;
        talloc_free(data);
    }

    mp_mutex_unlock(&clients->lock);

    return r;
}

int mp_client_send_event_dup(struct MPContext *mpctx, const char *client_name,
                             int event, void *data)
{
    if (!client_name) {
        mp_client_broadcast_event(mpctx, event, data);
        return 0;
    }

    struct mpv_event event_data = {
        .event_id = event,
        .data = data,
    };

    dup_event_data(&event_data);
    return mp_client_send_event(mpctx, client_name, 0, event, event_data.data);
}

static const bool deprecated_events[] = {
    [MPV_EVENT_IDLE] = true,
    [MPV_EVENT_TICK] = true,
};

int mpv_request_event(mpv_handle *ctx, mpv_event_id event, int enable)
{
    if (!mpv_event_name(event) || enable < 0 || enable > 1)
        return MPV_ERROR_INVALID_PARAMETER;
    if (event == MPV_EVENT_SHUTDOWN && !enable)
        return MPV_ERROR_INVALID_PARAMETER;
    assert(event < (int)INTERNAL_EVENT_BASE); // excluded above; they have no name
    mp_mutex_lock(&ctx->lock);
    uint64_t bit = 1ULL << event;
    ctx->event_mask = enable ? ctx->event_mask | bit : ctx->event_mask & ~bit;
    if (enable && event < MP_ARRAY_SIZE(deprecated_events) &&
        deprecated_events[event])
    {
        MP_WARN(ctx, "The '%s' event is deprecated and will be removed.\n",
                mpv_event_name(event));
    }
    mp_mutex_unlock(&ctx->lock);
    return 0;
}

// Set waiting_for_hook==true for all possibly pending properties.
static void set_wait_for_hook_flags(mpv_handle *ctx)
{
    for (int n = 0; n < ctx->num_properties; n++) {
        struct observe_property *prop = ctx->properties[n];

        if (prop->value_ret_ts != prop->change_ts)
            prop->waiting_for_hook = true;
    }
}

// Return whether any property still has waiting_for_hook set.
static bool check_for_for_hook_flags(mpv_handle *ctx)
{
    for (int n = 0; n < ctx->num_properties; n++) {
        if (ctx->properties[n]->waiting_for_hook)
            return true;
    }
    return false;
}

mpv_event *mpv_wait_event(mpv_handle *ctx, double timeout)
{
    mpv_event *event = ctx->cur_event;

    mp_mutex_lock(&ctx->lock);

    if (!ctx->fuzzy_initialized)
        mp_wakeup_core(ctx->clients->mpctx);
    ctx->fuzzy_initialized = true;

    if (timeout < 0)
        timeout = 1e20;

    int64_t deadline = mp_time_ns_add(mp_time_ns(), timeout);

    *event = (mpv_event){0};
    talloc_free_children(event);

    while (1) {
        if (ctx->queued_wakeup)
            deadline = 0;
        // Recover from overflow.
        if (ctx->choked && !ctx->num_events) {
            ctx->choked = false;
            event->event_id = MPV_EVENT_QUEUE_OVERFLOW;
            break;
        }
        struct mpv_event *ev =
            ctx->num_events ? &ctx->events[ctx->first_event] : NULL;
        if (ev && ev->event_id == MPV_EVENT_HOOK) {
            // Give old property notifications priority over hooks. This is a
            // guarantee given to clients to simplify their logic. New property
            // changes after this are treated normally, so
            if (!ctx->hook_pending) {
                ctx->hook_pending = true;
                set_wait_for_hook_flags(ctx);
            }
            if (check_for_for_hook_flags(ctx)) {
                ev = NULL; // delay
            } else {
                ctx->hook_pending = false;
            }
        }
        if (ev) {
            *event = *ev;
            ctx->first_event = (ctx->first_event + 1) % ctx->max_events;
            ctx->num_events--;
            talloc_steal(event, event->data);
            break;
        }
        // If there's a changed property, generate change event (never queued).
        if (gen_property_change_event(ctx))
            break;
        // Pop item from message queue, and return as event.
        if (gen_log_message_event(ctx))
            break;
        int r = wait_wakeup(ctx, deadline);
        if (r == ETIMEDOUT)
            break;
    }
    ctx->queued_wakeup = false;

    mp_mutex_unlock(&ctx->lock);

    return event;
}

void mpv_wakeup(mpv_handle *ctx)
{
    mp_mutex_lock(&ctx->lock);
    ctx->queued_wakeup = true;
    wakeup_client(ctx);
    mp_mutex_unlock(&ctx->lock);
}

// map client API types to internal types
static const struct m_option type_conv[] = {
    [MPV_FORMAT_STRING]     = { .type = CONF_TYPE_STRING },
    [MPV_FORMAT_FLAG]       = { .type = CONF_TYPE_FLAG },
    [MPV_FORMAT_INT64]      = { .type = CONF_TYPE_INT64 },
    [MPV_FORMAT_DOUBLE]     = { .type = CONF_TYPE_DOUBLE },
    [MPV_FORMAT_NODE]       = { .type = CONF_TYPE_NODE },
};

static const struct m_option *get_mp_type(mpv_format format)
{
    if ((unsigned)format >= MP_ARRAY_SIZE(type_conv))
        return NULL;
    if (!type_conv[format].type)
        return NULL;
    return &type_conv[format];
}

// for read requests - MPV_FORMAT_OSD_STRING special handling
static const struct m_option *get_mp_type_get(mpv_format format)
{
    if (format == MPV_FORMAT_OSD_STRING)
        format = MPV_FORMAT_STRING; // it's string data, just other semantics
    return get_mp_type(format);
}

// move src->dst, and do implicit conversion if possible (conversions to or
// from strings are handled otherwise)
static bool conv_node_to_format(void *dst, mpv_format dst_fmt, mpv_node *src)
{
    if (dst_fmt == src->format) {
        const struct m_option *type = get_mp_type(dst_fmt);
        memcpy(dst, &src->u, type->type->size);
        return true;
    }
    if (dst_fmt == MPV_FORMAT_DOUBLE && src->format == MPV_FORMAT_INT64) {
        *(double *)dst = src->u.int64;
        return true;
    }
    if (dst_fmt == MPV_FORMAT_INT64 && src->format == MPV_FORMAT_DOUBLE) {
        if (src->u.double_ > (double)INT64_MIN &&
            src->u.double_ < (double)INT64_MAX)
        {
            *(int64_t *)dst = src->u.double_;
            return true;
        }
    }
    return false;
}

void mpv_free_node_contents(mpv_node *node)
{
    static const struct m_option type = { .type = CONF_TYPE_NODE };
    m_option_free(&type, node);
}

int mpv_set_option(mpv_handle *ctx, const char *name, mpv_format format,
                   void *data)
{
    const struct m_option *type = get_mp_type(format);
    if (!type)
        return MPV_ERROR_OPTION_FORMAT;
    struct mpv_node tmp;
    if (format != MPV_FORMAT_NODE) {
        tmp.format = format;
        memcpy(&tmp.u, data, type->type->size);
        data = &tmp;
    }
    lock_core(ctx);
    int err = m_config_set_option_node(ctx->mpctx->mconfig, bstr0(name), data, 0);
    unlock_core(ctx);
    switch (err) {
    case M_OPT_MISSING_PARAM:
    case M_OPT_INVALID:
        return MPV_ERROR_OPTION_ERROR;
    case M_OPT_OUT_OF_RANGE:
        return MPV_ERROR_OPTION_FORMAT;
    case M_OPT_UNKNOWN:
        return MPV_ERROR_OPTION_NOT_FOUND;
    default:
        if (err >= 0)
            return 0;
        return MPV_ERROR_OPTION_ERROR;
    }
}

int mpv_set_option_string(mpv_handle *ctx, const char *name, const char *data)
{
    return mpv_set_option(ctx, name, MPV_FORMAT_STRING, &data);
}

// Run a command in the playback thread.
static void run_locked(mpv_handle *ctx, void (*fn)(void *fn_data), void *fn_data)
{
    mp_dispatch_lock(ctx->mpctx->dispatch);
    fn(fn_data);
    mp_dispatch_unlock(ctx->mpctx->dispatch);
}

// Run a command asynchronously. It's the responsibility of the caller to
// actually send the reply. This helper merely saves a small part of the
// required boilerplate to do so.
//  fn: callback to execute the request
//  fn_data: opaque caller-defined argument for fn. This will be automatically
//           freed with talloc_free(fn_data).
static int run_async(mpv_handle *ctx, void (*fn)(void *fn_data), void *fn_data)
{
    int err = reserve_reply(ctx);
    if (err < 0) {
        talloc_free(fn_data);
        return err;
    }
    mp_dispatch_enqueue(ctx->mpctx->dispatch, fn, fn_data);
    return 0;
}

struct cmd_request {
    struct MPContext *mpctx;
    struct mp_cmd *cmd;
    int status;
    struct mpv_node *res;
    struct mp_waiter completion;
};

static void cmd_complete(struct mp_cmd_ctx *cmd)
{
    struct cmd_request *req = cmd->on_completion_priv;

    req->status = cmd->success ? 0 : MPV_ERROR_COMMAND;
    if (req->res) {
        *req->res = cmd->result;
        cmd->result = (mpv_node){0};
    }

    // Unblock the waiting thread (especially for async commands).
    mp_waiter_wakeup(&req->completion, 0);
}

static int run_client_command(mpv_handle *ctx, struct mp_cmd *cmd, mpv_node *res)
{
    if (!cmd)
        return MPV_ERROR_INVALID_PARAMETER;
    if (!ctx->mpctx->initialized) {
        talloc_free(cmd);
        return MPV_ERROR_UNINITIALIZED;
    }

    cmd->sender = ctx->name;

    struct cmd_request req = {
        .mpctx = ctx->mpctx,
        .cmd = cmd,
        .res = res,
        .completion = MP_WAITER_INITIALIZER,
    };

    bool async = cmd->flags & MP_ASYNC_CMD;

    lock_core(ctx);
    if (async) {
        run_command(ctx->mpctx, cmd, NULL, NULL, NULL);
    } else {
        struct mp_abort_entry *abort = NULL;
        if (cmd->def->can_abort) {
            abort = talloc_zero(NULL, struct mp_abort_entry);
            abort->client = ctx;
        }
        run_command(ctx->mpctx, cmd, abort, cmd_complete, &req);
    }
    unlock_core(ctx);

    if (!async)
        mp_waiter_wait(&req.completion);

    return req.status;
}

int mpv_command(mpv_handle *ctx, const char **args)
{
    return run_client_command(ctx, mp_input_parse_cmd_strv(ctx->log, args), NULL);
}

int mpv_command_node(mpv_handle *ctx, mpv_node *args, mpv_node *result)
{
    struct mpv_node rn = {.format = MPV_FORMAT_NONE};
    int r = run_client_command(ctx, mp_input_parse_cmd_node(ctx->log, args), &rn);
    if (result && r >= 0)
        *result = rn;
    return r;
}

int mpv_command_ret(mpv_handle *ctx, const char **args, mpv_node *result)
{
    struct mpv_node rn = {.format = MPV_FORMAT_NONE};
    int r = run_client_command(ctx, mp_input_parse_cmd_strv(ctx->log, args), &rn);
    if (result && r >= 0)
        *result = rn;
    return r;
}

int mpv_command_string(mpv_handle *ctx, const char *args)
{
    return run_client_command(ctx,
        mp_input_parse_cmd(ctx->mpctx->input, bstr0((char*)args), ctx->name), NULL);
}

struct async_cmd_request {
    struct MPContext *mpctx;
    struct mp_cmd *cmd;
    struct mpv_handle *reply_ctx;
    uint64_t userdata;
};

static void async_cmd_complete(struct mp_cmd_ctx *cmd)
{
    struct async_cmd_request *req = cmd->on_completion_priv;

    struct mpv_event_command *data = talloc_zero(NULL, struct mpv_event_command);
    data->result = cmd->result;
    cmd->result = (mpv_node){0};
    talloc_steal(data, node_get_alloc(&data->result));

    struct mpv_event reply = {
        .event_id = MPV_EVENT_COMMAND_REPLY,
        .data = data,
        .error = cmd->success ? 0 : MPV_ERROR_COMMAND,
    };
    send_reply(req->reply_ctx, req->userdata, &reply);

    talloc_free(req);
}

static void async_cmd_fn(void *data)
{
    struct async_cmd_request *req = data;

    struct mp_cmd *cmd = req->cmd;
    ta_set_parent(cmd, NULL);
    req->cmd = NULL;

    struct mp_abort_entry *abort = NULL;
    if (cmd->def->can_abort) {
        abort = talloc_zero(NULL, struct mp_abort_entry);
        abort->client = req->reply_ctx;
        abort->client_work_type = MPV_EVENT_COMMAND_REPLY;
        abort->client_work_id = req->userdata;
    }

    // This will synchronously or asynchronously call cmd_complete (depending
    // on the command).
    run_command(req->mpctx, cmd, abort, async_cmd_complete, req);
}

static int run_async_cmd(mpv_handle *ctx, uint64_t ud, struct mp_cmd *cmd)
{
    if (!cmd)
        return MPV_ERROR_INVALID_PARAMETER;
    if (!ctx->mpctx->initialized) {
        talloc_free(cmd);
        return MPV_ERROR_UNINITIALIZED;
    }

    cmd->sender = ctx->name;

    struct async_cmd_request *req = talloc_ptrtype(NULL, req);
    *req = (struct async_cmd_request){
        .mpctx = ctx->mpctx,
        .cmd = talloc_steal(req, cmd),
        .reply_ctx = ctx,
        .userdata = ud,
    };
    return run_async(ctx, async_cmd_fn, req);
}

int mpv_command_async(mpv_handle *ctx, uint64_t ud, const char **args)
{
    return run_async_cmd(ctx, ud, mp_input_parse_cmd_strv(ctx->log, args));
}

int mpv_command_node_async(mpv_handle *ctx, uint64_t ud, mpv_node *args)
{
    return run_async_cmd(ctx, ud, mp_input_parse_cmd_node(ctx->log, args));
}

void mpv_abort_async_command(mpv_handle *ctx, uint64_t reply_userdata)
{
    abort_async(ctx->mpctx, ctx, MPV_EVENT_COMMAND_REPLY, reply_userdata);
}

static int translate_property_error(int errc)
{
    switch (errc) {
    case M_PROPERTY_OK:                 return 0;
    case M_PROPERTY_ERROR:              return MPV_ERROR_PROPERTY_ERROR;
    case M_PROPERTY_UNAVAILABLE:        return MPV_ERROR_PROPERTY_UNAVAILABLE;
    case M_PROPERTY_NOT_IMPLEMENTED:    return MPV_ERROR_PROPERTY_ERROR;
    case M_PROPERTY_UNKNOWN:            return MPV_ERROR_PROPERTY_NOT_FOUND;
    case M_PROPERTY_INVALID_FORMAT:     return MPV_ERROR_PROPERTY_FORMAT;
    // shouldn't happen
    default:                            return MPV_ERROR_PROPERTY_ERROR;
    }
}

struct setproperty_request {
    struct MPContext *mpctx;
    const char *name;
    int format;
    void *data;
    int status;
    struct mpv_handle *reply_ctx;
    uint64_t userdata;
};

static void setproperty_fn(void *arg)
{
    struct setproperty_request *req = arg;
    const struct m_option *type = get_mp_type(req->format);

    struct mpv_node *node;
    struct mpv_node tmp;
    if (req->format == MPV_FORMAT_NODE) {
        node = req->data;
    } else {
        tmp.format = req->format;
        memcpy(&tmp.u, req->data, type->type->size);
        node = &tmp;
    }

    int err = mp_property_do(req->name, M_PROPERTY_SET_NODE, node, req->mpctx);

    req->status = translate_property_error(err);

    if (req->reply_ctx) {
        struct mpv_event reply = {
            .event_id = MPV_EVENT_SET_PROPERTY_REPLY,
            .error = req->status,
        };
        send_reply(req->reply_ctx, req->userdata, &reply);
        talloc_free(req);
    }
}

int mpv_set_property(mpv_handle *ctx, const char *name, mpv_format format,
                     void *data)
{
    if (!ctx->mpctx->initialized) {
        int r = mpv_set_option(ctx, name, format, data);
        if (r == MPV_ERROR_OPTION_NOT_FOUND &&
            mp_get_property_id(ctx->mpctx, name) >= 0)
            return MPV_ERROR_PROPERTY_UNAVAILABLE;
        switch (r) {
        case MPV_ERROR_SUCCESS:          return MPV_ERROR_SUCCESS;
        case MPV_ERROR_OPTION_FORMAT:    return MPV_ERROR_PROPERTY_FORMAT;
        case MPV_ERROR_OPTION_NOT_FOUND: return MPV_ERROR_PROPERTY_NOT_FOUND;
        default:                         return MPV_ERROR_PROPERTY_ERROR;
        }
    }
    if (!get_mp_type(format))
        return MPV_ERROR_PROPERTY_FORMAT;

    struct setproperty_request req = {
        .mpctx = ctx->mpctx,
        .name = name,
        .format = format,
        .data = data,
    };
    run_locked(ctx, setproperty_fn, &req);
    return req.status;
}

int mpv_del_property(mpv_handle *ctx, const char *name)
{
    const char* args[] = { "del", name, NULL };
    return mpv_command(ctx, args);
}

int mpv_set_property_string(mpv_handle *ctx, const char *name, const char *data)
{
    return mpv_set_property(ctx, name, MPV_FORMAT_STRING, &data);
}

static void free_prop_set_req(void *ptr)
{
    struct setproperty_request *req = ptr;
    const struct m_option *type = get_mp_type(req->format);
    m_option_free(type, req->data);
}

int mpv_set_property_async(mpv_handle *ctx, uint64_t ud, const char *name,
                           mpv_format format, void *data)
{
    const struct m_option *type = get_mp_type(format);
    if (!ctx->mpctx->initialized)
        return MPV_ERROR_UNINITIALIZED;
    if (!type)
        return MPV_ERROR_PROPERTY_FORMAT;

    struct setproperty_request *req = talloc_ptrtype(NULL, req);
    *req = (struct setproperty_request){
        .mpctx = ctx->mpctx,
        .name = talloc_strdup(req, name),
        .format = format,
        .data = talloc_zero_size(req, type->type->size),
        .reply_ctx = ctx,
        .userdata = ud,
    };

    m_option_copy(type, req->data, data);
    talloc_set_destructor(req, free_prop_set_req);

    return run_async(ctx, setproperty_fn, req);
}

struct getproperty_request {
    struct MPContext *mpctx;
    const char *name;
    mpv_format format;
    void *data;
    int status;
    struct mpv_handle *reply_ctx;
    uint64_t userdata;
};

static void free_prop_data(void *ptr)
{
    struct mpv_event_property *prop = ptr;
    const struct m_option *type = get_mp_type_get(prop->format);
    m_option_free(type, prop->data);
}

static void getproperty_fn(void *arg)
{
    struct getproperty_request *req = arg;
    const struct m_option *type = get_mp_type_get(req->format);

    union m_option_value xdata = m_option_value_default;
    void *data = req->data ? req->data : &xdata;

    int err = -1;
    switch (req->format) {
    case MPV_FORMAT_OSD_STRING:
        err = mp_property_do(req->name, M_PROPERTY_PRINT, data, req->mpctx);
        break;
    case MPV_FORMAT_STRING: {
        char *s = NULL;
        err = mp_property_do(req->name, M_PROPERTY_GET_STRING, &s, req->mpctx);
        if (err == M_PROPERTY_OK)
            *(char **)data = s;
        break;
    }
    case MPV_FORMAT_NODE:
    case MPV_FORMAT_FLAG:
    case MPV_FORMAT_INT64:
    case MPV_FORMAT_DOUBLE: {
        struct mpv_node node = {{0}};
        err = mp_property_do(req->name, M_PROPERTY_GET_NODE, &node, req->mpctx);
        if (err == M_PROPERTY_NOT_IMPLEMENTED) {
            // Go through explicit string conversion. Same reasoning as on the
            // GET code path.
            char *s = NULL;
            err = mp_property_do(req->name, M_PROPERTY_GET_STRING, &s,
                                 req->mpctx);
            if (err != M_PROPERTY_OK)
                break;
            node.format = MPV_FORMAT_STRING;
            node.u.string = s;
        } else if (err <= 0)
            break;
        if (req->format == MPV_FORMAT_NODE) {
            *(struct mpv_node *)data = node;
        } else {
            if (!conv_node_to_format(data, req->format, &node)) {
                err = M_PROPERTY_INVALID_FORMAT;
                mpv_free_node_contents(&node);
            }
        }
        break;
    }
    default:
        abort();
    }

    req->status = translate_property_error(err);

    if (req->reply_ctx) {
        struct mpv_event_property *prop = talloc_ptrtype(NULL, prop);
        *prop = (struct mpv_event_property){
            .name = talloc_steal(prop, (char *)req->name),
            .format = req->format,
            .data = talloc_size(prop, type->type->size),
        };
        // move data
        memcpy(prop->data, &xdata, type->type->size);
        talloc_set_destructor(prop, free_prop_data);
        struct mpv_event reply = {
            .event_id = MPV_EVENT_GET_PROPERTY_REPLY,
            .data = prop,
            .error = req->status,
        };
        send_reply(req->reply_ctx, req->userdata, &reply);
        talloc_free(req);
    }
}

int mpv_get_property(mpv_handle *ctx, const char *name, mpv_format format,
                     void *data)
{
    if (!ctx->mpctx->initialized)
        return MPV_ERROR_UNINITIALIZED;
    if (!data)
        return MPV_ERROR_INVALID_PARAMETER;
    if (!get_mp_type_get(format))
        return MPV_ERROR_PROPERTY_FORMAT;

    struct getproperty_request req = {
        .mpctx = ctx->mpctx,
        .name = name,
        .format = format,
        .data = data,
    };
    run_locked(ctx, getproperty_fn, &req);
    return req.status;
}

char *mpv_get_property_string(mpv_handle *ctx, const char *name)
{
    char *str = NULL;
    mpv_get_property(ctx, name, MPV_FORMAT_STRING, &str);
    return str;
}

char *mpv_get_property_osd_string(mpv_handle *ctx, const char *name)
{
    char *str = NULL;
    mpv_get_property(ctx, name, MPV_FORMAT_OSD_STRING, &str);
    return str;
}

int mpv_get_property_async(mpv_handle *ctx, uint64_t ud, const char *name,
                           mpv_format format)
{
    if (!ctx->mpctx->initialized)
        return MPV_ERROR_UNINITIALIZED;
    if (!get_mp_type_get(format))
        return MPV_ERROR_PROPERTY_FORMAT;

    struct getproperty_request *req = talloc_ptrtype(NULL, req);
    *req = (struct getproperty_request){
        .mpctx = ctx->mpctx,
        .name = talloc_strdup(req, name),
        .format = format,
        .reply_ctx = ctx,
        .userdata = ud,
    };
    return run_async(ctx, getproperty_fn, req);
}

static void property_free(void *p)
{
    struct observe_property *prop = p;

    assert(prop->refcount == 0);

    if (prop->type) {
        m_option_free(prop->type, &prop->value);
        m_option_free(prop->type, &prop->value_ret);
    }
}

int mpv_observe_property(mpv_handle *ctx, uint64_t userdata,
                         const char *name, mpv_format format)
{
    const struct m_option *type = get_mp_type_get(format);
    if (format != MPV_FORMAT_NONE && !type)
        return MPV_ERROR_PROPERTY_FORMAT;
    // Explicitly disallow this, because it would require a special code path.
    if (format == MPV_FORMAT_OSD_STRING)
        return MPV_ERROR_PROPERTY_FORMAT;

    mp_mutex_lock(&ctx->lock);
    assert(!ctx->destroying);
    struct observe_property *prop = talloc_ptrtype(ctx, prop);
    talloc_set_destructor(prop, property_free);
    *prop = (struct observe_property){
        .owner = ctx,
        .name = talloc_strdup(prop, name),
        .id = mp_get_property_id(ctx->mpctx, name),
        .event_mask = mp_get_property_event_mask(name),
        .reply_id = userdata,
        .format = format,
        .type = type,
        .change_ts = 1, // force initial event
        .refcount = 1,
        .value = m_option_value_default,
        .value_ret = m_option_value_default,
    };
    ctx->properties_change_ts += 1;
    MP_TARRAY_APPEND(ctx, ctx->properties, ctx->num_properties, prop);
    ctx->property_event_masks |= prop->event_mask;
    ctx->new_property_events = true;
    ctx->cur_property_index = 0;
    ctx->has_pending_properties = true;
    mp_mutex_unlock(&ctx->lock);
    mp_wakeup_core(ctx->mpctx);
    return 0;
}

int mpv_unobserve_property(mpv_handle *ctx, uint64_t userdata)
{
    mp_mutex_lock(&ctx->lock);
    int count = 0;
    for (int n = ctx->num_properties - 1; n >= 0; n--) {
        struct observe_property *prop = ctx->properties[n];
        // Perform actual removal of the property lazily to avoid creating
        // dangling pointers and such.
        if (prop->reply_id == userdata) {
            prop_unref(prop);
            ctx->properties_change_ts += 1;
            MP_TARRAY_REMOVE_AT(ctx->properties, ctx->num_properties, n);
            ctx->cur_property_index = 0;
            count++;
        }
    }
    mp_mutex_unlock(&ctx->lock);
    return count;
}

static bool property_shared_prefix(const char *a0, const char *b0)
{
    bstr a = bstr0(a0);
    bstr b = bstr0(b0);

    // Treat options and properties as equivalent.
    bstr_eatstart0(&a, "options/");
    bstr_eatstart0(&b, "options/");

    // Compare the potentially-common portion
    if (memcmp(a.start, b.start, MPMIN(a.len, b.len)))
        return false;

    // If lengths were equal, we're done
    if (a.len == b.len)
        return true;

    // Check for a slash in the first non-common byte of the longer string
    if (a.len > b.len)
        return a.start[b.len] == '/';
    else
        return b.start[a.len] == '/';
}

// Broadcast that a property has changed.
void mp_client_property_change(struct MPContext *mpctx, const char *name)
{
    struct mp_client_api *clients = mpctx->clients;
    int id = mp_get_property_id(mpctx, name);
    bool any_pending = false;

    mp_mutex_lock(&clients->lock);

    for (int n = 0; n < clients->num_clients; n++) {
        struct mpv_handle *client = clients->clients[n];
        mp_mutex_lock(&client->lock);
        for (int i = 0; i < client->num_properties; i++) {
            if (client->properties[i]->id == id &&
                property_shared_prefix(name, client->properties[i]->name)) {
                client->properties[i]->change_ts += 1;
                client->has_pending_properties = true;
                any_pending = true;
            }
        }
        mp_mutex_unlock(&client->lock);
    }

    mp_mutex_unlock(&clients->lock);

    // If we're inside mp_dispatch_queue_process(), this will cause the playloop
    // to be re-run (to get mp_client_send_property_changes() called). If we're
    // inside the normal playloop, this does nothing, but the latter function
    // will be called at the end of the playloop anyway.
    if (any_pending)
        mp_dispatch_adjust_timeout(mpctx->dispatch, 0);
}

// Mark properties as changed in reaction to specific events.
// Called with ctx->lock held.
static void notify_property_events(struct mpv_handle *ctx, int event)
{
    uint64_t mask = 1ULL << event;
    for (int i = 0; i < ctx->num_properties; i++) {
        if (ctx->properties[i]->event_mask & mask) {
            ctx->properties[i]->change_ts += 1;
            ctx->has_pending_properties = true;
        }
    }

    // Same as in mp_client_property_change().
    if (ctx->has_pending_properties)
        mp_dispatch_adjust_timeout(ctx->mpctx->dispatch, 0);
}

// Call with ctx->lock held (only). May temporarily drop the lock.
static void send_client_property_changes(struct mpv_handle *ctx)
{
    uint64_t cur_ts = ctx->properties_change_ts;

    ctx->has_pending_properties = false;

    for (int n = 0; n < ctx->num_properties; n++) {
        struct observe_property *prop = ctx->properties[n];

        if (prop->value_ts == prop->change_ts)
            continue;

        bool changed = false;
        if (prop->format) {
            const struct m_option *type = prop->type;
            union m_option_value val = m_option_value_default;
            struct getproperty_request req = {
                .mpctx = ctx->mpctx,
                .name = prop->name,
                .format = prop->format,
                .data = &val,
            };

            // Temporarily unlock and read the property. The very important
            // thing is that property getters can do whatever they want, _and_
            // that they may wait on the client API user thread (if vo_libmpv
            // or similar things are involved).
            prop->refcount += 1; // keep prop alive (esp. prop->name)
            ctx->async_counter += 1; // keep ctx alive
            mp_mutex_unlock(&ctx->lock);
            getproperty_fn(&req);
            mp_mutex_lock(&ctx->lock);
            ctx->async_counter -= 1;
            prop_unref(prop);

            // Set if observed properties was changed or something similar
            // => start over, retry next time.
            if (cur_ts != ctx->properties_change_ts || ctx->destroying) {
                m_option_free(type, &val);
                mp_wakeup_core(ctx->mpctx);
                ctx->has_pending_properties = true;
                break;
            }
            assert(prop->refcount > 0);

            bool val_valid = req.status >= 0;
            changed = prop->value_valid != val_valid;
            if (prop->value_valid && val_valid)
                changed = !equal_mpv_value(&prop->value, &val, prop->format);
            if (prop->value_ts == 0)
                changed = true; // initial event

            prop->value_valid = val_valid;
            if (changed && val_valid) {
                // move val to prop->value
                m_option_free(type, &prop->value);
                memcpy(&prop->value, &val, type->type->size);
                memset(&val, 0, type->type->size);
            }

            m_option_free(prop->type, &val);
        } else {
            changed = true;
        }

        if (prop->waiting_for_hook)
            ctx->new_property_events = true; // make sure to wakeup

        // Avoid retriggering the change event if the property didn't change,
        // and the previous value was actually returned to the client.
        if (!changed && prop->value_ret_ts == prop->value_ts) {
            prop->value_ret_ts = prop->change_ts; // no change => no event
            prop->waiting_for_hook = false;
        } else {
            ctx->new_property_events = true;
        }

        prop->value_ts = prop->change_ts;
    }

    if (ctx->destroying || ctx->new_property_events)
        wakeup_client(ctx);
}

void mp_client_send_property_changes(struct MPContext *mpctx)
{
    struct mp_client_api *clients = mpctx->clients;

    mp_mutex_lock(&clients->lock);
    uint64_t cur_ts = clients->clients_list_change_ts;

    for (int n = 0; n < clients->num_clients; n++) {
        struct mpv_handle *ctx = clients->clients[n];

        mp_mutex_lock(&ctx->lock);
        if (!ctx->has_pending_properties || ctx->destroying) {
            mp_mutex_unlock(&ctx->lock);
            continue;
        }
        // Keep ctx->lock locked (unlock order does not matter).
        mp_mutex_unlock(&clients->lock);
        send_client_property_changes(ctx);
        mp_mutex_unlock(&ctx->lock);
        mp_mutex_lock(&clients->lock);
        if (cur_ts != clients->clients_list_change_ts) {
            // List changed; need to start over. Do it in the next iteration.
            mp_wakeup_core(mpctx);
            break;
        }
    }

    mp_mutex_unlock(&clients->lock);
}

// Set ctx->cur_event to a generated property change event, if there is any
// outstanding property.
static bool gen_property_change_event(struct mpv_handle *ctx)
{
    if (!ctx->mpctx->initialized)
        return false;

    while (1) {
        if (ctx->cur_property_index >= ctx->num_properties) {
            ctx->new_property_events &= ctx->num_properties > 0;
            if (!ctx->new_property_events)
                break;
            ctx->new_property_events = false;
            ctx->cur_property_index = 0;
        }

        struct observe_property *prop = ctx->properties[ctx->cur_property_index++];

        if (prop->value_ts == prop->change_ts &&    // not a stale value?
            prop->value_ret_ts != prop->value_ts)   // other value than last time?
        {
            prop->value_ret_ts = prop->value_ts;
            prop->waiting_for_hook = false;
            prop_unref(ctx->cur_property);
            ctx->cur_property = prop;
            prop->refcount += 1;

            if (prop->value_valid)
                m_option_copy(prop->type, &prop->value_ret, &prop->value);

            ctx->cur_property_event = (struct mpv_event_property){
                .name = prop->name,
                .format = prop->value_valid ? prop->format : 0,
                .data = prop->value_valid ? &prop->value_ret : NULL,
            };
            *ctx->cur_event = (struct mpv_event){
                .event_id = MPV_EVENT_PROPERTY_CHANGE,
                .reply_userdata = prop->reply_id,
                .data = &ctx->cur_property_event,
            };
            return true;
        }
    }

    return false;
}

int mpv_hook_add(mpv_handle *ctx, uint64_t reply_userdata,
                 const char *name, int priority)
{
    lock_core(ctx);
    mp_hook_add(ctx->mpctx, ctx->name, ctx->id, name, reply_userdata, priority);
    unlock_core(ctx);
    return 0;
}

int mpv_hook_continue(mpv_handle *ctx, uint64_t id)
{
    lock_core(ctx);
    int r = mp_hook_continue(ctx->mpctx, ctx->id, id);
    unlock_core(ctx);
    return r;
}

int mpv_load_config_file(mpv_handle *ctx, const char *filename)
{
    lock_core(ctx);
    int r = m_config_parse_config_file(ctx->mpctx->mconfig, ctx->mpctx->global, filename, NULL, 0);
    unlock_core(ctx);
    if (r == 0)
        return MPV_ERROR_INVALID_PARAMETER;
    if (r < 0)
        return MPV_ERROR_OPTION_ERROR;
    return 0;
}

static void msg_wakeup(void *p)
{
    mpv_handle *ctx = p;
    wakeup_client(ctx);
}

// Undocumented: if min_level starts with "silent:", then log messages are not
// returned to the API user, but are stored until logging is enabled normally
// again by calling this without "silent:". (Using a different level will
// flush it, though.)
int mpv_request_log_messages(mpv_handle *ctx, const char *min_level)
{
    bstr blevel = bstr0(min_level);
    bool silent = bstr_eatstart0(&blevel, "silent:");

    int level = -1;
    for (int n = 0; n < MSGL_MAX + 1; n++) {
        if (mp_log_levels[n] && bstr_equals0(blevel, mp_log_levels[n])) {
            level = n;
            break;
        }
    }
    if (bstr_equals0(blevel, "terminal-default"))
        level = MP_LOG_BUFFER_MSGL_TERM;

    if (level < 0 && strcmp(min_level, "no") != 0)
        return MPV_ERROR_INVALID_PARAMETER;

    mp_mutex_lock(&ctx->lock);
    if (level < 0 || level != ctx->messages_level) {
        mp_msg_log_buffer_destroy(ctx->messages);
        ctx->messages = NULL;
    }
    if (level >= 0) {
        if (!ctx->messages) {
            int size = level >= MSGL_V ? 10000 : 1000;
            ctx->messages = mp_msg_log_buffer_new(ctx->mpctx->global, size,
                                                  level, msg_wakeup, ctx);
            ctx->messages_level = level;
        }
        mp_msg_log_buffer_set_silent(ctx->messages, silent);
    }
    wakeup_client(ctx);
    mp_mutex_unlock(&ctx->lock);
    return 0;
}

// Set ctx->cur_event to a generated log message event, if any available.
static bool gen_log_message_event(struct mpv_handle *ctx)
{
    if (ctx->messages) {
        struct mp_log_buffer_entry *msg =
            mp_msg_log_buffer_read(ctx->messages);
        if (msg) {
            struct mpv_event_log_message *cmsg =
                talloc_ptrtype(ctx->cur_event, cmsg);
            talloc_steal(cmsg, msg);
            *cmsg = (struct mpv_event_log_message){
                .prefix = msg->prefix,
                .level = mp_log_levels[msg->level],
                .log_level = mp_mpv_log_levels[msg->level],
                .text = msg->text,
            };
            *ctx->cur_event = (struct mpv_event){
                .event_id = MPV_EVENT_LOG_MESSAGE,
                .data = cmsg,
            };
            return true;
        }
    }
    return false;
}

int mpv_get_wakeup_pipe(mpv_handle *ctx)
{
    mp_mutex_lock(&ctx->wakeup_lock);
    if (ctx->wakeup_pipe[0] == -1) {
        if (mp_make_wakeup_pipe(ctx->wakeup_pipe) >= 0)
            (void)write(ctx->wakeup_pipe[1], &(char){0}, 1);
    }
    int fd = ctx->wakeup_pipe[0];
    mp_mutex_unlock(&ctx->wakeup_lock);
    return fd;
}

unsigned long mpv_client_api_version(void)
{
    return MPV_CLIENT_API_VERSION;
}

int mpv_event_to_node(mpv_node *dst, mpv_event *event)
{
    *dst = (mpv_node){0};

    node_init(dst, MPV_FORMAT_NODE_MAP, NULL);
    node_map_add_string(dst, "event", mpv_event_name(event->event_id));

    if (event->error < 0)
        node_map_add_string(dst, "error", mpv_error_string(event->error));

    if (event->reply_userdata)
        node_map_add_int64(dst, "id", event->reply_userdata);

    switch (event->event_id) {

    case MPV_EVENT_START_FILE: {
        mpv_event_start_file *esf = event->data;

        node_map_add_int64(dst, "playlist_entry_id", esf->playlist_entry_id);
        break;
    }

    case MPV_EVENT_END_FILE: {
        mpv_event_end_file *eef = event->data;

        const char *reason;
        switch (eef->reason) {
        case MPV_END_FILE_REASON_EOF: reason = "eof"; break;
        case MPV_END_FILE_REASON_STOP: reason = "stop"; break;
        case MPV_END_FILE_REASON_QUIT: reason = "quit"; break;
        case MPV_END_FILE_REASON_ERROR: reason = "error"; break;
        case MPV_END_FILE_REASON_REDIRECT: reason = "redirect"; break;
        default:
            reason = "unknown";
        }
        node_map_add_string(dst, "reason", reason);

        node_map_add_int64(dst, "playlist_entry_id", eef->playlist_entry_id);

        if (eef->playlist_insert_id) {
            node_map_add_int64(dst, "playlist_insert_id", eef->playlist_insert_id);
            node_map_add_int64(dst, "playlist_insert_num_entries",
                               eef->playlist_insert_num_entries);
        }

        if (eef->reason == MPV_END_FILE_REASON_ERROR)
            node_map_add_string(dst, "file_error", mpv_error_string(eef->error));
        break;
    }

    case MPV_EVENT_LOG_MESSAGE: {
        mpv_event_log_message *msg = event->data;

        node_map_add_string(dst, "prefix", msg->prefix);
        node_map_add_string(dst, "level",  msg->level);
        node_map_add_string(dst, "text",   msg->text);
        break;
    }

    case MPV_EVENT_CLIENT_MESSAGE: {
        mpv_event_client_message *msg = event->data;

        struct mpv_node *args = node_map_add(dst, "args", MPV_FORMAT_NODE_ARRAY);
        for (int n = 0; n < msg->num_args; n++) {
            struct mpv_node *sn = node_array_add(args, MPV_FORMAT_NONE);
            sn->format = MPV_FORMAT_STRING;
            sn->u.string = (char *)msg->args[n];
        }
        break;
    }

    case MPV_EVENT_PROPERTY_CHANGE: {
        mpv_event_property *prop = event->data;

        node_map_add_string(dst, "name", prop->name);

        switch (prop->format) {
        case MPV_FORMAT_NODE:
            *node_map_add(dst, "data", MPV_FORMAT_NONE) =
                *(struct mpv_node *)prop->data;
            break;
        case MPV_FORMAT_DOUBLE:
            node_map_add_double(dst, "data", *(double *)prop->data);
            break;
        case MPV_FORMAT_FLAG:
            node_map_add_flag(dst, "data", *(int *)prop->data);
            break;
        case MPV_FORMAT_STRING:
            node_map_add_string(dst, "data", *(char **)prop->data);
            break;
        default: ;
        }
        break;
    }

    case MPV_EVENT_COMMAND_REPLY: {
        mpv_event_command *cmd = event->data;

        *node_map_add(dst, "result", MPV_FORMAT_NONE) = cmd->result;
        break;
    }

    case MPV_EVENT_HOOK: {
        mpv_event_hook *hook = event->data;

        node_map_add_int64(dst, "hook_id", hook->id);
        break;
    }

    }
    return 0;
}

static const char *const err_table[] = {
    [-MPV_ERROR_SUCCESS] = "success",
    [-MPV_ERROR_EVENT_QUEUE_FULL] = "event queue full",
    [-MPV_ERROR_NOMEM] = "memory allocation failed",
    [-MPV_ERROR_UNINITIALIZED] = "core not uninitialized",
    [-MPV_ERROR_INVALID_PARAMETER] = "invalid parameter",
    [-MPV_ERROR_OPTION_NOT_FOUND] = "option not found",
    [-MPV_ERROR_OPTION_FORMAT] = "unsupported format for accessing option",
    [-MPV_ERROR_OPTION_ERROR] = "error setting option",
    [-MPV_ERROR_PROPERTY_NOT_FOUND] = "property not found",
    [-MPV_ERROR_PROPERTY_FORMAT] = "unsupported format for accessing property",
    [-MPV_ERROR_PROPERTY_UNAVAILABLE] = "property unavailable",
    [-MPV_ERROR_PROPERTY_ERROR] = "error accessing property",
    [-MPV_ERROR_COMMAND] = "error running command",
    [-MPV_ERROR_LOADING_FAILED] = "loading failed",
    [-MPV_ERROR_AO_INIT_FAILED] = "audio output initialization failed",
    [-MPV_ERROR_VO_INIT_FAILED] = "video output initialization failed",
    [-MPV_ERROR_NOTHING_TO_PLAY] = "no audio or video data played",
    [-MPV_ERROR_UNKNOWN_FORMAT] = "unrecognized file format",
    [-MPV_ERROR_UNSUPPORTED] = "not supported",
    [-MPV_ERROR_NOT_IMPLEMENTED] = "operation not implemented",
    [-MPV_ERROR_GENERIC] = "something happened",
};

const char *mpv_error_string(int error)
{
    error = -error;
    if (error < 0)
        error = 0;
    const char *name = NULL;
    if (error < MP_ARRAY_SIZE(err_table))
        name = err_table[error];
    return name ? name : "unknown error";
}

static const char *const event_table[] = {
    [MPV_EVENT_NONE] = "none",
    [MPV_EVENT_SHUTDOWN] = "shutdown",
    [MPV_EVENT_LOG_MESSAGE] = "log-message",
    [MPV_EVENT_GET_PROPERTY_REPLY] = "get-property-reply",
    [MPV_EVENT_SET_PROPERTY_REPLY] = "set-property-reply",
    [MPV_EVENT_COMMAND_REPLY] = "command-reply",
    [MPV_EVENT_START_FILE] = "start-file",
    [MPV_EVENT_END_FILE] = "end-file",
    [MPV_EVENT_FILE_LOADED] = "file-loaded",
    [MPV_EVENT_IDLE] = "idle",
    [MPV_EVENT_TICK] = "tick",
    [MPV_EVENT_CLIENT_MESSAGE] = "client-message",
    [MPV_EVENT_VIDEO_RECONFIG] = "video-reconfig",
    [MPV_EVENT_AUDIO_RECONFIG] = "audio-reconfig",
    [MPV_EVENT_SEEK] = "seek",
    [MPV_EVENT_PLAYBACK_RESTART] = "playback-restart",
    [MPV_EVENT_PROPERTY_CHANGE] = "property-change",
    [MPV_EVENT_QUEUE_OVERFLOW] = "event-queue-overflow",
    [MPV_EVENT_HOOK] = "hook",
};

const char *mpv_event_name(mpv_event_id event)
{
    if ((unsigned)event >= MP_ARRAY_SIZE(event_table))
        return NULL;
    return event_table[event];
}

void mpv_free(void *data)
{
    talloc_free(data);
}

int64_t mpv_get_time_ns(mpv_handle *ctx)
{
    return mp_time_ns();
}

int64_t mpv_get_time_us(mpv_handle *ctx)
{
    return mp_time_ns() / 1000;
}

#include "video/out/libmpv.h"

static void do_kill(void *ptr)
{
    struct MPContext *mpctx = ptr;

    struct track *track = mpctx->vo_chain ? mpctx->vo_chain->track : NULL;
    uninit_video_out(mpctx);
    if (track) {
        mpctx->error_playing = MPV_ERROR_VO_INIT_FAILED;
        error_on_track(mpctx, track);
    }
}

// Used by vo_libmpv to (a)synchronously uninitialize video.
void kill_video_async(struct mp_client_api *client_api)
{
    struct MPContext *mpctx = client_api->mpctx;
    mp_dispatch_enqueue(mpctx->dispatch, do_kill, mpctx);
}

// Used by vo_libmpv to set the current render context.
bool mp_set_main_render_context(struct mp_client_api *client_api,
                                struct mpv_render_context *ctx, bool active)
{
    assert(ctx);

    mp_mutex_lock(&client_api->lock);
    bool is_set = !!client_api->render_context;
    bool is_same = client_api->render_context == ctx;
    // Can set if it doesn't remove another existing ctx.
    bool res = is_same || !is_set;
    if (res)
        client_api->render_context = active ? ctx : NULL;
    mp_mutex_unlock(&client_api->lock);
    return res;
}

// Used by vo_libmpv. Relies on guarantees by mp_render_context_acquire().
struct mpv_render_context *
mp_client_api_acquire_render_context(struct mp_client_api *ca)
{
    struct mpv_render_context *res = NULL;
    mp_mutex_lock(&ca->lock);
    if (ca->render_context && mp_render_context_acquire(ca->render_context))
        res = ca->render_context;
    mp_mutex_unlock(&ca->lock);
    return res;
}

// stream_cb

struct mp_custom_protocol {
    char *protocol;
    void *user_data;
    mpv_stream_cb_open_ro_fn open_fn;
};

int mpv_stream_cb_add_ro(mpv_handle *ctx, const char *protocol, void *user_data,
                         mpv_stream_cb_open_ro_fn open_fn)
{
    if (!open_fn)
        return MPV_ERROR_INVALID_PARAMETER;

    struct mp_client_api *clients = ctx->clients;
    int r = 0;
    mp_mutex_lock(&clients->lock);
    for (int n = 0; n < clients->num_custom_protocols; n++) {
        struct mp_custom_protocol *proto = &clients->custom_protocols[n];
        if (strcmp(proto->protocol, protocol) == 0) {
            r = MPV_ERROR_INVALID_PARAMETER;
            break;
        }
    }
    if (stream_has_proto(protocol))
        r = MPV_ERROR_INVALID_PARAMETER;
    if (r >= 0) {
        struct mp_custom_protocol proto = {
            .protocol = talloc_strdup(clients, protocol),
            .user_data = user_data,
            .open_fn = open_fn,
        };
        MP_TARRAY_APPEND(clients, clients->custom_protocols,
                         clients->num_custom_protocols, proto);
    }
    mp_mutex_unlock(&clients->lock);
    return r;
}

bool mp_streamcb_lookup(struct mpv_global *g, const char *protocol,
                        void **out_user_data, mpv_stream_cb_open_ro_fn *out_fn)
{
    struct mp_client_api *clients = g->client_api;
    bool found = false;
    mp_mutex_lock(&clients->lock);
    for (int n = 0; n < clients->num_custom_protocols; n++) {
        struct mp_custom_protocol *proto = &clients->custom_protocols[n];
        if (strcmp(proto->protocol, protocol) == 0) {
            *out_user_data = proto->user_data;
            *out_fn = proto->open_fn;
            found = true;
            break;
        }
    }
    mp_mutex_unlock(&clients->lock);
    return found;
}