summaryrefslogtreecommitdiffstats
path: root/binding/afm-mediaplayer-binding.c
blob: 25ec708ffdc656ae6fe7e1117bae8302413f3f85 (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
/*
 * Copyright (C) 2017, 2019 Konsulko Group
 * Author: Matt Ranostay <matt.ranostay@konsulko.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <glib.h>
#include <gio/gio.h>
#include <pthread.h>
#include <gst/gst.h>
#include <gst/tag/tag.h>
#include <json-c/json.h>
#include "afm-common.h"

#define AFB_BINDING_VERSION 3
#include <afb/afb-binding.h>

// Flag to enable using GST_STATE_READY instead of GST_STATE_PAUSED to trigger
// Wireplumber policy mechanism. Hopefully temporary.
#define WIREPLUMBER_WORKAROUND

static afb_event_t playlist_event;
static afb_event_t metadata_event;
static GMutex mutex;

static GList *playlist = NULL;
static GList *metadata_track = NULL;
static GList *current_track = NULL;

static const char *signalcomposer_events[] = {
	"event.media.next",
	"event.media.previous",
	"event.media.mode",
	NULL,
};

static json_object *populate_json_metadata(void);

enum {
        LOOP_OFF,
        LOOP_PLAYLIST,
        LOOP_TRACK,
	LOOP_NUM_TYPES,
};

static const char * const LOOP_STATES[LOOP_NUM_TYPES] = {
        "off",
        "playlist",
        "track",
};

typedef struct _CustomData {
	GstElement *playbin, *fake_sink, *audio_sink;
	gboolean playing;
	int loop_state;
	gboolean corked;
	gboolean one_time;
	long int volume;
	gint64 position;
	gint64 duration;
	afb_api_t api;

	/* avrcp */
	gboolean avrcp_connected;
} CustomData;

CustomData data = {
	.volume = 50,
	.corked = FALSE,
	.position = GST_CLOCK_TIME_NONE,
	.duration = GST_CLOCK_TIME_NONE,
};


static int find_loop_state_idx(const char *state)
{
	int idx;

	if (!state)
		return 0;

	for (idx = 0; idx < LOOP_NUM_TYPES; idx++) {
		if (!g_strcmp0(LOOP_STATES[idx], state))
			return idx;
        }

	/* default to 'off' state if invalid */
	return 0;
}

static void mediaplayer_set_role_state(afb_api_t api, int state)
{
	data.playing = (state == GST_STATE_PLAYING);
	gst_element_set_state(data.playbin, state);
}

static json_object *populate_json(struct playlist_item *track)
{
	json_object *jresp = json_object_new_object();
	json_object *jstring = json_object_new_string(track->media_path);
	json_object_object_add(jresp, "path", jstring);

	if (track->title) {
		jstring = json_object_new_string(track->title);
		json_object_object_add(jresp, "title", jstring);
	}

	if (track->album) {
		jstring = json_object_new_string(track->album);
		json_object_object_add(jresp, "album", jstring);
	}

	if (track->artist) {
		jstring = json_object_new_string(track->artist);
		json_object_object_add(jresp, "artist", jstring);
	}

	if (track->genre) {
		jstring = json_object_new_string(track->genre);
		json_object_object_add(jresp, "genre", jstring);
	}

	if (track->duration > 0)
		json_object_object_add(jresp, "duration",
			       json_object_new_int64(track->duration));

	json_object_object_add(jresp, "index",
			       json_object_new_int(track->id));

	if (current_track && current_track->data)
		json_object_object_add(jresp, "selected",
			json_object_new_boolean(track == current_track->data));

	return jresp;
}

static gboolean populate_from_json(struct playlist_item *item, json_object *jdict)
{
	gboolean ret;
	json_object *val = NULL;

	ret = json_object_object_get_ex(jdict, "path", &val);
	if (!ret)
		return ret;
	item->media_path = g_strdup(json_object_get_string(val));

	ret = json_object_object_get_ex(jdict, "type", &val);
	if (!ret) {
		g_free(item->media_path);
		return ret;
	}
	item->media_type = g_strdup(json_object_get_string(val));

	ret = json_object_object_get_ex(jdict, "title", &val);
	if (ret) {
		item->title = g_strdup(json_object_get_string(val));
	}

	ret = json_object_object_get_ex(jdict, "album", &val);
	if (ret) {
		item->album = g_strdup(json_object_get_string(val));
	}

	ret = json_object_object_get_ex(jdict, "artist", &val);
	if (ret) {
		item->artist = g_strdup(json_object_get_string(val));
	}

	ret = json_object_object_get_ex(jdict, "genre", &val);
	if (ret) {
		item->genre = g_strdup(json_object_get_string(val));
	}

	ret = json_object_object_get_ex(jdict, "duration", &val);
	if (ret) {
		item->duration = json_object_get_int64(val);
	}

	return TRUE;
}

static int set_media_uri(struct playlist_item *item, int state)
{
	if (!item || !item->media_path)
	{
		AFB_ERROR("Failed to set media URI: no item provided!");
		return -ENOENT;
	}

	gst_element_set_state(data.playbin, GST_STATE_NULL);
	AFB_DEBUG("GSTREAMER playbin.state = GST_STATE_NULL");

	g_object_set(data.playbin, "uri", item->media_path, NULL);
	AFB_DEBUG("GSTREAMER playbin.uri = %s", item->media_path);

	data.position = GST_CLOCK_TIME_NONE;
	data.duration = GST_CLOCK_TIME_NONE;

	if (state) {
		g_object_set(data.playbin, "audio-sink", data.audio_sink, NULL);
		AFB_DEBUG("GSTREAMER playbin.audio-sink = pipewire-sink");

		if (!data.playing)
			mediaplayer_set_role_state(data.api, GST_STATE_PLAYING);
		else
			gst_element_set_state(data.playbin, GST_STATE_PLAYING);

		AFB_DEBUG("GSTREAMER playbin.state = GST_STATE_PLAYING");
	} else {
		g_object_set(data.playbin, "audio-sink", data.fake_sink, NULL);
		AFB_DEBUG("GSTREAMER playbin.audio-sink = fake-sink");

#ifdef WIREPLUMBER_WORKAROUND
		gst_element_set_state(data.playbin, GST_STATE_READY);
		AFB_DEBUG("GSTREAMER playbin.state = GST_STATE_READY");
#else
		gst_element_set_state(data.playbin, GST_STATE_PAUSED);
		AFB_DEBUG("GSTREAMER playbin.state = GST_STATE_PAUSED");
#endif
	}

	double vol = (double) data.volume / 100.0;
	g_object_set(data.playbin, "volume", vol, NULL);
	AFB_DEBUG("GSTREAMER playbin.volume = %f", vol);

	return 0;
}


static int in_list(gconstpointer item, gconstpointer list)
{
	return g_strcmp0(((struct playlist_item *) item)->media_path,
			 ((struct playlist_item *) list)->media_path);
}

static void populate_playlist(json_object *jquery)
{
	int i, idx = 0;
	GList *list = g_list_last(playlist);

	if (list && list->data) {
		struct playlist_item *item = list->data;
		idx = item->id + 1;
	}

	for (i = 0; i < json_object_array_length(jquery); i++) {
		json_object *jdict = json_object_array_get_idx(jquery, i);
		struct playlist_item *item = g_malloc0(sizeof(*item));
		int ret;

		if (item == NULL)
			break;

		ret = populate_from_json(item, jdict);
		if (!ret || g_list_find_custom(playlist, item, in_list)) {
			g_free_playlist_item(item);
			continue;
		}

		item->id = idx++;
		playlist = g_list_append(playlist, item);
	}

	if (current_track == NULL) {
		current_track = g_list_first(playlist);
		if (current_track && current_track->data)
			set_media_uri(current_track->data, FALSE);
	}
}

static json_object *populate_json_playlist(json_object *jresp)
{
	GList *l;
	json_object *jarray = json_object_new_array();

	for (l = playlist; l; l = l->next) {
		struct playlist_item *track = l->data;

		if (track && !g_strcmp0(track->media_type, "audio")) {
			json_object *item = populate_json(track);
			json_object_array_add(jarray, item);
		}
	}

	json_object_object_add(jresp, "list", jarray);

	return jresp;
}

static void audio_playlist(afb_req_t request)
{
	const char *value = afb_req_value(request, "list");
	json_object *jresp = NULL;

	g_mutex_lock(&mutex);

	if (value) {
		json_object *jquery;

		if (playlist) {
			g_list_free_full(playlist, g_free_playlist_item);
			playlist = NULL;
		}

		jquery = json_tokener_parse(value);
		populate_playlist(jquery);

		if (playlist == NULL)
			afb_req_fail(request, "failed", "invalid playlist");
		else
			afb_req_success(request, NULL, NULL);

		json_object_put(jquery);
	} else {
		jresp = json_object_new_object();
		jresp = populate_json_playlist(jresp);

		afb_req_success(request, jresp, "Playlist results");
	}

	g_mutex_unlock(&mutex);
}

static int seek_stream(const char *value, int cmd)
{
	gint64 position, current = 0;

	if (value == NULL)
		return -EINVAL;

	position = strtoll(value, NULL, 10);

	if (cmd != SEEK_CMD) {
		gst_element_query_position (data.playbin, GST_FORMAT_TIME, &current);
		position = (current / GST_MSECOND) + (FASTFORWARD_CMD ? position : -position);
	}

	if (position < 0)
		position = 0;

	if (data.duration > 0 && position > data.duration)
		position = data.duration;

	return gst_element_seek_simple(data.playbin, GST_FORMAT_TIME,
				GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT,
				position * GST_MSECOND);
}

static int seek_track(int cmd)
{
	GList *item = NULL;
	int ret;

	if (current_track == NULL)
		return -EINVAL;

	item = (cmd == NEXT_CMD) ? current_track->next : current_track->prev;

	if (item == NULL) {
		if (cmd == PREVIOUS_CMD) {
			seek_stream("0", SEEK_CMD);
			return 0;
		}
		return -EINVAL;
	}

	ret = set_media_uri(item->data, TRUE);
	if (ret < 0)
		return -EINVAL;

	current_track = item;

	return 0;
}

static void avrcp_controls(afb_req_t request)
{
	const char *value = afb_req_value(request, "value");
	const char *action = NULL;
	afb_api_t api = afb_req_get_api(request);
	int cmd, ret;
	json_object *response, *jresp = NULL;

	if (!g_strcmp0(value, "connect") || !g_strcmp0(value, "disconnect")) {
		action = value;
	} else {
		cmd = get_command_index(value);

		if (cmd < 0) {
			afb_req_fail(request, "failed", "unknown command");
			return;
		}

		action = avrcp_control_commands[cmd];
		if (!action) {
			afb_req_fail(request, "failed", "command not supported");
			return;
		}
	}

	jresp = json_object_new_object();
	json_object_object_add(jresp, "action", json_object_new_string(action));

	ret = afb_api_call_sync(api, "Bluetooth-Manager",
			        "avrcp_controls", jresp, &response, NULL, NULL);
	json_object_put(response);

	if (ret < 0) {
		afb_req_fail(request, "failed", "cannot request avrcp_control");
		return;
	}

	afb_req_success(request, NULL, NULL);
}

static void gstreamer_controls(afb_req_t request)
{
	const char *value = afb_req_value(request, "value");
	const char *position = afb_req_value(request, "position");
	int cmd = get_command_index(value);
	afb_api_t api = afb_req_get_api(request);
	json_object *jresp = NULL;

	errno = 0;

	switch (cmd) {
	case PLAY_CMD: {
		GstElement *obj = NULL;
		g_object_get(data.playbin, "audio-sink", &obj, NULL);

		if (obj == data.fake_sink) {
			if (current_track && current_track->data)
				set_media_uri(current_track->data, TRUE);
			else {
				afb_req_fail(request, "failed", "No playlist");
				return;
			}
		} else {
			g_object_set(data.playbin, "audio-sink", data.audio_sink, NULL);
			AFB_DEBUG("GSTREAMER playbin.audio-sink = pipewire-sink");

			mediaplayer_set_role_state(api, GST_STATE_PLAYING);
			AFB_DEBUG("GSTREAMER playbin.state = GST_STATE_PLAYING");
		}

		jresp = json_object_new_object();
		json_object_object_add(jresp, "playing", json_object_new_boolean(TRUE));
		break;
	}
	case PAUSE_CMD:
#ifdef WIREPLUMBER_WORKAROUND
		mediaplayer_set_role_state(api, GST_STATE_READY);
		AFB_DEBUG("GSTREAMER playbin.state = GST_STATE_READY");
#else
		mediaplayer_set_role_state(api, GST_STATE_PAUSED);
		AFB_DEBUG("GSTREAMER playbin.state = GST_STATE_PAUSED");
#endif
		data.playing = FALSE;

		/* metadata event */
		jresp = populate_json_metadata();
		json_object_object_add(jresp, "status",
				       json_object_new_string("stopped"));
		afb_event_push(metadata_event, jresp);

		/* status returned */
		jresp = json_object_new_object();
		json_object_object_add(jresp, "playing", json_object_new_boolean(FALSE));
		break;
	case PREVIOUS_CMD:
	case NEXT_CMD:
		seek_track(cmd);
		break;
	case SEEK_CMD:
	case FASTFORWARD_CMD:
	case REWIND_CMD:
		seek_stream(position, cmd);
		break;
	case PICKTRACK_CMD: {
		const char *parameter = afb_req_value(request, "index");
		long int idx = strtol(parameter, NULL, 10);
		GList *list = NULL;

		if (idx == 0 && errno) {
			afb_req_fail(request, "failed", "invalid index");
			return;
		}

		list = find_media_index(playlist, idx);
		if (list != NULL) {
			struct playlist_item *item = list->data;
			set_media_uri(item, TRUE);
			current_track = list;
		} else {
			afb_req_fail(request, "failed", "couldn't find index");
			return;
		}

		break;
	}
	case VOLUME_CMD: {
		const char *parameter = afb_req_value(request, "volume");
		long int volume;

		if (!parameter) {
			afb_req_fail(request, "failed", "invalid volume");
			return;
		}

		volume = strtol(parameter, NULL, 10);
		errno = 0;

		if (volume == 0 && errno) {
			afb_req_fail(request, "failed", "invalid volume");
			return;
		}

		if (volume < 0)
			volume = 0;
		if (volume > 100)
			volume = 100;

		g_object_set(data.playbin, "volume", (double) volume / 100.0, NULL);
		AFB_DEBUG("GSTREAMER volume = %f", (double) volume / 100.0);

		data.volume = volume;

		break;
	}
	case LOOP_CMD:
		data.loop_state =
			find_loop_state_idx(afb_req_value(request, "state"));
		break;
	case STOP_CMD:
		mediaplayer_set_role_state(api, GST_STATE_NULL);
		AFB_DEBUG("GSTREAMER playbin.state = GST_STATE_NULL");
		break;
	default:
		afb_req_fail(request, "failed", "unknown command");
		return;
	}

	afb_req_success(request, jresp, NULL);
}

/* @value can be one of the following values:
 *   play     - go to playing transition
 *   pause    - go to pause transition
 *   previous - skip to previous track
 *   next     - skip to the next track
 *   seek     - go to position (in milliseconds)
 *
 *   fast-forward - skip forward in milliseconds
 *   rewind       - skip backward in milliseconds
 *
 *   pick-track   - select track via index number
 *   volume       - set volume between 0 - 100%
 *   loop         - set looping of playlist (true or false)
 */

static void controls(afb_req_t request)
{
	const char *value = afb_req_value(request, "value");

	if (!value) {
		afb_req_fail(request, "failed", "no value was passed");
		return;
	}

	g_mutex_lock(&mutex);
	if (data.avrcp_connected || !g_strcmp0(value, "connect")) {
		g_mutex_unlock(&mutex);
		avrcp_controls(request);
		return;
	}

	gstreamer_controls(request);
	g_mutex_unlock(&mutex);
}

static GstSample *parse_album(GstTagList *tags, gchar *tag_type)
{
	GstSample *sample = NULL;
	int num = gst_tag_list_get_tag_size(tags, tag_type);
	guint i;

	for (i = 0; i < num ; i++) {
		const GValue *value;
		GstStructure *caps;
		int type;

		value = gst_tag_list_get_value_index(tags, tag_type, i);
		if (value == NULL)
			break;

		sample = gst_value_get_sample(value);
		caps = gst_caps_get_structure(gst_sample_get_caps(sample), 0);
		gst_structure_get_enum(caps, "image-type",
				       GST_TYPE_TAG_IMAGE_TYPE, &type);

		if (type == GST_TAG_IMAGE_TYPE_FRONT_COVER)
			break;
	}

	return sample;
}

static gchar *get_album_art(GstTagList *tags)
{
	GstSample *sample;

	sample = parse_album(tags, GST_TAG_IMAGE);
	if (!sample)
		sample = parse_album(tags, GST_TAG_PREVIEW_IMAGE);

	if (sample) {
		GstBuffer *buffer = gst_sample_get_buffer(sample);
		GstMapInfo map;
		gchar *data, *mime_type, *image;

		if (!gst_buffer_map (buffer, &map, GST_MAP_READ))
			return NULL;

		image = g_base64_encode(map.data, map.size);
		mime_type = g_content_type_guess(NULL, map.data, map.size, NULL);

		data = g_strconcat("data:", mime_type, ";base64,", image, NULL);

		g_free(image);
		g_free(mime_type);
		gst_buffer_unmap(buffer, &map);

		return data;
	}

	return NULL;
}

static json_object *populate_json_metadata(void)
{
	struct playlist_item *track;
	json_object *jresp, *metadata;

	if (current_track == NULL || current_track->data == NULL)
		return NULL;

	track = current_track->data;
	metadata = populate_json(track);
	jresp = json_object_new_object();

	if (data.duration != GST_CLOCK_TIME_NONE)
		json_object_object_add(metadata, "duration",
			       json_object_new_int64(data.duration / GST_MSECOND));

	if (data.position != GST_CLOCK_TIME_NONE)
		json_object_object_add(jresp, "position",
			       json_object_new_int64(data.position / GST_MSECOND));

	json_object_object_add(jresp, "volume",
			       json_object_new_int64(data.volume));

	json_object_object_add(jresp, "track", metadata);

	return jresp;
}

static int bluetooth_subscribe(afb_api_t api)
{
	json_object *response, *query;
	int ret;

	query = json_object_new_object();
	json_object_object_add(query, "value", json_object_new_string("media"));

	ret = afb_api_call_sync(api, "Bluetooth-Manager", "subscribe", query, &response, NULL, NULL);
	json_object_put(response);

	if (ret < 0) {
		AFB_ERROR("Cannot subscribe to Bluetooth media event");
		return ret;
	}

	return 0;
}

static void subscribe(afb_req_t request)
{
	const char *value = afb_req_value(request, "value");

	if (!strcasecmp(value, "metadata")) {
		afb_api_t api = afb_req_get_api(request);
		json_object *jresp = NULL;

		afb_req_subscribe(request, metadata_event);
		afb_req_success(request, NULL, NULL);

		g_mutex_lock(&mutex);
		jresp = populate_json_metadata();
		g_mutex_unlock(&mutex);

		afb_event_push(metadata_event, jresp);

		bluetooth_subscribe(api);

		return;
	} else if (!strcasecmp(value, "playlist")) {
		json_object *jresp = json_object_new_object();

		afb_req_subscribe(request, playlist_event);
		afb_req_success(request, NULL, NULL);

		g_mutex_lock(&mutex);
		jresp = populate_json_playlist(jresp);
		g_mutex_unlock(&mutex);

		afb_event_push(playlist_event, jresp);

		return;
	}

	afb_req_fail(request, "failed", "Invalid event");
}

static void unsubscribe(afb_req_t request)
{
	const char *value = afb_req_value(request, "value");

	if (!strcasecmp(value, "metadata")) {
		afb_req_unsubscribe(request, metadata_event);
		afb_req_success(request, NULL, NULL);
		return;
	} else if (!strcasecmp(value, "playlist")) {
		afb_req_unsubscribe(request, playlist_event);
		afb_req_success(request, NULL, NULL);
		return;
	}

	afb_req_fail(request, "failed", "Invalid event");
}

static gboolean handle_message(GstBus *bus, GstMessage *msg, CustomData *data)
{
	switch (GST_MESSAGE_TYPE (msg)) {
	case GST_MESSAGE_EOS: {
		int ret;

		g_mutex_lock(&mutex);

		data->position = GST_CLOCK_TIME_NONE;
		data->duration = GST_CLOCK_TIME_NONE;

		if (data->loop_state == LOOP_TRACK)
			ret = seek_stream("0", SEEK_CMD);
		else
			ret = seek_track(NEXT_CMD);

		if (ret < 0) {
			int loop_playlist = data->loop_state == LOOP_PLAYLIST;

			if (!loop_playlist) {
				mediaplayer_set_role_state(data->api, GST_STATE_NULL);
				data->one_time = TRUE;
			}

			current_track = playlist;

			if (current_track != NULL)
				set_media_uri(current_track->data, loop_playlist);
		}

		g_mutex_unlock(&mutex);
		break;
	}
	case GST_MESSAGE_DURATION:
		data->duration = GST_CLOCK_TIME_NONE;
		break;
	case GST_MESSAGE_TAG: {
		GstTagList *tags = NULL;
		gchar *image = NULL;
		json_object *jresp, *jobj;

		// TODO: This will get triggered multipl times due to gstreamer
		// pipeline, and should be fixed in the future to stop spurious
		// events
		gst_message_parse_tag(msg, &tags);

		if (!tags)
			break;

		image = get_album_art(tags);

		jobj = json_object_new_object();
		json_object_object_add(jobj, "image",
			json_object_new_string(image ? image : ""));

		g_free(image);

		jresp = json_object_new_object();
		json_object_object_add(jresp, "track", jobj);

		afb_event_push(metadata_event, jresp);

		gst_tag_list_unref(tags);

		break;
	}
	case GST_MESSAGE_REQUEST_STATE: {
		GstState state;

		gst_message_parse_request_state(msg, &state);

		g_mutex_lock(&mutex);

		if (state == GST_STATE_PAUSED) {
			data->corked = TRUE;
		} else if (state == GST_STATE_PLAYING) {
			data->corked = FALSE;
		}

		g_mutex_unlock(&mutex);

		break;
	}
	default:
		break;
	}

	return TRUE;
}

static gboolean position_event(CustomData *data)
{
	struct playlist_item *track;
	json_object *jresp = NULL, *metadata;

	g_mutex_lock(&mutex);

	if (data->one_time) {
		data->one_time = FALSE;

		json_object *jresp = json_object_new_object();
		json_object_object_add(jresp, "status",
				       json_object_new_string("stopped"));
		g_mutex_unlock(&mutex);

		afb_event_push(metadata_event, jresp);
		return TRUE;
	}

	if (!data->playing || current_track == NULL) {
		g_mutex_unlock(&mutex);
		return TRUE;
	}

	track = current_track->data;
	metadata = populate_json(track);
	jresp = json_object_new_object();

	if (!GST_CLOCK_TIME_IS_VALID(data->duration))
		gst_element_query_duration(data->playbin,
					GST_FORMAT_TIME, &data->duration);

	gst_element_query_position(data->playbin,
					GST_FORMAT_TIME, &data->position);

	json_object_object_add(metadata, "duration",
			       json_object_new_int64(data->duration / GST_MSECOND));
	json_object_object_add(jresp, "position",
			       json_object_new_int64(data->position / GST_MSECOND));
	json_object_object_add(jresp, "status",
			       json_object_new_string("playing"));

	if (metadata_track != current_track)
		metadata_track = current_track;

	json_object_object_add(jresp, "track", metadata);

	g_mutex_unlock(&mutex);

        afb_event_push(metadata_event, jresp);

	return TRUE;
}

static void gstreamer_init(afb_api_t api)
{
	GstBus *bus;
	json_object *response;
	int ret;

	gst_init(NULL, NULL);

	data.api = api;
	data.playbin = gst_element_factory_make("playbin", "playbin");
	if (!data.playbin) {
		AFB_ERROR("GST Pipeline: Failed to create 'playbin' element!");
		exit(1);
	}

	data.fake_sink = gst_element_factory_make("fakesink", NULL);
	if (!data.fake_sink)
	{
		AFB_ERROR("GST Pipeline: Failed to create 'fakesink' element!");
		exit(1);
	}

	data.audio_sink = gst_element_factory_make("pwaudiosink", NULL);
	if (!data.audio_sink)
	{
		AFB_ERROR("GST Pipeline: Failed to create 'pwaudiosink' element!");
		exit(1);
	}
	gst_util_set_object_arg(G_OBJECT(data.audio_sink),
				"stream-properties", "p,media.role=Multimedia");

	g_object_set(data.playbin, "audio-sink", data.fake_sink, NULL);
	AFB_DEBUG("GSTREAMER playbin.audio-sink = fake-sink");

#ifdef WIREPLUMBER_WORKAROUND
	gst_element_set_state(data.playbin, GST_STATE_READY);
	AFB_DEBUG("GSTREAMER playbin.state = GST_STATE_READY");
#else
	gst_element_set_state(data.playbin, GST_STATE_PAUSED);
	AFB_DEBUG("GSTREAMER playbin.state = GST_STATE_PAUSED");
#endif

	bus = gst_element_get_bus(data.playbin);
	gst_bus_add_watch(bus, (GstBusFunc) handle_message, &data);
	g_timeout_add_seconds(1, (GSourceFunc) position_event, &data);

	ret = afb_api_call_sync(api, "mediascanner", "media_result", NULL, &response, NULL, NULL);
	if (!ret) {
		json_object *val = NULL;
		gboolean ret;

		ret = json_object_object_get_ex(response, "Media", &val);

		if (ret)
			populate_playlist(val);
	}
	json_object_put(response);
}

static void onevent(afb_api_t api, const char *event, struct json_object *object)
{
	json_object *jresp = NULL;

	if (!g_strcmp0(event, "mediascanner/media_added")) {
		json_object *val = NULL;
		gboolean ret;

		g_mutex_lock(&mutex);

		ret = json_object_object_get_ex(object, "Media", &val);
		if (ret)
			populate_playlist(val);

	} else if (!g_strcmp0(event, "mediascanner/media_removed")) {
		json_object *val = NULL;
		const char *path;
		GList *l = playlist;
		gboolean ret;

		ret = json_object_object_get_ex(object, "Path", &val);
		if (!ret)
			return;

		path = json_object_get_string(val);

		g_mutex_lock(&mutex);

		while (l) {
			struct playlist_item *item = l->data;

			l = l->next;

			if (!strncasecmp(path, item->media_path, strlen(path))) {
				if (current_track && current_track->data == item) {
					current_track = NULL;
					data.one_time = TRUE;
					mediaplayer_set_role_state(api, GST_STATE_NULL);
					AFB_DEBUG("GSTREAMER playbin.state = GST_STATE_NULL");
				}

				playlist = g_list_remove(playlist, item);
				g_free_playlist_item(item);
			}
		}

		if (current_track == NULL)
			current_track = g_list_first(playlist);
	} else if (!g_ascii_strcasecmp(event, "Bluetooth-Manager/media")) {
		json_object *val;

		g_mutex_lock(&mutex);

		if (json_object_object_get_ex(object, "connected", &val)) {
			gboolean state = json_object_get_boolean(val);
			data.avrcp_connected = state;

			if (state) {
#ifdef WIREPLUMBER_WORKAROUND
				mediaplayer_set_role_state(api, GST_STATE_READY);
#else
				mediaplayer_set_role_state(api, GST_STATE_PAUSED);
#endif
			} else {
				json_object *jresp = populate_json_metadata();

				if (!jresp)
					jresp = json_object_new_object();

				json_object_object_add(jresp, "status",
				       json_object_new_string("stopped"));
				afb_event_push(metadata_event, jresp);
			}
		}

		g_mutex_unlock(&mutex);

		json_object_get(object);
		afb_event_push(metadata_event, object);

		return;
	} else if (g_str_has_prefix(event, "signal-composer/")) {
		json_object *tmp = NULL;
		const char *uid;
		const char *value;
		int corked;

		json_object_object_get_ex(object, "uid", &tmp);
		if (tmp == NULL)
			return;

		uid = json_object_get_string(tmp);
		if (strncmp(uid, "event.media.", 12))
			return;

		g_mutex_lock(&mutex);
		corked = data.corked;
		g_mutex_unlock(&mutex);

		// drop events if we are in corked state
		if (corked)
			return;

		json_object_object_get_ex(object, "value", &tmp);
		if (tmp == NULL)
			return;

		value = json_object_get_string(tmp);
		if (strncmp(value, "true", 4))
			return;

		if (!strcmp(uid, "event.media.next")) {
			if(data.playing) {
				g_mutex_lock(&mutex);
				if (!data.avrcp_connected)
					seek_track(NEXT_CMD);
				else
					AFB_WARNING("currently '%s' not supported for AVRCP controls", uid);
				g_mutex_unlock(&mutex);

				json_object_get(object);
				afb_event_push(metadata_event, object);
			}
		} else if (!strcmp(uid, "event.media.previous")) {
			if(data.playing) {
				g_mutex_lock(&mutex);
				if (!data.avrcp_connected)
					seek_track(PREVIOUS_CMD);
				else
					AFB_WARNING("currently %s not supported for AVRCP controls", uid);
				g_mutex_unlock(&mutex);

				json_object_get(object);
				afb_event_push(metadata_event, object);
			}
		} else if (!strcmp(uid, "event.media.mode")) {
			// Do nothing ATM
		} else {
			AFB_WARNING("Unhandled signal-composer uid '%s'", uid);
		}
		return;
	} else {
		AFB_ERROR("Invalid event: %s", event);
		return;
	}

	// Fall through for mediascanner events

	jresp = json_object_new_object();
	jresp = populate_json_playlist(jresp);

	g_mutex_unlock(&mutex);

        afb_event_push(playlist_event, jresp);

	// send metadata out after event
	g_mutex_lock(&mutex);
	jresp = populate_json_metadata();
	g_mutex_unlock(&mutex);

	if (jresp)
		afb_event_push(metadata_event, jresp);
}

void *gstreamer_loop_thread(void *ptr)
{
	g_main_loop_run(g_main_loop_new(NULL, FALSE));

	return NULL;
}

static int init(afb_api_t api)
{
	pthread_t thread_id;
	json_object *response, *query;
	int ret;

	ret = afb_daemon_require_api("mediascanner", 1);
	if (ret < 0) {
		AFB_ERROR("Cannot request mediascanner");
		return ret;
	}

	query = json_object_new_object();
	json_object_object_add(query, "value", json_object_new_string("media_added"));

	ret = afb_api_call_sync(api, "mediascanner", "subscribe", query, &response, NULL, NULL);
	json_object_put(response);

	if (ret < 0) {
		AFB_ERROR("Cannot subscribe to mediascanner media_added event");
		return ret;
	}

	query = json_object_new_object();
	json_object_object_add(query, "value", json_object_new_string("media_removed"));

	ret = afb_api_call_sync(api, "mediascanner", "subscribe", query, &response, NULL, NULL);
	json_object_put(response);

	if (ret < 0) {
		AFB_ERROR("Cannot subscribe to mediascanner media_remove event");
		return ret;
	}

	ret = afb_daemon_require_api("signal-composer", 1);
	if (ret) {
		AFB_WARNING("unable to initialize signal-composer binding");
	} else {
		const char **tmp = signalcomposer_events;
		json_object *args = json_object_new_object();
		json_object *signals = json_object_new_array();

		while (*tmp) {
			json_object_array_add(signals, json_object_new_string(*tmp++));
		}
		json_object_object_add(args, "signal", signals);
		if(json_object_array_length(signals)) {
			afb_api_call_sync(api, "signal-composer", "subscribe",
					  args, NULL, NULL, NULL);
		} else {
			json_object_put(args);
		}
	}

	metadata_event = afb_daemon_make_event("metadata");
	playlist_event = afb_daemon_make_event("playlist");

	gstreamer_init(api);

	return pthread_create(&thread_id, NULL, gstreamer_loop_thread, NULL);
}

static const afb_verb_t binding_verbs[] = {
	{ .verb = "playlist",     .callback = audio_playlist, .info = "Get/set playlist" },
	{ .verb = "controls",     .callback = controls,       .info = "Audio controls" },
	{ .verb = "subscribe",    .callback = subscribe,      .info = "Subscribe to GStreamer events" },
	{ .verb = "unsubscribe",  .callback = unsubscribe,    .info = "Unsubscribe to GStreamer events" },
	{ }
};

/*
 * binder API description
 */
const afb_binding_t afbBindingV3 = {
	.api = "mediaplayer",
	.specification = "Mediaplayer API",
	.verbs = binding_verbs,
	.onevent = onevent,
	.init = init,
};
O(requested_num, "%s %s %s request is already queued", appid.c_str(), role.c_str(), area.c_str()); return REQ_REJECTED; } WMRequest req = WMRequest(appid, role, area, task); unsigned new_req = g_app_list.addRequest(req); *req_num = new_req; g_app_list.reqDump(); HMI_SEQ_DEBUG(current, "%s start sequence with %s, %s", appid.c_str(), role.c_str(), area.c_str()); return WMError::SUCCESS; } WMError WindowManager::doTransition(unsigned req_num) { HMI_SEQ_DEBUG(req_num, "check policy"); WMError ret = this->checkPolicy(req_num); if (ret != WMError::SUCCESS) { return ret; } HMI_SEQ_DEBUG(req_num, "Start transition."); ret = this->startTransition(req_num); return ret; } WMError WindowManager::checkPolicy(unsigned req_num) { /* * Check Policy */ // get current trigger bool found = false; bool split = false; WMError ret = WMError::LAYOUT_CHANGE_FAIL; auto trigger = g_app_list.getRequest(req_num, &found); if (!found) { ret = WMError::NO_ENTRY; return ret; } std::string req_area = trigger.area; // >>>> Compatible with current window manager until policy manager coming if (trigger.task == Task::TASK_ALLOCATE) { HMI_SEQ_DEBUG(req_num, "Check split or not"); const char *msg = this->check_surface_exist(trigger.role.c_str()); if (msg) { HMI_SEQ_ERROR(req_num, msg); ret = WMError::LAYOUT_CHANGE_FAIL; return ret; } auto const &surface_id = this->lookup_id(trigger.role.c_str()); auto o_state = *this->layers.get_layout_state(*surface_id); struct LayoutState &state = *o_state; unsigned curernt_sid = state.main; split = this->can_split(state, *surface_id); if (split) { HMI_SEQ_DEBUG(req_num, "Split happens"); // Get current visible role std::string add_role = this->lookup_name(state.main).value(); // Set next area std::string add_area = std::string(kNameLayoutSplit) + "." + std::string(kNameAreaMain); // Change request area req_area = std::string(kNameLayoutSplit) + "." + std::string(kNameAreaSub); HMI_SEQ_NOTICE(req_num, "Change request area from %s to %s, because split happens", trigger.area.c_str(), req_area.c_str()); // set another action std::string add_name = g_app_list.getAppID(curernt_sid, add_role, &found); if (!found) { HMI_SEQ_ERROR(req_num, "Couldn't widhdraw with surfaceID : %d", curernt_sid); ret = WMError::NOT_REGISTERED; return ret; } HMI_SEQ_INFO(req_num, "Additional split app %s, role: %s, area: %s", add_name.c_str(), add_role.c_str(), add_area.c_str()); // Set split action bool end_draw_finished = false; WMAction split_action{ add_name, add_role, add_area, TaskVisible::VISIBLE, end_draw_finished}; WMError ret = g_app_list.setAction(req_num, split_action); if (ret != WMError::SUCCESS) { HMI_SEQ_ERROR(req_num, "Failed to set action"); return ret; } g_app_list.reqDump(); } } else { HMI_SEQ_DEBUG(req_num, "split doesn't happen"); } // Set invisible task(Remove if policy manager finish) ret = this->setInvisibleTask(trigger.role, split); if(ret != WMError::SUCCESS) { HMI_SEQ_ERROR(req_num, "Failed to set invisible task: %s", errorDescription(ret)); return ret; } /* get new status from Policy Manager */ HMI_SEQ_NOTICE(req_num, "ATM, Policy manager does't exist, then set WMAction as is"); if(trigger.role == "homescreen") { // TODO : Remove when Policy Manager completed HMI_SEQ_NOTICE(req_num, "Hack. This process will be removed. Change HomeScreen code!!"); req_area = "fullscreen"; } TaskVisible task_visible = (trigger.task == Task::TASK_ALLOCATE) ? TaskVisible::VISIBLE : TaskVisible::INVISIBLE; ret = g_app_list.setAction(req_num, trigger.appid, trigger.role, req_area, task_visible); g_app_list.reqDump(); return ret; } WMError WindowManager::startTransition(unsigned req_num) { bool sync_draw_happen = false; bool found = false; WMError ret = WMError::SUCCESS; auto actions = g_app_list.getActions(req_num, &found); if (!found) { ret = WMError::NO_ENTRY; HMI_SEQ_ERROR(req_num, "Window Manager bug :%s : Action is not set", errorDescription(ret)); return ret; } for (const auto &action : actions) { if (action.visible != TaskVisible::INVISIBLE) { sync_draw_happen = true; // TODO: application requests by old role, // so convert role new to old for emitting event std::string old_role = this->rolenew2old[action.role]; this->emit_syncdraw(old_role, action.area); /* TODO: emit event for app not subscriber if(g_app_list.contains(y.appid)) g_app_list.lookUpClient(y.appid)->emit_syncdraw(y.role, y.area); */ } } if (sync_draw_happen) { this->setTimer(); } else { // deactivate only, no syncDraw // Make it deactivate here for (const auto &x : actions) { if (g_app_list.contains(x.appid)) { auto client = g_app_list.lookUpClient(x.appid); this->deactivate(client->surfaceID(x.role)); } } ret = NO_LAYOUT_CHANGE; } return ret; } WMError WindowManager::setInvisibleTask(const std::string &role, bool split) { unsigned req_num = g_app_list.currentRequestNumber(); HMI_SEQ_DEBUG(req_num, "set current visible app to invisible task"); // This task is copied from original actiavete surface const char *drawing_name = this->rolenew2old[role].c_str(); auto const &surface_id = this->lookup_id(role.c_str()); auto layer_id = this->layers.get_layer_id(*surface_id); auto o_state = *this->layers.get_layout_state(*surface_id); struct LayoutState &state = *o_state; std::string add_name, add_role; std::string add_area = ""; int surface; TaskVisible task_visible = TaskVisible::INVISIBLE; bool end_draw_finished = true; bool found = false; for (auto const &l : this->layers.mapping) { if (l.second.layer_id <= *layer_id) { continue; } HMI_DEBUG("wm", "debug: main %d , sub : %d", l.second.state.main, l.second.state.sub); if (l.second.state.main != -1) { //this->deactivate(l.second.state.main); surface = l.second.state.main; add_role = *this->id_alloc.lookup(surface); add_name = g_app_list.getAppID(surface, add_role, &found); if(!found){ return WMError::NOT_REGISTERED; } HMI_SEQ_INFO(req_num, "Invisible %s", add_name.c_str()); WMAction act{add_name, add_role, add_area, task_visible, end_draw_finished}; g_app_list.setAction(req_num, act); l.second.state.main = -1; } if (l.second.state.sub != -1) { //this->deactivate(l.second.state.sub); surface = l.second.state.sub; add_role = *this->id_alloc.lookup(surface); add_name = g_app_list.getAppID(surface, add_role, &found); if (!found) { return WMError::NOT_REGISTERED; } HMI_SEQ_INFO(req_num, "Invisible %s", add_name.c_str()); WMAction act{add_name, add_role, add_area, task_visible, end_draw_finished}; g_app_list.setAction(req_num, act); l.second.state.sub = -1; } } // change current state here, but this is hack auto layer = this->layers.get_layer(*layer_id); if (state.main == -1) { HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal); } else { if (0 != strcmp(drawing_name, "HomeScreen")) { if (split) { if (state.sub != *surface_id) { if (state.sub != -1) { //this->deactivate(state.sub); WMAction deact_sub; deact_sub.role = std::move(*this->id_alloc.lookup(state.sub)); deact_sub.area = add_area; deact_sub.appid = g_app_list.getAppID(state.sub, deact_sub.role, &found); if (!found) { HMI_SEQ_ERROR(req_num, "App doesn't exist for role : %s", deact_sub.role.c_str()); return WMError::NOT_REGISTERED; } deact_sub.visible = task_visible; deact_sub.end_draw_finished = end_draw_finished; HMI_SEQ_DEBUG(req_num, "Set invisible task for %s", deact_sub.appid.c_str()); g_app_list.setAction(req_num, deact_sub); } } //state = LayoutState{state.main, *surface_id}; } else { HMI_DEBUG("wm", "Layout: %s", kNameLayoutNormal); //this->surface_set_layout(*surface_id); if (state.main != *surface_id) { // this->deactivate(state.main); WMAction deact_main; deact_main.role = std::move(*this->id_alloc.lookup(state.main)); ; deact_main.area = add_area; deact_main.appid = g_app_list.getAppID(state.main, deact_main.role, &found); if (!found) { HMI_SEQ_DEBUG(req_num, "sub surface ddoesn't exist"); return WMError::NOT_REGISTERED; } deact_main.visible = task_visible; deact_main.end_draw_finished = end_draw_finished; HMI_SEQ_DEBUG(req_num, "sub surface doesn't exist"); g_app_list.setAction(req_num, deact_main); } if (state.sub != -1) { if (state.sub != *surface_id) { //this->deactivate(state.sub); WMAction deact_sub; deact_sub.role = std::move(*this->id_alloc.lookup(state.sub)); ; deact_sub.area = add_area; deact_sub.appid = g_app_list.getAppID(state.sub, deact_sub.role, &found); if (!found) { HMI_SEQ_DEBUG(req_num, "sub surface ddoesn't exist"); return WMError::NOT_REGISTERED; } deact_sub.visible = task_visible; deact_sub.end_draw_finished = end_draw_finished; HMI_SEQ_DEBUG(req_num, "sub surface doesn't exist"); g_app_list.setAction(req_num, deact_sub); } } //state = LayoutState{*surface_id}; } } } return WMError::SUCCESS; } WMError WindowManager::doEndDraw(unsigned req_num) { // get actions bool found; auto actions = g_app_list.getActions(req_num, &found); WMError ret = WMError::SUCCESS; if (!found) { ret = WMError::NO_ENTRY; return ret; } HMI_SEQ_INFO(req_num, "do endDraw"); // layout change and make it visible for (const auto &act : actions) { // layout change if(!g_app_list.contains(act.appid)){ ret = WMError::NOT_REGISTERED; } ret = this->layoutChange(act); if(ret != WMError::SUCCESS) { HMI_SEQ_WARNING(req_num, "Failed to manipulate surfaces while state change : %s", errorDescription(ret)); return ret; } ret = this->visibilityChange(act); if (ret != WMError::SUCCESS) { HMI_SEQ_WARNING(req_num, "Failed to manipulate surfaces while state change : %s", errorDescription(ret)); return ret; } HMI_SEQ_DEBUG(req_num, "visible %s", act.role.c_str()); //this->lm_enddraw(act.role.c_str()); } // Change current state this->changeCurrentState(req_num); HMI_SEQ_INFO(req_num, "emit flushDraw"); for(const auto &act_flush : actions) { if(act_flush.visible != TaskVisible::INVISIBLE) { // TODO: application requests by old role, // so convert role new to old for emitting event std::string old_role = this->rolenew2old[act_flush.role]; this->emit_flushdraw(old_role.c_str()); } } return ret; } WMError WindowManager::layoutChange(const WMAction &action) { if (action.visible == TaskVisible::INVISIBLE) { // Visibility is not change -> no redraw is required return WMError::SUCCESS; } auto client = g_app_list.lookUpClient(action.appid); unsigned surface = client->surfaceID(action.role); if (surface == 0) { HMI_SEQ_ERROR(g_app_list.currentRequestNumber(), "client doesn't have surface with role(%s)", action.role.c_str()); return WMError::NOT_REGISTERED; } // Layout Manager WMError ret = this->setSurfaceSize(surface, action.area); return ret; } WMError WindowManager::visibilityChange(const WMAction &action) { HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Change visibility"); if(!g_app_list.contains(action.appid)){ return WMError::NOT_REGISTERED; } auto client = g_app_list.lookUpClient(action.appid); unsigned surface = client->surfaceID(action.role); if(surface == 0) { HMI_SEQ_ERROR(g_app_list.currentRequestNumber(), "client doesn't have surface with role(%s)", action.role.c_str()); return WMError::NOT_REGISTERED; } if (action.visible != TaskVisible::INVISIBLE) { this->activate(surface); // Layout Manager task } else { this->deactivate(surface); // Layout Manager task } return WMError::SUCCESS; } WMError WindowManager::setSurfaceSize(unsigned surface, const std::string &area) { this->surface_set_layout(surface, area); return WMError::SUCCESS; } WMError WindowManager::changeCurrentState(unsigned req_num) { HMI_SEQ_DEBUG(req_num, "Change current layout state"); bool trigger_found = false, action_found = false; auto trigger = g_app_list.getRequest(req_num, &trigger_found); auto actions = g_app_list.getActions(req_num, &action_found); if (!trigger_found || !action_found) { HMI_SEQ_ERROR(req_num, "Action not found"); return WMError::LAYOUT_CHANGE_FAIL; } // Layout state reset struct LayoutState reset_state{-1, -1}; HMI_SEQ_DEBUG(req_num,"Reset layout state"); for (const auto &action : actions) { if(!g_app_list.contains(action.appid)){ return WMError::NOT_REGISTERED; } auto client = g_app_list.lookUpClient(action.appid); auto pCurState = *this->layers.get_layout_state((int)client->surfaceID(action.role)); if(pCurState == nullptr) { HMI_SEQ_ERROR(req_num, "Counldn't find current status"); continue; } pCurState->main = reset_state.main; pCurState->sub = reset_state.sub; } HMI_SEQ_DEBUG(req_num, "Change state"); for (const auto &action : actions) { auto client = g_app_list.lookUpClient(action.appid); auto pLayerCurState = *this->layers.get_layout_state((int)client->surfaceID(action.role)); if (pLayerCurState == nullptr) { HMI_SEQ_ERROR(req_num, "Counldn't find current status"); continue; } int surface = -1; if (action.visible != TaskVisible::INVISIBLE) { surface = (int)client->surfaceID(action.role); HMI_SEQ_INFO(req_num, "Change %s surface : %d, state visible area : %s", action.role.c_str(), surface, action.area.c_str()); // visible == true -> layout changes if(action.area == "normal.full" || action.area == "split.main") { pLayerCurState->main = surface; } else if (action.area == "split.sub") { pLayerCurState->sub = surface; } else { // normalfull pLayerCurState->main = surface; } } } return WMError::SUCCESS; } void WindowManager::emitScreenUpdated(unsigned req_num) { // Get visible apps HMI_SEQ_DEBUG(req_num, "emit screen updated"); bool found = false; auto actions = g_app_list.getActions(req_num, &found); // create json object json_object *j = json_object_new_object(); json_object *jarray = json_object_new_array(); for(const auto& action: actions) { if(action.visible != TaskVisible::INVISIBLE) { json_object_array_add(jarray, json_object_new_string(action.appid.c_str())); } } json_object_object_add(j, kKeyIds, jarray); HMI_SEQ_INFO(req_num, "Visible app: %s", json_object_get_string(j)); int ret = afb_event_push( this->map_afb_event[kListEventName[Event_ScreenUpdated]], j); if (ret != 0) { HMI_DEBUG("wm", "afb_event_push failed: %m"); } json_object_put(jarray); } void WindowManager::setTimer() { struct timespec ts; if (clock_gettime(CLOCK_BOOTTIME, &ts) != 0) { HMI_ERROR("wm", "Could't set time (clock_gettime() returns with error"); return; } HMI_SEQ_DEBUG(g_app_list.currentRequestNumber(), "Timer set activate"); if (g_timer_ev_src == nullptr) { // firsttime set into sd_event int ret = sd_event_add_time(afb_daemon_get_event_loop(), &g_timer_ev_src, CLOCK_BOOTTIME, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL, 1, processTimerHandler, this); if (ret < 0) { HMI_ERROR("wm", "Could't set timer"); } } else { // update timer limitation after second time sd_event_source_set_time(g_timer_ev_src, (uint64_t)(ts.tv_sec + kTimeOut) * 1000000ULL); sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_ONESHOT); } } void WindowManager::stopTimer() { unsigned req_num = g_app_list.currentRequestNumber(); HMI_SEQ_DEBUG(req_num, "Timer stop"); int rc = sd_event_source_set_enabled(g_timer_ev_src, SD_EVENT_OFF); if (rc < 0) { HMI_SEQ_ERROR(req_num, "Timer stop failed"); } } void WindowManager::processNextRequest() { g_app_list.next(); g_app_list.reqDump(); unsigned req_num = g_app_list.currentRequestNumber(); if (g_app_list.haveRequest()) { HMI_SEQ_DEBUG(req_num, "Process next request"); WMError rc = doTransition(req_num); if (rc != WMError::SUCCESS) { HMI_SEQ_ERROR(req_num, errorDescription(rc)); } } else { HMI_SEQ_DEBUG(req_num, "Nothing Request. Waiting Request"); } } const char* WindowManager::convertRoleOldToNew(char const *old_role) { const char *new_role = nullptr; for (auto const &on : this->roleold2new) { std::regex regex = std::regex(on.first); if (std::regex_match(old_role, regex)) { // role is old. So convert to new. new_role = on.second.c_str(); break; } } if (nullptr == new_role) { // role is new or fallback. new_role = old_role; } HMI_DEBUG("wm", "old:%s -> new:%s", old_role, new_role); return new_role; } int WindowManager::loadOldRoleDb() { // Get afm application installed dir char const *afm_app_install_dir = getenv("AFM_APP_INSTALL_DIR"); HMI_DEBUG("wm", "afm_app_install_dir:%s", afm_app_install_dir); std::string file_name; if (!afm_app_install_dir) { HMI_ERROR("wm", "AFM_APP_INSTALL_DIR is not defined"); } else { file_name = std::string(afm_app_install_dir) + std::string("/etc/old_roles.db"); } // Load old_role.db json_object* json_obj; int ret = jh::inputJsonFilie(file_name.c_str(), &json_obj); if (0 > ret) { HMI_ERROR("wm", "Could not open old_role.db, so use default old_role information"); json_obj = json_tokener_parse(kDefaultOldRoleDb); } HMI_DEBUG("wm", "json_obj dump:%s", json_object_get_string(json_obj)); // Perse apps json_object* json_cfg; if (!json_object_object_get_ex(json_obj, "old_roles", &json_cfg)) { HMI_ERROR("wm", "Parse Error!!"); return -1; } int len = json_object_array_length(json_cfg); HMI_DEBUG("wm", "json_cfg len:%d", len); HMI_DEBUG("wm", "json_cfg dump:%s", json_object_get_string(json_cfg)); for (int i=0; i<len; i++) { json_object* json_tmp = json_object_array_get_idx(json_cfg, i); const char* old_role = jh::getStringFromJson(json_tmp, "name"); if (nullptr == old_role) { HMI_ERROR("wm", "Parse Error!!"); return -1; } const char* new_role = jh::getStringFromJson(json_tmp, "new"); if (nullptr == new_role) { HMI_ERROR("wm", "Parse Error!!"); return -1; } this->roleold2new[old_role] = std::string(new_role); } // Check for(auto itr = this->roleold2new.begin(); itr != this->roleold2new.end(); ++itr) { HMI_DEBUG("wm", ">>> role old:%s new:%s", itr->first.c_str(), itr->second.c_str()); } // Release json_object json_object_put(json_obj); return 0; } const char *WindowManager::check_surface_exist(const char *drawing_name) { auto const &surface_id = this->lookup_id(drawing_name); if (!surface_id) { return "Surface does not exist"; } if (!this->controller->surface_exists(*surface_id)) { return "Surface does not exist in controller!"; } auto layer_id = this->layers.get_layer_id(*surface_id); if (!layer_id) { return "Surface is not on any layer!"; } auto o_state = *this->layers.get_layout_state(*surface_id); if (o_state == nullptr) { return "Could not find layer for surface"; } HMI_DEBUG("wm", "surface %d is detected", *surface_id); return nullptr; } bool WindowManager::can_split(struct LayoutState const &state, int new_id) { if (state.main != -1 && state.main != new_id) { auto new_id_layer = this->layers.get_layer_id(new_id).value(); auto current_id_layer = this->layers.get_layer_id(state.main).value(); // surfaces are on separate layers, don't bother. if (new_id_layer != current_id_layer) { return false; } std::string const &new_id_str = this->lookup_name(new_id).value(); std::string const &cur_id_str = this->lookup_name(state.main).value(); auto const &layer = this->layers.get_layer(new_id_layer); HMI_DEBUG("wm", "layer info name: %s", layer->name.c_str()); if (layer->layouts.empty()) { return false; } for (auto i = layer->layouts.cbegin(); i != layer->layouts.cend(); i++) { HMI_DEBUG("wm", "%d main_match '%s'", new_id_layer, i->main_match.c_str()); auto rem = std::regex(i->main_match); if (std::regex_match(cur_id_str, rem)) { // build the second one only if the first already matched HMI_DEBUG("wm", "%d sub_match '%s'", new_id_layer, i->sub_match.c_str()); auto res = std::regex(i->sub_match); if (std::regex_match(new_id_str, res)) { HMI_DEBUG("wm", "layout matched!"); return true; } } } } return false; } const char* WindowManager::kDefaultOldRoleDb = "{ \ \"old_roles\": [ \ { \ \"name\": \"HomeScreen\", \ \"new\": \"homescreen\" \ }, \ { \ \"name\": \"Music\", \ \"new\": \"music\" \ }, \ { \ \"name\": \"MediaPlayer\", \ \"new\": \"music\" \ }, \ { \ \"name\": \"Video\", \ \"new\": \"video\" \ }, \ { \ \"name\": \"VideoPlayer\", \ \"new\": \"video\" \ }, \ { \ \"name\": \"WebBrowser\", \ \"new\": \"browser\" \ }, \ { \ \"name\": \"Radio\", \ \"new\": \"radio\" \ }, \ { \ \"name\": \"Phone\", \ \"new\": \"phone\" \ }, \ { \ \"name\": \"Navigation\", \ \"new\": \"map\" \ }, \ { \ \"name\": \"HVAC\", \ \"new\": \"hvac\" \ }, \ { \ \"name\": \"Settings\", \ \"new\": \"settings\" \ }, \ { \ \"name\": \"Dashboard\", \ \"new\": \"dashboard\" \ }, \ { \ \"name\": \"POI\", \ \"new\": \"poi\" \ }, \ { \ \"name\": \"Mixer\", \ \"new\": \"mixer\" \ }, \ { \ \"name\": \"Restriction\", \ \"new\": \"restriction\" \ }, \ { \ \"name\": \"^OnScreen.*\", \ \"new\": \"on_screen\" \ } \ ] \ }"; /** * controller_hooks */ void controller_hooks::surface_created(uint32_t surface_id) { this->app->surface_created(surface_id); } void controller_hooks::surface_removed(uint32_t surface_id) { this->app->surface_removed(surface_id); } void controller_hooks::surface_visibility(uint32_t /*surface_id*/, uint32_t /*v*/) {} void controller_hooks::surface_destination_rectangle(uint32_t /*surface_id*/, uint32_t /*x*/, uint32_t /*y*/, uint32_t /*w*/, uint32_t /*h*/) {} } // namespace wm