Welcome to mirror list, hosted at ThFree Co, Russian Federation.

wm_playanim.c « intern « windowmanager « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 003932930eda453364dce40d7b8b0578285b663a (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
/*
 * ***** BEGIN GPL LICENSE BLOCK *****
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
 * All rights reserved.
 *
 * The Original Code is: all of this file.
 *
 * Contributor(s): Campbell Barton
 *
 * ***** END GPL LICENSE BLOCK *****
 */

/** \file blender/windowmanager/intern/wm_playanim.c
 *  \ingroup wm
 *
 * \note This file uses ghost directly and none of the WM definitions.
 *       this could be made into its own module, alongside creator/
 */

#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#ifndef WIN32
#  include <unistd.h>
#  include <sys/times.h>
#  include <sys/wait.h>
#else
#  include <io.h>
#endif
#include "MEM_guardedalloc.h"

#include "PIL_time.h"

#include "BLI_utildefines.h"
#include "BLI_fileops.h"
#include "BLI_listbase.h"
#include "BLI_path_util.h"
#include "BLI_string.h"

#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"

#include "BKE_image.h"

#include "BIF_gl.h"
#include "BIF_glutil.h"

#include "GPU_matrix.h"
#include "GPU_immediate.h"
#include "GPU_immediate_util.h"
#include "GPU_batch.h"
#include "GPU_init_exit.h"

#include "DNA_scene_types.h"
#include "ED_datafiles.h" /* for fonts */
#include "GHOST_C-api.h"
#include "BLF_api.h"

#include "DEG_depsgraph.h"

#include "WM_api.h"  /* only for WM_main_playanim */

#ifdef WITH_AUDASPACE
#  include <AUD_Device.h>
#  include <AUD_Handle.h>
#  include <AUD_Sound.h>
#  include <AUD_Special.h>

static AUD_Sound *source = NULL;
static AUD_Handle *playback_handle = NULL;
static AUD_Handle *scrub_handle = NULL;
static AUD_Device *audio_device = NULL;
#endif

/* simple limiter to avoid flooding memory */
#define USE_FRAME_CACHE_LIMIT
#ifdef USE_FRAME_CACHE_LIMIT
#  define PLAY_FRAME_CACHE_MAX 30
#endif

struct PlayState;
static void playanim_window_zoom(struct PlayState *ps, const float zoom_offset);

typedef struct PlayState {

	/* window and viewport size */
	int win_x, win_y;

	/* current zoom level */
	float zoom;

	/* playback state */
	short direction;
	short next_frame;

	bool  once;
	bool  turbo;
	bool  pingpong;
	bool  noskip;
	bool  indicator;
	bool  sstep;
	bool  wait2;
	bool  stopped;
	bool  go;
	/* waiting for images to load */
	bool  loading;
	/* x/y image flip */
	bool draw_flip[2];

	int fstep;

	/* current picture */
	struct PlayAnimPict *picture;

	/* set once at the start */
	int ibufx, ibufy;
	int fontid;

	/* saves passing args */
	struct ImBuf *curframe_ibuf;

	/* restarts player for file drop */
	char dropped_file[FILE_MAX];

	bool need_frame_update;
	int frame_cursor_x;
} PlayState;

/* for debugging */
#if 0
void print_ps(PlayState *ps)
{
	printf("ps:\n");
	printf("    direction=%d,\n", (int)ps->direction);
	printf("    next=%d,\n", ps->next);
	printf("    once=%d,\n", ps->once);
	printf("    turbo=%d,\n", ps->turbo);
	printf("    pingpong=%d,\n", ps->pingpong);
	printf("    noskip=%d,\n", ps->noskip);
	printf("    sstep=%d,\n", ps->sstep);
	printf("    pause=%d,\n", ps->pause);
	printf("    wait2=%d,\n", ps->wait2);
	printf("    stopped=%d,\n", ps->stopped);
	printf("    go=%d,\n\n", ps->go);
	fflush(stdout);
}
#endif

/* global for window and events */
typedef enum eWS_Qual {
	WS_QUAL_LSHIFT  = (1 << 0),
	WS_QUAL_RSHIFT  = (1 << 1),
	WS_QUAL_SHIFT   = (WS_QUAL_LSHIFT | WS_QUAL_RSHIFT),
	WS_QUAL_LALT    = (1 << 2),
	WS_QUAL_RALT    = (1 << 3),
	WS_QUAL_ALT     = (WS_QUAL_LALT | WS_QUAL_RALT),
	WS_QUAL_LCTRL   = (1 << 4),
	WS_QUAL_RCTRL   = (1 << 5),
	WS_QUAL_CTRL    = (WS_QUAL_LCTRL | WS_QUAL_RCTRL),
	WS_QUAL_LMOUSE  = (1 << 16),
	WS_QUAL_MMOUSE  = (1 << 17),
	WS_QUAL_RMOUSE  = (1 << 18),
	WS_QUAL_MOUSE   = (WS_QUAL_LMOUSE | WS_QUAL_MMOUSE | WS_QUAL_RMOUSE)
} eWS_Qual;

static struct WindowStateGlobal {
	GHOST_SystemHandle ghost_system;
	void *ghost_window;
	Gwn_Context *gwn_context;

	/* events */
	eWS_Qual qual;
} g_WS = {NULL};

static void playanim_window_get_size(int *r_width, int *r_height)
{
	GHOST_RectangleHandle bounds = GHOST_GetClientBounds(g_WS.ghost_window);
	*r_width = GHOST_GetWidthRectangle(bounds);
	*r_height = GHOST_GetHeightRectangle(bounds);
	GHOST_DisposeRectangle(bounds);
}

static void playanim_gl_matrix(void)
{
	/* unified matrix, note it affects offset for drawing */
	/* note! cannot use gpuOrtho2D here because shader ignores. */
	gpuOrtho(0.0f, 1.0f, 0.0f, 1.0f, -1.0, 1.0f);
}

/* implementation */
static void playanim_event_qual_update(void)
{
	int val;

	/* Shift */
	GHOST_GetModifierKeyState(g_WS.ghost_system, GHOST_kModifierKeyLeftShift, &val);
	if (val) g_WS.qual |=  WS_QUAL_LSHIFT;
	else     g_WS.qual &= ~WS_QUAL_LSHIFT;

	GHOST_GetModifierKeyState(g_WS.ghost_system, GHOST_kModifierKeyRightShift, &val);
	if (val) g_WS.qual |=  WS_QUAL_RSHIFT;
	else     g_WS.qual &= ~WS_QUAL_RSHIFT;

	/* Control */
	GHOST_GetModifierKeyState(g_WS.ghost_system, GHOST_kModifierKeyLeftControl, &val);
	if (val) g_WS.qual |=  WS_QUAL_LCTRL;
	else     g_WS.qual &= ~WS_QUAL_LCTRL;

	GHOST_GetModifierKeyState(g_WS.ghost_system, GHOST_kModifierKeyRightControl, &val);
	if (val) g_WS.qual |=  WS_QUAL_RCTRL;
	else     g_WS.qual &= ~WS_QUAL_RCTRL;

	/* Alt */
	GHOST_GetModifierKeyState(g_WS.ghost_system, GHOST_kModifierKeyLeftAlt, &val);
	if (val) g_WS.qual |=  WS_QUAL_LALT;
	else     g_WS.qual &= ~WS_QUAL_LALT;

	GHOST_GetModifierKeyState(g_WS.ghost_system, GHOST_kModifierKeyRightAlt, &val);
	if (val) g_WS.qual |=  WS_QUAL_RALT;
	else     g_WS.qual &= ~WS_QUAL_RALT;
}

typedef struct PlayAnimPict {
	struct PlayAnimPict *next, *prev;
	char *mem;
	int size;
	const char *name;
	struct ImBuf *ibuf;
	struct anim *anim;
	int frame;
	int IB_flags;
} PlayAnimPict;

static struct ListBase picsbase = {NULL, NULL};
/* frames in memory - store them here to for easy deallocation later */
static bool fromdisk = false;
static double ptottime = 0.0, swaptime = 0.04;
#ifdef WITH_AUDASPACE
static double fps_movie;
#endif

#ifdef USE_FRAME_CACHE_LIMIT
static struct ListBase inmempicsbase = {NULL, NULL};
static int added_images = 0;
#endif

static PlayAnimPict *playanim_step(PlayAnimPict *playanim, int step)
{
	if (step > 0) {
		while (step-- && playanim) {
			playanim = playanim->next;
		}
	}
	else if (step < 0) {
		while (step++ && playanim) {
			playanim = playanim->prev;
		}
	}
	return playanim;
}

static int pupdate_time(void)
{
	static double ltime;
	double time;

	time = PIL_check_seconds_timer();

	ptottime += (time - ltime);
	ltime = time;
	return (ptottime < 0);
}

static void playanim_toscreen(PlayState *ps, PlayAnimPict *picture, struct ImBuf *ibuf, int fontid, int fstep)
{
	float offs_x, offs_y;
	float span_x, span_y;

	if (ibuf == NULL) {
		printf("%s: no ibuf for picture '%s'\n", __func__, picture ? picture->name : "<NIL>");
		return;
	}
	if (ibuf->rect == NULL && ibuf->rect_float) {
		IMB_rect_from_float(ibuf);
		imb_freerectfloatImBuf(ibuf);
	}
	if (ibuf->rect == NULL)
		return;

	GHOST_ActivateWindowDrawingContext(g_WS.ghost_window);

	/* size within window */
	span_x = (ps->zoom * ibuf->x) / (float)ps->win_x;
	span_y = (ps->zoom * ibuf->y) / (float)ps->win_y;

	/* offset within window */
	offs_x = 0.5f * (1.0f - span_x);
	offs_y = 0.5f * (1.0f - span_y);

	CLAMP(offs_x, 0.0f, 1.0f);
	CLAMP(offs_y, 0.0f, 1.0f);

	glClearColor(0.1, 0.1, 0.1, 0.0);
	glClear(GL_COLOR_BUFFER_BIT);

	/* checkerboard for case alpha */
	if (ibuf->planes == 32) {
		glEnable(GL_BLEND);
		glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

		imm_draw_box_checker_2d(offs_x, offs_y, offs_x + span_x, offs_y + span_y);
	}

	IMMDrawPixelsTexState state = immDrawPixelsTexSetup(GPU_SHADER_2D_IMAGE_COLOR);

	immDrawPixelsTex(
	        &state,
	        offs_x + (ps->draw_flip[0] ? span_x : 0.0f),
	        offs_y + (ps->draw_flip[1] ? span_y : 0.0f),
	        ibuf->x, ibuf->y, GL_RGBA, GL_UNSIGNED_BYTE, GL_NEAREST,
	        ibuf->rect,
	        ((ps->draw_flip[0] ? -1.0f : 1.0f)) * (ps->zoom / (float)ps->win_x),
	        ((ps->draw_flip[1] ? -1.0f : 1.0f)) * (ps->zoom / (float)ps->win_y),
	        NULL);

	glDisable(GL_BLEND);

	pupdate_time();

	if (picture && (g_WS.qual & (WS_QUAL_SHIFT | WS_QUAL_LMOUSE)) && (fontid != -1)) {
		int sizex, sizey;
		float fsizex_inv, fsizey_inv;
		char str[32 + FILE_MAX];
		BLI_snprintf(str, sizeof(str), "%s | %.2f frames/s", picture->name, fstep / swaptime);

		playanim_window_get_size(&sizex, &sizey);
		fsizex_inv = 1.0f / sizex;
		fsizey_inv = 1.0f / sizey;

		BLF_color4f(fontid, 1.0, 1.0, 1.0, 1.0);
		BLF_enable(fontid, BLF_ASPECT);
		BLF_aspect(fontid, fsizex_inv, fsizey_inv, 1.0f);
		BLF_position(fontid, 10.0f * fsizex_inv, 10.0f * fsizey_inv, 0.0f);
		BLF_draw(fontid, str, sizeof(str));
	}

	if (ps->indicator) {
		float fac = ps->picture->frame / (double)(((PlayAnimPict *)picsbase.last)->frame - ((PlayAnimPict *)picsbase.first)->frame);

		fac = 2.0f * fac - 1.0f;
		gpuPushProjectionMatrix();
		gpuLoadIdentityProjectionMatrix();
		gpuPushMatrix();
		gpuLoadIdentity();

		uint pos = GWN_vertformat_attr_add(immVertexFormat(), "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);

		immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
		immUniformColor3ub(0, 255, 0);

		immBegin(GWN_PRIM_LINES, 2);
		immVertex2f(pos, fac, -1.0f);
		immVertex2f(pos, fac,  1.0f);
		immEnd();

		immUnbindProgram();

		gpuPopMatrix();
		gpuPopProjectionMatrix();
	}

	GHOST_SwapWindowBuffers(g_WS.ghost_window);
}

static void build_pict_list_ex(PlayState *ps, const char *first, int totframes, int fstep, int fontid)
{
	char *mem, filepath[FILE_MAX];
//	short val;
	PlayAnimPict *picture = NULL;
	struct ImBuf *ibuf = NULL;
	struct anim *anim;

	if (IMB_isanim(first)) {
		/* OCIO_TODO: support different input color space */
		anim = IMB_open_anim(first, IB_rect, 0, NULL);
		if (anim) {
			int pic;
			ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
			if (ibuf) {
				playanim_toscreen(ps, NULL, ibuf, fontid, fstep);
				IMB_freeImBuf(ibuf);
			}

			for (pic = 0; pic < IMB_anim_get_duration(anim, IMB_TC_NONE); pic++) {
				picture = (PlayAnimPict *)MEM_callocN(sizeof(PlayAnimPict), "Pict");
				picture->anim = anim;
				picture->frame = pic;
				picture->IB_flags = IB_rect;
				picture->name = BLI_sprintfN("%s : %4.d", first, pic + 1);
				BLI_addtail(&picsbase, picture);
			}
		}
		else {
			printf("couldn't open anim %s\n", first);
		}
	}
	else {
		int count = 0;

		int fp_framenr;
		struct {
			char head[FILE_MAX], tail[FILE_MAX];
			unsigned short digits;
		} fp_decoded;

		BLI_strncpy(filepath, first, sizeof(filepath));
		fp_framenr = BLI_stringdec(filepath, fp_decoded.head, fp_decoded.tail, &fp_decoded.digits);

		pupdate_time();
		ptottime = 1.0;

		/* O_DIRECT
		 *
		 * If set, all reads and writes on the resulting file descriptor will
		 * be performed directly to or from the user program buffer, provided
		 * appropriate size and alignment restrictions are met.  Refer to the
		 * F_SETFL and F_DIOINFO commands in the fcntl(2) manual entry for
		 * information about how to determine the alignment constraints.
		 * O_DIRECT is a Silicon Graphics extension and is only supported on
		 * local EFS and XFS file systems.
		 */

		while (IMB_ispic(filepath) && totframes) {
			bool hasevent;
			size_t size;
			int file;

			file = BLI_open(filepath, O_BINARY | O_RDONLY, 0);
			if (file < 0) {
				/* print errno? */
				return;
			}

			picture = (PlayAnimPict *)MEM_callocN(sizeof(PlayAnimPict), "picture");
			if (picture == NULL) {
				printf("Not enough memory for pict struct '%s'\n", filepath);
				close(file);
				return;
			}
			size = BLI_file_descriptor_size(file);

			if (size < 1) {
				close(file);
				MEM_freeN(picture);
				return;
			}

			picture->size = size;
			picture->IB_flags = IB_rect;

			if (fromdisk == false) {
				mem = (char *)MEM_mallocN(size, "build pic list");
				if (mem == NULL) {
					printf("Couldn't get memory\n");
					close(file);
					MEM_freeN(picture);
					return;
				}

				if (read(file, mem, size) != size) {
					printf("Error while reading %s\n", filepath);
					close(file);
					MEM_freeN(picture);
					MEM_freeN(mem);
					return;
				}
			}
			else {
				mem = NULL;
			}

			picture->mem = mem;
			picture->name = BLI_strdup(filepath);
			picture->frame = count;
			close(file);
			BLI_addtail(&picsbase, picture);
			count++;

			pupdate_time();

			if (ptottime > 1.0) {
				/* OCIO_TODO: support different input color space */
				if (picture->mem) {
					ibuf = IMB_ibImageFromMemory((unsigned char *)picture->mem, picture->size,
					                             picture->IB_flags, NULL, picture->name);
				}
				else {
					ibuf = IMB_loadiffname(picture->name, picture->IB_flags, NULL);
				}
				if (ibuf) {
					playanim_toscreen(ps, picture, ibuf, fontid, fstep);
					IMB_freeImBuf(ibuf);
				}
				pupdate_time();
				ptottime = 0.0;
			}

			/* create a new filepath each time */
			fp_framenr += fstep;
			BLI_stringenc(filepath, fp_decoded.head, fp_decoded.tail, fp_decoded.digits, fp_framenr);

			while ((hasevent = GHOST_ProcessEvents(g_WS.ghost_system, 0))) {
				if (hasevent) {
					GHOST_DispatchEvents(g_WS.ghost_system);
				}
				if (ps->loading == false) {
					return;
				}
			}

			totframes--;
		}
	}
	return;
}

static void build_pict_list(PlayState *ps, const char *first, int totframes, int fstep, int fontid)
{
	ps->loading = true;
	build_pict_list_ex(ps, first, totframes, fstep, fontid);
	ps->loading = false;
}

static void update_sound_fps(void)
{
#ifdef WITH_AUDASPACE
	if (playback_handle) {
		/* swaptime stores the 1.0/fps ratio */
		double speed = 1.0 / (swaptime * fps_movie);

		AUD_Handle_setPitch(playback_handle, speed);
	}
#endif
}

static void tag_change_frame(PlayState *ps, int cx)
{
	ps->need_frame_update = true;
	ps->frame_cursor_x = cx;
}

static void change_frame(PlayState *ps)
{
	if (!ps->need_frame_update) {
		return;
	}

	int sizex, sizey;
	int i, i_last;

	if (BLI_listbase_is_empty(&picsbase)) {
		return;
	}

	playanim_window_get_size(&sizex, &sizey);
	i_last = ((struct PlayAnimPict *)picsbase.last)->frame;
	i = (i_last * ps->frame_cursor_x) / sizex;
	CLAMP(i, 0, i_last);

#ifdef WITH_AUDASPACE
	if (scrub_handle) {
		AUD_Handle_stop(scrub_handle);
		scrub_handle = NULL;
	}

	if (playback_handle) {
		AUD_Status status = AUD_Handle_getStatus(playback_handle);
		if (status != AUD_STATUS_PLAYING) {
			AUD_Handle_stop(playback_handle);
			playback_handle = AUD_Device_play(audio_device, source, 1);
			if (playback_handle) {
				AUD_Handle_setPosition(playback_handle, i / fps_movie);
				scrub_handle = AUD_pauseAfter(playback_handle, 1 / fps_movie);
			}
			update_sound_fps();
		}
		else {
			AUD_Handle_setPosition(playback_handle, i / fps_movie);
			scrub_handle = AUD_pauseAfter(playback_handle, 1 / fps_movie);
		}
	}
	else if (source) {
		playback_handle = AUD_Device_play(audio_device, source, 1);
		if (playback_handle) {
			AUD_Handle_setPosition(playback_handle, i / fps_movie);
			scrub_handle = AUD_pauseAfter(playback_handle, 1 / fps_movie);
		}
		update_sound_fps();
	}
#endif

	ps->picture = BLI_findlink(&picsbase, i);
	BLI_assert(ps->picture != NULL);

	ps->sstep = true;
	ps->wait2 = false;
	ps->next_frame = 0;

	ps->need_frame_update = false;
}

static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr ps_void)
{
	PlayState *ps = (PlayState *)ps_void;
	GHOST_TEventType type = GHOST_GetEventType(evt);
	int val;

	// print_ps(ps);

	playanim_event_qual_update();

	/* convert ghost event into value keyboard or mouse */
	val = ELEM(type, GHOST_kEventKeyDown, GHOST_kEventButtonDown);

	/* first check if we're busy loading files */
	if (ps->loading) {
		switch (type) {
			case GHOST_kEventKeyDown:
			case GHOST_kEventKeyUp:
			{
				GHOST_TEventKeyData *key_data;

				key_data = (GHOST_TEventKeyData *)GHOST_GetEventData(evt);
				switch (key_data->key) {
					case GHOST_kKeyEsc:
						ps->loading = false;
						break;
					default:
						break;
				}
				break;
			}
			default:
				break;
		}
		return 1;
	}


	if (ps->wait2 && ps->stopped) {
		ps->stopped = false;
	}

	if (ps->wait2) {
		pupdate_time();
		ptottime = 0;
	}

	switch (type) {
		case GHOST_kEventKeyDown:
		case GHOST_kEventKeyUp:
		{
			GHOST_TEventKeyData *key_data;

			key_data = (GHOST_TEventKeyData *)GHOST_GetEventData(evt);
			switch (key_data->key) {
				case GHOST_kKeyA:
					if (val) ps->noskip = !ps->noskip;
					break;
				case GHOST_kKeyI:
					if (val) ps->indicator = !ps->indicator;
					break;
				case GHOST_kKeyP:
					if (val) ps->pingpong = !ps->pingpong;
					break;
				case GHOST_kKeyF:
				{
					if (val) {
						int axis = (g_WS.qual & WS_QUAL_SHIFT) ? 1 : 0;
						ps->draw_flip[axis] = !ps->draw_flip[axis];
					}
					break;
				}
				case GHOST_kKey1:
				case GHOST_kKeyNumpad1:
					if (val) {
						swaptime = ps->fstep / 60.0;
						update_sound_fps();
					}
					break;
				case GHOST_kKey2:
				case GHOST_kKeyNumpad2:
					if (val) {
						swaptime = ps->fstep / 50.0;
						update_sound_fps();
					}
					break;
				case GHOST_kKey3:
				case GHOST_kKeyNumpad3:
					if (val) {
						swaptime = ps->fstep / 30.0;
						update_sound_fps();
					}
					break;
				case GHOST_kKey4:
				case GHOST_kKeyNumpad4:
					if (g_WS.qual & WS_QUAL_SHIFT) {
						swaptime = ps->fstep / 24.0;
						update_sound_fps();
					}
					else {
						swaptime = ps->fstep / 25.0;
						update_sound_fps();
					}
					break;
				case GHOST_kKey5:
				case GHOST_kKeyNumpad5:
					if (val) {
						swaptime = ps->fstep / 20.0;
						update_sound_fps();
					}
					break;
				case GHOST_kKey6:
				case GHOST_kKeyNumpad6:
					if (val) {
						swaptime = ps->fstep / 15.0;
						update_sound_fps();
					}
					break;
				case GHOST_kKey7:
				case GHOST_kKeyNumpad7:
					if (val) {
						swaptime = ps->fstep / 12.0;
						update_sound_fps();
					}
					break;
				case GHOST_kKey8:
				case GHOST_kKeyNumpad8:
					if (val) {
						swaptime = ps->fstep / 10.0;
						update_sound_fps();
					}
					break;
				case GHOST_kKey9:
				case GHOST_kKeyNumpad9:
					if (val) {
						swaptime = ps->fstep / 6.0;
						update_sound_fps();
					}
					break;
				case GHOST_kKeyLeftArrow:
					if (val) {
						ps->sstep = true;
						ps->wait2 = false;
						if (g_WS.qual & WS_QUAL_SHIFT) {
							ps->picture = picsbase.first;
							ps->next_frame = 0;
						}
						else {
							ps->next_frame = -1;
						}
					}
					break;
				case GHOST_kKeyDownArrow:
					if (val) {
						ps->wait2 = false;
						if (g_WS.qual & WS_QUAL_SHIFT) {
							ps->next_frame = ps->direction = -1;
						}
						else {
							ps->next_frame = -10;
							ps->sstep = true;
						}
					}
					break;
				case GHOST_kKeyRightArrow:
					if (val) {
						ps->sstep = true;
						ps->wait2 = false;
						if (g_WS.qual & WS_QUAL_SHIFT) {
							ps->picture = picsbase.last;
							ps->next_frame = 0;
						}
						else {
							ps->next_frame = 1;
						}
					}
					break;
				case GHOST_kKeyUpArrow:
					if (val) {
						ps->wait2 = false;
						if (g_WS.qual & WS_QUAL_SHIFT) {
							ps->next_frame = ps->direction = 1;
						}
						else {
							ps->next_frame = 10;
							ps->sstep = true;
						}
					}
					break;

				case GHOST_kKeySlash:
				case GHOST_kKeyNumpadSlash:
					if (val) {
						if (g_WS.qual & WS_QUAL_SHIFT) {
							if (ps->curframe_ibuf)
								printf(" Name: %s | Speed: %.2f frames/s\n",
								       ps->curframe_ibuf->name, ps->fstep / swaptime);
						}
						else {
							swaptime = ps->fstep / 5.0;
							update_sound_fps();
						}
					}
					break;
				case GHOST_kKey0:
				case GHOST_kKeyNumpad0:
					if (val) {
						if (ps->once) {
							ps->once = ps->wait2 = false;
						}
						else {
							ps->picture = NULL;
							ps->once = true;
							ps->wait2 = false;
						}
					}
					break;

				case GHOST_kKeySpace:
					if (val) {
						if (ps->wait2 || ps->sstep) {
							ps->wait2 = ps->sstep = false;
#ifdef WITH_AUDASPACE
							{
								PlayAnimPict *picture = picsbase.first;
								/* TODO - store in ps direct? */
								int i = 0;

								while (picture && picture != ps->picture) {
									i++;
									picture = picture->next;
								}
								if (playback_handle)
									AUD_Handle_stop(playback_handle);
								playback_handle = AUD_Device_play(audio_device, source, 1);
								if (playback_handle)
									AUD_Handle_setPosition(playback_handle, i / fps_movie);
								update_sound_fps();
							}
#endif
						}
						else {
							ps->sstep = true;
							ps->wait2 = true;
#ifdef WITH_AUDASPACE
							if (playback_handle) {
								AUD_Handle_stop(playback_handle);
								playback_handle = NULL;
							}
#endif
						}
					}
					break;
				case GHOST_kKeyEnter:
				case GHOST_kKeyNumpadEnter:
					if (val) {
						ps->wait2 = ps->sstep = false;
#ifdef WITH_AUDASPACE
						{
							PlayAnimPict *picture = picsbase.first;
							/* TODO - store in ps direct? */
							int i = 0;
							while (picture && picture != ps->picture) {
								i++;
								picture = picture->next;
							}
							if (playback_handle)
								AUD_Handle_stop(playback_handle);
							playback_handle = AUD_Device_play(audio_device, source, 1);
							if (playback_handle)
								AUD_Handle_setPosition(playback_handle, i / fps_movie);
							update_sound_fps();
						}
#endif
					}
					break;
				case GHOST_kKeyPeriod:
				case GHOST_kKeyNumpadPeriod:
					if (val) {
						if (ps->sstep) {
							ps->wait2 = false;
						}
						else {
							ps->sstep = true;
							ps->wait2 = !ps->wait2;
#ifdef WITH_AUDASPACE
							if (playback_handle) {
								AUD_Handle_stop(playback_handle);
								playback_handle = NULL;
							}
#endif
						}
					}
					break;
				case GHOST_kKeyEqual:
				case GHOST_kKeyPlus:
				case GHOST_kKeyNumpadPlus:
				{
					if (val == 0) break;
					if (g_WS.qual & WS_QUAL_CTRL) {
						playanim_window_zoom(ps, 1.0f);
					}
					else {
						if (swaptime > ps->fstep / 60.0) {
							swaptime /= 1.1;
							update_sound_fps();
						}
					}
					break;
				}
				case GHOST_kKeyMinus:
				case GHOST_kKeyNumpadMinus:
				{
					if (val == 0) break;
					if (g_WS.qual & WS_QUAL_CTRL) {
						playanim_window_zoom(ps, -1.0f);
					}
					else {
						if (swaptime < ps->fstep / 5.0) {
							swaptime *= 1.1;
							update_sound_fps();
						}
					}
					break;
				}
				case GHOST_kKeyEsc:
					ps->go = false;
					break;
				default:
					break;
			}
			break;
		}
		case GHOST_kEventButtonDown:
		case GHOST_kEventButtonUp:
		{
			GHOST_TEventButtonData *bd = GHOST_GetEventData(evt);
			int cx, cy, sizex, sizey, inside_window;

			GHOST_GetCursorPosition(g_WS.ghost_system, &cx, &cy);
			GHOST_ScreenToClient(g_WS.ghost_window, cx, cy, &cx, &cy);
			playanim_window_get_size(&sizex, &sizey);

			inside_window = (cx >= 0 && cx < sizex && cy >= 0 && cy <= sizey);

			if (bd->button == GHOST_kButtonMaskLeft) {
				if (type == GHOST_kEventButtonDown) {
					if (inside_window) {
						g_WS.qual |= WS_QUAL_LMOUSE;
						tag_change_frame(ps, cx);
					}
				}
				else
					g_WS.qual &= ~WS_QUAL_LMOUSE;
			}
			else if (bd->button == GHOST_kButtonMaskMiddle) {
				if (type == GHOST_kEventButtonDown) {
					if (inside_window)
						g_WS.qual |= WS_QUAL_MMOUSE;
				}
				else
					g_WS.qual &= ~WS_QUAL_MMOUSE;
			}
			else if (bd->button == GHOST_kButtonMaskRight) {
				if (type == GHOST_kEventButtonDown) {
					if (inside_window)
						g_WS.qual |= WS_QUAL_RMOUSE;
				}
				else
					g_WS.qual &= ~WS_QUAL_RMOUSE;
			}
			break;
		}
		case GHOST_kEventCursorMove:
		{
			if (g_WS.qual & WS_QUAL_LMOUSE) {
				GHOST_TEventCursorData *cd = GHOST_GetEventData(evt);
				int cx, cy;

				/* Ignore 'in-between' events, since they can make scrubbing lag.
				 *
				 * Ideally we would keep into the event queue and see if this is the last motion event.
				 * however the API currently doesn't support this. */
				{
					int x_test, y_test;
					GHOST_GetCursorPosition(g_WS.ghost_system, &x_test, &y_test);
					if (x_test != cd->x || y_test != cd->y) {
						/* we're not the last event... skipping */
						break;
					}
				}

				GHOST_ScreenToClient(g_WS.ghost_window, cd->x, cd->y, &cx, &cy);

				tag_change_frame(ps, cx);
			}
			break;
		}
		case GHOST_kEventWindowActivate:
		case GHOST_kEventWindowDeactivate:
		{
			g_WS.qual &= ~WS_QUAL_MOUSE;
			break;
		}
		case GHOST_kEventWindowSize:
		case GHOST_kEventWindowMove:
		{
			float zoomx, zoomy;

			playanim_window_get_size(&ps->win_x, &ps->win_y);
			GHOST_ActivateWindowDrawingContext(g_WS.ghost_window);

			zoomx = (float) ps->win_x / ps->ibufx;
			zoomy = (float) ps->win_y / ps->ibufy;

			/* zoom always show entire image */
			ps->zoom = MIN2(zoomx, zoomy);

			/* zoom steps of 2 for speed */
			ps->zoom = floor(ps->zoom + 0.5f);
			if (ps->zoom < 1.0f) ps->zoom = 1.0f;

			glViewport(0, 0, ps->win_x, ps->win_y);
			glScissor(0, 0, ps->win_x, ps->win_y);

			playanim_gl_matrix();

			ptottime = 0.0;
			playanim_toscreen(ps, ps->picture, ps->curframe_ibuf, ps->fontid, ps->fstep);

			break;
		}
		case GHOST_kEventQuit:
		case GHOST_kEventWindowClose:
		{
			ps->go = false;
			break;
		}
		case GHOST_kEventDraggingDropDone:
		{
			GHOST_TEventDragnDropData *ddd = GHOST_GetEventData(evt);

			if (ddd->dataType == GHOST_kDragnDropTypeFilenames) {
				GHOST_TStringArray *stra = ddd->data;
				int a;

				for (a = 0; a < stra->count; a++) {
					BLI_strncpy(ps->dropped_file, (char *)stra->strings[a], sizeof(ps->dropped_file));
					ps->go = false;
					printf("drop file %s\n", stra->strings[a]);
					break; /* only one drop element supported now */
				}
			}
			break;
		}
		default:
			/* quiet warnings */
			break;
	}

	return 1;
}

static void playanim_window_open(const char *title, int posx, int posy, int sizex, int sizey)
{
	GHOST_GLSettings glsettings = {0};
	GHOST_TUns32 scr_w, scr_h;

	GHOST_GetMainDisplayDimensions(g_WS.ghost_system, &scr_w, &scr_h);

	posy = (scr_h - posy - sizey);

	g_WS.ghost_window = GHOST_CreateWindow(g_WS.ghost_system,
	                                       title,
	                                       posx, posy, sizex, sizey,
	                                       /* could optionally start fullscreen */
	                                       GHOST_kWindowStateNormal,
	                                       GHOST_kDrawingContextTypeOpenGL,
	                                       glsettings);
}

static void playanim_window_zoom(PlayState *ps, const float zoom_offset)
{
	int sizex, sizey;
	/* int ofsx, ofsy; */ /* UNUSED */

	if (ps->zoom + zoom_offset > 0.0f) ps->zoom += zoom_offset;

	// playanim_window_get_position(&ofsx, &ofsy);
	playanim_window_get_size(&sizex, &sizey);
	/* ofsx += sizex / 2; */ /* UNUSED */
	/* ofsy += sizey / 2; */ /* UNUSED */
	sizex = ps->zoom * ps->ibufx;
	sizey = ps->zoom * ps->ibufy;
	/* ofsx -= sizex / 2; */ /* UNUSED */
	/* ofsy -= sizey / 2; */ /* UNUSED */
	// window_set_position(g_WS.ghost_window, sizex, sizey);
	GHOST_SetClientSize(g_WS.ghost_window, sizex, sizey);
}

/* return path for restart */
static char *wm_main_playanim_intern(int argc, const char **argv)
{
	struct ImBuf *ibuf = NULL;
	static char filepath[FILE_MAX];	/* abused to return dropped file path */
	GHOST_TUns32 maxwinx, maxwiny;
	int i;
	/* This was done to disambiguate the name for use under c++. */
	int start_x = 0, start_y = 0;
	int sfra = -1;
	int efra = -1;
	int totblock;

	PlayState ps = {0};

	/* ps.doubleb   = true;*/ /* UNUSED */
	ps.go        = true;
	ps.direction = true;
	ps.next_frame = 1;
	ps.once      = false;
	ps.turbo     = false;
	ps.pingpong  = false;
	ps.noskip    = false;
	ps.sstep     = false;
	ps.wait2     = false;
	ps.stopped   = false;
	ps.loading   = false;
	ps.picture   = NULL;
	ps.indicator = false;
	ps.dropped_file[0] = 0;
	ps.zoom      = 1.0f;
	/* resetmap = false */
	ps.draw_flip[0] = false;
	ps.draw_flip[1] = false;

	ps.fstep     = 1;

	ps.fontid = -1;

	while (argc > 1) {
		if (argv[1][0] == '-') {
			switch (argv[1][1]) {
				case 'm':
					fromdisk = true;
					break;
				case 'p':
					if (argc > 3) {
						start_x = atoi(argv[2]);
						start_y = atoi(argv[3]);
						argc -= 2;
						argv += 2;
					}
					else {
						printf("too few arguments for -p (need 2): skipping\n");
					}
					break;
				case 'f':
					if (argc > 3) {
						double fps = atof(argv[2]);
						double fps_base = atof(argv[3]);
						if (fps == 0.0) {
							fps = 1;
							printf("invalid fps,"
							       "forcing 1\n");
						}
						swaptime = fps_base / fps;
						argc -= 2;
						argv += 2;
					}
					else {
						printf("too few arguments for -f (need 2): skipping\n");
					}
					break;
				case 's':
					sfra = atoi(argv[2]);
					CLAMP(sfra, 1, MAXFRAME);
					argc--;
					argv++;
					break;
				case 'e':
					efra = atoi(argv[2]);
					CLAMP(efra, 1, MAXFRAME);
					argc--;
					argv++;
					break;
				case 'j':
					ps.fstep = atoi(argv[2]);
					CLAMP(ps.fstep, 1, MAXFRAME);
					swaptime *= ps.fstep;
					argc--;
					argv++;
					break;
				default:
					printf("unknown option '%c': skipping\n", argv[1][1]);
					break;
			}
			argc--;
			argv++;
		}
		else {
			break;
		}
	}

	if (argc > 1) {
		BLI_strncpy(filepath, argv[1], sizeof(filepath));
	}
	else {
		printf("%s: no filepath argument given\n", __func__);
		exit(1);
	}

	if (IMB_isanim(filepath)) {
		/* OCIO_TODO: support different input color spaces */
		struct anim *anim;
		anim = IMB_open_anim(filepath, IB_rect, 0, NULL);
		if (anim) {
			ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
			IMB_close_anim(anim);
			anim = NULL;
		}
	}
	else if (!IMB_ispic(filepath)) {
		printf("%s: '%s' not an image file\n", __func__, filepath);
		exit(1);
	}

	if (ibuf == NULL) {
		/* OCIO_TODO: support different input color space */
		ibuf = IMB_loadiffname(filepath, IB_rect, NULL);
	}

	if (ibuf == NULL) {
		printf("%s: '%s' couldn't open\n", __func__, filepath);
		exit(1);
	}

	{

		GHOST_EventConsumerHandle consumer = GHOST_CreateEventConsumer(ghost_event_proc, &ps);

		g_WS.ghost_system = GHOST_CreateSystem();
		GHOST_AddEventConsumer(g_WS.ghost_system, consumer);

		playanim_window_open("Blender:Anim", start_x, start_y, ibuf->x, ibuf->y);

		playanim_gl_matrix();
	}

	GHOST_GetMainDisplayDimensions(g_WS.ghost_system, &maxwinx, &maxwiny);

	//GHOST_ActivateWindowDrawingContext(g_WS.ghost_window);

	/* initialize OpenGL immediate mode */
	g_WS.gwn_context =  GWN_context_create();
	GPU_init();
	immActivate();

	/* initialize the font */
	BLF_init();
	ps.fontid = BLF_load_mem("monospace", (unsigned char *)datatoc_bmonofont_ttf, datatoc_bmonofont_ttf_size);
	BLF_size(ps.fontid, 11, 72);

	ps.ibufx = ibuf->x;
	ps.ibufy = ibuf->y;

	ps.win_x = ps.ibufx;
	ps.win_y = ps.ibufy;

	if (maxwinx % ibuf->x) maxwinx = ibuf->x * (1 + (maxwinx / ibuf->x));
	if (maxwiny % ibuf->y) maxwiny = ibuf->y * (1 + (maxwiny / ibuf->y));


	glClearColor(0.1, 0.1, 0.1, 0.0);
	glClear(GL_COLOR_BUFFER_BIT);

	GHOST_SwapWindowBuffers(g_WS.ghost_window);

	if (sfra == -1 || efra == -1) {
		/* one of the frames was invalid, just use all images */
		sfra = 1;
		efra = MAXFRAME;
	}

	build_pict_list(&ps, filepath, (efra - sfra) + 1, ps.fstep, ps.fontid);

#ifdef WITH_AUDASPACE
	source = AUD_Sound_file(filepath);
	{
		struct anim *anim_movie = ((struct PlayAnimPict *)picsbase.first)->anim;
		if (anim_movie) {
			short frs_sec = 25;
			float frs_sec_base = 1.0;

			IMB_anim_get_fps(anim_movie, &frs_sec, &frs_sec_base, true);

			fps_movie = (double) frs_sec / (double) frs_sec_base;
			/* enforce same fps for movie as sound */
			swaptime = ps.fstep / fps_movie;
		}
	}
#endif

	for (i = 2; i < argc; i++) {
		BLI_strncpy(filepath, argv[i], sizeof(filepath));
		build_pict_list(&ps, filepath, (efra - sfra) + 1, ps.fstep, ps.fontid);
	}

	IMB_freeImBuf(ibuf);
	ibuf = NULL;

	pupdate_time();
	ptottime = 0;

	/* newly added in 2.6x, without this images never get freed */
#define USE_IMB_CACHE

	while (ps.go) {
		if (ps.pingpong)
			ps.direction = -ps.direction;

		if (ps.direction == 1) {
			ps.picture = picsbase.first;
		}
		else {
			ps.picture = picsbase.last;
		}

		if (ps.picture == NULL) {
			printf("couldn't find pictures\n");
			ps.go = false;
		}
		if (ps.pingpong) {
			if (ps.direction == 1) {
				ps.picture = ps.picture->next;
			}
			else {
				ps.picture = ps.picture->prev;
			}
		}
		if (ptottime > 0.0) ptottime = 0.0;

#ifdef WITH_AUDASPACE
		if (playback_handle)
			AUD_Handle_stop(playback_handle);
		playback_handle = AUD_Device_play(audio_device, source, 1);
		update_sound_fps();
#endif

		while (ps.picture) {
			int hasevent;
#ifndef USE_IMB_CACHE
			if (ibuf != NULL && ibuf->ftype == 0) IMB_freeImBuf(ibuf);
#endif
			if (ps.picture->ibuf) {
				ibuf = ps.picture->ibuf;
			}
			else if (ps.picture->anim) {
				ibuf = IMB_anim_absolute(ps.picture->anim, ps.picture->frame, IMB_TC_NONE, IMB_PROXY_NONE);
			}
			else if (ps.picture->mem) {
				/* use correct colorspace here */
				ibuf = IMB_ibImageFromMemory((unsigned char *) ps.picture->mem, ps.picture->size,
				                             ps.picture->IB_flags, NULL, ps.picture->name);
			}
			else {
				/* use correct colorspace here */
				ibuf = IMB_loadiffname(ps.picture->name, ps.picture->IB_flags, NULL);
			}

			if (ibuf) {
#ifdef USE_FRAME_CACHE_LIMIT
				LinkData *node;
#endif

#ifdef USE_IMB_CACHE
				ps.picture->ibuf = ibuf;
#endif

#ifdef USE_FRAME_CACHE_LIMIT
				/* really basic memory conservation scheme. Keep frames in a fifo queue */
				node = inmempicsbase.last;

				while (node && added_images > PLAY_FRAME_CACHE_MAX) {
					PlayAnimPict *pic = node->data;

					if (pic->ibuf && pic->ibuf != ibuf) {
						LinkData *node_tmp;
						IMB_freeImBuf(pic->ibuf);
						pic->ibuf = NULL;
						node_tmp = node->prev;
						BLI_freelinkN(&inmempicsbase, node);
						added_images--;
						node = node_tmp;
					}
					else {
						node = node->prev;
					}
				}

				BLI_addhead(&inmempicsbase, BLI_genericNodeN(ps.picture));
				added_images++;
#endif  /* USE_FRAME_CACHE_LIMIT */

				BLI_strncpy(ibuf->name, ps.picture->name, sizeof(ibuf->name));

				/* why only windows? (from 2.4x) - campbell */
#ifdef _WIN32
				GHOST_SetTitle(g_WS.ghost_window, ps.picture->name);
#endif

				while (pupdate_time()) PIL_sleep_ms(1);
				ptottime -= swaptime;
				playanim_toscreen(&ps, ps.picture, ibuf, ps.fontid, ps.fstep);
			} /* else delete */
			else {
				printf("error: can't play this image type\n");
				exit(0);
			}

			if (ps.once) {
				if (ps.picture->next == NULL) {
					ps.wait2 = true;
				}
				else if (ps.picture->prev == NULL) {
					ps.wait2 = true;
				}
			}

			ps.next_frame = ps.direction;

			while ((hasevent = GHOST_ProcessEvents(g_WS.ghost_system, 0))) {
				GHOST_DispatchEvents(g_WS.ghost_system);
			}
			if (ps.go == false) {
				break;
			}
			change_frame(&ps);
			if (!hasevent) {
				PIL_sleep_ms(1);
			}
			if (ps.wait2) {
				continue;
			}

			ps.wait2 = ps.sstep;

			if (ps.wait2 == false && ps.stopped == false) {
				ps.stopped = true;
			}

			pupdate_time();

			if (ps.picture && ps.next_frame) {
				/* always at least set one step */
				while (ps.picture) {
					ps.picture = playanim_step(ps.picture, ps.next_frame);

					if (ps.once && ps.picture != NULL) {
						if (ps.picture->next == NULL) {
							ps.wait2 = true;
						}
						else if (ps.picture->prev == NULL) {
							ps.wait2 = true;
						}
					}

					if (ps.wait2 || ptottime < swaptime || ps.turbo || ps.noskip) break;
					ptottime -= swaptime;
				}
				if (ps.picture == NULL && ps.sstep) {
					ps.picture = playanim_step(ps.picture, ps.next_frame);
				}
			}
			if (ps.go == false) {
				break;
			}
		}
	}
	while ((ps.picture = BLI_pophead(&picsbase))) {
		if (ps.picture->anim) {
			if ((ps.picture->next == NULL) ||
			    (ps.picture->next->anim != ps.picture->anim))
			{
				IMB_close_anim(ps.picture->anim);
			}
		}

		if (ps.picture->ibuf) {
			IMB_freeImBuf(ps.picture->ibuf);
		}
		if (ps.picture->mem) {
			MEM_freeN(ps.picture->mem);
		}

		MEM_freeN((void *)ps.picture->name);
		MEM_freeN(ps.picture);
	}

	/* cleanup */
#ifndef USE_IMB_CACHE
	if (ibuf) IMB_freeImBuf(ibuf);
#endif

	BLI_freelistN(&picsbase);
	BLI_freelistN(&inmempicsbase);
	added_images = 0;

#ifdef WITH_AUDASPACE
	if (playback_handle) {
		AUD_Handle_stop(playback_handle);
		playback_handle = NULL;
	}
	if (scrub_handle) {
		AUD_Handle_stop(scrub_handle);
		scrub_handle = NULL;
	}
	AUD_Sound_free(source);
	source = NULL;
#endif
	/* we still miss freeing a lot!,
	 * but many areas could skip initialization too for anim play */

	GPU_shader_free_builtin_shaders();

	if (g_WS.gwn_context) {
		GWN_context_active_set(g_WS.gwn_context);
		GWN_context_discard(g_WS.gwn_context);
		g_WS.gwn_context = NULL;
	}

	BLF_exit();

	immDeactivate();
	GPU_exit();

	GHOST_DisposeWindow(g_WS.ghost_system, g_WS.ghost_window);

	/* early exit, IMB and BKE should be exited only in end */
	if (ps.dropped_file[0]) {
		BLI_strncpy(filepath, ps.dropped_file, sizeof(filepath));
		return filepath;
	}

	IMB_exit();
	BKE_images_exit();
	DEG_free_node_types();

	totblock = MEM_get_memory_blocks_in_use();
	if (totblock != 0) {
		/* prints many bAKey, bArgument's which are tricky to fix */
#if 0
		printf("Error Totblock: %d\n", totblock);
		MEM_printmemlist();
#endif
	}

	return NULL;
}


void WM_main_playanim(int argc, const char **argv)
{
	const char *argv_next[2];
	bool looping = true;

#ifdef WITH_AUDASPACE
	{
		AUD_DeviceSpecs specs;

		specs.rate = AUD_RATE_48000;
		specs.format = AUD_FORMAT_S16;
		specs.channels = AUD_CHANNELS_STEREO;

		AUD_initOnce();

		if (!(audio_device = AUD_init("OpenAL", specs, 1024, "Blender"))) {
			audio_device = AUD_init("Null", specs, 0, "Blender");
		}
	}
#endif

	while (looping) {
		const char *filepath = wm_main_playanim_intern(argc, argv);

		if (filepath) {	/* use simple args */
			argv_next[0] = argv[0];
			argv_next[1] = filepath;
			argc = 2;

			/* continue with new args */
			argv = argv_next;
		}
		else {
			looping = false;
		}
	}

#ifdef WITH_AUDASPACE
	AUD_exit(audio_device);
	AUD_exitOnce();
#endif
}